@agimon-ai/doompi-autocompact 0.0.1-alpha.6 → 0.0.1-alpha.63

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 (112) hide show
  1. package/README.md +97 -18
  2. package/dist/adapters/compaction/modelOverrides.cjs +2 -0
  3. package/dist/adapters/compaction/modelOverrides.cjs.map +1 -0
  4. package/dist/adapters/compaction/modelOverrides.mjs +2 -0
  5. package/dist/adapters/compaction/modelOverrides.mjs.map +1 -0
  6. package/dist/adapters/compaction/policy.cjs +8 -0
  7. package/dist/adapters/compaction/policy.cjs.map +1 -0
  8. package/dist/adapters/compaction/policy.d.cts +6 -0
  9. package/dist/adapters/compaction/policy.d.cts.map +1 -0
  10. package/dist/adapters/compaction/policy.d.mts +6 -0
  11. package/dist/adapters/compaction/policy.d.mts.map +1 -0
  12. package/dist/adapters/compaction/policy.mjs +8 -0
  13. package/dist/adapters/compaction/policy.mjs.map +1 -0
  14. package/dist/adapters/pi/extension.cjs +44 -0
  15. package/dist/adapters/pi/extension.cjs.map +1 -0
  16. package/dist/adapters/pi/extension.d.cts +27 -0
  17. package/dist/adapters/pi/extension.d.cts.map +1 -0
  18. package/dist/adapters/pi/extension.d.mts +27 -0
  19. package/dist/adapters/pi/extension.d.mts.map +1 -0
  20. package/dist/adapters/pi/extension.mjs +44 -0
  21. package/dist/adapters/pi/extension.mjs.map +1 -0
  22. package/dist/adapters/telemetry/logSinkTelemetry.cjs +2 -0
  23. package/dist/adapters/telemetry/logSinkTelemetry.cjs.map +1 -0
  24. package/dist/adapters/telemetry/logSinkTelemetry.d.cts +26 -0
  25. package/dist/adapters/telemetry/logSinkTelemetry.d.cts.map +1 -0
  26. package/dist/adapters/telemetry/logSinkTelemetry.d.mts +26 -0
  27. package/dist/adapters/telemetry/logSinkTelemetry.d.mts.map +1 -0
  28. package/dist/adapters/telemetry/logSinkTelemetry.mjs +2 -0
  29. package/dist/adapters/telemetry/logSinkTelemetry.mjs.map +1 -0
  30. package/dist/extensions/pi.cjs +1 -2
  31. package/dist/extensions/pi.d.cts +2 -2
  32. package/dist/extensions/pi.d.mts +2 -2
  33. package/dist/extensions/pi.mjs +1 -2
  34. package/dist/index.cjs +1 -1
  35. package/dist/index.d.cts +4 -4
  36. package/dist/index.d.mts +4 -4
  37. package/dist/index.mjs +1 -1
  38. package/dist/services/summarizationModel.cjs +2 -0
  39. package/dist/services/summarizationModel.cjs.map +1 -0
  40. package/dist/{summarizationModel.d.cts → services/summarizationModel.d.cts} +2 -4
  41. package/dist/services/summarizationModel.d.cts.map +1 -0
  42. package/dist/{summarizationModel.d.mts → services/summarizationModel.d.mts} +2 -4
  43. package/dist/services/summarizationModel.d.mts.map +1 -0
  44. package/dist/services/summarizationModel.mjs +2 -0
  45. package/dist/services/summarizationModel.mjs.map +1 -0
  46. package/dist/types/constants.cjs.map +1 -0
  47. package/dist/types/constants.mjs.map +1 -0
  48. package/dist/types/index.d.cts +7 -0
  49. package/dist/types/index.d.cts.map +1 -0
  50. package/dist/types/index.d.mts +7 -0
  51. package/dist/types/index.d.mts.map +1 -0
  52. package/package.json +56 -17
  53. package/src/exports/webClient.ts +1 -0
  54. package/src/types/autocompactSettings.ts +97 -0
  55. package/src/types/constants.ts +27 -0
  56. package/src/web/index.ts +15 -0
  57. package/src/web/lib/autocompactSettings.ts +31 -0
  58. package/src/web/tsconfig.json +23 -0
  59. package/dist/checkpointWorker.cjs +0 -2
  60. package/dist/checkpointWorker.cjs.map +0 -1
  61. package/dist/checkpointWorker.d.cts +0 -1
  62. package/dist/checkpointWorker.d.mts +0 -1
  63. package/dist/checkpointWorker.mjs +0 -2
  64. package/dist/checkpointWorker.mjs.map +0 -1
  65. package/dist/constants.cjs.map +0 -1
  66. package/dist/constants.mjs.map +0 -1
  67. package/dist/extension.cjs +0 -50
  68. package/dist/extension.cjs.map +0 -1
  69. package/dist/extension.d.cts +0 -36
  70. package/dist/extension.d.cts.map +0 -1
  71. package/dist/extension.d.mts +0 -36
  72. package/dist/extension.d.mts.map +0 -1
  73. package/dist/extension.mjs +0 -50
  74. package/dist/extension.mjs.map +0 -1
  75. package/dist/extensions/pi.cjs.map +0 -1
  76. package/dist/extensions/pi.mjs.map +0 -1
  77. package/dist/logSinkTelemetry.cjs +0 -2
  78. package/dist/logSinkTelemetry.cjs.map +0 -1
  79. package/dist/logSinkTelemetry.d.cts +0 -26
  80. package/dist/logSinkTelemetry.d.cts.map +0 -1
  81. package/dist/logSinkTelemetry.d.mts +0 -26
  82. package/dist/logSinkTelemetry.d.mts.map +0 -1
  83. package/dist/logSinkTelemetry.mjs +0 -2
  84. package/dist/logSinkTelemetry.mjs.map +0 -1
  85. package/dist/policy.cjs +0 -8
  86. package/dist/policy.cjs.map +0 -1
  87. package/dist/policy.d.cts +0 -6
  88. package/dist/policy.d.cts.map +0 -1
  89. package/dist/policy.d.mts +0 -6
  90. package/dist/policy.d.mts.map +0 -1
  91. package/dist/policy.mjs +0 -8
  92. package/dist/policy.mjs.map +0 -1
  93. package/dist/standard.cjs +0 -2
  94. package/dist/standard.cjs.map +0 -1
  95. package/dist/standard.d.cts +0 -8
  96. package/dist/standard.d.cts.map +0 -1
  97. package/dist/standard.d.mts +0 -8
  98. package/dist/standard.d.mts.map +0 -1
  99. package/dist/standard.mjs +0 -2
  100. package/dist/standard.mjs.map +0 -1
  101. package/dist/summarizationModel.cjs +0 -2
  102. package/dist/summarizationModel.cjs.map +0 -1
  103. package/dist/summarizationModel.d.cts.map +0 -1
  104. package/dist/summarizationModel.d.mts.map +0 -1
  105. package/dist/summarizationModel.mjs +0 -2
  106. package/dist/summarizationModel.mjs.map +0 -1
  107. package/dist/types.d.cts +0 -5
  108. package/dist/types.d.cts.map +0 -1
  109. package/dist/types.d.mts +0 -5
  110. package/dist/types.d.mts.map +0 -1
  111. /package/dist/{constants.cjs → types/constants.cjs} +0 -0
  112. /package/dist/{constants.mjs → types/constants.mjs} +0 -0
package/README.md CHANGED
@@ -1,35 +1,114 @@
1
1
  # @agimon-ai/doompi-autocompact
2
2
 
