@linxin666/dsh-liangshen 0.4.18 → 0.4.20

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.
@@ -14,27 +14,40 @@
14
14
  * not depend on.
15
15
  * - `active namespaces: ...` — the paged tool namespaces currently on the
16
16
  * wire, replayed from `tool_activate` calls exactly the way the wire
17
- * partition in tool-catalog replays them.
17
+ * partition in tool-catalog replays them. Deferred idle reclaim
18
+ * (`idleReclaimSteps`) is applied by the same replay, so the line names
19
+ * exactly the applied active set.
18
20
  * - `in progress: ...` — the in-progress todo titles from the latest
19
21
  * `todo/write` event, cleared by the next `turn/start`, mirroring the host's
20
22
  * todos projection.
21
23
  *
22
24
  * When no field has anything to say the step is left untouched. The injection
23
- * and dedup discipline mirrors tool-catalog's pre-step: the message is
24
- * persistent, carries the plugin source shape, and a replacement is published
25
- * only when the rendered line changed or the published copy left the visible
26
- * surface.
25
+ * and dedup discipline is shared with tool-catalog's pre-step (paging.mjs owns
26
+ * it): the message is persistent, carries the plugin source shape, and a
27
+ * replacement is published only when the rendered line changed or the published
28
+ * copy left the visible surface.
29
+ *
30
+ * Every field folds in ONE pass over the durable stream: the plan-mode and todo
31
+ * projections, the register, and the failed-call index the activation replay
32
+ * needs are read event by event, and the replay itself only runs when the log
33
+ * holds an activation at all.
27
34
  */
28
35
 
29
36
  import {
37
+ DEFAULT_IDLE_RECLAIM_STEPS,
30
38
  DEFAULT_MAX_ACTIVE_NAMESPACES,
31
39
  DEFAULT_PAGED_TOOL_PATTERNS,
40
+ TOOL_ACTIVATE_NAME,
41
+ erroredCallId,
32
42
  integerAtLeast,
43
+ latestVisiblePluginMessage,
44
+ reconcileStepMessage,
33
45
  replayActivations,
46
+ sessionEvents,
34
47
  validatePagedToolPatterns,
35
48
  } from './paging.mjs'
36
49
 
37
- import { foldFactLedger, renderLedgerField } from './fact-ledger.mjs'
50
+ import { applyFactLedgerEvent, renderLedgerField } from './fact-ledger.mjs'
38
51
 
39
52
  /** Cordis plugin name used by loader diagnostics. */
40
53
  export const name = 'liangshen-working-context'
@@ -45,23 +58,33 @@ const MAX_TITLE_CHARS = 80
45
58
  /** At most this many in-progress titles render; the rest collapse to a count. */
46
59
  const MAX_TITLES = 3
47
60
 
