@linxin666/dsh-liangshen 0.3.22 → 0.3.24

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 (37) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +45 -38
  3. package/README.zh.md +44 -37
  4. package/lib/client.js +1058 -11
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +105 -22
  7. package/lib/types/client/LiangShenSettingsCard.d.ts +61 -0
  8. package/lib/types/client/PluginSettingsCard.d.ts +133 -0
  9. package/lib/types/client/index.d.ts +34 -0
  10. package/lib/types/client/locales.d.ts +27 -1
  11. package/lib/types/client/plugin-card-seat.d.ts +96 -0
  12. package/lib/types/client/settings-form.d.ts +197 -0
  13. package/lib/types/core/lever.d.ts +6 -3
  14. package/lib/types/index.d.ts +23 -11
  15. package/lib/types/sync.d.ts +29 -2
  16. package/package.json +6 -2
  17. package/presets/liangshen/NOTICE +4 -4
  18. package/presets/liangshen/agent.cordis.yml +130 -119
  19. package/presets/liangshen/minimal-prompt.mjs +71 -36
  20. package/presets/liangshen/paging.mjs +232 -0
  21. package/presets/liangshen/tool-activate.mjs +176 -0
  22. package/presets/liangshen/tool-catalog.mjs +610 -218
  23. package/presets/liangshen/working-context.mjs +214 -0
  24. package/src/client/LiangShenLever.tsx +4 -1
  25. package/src/client/LiangShenSettingsCard.tsx +149 -0
  26. package/src/client/PluginSettingsCard.tsx +550 -0
  27. package/src/client/index.ts +60 -1
  28. package/src/client/locales.ts +53 -1
  29. package/src/client/plugin-card-seat.ts +185 -0
  30. package/src/client/settings-card.module.css +418 -0
  31. package/src/client/settings-form.ts +439 -0
  32. package/src/core/lever.ts +7 -4
  33. package/src/index.ts +35 -14
  34. package/src/sync.test.ts +86 -7
  35. package/src/sync.ts +108 -6
  36. package/tools/benchmark-live-run.mjs +24 -33
  37. package/presets/liangshen/custom-bash.mjs +0 -213
package/src/sync.test.ts CHANGED
@@ -2,10 +2,24 @@ import { describe, expect, it } from 'vitest'
2
2
  import { existsSync, mkdirSync, mkdtempSync, rmSync, statSync, utimesSync, writeFileSync, readFileSync } from 'node:fs'
3
3
  import { tmpdir } from 'node:os'
4
4
  import { join } from 'node:path'
5
- import { syncOnePreset, syncPresetTrees } from './sync.ts'
5
+ import { renderPresetOverrides, syncOnePreset, syncPresetTrees } from './sync.ts'
6
6
 
7
- /** Minimal structurally valid agent.cordis.yml used by the sync fixtures. */
8
- const VALID_AGENT_YAML = "- id: persona\n name: '@deepseek-ai/dsh-persona'\n"
7
+ /**
8
+ * Minimal structurally valid agent.cordis.yml used by the sync fixtures. It
9
+ * carries the two rows the settings overlay writes into, because the overlay
10
+ * only rewrites keys that already exist in the source — a fixture without them
11
+ * could not tell "left alone" from "wrote nothing".
12
+ */
13
+ const VALID_AGENT_YAML = [
14
+ "- id: persona",
15
+ " name: '@deepseek-ai/dsh-persona'",
16
+ "",
17
+ "- id: tool-catalog",
18
+ " name: ./tool-catalog.mjs",
19
+ " config:",
20
+ " presentation: 'ptc'",
21
+ "",
22
+ ].join('\n')
9
23
 
