@linxin666/dsh-liangshen 0.3.24 → 0.4.0
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 +24 -17
- package/README.zh.md +25 -18
- package/cordis.patch.yml +3 -2
- package/icon.svg +3 -0
- package/lib/client.js +381 -77
- package/lib/client.js.map +1 -1
- package/lib/index.js +594 -428
- package/lib/types/announce.test.d.ts +10 -0
- package/lib/types/client/LiangShenSettingsCard.d.ts +27 -10
- package/lib/types/client/PluginSettingsCard.d.ts +4 -0
- package/lib/types/client/index.d.ts +32 -13
- package/lib/types/client/lever-controller.d.ts +16 -2
- package/lib/types/client/locales.d.ts +13 -0
- package/lib/types/client/main-session.d.ts +32 -0
- package/lib/types/client/plugin-card-seat.d.ts +23 -16
- package/lib/types/client/settings-form.d.ts +17 -17
- package/lib/types/composition.d.ts +116 -0
- package/lib/types/composition.test.d.ts +7 -0
- package/lib/types/index.d.ts +146 -31
- package/lib/types/index.test.d.ts +5 -0
- package/package.json +25 -20
- package/presets/liangshen/agent.cordis.yml +44 -10
- package/presets/liangshen/fact-ledger.mjs +141 -0
- package/presets/liangshen/guard.mjs +426 -0
- package/presets/liangshen/minimal-prompt.mjs +2 -2
- package/presets/liangshen/tool-catalog.mjs +24 -20
- package/presets/liangshen/working-context.mjs +10 -2
- package/src/announce.test.ts +248 -55
- package/src/client/LiangShenLever.module.css +2 -0
- package/src/client/LiangShenLever.tsx +37 -9
- package/src/client/LiangShenSettingsCard.tsx +96 -12
- package/src/client/PluginSettingsCard.tsx +7 -2
- package/src/client/index.ts +61 -23
- package/src/client/lever-controller.ts +76 -9
- package/src/client/locales.ts +30 -4
- package/src/client/main-session.ts +43 -0
- package/src/client/plugin-card-seat.ts +24 -17
- package/src/client/settings-form.ts +34 -31
- package/src/composition.test.ts +294 -0
- package/src/composition.ts +554 -0
- package/src/index.test.ts +68 -1
- package/src/index.ts +278 -107
- package/tools/benchmark-live-run.mjs +171 -32
- package/lib/types/schema.d.ts +0 -18
- package/lib/types/schema.test.d.ts +0 -1
- package/lib/types/sync.d.ts +0 -74
- package/lib/types/sync.test.d.ts +0 -1
- package/src/schema.test.ts +0 -64
- package/src/schema.ts +0 -110
- package/src/sync.test.ts +0 -303
- package/src/sync.ts +0 -324
|
@@ -0,0 +1,426 @@
|
|
|
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
|
+
}
|
|
@@ -412,7 +412,7 @@ export function buildInstructionHint(original, paths) {
|
|
|
412
412
|
+ 'Reading the relevant file before workspace tasks is recommended, but consult them only when you need those details; the task itself never depends on them.'
|
|
413
413
|
+ '\n</system-reminder>',
|
|
414
414
|
}],
|
|
415
|
-
source: { kind:
|
|
415
|
+
source: { kind: name },
|
|
416
416
|
}
|
|
417
417
|
}
|
|
418
418
|
|
|
@@ -849,7 +849,7 @@ export function apply(ctx, config) {
|
|
|
849
849
|
type: 'text',
|
|
850
850
|
text: `<system-reminder>\n${newSections.join('\n\n')}\n</system-reminder>`,
|
|
851
851
|
}],
|
|
852
|
-
source: { kind:
|
|
852
|
+
source: { kind: name },
|
|
853
853
|
})
|
|
854
854
|
}
|
|
855
855
|
}
|
|
@@ -125,9 +125,13 @@ export const DEFAULT_PRESENTATION = 'ptc'
|
|
|
125
125
|
* growth — a deployment adding tool families of its own — instead of the shipped
|
|
126
126
|
* configuration. The guard warns once per session and never truncates: silently
|
|
127
127
|
* dropping a tool the session needs would trade a measurable context cost for an
|
|
128
|
-
* unmeasurable capability loss.
|
|
128
|
+
* unmeasurable capability loss. The budget was re-estimated for DeepSeek-V4.1:
|
|
129
|
+
* its KV cache is a quarter of V4-Flash's (890 bytes/token), so the same schema
|
|
130
|
+
* load occupies a quarter of the sparse-index slots and the threshold moved from
|
|
131
|
+
* 6000 to 8000 — still calibrated above the shipped roster so only real growth
|
|
132
|
+
* trips it.
|
|
129
133
|
*/
|
|
130
|
-
export const DEFAULT_MAX_RESIDENT_TOKENS =
|
|
134
|
+
export const DEFAULT_MAX_RESIDENT_TOKENS = 8000
|
|
131
135
|
|
|
132
136
|
/**
|
|
133
137
|
* Rough token estimate for one tool surface: the serialized schema is the
|
|
@@ -322,7 +326,7 @@ const PTC_PROGRAM_LINES = [
|
|
|
322
326
|
* through the SDK inside a program even before activation.
|
|
323
327
|
*/
|
|
324
328
|
const BOTH_PROGRAM_LINES = [
|
|
325
|
-
'
|
|
329
|
+
'Prefer calling the tools above directly by name: ordinary single-step work (read, edit, bash, one search) goes through the native call, never through `run_code`. Reserve `run_code` for what a direct call cannot do — an async TypeScript body (`code`, with a short `description`) that reaches tools as `await tools.<name>({ ... })`, overlaps independent read-only calls under `Promise.all`, and catches `ToolCallError` to continue: programmatic batch computation, wide fan-out, or multi-step data shaping. Routing everyday calls through a program adds a wrapping layer with no payoff.',
|
|
326
330
|
'Paged-out namespaces below stay off the NATIVE wire but stay reachable through the SDK inside a program even before activation; activating one also puts its tools back on the direct surface.',
|
|
327
331
|
]
|
|
328
332
|
|
|
@@ -423,7 +427,7 @@ export function createCatalogMessage(entries, presentation = 'native', inactive
|
|
|
423
427
|
id: globalThis.crypto.randomUUID(),
|
|
424
428
|
role: 'user',
|
|
425
429
|
content: [{ type: 'text', text: renderCatalogText(entries, presentation, inactive) }],
|
|
426
|
-
source: { kind:
|
|
430
|
+
source: { kind: name },
|
|
427
431
|
}
|
|
428
432
|
}
|
|
429
433
|
|
|
@@ -439,7 +443,7 @@ function textOf(message) {
|
|
|
439
443
|
/** Whether one message is this plugin's catalog. */
|
|
440
444
|
function isCatalogMessage(message) {
|
|
441
445
|
const source = message?.source
|
|
442
|
-
return source?.kind === 'plugin' && source?.plugin === name
|
|
446
|
+
return source?.kind === name || (source?.kind === 'plugin' && source?.plugin === name)
|
|
443
447
|
}
|
|
444
448
|
|
|
445
449
|
/**
|
|
@@ -652,7 +656,11 @@ export function apply(ctx, config) {
|
|
|
652
656
|
|
|
653
657
|
|
|
654
658
|
const registry = () => ctx.get('tools')
|
|
655
|
-
|
|
659
|
+
// The 0.1.6 cohort renamed the service face from `codeRuntime` to
|
|
660
|
+
// `ptcRuntime` (package `@deepseek-ai/dsh-code-runtime` became
|
|
661
|
+
// `@deepseek-ai/dsh-ptc-runtime`); the old key is gone, so reading it would
|
|
662
|
+
// silently disable PTC staging for every session.
|
|
663
|
+
const transportReady = () => presentation !== 'native' && ctx.get('ptcRuntime') !== undefined
|
|
656
664
|
|
|
657
665
|
/**
|
|
658
666
|
* Declare this agent scope's presentation through the public
|
|
@@ -774,14 +782,18 @@ export function apply(ctx, config) {
|
|
|
774
782
|
return undefined
|
|
775
783
|
}
|
|
776
784
|
|
|
777
|
-
// Early lifecycle
|
|
785
|
+
// Early lifecycle hook: declare the presentation and page the scope as soon
|
|
778
786
|
// as it exists.
|
|
779
787
|
//
|
|
780
|
-
// The
|
|
781
|
-
// `agent/
|
|
782
|
-
// the
|
|
783
|
-
//
|
|
784
|
-
//
|
|
788
|
+
// The 0.1.6 cohort folded the former `agent/session-start` into the async
|
|
789
|
+
// serial `agent/created`, which carries the same payload object and runs
|
|
790
|
+
// before the first prompt assembly; the host waits for this listener, so the
|
|
791
|
+
// declaration is already in place when that assembly reads the presentation.
|
|
792
|
+
//
|
|
793
|
+
// The payload is destructured ON PURPOSE: `agent/created` passes its payload
|
|
794
|
+
// OBJECT as the first argument, not the agent itself. Reading that parameter
|
|
795
|
+
// as the agent yields an object with no `session` and no `ctx`, so the
|
|
796
|
+
// declaration is skipped and paging silently never engages.
|
|
785
797
|
ctx.on('agent/created', ({ agent }) => {
|
|
786
798
|
if (agent?.session !== undefined) agentBySession.set(agent.session, agent)
|
|
787
799
|
if (transportReady()) declarePresentation(agent)
|
|
@@ -813,14 +825,6 @@ export function apply(ctx, config) {
|
|
|
813
825
|
return next()
|
|
814
826
|
}, { prepend: true })
|
|
815
827
|
|
|
816
|
-
ctx.on('agent/session-start', ({ agent }) => {
|
|
817
|
-
if (agent?.session !== undefined) agentBySession.set(agent.session, agent)
|
|
818
|
-
if (transportReady()) declarePresentation(agent)
|
|
819
|
-
// The last point before the first turn assembles a prompt: a resumed
|
|
820
|
-
// session starts its first request already paged.
|
|
821
|
-
syncBeforeAssembly(agent)
|
|
822
|
-
})
|
|
823
|
-
|
|
824
828
|
// Per-agent, not one process-wide flag: two sessions assembling at once would
|
|
825
829
|
// otherwise let one skip the re-assembly the other is running.
|
|
826
830
|
const reassembling = new WeakSet()
|
|
@@ -34,6 +34,8 @@ import {
|
|
|
34
34
|
validatePagedToolPatterns,
|
|
35
35
|
} from './paging.mjs'
|
|
36
36
|
|
|
37
|
+
import { foldFactLedger, renderLedgerField } from './fact-ledger.mjs'
|
|
38
|
+
|
|
37
39
|
/** Cordis plugin name used by loader diagnostics. */
|
|
38
40
|
export const name = 'liangshen-working-context'
|
|
39
41
|
|
|
@@ -110,6 +112,12 @@ export function renderWorkingContext(events, options) {
|
|
|
110
112
|
fields.push(`in progress: ${shown.join('; ')}${rest > 0 ? `; +${rest} more` : ''}`)
|
|
111
113
|
}
|
|
112
114
|
|
|
115
|
+
// The key-fact register: facts the model pinned with fact_register, folded
|
|
116
|
+
// from the same event stream, ride this line so they land inside the local
|
|
117
|
+
// attention window every step.
|
|
118
|
+
const ledgerField = renderLedgerField(foldFactLedger(events))
|
|
119
|
+
if (ledgerField !== undefined) fields.push(ledgerField)
|
|
120
|
+
|
|
113
121
|
return fields.length === 0 ? undefined : `[Working Context: ${fields.join(' | ')}]`
|
|
114
122
|
}
|
|
115
123
|
|
|
@@ -125,7 +133,7 @@ function textOf(message) {
|
|
|
125
133
|
/** Whether one message is this plugin's working-context line. */
|
|
126
134
|
function isContextMessage(message) {
|
|
127
135
|
const source = message?.source
|
|
128
|
-
return source?.kind === 'plugin' && source?.plugin === name
|
|
136
|
+
return source?.kind === name || (source?.kind === 'plugin' && source?.plugin === name)
|
|
129
137
|
}
|
|
130
138
|
|
|
131
139
|
/** Visible surface positions, or undefined when the session exposes none. */
|
|
@@ -160,7 +168,7 @@ export function createContextMessage(line) {
|
|
|
160
168
|
id: globalThis.crypto.randomUUID(),
|
|
161
169
|
role: 'user',
|
|
162
170
|
content: [{ type: 'text', text: line }],
|
|
163
|
-
source: { kind:
|
|
171
|
+
source: { kind: name },
|
|
164
172
|
}
|
|
165
173
|
}
|
|
166
174
|
|