@agimon-ai/doompi-autocompact 0.0.1-alpha.2 → 0.0.1-alpha.21

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.
Files changed (96) hide show
  1. package/README.md +21 -16
  2. package/dist/adapters/pi/extension.cjs +50 -0
  3. package/dist/adapters/pi/extension.cjs.map +1 -0
  4. package/dist/{extension.d.cts → adapters/pi/extension.d.cts} +3 -4
  5. package/dist/adapters/pi/extension.d.cts.map +1 -0
  6. package/dist/{extension.d.mts → adapters/pi/extension.d.mts} +3 -4
  7. package/dist/adapters/pi/extension.d.mts.map +1 -0
  8. package/dist/adapters/pi/extension.mjs +50 -0
  9. package/dist/adapters/pi/extension.mjs.map +1 -0
  10. package/dist/adapters/process/checkpointWorker.cjs +2 -0
  11. package/dist/adapters/process/checkpointWorker.cjs.map +1 -0
  12. package/dist/adapters/process/checkpointWorker.mjs +2 -0
  13. package/dist/adapters/process/checkpointWorker.mjs.map +1 -0
  14. package/dist/adapters/telemetry/logSinkTelemetry.cjs.map +1 -0
  15. package/dist/{logSinkTelemetry.d.cts → adapters/telemetry/logSinkTelemetry.d.cts} +1 -1
  16. package/dist/adapters/telemetry/logSinkTelemetry.d.cts.map +1 -0
  17. package/dist/{logSinkTelemetry.d.mts → adapters/telemetry/logSinkTelemetry.d.mts} +1 -1
  18. package/dist/adapters/telemetry/logSinkTelemetry.d.mts.map +1 -0
  19. package/dist/adapters/telemetry/logSinkTelemetry.mjs.map +1 -0
  20. package/dist/checkpointWorker.cjs +1 -2
  21. package/dist/checkpointWorker.mjs +1 -2
  22. package/dist/extensions/pi.cjs +1 -1
  23. package/dist/extensions/pi.cjs.map +1 -1
  24. package/dist/extensions/pi.d.cts +1 -1
  25. package/dist/extensions/pi.d.mts +1 -1
  26. package/dist/extensions/pi.mjs +1 -1
  27. package/dist/extensions/pi.mjs.map +1 -1
  28. package/dist/index.cjs +1 -1
  29. package/dist/index.d.cts +3 -3
  30. package/dist/index.d.mts +3 -3
  31. package/dist/index.mjs +1 -1
  32. package/dist/{policy.cjs → services/compaction/policy.cjs} +1 -1
  33. package/dist/services/compaction/policy.cjs.map +1 -0
  34. package/dist/{policy.d.cts → services/compaction/policy.d.cts} +2 -2
  35. package/dist/services/compaction/policy.d.cts.map +1 -0
  36. package/dist/{policy.d.mts → services/compaction/policy.d.mts} +2 -2
  37. package/dist/services/compaction/policy.d.mts.map +1 -0
  38. package/dist/{policy.mjs → services/compaction/policy.mjs} +1 -1
  39. package/dist/services/compaction/policy.mjs.map +1 -0
  40. package/dist/services/compaction/standard.cjs +2 -0
  41. package/dist/services/compaction/standard.cjs.map +1 -0
  42. package/dist/{standard.d.cts → services/compaction/standard.d.cts} +1 -1
  43. package/dist/services/compaction/standard.d.cts.map +1 -0
  44. package/dist/{standard.d.mts → services/compaction/standard.d.mts} +1 -1
  45. package/dist/services/compaction/standard.d.mts.map +1 -0
  46. package/dist/services/compaction/standard.mjs +2 -0
  47. package/dist/services/compaction/standard.mjs.map +1 -0
  48. package/dist/services/compaction/summarizationModel.cjs.map +1 -0
  49. package/dist/{summarizationModel.d.cts → services/compaction/summarizationModel.d.cts} +1 -1
  50. package/dist/services/compaction/summarizationModel.d.cts.map +1 -0
  51. package/dist/{summarizationModel.d.mts → services/compaction/summarizationModel.d.mts} +1 -1
  52. package/dist/services/compaction/summarizationModel.d.mts.map +1 -0
  53. package/dist/services/compaction/summarizationModel.mjs.map +1 -0
  54. package/dist/types/constants.cjs.map +1 -0
  55. package/dist/types/constants.mjs.map +1 -0
  56. package/dist/{types.d.cts → types/index.d.cts} +2 -2
  57. package/dist/types/index.d.cts.map +1 -0
  58. package/dist/{types.d.mts → types/index.d.mts} +2 -2
  59. package/dist/types/index.d.mts.map +1 -0
  60. package/package.json +15 -8
  61. package/dist/checkpointWorker.cjs.map +0 -1
  62. package/dist/checkpointWorker.mjs.map +0 -1
  63. package/dist/constants.cjs.map +0 -1
  64. package/dist/constants.mjs.map +0 -1
  65. package/dist/extension.cjs +0 -50
  66. package/dist/extension.cjs.map +0 -1
  67. package/dist/extension.d.cts.map +0 -1
  68. package/dist/extension.d.mts.map +0 -1
  69. package/dist/extension.mjs +0 -50
  70. package/dist/extension.mjs.map +0 -1
  71. package/dist/logSinkTelemetry.cjs.map +0 -1
  72. package/dist/logSinkTelemetry.d.cts.map +0 -1
  73. package/dist/logSinkTelemetry.d.mts.map +0 -1
  74. package/dist/logSinkTelemetry.mjs.map +0 -1
  75. package/dist/policy.cjs.map +0 -1
  76. package/dist/policy.d.cts.map +0 -1
  77. package/dist/policy.d.mts.map +0 -1
  78. package/dist/policy.mjs.map +0 -1
  79. package/dist/standard.cjs +0 -2
  80. package/dist/standard.cjs.map +0 -1
  81. package/dist/standard.d.cts.map +0 -1
  82. package/dist/standard.d.mts.map +0 -1
  83. package/dist/standard.mjs +0 -2
  84. package/dist/standard.mjs.map +0 -1
  85. package/dist/summarizationModel.cjs.map +0 -1
  86. package/dist/summarizationModel.d.cts.map +0 -1
  87. package/dist/summarizationModel.d.mts.map +0 -1
  88. package/dist/summarizationModel.mjs.map +0 -1
  89. package/dist/types.d.cts.map +0 -1
  90. package/dist/types.d.mts.map +0 -1
  91. /package/dist/{logSinkTelemetry.cjs → adapters/telemetry/logSinkTelemetry.cjs} +0 -0
  92. /package/dist/{logSinkTelemetry.mjs → adapters/telemetry/logSinkTelemetry.mjs} +0 -0
  93. /package/dist/{summarizationModel.cjs → services/compaction/summarizationModel.cjs} +0 -0
  94. /package/dist/{summarizationModel.mjs → services/compaction/summarizationModel.mjs} +0 -0
  95. /package/dist/{constants.cjs → types/constants.cjs} +0 -0
  96. /package/dist/{constants.mjs → types/constants.mjs} +0 -0