48
- /** Session events, tolerating both snapshotEvents() and events array. */
49
- function sessionEvents(session) {
50
- if (Array.isArray(session?.events)) return session.events
51
- if (typeof session?.snapshotEvents === 'function') return session.snapshotEvents()
52
- return []
61
+ /** Fold one event into the plan-mode projection: the last plan/mode event wins. */
62
+ function foldPlanMode(projection, event) {
63
+ if (event?.type !== 'plan/mode' || typeof event.data?.active !== 'boolean') return projection
64
+ projection.seen = true
65
+ projection.active = event.data.active
66
+ return projection
67
+ }
68
+
69
+ /** Fold one event into the todo projection: the latest list, cleared by the next turn/start. */
70
+ function foldTodos(current, event) {
71
+ if (event?.type === 'turn/start') return undefined
72
+ if (event?.type === 'todo/write' && Array.isArray(event.data?.todos)) return event.data.todos
73
+ return current
74
+ }
75
+
76
+ /** The in-progress titles of one folded todo list, in list order. */
77
+ function inProgressTitles(todos) {
78
+ return (todos ?? [])
79
+ .filter(item => item?.status === 'in_progress' && typeof item?.content === 'string' && item.content.trim() !== '')
80
+ .map(item => item.content.trim())
53
81
  }
54
82
 
55
83
  /** The latest plan/mode state in the log: seen flag plus active value. */
56
84
  export function planModeState(events) {
57
- let seen = false
58
- let active = false
59
- for (const event of Array.isArray(events) ? events : []) {
60
- if (event?.type !== 'plan/mode' || typeof event.data?.active !== 'boolean') continue
61
- seen = true
62
- active = event.data.active
63
- }
64
- return { seen, active }
85
+ const projection = { seen: false, active: false }
86
+ for (const event of Array.isArray(events) ? events : []) foldPlanMode(projection, event)
87
+ return projection
65
88
  }
66
89
 
67
90
  /**
@@ -70,18 +93,8 @@ export function planModeState(events) {
70
93
  */
71
94
  export function inProgressTodos(events) {
72
95
  let todos
73
- for (const event of Array.isArray(events) ? events : []) {
74
- if (event?.type === 'turn/start') {
75
- todos = undefined
76
- continue
77
- }
78
- if (event?.type === 'todo/write' && Array.isArray(event.data?.todos)) {
79
- todos = event.data.todos
80
- }
81
- }
82
- return (todos ?? [])
83
- .filter(item => item?.status === 'in_progress' && typeof item?.content === 'string' && item.content.trim() !== '')
84
- .map(item => item.content.trim())
96
+ for (const event of Array.isArray(events) ? events : []) todos = foldTodos(todos, event)
97
+ return inProgressTitles(todos)
85
98
  }
86
99
 
87
100
  /** Clip one title to the per-title budget at a word-ish boundary. */
@@ -93,19 +106,44 @@ function clipTitle(title) {
93
106
  /**
94
107
  * Render the working-context line for one session's events, or undefined when
95
108
  * no field has anything objective to say.
109
+ *
110
+ * One pass over the stream folds everything this line renders plus the two
111
+ * facts the activation replay needs — the failed callIds and whether any
112
+ * activation was recorded at all. Without an activation the replay cannot find
113
+ * an active namespace (it reads activations, plus the recency of families one of
114
+ * them already lifted), so the second pass is skipped instead of walking the
115
+ * whole log again to derive an empty set.
96
116
  */
97
117
  export function renderWorkingContext(events, options) {
98
118
  const patterns = options?.pagedToolPatterns ?? DEFAULT_PAGED_TOOL_PATTERNS
99
119
  const maxActive = options?.maxActiveNamespaces ?? DEFAULT_MAX_ACTIVE_NAMESPACES
100
- const fields = []
120
+ const idleReclaim = options?.idleReclaimSteps ?? DEFAULT_IDLE_RECLAIM_STEPS
121
+ const list = Array.isArray(events) ? events : []
122
+ const plan = { seen: false, active: false }
123
+ const facts = []
124
+ const errored = new Set()
125
+ let todos
126
+ let sawActivation = false
127
+ for (const event of list) {
128
+ foldPlanMode(plan, event)
129
+ todos = foldTodos(todos, event)
130
+ applyFactLedgerEvent(facts, event)
131
+ const failedCallId = erroredCallId(event)
132
+ if (failedCallId !== undefined) errored.add(failedCallId)
133
+ if ((event?.type === 'tool/call' || event?.type === 'tool/ptc-dispatch') && event.data?.name === TOOL_ACTIVATE_NAME) {
134
+ sawActivation = true
135
+ }
136
+ }
101
137
 
102
- const plan = planModeState(events)
138
+ const fields = []
103
139
  if (plan.seen) fields.push(`plan mode: ${plan.active ? 'on' : 'off'}`)
104
140
 
105
- const { active } = replayActivations(events, maxActive, patterns)
106
- if (active.length > 0) fields.push(`active namespaces: ${[...active].sort().join(', ')}`)
141
+ if (sawActivation) {
142
+ const { active } = replayActivations(list, maxActive, patterns, errored, idleReclaim)
143
+ if (active.length > 0) fields.push(`active namespaces: ${[...active].sort().join(', ')}`)
144
+ }
107
145
 
108
- const titles = inProgressTodos(events)
146
+ const titles = inProgressTitles(todos)
109
147
  if (titles.length > 0) {
110
148
  const shown = titles.slice(0, MAX_TITLES).map(clipTitle)
111
149
  const rest = titles.length - shown.length
@@ -115,53 +153,18 @@ export function renderWorkingContext(events, options) {
115
153
  // The key-fact register: facts the model pinned with fact_register, folded
116
154
  // from the same event stream, ride this line so they land inside the local
117
155
  // attention window every step.
118
- const ledgerField = renderLedgerField(foldFactLedger(events))
156
+ const ledgerField = renderLedgerField(facts)
119
157
  if (ledgerField !== undefined) fields.push(ledgerField)
120
158
 
121
159
  return fields.length === 0 ? undefined : `[Working Context: ${fields.join(' | ')}]`
122
160
  }
123
161
 
124
- /** The text one message contributes, joined across its text blocks. */
125
- function textOf(message) {
126
- const blocks = Array.isArray(message?.content) ? message.content : []
127
- return blocks
128
- .filter(block => block?.type === 'text' && typeof block.text === 'string')
129
- .map(block => block.text)
130
- .join('\n')
131
- }
132
-
133
162
  /** Whether one message is this plugin's working-context line. */
134
163
  function isContextMessage(message) {
135
164
  const source = message?.source
136
165
  return source?.kind === name || (source?.kind === 'plugin' && source?.plugin === name)
137
166
  }
138
167
 
139
- /** Visible surface positions, or undefined when the session exposes none. */
140
- function visibleSeqSet(session) {
141
- const nodes = session?.surface?.nodes
142
- return Array.isArray(nodes) ? new Set(nodes) : undefined
143
- }
144
-
145
- /**
146
- * Published working-context state read back from the durable log: the latest
147
- * visible line's text, or just the published flag when every copy was shadowed.
148
- */
149
- function contextHistory(agent) {
150
- const session = agent?.session
151
- const events = sessionEvents(session)
152
- const visible = visibleSeqSet(session)
153
- let published = false
154
- for (let index = events.length - 1; index >= 0; index -= 1) {
155
- const event = events[index]
156
- if (event?.type !== 'user/message' || !isContextMessage(event.data)) continue
157
- published = true
158
- if (visible === undefined || typeof event.seq !== 'number' || visible.has(event.seq)) {
159
- return { published, text: textOf(event.data) }
160
- }
161
- }
162
- return { published }
163
- }
164
-
165
168
  /** Build the durable working-context message for one rendered line. */
166
169
  export function createContextMessage(line) {
167
170
  return {
@@ -182,6 +185,13 @@ export function apply(ctx, config) {
182
185
  1,
183
186
  DEFAULT_MAX_ACTIVE_NAMESPACES,
184
187
  )
188
+ const idleReclaimSteps = integerAtLeast(
189
+ name,
190
+ config?.idleReclaimSteps,
191
+ 'idleReclaimSteps',
192
+ 0,
193
+ DEFAULT_IDLE_RECLAIM_STEPS,
194
+ )
185
195
 
186
196
  ctx.on('agent/pre-step', async (payload, next) => {
187
197
  const decision = await next()
@@ -192,31 +202,19 @@ export function apply(ctx, config) {
192
202
  const line = renderWorkingContext(sessionEvents(agent.session), {
193
203
  pagedToolPatterns,
194
204
  maxActiveNamespaces,
205
+ idleReclaimSteps,
195
206
  })
196
207
 
197
- const history = contextHistory(agent)
198
- const existing = decision.messages.find(message => isContextMessage(message))
199
-
200
- // Nothing objective to say: inject nothing. A stale published line is left
201
- // for compaction to age out rather than replaced with an empty marker.
202
- if (line === undefined) {
203
- if (existing === undefined) return decision
204
- return { ...decision, messages: decision.messages.filter(message => message.id !== existing.id) }
205
- }
206
-
207
- if (history.text === line) {
208
- if (existing === undefined) return decision
209
- return { ...decision, messages: decision.messages.filter(message => message.id !== existing.id) }
210
- }
211
- if (existing !== undefined && textOf(existing) === line) return decision
212
-
213
- const message = createContextMessage(line)
214
- if (existing === undefined) {
215
- return { ...decision, messages: [...decision.messages, message] }
216
- }
217
- return {
218
- ...decision,
219
- messages: decision.messages.map(item => (item.id === existing.id ? message : item)),
220
- }
208
+ // Nothing objective to say: inject nothing (a stale published line is left
209
+ // for compaction to age out rather than replaced with an empty marker). The
210
+ // reconciliation is shared with tool-catalog's pre-step, so the two durable
211
+ // messages republish under exactly the same rules.
212
+ return reconcileStepMessage(
213
+ decision,
214
+ latestVisiblePluginMessage(agent, isContextMessage),
215
+ line,
216
+ () => createContextMessage(line),
217
+ isContextMessage,
218
+ )
221
219
  }, { prepend: true })
222
220
  }
@@ -335,3 +335,61 @@ describe('dsh-liangshen preset declaration', () => {
335
335
  expect(bundledPresetDir()).toContain('presets')
336
336
  })
337
337
  })
338
+
339
+ // A settings write re-declares the preset, and the two preset files cannot
340
+ // change under a running row: re-reading and re-parsing them on every write
341
+ // would block the event loop for a result the activation already holds. The
342
+ // rows no setting touches are therefore the same parsed objects in every
343
+ // declaration of one activation, while each declaration keeps the values it
344
+ // was built with.
345
+ describe('dsh-liangshen preset parse reuse', () => {
346
+ /** One declaration's rows as the loose records these tests read. */
347
+ const rowsOf = (host: FakeHost, index: number) =>
348
+ host.declarations[index]!.definition.plugins as readonly { id?: string, config?: Record<string, unknown>, disabled?: unknown }[]
349
+
350
+ it('operator gets every settings re-arm served by the one parse of the activation', async () => {
351
+ // Given a running row whose presentation the Host commits into
352
+ vi.resetModules()
353
+ const mod = await import('../src/index.ts')
354
+ let presentation = 'ptc'
355
+ const host = makeHost()
356
+ mounted.push(host)
357
+ mod.apply(host.ctx, { presentation: { get: () => presentation } as never })
358
+ await settle()
359
+ expect(host.declarations.length).toBe(1)
360
+
361
+ // When the operator commits a new presentation
362
+ presentation = 'native'
363
+ host.commit()
364
+ await settle()
365
+
366
+ // Then the row the setting shapes follows the write, and the row it does
367
+ // not touch is the very object the first declaration was built from: the
368
+ // activation parsed the preset once instead of reading the disk again
369
+ const catalogOf = (index: number) => rowsOf(host, index).find(row => row.id === 'tool-catalog')?.config?.['presentation']
370
+ expect(catalogOf(1)).toBe('native')
371
+ expect(rowsOf(host, 1).find(row => row.id === 'persona')).toBe(rowsOf(host, 0).find(row => row.id === 'persona'))
372
+
373
+ // And the declaration the write replaced still reports what it declared,
374
+ // so the overlay derived a new row list instead of mutating the cached one
375
+ expect(catalogOf(0)).toBe('ptc')
376
+ expect(rowsOf(host, 0).find(row => row.id === 'tool-executor-ptc')?.disabled).toBe(false)
377
+ expect(rowsOf(host, 1).find(row => row.id === 'tool-executor-ptc')?.disabled).toBe(true)
378
+
379
+ // When the operator commits the shipped value back
380
+ presentation = 'ptc'
381
+ host.commit()
382
+ await settle()
383
+
384
+ // Then the third declaration is the first one again: a re-arm never
385
+ // accumulates the previous write on the cached base
386
+ expect(host.declarations.length).toBe(3)
387
+ expect(catalogOf(2)).toBe('ptc')
388
+ expect(host.declarations[2]?.definition).toEqual(host.declarations[0]?.definition)
389
+ expect(host.declarations.filter(record => !record.released).length).toBe(1)
390
+ // The definition handed to the registry is this declaration's own object
391
+ // though: only the parsed rows are shared, so nothing can rewrite the
392
+ // cached preset through the definition it received.
393
+ expect(host.declarations[1]?.definition).not.toBe(host.declarations[0]?.definition)
394
+ })
395
+ })
@@ -15,7 +15,7 @@ import type { SnapshotStore } from '@deepseek-ai/dsh-client-store'
15
15
  import type { ConfigForm } from '@deepseek-ai/dsh-client-ui-settings/client'
16
16
  import { LiangShenMark } from './LiangShenMark.tsx'
17
17
  import { BooleanField, ChoiceField, PluginSettingsCard, ValueField } from './PluginSettingsCard.tsx'
18
- import { CardForm, booleanField, choiceField, textField, type CardActions, type CardShell, type FieldSpec, type FieldState as CardFieldState } from './settings-form.ts'
18
+ import { CardForm, booleanField, choiceField, numberField, textField, type CardActions, type CardShell, type FieldSpec, type FieldState as CardFieldState } from './settings-form.ts'
19
19
 
20
20
  /** A tool family entry: a prefix ending in exactly one trailing star. */
21
21
  const FAMILY_ENTRY_RE = /^[^*]+\*$/
@@ -52,6 +52,8 @@ export interface LiangShenSettings {
52
52
  dispatcher?: boolean
53
53
  /** Comma-separated on-demand tool families the Host writes to the tool-catalog row. */
54
54
  pagedToolPatterns?: string
55
+ /** Deferred idle-reclaim threshold in steps the Host writes to every paging row. */
56
+ idleReclaimSteps?: number
55
57
  }
56
58
 
57
59
  /** What the LiangShen card renders. */
@@ -61,6 +63,7 @@ export interface LiangShenSettingsCardState extends CardShell {
61
63
  presentation: CardFieldState
62
64
  dispatcher: CardFieldState
63
65
  pagedToolPatterns: CardFieldState
66
+ idleReclaimSteps: CardFieldState
64
67
  }
65
68
 
66
69
  /** The registration-side face the card's slot entry injects. */
@@ -84,6 +87,7 @@ export class LiangShenSettingsCardController {
84
87
  choiceField('presentation', PRESENTATION_CHOICES),
85
88
  booleanField('dispatcher'),
86
89
  pagedToolPatternsField('pagedToolPatterns'),
90
+ numberField('idleReclaimSteps', { integer: true, min: 0 }),
87
91
  ])
88
92
  this.store = this.form.bind(() => this.projection())
89
93
  }
@@ -96,6 +100,7 @@ export class LiangShenSettingsCardController {
96
100
  presentation: this.form.field('presentation'),
97
101
  dispatcher: this.form.field('dispatcher'),
98
102
  pagedToolPatterns: this.form.field('pagedToolPatterns'),
103
+ idleReclaimSteps: this.form.field('idleReclaimSteps'),
99
104
  }
100
105
  }
101
106
 
@@ -202,6 +207,17 @@ export function LiangShenSettingsCard(props: LiangShenSettingsCardProps) {
202
207
  onEdit={(text) => { props.edit('pagedToolPatterns', text) }}
203
208
  onReset={() => { props.resetField('pagedToolPatterns') }}
204
209
  />
210
+ <ValueField
211
+ id="settings-liangshen-idle-reclaim-steps"
212
+ label={t('settings.idleReclaimSteps')}
213
+ hint={t('settings.idleReclaimStepsHint')}
214
+ placeholder="0"
215
+ {...fieldProps}
216
+ invalidLabel={t('settings.idleReclaimStepsInvalid')}
217
+ {...state.idleReclaimSteps}
218
+ onEdit={(text) => { props.edit('idleReclaimSteps', text) }}
219
+ onReset={() => { props.resetField('idleReclaimSteps') }}
220
+ />
205
221
  </PluginSettingsCard>
206
222
  )
207
223
  }
