dsh-repeat-guard 0.1.3 → 0.1.5

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