@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.
Files changed (59) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +55 -41
  3. package/README.zh.md +54 -40
  4. package/cordis.patch.yml +3 -2
  5. package/icon.svg +3 -0
  6. package/lib/client.js +1380 -29
  7. package/lib/client.js.map +1 -1
  8. package/lib/index.js +616 -367
  9. package/lib/types/announce.test.d.ts +10 -0
  10. package/lib/types/client/LiangShenSettingsCard.d.ts +78 -0
  11. package/lib/types/client/PluginSettingsCard.d.ts +137 -0
  12. package/lib/types/client/index.d.ts +57 -4
  13. package/lib/types/client/lever-controller.d.ts +16 -2
  14. package/lib/types/client/locales.d.ts +40 -1
  15. package/lib/types/client/main-session.d.ts +32 -0
  16. package/lib/types/client/plugin-card-seat.d.ts +103 -0
  17. package/lib/types/client/settings-form.d.ts +197 -0
  18. package/lib/types/composition.d.ts +116 -0
  19. package/lib/types/composition.test.d.ts +7 -0
  20. package/lib/types/core/lever.d.ts +6 -3
  21. package/lib/types/index.d.ts +160 -33
  22. package/lib/types/index.test.d.ts +5 -0
  23. package/package.json +27 -18
  24. package/presets/liangshen/NOTICE +4 -4
  25. package/presets/liangshen/agent.cordis.yml +168 -123
  26. package/presets/liangshen/fact-ledger.mjs +141 -0
  27. package/presets/liangshen/guard.mjs +426 -0
  28. package/presets/liangshen/minimal-prompt.mjs +73 -38
  29. package/presets/liangshen/paging.mjs +232 -0
  30. package/presets/liangshen/tool-activate.mjs +176 -0
  31. package/presets/liangshen/tool-catalog.mjs +615 -219
  32. package/presets/liangshen/working-context.mjs +222 -0
  33. package/src/announce.test.ts +248 -55
  34. package/src/client/LiangShenLever.module.css +2 -0
  35. package/src/client/LiangShenLever.tsx +41 -10
  36. package/src/client/LiangShenSettingsCard.tsx +233 -0
  37. package/src/client/PluginSettingsCard.tsx +555 -0
  38. package/src/client/index.ts +102 -5
  39. package/src/client/lever-controller.ts +76 -9
  40. package/src/client/locales.ts +79 -1
  41. package/src/client/main-session.ts +43 -0
  42. package/src/client/plugin-card-seat.ts +192 -0
  43. package/src/client/settings-card.module.css +418 -0
  44. package/src/client/settings-form.ts +442 -0
  45. package/src/composition.test.ts +294 -0
  46. package/src/composition.ts +554 -0
  47. package/src/core/lever.ts +7 -4
  48. package/src/index.test.ts +68 -1
  49. package/src/index.ts +293 -101
  50. package/tools/benchmark-live-run.mjs +193 -63
  51. package/lib/types/schema.d.ts +0 -18
  52. package/lib/types/schema.test.d.ts +0 -1
  53. package/lib/types/sync.d.ts +0 -47
  54. package/lib/types/sync.test.d.ts +0 -1
  55. package/presets/liangshen/custom-bash.mjs +0 -213
  56. package/src/schema.test.ts +0 -64
  57. package/src/schema.ts +0 -110
  58. package/src/sync.test.ts +0 -224
  59. package/src/sync.ts +0 -222
