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