dsh-bash-terminal-ts 0.8.8 → 0.9.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 (44) hide show
  1. package/CHANGELOG.md +201 -190
  2. package/README.en.md +2 -1
  3. package/README.md +3 -2
  4. package/agent-presets/README.md +171 -170
  5. package/agent-presets/install-presets.mjs +180 -179
  6. package/agent-presets/standard-win-niu/agent.cordis.yml +271 -0
  7. package/agent-presets/standard-win-niu/preset.yml +2 -0
  8. package/cordis.patch.yml +84 -83
  9. package/dist/client.core.js +10 -1
  10. package/dist/client.js +10 -1
  11. package/docs/dsh-plugin-development.md +169 -0
  12. package/docs/niu-backend.md +197 -0
  13. package/dsh.plugin.json +3 -3
  14. package/lib/client.js +10 -1
  15. package/lib/dsh-types.d.ts +14 -2
  16. package/lib/index.d.ts +15 -2
  17. package/lib/index.js +43 -5
  18. package/lib/locales.js +9 -0
  19. package/lib/shell-id.d.ts +1 -1
  20. package/lib/shells.d.ts +1 -0
  21. package/lib/shells.js +8 -2
  22. package/lib/terminal.js +4 -0
  23. package/lib/webterminals/host.js +2 -2
  24. package/lib/webterminals/mount.js +1 -0
  25. package/locale/de.json +6 -6
  26. package/locale/en.json +6 -6
  27. package/locale/es.json +6 -6
  28. package/locale/fr.json +6 -6
  29. package/locale/it.json +6 -6
  30. package/locale/ja.json +6 -6
  31. package/locale/ko.json +6 -6
  32. package/locale/ru.json +6 -6
  33. package/locale/zh.json +6 -6
  34. package/package.json +151 -149
  35. package/scripts/check-artifacts.mjs +96 -96
  36. package/src/client.tsx +685 -685
  37. package/src/dsh-types.ts +332 -320
  38. package/src/index.ts +1316 -1275
  39. package/src/locales.ts +461 -452
  40. package/src/shell-id.ts +11 -11
  41. package/src/shells.ts +279 -272
  42. package/src/terminal.ts +616 -612
  43. package/src/webterminals/host.ts +361 -361
  44. package/src/webterminals/mount.ts +237 -236
