@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.
Files changed (52) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +24 -17
  3. package/README.zh.md +25 -18
  4. package/cordis.patch.yml +3 -2
  5. package/icon.svg +3 -0
  6. package/lib/client.js +381 -77
  7. package/lib/client.js.map +1 -1
  8. package/lib/index.js +594 -428
  9. package/lib/types/announce.test.d.ts +10 -0
  10. package/lib/types/client/LiangShenSettingsCard.d.ts +27 -10
  11. package/lib/types/client/PluginSettingsCard.d.ts +4 -0
  12. package/lib/types/client/index.d.ts +32 -13
  13. package/lib/types/client/lever-controller.d.ts +16 -2
  14. package/lib/types/client/locales.d.ts +13 -0
  15. package/lib/types/client/main-session.d.ts +32 -0
  16. package/lib/types/client/plugin-card-seat.d.ts +23 -16
  17. package/lib/types/client/settings-form.d.ts +17 -17
  18. package/lib/types/composition.d.ts +116 -0
  19. package/lib/types/composition.test.d.ts +7 -0
  20. package/lib/types/index.d.ts +146 -31
  21. package/lib/types/index.test.d.ts +5 -0
  22. package/package.json +25 -20
  23. package/presets/liangshen/agent.cordis.yml +44 -10
  24. package/presets/liangshen/fact-ledger.mjs +141 -0
  25. package/presets/liangshen/guard.mjs +426 -0
  26. package/presets/liangshen/minimal-prompt.mjs +2 -2
  27. package/presets/liangshen/tool-catalog.mjs +24 -20
  28. package/presets/liangshen/working-context.mjs +10 -2
  29. package/src/announce.test.ts +248 -55
  30. package/src/client/LiangShenLever.module.css +2 -0
  31. package/src/client/LiangShenLever.tsx +37 -9
  32. package/src/client/LiangShenSettingsCard.tsx +96 -12
  33. package/src/client/PluginSettingsCard.tsx +7 -2
  34. package/src/client/index.ts +61 -23
  35. package/src/client/lever-controller.ts +76 -9
  36. package/src/client/locales.ts +30 -4
  37. package/src/client/main-session.ts +43 -0
  38. package/src/client/plugin-card-seat.ts +24 -17
  39. package/src/client/settings-form.ts +34 -31
  40. package/src/composition.test.ts +294 -0
  41. package/src/composition.ts +554 -0
  42. package/src/index.test.ts +68 -1
  43. package/src/index.ts +278 -107
  44. package/tools/benchmark-live-run.mjs +171 -32
  45. package/lib/types/schema.d.ts +0 -18
  46. package/lib/types/schema.test.d.ts +0 -1
  47. package/lib/types/sync.d.ts +0 -74
  48. package/lib/types/sync.test.d.ts +0 -1
  49. package/src/schema.test.ts +0 -64
  50. package/src/schema.ts +0 -110
  51. package/src/sync.test.ts +0 -303
  52. package/src/sync.ts +0 -324
