@agimon-ai/doompi-autocompact 0.0.1-alpha.0
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/LICENSE +21 -0
- package/README.md +36 -0
- package/dist/checkpointWorker.cjs +2 -0
- package/dist/checkpointWorker.cjs.map +1 -0
- package/dist/checkpointWorker.d.cts +1 -0
- package/dist/checkpointWorker.d.mts +1 -0
- package/dist/checkpointWorker.mjs +2 -0
- package/dist/checkpointWorker.mjs.map +1 -0
- package/dist/constants.cjs +2 -0
- package/dist/constants.cjs.map +1 -0
- package/dist/constants.mjs +2 -0
- package/dist/constants.mjs.map +1 -0
- package/dist/extension.cjs +50 -0
- package/dist/extension.cjs.map +1 -0
- package/dist/extension.d.cts +36 -0
- package/dist/extension.d.cts.map +1 -0
- package/dist/extension.d.mts +36 -0
- package/dist/extension.d.mts.map +1 -0
- package/dist/extension.mjs +50 -0
- package/dist/extension.mjs.map +1 -0
- package/dist/extensions/pi.cjs +2 -0
- package/dist/extensions/pi.cjs.map +1 -0
- package/dist/extensions/pi.d.cts +2 -0
- package/dist/extensions/pi.d.mts +2 -0
- package/dist/extensions/pi.mjs +2 -0
- package/dist/extensions/pi.mjs.map +1 -0
- package/dist/index.cjs +1 -0
- package/dist/index.d.cts +4 -0
- package/dist/index.d.mts +4 -0
- package/dist/index.mjs +1 -0
- package/dist/logSinkTelemetry.cjs +2 -0
- package/dist/logSinkTelemetry.cjs.map +1 -0
- package/dist/logSinkTelemetry.d.cts +26 -0
- package/dist/logSinkTelemetry.d.cts.map +1 -0
- package/dist/logSinkTelemetry.d.mts +26 -0
- package/dist/logSinkTelemetry.d.mts.map +1 -0
- package/dist/logSinkTelemetry.mjs +2 -0
- package/dist/logSinkTelemetry.mjs.map +1 -0
- package/dist/policy.cjs +8 -0
- package/dist/policy.cjs.map +1 -0
- package/dist/policy.d.cts +6 -0
- package/dist/policy.d.cts.map +1 -0
- package/dist/policy.d.mts +6 -0
- package/dist/policy.d.mts.map +1 -0
- package/dist/policy.mjs +8 -0
- package/dist/policy.mjs.map +1 -0
- package/dist/standard.cjs +2 -0
- package/dist/standard.cjs.map +1 -0
- package/dist/standard.d.cts +8 -0
- package/dist/standard.d.cts.map +1 -0
- package/dist/standard.d.mts +8 -0
- package/dist/standard.d.mts.map +1 -0
- package/dist/standard.mjs +2 -0
- package/dist/standard.mjs.map +1 -0
- package/dist/summarizationModel.cjs +2 -0
- package/dist/summarizationModel.cjs.map +1 -0
- package/dist/summarizationModel.d.cts +10 -0
- package/dist/summarizationModel.d.cts.map +1 -0
- package/dist/summarizationModel.d.mts +10 -0
- package/dist/summarizationModel.d.mts.map +1 -0
- package/dist/summarizationModel.mjs +2 -0
- package/dist/summarizationModel.mjs.map +1 -0
- package/dist/types.d.cts +5 -0
- package/dist/types.d.cts.map +1 -0
- package/dist/types.d.mts +5 -0
- package/dist/types.d.mts.map +1 -0
- package/package.json +59 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Vuong Ngo
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# @agimon-ai/doompi-autocompact
|
|
2
|
+
|
|
3
|
+
Staged checkpoint steering and iterative context compaction for Doompi.
|
|
4
|
+
|
|
5
|
+
Compaction runs on a three-pass ladder in a worker thread, so the session never blocks on
|
|
6
|
+
it. It reads the live plan, task graph, and team snapshot and commits them next to the
|
|
7
|
+
summary as authoritative, rather than leaving coordination state to be reconstructed from
|
|
8
|
+
prose.
|
|
9
|
+
|
|
10
|
+
Part of [Doompi](https://www.npmjs.com/package/@agimon-ai/doompi), a coding agent that loads
|
|
11
|
+
only the skills and tools you name. This package is composed by Doompi and is not usually
|
|
12
|
+
installed on its own.
|
|
13
|
+
|
|
14
|
+
## Install
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
npm install @agimon-ai/doompi-autocompact
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## How it loads
|
|
21
|
+
|
|
22
|
+
Doompi loads this unconditionally. It is core, not a layer, so it does not appear in
|
|
23
|
+
`.doom/modes.yaml`: making it optional would only create broken configurations.
|
|
24
|
+
|
|
25
|
+
Extension entry: `@agimon-ai/doompi-autocompact/extensions/pi`
|
|
26
|
+
|
|
27
|
+
## Entry points
|
|
28
|
+
|
|
29
|
+
| Import |
|
|
30
|
+
| --------------------------------------------- |
|
|
31
|
+
| `@agimon-ai/doompi-autocompact` |
|
|
32
|
+
| `@agimon-ai/doompi-autocompact/extensions/pi` |
|
|
33
|
+
|
|
34
|
+
## License
|
|
35
|
+
|
|
36
|
+
MIT
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
let e=require(`node:worker_threads`),t=require(`@earendil-works/pi-coding-agent`);async function n(n){try{let r=await(0,t.generateSummary)(n.messages,n.model,n.reserveTokens,n.apiKey,n.headers,void 0,n.instructions,n.previousCheckpoint,n.thinkingLevel,void 0,n.env);e.parentPort?.postMessage({checkpoint:r})}catch(t){e.parentPort?.postMessage({error:t instanceof Error?t.message:String(t)})}}n(e.workerData);
|
|
2
|
+
//# sourceMappingURL=checkpointWorker.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"checkpointWorker.cjs","names":["workerData"],"sources":["../src/checkpointWorker.ts"],"sourcesContent":["import { parentPort, workerData } from 'node:worker_threads';\n\nimport { generateSummary } from '@earendil-works/pi-coding-agent';\n\ntype GenerateSummaryArguments = Parameters<typeof generateSummary>;\n\ninterface CheckpointWorkerInput {\n messages: GenerateSummaryArguments[0];\n model: GenerateSummaryArguments[1];\n reserveTokens: GenerateSummaryArguments[2];\n apiKey?: GenerateSummaryArguments[3];\n headers?: GenerateSummaryArguments[4];\n instructions: GenerateSummaryArguments[6];\n previousCheckpoint?: GenerateSummaryArguments[7];\n thinkingLevel?: GenerateSummaryArguments[8];\n env?: GenerateSummaryArguments[10];\n}\n\nasync function summarize(input: CheckpointWorkerInput): Promise<void> {\n try {\n const checkpoint = await generateSummary(\n input.messages,\n input.model,\n input.reserveTokens,\n input.apiKey,\n input.headers,\n undefined,\n input.instructions,\n input.previousCheckpoint,\n input.thinkingLevel,\n undefined,\n input.env,\n );\n parentPort?.postMessage({ checkpoint });\n } catch (error) {\n parentPort?.postMessage({ error: error instanceof Error ? error.message : String(error) });\n }\n}\n\nvoid summarize(workerData as CheckpointWorkerInput);\n"],"mappings":"kFAkBA,eAAe,EAAU,EAA6C,CACpE,GAAI,CACF,IAAM,EAAa,MAAA,EAAA,EAAA,iBACjB,EAAM,SACN,EAAM,MACN,EAAM,cACN,EAAM,OACN,EAAM,QACN,IAAA,GACA,EAAM,aACN,EAAM,mBACN,EAAM,cACN,IAAA,GACA,EAAM,IACP,CACD,EAAA,YAAY,YAAY,CAAE,aAAY,CAAC,OAChC,EAAO,CACd,EAAA,YAAY,YAAY,CAAE,MAAO,aAAiB,MAAQ,EAAM,QAAU,OAAO,EAAM,CAAE,CAAC,EAIzF,EAAUA,EAAAA,WAAoC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{parentPort as e,workerData as t}from"node:worker_threads";import{generateSummary as n}from"@earendil-works/pi-coding-agent";async function r(t){try{let r=await n(t.messages,t.model,t.reserveTokens,t.apiKey,t.headers,void 0,t.instructions,t.previousCheckpoint,t.thinkingLevel,void 0,t.env);e?.postMessage({checkpoint:r})}catch(t){e?.postMessage({error:t instanceof Error?t.message:String(t)})}}r(t);export{};
|
|
2
|
+
//# sourceMappingURL=checkpointWorker.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"checkpointWorker.mjs","names":[],"sources":["../src/checkpointWorker.ts"],"sourcesContent":["import { parentPort, workerData } from 'node:worker_threads';\n\nimport { generateSummary } from '@earendil-works/pi-coding-agent';\n\ntype GenerateSummaryArguments = Parameters<typeof generateSummary>;\n\ninterface CheckpointWorkerInput {\n messages: GenerateSummaryArguments[0];\n model: GenerateSummaryArguments[1];\n reserveTokens: GenerateSummaryArguments[2];\n apiKey?: GenerateSummaryArguments[3];\n headers?: GenerateSummaryArguments[4];\n instructions: GenerateSummaryArguments[6];\n previousCheckpoint?: GenerateSummaryArguments[7];\n thinkingLevel?: GenerateSummaryArguments[8];\n env?: GenerateSummaryArguments[10];\n}\n\nasync function summarize(input: CheckpointWorkerInput): Promise<void> {\n try {\n const checkpoint = await generateSummary(\n input.messages,\n input.model,\n input.reserveTokens,\n input.apiKey,\n input.headers,\n undefined,\n input.instructions,\n input.previousCheckpoint,\n input.thinkingLevel,\n undefined,\n input.env,\n );\n parentPort?.postMessage({ checkpoint });\n } catch (error) {\n parentPort?.postMessage({ error: error instanceof Error ? error.message : String(error) });\n }\n}\n\nvoid summarize(workerData as CheckpointWorkerInput);\n"],"mappings":"mIAkBA,eAAe,EAAU,EAA6C,CACpE,GAAI,CACF,IAAM,EAAa,MAAM,EACvB,EAAM,SACN,EAAM,MACN,EAAM,cACN,EAAM,OACN,EAAM,QACN,IAAA,GACA,EAAM,aACN,EAAM,mBACN,EAAM,cACN,IAAA,GACA,EAAM,IACP,CACD,GAAY,YAAY,CAAE,aAAY,CAAC,OAChC,EAAO,CACd,GAAY,YAAY,CAAE,MAAO,aAAiB,MAAQ,EAAM,QAAU,OAAO,EAAM,CAAE,CAAC,EAIzF,EAAU,EAAoC"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e={1:{ratio:.5,capTokens:2e5},2:{ratio:.75,capTokens:5e5},3:{ratio:.95,capTokens:8e5}},t=[`## Goal`,`## Constraints & Preferences`,`## Progress`,`### Done`,`### In Progress`,`### Blocked`,`## Key Decisions`,`## Next Steps`,`## Critical Context`];exports.CHECKPOINT_HEADINGS=t,exports.CHECKPOINT_MESSAGE_TYPE=`doom-autocompact-checkpoint`,exports.COMPACTION_THRESHOLDS=e,exports.CONTEXT_MESSAGE_TYPE=`doom-autocompact-context`,exports.RESUME_MESSAGE_TYPE=`doom-autocompact-resume`,exports.RUNTIME_STATE_MESSAGE_TYPE=`doom-autocompact-runtime-state`,exports.STATE_CUSTOM_TYPE=`doom-autocompact-state`;
|
|
2
|
+
//# sourceMappingURL=constants.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants.cjs","names":[],"sources":["../src/constants.ts"],"sourcesContent":["export const STATE_CUSTOM_TYPE = 'doom-autocompact-state';\nexport const CHECKPOINT_MESSAGE_TYPE = 'doom-autocompact-checkpoint';\nexport const CONTEXT_MESSAGE_TYPE = 'doom-autocompact-context';\nexport const RESUME_MESSAGE_TYPE = 'doom-autocompact-resume';\nexport const RUNTIME_STATE_MESSAGE_TYPE = 'doom-autocompact-runtime-state';\nexport const STATE_VERSION = 2;\n/** Retrying a malformed checkpoint costs a full summarization call per turn, so a pass that\n * keeps failing is abandoned instead of retried for the rest of the session. */\nexport const MAX_INVALID_CHECKPOINT_ATTEMPTS = 3;\n\nexport const COMPACTION_THRESHOLDS = {\n 1: { ratio: 0.5, capTokens: 200_000 },\n 2: { ratio: 0.75, capTokens: 500_000 },\n 3: { ratio: 0.95, capTokens: 800_000 },\n} as const;\n\nexport const CHECKPOINT_HEADINGS = [\n '## Goal',\n '## Constraints & Preferences',\n '## Progress',\n '### Done',\n '### In Progress',\n '### Blocked',\n '## Key Decisions',\n '## Next Steps',\n '## Critical Context',\n] as const;\n"],"mappings":"AAAA,MAUa,EAAwB,CACnC,EAAG,CAAE,MAAO,GAAK,UAAW,IAAS,CACrC,EAAG,CAAE,MAAO,IAAM,UAAW,IAAS,CACtC,EAAG,CAAE,MAAO,IAAM,UAAW,IAAS,CACvC,CAEY,EAAsB,CACjC,UACA,+BACA,cACA,WACA,kBACA,cACA,mBACA,gBACA,sBACD"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=`doom-autocompact-state`,t=`doom-autocompact-checkpoint`,n=`doom-autocompact-context`,r=`doom-autocompact-resume`,i=`doom-autocompact-runtime-state`,a={1:{ratio:.5,capTokens:2e5},2:{ratio:.75,capTokens:5e5},3:{ratio:.95,capTokens:8e5}},o=[`## Goal`,`## Constraints & Preferences`,`## Progress`,`### Done`,`### In Progress`,`### Blocked`,`## Key Decisions`,`## Next Steps`,`## Critical Context`];export{o as CHECKPOINT_HEADINGS,t as CHECKPOINT_MESSAGE_TYPE,a as COMPACTION_THRESHOLDS,n as CONTEXT_MESSAGE_TYPE,r as RESUME_MESSAGE_TYPE,i as RUNTIME_STATE_MESSAGE_TYPE,e as STATE_CUSTOM_TYPE};
|
|
2
|
+
//# sourceMappingURL=constants.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants.mjs","names":[],"sources":["../src/constants.ts"],"sourcesContent":["export const STATE_CUSTOM_TYPE = 'doom-autocompact-state';\nexport const CHECKPOINT_MESSAGE_TYPE = 'doom-autocompact-checkpoint';\nexport const CONTEXT_MESSAGE_TYPE = 'doom-autocompact-context';\nexport const RESUME_MESSAGE_TYPE = 'doom-autocompact-resume';\nexport const RUNTIME_STATE_MESSAGE_TYPE = 'doom-autocompact-runtime-state';\nexport const STATE_VERSION = 2;\n/** Retrying a malformed checkpoint costs a full summarization call per turn, so a pass that\n * keeps failing is abandoned instead of retried for the rest of the session. */\nexport const MAX_INVALID_CHECKPOINT_ATTEMPTS = 3;\n\nexport const COMPACTION_THRESHOLDS = {\n 1: { ratio: 0.5, capTokens: 200_000 },\n 2: { ratio: 0.75, capTokens: 500_000 },\n 3: { ratio: 0.95, capTokens: 800_000 },\n} as const;\n\nexport const CHECKPOINT_HEADINGS = [\n '## Goal',\n '## Constraints & Preferences',\n '## Progress',\n '### Done',\n '### In Progress',\n '### Blocked',\n '## Key Decisions',\n '## Next Steps',\n '## Critical Context',\n] as const;\n"],"mappings":"AAAA,MAAa,EAAoB,yBACpB,EAA0B,8BAC1B,EAAuB,2BACvB,EAAsB,0BACtB,EAA6B,iCAM7B,EAAwB,CACnC,EAAG,CAAE,MAAO,GAAK,UAAW,IAAS,CACrC,EAAG,CAAE,MAAO,IAAM,UAAW,IAAS,CACtC,EAAG,CAAE,MAAO,IAAM,UAAW,IAAS,CACvC,CAEY,EAAsB,CACjC,UACA,+BACA,cACA,WACA,kBACA,cACA,mBACA,gBACA,sBACD"}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
const e=require(`./constants.cjs`),t=require(`./policy.cjs`),n=require(`./logSinkTelemetry.cjs`),r=require(`./summarizationModel.cjs`);let i=require(`node:worker_threads`),a=require(`@agimon-ai/doompi-config`),o=require(`@agimon-ai/doompi-ui/footer`),s=require(`@agimon-ai/doompi-task/store/paths`),c=require(`@agimon-ai/doompi-task/store/taskStore`),l=require(`@agimon-ai/doompi-team/api/team-snapshot`),u=require(`@earendil-works/pi-coding-agent`);const d=`@root`,f={waiting:`waiting`,checkpointPending:`checkpoint_pending`,checkpointReady:`checkpoint_ready`,compacting:`compacting`};function p(e,t={}){return{"pi.session.id":e.sessionManager.getSessionId(),...t}}function m(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 h(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 g(e){return e instanceof Error?e.message:String(e)}function _(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}}}function v(e){let t=[];try{let n=new c.TaskStore({cwd:e.cwd,report:{error:(e,n)=>t.push(`${e}: ${g(n)}`),warn:(e,n)=>t.push(`${e}: ${g(n)}`),event:()=>void 0}});return n.configureSession((0,s.resolveSessionKey)(e.sessionManager.getSessionId())),{tasks:n.read().tasks,...t.length>0?{error:t.join(`; `)}:{}}}catch(e){return{tasks:[],error:g(e)}}}function y(){try{let e=(0,l.readActiveNativeTeamSnapshot)();return e?{members:e.members}:{}}catch(e){return{error:g(e)}}}function b(e){return e.tasks.filter(e=>e.status===`pending`||e.status===`in_progress`||e.status===`failed`).map(e=>({id:e.id,status:e.status,subject:e.subject,...e.activeForm?{activeForm:e.activeForm}:{},...e.owner?{owner:e.owner}:{},...e.blockedBy?.length?{blockedBy:e.blockedBy}:{},...e.delegation?{delegation:{agent:e.delegation.agent,state:e.delegation.state,...e.delegation.result?.error?{error:e.delegation.result.error}:{}}}:{}}))}function x(e,t){let n=e.map(e=>{let t=[e.activeForm?`active: ${e.activeForm}`:void 0,e.owner?`owner: ${e.owner}`:void 0,e.blockedBy?.length?`blocked by: ${e.blockedBy.join(`, `)}`:void 0,e.delegation?`delegation: ${e.delegation.agent} (${e.delegation.state})`:void 0,e.delegation?.error?`error: ${e.delegation.error}`:void 0].filter(e=>!!e);return`- #${e.id} [${e.status}] ${e.subject}${t.length>0?` | ${t.join(` | `)}`:``}`});return t&&n.push(`- Task snapshot error: ${t}`),n.length>0?n.join(`
|
|
2
|
+
`):`(no active tasks)`}function S(e){let t=(e.members??[]).map(e=>{let t=[`role: ${e.role}`,e.agent?`agent: ${e.agent}`:void 0,e.runId?`run: ${e.runId}`:void 0,e.task?`task ${e.task.id}: ${e.task.subject}`:void 0].filter(e=>!!e);return`- ${e.name} | ${t.join(` | `)}`});return e.error&&t.push(`- Team snapshot error: ${e.error}`),t.length>0?t.join(`
|
|
3
|
+
`):e.members?`(no active team members)`:`(team runtime unavailable)`}function C(e,t,n){let r=_(e);return{...r?{planPath:r.path}:{},tasks:b(t),...t.error?{taskError:t.error}:{},teamAvailable:!!n.members,teamMembers:n.members??[],...n.error?{teamError:n.error}:{}}}function w(e){let t=e.planPath?`Source: ${e.planPath}\nExact plan content is restored separately by Doom Plan.`:`(no active plan document)`,n={...e.teamAvailable?{members:e.teamMembers}:{},...e.teamError?{error:e.teamError}:{}};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
|
+
${t}
|
|
7
|
+
</active-plan>
|
|
8
|
+
<active-tasks>
|
|
9
|
+
${x(e.tasks,e.taskError)}
|
|
10
|
+
</active-tasks>
|
|
11
|
+
<active-team>
|
|
12
|
+
${S(n)}
|
|
13
|
+
</active-team>
|
|
14
|
+
</compaction-runtime-state>`}function T(e){return{"autocompact.runtime.plan_present":!!e.planPath,"autocompact.runtime.task_count":e.tasks.length,"autocompact.runtime.team_available":e.teamAvailable,"autocompact.runtime.team_member_count":e.teamMembers.length}}function E(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,tasks,team,important-context,recent-messages">
|
|
15
|
+
<user-prompt source="conversation">
|
|
16
|
+
Treat the user's explicit goals, constraints, corrections, and preferences in the conversation as authoritative. Newer user instructions override older ones.
|
|
17
|
+
</user-prompt>
|
|
18
|
+
<active-plan>
|
|
19
|
+
${t}
|
|
20
|
+
</active-plan>
|
|
21
|
+
<active-tasks>
|
|
22
|
+
${x(b(e.taskSnapshot),e.taskSnapshot.error)}
|
|
23
|
+
</active-tasks>
|
|
24
|
+
<active-team>
|
|
25
|
+
${S(e.teamSnapshot)}
|
|
26
|
+
</active-team>
|
|
27
|
+
<important-context>
|
|
28
|
+
${n.length>0?n.join(`
|
|
29
|
+
`):`(none recorded outside the conversation)`}
|
|
30
|
+
</important-context>
|
|
31
|
+
</compaction-steering>`}function D(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.
|
|
32
|
+
|
|
33
|
+
`:``;return`Create Doom autocompact checkpoint pass ${e}.
|
|
34
|
+
|
|
35
|
+
${E(t)}
|
|
36
|
+
|
|
37
|
+
Apply the steering evidence in priority order. Do not invent plan, task, or team state. Preserve verified facts and mark unresolved inference explicitly. Newer evidence replaces superseded information.
|
|
38
|
+
|
|
39
|
+
${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.
|
|
40
|
+
|
|
41
|
+
## Goal
|
|
42
|
+
## Constraints & Preferences
|
|
43
|
+
## Progress
|
|
44
|
+
### Done
|
|
45
|
+
### In Progress
|
|
46
|
+
### Blocked
|
|
47
|
+
## Key Decisions
|
|
48
|
+
## Next Steps
|
|
49
|
+
## Critical Context`}function O(e,n,r){let i=t.projectContextMessages((0,u.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,u.sessionEntryToContextMessages)(e))}function k(e,t){return new Promise((n,r)=>{let a=new i.Worker(new URL(`./checkpointWorker.mjs`,require(`url`).pathToFileURL(__filename).href),{workerData:e}),o=!1,s=e=>{o||(o=!0,t.removeEventListener(`abort`,c),e())},c=()=>{s(()=>{a.terminate(),r(t.reason instanceof Error?t.reason:Error(`Autocompact summarization aborted.`))})};a.once(`message`,e=>{s(()=>{typeof e.checkpoint==`string`?n(e.checkpoint):r(Error(e.error??`Autocompact summarization worker returned no checkpoint.`))})}),a.once(`error`,e=>s(()=>r(e))),a.once(`exit`,e=>{e!==0&&s(()=>r(Error(`Autocompact summarization worker exited with code ${e}.`)))}),t.addEventListener(`abort`,c,{once:!0}),a.unref(),t.aborted&&c()})}function A(e){try{return(0,a.loadDoomConfig)((0,a.getHarnessState)().root??e).modes?.planning?.subagents}catch{process.emitWarning(`Doom autocompact planning configuration could not be loaded; using the active session model instead.`);return}}function j(e){let t=A(e.cwd),n=t?.model?r.parseModelReference(t.model):void 0,i=n?e.modelRegistry.find(n.provider,n.modelId):void 0,a=i??e.model;if(!a)return;let o=t?.thinking??(i?n?.thinking:void 0)??e.thinkingLevel;return{model:a,...o?{thinkingLevel:o}:{}}}async function M(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);return k({messages:e.messages,model:n.model,reserveTokens:u.DEFAULT_COMPACTION_SETTINGS.reserveTokens,apiKey:r.apiKey,headers:r.headers,instructions:e.instructions,previousCheckpoint:e.previousCheckpoint,thinkingLevel:n.thinkingLevel,env:r.env},e.signal)}function N(e,t,n=`info`){e?.hasUI&&e.ui.notify(t,n)}function P(r,i={}){let a=i.resolveModel??j,s=i.generateCheckpoint??(e=>M(e,a)),c=i.readTaskSnapshot??v,l=i.readTeamSnapshot??y,g=i.telemetry??n.createAutocompactTelemetry(),b=i.doomIntegrations??!0,x=new Set,S=new Set,E=t.createInitialState(),k,A,P=b?(0,o.registerDoomFooterContribution)(r,{source:`doom-autocompact`,id:`autocompact`,order:20}):{update:()=>void 0,dispose:()=>void 0},F=e=>{let t=E.phase===f.checkpointPending?`summarizing`:E.phase===f.checkpointReady?`applying`:void 0;P.update(t?{fullText:`Compacting p${E.pass}`,compactText:`C${E.pass}`}:void 0);let n=e??k;n?.hasUI&&n.ui.setStatus(`doom-autocompact`,t?`Compacting pass ${E.pass} (${t})…`:void 0)},I=()=>{r.appendEntry(e.STATE_CUSTOM_TYPE,{...E}),F()},L=()=>{delete E.requestId,delete E.snapshotLeafId,delete E.snapshotTokens,delete E.pendingCheckpoint,delete E.compactionPass},R=e=>{E.checkpointQueue=E.checkpointQueue.filter(t=>t!==e)},z=e=>{E=m(e.sessionManager.getBranch())??t.createInitialState(),!(E.phase===f.checkpointReady&&E.requestId&&E.snapshotLeafId&&E.pendingCheckpoint||E.phase===f.waiting)&&(A?.abort(),A=void 0,E.phase=f.waiting,L(),I())},B=t=>{r.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:E.cycle,pass:E.pass}},{triggerTurn:!0,deliverAs:`steer`})},V=(e,t)=>{if(e!==E.requestId||E.phase!==f.checkpointPending)return;let n=E.snapshotLeafId;E.phase=f.waiting,n&&(E.lastAttemptLeafId=n),L(),I(),N(k,`Doom autocompact summarization pass ${E.pass} failed: ${t instanceof Error?t.message:String(t)}`,`error`)},H=(e,t,r,i)=>{t.error&&(N(e,`Doom autocompact task steering degraded: ${t.error}`,`warning`),g.recordWarning(n.AUTOCOMPACT_EVENT.taskSnapshotDegraded,Error(t.error),i)),r.error&&(N(e,`Doom autocompact team steering degraded: ${r.error}`,`warning`),g.recordWarning(n.AUTOCOMPACT_EVENT.teamSnapshotDegraded,Error(r.error),i))},U=(t,n,i)=>{let a=c(t),o=l();H(t,a,o,i);let s=C(n,a,o);return r.sendMessage({customType:e.RUNTIME_STATE_MESSAGE_TYPE,content:w(s),display:!1,details:{version:1,...s}}),s},W=(i,a)=>{if(!E.requestId||!E.snapshotLeafId||!E.pendingCheckpoint)return!1;let o=a.sessionManager.getBranch(),s=t.projectContextMessages((0,u.buildSessionContext)(o).messages,o).messages,c=t.mergeFileDetails(E,t.fileOperationsFromMessages(s)),l=E.requestId,d=E.cycle,m=t.withCanonicalFileSections(E.pendingCheckpoint,c),_={...c,doomAutocompact:{version:2,cycle:d,pass:i,requestId:l,snapshotLeafId:E.snapshotLeafId,tokensBefore:E.snapshotTokens??a.getContextUsage()?.tokens??0},retainedMessages:t.retainedMessagesAfterSnapshot(o,E.snapshotLeafId)};N(a,`Doom autocompact pass ${i} context commit started.`);let v=a.isIdle();r.sendMessage({customType:e.CONTEXT_MESSAGE_TYPE,content:m,display:!1,details:_});let y=h(a),b=U(a,o,p(a,{"autocompact.request.id":l,"autocompact.cycle":d,"autocompact.pass":i}));return v&&r.setLabel(y,`autocompact:c${d}:p${i}`),E.readFiles=c.readFiles,E.modifiedFiles=c.modifiedFiles,delete E.latestCheckpointSnapshotLeafId,E.phase=f.waiting,E.checkpointQueue=[],E.exhaustedPasses=[],E.invalidAttempts=0,E.baselinePending=!0,delete E.lastAttemptLeafId,L(),E.cycle+=1,E.pass=1,I(),g.recordEvent(n.AUTOCOMPACT_EVENT.contextCommitted,p(a,{"autocompact.request.id":l,"autocompact.cycle":d,"autocompact.pass":i,"autocompact.snapshot_leaf_id":_.doomAutocompact.snapshotLeafId,"autocompact.tokens_before":_.doomAutocompact.tokensBefore,"autocompact.message_count.before":s.length,"autocompact.message_count.retained":_.retainedMessages.length,"autocompact.apply_mode":v?`idle`:`turn_end`,...T(b)})),N(a,`Doom autocompact context committed. Baseline will be captured from the next settled context.`),v&&B(`Asynchronous compaction completed.`),!0},G=(e,r,i)=>{let a=r.sessionManager.getBranch(),o=h(r),u=t.createRequestId(r.sessionManager.getSessionId(),E.cycle,e,o),d=e>1?t.checkpointSummaryFromEntry(t.latestCheckpointArtifactEntry(a)):void 0,m=O(e,a,E.latestCheckpointSnapshotLeafId),v=c(r),y=l(),b=p(r,{"autocompact.request.id":u,"autocompact.cycle":E.cycle,"autocompact.pass":e,"autocompact.snapshot_leaf_id":o,"autocompact.tokens_before":i,"autocompact.message_count.before":m.length});H(r,v,y,b),E.phase=f.checkpointPending,E.pass=e,E.requestId=u,E.snapshotLeafId=o,E.snapshotTokens=i,delete E.pendingCheckpoint,delete E.compactionPass,delete E.lastAttemptLeafId,I(),A?.abort(),A=new AbortController;let x=A.signal;N(r,`Doom autocompact summarization pass ${e} started.`),g.runInSpan(`doom_autocompact.checkpoint`,b,async()=>{await g.recordEvent(n.AUTOCOMPACT_EVENT.checkpointStarted,b);try{let t=await s({messages:m,instructions:D(e,{plan:_(a),taskSnapshot:v,teamSnapshot:y,readFiles:E.readFiles,modifiedFiles:E.modifiedFiles}),...d?{previousCheckpoint:d}:{},context:r,signal:x});if(!t.trim())throw Error(`Summarization returned an empty checkpoint.`);return await g.recordEvent(n.AUTOCOMPACT_EVENT.checkpointCompleted,{...b,"autocompact.checkpoint.characters":t.length}),t}catch(e){throw await g.recordError(n.AUTOCOMPACT_EVENT.checkpointFailed,e,b),e}}).then(t=>{u!==E.requestId||E.phase!==f.checkpointPending||(E.phase=f.checkpointReady,E.pendingCheckpoint=t.trim(),I(),N(k,`Doom autocompact summarization pass ${e} completed.`),k&&Y(k))}).catch(e=>V(u,e))},K=e=>{if(E.phase!==f.waiting||e.hasPendingMessages())return!1;let n=e.getContextUsage();if(!n||n.tokens===null)return!1;if(E.baselinePending)return t.baselineUsageIsSettled(e.sessionManager.getBranch())?(E.baselineTokens=n.tokens,E.baselinePending=!1,I(),N(e,`Doom autocompact baseline captured at ${E.baselineTokens} tokens.`),!1):!1;let r=h(e);if(E.lastAttemptLeafId===r)return!1;for(let e of[1,2,3])e<E.pass||E.checkpointQueue.includes(e)||E.exhaustedPasses.includes(e)||n.tokens>=t.thresholdTokens(e,n.contextWindow,E.baselineTokens)&&E.checkpointQueue.push(e);let i=E.checkpointQueue[0];return i?(G(i,e,n.tokens),!0):!1},q=(n,i)=>{let a=E.snapshotLeafId;r.appendEntry(e.CHECKPOINT_MESSAGE_TYPE,{...t.checkpointRequestDetails(E.cycle,n,E.requestId??`completed`),summary:i}),a&&(E.latestCheckpointSnapshotLeafId=a)},J=e=>{if(E.phase!==f.checkpointReady||!E.requestId||!E.pendingCheckpoint)return`none`;let r=E.pass,i=t.parseCheckpointDecision(E.pendingCheckpoint);if(!t.isStructuredCheckpoint(i.summary)){let t=E.snapshotLeafId,i=E.requestId,a=E.invalidAttempts+1,o=a>=3;E.phase=f.waiting,t&&(E.lastAttemptLeafId=t),o?(R(r),E.exhaustedPasses=[...E.exhaustedPasses,r],E.invalidAttempts=0):E.invalidAttempts=a,L(),I();let s=Error(`Summarization pass ${r} returned an incomplete checkpoint.`);return N(e,o?`Doom autocompact summarization pass ${r} returned an incomplete checkpoint ${a} times and was abandoned.`:`Doom autocompact summarization pass ${r} returned an incomplete checkpoint.`,`error`),g.recordError(n.AUTOCOMPACT_EVENT.checkpointInvalid,s,p(e,{"autocompact.cycle":E.cycle,"autocompact.pass":r,"autocompact.checkpoint.attempts":a,"autocompact.checkpoint.exhausted":o,...i?{"autocompact.request.id":i}:{}})),`invalid`}return E.invalidAttempts=0,r===1?(q(1,i.summary),R(1),E.phase=f.waiting,E.pass=2,L(),I(),`pass1`):r===2&&i.shouldCompact!==!0?(q(2,i.summary),R(2),E.phase=f.waiting,E.pass=3,L(),I(),`deferred`):(E.pendingCheckpoint=i.summary,W(r,e)?`committed`:`invalid`)};function Y(e){k=e,e.isIdle()&&J(e)!==`committed`&&K(e)}r.on(`context`,(e,r)=>{let i=t.projectContextMessages(e.messages,r.sessionManager.getBranch());if(i.invalidMarker){let e=r.sessionManager.getLeafId()??d;S.has(e)||(S.add(e),g.recordError(n.AUTOCOMPACT_EVENT.contextMarkerInvalid,Error(`Doom autocompact context marker is malformed.`),p(r,{"autocompact.leaf_id":e})));return}if(i.marker)return x.has(i.marker.requestId)||(x.add(i.marker.requestId),g.recordEvent(n.AUTOCOMPACT_EVENT.contextApplied,p(r,{"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}}),r.on(`session_start`,(e,t)=>{k=t,z(t),Y(t)}),r.on(`session_tree`,(e,t)=>{k=t,z(t),Y(t)}),r.on(`turn_end`,(e,t)=>{if(k=t,t.isIdle()){Y(t);return}E.phase===f.checkpointReady&&(e.toolResults?.length??0)>0&&!t.hasPendingMessages()&&J(t)!==`none`||K(t)}),r.on(`agent_settled`,(e,t)=>{Y(t)}),r.on(`session_before_compact`,e=>{if(e.reason===`threshold`)return E.phase===f.checkpointPending||E.phase===f.checkpointReady||E.baselinePending?{cancel:!0}:void 0}),r.on(`session_compact`,(e,i)=>{A?.abort(),A=void 0;let a=t.fileDetailsFromUnknown(e.compactionEntry.details),o=t.mergeFileDetails(E,void 0,a);E.readFiles=o.readFiles,E.modifiedFiles=o.modifiedFiles,delete E.latestCheckpointSnapshotLeafId,E.baselinePending=!0,E.phase=f.waiting,L(),E.checkpointQueue=[],E.exhaustedPasses=[],E.invalidAttempts=0,delete E.lastAttemptLeafId,r.setLabel(e.compactionEntry.id,`autocompact:c${E.cycle}:external`);let s=E.cycle,c=p(i,{"autocompact.cycle":s,"autocompact.native.reason":e.reason}),l=U(i,i.sessionManager.getBranch(),c);E.cycle+=1,E.pass=1,I(),g.recordEvent(n.AUTOCOMPACT_EVENT.nativeCompactionCompleted,p(i,{"autocompact.cycle":s,"autocompact.native.reason":e.reason,"autocompact.native.from_extension":e.fromExtension,"autocompact.tokens_before":e.compactionEntry.tokensBefore,...T(l)})),N(i,`Doom autocompact completed. Baseline will be captured from the next settled context. Next pass: ${E.pass}.`)}),r.on(`session_shutdown`,async()=>{A?.abort(),A=void 0,P.dispose(),k=void 0,x.clear(),S.clear(),E=t.createInitialState(),await g.shutdown()})}exports.registerAutocompactExtension=P;
|
|
50
|
+
//# sourceMappingURL=extension.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"extension.cjs","names":["parseState","TaskStore","projectContextMessages","Worker","parseModelReference","DEFAULT_COMPACTION_SETTINGS","createAutocompactTelemetry","createInitialState","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"],"sources":["../src/extension.ts"],"sourcesContent":["import { Worker } from 'node:worker_threads';\n\nimport { getHarnessState, loadDoomConfig, type PlanningAgentConfig } from '@agimon-ai/doompi-config';\nimport { registerDoomFooterContribution } from '@agimon-ai/doompi-ui/footer';\nimport { resolveSessionKey } from '@agimon-ai/doompi-task/store/paths';\nimport { TaskStore } from '@agimon-ai/doompi-task/store/taskStore';\nimport type { Task } from '@agimon-ai/doompi-task/store/types';\nimport { readActiveNativeTeamSnapshot, type NativeTeamMemberSnapshot } from '@agimon-ai/doompi-team/api/team-snapshot';\nimport type { ExtensionAPI, ExtensionContext, SessionEntry } from '@earendil-works/pi-coding-agent';\nimport {\n buildSessionContext,\n DEFAULT_COMPACTION_SETTINGS,\n sessionEntryToContextMessages,\n} from '@earendil-works/pi-coding-agent';\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 './constants.ts';\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 './policy.ts';\nimport { AUTOCOMPACT_EVENT, createAutocompactTelemetry } from './logSinkTelemetry.ts';\nimport type { AutocompactEventAttributes, AutocompactTelemetry } from './logSinkTelemetry.ts';\nimport { parseModelReference, type SummarizationModel } from './summarizationModel.ts';\nexport { parseModelReference, resolveSummarizationModel } from './summarizationModel.ts';\nexport type { ModelReference, SummarizationModel } from './summarizationModel.ts';\nimport type { AutocompactContextDetails, AutocompactPass, AutocompactState } from './types.ts';\n\nconst ROOT_WORKING_LEAF = '@root';\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 TaskSnapshot {\n tasks: Task[];\n error?: string;\n}\n\ninterface TeamSnapshot {\n members?: NativeTeamMemberSnapshot[];\n error?: string;\n}\n\ninterface SteeringSnapshot {\n plan?: PlanSnapshot;\n taskSnapshot: TaskSnapshot;\n teamSnapshot: TeamSnapshot;\n readFiles: string[];\n modifiedFiles: string[];\n}\n\ninterface RuntimeTaskSnapshot {\n id: number;\n status: Task['status'];\n subject: string;\n activeForm?: string;\n owner?: string;\n blockedBy?: number[];\n delegation?: {\n agent: string;\n state: NonNullable<Task['delegation']>['state'];\n error?: string;\n };\n}\n\ninterface RuntimeStateSnapshot {\n planPath?: string;\n tasks: RuntimeTaskSnapshot[];\n taskError?: string;\n teamAvailable: boolean;\n teamMembers: NativeTeamMemberSnapshot[];\n teamError?: string;\n}\n\ninterface CheckpointGenerationInput {\n messages: CheckpointMessages;\n instructions: string;\n previousCheckpoint?: string;\n context: ExtensionContext;\n signal: AbortSignal;\n}\n\ninterface CheckpointWorkerResult {\n checkpoint?: string;\n error?: string;\n}\n\ninterface AutocompactDependencies {\n generateCheckpoint?: (input: CheckpointGenerationInput) => Promise<string>;\n readTaskSnapshot?: (context: ExtensionContext) => TaskSnapshot;\n readTeamSnapshot?: () => TeamSnapshot;\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\nfunction readTaskSnapshotWithDoomTask(context: ExtensionContext): TaskSnapshot {\n const failures: string[] = [];\n try {\n const store = new TaskStore({\n cwd: context.cwd,\n report: {\n error: (event, error) => failures.push(`${event}: ${errorMessage(error)}`),\n warn: (event, error) => failures.push(`${event}: ${errorMessage(error)}`),\n event: () => undefined,\n },\n });\n store.configureSession(resolveSessionKey(context.sessionManager.getSessionId()));\n const tasks = store.read().tasks;\n return { tasks, ...(failures.length > 0 ? { error: failures.join('; ') } : {}) };\n } catch (error) {\n return { tasks: [], error: errorMessage(error) };\n }\n}\n\nfunction readTeamSnapshotWithDoomTeam(): TeamSnapshot {\n try {\n const snapshot = readActiveNativeTeamSnapshot();\n return snapshot ? { members: snapshot.members } : {};\n } catch (error) {\n return { error: errorMessage(error) };\n }\n}\n\nfunction activeTaskSnapshots(snapshot: TaskSnapshot): RuntimeTaskSnapshot[] {\n return snapshot.tasks\n .filter((task) => task.status === 'pending' || task.status === 'in_progress' || task.status === 'failed')\n .map((task) => ({\n id: task.id,\n status: task.status,\n subject: task.subject,\n ...(task.activeForm ? { activeForm: task.activeForm } : {}),\n ...(task.owner ? { owner: task.owner } : {}),\n ...(task.blockedBy?.length ? { blockedBy: task.blockedBy } : {}),\n ...(task.delegation\n ? {\n delegation: {\n agent: task.delegation.agent,\n state: task.delegation.state,\n ...(task.delegation.result?.error ? { error: task.delegation.result.error } : {}),\n },\n }\n : {}),\n }));\n}\n\nfunction formatRuntimeTasks(tasks: RuntimeTaskSnapshot[], error?: string): string {\n const lines = tasks.map((task) => {\n const details = [\n task.activeForm ? `active: ${task.activeForm}` : undefined,\n task.owner ? `owner: ${task.owner}` : undefined,\n task.blockedBy?.length ? `blocked by: ${task.blockedBy.join(', ')}` : undefined,\n task.delegation ? `delegation: ${task.delegation.agent} (${task.delegation.state})` : undefined,\n task.delegation?.error ? `error: ${task.delegation.error}` : undefined,\n ].filter((value): value is string => Boolean(value));\n return `- #${task.id} [${task.status}] ${task.subject}${details.length > 0 ? ` | ${details.join(' | ')}` : ''}`;\n });\n if (error) lines.push(`- Task snapshot error: ${error}`);\n return lines.length > 0 ? lines.join('\\n') : '(no active tasks)';\n}\n\nfunction formatTeamSnapshot(snapshot: TeamSnapshot): string {\n const lines = (snapshot.members ?? []).map((member) => {\n const details = [\n `role: ${member.role}`,\n member.agent ? `agent: ${member.agent}` : undefined,\n member.runId ? `run: ${member.runId}` : undefined,\n member.task ? `task ${member.task.id}: ${member.task.subject}` : undefined,\n ].filter((value): value is string => Boolean(value));\n return `- ${member.name} | ${details.join(' | ')}`;\n });\n if (snapshot.error) lines.push(`- Team snapshot error: ${snapshot.error}`);\n if (lines.length > 0) return lines.join('\\n');\n return snapshot.members ? '(no active team members)' : '(team runtime unavailable)';\n}\n\nfunction runtimeStateSnapshot(\n branch: SessionEntry[],\n taskSnapshot: TaskSnapshot,\n teamSnapshot: TeamSnapshot,\n): RuntimeStateSnapshot {\n const plan = latestPlanSnapshot(branch);\n return {\n ...(plan ? { planPath: plan.path } : {}),\n tasks: activeTaskSnapshots(taskSnapshot),\n ...(taskSnapshot.error ? { taskError: taskSnapshot.error } : {}),\n teamAvailable: Boolean(teamSnapshot.members),\n teamMembers: teamSnapshot.members ?? [],\n ...(teamSnapshot.error ? { teamError: teamSnapshot.error } : {}),\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 const teamSnapshot: TeamSnapshot = {\n ...(snapshot.teamAvailable ? { members: snapshot.teamMembers } : {}),\n ...(snapshot.teamError ? { error: snapshot.teamError } : {}),\n };\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<active-tasks>\n${formatRuntimeTasks(snapshot.tasks, snapshot.taskError)}\n</active-tasks>\n<active-team>\n${formatTeamSnapshot(teamSnapshot)}\n</active-team>\n</compaction-runtime-state>`;\n}\n\nfunction runtimeTelemetryAttributes(snapshot: RuntimeStateSnapshot): AutocompactEventAttributes {\n return {\n 'autocompact.runtime.plan_present': Boolean(snapshot.planPath),\n 'autocompact.runtime.task_count': snapshot.tasks.length,\n 'autocompact.runtime.team_available': snapshot.teamAvailable,\n 'autocompact.runtime.team_member_count': snapshot.teamMembers.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,tasks,team,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<active-tasks>\n${formatRuntimeTasks(activeTaskSnapshots(snapshot.taskSnapshot), snapshot.taskSnapshot.error)}\n</active-tasks>\n<active-team>\n${formatTeamSnapshot(snapshot.teamSnapshot)}\n</active-team>\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, task, or team 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\nfunction runCheckpointWorker(workerInput: Record<string, unknown>, signal: AbortSignal): Promise<string> {\n return new Promise((resolve, reject) => {\n const worker = new Worker(new URL('./checkpointWorker.mjs', import.meta.url), { workerData: workerInput });\n let settled = false;\n\n const settle = (complete: () => void): void => {\n if (settled) return;\n settled = true;\n signal.removeEventListener('abort', abort);\n complete();\n };\n const abort = (): void => {\n settle(() => {\n void worker.terminate();\n reject(signal.reason instanceof Error ? signal.reason : new Error('Autocompact summarization aborted.'));\n });\n };\n\n worker.once('message', (result: CheckpointWorkerResult) => {\n settle(() => {\n if (typeof result.checkpoint === 'string') resolve(result.checkpoint);\n else reject(new Error(result.error ?? 'Autocompact summarization worker returned no checkpoint.'));\n });\n });\n worker.once('error', (error) => settle(() => reject(error)));\n worker.once('exit', (code) => {\n if (code !== 0) settle(() => reject(new Error(`Autocompact summarization worker exited with code ${code}.`)));\n });\n signal.addEventListener('abort', abort, { once: true });\n worker.unref();\n if (signal.aborted) abort();\n });\n}\n\nfunction subagentModelConfig(cwd: string): PlanningAgentConfig | undefined {\n try {\n return loadDoomConfig(getHarnessState().root ?? cwd).modes?.planning?.subagents;\n } catch {\n process.emitWarning(\n 'Doom autocompact planning configuration could not be loaded; using the active session model instead.',\n );\n return undefined;\n }\n}\n\n/** Explicit Doom model selection honors the configured planning subagent model. */\nexport function resolveDoomSummarizationModel(ctx: ExtensionContext): SummarizationModel | undefined {\n const configured = subagentModelConfig(ctx.cwd);\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\nasync 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 return runCheckpointWorker(\n {\n messages: input.messages,\n model: selection.model,\n reserveTokens: DEFAULT_COMPACTION_SETTINGS.reserveTokens,\n apiKey: auth.apiKey,\n headers: auth.headers,\n instructions: input.instructions,\n previousCheckpoint: input.previousCheckpoint,\n thinkingLevel: selection.thinkingLevel,\n env: auth.env,\n },\n input.signal,\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 registerAutocompactExtension(pi: ExtensionAPI, dependencies: AutocompactDependencies = {}): void {\n const resolveModel = dependencies.resolveModel ?? resolveDoomSummarizationModel;\n const generateCheckpoint =\n dependencies.generateCheckpoint ??\n ((input: CheckpointGenerationInput) => generateCheckpointWithPi(input, resolveModel));\n const readTaskSnapshot = dependencies.readTaskSnapshot ?? readTaskSnapshotWithDoomTask;\n const readTeamSnapshot = dependencies.readTeamSnapshot ?? readTeamSnapshotWithDoomTeam;\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 let state = createInitialState();\n let currentContext: ExtensionContext | undefined;\n let checkpointController: AbortController | undefined;\n const footerContribution = doomIntegrations\n ? registerDoomFooterContribution(pi, {\n source: FOOTER_SOURCE,\n id: 'autocompact',\n order: FOOTER_ORDER,\n })\n : { update: () => undefined, dispose: () => undefined };\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 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 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 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 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 const failCheckpoint = (requestId: string, error: unknown): void => {\n if (requestId !== state.requestId || state.phase !== STATE_PHASE.checkpointPending) return;\n const failedLeafId = state.snapshotLeafId;\n state.phase = STATE_PHASE.waiting;\n if (failedLeafId) state.lastAttemptLeafId = failedLeafId;\n clearPendingCheckpoint();\n persist();\n notify(\n currentContext,\n `Doom autocompact summarization pass ${state.pass} failed: ${error instanceof Error ? error.message : String(error)}`,\n 'error',\n );\n };\n\n const reportSnapshotFailures = (\n ctx: ExtensionContext,\n taskSnapshot: TaskSnapshot,\n teamSnapshot: TeamSnapshot,\n attributes: AutocompactEventAttributes,\n ): void => {\n if (taskSnapshot.error) {\n notify(ctx, `Doom autocompact task steering degraded: ${taskSnapshot.error}`, 'warning');\n void telemetry.recordWarning(AUTOCOMPACT_EVENT.taskSnapshotDegraded, new Error(taskSnapshot.error), attributes);\n }\n if (teamSnapshot.error) {\n notify(ctx, `Doom autocompact team steering degraded: ${teamSnapshot.error}`, 'warning');\n void telemetry.recordWarning(AUTOCOMPACT_EVENT.teamSnapshotDegraded, new Error(teamSnapshot.error), attributes);\n }\n };\n\n const preserveRuntimeState = (\n ctx: ExtensionContext,\n branch: SessionEntry[],\n attributes: AutocompactEventAttributes,\n ): RuntimeStateSnapshot => {\n const taskSnapshot = readTaskSnapshot(ctx);\n const teamSnapshot = readTeamSnapshot();\n reportSnapshotFailures(ctx, taskSnapshot, teamSnapshot, attributes);\n const snapshot = runtimeStateSnapshot(branch, taskSnapshot, teamSnapshot);\n pi.sendMessage({\n customType: RUNTIME_STATE_MESSAGE_TYPE,\n content: formatRuntimeState(snapshot),\n display: false,\n details: { version: 1, ...snapshot },\n });\n return snapshot;\n };\n\n const commitCheckpoint = (pass: 2 | 3, ctx: ExtensionContext): boolean => {\n if (!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 notify(ctx, `Doom autocompact pass ${pass} context commit started.`);\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 notify(ctx, `Doom autocompact context committed. Baseline will be captured from the next settled context.`);\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 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 taskSnapshot = readTaskSnapshot(ctx);\n const teamSnapshot = readTeamSnapshot();\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 reportSnapshotFailures(ctx, taskSnapshot, teamSnapshot, 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 notify(ctx, `Doom autocompact summarization pass ${pass} started.`);\n void 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 taskSnapshot,\n teamSnapshot,\n readFiles: state.readFiles,\n modifiedFiles: state.modifiedFiles,\n }),\n ...(previousCheckpoint ? { previousCheckpoint } : {}),\n context: ctx,\n signal: checkpointSignal,\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 await telemetry.recordError(AUTOCOMPACT_EVENT.checkpointFailed, error, attributes);\n throw error;\n }\n })\n .then((checkpoint) => {\n if (requestId !== state.requestId || state.phase !== STATE_PHASE.checkpointPending) return;\n state.phase = STATE_PHASE.checkpointReady;\n state.pendingCheckpoint = checkpoint.trim();\n persist();\n notify(currentContext, `Doom autocompact summarization pass ${pass} completed.`);\n if (currentContext) processProgress(currentContext);\n })\n .catch((error: unknown) => failCheckpoint(requestId, error));\n };\n\n const evaluateUsage = (ctx: ExtensionContext): boolean => {\n if (state.phase !== STATE_PHASE.waiting || ctx.hasPendingMessages()) 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 notify(ctx, `Doom autocompact baseline captured at ${state.baselineTokens} tokens.`);\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)) {\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 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 (state.phase !== STATE_PHASE.checkpointReady || !state.requestId || !state.pendingCheckpoint) return 'none';\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 = 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 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 currentContext = ctx;\n if (!ctx.isIdle()) return;\n if (captureReadyCheckpoint(ctx) !== 'committed') evaluateUsage(ctx);\n }\n\n pi.on('context', (event, ctx) => {\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 pi.on('session_start', (_event, ctx) => {\n currentContext = ctx;\n restore(ctx);\n processProgress(ctx);\n });\n\n pi.on('session_tree', (_event, ctx) => {\n currentContext = ctx;\n restore(ctx);\n processProgress(ctx);\n });\n\n pi.on('turn_end', (event, ctx) => {\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 processProgress(ctx);\n });\n\n pi.on('session_before_compact', (event) => {\n if (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 // 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 notify(\n ctx,\n `Doom autocompact completed. Baseline will be captured from the next settled context. Next pass: ${state.pass}.`,\n );\n });\n\n pi.on('session_shutdown', async () => {\n checkpointController?.abort();\n checkpointController = undefined;\n footerContribution.dispose();\n currentContext = undefined;\n appliedContextRequests.clear();\n invalidContextLeaves.clear();\n state = createInitialState();\n await telemetry.shutdown();\n });\n}\n"],"mappings":"kcAgDA,MAAM,EAAoB,QAKpB,EAAc,CAClB,QAAS,UACT,kBAAmB,qBACnB,gBAAiB,mBACjB,WAAY,aACb,CAwED,SAAS,EACP,EACA,EAAyC,EAAE,CACf,CAC5B,MAAO,CACL,gBAAiB,EAAQ,eAAe,cAAc,CACtD,GAAG,EACJ,CAGH,SAAS,EAAqB,EAAsD,CAClF,IAAK,IAAI,EAAQ,EAAO,OAAS,EAAG,GAAS,EAAG,IAAY,CAC1D,IAAM,EAAQ,EAAO,GACrB,GAAI,GAAO,OAAS,UAAY,EAAM,aAAA,yBAAkC,SACxE,IAAM,EAASA,EAAAA,WAAW,EAAM,KAAK,CACrC,GAAI,EAAQ,OAAO,GAKvB,SAAS,EAAc,EAA+B,CACpD,IAAK,IAAM,KAAS,EAAI,eAAe,WAAW,CAAC,YAAY,CACzD,OAAM,OAAS,UAAY,EAAM,aAAA,2BACjC,EAAM,OAAS,QACnB,OAAO,EAAM,GAEf,OAAO,EAGT,SAAS,EAAa,EAAwB,CAC5C,OAAO,aAAiB,MAAQ,EAAM,QAAU,OAAO,EAAM,CAG/D,SAAS,EAAmB,EAAkD,CAC5E,IAAK,IAAM,KAAS,EAAO,YAAY,CAAE,CACvC,GAAI,EAAM,OAAS,UAAY,EAAM,aAAe,8BAAqB,SACzE,GAAI,CAAC,EAAM,MAAQ,OAAO,EAAM,MAAS,SAAU,OACnD,IAAM,EAAO,EAAM,KAEnB,OADI,OAAO,EAAK,SAAY,UAAY,OAAO,EAAK,MAAS,SAAU,OAChE,CAAE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1B,EAAM,gBAAkB,EACxB,OAAO,EAAM,kBAEb,EAAG,SAAS,EAAM,gBAAgB,GAAI,gBAAgB,EAAM,MAAM,WAAW,CAC7E,IAAM,EAAiB,EAAM,MACvB,EAAoB,EAAoB,EAAK,CACjD,oBAAqB,EACrB,4BAA6B,EAAM,OACpC,CAAC,CACI,EAAkB,EAAqB,EAAK,EAAI,eAAe,WAAW,CAAE,EAAkB,CACpG,EAAM,OAAS,EACf,EAAM,KAAO,EACb,GAAS,CACJ,EAAU,YACbF,EAAAA,kBAAkB,0BAClB,EAAoB,EAAK,CACvB,oBAAqB,EACrB,4BAA6B,EAAM,OACnC,oCAAqC,EAAM,cAC3C,4BAA6B,EAAM,gBAAgB,aACnD,GAAG,EAA2B,EAAgB,CAC/C,CAAC,CACH,CACD,EACE,EACA,mGAAmG,EAAM,KAAK,GAC/G,EACD,CAEF,EAAG,GAAG,mBAAoB,SAAY,CACpC,GAAsB,OAAO,CAC7B,EAAuB,IAAA,GACvB,EAAmB,SAAS,CAC5B,EAAiB,IAAA,GACjB,EAAuB,OAAO,CAC9B,EAAqB,OAAO,CAC5B,EAAQH,EAAAA,oBAAoB,CAC5B,MAAM,EAAU,UAAU,EAC1B"}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { AutocompactTelemetry } from "./logSinkTelemetry.cjs";
|
|
2
|
+
import { SummarizationModel } from "./summarizationModel.cjs";
|
|
3
|
+
import { ExtensionAPI, ExtensionContext, buildSessionContext } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
import { Task } from "@agimon-ai/doompi-task/store/types";
|
|
5
|
+
import { NativeTeamMemberSnapshot } from "@agimon-ai/doompi-team/api/team-snapshot";
|
|
6
|
+
|
|
7
|
+
//#region src/extension.d.ts
|
|
8
|
+
type CheckpointMessages = ReturnType<typeof buildSessionContext>['messages'];
|
|
9
|
+
interface TaskSnapshot {
|
|
10
|
+
tasks: Task[];
|
|
11
|
+
error?: string;
|
|
12
|
+
}
|
|
13
|
+
interface TeamSnapshot {
|
|
14
|
+
members?: NativeTeamMemberSnapshot[];
|
|
15
|
+
error?: string;
|
|
16
|
+
}
|
|
17
|
+
interface CheckpointGenerationInput {
|
|
18
|
+
messages: CheckpointMessages;
|
|
19
|
+
instructions: string;
|
|
20
|
+
previousCheckpoint?: string;
|
|
21
|
+
context: ExtensionContext;
|
|
22
|
+
signal: AbortSignal;
|
|
23
|
+
}
|
|
24
|
+
interface AutocompactDependencies {
|
|
25
|
+
generateCheckpoint?: (input: CheckpointGenerationInput) => Promise<string>;
|
|
26
|
+
readTaskSnapshot?: (context: ExtensionContext) => TaskSnapshot;
|
|
27
|
+
readTeamSnapshot?: () => TeamSnapshot;
|
|
28
|
+
resolveModel?: (context: ExtensionContext) => SummarizationModel | undefined;
|
|
29
|
+
telemetry?: AutocompactTelemetry;
|
|
30
|
+
doomIntegrations?: boolean;
|
|
31
|
+
}
|
|
32
|
+
/** Explicit Doom model selection honors the configured planning subagent model. */
|
|
33
|
+
declare function registerAutocompactExtension(pi: ExtensionAPI, dependencies?: AutocompactDependencies): void;
|
|
34
|
+
//#endregion
|
|
35
|
+
export { registerAutocompactExtension };
|
|
36
|
+
//# sourceMappingURL=extension.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"extension.d.cts","names":[],"sources":["../src/extension.ts"],"mappings":";;;;;;;KA4DK,kBAAA,GAAqB,UAAA,QAAkB,mBAAA;AAAA,UAOlC,YAAA;EACR,KAAA,EAAO,IAAA;EACP,KAAA;AAAA;AAAA,UAGQ,YAAA;EACR,OAAA,GAAU,wBAAA;EACV,KAAA;AAAA;AAAA,UAkCQ,yBAAA;EACR,QAAA,EAAU,kBAAA;EACV,YAAA;EACA,kBAAA;EACA,OAAA,EAAS,gBAAA;EACT,MAAA,EAAQ,WAAA;AAAA;AAAA,UAQA,uBAAA;EACR,kBAAA,IAAsB,KAAA,EAAO,yBAAA,KAA8B,OAAA;EAC3D,gBAAA,IAAoB,OAAA,EAAS,gBAAA,KAAqB,YAAA;EAClD,gBAAA,SAAyB,YAAA;EACzB,YAAA,IAAgB,OAAA,EAAS,gBAAA,KAAqB,kBAAA;EAC9C,SAAA,GAAY,oBAAA;EACZ,gBAAA;AAAA;;iBAyUc,4BAAA,CAA6B,EAAA,EAAI,YAAA,EAAc,YAAA,GAAc,uBAAA"}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { AutocompactTelemetry } from "./logSinkTelemetry.mjs";
|
|
2
|
+
import { SummarizationModel } from "./summarizationModel.mjs";
|
|
3
|
+
import { NativeTeamMemberSnapshot } from "@agimon-ai/doompi-team/api/team-snapshot";
|
|
4
|
+
import { ExtensionAPI, ExtensionContext, buildSessionContext } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import { Task } from "@agimon-ai/doompi-task/store/types";
|
|
6
|
+
|
|
7
|
+
//#region src/extension.d.ts
|
|
8
|
+
type CheckpointMessages = ReturnType<typeof buildSessionContext>['messages'];
|
|
9
|
+
interface TaskSnapshot {
|
|
10
|
+
tasks: Task[];
|
|
11
|
+
error?: string;
|
|
12
|
+
}
|
|
13
|
+
interface TeamSnapshot {
|
|
14
|
+
members?: NativeTeamMemberSnapshot[];
|
|
15
|
+
error?: string;
|
|
16
|
+
}
|
|
17
|
+
interface CheckpointGenerationInput {
|
|
18
|
+
messages: CheckpointMessages;
|
|
19
|
+
instructions: string;
|
|
20
|
+
previousCheckpoint?: string;
|
|
21
|
+
context: ExtensionContext;
|
|
22
|
+
signal: AbortSignal;
|
|
23
|
+
}
|
|
24
|
+
interface AutocompactDependencies {
|
|
25
|
+
generateCheckpoint?: (input: CheckpointGenerationInput) => Promise<string>;
|
|
26
|
+
readTaskSnapshot?: (context: ExtensionContext) => TaskSnapshot;
|
|
27
|
+
readTeamSnapshot?: () => TeamSnapshot;
|
|
28
|
+
resolveModel?: (context: ExtensionContext) => SummarizationModel | undefined;
|
|
29
|
+
telemetry?: AutocompactTelemetry;
|
|
30
|
+
doomIntegrations?: boolean;
|
|
31
|
+
}
|
|
32
|
+
/** Explicit Doom model selection honors the configured planning subagent model. */
|
|
33
|
+
declare function registerAutocompactExtension(pi: ExtensionAPI, dependencies?: AutocompactDependencies): void;
|
|
34
|
+
//#endregion
|
|
35
|
+
export { registerAutocompactExtension };
|
|
36
|
+
//# sourceMappingURL=extension.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"extension.d.mts","names":[],"sources":["../src/extension.ts"],"mappings":";;;;;;;KA4DK,kBAAA,GAAqB,UAAA,QAAkB,mBAAA;AAAA,UAOlC,YAAA;EACR,KAAA,EAAO,IAAA;EACP,KAAA;AAAA;AAAA,UAGQ,YAAA;EACR,OAAA,GAAU,wBAAA;EACV,KAAA;AAAA;AAAA,UAkCQ,yBAAA;EACR,QAAA,EAAU,kBAAA;EACV,YAAA;EACA,kBAAA;EACA,OAAA,EAAS,gBAAA;EACT,MAAA,EAAQ,WAAA;AAAA;AAAA,UAQA,uBAAA;EACR,kBAAA,IAAsB,KAAA,EAAO,yBAAA,KAA8B,OAAA;EAC3D,gBAAA,IAAoB,OAAA,EAAS,gBAAA,KAAqB,YAAA;EAClD,gBAAA,SAAyB,YAAA;EACzB,YAAA,IAAgB,OAAA,EAAS,gBAAA,KAAqB,kBAAA;EAC9C,SAAA,GAAY,oBAAA;EACZ,gBAAA;AAAA;;iBAyUc,4BAAA,CAA6B,EAAA,EAAI,YAAA,EAAc,YAAA,GAAc,uBAAA"}
|
|
@@ -0,0 +1,50 @@
|
|
|
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"./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 v,thresholdTokens as ee,withCanonicalFileSections as te}from"./policy.mjs";import{AUTOCOMPACT_EVENT as y,createAutocompactTelemetry as ne}from"./logSinkTelemetry.mjs";import{parseModelReference as b}from"./summarizationModel.mjs";import{Worker as x}from"node:worker_threads";import{getHarnessState as S,loadDoomConfig as C}from"@agimon-ai/doompi-config";import{registerDoomFooterContribution as re}from"@agimon-ai/doompi-ui/footer";import{resolveSessionKey as w}from"@agimon-ai/doompi-task/store/paths";import{TaskStore as T}from"@agimon-ai/doompi-task/store/taskStore";import{readActiveNativeTeamSnapshot as E}from"@agimon-ai/doompi-team/api/team-snapshot";import{DEFAULT_COMPACTION_SETTINGS as D,buildSessionContext as O,sessionEntryToContextMessages as k}from"@earendil-works/pi-coding-agent";const A=`@root`,j={waiting:`waiting`,checkpointPending:`checkpoint_pending`,checkpointReady:`checkpoint_ready`,compacting:`compacting`};function M(e,t={}){return{"pi.session.id":e.sessionManager.getSessionId(),...t}}function ie(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 N(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 A}function P(e){return e instanceof Error?e.message:String(e)}function F(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}}}function I(e){let t=[];try{let n=new T({cwd:e.cwd,report:{error:(e,n)=>t.push(`${e}: ${P(n)}`),warn:(e,n)=>t.push(`${e}: ${P(n)}`),event:()=>void 0}});return n.configureSession(w(e.sessionManager.getSessionId())),{tasks:n.read().tasks,...t.length>0?{error:t.join(`; `)}:{}}}catch(e){return{tasks:[],error:P(e)}}}function ae(){try{let e=E();return e?{members:e.members}:{}}catch(e){return{error:P(e)}}}function L(e){return e.tasks.filter(e=>e.status===`pending`||e.status===`in_progress`||e.status===`failed`).map(e=>({id:e.id,status:e.status,subject:e.subject,...e.activeForm?{activeForm:e.activeForm}:{},...e.owner?{owner:e.owner}:{},...e.blockedBy?.length?{blockedBy:e.blockedBy}:{},...e.delegation?{delegation:{agent:e.delegation.agent,state:e.delegation.state,...e.delegation.result?.error?{error:e.delegation.result.error}:{}}}:{}}))}function R(e,t){let n=e.map(e=>{let t=[e.activeForm?`active: ${e.activeForm}`:void 0,e.owner?`owner: ${e.owner}`:void 0,e.blockedBy?.length?`blocked by: ${e.blockedBy.join(`, `)}`:void 0,e.delegation?`delegation: ${e.delegation.agent} (${e.delegation.state})`:void 0,e.delegation?.error?`error: ${e.delegation.error}`:void 0].filter(e=>!!e);return`- #${e.id} [${e.status}] ${e.subject}${t.length>0?` | ${t.join(` | `)}`:``}`});return t&&n.push(`- Task snapshot error: ${t}`),n.length>0?n.join(`
|
|
2
|
+
`):`(no active tasks)`}function z(e){let t=(e.members??[]).map(e=>{let t=[`role: ${e.role}`,e.agent?`agent: ${e.agent}`:void 0,e.runId?`run: ${e.runId}`:void 0,e.task?`task ${e.task.id}: ${e.task.subject}`:void 0].filter(e=>!!e);return`- ${e.name} | ${t.join(` | `)}`});return e.error&&t.push(`- Team snapshot error: ${e.error}`),t.length>0?t.join(`
|
|
3
|
+
`):e.members?`(no active team members)`:`(team runtime unavailable)`}function oe(e,t,n){let r=F(e);return{...r?{planPath:r.path}:{},tasks:L(t),...t.error?{taskError:t.error}:{},teamAvailable:!!n.members,teamMembers:n.members??[],...n.error?{teamError:n.error}:{}}}function se(e){let t=e.planPath?`Source: ${e.planPath}\nExact plan content is restored separately by Doom Plan.`:`(no active plan document)`,n={...e.teamAvailable?{members:e.teamMembers}:{},...e.teamError?{error:e.teamError}:{}};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
|
+
${t}
|
|
7
|
+
</active-plan>
|
|
8
|
+
<active-tasks>
|
|
9
|
+
${R(e.tasks,e.taskError)}
|
|
10
|
+
</active-tasks>
|
|
11
|
+
<active-team>
|
|
12
|
+
${z(n)}
|
|
13
|
+
</active-team>
|
|
14
|
+
</compaction-runtime-state>`}function B(e){return{"autocompact.runtime.plan_present":!!e.planPath,"autocompact.runtime.task_count":e.tasks.length,"autocompact.runtime.team_available":e.teamAvailable,"autocompact.runtime.team_member_count":e.teamMembers.length}}function V(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,tasks,team,important-context,recent-messages">
|
|
15
|
+
<user-prompt source="conversation">
|
|
16
|
+
Treat the user's explicit goals, constraints, corrections, and preferences in the conversation as authoritative. Newer user instructions override older ones.
|
|
17
|
+
</user-prompt>
|
|
18
|
+
<active-plan>
|
|
19
|
+
${t}
|
|
20
|
+
</active-plan>
|
|
21
|
+
<active-tasks>
|
|
22
|
+
${R(L(e.taskSnapshot),e.taskSnapshot.error)}
|
|
23
|
+
</active-tasks>
|
|
24
|
+
<active-team>
|
|
25
|
+
${z(e.teamSnapshot)}
|
|
26
|
+
</active-team>
|
|
27
|
+
<important-context>
|
|
28
|
+
${n.length>0?n.join(`
|
|
29
|
+
`):`(none recorded outside the conversation)`}
|
|
30
|
+
</important-context>
|
|
31
|
+
</compaction-steering>`}function ce(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.
|
|
32
|
+
|
|
33
|
+
`:``;return`Create Doom autocompact checkpoint pass ${e}.
|
|
34
|
+
|
|
35
|
+
${V(t)}
|
|
36
|
+
|
|
37
|
+
Apply the steering evidence in priority order. Do not invent plan, task, or team state. Preserve verified facts and mark unresolved inference explicitly. Newer evidence replaces superseded information.
|
|
38
|
+
|
|
39
|
+
${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.
|
|
40
|
+
|
|
41
|
+
## Goal
|
|
42
|
+
## Constraints & Preferences
|
|
43
|
+
## Progress
|
|
44
|
+
### Done
|
|
45
|
+
### In Progress
|
|
46
|
+
### Blocked
|
|
47
|
+
## Key Decisions
|
|
48
|
+
## Next Steps
|
|
49
|
+
## Critical Context`}function le(e,t,n){let r=_(O(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=>k(e))}function H(e,t){return new Promise((n,r)=>{let i=new x(new URL(`./checkpointWorker.mjs`,import.meta.url),{workerData:e}),a=!1,o=e=>{a||(a=!0,t.removeEventListener(`abort`,s),e())},s=()=>{o(()=>{i.terminate(),r(t.reason instanceof Error?t.reason:Error(`Autocompact summarization aborted.`))})};i.once(`message`,e=>{o(()=>{typeof e.checkpoint==`string`?n(e.checkpoint):r(Error(e.error??`Autocompact summarization worker returned no checkpoint.`))})}),i.once(`error`,e=>o(()=>r(e))),i.once(`exit`,e=>{e!==0&&o(()=>r(Error(`Autocompact summarization worker exited with code ${e}.`)))}),t.addEventListener(`abort`,s,{once:!0}),i.unref(),t.aborted&&s()})}function U(e){try{return C(S().root??e).modes?.planning?.subagents}catch{process.emitWarning(`Doom autocompact planning configuration could not be loaded; using the active session model instead.`);return}}function ue(e){let t=U(e.cwd),n=t?.model?b(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 de(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);return H({messages:e.messages,model:n.model,reserveTokens:D.reserveTokens,apiKey:r.apiKey,headers:r.headers,instructions:e.instructions,previousCheckpoint:e.previousCheckpoint,thinkingLevel:n.thinkingLevel,env:r.env},e.signal)}function W(e,t,n=`info`){e?.hasUI&&e.ui.notify(t,n)}function G(g,b={}){let x=b.resolveModel??ue,S=b.generateCheckpoint??(e=>de(e,x)),C=b.readTaskSnapshot??I,w=b.readTeamSnapshot??ae,T=b.telemetry??ne(),E=b.doomIntegrations??!0,D=new Set,k=new Set,P=c(),L,R,z=E?re(g,{source:`doom-autocompact`,id:`autocompact`,order:20}):{update:()=>void 0,dispose:()=>void 0},V=e=>{let t=P.phase===j.checkpointPending?`summarizing`:P.phase===j.checkpointReady?`applying`:void 0;z.update(t?{fullText:`Compacting p${P.pass}`,compactText:`C${P.pass}`}:void 0);let n=e??L;n?.hasUI&&n.ui.setStatus(`doom-autocompact`,t?`Compacting pass ${P.pass} (${t})…`:void 0)},H=()=>{g.appendEntry(i,{...P}),V()},U=()=>{delete P.requestId,delete P.snapshotLeafId,delete P.snapshotTokens,delete P.pendingCheckpoint,delete P.compactionPass},G=e=>{P.checkpointQueue=P.checkpointQueue.filter(t=>t!==e)},K=e=>{P=ie(e.sessionManager.getBranch())??c(),!(P.phase===j.checkpointReady&&P.requestId&&P.snapshotLeafId&&P.pendingCheckpoint||P.phase===j.waiting)&&(R?.abort(),R=void 0,P.phase=j.waiting,U(),H())},q=e=>{g.sendMessage({customType:n,content:`${e} Continue from the compacted checkpoint's immediate next action without repeating completed work.`,display:!1,details:{version:2,cycle:P.cycle,pass:P.pass}},{triggerTurn:!0,deliverAs:`steer`})},fe=(e,t)=>{if(e!==P.requestId||P.phase!==j.checkpointPending)return;let n=P.snapshotLeafId;P.phase=j.waiting,n&&(P.lastAttemptLeafId=n),U(),H(),W(L,`Doom autocompact summarization pass ${P.pass} failed: ${t instanceof Error?t.message:String(t)}`,`error`)},J=(e,t,n,r)=>{t.error&&(W(e,`Doom autocompact task steering degraded: ${t.error}`,`warning`),T.recordWarning(y.taskSnapshotDegraded,Error(t.error),r)),n.error&&(W(e,`Doom autocompact team steering degraded: ${n.error}`,`warning`),T.recordWarning(y.teamSnapshotDegraded,Error(n.error),r))},Y=(e,t,n)=>{let i=C(e),a=w();J(e,i,a,n);let o=oe(t,i,a);return g.sendMessage({customType:r,content:se(o),display:!1,details:{version:1,...o}}),o},pe=(e,n)=>{if(!P.requestId||!P.snapshotLeafId||!P.pendingCheckpoint)return!1;let r=n.sessionManager.getBranch(),i=_(O(r).messages,r).messages,a=m(P,d(i)),o=P.requestId,s=P.cycle,c=te(P.pendingCheckpoint,a),l={...a,doomAutocompact:{version:2,cycle:s,pass:e,requestId:o,snapshotLeafId:P.snapshotLeafId,tokensBefore:P.snapshotTokens??n.getContextUsage()?.tokens??0},retainedMessages:v(r,P.snapshotLeafId)};W(n,`Doom autocompact pass ${e} context commit started.`);let u=n.isIdle();g.sendMessage({customType:t,content:c,display:!1,details:l});let f=N(n),p=Y(n,r,M(n,{"autocompact.request.id":o,"autocompact.cycle":s,"autocompact.pass":e}));return u&&g.setLabel(f,`autocompact:c${s}:p${e}`),P.readFiles=a.readFiles,P.modifiedFiles=a.modifiedFiles,delete P.latestCheckpointSnapshotLeafId,P.phase=j.waiting,P.checkpointQueue=[],P.exhaustedPasses=[],P.invalidAttempts=0,P.baselinePending=!0,delete P.lastAttemptLeafId,U(),P.cycle+=1,P.pass=1,H(),T.recordEvent(y.contextCommitted,M(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`,...B(p)})),W(n,`Doom autocompact context committed. Baseline will be captured from the next settled context.`),u&&q(`Asynchronous compaction completed.`),!0},me=(e,t,n)=>{let r=t.sessionManager.getBranch(),i=N(t),a=l(t.sessionManager.getSessionId(),P.cycle,e,i),o=e>1?s(p(r)):void 0,c=le(e,r,P.latestCheckpointSnapshotLeafId),u=C(t),d=w(),f=M(t,{"autocompact.request.id":a,"autocompact.cycle":P.cycle,"autocompact.pass":e,"autocompact.snapshot_leaf_id":i,"autocompact.tokens_before":n,"autocompact.message_count.before":c.length});J(t,u,d,f),P.phase=j.checkpointPending,P.pass=e,P.requestId=a,P.snapshotLeafId=i,P.snapshotTokens=n,delete P.pendingCheckpoint,delete P.compactionPass,delete P.lastAttemptLeafId,H(),R?.abort(),R=new AbortController;let m=R.signal;W(t,`Doom autocompact summarization pass ${e} started.`),T.runInSpan(`doom_autocompact.checkpoint`,f,async()=>{await T.recordEvent(y.checkpointStarted,f);try{let n=await S({messages:c,instructions:ce(e,{plan:F(r),taskSnapshot:u,teamSnapshot:d,readFiles:P.readFiles,modifiedFiles:P.modifiedFiles}),...o?{previousCheckpoint:o}:{},context:t,signal:m});if(!n.trim())throw Error(`Summarization returned an empty checkpoint.`);return await T.recordEvent(y.checkpointCompleted,{...f,"autocompact.checkpoint.characters":n.length}),n}catch(e){throw await T.recordError(y.checkpointFailed,e,f),e}}).then(t=>{a!==P.requestId||P.phase!==j.checkpointPending||(P.phase=j.checkpointReady,P.pendingCheckpoint=t.trim(),H(),W(L,`Doom autocompact summarization pass ${e} completed.`),L&&$(L))}).catch(e=>fe(a,e))},X=e=>{if(P.phase!==j.waiting||e.hasPendingMessages())return!1;let t=e.getContextUsage();if(!t||t.tokens===null)return!1;if(P.baselinePending)return a(e.sessionManager.getBranch())?(P.baselineTokens=t.tokens,P.baselinePending=!1,H(),W(e,`Doom autocompact baseline captured at ${P.baselineTokens} tokens.`),!1):!1;let n=N(e);if(P.lastAttemptLeafId===n)return!1;for(let e of[1,2,3])e<P.pass||P.checkpointQueue.includes(e)||P.exhaustedPasses.includes(e)||t.tokens>=ee(e,t.contextWindow,P.baselineTokens)&&P.checkpointQueue.push(e);let r=P.checkpointQueue[0];return r?(me(r,e,t.tokens),!0):!1},Z=(t,n)=>{let r=P.snapshotLeafId;g.appendEntry(e,{...o(P.cycle,t,P.requestId??`completed`),summary:n}),r&&(P.latestCheckpointSnapshotLeafId=r)},Q=e=>{if(P.phase!==j.checkpointReady||!P.requestId||!P.pendingCheckpoint)return`none`;let t=P.pass,n=h(P.pendingCheckpoint);if(!f(n.summary)){let n=P.snapshotLeafId,r=P.requestId,i=P.invalidAttempts+1,a=i>=3;P.phase=j.waiting,n&&(P.lastAttemptLeafId=n),a?(G(t),P.exhaustedPasses=[...P.exhaustedPasses,t],P.invalidAttempts=0):P.invalidAttempts=i,U(),H();let o=Error(`Summarization pass ${t} returned an incomplete checkpoint.`);return W(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`),T.recordError(y.checkpointInvalid,o,M(e,{"autocompact.cycle":P.cycle,"autocompact.pass":t,"autocompact.checkpoint.attempts":i,"autocompact.checkpoint.exhausted":a,...r?{"autocompact.request.id":r}:{}})),`invalid`}return P.invalidAttempts=0,t===1?(Z(1,n.summary),G(1),P.phase=j.waiting,P.pass=2,U(),H(),`pass1`):t===2&&n.shouldCompact!==!0?(Z(2,n.summary),G(2),P.phase=j.waiting,P.pass=3,U(),H(),`deferred`):(P.pendingCheckpoint=n.summary,pe(t,e)?`committed`:`invalid`)};function $(e){L=e,e.isIdle()&&Q(e)!==`committed`&&X(e)}g.on(`context`,(e,t)=>{let n=_(e.messages,t.sessionManager.getBranch());if(n.invalidMarker){let e=t.sessionManager.getLeafId()??A;k.has(e)||(k.add(e),T.recordError(y.contextMarkerInvalid,Error(`Doom autocompact context marker is malformed.`),M(t,{"autocompact.leaf_id":e})));return}if(n.marker)return D.has(n.marker.requestId)||(D.add(n.marker.requestId),T.recordEvent(y.contextApplied,M(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}}),g.on(`session_start`,(e,t)=>{L=t,K(t),$(t)}),g.on(`session_tree`,(e,t)=>{L=t,K(t),$(t)}),g.on(`turn_end`,(e,t)=>{if(L=t,t.isIdle()){$(t);return}P.phase===j.checkpointReady&&(e.toolResults?.length??0)>0&&!t.hasPendingMessages()&&Q(t)!==`none`||X(t)}),g.on(`agent_settled`,(e,t)=>{$(t)}),g.on(`session_before_compact`,e=>{if(e.reason===`threshold`)return P.phase===j.checkpointPending||P.phase===j.checkpointReady||P.baselinePending?{cancel:!0}:void 0}),g.on(`session_compact`,(e,t)=>{R?.abort(),R=void 0;let n=u(e.compactionEntry.details),r=m(P,void 0,n);P.readFiles=r.readFiles,P.modifiedFiles=r.modifiedFiles,delete P.latestCheckpointSnapshotLeafId,P.baselinePending=!0,P.phase=j.waiting,U(),P.checkpointQueue=[],P.exhaustedPasses=[],P.invalidAttempts=0,delete P.lastAttemptLeafId,g.setLabel(e.compactionEntry.id,`autocompact:c${P.cycle}:external`);let i=P.cycle,a=M(t,{"autocompact.cycle":i,"autocompact.native.reason":e.reason}),o=Y(t,t.sessionManager.getBranch(),a);P.cycle+=1,P.pass=1,H(),T.recordEvent(y.nativeCompactionCompleted,M(t,{"autocompact.cycle":i,"autocompact.native.reason":e.reason,"autocompact.native.from_extension":e.fromExtension,"autocompact.tokens_before":e.compactionEntry.tokensBefore,...B(o)})),W(t,`Doom autocompact completed. Baseline will be captured from the next settled context. Next pass: ${P.pass}.`)}),g.on(`session_shutdown`,async()=>{R?.abort(),R=void 0,z.dispose(),L=void 0,D.clear(),k.clear(),P=c(),await T.shutdown()})}export{G as registerAutocompactExtension};
|
|
50
|
+
//# sourceMappingURL=extension.mjs.map
|