@jianxx/dsh-cc-compaction-micro 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,6 @@
1
+ # Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
2
+ # side as of the last confirmed-consistent state. Both languages carry equal authority;
3
+ # after editing either side, bring the other along and re-record with:
4
+ # pnpm run verify-translation-pairing --write packages/compaction/compaction-micro/README.md
5
+ README.md: f12e8e11121a5a72504cb32131380fb1794f73ec
6
+ README.zh.md: dee3ac73666a7b2ec946e282c8da55d9a3633c10
package/README.md ADDED
@@ -0,0 +1,66 @@
1
+ # @jianxx/dsh-cc-compaction-micro
2
+
3
+ English | [中文](README.zh.md)
4
+
5
+ The replay-safe model-free microcompaction service (`ctx.microcompactor`). It keeps the most recent `retainResults` `tool/result` surface nodes verbatim and replaces every older one with a deterministic placeholder that re-embeds the original's spill locator when one was cited — no model call, no summarization.
6
+
7
+ This is a concrete companion to [`dsh-compaction-basic`](../compaction-basic/README.md), not a compaction backend. It composes ahead of summarization so the summarizer reads an already window-reduced surface. Both packages remain independently composable.
8
+
9
+ ## Service API
10
+
11
+ `microcompactSession(session)` scans one stable snapshot of the current surface. The most recent `retainResults` tool results are kept verbatim; each older result that is not already a placeholder is replaced by one newly appended `tool/result` carrying `{ surfaceOp: { op: 'replace', start: originalSeq, end: originalSeq }, sourceEventSeqs: [originalSeq] }`. The replacement spreads the complete original data and changes only `content`, preserving `turn`, `step`, `callId`, error fields, `meta`, and later data additions. The original event remains available for persistence, replay, and exact-log inspection.
12
+
13
+ Each replacement is immediately preceded by a `compaction/prune` shadow-price event pricing the shadowed node through the injected token meter, and followed by a `compaction/microcompact` decision record naming the shadowed `originalSeq`, the `replacementSeq`, the shared `callId`, and any re-embedded `spillLocator`. Together these keep the decision reconstructable from the log.
14
+
15
+ The method throws synchronously when the session rejects a replacement. Replacements committed earlier in the pass remain durable.
16
+
17
+ `isMicrocompactPlaceholder(blocks)` reports whether a content list already carries the placeholder marker; `reuseSpillLocator(text)` extracts a rendered spill-locator sentence for re-embedding.
18
+
19
+ ## Freeze semantics
20
+
21
+ The decision to collapse a tool result is made once and stays stable for the session. A placeholder always begins with the fixed `[... tool result compacted ...]` marker, and a later pass recognizes an already-collapsed result by that marker and never re-decides it. An identical re-run therefore emits a byte-identical prompt: repeated passes over unchanged history change nothing (the `stable` field is `true` and no replacement lands), preserving prompt-cache reuse.
22
+
23
+ ## Config
24
+
25
+ Unrecognized keys fail at plugin construction. Resolved config is detached and deeply immutable.
26
+
27
+ | Key | Required | Meaning |
28
+ |---|---|---|
29
+ | `retainResults` | no (default `10`) | Keep the most recent N tool results verbatim; older ones are eligible. |
30
+ | `auto` | no (default `false`) | Register an `agent/pre-step` hook that collapses stale results ahead of the turn's request. |
31
+ | `placeholderChars` | no (default `256`) | Maximum text code points in a generated placeholder (excluding a re-embedded spill locator). |
32
+
33
+ All values are integers; `retainResults` and `placeholderChars` are positive.
34
+
35
+ ## Usage
36
+
37
+ ```ts
38
+ import type { Context } from '@deepseek-ai/cordis'
39
+ import Microcompactor from '@jianxx/dsh-cc-compaction-micro'
40
+
41
+ export function apply(ctx: Context): void {
42
+ ctx.plugin(Microcompactor, { retainResults: 4 })
43
+ }
44
+ ```
45
+
46
+ ## Model Experience
47
+
48
+ ### Collapsed tool result
49
+
50
+ #### What the model sees
51
+
52
+ Out-of-window tool results appear as the deterministic placeholder. When the original cited a spilled artifact (e.g. `Full grep result stored at: …`), the placeholder re-embeds that locator sentence so the model can still read the full result.
53
+
54
+ #### Token effect
55
+
56
+ Each collapsed result is replaced by a placeholder of at most `placeholderChars` text code points. Microcompact makes no model call.
57
+
58
+ #### KV Cache effect
59
+
60
+ Replacing an earlier result invalidates reuse from the first changed token. The remaining prefix (including the verbatim tail window) is eligible for reuse while its route, envelope, and preceding history remain identical. Freezing the decision keeps repeated passes from re-invalidating the cache.
61
+
62
+ ## Known Limitations and Deferred Work
63
+
64
+ - **Window, not semantics** — a result is collapsed purely by surface age, not by how much the model still needs it.
65
+ - **Spill-locator reuse is best-effort** — it matches the rendered `stored at:` phrasing used by `dsh-tool-fs`-style spill footers; a tool that phrase the locator differently will not have it re-embedded.
66
+ - **Grapheme clusters can split** — placeholder truncation slices by code point, protecting surrogate pairs but not locale-aware grapheme segmentation.
package/README.zh.md ADDED
@@ -0,0 +1,66 @@
1
+ # @jianxx/dsh-cc-compaction-micro
2
+
3
+ [English](README.md) | 中文
4
+
5
+ 可安全回放、不依赖模型的微压缩(microcompact)服务(`ctx.microcompactor`)。它会原样保留最近的 `retainResults` 个 `tool/result` 表层节点,并将更早的节点替换为确定性的占位摘要;若原始结果引用了 spill 文件的 locator,占位摘要会重新嵌入该 locator——全程不发起模型调用,也不做摘要。
6
+
7
+ 这是 [`dsh-compaction-basic`](../compaction-basic/README.md) 的具体配套服务,不是压缩(compaction)后端。它在摘要之前合成运行,使摘要器读到已经过窗口收缩的表层。两个包仍可各自独立组合。
8
+
9
+ ## 服务 API
10
+
11
+ `microcompactSession(session)` 会扫描当前表层的一个稳定快照。最近的 `retainResults` 个工具结果被原样保留;每个更早的、尚未成为占位符的结果,都会被一个新追加的 `tool/result` 替换,其携带 `{ surfaceOp: { op: 'replace', start: originalSeq, end: originalSeq }, sourceEventSeqs: [originalSeq] }`。替换会展开完整原始数据,只更改 `content`,保留 `turn`、`step`、`callId`、错误字段、`meta` 以及以后新增的数据字段。原始事件仍可用于持久化、回放和精确日志检查。
12
+
13
+ 每次替换都紧接着一条 `compaction/prune` 影子价格事件(通过注入的 token meter 为被遮蔽节点定价),后面还跟一条 `compaction/microcompact` 决策记录,记录被遮蔽的 `originalSeq`、`replacementSeq`、共享的 `callId` 以及重新嵌入的 `spillLocator`。这些共同保证决策可从日志重建。
14
+
15
+ 当会话拒绝替换时,该方法会同步抛出异常。本次扫描中先前已提交的替换仍会保留。
16
+
17
+ `isMicrocompactPlaceholder(blocks)` 报告内容列表是否已携带占位符标记;`reuseSpillLocator(text)` 提取渲染出的 spill locator 句子以供重新嵌入。
18
+
19
+ ## 冻结语义
20
+
21
+ 将某个工具结果折叠的决策只做一次,并在会话内保持稳定。占位符始终以固定的 `[... tool result compacted ...]` 标记开头,后续扫描会依据该标记识别已折叠的结果,绝不再做二次决策。因此对未变化历史的重复执行会生成逐字节一致的提示:重复通过的表面上没有任何改变(`stable` 为 `true`,且不会落地任何替换),从而保持提示缓存的复用。
22
+
23
+ ## 配置
24
+
25
+ 无法识别的配置键会使插件在构造时失败。已解析配置与输入脱离,并且深度不可变。
26
+
27
+ | 配置键 | 必填 | 含义 |
28
+ |---|---|---|
29
+ | `retainResults` | 否(默认 `10`) | 原样保留最近的 N 个工具结果,更早的结果可被折叠。 |
30
+ | `auto` | 否(默认 `false`) | 注册一个 `agent/pre-step` 钩子,在回合请求之前折叠过期结果。 |
31
+ | `placeholderChars` | 否(默认 `256`) | 生成占位符的最大文本码点数(不包含重新嵌入的 spill locator)。 |
32
+
33
+ 所有值都必须是整数;`retainResults` 与 `placeholderChars` 必须为正数。
34
+
35
+ ## 用法
36
+
37
+ ```ts
38
+ import type { Context } from '@deepseek-ai/cordis'
39
+ import Microcompactor from '@jianxx/dsh-cc-compaction-micro'
40
+
41
+ export function apply(ctx: Context): void {
42
+ ctx.plugin(Microcompactor, { retainResults: 4 })
43
+ }
44
+ ```
45
+
46
+ ## 模型体验
47
+
48
+ ### 被折叠的工具结果
49
+
50
+ #### 模型看到的内容
51
+
52
+ 窗口外的工具结果显示为确定性占位符。若原始结果引用了 spill 产物(例如 `Full grep result stored at: …`),占位符会重新嵌入该 locator 句子,使模型仍能读取完整结果。
53
+
54
+ #### Token 影响
55
+
56
+ 每个被折叠结果都被替换为至多 `placeholderChars` 个文本码点的占位符。微压缩本身不发起模型调用。
57
+
58
+ #### KV Cache 影响
59
+
60
+ 替换较早的结果会使从第一个改变的 token 起的复用失效。剩余前缀(包括原样保留的窗口尾部)在路由、envelope 与之前历史保持不变的情况下可复用。冻结决策避免重复执行再次失效缓存。
61
+
62
+ ## 已知限制与暂缓事项
63
+
64
+ - **只按窗口、不看语义**:结果仅依据表层新旧程度折叠,而不考虑模型当前是否仍需要它。
65
+ - **spill locator 复用是尽力而为**:它匹配 `dsh-tool-fs` 类 spill 页脚使用的渲染 `stored at:` 措辞;若某个工具以不同措辞呈现 locator,则不会重新嵌入。
66
+ - **字素簇可能被拆分**:占位符截断按码点切片,可保护代理项对,但不执行感知区域设置的字素簇分割。
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Configuration resolution and placeholder vocabulary for microcompaction.
3
+ * @module @jianxx/dsh-cc-compaction-micro/config
4
+ */
5
+ import type { ResolvedConfig, MicrocompactConfig } from './types.ts';
6
+ /**
7
+ * Fixed marker that opens every microcompact placeholder. Its presence in a
8
+ * `tool/result` content's first text block is how a later pass recognizes an
9
+ * already-collapsed result, so the decision is idempotent and the prompt stays
10
+ * byte-identical across passes.
11
+ */
12
+ export declare const MICROCOMPACT_MARKER = "[... earlier tool result compacted ...]";
13
+ /**
14
+ * Textual lead-in for a re-embedded spill locator. When the original result
15
+ * cited a spilled artifact (e.g. "Full grep result stored at: <locator>."), the
16
+ * placeholder keeps that sentence so the model can still retrieve the full
17
+ * result from disk.
18
+ */
19
+ export declare const SPILL_LOCATOR_LEAD = "Full result still available at: ";
20
+ /** Low-friction defaults for a coding-agent session. */
21
+ export declare const DEFAULTS: ResolvedConfig;
22
+ /**
23
+ * Whether a content list already carries a microcompact placeholder as its
24
+ * first text block. Used for freeze/idempotence: an already-collapsed result is
25
+ * never re-decided, so consecutive passes emit byte-identical prompts.
26
+ * @param blocks - tool-result content to inspect.
27
+ * @returns true when the first text block starts with {@link MICROCOMPACT_MARKER}.
28
+ */
29
+ export declare function isMicrocompactPlaceholder(blocks: readonly {
30
+ type: string;
31
+ text?: string;
32
+ }[]): boolean;
33
+ /**
34
+ * Extract a spill locator sentence from tool-result text, when present. The
35
+ * placeholder re-embeds the first such locator so the full-result retrieval
36
+ * handle survives compaction (model-visible ⟺ logged: the locator line is
37
+ * carried verbatim into the replacement event, so it is reconstructable from
38
+ * the log).
39
+ * @param text - the original tool-result text.
40
+ * @returns the captured locator sentence, or `undefined` when none is found.
41
+ */
42
+ export declare function reuseSpillLocator(text: string): string | undefined;
43
+ /**
44
+ * Resolve and validate microcompact configuration.
45
+ * @param config - raw plugin configuration.
46
+ * @returns a detached deeply immutable configuration.
47
+ */
48
+ export declare function resolveConfig(config?: MicrocompactConfig): ResolvedConfig;
49
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,KAAK,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAA;AAEpE;;;;;GAKG;AACH,eAAO,MAAM,mBAAmB,4CAA4C,CAAA;AAE5E;;;;;GAKG;AACH,eAAO,MAAM,kBAAkB,qCAAqC,CAAA;AAUpE,wDAAwD;AACxD,eAAO,MAAM,QAAQ,EAAE,cAIrB,CAAA;AAQF;;;;;;GAMG;AACH,wBAAgB,yBAAyB,CAAC,MAAM,EAAE,SAAS;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAA;CAAE,EAAE,GAAG,OAAO,CAMrG;AAED;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAMlE;AAED;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,MAAM,GAAE,kBAAuB,GAAG,cAAc,CAkB7E"}
package/lib/config.js ADDED
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Configuration resolution and placeholder vocabulary for microcompaction.
3
+ * @module @jianxx/dsh-cc-compaction-micro/config
4
+ */
5
+ import { deepFreeze } from '@deepseek-ai/dsh-llm';
6
+ /**
7
+ * Fixed marker that opens every microcompact placeholder. Its presence in a
8
+ * `tool/result` content's first text block is how a later pass recognizes an
9
+ * already-collapsed result, so the decision is idempotent and the prompt stays
10
+ * byte-identical across passes.
11
+ */
12
+ export const MICROCOMPACT_MARKER = '[... earlier tool result compacted ...]';
13
+ /**
14
+ * Textual lead-in for a re-embedded spill locator. When the original result
15
+ * cited a spilled artifact (e.g. "Full grep result stored at: <locator>."), the
16
+ * placeholder keeps that sentence so the model can still retrieve the full
17
+ * result from disk.
18
+ */
19
+ export const SPILL_LOCATOR_LEAD = 'Full result still available at: ';
20
+ /**
21
+ * Best-effort matcher for a rendered spill-locator sentence in tool-result
22
+ * text. Tool renderers phrase saved artifacts as "…stored at: <locator>."; we
23
+ * capture the locator token(s) up to the first sentence end so the placeholder
24
+ * can reproduce the retrieval hint verbatim.
25
+ */
26
+ const SPILL_LOCATOR_PATTERN = /stored at:\s*([^.\n]+)[.\n]/;
27
+ /** Low-friction defaults for a coding-agent session. */
28
+ export const DEFAULTS = deepFreeze({
29
+ retainResults: 10,
30
+ auto: false,
31
+ placeholderChars: 256,
32
+ });
33
+ const CONFIG_KEYS = new Set([
34
+ 'retainResults',
35
+ 'auto',
36
+ 'placeholderChars',
37
+ ]);
38
+ /**
39
+ * Whether a content list already carries a microcompact placeholder as its
40
+ * first text block. Used for freeze/idempotence: an already-collapsed result is
41
+ * never re-decided, so consecutive passes emit byte-identical prompts.
42
+ * @param blocks - tool-result content to inspect.
43
+ * @returns true when the first text block starts with {@link MICROCOMPACT_MARKER}.
44
+ */
45
+ export function isMicrocompactPlaceholder(blocks) {
46
+ for (const block of blocks) {
47
+ if (block.type !== 'text')
48
+ continue;
49
+ return block.text === undefined ? false : block.text.startsWith(MICROCOMPACT_MARKER);
50
+ }
51
+ return false;
52
+ }
53
+ /**
54
+ * Extract a spill locator sentence from tool-result text, when present. The
55
+ * placeholder re-embeds the first such locator so the full-result retrieval
56
+ * handle survives compaction (model-visible ⟺ logged: the locator line is
57
+ * carried verbatim into the replacement event, so it is reconstructable from
58
+ * the log).
59
+ * @param text - the original tool-result text.
60
+ * @returns the captured locator sentence, or `undefined` when none is found.
61
+ */
62
+ export function reuseSpillLocator(text) {
63
+ const match = SPILL_LOCATOR_PATTERN.exec(text);
64
+ if (match === null)
65
+ return undefined;
66
+ const locator = match[1]?.trim();
67
+ if (locator === undefined || locator.length === 0)
68
+ return undefined;
69
+ return `${SPILL_LOCATOR_LEAD}${locator}.`;
70
+ }
71
+ /**
72
+ * Resolve and validate microcompact configuration.
73
+ * @param config - raw plugin configuration.
74
+ * @returns a detached deeply immutable configuration.
75
+ */
76
+ export function resolveConfig(config = {}) {
77
+ for (const key of Object.keys(config)) {
78
+ if (!CONFIG_KEYS.has(key)) {
79
+ throw new Error(`MicrocompactConfig: unknown key "${key}" `
80
+ + '(allowed: retainResults, auto, placeholderChars)');
81
+ }
82
+ }
83
+ const resolved = {
84
+ retainResults: config.retainResults ?? DEFAULTS.retainResults,
85
+ auto: config.auto ?? DEFAULTS.auto,
86
+ placeholderChars: config.placeholderChars ?? DEFAULTS.placeholderChars,
87
+ };
88
+ assertPositiveInteger('retainResults', resolved.retainResults);
89
+ assertPositiveInteger('placeholderChars', resolved.placeholderChars);
90
+ return deepFreeze(structuredClone(resolved));
91
+ }
92
+ function assertPositiveInteger(name, value) {
93
+ if (!Number.isInteger(value) || value <= 0) {
94
+ throw new Error(`MicrocompactConfig: ${name} (${value}) must be a positive integer`);
95
+ }
96
+ }
97
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAA;AAGjD;;;;;GAKG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,yCAAyC,CAAA;AAE5E;;;;;GAKG;AACH,MAAM,CAAC,MAA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CAAC;QACtC,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC;YAC1B,MAAM,IAAI,KAAK,CACb,oCAAoC,GAAG,IAAI;kBACzC,kDAAkD,CACrD,CAAA;QACH,CAAC;IACH,CAAC;IAED,MAAM,QAAQ,GAAmB;QAC/B,aAAa,EAAE,MAAM,CAAC,aAAa,IAAI,QAAQ,CAAC,aAAa;QAC7D,IAAI,EAAE,MAAM,CAAC,IAAI,IAAI,QAAQ,CAAC,IAAI;QAClC,gBAAgB,EAAE,MAAM,CAAC,gBAAgB,IAAI,QAAQ,CAAC,gBAAgB;KACvE,CAAA;IACD,qBAAqB,CAAC,eAAe,EAAE,QAAQ,CAAC,aAAa,CAAC,CAAA;IAC9D,qBAAqB,CAAC,kBAAkB,EAAE,QAAQ,CAAC,gBAAgB,CAAC,CAAA;IACpE,OAAO,UAAU,CAAC,eAAe,CAAC,QAAQ,CAAC,CAAC,CAAA;AAC9C,CAAC;AAED,SAAS,qBAAqB,CAAC,IAAY,EAAE,KAAa;IACxD,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC,EAAE,CAAC;QAC3C,MAAM,IAAI,KAAK,CAAC,uBAAuB,IAAI,KAAK,KAAK,8BAA8B,CAAC,CAAA;IACtF,CAAC;AACH,CAAC"}
package/lib/index.d.ts ADDED
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Replay-safe, model-free microcompaction of stale tool-result surface nodes.
3
+ *
4
+ * Unlike summarization, microcompaction never calls a model: it collapses only
5
+ * the oldest tool results (beyond a retention window) into deterministic
6
+ * placeholder text, re-embedding any spill locator the original cited so the
7
+ * full result stays retrievable. The decision is frozen per session — a second
8
+ * pass over unchanged history emits a byte-identical prompt — and every
9
+ * landed replacement is returned in the pass result (the placeholder marker
10
+ * makes it reconstructable from the log even without a companion event;
11
+ * out-of-repo plugins cannot extend the upstream session vocabulary).
12
+ *
13
+ * @module @jianxx/dsh-cc-compaction-micro
14
+ */
15
+ import { Context, Service } from '@deepseek-ai/cordis';
16
+ import z from '@deepseek-ai/schemastery';
17
+ import type { Session } from '@deepseek-ai/dsh-session';
18
+ import type { MicrocompactConfig, MicrocompactResult, ResolvedConfig } from './types.ts';
19
+ export { DEFAULTS, MICROCOMPACT_MARKER, isMicrocompactPlaceholder, reuseSpillLocator, resolveConfig } from './config.ts';
20
+ export type { MicrocompactConfig, MicrocompactEntry, MicrocompactResult, ResolvedConfig, } from './types.ts';
21
+ declare module '@deepseek-ai/cordis' {
22
+ interface Context {
23
+ microcompactor: Microcompactor;
24
+ }
25
+ }
26
+ /**
27
+ * Model-free retention-window microcompaction service. Keeps the most recent
28
+ * {@link MicrocompactConfig.retainResults} tool results verbatim and replaces
29
+ * every older one with a deterministic placeholder that reuses the original
30
+ * spill locator when one was cited. Each replacement preserves the complete
31
+ * event data except for `content`, cites the shadowed node for replay, and is
32
+ * immediately preceded by a `compaction/prune` shadow-price event pricing the
33
+ * shadowed node through the injected token meter — mirroring the sibling
34
+ * `ToolResultPruner` shadow-price protocol.
35
+ */
36
+ export declare class Microcompactor extends Service {
37
+ static inject: string[];
38
+ static Config: z<MicrocompactConfig>;
39
+ /** Resolved and immutable policy. */
40
+ readonly config: ResolvedConfig;
41
+ constructor(ctx: Context, config?: MicrocompactConfig);
42
+ /**
43
+ * Register an `agent/pre-step` hook that collapses stale tool results ahead
44
+ * of the turn's request, so compaction-basic's summarizer reads an already
45
+ * window-reduced surface. Enabled only when `auto: true`.
46
+ */
47
+ private _registerAutomaticMicrocompact;
48
+ /**
49
+ * Collapse every out-of-window tool result from one stable current-surface
50
+ * snapshot. The most recent `retainResults` tool results are kept verbatim;
51
+ * each older result that is not already a placeholder is replaced by a
52
+ * deterministic placeholder (reusing the original's spill locator when one is
53
+ * cited). Already-collapsed results are never re-decided, so a repeated pass
54
+ * over unchanged history emits a byte-identical prompt (freeze semantics).
55
+ * @param session - session whose current surface is rewritten.
56
+ * @returns landed placeholder replacements and a stability flag.
57
+ * @throws when the session rejects a replacement; replacements committed
58
+ * earlier in the pass remain durable.
59
+ */
60
+ microcompactSession(session: Session): MicrocompactResult;
61
+ /** Deterministic placeholder body for one collapsed tool result. */
62
+ private placeholderContent;
63
+ }
64
+ export default Microcompactor;
65
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AACtD,OAAO,CAAC,MAAM,0BAA0B,CAAA;AAGxC,OAAO,KAAK,EAAE,OAAO,EAAmC,MAAM,0BAA0B,CAAA;AAYxF,OAAO,KAAK,EACV,kBAAkB,EAElB,kBAAkB,EAClB,cAAc,EACf,MAAM,YAAY,CAAA;AAEnB,OAAO,EAAE,QAAQ,EAAE,mBAAmB,EAAE,yBAAyB,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AACxH,YAAY,EACV,kBAAkB,EAClB,iBAAiB,EACjB,kBAAkB,EAClB,cAAc,GACf,MAAM,YAAY,CAAA;AAEnB,OAAO,QAAQ,qBAAqB,CAAC;IACnC,UAAU,OAAO;QACf,cAAc,EAAE,cAAc,CAAA;KAC/B;CACF;AAUD;;;;;;;;;GASG;AACH,qBAAa,cAAe,SAAQ,OAAO;IAGzC,MAAM,CAAC,MAAM,WAAiB;IAE9B,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,kBAAkB,CAAC,CAIlC;IAEF,qCAAqC;IACrC,QAAQ,CAAC,MAAM,EAAE,cAAc,CAAA;gBAEnB,GAAG,EAAE,OAAO,EAAE,MAAM,GAAE,kBAAuB;IAMzD;;;;OAIG;IACH,OAAO,CAAC,8BAA8B;IAwBtC;;;;;;;;;;;OAWG;IACH,mBAAmB,CAAC,OAAO,EAAE,OAAO,GAAG,kBAAkB;IAwDzD,oEAAoE;IACpE,OAAO,CAAC,kBAAkB;CAS3B;AAiCD,eAAe,cAAc,CAAA"}
package/lib/index.js ADDED
@@ -0,0 +1,181 @@
1
+ /**
2
+ * Replay-safe, model-free microcompaction of stale tool-result surface nodes.
3
+ *
4
+ * Unlike summarization, microcompaction never calls a model: it collapses only
5
+ * the oldest tool results (beyond a retention window) into deterministic
6
+ * placeholder text, re-embedding any spill locator the original cited so the
7
+ * full result stays retrievable. The decision is frozen per session — a second
8
+ * pass over unchanged history emits a byte-identical prompt — and every
9
+ * landed replacement is returned in the pass result (the placeholder marker
10
+ * makes it reconstructable from the log even without a companion event;
11
+ * out-of-repo plugins cannot extend the upstream session vocabulary).
12
+ *
13
+ * @module @jianxx/dsh-cc-compaction-micro
14
+ */
15
+ import { Service } from '@deepseek-ai/cordis';
16
+ import z from '@deepseek-ai/schemastery';
17
+ import { freezeMessage } from '@deepseek-ai/dsh-llm';
18
+ import { MICROCOMPACT_MARKER, isMicrocompactPlaceholder, resolveConfig, reuseSpillLocator, } from "./config.js";
19
+ export { DEFAULTS, MICROCOMPACT_MARKER, isMicrocompactPlaceholder, reuseSpillLocator, resolveConfig } from "./config.js";
20
+ const keepSchema = z.number().step(1).min(1);
21
+ const placeholderCharsSchema = z.number().step(1).min(1);
22
+ /**
23
+ * Model-free retention-window microcompaction service. Keeps the most recent
24
+ * {@link MicrocompactConfig.retainResults} tool results verbatim and replaces
25
+ * every older one with a deterministic placeholder that reuses the original
26
+ * spill locator when one was cited. Each replacement preserves the complete
27
+ * event data except for `content`, cites the shadowed node for replay, and is
28
+ * immediately preceded by a `compaction/prune` shadow-price event pricing the
29
+ * shadowed node through the injected token meter — mirroring the sibling
30
+ * `ToolResultPruner` shadow-price protocol.
31
+ */
32
+ export class Microcompactor extends Service {
33
+ // The token meter prices each shadowed node for its logged shadow-price
34
+ // event, so retainer-based pressure genuinely requires the pricing capability.
35
+ static inject = ['tokenMeter'];
36
+ static Config = z.object({
37
+ retainResults: keepSchema,
38
+ auto: z.boolean(),
39
+ placeholderChars: placeholderCharsSchema,
40
+ });
41
+ /** Resolved and immutable policy. */
42
+ config;
43
+ constructor(ctx, config = {}) {
44
+ super(ctx, 'microcompactor');
45
+ this.config = resolveConfig(config);
46
+ if (this.config.auto)
47
+ this._registerAutomaticMicrocompact();
48
+ }
49
+ /**
50
+ * Register an `agent/pre-step` hook that collapses stale tool results ahead
51
+ * of the turn's request, so compaction-basic's summarizer reads an already
52
+ * window-reduced surface. Enabled only when `auto: true`.
53
+ */
54
+ _registerAutomaticMicrocompact() {
55
+ const { ctx } = this;
56
+ ctx.on('agent/pre-step', async ({ agent, signal }, next) => {
57
+ if (!signal.aborted) {
58
+ try {
59
+ const result = this.microcompactSession(agent.session);
60
+ if (result.replaced.length > 0) {
61
+ ctx.logger.info(`microcompact: collapsed ${result.replaced.length} stale tool result(s) `
62
+ + `(retain ${this.config.retainResults})`);
63
+ }
64
+ }
65
+ catch (error) {
66
+ const message = error instanceof Error ? error.message : String(error);
67
+ ctx.logger.warn(`microcompact failed: ${message}; continuing the turn`);
68
+ }
69
+ }
70
+ return next();
71
+ });
72
+ }
73
+ /**
74
+ * Collapse every out-of-window tool result from one stable current-surface
75
+ * snapshot. The most recent `retainResults` tool results are kept verbatim;
76
+ * each older result that is not already a placeholder is replaced by a
77
+ * deterministic placeholder (reusing the original's spill locator when one is
78
+ * cited). Already-collapsed results are never re-decided, so a repeated pass
79
+ * over unchanged history emits a byte-identical prompt (freeze semantics).
80
+ * @param session - session whose current surface is rewritten.
81
+ * @returns landed placeholder replacements and a stability flag.
82
+ * @throws when the session rejects a replacement; replacements committed
83
+ * earlier in the pass remain durable.
84
+ */
85
+ microcompactSession(session) {
86
+ const candidates = snapshotCandidates(session);
87
+ const retainedFrom = Math.max(0, candidates.length - this.config.retainResults);
88
+ const replaced = [];
89
+ for (const candidate of candidates.slice(0, retainedFrom)) {
90
+ const { seq, event } = candidate;
91
+ const message = event.data.message;
92
+ const content = message.content[0];
93
+ const resultBlock = content?.type === 'tool-result' ? content : undefined;
94
+ const blocks = resultBlock?.content ?? [];
95
+ if (isMicrocompactPlaceholder(blocks))
96
+ continue;
97
+ const locatorLine = reuseSpillLocator(plainText(blocks));
98
+ const placeholder = this.placeholderContent(locatorLine);
99
+ // Preserve every non-content field of the original tool-result block (type,
100
+ // toolCallId, isError, plus future additions) so the surface rewrite honors
101
+ // the "may change only content" invariant.
102
+ const replacementBlock = resultBlock === undefined
103
+ ? { type: 'tool-result', toolCallId: message.source.callId, content: [{ type: 'text', text: placeholder }] }
104
+ : { ...resultBlock, content: [{ type: 'text', text: placeholder }] };
105
+ const replacementMessage = freezeMessage({
106
+ ...message,
107
+ content: [replacementBlock],
108
+ });
109
+ // Shadow-price protocol: the metering event and its replacement are
110
+ // appended synchronously adjacent so a pure consumer subtracts the
111
+ // shadowed node's heuristic price without retaining per-node state.
112
+ session.append('compaction/prune', {
113
+ shadowedRange: { start: seq, end: seq },
114
+ shadowedSeqs: [seq],
115
+ shadowedTokenCount: this.ctx.tokenMeter.estimateMessage(message),
116
+ });
117
+ const replacement = session.append('tool/result', {
118
+ ...event.data,
119
+ message: replacementMessage,
120
+ }, {
121
+ surfaceOp: { op: 'replace', start: seq, end: seq },
122
+ sourceEventSeqs: [seq],
123
+ });
124
+ // Decision metadata stays in the returned pass result only: out-of-repo
125
+ // plugins cannot extend the upstream session event vocabulary, so the
126
+ // fork's log-only `compaction/microcompact` record is intentionally not
127
+ // appended. The placeholder content already carries the deterministic
128
+ // marker, so the decision reconstructs from replay + code alone.
129
+ replaced.push({
130
+ originalSeq: seq,
131
+ replacementSeq: replacement.seq,
132
+ callId: message.source.callId,
133
+ ...(locatorLine === undefined ? {} : { spillLocator: locatorLine }),
134
+ });
135
+ }
136
+ return { replaced, stable: replaced.length === 0 };
137
+ }
138
+ /** Deterministic placeholder body for one collapsed tool result. */
139
+ placeholderContent(locatorLine) {
140
+ const markerText = `${MICROCOMPACT_MARKER} (tool result collapsed by microcompact; `
141
+ + 'the call id and human retrieval remain available in the session log)';
142
+ if (locatorLine === undefined || locatorLine.length === 0) {
143
+ return shrinkPlaceholder(markerText, this.config.placeholderChars);
144
+ }
145
+ const combined = `${markerText}\n${locatorLine}`;
146
+ return shrinkPlaceholder(combined, this.config.placeholderChars + locatorLine.length);
147
+ }
148
+ }
149
+ /** Collect a stable surface-order snapshot of current `tool/result` nodes. */
150
+ function snapshotCandidates(session) {
151
+ const candidates = [];
152
+ for (const seq of [...session.surface.nodes]) {
153
+ const event = session.events[seq];
154
+ /* v8 ignore next -- surface seqs are validated contiguous log references. */
155
+ if (event?.type === 'tool/result')
156
+ candidates.push({ seq, event });
157
+ }
158
+ return candidates;
159
+ }
160
+ /** Concatenate text from `text`-typed content blocks (code points). */
161
+ function plainText(blocks) {
162
+ let out = '';
163
+ for (const block of blocks) {
164
+ if (block.type === 'text')
165
+ out += block.text;
166
+ }
167
+ return out;
168
+ }
169
+ /**
170
+ * Bound a placeholder to at most `cap` code points without splitting a
171
+ * surrogate pair (grapheme clusters may still split). The marker prefix is
172
+ * always kept so the result remains a recognizable placeholder.
173
+ */
174
+ function shrinkPlaceholder(text, cap) {
175
+ const points = Array.from(text);
176
+ if (points.length <= cap)
177
+ return text;
178
+ return points.slice(0, cap).join('');
179
+ }
180
+ export default Microcompactor;
181
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAW,OAAO,EAAE,MAAM,qBAAqB,CAAA;AACtD,OAAO,CAAC,MAAM,0BAA0B,CAAA;AACxC,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAA;AAQpD,OAAO,EACL,mBAAmB,EACnB,yBAAyB,EACzB,aAAa,EACb,iBAAiB,GAClB,MAAM,aAAa,CAAA;AAQpB,OAAO,EAAE,QAAQ,EAAE,mBAAmB,EAAE,yBAAyB,EAAE,iBAAi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AAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAA;QACjC,6EAA6E;QAC7E,IAAI,KAAK,EAAE,IAAI,KAAK,aAAa;YAAE,UAAU,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,KAAK,EAAE,CAAC,CAAA;IACpE,CAAC;IACD,OAAO,UAAU,CAAA;AACnB,CAAC;AAED,uEAAuE;AACvE,SAAS,SAAS,CAAC,MAA+B;IAChD,IAAI,GAAG,GAAG,EAAE,CAAA;IACZ,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;QAC3B,IAAI,KAAK,CAAC,IAAI,KAAK,MAAM;YAAE,GAAG,IAAI,KAAK,CAAC,IAAI,CAAA;IAC9C,CAAC;IACD,OAAO,GAAG,CAAA;AACZ,CAAC;AAED;;;;GAIG;AACH,SAAS,iBAAiB,CAAC,IAAY,EAAE,GAAW;IAClD,MAAM,MAAM,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;IAC/B,IAAI,MAAM,CAAC,MAAM,IAAI,GAAG;QAAE,OAAO,IAAI,CAAA;IACrC,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;AACtC,CAAC;AAED,eAAe,cAAc,CAAA"}
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Package-owned invariant companion for `@jianxx/dsh-cc-compaction-micro`.
3
+ * @module @jianxx/dsh-cc-compaction-micro/invariant
4
+ */
5
+ import type { Context } from '@deepseek-ai/cordis';
6
+ /** Cordis companion plugin name. */
7
+ export declare const name = "compaction-micro-invariant";
8
+ /** Services required before the companion can register. */
9
+ export declare const inject: string[];
10
+ /**
11
+ * Register this package's invariant companion.
12
+ * @param ctx - Cordis context carrying the invariant service.
13
+ * @returns the installed registration's disposer after setup succeeds.
14
+ */
15
+ export declare const apply: (ctx: Context) => Promise<() => void>;
16
+ //# sourceMappingURL=invariant.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"invariant.d.ts","sourceRoot":"","sources":["../src/invariant.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AAKlD,oCAAoC;AACpC,eAAO,MAAM,IAAI,+BAA+B,CAAA;AAChD,2DAA2D;AAC3D,eAAO,MAAM,MAAM,UAAiB,CAAA;AAUpC;;;;GAIG;AACH,eAAO,MAAM,KAAK,GAAI,KAAK,OAAO,KAAG,OAAO,CAAC,MAAM,IAAI,CACU,CAAA"}
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Package-owned invariant companion for `@jianxx/dsh-cc-compaction-micro`.
3
+ * @module @jianxx/dsh-cc-compaction-micro/invariant
4
+ */
5
+ const PACKAGE_NAME = '@jianxx/dsh-cc-compaction-micro';
6
+ /** Cordis companion plugin name. */
7
+ export const name = 'compaction-micro-invariant';
8
+ /** Services required before the companion can register. */
9
+ export const inject = ['invariants'];
10
+ /**
11
+ * No runtime invariant: Session validates each content-only rewrite, and the
12
+ * freeze/idempotence contract (a collapsed placeholder is never re-decided) is
13
+ * enforced at the source by {@link isMicrocompactPlaceholder} marker detection
14
+ * rather than a cross-event postcondition.
15
+ */
16
+ const install = () => { };
17
+ /**
18
+ * Register this package's invariant companion.
19
+ * @param ctx - Cordis context carrying the invariant service.
20
+ * @returns the installed registration's disposer after setup succeeds.
21
+ */
22
+ export const apply = (ctx) => Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install));
23
+ /* jscpd:ignore-end */
24
+ //# sourceMappingURL=invariant.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"invariant.js","sourceRoot":"","sources":["../src/invariant.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAMH,MAAM,YAAY,GAAG,iCAAiC,CAAA;AAEtD,oCAAoC;AACpC,MAAM,CAAC,MAAM,IAAI,GAAG,4BAA4B,CAAA;AAChD,2DAA2D;AAC3D,MAAM,CAAC,MAAM,MAAM,GAAG,CAAC,YAAY,CAAC,CAAA;AAEpC;;;;;GAKG;AACH,MAAM,OAAO,GAAuB,GAAG,EAAE,GAAE,CAAC,CAAA;AAE5C;;;;GAIG;AACH,MAAM,CAAC,MAAM,KAAK,GAAG,CAAC,GAAY,EAAuB,EAAE,CACzD,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,QAAQ,CAAC,YAAY,EAAE,OAAO,CAAC,CAAC,CAAA;AACjE,sBAAsB"}
package/lib/types.d.ts ADDED
@@ -0,0 +1,47 @@
1
+ import type { CallId } from '@deepseek-ai/dsh-llm';
2
+ /**
3
+ * Microcompact policy: how many of the most recent `tool/result` surface nodes
4
+ * are retained verbatim, everything older being eligible for a placeholder
5
+ * replacement.
6
+ */
7
+ export interface MicrocompactConfig {
8
+ /** Keep the most recent N tool results verbatim. Defaults to `10`. */
9
+ retainResults?: number;
10
+ /**
11
+ * Register an `agent/pre-step` hook that runs the microcompact pass before
12
+ * the turn's model request, so stale results are collapsed ahead of
13
+ * summarization. Defaults to `false` (invoke {@link ToolResultMicrocompactor.microcompactSession} explicitly).
14
+ */
15
+ auto?: boolean;
16
+ /** Maximum text code points in a generated placeholder (excluding a re-embedded spill locator). Defaults to `256`. */
17
+ placeholderChars?: number;
18
+ }
19
+ /** Validated, detached, deeply immutable microcompact configuration. */
20
+ export interface ResolvedConfig {
21
+ readonly retainResults: number;
22
+ readonly auto: boolean;
23
+ readonly placeholderChars: number;
24
+ }
25
+ /** One landed placeholder replacement during a microcompact pass. */
26
+ export interface MicrocompactEntry {
27
+ /** Full-fidelity tool-result surface seq shadowed by the placeholder. */
28
+ readonly originalSeq: number;
29
+ /** Newly appended placeholder tool-result surface seq. */
30
+ readonly replacementSeq: number;
31
+ /** Tool call shared by the original and the placeholder. */
32
+ readonly callId: CallId;
33
+ /** Spill locator re-embedded into the placeholder, when the original cited one. */
34
+ readonly spillLocator?: string;
35
+ }
36
+ /** Aggregate outcome of one stable-surface microcompact pass. */
37
+ export interface MicrocompactResult {
38
+ /** Placeholder replacements in the snapshotted surface order. */
39
+ readonly replaced: readonly MicrocompactEntry[];
40
+ /**
41
+ * Whether this pass changed nothing — every out-of-window result was already
42
+ * a placeholder or within the retention window, so an identical re-run emits
43
+ * a byte-identical prompt.
44
+ */
45
+ readonly stable: boolean;
46
+ }
47
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAA;AAElD;;;;GAIG;AACH,MAAM,WAAW,kBAAkB;IACjC,sEAAsE;IACtE,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB;;;;OAIG;IACH,IAAI,CAAC,EAAE,OAAO,CAAA;IACd,sHAAsH;IACtH,gBAAgB,CAAC,EAAE,MAAM,CAAA;CAC1B;AAED,wEAAwE;AACxE,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAA;IAC9B,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAA;IACtB,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAA;CAClC;AAED,qEAAqE;AACrE,MAAM,WAAW,iBAAiB;IAChC,yEAAyE;IACzE,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAA;IAC5B,0DAA0D;IAC1D,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAA;IAC/B,4DAA4D;IAC5D,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,mFAAmF;IACnF,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAA;CAC/B;AAED,iEAAiE;AACjE,MAAM,WAAW,kBAAkB;IACjC,iEAAiE;IACjE,QAAQ,CAAC,QAAQ,EAAE,SAAS,iBAAiB,EAAE,CAAA;IAC/C;;;;OAIG;IACH,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAA;CACzB"}
package/lib/types.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "@jianxx/dsh-cc-compaction-micro",
3
+ "description": "Replay-safe model-free microcompaction of stale tool-result surface nodes",
4
+ "version": "0.1.0",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/jianxx/dsh-cc-plugins.git",
8
+ "directory": "packages/compaction/compaction-micro"
9
+ },
10
+ "type": "module",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./lib/index.d.ts",
14
+ "default": "./lib/index.js"
15
+ },
16
+ "./invariant": {
17
+ "types": "./lib/invariant.d.ts",
18
+ "default": "./lib/invariant.js"
19
+ },
20
+ "./src/*": "./src/*",
21
+ "./package.json": "./package.json"
22
+ },
23
+ "files": [
24
+ "lib"
25
+ ],
26
+ "license": "Apache-2.0",
27
+ "peerDependencies": {
28
+ "@deepseek-ai/dsh-agent": ">=0.1.1-rc.2",
29
+ "@deepseek-ai/dsh-compaction": ">=0.1.1-rc.2",
30
+ "@deepseek-ai/dsh-invariants": ">=0.1.1-rc.2",
31
+ "@deepseek-ai/dsh-llm": ">=0.1.1-rc.2",
32
+ "@deepseek-ai/dsh-session": ">=0.1.1-rc.2",
33
+ "@deepseek-ai/dsh-token-meter": ">=0.1.1-rc.2",
34
+ "@deepseek-ai/cordis": ">=0.1.1-rc.2",
35
+ "@deepseek-ai/schemastery": "^3.18.1"
36
+ },
37
+ "devDependencies": {
38
+ "@deepseek-ai/dsh-agent": "link:../../../../deepseek-harness/packages/core/agent",
39
+ "@deepseek-ai/cordis-plugin-include": "link:../../../../deepseek-harness/vendor/include",
40
+ "@deepseek-ai/cordis-plugin-loader": "link:../../../../deepseek-harness/vendor/loader",
41
+ "@deepseek-ai/dsh-compaction": "link:../../../../deepseek-harness/packages/compaction/compaction",
42
+ "@deepseek-ai/dsh-invariants": "link:../../../../deepseek-harness/packages/runtime-diagnostics/invariants",
43
+ "@deepseek-ai/dsh-llm": "link:../../../../deepseek-harness/packages/llm/llm",
44
+ "@deepseek-ai/dsh-session": "link:../../../../deepseek-harness/packages/core/session",
45
+ "@deepseek-ai/dsh-token-meter": "link:../../../../deepseek-harness/packages/llm/token-meter",
46
+ "@deepseek-ai/cordis": "link:../../../../deepseek-harness/vendor/cordis",
47
+ "@deepseek-ai/schemastery": "link:../../../../deepseek-harness/vendor/schemastery"
48
+ },
49
+ "publishConfig": {
50
+ "access": "public"
51
+ }
52
+ }