@@ -0,0 +1,554 @@
1
+ /**
2
+ * The LiangShen preset's composition reader: just enough YAML to turn the
3
+ * bundled `presets/liangshen/agent.cordis.yml` — and the flat `preset.yml`
4
+ * display map beside it — into the declaration the agent-preset registry takes.
5
+ *
6
+ * Under 0.1.7 a preset is an ordinary registry declaration instead of a
7
+ * directory the harness discovers, so this plugin hands `ctx.agentPresets` the
8
+ * rows of its OWN composition. No YAML package is resolvable from this package
9
+ * and the harness's reader is not importable from here, so the subset is owned
10
+ * here; the shipped composition is the only file it must read, and tests fence
11
+ * it against that whole file. Supported: block maps and sequences, quoted and
12
+ * plain scalars, single-line flow sequences, literal and folded block scalars,
13
+ * comments, and `!!js` expressions preserved as data (`{ __jsExpr }`, the shape
14
+ * the Loader itself hands a plugin).
15
+ *
16
+ * Fail-closed: a construct outside the subset — anchors, aliases, tags other
17
+ * than `!!js`, nested flow collections, multiple documents, tabs — raises
18
+ * {@link CompositionError} rather than being guessed at, so an unreadable
19
+ * composition is refused instead of half-declared.
20
+ *
21
+ * Relative module names (`name: ./minimal-prompt.mjs`) are resolved against
22
+ * the preset directory handed to {@link readCompositionRows} and emitted as
23
+ * file URLs: the registry mounts a declaration under the DECLARING LOADER's
24
+ * base, so a relative name would otherwise be resolved outside this package.
25
+ * @module @linxin666/dsh-liangshen/composition
26
+ */
27
+
28
+ import { readFileSync } from 'node:fs'
29
+ import { join, resolve } from 'node:path'
30
+ import { pathToFileURL } from 'node:url'
31
+ import type { PresetDefinition } from '@deepseek-ai/dsh-agent-preset-registry'
32
+
33
+ /** A construct outside the supported subset, or malformed YAML. */
34
+ export class CompositionError extends Error {
35
+ constructor(message: string) {
36
+ super(message)
37
+ this.name = 'CompositionError'
38
+ }
39
+ }
40
+
41
+ /** A Loader `!!js` expression preserved as data instead of executed. */
42
+ export interface JsExpression {
43
+ __jsExpr: string
44
+ }
45
+
46
+ /**
47
+ * One parsed composition row. Deliberately loose: the Loader owns each child
48
+ * plugin's own schema, and this reader only has to preserve what the file says.
49
+ */
50
+ export interface CompositionRow {
51
+ /** Row id; the settings overlay and the Loader's patch index address a row by it. */
52
+ id?: string
53
+ /** Module specifier: a bare package name, a `cordis:` builtin, or a relative path. */
54
+ name?: string
55
+ /** Whether this row's `config` is a nested entry list. */
56
+ group?: boolean
57
+ /** Boolean or `!!js` expression. */
58
+ disabled?: unknown
59
+ /** Shared-realm declarations of the group this row opens. */
60
+ isolate?: unknown
61
+ /** Row configuration, or the nested entry list of a group row. */
62
+ config?: unknown
63
+ }
64
+
65
+ interface Cursor {
66
+ /** Mutable line copy: sequence items rewrite their own line in place. */
67
+ readonly lines: string[]
68
+ index: number
69
+ }
70
+
71
+ const BLANK_OR_COMMENT_RE = /^[ \t]*(?:#.*)?$/
72
+ const INTEGER_RE = /^[+-]?\d+$/
73
+ const FLOAT_RE = /^[+-]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][+-]?\d+)?$/
74
+
75
+ /** The indentation width of one line (its leading spaces). */
76
+ function indentOf(line: string): number {
77
+ const match = /^ */.exec(line)
78
+ return match === null ? 0 : match[0].length
79
+ }
80
+
81
+ /**
82
+ * The indentation of one structurally significant line. A tab there is
83
+ * forbidden by YAML; block-scalar content is verbatim and never measured here.
84
+ */
85
+ function significantIndent(line: string, lineNumber: number): number {
86
+ const leading = /^[ \t]*/.exec(line)?.[0] ?? ''
87
+ if (leading.includes('\t')) {
88
+ throw new CompositionError(`line ${String(lineNumber)}: tabs must not be used for indentation`)
89
+ }
90
+ return leading.length
91
+ }
92
+
93
+ /** Advance past blank and comment-only lines. */
94
+ function skipInsignificant(cursor: Cursor): void {
95
+ while (cursor.index < cursor.lines.length && BLANK_OR_COMMENT_RE.test(cursor.lines[cursor.index] ?? '')) {
96
+ cursor.index += 1
97
+ }
98
+ }
99
+
100
+ /** Whether a line at `indent` opens a block sequence entry. */
101
+ function isSequenceEntry(line: string, indent: number): boolean {
102
+ if (line[indent] !== '-') return false
103
+ return line.length === indent + 1 || line[indent + 1] === ' '
104
+ }
105
+
106
+ /** The index of the quote that closes a quoted scalar starting at index 0. */
107
+ function closingQuote(text: string): number {
108
+ const quote = text[0]
109
+ for (let index = 1; index < text.length; index += 1) {
110
+ const char = text[index]
111
+ if (quote === '"' && char === '\\') { index += 1; continue }
112
+ if (quote === "'" && char === "'" && text[index + 1] === "'") { index += 1; continue }
113
+ if (char === quote) return index
114
+ }
115
+ return -1
116
+ }
117
+
118
+ /** Resolve one quoted scalar, or return the text unchanged when unquoted. */
119
+ function unquote(text: string): string {
120
+ const trimmed = text.trim()
121
+ if (trimmed.startsWith('"')) {
122
+ const end = closingQuote(trimmed)
123
+ if (end !== trimmed.length - 1) throw new CompositionError(`unterminated double-quoted scalar: ${trimmed}`)
124
+ return trimmed.slice(1, end).replace(/\\(u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|.)/g, (_, escape: string) => {
125
+ switch (escape[0]) {
126
+ case 'n': return '\n'
127
+ case 't': return '\t'
128
+ case 'r': return '\r'
129
+ case '0': return '\0'
130
+ case 'u': case 'x': return String.fromCharCode(Number.parseInt(escape.slice(1), 16))
131
+ default: return escape
132
+ }
133
+ })
134
+ }
135
+ if (trimmed.startsWith("'")) {
136
+ const end = closingQuote(trimmed)
137
+ if (end !== trimmed.length - 1) throw new CompositionError(`unterminated single-quoted scalar: ${trimmed}`)
138
+ return trimmed.slice(1, end).replaceAll("''", "'")
139
+ }
140
+ return trimmed
141
+ }
142
+
143
+ /** Split one block-map line into its key and the raw text after the colon. */
144
+ function matchKeyEntry(text: string): { key: string; rest: string } | undefined {
145
+ if (text.startsWith("'") || text.startsWith('"')) {
146
+ const end = closingQuote(text)
147
+ if (end === -1) return undefined
148
+ const after = text.slice(end + 1).trimStart()
149
+ if (!after.startsWith(':')) return undefined
150
+ return { key: unquote(text.slice(0, end + 1)), rest: after.slice(1).trim() }
151
+ }
152
+ for (let index = 0; index < text.length; index += 1) {
153
+ const char = text[index]
154
+ if (char === '#' && index > 0 && text[index - 1] === ' ') break
155
+ if (char === ':' && (index + 1 === text.length || text[index + 1] === ' ')) {
156
+ return { key: text.slice(0, index), rest: text.slice(index + 1).trim() }
157
+ }
158
+ }
159
+ return undefined
160
+ }
161
+
162
+ /** Resolve a plain scalar to the value YAML's JSON schema would produce. */
163
+ function plainScalar(text: string): unknown {
164
+ // A '#' opens a comment only after whitespace, so the first ' #' ends the
165
+ // scalar; anything else (including a lone '#') stays content.
166
+ const comment = text.indexOf(' #')
167
+ const value = (comment === -1 ? text : text.slice(0, comment)).trim()
168
+ if (value === '' || value === '~' || value === 'null' || value === 'Null' || value === 'NULL') return null
169
+ if (value === 'true' || value === 'True' || value === 'TRUE') return true
170
+ if (value === 'false' || value === 'False' || value === 'FALSE') return false
171
+ if (INTEGER_RE.test(value)) return Number(value)
172
+ if (FLOAT_RE.test(value)) return Number(value)
173
+ return value
174
+ }
175
+
176
+ /**
177
+ * Read one single-line flow sequence (`['mcp__*']`) into its scalar items.
178
+ * Nested flow collections are outside the subset and refused.
179
+ */
180
+ function flowSequence(text: string): unknown[] {
181
+ const end = text.lastIndexOf(']')
182
+ if (end === -1) throw new CompositionError(`unterminated flow sequence: ${text}`)
183
+ const tail = text.slice(end + 1).trim()
184
+ if (tail !== '' && !tail.startsWith('#')) {
185
+ throw new CompositionError(`unexpected content after a flow sequence: ${tail}`)
186
+ }
187
+ const body = text.slice(1, end)
188
+ if (body.trim() === '') return []
189
+ const items: unknown[] = []
190
+ for (const raw of body.split(',')) {
191
+ const item = raw.trim()
192
+ if (item === '') throw new CompositionError(`empty item in a flow sequence: ${text}`)
193
+ if (item.startsWith('[') || item.startsWith('{')) {
194
+ throw new CompositionError(`nested flow collections are not supported: ${item}`)
195
+ }
196
+ items.push(inlineScalar(item))
197
+ }
198
+ return items
199
+ }
200
+
201
+ /** Resolve the text that follows a colon or a dash on one line. */
202
+ function inlineScalar(text: string): unknown {
203
+ const value = text.trim()
204
+ if (value.startsWith('!!js')) {
205
+ const expression = value.slice('!!js'.length).trim()
206
+ if (expression === '') throw new CompositionError('!!js requires an expression')
207
+ return { __jsExpr: unquote(expression) } satisfies JsExpression
208
+ }
209
+ if (value.startsWith("'") || value.startsWith('"')) {
210
+ const end = closingQuote(value)
211
+ if (end === -1) throw new CompositionError(`unterminated quoted scalar: ${value}`)
212
+ const tail = value.slice(end + 1).trim()
213
+ if (tail !== '' && !tail.startsWith('#')) {
214
+ throw new CompositionError(`unexpected content after a quoted scalar: ${tail}`)
215
+ }
216
+ return unquote(value.slice(0, end + 1))
217
+ }
218
+ if (value.startsWith('[')) return flowSequence(value)
219
+ if (value.startsWith('{')) throw new CompositionError(`flow mappings are not supported: ${value}`)
220
+ if (value.startsWith('|') || value.startsWith('>')) {
221
+ throw new CompositionError(`block scalars need their own line: ${value}`)
222
+ }
223
+ if (value.startsWith('!') || value.startsWith('&') || value.startsWith('*')) {
224
+ throw new CompositionError(`unsupported YAML node: ${value}`)
225
+ }
226
+ return plainScalar(value)
227
+ }
228
+
229
+ /**
230
+ * Read one literal (`|`) or folded (`>`) block scalar, consuming its lines.
231
+ * @param cursor - line cursor positioned on the line that follows the header.
232
+ * @param parentIndent - indentation of the node that owns the scalar.
233
+ * @param header - the header text (`|-`, `>+2`, ...) possibly with a comment.
234
+ * @returns the scalar text after indentation stripping and chomping.
235
+ */
236
+ function blockScalar(cursor: Cursor, parentIndent: number, header: string): string {
237
+ const style = header[0]
238
+ const indicators = header.slice(1).split('#')[0]?.trim() ?? ''
239
+ let explicitIndent: number | undefined
240
+ let chomp: 'clip' | 'strip' | 'keep' = 'clip'
241
+ for (const char of indicators) {
242
+ if (char === '-') chomp = 'strip'
243
+ else if (char === '+') chomp = 'keep'
244
+ else if (char >= '1' && char <= '9') explicitIndent = Number(char)
245
+ else throw new CompositionError(`unsupported block scalar header: ${header}`)
246
+ }
247
+ const body: string[] = []
248
+ let blockIndent: number | undefined
249
+ let trailing = 0
250
+ while (cursor.index < cursor.lines.length) {
251
+ const line = cursor.lines[cursor.index] ?? ''
252
+ if (line.trim() === '') {
253
+ body.push('')
254
+ trailing += 1
255
+ cursor.index += 1
256
+ continue
257
+ }
258
+ const indent = indentOf(line)
259
+ if (indent <= parentIndent) break
260
+ if (blockIndent === undefined) blockIndent = explicitIndent === undefined ? indent : parentIndent + explicitIndent
261
+ if (indent < blockIndent) break
262
+ body.push(line.slice(blockIndent))
263
+ trailing = 0
264
+ cursor.index += 1
265
+ }
266
+ const lines = body.slice(0, body.length - trailing)
267
+ if (style === '>') {
268
+ // Folding: a single line break between two content lines reads as a space,
269
+ // and each blank line reads as one newline.
270
+ let folded = ''
271
+ let blank = 0
272
+ let started = false
273
+ for (const line of lines) {
274
+ if (line === '') { blank += 1; continue }
275
+ if (!started) { folded = line; started = true; blank = 0; continue }
276
+ folded += blank === 0 ? ' ' + line : '\n'.repeat(blank) + line
277
+ blank = 0
278
+ }
279
+ if (chomp === 'strip') return folded
280
+ if (chomp === 'keep') return folded + '\n'.repeat(trailing + 1)
281
+ return folded === '' ? '' : folded + '\n'
282
+ }
283
+ const text = lines.join('\n')
284
+ if (chomp === 'strip') return text
285
+ if (chomp === 'keep') return text + '\n'.repeat(trailing + 1)
286
+ return text === '' ? '' : text + '\n'
287
+ }
288
+
289
+ /** Resolve the value of one entry whose line has already been consumed. */
290
+ function parseValue(cursor: Cursor, parentIndent: number, rest: string): unknown {
291
+ if (rest !== '') {
292
+ if (rest.startsWith('|') || rest.startsWith('>')) return blockScalar(cursor, parentIndent, rest)
293
+ return inlineScalar(rest)
294
+ }
295
+ skipInsignificant(cursor)
296
+ const line = cursor.lines[cursor.index]
297
+ if (line === undefined || indentOf(line) <= parentIndent) return null
298
+ return parseNode(cursor, parentIndent + 1)
299
+ }
300
+
301
+ /** Parse a block map whose keys sit at exactly `indent`. */
302
+ function parseMap(cursor: Cursor, indent: number): Record<string, unknown> {
303
+ const map: Record<string, unknown> = {}
304
+ while (true) {
305
+ skipInsignificant(cursor)
306
+ const line = cursor.lines[cursor.index]
307
+ if (line === undefined) break
308
+ const lineIndent = significantIndent(line, cursor.index + 1)
309
+ if (lineIndent < indent) break
310
+ if (lineIndent > indent) {
311
+ throw new CompositionError(`line ${String(cursor.index + 1)}: unexpected indentation`)
312
+ }
313
+ if (isSequenceEntry(line, indent)) break
314
+ const entry = matchKeyEntry(line.slice(indent))
315
+ if (entry === undefined) {
316
+ throw new CompositionError(`line ${String(cursor.index + 1)}: expected "key: value", got "${line.trim()}"`)
317
+ }
318
+ if (Object.hasOwn(map, entry.key)) {
319
+ throw new CompositionError(`line ${String(cursor.index + 1)}: duplicate key "${entry.key}"`)
320
+ }
321
+ cursor.index += 1
322
+ map[entry.key] = parseValue(cursor, indent, entry.rest)
323
+ }
324
+ return map
325
+ }
326
+
327
+ /** Parse a block sequence whose dashes sit at exactly `indent`. */
328
+ function parseSequence(cursor: Cursor, indent: number): unknown[] {
329
+ const items: unknown[] = []
330
+ while (true) {
331
+ skipInsignificant(cursor)
332
+ const line = cursor.lines[cursor.index]
333
+ if (line === undefined) break
334
+ if (significantIndent(line, cursor.index + 1) !== indent || !isSequenceEntry(line, indent)) break
335
+ const rest = line.slice(indent + 1)
336
+ const content = rest.trimStart()
337
+ if (content === '') {
338
+ cursor.index += 1
339
+ skipInsignificant(cursor)
340
+ const nested = cursor.lines[cursor.index]
341
+ const nestedIndent = nested === undefined ? -1 : significantIndent(nested, cursor.index + 1)
342
+ items.push(nestedIndent <= indent ? null : parseNode(cursor, indent + 1))
343
+ continue
344
+ }
345
+ const contentIndent = indent + 1 + (rest.length - content.length)
346
+ if (matchKeyEntry(content) !== undefined) {
347
+ cursor.lines[cursor.index] = ' '.repeat(contentIndent) + content
348
+ items.push(parseMap(cursor, contentIndent))
349
+ continue
350
+ }
351
+ cursor.index += 1
352
+ items.push(parseValue(cursor, indent, content))
353
+ }
354
+ return items
355
+ }
356
+
357
+ /** Parse the block node that starts at the cursor. */
358
+ function parseNode(cursor: Cursor, minIndent: number): unknown {
359
+ skipInsignificant(cursor)
360
+ const line = cursor.lines[cursor.index]
361
+ if (line === undefined) return null
362
+ const indent = significantIndent(line, cursor.index + 1)
363
+ if (indent < minIndent) return null
364
+ return isSequenceEntry(line, indent) ? parseSequence(cursor, indent) : parseMap(cursor, indent)
365
+ }
366
+
367
+ /** Read one cordis YAML document (an entry list, or the flat map of `preset.yml`). */
368
+ function readYaml(text: string): unknown {
369
+ const cursor: Cursor = { lines: (text.startsWith('\uFEFF') ? text.slice(1) : text).split('\n'), index: 0 }
370
+ const value = parseNode(cursor, 0)
371
+ skipInsignificant(cursor)
372
+ const extra = cursor.lines[cursor.index]
373
+ if (extra !== undefined) {
374
+ throw new CompositionError(`line ${String(cursor.index + 1)}: unexpected content "${extra.trim()}"`)
375
+ }
376
+ return value
377
+ }
378
+
379
+ /** Whether a parsed value is one composition row (a map with a string `name`). */
380
+ function asRow(value: unknown, at: string): CompositionRow {
381
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
382
+ throw new CompositionError(`${at} is not a plugin row (expected a map with a "name")`)
383
+ }
384
+ const row = value as CompositionRow
385
+ if (typeof row.name !== 'string' || row.name === '') {
386
+ throw new CompositionError(`${at} names no plugin (a "name" string is required)`)
387
+ }
388
+ return row
389
+ }
390
+
391
+ /**
392
+ * Rewrite the relative module names of one row list, recursively through the
393
+ * nested entry lists of group rows, into absolute file URLs.
394
+ */
395
+ function absolutizeRows(rows: readonly CompositionRow[], baseDir: string, at = 'row'): CompositionRow[] {
396
+ return rows.map((row, index) => {
397
+ const label = `${at} ${String(index + 1)}`
398
+ const checked = asRow(row, label)
399
+ const name = checked.name ?? ''
400
+ const out: CompositionRow = { ...checked }
401
+ if (name.startsWith('./') || name.startsWith('../')) {
402
+ out.name = pathToFileURL(resolve(baseDir, name)).href
403
+ }
404
+ if (checked.group === true) {
405
+ if (!Array.isArray(checked.config)) {
406
+ throw new CompositionError(`group ${label} must hold a list of plugin rows`)
407
+ }
408
+ out.config = absolutizeRows(checked.config as CompositionRow[], baseDir, `${label} group`)
409
+ }
410
+ return out
411
+ })
412
+ }
413
+
414
+ /**
415
+ * Read the child plugin rows of one `agent.cordis.yml`.
416
+ * @param text - the raw composition document.
417
+ * @param baseDir - directory a relative row `name` resolves against (the preset's own directory).
418
+ * @returns the row list to hand the registry, relative names resolved to file URLs.
419
+ * @throws {CompositionError} on malformed YAML or a row the registry would reject.
420
+ */
421
+ export function readCompositionRows(text: string, baseDir: string): PresetDefinition['plugins'] {
422
+ const value = readYaml(text)
423
+ if (!Array.isArray(value)) {
424
+ throw new CompositionError('agent.cordis.yml must be a top-level list of plugin rows')
425
+ }
426
+ return absolutizeRows(value as CompositionRow[], baseDir) as PresetDefinition['plugins']
427
+ }
428
+
429
+ /** The display text `preset.yml` contributes to a declaration. */
430
+ export interface PresetMetadata {
431
+ /** Display name the roster shows. */
432
+ name?: string
433
+ /** One sentence on what the preset is for. */
434
+ description?: string
435
+ /** Roster ordering rank. */
436
+ order?: number
437
+ }
438
+
439
+ /** Read the single-line display scalars of one `preset.yml`. */
440
+ export function readPresetMetadata(text: string): PresetMetadata {
441
+ const value = readYaml(text)
442
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
443
+ throw new CompositionError('preset.yml must be a mapping')
444
+ }
445
+ const record = value as Record<string, unknown>
446
+ const metadata: PresetMetadata = {}
447
+ for (const key of ['name', 'description'] as const) {
448
+ const field = record[key]
449
+ if (field === undefined || field === null) continue
450
+ if (typeof field !== 'string' || field.includes('\n')) {
451
+ throw new CompositionError(`preset.yml: ${key} must be a single-line string`)
452
+ }
453
+ metadata[key] = field
454
+ }
455
+ const order = record['order']
456
+ if (order !== undefined && order !== null) {
457
+ if (typeof order !== 'number' || !Number.isFinite(order)) {
458
+ throw new CompositionError('preset.yml: order must be a number')
459
+ }
460
+ metadata.order = order
461
+ }
462
+ return metadata
463
+ }
464
+
465
+ /**
466
+ * Build the registry declaration of one preset directory.
467
+ * @param id - preset identity the roster keys the declaration by.
468
+ * @param dir - absolute preset directory holding `agent.cordis.yml` and `preset.yml`.
469
+ * @returns the definition to submit to `ctx.agentPresets.register`.
470
+ * @throws {CompositionError} when either file is missing, unreadable, or unparsable.
471
+ */
472
+ export function readPresetDefinition(id: string, dir: string): PresetDefinition {
473
+ const read = (name: string): string => {
474
+ try {
475
+ return readFileSync(join(dir, name), 'utf8')
476
+ } catch (error) {
477
+ throw new CompositionError(`${name} is unreadable: ${error instanceof Error ? error.message : String(error)}`)
478
+ }
479
+ }
480
+ return {
481
+ id,
482
+ ...readPresetMetadata(read('preset.yml')),
483
+ plugins: readCompositionRows(read('agent.cordis.yml'), dir),
484
+ }
485
+ }
486
+
487
+ /**
488
+ * The preset-row settings the plugin exposes in the web settings surface, as the
489
+ * values to apply to the declared composition.
490
+ *
491
+ * The settings surface edits the PLUGIN's own Config, while the values that
492
+ * shape a session live in the declared preset's rows; applying them here is what
493
+ * connects the two. Every field is optional — an absent value leaves the shipped
494
+ * row exactly as the composition declares it.
495
+ */
496
+ export interface PresetOverrides {
497
+ /** The `tool-catalog` row's `presentation` value. */
498
+ presentation?: string
499
+ /** The `guard` row's `enabled` switch. */
500
+ guardEnabled?: boolean
501
+ /** The `guard` row's sensitivity preset. */
502
+ guardSensitivity?: string
503
+ /** The `guard` row's per-step reasoning-character floor. */
504
+ guardStallReasoningChars?: number
505
+ /** The `guard` row's slow-burn step cap. */
506
+ guardGlobalStallCap?: number
507
+ /** The `guard` row's identical-argument failure count. */
508
+ guardEchoFailures?: number
509
+ }
510
+
511
+ /** One settings overlay entry: the row it targets and the keys it writes. */
512
+ type OverrideTarget = readonly [string, Readonly<Record<string, unknown>>]
513
+
514
+ /** The overlay table: settings field to composition row and config key. */
515
+ function overrideTargets(overrides: PresetOverrides): OverrideTarget[] {
516
+ return [
517
+ ['tool-catalog', { ...overrides.presentation === undefined ? {} : { presentation: overrides.presentation } }],
518
+ ['guard', {
519
+ ...overrides.guardEnabled === undefined ? {} : { enabled: overrides.guardEnabled },
520
+ ...overrides.guardSensitivity === undefined ? {} : { sensitivity: overrides.guardSensitivity },
521
+ ...overrides.guardStallReasoningChars === undefined ? {} : { stallReasoningChars: overrides.guardStallReasoningChars },
522
+ ...overrides.guardGlobalStallCap === undefined ? {} : { globalStallCap: overrides.guardGlobalStallCap },
523
+ ...overrides.guardEchoFailures === undefined ? {} : { echoFailures: overrides.guardEchoFailures },
524
+ }],
525
+ ]
526
+ }
527
+
528
+ /**
529
+ * Apply the settings overlay to one parsed row list.
530
+ *
531
+ * Rows are addressed by their `id`, and only a row the composition actually
532
+ * carries is touched: the overlay narrows the shipped configuration, it never
533
+ * invents a mount the preset did not have. The shipped composition declares
534
+ * every key the overlay writes, so leaving a key absent only matters for a
535
+ * composition that dropped it.
536
+ * @param rows - the parsed composition rows.
537
+ * @param overrides - the operator's settings-surface choices.
538
+ * @returns a new row list with the overlay applied.
539
+ */
540
+ export function applyPresetOverrides(
541
+ rows: PresetDefinition['plugins'],
542
+ overrides: PresetOverrides,
543
+ ): PresetDefinition['plugins'] {
544
+ const table = overrideTargets(overrides)
545
+ return rows.map((row) => {
546
+ const target = table.find(([id]) => id === (row as CompositionRow).id)
547
+ if (target === undefined) return row
548
+ const [, patch] = target
549
+ if (Object.keys(patch).length === 0) return row
550
+ const config = (row as CompositionRow).config
551
+ if (typeof config !== 'object' || config === null || Array.isArray(config)) return row
552
+ return { ...row, config: { ...(config as Record<string, unknown>), ...patch } }
553
+ })
554
+ }
package/src/index.test.ts CHANGED
@@ -1,8 +1,16 @@
1
+ /**
2
+ * The host half's own surface: the family-shared harness-home resolution it
3
+ * still carries as a synced copy, the schema defaults the effective settings
4
+ * fall back to, and the preset directory the declaration reads.
5
+ */
6
+
7
+ import { existsSync } from 'node:fs'
1
8
  import { describe, expect, it } from 'vitest'
