dsh-goal-contract 0.2.5 → 0.2.9

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.
@@ -11,6 +11,12 @@
11
11
  // 一个 delta 里根本不含换行,按行切永远等不到「整行重复」。
12
12
  // 对方实测过:行级/字符级各有盲区,先照抄它验证过的那一条,不自行发挥。
13
13
  //
14
+ // **2026-11-28 补一条**:抄来的那条只看「整条 delta 规范化后完全相同」,而这次事故
15
+ // 是模型在 **reasoning 通道**里把同一个 8~9 字符单元连续刷了 699 次 —— reasoning 的
16
+ // 分片碎成 1~5 个字符,规范化后多半是空串,那条判据一个都没吃到。
17
+ // 所以补了「尾部连续周期重复」这条(见下面 detectCycleRepeat / createCycleDetector),
18
+ // 并把 reasoning-delta 也纳入计数。两条判据任一命中即算命中。
19
+ //
14
20
  // 三条硬约束(全部来自实测踩坑,见 docs/llm-stream-break-contract.md):
15
21
  // ① 有 tool-call 块开着时**不许切** —— 闭合它会提交半截调用并被执行;
16
22
  // 不闭合,BlockAssembler 也会从 delta 组装出同样的半截调用。两种都会跑一个
@@ -46,6 +52,23 @@ export function normalizeDelta(text) {
46
52
  return text.replace(/\s+/g, ' ').trim();
47
53
  }
48
54
 
55
+ /**
56
+ * 把阈值解析成可用的数字。**两条判据共用这一份口径。**
57
+ *
58
+ * ★ 显式关闭(Infinity)和「值无效」必须走两条路。
59
+ * 前者是 index.js 在开关关掉时**主动**传下来的(见 index.js「关着时给 Infinity ⇒ 永不命中」),
60
+ * 必须原样保留成 Infinity;若走兜底分支,`Number.isFinite(Infinity) === false`
61
+ * 会把它当成「没配」并填 DEFAULT_DELTA_REPEAT_MAX,于是**开关关掉了却照样会截断**。
62
+ *
63
+ * @param {unknown} max
64
+ * @returns {number} `Infinity`(显式关闭)或一个 ≥1 的整数
65
+ */
66
+ function resolveRepeatLimit(max) {
67
+ if (max === Number.POSITIVE_INFINITY) return Number.POSITIVE_INFINITY;
68
+ if (Number.isFinite(max) && max >= 1) return Math.floor(max);
69
+ return DEFAULT_DELTA_REPEAT_MAX;
70
+ }
71
+
49
72
  /**
50
73
  * 连续相同 delta 的计数器。
51
74
  *
@@ -53,13 +76,8 @@ export function normalizeDelta(text) {
53
76
  * 每次喂一个 delta,相同就 +1、不同就归 1;返回是否达到阈值。
54
77
  */
