dsh-repeat-guard 0.1.2 → 0.1.4

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/src/detect.ts CHANGED
@@ -2,34 +2,84 @@
2
2
  * 复读退化判定:查表。
3
3
  *
4
4
  * 表里是已知会被模型复读的空话短句,**连标点一起写**,表本身可配置(见 config.ts)。
5
- * 判定是"思考里有没有独占一行的表项":整行与表项全等,不拆解行的内部。
5
+ * 基本判据是"整行与表项全等",不拆解行的内部。
6
6
  *
7
- * 阈值是"连续命中多少行才拦":默认 1 表示发现即拦;调到 n 时,要连着 n 行都命中
8
- * (句子可以各不相同)才拦,中间夹一行不命中的就重新计数。
7
+ * 行内重复检测(可开关,默认关)打开时,"整行由多个表项首尾相接拼成"也算命中,
8
+ * 用来兜住把短句连成一串写在同一行里的模型(如"好。好。好。")。
9
+ *
10
+ * 阈值是"连续命中多少次才拦":默认 1 表示发现即拦。计数单位是表项——整行全等算一次,
11
+ * 开了行内检测后行内每一段各算一次;中间夹一行不命中的就重新计数。
12
+ */
13
+
14
+ /**
15
+ * 在 line 的 at 处能匹配到的最长表项长度。
16
+ * @param line - 已小写化的行。
17
+ * @param at - 起始下标。
18
+ * @param fragments - 小写化的短句表。
19
+ * @returns 匹配到的长度,0 表示这个位置没有表项。
20
+ */
21
+ function longestFragmentAt(line: string, at: number, fragments: ReadonlySet<string>): number {
22
+ let size = 0;
23
+ for (const fragment of fragments) {
24
+ if (fragment.length > size && line.startsWith(fragment, at)) {
25
+ size = fragment.length;
26
+ }
27
+ }
28
+ return size;
29
+ }
30
+
31
+ /**
32
+ * 这一行算几次命中。
33
+ * @param line - 已 trim 并小写化的行。
34
+ * @param fragments - 小写化的短句表。
35
+ * @param inlineRepeat - 是否把"整行由多个表项拼成"也算命中。
36
+ * @returns 0 表示不是命中行,其余为这一行贡献的次数。
9
37
  */
38
+ function countHits(line: string, fragments: ReadonlySet<string>, inlineRepeat: boolean): number {
39
+ if (fragments.has(line)) {
40
+ return 1;
41
+ }
42
+ if (!inlineRepeat) {
43
+ return 0;
44
+ }
45
+ let at = 0;
46
+ let parts = 0;
47
+ while (at < line.length) {
48
+ const size = longestFragmentAt(line, at, fragments);
49
+ if (size === 0) {
50
+ return 0;
51
+ }
52
+ at += size;
53
+ parts += 1;
54
+ }
55
+ return parts > 1 ? parts : 0;
56
+ }
10
57
 
11
58
  /**
12
59
  * 找出退化的碎片行。
13
60
  * @param text - 已生成的思考文本。
14
61
  * @param fragments - 小写化的短句表。
15
- * @param threshold - 连续命中多少行才判定为复读。
62
+ * @param threshold - 连续命中多少次才判定为复读。
63
+ * @param inlineRepeat - 是否启用行内重复检测。
16
64
  * @returns 计数成立时返回那一行的原文,否则返回 null。
17
65
  */