@@ -1,24 +1,29 @@
1
1
  /**
2
2
  * One bounded live benchmark run: a real DeepSeek session driven through the
3
- * profile's own composition, with the evaluated preset supplied from an
4
- * ISOLATED preset root.
3
+ * profile's own composition, with the evaluated preset supplied as an ISOLATED
4
+ * registry declaration.
5
5
  *
6
6
  * Isolation rules this script follows:
7
7
  * - The harness home stays the real one, so credentials, settings, and the model
8
8
  * route resolve exactly as they do for a user session. Nothing is copied or read
9
9
  * by this script.
10
- * - The evaluated preset is written to a temporary root and selected through the
11
- * roster's own `roots` config, so the shipped/user roots cannot shadow it and no
12
- * installed preset is edited.
10
+ * - The evaluated preset is materialized into a temporary directory and declared
11
+ * to the run's own agent-preset registry from the variant patch, so an installed
12
+ * preset cannot shadow it and no installed preset is edited. (Presets stopped
13
+ * being discovered from a configured root at 0.1.7-alpha.1: a preset is an
14
+ * ordinary registry declaration now, so there is no roster `roots` config to
15
+ * aim at.)
13
16
  * - Session persistence is redirected into the run directory, so real session
14
17
  * history is never appended to.
15
18
  *
16
19
  * The candidate matrix follows the LiangShen V4.1 Flash improvement plan:
17
- * B (current persona), P (candidate persona), T (candidate persona + PTC from the
18
- * first turn), N (candidate persona + native tools throughout), and M (the
19
- * official bundle's Minimal preset as an external reference). Persona wording and
20
- * tool strategy vary independently, and a run records the baseline it ran against
21
- * so an aggregated report can attribute a difference to one factor.
20
+ * B (current persona), P (candidate persona), T (candidate persona + PTC-only
21
+ * presentation), T (candidate persona + 'both' presentation), N (candidate
22
+ * persona + native presentation throughout), and M
23
+ * (the official bundle's Minimal preset as an external reference). Persona
24
+ * wording and tool presentation vary independently, and a run records the
25
+ * baseline it ran against so an aggregated report can attribute a difference to
26
+ * one factor.
22
27
  *
23
28
  * Usage:
24
29
  * node tools/benchmark-live-run.mjs --variant B [--timeout 300000] [--keep]
@@ -27,11 +32,11 @@
27
32
 
28
33
  import { execFileSync, spawn } from 'node:child_process'
29
34
  import { createHash } from 'node:crypto'
30
- import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
35
+ import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs'
31
36
  import { createRequire } from 'node:module'
32
37
  import { tmpdir } from 'node:os'
33
38
  import { dirname, join, relative, resolve, sep } from 'node:path'
34
- import { fileURLToPath } from 'node:url'
39
+ import { fileURLToPath, pathToFileURL } from 'node:url'
35
40
 
36
41
  const HERE = dirname(fileURLToPath(import.meta.url))
37
42
  const PACKAGE_ROOT = resolve(HERE, '..')
@@ -67,39 +72,34 @@ export const CANDIDATE_PERSONA = [
67
72
 
68
73
  /**
69
74
  * Variant definitions: what changes in the evaluated preset copy. `persona` picks
70
- * the prompt wording, `anchors` the staged tool surface (`null` keeps the shipped
71
- * default, an empty list disables staging), `ptc` the presentation after the
72
- * boundary, and `official` selects the bundle's Minimal preset untouched.
75
+ * the prompt wording, `presentation` the wire presentation (`null` keeps the
76
+ * shipped default), and `official` selects the bundle's Minimal preset
77
+ * untouched.
73
78
  */
74
79
  export const LIVE_VARIANTS = {
75
80
  B: {
76
81
  persona: 'current',
77
- anchors: null,
78
- ptc: true,
79
- note: 'baseline: shipped persona, four-tool anchor, PTC after the boundary',
82
+ presentation: null,
83
+ note: "baseline: shipped persona, shipped 'both' presentation",
80
84
  },
81
85
  P: {
82
86
  persona: 'candidate',
83
- anchors: null,
84
- ptc: true,
85
- note: 'candidate persona, four-tool anchor, PTC after the boundary',
87
+ presentation: null,
88
+ note: "candidate persona, shipped 'both' presentation",
86
89
  },
87
90
  T: {
88
91
  persona: 'candidate',
89
- anchors: [],
90
- ptc: true,
91
- note: 'candidate persona, PTC from the first turn',
92
+ presentation: 'ptc',
93
+ note: "candidate persona, 'ptc' presentation (collapsed wire to run_code)",
92
94
  },
93
95
  N: {
94
96
  persona: 'candidate',
95
- anchors: [],
96
- ptc: false,
97
- note: 'candidate persona, full native roster throughout',
97
+ presentation: 'native',
98
+ note: 'candidate persona, native roster throughout',
98
99
  },
99
100
  M: {
100
101
  persona: 'minimal',
101
- anchors: null,
102
- ptc: null,
102
+ presentation: null,
103
103
  official: true,
104
104
  note: 'external reference: the official Minimal preset, official configuration',
105
105
  },
@@ -139,13 +139,51 @@ function spawnCaptured(command, args, options, timeoutMs) {
139
139
  })
140
140
  }
141
141
 