10
24
  function fixture(): { source: string; target: string; dispose: () => void } {
11
25
  const base = mkdtempSync(join(tmpdir(), 'dsh-liangshen-'))
@@ -18,6 +32,44 @@ function fixture(): { source: string; target: string; dispose: () => void } {
18
32
  return { source, target, dispose: () => rmSync(base, { recursive: true, force: true }) }
19
33
  }
20
34
 
35
+ describe('renderPresetOverrides', () => {
36
+ const SOURCE = [
37
+ "# a comment that names presentation: 'ptc'",
38
+ "- id: tool-catalog",
39
+ " name: ./tool-catalog.mjs",
40
+ " config:",
41
+ " descriptionMaxLength: 200",
42
+ " presentation: 'ptc'",
43
+ " pagedToolPatterns: ['mcp__*']",
44
+ "",
45
+ ].join('\n')
46
+
47
+ it('rewrites exactly the targeted keys and nothing else', () => {
48
+ const out = renderPresetOverrides(SOURCE, {
49
+ presentation: 'native',
50
+ })
51
+ expect(out).toContain("presentation: 'native'")
52
+ // Untouched values and the surrounding rows survive verbatim.
53
+ expect(out).toContain('descriptionMaxLength: 200')
54
+ expect(out).toContain("pagedToolPatterns: ['mcp__*']")
55
+ // The comment that mentions the key is not a config line and stays put.
56
+ expect(out).toContain("# a comment that names presentation: 'ptc'")
57
+ })
58
+
59
+ it('leaves absent settings and unknown rows alone', () => {
60
+ expect(renderPresetOverrides(SOURCE, {})).toBe(SOURCE)
61
+ // A row the composition does not mount is never invented.
62
+ const out = renderPresetOverrides("- id: persona\n name: x\n", { presentation: 'native' })
63
+ expect(out).toBe("- id: persona\n name: x\n")
64
+ })
65
+
66
+ it('does not write a key the target row does not carry', () => {
67
+ const noPresentation = "- id: persona\n name: x\n config:\n name: 'test'\n"
68
+ const out = renderPresetOverrides(noPresentation, { presentation: 'native' })
69
+ expect(out).toBe(noPresentation)
70
+ })
71
+ })
72
+
21
73
  describe('syncPresetTrees', () => {
22
74
  it('copies the bundled preset tree into the target root', () => {
23
75
  const f = fixture()
@@ -160,18 +212,45 @@ describe('syncPresetTrees', () => {
160
212
  })
161
213
 
162
214
  describe('mtime fast path', () => {
163
- it('re-syncs a byte-identical file whose mtime drifted beyond tolerance', () => {
215
+ it('re-syncs an ordinary file whose mtime drifted beyond tolerance', () => {
216
+ // Plain copies keep the size-and-mtime fast path: a gap beyond tolerance
217
+ // proves the pair cannot be byte-identical, so the read is skipped and the
218
+ // tree counts as moved.
164
219
  const f = fixture()
165
220
  try {
166
221
  syncPresetTrees(f.source, f.target)
167
- const dest = join(f.target, 'liangshen', 'agent.cordis.yml')
222
+ const dest = join(f.target, 'liangshen', 'preset.yml')
168
223
  const stat = statSync(dest)
169
- // Bump mtime a day into the future, keep the bytes identical.
170
224
  utimesSync(dest, stat.atime, new Date(stat.mtimeMs + 86400_000))
171
225
  const second = syncPresetTrees(f.source, f.target)
172
226
  expect(second.synced).toEqual(['liangshen'])
173
227
  expect(second.current).toEqual([])
174
- expect(readFileSync(dest, 'utf8')).toBe(VALID_AGENT_YAML)
228
+ } finally { f.dispose() }
229
+ })
230
+
231
+ it('treats the composition as current when its bytes match the overlaid source', () => {
232
+ // The composition is the one file the overlay may legitimately make differ
233
+ // from the raw source, so it is compared by content: an unchanged tree must
234
+ // report `current`, never a rewrite on every start.
235
+ const f = fixture()
236
+ try {
237
+ syncPresetTrees(f.source, f.target, [], { presentation: 'native' })
238
+ const dest = join(f.target, 'liangshen', 'agent.cordis.yml')
239
+ expect(readFileSync(dest, 'utf8')).toContain("presentation: 'native'")
240
+ const second = syncPresetTrees(f.source, f.target, [], { presentation: 'native' })
241
+ expect(second.current).toEqual(['liangshen'])
242
+ expect(second.synced).toEqual([])
243
+ } finally { f.dispose() }
244
+ })
245
+
246
+ it('rewrites the composition when the settings change', () => {
247
+ const f = fixture()
248
+ try {
249
+ syncPresetTrees(f.source, f.target, [], { presentation: 'native' })
250
+ const dest = join(f.target, 'liangshen', 'agent.cordis.yml')
251
+ const second = syncPresetTrees(f.source, f.target, [], { presentation: 'both' })
252
+ expect(second.synced).toEqual(['liangshen'])
253
+ expect(readFileSync(dest, 'utf8')).toContain("presentation: 'both'")
175
254
  } finally { f.dispose() }
176
255
  })
177
256
 
package/src/sync.ts CHANGED
@@ -15,7 +15,7 @@
15
15
  * can observe (and surface) a broken preset rather than silently shipping it.
16
16
  */
17
17
 
18
- import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, utimesSync } from 'node:fs'
18
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs'
19
19
  import { basename, dirname, join, relative } from 'node:path'
20
20
  import { validateAgentCordis } from './schema.ts'
21
21
 
@@ -126,24 +126,114 @@ function copyTreeSync(sourceDir: string, targetDir: string): void {
126
126
  }
127
127
  }
128
128
 
129
+ /**
130
+ * The preset-row settings the plugin exposes in the web settings surface, as the
131
+ * overrides to write into the synced `agent.cordis.yml`.
132
+ *
133
+ * The settings surface edits the PLUGIN's namespace, while the values that shape
134
+ * a session live in the preset's rows. Writing the chosen values into the synced
135
+ * tree is what connects the two: the bundled source stays the shipped default,
136
+ * and the operator's choice rides on top of it. Every field is optional — an
137
+ * absent value leaves the shipped row exactly as it is.
138
+ */
139
+ export interface PresetOverrides {
140
+ /** The `tool-catalog` row's `presentation` value. */
141
+ presentation?: string
142
+ }
143
+
144
+ /**
145
+ * Replace one indented `key: <value>` line inside the block of `- id: <row>`.
146
+ *
147
+ * Strings render single-quoted and booleans render bare: YAML reads an unquoted
148
+ * `false` as a boolean, while `'false'` would be a truthy string and silently
149
+ * invert the switch.
150
+ */
151
+ function setRowValue(text: string, rowId: string, key: string, value: string | boolean | undefined): string {
152
+ if (value === undefined) return text
153
+ const literal = typeof value === 'boolean' ? String(value) : `'${value}'`
154
+ const rowStart = text.indexOf(`- id: ${rowId}
155
+ `)
156
+ if (rowStart < 0) return text
157
+ const afterRow = rowStart + `- id: ${rowId}
158
+ `.length
159
+ // The row body ends at the first line that is not indented (the next top-level
160
+ // entry or a comment block).
161
+ const rest = text.slice(afterRow)
162
+ const boundary = rest.search(/^\S/m)
163
+ const body = boundary < 0 ? rest : rest.slice(0, boundary)
164
+ const tail = boundary < 0 ? '' : rest.slice(boundary)
165
+ const pattern = new RegExp(`^(\\s*)${key}:\\s*.*$`, 'm')
166
+ const rewritten = pattern.test(body)
167
+ ? body.replace(pattern, `$1${key}: ${literal}`)
168
+ : body
169
+ return text.slice(0, afterRow) + rewritten + tail
170
+ }
171
+
172
+ /**
173
+ * Render `agent.cordis.yml` with the settings overrides applied.
174
+ *
175
+ * Rows are matched by their `- id:` marker, so the transform does not depend on
176
+ * line numbers or on the values the shipped file happens to carry. A row or key
177
+ * the source does not contain is left alone rather than invented: the overlay
178
+ * narrows the shipped configuration, it never adds a mount the preset did not
179
+ * have.
180
+ * @param text - the bundled preset composition.
181
+ * @param overrides - the operator's settings-surface choices.
182
+ * @returns the composition to write into the synced tree.
183
+ */
184
+ export function renderPresetOverrides(text: string, overrides: PresetOverrides): string {
185
+ let out = text
186
+ out = setRowValue(out, 'tool-catalog', 'presentation', overrides.presentation)
187
+ return out
188
+ }
189
+
129
190
  /** Copy `sourceRoot/<id>` into `targetRoot/<id>`, idempotently. */
130
- export function syncOnePreset(sourceDir: string, targetDir: string): 'synced' | 'current' {
191
+ export function syncOnePreset(sourceDir: string, targetDir: string, overrides: PresetOverrides = {}): 'synced' | 'current' {
131
192
  const sourceFiles = filesUnder(sourceDir)
132
193
  const sourceSet = new Set(sourceFiles.map(file => relative(sourceDir, file)))
133
194
 
134
195
  if (existsSync(targetDir) && !statSync(targetDir).isDirectory()) {
135
196
  rmSync(targetDir, { recursive: true, force: true })
136
197
  }
198
+ const applyOverrides = (): void => {
199
+ const agentFile = join(targetDir, 'agent.cordis.yml')
200
+ if (!existsSync(agentFile)) return
201
+ const rendered = renderPresetOverrides(readFileSync(agentFile, 'utf8'), overrides)
202
+ if (rendered !== readFileSync(agentFile, 'utf8')) writeFileSync(agentFile, rendered)
203
+ }
204
+
137
205
  if (!existsSync(targetDir)) {
138
206
  copyTreeSync(sourceDir, targetDir)
139
207
  pruneExtras(targetDir, sourceSet)
208
+ applyOverrides()
140
209
  return 'synced'
141
210
  }
142
211
 
212
+ // The composition is compared against the SOURCE AFTER the overlay, because the
213
+ // target legitimately carries the operator's settings there. Every other file
214
+ // is a plain copy, so it keeps the original size-and-mtime fast path — the
215
+ // overlay is the one thing that can make target bytes differ from source bytes
216
+ // on purpose.
217
+ const agentEntry = join(sourceDir, 'agent.cordis.yml')
218
+ const expectedAgent = existsSync(agentEntry)
219
+ ? Buffer.from(renderPresetOverrides(readFileSync(agentEntry, 'utf8'), overrides))
220
+ : undefined
221
+
143
222
  let dirty = false
144
223
  for (const file of sourceFiles) {
145
224
  const dest = join(targetDir, relative(sourceDir, file))
146
- if (!existsSync(dest) || !sameFile(file, dest)) {
225
+ if (!existsSync(dest)) {
226
+ dirty = true
227
+ break
228
+ }
229
+ if (file === agentEntry) {
230
+ if (expectedAgent === undefined || !expectedAgent.equals(readFileSync(dest))) {
231
+ dirty = true
232
+ break
233
+ }
234
+ continue
235
+ }
236
+ if (!sameFile(file, dest)) {
147
237
  dirty = true
148
238
  break
149
239
  }
@@ -156,13 +246,25 @@ export function syncOnePreset(sourceDir: string, targetDir: string): 'synced' |
156
246
  }
157
247
  }
158
248
  }
159
- if (!dirty) return 'current'
249
+ if (!dirty) {
250
+ // Content matches, but a previous run may have written the tree before the
251
+ // overlay existed (or under different settings). Re-apply so an upgrade and
252
+ // a settings change both converge without a spurious "synced" report.
253
+ const before = readFileSync(join(targetDir, 'agent.cordis.yml'), 'utf8')
254
+ const after = renderPresetOverrides(before, overrides)
255
+ if (after !== before) {
256
+ writeFileSync(join(targetDir, 'agent.cordis.yml'), after)
257
+ return 'synced'
258
+ }
259
+ return 'current'
260
+ }
160
261
 
161
262
  // Drop target-only entries first so file/dir type clashes never reach the
162
263
  // copy, then copy and prune again per the post-copy contract.
163
264
  pruneExtras(targetDir, sourceSet)
164
265
  copyTreeSync(sourceDir, targetDir)
165
266
  pruneExtras(targetDir, sourceSet)
267
+ applyOverrides()
166
268
  return 'synced'
167
269
  }
168
270
 
@@ -180,7 +282,7 @@ export function syncOnePreset(sourceDir: string, targetDir: string): 'synced' |
180
282
  * @param targetRoot - dsh agent-presets discovery root (e.g. <home>/.dsh/.agent-presets).
181
283
  * @param retire - previously bundled preset ids to remove when absent from the source.
182
284
  */
183
- export function syncPresetTrees(sourceRoot: string, targetRoot: string, retire: string[] = []): SyncResult {
285
+ export function syncPresetTrees(sourceRoot: string, targetRoot: string, retire: string[] = [], overrides: PresetOverrides = {}): SyncResult {
184
286
  const result: SyncResult = { synced: [], current: [], failed: [], retired: [] }
185
287
  mkdirSync(targetRoot, { recursive: true })
186
288
  if (existsSync(sourceRoot)) {
@@ -191,7 +293,7 @@ export function syncPresetTrees(sourceRoot: string, targetRoot: string, retire:
191
293
  const targetDir = join(targetRoot, id)
192
294
  let outcome: 'synced' | 'current'
193
295
  try {
194
- outcome = syncOnePreset(source, targetDir)
296
+ outcome = syncOnePreset(source, targetDir, overrides)
195
297
  } catch (error) {
196
298
  result.failed.push({ id, error: error instanceof Error ? error.message : String(error) })
197
299
  continue
@@ -14,11 +14,13 @@
14
14
  * history is never appended to.
15
15
  *
16
16
  * 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.
17
+ * B (current persona), P (candidate persona), T (candidate persona + PTC-only
18
+ * presentation), T (candidate persona + 'both' presentation), N (candidate
19
+ * persona + native presentation throughout), and M
20
+ * (the official bundle's Minimal preset as an external reference). Persona
21
+ * wording and tool presentation vary independently, and a run records the
22
+ * baseline it ran against so an aggregated report can attribute a difference to
23
+ * one factor.
22
24
  *
23
25
  * Usage:
24
26
  * node tools/benchmark-live-run.mjs --variant B [--timeout 300000] [--keep]
@@ -67,39 +69,34 @@ export const CANDIDATE_PERSONA = [
67
69
 
68
70
  /**
69
71
  * 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.
72
+ * the prompt wording, `presentation` the wire presentation (`null` keeps the
73
+ * shipped default), and `official` selects the bundle's Minimal preset
74
+ * untouched.
73
75
  */
74
76
  export const LIVE_VARIANTS = {
75
77
  B: {
76
78
  persona: 'current',
77
- anchors: null,
78
- ptc: true,
79
- note: 'baseline: shipped persona, four-tool anchor, PTC after the boundary',
79
+ presentation: null,
80
+ note: "baseline: shipped persona, shipped 'both' presentation",
80
81
  },
81
82
  P: {
82
83
  persona: 'candidate',
83
- anchors: null,
84
- ptc: true,
85
- note: 'candidate persona, four-tool anchor, PTC after the boundary',
84
+ presentation: null,
85
+ note: "candidate persona, shipped 'both' presentation",
86
86
  },
87
87
  T: {
88
88
  persona: 'candidate',
89
- anchors: [],
90
- ptc: true,
91
- note: 'candidate persona, PTC from the first turn',
89
+ presentation: 'ptc',
90
+ note: "candidate persona, 'ptc' presentation (collapsed wire to run_code)",
92
91
  },
93
92
  N: {
94
93
  persona: 'candidate',
95
- anchors: [],
96
- ptc: false,
97
- note: 'candidate persona, full native roster throughout',
94
+ presentation: 'native',
95
+ note: 'candidate persona, native roster throughout',
98
96
  },
99
97
  M: {
100
98
  persona: 'minimal',
101
- anchors: null,
102
- ptc: null,
99
+ presentation: null,
103
100
  official: true,
104
101
  note: 'external reference: the official Minimal preset, official configuration',
105
102
  },
@@ -201,18 +198,12 @@ export function materializePreset(root, variantId, variant) {
201
198
  cpSync(variant.official === true ? officialMinimalPresetDir() : PRESET_SOURCE, target, { recursive: true })
202
199
  if (variant.official === true) return target
203
200
  const composition = join(target, 'agent.cordis.yml')
204
- if (variant.anchors !== null && variant.anchors !== undefined) {
201
+ if (variant.presentation !== null && variant.presentation !== undefined) {
205
202
  const text = readFileSync(composition, 'utf8')
206
- // Anchor on the config line: the composition also NAMES `anchorTools: [bash]`
203
+ // Anchor on the config line: the composition also NAMES the presentation key
207
204
  // 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')
205
+ const replaced = text.replace(/^(\s*)presentation: '[^']*'/m, `$1presentation: '${variant.presentation}'`)
206
+ if (replaced === text) throw new Error('benchmark: the preset composition carries no presentation line to vary')
216
207
  writeFileSync(composition, replaced)
217
208
  }
218
209
  if (variant.persona === 'candidate') {
@@ -768,4 +759,4 @@ if (isMain) {
768
759
  console.log(` tokens ${report.usage.totalTokens} (input ${report.usage.uncachedInputTokens}, output ${report.usage.outputTokens}, cacheRead ${report.usage.cacheReadTokens})`)
769
760
  console.log(` report ${outFile}`)
770
761
  }
771
- }
762
+ }
@@ -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
- }