package/README.md CHANGED
@@ -1,15 +1,22 @@
1
1
  # @agimon-ai/doompi-autocompact
2
2
 
3
- Staged checkpoint steering and iterative context compaction for Doompi.
3
+ **Compaction with breadcrumbs.**
4
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.
5
+ Waiting until the context window is full leaves one hurried summary to save an entire
6
+ session. Doompi checkpoints the work before that cliff, then carries the live plan, task
7
+ graph, and team state beside the prose instead of asking a later model to reconstruct them.
9
8
 
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.
9
+ The ladder has three passes:
10
+
11
+ 1. At 50%, write the first compact summary.
12
+ 2. Combine that checkpoint with later messages; let the model decide whether it is ready
13
+ to compact.
14
+ 3. Combine the next checkpoint with later messages and force compaction.
15
+
16
+ The work runs in a worker thread, so writing a checkpoint does not stop the session.
17
+
18
+ This is part of [Doompi](https://www.npmjs.com/package/@agimon-ai/doompi). Most users get
19
+ it with the distribution.
13
20
 
14
21
  ## Install
15
22
 
@@ -19,17 +26,15 @@ npm install @agimon-ai/doompi-autocompact
19
26
 
20
27
  ## How it loads
21
28
 
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`
29
+ Doompi loads auto-compact as core. It is not a layer and does not appear in
30
+ `.doom/modes.yaml`. The bare package name follows its Pi manifest and loads the Pi adapter.
26
31
 
27
32
  ## Entry points
28
33
 
29
- | Import |
30
- | --------------------------------------------- |
31
- | `@agimon-ai/doompi-autocompact` |
32
- | `@agimon-ai/doompi-autocompact/extensions/pi` |
34
+ | Import | Purpose |
35
+ | --------------------------------------------- | ------------------------ |
36
+ | `@agimon-ai/doompi-autocompact` | Library API |
37
+ | `@agimon-ai/doompi-autocompact/extensions/pi` | Pi extension entry point |
33
38
 
34
39
  ## License
35
40
 
@@ -0,0 +1,50 @@
1
+ const e=require(`../../types/constants.cjs`),t=require(`../../services/compaction/policy.cjs`),n=require(`../../services/compaction/summarizationModel.cjs`),r=require(`../telemetry/logSinkTelemetry.cjs`);let i=require(`node:fs`),a=require(`node:path`),o=require(`node:url`),s=require(`node:worker_threads`),c=require(`@agimon-ai/doompi-config`),l=require(`@agimon-ai/doompi-task/store/paths`),u=require(`@agimon-ai/doompi-task/store/taskStore`),d=require(`@agimon-ai/doompi-team/api/team-snapshot`),f=require(`@agimon-ai/doompi-ui/footer`),p=require(`@earendil-works/pi-coding-agent`);const m=`@root`,h={waiting:`waiting`,checkpointPending:`checkpoint_pending`,checkpointReady:`checkpoint_ready`,compacting:`compacting`};function g(e,t={}){return{"pi.session.id":e.sessionManager.getSessionId(),...t}}function _(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 v(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 m}function y(e){return e instanceof Error?e.message:String(e)}function b(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 x(e){let t=[];try{let n=new u.TaskStore({cwd:e.cwd,report:{error:(e,n)=>t.push(`${e}: ${y(n)}`),warn:(e,n)=>t.push(`${e}: ${y(n)}`),event:()=>void 0}});return n.configureSession((0,l.resolveSessionKey)(e.sessionManager.getSessionId())),{tasks:n.read().tasks,...t.length>0?{error:t.join(`; `)}:{}}}catch(e){return{tasks:[],error:y(e)}}}function S(){try{let e=(0,d.readActiveNativeTeamSnapshot)();return e?{members:e.members}:{}}catch(e){return{error:y(e)}}}function C(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 w(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 T(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 E(e,t,n){let r=b(e);return{...r?{planPath:r.path}:{},tasks:C(t),...t.error?{taskError:t.error}:{},teamAvailable:!!n.members,teamMembers:n.members??[],...n.error?{teamError:n.error}:{}}}function D(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
+ ${w(e.tasks,e.taskError)}
10
+ </active-tasks>
11
+ <active-team>
12
+ ${T(n)}
13
+ </active-team>
14
+ </compaction-runtime-state>`}function O(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 k(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
+ ${w(C(e.taskSnapshot),e.taskSnapshot.error)}
23
+ </active-tasks>
24
+ <active-team>
25
+ ${T(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 A(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
+ ${k(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 j(e,n,r){let i=t.projectContextMessages((0,p.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,p.sessionEntryToContextMessages)(e))}function M(e){let t=(0,o.fileURLToPath)(e),n=(0,a.dirname)(t);for(;;){let e=(0,a.join)(n,`checkpointWorker.mjs`);if((0,i.existsSync)(e))return(0,o.pathToFileURL)(e);let t=(0,a.dirname)(n);if(t===n)break;n=t}throw Error(`Cannot find checkpointWorker.mjs by walking from ${t}.`)}function N(e,t){return new Promise((n,r)=>{let i=new s.Worker(M(require(`url`).pathToFileURL(__filename).href),{workerData:e}),a=!1,o=e=>{a||(a=!0,t.removeEventListener(`abort`,c),e())},c=()=>{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`,c,{once:!0}),i.unref(),t.aborted&&c()})}function P(e){try{return(0,c.loadDoomConfig)((0,c.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 F(e){let t=P(e.cwd),r=t?.model?n.parseModelReference(t.model):void 0,i=r?e.modelRegistry.find(r.provider,r.modelId):void 0,a=i??e.model;if(!a)return;let o=t?.thinking??(i?r?.thinking:void 0)??e.thinkingLevel;return{model:a,...o?{thinkingLevel:o}:{}}}async function I(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 N({messages:e.messages,model:n.model,reserveTokens:p.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 L(e,t,n=`info`){e?.hasUI&&e.ui.notify(t,n)}function R(n,i={}){let a=i.resolveModel??F,o=i.generateCheckpoint??(e=>I(e,a)),s=i.readTaskSnapshot??x,c=i.readTeamSnapshot??S,l=i.telemetry??r.createAutocompactTelemetry(),u=i.doomIntegrations??!0,d=new Set,y=new Set,C=t.createInitialState(),w,T,k=u?(0,f.registerDoomFooterContribution)(n,{source:`doom-autocompact`,id:`autocompact`,order:20}):{update:()=>void 0,dispose:()=>void 0},M=e=>{let t=C.phase===h.checkpointPending?`summarizing`:C.phase===h.checkpointReady?`applying`:void 0;k.update(t?{fullText:`Compacting p${C.pass}`,compactText:`C${C.pass}`}:void 0);let n=e??w;n?.hasUI&&n.ui.setStatus(`doom-autocompact`,t?`Compacting pass ${C.pass} (${t})…`:void 0)},N=()=>{n.appendEntry(e.STATE_CUSTOM_TYPE,{...C}),M()},P=()=>{delete C.requestId,delete C.snapshotLeafId,delete C.snapshotTokens,delete C.pendingCheckpoint,delete C.compactionPass},R=e=>{C.checkpointQueue=C.checkpointQueue.filter(t=>t!==e)},z=e=>{C=_(e.sessionManager.getBranch())??t.createInitialState(),!(C.phase===h.checkpointReady&&C.requestId&&C.snapshotLeafId&&C.pendingCheckpoint||C.phase===h.waiting)&&(T?.abort(),T=void 0,C.phase=h.waiting,P(),N())},B=t=>{n.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:C.cycle,pass:C.pass}},{triggerTurn:!0,deliverAs:`steer`})},V=(e,t)=>{if(e!==C.requestId||C.phase!==h.checkpointPending)return;let n=C.snapshotLeafId;C.phase=h.waiting,n&&(C.lastAttemptLeafId=n),P(),N(),L(w,`Doom autocompact summarization pass ${C.pass} failed: ${t instanceof Error?t.message:String(t)}`,`error`)},H=(e,t,n,i)=>{t.error&&(L(e,`Doom autocompact task steering degraded: ${t.error}`,`warning`),l.recordWarning(r.AUTOCOMPACT_EVENT.taskSnapshotDegraded,Error(t.error),i)),n.error&&(L(e,`Doom autocompact team steering degraded: ${n.error}`,`warning`),l.recordWarning(r.AUTOCOMPACT_EVENT.teamSnapshotDegraded,Error(n.error),i))},U=(t,r,i)=>{let a=s(t),o=c();H(t,a,o,i);let l=E(r,a,o);return n.sendMessage({customType:e.RUNTIME_STATE_MESSAGE_TYPE,content:D(l),display:!1,details:{version:1,...l}}),l},W=(i,a)=>{if(!C.requestId||!C.snapshotLeafId||!C.pendingCheckpoint)return!1;let o=a.sessionManager.getBranch(),s=t.projectContextMessages((0,p.buildSessionContext)(o).messages,o).messages,c=t.mergeFileDetails(C,t.fileOperationsFromMessages(s)),u=C.requestId,d=C.cycle,f=t.withCanonicalFileSections(C.pendingCheckpoint,c),m={...c,doomAutocompact:{version:2,cycle:d,pass:i,requestId:u,snapshotLeafId:C.snapshotLeafId,tokensBefore:C.snapshotTokens??a.getContextUsage()?.tokens??0},retainedMessages:t.retainedMessagesAfterSnapshot(o,C.snapshotLeafId)};L(a,`Doom autocompact pass ${i} context commit started.`);let _=a.isIdle();n.sendMessage({customType:e.CONTEXT_MESSAGE_TYPE,content:f,display:!1,details:m});let y=v(a),b=U(a,o,g(a,{"autocompact.request.id":u,"autocompact.cycle":d,"autocompact.pass":i}));return _&&n.setLabel(y,`autocompact:c${d}:p${i}`),C.readFiles=c.readFiles,C.modifiedFiles=c.modifiedFiles,delete C.latestCheckpointSnapshotLeafId,C.phase=h.waiting,C.checkpointQueue=[],C.exhaustedPasses=[],C.invalidAttempts=0,C.baselinePending=!0,delete C.lastAttemptLeafId,P(),C.cycle+=1,C.pass=1,N(),l.recordEvent(r.AUTOCOMPACT_EVENT.contextCommitted,g(a,{"autocompact.request.id":u,"autocompact.cycle":d,"autocompact.pass":i,"autocompact.snapshot_leaf_id":m.doomAutocompact.snapshotLeafId,"autocompact.tokens_before":m.doomAutocompact.tokensBefore,"autocompact.message_count.before":s.length,"autocompact.message_count.retained":m.retainedMessages.length,"autocompact.apply_mode":_?`idle`:`turn_end`,...O(b)})),L(a,`Doom autocompact context committed. Baseline will be captured from the next settled context.`),_&&B(`Asynchronous compaction completed.`),!0},G=(e,n,i)=>{let a=n.sessionManager.getBranch(),u=v(n),d=t.createRequestId(n.sessionManager.getSessionId(),C.cycle,e,u),f=e>1?t.checkpointSummaryFromEntry(t.latestCheckpointArtifactEntry(a)):void 0,p=j(e,a,C.latestCheckpointSnapshotLeafId),m=s(n),_=c(),y=g(n,{"autocompact.request.id":d,"autocompact.cycle":C.cycle,"autocompact.pass":e,"autocompact.snapshot_leaf_id":u,"autocompact.tokens_before":i,"autocompact.message_count.before":p.length});H(n,m,_,y),C.phase=h.checkpointPending,C.pass=e,C.requestId=d,C.snapshotLeafId=u,C.snapshotTokens=i,delete C.pendingCheckpoint,delete C.compactionPass,delete C.lastAttemptLeafId,N(),T?.abort(),T=new AbortController;let x=T.signal;L(n,`Doom autocompact summarization pass ${e} started.`),l.runInSpan(`doom_autocompact.checkpoint`,y,async()=>{await l.recordEvent(r.AUTOCOMPACT_EVENT.checkpointStarted,y);try{let t=await o({messages:p,instructions:A(e,{plan:b(a),taskSnapshot:m,teamSnapshot:_,readFiles:C.readFiles,modifiedFiles:C.modifiedFiles}),...f?{previousCheckpoint:f}:{},context:n,signal:x});if(!t.trim())throw Error(`Summarization returned an empty checkpoint.`);return await l.recordEvent(r.AUTOCOMPACT_EVENT.checkpointCompleted,{...y,"autocompact.checkpoint.characters":t.length}),t}catch(e){throw await l.recordError(r.AUTOCOMPACT_EVENT.checkpointFailed,e,y),e}}).then(t=>{d!==C.requestId||C.phase!==h.checkpointPending||(C.phase=h.checkpointReady,C.pendingCheckpoint=t.trim(),N(),L(w,`Doom autocompact summarization pass ${e} completed.`),w&&Y(w))}).catch(e=>V(d,e))},K=e=>{if(C.phase!==h.waiting||e.hasPendingMessages())return!1;let n=e.getContextUsage();if(!n||n.tokens===null)return!1;if(C.baselinePending)return t.baselineUsageIsSettled(e.sessionManager.getBranch())?(C.baselineTokens=n.tokens,C.baselinePending=!1,N(),L(e,`Doom autocompact baseline captured at ${C.baselineTokens} tokens.`),!1):!1;let r=v(e);if(C.lastAttemptLeafId===r)return!1;for(let e of[1,2,3])e<C.pass||C.checkpointQueue.includes(e)||C.exhaustedPasses.includes(e)||n.tokens>=t.thresholdTokens(e,n.contextWindow,C.baselineTokens)&&C.checkpointQueue.push(e);let i=C.checkpointQueue[0];return i?(G(i,e,n.tokens),!0):!1},q=(r,i)=>{let a=C.snapshotLeafId;n.appendEntry(e.CHECKPOINT_MESSAGE_TYPE,{...t.checkpointRequestDetails(C.cycle,r,C.requestId??`completed`),summary:i}),a&&(C.latestCheckpointSnapshotLeafId=a)},J=e=>{if(C.phase!==h.checkpointReady||!C.requestId||!C.pendingCheckpoint)return`none`;let n=C.pass,i=t.parseCheckpointDecision(C.pendingCheckpoint);if(!t.isStructuredCheckpoint(i.summary)){let t=C.snapshotLeafId,i=C.requestId,a=C.invalidAttempts+1,o=a>=3;C.phase=h.waiting,t&&(C.lastAttemptLeafId=t),o?(R(n),C.exhaustedPasses=[...C.exhaustedPasses,n],C.invalidAttempts=0):C.invalidAttempts=a,P(),N();let s=Error(`Summarization pass ${n} returned an incomplete checkpoint.`);return L(e,o?`Doom autocompact summarization pass ${n} returned an incomplete checkpoint ${a} times and was abandoned.`:`Doom autocompact summarization pass ${n} returned an incomplete checkpoint.`,`error`),l.recordError(r.AUTOCOMPACT_EVENT.checkpointInvalid,s,g(e,{"autocompact.cycle":C.cycle,"autocompact.pass":n,"autocompact.checkpoint.attempts":a,"autocompact.checkpoint.exhausted":o,...i?{"autocompact.request.id":i}:{}})),`invalid`}return C.invalidAttempts=0,n===1?(q(1,i.summary),R(1),C.phase=h.waiting,C.pass=2,P(),N(),`pass1`):n===2&&i.shouldCompact!==!0?(q(2,i.summary),R(2),C.phase=h.waiting,C.pass=3,P(),N(),`deferred`):(C.pendingCheckpoint=i.summary,W(n,e)?`committed`:`invalid`)};function Y(e){w=e,e.isIdle()&&J(e)!==`committed`&&K(e)}n.on(`context`,(e,n)=>{let i=t.projectContextMessages(e.messages,n.sessionManager.getBranch());if(i.invalidMarker){let e=n.sessionManager.getLeafId()??m;y.has(e)||(y.add(e),l.recordError(r.AUTOCOMPACT_EVENT.contextMarkerInvalid,Error(`Doom autocompact context marker is malformed.`),g(n,{"autocompact.leaf_id":e})));return}if(i.marker)return d.has(i.marker.requestId)||(d.add(i.marker.requestId),l.recordEvent(r.AUTOCOMPACT_EVENT.contextApplied,g(n,{"autocompact.request.id":i.marker.requestId,"autocompact.cycle":i.marker.cycle,"autocompact.pass":i.marker.pass,"autocompact.snapshot_leaf_id":i.marker.snapshotLeafId,"autocompact.tokens_before":i.marker.tokensBefore,"autocompact.message_count.before":e.messages.length,"autocompact.message_count.after":i.messages.length,"autocompact.message_count.retained":i.retainedMessageCount}))),{messages:i.messages}}),n.on(`session_start`,(e,t)=>{w=t,z(t),Y(t)}),n.on(`session_tree`,(e,t)=>{w=t,z(t),Y(t)}),n.on(`turn_end`,(e,t)=>{if(w=t,t.isIdle()){Y(t);return}C.phase===h.checkpointReady&&(e.toolResults?.length??0)>0&&!t.hasPendingMessages()&&J(t)!==`none`||K(t)}),n.on(`agent_settled`,(e,t)=>{Y(t)}),n.on(`session_before_compact`,e=>{if(e.reason===`threshold`)return C.phase===h.checkpointPending||C.phase===h.checkpointReady||C.baselinePending?{cancel:!0}:void 0}),n.on(`session_compact`,(e,i)=>{T?.abort(),T=void 0;let a=t.fileDetailsFromUnknown(e.compactionEntry.details),o=t.mergeFileDetails(C,void 0,a);C.readFiles=o.readFiles,C.modifiedFiles=o.modifiedFiles,delete C.latestCheckpointSnapshotLeafId,C.baselinePending=!0,C.phase=h.waiting,P(),C.checkpointQueue=[],C.exhaustedPasses=[],C.invalidAttempts=0,delete C.lastAttemptLeafId,n.setLabel(e.compactionEntry.id,`autocompact:c${C.cycle}:external`);let s=C.cycle,c=g(i,{"autocompact.cycle":s,"autocompact.native.reason":e.reason}),u=U(i,i.sessionManager.getBranch(),c);C.cycle+=1,C.pass=1,N(),l.recordEvent(r.AUTOCOMPACT_EVENT.nativeCompactionCompleted,g(i,{"autocompact.cycle":s,"autocompact.native.reason":e.reason,"autocompact.native.from_extension":e.fromExtension,"autocompact.tokens_before":e.compactionEntry.tokensBefore,...O(u)})),L(i,`Doom autocompact completed. Baseline will be captured from the next settled context. Next pass: ${C.pass}.`)}),n.on(`session_shutdown`,async()=>{T?.abort(),T=void 0,k.dispose(),w=void 0,d.clear(),y.clear(),C=t.createInitialState(),await l.shutdown()})}exports.registerAutocompactExtension=R;
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/adapters/pi/extension.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport { Worker } from 'node:worker_threads';\n\nimport { getHarnessState, loadDoomConfig, type PlanningAgentConfig } from '@agimon-ai/doompi-config';\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 { type NativeTeamMemberSnapshot, readActiveNativeTeamSnapshot } from '@agimon-ai/doompi-team/api/team-snapshot';\nimport { registerDoomFooterContribution } from '@agimon-ai/doompi-ui/footer';\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 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 '../../services/compaction/policy.ts';\nimport { parseModelReference, type SummarizationModel } from '../../services/compaction/summarizationModel.ts';\nimport {\n CHECKPOINT_MESSAGE_TYPE,\n CONTEXT_MESSAGE_TYPE,\n MAX_INVALID_CHECKPOINT_ATTEMPTS,\n RESUME_MESSAGE_TYPE,\n RUNTIME_STATE_MESSAGE_TYPE,\n STATE_CUSTOM_TYPE,\n STATE_VERSION,\n} from '../../types/constants.ts';\nimport type { AutocompactEventAttributes, AutocompactTelemetry } from '../telemetry/logSinkTelemetry.ts';\nimport { AUTOCOMPACT_EVENT, createAutocompactTelemetry } from '../telemetry/logSinkTelemetry.ts';\n\nexport type { ModelReference, SummarizationModel } from '../../services/compaction/summarizationModel.ts';\nexport { parseModelReference, resolveSummarizationModel } from '../../services/compaction/summarizationModel.ts';\n\nimport type { AutocompactContextDetails, AutocompactPass, AutocompactState } from '../../types/index.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\nexport function findCheckpointWorkerUrl(importFileUrl: string | URL): URL {\n const importFilePath = fileURLToPath(importFileUrl);\n let directory = dirname(importFilePath);\n\n while (true) {\n const workerPath = join(directory, 'checkpointWorker.mjs');\n if (existsSync(workerPath)) return pathToFileURL(workerPath);\n\n const parent = dirname(directory);\n if (parent === directory) break;\n directory = parent;\n }\n\n throw new Error(`Cannot find checkpointWorker.mjs by walking from ${importFilePath}.`);\n}\n\nfunction runCheckpointWorker(workerInput: Record<string, unknown>, signal: AbortSignal): Promise<string> {\n return new Promise((resolve, reject) => {\n const worker = new Worker(findCheckpointWorkerUrl(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":"ykBAqDA,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,OA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,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"}
@@ -1,10 +1,10 @@
1
- import { AutocompactTelemetry } from "./logSinkTelemetry.cjs";
2
- import { SummarizationModel } from "./summarizationModel.cjs";
1
+ import { SummarizationModel } from "../../services/compaction/summarizationModel.cjs";
2
+ import { AutocompactTelemetry } from "../telemetry/logSinkTelemetry.cjs";
3
3
  import { ExtensionAPI, ExtensionContext, buildSessionContext } from "@earendil-works/pi-coding-agent";
4
4
  import { Task } from "@agimon-ai/doompi-task/store/types";
5
5
  import { NativeTeamMemberSnapshot } from "@agimon-ai/doompi-team/api/team-snapshot";
6
6
 
7
- //#region src/extension.d.ts
7
+ //#region src/adapters/pi/extension.d.ts
8
8
  type CheckpointMessages = ReturnType<typeof buildSessionContext>['messages'];
9
9
  interface TaskSnapshot {
10
10
  tasks: Task[];
@@ -29,7 +29,6 @@ interface AutocompactDependencies {
29
29
  telemetry?: AutocompactTelemetry;
30
30
  doomIntegrations?: boolean;
31
31
  }
32
- /** Explicit Doom model selection honors the configured planning subagent model. */
33
32
  declare function registerAutocompactExtension(pi: ExtensionAPI, dependencies?: AutocompactDependencies): void;
34
33
  //#endregion
35
34
  export { registerAutocompactExtension };
@@ -0,0 +1 @@
1
+ {"version":3,"file":"extension.d.cts","names":[],"sources":["../../../src/adapters/pi/extension.ts"],"mappings":";;;;;;;KAiEK,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;AAAA,iBAyVc,4BAAA,CAA6B,EAAA,EAAI,YAAA,EAAc,YAAA,GAAc,uBAAA"}
@@ -1,10 +1,10 @@
1
- import { AutocompactTelemetry } from "./logSinkTelemetry.mjs";
2
- import { SummarizationModel } from "./summarizationModel.mjs";
1
+ import { SummarizationModel } from "../../services/compaction/summarizationModel.mjs";
2
+ import { AutocompactTelemetry } from "../telemetry/logSinkTelemetry.mjs";
3
3
  import { NativeTeamMemberSnapshot } from "@agimon-ai/doompi-team/api/team-snapshot";
4
4
  import { ExtensionAPI, ExtensionContext, buildSessionContext } from "@earendil-works/pi-coding-agent";
5
5
  import { Task } from "@agimon-ai/doompi-task/store/types";
6
6
 
7
- //#region src/extension.d.ts
7
+ //#region src/adapters/pi/extension.d.ts
8
8
  type CheckpointMessages = ReturnType<typeof buildSessionContext>['messages'];
9
9
  interface TaskSnapshot {
10
10
  tasks: Task[];
@@ -29,7 +29,6 @@ interface AutocompactDependencies {
29
29
  telemetry?: AutocompactTelemetry;
30
30
  doomIntegrations?: boolean;
31
31
  }
32
- /** Explicit Doom model selection honors the configured planning subagent model. */
33
32
  declare function registerAutocompactExtension(pi: ExtensionAPI, dependencies?: AutocompactDependencies): void;
34
33
  //#endregion
35
34
  export { registerAutocompactExtension };
@@ -0,0 +1 @@
1
+ {"version":3,"file":"extension.d.mts","names":[],"sources":["../../../src/adapters/pi/extension.ts"],"mappings":";;;;;;;KAiEK,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;AAAA,iBAyVc,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"../../types/constants.mjs";import{baselineUsageIsSettled as a,checkpointRequestDetails as o,checkpointSummaryFromEntry as s,createInitialState as c,createRequestId as l,fileDetailsFromUnknown as u,fileOperationsFromMessages as d,isStructuredCheckpoint as f,latestCheckpointArtifactEntry as p,mergeFileDetails as m,parseCheckpointDecision as ee,parseState as h,projectContextMessages as g,retainedMessagesAfterSnapshot as _,thresholdTokens as te,withCanonicalFileSections as ne}from"../../services/compaction/policy.mjs";import{parseModelReference as v}from"../../services/compaction/summarizationModel.mjs";import{AUTOCOMPACT_EVENT as y,createAutocompactTelemetry as re}from"../telemetry/logSinkTelemetry.mjs";import{existsSync as b}from"node:fs";import{dirname as x,join as S}from"node:path";import{fileURLToPath as C,pathToFileURL as w}from"node:url";import{Worker as T}from"node:worker_threads";import{getHarnessState as E,loadDoomConfig as D}from"@agimon-ai/doompi-config";import{resolveSessionKey as O}from"@agimon-ai/doompi-task/store/paths";import{TaskStore as k}from"@agimon-ai/doompi-task/store/taskStore";import{readActiveNativeTeamSnapshot as A}from"@agimon-ai/doompi-team/api/team-snapshot";import{registerDoomFooterContribution as ie}from"@agimon-ai/doompi-ui/footer";import{DEFAULT_COMPACTION_SETTINGS as j,buildSessionContext as M,sessionEntryToContextMessages as N}from"@earendil-works/pi-coding-agent";const P=`@root`,F={waiting:`waiting`,checkpointPending:`checkpoint_pending`,checkpointReady:`checkpoint_ready`,compacting:`compacting`};function I(e,t={}){return{"pi.session.id":e.sessionManager.getSessionId(),...t}}function ae(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=h(n.data);if(r)return r}}function L(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 P}function R(e){return e instanceof Error?e.message:String(e)}function z(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 oe(e){let t=[];try{let n=new k({cwd:e.cwd,report:{error:(e,n)=>t.push(`${e}: ${R(n)}`),warn:(e,n)=>t.push(`${e}: ${R(n)}`),event:()=>void 0}});return n.configureSession(O(e.sessionManager.getSessionId())),{tasks:n.read().tasks,...t.length>0?{error:t.join(`; `)}:{}}}catch(e){return{tasks:[],error:R(e)}}}function se(){try{let e=A();return e?{members:e.members}:{}}catch(e){return{error:R(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 V(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 H(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 ce(e,t,n){let r=z(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 le(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
+ ${V(e.tasks,e.taskError)}
10
+ </active-tasks>
11
+ <active-team>
12
+ ${H(n)}
13
+ </active-team>
14
+ </compaction-runtime-state>`}function U(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 W(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
+ ${V(B(e.taskSnapshot),e.taskSnapshot.error)}
23
+ </active-tasks>
24
+ <active-team>
25
+ ${H(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 ue(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
+ ${W(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 de(e,t,n){let r=g(M(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=>N(e))}function G(e){let t=C(e),n=x(t);for(;;){let e=S(n,`checkpointWorker.mjs`);if(b(e))return w(e);let t=x(n);if(t===n)break;n=t}throw Error(`Cannot find checkpointWorker.mjs by walking from ${t}.`)}function K(e,t){return new Promise((n,r)=>{let i=new T(G(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 q(e){try{return D(E().root??e).modes?.planning?.subagents}catch{process.emitWarning(`Doom autocompact planning configuration could not be loaded; using the active session model instead.`);return}}function fe(e){let t=q(e.cwd),n=t?.model?v(t.model):void 0,r=n?e.modelRegistry.find(n.provider,n.modelId):void 0,i=r??e.model;if(!i)return;let a=t?.thinking??(r?n?.thinking:void 0)??e.thinkingLevel;return{model:i,...a?{thinkingLevel:a}:{}}}async function pe(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:j.reserveTokens,apiKey:r.apiKey,headers:r.headers,instructions:e.instructions,previousCheckpoint:e.previousCheckpoint,thinkingLevel:n.thinkingLevel,env:r.env},e.signal)}function J(e,t,n=`info`){e?.hasUI&&e.ui.notify(t,n)}function Y(h,v={}){let b=v.resolveModel??fe,x=v.generateCheckpoint??(e=>pe(e,b)),S=v.readTaskSnapshot??oe,C=v.readTeamSnapshot??se,w=v.telemetry??re(),T=v.doomIntegrations??!0,E=new Set,D=new Set,O=c(),k,A,j=T?ie(h,{source:`doom-autocompact`,id:`autocompact`,order:20}):{update:()=>void 0,dispose:()=>void 0},N=e=>{let t=O.phase===F.checkpointPending?`summarizing`:O.phase===F.checkpointReady?`applying`:void 0;j.update(t?{fullText:`Compacting p${O.pass}`,compactText:`C${O.pass}`}:void 0);let n=e??k;n?.hasUI&&n.ui.setStatus(`doom-autocompact`,t?`Compacting pass ${O.pass} (${t})…`:void 0)},R=()=>{h.appendEntry(i,{...O}),N()},B=()=>{delete O.requestId,delete O.snapshotLeafId,delete O.snapshotTokens,delete O.pendingCheckpoint,delete O.compactionPass},V=e=>{O.checkpointQueue=O.checkpointQueue.filter(t=>t!==e)},H=e=>{O=ae(e.sessionManager.getBranch())??c(),!(O.phase===F.checkpointReady&&O.requestId&&O.snapshotLeafId&&O.pendingCheckpoint||O.phase===F.waiting)&&(A?.abort(),A=void 0,O.phase=F.waiting,B(),R())},W=e=>{h.sendMessage({customType:n,content:`${e} Continue from the compacted checkpoint's immediate next action without repeating completed work.`,display:!1,details:{version:2,cycle:O.cycle,pass:O.pass}},{triggerTurn:!0,deliverAs:`steer`})},G=(e,t)=>{if(e!==O.requestId||O.phase!==F.checkpointPending)return;let n=O.snapshotLeafId;O.phase=F.waiting,n&&(O.lastAttemptLeafId=n),B(),R(),J(k,`Doom autocompact summarization pass ${O.pass} failed: ${t instanceof Error?t.message:String(t)}`,`error`)},K=(e,t,n,r)=>{t.error&&(J(e,`Doom autocompact task steering degraded: ${t.error}`,`warning`),w.recordWarning(y.taskSnapshotDegraded,Error(t.error),r)),n.error&&(J(e,`Doom autocompact team steering degraded: ${n.error}`,`warning`),w.recordWarning(y.teamSnapshotDegraded,Error(n.error),r))},q=(e,t,n)=>{let i=S(e),a=C();K(e,i,a,n);let o=ce(t,i,a);return h.sendMessage({customType:r,content:le(o),display:!1,details:{version:1,...o}}),o},Y=(e,n)=>{if(!O.requestId||!O.snapshotLeafId||!O.pendingCheckpoint)return!1;let r=n.sessionManager.getBranch(),i=g(M(r).messages,r).messages,a=m(O,d(i)),o=O.requestId,s=O.cycle,c=ne(O.pendingCheckpoint,a),l={...a,doomAutocompact:{version:2,cycle:s,pass:e,requestId:o,snapshotLeafId:O.snapshotLeafId,tokensBefore:O.snapshotTokens??n.getContextUsage()?.tokens??0},retainedMessages:_(r,O.snapshotLeafId)};J(n,`Doom autocompact pass ${e} context commit started.`);let u=n.isIdle();h.sendMessage({customType:t,content:c,display:!1,details:l});let f=L(n),p=q(n,r,I(n,{"autocompact.request.id":o,"autocompact.cycle":s,"autocompact.pass":e}));return u&&h.setLabel(f,`autocompact:c${s}:p${e}`),O.readFiles=a.readFiles,O.modifiedFiles=a.modifiedFiles,delete O.latestCheckpointSnapshotLeafId,O.phase=F.waiting,O.checkpointQueue=[],O.exhaustedPasses=[],O.invalidAttempts=0,O.baselinePending=!0,delete O.lastAttemptLeafId,B(),O.cycle+=1,O.pass=1,R(),w.recordEvent(y.contextCommitted,I(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`,...U(p)})),J(n,`Doom autocompact context committed. Baseline will be captured from the next settled context.`),u&&W(`Asynchronous compaction completed.`),!0},me=(e,t,n)=>{let r=t.sessionManager.getBranch(),i=L(t),a=l(t.sessionManager.getSessionId(),O.cycle,e,i),o=e>1?s(p(r)):void 0,c=de(e,r,O.latestCheckpointSnapshotLeafId),u=S(t),d=C(),f=I(t,{"autocompact.request.id":a,"autocompact.cycle":O.cycle,"autocompact.pass":e,"autocompact.snapshot_leaf_id":i,"autocompact.tokens_before":n,"autocompact.message_count.before":c.length});K(t,u,d,f),O.phase=F.checkpointPending,O.pass=e,O.requestId=a,O.snapshotLeafId=i,O.snapshotTokens=n,delete O.pendingCheckpoint,delete O.compactionPass,delete O.lastAttemptLeafId,R(),A?.abort(),A=new AbortController;let m=A.signal;J(t,`Doom autocompact summarization pass ${e} started.`),w.runInSpan(`doom_autocompact.checkpoint`,f,async()=>{await w.recordEvent(y.checkpointStarted,f);try{let n=await x({messages:c,instructions:ue(e,{plan:z(r),taskSnapshot:u,teamSnapshot:d,readFiles:O.readFiles,modifiedFiles:O.modifiedFiles}),...o?{previousCheckpoint:o}:{},context:t,signal:m});if(!n.trim())throw Error(`Summarization returned an empty checkpoint.`);return await w.recordEvent(y.checkpointCompleted,{...f,"autocompact.checkpoint.characters":n.length}),n}catch(e){throw await w.recordError(y.checkpointFailed,e,f),e}}).then(t=>{a!==O.requestId||O.phase!==F.checkpointPending||(O.phase=F.checkpointReady,O.pendingCheckpoint=t.trim(),R(),J(k,`Doom autocompact summarization pass ${e} completed.`),k&&$(k))}).catch(e=>G(a,e))},X=e=>{if(O.phase!==F.waiting||e.hasPendingMessages())return!1;let t=e.getContextUsage();if(!t||t.tokens===null)return!1;if(O.baselinePending)return a(e.sessionManager.getBranch())?(O.baselineTokens=t.tokens,O.baselinePending=!1,R(),J(e,`Doom autocompact baseline captured at ${O.baselineTokens} tokens.`),!1):!1;let n=L(e);if(O.lastAttemptLeafId===n)return!1;for(let e of[1,2,3])e<O.pass||O.checkpointQueue.includes(e)||O.exhaustedPasses.includes(e)||t.tokens>=te(e,t.contextWindow,O.baselineTokens)&&O.checkpointQueue.push(e);let r=O.checkpointQueue[0];return r?(me(r,e,t.tokens),!0):!1},Z=(t,n)=>{let r=O.snapshotLeafId;h.appendEntry(e,{...o(O.cycle,t,O.requestId??`completed`),summary:n}),r&&(O.latestCheckpointSnapshotLeafId=r)},Q=e=>{if(O.phase!==F.checkpointReady||!O.requestId||!O.pendingCheckpoint)return`none`;let t=O.pass,n=ee(O.pendingCheckpoint);if(!f(n.summary)){let n=O.snapshotLeafId,r=O.requestId,i=O.invalidAttempts+1,a=i>=3;O.phase=F.waiting,n&&(O.lastAttemptLeafId=n),a?(V(t),O.exhaustedPasses=[...O.exhaustedPasses,t],O.invalidAttempts=0):O.invalidAttempts=i,B(),R();let o=Error(`Summarization pass ${t} returned an incomplete checkpoint.`);return J(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`),w.recordError(y.checkpointInvalid,o,I(e,{"autocompact.cycle":O.cycle,"autocompact.pass":t,"autocompact.checkpoint.attempts":i,"autocompact.checkpoint.exhausted":a,...r?{"autocompact.request.id":r}:{}})),`invalid`}return O.invalidAttempts=0,t===1?(Z(1,n.summary),V(1),O.phase=F.waiting,O.pass=2,B(),R(),`pass1`):t===2&&n.shouldCompact!==!0?(Z(2,n.summary),V(2),O.phase=F.waiting,O.pass=3,B(),R(),`deferred`):(O.pendingCheckpoint=n.summary,Y(t,e)?`committed`:`invalid`)};function $(e){k=e,e.isIdle()&&Q(e)!==`committed`&&X(e)}h.on(`context`,(e,t)=>{let n=g(e.messages,t.sessionManager.getBranch());if(n.invalidMarker){let e=t.sessionManager.getLeafId()??P;D.has(e)||(D.add(e),w.recordError(y.contextMarkerInvalid,Error(`Doom autocompact context marker is malformed.`),I(t,{"autocompact.leaf_id":e})));return}if(n.marker)return E.has(n.marker.requestId)||(E.add(n.marker.requestId),w.recordEvent(y.contextApplied,I(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}}),h.on(`session_start`,(e,t)=>{k=t,H(t),$(t)}),h.on(`session_tree`,(e,t)=>{k=t,H(t),$(t)}),h.on(`turn_end`,(e,t)=>{if(k=t,t.isIdle()){$(t);return}O.phase===F.checkpointReady&&(e.toolResults?.length??0)>0&&!t.hasPendingMessages()&&Q(t)!==`none`||X(t)}),h.on(`agent_settled`,(e,t)=>{$(t)}),h.on(`session_before_compact`,e=>{if(e.reason===`threshold`)return O.phase===F.checkpointPending||O.phase===F.checkpointReady||O.baselinePending?{cancel:!0}:void 0}),h.on(`session_compact`,(e,t)=>{A?.abort(),A=void 0;let n=u(e.compactionEntry.details),r=m(O,void 0,n);O.readFiles=r.readFiles,O.modifiedFiles=r.modifiedFiles,delete O.latestCheckpointSnapshotLeafId,O.baselinePending=!0,O.phase=F.waiting,B(),O.checkpointQueue=[],O.exhaustedPasses=[],O.invalidAttempts=0,delete O.lastAttemptLeafId,h.setLabel(e.compactionEntry.id,`autocompact:c${O.cycle}:external`);let i=O.cycle,a=I(t,{"autocompact.cycle":i,"autocompact.native.reason":e.reason}),o=q(t,t.sessionManager.getBranch(),a);O.cycle+=1,O.pass=1,R(),w.recordEvent(y.nativeCompactionCompleted,I(t,{"autocompact.cycle":i,"autocompact.native.reason":e.reason,"autocompact.native.from_extension":e.fromExtension,"autocompact.tokens_before":e.compactionEntry.tokensBefore,...U(o)})),J(t,`Doom autocompact completed. Baseline will be captured from the next settled context. Next pass: ${O.pass}.`)}),h.on(`session_shutdown`,async()=>{A?.abort(),A=void 0,j.dispose(),k=void 0,E.clear(),D.clear(),O=c(),await w.shutdown()})}export{Y as registerAutocompactExtension};
50
+ //# sourceMappingURL=extension.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"extension.mjs","names":[],"sources":["../../../src/adapters/pi/extension.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport { Worker } from 'node:worker_threads';\n\nimport { getHarnessState, loadDoomConfig, type PlanningAgentConfig } from '@agimon-ai/doompi-config';\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 { type NativeTeamMemberSnapshot, readActiveNativeTeamSnapshot } from '@agimon-ai/doompi-team/api/team-snapshot';\nimport { registerDoomFooterContribution } from '@agimon-ai/doompi-ui/footer';\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 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 '../../services/compaction/policy.ts';\nimport { parseModelReference, type SummarizationModel } from '../../services/compaction/summarizationModel.ts';\nimport {\n CHECKPOINT_MESSAGE_TYPE,\n CONTEXT_MESSAGE_TYPE,\n MAX_INVALID_CHECKPOINT_ATTEMPTS,\n RESUME_MESSAGE_TYPE,\n RUNTIME_STATE_MESSAGE_TYPE,\n STATE_CUSTOM_TYPE,\n STATE_VERSION,\n} from '../../types/constants.ts';\nimport type { AutocompactEventAttributes, AutocompactTelemetry } from '../telemetry/logSinkTelemetry.ts';\nimport { AUTOCOMPACT_EVENT, createAutocompactTelemetry } from '../telemetry/logSinkTelemetry.ts';\n\nexport type { ModelReference, SummarizationModel } from '../../services/compaction/summarizationModel.ts';\nexport { parseModelReference, resolveSummarizationModel } from '../../services/compaction/summarizationModel.ts';\n\nimport type { AutocompactContextDetails, AutocompactPass, AutocompactState } from '../../types/index.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\nexport function findCheckpointWorkerUrl(importFileUrl: string | URL): URL {\n const importFilePath = fileURLToPath(importFileUrl);\n let directory = dirname(importFilePath);\n\n while (true) {\n const workerPath = join(directory, 'checkpointWorker.mjs');\n if (existsSync(workerPath)) return pathToFileURL(workerPath);\n\n const parent = dirname(directory);\n if (parent === directory) break;\n directory = parent;\n }\n\n throw new Error(`Cannot find checkpointWorker.mjs by walking from ${importFilePath}.`);\n}\n\nfunction runCheckpointWorker(workerInput: Record<string, unknown>, signal: AbortSignal): Promise<string> {\n return new Promise((resolve, reject) => {\n const worker = new Worker(findCheckpointWorkerUrl(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":"8hDAqDA,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,GAAqB,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,EAAS,EAAW,EAAM,KAAK,CACrC,GAAI,EAAQ,OAAO,GAKvB,SAAS,EAAc,EAA+B,CACpD,IAAK,IAAM,KAAS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AuB,EAAM,gBAAgB,QAAQ,CACpE,EAAa,EAAiB,EAAO,IAAA,GAAW,EAAa,CACnE,EAAM,UAAY,EAAW,UAC7B,EAAM,cAAgB,EAAW,cACjC,OAAO,EAAM,+BAGb,EAAM,gBAAkB,GACxB,EAAM,MAAQ,EAAY,QAC1B,GAAwB,CACxB,EAAM,gBAAkB,EAAE,CAC1B,EAAM,gBAAkB,EAAE,CAC1B,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,YACb,EAAkB,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,EAAQ,GAAoB,CAC5B,MAAM,EAAU,UAAU,EAC1B"}
@@ -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/adapters/process/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,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/adapters/process/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 @@
1
+ {"version":3,"file":"logSinkTelemetry.cjs","names":[],"sources":["../../../src/adapters/telemetry/logSinkTelemetry.ts"],"sourcesContent":["import { createDoomTelemetry, type DoomTelemetry, type DoomTelemetryOptions } from '@agimon-ai/doompi-telemetry';\n\nconst SERVICE_NAME = 'doom-autocompact';\nconst PACKAGE_NAME = '@agimon-ai/doompi-autocompact';\n\nexport const AUTOCOMPACT_EVENT = {\n checkpointStarted: 'doom_autocompact.checkpoint_started',\n checkpointCompleted: 'doom_autocompact.checkpoint_completed',\n checkpointFailed: 'doom_autocompact.checkpoint_failed',\n checkpointInvalid: 'doom_autocompact.checkpoint_invalid',\n taskSnapshotDegraded: 'doom_autocompact.task_snapshot_degraded',\n teamSnapshotDegraded: 'doom_autocompact.team_snapshot_degraded',\n contextCommitted: 'doom_autocompact.context_committed',\n contextApplied: 'doom_autocompact.context_applied',\n contextMarkerInvalid: 'doom_autocompact.context_marker_invalid',\n nativeCompactionCompleted: 'doom_autocompact.native_compaction_completed',\n} as const;\n\nexport type AutocompactEventName = (typeof AUTOCOMPACT_EVENT)[keyof typeof AUTOCOMPACT_EVENT];\nexport type AutocompactEventAttributes = Record<string, string | number | boolean>;\n\nexport interface AutocompactTelemetryOptions {\n cwd?: string;\n workspaceRoot?: string;\n env?: NodeJS.ProcessEnv;\n telemetryFactory?: NonNullable<DoomTelemetryOptions['telemetryFactory']>;\n warn?: (message: string) => void;\n}\n\nexport interface AutocompactTelemetry {\n recordError(event: AutocompactEventName, error: unknown, attributes?: AutocompactEventAttributes): Promise<void>;\n recordWarning(event: AutocompactEventName, error: unknown, attributes?: AutocompactEventAttributes): Promise<void>;\n recordEvent(event: AutocompactEventName, attributes?: AutocompactEventAttributes): Promise<void>;\n runInSpan<T>(name: string, attributes: AutocompactEventAttributes, callback: () => Promise<T>): Promise<T>;\n flush(): Promise<void>;\n shutdown(): Promise<void>;\n}\n\nexport function createAutocompactTelemetry(options: AutocompactTelemetryOptions = {}): AutocompactTelemetry {\n const telemetry: DoomTelemetry = createDoomTelemetry({\n serviceName: SERVICE_NAME,\n packageName: PACKAGE_NAME,\n cwd: options.cwd,\n workspaceRoot: options.workspaceRoot,\n env: options.env,\n telemetryFactory: options.telemetryFactory,\n warn: options.warn,\n enableLogs: true,\n enableTraces: true,\n });\n return {\n recordError: (event, error, attributes) => telemetry.recordError(event, error, attributes),\n recordWarning: (event, error, attributes) => telemetry.recordWarning(event, error, attributes),\n recordEvent: (event, attributes) => telemetry.recordEvent(event, attributes),\n runInSpan: (name, attributes, callback) => telemetry.runInSpan(name, attributes, callback),\n flush: () => telemetry.flush(),\n shutdown: () => telemetry.shutdown(),\n };\n}\n"],"mappings":"6CAEA,MAGa,EAAoB,CAC/B,kBAAmB,sCACnB,oBAAqB,wCACrB,iBAAkB,qCAClB,kBAAmB,sCACnB,qBAAsB,0CACtB,qBAAsB,0CACtB,iBAAkB,qCAClB,eAAgB,mCAChB,qBAAsB,0CACtB,0BAA2B,+CAC5B,CAsBD,SAAgB,EAA2B,EAAuC,EAAE,CAAwB,CAC1G,IAAM,GAAA,EAAA,EAAA,qBAA+C,CACnD,YAAa,mBACb,YAAa,gCACb,IAAK,EAAQ,IACb,cAAe,EAAQ,cACvB,IAAK,EAAQ,IACb,iBAAkB,EAAQ,iBAC1B,KAAM,EAAQ,KACd,WAAY,GACZ,aAAc,GACf,CAAC,CACF,MAAO,CACL,aAAc,EAAO,EAAO,IAAe,EAAU,YAAY,EAAO,EAAO,EAAW,CAC1F,eAAgB,EAAO,EAAO,IAAe,EAAU,cAAc,EAAO,EAAO,EAAW,CAC9F,aAAc,EAAO,IAAe,EAAU,YAAY,EAAO,EAAW,CAC5E,WAAY,EAAM,EAAY,IAAa,EAAU,UAAU,EAAM,EAAY,EAAS,CAC1F,UAAa,EAAU,OAAO,CAC9B,aAAgB,EAAU,UAAU,CACrC"}
@@ -1,4 +1,4 @@
1
- //#region src/logSinkTelemetry.d.ts
1
+ //#region src/adapters/telemetry/logSinkTelemetry.d.ts
2
2
  declare const AUTOCOMPACT_EVENT: {
3
3
  readonly checkpointStarted: "doom_autocompact.checkpoint_started";
4
4
  readonly checkpointCompleted: "doom_autocompact.checkpoint_completed";