@linxin666/dsh-liangshen 0.4.6 → 0.4.8
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/README.i18n.yaml +2 -2
- package/README.md +16 -22
- package/README.zh.md +16 -22
- package/lib/client.js +28 -228
- package/lib/client.js.map +1 -1
- package/lib/index.js +19 -61
- package/lib/types/client/LiangShenSettingsCard.d.ts +1 -18
- package/lib/types/client/PluginSettingsCard.d.ts +39 -0
- package/lib/types/client/locales.d.ts +0 -15
- package/lib/types/composition.d.ts +3 -15
- package/lib/types/index.d.ts +14 -66
- package/package.json +19 -19
- package/presets/liangshen/agent.cordis.yml +17 -40
- package/presets/liangshen/dispatcher-rules.mjs +175 -106
- package/presets/liangshen/minimal-prompt.mjs +17 -10
- package/presets/liangshen/tool-catalog.mjs +159 -82
- package/src/announce.test.ts +7 -14
- package/src/client/LiangShenSettingsCard.tsx +3 -85
- package/src/client/PluginSettingsCard.tsx +63 -3
- package/src/client/locales.ts +2 -32
- package/src/client/settings-card.module.css +70 -1
- package/src/client/settings-entry-form.ts +0 -1
- package/src/composition.test.ts +6 -45
- package/src/composition.ts +3 -22
- package/src/index.test.ts +6 -37
- package/src/index.ts +20 -80
- package/tools/benchmark-live-run.mjs +12 -17
- package/tools/benchmark-report.mjs +4 -6
- package/presets/liangshen/guard.mjs +0 -526
|
@@ -1,526 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* guard — the LiangShen preset's runtime degeneration circuit breaker.
|
|
3
|
-
*
|
|
4
|
-
* Why this exists: DSH discussion #5976 documents a model-side generation
|
|
5
|
-
* degeneration on DeepSeek-V4.1-Flash under very long context and max
|
|
6
|
-
* reasoning effort — the agent emits turn after turn of zero-output
|
|
7
|
-
* self-urging reasoning with no tool call, no automatic fuse, and the run
|
|
8
|
-
* has to be killed by hand. The persona's reflection-fuse discipline cannot
|
|
9
|
-
* stop it, because in that state the discipline text itself has fallen out of
|
|
10
|
-
* the effective context. The only thing that works is an OUTSIDE force, and
|
|
11
|
-
* the report's own conclusion is that this guard-layer gap can be filled by a
|
|
12
|
-
* plugin without touching the DSH core. This plugin is that outside force.
|
|
13
|
-
*
|
|
14
|
-
* Two signals, both folded from the durable session event stream (never from
|
|
15
|
-
* process memory, so resume and compaction rebuild the same verdict):
|
|
16
|
-
*
|
|
17
|
-
* - STALL: N consecutive assistant steps that carry reasoning but neither a
|
|
18
|
-
* tool call nor any visible reply text — the #5976 shape. Reading the
|
|
19
|
-
* reasoning TEXT is unnecessary (and impossible on routes that redact it);
|
|
20
|
-
* the block's character count is the objective "long thinking" measure.
|
|
21
|
-
* On a route that persists signed reasoning blocks with NO text, every
|
|
22
|
-
* character count reads zero and the character ladders can never fire, so a
|
|
23
|
-
* session in which no reasoning text was ever observed falls back to a
|
|
24
|
-
* step-count measure (see DEFAULT_BLIND_STALL_CAP) and says so once.
|
|
25
|
-
* - ECHO: the same tool called with the same arguments failing M times in a
|
|
26
|
-
* row with no success in between — the closed loop of repeating one broken
|
|
27
|
-
* call.
|
|
28
|
-
*
|
|
29
|
-
* On either signal the breaker FIRES once per episode with a circuit-breaker
|
|
30
|
-
* user message injected at the next pre-step (the one channel guaranteed to
|
|
31
|
-
* reach the model, as durable as the working-context projection), telling the
|
|
32
|
-
* model the loop was interrupted and to close out or pick a materially
|
|
33
|
-
* different action.
|
|
34
|
-
*
|
|
35
|
-
* A STALL additionally arms a temporary reasoning-effort step-down that rides
|
|
36
|
-
* the `agent/request` waterfall for the next FEW requests: one notch down
|
|
37
|
-
* `max -> high`, and `high` (like every other level) is left alone. Lowering
|
|
38
|
-
* the budget is the community-observed recovery move (r/DeepSeek 1whgo3e) and
|
|
39
|
-
* the official effort-cost curve puts the sweet spot below max — neither piece
|
|
40
|
-
* of evidence supports going BELOW the 60-80 sweet spot, so the ladder stops
|
|
41
|
-
* at `high`. ECHO does NOT step down: its cause is a broken call, not an
|
|
42
|
-
* over-large budget, and lowering the effort would weaken a model that is
|
|
43
|
-
* already stuck. This is the ONLY moment this plugin rewrites a request: with
|
|
44
|
-
* no signal it never touches one, so prefix-cache stability and the user's
|
|
45
|
-
* explicit model-selector effort stay untouched — the constraint recorded in
|
|
46
|
-
* the Agent Note that removed the old phase-based switching.
|
|
47
|
-
*
|
|
48
|
-
* Recovery: a step with a tool call or a visible reply re-arms the breaker
|
|
49
|
-
* and, once the step-down window has run its requests, the route's own effort
|
|
50
|
-
* resumes unchanged. Thresholds are deliberately conservative — a false
|
|
51
|
-
* interruption of real long thinking hurts more than a missed episode.
|
|
52
|
-
*/
|
|
53
|
-
|
|
54
|
-
/** Cordis plugin name used by loader diagnostics. */
|
|
55
|
-
export const name = 'liangshen-guard'
|
|
56
|
-
|
|
57
|
-
/**
|
|
58
|
-
* How many consecutive runaway-reasoning zero-output steps trip the per-step
|
|
59
|
-
* ladder. ONE is deliberate: a single step whose reasoning alone blows past
|
|
60
|
-
* the character floor with no output is already the runaway-generation shape
|
|
61
|
-
* (#5976's first symptom), and waiting for a second one just lets the episode
|
|
62
|
-
* burn another 384K-scale generation. The slow-burn ladder below carries the
|
|
63
|
-
* burden of proof for smaller steps, so this ladder staying hair-trigger does
|
|
64
|
-
* not raise the false-positive rate — a step has to be individually enormous
|
|
65
|
-
* AND output-free to count.
|
|
66
|
-
*/
|
|
67
|
-
export const DEFAULT_STALL_STEPS = 1
|
|
68
|
-
|
|
69
|
-
/**
|
|
70
|
-
* The per-step reasoning-character floor for a step to count as "long",
|
|
71
|
-
* keyed by the request's CURRENT reasoning effort. The floor follows the
|
|
72
|
-
* budget the model was asked to spend: max effort produces the longest
|
|
73
|
-
* trajectories (official data: 1.6-1.8x the sweet spot) and is where every
|
|
74
|
-
* documented runaway happened, so its floor is the lowest; low effort thinks
|
|
75
|
-
* briefly by design, so a zero-output step that still runs long is almost
|
|
76
|
-
* certainly abnormal and the floor can sit higher without false positives.
|
|
77
|
-
*
|
|
78
|
-
* Calibration anchor: DeepSeek-V4.1's official MAX OUTPUT is 384K. The max-
|
|
79
|
-
* effort floor of 8000 chars (roughly 2-4K thinking tokens) is far beyond any
|
|
80
|
-
* healthy single step yet catches a runaway in its first 2% — waiting for a
|
|
81
|
-
* higher floor just lets the episode burn more of the 384K budget.
|
|
82
|
-
*/
|
|
83
|
-
export const STALL_REASONING_CHARS_BY_EFFORT = {
|
|
84
|
-
max: 8000,
|
|
85
|
-
high: 12000,
|
|
86
|
-
low: 20000,
|
|
87
|
-
}
|
|
88
|
-
/** Floor for unknown effort levels (numeric efforts, off): the per-step ladder
|
|
89
|
-
* stays armed at the high-effort floor; the slow-burn ladder carries the rest. */
|
|
90
|
-
export const DEFAULT_STALL_REASONING_CHARS = 12000
|
|
91
|
-
|
|
92
|
-
/** How many identical-argument failures in a row constitute an echo loop. */
|
|
93
|
-
export const DEFAULT_ECHO_FAILURES = 3
|
|
94
|
-
|
|
95
|
-
/**
|
|
96
|
-
* Steps with at least this much reasoning count toward the global (slow-burn)
|
|
97
|
-
* stall ladder. Deliberately low: the ladder exists to catch the loop of many
|
|
98
|
-
* individually-plausible-but-output-free steps, so any step that really thought
|
|
99
|
-
* counts; a step that barely reasoned (a tool ack, an empty turn) must not.
|
|
100
|
-
*/
|
|
101
|
-
export const GLOBAL_MIN_REASONING_CHARS = 200
|
|
102
|
-
|
|
103
|
-
/** How many consecutive output-free reasoning steps trip the slow-burn ladder. */
|
|
104
|
-
export const DEFAULT_GLOBAL_STALL_CAP = 4
|
|
105
|
-
|
|
106
|
-
/**
|
|
107
|
-
* Consecutive output-free steps that trip STALL on a route that never produced
|
|
108
|
-
* any reasoning text. Both character ladders read zero there, so the step count
|
|
109
|
-
* is the only objective measure left; the cap matches the slow-burn ladder's,
|
|
110
|
-
* which keeps the fallback as conservative as the ladder it stands in for.
|
|
111
|
-
*/
|
|
112
|
-
export const DEFAULT_BLIND_STALL_CAP = 4
|
|
113
|
-
|
|
114
|
-
/**
|
|
115
|
-
* Sensitivity presets: a whole-scale multiplier over the adaptive thresholds,
|
|
116
|
-
* for operators who know they fear false interruptions more than missed
|
|
117
|
-
* episodes (or the reverse) without hand-tuning four numbers.
|
|
118
|
-
* - conservative: every floor and cap x 1.5, rounded — fewest interruptions.
|
|
119
|
-
* - balanced: x 1.0, the calibrated defaults.
|
|
120
|
-
* - aggressive: every floor x 0.5 and every cap - 1 (floored at the minimums) —
|
|
121
|
-
* catches episodes earlier at the cost of more false positives.
|
|
122
|
-
*/
|
|
123
|
-
export const SENSITIVITY_OPTIONS = ['conservative', 'balanced', 'aggressive']
|
|
124
|
-
export const DEFAULT_SENSITIVITY = 'balanced'
|
|
125
|
-
const SENSITIVITY_SCALE = { conservative: 1.5, balanced: 1.0, aggressive: 0.5 }
|
|
126
|
-
|
|
127
|
-
/** Requests the temporary effort step-down stays on for after firing. */
|
|
128
|
-
export const DEFAULT_STEP_DOWN_REQUESTS = 3
|
|
129
|
-
|
|
130
|
-
/** Steps the breaker stays quiet after firing once (no message spam). */
|
|
131
|
-
export const DEFAULT_REFIRE_COOLDOWN_STEPS = 5
|
|
132
|
-
|
|
133
|
-
/**
|
|
134
|
-
* The effort ladder a step-down walks along: one notch down from `max` only.
|
|
135
|
-
* `high` is where the ladder stops, because the official effort-cost curve
|
|
136
|
-
* puts the model's sweet spot at 60-80 and nothing supports stepping below it;
|
|
137
|
-
* every other level (including `high` itself) is left alone.
|
|
138
|
-
*/
|
|
139
|
-
const EFFORT_LADDER = ['max', 'high']
|
|
140
|
-
|
|
141
|
-
/** Validate a positive-integer config value, or fall back when absent. */
|
|
142
|
-
function integerAtLeast(value, field, minimum, fallback) {
|
|
143
|
-
if (value === undefined) return fallback
|
|
144
|
-
if (!Number.isInteger(value) || value < minimum) {
|
|
145
|
-
throw new TypeError(`${name}: ${field} must be an integer >= ${minimum}`)
|
|
146
|
-
}
|
|
147
|
-
return value
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
/** Session events, tolerating both snapshotEvents() and events array. */
|
|
151
|
-
function sessionEvents(session) {
|
|
152
|
-
if (Array.isArray(session?.events)) return session.events
|
|
153
|
-
if (typeof session?.snapshotEvents === 'function') return session.snapshotEvents()
|
|
154
|
-
return []
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
/** Reasoning characters one assistant/message event carries. */
|
|
158
|
-
function reasoningCharsOf(event) {
|
|
159
|
-
let chars = 0
|
|
160
|
-
for (const block of event?.data?.message?.content ?? []) {
|
|
161
|
-
if (block?.type === 'reasoning') chars += String(block.text ?? '').length
|
|
162
|
-
}
|
|
163
|
-
return chars
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
/** Reasoning blocks one assistant/message event carries, text or not. */
|
|
167
|
-
function reasoningBlocksOf(event) {
|
|
168
|
-
let blocks = 0
|
|
169
|
-
for (const block of event?.data?.message?.content ?? []) {
|
|
170
|
-
if (block?.type === 'reasoning') blocks += 1
|
|
171
|
-
}
|
|
172
|
-
return blocks
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
/** Visible reply blocks (non-empty text) one assistant/message event carries. */
|
|
176
|
-
function visibleRepliesOf(event) {
|
|
177
|
-
let count = 0
|
|
178
|
-
for (const block of event?.data?.message?.content ?? []) {
|
|
179
|
-
if (block?.type === 'text' && String(block.text ?? '').trim().length > 0) count += 1
|
|
180
|
-
}
|
|
181
|
-
return count
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
/** Stable signature for one tool call: name plus canonicalized arguments. */
|
|
185
|
-
function callSignature(event) {
|
|
186
|
-
const tool = event?.data?.name
|
|
187
|
-
if (typeof tool !== 'string') return undefined
|
|
188
|
-
let args = event.data?.arguments
|
|
189
|
-
if (typeof args === 'string') {
|
|
190
|
-
try { args = JSON.parse(args) } catch { /* keep raw string */ }
|
|
191
|
-
}
|
|
192
|
-
let canonical
|
|
193
|
-
try { canonical = JSON.stringify(args ?? null) } catch { canonical = String(args) }
|
|
194
|
-
return `${tool}${canonical}`
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
/** The tool/result matching one callId carried an error. */
|
|
198
|
-
function isErrorResult(event) {
|
|
199
|
-
if (event?.type !== 'tool/result') return false
|
|
200
|
-
const data = event.data
|
|
201
|
-
if (data?.error !== undefined && data.error !== null) return true
|
|
202
|
-
const message = data?.message
|
|
203
|
-
if (message?.isError === true) return true
|
|
204
|
-
return false
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
/**
|
|
208
|
-
* Fold the breaker verdict from the event stream.
|
|
209
|
-
*
|
|
210
|
-
* The fold tracks, walking newest-last:
|
|
211
|
-
* - a running count of consecutive zero-output long-reasoning steps
|
|
212
|
-
* (assistant/message events with reasoning chars above the threshold and
|
|
213
|
-
* neither a following tool/call nor visible text before the next step/
|
|
214
|
-
* turn boundary);
|
|
215
|
-
* - the latest tool call's signature and its consecutive-failure count,
|
|
216
|
-
* reset by any success or any differently-shaped call.
|
|
217
|
-
*
|
|
218
|
-
* Returns `{ signal: 'stall' | 'echo' | undefined, detail, blind }` for the TAIL
|
|
219
|
-
* of the stream: the breaker only cares whether the session is degenerate NOW.
|
|
220
|
-
* `blind` reports the session-level fact that reasoning blocks were observed
|
|
221
|
-
* without a single character of reasoning text, so the caller can say once that
|
|
222
|
-
* this session's stall detection is running on step counts.
|
|
223
|
-
*/
|
|
224
|
-
export function foldGuardSignal(events, options) {
|
|
225
|
-
const stallSteps = options?.stallSteps ?? DEFAULT_STALL_STEPS
|
|
226
|
-
const stallChars = options?.stallReasoningChars ?? DEFAULT_STALL_REASONING_CHARS
|
|
227
|
-
const echoFailures = options?.echoFailures ?? DEFAULT_ECHO_FAILURES
|
|
228
|
-
const globalCap = options?.globalStallCap ?? DEFAULT_GLOBAL_STALL_CAP
|
|
229
|
-
const blindCap = options?.blindStallCap ?? DEFAULT_BLIND_STALL_CAP
|
|
230
|
-
|
|
231
|
-
// Stall, two independent ladders walked in parallel:
|
|
232
|
-
// 1. PER-STEP: one step whose reasoning alone blows past the character floor
|
|
233
|
-
// with no output — the runaway-generation shape (#5976's first symptom).
|
|
234
|
-
// 2. GLOBAL: N consecutive steps with NO output at all, regardless of each
|
|
235
|
-
// step's size — the slow-burn closed loop. This ladder is bounded by a
|
|
236
|
-
// hard global cap so a legitimately long investigation (many small
|
|
237
|
-
// read-only steps) cannot trip it by accumulation alone: the streak only
|
|
238
|
-
// counts while the steps are also individually reasoning-heavy.
|
|
239
|
-
// 3. BLIND (fallback): on a route that persists signed reasoning blocks
|
|
240
|
-
// with no text, every character measure reads zero and ladders 1 and 2
|
|
241
|
-
// are structurally dead. When the whole stream carried reasoning blocks
|
|
242
|
-
// but not one character of reasoning text, the step count is the only
|
|
243
|
-
// measure left, so consecutive output-free reasoning-block steps trip
|
|
244
|
-
// STALL at the same cap the slow-burn ladder uses.
|
|
245
|
-
let stallStreak = 0
|
|
246
|
-
let globalStreak = 0
|
|
247
|
-
let blindStreak = 0
|
|
248
|
-
// Session-level facts the blind fallback keys on: whether ANY reasoning text
|
|
249
|
-
// was ever observed, and whether any reasoning block was observed at all.
|
|
250
|
-
// A stream with no reasoning block yet (a fresh session) is NOT blind — the
|
|
251
|
-
// character ladders have simply not had their chance.
|
|
252
|
-
let reasoningTextSeen = false
|
|
253
|
-
let reasoningBlocksSeen = 0
|
|
254
|
-
// pending holds, for the current step, whether we saw reasoning and whether
|
|
255
|
-
// we saw any output (tool call or visible text).
|
|
256
|
-
let pendingReasoning = 0
|
|
257
|
-
let pendingReasoningBlocks = 0
|
|
258
|
-
let pendingOutput = false
|
|
259
|
-
|
|
260
|
-
const closeStep = () => {
|
|
261
|
-
// Per-step ladder: one bloated zero-output step is enough to advance it.
|
|
262
|
-
if (pendingReasoning >= stallChars && !pendingOutput) {
|
|
263
|
-
stallStreak += 1
|
|
264
|
-
} else if (pendingOutput || pendingReasoning > 0) {
|
|
265
|
-
stallStreak = 0
|
|
266
|
-
}
|
|
267
|
-
// Global ladder: any output resets; an output-free step advances it only
|
|
268
|
-
// while the step also carried real reasoning (a bare tool-ack or an empty
|
|
269
|
-
// thought must not count toward a stall).
|
|
270
|
-
if (pendingOutput) {
|
|
271
|
-
globalStreak = 0
|
|
272
|
-
} else if (pendingReasoning >= GLOBAL_MIN_REASONING_CHARS) {
|
|
273
|
-
globalStreak = Math.min(globalStreak + 1, globalCap)
|
|
274
|
-
}
|
|
275
|
-
// Blind ladder: an output-free step that still carried a reasoning block —
|
|
276
|
-
// the exact shape a redacted route produces. Character count is not part of
|
|
277
|
-
// the test, because on that route it is always zero.
|
|
278
|
-
if (pendingOutput) {
|
|
279
|
-
blindStreak = 0
|
|
280
|
-
} else if (pendingReasoningBlocks > 0) {
|
|
281
|
-
blindStreak = Math.min(blindStreak + 1, blindCap)
|
|
282
|
-
}
|
|
283
|
-
pendingReasoning = 0
|
|
284
|
-
pendingReasoningBlocks = 0
|
|
285
|
-
pendingOutput = false
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
// Echo: latest call signature and its consecutive failure count.
|
|
289
|
-
let lastSignature
|
|
290
|
-
let lastCallId
|
|
291
|
-
let failStreak = 0
|
|
292
|
-
|
|
293
|
-
for (const event of Array.isArray(events) ? events : []) {
|
|
294
|
-
switch (event?.type) {
|
|
295
|
-
case 'step/start':
|
|
296
|
-
case 'turn/start':
|
|
297
|
-
closeStep()
|
|
298
|
-
break
|
|
299
|
-
case 'assistant/message': {
|
|
300
|
-
const reasoning = reasoningCharsOf(event)
|
|
301
|
-
if (reasoning > 0) {
|
|
302
|
-
pendingReasoning += reasoning
|
|
303
|
-
reasoningTextSeen = true
|
|
304
|
-
}
|
|
305
|
-
const blocks = reasoningBlocksOf(event)
|
|
306
|
-
if (blocks > 0) {
|
|
307
|
-
pendingReasoningBlocks += blocks
|
|
308
|
-
reasoningBlocksSeen += blocks
|
|
309
|
-
}
|
|
310
|
-
if (visibleRepliesOf(event) > 0) pendingOutput = true
|
|
311
|
-
break
|
|
312
|
-
}
|
|
313
|
-
case 'tool/call': {
|
|
314
|
-
pendingOutput = true
|
|
315
|
-
const signature = callSignature(event)
|
|
316
|
-
if (signature !== lastSignature) {
|
|
317
|
-
lastSignature = signature
|
|
318
|
-
failStreak = 0
|
|
319
|
-
}
|
|
320
|
-
lastCallId = event.data?.callId
|
|
321
|
-
break
|
|
322
|
-
}
|
|
323
|
-
case 'tool/result': {
|
|
324
|
-
const callId = event.data?.callId ?? event.data?.message?.source?.callId
|
|
325
|
-
if (callId !== undefined && lastCallId !== undefined && callId !== lastCallId) break
|
|
326
|
-
if (isErrorResult(event)) {
|
|
327
|
-
if (lastSignature !== undefined) failStreak += 1
|
|
328
|
-
} else {
|
|
329
|
-
failStreak = 0
|
|
330
|
-
lastSignature = undefined
|
|
331
|
-
lastCallId = undefined
|
|
332
|
-
}
|
|
333
|
-
break
|
|
334
|
-
}
|
|
335
|
-
default:
|
|
336
|
-
break
|
|
337
|
-
}
|
|
338
|
-
}
|
|
339
|
-
closeStep()
|
|
340
|
-
|
|
341
|
-
// The blind fallback applies only when the session really is on a redacted
|
|
342
|
-
// route: reasoning blocks were observed, none of them carried any text.
|
|
343
|
-
const blind = !reasoningTextSeen && reasoningBlocksSeen > 0
|
|
344
|
-
if (blind && blindStreak >= blindCap) {
|
|
345
|
-
return {
|
|
346
|
-
signal: 'stall',
|
|
347
|
-
detail: `${blindStreak} consecutive output-free reasoning steps (no reasoning text in this session)`,
|
|
348
|
-
blind,
|
|
349
|
-
}
|
|
350
|
-
}
|
|
351
|
-
if (stallStreak >= stallSteps) {
|
|
352
|
-
return { signal: 'stall', detail: `${stallStreak} consecutive runaway-reasoning steps (${stallChars}+ chars each)`, blind }
|
|
353
|
-
}
|
|
354
|
-
if (globalStreak >= globalCap) {
|
|
355
|
-
return { signal: 'stall', detail: `${globalStreak} consecutive output-free reasoning steps (slow burn)`, blind }
|
|
356
|
-
}
|
|
357
|
-
if (failStreak >= echoFailures) {
|
|
358
|
-
return { signal: 'echo', detail: `${failStreak} consecutive identical-argument tool failures`, blind }
|
|
359
|
-
}
|
|
360
|
-
return { signal: undefined, detail: '', blind }
|
|
361
|
-
}
|
|
362
|
-
|
|
363
|
-
/**
|
|
364
|
-
* Resolve the concrete thresholds for one request: the adaptive floor for the
|
|
365
|
-
* current effort, scaled by the sensitivity preset, with any explicit fine-
|
|
366
|
-
* tuning override winning over the table. All inputs are optional; the result
|
|
367
|
-
* is always a complete, valid set. Every guard fine-tuning field is absent by
|
|
368
|
-
* default, which is what lets the effort table and the sensitivity preset be
|
|
369
|
-
* the shipped behavior rather than dead branches behind a factory value.
|
|
370
|
-
*/
|
|
371
|
-
export function resolveThresholds(options) {
|
|
372
|
-
const effort = options?.effort
|
|
373
|
-
const sensitivity = SENSITIVITY_SCALE[options?.sensitivity] !== undefined ? options.sensitivity : DEFAULT_SENSITIVITY
|
|
374
|
-
const scale = SENSITIVITY_SCALE[sensitivity]
|
|
375
|
-
const baseFloor = STALL_REASONING_CHARS_BY_EFFORT[effort] ?? DEFAULT_STALL_REASONING_CHARS
|
|
376
|
-
const stallReasoningChars = options?.stallReasoningChars !== undefined
|
|
377
|
-
? options.stallReasoningChars
|
|
378
|
-
: Math.max(200, Math.round(baseFloor * scale))
|
|
379
|
-
const globalStallCap = options?.globalStallCap !== undefined
|
|
380
|
-
? options.globalStallCap
|
|
381
|
-
: Math.max(2, Math.round(DEFAULT_GLOBAL_STALL_CAP * scale))
|
|
382
|
-
const echoFailures = options?.echoFailures !== undefined
|
|
383
|
-
? options.echoFailures
|
|
384
|
-
: Math.max(2, Math.round(DEFAULT_ECHO_FAILURES * scale))
|
|
385
|
-
// The blind fallback carries no fine-tuning field of its own: it is a
|
|
386
|
-
// degraded stand-in for the slow-burn ladder, so it scales with the same
|
|
387
|
-
// sensitivity preset unless the caller pins the slow-burn cap explicitly.
|
|
388
|
-
const blindStallCap = options?.blindStallCap !== undefined
|
|
389
|
-
? options.blindStallCap
|
|
390
|
-
: globalStallCap
|
|
391
|
-
return { stallReasoningChars, globalStallCap, echoFailures, blindStallCap }
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
/**
|
|
395
|
-
* One notch down the effort ladder, or undefined when the level is left alone.
|
|
396
|
-
* Only `max` moves, and it moves to `high`: the ladder stops at the sweet
|
|
397
|
-
* spot, so a session the user explicitly put on `high` is never weakened.
|
|
398
|
-
*/
|
|
399
|
-
export function stepDownEffort(effort) {
|
|
400
|
-
const index = EFFORT_LADDER.indexOf(effort)
|
|
401
|
-
if (index < 0 || index === EFFORT_LADDER.length - 1) return undefined
|
|
402
|
-
return EFFORT_LADDER[index + 1]
|
|
403
|
-
}
|
|
404
|
-
|
|
405
|
-
/** The breaker message injected at pre-step. */
|
|
406
|
-
export function renderGuardMessage(verdict) {
|
|
407
|
-
const what = verdict.signal === 'stall'
|
|
408
|
-
? 'repeated long reasoning with no tool call and no reply'
|
|
409
|
-
: 'the same tool call failing repeatedly with identical arguments'
|
|
410
|
-
return [
|
|
411
|
-
`[Circuit Breaker] The runtime interrupted a degeneration loop: ${what}.`,
|
|
412
|
-
'Stop re-deriving in thought. Do exactly ONE of these now:',
|
|
413
|
-
'1. give the user the best final answer you already have, or',
|
|
414
|
-
'2. take ONE materially different concrete action (a different tool, different arguments, or a smaller sub-step) and verify its result.',
|
|
415
|
-
'Do not repeat the interrupted pattern.',
|
|
416
|
-
].join(' ')
|
|
417
|
-
}
|
|
418
|
-
|
|
419
|
-
/** Register the signal fold, the pre-step injection, and the stall-triggered effort step-down. */
|
|
420
|
-
export function apply(ctx, config) {
|
|
421
|
-
const enabled = config?.enabled !== false
|
|
422
|
-
if (!enabled) return
|
|
423
|
-
const sensitivity = SENSITIVITY_OPTIONS.includes(config?.sensitivity) ? config.sensitivity : DEFAULT_SENSITIVITY
|
|
424
|
-
// Fine-tuning overrides: when the operator sets one, it wins over the
|
|
425
|
-
// adaptive table for every effort level; absent, the table applies.
|
|
426
|
-
const overrideStallChars = config?.stallReasoningChars !== undefined
|
|
427
|
-
? integerAtLeast(config.stallReasoningChars, 'stallReasoningChars', 200, DEFAULT_STALL_REASONING_CHARS)
|
|
428
|
-
: undefined
|
|
429
|
-
const overrideGlobalCap = config?.globalStallCap !== undefined
|
|
430
|
-
? integerAtLeast(config.globalStallCap, 'globalStallCap', 2, DEFAULT_GLOBAL_STALL_CAP)
|
|
431
|
-
: undefined
|
|
432
|
-
const overrideEcho = config?.echoFailures !== undefined
|
|
433
|
-
? integerAtLeast(config.echoFailures, 'echoFailures', 2, DEFAULT_ECHO_FAILURES)
|
|
434
|
-
: undefined
|
|
435
|
-
const stallSteps = integerAtLeast(config?.stallSteps, 'stallSteps', 1, DEFAULT_STALL_STEPS)
|
|
436
|
-
const stepDownRequests = integerAtLeast(config?.stepDownRequests, 'stepDownRequests', 1, DEFAULT_STEP_DOWN_REQUESTS)
|
|
437
|
-
const refireCooldown = integerAtLeast(config?.refireCooldownSteps, 'refireCooldownSteps', 1, DEFAULT_REFIRE_COOLDOWN_STEPS)
|
|
438
|
-
|
|
439
|
-
// Per-agent runtime state: the breaker cooldown / step-down window, the
|
|
440
|
-
// current reasoning effort the request waterfall observed, and whether this
|
|
441
|
-
// session's degraded stall detection has already been reported. The signal
|
|
442
|
-
// itself always re-derives from the durable event stream, so a resume never
|
|
443
|
-
// inherits a stale verdict; the effort is a read-only observation, never a
|
|
444
|
-
// rewrite outside a fired episode.
|
|
445
|
-
const stateByAgent = new WeakMap()
|
|
446
|
-
const stateOf = (agent) => {
|
|
447
|
-
let state = stateByAgent.get(agent)
|
|
448
|
-
if (state === undefined) {
|
|
449
|
-
state = { cooldown: 0, firedVerdict: undefined, stepDownLeft: 0, currentEffort: undefined, blindWarned: false }
|
|
450
|
-
stateByAgent.set(agent, state)
|
|
451
|
-
}
|
|
452
|
-
return state
|
|
453
|
-
}
|
|
454
|
-
|
|
455
|
-
ctx.on('agent/disposed', ({ agent }) => { stateByAgent.delete(agent) })
|
|
456
|
-
|
|
457
|
-
// One listener, two jobs ordered by where the information lives: the request
|
|
458
|
-
// waterfall sees the effort FIRST (it is part of the resolved call config),
|
|
459
|
-
// so it records the current effort for the NEXT pre-step's threshold
|
|
460
|
-
// resolution, and — only inside a fired episode's window — steps it down.
|
|
461
|
-
ctx.on('agent/request', async (payload, next) => {
|
|
462
|
-
const resolved = await next()
|
|
463
|
-
const agent = payload?.agent
|
|
464
|
-
if (agent === undefined) return resolved
|
|
465
|
-
const state = stateOf(agent)
|
|
466
|
-
// Read-only observation: the effort the route actually resolved. This never
|
|
467
|
-
// changes the request by itself.
|
|
468
|
-
if (typeof resolved?.reasoningEffort === 'string') state.currentEffort = resolved.reasoningEffort
|
|
469
|
-
if (state.stepDownLeft === 0) return resolved
|
|
470
|
-
state.stepDownLeft -= 1
|
|
471
|
-
const lowered = stepDownEffort(resolved?.reasoningEffort)
|
|
472
|
-
if (lowered === undefined) return resolved
|
|
473
|
-
return { ...resolved, reasoningEffort: lowered }
|
|
474
|
-
})
|
|
475
|
-
|
|
476
|
-
// Fold the signal and inject the breaker message. step/start is not emitted
|
|
477
|
-
// as a ctx event on every host, so the fold runs inside pre-step — the one
|
|
478
|
-
// hook guaranteed before each model request — using the effort the most
|
|
479
|
-
// recent agent/request observation recorded (undefined until the first one).
|
|
480
|
-
ctx.on('agent/pre-step', async (payload, next) => {
|
|
481
|
-
const decision = await next()
|
|
482
|
-
if (decision.kind !== 'enter') return decision
|
|
483
|
-
const agent = payload?.agent
|
|
484
|
-
if (agent === undefined) return decision
|
|
485
|
-
const state = stateOf(agent)
|
|
486
|
-
|
|
487
|
-
const thresholds = resolveThresholds({
|
|
488
|
-
effort: state.currentEffort,
|
|
489
|
-
sensitivity,
|
|
490
|
-
stallReasoningChars: overrideStallChars,
|
|
491
|
-
globalStallCap: overrideGlobalCap,
|
|
492
|
-
echoFailures: overrideEcho,
|
|
493
|
-
})
|
|
494
|
-
const verdict = foldGuardSignal(sessionEvents(agent.session), { stallSteps, ...thresholds })
|
|
495
|
-
|
|
496
|
-
// A redacted route makes both character ladders structurally dead; the fold
|
|
497
|
-
// has fallen back to step counts. Say so once per agent, because a session
|
|
498
|
-
// whose stall detection is degraded is a fact an operator debugging a
|
|
499
|
-
// missed episode needs, and the breaker's own fire log never carries it.
|
|
500
|
-
if (verdict.blind && !state.blindWarned) {
|
|
501
|
-
state.blindWarned = true
|
|
502
|
-
try { ctx.logger?.warn?.(`${name}: this session persisted reasoning blocks without any reasoning text, so stall detection is degraded to step counts (${thresholds.blindStallCap} consecutive output-free steps)`) } catch {}
|
|
503
|
-
}
|
|
504
|
-
|
|
505
|
-
if (verdict.signal !== undefined && state.cooldown === 0) {
|
|
506
|
-
// Fire: inject the breaker message, and arm the effort step-down only for
|
|
507
|
-
// a STALL. A stall is an over-large reasoning budget, which is what
|
|
508
|
-
// lowering the effort addresses; an echo is a broken call, where
|
|
509
|
-
// weakening the model would only make the loop harder to escape.
|
|
510
|
-
state.cooldown = refireCooldown
|
|
511
|
-
if (verdict.signal === 'stall') state.stepDownLeft = stepDownRequests
|
|
512
|
-
state.firedVerdict = verdict
|
|
513
|
-
const message = {
|
|
514
|
-
id: globalThis.crypto.randomUUID(),
|
|
515
|
-
role: 'user',
|
|
516
|
-
content: [{ type: 'text', text: renderGuardMessage(verdict) }],
|
|
517
|
-
source: { kind: name },
|
|
518
|
-
}
|
|
519
|
-
try { ctx.logger?.warn?.(`${name}: circuit breaker fired (${verdict.detail}) [${thresholds.stallReasoningChars}ch/${thresholds.globalStallCap}steps/${thresholds.echoFailures}fails, ${sensitivity}, effort ${state.currentEffort ?? 'unknown'}, ${verdict.signal === 'stall' ? `step-down ${String(stepDownRequests)} requests` : 'message only'}]`) } catch {}
|
|
520
|
-
return { ...decision, messages: [...decision.messages, message] }
|
|
521
|
-
}
|
|
522
|
-
|
|
523
|
-
if (state.cooldown > 0) state.cooldown -= 1
|
|
524
|
-
return decision
|
|
525
|
-
})
|
|
526
|
-
}
|