@fishwithcat/dsh-compaction-basic 0.0.0-stage → 0.2.2-alpha.3

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.
@@ -0,0 +1,103 @@
1
+ # Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading
2
+ # section, a hash of its English and Chinese blocks outside code blocks and generated regions.
3
+ # After editing either side, bring the other along and re-record with:
4
+ # pnpm run verify-translation-pairing --write packages/compaction/compaction-basic/README.md
5
+ /:
6
+ en: 4c3172f95eb524e1
7
+ zh: dd92ec1300ad9cbe
8
+ /deepseek-ai-dsh-compaction-basic:
9
+ en: 3ba5f9e37ab36328
10
+ zh: 2390a55415d4c27b
11
+ /deepseek-ai-dsh-compaction-basic/summary:
12
+ en: 31202d573182cc31
13
+ zh: e0a0c96f67a9c1ba
14
+ /deepseek-ai-dsh-compaction-basic/table-of-contents:
15
+ en: d152484eb41ac6b4
16
+ zh: bda879a892f240f0
17
+ /deepseek-ai-dsh-compaction-basic/use-this-package:
18
+ en: b40fa08b8ad55cca
19
+ zh: f8765a6f199c8c7b
20
+ /deepseek-ai-dsh-compaction-basic/use-this-package/what-you-get:
21
+ en: eb8e340061f72b98
22
+ zh: 327a51037b2d1adf
23
+ /deepseek-ai-dsh-compaction-basic/use-this-package/smallest-working-composition:
24
+ en: 4cb73d7a57908948
25
+ zh: 7ba2ddc4c76e4957
26
+ /deepseek-ai-dsh-compaction-basic/use-this-package/tuning-when-condensation-starts:
27
+ en: 3446c54c062d7e34
28
+ zh: fb502c941e508ae0
29
+ /deepseek-ai-dsh-compaction-basic/use-this-package/what-happens-when-condensation-runs:
30
+ en: c872a8ef069596f0
31
+ zh: b3a48e309ae830d4
32
+ /deepseek-ai-dsh-compaction-basic/use-this-package/switching-models:
33
+ en: 48978abc46da1afa
34
+ zh: 11931af05db7b41f
35
+ /deepseek-ai-dsh-compaction-basic/use-this-package/on-demand-condensation-with-compact:
36
+ en: 4c5067e4c57ca708
37
+ zh: 1c0e70319b9b2112
38
+ /deepseek-ai-dsh-compaction-basic/use-this-package/trimming-oversized-tool-outputs:
39
+ en: 1d6a74c0dc874dc8
40
+ zh: bcfa95549308c030
41
+ /deepseek-ai-dsh-compaction-basic/understand-the-implementation:
42
+ en: deb655b3b1860576
43
+ zh: 79f56e41a9dfe01f
44
+ /deepseek-ai-dsh-compaction-basic/understand-the-implementation/design-philosophy:
45
+ en: ed2d43610d4eaa83
46
+ zh: b46a1eaad396cdd7
47
+ /deepseek-ai-dsh-compaction-basic/understand-the-implementation/automatic-triggers-and-overflow-recovery:
48
+ en: 9e6e472b0f3977d3
49
+ zh: fdc0e827c19ba401
50
+ /deepseek-ai-dsh-compaction-basic/understand-the-implementation/summarization-mechanics:
51
+ en: 967531b71453eb88
52
+ zh: c7919b46e36763e6
53
+ /deepseek-ai-dsh-compaction-basic/understand-the-implementation/the-region-transaction:
54
+ en: f4330f6bff22d400
55
+ zh: 46e16c51bb66a0f7
56
+ /deepseek-ai-dsh-compaction-basic/understand-the-implementation/config-resolution:
57
+ en: 313e019b1a9f8aa8
58
+ zh: 3c75d11b02adb693
59
+ /deepseek-ai-dsh-compaction-basic/understand-the-implementation/source-map:
60
+ en: 747bad235fbb04ad
61
+ zh: 02e6562f3d745d4f
62
+ /deepseek-ai-dsh-compaction-basic/further-exploration:
63
+ en: 84b5b81eb9b5965d
64
+ zh: 7000af0fa502fcc1
65
+ /deepseek-ai-dsh-compaction-basic/model-experience:
66
+ en: 215e7ba838619b7b
67
+ zh: a311da3843709f90
68
+ /deepseek-ai-dsh-compaction-basic/model-experience/conversation-history:
69
+ en: 2e1148dd0f39a281
70
+ zh: cd68c9fff63534af
71
+ /deepseek-ai-dsh-compaction-basic/model-experience/conversation-history/what-the-model-sees:
72
+ en: 8d4325e6659bc314
73
+ zh: f80e69305b39f4a3
74
+ /deepseek-ai-dsh-compaction-basic/model-experience/conversation-history/what-the-model-sees/conversation-checkpoint-preamble:
75
+ en: 129d1eaba2519330
76
+ zh: 3ec517bdc6cb5ae3
77
+ /deepseek-ai-dsh-compaction-basic/model-experience/conversation-history/token-effect:
78
+ en: 872515a75b5a9726
79
+ zh: c0045e1972bbac4e
80
+ /deepseek-ai-dsh-compaction-basic/model-experience/conversation-history/kv-cache-effect:
81
+ en: a22b43f321843aee
82
+ zh: a5960da1bef34441
83
+ /deepseek-ai-dsh-compaction-basic/model-experience/auxiliary-summarizer-request:
84
+ en: 7169bd02a7a6c396
85
+ zh: 7c62e3d4a97c73f7
86
+ /deepseek-ai-dsh-compaction-basic/model-experience/auxiliary-summarizer-request/what-the-model-sees:
87
+ en: b7afcf1cc1c85c40
88
+ zh: a112c5b3984c31dc
89
+ /deepseek-ai-dsh-compaction-basic/model-experience/auxiliary-summarizer-request/what-the-model-sees/compaction-instruction-final-user-message:
90
+ en: 39a362ee4890dbdb
91
+ zh: 3b98699120b1548e
92
+ /deepseek-ai-dsh-compaction-basic/model-experience/auxiliary-summarizer-request/token-effect:
93
+ en: 5e0679cb7cb4291a
94
+ zh: c9df8ebc526b05d9
95
+ /deepseek-ai-dsh-compaction-basic/model-experience/auxiliary-summarizer-request/kv-cache-effect:
96
+ en: d31d3e3d46542c91
97
+ zh: 5a42f873993e0c79
98
+ /deepseek-ai-dsh-compaction-basic/known-limitations-and-deferred-work:
99
+ en: e2514d868dd5abbb
100
+ zh: a84fd6428d5c245a
101
+ /deepseek-ai-dsh-compaction-basic/known-limitations-and-deferred-work/dev-note:
102
+ en: 1fec7b90c3b68c49
103
+ zh: ad9ae54a598846d0
package/README.md CHANGED
@@ -1,3 +1,273 @@
1
- # Temporary Holding Version
1
+ ---
2
+ description: "Automatic conversation condensation for deployments choosing, tuning, or debugging how older history is summarized as token pressure builds."
3
+ kind: "package-reference"
4
+ ---
2
5
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
6
+ # @deepseek-ai/dsh-compaction-basic
7
+
8
+ English | [中文](README.zh.md)
9
+
10
+ ## Summary
11
+
12
+ This package keeps long agent conversations working near the model's context limit. As token pressure builds, it condenses the oldest history into a summary while preserving recent messages; after a context-overflow error, it condenses and retries. You can also request condensation with `/compact` and optionally trim oversized tool outputs first. Condensation uses one extra model request and retains only its summary text. It cannot reduce the system prompt, tools, or session prefix, or split one indivisible unit such as a single huge tool call.
13
+
14
+ ## Table of Contents
15
+
16
+ - [Use this package](#use-this-package)
17
+ - [Understand the implementation](#understand-the-implementation)
18
+ - [Further Exploration](#further-exploration)
19
+ - [Model Experience](#model-experience)
20
+ - [Known Limitations and Deferred Work](#known-limitations-and-deferred-work)
21
+ - [Dev Note](#dev-note)
22
+
23
+ -----
24
+
25
+ <a id="use-this-package"></a>
26
+ ## Use this package
27
+
28
+ Mount this package to get automatic conversation condensation in a composition that already provides an LLM, session storage, and token measurement. The shipped `dsh` base enables it by default; mount it explicitly to control when condensation starts.
29
+
30
+ ### What you get
31
+
32
+ With the default settings you get four behaviors: automatic condensation as the conversation grows toward the model's context limit; recovery after a confirmed context-overflow error, where the conversation condenses and the request retries; on-demand condensation through the `/compact` command; and — when the pruner is mounted — trimming of oversized tool outputs before condensation.
33
+
34
+ ### Smallest working composition
35
+
36
+ Mount session storage, token measurement, the optional pruner, this backend, and optionally the on-demand command:
37
+
38
+ ```yaml
39
+ - name: '@deepseek-ai/dsh-session'
40
+ - name: '@deepseek-ai/dsh-token-meter'
41
+ - name: '@deepseek-ai/dsh-compaction-tool-result-pruner'
42
+ - name: '@deepseek-ai/dsh-compaction-basic'
43
+ - name: '@deepseek-ai/dsh-command-compact'
44
+ ```
45
+
46
+ You can verify success by watching the conversation continue past the point where it would otherwise overflow, and by running `/compact` for an immediate condensation. If the composition lacks an LLM, session storage, or token measurement, the plugin fails to load. One backend can serve models with different context sizes; give each route its own threshold and retention with a per-model override:
47
+
48
+ ```yaml
49
+ - name: '@deepseek-ai/dsh-compaction-basic'
50
+ config:
51
+ thresholdRatio: 0.8
52
+ retainRatio: 0.16
53
+ modelPolicies:
54
+ - provider: local
55
+ model: small-context
56
+ thresholdRatio: 0.7
57
+ headroomTokens: 4096
58
+ maxTokens: 4096
59
+ retainTokens: 2048
60
+ ```
61
+
62
+ ### Tuning when condensation starts
63
+
64
+ All settings are optional. With context window `W`, effective request output cap `O`, and headroom `B`, the default trigger is `floor(min(W × 0.8, W − O − B))`, where `B = 65,536` tokens. Retention keeps the newest 16% of `W − O` verbatim. The table below lists every setting; the generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-compaction-basic) also includes their types.
65
+
66
+ | Field | Default | Meaning |
67
+ |---|---|---|
68
+ | `thresholdRatio` | `0.8` | Window fraction used in `floor(min(W × thresholdRatio, W − O − headroomTokens))`. |
69
+ | `headroomTokens` | `65536` | Additional pressure headroom beyond the routed output reservation; a non-negative integer. |
70
+ | `retainRatio` | `0.16` | Recent conversation kept verbatim as a fraction of `W − O`; mutually exclusive with `retainTokens`. |
71
+ | `retainTokens` | — | Absolute recent-conversation budget kept verbatim; mutually exclusive with `retainRatio` and must be below the resolved threshold. |
72
+ | `summarizationProvider` | `''` | Set together with `summarizationModel`; an empty pair uses the latest routed request target, then the `AgentOptions` pair. |
73
+ | `summarizationModel` | `''` | Set together with `summarizationProvider`; an empty pair uses the latest routed request target, then the `AgentOptions` pair. |
74
+ | `maxTokens` | `headroomTokens` (`65536`) | Positive summary output cap, including any provider-counted reasoning tokens. Explicit per-model caps override explicit global caps; otherwise the cap follows the resolved headroom. |
75
+ | `compactionRetries` | `1` | Extra condensation attempts after the first when pressure remains above threshold. |
76
+ | `maxOverflowRetries` | `1` | Maximum retries after a confirmed context-window overflow; `0` disables recovery only. |
77
+ | `modelPolicies` | `[]` | Exact `{ provider, model, ...partialPolicy }` overrides for individual model routes. |
78
+ | `auto` | `true` | Enable automatic condensation and overflow recovery; set `false` for manual-only operation. |
79
+
80
+ Misconfiguration fails fast: unknown settings, duplicate per-model overrides, invalid token counts, both retention forms together, or a retention ratio at least as large as the threshold ratio reject the plugin at load. When the model is first used, `W − O − B` must be positive and the resolved retained budget must be below the trigger. Zero headroom requires an explicit positive `maxTokens`, globally or in that model policy. Small-window deployments must configure headroom that fits their capacity; lower `thresholdRatio` to compact earlier.
81
+
82
+ ### What happens when condensation runs
83
+
84
+ The oldest balanced span is replaced by one summary message and the recent tail stays verbatim; the conversation continues from the summary. The operation reports how many history items were condensed and the estimated tokens freed. If nothing can be condensed safely — for example the whole conversation is one indivisible unit — nothing changes and nothing is written to the session log. If no model is available to write the summary (no configured target and no routed request yet), condensation fails with a clear error telling you to configure the summarization provider and model or route one request.
85
+
86
+ ### Switching models
87
+
88
+ Before a changed provider/model request is committed, automatic compaction measures the existing history against the destination model's capacity, output reservation, and pressure policy. When condensation is needed, it uses the previous routed model and its summary settings; an explicitly configured summary target still takes precedence. The destination request proceeds only after history falls below its threshold. Failure reports `MODEL_SWITCH_COMPACTION_FAILED` and leaves the previous request header intact; select a larger model or retry after correcting the reported cause. Completed pruning or condensation remains in the session even when a later attempt fails. The check runs when the next request is prepared, and `auto: false` disables it.
89
+
90
+ The destination must have a registered adapter, declared context capacity, and a valid pressure budget even for short history. The default 65,536-token headroom does not fit a window of that size or smaller; set `modelPolicies[].headroomTokens` for that route as in the example above. See the [upgrade guide](../../../docs/upgrade-guide/v0.2.1-alpha.4/model-switch-compaction/guide.md) for migration.
91
+
92
+ ### On-demand condensation with /compact
93
+
94
+ With `dsh-command-compact` mounted, type `/compact` in a chat UI to condense immediately, even below the pressure threshold. The command reports how many history items were condensed and the estimated tokens saved. While the agent is mid-turn or condensation is already running, `/compact` reports that condensation is unavailable; prompts you send while it runs are accepted and start after it finishes.
95
+
96
+ ### Trimming oversized tool outputs
97
+
98
+ Mount `dsh-compaction-tool-result-pruner` before this package to trim oversized tool results as part of condensation. Trimming makes no model call and can remove the need to summarize at all: when the trimmed conversation fits within the threshold, condensation skips the summary. Trimming only runs after a condensation trigger qualifies — a below-pressure conversation is never touched.
99
+
100
+ -----
101
+
102
+ <a id="understand-the-implementation"></a>
103
+ ## Understand the implementation
104
+
105
+ <details>
106
+ <summary>Implementation internals — click to expand</summary>
107
+
108
+ This section explains the design decisions behind the backend; the observable behavior is fully covered in [Use this package](#use-this-package).
109
+
110
+ ### Design philosophy
111
+
112
+ The backend is built on four commitments:
113
+
114
+ - **One measurement service prices every decision.** The singleton `ctx.tokenMeter` measures the latest canonical logged envelope and current surface at one consumed-log revision. When the routed adapter declares request-image pricing, the meter applies it to image history. Model-switch pressure, retention, and range selection use destination pricing; region shrink validation uses the last committed route; logged replacement shadow prices stay on the route-independent heuristic so pure projection folds remain consistent.
115
+ - **The log-recorded bracket is the transaction.** All entry points share one bracket-first region transaction: validate the range and live lock, append `compaction/start` synchronously, prepare and await the summary, revalidate, append `compaction/summary` plus the replacement, and make exactly one closing attempt. Automatic and explicit-region calls require a numeric open-turn owner and whole-surface stability; `compactNow()` reserves idle admission, uses `turn: null`, accepts append-only context outside its selected span, flushes every closed attempt, and releases admission in `finally`.
116
+ - **Summarization reuses the provider's warm prefix.** Replaying the system prompt held by the `system/message` at surface node 0, the last routed request's tools, and the shadowed-region messages byte-for-byte makes the auxiliary call a genuine prefix of the conversation, so only the trailing instruction and the summary output are uncached.
117
+ - **`summarize()` is the sole subclass hook.** A template- or remote-summarizer subclass can override it while pressure, retention, cited source events, shrink validation, and shadowed-token accounting stay on the token meter.
118
+
119
+ ### Automatic triggers and overflow recovery
120
+
121
+ The `agent/request` listener waits for routing listeners to select the destination, then checks its pressure before the new header is logged. It uses `compactPressure` directly because `compactIfNeeded` reads the committed header; both paths generate summaries through `summarize()`.
122
+
123
+ With `auto: true`, a serial `agent/pre-step` listener checks pressure before request derivation: it prices the latest durable routed request envelope through `ctx.tokenMeter`, and when pressure crosses the routed model's threshold it prunes, then summarizes the oldest balanced span while keeping a priced recent tail. Every selected range starts at the first surface node that is not a `system/message`, so a system prompt at surface node 0 is never shadowed; a later `system/message` appended by an in-history prompt update is ordinary history that the range may shadow, and the agent loop's projection then replaces node 0 with the current prompt when their text differs ([decision rule](../../core/agent-loop/README.md#understand-the-implementation)). The `agent/request-error` listener reacts to a provider-confirmed `CONTEXT_WINDOW_EXCEEDED`: it bypasses the normal threshold and retention policy, attempts one maximal balanced head reduction, and authorizes a retry only after the surface replacement generation advances. Cancellation stays authoritative throughout.
124
+
125
+ Pressure policy resolves capacity from the adapter that owns the durable route. Missing capacity, output plus headroom exhausting the window, or a retained budget at least as large as the threshold makes the manual pressure path throw a target-specific configuration error. The `agent/pre-step` listener warns once for that exact target and continues the turn; provider-confirmed overflow recovery remains available. Model-switch checks instead reject the request with `MODEL_SWITCH_COMPACTION_FAILED`, including when capacity or adapter lookup fails.
126
+
127
+ ### Summarization mechanics
128
+
129
+ A direct `ctx.llm.stream()` call uses the configured provider/model pair and cap, falling back to the latest logged request target and then the `AgentOptions` pair, without running the loop-only `agent/request` extension point. The call replays the derived `system/message` at surface node 0 as the leading entry of `messages`, followed by the shadowed-region messages (including a shadowed in-history `system/message` in its surface position), and supplies the header's active tools for route-specific projection. The selected adapter must resolve image references in the replayed messages or explicitly reject them. The call appends the compaction instruction as the final user message, preserving the provider's warm prefix where projection permits. An empty-content system head contributes no message but remains outside the compacted range. The final instruction is a frozen `RequestUserInput` without durable identity or source; the replayed history and persisted checkpoint remain durable messages. The call sets `GenerateOptions.purpose` to `compaction`; only returned text enters the checkpoint, excluding reasoning and tool calls. Image output fails with `UNSUPPORTED_CONTENT` rather than disappearing. The replacement user message frames the summary with `<compacted-summary>` tags; the raw summary remains on the `compaction/summary` event. The call also carries `Session.toolHistory()` so the runtime can project deferred and retained definitions; a prefix missing update messages uses active declarations without developer updates.
130
+
131
+ ### The region transaction
132
+
133
+ Failed summary requests dispatch synchronous `compaction/summary-error` after checking cancellation and selection stability. A recovery listener must record a durable input change before requesting retry. The backend re-derives the selected messages and refreshes their token prices and shrink baseline. The image-offload plugin owns image selection; its recorded omissions remain effective if the summary later fails or is cancelled.
134
+
135
+ The transaction validates the surface span and the durable lock, appends `compaction/start`, summarizes through the hook, revalidates stability (whole-surface for automatic calls, selected-span for manual calls), rejects a summary that does not shrink its source, appends `compaction/summary` plus the replacement `user/message`, and makes exactly one `compaction/end` attempt. A live unmatched start is the durable lock: an unmatched marker before a newer `session/end-seed` is stale evidence from a prior lifecycle and does not block; one after that boundary reports `busy`. A failed close deliberately leaves a blocking orphan. Cancellation remains authoritative after cleanup and durability.
136
+
137
+ ### Config resolution
138
+
139
+ `resolveConfig` validates and detaches defaults, `resolveTargetPolicy` merges exact provider/model overrides, and `resolveCompactSpec` requires explicit adapter capacity and routed output reservation to resolve the trigger and retained budget. The effective envelope’s `maxTokens` supplies that reservation, falling back to the adapter default and then zero. Model discovery (`listModels()`) is never consulted for policy; capacity comes from the durable route or the proposed destination during a model switch.
140
+
141
+ ### Source map
142
+
143
+ | File | Role |
144
+ |---|---|
145
+ | [`src/index.ts`](src/index.ts) | Plugin entry: `BasicCompactionEngine`, automatic listeners, entry-point dispatch |
146
+ | [`src/region.ts`](src/region.ts) | Retention selection and the shared bracket-first compaction transaction |
147
+ | [`src/summarizer.ts`](src/summarizer.ts) | Default `ctx.llm.stream()` summarization, checkpoint framing, safe-summary projection |
148
+ | [`src/config.ts`](src/config.ts) | Load-time validation and routed-model policy resolution |
149
+ | [`src/types.ts`](src/types.ts) | `BasicCompactionConfig` and resolved policy vocabulary |
150
+
151
+ The package root's type declarations add `compaction` to `LlmRequestPurposeMap`. Direct callers constructing compaction requests use `import type {} from '@deepseek-ai/dsh-compaction-basic'` so `GenerateOptions.purpose` includes that key.
152
+
153
+ </details>
154
+
155
+ -----
156
+
157
+ <a id="further-exploration"></a>
158
+ ## Further Exploration
159
+
160
+ Read these pages when the package-level contract is not enough; they move from the shared seam to the optional companions and the decision evidence.
161
+
162
+ - [Compaction seam](../compaction/README.md) — the condensation contract this backend implements.
163
+ - [Compaction subsystem reference](../../../docs/subsystems/compaction.md) — the condensation vocabulary, results, and service behavior.
164
+ - [Tool-result pruner](../compaction-tool-result-pruner/README.md) — the optional companion that trims oversized tool outputs first.
165
+ - [Human /compact command](../command-compact/README.md) — on-demand condensation without waiting for pressure.
166
+ - [Token meter](../../llm/token-meter/README.md) — the measurement service that decides when to condense.
167
+ - [Generated configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-compaction-basic) — every accepted config field and its source declaration.
168
+
169
+ -----
170
+
171
+ <a id="model-experience"></a>
172
+ ## Model Experience
173
+
174
+ ### Conversation history
175
+
176
+ #### What the model sees
177
+
178
+ After a successful step crosses the threshold, oversized tool results are first rewritten when the optional pruner is loaded. If summarization remains necessary, the next request receives the checkpoint preamble below, a blank line, `<compacted-summary>`, the data-dependent summary, and `</compacted-summary>`. Overflow recovery rebuilds the immediate retry from whatever replacement advanced the surface. A checkpoint replaces the selected older range and is followed by the retained recent units.
179
+
180
+ ##### Conversation checkpoint preamble
181
+
182
+ ```markdown
183
+ This is an automatically generated checkpoint condensing an earlier span of the conversation to free up context. Treat the captured context as established background and build on it without restating it. Continue the task directly from the messages that follow, without acknowledging this checkpoint.
184
+ ```
185
+
186
+ #### Token effect
187
+
188
+ Model-free pruning can avoid the auxiliary call entirely; otherwise it reduces that call's transcript before the summary replaces an older range. The replacement reduces future input history rather than appending a second copy. A summary remains until a later compaction replaces it, while an indivisible non-tool unit can still exceed the budget.
189
+
190
+ #### KV Cache effect
191
+
192
+ Replacing rather than append-only. Each checkpoint invalidates reuse from the first replaced history token; the unchanged request prefix before that range remains reusable.
193
+
194
+ ### Auxiliary summarizer request
195
+
196
+ #### What the model sees
197
+
198
+ The summarization model receives the system prompt and shadowed-region history, with tool declarations and developer updates projected for its route, followed by one final user message: the compaction instruction below. The conversation model never sees this private request or its reasoning; only returned text is stored.
199
+
200
+ ##### Compaction instruction (final user message)
201
+
202
+ ```markdown
203
+ You are now acting as a compaction engine for this AI coding assistant. Condense the conversation ABOVE into a structured checkpoint that lets another model resume the work with no loss of essential context.
204
+
205
+ Output EXACTLY the Markdown structure below: keep every section, in order. Use terse bullets, not prose paragraphs. Write "(none)" for an empty section — never drop a section.
206
+
207
+ ## Primary Request and Intent
208
+ - [the user's original and evolving goals; quote verbatim where the exact wording matters]
209
+
210
+ ## Key Technical Concepts
211
+ - [technologies, frameworks, patterns, and conventions in play]
212
+
213
+ ## Files and Code
214
+ - [exact path: why it matters, key changes or snippets]
215
+
216
+ ## Errors and Fixes
217
+ - [error: how it was resolved, plus any related user feedback]
218
+
219
+ ## Pending Jobs
220
+ - [explicitly requested work not yet completed]
221
+
222
+ ## Current Work
223
+ - [precisely what was in progress at this checkpoint]
224
+
225
+ ## Next Step
226
+ - [the single next action, directly in line with the most recent request, or "(none)"]
227
+
228
+ ## Critical Context
229
+ - [decisions and their rationale, constraints, user preferences, open questions, data needed to continue]
230
+
231
+ Rules:
232
+ - Write concise English engineering prose. Preserve exact file paths, commands, error strings, identifiers, numeric values, function signatures, and syntax fragments.
233
+ - Capture user feedback and explicit instructions faithfully, especially corrections.
234
+ - Do NOT mention this summarization request or that the context was compacted.
235
+ - Output only the checkpoint text: do not call any tool or take any other action.
236
+ - If the conversation already contains a <compacted-summary> block, it is a PRIOR checkpoint. Do not copy it forward verbatim: preserve still-true facts, drop stale ones, and merge newer information into a single consolidated summary under the same structure.
237
+ ```
238
+
239
+ #### Token effect
240
+
241
+ This is a separate model call: the replayed conversation prefix plus the fixed instruction as input, with `maxTokens`-capped output. Convergence retries can pay this cost more than once.
242
+
243
+ #### KV Cache effect
244
+
245
+ The replayed system prompt, tools, and shadowed-region messages match the conversation's last routed request byte-for-byte, so the provider's warm prefix cache is reused up to the trailing instruction; only that instruction, and the summary output, is uncached. Routing the summarizer to a different provider/model, or compacting a non-head range, forgoes this reuse.
246
+
247
+ ## Known Limitations and Deferred Work
248
+
249
+ <a id="known-limitations-and-deferred-work"></a>
250
+
251
+
252
+ These limits define when automatic condensation is a poor fit or needs special care; they are the current package constraints.
253
+
254
+ - **Meter accuracy follows the fixed heuristic** — missing reusable provider usage falls back to character count plus structural overhead rather than exact tokenization; image occurrences carry provider-exact visual tokens only on routes whose adapter declares request-image pricing.
255
+ - **Overflow classification is adapter-maintained** — provider wording can change; both DeepSeek adapters normalize recognized context-limit failures to `CONTEXT_WINDOW_EXCEEDED`.
256
+ - **Some indivisible-unit and envelope-only overflow remains outside surface compaction** — recovery cannot shrink system/tools/prefix, split an indivisible non-tool node, or repair a tool unit whose non-prunable remainder still exceeds the window. The optional pruner can shrink text-bearing tool-result bulk inside an otherwise indivisible pair.
257
+ - **`compactRegion` requires an open turn** — a manual call on a fully-closed session throws ("no open turn") rather than compacting.
258
+ - **Summarization failure preserves the latest durable surface** — pre-step pressure logs a warning and continues; model-switch pressure rejects the destination request. Completed pruning and earlier checkpoints survive either failure. Summarization truncation at `maxTokens`, which hidden reasoning tokens can consume, follows the same rule.
259
+ - **Cross-model image pricing can reject a useful summary** — switch range selection uses destination pricing, while shrink validation uses the committed route. Different image prices can make a summary fail shrink validation even when it would reduce destination pressure.
260
+
261
+ <a id="dev-note"></a>
262
+ ### Dev Note
263
+
264
+ <details>
265
+ <summary>Working context for maintainers — click to expand</summary>
266
+
267
+ This Dev Note is working context for maintainers and is explicitly non-authoritative; shipped behavior lives in the sections above, the package code, and the linked Agent Notes.
268
+
269
+ - **Default ratios, undecided** — `thresholdRatio: 0.8` and `retainRatio: 0.16` are fixed defaults; per-model tuning via `modelPolicies` exists, but no corpus-backed guidance on ideal values is recorded.
270
+ - **Tokenizer-accurate measurement, deferred** — the token meter's four-characters-per-token heuristic underprices CJK text and JSON Schema documents; exact tokenization remains an open direction for the measurement service.
271
+ - **Overflow recovery beyond canonical errors, undecided** — recovery triggers on `CONTEXT_WINDOW_EXCEEDED` only; other provider-side context failures are not classified.
272
+
273
+ </details>