142
- /** The directory the installed bundle publishes the official Minimal preset in. */
143
- export function officialMinimalPresetDir() {
142
+ /**
143
+ * The official Minimal preset's declaration file: the `dsh-web-app` bundle
144
+ * patch that inserts the `@deepseek-ai/dsh-agent-preset` row for `minimal`.
145
+ * Resolved from the harness install the run actually spawns, because the
146
+ * benchmark drives whatever `dsh` this machine launched with credentials.
147
+ * @returns the absolute path of the official patch file.
148
+ * @throws when that harness cannot be located or ships no such preset.
149
+ */
150
+ export function officialMinimalPresetPatch() {
151
+ const relative = join('@deepseek-ai', 'dsh-web-app', 'presets', 'minimal.patch.yml')
152
+ const tried = []
153
+ for (const shim of dshCommands()) {
154
+ try {
155
+ // The `dsh` shim is the only handle on the harness install: resolve the
156
+ // CLI package beside it, then the bundle package inside that install.
157
+ // alpha.2 note: createRequire derives module paths from the literal
158
+ // filename without resolving symlinks, so from the PATH shim
159
+ // (/opt/homebrew/bin/dsh) the lookup walks bin/node_modules and never
160
+ // reaches the install tree; realpath first lands inside the package.
161
+ const fromShim = createRequire(realpathSync(shim))
162
+ const cliPackage = fromShim.resolve('@deepseek-ai/dsh/package.json')
163
+ const patch = createRequire(cliPackage).resolve(relative)
164
+ if (existsSync(patch)) return patch
165
+ } catch (error) {
166
+ tried.push(`${shim}: ${error instanceof Error ? error.message : String(error)}`)
167
+ }
168
+ }
169
+ throw new Error('benchmark: the official Minimal preset is unavailable'
170
+ + (tried.length === 0 ? ' (no dsh command on PATH)' : `; tried ${tried.join(' | ')}`))
171
+ }
172
+
173
+ /** Whether any `dsh` command is on PATH (the preset reference tests gate on it). */
174
+ export function harnessInstallAvailable() {
175
+ return dshCommands().length > 0
176
+ }
177
+
178
+ /** Every `dsh` command the platform's PATH lookup reports. */
179
+ function dshCommands() {
144
180
  try {
145
- const pkg = require.resolve('@deepseek-ai/dsh-agent-presets/package.json')
146
- return join(dirname(pkg), 'presets', 'minimal')
147
- } catch (error) {
148
- throw new Error(`benchmark: the official Minimal preset is unavailable: ${error instanceof Error ? error.message : String(error)}`)
181
+ return execFileSync(process.platform === 'win32' ? 'where' : 'which', ['dsh'], { encoding: 'utf8' })
182
+ .split(/\r?\n/)
183
+ .map(line => line.trim())
184
+ .filter(line => line !== '')
185
+ } catch {
186
+ return []
149
187
  }
150
188
  }
151
189
 
@@ -195,24 +233,76 @@ export function replacePersonaPrefix(text, persona) {
195
233
  return [...lines.slice(0, start + 1), ...replacement, ...lines.slice(blockEnd)].join('\n')
196
234
  }
197
235
 
198
- /** Copy the preset and apply the variant's configuration change. */
236
+ /**
237
+ * Absolutize the relative module names of one composition.
238
+ *
239
+ * A declared preset's rows resolve a relative `name` against the DECLARING
240
+ * loader's base, not against the directory the row list came from, so the
241
+ * variant patch inlines the composition with every `./x.mjs` already resolved
242
+ * to the materialized copy's file URL. The scan is block-scalar aware: the
243
+ * persona prefix is prose, and a line inside it that happens to read
244
+ * `name: ./something` is content, not a row.
245
+ */
246
+ export function absolutizeModuleNames(text, baseDir) {
247
+ const base = pathToFileURL(baseDir + sep).href
248
+ const out = []
249
+ /** Indentation of the block scalar currently open, if any. */
250
+ let blockScalarIndent
251
+ for (const line of text.split('\n')) {
252
+ const body = line.trim()
253
+ if (blockScalarIndent !== undefined) {
254
+ // Content keeps the scalar open; blank lines belong to it too, and a line
255
+ // at or above the owning key's indentation closes it.
256
+ if (body === '' || line.length - line.trimStart().length > blockScalarIndent) {
257
+ out.push(line)
258
+ continue
259
+ }
260
+ blockScalarIndent = undefined
261
+ }
262
+ if (/^\s*[\w-]+:\s*[|>][-+]?\s*$/.test(line)) {
263
+ blockScalarIndent = line.length - line.trimStart().length
264
+ out.push(line)
265
+ continue
266
+ }
267
+ const match = /^(\s*)name: (\.\.?\/[^\s'"]+)$/.exec(line)
268
+ out.push(match === null ? line : `${match[1]}name: ${new URL(match[2], base).href}`)
269
+ }
270
+ return out.join('\n')
271
+ }
272
+
273
+ /** Indent one composition block so it can sit under a `plugins:` key. */
274
+ export function inlineComposition(text, baseDir, indent) {
275
+ const pad = ' '.repeat(indent)
276
+ return absolutizeModuleNames(text, baseDir)
277
+ .split('\n')
278
+ .map(line => (line.trim() === '' ? '' : pad + line))
279
+ .join('\n')
280
+ }
281
+
282
+ /**
283
+ * Copy the evaluated preset into the run directory and apply the variant's
284
+ * configuration change.
285
+ *
286
+ * The non-official variants get the bundled preset tree with their persona and
287
+ * presentation applied; the official reference gets the harness bundle's own
288
+ * Minimal preset patch, copied so the run records the exact bytes it evaluated.
289
+ */
199
290
  export function materializePreset(root, variantId, variant) {
200
291
  const target = join(root, variantId)
201
- cpSync(variant.official === true ? officialMinimalPresetDir() : PRESET_SOURCE, target, { recursive: true })
202
- if (variant.official === true) return target
292
+ if (variant.official === true) {
293
+ mkdirSync(target, { recursive: true })
294
+ cpSync(officialMinimalPresetPatch(), join(target, 'minimal.patch.yml'))
295
+ return target
296
+ }
297
+ cpSync(PRESET_SOURCE, target, { recursive: true })
203
298
  const composition = join(target, 'agent.cordis.yml')
204
- if (variant.anchors !== null && variant.anchors !== undefined) {
299
+ if (variant.presentation !== null && variant.presentation !== undefined) {
205
300
  const text = readFileSync(composition, 'utf8')
206
- // Anchor on the config line: the composition also NAMES `anchorTools: [bash]`
301
+ // Anchor on the config line: the composition also NAMES the presentation key
207
302
  // inside its prose, and rewriting a comment would leave the real surface alone.
208
- const replaced = text.replace(/^(\s*)anchorTools: \[[^\]]*\]/m, `$1anchorTools: [${variant.anchors.join(', ')}]`)
209
- if (replaced === text) throw new Error('benchmark: the preset composition carries no anchorTools line to vary')
210
- writeFileSync(composition, replaced)
211
- }
212
- if (variant.ptc === false) {
213
- const text = readFileSync(composition, 'utf8')
214
- const replaced = text.replace(/ptcPresentation: true/, 'ptcPresentation: false')
215
- if (replaced === text) throw new Error('benchmark: the preset composition carries no ptcPresentation line to vary')
303
+ const pattern = /^(\s*)presentation: '[^']*'/m
304
+ if (!pattern.test(text)) throw new Error('benchmark: the preset composition carries no presentation line to vary')
305
+ const replaced = text.replace(pattern, `$1presentation: '${variant.presentation}'`)
216
306
  writeFileSync(composition, replaced)
217
307
  }
218
308
  if (variant.persona === 'candidate') {
@@ -501,8 +591,9 @@ export function priceRun(usage, prices, route) {
501
591
  }
502
592
 
503
593
  /** Build the variant patch that redirects persistence and selects the isolated preset. */
504
- function buildPatch({ variantId, presetRoot, runDir, turns }) {
505
- return [
594
+ export function buildPatch({ variantId, variant, presetDir, runDir, turns }) {
595
+ const presetId = variant.official === true ? OFFICIAL_PRESET_ID : variantId
596
+ const lines = [
506
597
  '- id: headless-startup',
507
598
  ' disabled: true',
508
599
  '',
@@ -520,26 +611,59 @@ function buildPatch({ variantId, presetRoot, runDir, turns }) {
520
611
  ` model: ${FIXED_ROUTE.model}`,
521
612
  ` reasoningEffort: ${FIXED_ROUTE.reasoningEffort}`,
522
613
  '',
614
+ '# The preset roster. The headless profile mounts neither the registry nor a',
615
+ '# preset, so the variant supplies both: `default` names the evaluated preset',
616
+ '# for the session this run creates, and mode selection stays off so no picker',
617
+ '# or default-preset write can move a run off the evaluated arm.',
523
618
  '- insert:',
524
- ' - id: agent-presets',
525
- " name: '@deepseek-ai/dsh-agent-presets'",
619
+ ' - id: agent-preset-registry',
620
+ " name: '@deepseek-ai/dsh-agent-preset-registry'",
526
621
  ' config:',
527
- ` default: ${variantId}`,
528
- ' includeShippedRoot: false',
529
- ' includeUserRoot: false',
530
- ' roots:',
531
- ` - path: ${JSON.stringify(presetRoot.replace(/\\/g, '/'))}`,
532
- " trust: 'user'",
622
+ ` default: ${JSON.stringify(presetId)}`,
623
+ ' modeSelectionEnabled: false',
624
+ ]
625
+ if (variant.official !== true) {
626
+ lines.push(
627
+ '',
628
+ '# The evaluated preset as an ordinary declaration: its rows are the',
629
+ '# materialized composition, with every relative module name already',
630
+ '# resolved to that copy so the registry mounts exactly this tree.',
631
+ '- insert:',
632
+ ` - id: preset-${variantId}`,
633
+ " name: '@deepseek-ai/dsh-agent-preset'",
634
+ ' config:',
635
+ ` id: ${JSON.stringify(presetId)}`,
636
+ ' order: 1',
637
+ ' plugins:',
638
+ inlineComposition(readFileSync(join(presetDir, 'agent.cordis.yml'), 'utf8'), presetDir, 10),
639
+ )
640
+ }
641
+ lines.push(
533
642
  '',
534
643
  '- insert:',
535
644
  ' - id: benchmark-driver',
536
645
  ` name: ${JSON.stringify(DRIVER)}`,
537
646
  ' config:',
538
- ` preset: ${JSON.stringify(variantId)}`,
647
+ ` preset: ${JSON.stringify(presetId)}`,
539
648
  ' turns:',
540
649
  ...(turns ?? DEFAULT_TURNS).map((turn) => ` - ${JSON.stringify(turn)}`),
541
650
  '',
542
- ].join('\n')
651
+ )
652
+ return lines.join('\n')
653
+ }
654
+
655
+ /**
656
+ * The official Minimal preset's own id: the harness bundle declares it, so the
657
+ * variant patch only selects it rather than declaring a second preset.
658
+ */
659
+ export const OFFICIAL_PRESET_ID = 'minimal'
660
+
661
+ /**
662
+ * The reference variant's overlay: the harness bundle's own Minimal preset
663
+ * patch, copied into the run directory so the run records the exact bytes.
664
+ */
665
+ function officialPresetPatchPath(presetDir) {
666
+ return join(presetDir, 'minimal.patch.yml')
543
667
  }
544
668
 
545
669
  /**
@@ -562,12 +686,18 @@ export async function runLiveCase(options) {
562
686
  if (options.task !== undefined) writeTaskFiles(workspace, options.task.files)
563
687
 
564
688
  const turns = options.turns ?? options.task?.turns ?? DEFAULT_TURNS
565
- const patch = buildPatch({ variantId, presetRoot, runDir, turns })
689
+ const patch = buildPatch({ variantId, variant, presetDir, runDir, turns })
566
690
 
567
691
  const patchPath = join(runDir, 'variant.patch.yml')
568
692
  writeFileSync(patchPath, patch, 'utf8')
569
693
 
570
- const args = ['--profile', 'headless', '--patch', patchPath, 'run the configured turns']
694
+ // The reference variant evaluates the harness's own preset row, so its
695
+ // declaration rides a second overlay instead of the variant patch.
696
+ const overlays = ['--patch', patchPath]
697
+ if (variant.official === true) {
698
+ overlays.push('--patch', officialPresetPatchPath(presetDir))
699
+ }
700
+ const args = ['--profile', 'headless', ...overlays, 'run the configured turns']
571
701
  const spec = process.platform === 'win32'
572
702
  ? { command: 'cmd.exe', args: windowsCmdShimArgs('dsh', args), windowsVerbatimArguments: true }
573
703
  : { command: 'dsh', args }
@@ -768,4 +898,4 @@ if (isMain) {
768
898
  console.log(` tokens ${report.usage.totalTokens} (input ${report.usage.uncachedInputTokens}, output ${report.usage.outputTokens}, cacheRead ${report.usage.cacheReadTokens})`)
769
899
  console.log(` report ${outFile}`)
770
900
  }
771
- }
901
+ }
@@ -1,18 +0,0 @@
1
- /**
2
- * Structural validation for a bundled `agent.cordis.yml`.
3
- *
4
- * Deliberately dependency-free: it parses only the flat row metadata the sync
5
- * and the dsh agent-presets loader rely on. Every top-level row is written as
6
- * `- id: <id>` at column zero, with the `name`/`group`/`disabled` keys at two
7
- * spaces of indentation. Nested `config:` and `isolate:` bodies are opaque to
8
- * this validator — the dsh loader checks their semantics.
9
- *
10
- * Returns the list of problems found; an empty array means the document is
11
- * structurally valid.
12
- */
13
- /**
14
- * Validate the structural contract of an `agent.cordis.yml` document.
15
- * @param text - the raw YAML document text.
16
- * @returns a list of human-readable problems; empty means valid.
17
- */
18
- export declare function validateAgentCordis(text: string): string[];
@@ -1 +0,0 @@
1
- export {};
@@ -1,47 +0,0 @@
1
- /**
2
- * Sync every preset directory under `sourceRoot` into `targetRoot` — the
3
- * dsh agent-presets discovery root (harness-home `.agent-presets`).
4
- *
5
- * A preset is a directory holding `agent.cordis.yml`; the directory name is
6
- * the preset id. Copy is per-directory and idempotent: a preset whose target
7
- * tree is byte-identical to the source tree is skipped, otherwise the source
8
- * tree is copied and any target files the source does not contain are removed.
9
- * Directories the plugin does not own (other presets the user authored) are
10
- * never touched.
11
- *
12
- * After a preset is synced its `agent.cordis.yml` is validated against the
13
- * structural preset schema; a validation failure is reported through the
14
- * run's `failed` entries instead of being a warn-only side effect, so callers
15
- * can observe (and surface) a broken preset rather than silently shipping it.
16
- */
17
- /** One sync run's outcome, grouped for diagnostics. */
18
- export interface SyncResult {
19
- /** Preset ids whose tree was (re)written this run. */
20
- synced: string[];
21
- /** Preset ids already current — nothing copied. */
22
- current: string[];
23
- /** Preset ids that failed, with the underlying error message. */
24
- failed: {
25
- id: string;
26
- error: string;
27
- }[];
28
- /** Previously bundled preset ids removed from the target root this run. */
29
- retired: string[];
30
- }
31
- /** Copy `sourceRoot/<id>` into `targetRoot/<id>`, idempotently. */
32
- export declare function syncOnePreset(sourceDir: string, targetDir: string): 'synced' | 'current';
33
- /**
34
- * Sync every preset under `sourceRoot` into `targetRoot`, then remove
35
- * target directories named in `retire` that the bundle no longer ships —
36
- * preset ids the plugin once owned and later dropped. Only those exact ids
37
- * are removed; every other target directory is left untouched.
38
- *
39
- * Each synced (or already-current) preset is validated against the structural
40
- * `agent.cordis.yml` schema; a validation failure lands in `failed` so the
41
- * caller can surface a broken preset as a first-class result instead of a
42
- * warn-only log line.
43
- * @param sourceRoot - plugin-owned preset tree (bundled in the package).
44
- * @param targetRoot - dsh agent-presets discovery root (e.g. <home>/.dsh/.agent-presets).
45
- * @param retire - previously bundled preset ids to remove when absent from the source.
46
- */
47
- export declare function syncPresetTrees(sourceRoot: string, targetRoot: string, retire?: string[]): SyncResult;
@@ -1 +0,0 @@
1
- export {};
@@ -1,213 +0,0 @@
1
- /**
2
- * custom-bash — a Windows-capable `bash` tool for the liangshen preset. It
3
- * registers under the SAME name (`bash`) as the persistent shell so every
4
- * platform exposes one shell tool of that name, but executes through
5
- * `ctx.subprocess.spawn` instead of a PTY.
6
- *
7
- * WHY: DSH's PTY backend is linux/darwin-only — subprocess-local throws
8
- * "terminal inspection is unsupported on platform win32", so the
9
- * persistent-shell group (dsh-terminal + dsh-terminal-bash +
10
- * dsh-tool-bash-persistent) cannot spawn on Windows. agent.cordis.yml disables
11
- * that group on win32 and enables this tool instead; both platforms end up
12
- * with exactly one `bash` tool.
13
- *
14
- * Executable resolution (config `bashPath`, no hardcoded install path):
15
- * an explicit non-empty `bashPath` wins unconditionally. Unset, the Git Bash
16
- * executable is INFERRED in probe order:
17
- * 1. the `git` executable on PATH — its install root carries `bin\bash.exe`
18
- * one level up from `cmd\`, beside `bin\`, or two levels up from
19
- * `mingw64\bin\` (the standard installer, choco, and winget all resolve
20
- * here);
21
- * 2. the well-known Git-for-Windows roots derived from environment variables
22
- * (ProgramFiles, ProgramFiles(x86), LOCALAPPDATA\Programs\Git, scoop's
23
- * ~\scoop\apps\git\current junction);
24
- * 3. plain `bash` through `ctx.subprocess.resolveExecutable` (PATH lookup —
25
- * last resort; on Windows that may pick the WSL shim, which is still true
26
- * bash even though paths shift to /mnt/…).
27
- *
28
- * If NOTHING resolves the tool fails with an actionable error — it never
29
- * silently executes under pwsh/cmd, which are different command languages.
30
- *
31
- * Semantics mirror the official bash tool: `bash -c <command>` in a fresh
32
- * process, bounded output, non-zero exit reported not thrown. No sandbox
33
- * confinement on Windows (the sandbox backend is linux-only); the description
34
- * says so.
35
- *
36
- * Ported from xiaobright/dsh-anchored-standard (MIT) — see NOTICE.
37
- */
38
-
39
- import { access } from 'node:fs/promises'
40
- import { dirname, join } from 'node:path'
41
-
42
- /** Cordis plugin name used by loader diagnostics. */
43
- export const name = 'custom-bash'
44
-
45
- /** The subprocess and tools services must exist before this tool can register. */
46
- export const inject = ['subprocess', 'tools']
47
-
48
- const DEFAULT_TIMEOUT_MS = 120000
49
- const DEFAULT_MAX_OUTPUT_BYTES = 64000
50
-
51
- /**
52
- * Git Bash candidate paths, in probe order (see the header): the `git`
53
- * executable's install root first, then the well-known env-derived roots.
54
- * Exported for tests; pure — existence probing happens at the call site.
55
- */
56
- export function bashCandidates(env, gitExe) {
57
- const candidates = []
58
- // git at <root>\cmd\git.exe (installer/scoop) or <root>\bin\git.exe →
59
- // <root>\bin\bash.exe; <root>\mingw64\bin\git.exe (portable) → two up.
60
- // A bare relative name means `git` did not actually resolve to a path.
61
- if (typeof gitExe === 'string' && /[/\\]/.test(gitExe)) {
62
- const dir = dirname(gitExe)
63
- const root = dirname(dir)
64
- candidates.push(
65
- join(root, 'bin', 'bash.exe'),
66
- join(dir, 'bash.exe'),
67
- join(dirname(root), 'bin', 'bash.exe'),
68
- )
69
- }
70
- if (env.ProgramFiles) candidates.push(join(env.ProgramFiles, 'Git', 'bin', 'bash.exe'))
71
- if (env['ProgramFiles(x86)']) candidates.push(join(env['ProgramFiles(x86)'], 'Git', 'bin', 'bash.exe'))
72
- if (env.LOCALAPPDATA) candidates.push(join(env.LOCALAPPDATA, 'Programs', 'Git', 'bin', 'bash.exe'))
73
- if (env.USERPROFILE) candidates.push(join(env.USERPROFILE, 'scoop', 'apps', 'git', 'current', 'bin', 'bash.exe'))
74
- // Layouts overlap (a `bin` git.exe derives the same bash twice) — probe
75
- // order survives the dedupe, insertion order is preserved.
76
- return [...new Set(candidates)]
77
- }
78
-
79
- /** Tool parameter schema for the model-facing command. */
80
- const commandSchema = {
81
- type: 'object',
82
- properties: {
83
- command: {
84
- type: 'string',
85
- description: 'The bash command to execute (`bash -c` string domain).',
86
- },
87
- workdir: {
88
- type: 'string',
89
- description: 'Optional working directory; defaults to the session cwd.',
90
- },
91
- },
92
- required: ['command'],
93
- additionalProperties: false,
94
- }
95
-
96
- /** Register the model-facing `bash` tool. */
97
- export function apply(ctx, config) {
98
- const explicitBashPath = typeof config?.bashPath === 'string' && config.bashPath.length > 0 ? config.bashPath : undefined
99
- const timeoutMs = Number.isSafeInteger(config?.timeoutMs) && config.timeoutMs > 0 ? config.timeoutMs : DEFAULT_TIMEOUT_MS
100
- const maxOutputBytes = Number.isSafeInteger(config?.maxOutputBytes) && config.maxOutputBytes > 0 ? config.maxOutputBytes : DEFAULT_MAX_OUTPUT_BYTES
101
-
102
- // The inferred executable is memoized per plugin instance: candidate probing
103
- // walks the filesystem, and the answer cannot change within a mount. A
104
- // failed inference is NOT memoized — the plain `bash` fallback resolves
105
- // fresh on every execute until some probe succeeds.
106
- let inferredShell
107
- const exists = (path) => access(path).then(() => true, () => false)
108
- const resolveShell = async (signal) => {
109
- if (explicitBashPath !== undefined) {
110
- // A misconfigured explicit path must fail as itself, not as a
111
- // discovery miss — the raw resolution error says which path failed.
112
- return ctx.subprocess.resolveExecutable(explicitBashPath, undefined, signal)
113
- }
114
- if (inferredShell !== undefined) {
115
- return ctx.subprocess.resolveExecutable(inferredShell, undefined, signal)
116
- }
117
- let gitExe
118
- try {
119
- gitExe = await ctx.subprocess.resolveExecutable('git', undefined, signal)
120
- } catch {
121
- // git unresolvable → the env-derived candidates below still apply
122
- }
123
- for (const candidate of bashCandidates(process.env, gitExe)) {
124
- if (!(await exists(candidate))) continue
125
- try {
126
- inferredShell = await ctx.subprocess.resolveExecutable(candidate, undefined, signal)
127
- return inferredShell
128
- } catch {
129
- // Exists but unresolvable (EPERM, a broken scoop junction): keep
130
- // probing — one bad root must not block the rest of the chain, and
131
- // nothing is memoized so later executes can still find a good one.
132
- continue
133
- }
134
- }
135
- try {
136
- return await ctx.subprocess.resolveExecutable('bash', undefined, signal)
137
- } catch (error) {
138
- // Total discovery failure (no Git Bash root, no env root, no bash on
139
- // PATH): name the remedies instead of leaking a raw ENOENT. Never
140
- // fall back to pwsh/cmd here — the schema promises `bash -c`
141
- // semantics; a different shell would silently break every command.
142
- throw new Error(`bash executable not found — install Git for Windows, expose a bash on PATH, or set the custom-bash \`bashPath\` config (${String((error && error.message) || error)})`)
143
- }
144
- }
145
-
146
- ctx.tools.register({
147
- name: 'bash',
148
- description: [
149
- 'Run commands in a bash shell (Git Bash on Windows)',
150
- '* When invoking this tool, the contents of the "command" parameter does NOT need to be XML-escaped.',
151
- "* You don't have access to the internet via this tool.",
152
- '* You do have access to a mirror of common linux and python packages via apt and pip.',
153
- '* State does NOT persist across command calls: each call runs in a fresh shell.',
154
- "* To inspect a particular line range of a file, e.g. lines 10-25, try 'sed -n 10,25p /path/to/the/file'.",
155
- '* Please avoid commands that may produce a very large amount of output.',
156
- '* NOTE: runs without OS sandbox confinement on Windows (no landlock); treat output as untrusted.',
157
- ].join('\n'),
158
- parameters: commandSchema,
159
- output: {
160
- schema: {
161
- type: 'object',
162
- additionalProperties: false,
163
- properties: {
164
- text: { type: 'string' },
165
- },
166
- required: ['text'],
167
- },
168
- render: (_args, value) => [{ type: 'text', text: value.text }],
169
- },
170
- async execute(args, exec) {
171
- const shell = await resolveShell(exec?.signal)
172
- const workdir = typeof args.workdir === 'string' && args.workdir.length > 0
173
- ? args.workdir
174
- : exec?.agent?.session?.header?.cwd
175
- const signal = exec?.signal
176
- const handle = ctx.subprocess.spawn({
177
- argv: [shell, '-c', args.command],
178
- ...workdir !== undefined ? { cwd: workdir } : {},
179
- stdio: {
180
- stdin: 'ignore',
181
- stdout: { maxBytes: maxOutputBytes },
182
- stderr: { maxBytes: maxOutputBytes },
183
- },
184
- ...signal !== undefined ? { signal } : {},
185
- graceMs: 3000,
186
- })
187
- let outcome
188
- try {
189
- outcome = await handle.done
190
- } catch (error) {
191
- // A spawn-level failure (bad executable, EPERM) surfaces as a throw,
192
- // which the runtime turns into an isError result.
193
- throw new Error(`bash spawn failed: ${String(error)}`)
194
- }
195
- let stdout = ''
196
- let stderr = ''
197
- try {
198
- stdout = handle.collected.stdout.readFrom(0).text
199
- stderr = handle.collected.stderr.readFrom(0).text
200
- } catch {
201
- // Collected readers may be unavailable on some backends; tolerate.
202
- }
203
- const text = [stdout, stderr].filter((part) => part.length > 0).join('\n')
204
- const tail = text.length > 0 ? text : `exit code: ${outcome.exitCode} (no output)`
205
- if (outcome.exitCode !== 0) {
206
- // Non-zero exit is a reported failure, not a throw: the model sees the
207
- // command output plus the exit code.
208
- throw new Error(tail)
209
- }
210
- return { text: tail }
211
- },
212
- })
213
- }