package/src/index.ts CHANGED
@@ -1,1275 +1,1316 @@
1
- // dsh-bash-terminal-ts - one shell tool, four Windows terminals.
2
- //
3
- // Registers a model-facing shell tool. The terminal backend (powershell /
4
- // gitbash / msys2 / wsl) is chosen by the USER in the Web UI settings (default
5
- // terminal); the model cannot pick it — the tool always obeys the user's
6
- // choice:
7
- // - powershell: pwsh -NoLogo -NoProfile -NonInteractive -Command <cmd>
8
- // - gitbash: Git for Windows bash -lc <cmd> (POSIX; /d/... paths)
9
- // - msys2: MSYS2 bash -lc <cmd> (POSIX; /c/... paths, full GCC/mingw64 toolchain)
10
- // - wsl: wsl [-d <distro>] -e bash -lc <cmd> (Linux; /mnt/d/... paths)
11
- //
12
- // The tool spawns through the shared ctx.subprocess seam (process-tree
13
- // termination, SIGTERM->grace->SIGKILL, spill files) and registers background
14
- // handles with the generic ctx.jobs registry, mirroring the shipped
15
- // dsh-tool-bash / dsh-tool-pwsh story call-for-call. It deliberately
16
- // does NOT consume the ctx.shell capability seam: the platform's own
17
- // sandboxed PowerShell executor keeps serving the pwsh tool. This tool is
18
- // an additional, user-selected terminal that still honors the DSH sandbox:
19
- // confined modes wrap PowerShell's spawn argv through ctx.sandbox
20
- // (fail-closed), while danger-full-access, Git Bash, MSYS2, and WSL run
21
- // unconfined. Git Bash and MSYS2 are unconfined because the DSH Windows ACL
22
- // restricted-token runner cannot host Cygwin/MSYS2: bash aborts with
23
- // "CreateFileMapping ... Win32 error 5" during startup.
24
-
25
- import { lstatSync } from "node:fs";
26
- import { isAbsolute, join, resolve } from "node:path";
27
- import { mountBrowserTerminals } from "./webterminals/mount.js";
28
- import {
29
- ESCALATION_TARGETS,
30
- TOOL_ABORTED,
31
- approveEscalation,
32
- defineTool,
33
- escalationHintMarker,
34
- clampTimeout,
35
- deadline,
36
- parseExitStatus,
37
- timeoutOf,
38
- sandboxDenialMarker,
39
- validateEscalationArgs,
40
- z,
41
- HarnessError
42
- } from "./dsh.js";
43
- import type {
44
- BashTerminalContext,
45
- ExecAgent,
46
- JobsRegistry,
47
- JsonSchemaNode,
48
- ResolvedPaths,
49
- SandboxFacts,
50
- SandboxPolicy,
51
- ShellId,
52
- ToolRunContext
53
- } from "./dsh-types.js";
54
- import { createTerminalRegistry, terminalTool } from "./terminal.js";
55
- import { resolvePayloadBash } from "./payload.js";
56
-
57
- /** Stable Cordis plugin name. */
58
- export const name = "bash-terminal";
59
- /** Composition entry id (the `tool-bash-terminal` row the bundle patch declares). */
60
- const ENTRY_ID = "tool-bash-terminal";
61
- /** Services required before the tool can register. */
62
- export const inject = ["tools", "systemPrompt", "shellEnv", "subprocess", "settings", "sandbox", "sandboxPolicy"];
63
-
64
- /** The terminal backends this tool exposes, in catalog order. */
65
- export const SHELLS = ["powershell", "gitbash", "msys2", "wsl", "payload"] as const;
66
- /** The backend used when the caller does not name one. */
67
- export const DEFAULT_SHELL: ShellId = "powershell";
68
- /** Default per-command timeout (ms). */
69
- const DEFAULT_TIMEOUT_MS = 120000;
70
- /** Upper bound a caller's timeoutMs is capped to. */
71
- const MAX_TIMEOUT_MS = 600000;
72
- /** SIGTERM->SIGKILL grace (ms), matching dsh-bash-local's default. */
73
- const DEFAULT_GRACE_MS = 3000;
74
- /** Per-stream in-memory cap before spilling (bytes). */
75
- const DEFAULT_MAX_OUTPUT_BYTES = 64 * 1024;
76
- /** Per-stream spill file cap (bytes). */
77
- const DEFAULT_MAX_SPILL_BYTES = 64 * 1024 * 1024;
78
- /** Timeout code stamped on the deadline's TimeoutReason. */
79
- const TIMEOUT_CODE = "SHELL_TIMEOUT";
80
-
81
- /** Model-friendly environment overrides (same set dsh-bash-local hardcodes). */
82
- const ENV_OVERRIDES: Record<string, string> = {
83
- NO_COLOR: "1",
84
- TERM: "dumb",
85
- PAGER: "cat",
86
- GIT_PAGER: "cat"
87
- };
88
-
89
- /** Live reference the 0.1.7 loader hands `apply` for `.volatile()` config fields. */
90
- interface VolatileRef<T> {
91
- get(): T;
92
- }
93
-
94
- /** Static shape of the runtime configuration schema. */
95
- export interface ConfigValues {
96
- defaultShell: string;
97
- timeoutMs: number;
98
- maxTimeoutMs: number;
99
- pwshPath: string;
100
- gitBashPath: string;
101
- msys2Path: string;
102
- wslPath: string;
103
- /**
104
- * The bottom terminal's MASTER switch. Off outranks every child choice: the
105
- * settings row hides the per-shell switches (a switch for something that cannot
106
- * run is a lie) and the routes refuse allocations.
107
- */
108
- bottomTerminal: boolean;
109
- /**
110
- * Opt in to publishing the client-side `webTerminals` service, which is what powers
111
- * dsh-better-sidebar's OFFICIAL bottom "Terminal" row on a deployment that has no
112
- * terminal controller. Default false: the name is also provided by the host's own
113
- * controller client, cordis refuses the second provider, and the controller's provide
114
- * is unguarded - so claiming it by default breaks the first-party terminal and the
115
- * whole web boot on DSH 0.2.0+ (measured). Turn it on only where the official row is
116
- * dead because no controller exists.
117
- */
118
- shimOfficialTerminal: boolean;
119
- /**
120
- * Browser-terminal activation (R1/R2). The default is `true` for all three:
121
- * a switch means "allowed", and availability is ANDed with it by the catalog -
122
- * so "detected means on" needs no probe at schema level, while an explicit
123
- * `false` is a real opt-out even on a machine that has the shell.
124
- */
125
- shellGitBash: boolean;
126
- shellMsys2: boolean;
127
- shellWsl: boolean;
128
- /**
129
- * Activation switch for the payload row in the bottom-terminal UI. Separate
130
- * from `enablePosixPayload` (the operator gate that RUNS the digest check at
131
- * startup): this one only decides whether a resolved payload may appear in
132
- * pickers. Default false - the payload is opt-in twice, provisioning and
133
- * activation.
134
- */
135
- shellPayload: boolean;
136
- /** WSL distribution for the browser terminal; '' means the WSL default. */
137
- wslDistro: string;
138
- /**
139
- * Pinned backup POSIX runtime payload (see src/payload.ts - the artifact is
140
- * a Git-for-Windows tree; OUR name avoids the bash/msys tokens by policy).
141
- * Default off; enabling it lets a digest-verified payload fill the Git Bash
142
- * slot as a LAST-RESORT source when the machine has no system Git Bash. A
143
- * detected WSL distro outranks the payload entirely (a real WSL bash is the
144
- * better POSIX shell), and an unverifiable payload fails closed - it is
145
- * never run, never silently replaced. Resolved at startup, so toggling
146
- * takes effect on the next restart.
147
- */
148
- enablePosixPayload: boolean;
149
- /** Explicit payload root or bin/bash.exe path; '' = auto-discovery only. */
150
- payloadPosixPath: string;
151
- }
152
-
153
- /** Runtime configuration schema. */
154
- export const Config = z.object({
155
- defaultShell: z.string().default(DEFAULT_SHELL).volatile(),
156
- timeoutMs: z.number().default(DEFAULT_TIMEOUT_MS),
157
- maxTimeoutMs: z.number().default(MAX_TIMEOUT_MS),
158
- pwshPath: z.string().default(""),
159
- gitBashPath: z.string().default(""),
160
- msys2Path: z.string().default(""),
161
- wslPath: z.string().default(""),
162
- // `.volatile()` on the new fields: the browser terminal reads them on every
163
- // allocation, and a flip in the settings page has to take effect without a
164
- // restart (0.1.7+ hands apply a live ref; older lines re-read the same value).
165
- bottomTerminal: z.boolean().default(true).volatile(),
166
- shimOfficialTerminal: z.boolean().default(false).volatile(),
167
- shellGitBash: z.boolean().default(true).volatile(),
168
- shellMsys2: z.boolean().default(true).volatile(),
169
- shellWsl: z.boolean().default(true).volatile(),
170
- shellPayload: z.boolean().default(false).volatile(),
171
- wslDistro: z.string().default("").volatile(),
172
- // Payload gate state is read once per process (paths resolve at startup), so
173
- // these are deliberately NOT volatile: a flip needs the restart it implies.
174
- enablePosixPayload: z.boolean().default(false),
175
- payloadPosixPath: z.string().default("")
176
- });
177
-
178
- // ---- executable resolution ------------------------------------------------
179
-
180
- function candidateExists(candidate: string): boolean {
181
- try {
182
- const stat = lstatSync(candidate);
183
- return stat.isFile() || stat.isSymbolicLink();
184
- } catch {
185
- return false;
186
- }
187
- }
188
-
189
- function resolveFromCandidates(candidates: readonly string[]): string | undefined {
190
- for (const candidate of candidates) {
191
- if (candidateExists(candidate)) return candidate;
192
- }
193
- return undefined;
194
- }
195
-
196
- /** Well-known PowerShell install locations plus PATH entries, newest first. */
197
- export function candidatePwshPaths(env: NodeJS.ProcessEnv = process.env): string[] {
198
- const programFiles = env.ProgramFiles ?? "C:\\Program Files";
199
- const systemRoot = env.SystemRoot ?? "C:\\Windows";
200
- const candidates = [join(programFiles, "PowerShell", "7", "pwsh.exe")];
201
- for (const entry of (env.PATH ?? "").split(";")) {
202
- const trimmed = entry.trim().replace(/^"|"$/g, "");
203
- if (trimmed.length === 0) continue;
204
- candidates.push(join(trimmed, "pwsh.exe"));
205
- }
206
- candidates.push(join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"));
207
- return candidates;
208
- }
209
-
210
- /**
211
- * Git for Windows locations, then PATH bash.exe entries EXCLUDING the
212
- * System32 launcher (c:\\windows\\system32\\bash.exe is the WSL
213
- * forwarder, not a Git Bash shell).
214
- */
215
- export function candidateGitBashPaths(env: NodeJS.ProcessEnv = process.env): string[] {
216
- const programFiles = env.ProgramFiles ?? "C:\\Program Files";
217
- const systemRoot = (env.SystemRoot ?? "C:\\Windows").toLowerCase();
218
- const localAppData = env.LOCALAPPDATA ?? "";
219
- const candidates = [
220
- join(programFiles, "Git", "bin", "bash.exe"),
221
- join(programFiles, "Git", "usr", "bin", "bash.exe")
222
- ];
223
- if (localAppData.length > 0) candidates.push(join(localAppData, "Programs", "Git", "bin", "bash.exe"));
224
- for (const entry of (env.PATH ?? "").split(";")) {
225
- const trimmed = entry.trim().replace(/^"|"$/g, "");
226
- if (trimmed.length === 0) continue;
227
- if (trimmed.toLowerCase().includes(systemRoot)) continue;
228
- candidates.push(join(trimmed, "bash.exe"));
229
- }
230
- return candidates;
231
- }
232
-
233
- /**
234
- * MSYS2 locations, in preference order: the real `bash.exe` under usr\bin
235
- * first, then bin\bash.exe, and `msys2.exe` dead last.
236
- *
237
- * msys2.exe is NOT a usable backend for piped execution: it is the console-
238
- * allocating Cygwin launcher, so a spawn with piped stdio returns exit 0 with
239
- * zero bytes on both stdout and stderr (measured on this machine against
240
- * MSYS2 with bash 5.3.15). Keeping it in the list only as a last-resort
241
- * fallback preserves the path the config docs reference, but a working
242
- * bash.exe always wins.
243
- *
244
- * MSYS2 uses the same Cygwin/MSYS2 runtime as Git Bash, so it cannot run
245
- * under the DSH Windows ACL restricted-token sandbox.
246
- */
247
- export function candidateMsys2Paths(env: NodeJS.ProcessEnv = process.env): string[] {
248
- const candidates = [
249
- "C:\\msys64\\usr\\bin\\bash.exe",
250
- "C:\\msys64\\bin\\bash.exe"
251
- ];
252
- for (const entry of (env.PATH ?? "").split(";")) {
253
- const trimmed = entry.trim().replace(/^"|"$/g, "");
254
- if (trimmed.length === 0) continue;
255
- const lower = trimmed.toLowerCase();
256
- if (lower.includes("msys64") || lower.includes("mingw64")) {
257
- candidates.push(join(trimmed, "bash.exe"));
258
- }
259
- }
260
- candidates.push("C:\\msys64\\msys2.exe"); // last resort: see the note above
261
- return candidates;
262
- }
263
-
264
- export function defaultWslPath(env: NodeJS.ProcessEnv = process.env): string {
265
- const systemRoot = env.SystemRoot ?? "C:\\Windows";
266
- return join(systemRoot, "System32", "wsl.exe");
267
- }
268
-
269
- /** Executable paths, possibly undefined when a backend is not installed. */
270
- export type { ResolvedPaths };
271
-
272
- type PathConfig = Partial<Pick<ConfigValues, "pwshPath" | "gitBashPath" | "msys2Path" | "wslPath">>;
273
-
274
- export function resolveAllPaths(
275
- config: PathConfig = {},
276
- env: NodeJS.ProcessEnv = process.env,
277
- payloadBash?: string
278
- ): ResolvedPaths {
279
- const pwsh = config.pwshPath && config.pwshPath.trim().length > 0
280
- ? config.pwshPath
281
- : resolveFromCandidates(candidatePwshPaths(env));
282
- const gitbash = config.gitBashPath && config.gitBashPath.trim().length > 0
283
- ? config.gitBashPath
284
- : resolveFromCandidates(candidateGitBashPaths(env));
285
- const msys2 = config.msys2Path && config.msys2Path.trim().length > 0
286
- ? config.msys2Path
287
- : resolveFromCandidates(candidateMsys2Paths(env));
288
- const wsl = config.wslPath && config.wslPath.trim().length > 0
289
- ? config.wslPath
290
- : defaultWslPath(env);
291
- // The payload is its OWN backend (first-class catalog row) - it never
292
- // silently substitutes for the gitbash slot, so a row labelled "Git Bash"
293
- // always names a shell the machine actually has.
294
- return { pwsh, gitbash, msys2, wsl, ...(payloadBash !== undefined ? { payload: payloadBash } : {}) };
295
- }
296
-
297
- // ---- argv / env construction ------------------------------------------------
298
-
299
- export function buildArgv(
300
- shell: string,
301
- command: string,
302
- paths: ResolvedPaths,
303
- distro?: string
304
- ): Array<string | undefined> {
305
- switch (shell) {
306
- case "powershell":
307
- return [paths.pwsh, "-NoLogo", "-NoProfile", "-NonInteractive", "-Command", command];
308
- case "gitbash":
309
- return [paths.gitbash, "-lc", command];
310
- case "msys2":
311
- // -lc, not -c: a login shell sources /etc/profile, which is what puts
312
- // /usr/bin and /mingw64/bin on PATH. With a bare -c, `tr`, `sed`, `gcc`
313
- // and friends are all "command not found".
314
- return [paths.msys2, "-lc", command];
315
- case "payload":
316
- // Same login-shell rule as msys2/gitbash: the payload is a
317
- // Git-for-Windows tree and `-lc` is what gives it a usable PATH.
318
- return [paths.payload, "-lc", command];
319
- case "wsl": {
320
- const distroArg = distro !== undefined && distro.trim().length > 0 ? ["-d", distro.trim()] : [];
321
- return [paths.wsl, ...distroArg, "-e", "bash", "-lc", command];
322
- }
323
- default:
324
- throw new Error(`invalid shell: ${JSON.stringify(shell)} (expected one of ${SHELLS.join(", ")})`);
325
- }
326
- }
327
-
328
- /**
329
- * Merge the DSH_* environment over the process environment. For WSL, only
330
- * variables explicitly listed in WSLENV cross the boundary, so every DSH_*
331
- * key is appended there — and the list is *layered onto* whatever WSLENV the
332
- * host already had (Windows Terminal exports e.g. `WT_SESSION:WT_PROFILE_ID:`),
333
- * never rebuilt from scratch: WSLENV is an allow-list, so dropping the
334
- * inherited entries would silently stop them crossing into WSL.
335
- *
336
- * @param inheritedWslenv - the ambient WSLENV to layer onto. Callers that
337
- * replace the child environment wholesale (the PTY path) must pass
338
- * `process.env.WSLENV` explicitly, because the ambient value is not visible
339
- * through `dshEnv`.
340
- */
341
- export function buildEnv(
342
- shell: string,
343
- dshEnv?: Record<string, string>,
344
- inheritedWslenv: string | undefined = process.env.WSLENV
345
- ): Record<string, string | undefined> {
346
- const env: Record<string, string | undefined> = { ...ENV_OVERRIDES, ...dshEnv };
347
- if (shell === "msys2") {
348
- // Picks the MINGW64 environment, so /mingw64/bin (gcc, make, ...) joins
349
- // PATH via /etc/profile. Without it MSYS2 defaults to the bare MSYS
350
- // environment. An explicit caller-supplied value wins.
351
- if (env.MSYSTEM === undefined) env.MSYSTEM = "MINGW64";
352
- }
353
- if (shell === "wsl") {
354
- const keys = Object.keys(dshEnv ?? {});
355
- if (keys.length > 0) {
356
- // An explicit WSLENV in dshEnv wins over the inherited one; otherwise the
357
- // inherited value is the base. Either way the base is SPLIT into entries
358
- // (the host value ends with a trailing ":", so string concatenation would
359
- // produce a malformed empty entry) and the WSLENV key itself is excluded
360
- // (it is a key of dshEnv too, and appending it would add a bogus entry).
361
- const declared = Object.prototype.hasOwnProperty.call(dshEnv ?? {}, "WSLENV");
362
- const base = declared
363
- ? env.WSLENV
364
- : (typeof inheritedWslenv === "string" && inheritedWslenv.length > 0 ? inheritedWslenv : env.WSLENV);
365
- const parts = typeof base === "string" ? base.split(":") : [];
366
- env.WSLENV = [...parts, ...keys.filter((k) => k !== "WSLENV").flatMap((k) => k.split(":"))]
367
- .map((p) => p.trim())
368
- .filter((p) => p.length > 0)
369
- .join(":");
370
- }
371
- }
372
- return env;
373
- }
374
-
375
- // ---- spawn plumbing over ctx.subprocess ---------------------------------------
376
-
377
- export interface SpawnResolution {
378
- command: string;
379
- workdir: string;
380
- timeoutMs: number;
381
- stdoutMaxBytes: number;
382
- stdin?: string;
383
- }
384
-
385
- function spawnSpec(resolved: SpawnResolution, argv: string[], env: Record<string, string | undefined>, signal: AbortSignal) {
386
- const collect = (maxBytes: number) => ({ maxBytes, spill: { maxBytes: DEFAULT_MAX_SPILL_BYTES } });
387
- return {
388
- argv,
389
- cwd: resolved.workdir,
390
- stdio: {
391
- stdin: resolved.stdin !== undefined ? { data: resolved.stdin } : "ignore",
392
- stdout: collect(resolved.stdoutMaxBytes),
393
- stderr: collect(DEFAULT_MAX_OUTPUT_BYTES)
394
- },
395
- graceMs: DEFAULT_GRACE_MS,
396
- signal,
397
- env
398
- } as const;
399
- }
400
-
401
- function collectedOutput(handle: { collected: { stdout: unknown; stderr: unknown } }) {
402
- const { stdout, stderr } = handle.collected;
403
- if (!isCollectedStream(stdout) || !isCollectedStream(stderr)) {
404
- throw new Error("dsh-bash-terminal-ts: subprocess implementation dropped a requested collect stream");
405
- }
406
- return { stdout, stderr };
407
- }
408
-
409
- function isCollectedStream(value: unknown): value is CollectedLike {
410
- return typeof value === "object" && value !== null && typeof (value as CollectedLike).readFrom === "function";
411
- }
412
-
413
- interface CollectedLike {
414
- readFrom(offset: number): { text: string; lossy: boolean; nextOffset: number; spillPath?: string };
415
- }
416
-
417
- interface StreamOutput {
418
- text: string;
419
- truncated: boolean;
420
- spillPath?: string;
421
- }
422
-
423
- function finalOutput(reader: CollectedLike): StreamOutput {
424
- const read = reader.readFrom(0);
425
- return {
426
- text: read.text,
427
- truncated: read.lossy,
428
- ...(read.spillPath !== undefined ? { spillPath: read.spillPath } : {})
429
- };
430
- }
431
-
432
- export interface ForegroundOutcome {
433
- exitCode: number | null;
434
- signal: string | null;
435
- timedOut: boolean;
436
- aborted: boolean;
437
- timeoutMs: number;
438
- stdout: StreamOutput;
439
- stderr: StreamOutput;
440
- }
441
-
442
- async function runForeground(
443
- ctx: BashTerminalContext,
444
- argv: string[],
445
- resolved: SpawnResolution,
446
- env: Record<string, string | undefined>,
447
- signal: AbortSignal,
448
- timeoutMs: number
449
- ): Promise<ForegroundOutcome> {
450
- const subprocess = requireSubprocess(ctx);
451
- const d = deadline(signal, timeoutMs, TIMEOUT_CODE);
452
- try {
453
- const handle = subprocess.spawn(spawnSpec(resolved, argv, env, d.signal));
454
- const outcome = await handle.done;
455
- const collected = collectedOutput(handle);
456
- const timedOut = timeoutOf(d.signal, TIMEOUT_CODE) !== undefined;
457
- const aborted = d.signal.aborted && !timedOut;
458
- return {
459
- exitCode: outcome.exitCode,
460
- signal: outcome.signal,
461
- timedOut,
462
- aborted,
463
- timeoutMs,
464
- stdout: finalOutput(collected.stdout),
465
- stderr: finalOutput(collected.stderr)
466
- };
467
- } finally {
468
- d[Symbol.dispose]();
469
- }
470
- }
471
-
472
- function requireSubprocess(ctx: BashTerminalContext) {
473
- const subprocess = ctx.subprocess;
474
- if (subprocess === null) {
475
- throw new Error("dsh-bash-terminal-ts: ctx.subprocess seam unavailable (missing inject service)");
476
- }
477
- return subprocess;
478
- }
479
-
480
- export interface ProcessRead {
481
- delta: string;
482
- lossy: boolean;
483
- stdoutSpillPath?: string;
484
- stderrSpillPath?: string;
485
- }
486
-
487
- interface BackgroundProc {
488
- status: "running" | "killed" | "completed";
489
- exitCode: number | null;
490
- signal: string | null;
491
- done: Promise<void>;
492
- readOutput(): ProcessRead;
493
- kill(): boolean;
494
- }
495
-
496
- function startBackground(
497
- ctx: BashTerminalContext,
498
- argv: string[],
499
- resolved: SpawnResolution,
500
- env: Record<string, string | undefined>,
501
- signal: AbortSignal
502
- ): BackgroundProc {
503
- const subprocess = requireSubprocess(ctx);
504
- const running = subprocess.spawn(spawnSpec(resolved, argv, env, signal));
505
- const collected = collectedOutput(running);
506
- let stdoutOffset = 0;
507
- let stderrOffset = 0;
508
- let spawnFailureNote: string | undefined;
509
- const consumeSpawnFailure = (): string => {
510
- const note = spawnFailureNote ?? "";
511
- spawnFailureNote = undefined;
512
- return note;
513
- };
514
- const proc: BackgroundProc = {
515
- status: "running",
516
- exitCode: null,
517
- signal: null,
518
- done: running.done.then((outcome) => {
519
- if (proc.status === "running") {
520
- proc.status = signal?.aborted === true || outcome.signal !== null ? "killed" : "completed";
521
- }
522
- proc.exitCode = outcome.exitCode;
523
- proc.signal = outcome.signal;
524
- }, (error: unknown) => {
525
- proc.status = "killed";
526
- spawnFailureNote = `spawn failed: ${String(error)}`;
527
- }),
528
- readOutput: () => {
529
- const out = collected.stdout.readFrom(stdoutOffset);
530
- const err = collected.stderr.readFrom(stderrOffset);
531
- stdoutOffset = out.nextOffset;
532
- stderrOffset = err.nextOffset;
533
- const errText = err.text.length > 0 ? err.text : consumeSpawnFailure();
534
- const separator = out.text.length > 0 && !out.text.endsWith("\n") ? "\n" : "";
535
- return {
536
- delta: out.text + (errText.length > 0 ? `${separator}[stderr]\n${errText}` : ""),
537
- lossy: out.lossy || err.lossy,
538
- ...(out.spillPath !== undefined ? { stdoutSpillPath: out.spillPath } : {}),
539
- ...(err.spillPath !== undefined ? { stderrSpillPath: err.spillPath } : {})
540
- };
541
- },
542
- kill: () => {
543
- if (proc.status !== "running") return false;
544
- proc.status = "killed";
545
- running.terminate();
546
- return true;
547
- }
548
- };
549
- return proc;
550
- }
551
-
552
- function processOutcome(proc: BackgroundProc): { status: string; detail: string } {
553
- if (proc.status === "killed") {
554
- return { status: "killed", detail: proc.signal !== null ? `signal: ${proc.signal}` : "killed before exit" };
555
- }
556
- return { status: "completed", detail: `exit code: ${proc.exitCode ?? 0}` };
557
- }
558
-
559
- // ---- model-facing rendering ---------------------------------------------------
560
-
561
- function streamText(output: StreamOutput): string {
562
- if (!output.truncated) return output.text;
563
- return `${output.text}\n[output truncated; full output: ${output.spillPath ?? "(unavailable)"}]`;
564
- }
565
-
566
- export interface RenderedResult {
567
- stdout: StreamOutput;
568
- stderr: StreamOutput;
569
- exitCode: number | null;
570
- signal: string | null;
571
- timedOut: boolean;
572
- timeoutMs: number;
573
- }
574
-
575
- export function renderResult(result: RenderedResult): string {
576
- const out = streamText(result.stdout);
577
- const err = streamText(result.stderr);
578
- let body = out;
579
- if (err.length > 0) {
580
- if (body.length > 0 && !body.endsWith("\n")) body += "\n";
581
- body += `[stderr]\n${err}`;
582
- }
583
- if (body.length === 0) body = "(no output)";
584
- const markers: string[] = [];
585
- if (result.timedOut) markers.push(`[timed out after ${result.timeoutMs}ms]`);
586
- if (result.signal !== null) markers.push(`[killed by signal: ${result.signal}]`);
587
- else if (result.exitCode !== 0) markers.push(`[exit code: ${result.exitCode}]`);
588
- if (markers.length === 0) return body;
589
- if (!body.endsWith("\n")) body += "\n";
590
- return body + markers.join("\n");
591
- }
592
-
593
- function renderProcessRead(read: ProcessRead): string {
594
- const notices: string[] = [];
595
- if (read.lossy) {
596
- const paths = [read.stdoutSpillPath, read.stderrSpillPath].filter((p) => p !== undefined);
597
- notices.push(`[some output was dropped from memory; full output: ${paths.length > 0 ? paths.join(", ") : "(unavailable)"}]`);
598
- }
599
- if (notices.length === 0) return read.delta;
600
- return `${read.delta}${read.delta.length > 0 && !read.delta.endsWith("\n") ? "\n" : ""}${notices.join("\n")}`;
601
- }
602
-
603
- // ---- tool description / validation --------------------------------------------
604
-
605
- /** Model-facing lead sentence for each backend. The user's default terminal is
606
- * stated up front so the model never has to guess which syntax applies. */
607
- export const SHELL_DESCRIPTIONS: Record<ShellId, string> = {
608
- powershell: "Execute a PowerShell command (pwsh -NoLogo -NoProfile -NonInteractive -Command <command>) and return its stdout/stderr. PowerShell syntax; native Windows paths (C:\\...); environment variables via $env:NAME.",
609
- gitbash: "Execute a bash command (Git for Windows bash -lc <command>) and return its stdout/stderr. POSIX syntax; paths like /d/WorkSpace; PATH includes /usr/bin and /mingw64/bin so git, npm, ssh etc. work; environment variables via $NAME.",
610
- msys2: "Execute a bash command (MSYS2 bash -lc <command>) and return its stdout/stderr. POSIX syntax; paths like /c/...; PATH includes /usr/bin and /mingw64/bin so git, npm, gcc, make etc. work; environment variables via $NAME. MSYS2 provides a full GCC/mingw64 toolchain.",
611
- wsl: "Execute a Linux bash command (wsl [-d <distro>] -e bash -lc <command>) and return its stdout/stderr. Linux syntax; Windows files under /mnt/d/...; environment variables via $NAME.",
612
- payload: "Execute a bash command in the plugin's pinned POSIX runtime payload (a digest-verified Git-for-Windows bash -lc <command>) and return its stdout/stderr. POSIX syntax; paths like /c/...; PATH includes /usr/bin so git, npm, ssh etc. work; environment variables via $NAME. Use it only when the user has deliberately enabled the payload backend."
613
- };
614
-
615
- /**
616
- * Render the model-facing tool description for one backend. The backend is
617
- * whatever the user chose in Settings -> General -> Default terminal; the
618
- * description names it explicitly so the model writes the right syntax.
619
- * @param backgroundEnabled - advertise `run_in_background` controls.
620
- * @param shell - active backend; unknown values fall back to the default.
621
- */
622
- export function toolDescription(backgroundEnabled: boolean, shell: string = DEFAULT_SHELL): string {
623
- const active: ShellId = (SHELLS as readonly string[]).includes(shell) ? (shell as ShellId) : DEFAULT_SHELL;
624
- const lead = SHELL_DESCRIPTIONS[active];
625
- const base = [
626
- `The user's chosen default terminal (Settings -> General -> Default terminal) is ${active}; commands run there.`,
627
- lead,
628
- "Each call spawns a fresh shell: no state (cwd, variables, aliases) persists between calls - pass workdir instead of using cd. Non-zero exits are reported as [exit code: N] markers; investigate failures before moving on. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Commands run under the DSH sandbox: confined modes (read-only / workspace-write) are enforced through ctx.sandbox and deny fail-closed for PowerShell; danger-full-access, Git Bash, MSYS2, the pinned POSIX payload, and WSL run unconfined."
629
- ].join(" ");
630
- if (!backgroundEnabled) return base;
631
- return base + " Set run_in_background: true for long-running commands: the call returns a job id immediately; read its output with job_output and stop it with job_kill. No timeout applies to background runs.";
632
- }
633
-
634
- /** The shell tool's arguments after runtime validation. */
635
- export type ValidatedShellArgs = {
636
- command: string;
637
- description: string;
638
- timeoutMs?: number;
639
- distro?: string;
640
- sandbox_permissions?: string;
641
- justification?: string;
642
- workdir?: string;
643
- run_in_background?: boolean;
644
- stdin?: string;
645
- };
646
-
647
- export function validateArgs(args: Record<string, unknown>): ValidatedShellArgs {
648
- if (typeof args.command !== "string" || args.command.trim().length === 0) {
649
- throw new Error("invalid command: expected a non-empty string");
650
- }
651
- if (typeof args.description !== "string" || args.description.trim().length === 0) {
652
- throw new Error("invalid description: expected a non-empty string");
653
- }
654
- if (args.timeoutMs !== undefined && (typeof args.timeoutMs !== "number" || !Number.isFinite(args.timeoutMs) || args.timeoutMs <= 0)) {
655
- throw new Error(`invalid timeoutMs: expected a positive number, got ${JSON.stringify(args.timeoutMs)}`);
656
- }
657
- validateEscalationArgs(args.sandbox_permissions, args.justification);
658
- return args as ValidatedShellArgs;
659
- }
660
-
661
- /**
662
- * Official sandbox seam (mirrors dsh-tool-bash / dsh-pwsh-sandbox): resolve the
663
- * per-call policy from ctx.sandboxPolicy, and — unless the call runs
664
- * danger-full-access — confine the spawn argv through ctx.sandbox. WSL is a
665
- * self-contained Linux VM and is not confined (its isolation IS the sandbox).
666
- * Git Bash and MSYS2 are also not confined: DSH's Windows ACL restricted-token
667
- * runner cannot start Cygwin/MSYS2 (CreateFileMapping Win32 error 5), so
668
- * attempting to wrap them would abort every Git Bash / MSYS2 command. A
669
- * requested confined mode
670
- * with no usable backend throws the fail-closed SandboxUnavailableError,
671
- * exactly like the shipped executors.
672
- */
673
- function confineSpawn(
674
- ctx: BashTerminalContext,
675
- argv: string[],
676
- policy: SandboxPolicy,
677
- shell: string
678
- ): { argv: string[]; sandbox?: SandboxFacts } {
679
- if (policy.mode === "danger-full-access" || shell === "wsl" || shell === "gitbash" || shell === "msys2" || shell === "payload") {
680
- const sandbox = shell === "wsl"
681
- ? { mode: policy.mode, enforcement: "wsl-isolation" }
682
- : shell === "gitbash"
683
- ? { mode: policy.mode, enforcement: "gitbash-unconfined" }
684
- : shell === "msys2"
685
- ? { mode: policy.mode, enforcement: "msys2-unconfined" }
686
- : shell === "payload"
687
- // The payload cannot be confined either (same Cygwin/MSYS runtime
688
- // constraint as Git Bash) - its safety layer is the digest gate.
689
- ? { mode: policy.mode, enforcement: "payload-unconfined" }
690
- : undefined;
691
- return { argv, sandbox };
692
- }
693
- const confined = ctx.sandbox.confine(argv, policy);
694
- return {
695
- argv: confined.argv,
696
- sandbox: { mode: policy.mode, enforcement: confined.enforcement, denialSignatures: confined.denialSignatures }
697
- };
698
- }
699
-
700
- function resolveWorkdir(modelWorkdir: string | undefined, exec: ToolRunContext): string | undefined {
701
- const headerCwd = exec.agent?.session.header.cwd;
702
- if (modelWorkdir === undefined) return headerCwd;
703
- if (headerCwd !== undefined && !isAbsolute(modelWorkdir)) return resolve(headerCwd, modelWorkdir);
704
- return modelWorkdir;
705
- }
706
-
707
- export interface ForegroundResult {
708
- kind: "foreground";
709
- exitCode: number | null;
710
- signal: string | null;
711
- timedOut: boolean;
712
- aborted: boolean;
713
- timeoutMs: number;
714
- stdout: StreamOutput;
715
- stderr: StreamOutput;
716
- sandbox?: SandboxFacts;
717
- }
718
-
719
- export interface BackgroundResult {
720
- kind: "background";
721
- jobId: string;
722
- }
723
-
724
- export type ShellToolResult = ForegroundResult | BackgroundResult;
725
-
726
- function canonicalResult(result: ForegroundOutcome & { sandbox?: SandboxFacts }): ForegroundResult {
727
- const output = (stream: StreamOutput): StreamOutput => ({
728
- text: stream.text,
729
- truncated: stream.truncated,
730
- ...(stream.spillPath !== undefined ? { spillPath: stream.spillPath } : {})
731
- });
732
- return {
733
- kind: "foreground",
734
- exitCode: result.exitCode,
735
- signal: result.signal,
736
- timedOut: result.timedOut,
737
- aborted: result.aborted,
738
- timeoutMs: result.timeoutMs,
739
- stdout: output(result.stdout),
740
- stderr: output(result.stderr),
741
- ...(result.sandbox !== undefined ? { sandbox: result.sandbox } : {})
742
- };
743
- }
744
-
745
- const BACKGROUND_OUTPUT_PROPERTIES: Record<string, JsonSchemaNode> = {
746
- kind: { type: "string", required: true, const: "background" },
747
- jobId: { type: "string", required: true }
748
- };
749
-
750
- /**
751
- * Persist one config path through the host settings service.
752
- *
753
- * Shared by the model tool's `defaultShell` write and the browser terminal's
754
- * activation switches, because the line-dependent part is the whole difficulty:
755
- * ≤0.1.6 loaders do not register a plugin's settings namespace automatically, so
756
- * the first `mutate` fails with "not registered" and the caller has to register it
757
- * (with the written value as the base, so the retry sees it) and retry. On rc.1+
758
- * the namespace is already owned by the loader, that branch never fires, and the
759
- * plain `mutate` is the whole story.
760
- * @param svc - the host `settings` service (untyped: shapes differ per line).
761
- * @param path - the config path inside this plugin's entry (one level today).
762
- * @throws when the line has no `mutate` at all - the caller reports it, and the
763
- * value then applies for this process only.
764
- */
765
- export async function persistConfigValue(svc: unknown, path: readonly string[], value: unknown): Promise<void> {
766
- const service = svc as {
767
- mutate?: (id: string, ops: { op: "set"; path: string[]; value: unknown }[]) => Promise<unknown>;
768
- register?: (id: string, schema: unknown, opts?: unknown) => unknown;
769
- };
770
- if (typeof service?.mutate !== "function") {
771
- throw new Error(
772
- "settings service exposes no mutate on this host line - the value applies for this process only; persist via cordis.patch.yml"
773
- );
774
- }
775
- const ops = [{ op: "set" as const, path: [...path], value }];
776
- try {
777
- await service.mutate(ENTRY_ID, ops);
778
- } catch (e) {
779
- const message = e instanceof Error ? e.message : String(e);
780
- if (!/not registered/i.test(message) || typeof service.register !== "function") {
781
- throw e;
782
- }
783
- console.warn(`[dsh-bash-terminal-ts] legacy line: registering settings namespace ${ENTRY_ID}`);
784
- service.register(ENTRY_ID, Config, { base: { [path.join(".")]: value } });
785
- await service.mutate(ENTRY_ID, ops);
786
- console.warn("[dsh-bash-terminal-ts] legacy settings namespace registered");
787
- }
788
- }
789
-
790
- // ---- plugin -------------------------------------------------------------------
791
-
792
- export function apply(ctx: BashTerminalContext, config: Partial<ConfigValues> = {}): void {
793
- // Pinned backup POSIX runtime payload: opt-in, its OWN backend slot. A
794
- // detected WSL distro is an advisory note only (the official menu lists both
795
- // side by side, so our picker must not be stricter); the digest gate is the
796
- // only hard no: an unverified payload simply does not run.
797
- let payloadBash: string | undefined;
798
- const payloadSuppressed = false;
799
- if (config.enablePosixPayload === true && process.platform === "win32") {
800
- const outcome = resolvePayloadBash({ payloadBashPath: config.payloadPosixPath ?? "" });
801
- if (outcome.engaged) payloadBash = outcome.bashPath;
802
- for (const note of outcome.notes) ctx.logger?.warn?.(`dsh-bash-terminal-ts: ${note}`);
803
- }
804
- const paths = resolveAllPaths(config, process.env, payloadBash);
805
- // 0.1.7: `defaultShell` is a `.volatile()` config field — the loader hands
806
- // `apply` a live ref and the latest value is resolved on every read; there
807
- // is no settings registration call anymore (removed with the 0.1.7 host).
808
- // compat-legacy: ≤0.1.6 的宿主没有配置热重载,bridge 写入走这个覆盖值
809
- // (rc.1+ 上 volatile 与覆盖值同源同写,二者一致)。
810
- let shellOverride: string | undefined;
811
- /** The stored value, verbatim - including one that is no longer selectable. */
812
- const storedShell = (): string => {
813
- if (typeof shellOverride === "string" && (SHELLS as readonly string[]).includes(shellOverride)) {
814
- return shellOverride;
815
- }
816
- const v = config.defaultShell as string | VolatileRef<string> | undefined;
817
- if (typeof v === "string") return v;
818
- const got = typeof v?.get === "function" ? v.get() : undefined;
819
- return typeof got === "string" ? got : DEFAULT_SHELL;
820
- };
821
- let warnedStale = false;
822
- /**
823
- * The shell the TOOL will run. Deliberately the stored value, un-sanitised:
824
- * `buildArgv`/`terminalArgv` throw for anything outside SHELLS, so an
825
- * out-of-enum choice fails closed at call time rather than quietly running the
826
- * command in a different shell than the model was told about.
827
- */
828
- const currentShell = storedShell;
829
- /**
830
- * The activation switches are ONE truth: a switch off hides the backend from
831
- * the dock AND makes it an invalid shell-tool target (powershell is the
832
- * floor and always on). A stored defaultShell pointing at a switched-off
833
- * backend is therefore stale, not executable.
834
- */
835
- const switchOn = (shell: string): boolean => {
836
- const read = <T>(v: T | VolatileRef<T> | undefined, fallback: T): T =>
837
- typeof v === "object" && v !== null && typeof (v as VolatileRef<T>).get === "function"
838
- ? ((v as VolatileRef<T>).get() ?? fallback)
839
- : ((v as T | undefined) ?? fallback);
840
- if (shell === "powershell") return true;
841
- if (shell === "gitbash") return read(config.shellGitBash as boolean | undefined, true);
842
- if (shell === "msys2") return read(config.shellMsys2 as boolean | undefined, true);
843
- if (shell === "wsl") return read(config.shellWsl as boolean | undefined, true);
844
- if (shell === "payload") return read(config.shellPayload as boolean | undefined, false);
845
- return false;
846
- };
847
- /**
848
- * What the model is TOLD. Sanitised, because this one runs on every prompt
849
- * assembly: an invalid stored value must not break the whole prompt, and naming
850
- * the floor is honest about what a successful call would use.
851
- */
852
- const describedShell = (): string => {
853
- const stored = storedShell();
854
- if ((SHELLS as readonly string[]).includes(stored) && switchOn(stored)) return stored;
855
- if (!warnedStale) {
856
- warnedStale = true;
857
- ctx.logger?.warn?.(`dsh-bash-terminal-ts: defaultShell ${JSON.stringify(stored)} is not a selectable/activated backend; shell calls will fail closed and the bottom terminal falls back to ${DEFAULT_SHELL}`);
858
- }
859
- return DEFAULT_SHELL;
860
- };
861
-
862
- // The browser terminal (bottom dock / embedded shell). Mounted BEFORE the
863
- // win32 return below: the model tool is Windows-only, the terminal is not
864
- // (finding F1). Its routes report their own availability, so a host without
865
- // `registerUpgrade` or without any PTY backend shows a reason instead of a
866
- // dead panel.
867
- const browserTerminals = mountBrowserTerminals({
868
- ctx: ctx as never,
869
- config: config as Record<string, unknown>,
870
- paths,
871
- configuredShell: storedShell,
872
- payloadSuppressed: () => payloadSuppressed,
873
- persist: async (svc, path, value) => {
874
- await persistConfigValue(svc, path, value);
875
- // ≤0.1.6 hosts have no config hot-reload, so mirror a defaultShell write into
876
- // the same in-process override the legacy bridge uses. Without it, choosing a
877
- // shell in the bottom-terminal section would only reach the model tool after
878
- // a restart - the exact divergence the bridge's `shellOverride` exists to kill.
879
- if (path.length === 1 && path[0] === "defaultShell" && typeof value === "string") {
880
- shellOverride = value;
881
- }
882
- },
883
- });
884
- ctx.effect(() => () => browserTerminals.dispose(), "bash-terminal: browser terminal teardown");
885
-
886
- if (process.platform !== "win32") {
887
- ctx.logger?.info?.("dsh-bash-terminal-ts: only meaningful on win32; skipping tool registration");
888
- return;
889
- }
890
- const backgroundEnabled = true;
891
- // R5/R6 and finding F8: an invalid stored value used to throw here, which failed
892
- // the whole entry - the tool, the settings row and the browser terminal all
893
- // disappeared. The entry now stays mounted, the tool fails closed per call, and
894
- // the browser terminal substitutes the floor and says so.
895
- /** Official sandbox-escalation surface (mirrors tool-bash): advertise the
896
- * escalation modes whenever the deployment confines. */
897
- const escalationModes = ESCALATION_TARGETS;
898
- const approveShellEscalation = (
899
- mode: string,
900
- justification: string,
901
- exec: ToolRunContext,
902
- standingPolicy: SandboxPolicy
903
- ): Promise<string> => {
904
- return approveEscalation({
905
- requestedMode: mode,
906
- justification,
907
- effectiveMode: standingPolicy.mode,
908
- subject: "command"
909
- }, {
910
- approver: ctx.get("approval"),
911
- agent: exec.agent,
912
- callId: exec.callId,
913
- toolName: "shell",
914
- signal: exec.signal
915
- });
916
- };
917
-
918
- ctx.systemPrompt.section({
919
- name: "tool:bash-terminal",
920
- order: 105,
921
- text: "Use the shell tool for terminal commands: it runs in the terminal the user chose in Settings -> General -> Default terminal (PowerShell, Git Bash, MSYS2, or WSL) and honors the DSH sandbox. Prefer it over the pwsh tool for everyday commands; keep the pwsh tool for cases that specifically need the sandboxed PowerShell surface."
922
- });
923
-
924
- // compat-legacy: 六线统一配置通道(≤0.1.6 无 client-store 模块表,client 走本
925
- // bridge 读写 defaultShell)。写路径 = settings.mutate;≤0.1.6 的 loader 不会自动
926
- // 注册命名空间,复用 perm-gate 自门控(not registered → register → 重试);
927
- // rc.1+ 命名空间由 loader 占用,该分支自然不命中。GET 带回当前值与可选集。
928
- // 宿主 context 类型未收录 inject/局部服务形状,compat 桥按宽化面调用。
929
- // 窄面型只覆盖本桥用到的三个字段,避免 any 外泄。
930
- interface BridgeReq {
931
- socket?: { remoteAddress?: string };
932
- method?: string;
933
- on(event: "data", cb: (chunk: Buffer) => void): void;
934
- on(event: "end", cb: () => void): void;
935
- }
936
- interface BridgeRes {
937
- writeHead(status: number, headers: Record<string, string>): void;
938
- end(body: string): void;
939
- }
940
- type BridgeSvcCtx = {
941
- settings: unknown;
942
- webServer: { register: (route: { kind: string; path: string; handler: (req: BridgeReq, res: BridgeRes) => void }) => () => void };
943
- effect: (fn: () => (() => void) | void, label?: string) => void;
944
- };
945
- const compatCtx = ctx as unknown as { inject?: (deps: string[], fn: (svcCtx: BridgeSvcCtx) => void) => void };
946
- if (typeof compatCtx.inject !== "function") {
947
- // A context without `inject` (a bare mock, or a host that resolves services
948
- // only synchronously) cannot receive the bridge at all. Skipping it must not
949
- // take the tool down with it - the tool is what the model calls.
950
- ctx.logger?.warn?.("dsh-bash-terminal-ts: ctx.inject unavailable - the settings bridge is not mounted (defaultShell reads still work, writes will not)");
951
- } else compatCtx.inject(["webServer", "settings"], (svcCtx: BridgeSvcCtx) => {
952
- const svc = svcCtx.settings;
953
- const writeShell = async (value: string): Promise<void> => {
954
- // One implementation for every config write (the browser terminal's switches
955
- // go through the same helper), so the legacy self-registration dance exists
956
- // in exactly one place.
957
- await persistConfigValue(svc, ["defaultShell"], value);
958
- shellOverride = value;
959
- };
960
- svcCtx.effect(
961
- () => {
962
- const json = (res: unknown, status: number, body: unknown): void => {
963
- (res as { writeHead: (s: number, h: Record<string, string>) => void; end: (b: string) => void }).writeHead(status, { "content-type": "application/json; charset=utf-8" });
964
- (res as { end: (b: string) => void }).end(JSON.stringify(body));
965
- };
966
- const handler = (req: BridgeReq, res: BridgeRes): void => {
967
- const addr = req.socket?.remoteAddress ?? "";
968
- if (addr !== "127.0.0.1" && addr !== "::1" && addr !== "::ffff:127.0.0.1") {
969
- json(res, 403, { ok: false, code: "loopback-only" });
970
- return;
971
- }
972
- if (req.method === "GET") {
973
- // 缝内省:compat 验证用——当前线 ctx.subprocess 的真实能力面
974
- const seam = ctx as unknown as { subprocess?: Record<string, unknown> };
975
- const sp = seam.subprocess as { spawn?: unknown; spawnTerminal?: unknown } | undefined;
976
- json(res, 200, {
977
- ok: true,
978
- value: {
979
- defaultShell: currentShell(),
980
- shells: SHELLS,
981
- seam: { spawn: typeof sp?.spawn, spawnTerminal: typeof sp?.spawnTerminal },
982
- },
983
- });
984
- return;
985
- }
986
- if (req.method !== "POST") {
987
- json(res, 405, { ok: false, code: "method-not-allowed" });
988
- return;
989
- }
990
- const chunks: Buffer[] = [];
991
- let size = 0;
992
- req.on("data", (c: Buffer) => {
993
- size += c.length;
994
- if (size <= 65536) chunks.push(c);
995
- });
996
- req.on("end", () => {
997
- let body: { defaultShell?: unknown };
998
- try {
999
- body = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
1000
- } catch {
1001
- json(res, 400, { ok: false, code: "bad-json" });
1002
- return;
1003
- }
1004
- const value = typeof body.defaultShell === "string" ? body.defaultShell : "";
1005
- if (!(SHELLS as readonly string[]).includes(value)) {
1006
- json(res, 400, { ok: false, code: "invalid-shell" });
1007
- return;
1008
- }
1009
- void writeShell(value)
1010
- .then(() => json(res, 200, { ok: true, value: { defaultShell: value } }))
1011
- .catch((e: unknown) => json(res, 500, { ok: false, code: "write-failed", message: e instanceof Error ? e.message : String(e) }));
1012
- });
1013
- };
1014
- const registered = [
1015
- svcCtx.webServer.register({ kind: "exact", path: "/api/bash-terminal/config", handler }),
1016
- ];
1017
- return () => {
1018
- for (const dispose of registered) dispose();
1019
- };
1020
- }, "bash-terminal: compat config bridge");
1021
- });
1022
-
1023
- const toolName = "shell";
1024
- const terminalRegistry = createTerminalRegistry(ctx);
1025
- // The interactive terminal obeys the SAME activation gate as the shell tool:
1026
- // the getter throws for a switched-off backend, so a session cannot open on
1027
- // a shell the user just disabled.
1028
- ctx.tools.register(terminalTool(ctx, terminalRegistry, paths, () => {
1029
- const shell = currentShell();
1030
- if ((SHELLS as readonly string[]).includes(shell) && !switchOn(shell)) {
1031
- throw new Error(`dsh-bash-terminal-ts: ${shell} backend is not activated - enable its switch in the plugin settings first.`);
1032
- }
1033
- return shell;
1034
- }));
1035
-
1036
- // The model-facing description must track the user's chosen default
1037
- // terminal: a static description listing every backend leaves the model
1038
- // guessing which syntax applies. Re-render it on every prompt assembly —
1039
- // settings are hot-reloaded, so a change shows up on the next request
1040
- // without a restart.
1041
- ctx.on("system-prompt/assemble", async (_assembly, _context, next) => {
1042
- const assembled = await next();
1043
- const description = toolDescription(backgroundEnabled, describedShell());
1044
- const tools = Array.isArray(assembled.tools)
1045
- ? assembled.tools.map((tool) => (tool.name === toolName ? { ...tool, description } : tool))
1046
- : assembled.tools;
1047
- return { ...assembled, tools };
1048
- });
1049
-
1050
- ctx.tools.register(defineTool<ShellToolResult>({
1051
- name: toolName,
1052
- description: toolDescription(backgroundEnabled, currentShell()),
1053
- parameters: {
1054
- command: {
1055
- type: "string",
1056
- required: true,
1057
- description: "The command to execute in the selected terminal."
1058
- },
1059
- description: {
1060
- type: "string",
1061
- required: true,
1062
- description: "Clear, concise description of what this command does in active voice, 5-10 words (shown in the UI). Examples: \"ls\" -> \"List files in current directory\"; \"git status\" -> \"Show working tree status\"; \"npm install\" -> \"Install package dependencies\"."
1063
- },
1064
- distro: {
1065
- type: "string",
1066
- description: "WSL distribution to use (only when the configured default terminal is wsl). Defaults to the system default distribution."
1067
- },
1068
- sandbox_permissions: {
1069
- type: "string",
1070
- enum: escalationModes,
1071
- description: "The wider sandbox mode this command needs. Only valid as a one-shot retry of a command the sandbox just denied; requires justification and user approval."
1072
- },
1073
- justification: {
1074
- type: "string",
1075
- description: "Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access."
1076
- },
1077
- workdir: {
1078
- type: "string",
1079
- description: "Working directory for this command. Defaults to the session workspace; a relative path is resolved against it."
1080
- },
1081
- timeoutMs: {
1082
- type: "number",
1083
- description: "Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry."
1084
- },
1085
- run_in_background: {
1086
- type: "boolean",
1087
- description: "Run in the background and return a job id immediately (collect with job_output, stop with job_kill). No timeout applies."
1088
- }
1089
- },
1090
- output: {
1091
- schema: {
1092
- oneOf: [
1093
- { type: "object", additionalProperties: false, properties: BACKGROUND_OUTPUT_PROPERTIES },
1094
- {
1095
- type: "object",
1096
- additionalProperties: false,
1097
- properties: {
1098
- kind: { type: "string", required: true, const: "foreground" },
1099
- exitCode: { required: true, oneOf: [{ type: "integer" }, { type: "null" }] },
1100
- signal: { required: true, oneOf: [{ type: "string" }, { type: "null" }] },
1101
- timedOut: { type: "boolean", required: true },
1102
- aborted: { type: "boolean", required: true },
1103
- timeoutMs: { type: "number", required: true },
1104
- sandbox: {
1105
- type: "object",
1106
- additionalProperties: false,
1107
- properties: {
1108
- mode: { type: "string", required: true },
1109
- enforcement: { type: "string", required: true },
1110
- denied: { type: "boolean" }
1111
- }
1112
- },
1113
- stdout: {
1114
- type: "object",
1115
- additionalProperties: false,
1116
- required: true,
1117
- properties: {
1118
- text: { type: "string", required: true },
1119
- truncated: { type: "boolean", required: true },
1120
- spillPath: { type: "string" }
1121
- }
1122
- },
1123
- stderr: {
1124
- type: "object",
1125
- additionalProperties: false,
1126
- required: true,
1127
- properties: {
1128
- text: { type: "string", required: true },
1129
- truncated: { type: "boolean", required: true },
1130
- spillPath: { type: "string" }
1131
- }
1132
- }
1133
- }
1134
- }
1135
- ]
1136
- },
1137
- render: (_args, value) => {
1138
- if (value.kind === "background") return [{ type: "text", text: `started background job ${value.jobId}` }];
1139
- let text = renderResult(value);
1140
- if (value.sandbox?.denied === true) {
1141
- if (!text.endsWith("\n")) text += "\n";
1142
- text += sandboxDenialMarker(value.sandbox.mode) + "\n" + escalationHintMarker("command");
1143
- }
1144
- return [{ type: "text", text }];
1145
- }
1146
- },
1147
- async execute(args, exec) {
1148
- const v = validateArgs(args);
1149
- const shell = currentShell();
1150
- if ((SHELLS as readonly string[]).includes(shell) && !switchOn(shell)) {
1151
- throw new Error(`dsh-bash-terminal-ts: ${shell} backend is not activated - ask the user to enable its switch in the plugin settings (bottom terminal), or choose another default terminal.`);
1152
- }
1153
- const argv0 = buildArgv(shell, v.command, paths, v.distro);
1154
- if (argv0[0] === undefined) {
1155
- throw new Error(`dsh-bash-terminal-ts: ${shell} backend unavailable - executable not found. Install it or set the corresponding *Path config.`);
1156
- }
1157
- // Only element 0 (the resolved executable) can be undefined; guarded above.
1158
- const argv = argv0 as string[];
1159
- const workdir = resolveWorkdir(v.workdir, exec);
1160
- const timeoutMs = clampTimeout(v.timeoutMs, config.timeoutMs ?? DEFAULT_TIMEOUT_MS, config.maxTimeoutMs ?? MAX_TIMEOUT_MS, "shell timeoutMs");
1161
- const dshEnv = ctx.shellEnv.collect(exec);
1162
- const env = buildEnv(shell, dshEnv);
1163
- let policy = ctx.sandboxPolicy.resolve(exec.agent ? { session: exec.agent.session } : {});
1164
- if (v.sandbox_permissions !== undefined && v.justification !== undefined) {
1165
- const approvedMode = await approveShellEscalation(v.sandbox_permissions, v.justification, exec, policy);
1166
- policy = { ...policy, mode: approvedMode };
1167
- }
1168
- const { argv: confinedArgv, sandbox } = confineSpawn(ctx, argv, policy, shell);
1169
- const resolved: SpawnResolution = {
1170
- command: v.command,
1171
- workdir: workdir ?? process.cwd(),
1172
- timeoutMs,
1173
- stdoutMaxBytes: DEFAULT_MAX_OUTPUT_BYTES,
1174
- ...(v.stdin !== undefined ? { stdin: v.stdin } : {})
1175
- };
1176
- if (v.run_in_background === true) {
1177
- const jobs = ctx.get("jobs") as JobsRegistry | undefined;
1178
- if (jobs === undefined) throw new Error("background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs");
1179
- if (exec.signal.aborted) {
1180
- const error = new HarnessError("tool call aborted", TOOL_ABORTED);
1181
- error.name = "AbortError";
1182
- throw error;
1183
- }
1184
- return {
1185
- kind: "background",
1186
- jobId: jobs.start({
1187
- kind: `shell/${shell}`,
1188
- label: v.command,
1189
- ...(exec.agent ? { owner: exec.agent } : {}),
1190
- run: () => {
1191
- const proc = startBackground(ctx, confinedArgv, resolved, env, exec.signal);
1192
- return {
1193
- cancel: () => void proc.kill(),
1194
- done: proc.done.then(() => processOutcome(proc)),
1195
- readOutput: () => renderProcessRead(proc.readOutput())
1196
- };
1197
- }
1198
- })
1199
- };
1200
- }
1201
- const result = await runForeground(ctx, confinedArgv, resolved, env, exec.signal, timeoutMs);
1202
- if (result.aborted) {
1203
- const error = new HarnessError("tool call aborted", TOOL_ABORTED);
1204
- error.name = "AbortError";
1205
- throw error;
1206
- }
1207
- const denied = sandbox?.denialSignatures !== undefined
1208
- ? sandbox.denialSignatures.some((sig) => result.stderr.text.toLowerCase().includes(sig.toLowerCase()))
1209
- : false;
1210
- return canonicalResult({
1211
- ...result,
1212
- ...(sandbox !== undefined ? { sandbox: { mode: sandbox.mode, enforcement: sandbox.enforcement, denied } } : {})
1213
- });
1214
- },
1215
- presentCall: (args) => {
1216
- if (args.run_in_background === true) {
1217
- return {
1218
- card: "generic",
1219
- title: args.command as string,
1220
- kind: "execute",
1221
- rawInput: args.command,
1222
- content: [{ type: "text", text: args.description as string }]
1223
- };
1224
- }
1225
- return {
1226
- card: "terminal",
1227
- title: args.command as string,
1228
- description: args.description as string,
1229
- ...(args.workdir !== undefined ? { cwd: args.workdir } : {})
1230
- };
1231
- },
1232
- presentResult: (args, result) => {
1233
- const block = result.content.length === 1 ? result.content[0] : undefined;
1234
- if (block === undefined || block.type !== "text") return undefined;
1235
- const raw = block.text ?? "";
1236
- if (args.run_in_background === true || result.isError) {
1237
- return { card: "generic", content: [{ type: "text", text: "```console\n" + raw.replace(/\n+$/, "") + "\n```" }] };
1238
- }
1239
- const { body, ...exit } = parseExitStatus(raw);
1240
- return { card: "terminal", output: body, ...exit };
1241
- }
1242
- }));
1243
- }
1244
-
1245
- //#region internals for tests
1246
- export const internals = {
1247
- candidateExists,
1248
- resolveAllPaths,
1249
- resolveWorkdir,
1250
- renderResult,
1251
- processOutcome,
1252
- startBackground,
1253
- runForeground,
1254
- spawnSpec,
1255
- buildEnv,
1256
- buildArgv,
1257
- validateArgs,
1258
- toolDescription,
1259
- SHELL_DESCRIPTIONS,
1260
- DEFAULT_TIMEOUT_MS,
1261
- MAX_TIMEOUT_MS,
1262
- DEFAULT_MAX_OUTPUT_BYTES
1263
- };
1264
- //#endregion
1265
-
1266
- // re-export for plugin consumers (type-only)
1267
- export type {
1268
- ExecAgent,
1269
- JobsRegistry,
1270
- JsonSchemaNode,
1271
- SandboxFacts,
1272
- SandboxPolicy,
1273
- ShellId,
1274
- ToolRunContext
1275
- };
1
+ // dsh-bash-terminal-ts - one shell tool, four Windows terminals.
2
+ //
3
+ // Registers a model-facing shell tool. The terminal backend (powershell /
4
+ // gitbash / msys2 / wsl) is chosen by the USER in the Web UI settings (default
5
+ // terminal); the model cannot pick it — the tool always obeys the user's
6
+ // choice:
7
+ // - powershell: pwsh -NoLogo -NoProfile -NonInteractive -Command <cmd>
8
+ // - gitbash: Git for Windows bash -lc <cmd> (POSIX; /d/... paths)
9
+ // - msys2: MSYS2 bash -lc <cmd> (POSIX; /c/... paths, full GCC/mingw64 toolchain)
10
+ // - wsl: wsl [-d <distro>] -e bash -lc <cmd> (Linux; /mnt/d/... paths)
11
+ //
12
+ // The tool spawns through the shared ctx.subprocess seam (process-tree
13
+ // termination, SIGTERM->grace->SIGKILL, spill files) and registers background
14
+ // handles with the generic ctx.jobs registry, mirroring the shipped
15
+ // dsh-tool-bash / dsh-tool-pwsh story call-for-call. It deliberately
16
+ // does NOT consume the ctx.shell capability seam: the platform's own
17
+ // sandboxed PowerShell executor keeps serving the pwsh tool. This tool is
18
+ // an additional, user-selected terminal that still honors the DSH sandbox:
19
+ // confined modes wrap PowerShell's spawn argv through ctx.sandbox
20
+ // (fail-closed), while danger-full-access, Git Bash, MSYS2, and WSL run
21
+ // unconfined. Git Bash and MSYS2 are unconfined because the DSH Windows ACL
22
+ // restricted-token runner cannot host Cygwin/MSYS2: bash aborts with
23
+ // "CreateFileMapping ... Win32 error 5" during startup.
24
+
25
+ import { lstatSync } from "node:fs";
26
+ import { isAbsolute, join, resolve } from "node:path";
27
+ import { mountBrowserTerminals } from "./webterminals/mount.js";
28
+ import {
29
+ ESCALATION_TARGETS,
30
+ TOOL_ABORTED,
31
+ approveEscalation,
32
+ defineTool,
33
+ escalationHintMarker,
34
+ clampTimeout,
35
+ deadline,
36
+ parseExitStatus,
37
+ timeoutOf,
38
+ sandboxDenialMarker,
39
+ validateEscalationArgs,
40
+ z,
41
+ HarnessError
42
+ } from "./dsh.js";
43
+ import type {
44
+ BashTerminalContext,
45
+ ExecAgent,
46
+ JobsRegistry,
47
+ JsonSchemaNode,
48
+ ResolvedPaths,
49
+ SandboxFacts,
50
+ SandboxPolicy,
51
+ ShellId,
52
+ ToolRunContext
53
+ } from "./dsh-types.js";
54
+ import { createTerminalRegistry, terminalTool } from "./terminal.js";
55
+ import { resolvePayloadBash } from "./payload.js";
56
+
57
+ /** Stable Cordis plugin name. */
58
+ export const name = "bash-terminal";
59
+ /** Composition entry id (the `tool-bash-terminal` row the bundle patch declares). */
60
+ const ENTRY_ID = "tool-bash-terminal";
61
+ /** Services required before the tool can register. */
62
+ export const inject = ["tools", "systemPrompt", "shellEnv", "subprocess", "settings", "sandbox", "sandboxPolicy"];
63
+
64
+ /** The terminal backends this tool exposes, in catalog order. */
65
+ export const SHELLS = ["powershell", "gitbash", "msys2", "wsl", "payload", "niu"] as const;
66
+ /** The backend used when the caller does not name one. */
67
+ export const DEFAULT_SHELL: ShellId = "powershell";
68
+ /** Default per-command timeout (ms). */
69
+ const DEFAULT_TIMEOUT_MS = 120000;
70
+ /** Upper bound a caller's timeoutMs is capped to. */
71
+ const MAX_TIMEOUT_MS = 600000;
72
+ /** SIGTERM->SIGKILL grace (ms), matching dsh-bash-local's default. */
73
+ const DEFAULT_GRACE_MS = 3000;
74
+ /** Per-stream in-memory cap before spilling (bytes). */
75
+ const DEFAULT_MAX_OUTPUT_BYTES = 64 * 1024;
76
+ /** Per-stream spill file cap (bytes). */
77
+ const DEFAULT_MAX_SPILL_BYTES = 64 * 1024 * 1024;
78
+ /** Timeout code stamped on the deadline's TimeoutReason. */
79
+ const TIMEOUT_CODE = "SHELL_TIMEOUT";
80
+
81
+ /** Model-friendly environment overrides (same set dsh-bash-local hardcodes). */
82
+ const ENV_OVERRIDES: Record<string, string> = {
83
+ NO_COLOR: "1",
84
+ TERM: "dumb",
85
+ PAGER: "cat",
86
+ GIT_PAGER: "cat"
87
+ };
88
+
89
+ /** Live reference the 0.1.7 loader hands `apply` for `.volatile()` config fields. */
90
+ interface VolatileRef<T> {
91
+ get(): T;
92
+ }
93
+
94
+ /** Static shape of the runtime configuration schema. */
95
+ export interface ConfigValues {
96
+ defaultShell: string;
97
+ timeoutMs: number;
98
+ maxTimeoutMs: number;
99
+ pwshPath: string;
100
+ gitBashPath: string;
101
+ msys2Path: string;
102
+ wslPath: string;
103
+ /**
104
+ * The bottom terminal's MASTER switch. Off outranks every child choice: the
105
+ * settings row hides the per-shell switches (a switch for something that cannot
106
+ * run is a lie) and the routes refuse allocations.
107
+ */
108
+ bottomTerminal: boolean;
109
+ /**
110
+ * Opt in to publishing the client-side `webTerminals` service, which is what powers
111
+ * dsh-better-sidebar's OFFICIAL bottom "Terminal" row on a deployment that has no
112
+ * terminal controller. Default false: the name is also provided by the host's own
113
+ * controller client, cordis refuses the second provider, and the controller's provide
114
+ * is unguarded - so claiming it by default breaks the first-party terminal and the
115
+ * whole web boot on DSH 0.2.0+ (measured). Turn it on only where the official row is
116
+ * dead because no controller exists.
117
+ */
118
+ shimOfficialTerminal: boolean;
119
+ /**
120
+ * Browser-terminal activation (R1/R2). The default is `true` for all three:
121
+ * a switch means "allowed", and availability is ANDed with it by the catalog -
122
+ * so "detected means on" needs no probe at schema level, while an explicit
123
+ * `false` is a real opt-out even on a machine that has the shell.
124
+ */
125
+ shellGitBash: boolean;
126
+ shellMsys2: boolean;
127
+ shellWsl: boolean;
128
+ /**
129
+ * Activation switch for the payload row in the bottom-terminal UI. Separate
130
+ * from `enablePosixPayload` (the operator gate that RUNS the digest check at
131
+ * startup): this one only decides whether a resolved payload may appear in
132
+ * pickers. Default false - the payload is opt-in twice, provisioning and
133
+ * activation.
134
+ */
135
+ shellPayload: boolean;
136
+ /** WSL distribution for the browser terminal; '' means the WSL default. */
137
+ wslDistro: string;
138
+ /**
139
+ * Pinned backup POSIX runtime payload (see src/payload.ts - the artifact is
140
+ * a Git-for-Windows tree; OUR name avoids the bash/msys tokens by policy).
141
+ * Default off; enabling it lets a digest-verified payload fill the Git Bash
142
+ * slot as a LAST-RESORT source when the machine has no system Git Bash. A
143
+ * detected WSL distro outranks the payload entirely (a real WSL bash is the
144
+ * better POSIX shell), and an unverifiable payload fails closed - it is
145
+ * never run, never silently replaced. Resolved at startup, so toggling
146
+ * takes effect on the next restart.
147
+ */
148
+ enablePosixPayload: boolean;
149
+ /** Explicit payload root or bin/bash.exe path; '' = auto-discovery only. */
150
+ payloadPosixPath: string;
151
+ /** Fixed niu.exe path; '' = auto-discovery via candidateNiuPaths. */
152
+ niuPath: string;
153
+ /** Activation switch for the Niubash row (default true: detected means on). */
154
+ shellNiu: boolean;
155
+ }
156
+
157
+ /** Runtime configuration schema. */
158
+ export const Config = z.object({
159
+ defaultShell: z.string().default(DEFAULT_SHELL).volatile(),
160
+ timeoutMs: z.number().default(DEFAULT_TIMEOUT_MS),
161
+ maxTimeoutMs: z.number().default(MAX_TIMEOUT_MS),
162
+ pwshPath: z.string().default(""),
163
+ gitBashPath: z.string().default(""),
164
+ msys2Path: z.string().default(""),
165
+ wslPath: z.string().default(""),
166
+ // `.volatile()` on the new fields: the browser terminal reads them on every
167
+ // allocation, and a flip in the settings page has to take effect without a
168
+ // restart (0.1.7+ hands apply a live ref; older lines re-read the same value).
169
+ bottomTerminal: z.boolean().default(true).volatile(),
170
+ shimOfficialTerminal: z.boolean().default(false).volatile(),
171
+ shellGitBash: z.boolean().default(true).volatile(),
172
+ shellMsys2: z.boolean().default(true).volatile(),
173
+ shellWsl: z.boolean().default(true).volatile(),
174
+ shellPayload: z.boolean().default(false).volatile(),
175
+ wslDistro: z.string().default("").volatile(),
176
+ // Payload gate state is read once per process (paths resolve at startup), so
177
+ // these are deliberately NOT volatile: a flip needs the restart it implies.
178
+ enablePosixPayload: z.boolean().default(false),
179
+ payloadPosixPath: z.string().default(""),
180
+ niuPath: z.string().default(""),
181
+ shellNiu: z.boolean().default(true).volatile()
182
+ });
183
+
184
+ // ---- executable resolution ------------------------------------------------
185
+
186
+ function candidateExists(candidate: string): boolean {
187
+ try {
188
+ const stat = lstatSync(candidate);
189
+ return stat.isFile() || stat.isSymbolicLink();
190
+ } catch {
191
+ return false;
192
+ }
193
+ }
194
+
195
+ function resolveFromCandidates(candidates: readonly string[]): string | undefined {
196
+ for (const candidate of candidates) {
197
+ if (candidateExists(candidate)) return candidate;
198
+ }
199
+ return undefined;
200
+ }
201
+
202
+ /** Well-known PowerShell install locations plus PATH entries, newest first. */
203
+ export function candidatePwshPaths(env: NodeJS.ProcessEnv = process.env): string[] {
204
+ const programFiles = env.ProgramFiles ?? "C:\\Program Files";
205
+ const systemRoot = env.SystemRoot ?? "C:\\Windows";
206
+ const candidates = [join(programFiles, "PowerShell", "7", "pwsh.exe")];
207
+ for (const entry of (env.PATH ?? "").split(";")) {
208
+ const trimmed = entry.trim().replace(/^"|"$/g, "");
209
+ if (trimmed.length === 0) continue;
210
+ candidates.push(join(trimmed, "pwsh.exe"));
211
+ }
212
+ candidates.push(join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"));
213
+ return candidates;
214
+ }
215
+
216
+ /**
217
+ * Git for Windows locations, then PATH bash.exe entries EXCLUDING the
218
+ * System32 launcher (c:\\windows\\system32\\bash.exe is the WSL
219
+ * forwarder, not a Git Bash shell).
220
+ */
221
+ export function candidateGitBashPaths(env: NodeJS.ProcessEnv = process.env): string[] {
222
+ const programFiles = env.ProgramFiles ?? "C:\\Program Files";
223
+ const systemRoot = (env.SystemRoot ?? "C:\\Windows").toLowerCase();
224
+ const localAppData = env.LOCALAPPDATA ?? "";
225
+ const candidates = [
226
+ join(programFiles, "Git", "bin", "bash.exe"),
227
+ join(programFiles, "Git", "usr", "bin", "bash.exe")
228
+ ];
229
+ if (localAppData.length > 0) candidates.push(join(localAppData, "Programs", "Git", "bin", "bash.exe"));
230
+ for (const entry of (env.PATH ?? "").split(";")) {
231
+ const trimmed = entry.trim().replace(/^"|"$/g, "");
232
+ if (trimmed.length === 0) continue;
233
+ if (trimmed.toLowerCase().includes(systemRoot)) continue;
234
+ candidates.push(join(trimmed, "bash.exe"));
235
+ }
236
+ return candidates;
237
+ }
238
+
239
+ /**
240
+ * MSYS2 locations, in preference order: the real `bash.exe` under usr\bin
241
+ * first, then bin\bash.exe, and `msys2.exe` dead last.
242
+ *
243
+ * msys2.exe is NOT a usable backend for piped execution: it is the console-
244
+ * allocating Cygwin launcher, so a spawn with piped stdio returns exit 0 with
245
+ * zero bytes on both stdout and stderr (measured on this machine against
246
+ * MSYS2 with bash 5.3.15). Keeping it in the list only as a last-resort
247
+ * fallback preserves the path the config docs reference, but a working
248
+ * bash.exe always wins.
249
+ *
250
+ * MSYS2 uses the same Cygwin/MSYS2 runtime as Git Bash, so it cannot run
251
+ * under the DSH Windows ACL restricted-token sandbox.
252
+ */
253
+ export function candidateMsys2Paths(env: NodeJS.ProcessEnv = process.env): string[] {
254
+ const candidates = [
255
+ "C:\\msys64\\usr\\bin\\bash.exe",
256
+ "C:\\msys64\\bin\\bash.exe"
257
+ ];
258
+ for (const entry of (env.PATH ?? "").split(";")) {
259
+ const trimmed = entry.trim().replace(/^"|"$/g, "");
260
+ if (trimmed.length === 0) continue;
261
+ const lower = trimmed.toLowerCase();
262
+ if (lower.includes("msys64") || lower.includes("mingw64")) {
263
+ candidates.push(join(trimmed, "bash.exe"));
264
+ }
265
+ }
266
+ candidates.push("C:\\msys64\\msys2.exe"); // last resort: see the note above
267
+ return candidates;
268
+ }
269
+
270
+ /**
271
+ * Niubash locations, in preference order: the per-user installer default
272
+ * (LOCALAPPDATA\Programs\Niubash) first, then the winget shim link, then a
273
+ * machine-wide install, then PATH entries. Read from the registry on this
274
+ * machine: the installer writes a USER Path entry pointing at the capitalized
275
+ * directory, so the first candidate must match that exact casing on
276
+ * case-sensitive filesystems (Windows itself is case-insensitive).
277
+ */
278
+ export function candidateNiuPaths(env: NodeJS.ProcessEnv = process.env): string[] {
279
+ const localAppData = env.LOCALAPPDATA ?? "";
280
+ const programFiles = env.ProgramFiles ?? "C:\\Program Files";
281
+ const candidates: string[] = [];
282
+ if (localAppData.length > 0) {
283
+ candidates.push(join(localAppData, "Programs", "Niubash", "niu.exe"));
284
+ candidates.push(join(localAppData, "Microsoft", "WinGet", "Links", "niu.exe"));
285
+ }
286
+ candidates.push(join(programFiles, "Niubash", "niu.exe"));
287
+ for (const entry of (env.PATH ?? "").split(";")) {
288
+ const trimmed = entry.trim().replace(/^"|"$/g, "");
289
+ if (trimmed.length === 0) continue;
290
+ candidates.push(join(trimmed, "niu.exe"));
291
+ }
292
+ return candidates;
293
+ }
294
+
295
+ export function defaultWslPath(env: NodeJS.ProcessEnv = process.env): string {
296
+ const systemRoot = env.SystemRoot ?? "C:\\Windows";
297
+ return join(systemRoot, "System32", "wsl.exe");
298
+ }
299
+
300
+ /** Executable paths, possibly undefined when a backend is not installed. */
301
+ export type { ResolvedPaths };
302
+
303
+ type PathConfig = Partial<Pick<ConfigValues, "pwshPath" | "gitBashPath" | "msys2Path" | "wslPath" | "niuPath">>;
304
+
305
+ export function resolveAllPaths(
306
+ config: PathConfig = {},
307
+ env: NodeJS.ProcessEnv = process.env,
308
+ payloadBash?: string
309
+ ): ResolvedPaths {
310
+ const pwsh = config.pwshPath && config.pwshPath.trim().length > 0
311
+ ? config.pwshPath
312
+ : resolveFromCandidates(candidatePwshPaths(env));
313
+ const gitbash = config.gitBashPath && config.gitBashPath.trim().length > 0
314
+ ? config.gitBashPath
315
+ : resolveFromCandidates(candidateGitBashPaths(env));
316
+ const msys2 = config.msys2Path && config.msys2Path.trim().length > 0
317
+ ? config.msys2Path
318
+ : resolveFromCandidates(candidateMsys2Paths(env));
319
+ const wsl = config.wslPath && config.wslPath.trim().length > 0
320
+ ? config.wslPath
321
+ : defaultWslPath(env);
322
+ const niu = config.niuPath && config.niuPath.trim().length > 0
323
+ ? config.niuPath
324
+ : resolveFromCandidates(candidateNiuPaths(env));
325
+ // The payload is its OWN backend (first-class catalog row) - it never
326
+ // silently substitutes for the gitbash slot, so a row labelled "Git Bash"
327
+ // always names a shell the machine actually has.
328
+ return { pwsh, gitbash, msys2, wsl, niu, ...(payloadBash !== undefined ? { payload: payloadBash } : {}) };
329
+ }
330
+
331
+ // ---- argv / env construction ------------------------------------------------
332
+
333
+ export function buildArgv(
334
+ shell: string,
335
+ command: string,
336
+ paths: ResolvedPaths,
337
+ distro?: string
338
+ ): Array<string | undefined> {
339
+ switch (shell) {
340
+ case "powershell":
341
+ return [paths.pwsh, "-NoLogo", "-NoProfile", "-NonInteractive", "-Command", command];
342
+ case "gitbash":
343
+ return [paths.gitbash, "-lc", command];
344
+ case "msys2":
345
+ // -lc, not -c: a login shell sources /etc/profile, which is what puts
346
+ // /usr/bin and /mingw64/bin on PATH. With a bare -c, `tr`, `sed`, `gcc`
347
+ // and friends are all "command not found".
348
+ return [paths.msys2, "-lc", command];
349
+ case "payload":
350
+ // Same login-shell rule as msys2/gitbash: the payload is a
351
+ // Git-for-Windows tree and `-lc` is what gives it a usable PATH.
352
+ return [paths.payload, "-lc", command];
353
+ case "niu":
354
+ // Same login-shell rule: -lc sources the profile chain so winuxcmd's
355
+ // bin directory joins PATH. (niu has no MSYS runtime; see findings F2
356
+ // for the sandbox question this backend answers.)
357
+ return [paths.niu, "-lc", command];
358
+ case "wsl": {
359
+ const distroArg = distro !== undefined && distro.trim().length > 0 ? ["-d", distro.trim()] : [];
360
+ return [paths.wsl, ...distroArg, "-e", "bash", "-lc", command];
361
+ }
362
+ default:
363
+ throw new Error(`invalid shell: ${JSON.stringify(shell)} (expected one of ${SHELLS.join(", ")})`);
364
+ }
365
+ }
366
+
367
+ /**
368
+ * Merge the DSH_* environment over the process environment. For WSL, only
369
+ * variables explicitly listed in WSLENV cross the boundary, so every DSH_*
370
+ * key is appended there — and the list is *layered onto* whatever WSLENV the
371
+ * host already had (Windows Terminal exports e.g. `WT_SESSION:WT_PROFILE_ID:`),
372
+ * never rebuilt from scratch: WSLENV is an allow-list, so dropping the
373
+ * inherited entries would silently stop them crossing into WSL.
374
+ *
375
+ * @param inheritedWslenv - the ambient WSLENV to layer onto. Callers that
376
+ * replace the child environment wholesale (the PTY path) must pass
377
+ * `process.env.WSLENV` explicitly, because the ambient value is not visible
378
+ * through `dshEnv`.
379
+ */
380
+ export function buildEnv(
381
+ shell: string,
382
+ dshEnv?: Record<string, string>,
383
+ inheritedWslenv: string | undefined = process.env.WSLENV
384
+ ): Record<string, string | undefined> {
385
+ const env: Record<string, string | undefined> = { ...ENV_OVERRIDES, ...dshEnv };
386
+ if (shell === "msys2") {
387
+ // Picks the MINGW64 environment, so /mingw64/bin (gcc, make, ...) joins
388
+ // PATH via /etc/profile. Without it MSYS2 defaults to the bare MSYS
389
+ // environment. An explicit caller-supplied value wins.
390
+ if (env.MSYSTEM === undefined) env.MSYSTEM = "MINGW64";
391
+ }
392
+ if (shell === "wsl") {
393
+ const keys = Object.keys(dshEnv ?? {});
394
+ if (keys.length > 0) {
395
+ // An explicit WSLENV in dshEnv wins over the inherited one; otherwise the
396
+ // inherited value is the base. Either way the base is SPLIT into entries
397
+ // (the host value ends with a trailing ":", so string concatenation would
398
+ // produce a malformed empty entry) and the WSLENV key itself is excluded
399
+ // (it is a key of dshEnv too, and appending it would add a bogus entry).
400
+ const declared = Object.prototype.hasOwnProperty.call(dshEnv ?? {}, "WSLENV");
401
+ const base = declared
402
+ ? env.WSLENV
403
+ : (typeof inheritedWslenv === "string" && inheritedWslenv.length > 0 ? inheritedWslenv : env.WSLENV);
404
+ const parts = typeof base === "string" ? base.split(":") : [];
405
+ env.WSLENV = [...parts, ...keys.filter((k) => k !== "WSLENV").flatMap((k) => k.split(":"))]
406
+ .map((p) => p.trim())
407
+ .filter((p) => p.length > 0)
408
+ .join(":");
409
+ }
410
+ }
411
+ return env;
412
+ }
413
+
414
+ // ---- spawn plumbing over ctx.subprocess ---------------------------------------
415
+
416
+ export interface SpawnResolution {
417
+ command: string;
418
+ workdir: string;
419
+ timeoutMs: number;
420
+ stdoutMaxBytes: number;
421
+ stdin?: string;
422
+ }
423
+
424
+ function spawnSpec(resolved: SpawnResolution, argv: string[], env: Record<string, string | undefined>, signal: AbortSignal) {
425
+ const collect = (maxBytes: number) => ({ maxBytes, spill: { maxBytes: DEFAULT_MAX_SPILL_BYTES } });
426
+ return {
427
+ argv,
428
+ cwd: resolved.workdir,
429
+ stdio: {
430
+ stdin: resolved.stdin !== undefined ? { data: resolved.stdin } : "ignore",
431
+ stdout: collect(resolved.stdoutMaxBytes),
432
+ stderr: collect(DEFAULT_MAX_OUTPUT_BYTES)
433
+ },
434
+ graceMs: DEFAULT_GRACE_MS,
435
+ signal,
436
+ env
437
+ } as const;
438
+ }
439
+
440
+ function collectedOutput(handle: { collected: { stdout: unknown; stderr: unknown } }) {
441
+ const { stdout, stderr } = handle.collected;
442
+ if (!isCollectedStream(stdout) || !isCollectedStream(stderr)) {
443
+ throw new Error("dsh-bash-terminal-ts: subprocess implementation dropped a requested collect stream");
444
+ }
445
+ return { stdout, stderr };
446
+ }
447
+
448
+ function isCollectedStream(value: unknown): value is CollectedLike {
449
+ return typeof value === "object" && value !== null && typeof (value as CollectedLike).readFrom === "function";
450
+ }
451
+
452
+ interface CollectedLike {
453
+ readFrom(offset: number): { text: string; lossy: boolean; nextOffset: number; spillPath?: string };
454
+ }
455
+
456
+ interface StreamOutput {
457
+ text: string;
458
+ truncated: boolean;
459
+ spillPath?: string;
460
+ }
461
+
462
+ function finalOutput(reader: CollectedLike): StreamOutput {
463
+ const read = reader.readFrom(0);
464
+ return {
465
+ text: read.text,
466
+ truncated: read.lossy,
467
+ ...(read.spillPath !== undefined ? { spillPath: read.spillPath } : {})
468
+ };
469
+ }
470
+
471
+ export interface ForegroundOutcome {
472
+ exitCode: number | null;
473
+ signal: string | null;
474
+ timedOut: boolean;
475
+ aborted: boolean;
476
+ timeoutMs: number;
477
+ stdout: StreamOutput;
478
+ stderr: StreamOutput;
479
+ }
480
+
481
+ async function runForeground(
482
+ ctx: BashTerminalContext,
483
+ argv: string[],
484
+ resolved: SpawnResolution,
485
+ env: Record<string, string | undefined>,
486
+ signal: AbortSignal,
487
+ timeoutMs: number
488
+ ): Promise<ForegroundOutcome> {
489
+ const subprocess = requireSubprocess(ctx);
490
+ const d = deadline(signal, timeoutMs, TIMEOUT_CODE);
491
+ try {
492
+ const handle = subprocess.spawn(spawnSpec(resolved, argv, env, d.signal));
493
+ const outcome = await handle.done;
494
+ const collected = collectedOutput(handle);
495
+ const timedOut = timeoutOf(d.signal, TIMEOUT_CODE) !== undefined;
496
+ const aborted = d.signal.aborted && !timedOut;
497
+ return {
498
+ exitCode: outcome.exitCode,
499
+ signal: outcome.signal,
500
+ timedOut,
501
+ aborted,
502
+ timeoutMs,
503
+ stdout: finalOutput(collected.stdout),
504
+ stderr: finalOutput(collected.stderr)
505
+ };
506
+ } finally {
507
+ d[Symbol.dispose]();
508
+ }
509
+ }
510
+
511
+ function requireSubprocess(ctx: BashTerminalContext) {
512
+ const subprocess = ctx.subprocess;
513
+ if (subprocess === null) {
514
+ throw new Error("dsh-bash-terminal-ts: ctx.subprocess seam unavailable (missing inject service)");
515
+ }
516
+ return subprocess;
517
+ }
518
+
519
+ export interface ProcessRead {
520
+ delta: string;
521
+ lossy: boolean;
522
+ stdoutSpillPath?: string;
523
+ stderrSpillPath?: string;
524
+ }
525
+
526
+ interface BackgroundProc {
527
+ status: "running" | "killed" | "completed";
528
+ exitCode: number | null;
529
+ signal: string | null;
530
+ done: Promise<void>;
531
+ readOutput(): ProcessRead;
532
+ kill(): boolean;
533
+ }
534
+
535
+ function startBackground(
536
+ ctx: BashTerminalContext,
537
+ argv: string[],
538
+ resolved: SpawnResolution,
539
+ env: Record<string, string | undefined>,
540
+ signal: AbortSignal
541
+ ): BackgroundProc {
542
+ const subprocess = requireSubprocess(ctx);
543
+ const running = subprocess.spawn(spawnSpec(resolved, argv, env, signal));
544
+ const collected = collectedOutput(running);
545
+ let stdoutOffset = 0;
546
+ let stderrOffset = 0;
547
+ let spawnFailureNote: string | undefined;
548
+ const consumeSpawnFailure = (): string => {
549
+ const note = spawnFailureNote ?? "";
550
+ spawnFailureNote = undefined;
551
+ return note;
552
+ };
553
+ const proc: BackgroundProc = {
554
+ status: "running",
555
+ exitCode: null,
556
+ signal: null,
557
+ done: running.done.then((outcome) => {
558
+ if (proc.status === "running") {
559
+ proc.status = signal?.aborted === true || outcome.signal !== null ? "killed" : "completed";
560
+ }
561
+ proc.exitCode = outcome.exitCode;
562
+ proc.signal = outcome.signal;
563
+ }, (error: unknown) => {
564
+ proc.status = "killed";
565
+ spawnFailureNote = `spawn failed: ${String(error)}`;
566
+ }),
567
+ readOutput: () => {
568
+ const out = collected.stdout.readFrom(stdoutOffset);
569
+ const err = collected.stderr.readFrom(stderrOffset);
570
+ stdoutOffset = out.nextOffset;
571
+ stderrOffset = err.nextOffset;
572
+ const errText = err.text.length > 0 ? err.text : consumeSpawnFailure();
573
+ const separator = out.text.length > 0 && !out.text.endsWith("\n") ? "\n" : "";
574
+ return {
575
+ delta: out.text + (errText.length > 0 ? `${separator}[stderr]\n${errText}` : ""),
576
+ lossy: out.lossy || err.lossy,
577
+ ...(out.spillPath !== undefined ? { stdoutSpillPath: out.spillPath } : {}),
578
+ ...(err.spillPath !== undefined ? { stderrSpillPath: err.spillPath } : {})
579
+ };
580
+ },
581
+ kill: () => {
582
+ if (proc.status !== "running") return false;
583
+ proc.status = "killed";
584
+ running.terminate();
585
+ return true;
586
+ }
587
+ };
588
+ return proc;
589
+ }
590
+
591
+ function processOutcome(proc: BackgroundProc): { status: string; detail: string } {
592
+ if (proc.status === "killed") {
593
+ return { status: "killed", detail: proc.signal !== null ? `signal: ${proc.signal}` : "killed before exit" };
594
+ }
595
+ return { status: "completed", detail: `exit code: ${proc.exitCode ?? 0}` };
596
+ }
597
+
598
+ // ---- model-facing rendering ---------------------------------------------------
599
+
600
+ function streamText(output: StreamOutput): string {
601
+ if (!output.truncated) return output.text;
602
+ return `${output.text}\n[output truncated; full output: ${output.spillPath ?? "(unavailable)"}]`;
603
+ }
604
+
605
+ export interface RenderedResult {
606
+ stdout: StreamOutput;
607
+ stderr: StreamOutput;
608
+ exitCode: number | null;
609
+ signal: string | null;
610
+ timedOut: boolean;
611
+ timeoutMs: number;
612
+ }
613
+
614
+ export function renderResult(result: RenderedResult): string {
615
+ const out = streamText(result.stdout);
616
+ const err = streamText(result.stderr);
617
+ let body = out;
618
+ if (err.length > 0) {
619
+ if (body.length > 0 && !body.endsWith("\n")) body += "\n";
620
+ body += `[stderr]\n${err}`;
621
+ }
622
+ if (body.length === 0) body = "(no output)";
623
+ const markers: string[] = [];
624
+ if (result.timedOut) markers.push(`[timed out after ${result.timeoutMs}ms]`);
625
+ if (result.signal !== null) markers.push(`[killed by signal: ${result.signal}]`);
626
+ else if (result.exitCode !== 0) markers.push(`[exit code: ${result.exitCode}]`);
627
+ if (markers.length === 0) return body;
628
+ if (!body.endsWith("\n")) body += "\n";
629
+ return body + markers.join("\n");
630
+ }
631
+
632
+ function renderProcessRead(read: ProcessRead): string {
633
+ const notices: string[] = [];
634
+ if (read.lossy) {
635
+ const paths = [read.stdoutSpillPath, read.stderrSpillPath].filter((p) => p !== undefined);
636
+ notices.push(`[some output was dropped from memory; full output: ${paths.length > 0 ? paths.join(", ") : "(unavailable)"}]`);
637
+ }
638
+ if (notices.length === 0) return read.delta;
639
+ return `${read.delta}${read.delta.length > 0 && !read.delta.endsWith("\n") ? "\n" : ""}${notices.join("\n")}`;
640
+ }
641
+
642
+ // ---- tool description / validation --------------------------------------------
643
+
644
+ /** Model-facing lead sentence for each backend. The user's default terminal is
645
+ * stated up front so the model never has to guess which syntax applies. */
646
+ export const SHELL_DESCRIPTIONS: Record<ShellId, string> = {
647
+ powershell: "Execute a PowerShell command (pwsh -NoLogo -NoProfile -NonInteractive -Command <command>) and return its stdout/stderr. PowerShell syntax; native Windows paths (C:\\...); environment variables via $env:NAME.",
648
+ gitbash: "Execute a bash command (Git for Windows bash -lc <command>) and return its stdout/stderr. POSIX syntax; paths like /d/WorkSpace; PATH includes /usr/bin and /mingw64/bin so git, npm, ssh etc. work; environment variables via $NAME.",
649
+ msys2: "Execute a bash command (MSYS2 bash -lc <command>) and return its stdout/stderr. POSIX syntax; paths like /c/...; PATH includes /usr/bin and /mingw64/bin so git, npm, gcc, make etc. work; environment variables via $NAME. MSYS2 provides a full GCC/mingw64 toolchain.",
650
+ wsl: "Execute a Linux bash command (wsl [-d <distro>] -e bash -lc <command>) and return its stdout/stderr. Linux syntax; Windows files under /mnt/d/...; environment variables via $NAME.",
651
+ payload: "Execute a bash command in the plugin's pinned POSIX runtime payload (a digest-verified Git-for-Windows bash -lc <command>) and return its stdout/stderr. POSIX syntax; paths like /c/...; PATH includes /usr/bin so git, npm, ssh etc. work; environment variables via $NAME. Use it only when the user has deliberately enabled the payload backend.",
652
+ niu: "Execute a bash command (Niubash niu -lc <command>) and return its stdout/stderr. GNU bash 5.3 semantics; WinuxCmd applets (ls, cp, rm, grep, find, cat, sed, awk, ...) are on PATH; native Windows paths such as C:\\... are kept as-is while /c/... style arguments are translated; environment variables via $NAME. Niubash is a native binary with no MSYS emulation layer, so /dev/* redirects other than /dev/null do not exist; its startup file is ~/.niubashrc."
653
+ };
654
+
655
+ /**
656
+ * Render the model-facing tool description for one backend. The backend is
657
+ * whatever the user chose in Settings -> General -> Default terminal; the
658
+ * description names it explicitly so the model writes the right syntax.
659
+ * @param backgroundEnabled - advertise `run_in_background` controls.
660
+ * @param shell - active backend; unknown values fall back to the default.
661
+ */
662
+ export function toolDescription(backgroundEnabled: boolean, shell: string = DEFAULT_SHELL): string {
663
+ const active: ShellId = (SHELLS as readonly string[]).includes(shell) ? (shell as ShellId) : DEFAULT_SHELL;
664
+ const lead = SHELL_DESCRIPTIONS[active];
665
+ const base = [
666
+ `The user's chosen default terminal (Settings -> General -> Default terminal) is ${active}; commands run there.`,
667
+ lead,
668
+ "Each call spawns a fresh shell: no state (cwd, variables, aliases) persists between calls - pass workdir instead of using cd. Non-zero exits are reported as [exit code: N] markers; investigate failures before moving on. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Commands run under the DSH sandbox: confined modes (read-only / workspace-write) are enforced through ctx.sandbox and deny fail-closed for PowerShell; danger-full-access, Git Bash, MSYS2, the pinned POSIX payload, Niubash, and WSL run unconfined."
669
+ ].join(" ");
670
+ if (!backgroundEnabled) return base;
671
+ return base + " Set run_in_background: true for long-running commands: the call returns a job id immediately; read its output with job_output and stop it with job_kill. No timeout applies to background runs.";
672
+ }
673
+
674
+ /** The shell tool's arguments after runtime validation. */
675
+ export type ValidatedShellArgs = {
676
+ command: string;
677
+ description: string;
678
+ timeoutMs?: number;
679
+ distro?: string;
680
+ sandbox_permissions?: string;
681
+ justification?: string;
682
+ workdir?: string;
683
+ run_in_background?: boolean;
684
+ stdin?: string;
685
+ };
686
+
687
+ export function validateArgs(args: Record<string, unknown>): ValidatedShellArgs {
688
+ if (typeof args.command !== "string" || args.command.trim().length === 0) {
689
+ throw new Error("invalid command: expected a non-empty string");
690
+ }
691
+ if (typeof args.description !== "string" || args.description.trim().length === 0) {
692
+ throw new Error("invalid description: expected a non-empty string");
693
+ }
694
+ if (args.timeoutMs !== undefined && (typeof args.timeoutMs !== "number" || !Number.isFinite(args.timeoutMs) || args.timeoutMs <= 0)) {
695
+ throw new Error(`invalid timeoutMs: expected a positive number, got ${JSON.stringify(args.timeoutMs)}`);
696
+ }
697
+ validateEscalationArgs(args.sandbox_permissions, args.justification);
698
+ return args as ValidatedShellArgs;
699
+ }
700
+
701
+ /**
702
+ * Official sandbox seam (mirrors dsh-tool-bash / dsh-pwsh-sandbox): resolve the
703
+ * per-call policy from ctx.sandboxPolicy, and — unless the call runs
704
+ * danger-full-access — confine the spawn argv through ctx.sandbox. WSL is a
705
+ * self-contained Linux VM and is not confined (its isolation IS the sandbox).
706
+ * Git Bash and MSYS2 are also not confined: DSH's Windows ACL restricted-token
707
+ * runner cannot start Cygwin/MSYS2 (CreateFileMapping Win32 error 5), so
708
+ * attempting to wrap them would abort every Git Bash / MSYS2 command. A
709
+ * requested confined mode
710
+ * with no usable backend throws the fail-closed SandboxUnavailableError,
711
+ * exactly like the shipped executors.
712
+ */
713
+ function confineSpawn(
714
+ ctx: BashTerminalContext,
715
+ argv: string[],
716
+ policy: SandboxPolicy,
717
+ shell: string
718
+ ): { argv: string[]; sandbox?: SandboxFacts } {
719
+ if (policy.mode === "danger-full-access" || shell === "wsl" || shell === "gitbash" || shell === "msys2" || shell === "payload") {
720
+ const sandbox = shell === "wsl"
721
+ ? { mode: policy.mode, enforcement: "wsl-isolation" }
722
+ : shell === "gitbash"
723
+ ? { mode: policy.mode, enforcement: "gitbash-unconfined" }
724
+ : shell === "msys2"
725
+ ? { mode: policy.mode, enforcement: "msys2-unconfined" }
726
+ : shell === "payload"
727
+ // The payload cannot be confined either (same Cygwin/MSYS runtime
728
+ // constraint as Git Bash) - its safety layer is the digest gate.
729
+ ? { mode: policy.mode, enforcement: "payload-unconfined" }
730
+ : undefined;
731
+ return { argv, sandbox };
732
+ }
733
+ const confined = ctx.sandbox.confine(argv, policy);
734
+ return {
735
+ argv: confined.argv,
736
+ sandbox: { mode: policy.mode, enforcement: confined.enforcement, denialSignatures: confined.denialSignatures }
737
+ };
738
+ }
739
+
740
+ function resolveWorkdir(modelWorkdir: string | undefined, exec: ToolRunContext): string | undefined {
741
+ const headerCwd = exec.agent?.session.header.cwd;
742
+ if (modelWorkdir === undefined) return headerCwd;
743
+ if (headerCwd !== undefined && !isAbsolute(modelWorkdir)) return resolve(headerCwd, modelWorkdir);
744
+ return modelWorkdir;
745
+ }
746
+
747
+ export interface ForegroundResult {
748
+ kind: "foreground";
749
+ exitCode: number | null;
750
+ signal: string | null;
751
+ timedOut: boolean;
752
+ aborted: boolean;
753
+ timeoutMs: number;
754
+ stdout: StreamOutput;
755
+ stderr: StreamOutput;
756
+ sandbox?: SandboxFacts;
757
+ }
758
+
759
+ export interface BackgroundResult {
760
+ kind: "background";
761
+ jobId: string;
762
+ }
763
+
764
+ export type ShellToolResult = ForegroundResult | BackgroundResult;
765
+
766
+ function canonicalResult(result: ForegroundOutcome & { sandbox?: SandboxFacts }): ForegroundResult {
767
+ const output = (stream: StreamOutput): StreamOutput => ({
768
+ text: stream.text,
769
+ truncated: stream.truncated,
770
+ ...(stream.spillPath !== undefined ? { spillPath: stream.spillPath } : {})
771
+ });
772
+ return {
773
+ kind: "foreground",
774
+ exitCode: result.exitCode,
775
+ signal: result.signal,
776
+ timedOut: result.timedOut,
777
+ aborted: result.aborted,
778
+ timeoutMs: result.timeoutMs,
779
+ stdout: output(result.stdout),
780
+ stderr: output(result.stderr),
781
+ ...(result.sandbox !== undefined ? { sandbox: result.sandbox } : {})
782
+ };
783
+ }
784
+
785
+ const BACKGROUND_OUTPUT_PROPERTIES: Record<string, JsonSchemaNode> = {
786
+ kind: { type: "string", required: true, const: "background" },
787
+ jobId: { type: "string", required: true }
788
+ };
789
+
790
+ /**
791
+ * Persist one config path through the host settings service.
792
+ *
793
+ * Shared by the model tool's `defaultShell` write and the browser terminal's
794
+ * activation switches, because the line-dependent part is the whole difficulty:
795
+ * ≤0.1.6 loaders do not register a plugin's settings namespace automatically, so
796
+ * the first `mutate` fails with "not registered" and the caller has to register it
797
+ * (with the written value as the base, so the retry sees it) and retry. On rc.1+
798
+ * the namespace is already owned by the loader, that branch never fires, and the
799
+ * plain `mutate` is the whole story.
800
+ * @param svc - the host `settings` service (untyped: shapes differ per line).
801
+ * @param path - the config path inside this plugin's entry (one level today).
802
+ * @throws when the line has no `mutate` at all - the caller reports it, and the
803
+ * value then applies for this process only.
804
+ */
805
+ export async function persistConfigValue(svc: unknown, path: readonly string[], value: unknown): Promise<void> {
806
+ const service = svc as {
807
+ mutate?: (id: string, ops: { op: "set"; path: string[]; value: unknown }[]) => Promise<unknown>;
808
+ register?: (id: string, schema: unknown, opts?: unknown) => unknown;
809
+ };
810
+ if (typeof service?.mutate !== "function") {
811
+ throw new Error(
812
+ "settings service exposes no mutate on this host line - the value applies for this process only; persist via cordis.patch.yml"
813
+ );
814
+ }
815
+ const ops = [{ op: "set" as const, path: [...path], value }];
816
+ try {
817
+ await service.mutate(ENTRY_ID, ops);
818
+ } catch (e) {
819
+ const message = e instanceof Error ? e.message : String(e);
820
+ if (!/not registered/i.test(message) || typeof service.register !== "function") {
821
+ throw e;
822
+ }
823
+ console.warn(`[dsh-bash-terminal-ts] legacy line: registering settings namespace ${ENTRY_ID}`);
824
+ service.register(ENTRY_ID, Config, { base: { [path.join(".")]: value } });
825
+ await service.mutate(ENTRY_ID, ops);
826
+ console.warn("[dsh-bash-terminal-ts] legacy settings namespace registered");
827
+ }
828
+ }
829
+
830
+ // ---- plugin -------------------------------------------------------------------
831
+
832
+ export function apply(ctx: BashTerminalContext, config: Partial<ConfigValues> = {}): void {
833
+ // Pinned backup POSIX runtime payload: opt-in, its OWN backend slot. A
834
+ // detected WSL distro is an advisory note only (the official menu lists both
835
+ // side by side, so our picker must not be stricter); the digest gate is the
836
+ // only hard no: an unverified payload simply does not run.
837
+ let payloadBash: string | undefined;
838
+ const payloadSuppressed = false;
839
+ if (config.enablePosixPayload === true && process.platform === "win32") {
840
+ const outcome = resolvePayloadBash({ payloadBashPath: config.payloadPosixPath ?? "" });
841
+ if (outcome.engaged) payloadBash = outcome.bashPath;
842
+ for (const note of outcome.notes) ctx.logger?.warn?.(`dsh-bash-terminal-ts: ${note}`);
843
+ }
844
+ const paths = resolveAllPaths(config, process.env, payloadBash);
845
+ // 0.1.7: `defaultShell` is a `.volatile()` config field — the loader hands
846
+ // `apply` a live ref and the latest value is resolved on every read; there
847
+ // is no settings registration call anymore (removed with the 0.1.7 host).
848
+ // compat-legacy: ≤0.1.6 的宿主没有配置热重载,bridge 写入走这个覆盖值
849
+ // (rc.1+ 上 volatile 与覆盖值同源同写,二者一致)。
850
+ let shellOverride: string | undefined;
851
+ /** The stored value, verbatim - including one that is no longer selectable. */
852
+ const storedShell = (): string => {
853
+ if (typeof shellOverride === "string" && (SHELLS as readonly string[]).includes(shellOverride)) {
854
+ return shellOverride;
855
+ }
856
+ const v = config.defaultShell as string | VolatileRef<string> | undefined;
857
+ if (typeof v === "string") return v;
858
+ const got = typeof v?.get === "function" ? v.get() : undefined;
859
+ return typeof got === "string" ? got : DEFAULT_SHELL;
860
+ };
861
+ let warnedStale = false;
862
+ /**
863
+ * The shell the TOOL will run. Deliberately the stored value, un-sanitised:
864
+ * `buildArgv`/`terminalArgv` throw for anything outside SHELLS, so an
865
+ * out-of-enum choice fails closed at call time rather than quietly running the
866
+ * command in a different shell than the model was told about.
867
+ */
868
+ const currentShell = storedShell;
869
+ /**
870
+ * The activation switches are ONE truth: a switch off hides the backend from
871
+ * the dock AND makes it an invalid shell-tool target (powershell is the
872
+ * floor and always on). A stored defaultShell pointing at a switched-off
873
+ * backend is therefore stale, not executable.
874
+ */
875
+ const switchOn = (shell: string): boolean => {
876
+ const read = <T>(v: T | VolatileRef<T> | undefined, fallback: T): T =>
877
+ typeof v === "object" && v !== null && typeof (v as VolatileRef<T>).get === "function"
878
+ ? ((v as VolatileRef<T>).get() ?? fallback)
879
+ : ((v as T | undefined) ?? fallback);
880
+ if (shell === "powershell") return true;
881
+ if (shell === "gitbash") return read(config.shellGitBash as boolean | undefined, true);
882
+ if (shell === "msys2") return read(config.shellMsys2 as boolean | undefined, true);
883
+ if (shell === "wsl") return read(config.shellWsl as boolean | undefined, true);
884
+ if (shell === "payload") return read(config.shellPayload as boolean | undefined, false);
885
+ if (shell === "niu") return read(config.shellNiu as boolean | undefined, true);
886
+ return false;
887
+ };
888
+ /**
889
+ * What the model is TOLD. Sanitised, because this one runs on every prompt
890
+ * assembly: an invalid stored value must not break the whole prompt, and naming
891
+ * the floor is honest about what a successful call would use.
892
+ */
893
+ const describedShell = (): string => {
894
+ const stored = storedShell();
895
+ if ((SHELLS as readonly string[]).includes(stored) && switchOn(stored)) return stored;
896
+ if (!warnedStale) {
897
+ warnedStale = true;
898
+ ctx.logger?.warn?.(`dsh-bash-terminal-ts: defaultShell ${JSON.stringify(stored)} is not a selectable/activated backend; shell calls will fail closed and the bottom terminal falls back to ${DEFAULT_SHELL}`);
899
+ }
900
+ return DEFAULT_SHELL;
901
+ };
902
+
903
+ // The browser terminal (bottom dock / embedded shell). Mounted BEFORE the
904
+ // win32 return below: the model tool is Windows-only, the terminal is not
905
+ // (finding F1). Its routes report their own availability, so a host without
906
+ // `registerUpgrade` or without any PTY backend shows a reason instead of a
907
+ // dead panel.
908
+ const browserTerminals = mountBrowserTerminals({
909
+ ctx: ctx as never,
910
+ config: config as Record<string, unknown>,
911
+ paths,
912
+ configuredShell: storedShell,
913
+ payloadSuppressed: () => payloadSuppressed,
914
+ persist: async (svc, path, value) => {
915
+ await persistConfigValue(svc, path, value);
916
+ // ≤0.1.6 hosts have no config hot-reload, so mirror a defaultShell write into
917
+ // the same in-process override the legacy bridge uses. Without it, choosing a
918
+ // shell in the bottom-terminal section would only reach the model tool after
919
+ // a restart - the exact divergence the bridge's `shellOverride` exists to kill.
920
+ if (path.length === 1 && path[0] === "defaultShell" && typeof value === "string") {
921
+ shellOverride = value;
922
+ }
923
+ },
924
+ });
925
+ ctx.effect(() => () => browserTerminals.dispose(), "bash-terminal: browser terminal teardown");
926
+
927
+ if (process.platform !== "win32") {
928
+ ctx.logger?.info?.("dsh-bash-terminal-ts: only meaningful on win32; skipping tool registration");
929
+ return;
930
+ }
931
+ const backgroundEnabled = true;
932
+ // R5/R6 and finding F8: an invalid stored value used to throw here, which failed
933
+ // the whole entry - the tool, the settings row and the browser terminal all
934
+ // disappeared. The entry now stays mounted, the tool fails closed per call, and
935
+ // the browser terminal substitutes the floor and says so.
936
+ /** Official sandbox-escalation surface (mirrors tool-bash): advertise the
937
+ * escalation modes whenever the deployment confines. */
938
+ const escalationModes = ESCALATION_TARGETS;
939
+ const approveShellEscalation = (
940
+ mode: string,
941
+ justification: string,
942
+ exec: ToolRunContext,
943
+ standingPolicy: SandboxPolicy
944
+ ): Promise<string> => {
945
+ return approveEscalation({
946
+ requestedMode: mode,
947
+ justification,
948
+ effectiveMode: standingPolicy.mode,
949
+ subject: "command"
950
+ }, {
951
+ approver: ctx.get("approval"),
952
+ agent: exec.agent,
953
+ callId: exec.callId,
954
+ toolName: "shell",
955
+ signal: exec.signal
956
+ });
957
+ };
958
+
959
+ ctx.systemPrompt.section({
960
+ name: "tool:bash-terminal",
961
+ order: 105,
962
+ text: "Use the shell tool for terminal commands: it runs in the terminal the user chose in Settings -> General -> Default terminal (PowerShell, Git Bash, MSYS2, or WSL) and honors the DSH sandbox. Prefer it over the pwsh tool for everyday commands; keep the pwsh tool for cases that specifically need the sandboxed PowerShell surface."
963
+ });
964
+
965
+ // compat-legacy: 六线统一配置通道(≤0.1.6 无 client-store 模块表,client 走本
966
+ // bridge 读写 defaultShell)。写路径 = settings.mutate;≤0.1.6 的 loader 不会自动
967
+ // 注册命名空间,复用 perm-gate 自门控(not registered → register → 重试);
968
+ // rc.1+ 命名空间由 loader 占用,该分支自然不命中。GET 带回当前值与可选集。
969
+ // 宿主 context 类型未收录 inject/局部服务形状,compat 桥按宽化面调用。
970
+ // 窄面型只覆盖本桥用到的三个字段,避免 any 外泄。
971
+ interface BridgeReq {
972
+ socket?: { remoteAddress?: string };
973
+ method?: string;
974
+ on(event: "data", cb: (chunk: Buffer) => void): void;
975
+ on(event: "end", cb: () => void): void;
976
+ }
977
+ interface BridgeRes {
978
+ writeHead(status: number, headers: Record<string, string>): void;
979
+ end(body: string): void;
980
+ }
981
+ type BridgeSvcCtx = {
982
+ settings: unknown;
983
+ webServer: { register: (route: { kind: string; path: string; handler: (req: BridgeReq, res: BridgeRes) => void }) => () => void };
984
+ effect: (fn: () => (() => void) | void, label?: string) => void;
985
+ };
986
+ const compatCtx = ctx as unknown as { inject?: (deps: string[], fn: (svcCtx: BridgeSvcCtx) => void) => void };
987
+ if (typeof compatCtx.inject !== "function") {
988
+ // A context without `inject` (a bare mock, or a host that resolves services
989
+ // only synchronously) cannot receive the bridge at all. Skipping it must not
990
+ // take the tool down with it - the tool is what the model calls.
991
+ ctx.logger?.warn?.("dsh-bash-terminal-ts: ctx.inject unavailable - the settings bridge is not mounted (defaultShell reads still work, writes will not)");
992
+ } else compatCtx.inject(["webServer", "settings"], (svcCtx: BridgeSvcCtx) => {
993
+ const svc = svcCtx.settings;
994
+ const writeShell = async (value: string): Promise<void> => {
995
+ // One implementation for every config write (the browser terminal's switches
996
+ // go through the same helper), so the legacy self-registration dance exists
997
+ // in exactly one place.
998
+ await persistConfigValue(svc, ["defaultShell"], value);
999
+ shellOverride = value;
1000
+ };
1001
+ svcCtx.effect(
1002
+ () => {
1003
+ const json = (res: unknown, status: number, body: unknown): void => {
1004
+ (res as { writeHead: (s: number, h: Record<string, string>) => void; end: (b: string) => void }).writeHead(status, { "content-type": "application/json; charset=utf-8" });
1005
+ (res as { end: (b: string) => void }).end(JSON.stringify(body));
1006
+ };
1007
+ const handler = (req: BridgeReq, res: BridgeRes): void => {
1008
+ const addr = req.socket?.remoteAddress ?? "";
1009
+ if (addr !== "127.0.0.1" && addr !== "::1" && addr !== "::ffff:127.0.0.1") {
1010
+ json(res, 403, { ok: false, code: "loopback-only" });
1011
+ return;
1012
+ }
1013
+ if (req.method === "GET") {
1014
+ // 缝内省:compat 验证用——当前线 ctx.subprocess 的真实能力面
1015
+ const seam = ctx as unknown as { subprocess?: Record<string, unknown> };
1016
+ const sp = seam.subprocess as { spawn?: unknown; spawnTerminal?: unknown } | undefined;
1017
+ json(res, 200, {
1018
+ ok: true,
1019
+ value: {
1020
+ defaultShell: currentShell(),
1021
+ shells: SHELLS,
1022
+ seam: { spawn: typeof sp?.spawn, spawnTerminal: typeof sp?.spawnTerminal },
1023
+ },
1024
+ });
1025
+ return;
1026
+ }
1027
+ if (req.method !== "POST") {
1028
+ json(res, 405, { ok: false, code: "method-not-allowed" });
1029
+ return;
1030
+ }
1031
+ const chunks: Buffer[] = [];
1032
+ let size = 0;
1033
+ req.on("data", (c: Buffer) => {
1034
+ size += c.length;
1035
+ if (size <= 65536) chunks.push(c);
1036
+ });
1037
+ req.on("end", () => {
1038
+ let body: { defaultShell?: unknown };
1039
+ try {
1040
+ body = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
1041
+ } catch {
1042
+ json(res, 400, { ok: false, code: "bad-json" });
1043
+ return;
1044
+ }
1045
+ const value = typeof body.defaultShell === "string" ? body.defaultShell : "";
1046
+ if (!(SHELLS as readonly string[]).includes(value)) {
1047
+ json(res, 400, { ok: false, code: "invalid-shell" });
1048
+ return;
1049
+ }
1050
+ void writeShell(value)
1051
+ .then(() => json(res, 200, { ok: true, value: { defaultShell: value } }))
1052
+ .catch((e: unknown) => json(res, 500, { ok: false, code: "write-failed", message: e instanceof Error ? e.message : String(e) }));
1053
+ });
1054
+ };
1055
+ const registered = [
1056
+ svcCtx.webServer.register({ kind: "exact", path: "/api/bash-terminal/config", handler }),
1057
+ ];
1058
+ return () => {
1059
+ for (const dispose of registered) dispose();
1060
+ };
1061
+ }, "bash-terminal: compat config bridge");
1062
+ });
1063
+
1064
+ const toolName = "shell";
1065
+ const terminalRegistry = createTerminalRegistry(ctx);
1066
+ // The interactive terminal obeys the SAME activation gate as the shell tool:
1067
+ // the getter throws for a switched-off backend, so a session cannot open on
1068
+ // a shell the user just disabled.
1069
+ ctx.tools.register(terminalTool(ctx, terminalRegistry, paths, () => {
1070
+ const shell = currentShell();
1071
+ if ((SHELLS as readonly string[]).includes(shell) && !switchOn(shell)) {
1072
+ throw new Error(`dsh-bash-terminal-ts: ${shell} backend is not activated - enable its switch in the plugin settings first.`);
1073
+ }
1074
+ return shell;
1075
+ }));
1076
+
1077
+ // The model-facing description must track the user's chosen default
1078
+ // terminal: a static description listing every backend leaves the model
1079
+ // guessing which syntax applies. Re-render it on every prompt assembly —
1080
+ // settings are hot-reloaded, so a change shows up on the next request
1081
+ // without a restart.
1082
+ ctx.on("system-prompt/assemble", async (_assembly, _context, next) => {
1083
+ const assembled = await next();
1084
+ const description = toolDescription(backgroundEnabled, describedShell());
1085
+ const tools = Array.isArray(assembled.tools)
1086
+ ? assembled.tools.map((tool) => (tool.name === toolName ? { ...tool, description } : tool))
1087
+ : assembled.tools;
1088
+ return { ...assembled, tools };
1089
+ });
1090
+
1091
+ ctx.tools.register(defineTool<ShellToolResult>({
1092
+ name: toolName,
1093
+ description: toolDescription(backgroundEnabled, currentShell()),
1094
+ parameters: {
1095
+ command: {
1096
+ type: "string",
1097
+ required: true,
1098
+ description: "The command to execute in the selected terminal."
1099
+ },
1100
+ description: {
1101
+ type: "string",
1102
+ required: true,
1103
+ description: "Clear, concise description of what this command does in active voice, 5-10 words (shown in the UI). Examples: \"ls\" -> \"List files in current directory\"; \"git status\" -> \"Show working tree status\"; \"npm install\" -> \"Install package dependencies\"."
1104
+ },
1105
+ distro: {
1106
+ type: "string",
1107
+ description: "WSL distribution to use (only when the configured default terminal is wsl). Defaults to the system default distribution."
1108
+ },
1109
+ sandbox_permissions: {
1110
+ type: "string",
1111
+ enum: escalationModes,
1112
+ description: "The wider sandbox mode this command needs. Only valid as a one-shot retry of a command the sandbox just denied; requires justification and user approval."
1113
+ },
1114
+ justification: {
1115
+ type: "string",
1116
+ description: "Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access."
1117
+ },
1118
+ workdir: {
1119
+ type: "string",
1120
+ description: "Working directory for this command. Defaults to the session workspace; a relative path is resolved against it."
1121
+ },
1122
+ timeoutMs: {
1123
+ type: "number",
1124
+ description: "Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry."
1125
+ },
1126
+ run_in_background: {
1127
+ type: "boolean",
1128
+ description: "Run in the background and return a job id immediately (collect with job_output, stop with job_kill). No timeout applies."
1129
+ }
1130
+ },
1131
+ output: {
1132
+ schema: {
1133
+ oneOf: [
1134
+ { type: "object", additionalProperties: false, properties: BACKGROUND_OUTPUT_PROPERTIES },
1135
+ {
1136
+ type: "object",
1137
+ additionalProperties: false,
1138
+ properties: {
1139
+ kind: { type: "string", required: true, const: "foreground" },
1140
+ exitCode: { required: true, oneOf: [{ type: "integer" }, { type: "null" }] },
1141
+ signal: { required: true, oneOf: [{ type: "string" }, { type: "null" }] },
1142
+ timedOut: { type: "boolean", required: true },
1143
+ aborted: { type: "boolean", required: true },
1144
+ timeoutMs: { type: "number", required: true },
1145
+ sandbox: {
1146
+ type: "object",
1147
+ additionalProperties: false,
1148
+ properties: {
1149
+ mode: { type: "string", required: true },
1150
+ enforcement: { type: "string", required: true },
1151
+ denied: { type: "boolean" }
1152
+ }
1153
+ },
1154
+ stdout: {
1155
+ type: "object",
1156
+ additionalProperties: false,
1157
+ required: true,
1158
+ properties: {
1159
+ text: { type: "string", required: true },
1160
+ truncated: { type: "boolean", required: true },
1161
+ spillPath: { type: "string" }
1162
+ }
1163
+ },
1164
+ stderr: {
1165
+ type: "object",
1166
+ additionalProperties: false,
1167
+ required: true,
1168
+ properties: {
1169
+ text: { type: "string", required: true },
1170
+ truncated: { type: "boolean", required: true },
1171
+ spillPath: { type: "string" }
1172
+ }
1173
+ }
1174
+ }
1175
+ }
1176
+ ]
1177
+ },
1178
+ render: (_args, value) => {
1179
+ if (value.kind === "background") return [{ type: "text", text: `started background job ${value.jobId}` }];
1180
+ let text = renderResult(value);
1181
+ if (value.sandbox?.denied === true) {
1182
+ if (!text.endsWith("\n")) text += "\n";
1183
+ text += sandboxDenialMarker(value.sandbox.mode) + "\n" + escalationHintMarker("command");
1184
+ }
1185
+ return [{ type: "text", text }];
1186
+ }
1187
+ },
1188
+ async execute(args, exec) {
1189
+ const v = validateArgs(args);
1190
+ const shell = currentShell();
1191
+ if ((SHELLS as readonly string[]).includes(shell) && !switchOn(shell)) {
1192
+ throw new Error(`dsh-bash-terminal-ts: ${shell} backend is not activated - ask the user to enable its switch in the plugin settings (bottom terminal), or choose another default terminal.`);
1193
+ }
1194
+ const argv0 = buildArgv(shell, v.command, paths, v.distro);
1195
+ if (argv0[0] === undefined) {
1196
+ throw new Error(`dsh-bash-terminal-ts: ${shell} backend unavailable - executable not found. Install it or set the corresponding *Path config.`);
1197
+ }
1198
+ // Only element 0 (the resolved executable) can be undefined; guarded above.
1199
+ const argv = argv0 as string[];
1200
+ const workdir = resolveWorkdir(v.workdir, exec);
1201
+ const timeoutMs = clampTimeout(v.timeoutMs, config.timeoutMs ?? DEFAULT_TIMEOUT_MS, config.maxTimeoutMs ?? MAX_TIMEOUT_MS, "shell timeoutMs");
1202
+ const dshEnv = ctx.shellEnv.collect(exec);
1203
+ const env = buildEnv(shell, dshEnv);
1204
+ let policy = ctx.sandboxPolicy.resolve(exec.agent ? { session: exec.agent.session } : {});
1205
+ if (v.sandbox_permissions !== undefined && v.justification !== undefined) {
1206
+ const approvedMode = await approveShellEscalation(v.sandbox_permissions, v.justification, exec, policy);
1207
+ policy = { ...policy, mode: approvedMode };
1208
+ }
1209
+ const { argv: confinedArgv, sandbox } = confineSpawn(ctx, argv, policy, shell);
1210
+ const resolved: SpawnResolution = {
1211
+ command: v.command,
1212
+ workdir: workdir ?? process.cwd(),
1213
+ timeoutMs,
1214
+ stdoutMaxBytes: DEFAULT_MAX_OUTPUT_BYTES,
1215
+ ...(v.stdin !== undefined ? { stdin: v.stdin } : {})
1216
+ };
1217
+ if (v.run_in_background === true) {
1218
+ const jobs = ctx.get("jobs") as JobsRegistry | undefined;
1219
+ if (jobs === undefined) throw new Error("background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs");
1220
+ if (exec.signal.aborted) {
1221
+ const error = new HarnessError("tool call aborted", TOOL_ABORTED);
1222
+ error.name = "AbortError";
1223
+ throw error;
1224
+ }
1225
+ return {
1226
+ kind: "background",
1227
+ jobId: jobs.start({
1228
+ kind: `shell/${shell}`,
1229
+ label: v.command,
1230
+ ...(exec.agent ? { owner: exec.agent } : {}),
1231
+ run: () => {
1232
+ const proc = startBackground(ctx, confinedArgv, resolved, env, exec.signal);
1233
+ return {
1234
+ cancel: () => void proc.kill(),
1235
+ done: proc.done.then(() => processOutcome(proc)),
1236
+ readOutput: () => renderProcessRead(proc.readOutput())
1237
+ };
1238
+ }
1239
+ })
1240
+ };
1241
+ }
1242
+ const result = await runForeground(ctx, confinedArgv, resolved, env, exec.signal, timeoutMs);
1243
+ if (result.aborted) {
1244
+ const error = new HarnessError("tool call aborted", TOOL_ABORTED);
1245
+ error.name = "AbortError";
1246
+ throw error;
1247
+ }
1248
+ const denied = sandbox?.denialSignatures !== undefined
1249
+ ? sandbox.denialSignatures.some((sig) => result.stderr.text.toLowerCase().includes(sig.toLowerCase()))
1250
+ : false;
1251
+ return canonicalResult({
1252
+ ...result,
1253
+ ...(sandbox !== undefined ? { sandbox: { mode: sandbox.mode, enforcement: sandbox.enforcement, denied } } : {})
1254
+ });
1255
+ },
1256
+ presentCall: (args) => {
1257
+ if (args.run_in_background === true) {
1258
+ return {
1259
+ card: "generic",
1260
+ title: args.command as string,
1261
+ kind: "execute",
1262
+ rawInput: args.command,
1263
+ content: [{ type: "text", text: args.description as string }]
1264
+ };
1265
+ }
1266
+ return {
1267
+ card: "terminal",
1268
+ title: args.command as string,
1269
+ description: args.description as string,
1270
+ ...(args.workdir !== undefined ? { cwd: args.workdir } : {})
1271
+ };
1272
+ },
1273
+ presentResult: (args, result) => {
1274
+ const block = result.content.length === 1 ? result.content[0] : undefined;
1275
+ if (block === undefined || block.type !== "text") return undefined;
1276
+ const raw = block.text ?? "";
1277
+ if (args.run_in_background === true || result.isError) {
1278
+ return { card: "generic", content: [{ type: "text", text: "```console\n" + raw.replace(/\n+$/, "") + "\n```" }] };
1279
+ }
1280
+ const { body, ...exit } = parseExitStatus(raw);
1281
+ return { card: "terminal", output: body, ...exit };
1282
+ }
1283
+ }));
1284
+ }
1285
+
1286
+ //#region internals for tests
1287
+ export const internals = {
1288
+ candidateExists,
1289
+ resolveAllPaths,
1290
+ resolveWorkdir,
1291
+ renderResult,
1292
+ processOutcome,
1293
+ startBackground,
1294
+ runForeground,
1295
+ spawnSpec,
1296
+ buildEnv,
1297
+ buildArgv,
1298
+ validateArgs,
1299
+ toolDescription,
1300
+ SHELL_DESCRIPTIONS,
1301
+ DEFAULT_TIMEOUT_MS,
1302
+ MAX_TIMEOUT_MS,
1303
+ DEFAULT_MAX_OUTPUT_BYTES
1304
+ };
1305
+ //#endregion
1306
+
1307
+ // re-export for plugin consumers (type-only)
1308
+ export type {
1309
+ ExecAgent,
1310
+ JobsRegistry,
1311
+ JsonSchemaNode,
1312
+ SandboxFacts,
1313
+ SandboxPolicy,
1314
+ ShellId,
1315
+ ToolRunContext
1316
+ };