@linxin666/dsh-liangshen 0.4.17 → 0.4.19

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.
@@ -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
+ })
@@ -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 {
@@ -31,7 +31,7 @@
31
31
  import type { ConfigForm, ConfigFormSnapshot, ConfigForms } from '@deepseek-ai/dsh-client-ui-settings/client'
32
32
 
33
33
  /** Options of {@link createServedEntryForm}. */
34
- export interface ServedEntryFormOptions<T> {
34
+ export interface ServedEntryFormOptions<_T> {
35
35
  /** The shared configuration forms service (`ctx.configForms`). */
36
36
  forms: ConfigForms
37
37
  /**
@@ -193,6 +193,32 @@ describe('readCompositionRows', () => {
193
193
  })
194
194
  })
195
195
 
196
+ it('operator reads a __proto__ key as own data without reaching the prototype chain', () => {
197
+ // Given a config map whose first key is __proto__, When the operator
198
+ // reads it, Then the entry is an own enumerable property of that map: a
199
+ // plain assignment would have rewritten the map's prototype instead and
200
+ // carried a parsed document into the prototype chain of everything read
201
+ // from it, while the key itself would have vanished from the map.
202
+ const parsed = readCompositionRows([
203
+ '- name: ./x.mjs',
204
+ ' config:',
205
+ ' __proto__:',
206
+ ' polluted: true',
207
+ ' plain: kept',
208
+ '',
209
+ ].join('\n'), presetDir)
210
+ const config = configOf(loose(parsed)[0]!)
211
+ const descriptor = Object.getOwnPropertyDescriptor(config, '__proto__')
212
+ expect(descriptor?.enumerable).toBe(true)
213
+ expect(descriptor?.value).toEqual({ polluted: true })
214
+ expect(Object.keys(config)).toEqual(['__proto__', 'plain'])
215
+ // And neither prototype moved: the map keeps Object.prototype, and no
216
+ // object in the process gained the parsed key.
217
+ expect(Object.getPrototypeOf(config)).toBe(Object.prototype)
218
+ expect(Object.hasOwn(Object.prototype, 'polluted')).toBe(false)
219
+ expect(config['plain']).toBe('kept')
220
+ })
221
+
196
222
  it('operator reads an absolute name as written and nested sequences of maps', () => {
197
223
  // Given a group row whose child rows carry a nested list and an absolute
198
224
  // module path, When the operator reads it, Then neither is rewritten.
@@ -319,7 +319,15 @@ function parseMap(cursor: Cursor, indent: number): Record<string, unknown> {
319
319
  throw new CompositionError(`line ${String(cursor.index + 1)}: duplicate key "${entry.key}"`)
320
320
  }
321
321
  cursor.index += 1
322
- map[entry.key] = parseValue(cursor, indent, entry.rest)
322
+ // Defined rather than assigned: a '__proto__' key is ordinary data here,
323
+ // and a plain assignment would rewrite the map's prototype instead of
324
+ // carrying the entry, letting a parsed document reach the prototype chain.
325
+ Object.defineProperty(map, entry.key, {
326
+ value: parseValue(cursor, indent, entry.rest),
327
+ enumerable: true,
328
+ writable: true,
329
+ configurable: true,
330
+ })
323
331
  }
324
332
  return map
325
333
  }
package/src/index.ts CHANGED
@@ -196,12 +196,12 @@ export function bundledPresetDir(): string {
196
196
  /**
197
197
  * Build the registry declaration of the bundled preset with the settings
198
198
  * currently committed applied to the rows they shape.
199
+ * @param base - the bundled preset as parsed for this activation.
199
200
  * @param values - the activation's effective settings.
200
201
  * @returns the definition to submit to `ctx.agentPresets.register`.
201
202
  */
202
- function declaration(values: ResolvedConfig): PresetDefinition {
203
- const definition = readPresetDefinition(LIANGSHEN_PRESET_ID, bundledPresetDir())
204
- return { ...definition, plugins: applyPresetOverrides(definition.plugins, values) }
203
+ function declaration(base: PresetDefinition, values: ResolvedConfig): PresetDefinition {
204
+ return { ...base, plugins: applyPresetOverrides(base.plugins, values) }
205
205
  }
206
206
 
207
207
  /**
@@ -237,6 +237,24 @@ function applyImpl(ctx: Context, config?: Config): void {
237
237
  * already present at activation is never re-declared.
238
238
  */
239
239
  let registryMissing = false
240
+ /**
241
+ * The bundled preset as parsed by this activation, read on first declaration.
242
+ * Every settings write re-declares, and the two preset files cannot change
243
+ * under a running row, so re-reading and re-parsing them on each write would
244
+ * block the event loop for a result identical to the one already held. A
245
+ * failed read is not remembered: the next declaration tries the disk again.
246
+ */
247
+ let basePreset: PresetDefinition | undefined
248
+
249
+ /**
250
+ * The bundled preset definition for this activation, parsed at most once.
251
+ * The overlay derives a new row list from it, so the cached base keeps the
252
+ * values the composition ships for every declaration that follows.
253
+ */
254
+ const baseDefinition = (): PresetDefinition => {
255
+ if (basePreset === undefined) basePreset = readPresetDefinition(LIANGSHEN_PRESET_ID, bundledPresetDir())
256
+ return basePreset
257
+ }
240
258
 
241
259
  const warn = (message: string): void => { ctx.logger?.warn?.(`dsh-liangshen: ${message}`) }
242
260
 
@@ -275,7 +293,7 @@ function applyImpl(ctx: Context, config?: Config): void {
275
293
  return
276
294
  }
277
295
  try {
278
- release = await registry.register(declaration(values))
296
+ release = await registry.register(declaration(baseDefinition(), values))
279
297
  registryMissing = false
280
298
  ctx.logger?.info?.(`liangshen: preset ${LIANGSHEN_PRESET_ID} declared`)
281
299
  } catch (error) {
@@ -35,7 +35,7 @@ function sessionIdFor(runId) {
35
35
  * @param config - resolved driver config.
36
36
  * @param io - process-facing effects.
37
37
  */
38
- async function run(ctx, config, io) {
38
+ async function run(ctx, config, _io) {
39
39
  // Loader siblings mount concurrently: await the whole application before
40
40
  // creating an agent, or its scoped tools and adapters are half-composed.
41
41
  await ctx.get('loader')?.await()
@@ -48,7 +48,6 @@ const HERE = dirname(fileURLToPath(import.meta.url))
48
48
  const PACKAGE_ROOT = resolve(HERE, '..')
49
49
  const PRESET_SOURCE = join(PACKAGE_ROOT, 'presets', 'liangshen')
50
50
  const DRIVER = join(HERE, 'benchmark-driver.mjs').replace(/\\/g, '/')
51
- const require = createRequire(import.meta.url)
52
51
 
53
52
  /** Fixed route every variant runs on, so the comparison isolates the preset. */
54
53
  export const FIXED_ROUTE = { provider: 'deepseek-official', model: 'deepseek-flash', reasoningEffort: 'max' }
@@ -402,8 +402,7 @@ function isMain() {
402
402
 
403
403
  if (isMain()) {
404
404
  const args = process.argv.slice(2)
405
- const positional = args.filter((arg) => !arg.startsWith('--'))
406
- const dir = positional[0]
405
+ const dir = args.find((arg) => !arg.startsWith('--'))
407
406
  if (dir === undefined || !existsSync(dir)) {
408
407
  console.error('usage: node tools/benchmark-report.mjs <results-dir> [--baseline B]')
409
408
  process.exitCode = 1
@@ -16,7 +16,7 @@
16
16
  *
17
17
  * Usage: node tools/check-dispatcher-rules.mjs [--strict] [--verbose]
18
18
  */
19
- import { existsSync, readFileSync, readdirSync } from 'node:fs'
19
+ import { readFileSync, readdirSync } from 'node:fs'
20
20
  import { createRequire } from 'node:module'
21
21
  import { dirname, join } from 'node:path'
22
22
 
@@ -105,7 +105,7 @@ export async function runSelftest(options = {}) {
105
105
 
106
106
  function render(result) {
107
107
  const lines = []
108
- lines.push('probe bad policy good policy ' + 'discriminates')
108
+ lines.push('probe bad policy good policy discriminates')
109
109
  for (const row of result.rows) {
110
110
  const bad = (row.bad.passed ? 'PASS' : 'fail') + ' ' + row.rule.metric + '=' + row.bad.value
111
111
  const good = (row.good.passed ? 'PASS' : 'fail') + ' ' + row.rule.metric + '=' + row.good.value