@@ -89,6 +89,9 @@ export interface LeverFace {
89
89
  t: (key: LiangShenKey, vars?: Record<string, string | number>) => string
90
90
  }
91
91
 
92
+ /** A translation function bound to this plugin's locale namespace. */
93
+ type Translator = (key: LiangShenKey, vars?: Record<string, string | number>) => string
94
+
92
95
  /** Read the preset a session summary reports, when it reports one. */
93
96
  function presetOf(session: { projectionValues?: Record<string, unknown> } | undefined): string | undefined {
94
97
  const value = session?.projectionValues?.['agentPreset']
@@ -122,6 +125,16 @@ export class LeverController {
122
125
 
123
126
  private readonly disposers: (() => void)[] = []
124
127
 
128
+ /** The one face this controller hands out: the view reads it on every render. */
129
+ private cachedFace: LeverFace | undefined
130
+
131
+ /**
132
+ * The translator bound to this plugin's locale namespace, resolved on first
133
+ * use. A lookup that resolved nothing is never cached, so a locale service
134
+ * registered after activation still reaches the same face.
135
+ */
136
+ private cachedTranslate: Translator | undefined
137
+
125
138
  constructor(private readonly ctx: ClientContext, options: LeverControllerOptions = {}) {
126
139
  this.selectTimeoutMs = options.selectTimeoutMs ?? SELECT_TIMEOUT_MS
127
140
  this.sessions = readService<ISessions>(() => (ctx as unknown as { sessions: ISessions }).sessions)
@@ -164,19 +177,35 @@ export class LeverController {
164
177
  for (const dispose of this.disposers.splice(0)) dispose()
165
178
  }
166
179
 
167
- /** The inject face handed to the slot entry. */
180
+ /** The inject face handed to the slot entry; the same instance on every read. */
168
181
  face(): LeverFace {
169
- return {
182
+ const cached = this.cachedFace
183
+ if (cached !== undefined) return cached
184
+ const face: LeverFace = {
170
185
  store: this.store,
171
186
  pull: () => { void this.toggle('down') },
172
187
  push: () => { void this.toggle('up') },
173
188
  t: (key, vars) => {
174
- const translate = readService<(key: LiangShenKey, vars?: Record<string, string | number>) => string>(
175
- () => this.ctx.locale.bind('liangshen'),
176
- )
189
+ const translate = this.translate()
177
190
  return translate === undefined ? key : translate(key, vars)
178
191
  },
179
192
  }
193
+ this.cachedFace = face
194
+ return face
195
+ }
196
+
197
+ /**
198
+ * The translator bound to this plugin's locale namespace, or undefined while
199
+ * none answers. The binding is resolved once and only on success: a locale
200
+ * service that arrives later than this controller still gets its chance.
201
+ */
202
+ private translate(): Translator | undefined {
203
+ const cached = this.cachedTranslate
204
+ if (cached !== undefined) return cached
205
+ const bound = readService<Translator>(() => this.ctx.locale.bind('liangshen'))
206
+ if (typeof bound !== 'function') return undefined
207
+ this.cachedTranslate = bound
208
+ return bound
180
209
  }
181
210
 
182
211
  /** Read the roster; a refusal leaves the lever as it was. */
@@ -205,12 +234,20 @@ export class LeverController {
205
234
  const facts = this.facts()
206
235
  const snapshot = this.store.getSnapshot()
207
236
  const state = leverState(facts)
208
- const target = restoreTarget(facts)
209
- const restoreLabel = target === undefined ? '' : this.labelOf(target)
237
+ // Only a blank session can push the lever back up, so only there does a
238
+ // restore target exist to name; 'locked' and 'missing' are decided by the
239
+ // roster alone and never read the label.
240
+ const restoreLabel = facts.blank ? this.restoreLabelOf(facts) : ''
210
241
  if (snapshot.state === state && snapshot.restoreLabel === restoreLabel) return
211
242
  this.store.set({ ...snapshot, state, restoreLabel })
212
243
  }
213
244
 
245
+ /** Display name of the preset a push-up would restore; empty when there is none. */
246
+ private restoreLabelOf(facts: LeverFacts): string {
247
+ const target = restoreTarget(facts)
248
+ return target === undefined ? '' : this.labelOf(target)
249
+ }
250
+
214
251
  /** The verb behind one gesture direction. */
215
252
  private async toggle(direction: 'down' | 'up'): Promise<void> {
216
253
  const snapshot = this.store.getSnapshot()
@@ -305,12 +342,23 @@ export class LeverController {
305
342
  }
306
343
  }
307
344
 
308
- /** The facts one decision reads, from the live session and the roster. */
345
+ /**
346
+ * The facts one decision reads, from the live session and the roster.
347
+ *
348
+ * `previous` is resolved only for a blank session: it exists to name the
349
+ * preset a push-up restores, and only a blank session may switch preset at
350
+ * all. Resolving it costs a DOM chip lookup and a session-storage read
351
+ * ({@link detectPreset}), which a started session -- reported as 'locked' or
352
+ * 'missing' -- would pay for on every roster and session update and never use.
353
+ */
309
354
  private facts(): LeverFacts {
310
355
  const summary = this.currentSession()
311
356
  const available = this.rows.filter(row => row.broken === undefined).map(row => row.id)
312
357
  const fallback = this.rows.find(row => row.isDefault)?.id
313
358
  const currentPreset = presetOf(summary)
359
+ const blank = summary?.blank === true
360
+
361
+ if (!blank) return { blank, agentPreset: currentPreset, available, fallback }
314
362
 
315
363
  if (currentPreset !== undefined && currentPreset !== LIANGSHEN_PRESET_ID) {
316
364
  this.rememberPrevious(currentPreset)
@@ -318,13 +366,7 @@ export class LeverController {
318
366
 
319
367
  const previous = this.previous ?? this.detectPreset()
320
368
 
321
- return {
322
- blank: summary?.blank === true,
323
- agentPreset: currentPreset,
324
- available,
325
- fallback,
326
- previous,
327
- }
369
+ return { blank, agentPreset: currentPreset, available, fallback, previous }
328
370
  }
329
371
 
330
372
  private currentSessionId(): string | undefined {
@@ -34,6 +34,9 @@ export const zh = {
34
34
  'settings.pagedToolPatterns': '按需工具族',
35
35
  'settings.pagedToolPatternsHint': '逗号分隔,每项以单个 * 结尾。命中这些前缀的工具默认不进上下文,需要时用 tool_activate 按需加载。留空继承出厂 7 项:mcp__*, browser_*, task_board_*, team_*, squad*, ui_*, ssh_*。',
36
36
  'settings.pagedToolPatternsInvalid': '每项须是非空前缀并以单个 * 结尾,逗号分隔,例如 task_board_*。',
37
+ 'settings.idleReclaimSteps': '空闲收回步数',
38
+ 'settings.idleReclaimStepsHint': '连续 N 步没有成功调用的已激活工具族会过期,但只在下次激活或压缩时收回——这些时机前缀缓存本就要重建,因此不新增缓存重建;收回前仍常驻可用,再次调用即续命。0 或留空 = 不收回(出厂行为)。',
39
+ 'settings.idleReclaimStepsInvalid': '填一个非负整数(步数),例如 30;0 或留空表示不收回。',
37
40
  'settings.on': '开',
38
41
  'settings.off': '关',
39
42
  'settings.inherit': '继承',
@@ -79,6 +82,9 @@ export const en: Record<keyof typeof zh, string> = {
79
82
  'settings.pagedToolPatterns': 'On-demand tool families',
80
83
  'settings.pagedToolPatternsHint': 'Comma separated, each entry ending in a single *. Tools matching these prefixes stay out of context by default; load them with tool_activate when needed. Leave empty to inherit the 7 factory entries: mcp__*, browser_*, task_board_*, team_*, squad*, ui_*, ssh_*.',
81
84
  'settings.pagedToolPatternsInvalid': 'Each entry must be a non-empty prefix ending in a single *, comma separated, for example task_board_*.',
85
+ 'settings.idleReclaimSteps': 'Idle reclaim steps',
86
+ 'settings.idleReclaimStepsHint': 'An activated tool family with no successful call for N steps expires, but is reclaimed only at the next activation or compaction — moments the prefix cache rebuilds anyway, so no extra rebuild is paid. It stays resident and callable until then; any call refreshes it. 0 or empty = no reclaim (factory behavior).',
87
+ 'settings.idleReclaimStepsInvalid': 'Enter a non-negative integer number of steps, for example 30; 0 or empty means no reclaim.',
82
88
  'settings.on': 'On',
83
89
  'settings.off': 'Off',
84
90
  'settings.inherit': 'Inherit',
@@ -141,11 +141,13 @@ export interface NumberConstraints {
141
141
  integer?: boolean
142
142
  /** The accepted value must be at least this. */
143
143
  min?: number
144
+ /** The accepted value must be at most this. */
145
+ max?: number
144
146
  }
145
147
 
146
148
  /** A whole- or decimal-number field. An empty draft clears the field; any other draft that is not a finite number within the constraints stays unwritten. */
147
149
  export function numberField(field: string, constraints: NumberConstraints = {}): FieldSpec {
148
- const { integer = false, min } = constraints
150
+ const { integer = false, min, max } = constraints
149
151
  return {
150
152
  field,
151
153
  entry: 'type',
@@ -157,6 +159,7 @@ export function numberField(field: string, constraints: NumberConstraints = {}):
157
159
  if (!Number.isFinite(parsed)) return undefined
158
160
  if (integer && !Number.isInteger(parsed)) return undefined
159
161
  if (min !== undefined && parsed < min) return undefined
162
+ if (max !== undefined && parsed > max) return undefined
160
163
  return { kind: 'set', value: parsed }
161
164
  },
162
165
  }
@@ -439,7 +442,7 @@ export class CardForm<T> {
439
442
  // against. Settling is the only signal the form has; the rest of the
440
443
  // batch, when one exists, still carries the atomic verdict by read-back.
441
444
  if (this.specOf(field).secret) return true
442
- return this.userLayer()?.[field] === value
445
+ return jsonValuesEqual(this.userLayer()?.[field], value)
443
446
  }
444
447
 
445
448
  /**
@@ -508,3 +511,19 @@ export class CardForm<T> {
508
511
  for (const listener of this.listeners) listener()
509
512
  }
510
513
  }
514
+
515
+ /** Structural equality for JSON settings values (primitives, arrays, plain objects). */
516
+ function jsonValuesEqual(left: unknown, right: unknown): boolean {
517
+ if (Object.is(left, right)) return true
518
+ if (typeof left !== 'object' || left === null || typeof right !== 'object' || right === null) return false
519
+ if (Array.isArray(left) || Array.isArray(right)) {
520
+ if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) return false
521
+ return left.every((item, index) => jsonValuesEqual(item, right[index]))
522
+ }
523
+ const a = left as Record<string, unknown>
524
+ const b = right as Record<string, unknown>
525
+ const keysA = Object.keys(a).filter(key => a[key] !== undefined)
526
+ const keysB = Object.keys(b).filter(key => b[key] !== undefined)
527
+ if (keysA.length !== keysB.length) return false
528
+ return keysA.every(key => Object.hasOwn(b, key) && jsonValuesEqual(a[key], b[key]))
529
+ }
@@ -93,6 +93,13 @@ describe('readCompositionRows', () => {
93
93
  expect(configOf(rowOf(rows(), 'minimal-prompt'))['dispatcher']).toBe(true)
94
94
  })
95
95
 
96
+ it('operator reads an empty third-party section allowlist by default', () => {
97
+ // Given the factory composition
98
+ // When the operator reads the minimal-prompt row
99
+ // Then the opt-in extension point is present but changes no default selection
100
+ expect(configOf(rowOf(rows(), 'minimal-prompt'))['keepSections']).toEqual([])
101
+ })
102
+
96
103
  it('operator keeps a literal block scalar verbatim', () => {
97
104
  // Given the persona row's `prefix: |-` scalar, When the operator reads it,
98
105
  // Then the prose is content and the next composition row ends it.
@@ -193,6 +200,32 @@ describe('readCompositionRows', () => {
193
200
  })
194
201
  })
195
202
 
203
+ it('operator reads a __proto__ key as own data without reaching the prototype chain', () => {
204
+ // Given a config map whose first key is __proto__, When the operator
205
+ // reads it, Then the entry is an own enumerable property of that map: a
206
+ // plain assignment would have rewritten the map's prototype instead and
207
+ // carried a parsed document into the prototype chain of everything read
208
+ // from it, while the key itself would have vanished from the map.
209
+ const parsed = readCompositionRows([
210
+ '- name: ./x.mjs',
211
+ ' config:',
212
+ ' __proto__:',
213
+ ' polluted: true',
214
+ ' plain: kept',
215
+ '',
216
+ ].join('\n'), presetDir)
217
+ const config = configOf(loose(parsed)[0]!)
218
+ const descriptor = Object.getOwnPropertyDescriptor(config, '__proto__')
219
+ expect(descriptor?.enumerable).toBe(true)
220
+ expect(descriptor?.value).toEqual({ polluted: true })
221
+ expect(Object.keys(config)).toEqual(['__proto__', 'plain'])
222
+ // And neither prototype moved: the map keeps Object.prototype, and no
223
+ // object in the process gained the parsed key.
224
+ expect(Object.getPrototypeOf(config)).toBe(Object.prototype)
225
+ expect(Object.hasOwn(Object.prototype, 'polluted')).toBe(false)
226
+ expect(config['plain']).toBe('kept')
227
+ })
228
+
196
229
  it('operator reads an absolute name as written and nested sequences of maps', () => {
197
230
  // Given a group row whose child rows carry a nested list and an absolute
198
231
  // module path, When the operator reads it, Then neither is rewritten.