2
9
  import { homedir } from 'node:os'
3
10
  import { join } from 'node:path'
4
11
  import process from 'node:process'
5
- import { dshHome } from './index.ts'
12
+ import { dshHome } from './dsh-home.ts'
13
+ import { Config, DEFAULT_CONFIG, bundledPresetDir, resolveConfig } from './index.ts'
6
14
 
7
15
  /** Run `body` with the given DSH_HOME overrides, restoring the env afterwards. */
8
16
  function withEnv(values: Record<string, string | undefined>, body: () => void): void {
@@ -65,3 +73,62 @@ describe('dshHome', () => {
65
73
  })
66
74
  })
67
75
  })
76
+
77
+ describe('resolveConfig', () => {
78
+ it('operator gets the schema defaults for an activation with no config', () => {
79
+ // Given an activation the Host passed no config to, When the operator
80
+ // reads the effective settings, Then every field is the schema default.
81
+ expect(resolveConfig(undefined)).toEqual(DEFAULT_CONFIG)
82
+ expect(resolveConfig({})).toEqual(DEFAULT_CONFIG)
83
+ // The schema and the reader agree on every default the settings card shows:
84
+ // the Host hands the activation the schema's own output, whose volatile
85
+ // fields are references, and the reader resolves them back to values.
86
+ expect(resolveConfig(Config({}))).toEqual(DEFAULT_CONFIG)
87
+ })
88
+
89
+ it('operator sees a committed volatile write through the held reference', () => {
90
+ // Given a volatile field the Host hands over as a stable reference, When
91
+ // the operator commits a write and reads again, Then the read moves with it.
92
+ let committed = false
93
+ const live = { get: () => committed }
94
+ const config = { announceToAgent: live, enabled: { get: () => true } }
95
+ expect(resolveConfig(config).announceToAgent).toBe(false)
96
+ committed = true
97
+ expect(resolveConfig(config).announceToAgent).toBe(true)
98
+ })
99
+
100
+ it('operator gets a plain profile-patch value as it is', () => {
101
+ // Given a config written as plain values, When the operator reads the
102
+ // effective settings, Then each one passes through unchanged.
103
+ expect(resolveConfig({
104
+ enabled: false,
105
+ announceToAgent: true,
106
+ presentation: 'ptc',
107
+ guardEnabled: false,
108
+ guardSensitivity: 'aggressive',
109
+ guardStallReasoningChars: 12000,
110
+ guardGlobalStallCap: 6,
111
+ guardEchoFailures: 2,
112
+ })).toEqual({
113
+ enabled: false,
114
+ announceToAgent: true,
115
+ presentation: 'ptc',
116
+ guardEnabled: false,
117
+ guardSensitivity: 'aggressive',
118
+ guardStallReasoningChars: 12000,
119
+ guardGlobalStallCap: 6,
120
+ guardEchoFailures: 2,
121
+ })
122
+ })
123
+ })
124
+
125
+ describe('bundledPresetDir', () => {
126
+ it('operator has the bundled preset directory the declaration reads', () => {
127
+ // Given the installed package, When the operator resolves the bundled
128
+ // preset directory, Then it holds the composition and its local plugins.
129
+ const dir = bundledPresetDir()
130
+ expect(existsSync(join(dir, 'agent.cordis.yml'))).toBe(true)
131
+ expect(existsSync(join(dir, 'preset.yml'))).toBe(true)
132
+ expect(existsSync(join(dir, 'minimal-prompt.mjs'))).toBe(true)
133
+ })
134
+ })