3
- Staged checkpoint steering and iterative context compaction for Doompi.
3
+ Staged checkpoint summarization and iterative context compaction for DoomPi.
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
+ Part of the [DoomPi distribution](https://www.npmjs.com/package/@agimon-ai/doompi).
9
6
 
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.
7
+ Instead of waiting for one final summary near the context limit, Autocompact creates up to three
8
+ asynchronous checkpoints and combines each checkpoint with subsequent messages.
9
+
10
+ > **Alpha:** thresholds and compaction steering may change between releases.
11
+
12
+ ## Requirements
13
+
14
+ - Node.js 22.19.0 or newer
15
+ - Pi 0.85.0
16
+ - Authentication for the model selected for summarization
13
17
 
14
18
  ## Install
15
19
 
20
+ `doompi init` and `dpi init` include Autocompact in `default.packages` in `.doom/modes.yaml`.
21
+ Remove it or move it to a named layer to change which major modes load it. Pi discovers its sole
22
+ extension entry through `package.json.pi.extensions`. For direct Pi installation:
23
+
16
24
  ```bash
17
- npm install @agimon-ai/doompi-autocompact
25
+ pi install npm:@agimon-ai/doompi-autocompact
26
+ ```
27
+
28
+ The extension entry is `@agimon-ai/doompi-autocompact/extensions/pi`.
29
+
30
+ ## Checkpoint ladder
31
+
32
+ The standard adapter uses thresholds around 50%, 75%, and 95% of the usable context window,
33
+ subject to token caps and Pi's native-compaction clamp:
34
+
35
+ 1. create an initial compact summary;
36
+ 2. combine it with later messages and allow the model to decide whether compaction is ready;
37
+ 3. combine again and force compaction on the final pass.
38
+
39
+ ## Per-model token checkpoints
40
+
41
+ Ratios scale with the window, which is usually what you want. On a very large window they can
42
+ also mean the first checkpoint waits far longer than you would like: half of a one-million-token
43
+ window is 500,000 tokens. `modes.autocompact.overrides` pins individual passes to an absolute
44
+ token count for the models you name, and leaves every other model on the ratio ladder.
45
+
46
+ ```yaml
47
+ modes:
48
+ autocompact:
49
+ overrides:
50
+ - model: 'claude-opus-4-[6-9]'
51
+ tokens:
52
+ pass1: 75000
53
+ pass2: 150000
54
+ pass3: 200000
18
55
  ```
19
56
 
20
- ## How it loads
57
+ - Entries are tried in file order and the first match wins. A model matching nothing behaves
58
+ exactly as it does without this key.
59
+ - `model` is a glob supporting `*` and character classes such as `[6-9]`. A pattern containing
60
+ `/` is matched against `provider/id`, anything else against the bare model id, because the
61
+ wildcard does not cross the separator. Matching ignores case.
62
+ - The lower of the ratio and the token count wins, so an override can only bring a checkpoint
63
+ forward, never push one past the point Pi compacts natively.
64
+ - Counts are compared against total context usage, not against growth since the last compaction.
65
+ - A count at or below the current cycle's baseline is ignored and the pass falls back to its
66
+ ratio. Without that, a compaction landing above the count would satisfy the pass as soon as
67
+ the next cycle opened and re-fire it every turn.
68
+ - A pass never fires before the one before it. A list that puts a later pass lower is raised to
69
+ match, the same way a ratio below the previous pass is.
70
+ - A repository config replaces the global list whole rather than merging entry by entry.
71
+ - These keys are not on the cockpit settings page; edit `.doom/config.yaml` directly.
72
+ Summarization runs asynchronously in the background, on the session's own provider, so a model
73
+ registered by a Pi provider extension summarizes through that extension. Checkpoints are
74
+ persisted as hidden session entries and used for later steering.
75
+
76
+ DoomPi uses the configured planning subagent model and thinking level when available, then falls
77
+ back to the active Pi model. Standalone Pi without DoomPi planning configuration uses the active
78
+ model. Each checkpoint can therefore make another provider request, consume quota, and require the
79
+ credentials for the selected model. Provider errors or missing authentication affect checkpoint
80
+ generation rather than granting a free local summary.
81
+
82
+ ## Coordination state
83
+
84
+ Autocompact does not own `@agimon-ai/doompi-task` or `@agimon-ai/doompi-team` persistence. The
85
+ standard adapter reads best-effort snapshots from those packages when available, while Task's
86
+ `tasks.json` and Team's run and intercom state remain owned by their respective packages. Missing
87
+ snapshot data is reported as unavailable and must not be inferred from an Autocompact summary.
21
88
 
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.
89
+ ## Public API
24
90
 
25
- Extension entry: `@agimon-ai/doompi-autocompact/extensions/pi`
91
+ ```ts
92
+ import { installAutocompactRuntime, thresholdTokens } from '@agimon-ai/doompi-autocompact';
93
+ import type { AutocompactPass } from '@agimon-ai/doompi-autocompact';
94
+ ```
95
+
96
+ Normal Pi activation should use the discovered `extensions/pi` entry. Host integrations can call
97
+ `installAutocompactRuntime` to install package resources into the shared runner-scoped Cordis host.
98
+ The extension entry manages its plugin lifecycle and releases the host lease when the Pi session
99
+ shuts down. `thresholdTokens` exposes the threshold policy for hosts that need to preview or test
100
+ checkpoint boundaries.
101
+
102
+ ## Development
26
103
 
27
- ## Entry points
104
+ ```bash
105
+ pnpm build
106
+ pnpm typecheck
107
+ pnpm test
108
+ pnpm lint
109
+ ```
28
110
 
29
- | Import |
30
- | --------------------------------------------- |
31
- | `@agimon-ai/doompi-autocompact` |
32
- | `@agimon-ai/doompi-autocompact/extensions/pi` |
111
+ Maintained by [Agimon](https://agimon.ai/about).
33
112
 
34
113
  ## License
35
114
 
@@ -0,0 +1,2 @@
1
+ let e=require("minimatch");function t(t,n){let r=t.includes(`/`)?`${n.provider}/${n.id}`:n.id;return(0,e.minimatch)(r,t,{nocase:!0})}function n(e,n){if(!e)return{};let r=n.find(n=>t(n.model,e));if(!r)return{};let{pass1:i,pass2:a,pass3:o}=r.tokens;return{...i===void 0?{}:{1:i},...a===void 0?{}:{2:a},...o===void 0?{}:{3:o}}}exports.resolveModelTokenOverrides=n;
2
+ //# sourceMappingURL=modelOverrides.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"modelOverrides.cjs","names":[],"sources":["../../../src/adapters/compaction/modelOverrides.ts"],"sourcesContent":["/**\n * Picks the absolute token checkpoints configured for the model a session is running.\n *\n * DESIGN PATTERNS:\n * - Pure decision function, so the matching rule is unit-testable without a session,\n * a config file or a filesystem\n * - First match in file order wins, so a reader resolves a model by reading down the\n * list rather than by working out which pattern is the most specific\n * - A model matching nothing returns no overrides at all, which leaves the ratio\n * ladder exactly as it behaves without this feature\n *\n * AVOID:\n * - Stripping a thinking suffix the way subagent model scope does. That matches\n * free-typed config strings; this matches a resolved `Model`, whose `id` carries\n * the level in a separate field and never in the id itself.\n * - Matching a bare pattern against `provider/id`. The glob wildcard does not cross\n * the separator, so the subject has to follow the pattern's own shape.\n */\n\nimport { minimatch } from 'minimatch';\nimport type { AutocompactOverrideConfig } from '@agimon-ai/doompi-config';\nimport type { AutocompactTokenOverrides } from '../../types/index.ts';\n\n/** The parts of a resolved model the rules match on. */\nexport interface AutocompactModelIdentity {\n id: string;\n provider: string;\n}\n\n/**\n * A pattern naming a provider is matched against `provider/id`, anything else\n * against the bare id. `*` does not cross `/`, so a bare pattern tested against a\n * qualified subject would never match and would read as a silently dead rule.\n */\nfunction matchesModelPattern(pattern: string, model: AutocompactModelIdentity): boolean {\n const subject = pattern.includes('/') ? `${model.provider}/${model.id}` : model.id;\n return minimatch(subject, pattern, { nocase: true });\n}\n\nexport function resolveModelTokenOverrides(\n model: AutocompactModelIdentity | undefined,\n overrides: readonly AutocompactOverrideConfig[],\n): AutocompactTokenOverrides {\n if (!model) return {};\n const matched = overrides.find((entry) => matchesModelPattern(entry.model, model));\n if (!matched) return {};\n const { pass1, pass2, pass3 } = matched.tokens;\n return {\n ...(pass1 === undefined ? {} : { 1: pass1 }),\n ...(pass2 === undefined ? {} : { 2: pass2 }),\n ...(pass3 === undefined ? {} : { 3: pass3 }),\n };\n}\n"],"mappings":"2BAkCA,SAAS,EAAoB,EAAiB,EAA0C,CACtF,IAAM,EAAU,EAAQ,SAAS,GAAG,EAAI,GAAG,EAAM,SAAS,GAAG,EAAM,KAAO,EAAM,GAChF,OAAA,EAAO,EAAA,UAAA,CAAU,EAAS,EAAS,CAAE,OAAQ,EAAK,CAAC,CACrD,CAEA,SAAgB,EACd,EACA,EAC2B,CAC3B,GAAI,CAAC,EAAO,MAAO,CAAC,EACpB,IAAM,EAAU,EAAU,KAAM,GAAU,EAAoB,EAAM,MAAO,CAAK,CAAC,EACjF,GAAI,CAAC,EAAS,MAAO,CAAC,EACtB,GAAM,CAAE,QAAO,QAAO,SAAU,EAAQ,OACxC,MAAO,CACL,GAAI,IAAU,IAAA,GAAY,CAAC,EAAI,CAAE,EAAG,CAAM,EAC1C,GAAI,IAAU,IAAA,GAAY,CAAC,EAAI,CAAE,EAAG,CAAM,EAC1C,GAAI,IAAU,IAAA,GAAY,CAAC,EAAI,CAAE,EAAG,CAAM,CAC5C,CACF"}
@@ -0,0 +1,2 @@
1
+ import{minimatch as e}from"minimatch";function t(t,n){let r=t.includes(`/`)?`${n.provider}/${n.id}`:n.id;return e(r,t,{nocase:!0})}function n(e,n){if(!e)return{};let r=n.find(n=>t(n.model,e));if(!r)return{};let{pass1:i,pass2:a,pass3:o}=r.tokens;return{...i===void 0?{}:{1:i},...a===void 0?{}:{2:a},...o===void 0?{}:{3:o}}}export{n as resolveModelTokenOverrides};
2
+ //# sourceMappingURL=modelOverrides.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"modelOverrides.mjs","names":[],"sources":["../../../src/adapters/compaction/modelOverrides.ts"],"sourcesContent":["/**\n * Picks the absolute token checkpoints configured for the model a session is running.\n *\n * DESIGN PATTERNS:\n * - Pure decision function, so the matching rule is unit-testable without a session,\n * a config file or a filesystem\n * - First match in file order wins, so a reader resolves a model by reading down the\n * list rather than by working out which pattern is the most specific\n * - A model matching nothing returns no overrides at all, which leaves the ratio\n * ladder exactly as it behaves without this feature\n *\n * AVOID:\n * - Stripping a thinking suffix the way subagent model scope does. That matches\n * free-typed config strings; this matches a resolved `Model`, whose `id` carries\n * the level in a separate field and never in the id itself.\n * - Matching a bare pattern against `provider/id`. The glob wildcard does not cross\n * the separator, so the subject has to follow the pattern's own shape.\n */\n\nimport { minimatch } from 'minimatch';\nimport type { AutocompactOverrideConfig } from '@agimon-ai/doompi-config';\nimport type { AutocompactTokenOverrides } from '../../types/index.ts';\n\n/** The parts of a resolved model the rules match on. */\nexport interface AutocompactModelIdentity {\n id: string;\n provider: string;\n}\n\n/**\n * A pattern naming a provider is matched against `provider/id`, anything else\n * against the bare id. `*` does not cross `/`, so a bare pattern tested against a\n * qualified subject would never match and would read as a silently dead rule.\n */\nfunction matchesModelPattern(pattern: string, model: AutocompactModelIdentity): boolean {\n const subject = pattern.includes('/') ? `${model.provider}/${model.id}` : model.id;\n return minimatch(subject, pattern, { nocase: true });\n}\n\nexport function resolveModelTokenOverrides(\n model: AutocompactModelIdentity | undefined,\n overrides: readonly AutocompactOverrideConfig[],\n): AutocompactTokenOverrides {\n if (!model) return {};\n const matched = overrides.find((entry) => matchesModelPattern(entry.model, model));\n if (!matched) return {};\n const { pass1, pass2, pass3 } = matched.tokens;\n return {\n ...(pass1 === undefined ? {} : { 1: pass1 }),\n ...(pass2 === undefined ? {} : { 2: pass2 }),\n ...(pass3 === undefined ? {} : { 3: pass3 }),\n };\n}\n"],"mappings":"sCAkCA,SAAS,EAAoB,EAAiB,EAA0C,CACtF,IAAM,EAAU,EAAQ,SAAS,GAAG,EAAI,GAAG,EAAM,SAAS,GAAG,EAAM,KAAO,EAAM,GAChF,OAAO,EAAU,EAAS,EAAS,CAAE,OAAQ,EAAK,CAAC,CACrD,CAEA,SAAgB,EACd,EACA,EAC2B,CAC3B,GAAI,CAAC,EAAO,MAAO,CAAC,EACpB,IAAM,EAAU,EAAU,KAAM,GAAU,EAAoB,EAAM,MAAO,CAAK,CAAC,EACjF,GAAI,CAAC,EAAS,MAAO,CAAC,EACtB,GAAM,CAAE,QAAO,QAAO,SAAU,EAAQ,OACxC,MAAO,CACL,GAAI,IAAU,IAAA,GAAY,CAAC,EAAI,CAAE,EAAG,CAAM,EAC1C,GAAI,IAAU,IAAA,GAAY,CAAC,EAAI,CAAE,EAAG,CAAM,EAC1C,GAAI,IAAU,IAAA,GAAY,CAAC,EAAI,CAAE,EAAG,CAAM,CAC5C,CACF"}
@@ -0,0 +1,8 @@
1
+ const e=require("../../types/constants.cjs");let t=require("@earendil-works/pi-coding-agent");const n=/<shouldCompact>\s*(true|false)\s*<\/shouldCompact>/i,r=/\n*<(?:read-files|modified-files)>[\s\S]*?<\/(?:read-files|modified-files)>/g;function i(e){return typeof e==`object`&&!!e}function a(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function o(e){return e===1||e===2||e===3}function s(e){if(e.type===`message`&&e.message.role===`assistant`)return e.message.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
2
+ `).trim()||void 0}function c(e){return i(e)&&typeof e.role==`string`}function l(e){if(!i(e)||!a(e.readFiles)||!a(e.modifiedFiles)||!Array.isArray(e.retainedMessages)||!e.retainedMessages.every(c)||!i(e.doomAutocompact))return;let t=e.doomAutocompact;if(!(t.version!==2||t.pass!==2&&t.pass!==3||typeof t.cycle!=`number`||typeof t.requestId!=`string`||typeof t.snapshotLeafId!=`string`||typeof t.tokensBefore!=`number`))return{readFiles:[...e.readFiles],modifiedFiles:[...e.modifiedFiles],retainedMessages:[...e.retainedMessages],doomAutocompact:{version:2,cycle:t.cycle,pass:t.pass,requestId:t.requestId,snapshotLeafId:t.snapshotLeafId,tokensBefore:t.tokensBefore}}}function u(){return{version:2,cycle:1,pass:1,phase:`waiting`,checkpointQueue:[],exhaustedPasses:[],invalidAttempts:0,baselineTokens:0,baselinePending:!1,readFiles:[],modifiedFiles:[]}}function d(t={}){let n=0,r={};for(let i of[1,2,3]){let a=Math.max(t[i]??e.COMPACTION_THRESHOLDS[i].ratio,n);r[i]=a,n=a}return r}function f(n,r,i=0,a={}){let o=e.COMPACTION_THRESHOLDS[n],s=d(a)[n],c=Math.max(0,Math.min(i,r)),l=r-c,u=c+Math.min(Math.floor(l*s),o.capTokens),f=r-t.DEFAULT_COMPACTION_SETTINGS.reserveTokens;return f>c?Math.min(u,f):u}function p(e,t=0,n={},r={}){let i=0,a={};for(let o of[1,2,3]){let s=f(o,e,t,n),c=r[o];a[o]=Math.max(c!==void 0&&c>t?Math.min(s,c):s,i),i=a[o]}return a}function m(e){return e.findLast(e=>e.type===`compaction`||e.type===`custom`&&e.customType===`doom-autocompact-checkpoint`||e.type===`custom_message`&&(e.customType===`doom-autocompact-checkpoint`||e.customType===`doom-autocompact-context`))}function h(e){let t=e.findLastIndex(e=>e.type===`compaction`||e.type===`custom_message`&&e.customType===`doom-autocompact-context`);return e.slice(t+1).some(e=>{if(e.type!==`message`||e.message.role!==`assistant`)return!1;let{stopReason:t,usage:n}=e.message;return t===`aborted`||t===`error`||!n?!1:(n.totalTokens||n.input+n.output+n.cacheRead+n.cacheWrite)>0})}function g(e,n){let r=e.findIndex(e=>e.id===n);return r===-1?[]:e.slice(r+1).filter(e=>e.type!==`custom_message`||e.customType!==`doom-autocompact-checkpoint`).flatMap(e=>(0,t.sessionEntryToContextMessages)(e))}function _(e,t){let n=t.findLastIndex(e=>e.type===`compaction`),r=t.slice(n+1).findLast(e=>e.type===`custom_message`&&e.customType===`doom-autocompact-context`);if(!r||r.type!==`custom_message`)return{messages:e,retainedMessageCount:0};let i=l(r.details),a=b(r);if(!i||!a)return{messages:e,invalidMarker:!0,retainedMessageCount:0};let o=e.findLastIndex(e=>e.role===`custom`&&e.customType===`doom-autocompact-context`&&l(e.details)?.doomAutocompact.requestId===i.doomAutocompact.requestId);return o===-1?{messages:e,invalidMarker:!0,retainedMessageCount:0}:{messages:[{role:`compactionSummary`,summary:a,tokensBefore:i.doomAutocompact.tokensBefore,timestamp:e[o]?.timestamp??Date.now()},...i.retainedMessages,...e.slice(o+1)],marker:i.doomAutocompact,retainedMessageCount:i.retainedMessages.length}}function v(e){let t={read:new Set,written:new Set,edited:new Set};for(let n of e)if(n.role===`assistant`)for(let e of n.content){if(e.type!==`toolCall`)continue;let n=typeof e.arguments.path==`string`?e.arguments.path:void 0;n&&(e.name===`read`?t.read.add(n):e.name===`write`?t.written.add(n):e.name===`edit`&&t.edited.add(n))}return t}function y(e){if(!i(e)||e.version!==2||typeof e.cycle!=`number`||!o(e.pass)||e.phase!==`waiting`&&e.phase!==`checkpoint_pending`&&e.phase!==`checkpoint_ready`&&e.phase!==`compacting`)return;let t=e.baselineTokens??0;if(typeof t!=`number`||t<0)return;let n=e.baselinePending??!1;if(typeof n!=`boolean`)return;let r=e.checkpointQueue??[];if(!Array.isArray(r)||!r.every(o)||r.some((e,t)=>t>0&&e<=r[t-1]))return;let s=e.exhaustedPasses??[];if(!Array.isArray(s)||!s.every(o))return;let c=e.invalidAttempts??0;if(!(typeof c!=`number`||c<0)&&a(e.readFiles)&&a(e.modifiedFiles)&&(e.requestId===void 0||typeof e.requestId==`string`)&&(e.compactionPass===void 0||e.compactionPass===2||e.compactionPass===3)&&!(`latestCheckpointEntryId`in e)&&(e.latestCheckpointSnapshotLeafId===void 0||typeof e.latestCheckpointSnapshotLeafId==`string`)&&(e.lastAttemptLeafId===void 0||typeof e.lastAttemptLeafId==`string`)&&(e.snapshotLeafId===void 0||typeof e.snapshotLeafId==`string`)&&!(e.snapshotTokens!==void 0&&(typeof e.snapshotTokens!=`number`||e.snapshotTokens<0))&&(e.pendingCheckpoint===void 0||typeof e.pendingCheckpoint==`string`))return{version:2,cycle:e.cycle,pass:e.pass,phase:e.phase,checkpointQueue:[...r],exhaustedPasses:[...s],invalidAttempts:c,baselineTokens:t,baselinePending:n,readFiles:[...e.readFiles],modifiedFiles:[...e.modifiedFiles],...e.requestId?{requestId:e.requestId}:{},...e.compactionPass?{compactionPass:e.compactionPass}:{},...e.latestCheckpointSnapshotLeafId?{latestCheckpointSnapshotLeafId:e.latestCheckpointSnapshotLeafId}:{},...e.lastAttemptLeafId?{lastAttemptLeafId:e.lastAttemptLeafId}:{},...e.snapshotLeafId?{snapshotLeafId:e.snapshotLeafId}:{},...e.snapshotTokens===void 0?{}:{snapshotTokens:e.snapshotTokens},...e.pendingCheckpoint?{pendingCheckpoint:e.pendingCheckpoint}:{}}}function b(e){if(e)return e.type===`compaction`?e.summary.trim()||void 0:e.type===`custom`?i(e.data)&&typeof e.data.summary==`string`&&e.data.summary.trim()||void 0:e.type===`custom_message`?(typeof e.content==`string`?e.content:e.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
3
+ `)).trim()||void 0:s(e)}function x(e){let t=e.match(n),r=e.replace(n,``).trim();return t?{summary:r,shouldCompact:t[1]?.toLowerCase()===`true`}:{summary:r}}function S(t){return e.CHECKPOINT_HEADINGS.every(e=>t.includes(e))}function C(e,t,n,r){return`${e}:${t}:${n}:${r??`root`}`}function w(e,t,n){return{version:2,cycle:e,pass:t,requestId:n}}function T(e,t,n){let r=new Set([...e.modifiedFiles,...n?.modifiedFiles??[],...t?[...t.edited,...t.written]:[]]),i=new Set([...e.readFiles,...n?.readFiles??[],...t?[...t.read]:[]]);for(let e of r)i.delete(e);return{readFiles:[...i].sort(),modifiedFiles:[...r].sort()}}function E(e){if(i(e)&&a(e.readFiles)&&a(e.modifiedFiles))return{readFiles:e.readFiles,modifiedFiles:e.modifiedFiles}}function D(e,t){let n=[];t.readFiles.length>0&&n.push(`<read-files>\n${t.readFiles.join(`
4
+ `)}\n</read-files>`),t.modifiedFiles.length>0&&n.push(`<modified-files>\n${t.modifiedFiles.join(`
5
+ `)}\n</modified-files>`);let i=e.replace(r,``).trim();return n.length>0?`${i}\n\n${n.join(`
6
+
7
+ `)}`:i}exports.baselineUsageIsSettled=h,exports.checkpointRequestDetails=w,exports.checkpointSummaryFromEntry=b,exports.compactionRatios=d,exports.contextDetailsFromUnknown=l,exports.createInitialState=u,exports.createRequestId=C,exports.effectiveThresholds=p,exports.fileDetailsFromUnknown=E,exports.fileOperationsFromMessages=v,exports.isStructuredCheckpoint=S,exports.latestCheckpointArtifactEntry=m,exports.mergeFileDetails=T,exports.parseCheckpointDecision=x,exports.parseState=y,exports.projectContextMessages=_,exports.retainedMessagesAfterSnapshot=g,exports.thresholdTokens=f,exports.withCanonicalFileSections=D;
8
+ //# sourceMappingURL=policy.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"policy.cjs","names":["COMPACTION_THRESHOLDS","DEFAULT_COMPACTION_SETTINGS","sessionEntryToContextMessages","CHECKPOINT_HEADINGS"],"sources":["../../../src/adapters/compaction/policy.ts"],"sourcesContent":["import {\n DEFAULT_COMPACTION_SETTINGS,\n type FileOperations,\n type SessionEntry,\n sessionEntryToContextMessages,\n} from '@earendil-works/pi-coding-agent';\nimport {\n CHECKPOINT_HEADINGS,\n CHECKPOINT_MESSAGE_TYPE,\n COMPACTION_THRESHOLDS,\n CONTEXT_MESSAGE_TYPE,\n STATE_VERSION,\n} from '../../types/constants.ts';\nimport type {\n AutocompactContextDetails,\n AutocompactFileDetails,\n AutocompactRatioOverrides,\n AutocompactTokenOverrides,\n AutocompactMessage,\n AutocompactPass,\n AutocompactState,\n CheckpointDecision,\n CheckpointRequestDetails,\n ContextProjection,\n} from '../../types/index.ts';\n\nconst SHOULD_COMPACT_PATTERN = /<shouldCompact>\\s*(true|false)\\s*<\\/shouldCompact>/i;\nconst FILE_SECTION_PATTERN = /\\n*<(?:read-files|modified-files)>[\\s\\S]*?<\\/(?:read-files|modified-files)>/g;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((item) => typeof item === 'string');\n}\n\nfunction isPass(value: unknown): value is AutocompactPass {\n return value === 1 || value === 2 || value === 3;\n}\n\nfunction assistantText(entry: SessionEntry): string | undefined {\n if (entry.type !== 'message' || entry.message.role !== 'assistant') return undefined;\n const text = entry.message.content\n .filter((block) => block.type === 'text')\n .map((block) => block.text)\n .join('\\n')\n .trim();\n return text || undefined;\n}\n\nfunction isAutocompactMessage(value: unknown): value is AutocompactMessage {\n return isRecord(value) && typeof value.role === 'string';\n}\n\nexport function contextDetailsFromUnknown(value: unknown): AutocompactContextDetails | undefined {\n if (!isRecord(value) || !isStringArray(value.readFiles) || !isStringArray(value.modifiedFiles)) return undefined;\n if (!Array.isArray(value.retainedMessages) || !value.retainedMessages.every(isAutocompactMessage)) return undefined;\n if (!isRecord(value.doomAutocompact)) return undefined;\n const marker = value.doomAutocompact;\n if (\n marker.version !== STATE_VERSION ||\n (marker.pass !== 2 && marker.pass !== 3) ||\n typeof marker.cycle !== 'number' ||\n typeof marker.requestId !== 'string' ||\n typeof marker.snapshotLeafId !== 'string' ||\n typeof marker.tokensBefore !== 'number'\n )\n return undefined;\n return {\n readFiles: [...value.readFiles],\n modifiedFiles: [...value.modifiedFiles],\n retainedMessages: [...value.retainedMessages],\n doomAutocompact: {\n version: STATE_VERSION,\n cycle: marker.cycle,\n pass: marker.pass,\n requestId: marker.requestId,\n snapshotLeafId: marker.snapshotLeafId,\n tokensBefore: marker.tokensBefore,\n },\n };\n}\n\nexport function createInitialState(): AutocompactState {\n return {\n version: STATE_VERSION,\n cycle: 1,\n pass: 1,\n phase: 'waiting',\n checkpointQueue: [],\n exhaustedPasses: [],\n invalidAttempts: 0,\n baselineTokens: 0,\n baselinePending: false,\n readFiles: [],\n modifiedFiles: [],\n };\n}\n\n/**\n * The ratios each pass fires at, with configured values folded in.\n *\n * The ladder only works if it climbs, so a configured pass never sits below the\n * one before it: a file that says pass 2 fires earlier than pass 1 gets pass 1's\n * ratio for pass 2 rather than a pass that can never contribute.\n */\nexport function compactionRatios(configured: AutocompactRatioOverrides = {}): Record<AutocompactPass, number> {\n let previous = 0;\n const ratios = {} as Record<AutocompactPass, number>;\n for (const pass of [1, 2, 3] as const) {\n const ratio = Math.max(configured[pass] ?? COMPACTION_THRESHOLDS[pass].ratio, previous);\n ratios[pass] = ratio;\n previous = ratio;\n }\n return ratios;\n}\n\nexport function thresholdTokens(\n pass: AutocompactPass,\n contextWindow: number,\n baselineTokens = 0,\n configured: AutocompactRatioOverrides = {},\n): number {\n const threshold = COMPACTION_THRESHOLDS[pass];\n const ratio = compactionRatios(configured)[pass];\n const baseline = Math.max(0, Math.min(baselineTokens, contextWindow));\n const remaining = contextWindow - baseline;\n const staged = baseline + Math.min(Math.floor(remaining * ratio), threshold.capTokens);\n // Pi compacts natively above `contextWindow - reserveTokens`. A staged threshold above that\n // point can never fire, so the ladder would silently degrade into native compaction: on a\n // 200k window the raw pass 3 ratio lands at 190_000, while Pi already compacted at 183_616.\n const nativeTrigger = contextWindow - DEFAULT_COMPACTION_SETTINGS.reserveTokens;\n return nativeTrigger > baseline ? Math.min(staged, nativeTrigger) : staged;\n}\n\n/**\n * Where every pass fires, with a matching model's absolute token checkpoints folded in.\n *\n * A configured token count replaces the ratio only when it fires earlier, so an\n * override can bring a checkpoint forward on a very large window without ever\n * pushing one past the point Pi compacts natively.\n *\n * Two rules keep the ladder usable. A token count at or below the baseline is\n * ignored, because a compaction that lands above it would otherwise satisfy that\n * pass the moment the next cycle opens and re-fire it every turn. And a pass never\n * sits below the one before it, for the same reason {@link compactionRatios}\n * climbs: `evaluateUsage` skips any pass below the one already reached, so a later\n * pass that fires first does not merely reorder the ladder, it locks the earlier\n * passes out of the cycle and forces compaction with no summary ever written.\n */\nexport function effectiveThresholds(\n contextWindow: number,\n baselineTokens = 0,\n configured: AutocompactRatioOverrides = {},\n tokenOverrides: AutocompactTokenOverrides = {},\n): Record<AutocompactPass, number> {\n let previous = 0;\n const thresholds = {} as Record<AutocompactPass, number>;\n for (const pass of [1, 2, 3] as const) {\n const ratioTokens = thresholdTokens(pass, contextWindow, baselineTokens, configured);\n const absolute = tokenOverrides[pass];\n const staged = absolute !== undefined && absolute > baselineTokens ? Math.min(ratioTokens, absolute) : ratioTokens;\n thresholds[pass] = Math.max(staged, previous);\n previous = thresholds[pass];\n }\n return thresholds;\n}\nexport function latestCheckpointArtifactEntry(branchEntries: SessionEntry[]): SessionEntry | undefined {\n return branchEntries.findLast(\n (entry) =>\n entry.type === 'compaction' ||\n // Staged checkpoints are plain entries so they stay out of the agent's LLM context.\n (entry.type === 'custom' && entry.customType === CHECKPOINT_MESSAGE_TYPE) ||\n // Legacy sessions staged checkpoints as custom messages; committed markers still are.\n (entry.type === 'custom_message' &&\n (entry.customType === CHECKPOINT_MESSAGE_TYPE || entry.customType === CONTEXT_MESSAGE_TYPE)),\n );\n}\n\nexport function baselineUsageIsSettled(branchEntries: SessionEntry[]): boolean {\n const boundaryIndex = branchEntries.findLastIndex(\n (entry) =>\n entry.type === 'compaction' || (entry.type === 'custom_message' && entry.customType === CONTEXT_MESSAGE_TYPE),\n );\n return branchEntries.slice(boundaryIndex + 1).some((entry) => {\n if (entry.type !== 'message' || entry.message.role !== 'assistant') return false;\n const { stopReason, usage } = entry.message;\n if (stopReason === 'aborted' || stopReason === 'error' || !usage) return false;\n return (usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite) > 0;\n });\n}\n\nexport function retainedMessagesAfterSnapshot(\n branchEntries: SessionEntry[],\n snapshotLeafId: string,\n): AutocompactMessage[] {\n const snapshotIndex = branchEntries.findIndex((entry) => entry.id === snapshotLeafId);\n if (snapshotIndex === -1) return [];\n return branchEntries\n .slice(snapshotIndex + 1)\n .filter((entry) => entry.type !== 'custom_message' || entry.customType !== CHECKPOINT_MESSAGE_TYPE)\n .flatMap((entry) => sessionEntryToContextMessages(entry));\n}\n\nexport function projectContextMessages(\n messages: AutocompactMessage[],\n branchEntries: SessionEntry[],\n): ContextProjection {\n const nativeCompactionIndex = branchEntries.findLastIndex((entry) => entry.type === 'compaction');\n const markerEntry = branchEntries\n .slice(nativeCompactionIndex + 1)\n .findLast((entry) => entry.type === 'custom_message' && entry.customType === CONTEXT_MESSAGE_TYPE);\n if (!markerEntry || markerEntry.type !== 'custom_message') {\n return { messages, retainedMessageCount: 0 };\n }\n\n const details = contextDetailsFromUnknown(markerEntry.details);\n const summary = checkpointSummaryFromEntry(markerEntry);\n if (!details || !summary) return { messages, invalidMarker: true, retainedMessageCount: 0 };\n\n const markerMessageIndex = messages.findLastIndex(\n (message) =>\n message.role === 'custom' &&\n message.customType === CONTEXT_MESSAGE_TYPE &&\n contextDetailsFromUnknown(message.details)?.doomAutocompact.requestId === details.doomAutocompact.requestId,\n );\n if (markerMessageIndex === -1) return { messages, invalidMarker: true, retainedMessageCount: 0 };\n\n const summaryMessage: AutocompactMessage = {\n role: 'compactionSummary',\n summary,\n tokensBefore: details.doomAutocompact.tokensBefore,\n timestamp: messages[markerMessageIndex]?.timestamp ?? Date.now(),\n };\n return {\n messages: [summaryMessage, ...details.retainedMessages, ...messages.slice(markerMessageIndex + 1)],\n marker: details.doomAutocompact,\n retainedMessageCount: details.retainedMessages.length,\n };\n}\n\nexport function fileOperationsFromMessages(messages: AutocompactMessage[]): FileOperations {\n const fileOps: FileOperations = { read: new Set(), written: new Set(), edited: new Set() };\n for (const message of messages) {\n if (message.role !== 'assistant') continue;\n for (const block of message.content) {\n if (block.type !== 'toolCall') continue;\n const path = typeof block.arguments.path === 'string' ? block.arguments.path : undefined;\n if (!path) continue;\n if (block.name === 'read') fileOps.read.add(path);\n else if (block.name === 'write') fileOps.written.add(path);\n else if (block.name === 'edit') fileOps.edited.add(path);\n }\n }\n return fileOps;\n}\n\nexport function parseState(value: unknown): AutocompactState | undefined {\n if (!isRecord(value)) return undefined;\n if (value.version !== STATE_VERSION || typeof value.cycle !== 'number' || !isPass(value.pass)) return undefined;\n if (\n value.phase !== 'waiting' &&\n value.phase !== 'checkpoint_pending' &&\n value.phase !== 'checkpoint_ready' &&\n value.phase !== 'compacting'\n )\n return undefined;\n const baselineTokens = value.baselineTokens ?? 0;\n if (typeof baselineTokens !== 'number' || baselineTokens < 0) return undefined;\n const baselinePending = value.baselinePending ?? false;\n if (typeof baselinePending !== 'boolean') return undefined;\n const checkpointQueue = value.checkpointQueue ?? [];\n if (\n !Array.isArray(checkpointQueue) ||\n !checkpointQueue.every(isPass) ||\n checkpointQueue.some((pass, index) => index > 0 && pass <= checkpointQueue[index - 1]!)\n )\n return undefined;\n // Sessions persisted before bounded retry landed simply have no attempt history to restore.\n const exhaustedPasses = value.exhaustedPasses ?? [];\n if (!Array.isArray(exhaustedPasses) || !exhaustedPasses.every(isPass)) return undefined;\n const invalidAttempts = value.invalidAttempts ?? 0;\n if (typeof invalidAttempts !== 'number' || invalidAttempts < 0) return undefined;\n if (!isStringArray(value.readFiles) || !isStringArray(value.modifiedFiles)) return undefined;\n if (value.requestId !== undefined && typeof value.requestId !== 'string') return undefined;\n if (value.compactionPass !== undefined && value.compactionPass !== 2 && value.compactionPass !== 3) return undefined;\n if ('latestCheckpointEntryId' in value) return undefined;\n if (value.latestCheckpointSnapshotLeafId !== undefined && typeof value.latestCheckpointSnapshotLeafId !== 'string')\n return undefined;\n if (value.lastAttemptLeafId !== undefined && typeof value.lastAttemptLeafId !== 'string') return undefined;\n if (value.snapshotLeafId !== undefined && typeof value.snapshotLeafId !== 'string') return undefined;\n if (value.snapshotTokens !== undefined && (typeof value.snapshotTokens !== 'number' || value.snapshotTokens < 0))\n return undefined;\n if (value.pendingCheckpoint !== undefined && typeof value.pendingCheckpoint !== 'string') return undefined;\n\n return {\n version: STATE_VERSION,\n cycle: value.cycle,\n pass: value.pass,\n phase: value.phase,\n checkpointQueue: [...checkpointQueue],\n exhaustedPasses: [...exhaustedPasses],\n invalidAttempts,\n baselineTokens,\n baselinePending,\n readFiles: [...value.readFiles],\n modifiedFiles: [...value.modifiedFiles],\n ...(value.requestId ? { requestId: value.requestId } : {}),\n ...(value.compactionPass ? { compactionPass: value.compactionPass } : {}),\n ...(value.latestCheckpointSnapshotLeafId\n ? { latestCheckpointSnapshotLeafId: value.latestCheckpointSnapshotLeafId }\n : {}),\n ...(value.lastAttemptLeafId ? { lastAttemptLeafId: value.lastAttemptLeafId } : {}),\n ...(value.snapshotLeafId ? { snapshotLeafId: value.snapshotLeafId } : {}),\n ...(value.snapshotTokens !== undefined ? { snapshotTokens: value.snapshotTokens } : {}),\n ...(value.pendingCheckpoint ? { pendingCheckpoint: value.pendingCheckpoint } : {}),\n };\n}\n\nexport function checkpointSummaryFromEntry(entry: SessionEntry | undefined): string | undefined {\n if (!entry) return undefined;\n if (entry.type === 'compaction') return entry.summary.trim() || undefined;\n if (entry.type === 'custom') {\n return isRecord(entry.data) && typeof entry.data.summary === 'string'\n ? entry.data.summary.trim() || undefined\n : undefined;\n }\n if (entry.type === 'custom_message') {\n const content =\n typeof entry.content === 'string'\n ? entry.content\n : entry.content\n .filter((block) => block.type === 'text')\n .map((block) => block.text)\n .join('\\n');\n return content.trim() || undefined;\n }\n return assistantText(entry);\n}\n\nexport function parseCheckpointDecision(response: string): CheckpointDecision {\n const match = response.match(SHOULD_COMPACT_PATTERN);\n const summary = response.replace(SHOULD_COMPACT_PATTERN, '').trim();\n if (!match) return { summary };\n return { summary, shouldCompact: match[1]?.toLowerCase() === 'true' };\n}\n\nexport function isStructuredCheckpoint(summary: string): boolean {\n return CHECKPOINT_HEADINGS.every((heading) => summary.includes(heading));\n}\n\nexport function createRequestId(\n sessionId: string,\n cycle: number,\n pass: AutocompactPass,\n leafId: string | null,\n): string {\n return `${sessionId}:${cycle}:${pass}:${leafId ?? 'root'}`;\n}\n\nexport function checkpointRequestDetails(\n cycle: number,\n pass: AutocompactPass,\n requestId: string,\n): CheckpointRequestDetails {\n return { version: STATE_VERSION, cycle, pass, requestId };\n}\n\nexport function mergeFileDetails(\n current: AutocompactFileDetails,\n fileOps?: FileOperations,\n additional?: AutocompactFileDetails,\n): AutocompactFileDetails {\n const modified = new Set([\n ...current.modifiedFiles,\n ...(additional?.modifiedFiles ?? []),\n ...(fileOps ? [...fileOps.edited, ...fileOps.written] : []),\n ]);\n const read = new Set([...current.readFiles, ...(additional?.readFiles ?? []), ...(fileOps ? [...fileOps.read] : [])]);\n for (const path of modified) read.delete(path);\n return { readFiles: [...read].sort(), modifiedFiles: [...modified].sort() };\n}\n\nexport function fileDetailsFromUnknown(value: unknown): AutocompactFileDetails | undefined {\n if (!isRecord(value) || !isStringArray(value.readFiles) || !isStringArray(value.modifiedFiles)) return undefined;\n return { readFiles: value.readFiles, modifiedFiles: value.modifiedFiles };\n}\n\nexport function withCanonicalFileSections(summary: string, details: AutocompactFileDetails): string {\n const sections: string[] = [];\n if (details.readFiles.length > 0) sections.push(`<read-files>\\n${details.readFiles.join('\\n')}\\n</read-files>`);\n if (details.modifiedFiles.length > 0) {\n sections.push(`<modified-files>\\n${details.modifiedFiles.join('\\n')}\\n</modified-files>`);\n }\n const normalized = summary.replace(FILE_SECTION_PATTERN, '').trim();\n return sections.length > 0 ? `${normalized}\\n\\n${sections.join('\\n\\n')}` : normalized;\n}\n"],"mappings":"8FA0BA,MAAM,EAAyB,sDACzB,EAAuB,+EAE7B,SAAS,EAAS,EAAkD,CAClE,OAAO,OAAO,GAAU,YAAY,CACtC,CAEA,SAAS,EAAc,EAAmC,CACxD,OAAO,MAAM,QAAQ,CAAK,GAAK,EAAM,MAAO,GAAS,OAAO,GAAS,QAAQ,CAC/E,CAEA,SAAS,EAAO,EAA0C,CACxD,OAAO,IAAU,GAAK,IAAU,GAAK,IAAU,CACjD,CAEA,SAAS,EAAc,EAAyC,CAC1D,KAAM,OAAS,WAAa,EAAM,QAAQ,OAAS,YAMvD,OALa,EAAM,QAAQ,QACxB,OAAQ,GAAU,EAAM,OAAS,MAAM,CAAC,CACxC,IAAK,GAAU,EAAM,IAAI,CAAC,CAC1B,KAAK;CAAI,CAAC,CACV,KACO,GAAK,IAAA,EACjB,CAEA,SAAS,EAAqB,EAA6C,CACzE,OAAO,EAAS,CAAK,GAAK,OAAO,EAAM,MAAS,QAClD,CAEA,SAAgB,EAA0B,EAAuD,CAG/F,GAFI,CAAC,EAAS,CAAK,GAAK,CAAC,EAAc,EAAM,SAAS,GAAK,CAAC,EAAc,EAAM,aAAa,GACzF,CAAC,MAAM,QAAQ,EAAM,gBAAgB,GAAK,CAAC,EAAM,iBAAiB,MAAM,CAAoB,GAC5F,CAAC,EAAS,EAAM,eAAe,EAAG,OACtC,IAAM,EAAS,EAAM,gBAEnB,OAAO,UAAA,GACN,EAAO,OAAS,GAAK,EAAO,OAAS,GACtC,O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AqB,CAAC,EACxB,EAAQ,UAAU,OAAS,GAAG,EAAS,KAAK,iBAAiB,EAAQ,UAAU,KAAK;CAAI,EAAE,gBAAgB,EAC1G,EAAQ,cAAc,OAAS,GACjC,EAAS,KAAK,qBAAqB,EAAQ,cAAc,KAAK;CAAI,EAAE,oBAAoB,EAE1F,IAAM,EAAa,EAAQ,QAAQ,EAAsB,EAAE,CAAC,CAAC,KAAK,EAClE,OAAO,EAAS,OAAS,EAAI,GAAG,EAAW,MAAM,EAAS,KAAK;;CAAM,IAAM,CAC7E"}
@@ -0,0 +1,6 @@
1
+ import { AutocompactPass, AutocompactRatioOverrides } from "../../types/index.cjs";
2
+ import "@earendil-works/pi-coding-agent";
3
+ //#region src/adapters/compaction/policy.d.ts
4
+ export declare function thresholdTokens(pass: AutocompactPass, contextWindow: number, baselineTokens?: number, configured?: AutocompactRatioOverrides): number;
5
+ //#endregion
6
+ //# sourceMappingURL=policy.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"policy.d.cts","names":[],"sources":["../../../src/adapters/compaction/policy.ts"],"mappings":";;;wBAsHgB,gBACd,MAAM,iBACN,uBACA,yBACA,aAAY"}
@@ -0,0 +1,6 @@
1
+ import { AutocompactPass, AutocompactRatioOverrides } from "../../types/index.mjs";
2
+ import "@earendil-works/pi-coding-agent";
3
+ //#region src/adapters/compaction/policy.d.ts
4
+ export declare function thresholdTokens(pass: AutocompactPass, contextWindow: number, baselineTokens?: number, configured?: AutocompactRatioOverrides): number;
5
+ //#endregion
6
+ //# sourceMappingURL=policy.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"policy.d.mts","names":[],"sources":["../../../src/adapters/compaction/policy.ts"],"mappings":";;;wBAsHgB,gBACd,MAAM,iBACN,uBACA,yBACA,aAAY"}
@@ -0,0 +1,8 @@
1
+ import{CHECKPOINT_HEADINGS as e,COMPACTION_THRESHOLDS as t}from"../../types/constants.mjs";import{DEFAULT_COMPACTION_SETTINGS as n,sessionEntryToContextMessages as r}from"@earendil-works/pi-coding-agent";const i=/<shouldCompact>\s*(true|false)\s*<\/shouldCompact>/i,a=/\n*<(?:read-files|modified-files)>[\s\S]*?<\/(?:read-files|modified-files)>/g;function o(e){return typeof e==`object`&&!!e}function s(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function c(e){return e===1||e===2||e===3}function l(e){if(e.type===`message`&&e.message.role===`assistant`)return e.message.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
2
+ `).trim()||void 0}function u(e){return o(e)&&typeof e.role==`string`}function d(e){if(!o(e)||!s(e.readFiles)||!s(e.modifiedFiles)||!Array.isArray(e.retainedMessages)||!e.retainedMessages.every(u)||!o(e.doomAutocompact))return;let t=e.doomAutocompact;if(!(t.version!==2||t.pass!==2&&t.pass!==3||typeof t.cycle!=`number`||typeof t.requestId!=`string`||typeof t.snapshotLeafId!=`string`||typeof t.tokensBefore!=`number`))return{readFiles:[...e.readFiles],modifiedFiles:[...e.modifiedFiles],retainedMessages:[...e.retainedMessages],doomAutocompact:{version:2,cycle:t.cycle,pass:t.pass,requestId:t.requestId,snapshotLeafId:t.snapshotLeafId,tokensBefore:t.tokensBefore}}}function f(){return{version:2,cycle:1,pass:1,phase:`waiting`,checkpointQueue:[],exhaustedPasses:[],invalidAttempts:0,baselineTokens:0,baselinePending:!1,readFiles:[],modifiedFiles:[]}}function p(e={}){let n=0,r={};for(let i of[1,2,3]){let a=Math.max(e[i]??t[i].ratio,n);r[i]=a,n=a}return r}function m(e,r,i=0,a={}){let o=t[e],s=p(a)[e],c=Math.max(0,Math.min(i,r)),l=r-c,u=c+Math.min(Math.floor(l*s),o.capTokens),d=r-n.reserveTokens;return d>c?Math.min(u,d):u}function h(e,t=0,n={},r={}){let i=0,a={};for(let o of[1,2,3]){let s=m(o,e,t,n),c=r[o];a[o]=Math.max(c!==void 0&&c>t?Math.min(s,c):s,i),i=a[o]}return a}function g(e){return e.findLast(e=>e.type===`compaction`||e.type===`custom`&&e.customType===`doom-autocompact-checkpoint`||e.type===`custom_message`&&(e.customType===`doom-autocompact-checkpoint`||e.customType===`doom-autocompact-context`))}function _(e){let t=e.findLastIndex(e=>e.type===`compaction`||e.type===`custom_message`&&e.customType===`doom-autocompact-context`);return e.slice(t+1).some(e=>{if(e.type!==`message`||e.message.role!==`assistant`)return!1;let{stopReason:t,usage:n}=e.message;return t===`aborted`||t===`error`||!n?!1:(n.totalTokens||n.input+n.output+n.cacheRead+n.cacheWrite)>0})}function v(e,t){let n=e.findIndex(e=>e.id===t);return n===-1?[]:e.slice(n+1).filter(e=>e.type!==`custom_message`||e.customType!==`doom-autocompact-checkpoint`).flatMap(e=>r(e))}function y(e,t){let n=t.findLastIndex(e=>e.type===`compaction`),r=t.slice(n+1).findLast(e=>e.type===`custom_message`&&e.customType===`doom-autocompact-context`);if(!r||r.type!==`custom_message`)return{messages:e,retainedMessageCount:0};let i=d(r.details),a=S(r);if(!i||!a)return{messages:e,invalidMarker:!0,retainedMessageCount:0};let o=e.findLastIndex(e=>e.role===`custom`&&e.customType===`doom-autocompact-context`&&d(e.details)?.doomAutocompact.requestId===i.doomAutocompact.requestId);return o===-1?{messages:e,invalidMarker:!0,retainedMessageCount:0}:{messages:[{role:`compactionSummary`,summary:a,tokensBefore:i.doomAutocompact.tokensBefore,timestamp:e[o]?.timestamp??Date.now()},...i.retainedMessages,...e.slice(o+1)],marker:i.doomAutocompact,retainedMessageCount:i.retainedMessages.length}}function b(e){let t={read:new Set,written:new Set,edited:new Set};for(let n of e)if(n.role===`assistant`)for(let e of n.content){if(e.type!==`toolCall`)continue;let n=typeof e.arguments.path==`string`?e.arguments.path:void 0;n&&(e.name===`read`?t.read.add(n):e.name===`write`?t.written.add(n):e.name===`edit`&&t.edited.add(n))}return t}function x(e){if(!o(e)||e.version!==2||typeof e.cycle!=`number`||!c(e.pass)||e.phase!==`waiting`&&e.phase!==`checkpoint_pending`&&e.phase!==`checkpoint_ready`&&e.phase!==`compacting`)return;let t=e.baselineTokens??0;if(typeof t!=`number`||t<0)return;let n=e.baselinePending??!1;if(typeof n!=`boolean`)return;let r=e.checkpointQueue??[];if(!Array.isArray(r)||!r.every(c)||r.some((e,t)=>t>0&&e<=r[t-1]))return;let i=e.exhaustedPasses??[];if(!Array.isArray(i)||!i.every(c))return;let a=e.invalidAttempts??0;if(!(typeof a!=`number`||a<0)&&s(e.readFiles)&&s(e.modifiedFiles)&&(e.requestId===void 0||typeof e.requestId==`string`)&&(e.compactionPass===void 0||e.compactionPass===2||e.compactionPass===3)&&!(`latestCheckpointEntryId`in e)&&(e.latestCheckpointSnapshotLeafId===void 0||typeof e.latestCheckpointSnapshotLeafId==`string`)&&(e.lastAttemptLeafId===void 0||typeof e.lastAttemptLeafId==`string`)&&(e.snapshotLeafId===void 0||typeof e.snapshotLeafId==`string`)&&!(e.snapshotTokens!==void 0&&(typeof e.snapshotTokens!=`number`||e.snapshotTokens<0))&&(e.pendingCheckpoint===void 0||typeof e.pendingCheckpoint==`string`))return{version:2,cycle:e.cycle,pass:e.pass,phase:e.phase,checkpointQueue:[...r],exhaustedPasses:[...i],invalidAttempts:a,baselineTokens:t,baselinePending:n,readFiles:[...e.readFiles],modifiedFiles:[...e.modifiedFiles],...e.requestId?{requestId:e.requestId}:{},...e.compactionPass?{compactionPass:e.compactionPass}:{},...e.latestCheckpointSnapshotLeafId?{latestCheckpointSnapshotLeafId:e.latestCheckpointSnapshotLeafId}:{},...e.lastAttemptLeafId?{lastAttemptLeafId:e.lastAttemptLeafId}:{},...e.snapshotLeafId?{snapshotLeafId:e.snapshotLeafId}:{},...e.snapshotTokens===void 0?{}:{snapshotTokens:e.snapshotTokens},...e.pendingCheckpoint?{pendingCheckpoint:e.pendingCheckpoint}:{}}}function S(e){if(e)return e.type===`compaction`?e.summary.trim()||void 0:e.type===`custom`?o(e.data)&&typeof e.data.summary==`string`&&e.data.summary.trim()||void 0:e.type===`custom_message`?(typeof e.content==`string`?e.content:e.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
3
+ `)).trim()||void 0:l(e)}function C(e){let t=e.match(i),n=e.replace(i,``).trim();return t?{summary:n,shouldCompact:t[1]?.toLowerCase()===`true`}:{summary:n}}function w(t){return e.every(e=>t.includes(e))}function T(e,t,n,r){return`${e}:${t}:${n}:${r??`root`}`}function E(e,t,n){return{version:2,cycle:e,pass:t,requestId:n}}function D(e,t,n){let r=new Set([...e.modifiedFiles,...n?.modifiedFiles??[],...t?[...t.edited,...t.written]:[]]),i=new Set([...e.readFiles,...n?.readFiles??[],...t?[...t.read]:[]]);for(let e of r)i.delete(e);return{readFiles:[...i].sort(),modifiedFiles:[...r].sort()}}function O(e){if(o(e)&&s(e.readFiles)&&s(e.modifiedFiles))return{readFiles:e.readFiles,modifiedFiles:e.modifiedFiles}}function k(e,t){let n=[];t.readFiles.length>0&&n.push(`<read-files>\n${t.readFiles.join(`
4
+ `)}\n</read-files>`),t.modifiedFiles.length>0&&n.push(`<modified-files>\n${t.modifiedFiles.join(`
5
+ `)}\n</modified-files>`);let r=e.replace(a,``).trim();return n.length>0?`${r}\n\n${n.join(`
6
+
7
+ `)}`:r}export{_ as baselineUsageIsSettled,E as checkpointRequestDetails,S as checkpointSummaryFromEntry,p as compactionRatios,d as contextDetailsFromUnknown,f as createInitialState,T as createRequestId,h as effectiveThresholds,O as fileDetailsFromUnknown,b as fileOperationsFromMessages,w as isStructuredCheckpoint,g as latestCheckpointArtifactEntry,D as mergeFileDetails,C as parseCheckpointDecision,x as parseState,y as projectContextMessages,v as retainedMessagesAfterSnapshot,m as thresholdTokens,k as withCanonicalFileSections};
8
+ //# sourceMappingURL=policy.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"policy.mjs","names":[],"sources":["../../../src/adapters/compaction/policy.ts"],"sourcesContent":["import {\n DEFAULT_COMPACTION_SETTINGS,\n type FileOperations,\n type SessionEntry,\n sessionEntryToContextMessages,\n} from '@earendil-works/pi-coding-agent';\nimport {\n CHECKPOINT_HEADINGS,\n CHECKPOINT_MESSAGE_TYPE,\n COMPACTION_THRESHOLDS,\n CONTEXT_MESSAGE_TYPE,\n STATE_VERSION,\n} from '../../types/constants.ts';\nimport type {\n AutocompactContextDetails,\n AutocompactFileDetails,\n AutocompactRatioOverrides,\n AutocompactTokenOverrides,\n AutocompactMessage,\n AutocompactPass,\n AutocompactState,\n CheckpointDecision,\n CheckpointRequestDetails,\n ContextProjection,\n} from '../../types/index.ts';\n\nconst SHOULD_COMPACT_PATTERN = /<shouldCompact>\\s*(true|false)\\s*<\\/shouldCompact>/i;\nconst FILE_SECTION_PATTERN = /\\n*<(?:read-files|modified-files)>[\\s\\S]*?<\\/(?:read-files|modified-files)>/g;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((item) => typeof item === 'string');\n}\n\nfunction isPass(value: unknown): value is AutocompactPass {\n return value === 1 || value === 2 || value === 3;\n}\n\nfunction assistantText(entry: SessionEntry): string | undefined {\n if (entry.type !== 'message' || entry.message.role !== 'assistant') return undefined;\n const text = entry.message.content\n .filter((block) => block.type === 'text')\n .map((block) => block.text)\n .join('\\n')\n .trim();\n return text || undefined;\n}\n\nfunction isAutocompactMessage(value: unknown): value is AutocompactMessage {\n return isRecord(value) && typeof value.role === 'string';\n}\n\nexport function contextDetailsFromUnknown(value: unknown): AutocompactContextDetails | undefined {\n if (!isRecord(value) || !isStringArray(value.readFiles) || !isStringArray(value.modifiedFiles)) return undefined;\n if (!Array.isArray(value.retainedMessages) || !value.retainedMessages.every(isAutocompactMessage)) return undefined;\n if (!isRecord(value.doomAutocompact)) return undefined;\n const marker = value.doomAutocompact;\n if (\n marker.version !== STATE_VERSION ||\n (marker.pass !== 2 && marker.pass !== 3) ||\n typeof marker.cycle !== 'number' ||\n typeof marker.requestId !== 'string' ||\n typeof marker.snapshotLeafId !== 'string' ||\n typeof marker.tokensBefore !== 'number'\n )\n return undefined;\n return {\n readFiles: [...value.readFiles],\n modifiedFiles: [...value.modifiedFiles],\n retainedMessages: [...value.retainedMessages],\n doomAutocompact: {\n version: STATE_VERSION,\n cycle: marker.cycle,\n pass: marker.pass,\n requestId: marker.requestId,\n snapshotLeafId: marker.snapshotLeafId,\n tokensBefore: marker.tokensBefore,\n },\n };\n}\n\nexport function createInitialState(): AutocompactState {\n return {\n version: STATE_VERSION,\n cycle: 1,\n pass: 1,\n phase: 'waiting',\n checkpointQueue: [],\n exhaustedPasses: [],\n invalidAttempts: 0,\n baselineTokens: 0,\n baselinePending: false,\n readFiles: [],\n modifiedFiles: [],\n };\n}\n\n/**\n * The ratios each pass fires at, with configured values folded in.\n *\n * The ladder only works if it climbs, so a configured pass never sits below the\n * one before it: a file that says pass 2 fires earlier than pass 1 gets pass 1's\n * ratio for pass 2 rather than a pass that can never contribute.\n */\nexport function compactionRatios(configured: AutocompactRatioOverrides = {}): Record<AutocompactPass, number> {\n let previous = 0;\n const ratios = {} as Record<AutocompactPass, number>;\n for (const pass of [1, 2, 3] as const) {\n const ratio = Math.max(configured[pass] ?? COMPACTION_THRESHOLDS[pass].ratio, previous);\n ratios[pass] = ratio;\n previous = ratio;\n }\n return ratios;\n}\n\nexport function thresholdTokens(\n pass: AutocompactPass,\n contextWindow: number,\n baselineTokens = 0,\n configured: AutocompactRatioOverrides = {},\n): number {\n const threshold = COMPACTION_THRESHOLDS[pass];\n const ratio = compactionRatios(configured)[pass];\n const baseline = Math.max(0, Math.min(baselineTokens, contextWindow));\n const remaining = contextWindow - baseline;\n const staged = baseline + Math.min(Math.floor(remaining * ratio), threshold.capTokens);\n // Pi compacts natively above `contextWindow - reserveTokens`. A staged threshold above that\n // point can never fire, so the ladder would silently degrade into native compaction: on a\n // 200k window the raw pass 3 ratio lands at 190_000, while Pi already compacted at 183_616.\n const nativeTrigger = contextWindow - DEFAULT_COMPACTION_SETTINGS.reserveTokens;\n return nativeTrigger > baseline ? Math.min(staged, nativeTrigger) : staged;\n}\n\n/**\n * Where every pass fires, with a matching model's absolute token checkpoints folded in.\n *\n * A configured token count replaces the ratio only when it fires earlier, so an\n * override can bring a checkpoint forward on a very large window without ever\n * pushing one past the point Pi compacts natively.\n *\n * Two rules keep the ladder usable. A token count at or below the baseline is\n * ignored, because a compaction that lands above it would otherwise satisfy that\n * pass the moment the next cycle opens and re-fire it every turn. And a pass never\n * sits below the one before it, for the same reason {@link compactionRatios}\n * climbs: `evaluateUsage` skips any pass below the one already reached, so a later\n * pass that fires first does not merely reorder the ladder, it locks the earlier\n * passes out of the cycle and forces compaction with no summary ever written.\n */\nexport function effectiveThresholds(\n contextWindow: number,\n baselineTokens = 0,\n configured: AutocompactRatioOverrides = {},\n tokenOverrides: AutocompactTokenOverrides = {},\n): Record<AutocompactPass, number> {\n let previous = 0;\n const thresholds = {} as Record<AutocompactPass, number>;\n for (const pass of [1, 2, 3] as const) {\n const ratioTokens = thresholdTokens(pass, contextWindow, baselineTokens, configured);\n const absolute = tokenOverrides[pass];\n const staged = absolute !== undefined && absolute > baselineTokens ? Math.min(ratioTokens, absolute) : ratioTokens;\n thresholds[pass] = Math.max(staged, previous);\n previous = thresholds[pass];\n }\n return thresholds;\n}\nexport function latestCheckpointArtifactEntry(branchEntries: SessionEntry[]): SessionEntry | undefined {\n return branchEntries.findLast(\n (entry) =>\n entry.type === 'compaction' ||\n // Staged checkpoints are plain entries so they stay out of the agent's LLM context.\n (entry.type === 'custom' && entry.customType === CHECKPOINT_MESSAGE_TYPE) ||\n // Legacy sessions staged checkpoints as custom messages; committed markers still are.\n (entry.type === 'custom_message' &&\n (entry.customType === CHECKPOINT_MESSAGE_TYPE || entry.customType === CONTEXT_MESSAGE_TYPE)),\n );\n}\n\nexport function baselineUsageIsSettled(branchEntries: SessionEntry[]): boolean {\n const boundaryIndex = branchEntries.findLastIndex(\n (entry) =>\n entry.type === 'compaction' || (entry.type === 'custom_message' && entry.customType === CONTEXT_MESSAGE_TYPE),\n );\n return branchEntries.slice(boundaryIndex + 1).some((entry) => {\n if (entry.type !== 'message' || entry.message.role !== 'assistant') return false;\n const { stopReason, usage } = entry.message;\n if (stopReason === 'aborted' || stopReason === 'error' || !usage) return false;\n return (usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite) > 0;\n });\n}\n\nexport function retainedMessagesAfterSnapshot(\n branchEntries: SessionEntry[],\n snapshotLeafId: string,\n): AutocompactMessage[] {\n const snapshotIndex = branchEntries.findIndex((entry) => entry.id === snapshotLeafId);\n if (snapshotIndex === -1) return [];\n return branchEntries\n .slice(snapshotIndex + 1)\n .filter((entry) => entry.type !== 'custom_message' || entry.customType !== CHECKPOINT_MESSAGE_TYPE)\n .flatMap((entry) => sessionEntryToContextMessages(entry));\n}\n\nexport function projectContextMessages(\n messages: AutocompactMessage[],\n branchEntries: SessionEntry[],\n): ContextProjection {\n const nativeCompactionIndex = branchEntries.findLastIndex((entry) => entry.type === 'compaction');\n const markerEntry = branchEntries\n .slice(nativeCompactionIndex + 1)\n .findLast((entry) => entry.type === 'custom_message' && entry.customType === CONTEXT_MESSAGE_TYPE);\n if (!markerEntry || markerEntry.type !== 'custom_message') {\n return { messages, retainedMessageCount: 0 };\n }\n\n const details = contextDetailsFromUnknown(markerEntry.details);\n const summary = checkpointSummaryFromEntry(markerEntry);\n if (!details || !summary) return { messages, invalidMarker: true, retainedMessageCount: 0 };\n\n const markerMessageIndex = messages.findLastIndex(\n (message) =>\n message.role === 'custom' &&\n message.customType === CONTEXT_MESSAGE_TYPE &&\n contextDetailsFromUnknown(message.details)?.doomAutocompact.requestId === details.doomAutocompact.requestId,\n );\n if (markerMessageIndex === -1) return { messages, invalidMarker: true, retainedMessageCount: 0 };\n\n const summaryMessage: AutocompactMessage = {\n role: 'compactionSummary',\n summary,\n tokensBefore: details.doomAutocompact.tokensBefore,\n timestamp: messages[markerMessageIndex]?.timestamp ?? Date.now(),\n };\n return {\n messages: [summaryMessage, ...details.retainedMessages, ...messages.slice(markerMessageIndex + 1)],\n marker: details.doomAutocompact,\n retainedMessageCount: details.retainedMessages.length,\n };\n}\n\nexport function fileOperationsFromMessages(messages: AutocompactMessage[]): FileOperations {\n const fileOps: FileOperations = { read: new Set(), written: new Set(), edited: new Set() };\n for (const message of messages) {\n if (message.role !== 'assistant') continue;\n for (const block of message.content) {\n if (block.type !== 'toolCall') continue;\n const path = typeof block.arguments.path === 'string' ? block.arguments.path : undefined;\n if (!path) continue;\n if (block.name === 'read') fileOps.read.add(path);\n else if (block.name === 'write') fileOps.written.add(path);\n else if (block.name === 'edit') fileOps.edited.add(path);\n }\n }\n return fileOps;\n}\n\nexport function parseState(value: unknown): AutocompactState | undefined {\n if (!isRecord(value)) return undefined;\n if (value.version !== STATE_VERSION || typeof value.cycle !== 'number' || !isPass(value.pass)) return undefined;\n if (\n value.phase !== 'waiting' &&\n value.phase !== 'checkpoint_pending' &&\n value.phase !== 'checkpoint_ready' &&\n value.phase !== 'compacting'\n )\n return undefined;\n const baselineTokens = value.baselineTokens ?? 0;\n if (typeof baselineTokens !== 'number' || baselineTokens < 0) return undefined;\n const baselinePending = value.baselinePending ?? false;\n if (typeof baselinePending !== 'boolean') return undefined;\n const checkpointQueue = value.checkpointQueue ?? [];\n if (\n !Array.isArray(checkpointQueue) ||\n !checkpointQueue.every(isPass) ||\n checkpointQueue.some((pass, index) => index > 0 && pass <= checkpointQueue[index - 1]!)\n )\n return undefined;\n // Sessions persisted before bounded retry landed simply have no attempt history to restore.\n const exhaustedPasses = value.exhaustedPasses ?? [];\n if (!Array.isArray(exhaustedPasses) || !exhaustedPasses.every(isPass)) return undefined;\n const invalidAttempts = value.invalidAttempts ?? 0;\n if (typeof invalidAttempts !== 'number' || invalidAttempts < 0) return undefined;\n if (!isStringArray(value.readFiles) || !isStringArray(value.modifiedFiles)) return undefined;\n if (value.requestId !== undefined && typeof value.requestId !== 'string') return undefined;\n if (value.compactionPass !== undefined && value.compactionPass !== 2 && value.compactionPass !== 3) return undefined;\n if ('latestCheckpointEntryId' in value) return undefined;\n if (value.latestCheckpointSnapshotLeafId !== undefined && typeof value.latestCheckpointSnapshotLeafId !== 'string')\n return undefined;\n if (value.lastAttemptLeafId !== undefined && typeof value.lastAttemptLeafId !== 'string') return undefined;\n if (value.snapshotLeafId !== undefined && typeof value.snapshotLeafId !== 'string') return undefined;\n if (value.snapshotTokens !== undefined && (typeof value.snapshotTokens !== 'number' || value.snapshotTokens < 0))\n return undefined;\n if (value.pendingCheckpoint !== undefined && typeof value.pendingCheckpoint !== 'string') return undefined;\n\n return {\n version: STATE_VERSION,\n cycle: value.cycle,\n pass: value.pass,\n phase: value.phase,\n checkpointQueue: [...checkpointQueue],\n exhaustedPasses: [...exhaustedPasses],\n invalidAttempts,\n baselineTokens,\n baselinePending,\n readFiles: [...value.readFiles],\n modifiedFiles: [...value.modifiedFiles],\n ...(value.requestId ? { requestId: value.requestId } : {}),\n ...(value.compactionPass ? { compactionPass: value.compactionPass } : {}),\n ...(value.latestCheckpointSnapshotLeafId\n ? { latestCheckpointSnapshotLeafId: value.latestCheckpointSnapshotLeafId }\n : {}),\n ...(value.lastAttemptLeafId ? { lastAttemptLeafId: value.lastAttemptLeafId } : {}),\n ...(value.snapshotLeafId ? { snapshotLeafId: value.snapshotLeafId } : {}),\n ...(value.snapshotTokens !== undefined ? { snapshotTokens: value.snapshotTokens } : {}),\n ...(value.pendingCheckpoint ? { pendingCheckpoint: value.pendingCheckpoint } : {}),\n };\n}\n\nexport function checkpointSummaryFromEntry(entry: SessionEntry | undefined): string | undefined {\n if (!entry) return undefined;\n if (entry.type === 'compaction') return entry.summary.trim() || undefined;\n if (entry.type === 'custom') {\n return isRecord(entry.data) && typeof entry.data.summary === 'string'\n ? entry.data.summary.trim() || undefined\n : undefined;\n }\n if (entry.type === 'custom_message') {\n const content =\n typeof entry.content === 'string'\n ? entry.content\n : entry.content\n .filter((block) => block.type === 'text')\n .map((block) => block.text)\n .join('\\n');\n return content.trim() || undefined;\n }\n return assistantText(entry);\n}\n\nexport function parseCheckpointDecision(response: string): CheckpointDecision {\n const match = response.match(SHOULD_COMPACT_PATTERN);\n const summary = response.replace(SHOULD_COMPACT_PATTERN, '').trim();\n if (!match) return { summary };\n return { summary, shouldCompact: match[1]?.toLowerCase() === 'true' };\n}\n\nexport function isStructuredCheckpoint(summary: string): boolean {\n return CHECKPOINT_HEADINGS.every((heading) => summary.includes(heading));\n}\n\nexport function createRequestId(\n sessionId: string,\n cycle: number,\n pass: AutocompactPass,\n leafId: string | null,\n): string {\n return `${sessionId}:${cycle}:${pass}:${leafId ?? 'root'}`;\n}\n\nexport function checkpointRequestDetails(\n cycle: number,\n pass: AutocompactPass,\n requestId: string,\n): CheckpointRequestDetails {\n return { version: STATE_VERSION, cycle, pass, requestId };\n}\n\nexport function mergeFileDetails(\n current: AutocompactFileDetails,\n fileOps?: FileOperations,\n additional?: AutocompactFileDetails,\n): AutocompactFileDetails {\n const modified = new Set([\n ...current.modifiedFiles,\n ...(additional?.modifiedFiles ?? []),\n ...(fileOps ? [...fileOps.edited, ...fileOps.written] : []),\n ]);\n const read = new Set([...current.readFiles, ...(additional?.readFiles ?? []), ...(fileOps ? [...fileOps.read] : [])]);\n for (const path of modified) read.delete(path);\n return { readFiles: [...read].sort(), modifiedFiles: [...modified].sort() };\n}\n\nexport function fileDetailsFromUnknown(value: unknown): AutocompactFileDetails | undefined {\n if (!isRecord(value) || !isStringArray(value.readFiles) || !isStringArray(value.modifiedFiles)) return undefined;\n return { readFiles: value.readFiles, modifiedFiles: value.modifiedFiles };\n}\n\nexport function withCanonicalFileSections(summary: string, details: AutocompactFileDetails): string {\n const sections: string[] = [];\n if (details.readFiles.length > 0) sections.push(`<read-files>\\n${details.readFiles.join('\\n')}\\n</read-files>`);\n if (details.modifiedFiles.length > 0) {\n sections.push(`<modified-files>\\n${details.modifiedFiles.join('\\n')}\\n</modified-files>`);\n }\n const normalized = summary.replace(FILE_SECTION_PATTERN, '').trim();\n return sections.length > 0 ? `${normalized}\\n\\n${sections.join('\\n\\n')}` : normalized;\n}\n"],"mappings":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.cjs"),t=require("../compaction/policy.cjs"),n=require("../compaction/modelOverrides.cjs"),r=require("../../services/summarizationModel.cjs"),i=require("../telemetry/logSinkTelemetry.cjs");let a=require("@agimon-ai/doompi-config"),o=require("@agimon-ai/doompi-extension-contracts/cordis-host"),s=require("@agimon-ai/doompi-extension-contracts/context-contributions"),c=require("@agimon-ai/doompi-extension-contracts/ui-hub"),l=require("@earendil-works/pi-coding-agent");const u=`@root`,d=`doom-autocompact`,f={waiting:`waiting`,checkpointPending:`checkpoint_pending`,checkpointReady:`checkpoint_ready`,compacting:`compacting`};function p(e,t={}){return{"pi.session.id":e.sessionManager.getSessionId(),...t}}function m(e){for(let n=e.length-1;n>=0;--n){let r=e[n];if(r?.type!==`custom`||r.customType!==`doom-autocompact-state`)continue;let i=t.parseState(r.data);if(i)return i}}function h(e){for(let t of e.sessionManager.getBranch().toReversed())if((t.type!==`custom`||t.customType!==`doom-autocompact-state`)&&t.type!==`label`)return t.id;return u}function g(e){return e instanceof Error?e.message:String(e)}function _(e){for(let t of e.toReversed()){if(t.type!==`custom`||t.customType!==`agent-harness-plan-document`)continue;if(!t.data||typeof t.data!=`object`)return;let e=t.data;return typeof e.content!=`string`||typeof e.path!=`string`?void 0:{content:e.content,path:e.path}}}const v=Object.freeze({entries:Object.freeze([]),errors:Object.freeze([])});function y(e){if(!e)return v;try{return e.snapshot()}catch(e){return{entries:[],errors:[{source:s.DOOM_CONTEXT_CONTRIBUTIONS_SERVICE,id:`service-snapshot`,label:`Context contributions`,order:0,message:g(e)}]}}}function b(e){let t=e.entries.map(e=>`### ${e.label}\n${e.text}`);return t.push(...e.errors.map(e=>`### ${e.label}\n(unavailable: ${e.message})`)),t.length>0?t.join(`
2
+
3
+ `):`(no registered context contributions)`}function x(e,t){let n=_(e);return{...n?{planPath:n.path}:{},contributions:t.entries,contributionErrors:t.errors}}function S(e){return`<compaction-runtime-state>
4
+ Authoritative runtime state captured when compaction committed. Use it to resume coordination without reconstructing state from the summary.
5
+ <active-plan>
6
+ ${e.planPath?`Source: ${e.planPath}\nExact plan content is restored separately by Doom Plan.`:`(no active plan document)`}
7
+ </active-plan>
8
+ <context-contributions>
9
+ ${b({entries:e.contributions,errors:e.contributionErrors})}
10
+ </context-contributions>
11
+ </compaction-runtime-state>`}function C(e){return{"autocompact.runtime.plan_present":!!e.planPath,"autocompact.runtime.contribution_count":e.contributions.length,"autocompact.runtime.contribution_error_count":e.contributionErrors.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,context-contributions,important-context,recent-messages">
12
+ <user-prompt source="conversation">
13
+ Treat the user's explicit goals, constraints, corrections, and preferences in the conversation as authoritative. Newer user instructions override older ones.
14
+ </user-prompt>
15
+ <active-plan>
16
+ ${t}
17
+ </active-plan>
18
+ <context-contributions>
19
+ ${b(e.contextContributions)}
20
+ </context-contributions>
21
+ <important-context>
22
+ ${n.length>0?n.join(`
23
+ `):`(none recorded outside the conversation)`}
24
+ </important-context>
25
+ </compaction-steering>`}function T(e,t){let n=e===2?`Start with exactly <shouldCompact>true</shouldCompact> or <shouldCompact>false</shouldCompact>. Use true when the staged summary safely retains the important parent context. Use false only when it is not yet sufficient for safe compaction.
26
+
27
+ `:``;return`Create Doom autocompact checkpoint pass ${e}.
28
+
29
+ ${w(t)}
30
+
31
+ Apply the steering evidence in priority order. Do not invent plan or contributed runtime state. Preserve verified facts and mark unresolved inference explicitly. Newer evidence replaces superseded information.
32
+
33
+ ${n}Return only the decision tag when required, followed by a concise structured checkpoint using every heading below. Keep exact goals, constraints, decisions, blockers, commands, errors, file paths, validation evidence, and the immediate next action. Separate verified facts from unresolved inference.
34
+
35
+ ## Goal
36
+ ## Constraints & Preferences
37
+ ## Progress
38
+ ### Done
39
+ ### In Progress
40
+ ### Blocked
41
+ ## Key Decisions
42
+ ## Next Steps
43
+ ## Critical Context`}function E(e,n,r){let i=t.projectContextMessages((0,l.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,l.sessionEntryToContextMessages)(e))}const D={enabled:!0,ratios:{},overrides:[]};function O(e,t){let n;try{n=(0,a.loadDoomConfig)((0,a.getHarnessState)().root??e).modes}catch(e){return process.emitWarning(`Doom autocompact configuration could not be loaded; using the active session model instead.`),t?.(e),D}let r=n?.autocompact,i=(r&&(r.model!==void 0||r.thinking!==void 0)?{...r.model?{model:r.model}:{},...r.thinking?{thinking:r.thinking}:{}}:void 0)??n?.planning?.subagents,o=r?.thresholds;return{enabled:r?.enabled??!0,...i?{agent:i}:{},ratios:{...o?.pass1===void 0?{}:{1:o.pass1},...o?.pass2===void 0?{}:{2:o.pass2},...o?.pass3===void 0?{}:{3:o.pass3}},overrides:r?.overrides??[]}}function k(e){let t=O(e.cwd).agent,n=t?.model?r.parseModelReference(t.model):void 0,i=n?e.modelRegistry.find(n.provider,n.modelId):void 0,a=i??e.model;if(!a)return;let o=t?.thinking??(i?n?.thinking:void 0)??e.thinkingLevel;return{model:a,...o?{thinkingLevel:o}:{}}}async function A(e,t){let n=t(e.context);if(!n)throw Error(`No active model is available for autocompact summarization.`);let r=await e.context.modelRegistry.getApiKeyAndHeaders(n.model);if(!r.ok)throw Error(r.error);let i=e.context.modelRegistry.getProvider(n.model.provider);if(!i)throw Error(`No provider is registered for "${n.model.provider}" in this session.`);return(0,l.generateSummary)(e.messages,n.model,l.DEFAULT_COMPACTION_SETTINGS.reserveTokens,r.apiKey,r.headers,e.signal,e.instructions,e.previousCheckpoint,n.thinkingLevel,(e,t,n)=>i.streamSimple(e,t,n),r.env)}function j(e,t,n=`info`){e?.hasUI&&e.ui.notify(t,n)}function M(r,a,o={}){let g=o.resolveModel??k,v=o.generateCheckpoint??(e=>A(e,g)),b=o.telemetry??i.createAutocompactTelemetry(),w=o.doomIntegrations??!0,D=new Set,M=new Set,N=new Set,P=!0,F=0,I=t.createInitialState(),L,R,z,B,V=!1;r.effect(()=>async()=>{P=!1,F+=1,R?.abort(Error(`Autocompact runtime is shutting down.`)),R=void 0,await Promise.allSettled(N),z=void 0,B=void 0,L=void 0,D.clear(),M.clear(),I=t.createInitialState(),V=!1,await b.shutdown()},`${d}/runtime`),r.inject([s.DOOM_CONTEXT_CONTRIBUTIONS_SERVICE],e=>{let t=(0,s.requireDoomContextContributions)(e);return B=t,()=>{B===t&&(B=void 0)}}),w&&r.inject([c.DOOM_UI_HUB_SERVICE],e=>{let t=(0,c.requireDoomUiHub)(e).registerFooter({source:d,id:`autocompact`,order:20});return z=t,()=>{t.dispose(),z===t&&(z=void 0)}});let H=e=>{if(!P)return;let t=I.phase===f.checkpointPending?`summarizing`:I.phase===f.checkpointReady?`applying`:void 0;z?.update(t?{fullText:`Compacting p${I.pass}`,compactText:`C${I.pass}`}:void 0);let n=e??L;n?.hasUI&&n.ui.setStatus(`doom-autocompact`,t?`Compacting pass ${I.pass} (${t})…`:void 0)},U=()=>{P&&(a.appendEntry(e.STATE_CUSTOM_TYPE,{...I}),H())},W=()=>{delete I.requestId,delete I.snapshotLeafId,delete I.snapshotTokens,delete I.pendingCheckpoint,delete I.compactionPass},G=e=>{I.checkpointQueue=I.checkpointQueue.filter(t=>t!==e)},ee=e=>{P&&(I=m(e.sessionManager.getBranch())??t.createInitialState(),!(I.phase===f.checkpointReady&&I.requestId&&I.snapshotLeafId&&I.pendingCheckpoint||I.phase===f.waiting)&&(R?.abort(),R=void 0,I.phase=f.waiting,W(),U()))},te=t=>{P&&a.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:I.cycle,pass:I.pass}},{triggerTurn:!0,deliverAs:`steer`})},K=(e,t)=>{let n=I.invalidAttempts+1,r=n>=3;return I.phase=f.waiting,t&&(I.lastAttemptLeafId=t),r?(G(e),I.exhaustedPasses=[...I.exhaustedPasses,e],I.invalidAttempts=0):I.invalidAttempts=n,W(),U(),{attempts:n,exhausted:r}},ne=(e,t)=>{if(!P||e!==I.requestId||I.phase!==f.checkpointPending)return;let n=I.pass,{attempts:r,exhausted:i}=K(n,I.snapshotLeafId),a=t instanceof Error?t.message:String(t);j(L,i?`Doom autocompact summarization pass ${n} failed ${r} times and was abandoned: ${a}`:`Doom autocompact summarization pass ${n} failed: ${a}`,`error`)},re=(e,t)=>{P&&!V&&(V=!0,b.recordWarning(i.AUTOCOMPACT_EVENT.configurationLoadFailed,t,p(e,{"autocompact.cycle":I.cycle,"autocompact.pass":I.pass})))},q=(e,t,n)=>{if(P)for(let r of t.errors)j(e,`Doom autocompact context contribution degraded (${r.source}/${r.id}): ${r.message}`,`warning`),b.recordWarning(i.AUTOCOMPACT_EVENT.contextContributionDegraded,Error(r.message),{...n,"autocompact.context_contribution.source":r.source,"autocompact.context_contribution.id":r.id,"autocompact.context_contribution.order":r.order})},J=(t,n,r)=>{if(!P)return{contributions:[],contributionErrors:[]};let i=y(B);q(t,i,r);let o=x(n,i);return a.sendMessage({customType:e.RUNTIME_STATE_MESSAGE_TYPE,content:S(o),display:!1,details:{version:2,...o}}),o},ie=(n,r)=>{if(!P||!I.requestId||!I.snapshotLeafId||!I.pendingCheckpoint)return!1;let o=r.sessionManager.getBranch(),s=t.projectContextMessages((0,l.buildSessionContext)(o).messages,o).messages,c=t.mergeFileDetails(I,t.fileOperationsFromMessages(s)),u=I.requestId,d=I.cycle,m=t.withCanonicalFileSections(I.pendingCheckpoint,c),g={...c,doomAutocompact:{version:2,cycle:d,pass:n,requestId:u,snapshotLeafId:I.snapshotLeafId,tokensBefore:I.snapshotTokens??r.getContextUsage()?.tokens??0},retainedMessages:t.retainedMessagesAfterSnapshot(o,I.snapshotLeafId)},_=r.isIdle();a.sendMessage({customType:e.CONTEXT_MESSAGE_TYPE,content:m,display:!1,details:g});let v=h(r),y=p(r,{"autocompact.request.id":u,"autocompact.cycle":d,"autocompact.pass":n}),x=J(r,o,y);return _&&a.setLabel(v,`autocompact:c${d}:p${n}`),I.readFiles=c.readFiles,I.modifiedFiles=c.modifiedFiles,delete I.latestCheckpointSnapshotLeafId,I.phase=f.waiting,I.checkpointQueue=[],I.exhaustedPasses=[],I.invalidAttempts=0,I.baselinePending=!0,delete I.lastAttemptLeafId,W(),I.cycle+=1,I.pass=1,U(),b.recordEvent(i.AUTOCOMPACT_EVENT.contextCommitted,p(r,{"autocompact.request.id":u,"autocompact.cycle":d,"autocompact.pass":n,"autocompact.snapshot_leaf_id":g.doomAutocompact.snapshotLeafId,"autocompact.tokens_before":g.doomAutocompact.tokensBefore,"autocompact.message_count.before":s.length,"autocompact.message_count.retained":g.retainedMessages.length,"autocompact.apply_mode":_?`idle`:`turn_end`,...C(x)})),_&&te(`Asynchronous compaction completed.`),!0},ae=(e,n,r)=>{if(!P)return;let a=F,o=n.sessionManager.getBranch(),s=h(n),c=t.createRequestId(n.sessionManager.getSessionId(),I.cycle,e,s),l=e>1?t.checkpointSummaryFromEntry(t.latestCheckpointArtifactEntry(o)):void 0,u=E(e,o,I.latestCheckpointSnapshotLeafId),d=y(B),m=p(n,{"autocompact.request.id":c,"autocompact.cycle":I.cycle,"autocompact.pass":e,"autocompact.snapshot_leaf_id":s,"autocompact.tokens_before":r,"autocompact.message_count.before":u.length});q(n,d,m),I.phase=f.checkpointPending,I.pass=e,I.requestId=c,I.snapshotLeafId=s,I.snapshotTokens=r,delete I.pendingCheckpoint,delete I.compactionPass,delete I.lastAttemptLeafId,U(),R?.abort(),R=new AbortController;let g=R.signal,x=b.runInSpan(`doom_autocompact.checkpoint`,m,async()=>{await b.recordEvent(i.AUTOCOMPACT_EVENT.checkpointStarted,m);try{let t=await v({messages:u,instructions:T(e,{plan:_(o),contextContributions:d,readFiles:I.readFiles,modifiedFiles:I.modifiedFiles}),...l?{previousCheckpoint:l}:{},context:n,signal:g});if(!P||a!==F)throw g.reason??Error(`Autocompact checkpoint became stale.`);if(!t.trim())throw Error(`Summarization returned an empty checkpoint.`);return await b.recordEvent(i.AUTOCOMPACT_EVENT.checkpointCompleted,{...m,"autocompact.checkpoint.characters":t.length}),t}catch(e){throw P&&a===F&&await b.recordError(i.AUTOCOMPACT_EVENT.checkpointFailed,e,m),e}}).then(e=>{P&&a===F&&c===I.requestId&&I.phase===f.checkpointPending&&(I.phase=f.checkpointReady,I.pendingCheckpoint=e.trim(),U(),L&&Q(L))}).catch(e=>{P&&a===F&&ne(c,e)});N.add(x),x.finally(()=>N.delete(x))},Y=e=>{if(!P||I.phase!==f.waiting||e.hasPendingMessages())return!1;let r=O(e.cwd,t=>re(e,t));if(!r.enabled)return!1;let i=e.getContextUsage();if(!i||i.tokens===null)return!1;if(I.baselinePending)return t.baselineUsageIsSettled(e.sessionManager.getBranch())?(I.baselineTokens=i.tokens,I.baselinePending=!1,U(),!1):!1;let a=h(e);if(I.lastAttemptLeafId===a)return!1;let o=n.resolveModelTokenOverrides(e.model,r.overrides),s=t.effectiveThresholds(i.contextWindow,I.baselineTokens,r.ratios,o);for(let e of[1,2,3])e<I.pass||I.checkpointQueue.includes(e)||I.exhaustedPasses.includes(e)||i.tokens>=s[e]&&I.checkpointQueue.push(e);let c=I.checkpointQueue[0];return c?(ae(c,e,i.tokens),!0):!1},X=(n,r)=>{if(!P)return;let i=I.snapshotLeafId;a.appendEntry(e.CHECKPOINT_MESSAGE_TYPE,{...t.checkpointRequestDetails(I.cycle,n,I.requestId??`completed`),summary:r}),i&&(I.latestCheckpointSnapshotLeafId=i)},Z=e=>{if(!P||I.phase!==f.checkpointReady||!I.requestId||!I.pendingCheckpoint)return`none`;let n=I.pass,r=t.parseCheckpointDecision(I.pendingCheckpoint);if(!t.isStructuredCheckpoint(r.summary)){let t=I.snapshotLeafId,r=I.requestId,{attempts:a,exhausted:o}=K(n,t),s=Error(`Summarization pass ${n} returned an incomplete checkpoint.`);return j(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`),b.recordError(i.AUTOCOMPACT_EVENT.checkpointInvalid,s,p(e,{"autocompact.cycle":I.cycle,"autocompact.pass":n,"autocompact.checkpoint.attempts":a,"autocompact.checkpoint.exhausted":o,...r?{"autocompact.request.id":r}:{}})),`invalid`}return I.invalidAttempts=0,n===1?(X(1,r.summary),G(1),I.phase=f.waiting,I.pass=2,W(),U(),`pass1`):n===2&&r.shouldCompact!==!0?(X(2,r.summary),G(2),I.phase=f.waiting,I.pass=3,W(),U(),`deferred`):(I.pendingCheckpoint=r.summary,ie(n,e)?`committed`:`invalid`)};function Q(e){P&&(L=e,e.isIdle()&&Z(e)!==`committed`&&Y(e))}a.on(`context`,(e,n)=>{if(!P)return;let r=t.projectContextMessages(e.messages,n.sessionManager.getBranch());if(r.invalidMarker){let e=n.sessionManager.getLeafId()??u;M.has(e)||(M.add(e),b.recordError(i.AUTOCOMPACT_EVENT.contextMarkerInvalid,Error(`Doom autocompact context marker is malformed.`),p(n,{"autocompact.leaf_id":e})));return}if(r.marker)return D.has(r.marker.requestId)||(D.add(r.marker.requestId),b.recordEvent(i.AUTOCOMPACT_EVENT.contextApplied,p(n,{"autocompact.request.id":r.marker.requestId,"autocompact.cycle":r.marker.cycle,"autocompact.pass":r.marker.pass,"autocompact.snapshot_leaf_id":r.marker.snapshotLeafId,"autocompact.tokens_before":r.marker.tokensBefore,"autocompact.message_count.before":e.messages.length,"autocompact.message_count.after":r.messages.length,"autocompact.message_count.retained":r.retainedMessageCount}))),{messages:r.messages}});let $=e=>{P&&(F+=1,R?.abort(Error(`Autocompact session generation was replaced.`)),R=void 0,D.clear(),M.clear(),L=e,ee(e),Q(e))};a.on(`session_start`,(e,t)=>$(t)),a.on(`session_tree`,(e,t)=>$(t)),a.on(`turn_end`,(e,t)=>{if(P){if(L=t,t.isIdle()){Q(t);return}I.phase===f.checkpointReady&&(e.toolResults?.length??0)>0&&!t.hasPendingMessages()&&Z(t)!==`none`||Y(t)}}),a.on(`agent_settled`,(e,t)=>{P&&Q(t)}),a.on(`session_before_compact`,e=>{if(P&&e.reason===`threshold`)return I.phase===f.checkpointPending||I.phase===f.checkpointReady||I.baselinePending?{cancel:!0}:void 0}),a.on(`session_compact`,(e,n)=>{if(!P)return;F+=1,R?.abort(),R=void 0;let r=t.fileDetailsFromUnknown(e.compactionEntry.details),o=t.mergeFileDetails(I,void 0,r);I.readFiles=o.readFiles,I.modifiedFiles=o.modifiedFiles,delete I.latestCheckpointSnapshotLeafId,I.baselinePending=!0,I.phase=f.waiting,W(),I.checkpointQueue=[],I.exhaustedPasses=[],I.invalidAttempts=0,delete I.lastAttemptLeafId,a.setLabel(e.compactionEntry.id,`autocompact:c${I.cycle}:external`);let s=I.cycle,c=p(n,{"autocompact.cycle":s,"autocompact.native.reason":e.reason}),l=J(n,n.sessionManager.getBranch(),c);I.cycle+=1,I.pass=1,U(),b.recordEvent(i.AUTOCOMPACT_EVENT.nativeCompactionCompleted,p(n,{"autocompact.cycle":s,"autocompact.native.reason":e.reason,"autocompact.native.from_extension":e.fromExtension,"autocompact.tokens_before":e.compactionEntry.tokensBefore,...C(l)}))})}async function N(e){let t=await(0,o.connectDoomCordisHost)(e,`@agimon-ai/doompi-autocompact`),n=t.root.plugin(P,{pi:e});try{await n}catch(e){try{await n.dispose()}finally{await t.dispose()}throw e}let r;e.on(`session_shutdown`,()=>r??=(async()=>{try{await n.dispose()}finally{await t.dispose()}})())}function P(e,t){M(e,t.pi)}exports.autocompactExtension=N,exports.default=N,exports.autocompactRuntimeConfig=O,exports.generateCheckpointWithPi=A,exports.installAutocompactRuntime=M,exports.resolveDoomSummarizationModel=k;
44
+ //# sourceMappingURL=extension.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"extension.cjs","names":["parseState","DOOM_CONTEXT_CONTRIBUTIONS_SERVICE","projectContextMessages","buildSessionContext","sessionEntryToContextMessages","loadDoomConfig","getHarnessState","parseModelReference","generateSummary","DEFAULT_COMPACTION_SETTINGS","createAutocompactTelemetry","createInitialState","requireDoomContextContributions","DOOM_UI_HUB_SERVICE","requireDoomUiHub","STATE_CUSTOM_TYPE","RESUME_MESSAGE_TYPE","AUTOCOMPACT_EVENT","RUNTIME_STATE_MESSAGE_TYPE","mergeFileDetails","fileOperationsFromMessages","withCanonicalFileSections","retainedMessagesAfterSnapshot","CONTEXT_MESSAGE_TYPE","createRequestId","checkpointSummaryFromEntry","latestCheckpointArtifactEntry","baselineUsageIsSettled","resolveModelTokenOverrides","effectiveThresholds","CHECKPOINT_MESSAGE_TYPE","checkpointRequestDetails","parseCheckpointDecision","isStructuredCheckpoint","fileDetailsFromUnknown","connectDoomCordisHost"],"sources":["../../../src/adapters/pi/extension.ts"],"sourcesContent":["import {\n getHarnessState,\n loadDoomConfig,\n type AutocompactOverrideConfig,\n type PlanningAgentConfig,\n} from '@agimon-ai/doompi-config';\nimport { connectDoomCordisHost } from '@agimon-ai/doompi-extension-contracts/cordis-host';\nimport {\n DOOM_CONTEXT_CONTRIBUTIONS_SERVICE,\n requireDoomContextContributions,\n type DoomContextContributionEntry,\n type DoomContextContributionError,\n type DoomContextContributionsService,\n type DoomContextContributionsSnapshot,\n} from '@agimon-ai/doompi-extension-contracts/context-contributions';\nimport type { DoomFooterContributionHandle } from '@agimon-ai/doompi-extension-contracts/footer';\nimport { DOOM_UI_HUB_SERVICE, requireDoomUiHub } from '@agimon-ai/doompi-extension-contracts/ui-hub';\nimport type { Context } from '@deepseek-ai/cordis';\nimport type { ExtensionAPI, ExtensionContext, SessionEntry } from '@earendil-works/pi-coding-agent';\nimport {\n buildSessionContext,\n DEFAULT_COMPACTION_SETTINGS,\n generateSummary,\n sessionEntryToContextMessages,\n} from '@earendil-works/pi-coding-agent';\nimport {\n baselineUsageIsSettled,\n checkpointRequestDetails,\n checkpointSummaryFromEntry,\n createInitialState,\n createRequestId,\n fileDetailsFromUnknown,\n fileOperationsFromMessages,\n isStructuredCheckpoint,\n latestCheckpointArtifactEntry,\n mergeFileDetails,\n parseCheckpointDecision,\n parseState,\n projectContextMessages,\n retainedMessagesAfterSnapshot,\n effectiveThresholds,\n withCanonicalFileSections,\n} from '../../adapters/compaction/policy';\nimport { resolveModelTokenOverrides } from '../../adapters/compaction/modelOverrides.ts';\nimport { parseModelReference, type SummarizationModel } from '../../services/summarizationModel.ts';\nimport {\n CHECKPOINT_MESSAGE_TYPE,\n CONTEXT_MESSAGE_TYPE,\n MAX_INVALID_CHECKPOINT_ATTEMPTS,\n RESUME_MESSAGE_TYPE,\n RUNTIME_STATE_MESSAGE_TYPE,\n STATE_CUSTOM_TYPE,\n STATE_VERSION,\n} from '../../types/constants.ts';\nimport type { AutocompactEventAttributes, AutocompactTelemetry } from '../telemetry/logSinkTelemetry.ts';\nimport { AUTOCOMPACT_EVENT, createAutocompactTelemetry } from '../telemetry/logSinkTelemetry.ts';\n\nexport type { ModelReference, SummarizationModel } from '../../services/summarizationModel.ts';\nexport { parseModelReference, resolveSummarizationModel } from '../../services/summarizationModel.ts';\n\nimport type {\n AutocompactContextDetails,\n AutocompactPass,\n AutocompactRatioOverrides,\n AutocompactState,\n} from '../../types/index.ts';\n\nconst ROOT_WORKING_LEAF = '@root';\nconst PACKAGE_SOURCE = '@agimon-ai/doompi-autocompact';\nconst PLAN_DOCUMENT_ENTRY = 'agent-harness-plan-document';\nconst FOOTER_SOURCE = 'doom-autocompact';\nconst FOOTER_ORDER = 20;\nconst STATUS_KEY = 'doom-autocompact';\nconst STATE_PHASE = {\n waiting: 'waiting',\n checkpointPending: 'checkpoint_pending',\n checkpointReady: 'checkpoint_ready',\n compacting: 'compacting',\n} as const;\ntype CheckpointCapture = 'none' | 'pass1' | 'committed' | 'deferred' | 'invalid';\ntype CheckpointMessages = ReturnType<typeof buildSessionContext>['messages'];\n\ninterface PlanSnapshot {\n content: string;\n path: string;\n}\n\ninterface SteeringSnapshot {\n plan?: PlanSnapshot;\n contextContributions: DoomContextContributionsSnapshot;\n readFiles: string[];\n modifiedFiles: string[];\n}\n\ninterface RuntimeStateSnapshot {\n planPath?: string;\n contributions: readonly DoomContextContributionEntry[];\n contributionErrors: readonly DoomContextContributionError[];\n}\n\ninterface CheckpointGenerationInput {\n messages: CheckpointMessages;\n instructions: string;\n previousCheckpoint?: string;\n context: ExtensionContext;\n signal: AbortSignal;\n}\n\nexport interface AutocompactDependencies {\n generateCheckpoint?: (input: CheckpointGenerationInput) => Promise<string>;\n resolveModel?: (context: ExtensionContext) => SummarizationModel | undefined;\n telemetry?: AutocompactTelemetry;\n doomIntegrations?: boolean;\n}\n\nfunction telemetryAttributes(\n context: ExtensionContext,\n attributes: AutocompactEventAttributes = {},\n): AutocompactEventAttributes {\n return {\n 'pi.session.id': context.sessionManager.getSessionId(),\n ...attributes,\n };\n}\n\nfunction latestPersistedState(branch: SessionEntry[]): AutocompactState | undefined {\n for (let index = branch.length - 1; index >= 0; index -= 1) {\n const entry = branch[index];\n if (entry?.type !== 'custom' || entry.customType !== STATE_CUSTOM_TYPE) continue;\n const parsed = parseState(entry.data);\n if (parsed) return parsed;\n }\n return undefined;\n}\n\nfunction workingLeafId(ctx: ExtensionContext): string {\n for (const entry of ctx.sessionManager.getBranch().toReversed()) {\n if (entry.type === 'custom' && entry.customType === STATE_CUSTOM_TYPE) continue;\n if (entry.type === 'label') continue;\n return entry.id;\n }\n return ROOT_WORKING_LEAF;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction latestPlanSnapshot(branch: SessionEntry[]): PlanSnapshot | undefined {\n for (const entry of branch.toReversed()) {\n if (entry.type !== 'custom' || entry.customType !== PLAN_DOCUMENT_ENTRY) continue;\n if (!entry.data || typeof entry.data !== 'object') return undefined;\n const data = entry.data as Record<string, unknown>;\n if (typeof data.content !== 'string' || typeof data.path !== 'string') return undefined;\n return { content: data.content, path: data.path };\n }\n return undefined;\n}\n\nconst EMPTY_CONTEXT_CONTRIBUTIONS: DoomContextContributionsSnapshot = Object.freeze({\n entries: Object.freeze([]),\n errors: Object.freeze([]),\n});\n\nfunction readContextContributionsSnapshot(\n service: DoomContextContributionsService | undefined,\n): DoomContextContributionsSnapshot {\n if (!service) return EMPTY_CONTEXT_CONTRIBUTIONS;\n try {\n return service.snapshot();\n } catch (error) {\n return {\n entries: [],\n errors: [\n {\n source: DOOM_CONTEXT_CONTRIBUTIONS_SERVICE,\n id: 'service-snapshot',\n label: 'Context contributions',\n order: 0,\n message: errorMessage(error),\n },\n ],\n };\n }\n}\n\nfunction formatContextContributions(snapshot: DoomContextContributionsSnapshot): string {\n const sections = snapshot.entries.map((entry) => `### ${entry.label}\\n${entry.text}`);\n sections.push(...snapshot.errors.map((error) => `### ${error.label}\\n(unavailable: ${error.message})`));\n return sections.length > 0 ? sections.join('\\n\\n') : '(no registered context contributions)';\n}\n\nfunction runtimeStateSnapshot(\n branch: SessionEntry[],\n contextContributions: DoomContextContributionsSnapshot,\n): RuntimeStateSnapshot {\n const plan = latestPlanSnapshot(branch);\n return {\n ...(plan ? { planPath: plan.path } : {}),\n contributions: contextContributions.entries,\n contributionErrors: contextContributions.errors,\n };\n}\n\nfunction formatRuntimeState(snapshot: RuntimeStateSnapshot): string {\n const plan = snapshot.planPath\n ? `Source: ${snapshot.planPath}\\nExact plan content is restored separately by Doom Plan.`\n : '(no active plan document)';\n return `<compaction-runtime-state>\nAuthoritative runtime state captured when compaction committed. Use it to resume coordination without reconstructing state from the summary.\n<active-plan>\n${plan}\n</active-plan>\n<context-contributions>\n${formatContextContributions({ entries: snapshot.contributions, errors: snapshot.contributionErrors })}\n</context-contributions>\n</compaction-runtime-state>`;\n}\n\nfunction runtimeTelemetryAttributes(snapshot: RuntimeStateSnapshot): AutocompactEventAttributes {\n return {\n 'autocompact.runtime.plan_present': Boolean(snapshot.planPath),\n 'autocompact.runtime.contribution_count': snapshot.contributions.length,\n 'autocompact.runtime.contribution_error_count': snapshot.contributionErrors.length,\n };\n}\n\nfunction steeringEnvelope(snapshot: SteeringSnapshot): string {\n const plan = snapshot.plan\n ? `Source: ${snapshot.plan.path}\\n\\n${snapshot.plan.content}`\n : '(no active plan document)';\n const importantContext = [\n snapshot.readFiles.length > 0 ? `Read files: ${snapshot.readFiles.join(', ')}` : undefined,\n snapshot.modifiedFiles.length > 0 ? `Modified files: ${snapshot.modifiedFiles.join(', ')}` : undefined,\n ].filter((value): value is string => Boolean(value));\n\n return `<compaction-steering priority=\"user,plan,context-contributions,important-context,recent-messages\">\n<user-prompt source=\"conversation\">\nTreat the user's explicit goals, constraints, corrections, and preferences in the conversation as authoritative. Newer user instructions override older ones.\n</user-prompt>\n<active-plan>\n${plan}\n</active-plan>\n<context-contributions>\n${formatContextContributions(snapshot.contextContributions)}\n</context-contributions>\n<important-context>\n${importantContext.length > 0 ? importantContext.join('\\n') : '(none recorded outside the conversation)'}\n</important-context>\n</compaction-steering>`;\n}\n\nfunction checkpointInstructions(pass: AutocompactPass, steering: SteeringSnapshot): string {\n const decision =\n pass === 2\n ? 'Start with exactly <shouldCompact>true</shouldCompact> or <shouldCompact>false</shouldCompact>. Use true when the staged summary safely retains the important parent context. Use false only when it is not yet sufficient for safe compaction.\\n\\n'\n : '';\n\n // Summarization is a tool-less single LLM call, so instructions describe only what to\n // produce. Directives aimed at an implementing agent leak into the checkpoint body.\n return `Create Doom autocompact checkpoint pass ${pass}.\n\n${steeringEnvelope(steering)}\n\nApply the steering evidence in priority order. Do not invent plan or contributed runtime state. Preserve verified facts and mark unresolved inference explicitly. Newer evidence replaces superseded information.\n\n${decision}Return only the decision tag when required, followed by a concise structured checkpoint using every heading below. Keep exact goals, constraints, decisions, blockers, commands, errors, file paths, validation evidence, and the immediate next action. Separate verified facts from unresolved inference.\n\n## Goal\n## Constraints & Preferences\n## Progress\n### Done\n### In Progress\n### Blocked\n## Key Decisions\n## Next Steps\n## Critical Context`;\n}\n\nfunction messagesForCheckpoint(\n pass: AutocompactPass,\n branch: SessionEntry[],\n previousSnapshotLeafId: string | undefined,\n): CheckpointMessages {\n const projected = projectContextMessages(buildSessionContext(branch).messages, branch).messages;\n if (pass === 1 || !previousSnapshotLeafId) return projected;\n const snapshotIndex = branch.findIndex((entry) => entry.id === previousSnapshotLeafId);\n if (snapshotIndex === -1) return projected;\n return branch\n .slice(snapshotIndex + 1)\n .filter((entry) => entry.type !== 'custom_message' || entry.customType !== CHECKPOINT_MESSAGE_TYPE)\n .flatMap((entry) => sessionEntryToContextMessages(entry));\n}\n\ninterface AutocompactRuntimeConfig {\n /** Off leaves compaction to Pi; unset is on. */\n enabled: boolean;\n /** The agent that writes the summaries, from autocompact's own keys or planning's. */\n agent?: PlanningAgentConfig;\n ratios: AutocompactRatioOverrides;\n /** Per-model absolute token checkpoints, tried in file order. */\n overrides: AutocompactOverrideConfig[];\n}\n\nconst DEFAULT_RUNTIME_CONFIG: AutocompactRuntimeConfig = { enabled: true, ratios: {}, overrides: [] };\n\n/**\n * What the Doom config says about this package.\n *\n * `modes.autocompact` is read first and `modes.planning.subagents` is the\n * fallback, because summarization borrowed the planning subagent model before\n * it had keys of its own and existing files still spell it that way.\n */\nexport function autocompactRuntimeConfig(\n cwd: string,\n onLoadFailure?: (error: unknown) => void,\n): AutocompactRuntimeConfig {\n let modes: ReturnType<typeof loadDoomConfig>['modes'];\n try {\n modes = loadDoomConfig(getHarnessState().root ?? cwd).modes;\n } catch (error) {\n process.emitWarning('Doom autocompact configuration could not be loaded; using the active session model instead.');\n onLoadFailure?.(error);\n return DEFAULT_RUNTIME_CONFIG;\n }\n const configured = modes?.autocompact;\n const ownAgent: PlanningAgentConfig | undefined =\n configured && (configured.model !== undefined || configured.thinking !== undefined)\n ? {\n ...(configured.model ? { model: configured.model } : {}),\n ...(configured.thinking ? { thinking: configured.thinking } : {}),\n }\n : undefined;\n const agent = ownAgent ?? modes?.planning?.subagents;\n const thresholds = configured?.thresholds;\n return {\n enabled: configured?.enabled ?? true,\n ...(agent ? { agent } : {}),\n ratios: {\n ...(thresholds?.pass1 === undefined ? {} : { 1: thresholds.pass1 }),\n ...(thresholds?.pass2 === undefined ? {} : { 2: thresholds.pass2 }),\n ...(thresholds?.pass3 === undefined ? {} : { 3: thresholds.pass3 }),\n },\n overrides: configured?.overrides ?? [],\n };\n}\n\n/** Explicit Doom model selection honors the configured summarization model. */\nexport function resolveDoomSummarizationModel(ctx: ExtensionContext): SummarizationModel | undefined {\n const configured = autocompactRuntimeConfig(ctx.cwd).agent;\n const reference = configured?.model ? parseModelReference(configured.model) : undefined;\n const configuredModel = reference ? ctx.modelRegistry.find(reference.provider, reference.modelId) : undefined;\n const model = configuredModel ?? ctx.model;\n if (!model) return undefined;\n const thinkingLevel =\n configured?.thinking ?? (configuredModel ? reference?.thinking : undefined) ?? ctx.thinkingLevel;\n return { model, ...(thinkingLevel ? { thinkingLevel } : {}) };\n}\n\n/**\n * Summarization borrows the session's own provider instead of re-resolving one.\n *\n * The selected model can come from a Pi provider extension, and that extension's\n * `streamSimple` closure lives only in this process: it is never in Pi's global api\n * registry, so any other thread or process sees `No API provider registered for api`.\n * Passing the composed provider in as `generateSummary`'s stream function keeps\n * summarization on exactly the path the agent's own requests take.\n */\nexport async function generateCheckpointWithPi(\n input: CheckpointGenerationInput,\n resolveModel: (context: ExtensionContext) => SummarizationModel | undefined,\n): Promise<string> {\n const selection = resolveModel(input.context);\n if (!selection) throw new Error('No active model is available for autocompact summarization.');\n const auth = await input.context.modelRegistry.getApiKeyAndHeaders(selection.model);\n if (!auth.ok) throw new Error(auth.error);\n const provider = input.context.modelRegistry.getProvider(selection.model.provider);\n if (!provider) {\n throw new Error(`No provider is registered for \"${selection.model.provider}\" in this session.`);\n }\n return generateSummary(\n input.messages,\n selection.model,\n DEFAULT_COMPACTION_SETTINGS.reserveTokens,\n auth.apiKey,\n // A null header value suppresses a provider default, which the narrower\n // `generateSummary` signature does not model but every provider honors.\n auth.headers as Record<string, string> | undefined,\n input.signal,\n input.instructions,\n input.previousCheckpoint,\n selection.thinkingLevel,\n (model, context, options) => provider.streamSimple(model, context, options),\n auth.env,\n );\n}\n\nfunction notify(ctx: ExtensionContext | undefined, message: string, level: 'info' | 'warning' | 'error' = 'info') {\n if (ctx?.hasUI) ctx.ui.notify(message, level);\n}\n\nexport function installAutocompactRuntime(\n cordis: Context,\n pi: ExtensionAPI,\n dependencies: AutocompactDependencies = {},\n): void {\n const resolveModel = dependencies.resolveModel ?? resolveDoomSummarizationModel;\n const generateCheckpoint =\n dependencies.generateCheckpoint ??\n ((input: CheckpointGenerationInput) => generateCheckpointWithPi(input, resolveModel));\n const telemetry = dependencies.telemetry ?? createAutocompactTelemetry();\n const doomIntegrations = dependencies.doomIntegrations ?? true;\n const appliedContextRequests = new Set<string>();\n const invalidContextLeaves = new Set<string>();\n const checkpointWork = new Set<Promise<void>>();\n let active = true;\n let sessionGeneration = 0;\n let state = createInitialState();\n let currentContext: ExtensionContext | undefined;\n let checkpointController: AbortController | undefined;\n let footerContribution: DoomFooterContributionHandle | undefined;\n let contextContributionsService: DoomContextContributionsService | undefined;\n let configLoadFailureReported = false;\n\n cordis.effect(\n () => async () => {\n active = false;\n sessionGeneration += 1;\n checkpointController?.abort(new Error('Autocompact runtime is shutting down.'));\n checkpointController = undefined;\n await Promise.allSettled(checkpointWork);\n footerContribution = undefined;\n contextContributionsService = undefined;\n currentContext = undefined;\n appliedContextRequests.clear();\n invalidContextLeaves.clear();\n state = createInitialState();\n configLoadFailureReported = false;\n await telemetry.shutdown();\n },\n `${FOOTER_SOURCE}/runtime`,\n );\n\n cordis.inject([DOOM_CONTEXT_CONTRIBUTIONS_SERVICE], (contextContributionsContext) => {\n const service = requireDoomContextContributions(contextContributionsContext);\n contextContributionsService = service;\n return () => {\n if (contextContributionsService === service) contextContributionsService = undefined;\n };\n });\n\n if (doomIntegrations) {\n cordis.inject([DOOM_UI_HUB_SERVICE], (uiContext) => {\n const contribution = requireDoomUiHub(uiContext).registerFooter({\n source: FOOTER_SOURCE,\n id: 'autocompact',\n order: FOOTER_ORDER,\n });\n footerContribution = contribution;\n return () => {\n contribution.dispose();\n if (footerContribution === contribution) footerContribution = undefined;\n };\n });\n }\n\n /** Compaction runs off the main thread, so the phase is the only signal the user gets. */\n const refreshStatus = (ctx?: ExtensionContext): void => {\n if (!active) return;\n const phase =\n state.phase === STATE_PHASE.checkpointPending\n ? 'summarizing'\n : state.phase === STATE_PHASE.checkpointReady\n ? 'applying'\n : undefined;\n footerContribution?.update(\n phase ? { fullText: `Compacting p${state.pass}`, compactText: `C${state.pass}` } : undefined,\n );\n const target = ctx ?? currentContext;\n if (target?.hasUI) target.ui.setStatus(STATUS_KEY, phase ? `Compacting pass ${state.pass} (${phase})…` : undefined);\n };\n\n // Every phase transition persists, so this is the one place that keeps the status honest.\n const persist = (): void => {\n if (!active) return;\n pi.appendEntry(STATE_CUSTOM_TYPE, { ...state });\n refreshStatus();\n };\n\n const clearPendingCheckpoint = (): void => {\n delete state.requestId;\n delete state.snapshotLeafId;\n delete state.snapshotTokens;\n delete state.pendingCheckpoint;\n delete state.compactionPass;\n };\n\n const completeQueuedPass = (pass: AutocompactPass): void => {\n state.checkpointQueue = state.checkpointQueue.filter((queuedPass) => queuedPass !== pass);\n };\n\n const restore = (ctx: ExtensionContext): void => {\n if (!active) return;\n state = latestPersistedState(ctx.sessionManager.getBranch()) ?? createInitialState();\n const resumablePending =\n state.phase === STATE_PHASE.checkpointReady && state.requestId && state.snapshotLeafId && state.pendingCheckpoint;\n if (resumablePending || state.phase === STATE_PHASE.waiting) return;\n\n checkpointController?.abort();\n checkpointController = undefined;\n state.phase = STATE_PHASE.waiting;\n clearPendingCheckpoint();\n persist();\n };\n\n const resumeAgent = (message: string): void => {\n if (!active) return;\n pi.sendMessage(\n {\n customType: RESUME_MESSAGE_TYPE,\n content: `${message} Continue from the compacted checkpoint's immediate next action without repeating completed work.`,\n display: false,\n details: { version: STATE_VERSION, cycle: state.cycle, pass: state.pass },\n },\n { triggerTurn: true, deliverAs: 'steer' },\n );\n };\n\n /**\n * Both failure paths share one attempt budget: a summarizer that keeps failing would\n * otherwise cost a full summarization call every turn for the rest of the session, so the\n * pass is abandoned once the budget is spent and becomes eligible again on the next cycle.\n */\n const registerFailedAttempt = (\n pass: AutocompactPass,\n failedLeafId: string | undefined,\n ): { attempts: number; exhausted: boolean } => {\n const attempts = state.invalidAttempts + 1;\n const exhausted = attempts >= MAX_INVALID_CHECKPOINT_ATTEMPTS;\n state.phase = STATE_PHASE.waiting;\n if (failedLeafId) state.lastAttemptLeafId = failedLeafId;\n if (exhausted) {\n completeQueuedPass(pass);\n state.exhaustedPasses = [...state.exhaustedPasses, pass];\n state.invalidAttempts = 0;\n } else {\n state.invalidAttempts = attempts;\n }\n clearPendingCheckpoint();\n persist();\n return { attempts, exhausted };\n };\n\n const failCheckpoint = (requestId: string, error: unknown): void => {\n if (!active || requestId !== state.requestId || state.phase !== STATE_PHASE.checkpointPending) return;\n const pass = state.pass;\n const { attempts, exhausted } = registerFailedAttempt(pass, state.snapshotLeafId);\n const reason = error instanceof Error ? error.message : String(error);\n notify(\n currentContext,\n exhausted\n ? `Doom autocompact summarization pass ${pass} failed ${attempts} times and was abandoned: ${reason}`\n : `Doom autocompact summarization pass ${pass} failed: ${reason}`,\n 'error',\n );\n };\n\n // A configuration that cannot be read degrades every later pass silently, and the process\n // warning never reaches the log sink. Report it once per session instead of once per turn.\n const reportConfigLoadFailure = (ctx: ExtensionContext, error: unknown): void => {\n if (!active || configLoadFailureReported) return;\n configLoadFailureReported = true;\n void telemetry.recordWarning(\n AUTOCOMPACT_EVENT.configurationLoadFailed,\n error,\n telemetryAttributes(ctx, { 'autocompact.cycle': state.cycle, 'autocompact.pass': state.pass }),\n );\n };\n\n const reportContributionFailures = (\n ctx: ExtensionContext,\n snapshot: DoomContextContributionsSnapshot,\n attributes: AutocompactEventAttributes,\n ): void => {\n if (!active) return;\n for (const error of snapshot.errors) {\n notify(\n ctx,\n `Doom autocompact context contribution degraded (${error.source}/${error.id}): ${error.message}`,\n 'warning',\n );\n void telemetry.recordWarning(AUTOCOMPACT_EVENT.contextContributionDegraded, new Error(error.message), {\n ...attributes,\n 'autocompact.context_contribution.source': error.source,\n 'autocompact.context_contribution.id': error.id,\n 'autocompact.context_contribution.order': error.order,\n });\n }\n };\n\n const preserveRuntimeState = (\n ctx: ExtensionContext,\n branch: SessionEntry[],\n attributes: AutocompactEventAttributes,\n ): RuntimeStateSnapshot => {\n if (!active) {\n return { contributions: [], contributionErrors: [] };\n }\n const contextContributions = readContextContributionsSnapshot(contextContributionsService);\n reportContributionFailures(ctx, contextContributions, attributes);\n const snapshot = runtimeStateSnapshot(branch, contextContributions);\n pi.sendMessage({\n customType: RUNTIME_STATE_MESSAGE_TYPE,\n content: formatRuntimeState(snapshot),\n display: false,\n details: { version: 2, ...snapshot },\n });\n return snapshot;\n };\n\n const commitCheckpoint = (pass: 2 | 3, ctx: ExtensionContext): boolean => {\n if (!active || !state.requestId || !state.snapshotLeafId || !state.pendingCheckpoint) return false;\n const branch = ctx.sessionManager.getBranch();\n const projected = projectContextMessages(buildSessionContext(branch).messages, branch).messages;\n const fileDetails = mergeFileDetails(state, fileOperationsFromMessages(projected));\n const requestId = state.requestId;\n const cycle = state.cycle;\n const summary = withCanonicalFileSections(state.pendingCheckpoint, fileDetails);\n const details: AutocompactContextDetails = {\n ...fileDetails,\n doomAutocompact: {\n version: STATE_VERSION,\n cycle,\n pass,\n requestId,\n snapshotLeafId: state.snapshotLeafId,\n tokensBefore: state.snapshotTokens ?? ctx.getContextUsage()?.tokens ?? 0,\n },\n retainedMessages: retainedMessagesAfterSnapshot(branch, state.snapshotLeafId),\n };\n\n const committedWhileIdle = ctx.isIdle();\n pi.sendMessage({ customType: CONTEXT_MESSAGE_TYPE, content: summary, display: false, details });\n const contextMessageLeafId = workingLeafId(ctx);\n const runtimeAttributes = telemetryAttributes(ctx, {\n 'autocompact.request.id': requestId,\n 'autocompact.cycle': cycle,\n 'autocompact.pass': pass,\n });\n const runtimeSnapshot = preserveRuntimeState(ctx, branch, runtimeAttributes);\n // Mid-run the marker is queued as a steering message, so its entry id is not resolvable yet.\n if (committedWhileIdle) pi.setLabel(contextMessageLeafId, `autocompact:c${cycle}:p${pass}`);\n\n state.readFiles = fileDetails.readFiles;\n state.modifiedFiles = fileDetails.modifiedFiles;\n delete state.latestCheckpointSnapshotLeafId;\n state.phase = STATE_PHASE.waiting;\n state.checkpointQueue = [];\n // A compacted context is a fresh ladder: passes abandoned in the previous cycle are eligible again.\n state.exhaustedPasses = [];\n state.invalidAttempts = 0;\n state.baselinePending = true;\n delete state.lastAttemptLeafId;\n clearPendingCheckpoint();\n state.cycle += 1;\n state.pass = 1;\n persist();\n void telemetry.recordEvent(\n AUTOCOMPACT_EVENT.contextCommitted,\n telemetryAttributes(ctx, {\n 'autocompact.request.id': requestId,\n 'autocompact.cycle': cycle,\n 'autocompact.pass': pass,\n 'autocompact.snapshot_leaf_id': details.doomAutocompact.snapshotLeafId,\n 'autocompact.tokens_before': details.doomAutocompact.tokensBefore,\n 'autocompact.message_count.before': projected.length,\n 'autocompact.message_count.retained': details.retainedMessages.length,\n 'autocompact.apply_mode': committedWhileIdle ? 'idle' : 'turn_end',\n ...runtimeTelemetryAttributes(runtimeSnapshot),\n }),\n );\n // A mid-run commit needs no resume steer: the agent is already continuing.\n if (committedWhileIdle) resumeAgent('Asynchronous compaction completed.');\n return true;\n };\n\n const requestCheckpoint = (pass: AutocompactPass, ctx: ExtensionContext, tokensBefore: number): void => {\n if (!active) return;\n const generation = sessionGeneration;\n const branch = ctx.sessionManager.getBranch();\n const snapshotLeafId = workingLeafId(ctx);\n const requestId = createRequestId(ctx.sessionManager.getSessionId(), state.cycle, pass, snapshotLeafId);\n const previousCheckpoint = pass > 1 ? checkpointSummaryFromEntry(latestCheckpointArtifactEntry(branch)) : undefined;\n const messages = messagesForCheckpoint(pass, branch, state.latestCheckpointSnapshotLeafId);\n const contextContributions = readContextContributionsSnapshot(contextContributionsService);\n const attributes = telemetryAttributes(ctx, {\n 'autocompact.request.id': requestId,\n 'autocompact.cycle': state.cycle,\n 'autocompact.pass': pass,\n 'autocompact.snapshot_leaf_id': snapshotLeafId,\n 'autocompact.tokens_before': tokensBefore,\n 'autocompact.message_count.before': messages.length,\n });\n reportContributionFailures(ctx, contextContributions, attributes);\n\n state.phase = STATE_PHASE.checkpointPending;\n state.pass = pass;\n state.requestId = requestId;\n state.snapshotLeafId = snapshotLeafId;\n state.snapshotTokens = tokensBefore;\n delete state.pendingCheckpoint;\n delete state.compactionPass;\n delete state.lastAttemptLeafId;\n persist();\n\n checkpointController?.abort();\n checkpointController = new AbortController();\n const checkpointSignal = checkpointController.signal;\n const operation = telemetry\n .runInSpan('doom_autocompact.checkpoint', attributes, async () => {\n await telemetry.recordEvent(AUTOCOMPACT_EVENT.checkpointStarted, attributes);\n try {\n const checkpoint = await generateCheckpoint({\n messages,\n instructions: checkpointInstructions(pass, {\n plan: latestPlanSnapshot(branch),\n contextContributions,\n readFiles: state.readFiles,\n modifiedFiles: state.modifiedFiles,\n }),\n ...(previousCheckpoint ? { previousCheckpoint } : {}),\n context: ctx,\n signal: checkpointSignal,\n });\n if (!active || generation !== sessionGeneration) {\n throw checkpointSignal.reason ?? new Error('Autocompact checkpoint became stale.');\n }\n if (!checkpoint.trim()) throw new Error('Summarization returned an empty checkpoint.');\n await telemetry.recordEvent(AUTOCOMPACT_EVENT.checkpointCompleted, {\n ...attributes,\n 'autocompact.checkpoint.characters': checkpoint.length,\n });\n return checkpoint;\n } catch (error) {\n if (active && generation === sessionGeneration) {\n await telemetry.recordError(AUTOCOMPACT_EVENT.checkpointFailed, error, attributes);\n }\n throw error;\n }\n })\n .then((checkpoint) => {\n if (\n !active ||\n generation !== sessionGeneration ||\n requestId !== state.requestId ||\n state.phase !== STATE_PHASE.checkpointPending\n ) {\n return;\n }\n state.phase = STATE_PHASE.checkpointReady;\n state.pendingCheckpoint = checkpoint.trim();\n persist();\n if (currentContext) processProgress(currentContext);\n })\n .catch((error: unknown) => {\n if (active && generation === sessionGeneration) failCheckpoint(requestId, error);\n });\n checkpointWork.add(operation);\n void operation.finally(() => checkpointWork.delete(operation));\n };\n\n const evaluateUsage = (ctx: ExtensionContext): boolean => {\n if (!active || state.phase !== STATE_PHASE.waiting || ctx.hasPendingMessages()) return false;\n // Read per evaluation rather than once at install, so turning the ladder off\n // or moving a threshold in settings takes effect on the next turn instead of\n // the next session.\n const configured = autocompactRuntimeConfig(ctx.cwd, (error) => reportConfigLoadFailure(ctx, error));\n if (!configured.enabled) return false;\n const usage = ctx.getContextUsage();\n if (!usage || usage.tokens === null) return false;\n if (state.baselinePending) {\n // Reported usage still describes the pre-compaction context until an assistant\n // responds against the projected one, and capturing it early poisons every threshold.\n if (!baselineUsageIsSettled(ctx.sessionManager.getBranch())) return false;\n state.baselineTokens = usage.tokens;\n state.baselinePending = false;\n persist();\n return false;\n }\n const leafId = workingLeafId(ctx);\n if (state.lastAttemptLeafId === leafId) return false;\n\n // The baseline branch above always returns, so by here it is settled for this cycle and the\n // token overrides can be compared against it without re-checking `baselinePending`.\n const tokenOverrides = resolveModelTokenOverrides(ctx.model, configured.overrides);\n const thresholds = effectiveThresholds(\n usage.contextWindow,\n state.baselineTokens,\n configured.ratios,\n tokenOverrides,\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 >= thresholds[pass]) {\n state.checkpointQueue.push(pass);\n }\n }\n const nextPass = state.checkpointQueue[0];\n if (!nextPass) return false;\n requestCheckpoint(nextPass, ctx, usage.tokens);\n return true;\n };\n\n // Staged checkpoints seed the next summarization pass only. They are appended as plain\n // session entries so they never enter the agent's LLM context: delivering them as messages\n // reads like a user instruction and derails the run (\"Checkpoint acknowledged...\").\n const stageCheckpoint = (pass: 1 | 2, summary: string): void => {\n if (!active) return;\n const checkpointSnapshotLeafId = state.snapshotLeafId;\n pi.appendEntry(CHECKPOINT_MESSAGE_TYPE, {\n ...checkpointRequestDetails(state.cycle, pass, state.requestId ?? 'completed'),\n summary,\n });\n if (checkpointSnapshotLeafId) state.latestCheckpointSnapshotLeafId = checkpointSnapshotLeafId;\n };\n\n const captureReadyCheckpoint = (ctx: ExtensionContext): CheckpointCapture => {\n if (!active || state.phase !== STATE_PHASE.checkpointReady || !state.requestId || !state.pendingCheckpoint) {\n return 'none';\n }\n const pass = state.pass;\n const decision = parseCheckpointDecision(state.pendingCheckpoint);\n if (!isStructuredCheckpoint(decision.summary)) {\n const failedLeafId = state.snapshotLeafId;\n const invalidRequestId = state.requestId;\n // A queued pass is retried once per new leaf, so an output the summarizer never formats\n // correctly would otherwise burn a full summarization call every turn for the session.\n const { attempts, exhausted } = registerFailedAttempt(pass, failedLeafId);\n const error = new Error(`Summarization pass ${pass} returned an incomplete checkpoint.`);\n notify(\n ctx,\n exhausted\n ? `Doom autocompact summarization pass ${pass} returned an incomplete checkpoint ${attempts} times and was abandoned.`\n : `Doom autocompact summarization pass ${pass} returned an incomplete checkpoint.`,\n 'error',\n );\n void telemetry.recordError(\n AUTOCOMPACT_EVENT.checkpointInvalid,\n error,\n telemetryAttributes(ctx, {\n 'autocompact.cycle': state.cycle,\n 'autocompact.pass': pass,\n 'autocompact.checkpoint.attempts': attempts,\n 'autocompact.checkpoint.exhausted': exhausted,\n ...(invalidRequestId ? { 'autocompact.request.id': invalidRequestId } : {}),\n }),\n );\n return 'invalid';\n }\n\n state.invalidAttempts = 0;\n\n if (pass === 1) {\n stageCheckpoint(1, decision.summary);\n completeQueuedPass(1);\n state.phase = STATE_PHASE.waiting;\n state.pass = 2;\n clearPendingCheckpoint();\n persist();\n return 'pass1';\n }\n\n if (pass === 2 && decision.shouldCompact !== true) {\n stageCheckpoint(2, decision.summary);\n completeQueuedPass(2);\n state.phase = STATE_PHASE.waiting;\n state.pass = 3;\n clearPendingCheckpoint();\n persist();\n return 'deferred';\n }\n\n state.pendingCheckpoint = decision.summary;\n return commitCheckpoint(pass, ctx) ? 'committed' : 'invalid';\n };\n\n function processProgress(ctx: ExtensionContext): void {\n if (!active) return;\n currentContext = ctx;\n if (!ctx.isIdle()) return;\n if (captureReadyCheckpoint(ctx) !== 'committed') evaluateUsage(ctx);\n }\n\n pi.on('context', (event, ctx) => {\n if (!active) return undefined;\n const projection = projectContextMessages(event.messages, ctx.sessionManager.getBranch());\n if (projection.invalidMarker) {\n const leafId = ctx.sessionManager.getLeafId() ?? ROOT_WORKING_LEAF;\n if (!invalidContextLeaves.has(leafId)) {\n invalidContextLeaves.add(leafId);\n void telemetry.recordError(\n AUTOCOMPACT_EVENT.contextMarkerInvalid,\n new Error('Doom autocompact context marker is malformed.'),\n telemetryAttributes(ctx, { 'autocompact.leaf_id': leafId }),\n );\n }\n return undefined;\n }\n if (!projection.marker) return undefined;\n if (!appliedContextRequests.has(projection.marker.requestId)) {\n appliedContextRequests.add(projection.marker.requestId);\n void telemetry.recordEvent(\n AUTOCOMPACT_EVENT.contextApplied,\n telemetryAttributes(ctx, {\n 'autocompact.request.id': projection.marker.requestId,\n 'autocompact.cycle': projection.marker.cycle,\n 'autocompact.pass': projection.marker.pass,\n 'autocompact.snapshot_leaf_id': projection.marker.snapshotLeafId,\n 'autocompact.tokens_before': projection.marker.tokensBefore,\n 'autocompact.message_count.before': event.messages.length,\n 'autocompact.message_count.after': projection.messages.length,\n 'autocompact.message_count.retained': projection.retainedMessageCount,\n }),\n );\n }\n return { messages: projection.messages };\n });\n\n const beginSessionGeneration = (ctx: ExtensionContext): void => {\n if (!active) return;\n sessionGeneration += 1;\n checkpointController?.abort(new Error('Autocompact session generation was replaced.'));\n checkpointController = undefined;\n appliedContextRequests.clear();\n invalidContextLeaves.clear();\n currentContext = ctx;\n restore(ctx);\n processProgress(ctx);\n };\n\n pi.on('session_start', (_event, ctx) => beginSessionGeneration(ctx));\n\n pi.on('session_tree', (_event, ctx) => beginSessionGeneration(ctx));\n\n pi.on('turn_end', (event, ctx) => {\n if (!active) return;\n currentContext = ctx;\n if (ctx.isIdle()) {\n processProgress(ctx);\n return;\n }\n // A ready checkpoint must be applied without waiting for the run to finish, otherwise\n // context keeps growing past the window for the rest of a long autonomous run. Tool\n // results confirm the run continues, so the queued marker lands before the next request.\n const canApplyDuringRun =\n state.phase === STATE_PHASE.checkpointReady && (event.toolResults?.length ?? 0) > 0 && !ctx.hasPendingMessages();\n if (canApplyDuringRun && captureReadyCheckpoint(ctx) !== 'none') return;\n evaluateUsage(ctx);\n });\n\n pi.on('agent_settled', (_event, ctx) => {\n if (!active) return;\n processProgress(ctx);\n });\n\n pi.on('session_before_compact', (event) => {\n if (!active || event.reason !== 'threshold') return undefined;\n // Native compaction stays cancelled while our own machinery is working, and stays\n // available as the emergency backstop once that machinery has stalled or declined.\n const machineryActive =\n state.phase === STATE_PHASE.checkpointPending ||\n state.phase === STATE_PHASE.checkpointReady ||\n state.baselinePending;\n return machineryActive ? { cancel: true } : undefined;\n });\n\n pi.on('session_compact', (event, ctx) => {\n if (!active) return;\n sessionGeneration += 1;\n // Native compaction supersedes any summarization still in flight.\n checkpointController?.abort();\n checkpointController = undefined;\n const eventDetails = fileDetailsFromUnknown(event.compactionEntry.details);\n const cumulative = mergeFileDetails(state, undefined, eventDetails);\n state.readFiles = cumulative.readFiles;\n state.modifiedFiles = cumulative.modifiedFiles;\n delete state.latestCheckpointSnapshotLeafId;\n // Reported usage still describes the pre-compaction context here too, so the baseline\n // waits for the first assistant response measured against the compacted one.\n state.baselinePending = true;\n state.phase = STATE_PHASE.waiting;\n clearPendingCheckpoint();\n state.checkpointQueue = [];\n state.exhaustedPasses = [];\n state.invalidAttempts = 0;\n delete state.lastAttemptLeafId;\n\n pi.setLabel(event.compactionEntry.id, `autocompact:c${state.cycle}:external`);\n const completedCycle = state.cycle;\n const runtimeAttributes = telemetryAttributes(ctx, {\n 'autocompact.cycle': completedCycle,\n 'autocompact.native.reason': event.reason,\n });\n const runtimeSnapshot = preserveRuntimeState(ctx, ctx.sessionManager.getBranch(), runtimeAttributes);\n state.cycle += 1;\n state.pass = 1;\n persist();\n void telemetry.recordEvent(\n AUTOCOMPACT_EVENT.nativeCompactionCompleted,\n telemetryAttributes(ctx, {\n 'autocompact.cycle': completedCycle,\n 'autocompact.native.reason': event.reason,\n 'autocompact.native.from_extension': event.fromExtension,\n 'autocompact.tokens_before': event.compactionEntry.tokensBefore,\n ...runtimeTelemetryAttributes(runtimeSnapshot),\n }),\n );\n });\n}\n\n/** The package's single standard Pi factory. */\nexport async function autocompactExtension(pi: ExtensionAPI): Promise<void> {\n const connection = await connectDoomCordisHost(pi, PACKAGE_SOURCE);\n const fiber = connection.root.plugin(autocompactPlugin, { pi });\n try {\n await fiber;\n } catch (error) {\n try {\n await fiber.dispose();\n } finally {\n await connection.dispose();\n }\n throw error;\n }\n let disposal: Promise<void> | undefined;\n pi.on(\n 'session_shutdown',\n () =>\n (disposal ??= (async () => {\n try {\n await fiber.dispose();\n } finally {\n await connection.dispose();\n }\n })()),\n );\n}\n\ninterface AutocompactPluginConfig {\n readonly pi: ExtensionAPI;\n}\n\nfunction autocompactPlugin(cordis: Context, config: AutocompactPluginConfig): void {\n installAutocompactRuntime(cordis, config.pi);\n}\n\nexport default autocompactExtension;\n"],"mappings":"4fAmEA,MAAM,EAAoB,QAGpB,EAAgB,mBAGhB,EAAc,CAClB,QAAS,UACT,kBAAmB,qBACnB,gBAAiB,mBACjB,WAAY,YACd,EAqCA,SAAS,EACP,EACA,EAAyC,CAAC,EACd,CAC5B,MAAO,CACL,gBAAiB,EAAQ,eAAe,aAAa,EACrD,GAAG,CACL,CACF,CAEA,SAAS,EAAqB,EAAsD,CAClF,IAAK,IAAI,EAAQ,EAAO,OAAS,EAAG,GAAS,EAAG,IAAY,CAC1D,IAAM,EAAQ,EAAO,GACrB,GAAI,GAAO,OAAS,UAAY,EAAM,aAAA,yBAAkC,SACxE,IAAM,EAASA,EAAAA,WAAW,EAAM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