@linxin666/dsh-liangshen 0.3.23 → 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 +55 -41
- package/README.zh.md +54 -40
- package/cordis.patch.yml +3 -2
- package/icon.svg +3 -0
- package/lib/client.js +1380 -29
- package/lib/client.js.map +1 -1
- package/lib/index.js +616 -367
- package/lib/types/announce.test.d.ts +10 -0
- package/lib/types/client/LiangShenSettingsCard.d.ts +78 -0
- package/lib/types/client/PluginSettingsCard.d.ts +137 -0
- package/lib/types/client/index.d.ts +57 -4
- package/lib/types/client/lever-controller.d.ts +16 -2
- package/lib/types/client/locales.d.ts +40 -1
- package/lib/types/client/main-session.d.ts +32 -0
- package/lib/types/client/plugin-card-seat.d.ts +103 -0
- package/lib/types/client/settings-form.d.ts +197 -0
- package/lib/types/composition.d.ts +116 -0
- package/lib/types/composition.test.d.ts +7 -0
- package/lib/types/core/lever.d.ts +6 -3
- package/lib/types/index.d.ts +160 -33
- package/lib/types/index.test.d.ts +5 -0
- package/package.json +27 -18
- package/presets/liangshen/NOTICE +4 -4
- package/presets/liangshen/agent.cordis.yml +168 -123
- package/presets/liangshen/fact-ledger.mjs +141 -0
- package/presets/liangshen/guard.mjs +426 -0
- package/presets/liangshen/minimal-prompt.mjs +73 -38
- package/presets/liangshen/paging.mjs +232 -0
- package/presets/liangshen/tool-activate.mjs +176 -0
- package/presets/liangshen/tool-catalog.mjs +615 -219
- package/presets/liangshen/working-context.mjs +222 -0
- package/src/announce.test.ts +248 -55
- package/src/client/LiangShenLever.module.css +2 -0
- package/src/client/LiangShenLever.tsx +41 -10
- package/src/client/LiangShenSettingsCard.tsx +233 -0
- package/src/client/PluginSettingsCard.tsx +555 -0
- package/src/client/index.ts +102 -5
- package/src/client/lever-controller.ts +76 -9
- package/src/client/locales.ts +79 -1
- package/src/client/main-session.ts +43 -0
- package/src/client/plugin-card-seat.ts +192 -0
- package/src/client/settings-card.module.css +418 -0
- package/src/client/settings-form.ts +442 -0
- package/src/composition.test.ts +294 -0
- package/src/composition.ts +554 -0
- package/src/core/lever.ts +7 -4
- package/src/index.test.ts +68 -1
- package/src/index.ts +293 -101
- package/tools/benchmark-live-run.mjs +193 -63
- package/lib/types/schema.d.ts +0 -18
- package/lib/types/schema.test.d.ts +0 -1
- package/lib/types/sync.d.ts +0 -47
- package/lib/types/sync.test.d.ts +0 -1
- package/presets/liangshen/custom-bash.mjs +0 -213
- package/src/schema.test.ts +0 -64
- package/src/schema.ts +0 -110
- package/src/sync.test.ts +0 -224
- package/src/sync.ts +0 -222
|
@@ -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
|
+
}
|
|
@@ -1,42 +1,56 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* minimal-prompt — keep this preset's system prompt on the builtin Minimal
|
|
3
3
|
* preset's one-line persona (plus the session's workspace directory) while the
|
|
4
|
-
* tool
|
|
5
|
-
*
|
|
4
|
+
* sibling tool-catalog plugin owns the wire: one presentation declaration per
|
|
5
|
+
* session ('native' | 'ptc' | 'both') and gentle paging for high-fan-out
|
|
6
|
+
* namespaces.
|
|
6
7
|
*
|
|
7
8
|
* The assembled prompt is filtered down to the persona section, plus the plan
|
|
8
|
-
* policy when plan mode is active
|
|
9
|
-
* (`tools:sdk` and `tools:ptc-only`) when
|
|
9
|
+
* policy when plan mode is active, plus the official PTC tool SDK sections
|
|
10
|
+
* (`tools:sdk` and `tools:ptc-only`) exactly when the assembled wire carries
|
|
11
|
+
* the `run_code` transport (presentations 'ptc' and 'both'; an unreadable wire
|
|
12
|
+
* keeps them, matching the harness's own empty-section drop): the harness
|
|
10
13
|
* identity, web-surface, tool-guidance, file-reference, and structured-output
|
|
11
|
-
* sections never reach the model.
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
14
|
+
* sections never reach the model. Keeping the official SDK sections when the
|
|
15
|
+
* transport is present ensures the model receives the complete generated tool
|
|
16
|
+
* signatures, argument types, output schemas, and parameter comments without
|
|
17
|
+
* private SDK schemas or renderer duplication.
|
|
15
18
|
*
|
|
16
19
|
* WORKSPACE LINE: the bare persona says nothing about where the session
|
|
17
20
|
* operates, so the selected workspace directory is appended to the persona at
|
|
18
21
|
* assembly time (`Your working directory is <cwd>.`), read from the session
|
|
19
22
|
* header. This is the only orientation fact the persona block carries.
|
|
20
23
|
*
|
|
21
|
-
* WORKSPACE INSTRUCTIONS (default `
|
|
22
|
-
* AGENTS.md-style instruction files the
|
|
23
|
-
* context are instead read at assembly time and become part of the system
|
|
24
|
-
* prompt itself, as one `workspace-instructions` section appended after the
|
|
25
|
-
* persona block and plan mode's policy. Discovery mirrors the harness's
|
|
26
|
-
* baseline chain — `$DSH_HOME/AGENTS.md`, then `AGENTS.md` / `CLAUDE.md` and
|
|
27
|
-
* their `.local` overlays from the project root (the nearest ancestor holding
|
|
28
|
-
* a `.git` marker) down to the session cwd, broadest first, with the harness's
|
|
29
|
-
* per-directory duplicate suppression and byte budget — so the content rides
|
|
30
|
-
* the prompt on every request: it survives compaction, needs no durable
|
|
31
|
-
* message, and picks up file edits on the next assembly. The section is
|
|
32
|
-
* appended after the stable prefix, so the anchor's KV-cache prefix stays
|
|
33
|
-
* intact. Because the harness's prompt renderer interpolates every section
|
|
34
|
-
* strictly, the section text is only a `{{workspace_instructions}}` reference
|
|
35
|
-
* and the rendered content travels as that assembly variable's value —
|
|
36
|
-
* variable values are inserted verbatim and never re-scanned, so instruction
|
|
37
|
-
* files may contain `{{...}}` examples without breaking every request.
|
|
24
|
+
* WORKSPACE INSTRUCTIONS (`instructionSource`, default `'host'`): where the
|
|
25
|
+
* AGENTS.md-style instruction files reach the model.
|
|
38
26
|
*
|
|
39
|
-
*
|
|
27
|
+
* - `'host'` (default): the plugin appends no prompt section and leaves
|
|
28
|
+
* `decision.messages` byte-for-byte untouched, so the preset's own mounted
|
|
29
|
+
* `@deepseek-ai/dsh-agent-instructions` row delivers the baseline and the
|
|
30
|
+
* dynamic subdirectory instructions as ordinary user-role messages, exactly
|
|
31
|
+
* as the upstream presets do. The system prompt stays the bare persona (plus
|
|
32
|
+
* plan mode's policy), and the durability cost is the harness's: the baseline
|
|
33
|
+
* is a message the host re-derives on every step, not prompt text that
|
|
34
|
+
* survives compaction for free.
|
|
35
|
+
* - `'system-prompt'`: the files are instead read at assembly time and become
|
|
36
|
+
* part of the system prompt itself, as one `workspace-instructions` section
|
|
37
|
+
* appended after the persona block and plan mode's policy, while the
|
|
38
|
+
* harness's own injections are condensed or dropped so nothing duplicates.
|
|
39
|
+
* Discovery mirrors the harness's baseline chain — `$DSH_HOME/AGENTS.md`,
|
|
40
|
+
* then `AGENTS.md` / `CLAUDE.md` and their `.local` overlays from the
|
|
41
|
+
* project root (the nearest ancestor holding a `.git` marker) down to the
|
|
42
|
+
* session cwd, broadest first, with the harness's per-directory duplicate
|
|
43
|
+
* suppression and byte budget — so the content rides the prompt on every
|
|
44
|
+
* request: it survives compaction, needs no durable message, and picks up
|
|
45
|
+
* file edits on the next assembly. The section is appended after the stable
|
|
46
|
+
* prefix, so the anchor's KV-cache prefix stays intact. Because the harness's
|
|
47
|
+
* prompt renderer interpolates every section strictly, the section text is
|
|
48
|
+
* only a `{{workspace_instructions}}` reference and the rendered content
|
|
49
|
+
* travels as that assembly variable's value — variable values are inserted
|
|
50
|
+
* verbatim and never re-scanned, so instruction files may contain `{{...}}`
|
|
51
|
+
* examples without breaking every request.
|
|
52
|
+
*
|
|
53
|
+
* DYNAMIC RECONCILIATION & HOST CONTRACT (`'system-prompt'` only):
|
|
40
54
|
* - Baseline instructions are resident in the system prompt. When the host's
|
|
41
55
|
* agent-instructions emits a pure baseline message (`source.baseline === true`),
|
|
42
56
|
* if the baseline was successfully loaded in the system prompt for this session,
|
|
@@ -59,10 +73,12 @@
|
|
|
59
73
|
* instructions triggered by an inner read/edit are projected on the NEXT step;
|
|
60
74
|
* same-program writes execute before that next-step projection reaches model context.
|
|
61
75
|
*
|
|
62
|
-
* `instructionSource: 'hint'`
|
|
76
|
+
* `instructionSource: 'hint'` is the third source: the first injection
|
|
63
77
|
* becomes a single non-imperative pointer to the reference files (issue #388,
|
|
64
78
|
* upstream dsh-anchored-standard #49) and every later injection is dropped; the
|
|
65
|
-
* model reaches the knowledge through read / skill_load.
|
|
79
|
+
* model reaches the knowledge through read / skill_load. Like `'host'` it
|
|
80
|
+
* appends no prompt section, but unlike `'host'` it rewrites the host's
|
|
81
|
+
* messages.
|
|
66
82
|
*
|
|
67
83
|
* PLAN MODE is kept by default. `dsh-plan-mode` enforces its rules through
|
|
68
84
|
* the `plan:policy` prompt section alone. `keepPlanPolicy: false` restores the
|
|
@@ -106,8 +122,13 @@ export const PTC_SECTION_NAMES = ['tools:ptc-only', 'tools:sdk']
|
|
|
106
122
|
export const WORKSPACE_INSTRUCTIONS_SECTION_NAME = 'workspace-instructions'
|
|
107
123
|
export const WORKSPACE_INSTRUCTIONS_VARIABLE = 'workspace_instructions'
|
|
108
124
|
|
|
109
|
-
/**
|
|
110
|
-
|
|
125
|
+
/**
|
|
126
|
+
* Accepted `instructionSource` values, default first: `'host'` hands the
|
|
127
|
+
* instructions back to the harness's own user-role injection, `'system-prompt'`
|
|
128
|
+
* lifts them into the system prompt, `'hint'` replaces them with a one-time
|
|
129
|
+
* pointer.
|
|
130
|
+
*/
|
|
131
|
+
export const INSTRUCTION_SOURCES = ['host', 'system-prompt', 'hint']
|
|
111
132
|
|
|
112
133
|
/** Tools whose executions touch workspace files and may trigger dynamic instruction discovery. */
|
|
113
134
|
export const FILE_TOUCH_TOOL_NAMES = new Set(['read', 'write', 'edit', 'str_replace_editor'])
|
|
@@ -391,7 +412,7 @@ export function buildInstructionHint(original, paths) {
|
|
|
391
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.'
|
|
392
413
|
+ '\n</system-reminder>',
|
|
393
414
|
}],
|
|
394
|
-
source: { kind:
|
|
415
|
+
source: { kind: name },
|
|
395
416
|
}
|
|
396
417
|
}
|
|
397
418
|
|
|
@@ -664,13 +685,8 @@ export function withWorkspaceLine(sections, agent) {
|
|
|
664
685
|
/** Register the section filter, workspace-instruction source, and dynamic discovery hooks. */
|
|
665
686
|
export function apply(ctx, config) {
|
|
666
687
|
const keepPlanPolicy = optionalBoolean(config?.keepPlanPolicy, 'keepPlanPolicy', true)
|
|
667
|
-
const instructionSource = optionalSource(config?.instructionSource, 'instructionSource', '
|
|
688
|
+
const instructionSource = optionalSource(config?.instructionSource, 'instructionSource', 'host')
|
|
668
689
|
const instructionMaxBytes = optionalByteSize(config?.instructionMaxBytes, 'instructionMaxBytes', DEFAULT_INSTRUCTION_MAX_BYTES)
|
|
669
|
-
const keep = new Set([
|
|
670
|
-
...PERSONA_SECTION_NAMES,
|
|
671
|
-
...(keepPlanPolicy ? [PLAN_POLICY_SECTION_NAME] : []),
|
|
672
|
-
...PTC_SECTION_NAMES,
|
|
673
|
-
])
|
|
674
690
|
|
|
675
691
|
// Per-session state tracking (durable across steps, recoverable on replay)
|
|
676
692
|
const sessionStateMap = new WeakMap()
|
|
@@ -724,6 +740,17 @@ export function apply(ctx, config) {
|
|
|
724
740
|
ctx.on('system-prompt/assemble', async (_assembly, context, next) => {
|
|
725
741
|
const assembled = await next()
|
|
726
742
|
if (!Array.isArray(assembled.sections)) return assembled
|
|
743
|
+
// The official SDK sections belong to the run_code transport: keep them
|
|
744
|
+
// exactly when this assembly's wire carries it ('ptc' and 'both'), drop
|
|
745
|
+
// them from a native wire they would only confuse. An unreadable wire keeps
|
|
746
|
+
// them, matching the harness's own empty-section drop under 'native'.
|
|
747
|
+
const wire = Array.isArray(assembled?.tools) ? assembled.tools : undefined
|
|
748
|
+
const wireHasRunCode = wire === undefined ? true : wire.some(tool => tool?.name === 'run_code')
|
|
749
|
+
const keep = new Set([
|
|
750
|
+
...PERSONA_SECTION_NAMES,
|
|
751
|
+
...(keepPlanPolicy ? [PLAN_POLICY_SECTION_NAME] : []),
|
|
752
|
+
...(wireHasRunCode ? PTC_SECTION_NAMES : []),
|
|
753
|
+
])
|
|
727
754
|
const sections = assembled.sections.filter(section => keep.has(section?.name))
|
|
728
755
|
if (sections.length === 0) {
|
|
729
756
|
warnOnce(`${name}: no section matched ${JSON.stringify([...keep])} — `
|
|
@@ -731,6 +758,8 @@ export function apply(ctx, config) {
|
|
|
731
758
|
return assembled
|
|
732
759
|
}
|
|
733
760
|
const narrowed = withWorkspaceLine(sections, context?.agent)
|
|
761
|
+
// 'host' and 'hint' append no workspace-instructions section: the harness's
|
|
762
|
+
// own agent-instructions row carries the content (or the hint replaces it).
|
|
734
763
|
if (instructionSource !== 'system-prompt') return { ...assembled, sections: narrowed }
|
|
735
764
|
|
|
736
765
|
let text
|
|
@@ -788,6 +817,12 @@ export function apply(ctx, config) {
|
|
|
788
817
|
return { ...decision, messages: instructionHintMessages(decision.messages, state) }
|
|
789
818
|
}
|
|
790
819
|
|
|
820
|
+
// Host mode: the harness's agent-instructions row owns the channel, so every
|
|
821
|
+
// message it queued — baseline and dynamic alike — passes through verbatim:
|
|
822
|
+
// no filterInstructionMessages, no dynamic subdirectory discovery, no
|
|
823
|
+
// plugin-authored message. Handing the decision back unchanged is the point.
|
|
824
|
+
if (instructionSource === 'host') return decision
|
|
825
|
+
|
|
791
826
|
// System-prompt mode:
|
|
792
827
|
const cwd = session?.header?.cwd
|
|
793
828
|
const baselineLoaded = state?.baselineLoaded ?? false
|
|
@@ -814,7 +849,7 @@ export function apply(ctx, config) {
|
|
|
814
849
|
type: 'text',
|
|
815
850
|
text: `<system-reminder>\n${newSections.join('\n\n')}\n</system-reminder>`,
|
|
816
851
|
}],
|
|
817
|
-
source: { kind:
|
|
852
|
+
source: { kind: name },
|
|
818
853
|
})
|
|
819
854
|
}
|
|
820
855
|
}
|