18
66
  export function findDegenerateLine(
19
67
  text: string,
20
68
  fragments: ReadonlySet<string>,
21
69
  threshold: number,
70
+ inlineRepeat: boolean,
22
71
  ): string | null {
23
72
  let run = 0;
24
73
  for (const raw of text.split('\n')) {
25
74
  const line = raw.trim();
26
- if (line !== '' && fragments.has(line.toLowerCase())) {
27
- run += 1;
28
- if (run >= threshold) {
29
- return line;
30
- }
31
- } else {
75
+ const hits = line === '' ? 0 : countHits(line.toLowerCase(), fragments, inlineRepeat);
76
+ if (hits === 0) {
32
77
  run = 0;
78
+ continue;
79
+ }
80
+ run += hits;
81
+ if (run >= threshold) {
82
+ return line;
33
83
  }
34
84
  }
35
85
  return null;
package/src/index.ts CHANGED
@@ -22,7 +22,7 @@
22
22
  // 本文件只做装配,具体逻辑在各自的模块里。
23
23
 
24
24
  import type { Context } from '@deepseek-ai/cordis';
25
- import { createConfigSource } from './config.js';
25
+ import { createRuntime } from './config.js';
26
26
  import { createStreamGuard } from './stream-guard.js';
27
27
  import { createTurnStoppingGuard } from './turn-stopping-guard.js';
28
28
  import type { GuardState } from './types.js';
@@ -35,7 +35,7 @@ export default function repeatGuard(ctx: Context): void {
35
35
  // 直接写 stdout:dsh 把插件的 stdout 收进 journal,便于确认插件确实被加载。
36
36
  console.log('[repeat-guard] 已加载,复读拦截生效');
37
37
  const state: GuardState = { pending: new Set() };
38
- const readConfig = createConfigSource(ctx);
39
- ctx.on('llm/stream', createStreamGuard(state, readConfig), { global: true });
40
- ctx.on('agent/turn-stopping', createTurnStoppingGuard(state));
38
+ const runtime = createRuntime(ctx);
39
+ ctx.on('llm/stream', createStreamGuard(state, runtime.read, runtime.countHit), { global: true });
40
+ ctx.on('agent/turn-stopping', createTurnStoppingGuard(state, runtime.read));
41
41
  }
package/src/resume.ts CHANGED
@@ -11,37 +11,22 @@
11
11
  *
12
12
  * 所以在监听器里调 `agent.steer(...)` 推入一条输入,本轮就会再跑一步,而不是停下来等
13
13
  * 用户输入。dsh 自己的 dsh-hooks-claude-code/lib/index.js:300 就是这么用的。
14
+ *
15
+ * 推什么内容由配置决定(见 config.ts 的 resumeText / resumeSummary)。
14
16
  */
15
17
 
16
18
  import type { Agent } from '@deepseek-ai/dsh-agent';
17
19
  import { createUserMessage } from '@deepseek-ai/dsh-llm';
20
+ import type { RepeatGuardConfig } from './config.js';
18
21
  import type { GuardState } from './types.js';
19
22
 
20
- /** 续跑时推给模型的指令正文。 */
21
- const RESUME_TEXT = [
22
- '[复读拦截]',
23
- '你上一段思考退化成了碎片复读(反复输出"好。"一类的空话),已被系统截断。',
24
- '请直接继续执行下一步,不要再输出任何确认语、寒暄或空话。',
25
- ].join('\n');
26
-
27
- /**
28
- * 这条注入消息的来源标记。
29
- * `form: 'notice'` 要求同时给出 `summary`(dsh-llm 的 ContextFormed),
30
- * 客户端据此把它渲染成折叠的 context 行,而不是用户气泡。
31
- */
32
- const PLUGIN_SOURCE = {
33
- kind: 'plugin',
34
- plugin: 'repeat-guard',
35
- form: 'notice',
36
- summary: '复读已截断:请继续执行',
37
- } as const;
38
-
39
23
  /**
40
24
  * 本轮即将关闭时,若上一步刚被掐断过,就推一条输入让本轮继续。
41
25
  * @param state - 跨监听保留的拦截状态。
42
26
  * @param agent - 本轮所属的 agent 句柄。
27
+ * @param config - 当前配置,正文与摘要都从这里取。
43
28
  */
44
- export function reviveTurn(state: GuardState, agent: Agent): void {
29
+ export function reviveTurn(state: GuardState, agent: Agent, config: RepeatGuardConfig): void {
45
30
  const sessionId = agent.session.id;
46
31
  if (!state.pending.has(sessionId)) {
47
32
  return;
@@ -50,8 +35,15 @@ export function reviveTurn(state: GuardState, agent: Agent): void {
50
35
  console.log(`[repeat-guard] turn-stopping:会话 ${sessionId} 续跑一步`);
51
36
  agent.steer(
52
37
  createUserMessage({
53
- content: [{ type: 'text', text: RESUME_TEXT }],
54
- source: PLUGIN_SOURCE,
38
+ content: [{ type: 'text', text: config.resumeText }],
39
+ // `form: 'notice'` 要求同时给出 `summary`(dsh-llm 的 ContextFormed),
40
+ // 客户端据此把它渲染成折叠的 context 行,而不是用户气泡。
41
+ source: {
42
+ kind: 'plugin',
43
+ plugin: 'repeat-guard',
44
+ form: 'notice',
45
+ summary: config.resumeSummary,
46
+ },
55
47
  }),
56
48
  );
57
49
  }
@@ -29,6 +29,7 @@ type StreamListener = (
29
29
  * @param sessionId - 当前会话 id;有值才登记待续跑标记。
30
30
  * @param state - 跨监听保留的拦截状态。
31
31
  * @param readConfig - 取当前配置;每个 chunk 现取,改设置立即生效。
32
+ * @param countHit - 记一次拦截;只在真的掐断时调用。
32
33
  * @returns 包好的流。
33
34
  */
34
35
  async function* guardStream(
@@ -36,6 +37,7 @@ async function* guardStream(
36
37
  sessionId: GenerateOptions['sessionId'],
37
38
  state: GuardState,
38
39
  readConfig: ConfigSource,
40
+ countHit: () => void,
39
41
  ): AsyncGenerator<StreamChunk> {
40
42
  const iterator = downstream[Symbol.asyncIterator]();
41
43
  let accumulated = '';
@@ -49,10 +51,16 @@ async function* guardStream(
49
51
  if (chunk.type === 'reasoning-delta') {
50
52
  accumulated += chunk.text;
51
53
  const config = readConfig();
52
- const hit = findDegenerateLine(accumulated, config.fragments, config.threshold);
54
+ const hit = findDegenerateLine(
55
+ accumulated,
56
+ config.fragments,
57
+ config.threshold,
58
+ config.inlineRepeat,
59
+ );
53
60
  if (hit !== null) {
54
61
  const probe = await iterator.next();
55
62
  if (!probe.done && probe.value.type === 'reasoning-delta') {
63
+ countHit();
56
64
  if (sessionId !== undefined) {
57
65
  state.pending.add(sessionId);
58
66
  }
@@ -92,14 +100,19 @@ async function* guardStream(
92
100
  * 造一个 `llm/stream` 监听器。
93
101
  * @param state - 跨监听保留的拦截状态。
94
102
  * @param readConfig - 取当前配置。
103
+ * @param countHit - 记一次拦截。
95
104
  * @returns 监听器;辅助调用直接透传,其余包一层复读检测。
96
105
  */
97
- export function createStreamGuard(state: GuardState, readConfig: ConfigSource): StreamListener {
106
+ export function createStreamGuard(
107
+ state: GuardState,
108
+ readConfig: ConfigSource,
109
+ countHit: () => void,
110
+ ): StreamListener {
98
111
  return (options, next) => {
99
112
  // 辅助调用(上下文压缩、会话标题)不参与检测。
100
113
  if (options.purpose !== undefined) {
101
114
  return next();
102
115
  }
103
- return guardStream(next(), options.sessionId, state, readConfig);
116
+ return guardStream(next(), options.sessionId, state, readConfig, countHit);
104
117
  };
105
118
  }
@@ -6,16 +6,18 @@
6
6
  */
7
7
 
8
8
  import type { Agent } from '@deepseek-ai/dsh-agent';
9
+ import type { ConfigSource } from './config.js';
9
10
  import { reviveTurn } from './resume.js';
10
11
  import type { GuardState } from './types.js';
11
12
 
12
13
  /**
13
14
  * 造一个 `agent/turn-stopping` 监听器。
14
15
  * @param state - 跨监听保留的拦截状态。
16
+ * @param readConfig - 取当前配置。
15
17
  * @returns 监听器;只在有待续跑标记时推一条输入。
16
18
  */
17
- export function createTurnStoppingGuard(state: GuardState) {
19
+ export function createTurnStoppingGuard(state: GuardState, readConfig: ConfigSource) {
18
20
  return (payload: { agent: Agent }): void => {
19
- reviveTurn(state, payload.agent);
21
+ reviveTurn(state, payload.agent, readConfig());
20
22
  };
21
23
  }