55
78
  export function createDeltaCounter(max) {
56
- // ★ 显式关闭(Infinity)和「值无效」必须走两条路。
57
- // 前者是 index.js 在开关关掉时**主动**传下来的(见 index.js「关着时给 Infinity ⇒ 永不命中」),
58
- // 必须原样保留成 Infinity;若走下面的兜底分支,`Number.isFinite(Infinity) === false`
59
- // 会把它当成「没配」并填 DEFAULT_DELTA_REPEAT_MAX,于是**开关关掉了却照样会截断**。
60
- const limit = max === Number.POSITIVE_INFINITY
61
- ? Number.POSITIVE_INFINITY
62
- : (Number.isFinite(max) && max >= 1 ? Math.floor(max) : DEFAULT_DELTA_REPEAT_MAX);
79
+ // ★ 显式关闭(Infinity)和「值无效」必须走两条路 —— 口径见 resolveRepeatLimit。
80
+ const limit = resolveRepeatLimit(max);
63
81
  let last = null;
64
82
  let count = 0;
65
83
  return {
@@ -79,6 +97,107 @@ export function createDeltaCounter(max) {
79
97
  };
80
98
  }
81
99
 
100
+ // ── 尾部「连续周期重复」判据(2026-11-28 新增) ──────────────────────────
101
+ //
102
+ // 事故复盘:模型在 **reasoning 通道**里把 `\n\n**做。**` 这个 8~9 字符的单元
103
+ // 连续重复了 699 次(turn 458 step 1,2400 个 reasoning 分片,text 分片 0 个),
104
+ // 而旧判据只看「整条 delta 规范化后完全相同」—— reasoning 的分片碎成 1~5 个字符,
105
+ // 规范化后多半是空串,旧判据一个都没吃到。
106
+ //
107
+ // 这条判据换个问法:**只看尾巴** —— 末尾是不是同一个 L 字符单元连续重复了 N 次?
108
+ // L 取 3..64(单元下限 3:单字符刷屏交给原判据;上限 64:再长就不像「一个单元」了)。
109
+ //
110
+ // ★ 只认连续,绝不累计:中间插进任何不匹配的内容,周期立刻断掉重新数;
111
+ // 计数不跨 delta、跨 block、跨 step。
112
+
113
+ /** 周期判据的单元长度下限:单字符刷屏(「0」「|」)归原判据管。 */
114
+ export const MIN_CYCLE_UNIT_LEN = 3;
115
+ /** 周期判据的单元长度上限。 */
116
+ export const MAX_CYCLE_UNIT_LEN = 64;
117
+ /** 报给模型 / 写进日志的重复单元最多留多少字符。 */
118
+ export const MAX_CYCLE_UNIT_PREVIEW = 40;
119
+
120
+ /**
121
+ * 在一段文本的**尾部**找「同一个 L 字符单元连续重复」的段。
122
+ *
123
+ * 判据:末尾能凑出 `minCount` 个完全相同的 L 字符块 ⇒ 命中。
124
+ * 只取**最小**的 L(最小周期):`ABCABCABC` 报出来的是 `ABC` 而不是 `ABCABC`。
125
+ *
126
+ * @param {string} text
127
+ * @param {{minCount?: number, minLen?: number, maxLen?: number}} [options]
128
+ * minCount:至少要连续几个单元(默认 2)。
129
+ * @returns {{count: number, unit: string, kind: 'cycle'} | null}
130
+ */
131
+ export function detectCycleRepeat(text, options = {}) {
132
+ if (typeof text !== 'string' || text === '') return null;
133
+ const minCount = Number.isFinite(options.minCount) && options.minCount >= 1
134
+ ? Math.floor(options.minCount) : 2;
135
+ const minLen = Number.isFinite(options.minLen) && options.minLen >= 1
136
+ ? Math.floor(options.minLen) : MIN_CYCLE_UNIT_LEN;
137
+ const maxLen = Number.isFinite(options.maxLen) && options.maxLen >= minLen
138
+ ? Math.floor(options.maxLen) : MAX_CYCLE_UNIT_LEN;
139
+ const len = text.length;
140
+ for (let p = minLen; p <= maxLen; p += 1) {
141
+ const need = minCount * p;
142
+ // p 越大 need 越大;长度不够就不用往下试了。
143
+ if (len < need) break;
144
+ // 末尾 need 个字符是不是以 p 为周期?错的 p 几乎第一格就露馅(成本 O(1))。
145
+ let ok = true;
146
+ for (let j = len - 1; j >= len - need + p; j -= 1) {
147
+ if (text[j] !== text[j - p]) { ok = false; break; }
148
+ }
149
+ if (!ok) continue;
150
+ // 命中:往回找周期后缀的起点 → 真实的连续次数 + 重复单元。
151
+ let start = len - 1;
152
+ while (start >= p && text[start] === text[start - p]) start -= 1;
153
+ // 关系在 start 处断了 ⇒ 周期段从 start-p+1 开始(起点允许是半个单元)。
154
+ const regionStart = start >= p ? start - p + 1 : 0;
155
+ const count = Math.floor((len - regionStart) / p);
156
+ // 单元取**末尾这 p 个字符**:模型最后正在重复的那一段(不是某次旋转)。
157
+ const unit = text.slice(len - p).slice(0, MAX_CYCLE_UNIT_PREVIEW);
158
+ return { count, unit, kind: 'cycle' };
159
+ }
160
+ return null;
161
+ }
162
+
163
+ /**
164
+ * 造一个「尾部连续周期重复」检测器(**每个 block 一个**)。
165
+ *
166
+ * 它只维护该 block 已输出文本的**尾部窗口**(最近 `limit * MAX_CYCLE_UNIT_LEN`
167
+ * 个字符,不无限增长),每次喂一段文本就问一遍:
168
+ * 「末尾是不是同一个 L 字符单元连续重复了 ≥ limit 次?」
169
+ *
170
+ * @param {number} [max] 阈值;`Infinity` 表示显式关闭 ⇒ 永不命中。
171
+ * @returns {{push(text: string): {count: number, unit: string, kind: 'cycle'} | null,
172
+ * count: number, unit: string, limit: number}}
173
+ */
174
+ export function createCycleDetector(max) {
175
+ const limit = resolveRepeatLimit(max);
176
+ const windowSize = Number.isFinite(limit)
177
+ ? Math.max(limit * MAX_CYCLE_UNIT_LEN, MAX_CYCLE_UNIT_LEN)
178
+ : MAX_CYCLE_UNIT_LEN;
179
+ let tail = '';
180
+ let hit = null;
181
+ return {
182
+ /** 喂一段文本;命中返回 { count, unit, kind: 'cycle' },没命中返回 null。 */
183
+ push(text) {
184
+ if (hit !== null) return hit; // 已命中就不再重算
185
+ if (limit === Number.POSITIVE_INFINITY) return null; // 显式关闭 ⇒ 永不命中
186
+ if (typeof text !== 'string' || text === '') return null;
187
+ tail += text;
188
+ if (tail.length > windowSize) tail = tail.slice(tail.length - windowSize);
189
+ const found = detectCycleRepeat(tail, { minCount: limit });
190
+ if (found !== null) hit = found;
191
+ return hit;
192
+ },
193
+ /** 命中时的连续次数(没命中过是 0)。 */
194
+ get count() { return hit === null ? 0 : hit.count; },
195
+ /** 命中时的重复单元(没命中过是空串)。 */
196
+ get unit() { return hit === null ? '' : hit.unit; },
197
+ get limit() { return limit; },
198
+ };
199
+ }
200
+
82
201
  /**
83
202
  * 造一个 `llm/stream` 监听器。
84
203
  *
@@ -87,8 +206,10 @@ export function createDeltaCounter(max) {
87
206
  * @param {number} [deps.max] 连续相同 delta 的阈值,缺省 60
88
207
  * @param {(options: any) => boolean} [deps.isAgentLoopRequest]
89
208
  * 可选精确过滤器;缺省时退化为「有 sessionId」。
90
- * @param {(agent: any, detail: {count: number, unit: string}) => void} [deps.onBreak]
209
+ * @param {(agent: any, detail: {count: number, unit: string, kind: 'cycle' | 'same'}) => void} [deps.onBreak]
91
210
  * 截断成功后回调,用来给模型发纠偏提示。
211
+ * `kind` 区分命中的是哪条判据:`'same'` = 整条 delta 规范化后连续相同;
212
+ * `'cycle'` = 尾部同一单元连续周期重复(这次事故的形态)。
92
213
  * @param {object} [deps.logger]
93
214
  * @returns {(options: any, next: () => AsyncIterable<any>) => AsyncIterable<any>}
94
215
  */
@@ -105,19 +226,25 @@ export function createStreamBreaker({ getAgent, max, isAgentLoopRequest, onBreak
105
226
  return (async function* guarded() {
106
227
  /** index → { blockType, text },顺序即流顺序。 */
107
228
  const open = new Map();
108
- /** 本步的连续相同 delta 计数器。`max` 允许是函数 —— 这样改配置不用重启。 */
109
- const counter = createDeltaCounter(typeof max === 'function' ? max() : max);
229
+ /**
230
+ * index → 该 block 的两条判据。
231
+ *
232
+ * ★ 按 block 分开记:用户口径「不许跨 block 累加总数」——
233
+ * reasoning 块和 text 块各记各的,混着来不算连续。
234
+ */
235
+ const judges = new Map();
236
+ /** 阈值。`max` 允许是函数 —— 这样改配置不用重启(每条流开始时求值一次)。 */
237
+ const limit = resolveRepeatLimit(typeof max === 'function' ? max() : max);
110
238
 
111
239
  for await (const chunk of next()) {
112
240
  // 记录 block 生命周期,供命中时闭合用。
113
241
  if (chunk?.type === 'block-start') {
114
242
  open.set(chunk.index, { blockType: String(chunk.blockType ?? 'text'), text: '' });
243
+ judges.delete(chunk.index);
115
244
  } else if (chunk?.type === 'block-end') {
116
245
  open.delete(chunk.index);
117
- } else if (chunk?.type === 'text-delta') {
118
- const block = open.get(chunk.index);
119
- if (block !== undefined) block.text += chunk.text ?? '';
120
- } else if (chunk?.type === 'reasoning-delta') {
246
+ judges.delete(chunk.index);
247
+ } else if (chunk?.type === 'text-delta' || chunk?.type === 'reasoning-delta') {
121
248
  const block = open.get(chunk.index);
122
249
  if (block !== undefined) block.text += chunk.text ?? '';
123
250
  }
@@ -125,25 +252,38 @@ export function createStreamBreaker({ getAgent, max, isAgentLoopRequest, onBreak
125
252
  // 先把这一块原样交给下游 —— 已产生的输出一律保留。
126
253
  yield chunk;
127
254
 
128
- // 只在可见文本 delta 上判(reasoning 合理会复述计划,不参与这条判据)。
129
- if (chunk?.type !== 'text-delta') continue;
255
+ // ★ text-delta 与 reasoning-delta **都参与**判据。
256
+ // 旧实现只判 text-delta(注释写「reasoning 合理会复述计划」),
257
+ // 漏掉了这次事故的真实形态:模型在 reasoning 通道里把同一个单元刷了几百次。
258
+ if (chunk?.type !== 'text-delta' && chunk?.type !== 'reasoning-delta') continue;
130
259
 
131
- if (!counter.push(chunk.text)) continue;
260
+ let judge = judges.get(chunk.index);
261
+ if (judge === undefined) {
262
+ judge = { same: createDeltaCounter(limit), cycle: createCycleDetector(limit) };
263
+ judges.set(chunk.index, judge);
264
+ }
265
+ // 两条判据任一命中即算命中;周期判据优先(它能报出「在重复哪一段」)。
266
+ const cycleHit = judge.cycle.push(chunk.text);
267
+ const sameHit = judge.same.push(chunk.text);
268
+ let hit = null;
269
+ if (cycleHit !== null) hit = cycleHit;
270
+ else if (sameHit) hit = { count: judge.same.count, unit: judge.same.unit ?? '', kind: 'same' };
271
+ if (hit === null) continue;
132
272
 
133
273
  const tail = buildTerminal(open);
134
274
  if (tail === null) {
135
275
  // 有非 text/reasoning 的块开着 —— 切不安全,本轮放弃。
136
- logger?.warn?.(`[轮次控制] 文本重复命中,但有非文本块开着,放弃截断(连续 ${counter.count} 次相同)`);
276
+ logger?.warn?.(`[轮次控制] 文本重复命中,但有非文本块开着,放弃截断(连续 ${hit.count} 次,判据 ${hit.kind})`);
137
277
  continue;
138
278
  }
139
279
  for (const out of tail) yield out;
140
- logger?.info?.(`[轮次控制] 已截断本轮(连续 ${counter.count} 个相同 delta,阈值 ${counter.limit})`);
280
+ logger?.info?.(`[轮次控制] 已截断本轮(连续 ${hit.count} 次${hit.kind === 'cycle' ? '同一单元' : '相同 delta'},阈值 ${limit})`);
141
281
  // ★ 截断之后必须告诉模型「为什么停、接下来做什么」。
142
282
  // 没有这一步,截断就只是把话掐断:模型不知道自己被拦了,下一轮很可能照旧重复。
143
283
  // 失败绝不连累流(steer 收到的形状不对时宿主会抛),只记一笔。
144
284
  if (typeof onBreak === 'function') {
145
285
  try {
146
- onBreak(agent, { count: counter.count, unit: counter.unit ?? '' });
286
+ onBreak(agent, { count: hit.count, unit: hit.unit ?? '', kind: hit.kind });
147
287
  } catch (error) {
148
288
  logger?.warn?.(`[轮次控制] 纠偏提示发送失败(不影响截断):${error?.message ?? error}`);
149
289
  }