dsh-echo-guard 0.0.0-stage → 0.2.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 dsh-echo-guard contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.en.md ADDED
@@ -0,0 +1,131 @@
1
+ # dsh-echo-guard
2
+
3
+ [![npm](https://img.shields.io/npm/v/dsh-echo-guard)](https://www.npmjs.com/package/dsh-echo-guard)
4
+ [![license](https://img.shields.io/npm/l/dsh-echo-guard)](./LICENSE)
5
+
6
+ A DeepSeek Harness (DSH) plugin that removes filler-word flooding from the **model-visible reasoning history** — and leaves everything else verbatim.
7
+
8
+ ## What it treats
9
+
10
+ In long sessions, reasoning degrades into stamping: one closing word after every sentence — «好。» «好。» «好。» … until the reasoning holds nothing else and the actual reply never gets written.
11
+
12
+ That is not the model getting worse. It is **over-confirmation under pressure**: the model revises a sentence, confirms the revision, the confirmation spawns another action, and so on. And the history is full of those samples, so the next turn copies them.
13
+
14
+ Worse, DSH sends historical `reasoning` blocks back upstream, so the loop is not confined to that one step: it stays in context and replays every step, every turn.
15
+
16
+ ## What it does
17
+
18
+ When filler words appear ≥ N times (default 5) in one reasoning block:
19
+
20
+ 1. **Only standalone occurrences are removed** — «好。», «好,»; occurrences inside words («好像», «刚好») stay;
21
+ 2. **everything else is kept verbatim**;
22
+ 3. a **one-line receipt** is left in the visible history (configurable — including empty or zero-width).
23
+
24
+ The event log is never modified, so "what the model remembers" and "what the log says" can both be true.
25
+
26
+ ## What it does not do
27
+
28
+ - **It does not fold** whole repeated blocks. That is thinking-guard's job in [dsh-degeneration-kit](https://github.com/walksls/dsh-degeneration-kit). The two can run together: this plugin only touches **pure-reasoning steps with no tool calls**, leaving steps with tool calls to the other one, so they never rewrite the same node.
29
+ - **It does not save money.** Removing a handful of characters barely changes token count (90–97% remains). Its value is stopping the history from teaching the model to keep looping.
30
+
31
+ ## Install
32
+
33
+ From npm:
34
+
35
+ ```bash
36
+ pnpm add dsh-echo-guard
37
+ ```
38
+
39
+ Or install it from the DSH plugin manager with the spec `dsh-echo-guard@^0.2.0`.
40
+
41
+ For local development use `link:`: add a `link:` dependency to the profile's `package.json` and include it in `dsh.profile.bundles`.
42
+
43
+ Configure via `cordis.patch.yml`. **Start with `dryRun: true`** for a day.
44
+
45
+ ## Fillers
46
+
47
+ ```yaml
48
+ fillers: ["好", "嗯"] # Chinese
49
+ fillers: ["OK", "let me go"] # English, case-insensitive
50
+ ```
51
+
52
+ - **Counting** includes occurrences inside words (`好` inside `好像`, `OK` inside `Okay`).
53
+ - **Deletion** only removes standalone ones: preceded by a non-word char, followed by punctuation/space/EOL.
54
+ - CJK uses character boundaries, Latin uses alphanumeric boundaries; multi-word phrases are removed whole.
55
+
56
+ ### Per-word thresholds (0.2.0)
57
+
58
+ ```yaml
59
+ fillers: ["好", "嗯"]
60
+ fillerMinCounts:
61
+ "好": 5
62
+ "嗯": 3
63
+ burstMinCount: 5 # fallback for words without their own threshold
64
+ ```
65
+
66
+ Each word is counted and judged on its own; they never add up. `好` ×4 + `嗯` ×2 is **not** a hit, because neither reached its line. If only one word crosses, only that word is removed.
67
+
68
+ ## Manual pass: clear the last turn (0.2.0)
69
+
70
+ The automatic pass waits for the count. `/strip-last` clears the previous turn right now, in the session you type it in. Other processes (a phone UI, a bot) can drop a request file instead; the plugin writes `.result.json` back.
71
+
72
+ ```yaml
73
+ manual:
74
+ enabled: true
75
+ requestFile: "C:\\Users\\you\\.dsh\\strip-last.json" # omit = slash command only
76
+ ```
77
+
78
+ Three boundaries: only the **most recent pure-reasoning step**; never a tool-call step; and **never the turn that is currently running** — replacing a message that is still streaming would orphan its tool result and break the transcript.
79
+
80
+ ## Receipt
81
+
82
+ - `receipt: "⟪已整理⟫"` — visible (default);
83
+ - `receipt: ""` — nothing. **Not recommended**: an invisible edit is a forged history; the reader eventually assumes the text was always there;
84
+ - `receipt: "\u200B\u200B\u200B"` — invisible but greppable by code point.
85
+
86
+ ## Measured on 1000+ real reasoning blocks
87
+
88
+ - occurrences per block: median 1, P90 = 4, P99 = 12, ≥5 in only 7%;
89
+ - position: first 10% holds 2%, **last 20% holds 40%** — a closing move, not an opening habit;
90
+ - the worst collapses were all above ~200k tokens; compaction removed them instantly. **Context amplifies, it does not cause.**
91
+
92
+ Hence the threshold of 5, aimed at the "one per sentence" drift.
93
+
94
+
95
+ ## Version and testing
96
+
97
+ **Version 0.2.0.** (0.1.0 → 0.2.0: per-word thresholds; manual `/strip-last` and request-file entry; the manual path never touches a running step.)
98
+
99
+ Verified on 2026-12-05 with:
100
+
101
+ - DSH 0.2.2-rc.5 (Windows)
102
+ - Node 24.22.1
103
+ - Method: `dryRun: true` for one pass → 5 reasoning blocks matched in the log; then `dryRun: false` → all 5 were actually rewritten.
104
+ - Checked item by item:
105
+ - replacement messages carry id `echo-guard-<seq>` and source `plugin:echo-guard`, starting with the receipt;
106
+ - the original `assistant/message` events remain in the event stream, untouched;
107
+ - all 5 matches were "reasoning + text" steps with zero tool calls — steps with tool calls are skipped by design;
108
+ - the other session's file was never written (`onlySessions` respected).
109
+ - Unit tests: `node --test test/core.test.mjs` — 10 cases pass.
110
+
111
+ **Not verified**: the case where both this plugin and thinking-guard match the same step. They do not overlap by design (steps with tool calls are skipped here), but that scenario was not exercised.
112
+
113
+ ## Limitations
114
+
115
+ - DSH only; built on `session.append` + `surfaceOp`.
116
+ - Steps with tool calls are skipped by design.
117
+ - Tokenizers may swallow invisible characters — measure before using a zero-width receipt.
118
+
119
+ ## Test
120
+
121
+ ```bash
122
+ npm test
123
+ ```
124
+
125
+ ## Credits
126
+
127
+ Host API usage was learned from [dsh-degeneration-kit](https://github.com/walksls/dsh-degeneration-kit) by walksls (MIT) — same problem, same API. The code here is rewritten and keeps only the strip behaviour.
128
+
129
+ ## License
130
+
131
+ MIT.
package/README.md CHANGED
@@ -1,3 +1,151 @@
1
- # Temporary Holding Version
1
+ # dsh-echo-guard
2
2
 
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.
3
+ [![npm](https://img.shields.io/npm/v/dsh-echo-guard)](https://www.npmjs.com/package/dsh-echo-guard)
4
+ [![license](https://img.shields.io/npm/l/dsh-echo-guard)](./LICENSE)
5
+
6
+ 一个 DeepSeek Harness(DSH)插件:把「收束词灌水」从**模型可见的思考历史**里删掉,其余一个字不动。
7
+
8
+ ## 它治什么
9
+
10
+ 长对话跑久了,模型的思考里会出现一种退化:每句话后面盖个章——「好。」「好。」「好。」……
11
+
12
+ 整段思考最后只剩那个字,正文反而没发出来。
13
+
14
+ 这不是模型变笨,是**高压下的过度确认**:它每改一版就自我确认一次,确认动作又生出新动作,越确认越多。而历史里全是这种样本,下一轮它照着学。
15
+
16
+ 更麻烦的是:DSH 会把历史里的 `reasoning` 块回传给上游,所以这段复读不只是"这一步废了"——它留在上下文里,之后每一步、每一轮都带着它重放。
17
+
18
+ ## 它做什么
19
+
20
+ 一段思考里,收束词累计 ≥ N 次(默认 5)时:
21
+
22
+ 1. **只删单独成句的那几个**——「好。」「好,」;词里的(「好像」「刚好」「挺好」)留着;
23
+ 2. **其余原文照录**,一个字不改;
24
+ 3. 在可见历史里留**一行回执**(可配,也可以设成零宽字符或留空)。
25
+
26
+ 事件流一个字不动。所以「模型记得什么」和「日志里写的是什么」可以同时对。
27
+
28
+ ## 它不做什么
29
+
30
+ - **不折叠**整段复读。那是 [dsh-degeneration-kit](https://github.com/walksls/dsh-degeneration-kit) 里 thinking-guard 的活,两个插件可以同时装:本插件只处理**没有工具调用的纯思考步**,带工具调用的整步留给它,互不抢同一段改写。
31
+ - **不省钱**。删几个字,token 几乎不变(实测剩下 90%~97%)。它的价值是"不再拿这些当示范教模型",不是省 token。
32
+
33
+ ## 装法
34
+
35
+ 从 npm 装:
36
+
37
+ ```bash
38
+ pnpm add dsh-echo-guard
39
+ ```
40
+
41
+ 在 DSH 的插件管理器里装也行,spec 写 `dsh-echo-guard@^0.2.0`。
42
+
43
+ 本地改代码时用 `link:`:在 profile 的 `package.json` 里加一条 `link:` 依赖,并把它加进 `dsh.profile.bundles`。
44
+
45
+ 配置见 `cordis.patch.yml`。
46
+
47
+ **第一次建议 `dryRun: true`**,跑一天看日志里命中多少、删掉多少,再决定阈值。
48
+
49
+ ## 词表
50
+
51
+ ```yaml
52
+ fillers: ["好", "嗯"] # 中文
53
+ fillers: ["OK", "let me go"] # 英文,大小写不敏感
54
+ ```
55
+
56
+ 规则:
57
+
58
+ - **计数**算全部:`好` 会数进「好像」,`OK` 会数进 `Okay`。
59
+ - **删除**只删单独成句的:前面不是词、后面是标点/空白/行尾。
60
+ - 中文按汉字边界判,英文按字母数字边界判;多词短语(`let me go`)整句删。
61
+
62
+ ### 每个词各算各的(0.2.0)
63
+
64
+ ```yaml
65
+ fillers: ["好", "嗯"]
66
+ fillerMinCounts:
67
+ "好": 5
68
+ "嗯": 3
69
+ burstMinCount: 5 # 没单独配的词用这个
70
+ ```
71
+
72
+ 各算各的,**不互相凑数**:「好 4 个 + 嗯 2 个」不算命中,因为两边都没到自己的线。
73
+ 命中哪个只删哪个——嗯够 3 但好只有 2,就只删嗯,好一个不动。
74
+
75
+ 为什么不合计:合起来算会让两个词互相掩护,各自其实都没到线也会被清。
76
+
77
+ ## 手动清上一轮(0.2.0)
78
+
79
+ 自动那条要攒够次数。有时候不用等:想现在就清掉上一条,用 `/strip-last`。
80
+
81
+ - 在 DSH 里打字 `/strip-last` 就清当前这个框的上一轮;
82
+ - 别的进程(比如手机上的门)可以写一个请求文件,插件读它、清完把结果写回 `.result.json`:
83
+
84
+ ```yaml
85
+ manual:
86
+ enabled: true
87
+ requestFile: "C:\\Users\\you\\.dsh\\strip-last.json" # 不填 = 只留斜杠命令
88
+ ```
89
+
90
+ 三条边界:
91
+
92
+ - 只看**最近的那一条纯思考步**,不是整个历史;
93
+ - 带工具调用的步不碰(那是整步替换的活,不归这个插件);
94
+ - **正在跑的那一轮不碰**——消息还在流上时换掉,工具结果回来会找不到调用,历史就坏了。
95
+
96
+ ## 回执
97
+
98
+ 删完会在那条历史里留一行。三种配法:
99
+
100
+ - `receipt: "⟪已整理⟫"` —— 默认,看得见;
101
+ - `receipt: ""` —— 完全不留。**不建议**:看不见的改动等于篡改历史,使用者某天翻回去会以为字本来就在;
102
+ - `receipt: "\u200B\u200B\u200B"` —— 看不见,但按码点查得到。
103
+
104
+ ## 实测数据(1000+ 条真实思考)
105
+
106
+ - 那个词的出现次数:中位数 1,P90 = 4,P99 = 12,≥5 次的只占 7%。
107
+ - 位置:开头 10% 只占 2%,**最后 20% 占 40%**——是收束动作,不是起笔习惯。
108
+ - 崩得最狠的那几条都在 20 万 token 以上;压缩之后立刻消失。**上下文是放大器,不是原因。**
109
+
110
+ 所以阈值定在 5,专抓「一句一个」的分散型;整段复读交给折叠和急停阀。
111
+
112
+
113
+ ## 版本与验证
114
+
115
+ **版本 0.2.0。**(0.1.0 → 0.2.0:每个词各算各的门槛;新增手动清上一轮 `/strip-last` 和请求文件入口;手动那条不碰正在跑的步。)
116
+
117
+ 在以下环境实测通过(2026-12-05):
118
+
119
+ - DSH 0.2.2-rc.5(Windows)
120
+ - Node 24.22.1
121
+ - 验证方式:先 `dryRun: true` 跑一轮,日志里命中 5 段思考;再关掉 dryRun 重跑,5 段全部真改写。
122
+ - 逐条核对过:
123
+ - 替换消息的 id 形如 `echo-guard-<seq>`,来源 `plugin:echo-guard`,正文以回执开头;
124
+ - 原始 `assistant/message` 事件仍在事件流里,一个字没动;
125
+ - 命中的 5 段全是「纯思考 + 正文」、零工具调用——带工具调用的步按设计跳过;
126
+ - 另一个会话的文件没有被写过(`onlySessions` 生效)。
127
+ - 单测:`node --test test/core.test.mjs`,16 个用例全过。
128
+
129
+ **未验证**:两个插件同时命中同一步的交叉场景。设计上不重叠(带工具调用的步本插件直接跳过),但确实没实测到。
130
+
131
+ ## 限制
132
+
133
+ - 只对 DSH 有效,用的宿主接口是 `session.append` + `surfaceOp`。
134
+ - 只处理没有工具调用的步(带工具调用的整步替换会跟 thinking-guard 打架)。
135
+ - 分词器可能吞掉不可见字符,用零宽回执前先实测。
136
+
137
+ ## 测试
138
+
139
+ ```bash
140
+ npm test
141
+ ```
142
+
143
+ `lib/core.mjs` 是纯函数、不依赖宿主,单测覆盖中英文、词内/独立、标点清理。
144
+
145
+ ## 来源
146
+
147
+ 宿主接口的用法参考过 [dsh-degeneration-kit](https://github.com/walksls/dsh-degeneration-kit)(作者 walksls,MIT)——同一个问题、同一套 API。代码是重写的,只保留了「删字」这一件事。
148
+
149
+ ## 许可
150
+
151
+ MIT。
@@ -0,0 +1,46 @@
1
+ - insert:
2
+ - id: echo-guard
3
+ name: dsh-echo-guard
4
+ # agents:要读 agent.session;commands:0.2.0 起的 /strip-last 手动清靠它注册。
5
+ inject: [ agents, commands ]
6
+ config:
7
+ enabled: true
8
+
9
+ # 哪些词算「收束词灌水」。中文常见这两个;英文可以写 ["OK", "let me go", "alright"]。
10
+ # 计数算全部(「好像」里的「好」也算),删除只删单独成句的那一个。
11
+ fillers:
12
+ - "好"
13
+ - "嗯"
14
+
15
+ # 每个词各算各的门槛,不互相凑数。
16
+ # 例:好 够 5 次才算,嗯 够 3 次就算;「好 4 + 嗯 2」不算命中。
17
+ fillerMinCounts:
18
+ "好": 5
19
+ "嗯": 3
20
+
21
+ # 没在 fillerMinCounts 里单独配的词,用这个数。
22
+ burstMinCount: 5
23
+
24
+ # 删完在历史里留的那一行,可配:
25
+ # "⟪已整理⟫" 看得见(默认)
26
+ # "" 完全不留(不建议)
27
+ # "\u200B\u200B\u200B" 看不见,但按码点查得到
28
+ receipt: "⟪已整理⟫"
29
+
30
+ # 删完剩下的字数不到原来的这个比例就放弃(防止整段都是收束词时被删空)
31
+ stripMinKeepRatio: 0.2
32
+
33
+ # 只对这些会话生效(空 = 全部)。填会话 id 的片段。
34
+ onlySessions: []
35
+
36
+ # 先观察:true 时只写日志、不改历史。建议先跑一天。
37
+ dryRun: true
38
+
39
+ # 手动「清上一轮」(0.2.0):斜杠命令 /strip-last 一直挂着;
40
+ # 要给别的进程(比如手机上的门)用,就填一个请求文件的绝对路径。
41
+ manual:
42
+ enabled: true
43
+ # requestFile: "C:\\Users\\you\\.dsh\\strip-last.json"
44
+
45
+ # 日志(每次命中一条)
46
+ # debugFile: "./echo-guard.log"
package/lib/core.mjs ADDED
@@ -0,0 +1,135 @@
1
+ // 收束词/复读词检测与清理的核心,跟宿主无关,纯函数,方便单测和复用。
2
+ //
3
+ // 为什么单独一个文件:原来这套逻辑写死了一个中文字(中文里最常见的收束词),
4
+ // 换英文、换别的模型就得改代码。这里把它抽成「词表 + 边界规则」,词表从配置来。
5
+ //
6
+ // 两个概念要分清:
7
+ // - **计数**算全部:连「好像」「刚好」里夹着的那个字也算,因为门槛是"出现得太多"。
8
+ // - **删除**只删单独成句的那一个:前后都不是词的一部分才删。
9
+ // 这条区分是整套逻辑的关键,别简化。
10
+
11
+ export const DEFAULT_FILLERS = ['好', '嗯']
12
+
13
+ // 跟着被删词一起带走的标点(中文、中文全角、英文常见)
14
+ const TRAILING_PUNCT = '[,,、。.!!??;;::.…")”’]'
15
+ const PUNCT_AFTER = '[,,、。.!!??;;::.…\\s")”’]|$'
16
+
17
+ const CJK = /[\u3400-\u4dbf\u4e00-\u9fff]/
18
+
19
+ /** 判断一个词是不是纯中文(用汉字边界),否则按拉丁字母词边界处理。 */
20
+ export function isCJKWord(word) {
21
+ return Array.from(word).every((ch) => CJK.test(ch))
22
+ }
23
+
24
+ function escapeRe(s) {
25
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
26
+ }
27
+
28
+ /**
29
+ * 造一个「单独出现」的正则。
30
+ * @param {string} word
31
+ * @param {{caseInsensitive?:boolean}} [opts]
32
+ */
33
+ export function standalonePattern(word, opts = {}) {
34
+ const w = escapeRe(word)
35
+ if (isCJKWord(word)) {
36
+ // 前面不是汉字;后面是标点/空白/行尾,或紧跟标点时一起带走
37
+ return new RegExp(`(?<![\\u3400-\\u4dbf\\u4e00-\\u9fff])${w}(?=${PUNCT_AFTER})${TRAILING_PUNCT}?`, 'g')
38
+ }
39
+ const flags = opts.caseInsensitive === false ? 'g' : 'gi'
40
+ // 前后都不能是字母/数字,避免误杀 okra、book 这类
41
+ return new RegExp(`(?<![A-Za-z0-9])${w}(?![A-Za-z0-9])(?=${PUNCT_AFTER})${TRAILING_PUNCT}?`, flags)
42
+ }
43
+
44
+ /** 计数:整段里这些词一共出现多少次(含词内部的,比如「好像」里的「好」)。 */
45
+ export function countFillers(text, fillers = DEFAULT_FILLERS) {
46
+ if (typeof text !== 'string' || text === '') return 0
47
+ let n = 0
48
+ for (const word of fillers) {
49
+ if (!word) continue
50
+ const re = new RegExp(escapeRe(word), isCJKWord(word) ? 'g' : 'gi')
51
+ n += (text.match(re) || []).length
52
+ }
53
+ return n
54
+ }
55
+
56
+ /**
57
+ * 每个词各算各的次数。
58
+ * 为什么分开算:中文里「好」和「嗯」的密度不一样,合成一个门槛会互相掩护——
59
+ * 三个「好」加三个「嗯」凑成六次,各自其实都没到线。
60
+ * @returns {Record<string, number>}
61
+ */
62
+ export function countPerWord(text, fillers = DEFAULT_FILLERS) {
63
+ const out = {}
64
+ if (typeof text !== 'string' || text === '') return out
65
+ for (const word of fillers) {
66
+ if (!word) continue
67
+ const re = new RegExp(escapeRe(word), isCJKWord(word) ? 'g' : 'gi')
68
+ out[word] = (text.match(re) || []).length
69
+ }
70
+ return out
71
+ }
72
+
73
+ /**
74
+ * 只删单独成句的那些,其余原样。
75
+ * @returns {{text:string, removed:number, counted:number}}
76
+ */
77
+ export function stripFillers(text, fillers = DEFAULT_FILLERS) {
78
+ if (typeof text !== 'string' || text === '') return { text: '', removed: 0, counted: 0 }
79
+ const counted = countFillers(text, fillers)
80
+ if (counted === 0) return { text, removed: 0, counted: 0 }
81
+
82
+ let out = text
83
+ let removed = 0
84
+ for (const word of fillers) {
85
+ if (!word) continue
86
+ const re = standalonePattern(word)
87
+ out = out.replace(re, () => {
88
+ removed += 1
89
+ return ''
90
+ })
91
+ }
92
+
93
+ // 删完可能留下的残渣
94
+ out = out.replace(/「」/g, '')
95
+ out = out.replace(/([。!?!?])(?:\s*[。!?!?])+/g, '$1')
96
+ out = out.replace(/([,,、])(?:\s*[,,、])+/g, '$1')
97
+ out = out.replace(/^\s*[,,、。!?!?]+\s*/gm, '')
98
+ out = out.replace(/[,,、]\s*$/gm, '')
99
+ out = out.replace(/\n{3,}/g, '\n\n').replace(/[ \t]+\n/g, '\n').trim()
100
+
101
+ return { text: out, removed, counted }
102
+ }
103
+
104
+ /**
105
+ * 在一段文字里找「这些词扎堆出现」的位置。
106
+ * 每个词按自己的门槛算(没配就用 minCount),命中哪个只算哪个,不互相凑数。
107
+ * @param {string} text
108
+ * @param {string[]} fillers
109
+ * @param {{minCount?:number, minCounts?:Record<string,number>}} [cfg]
110
+ * @returns {null | {firstAt:number, count:number, words:string[]}}
111
+ */
112
+ export function findBurst(text, fillers = DEFAULT_FILLERS, cfg = {}) {
113
+ if (typeof text !== 'string' || text === '') return null
114
+ const dflt = Number.isSafeInteger(cfg.minCount) ? cfg.minCount : 5
115
+ const mins = cfg.minCounts && typeof cfg.minCounts === 'object' ? cfg.minCounts : {}
116
+ const counts = countPerWord(text, fillers)
117
+ const words = []
118
+ let count = 0
119
+ for (const word of fillers) {
120
+ if (!word) continue
121
+ const n = counts[word] || 0
122
+ const min = Number.isSafeInteger(mins[word]) ? mins[word] : dflt
123
+ if (n >= min) {
124
+ words.push(word)
125
+ count += n
126
+ }
127
+ }
128
+ if (words.length === 0) return null
129
+ let firstAt = -1
130
+ for (const word of words) {
131
+ const i = text.indexOf(word)
132
+ if (i >= 0 && (firstAt < 0 || i < firstAt)) firstAt = i
133
+ }
134
+ return { firstAt, count, words }
135
+ }
package/lib/index.mjs ADDED
@@ -0,0 +1,318 @@
1
+ /**
2
+ * dsh-echo-guard —— 把「收束词灌水」从模型可见历史里删掉。
3
+ *
4
+ * 跟 dsh-degeneration-kit(作者 walksls,MIT)里的 thinking-guard 的区别,一句话:
5
+ * - 那个是**折叠**:整条步骤从可见历史里换掉,抓「同一句重复」;
6
+ * - 这个是**删字**:只删单独成句的收束词,其余原文照录,抓「一句一个」。
7
+ *
8
+ * 两个可以同时装:这个只处理「没有工具调用的纯思考步」,带工具调用的整步折叠留给
9
+ * thinking-guard,互不抢同一段改写。
10
+ *
11
+ * 一条硬约束:**只改 surface(模型读到的那层),事件流一个字不动。**
12
+ * 所以「模型记得什么」和「日志里写的是什么」可以同时对。
13
+ */
14
+
15
+ import fs from 'node:fs'
16
+ import { stripFillers, countFillers, findBurst, DEFAULT_FILLERS } from './core.mjs'
17
+
18
+ export const name = 'echo-guard'
19
+
20
+ export const DEFAULT_RECEIPT = '⟪已整理⟫'
21
+
22
+ let DEBUG_FILE = ''
23
+
24
+ function dbg(line) {
25
+ if (!DEBUG_FILE) return
26
+ try {
27
+ // 保持只追加;单行写入,避免并发时交错。
28
+ fs.appendFileSync(DEBUG_FILE, `${new Date().toISOString()} [echo-guard] ${line}\n`, 'utf8')
29
+ } catch {
30
+ /* 日志写不进去不影响主流程 */
31
+ }
32
+ }
33
+
34
+ function isSubagent(agent) {
35
+ return Boolean(agent?.parentSessionId || agent?.parent)
36
+ }
37
+
38
+ /** 该消息里第一段 reasoning 的全文(宿主把它映射成上游的 thinking)。 */
39
+ function reasoningOf(message) {
40
+ if (!Array.isArray(message?.content)) return null
41
+ for (const block of message.content) {
42
+ if (block && block.type === 'reasoning' && typeof block.text === 'string') return block
43
+ }
44
+ return null
45
+ }
46
+
47
+ /** 该消息里说出口的话(text 块),原样拼起来。 */
48
+ function speechOf(message) {
49
+ if (!Array.isArray(message?.content)) return ''
50
+ return message.content
51
+ .filter((b) => b && b.type === 'text' && typeof b.text === 'string')
52
+ .map((b) => b.text)
53
+ .join('')
54
+ .trim()
55
+ }
56
+
57
+ function hasToolCall(message) {
58
+ return Array.isArray(message?.content) && message.content.some((b) => b?.type === 'tool-call')
59
+ }
60
+
61
+ /** 会话 id -> 最近的 agent 句柄。手动入口要用它:命令和门都只能拿到 id。 */
62
+ const LIVE_AGENTS = new Map()
63
+
64
+ /**
65
+ * 这一轮有没有在跑、它是第几轮。
66
+ * 读法用 `session.seq` + `session.eventAt(i)`——这是宿主暴露的只读接口,别换成 session.events,
67
+ * 那个在运行时不是数组(2026-12-05 实测)。
68
+ * 拿不到就当作在跑、轮次未知(什么都不许动)。
69
+ * @returns {{live:boolean, turn:number|null, unknown:boolean}}
70
+ */
71
+ export function activeTurn(session) {
72
+ const len = session?.seq
73
+ if (!Number.isSafeInteger(len)) return { live: true, turn: null, unknown: true }
74
+ for (let i = len - 1; i >= 0; i -= 1) {
75
+ let ev
76
+ try { ev = session.eventAt?.(i) } catch { ev = undefined }
77
+ if (ev === undefined || ev === null) continue
78
+ if (ev.type === 'turn/end') return { live: false, turn: null, unknown: false }
79
+ if (ev.type === 'turn/start') return { live: true, turn: ev.data?.turn ?? null, unknown: false }
80
+ }
81
+ return { live: false, turn: null, unknown: false }
82
+ }
83
+
84
+ /**
85
+ * 手动清「上一轮」:从最近往前找第一条纯思考步,删掉单独成句的收束词,其余原文照录。
86
+ *
87
+ * 只碰纯思考步(没有 tool-call 的)——带工具调用的整步替换不归这个插件管,
88
+ * 这也是它和 thinking-guard 能同时装的原因。
89
+ * 正在跑的那一轮、以及拿不到状态的时候,一律不动。
90
+ *
91
+ * @returns {{ok:true, seq:number, deleted:number, counted:number} | {ok:false, why:string}}
92
+ */
93
+ export function stripLastTurn(agent, cfg) {
94
+ const session = agent?.session
95
+ if (session === undefined || session === null) return { ok: false, why: '这个会话拿不到' }
96
+ const turn = activeTurn(session)
97
+ if (turn.unknown) return { ok: false, why: '读不到这一轮的状态,先不动' }
98
+ const nodes = [...(session.surface?.nodes ?? [])]
99
+ for (let i = nodes.length - 1; i >= 0; i -= 1) {
100
+ const seq = nodes[i]
101
+ const event = session.eventAt(seq)
102
+ if (event === undefined || event === null) continue
103
+ if (event.type !== 'assistant/message' || event.surfaceOp !== 'append') continue
104
+ const message = session.deriveEventMessage(event)
105
+ if (message === null || !Array.isArray(message.content)) continue
106
+ const block = reasoningOf(message)
107
+ if (block === null) continue
108
+ const burst = findBurst(block.text, cfg.fillers, { minCount: cfg.burstMinCount, minCounts: cfg.fillerMinCounts })
109
+ if (burst === null) continue
110
+ if (hasToolCall(message)) {
111
+ return { ok: false, why: '这一条带工具调用,echo-guard 只清纯思考步' }
112
+ }
113
+ if (turn.live && !(Number.isSafeInteger(turn.turn) && Number.isSafeInteger(event?.data?.turn) && event.data.turn < turn.turn)) {
114
+ return { ok: false, why: '这一步还在跑,等它落地再清' }
115
+ }
116
+ const stripped = stripFillers(block.text, burst.words)
117
+ if (stripped.removed === 0) return { ok: false, why: '上一轮里没有单独成句的收束词' }
118
+ const speech = speechOf(message)
119
+ let body = cfg.receipt
120
+ if (stripped.text !== '') body = body ? `${body}\n\n${stripped.text}` : stripped.text
121
+ if (speech !== '') body = `${body}\n\n此处说出口的话(原文照录):\n${speech}`
122
+ session.append('user/message', {
123
+ id: `echo-guard-manual-${seq}-${Date.now()}`,
124
+ role: 'user',
125
+ source: { kind: 'plugin:echo-guard' },
126
+ content: [{ type: 'text', text: body }]
127
+ }, {
128
+ surfaceOp: { op: 'replace', startSeq: seq, endSeq: seq },
129
+ sourceEventSeqs: [seq]
130
+ })
131
+ return { ok: true, seq, deleted: stripped.removed, counted: stripped.counted }
132
+ }
133
+ return { ok: false, why: '上一轮里没有可清的收束词' }
134
+ }
135
+
136
+ export function apply(ctx, config = {}) {
137
+ if (typeof config.debugFile === 'string' && config.debugFile.length > 0) DEBUG_FILE = config.debugFile
138
+ if (config.enabled === false) return
139
+
140
+ const cfg = {
141
+ fillers: Array.isArray(config.fillers) && config.fillers.length ? config.fillers.map(String) : DEFAULT_FILLERS,
142
+ burstMinCount: Number.isSafeInteger(config.burstMinCount) ? config.burstMinCount : 5,
143
+ // 每个词各算各的门槛;没配的词用 burstMinCount。
144
+ // 例:{ "好": 5, "嗯": 3 } —— 好 够 5 次才算,嗯 够 3 次就算,不互相凑。
145
+ fillerMinCounts: config.fillerMinCounts && typeof config.fillerMinCounts === 'object' ? config.fillerMinCounts : {},
146
+ receipt: typeof config.receipt === 'string' ? config.receipt : DEFAULT_RECEIPT,
147
+ // 删完剩不到两成就放弃:整段都是收束词时删光只会剩个空块,不如留着。
148
+ stripMinKeepRatio: typeof config.stripMinKeepRatio === 'number' ? config.stripMinKeepRatio : 0.2,
149
+ // 只对这些会话生效(空 = 全部)。填会话 id 片段。
150
+ onlySessions: Array.isArray(config.onlySessions) ? config.onlySessions.map(String) : [],
151
+ includeSubagents: config.includeSubagents !== false,
152
+ dryRun: config.dryRun === true,
153
+ // 手动「清上一轮」(0.2.0 起):命令 + 请求文件。
154
+ // requestFile 留空 = 不监听请求文件,只留斜杠命令。
155
+ manual: {
156
+ enabled: config.manual?.enabled !== false,
157
+ requestFile: typeof config.manual?.requestFile === 'string' ? config.manual.requestFile : ''
158
+ }
159
+ }
160
+
161
+ const state = new WeakMap() // session -> { seen: Set<seq> }
162
+
163
+ ctx.on('agent/pre-step', async ({ agent, signal }, next) => {
164
+ try {
165
+ const session = agent?.session
166
+ if (!session || signal?.aborted) return next()
167
+ if (!cfg.includeSubagents && isSubagent(agent)) return next()
168
+
169
+ const rawId = String(session.id ?? '')
170
+ const inList = cfg.onlySessions.length === 0 || cfg.onlySessions.some((p) => rawId.includes(p))
171
+ if (!inList) return next()
172
+ LIVE_AGENTS.set(rawId, agent)
173
+
174
+ let s = state.get(session)
175
+ if (s === undefined) {
176
+ s = { seen: new Set() }
177
+ state.set(session, s)
178
+ dbg(`首次扫描:surface ${session.surface.nodes.length} 节点`)
179
+ }
180
+
181
+ for (const seq of [...session.surface.nodes]) {
182
+ if (s.seen.has(seq)) continue
183
+ const event = session.eventAt(seq)
184
+ if (event === undefined || event.type !== 'assistant/message') {
185
+ s.seen.add(seq)
186
+ continue
187
+ }
188
+ if (event.surfaceOp !== 'append') {
189
+ s.seen.add(seq)
190
+ continue
191
+ }
192
+
193
+ const message = session.deriveEventMessage(event)
194
+ if (message === null || !Array.isArray(message.content)) {
195
+ s.seen.add(seq)
196
+ continue
197
+ }
198
+
199
+ // 带工具调用的步不碰:整步替换是 thinking-guard 的活,两个插件抢同一段会打架。
200
+ if (hasToolCall(message)) {
201
+ s.seen.add(seq)
202
+ continue
203
+ }
204
+
205
+ const block = reasoningOf(message)
206
+ if (block === null) {
207
+ s.seen.add(seq)
208
+ continue
209
+ }
210
+
211
+ const burst = findBurst(block.text, cfg.fillers, {
212
+ minCount: cfg.burstMinCount,
213
+ minCounts: cfg.fillerMinCounts
214
+ })
215
+ if (burst === null) {
216
+ s.seen.add(seq)
217
+ continue
218
+ }
219
+ const counted = burst.count
220
+
221
+ const stripped = stripFillers(block.text, burst.words)
222
+ if (stripped.text !== '' && stripped.text.length < block.text.length * cfg.stripMinKeepRatio) {
223
+ s.seen.add(seq)
224
+ dbg(`跳过 seq ${seq}:删完只剩 ${stripped.text.length}/${block.text.length}`)
225
+ continue
226
+ }
227
+
228
+ const speech = speechOf(message)
229
+ let body = cfg.receipt
230
+ if (stripped.text !== '') body = body ? `${body}\n\n${stripped.text}` : stripped.text
231
+ if (speech !== '') body = `${body}\n\n此处说出口的话(原文照录):\n${speech}`
232
+
233
+ if (cfg.dryRun) {
234
+ s.seen.add(seq)
235
+ dbg(`DRY-RUN 命中 seq ${seq}:${counted} 次,删 ${stripped.removed} 个,${block.text.length}→${stripped.text.length} 字`)
236
+ continue
237
+ }
238
+
239
+ try {
240
+ session.append('user/message', {
241
+ id: `echo-guard-${seq}`,
242
+ role: 'user',
243
+ source: { kind: 'plugin:echo-guard' },
244
+ content: [{ type: 'text', text: body }]
245
+ }, {
246
+ surfaceOp: { op: 'replace', startSeq: seq, endSeq: seq },
247
+ sourceEventSeqs: [seq]
248
+ })
249
+ } catch (error) {
250
+ // 落不下去就下次再说:不记 seen,避免把这一步永久漏掉。
251
+ dbg(`写入失败 seq ${seq}:${String(error)}`)
252
+ ctx.logger?.warn?.(`[${name}] 改写失败 seq ${seq}:${String(error)}`)
253
+ continue
254
+ }
255
+
256
+ s.seen.add(seq)
257
+ dbg(`已删字 seq ${seq}:${counted} 次,删 ${stripped.removed} 个,${block.text.length}→${stripped.text.length} 字`)
258
+ }
259
+ } catch (error) {
260
+ dbg(`扫描失败:${String(error)}`)
261
+ ctx.logger?.warn?.(`[${name}] 扫描失败(已忽略,不影响本步):${String(error)}`)
262
+ }
263
+ return next()
264
+ })
265
+
266
+ // ── 手动「清上一轮」(0.2.0)──────────────────────────────────────────
267
+ // 两个入口,同一个动作:
268
+ // ① DSH 里打 `/strip-last`;
269
+ // ② 别的进程(比如手机上的门)写一个请求文件,插件读它、清完把结果写回去。
270
+ // 手动不看次数门槛;只碰纯思考步;正在跑的那一轮不动。
271
+ if (cfg.manual.enabled) {
272
+ try {
273
+ ctx.commands?.register?.({
274
+ name: 'strip-last',
275
+ description: '清掉上一轮纯思考步里单独成句的收束词,其余原文照录',
276
+ handler: ({ agent }) => {
277
+ const r = stripLastTurn(agent, cfg)
278
+ if (!r.ok) return { kind: 'error', text: r.why }
279
+ return { kind: 'success', text: `清掉 ${r.deleted} 个(seq ${r.seq}),其余原文照录。原文仍在会话日志里。` }
280
+ }
281
+ })
282
+ dbg('已注册斜杠命令 /strip-last')
283
+ } catch (error) {
284
+ dbg(`注册命令失败:${String(error)}`)
285
+ ctx.logger?.warn?.(`[${name}] 注册 /strip-last 失败:${String(error)}`)
286
+ }
287
+
288
+ const requestFile = cfg.manual.requestFile
289
+ if (typeof requestFile === 'string' && requestFile.length > 0) {
290
+ const resultFile = requestFile.replace(/\.json$/i, '.result.json')
291
+ ctx.effect?.(() => {
292
+ const timer = setInterval(() => {
293
+ try {
294
+ if (!fs.existsSync(requestFile)) return
295
+ // 请求文件可能是别的进程写的,先去掉 BOM(PowerShell 的 UTF-8 带 BOM)。
296
+ const raw = fs.readFileSync(requestFile, 'utf8').replace(/^\uFEFF/, '')
297
+ let request = null
298
+ let parseError = null
299
+ try { request = JSON.parse(raw) } catch (error) { parseError = error }
300
+ try { fs.unlinkSync(requestFile) } catch { /* 被别的进程抢先删了也无所谓 */ }
301
+ if (parseError !== null) {
302
+ fs.writeFileSync(resultFile, JSON.stringify({ at: new Date().toISOString(), ok: false, why: `请求文件格式不对:${String(parseError)}` }), 'utf8')
303
+ return
304
+ }
305
+ const agent = LIVE_AGENTS.get(String(request?.sessionId ?? ''))
306
+ const result = agent ? stripLastTurn(agent, cfg) : { ok: false, why: '这个会话还没跑过一轮(插件手里没有它的句柄)' }
307
+ fs.writeFileSync(resultFile, JSON.stringify({ at: new Date().toISOString(), ...result }), 'utf8')
308
+ dbg(`请求文件:${JSON.stringify(result)}`)
309
+ } catch (error) {
310
+ dbg(`请求文件处理失败:${String(error)}`)
311
+ try { fs.writeFileSync(resultFile, JSON.stringify({ at: new Date().toISOString(), ok: false, why: String(error) }), 'utf8') } catch { /* 结果写不进去就只能丢 */ }
312
+ }
313
+ }, 800)
314
+ return () => clearInterval(timer)
315
+ })
316
+ }
317
+ }
318
+ }
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "dsh-echo-guard",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Strips filler-word bursts out of the model-visible reasoning history — only standalone occurrences, everything else verbatim. DSH plugin.",
5
+ "type": "module",
6
+ "main": "lib/index.mjs",
7
+ "exports": {
8
+ ".": "./lib/index.mjs",
9
+ "./core": "./lib/core.mjs",
10
+ "./package.json": "./package.json"
11
+ },
12
+ "files": [
13
+ "lib",
14
+ "cordis.patch.yml",
15
+ "README.md",
16
+ "README.en.md",
17
+ "LICENSE"
18
+ ],
19
+ "scripts": {
20
+ "test": "node --test test/core.test.mjs"
21
+ },
22
+ "engines": {
23
+ "node": ">=22.19.0"
24
+ },
25
+ "keywords": [
26
+ "deepseek",
27
+ "deepseek-harness",
28
+ "dsh",
29
+ "dsh-plugin",
30
+ "reasoning",
31
+ "loop",
32
+ "degeneration",
33
+ "long-context"
34
+ ],
35
+ "license": "MIT",
36
+ "dsh": {
37
+ "bundle": {
38
+ "patch": "./cordis.patch.yml"
39
+ }
40
+ },
41
+ "repository": {
42
+ "type": "git",
43
+ "url": "git+https://github.com/efef3/dsh-echo-guard.git"
44
+ },
45
+ "homepage": "https://github.com/efef3/dsh-echo-guard#readme",
46
+ "bugs": {
47
+ "url": "https://github.com/efef3/dsh-echo-guard/issues"
48
+ }
49
+ }