dsh-bash-terminal-ts 0.5.0 → 0.5.2

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.
package/lib/index.js CHANGED
@@ -1,759 +1,759 @@
1
- // dsh-bash-terminal - 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
- import { lstatSync } from "node:fs";
25
- import { isAbsolute, join, resolve } from "node:path";
26
- import { ESCALATION_TARGETS, TOOL_ABORTED, approveEscalation, defineTool, escalationHintMarker, clampTimeout, deadline, parseExitStatus, timeoutOf, sandboxDenialMarker, validateEscalationArgs, z, HarnessError } from "./dsh.js";
27
- import { createTerminalRegistry, terminalTool } from "./terminal.js";
28
- /** Stable Cordis plugin name. */
29
- export const name = "bash-terminal";
30
- /** Services required before the tool can register. */
31
- export const inject = ["tools", "systemPrompt", "shellEnv", "subprocess", "settings", "sandbox", "sandboxPolicy"];
32
- /** The terminal backends this tool exposes, in catalog order. */
33
- export const SHELLS = ["powershell", "gitbash", "msys2", "wsl"];
34
- /** The backend used when the caller does not name one. */
35
- export const DEFAULT_SHELL = "powershell";
36
- /** Settings namespace backing the user-chosen default terminal. */
37
- export const SETTINGS_NAMESPACE = "bash-terminal";
38
- /** Default per-command timeout (ms). */
39
- const DEFAULT_TIMEOUT_MS = 120000;
40
- /** Upper bound a caller's timeoutMs is capped to. */
41
- const MAX_TIMEOUT_MS = 600000;
42
- /** SIGTERM->SIGKILL grace (ms), matching dsh-bash-local's default. */
43
- const DEFAULT_GRACE_MS = 3000;
44
- /** Per-stream in-memory cap before spilling (bytes). */
45
- const DEFAULT_MAX_OUTPUT_BYTES = 64 * 1024;
46
- /** Per-stream spill file cap (bytes). */
47
- const DEFAULT_MAX_SPILL_BYTES = 64 * 1024 * 1024;
48
- /** Timeout code stamped on the deadline's TimeoutReason. */
49
- const TIMEOUT_CODE = "SHELL_TIMEOUT";
50
- /** Model-friendly environment overrides (same set dsh-bash-local hardcodes). */
51
- const ENV_OVERRIDES = {
52
- NO_COLOR: "1",
53
- TERM: "dumb",
54
- PAGER: "cat",
55
- GIT_PAGER: "cat"
56
- };
57
- /** Runtime configuration schema. */
58
- export const Config = z.object({
59
- defaultShell: z.string().default(DEFAULT_SHELL),
60
- timeoutMs: z.number().default(DEFAULT_TIMEOUT_MS),
61
- maxTimeoutMs: z.number().default(MAX_TIMEOUT_MS),
62
- pwshPath: z.string().default(""),
63
- gitBashPath: z.string().default(""),
64
- msys2Path: z.string().default(""),
65
- wslPath: z.string().default("")
66
- });
67
- // ---- executable resolution ------------------------------------------------
68
- function candidateExists(candidate) {
69
- try {
70
- const stat = lstatSync(candidate);
71
- return stat.isFile() || stat.isSymbolicLink();
72
- }
73
- catch {
74
- return false;
75
- }
76
- }
77
- function resolveFromCandidates(candidates) {
78
- for (const candidate of candidates) {
79
- if (candidateExists(candidate))
80
- return candidate;
81
- }
82
- return undefined;
83
- }
84
- /** Well-known PowerShell install locations plus PATH entries, newest first. */
85
- export function candidatePwshPaths(env = process.env) {
86
- const programFiles = env.ProgramFiles ?? "C:\\Program Files";
87
- const systemRoot = env.SystemRoot ?? "C:\\Windows";
88
- const candidates = [join(programFiles, "PowerShell", "7", "pwsh.exe")];
89
- for (const entry of (env.PATH ?? "").split(";")) {
90
- const trimmed = entry.trim().replace(/^"|"$/g, "");
91
- if (trimmed.length === 0)
92
- continue;
93
- candidates.push(join(trimmed, "pwsh.exe"));
94
- }
95
- candidates.push(join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"));
96
- return candidates;
97
- }
98
- /**
99
- * Git for Windows locations, then PATH bash.exe entries EXCLUDING the
100
- * System32 launcher (c:\\windows\\system32\\bash.exe is the WSL
101
- * forwarder, not a Git Bash shell).
102
- */
103
- export function candidateGitBashPaths(env = process.env) {
104
- const programFiles = env.ProgramFiles ?? "C:\\Program Files";
105
- const systemRoot = (env.SystemRoot ?? "C:\\Windows").toLowerCase();
106
- const localAppData = env.LOCALAPPDATA ?? "";
107
- const candidates = [
108
- join(programFiles, "Git", "bin", "bash.exe"),
109
- join(programFiles, "Git", "usr", "bin", "bash.exe")
110
- ];
111
- if (localAppData.length > 0)
112
- candidates.push(join(localAppData, "Programs", "Git", "bin", "bash.exe"));
113
- for (const entry of (env.PATH ?? "").split(";")) {
114
- const trimmed = entry.trim().replace(/^"|"$/g, "");
115
- if (trimmed.length === 0)
116
- continue;
117
- if (trimmed.toLowerCase().includes(systemRoot))
118
- continue;
119
- candidates.push(join(trimmed, "bash.exe"));
120
- }
121
- return candidates;
122
- }
123
- /**
124
- * MSYS2 locations, in preference order: the real `bash.exe` under usr\bin
125
- * first, then bin\bash.exe, and `msys2.exe` dead last.
126
- *
127
- * msys2.exe is NOT a usable backend for piped execution: it is the console-
128
- * allocating Cygwin launcher, so a spawn with piped stdio returns exit 0 with
129
- * zero bytes on both stdout and stderr (measured on this machine against
130
- * MSYS2 with bash 5.3.15). Keeping it in the list only as a last-resort
131
- * fallback preserves the path the config docs reference, but a working
132
- * bash.exe always wins.
133
- *
134
- * MSYS2 uses the same Cygwin/MSYS2 runtime as Git Bash, so it cannot run
135
- * under the DSH Windows ACL restricted-token sandbox.
136
- */
137
- export function candidateMsys2Paths(env = process.env) {
138
- const candidates = [
139
- "C:\\msys64\\usr\\bin\\bash.exe",
140
- "C:\\msys64\\bin\\bash.exe"
141
- ];
142
- for (const entry of (env.PATH ?? "").split(";")) {
143
- const trimmed = entry.trim().replace(/^"|"$/g, "");
144
- if (trimmed.length === 0)
145
- continue;
146
- const lower = trimmed.toLowerCase();
147
- if (lower.includes("msys64") || lower.includes("mingw64")) {
148
- candidates.push(join(trimmed, "bash.exe"));
149
- }
150
- }
151
- candidates.push("C:\\msys64\\msys2.exe"); // last resort: see the note above
152
- return candidates;
153
- }
154
- export function defaultWslPath(env = process.env) {
155
- const systemRoot = env.SystemRoot ?? "C:\\Windows";
156
- return join(systemRoot, "System32", "wsl.exe");
157
- }
158
- export function resolveAllPaths(config = {}, env = process.env) {
159
- const pwsh = config.pwshPath && config.pwshPath.trim().length > 0
160
- ? config.pwshPath
161
- : resolveFromCandidates(candidatePwshPaths(env));
162
- const gitbash = config.gitBashPath && config.gitBashPath.trim().length > 0
163
- ? config.gitBashPath
164
- : resolveFromCandidates(candidateGitBashPaths(env));
165
- const msys2 = config.msys2Path && config.msys2Path.trim().length > 0
166
- ? config.msys2Path
167
- : resolveFromCandidates(candidateMsys2Paths(env));
168
- const wsl = config.wslPath && config.wslPath.trim().length > 0
169
- ? config.wslPath
170
- : defaultWslPath(env);
171
- return { pwsh, gitbash, msys2, wsl };
172
- }
173
- // ---- argv / env construction ------------------------------------------------
174
- export function buildArgv(shell, command, paths, distro) {
175
- switch (shell) {
176
- case "powershell":
177
- return [paths.pwsh, "-NoLogo", "-NoProfile", "-NonInteractive", "-Command", command];
178
- case "gitbash":
179
- return [paths.gitbash, "-lc", command];
180
- case "msys2":
181
- // -lc, not -c: a login shell sources /etc/profile, which is what puts
182
- // /usr/bin and /mingw64/bin on PATH. With a bare -c, `tr`, `sed`, `gcc`
183
- // and friends are all "command not found".
184
- return [paths.msys2, "-lc", command];
185
- case "wsl": {
186
- const distroArg = distro !== undefined && distro.trim().length > 0 ? ["-d", distro.trim()] : [];
187
- return [paths.wsl, ...distroArg, "-e", "bash", "-lc", command];
188
- }
189
- default:
190
- throw new Error(`invalid shell: ${JSON.stringify(shell)} (expected one of ${SHELLS.join(", ")})`);
191
- }
192
- }
193
- /**
194
- * Merge the DSH_* environment over the process environment. For WSL, only
195
- * variables explicitly listed in WSLENV cross the boundary, so every DSH_*
196
- * key is appended there — and the list is *layered onto* whatever WSLENV the
197
- * host already had (Windows Terminal exports e.g. `WT_SESSION:WT_PROFILE_ID:`),
198
- * never rebuilt from scratch: WSLENV is an allow-list, so dropping the
199
- * inherited entries would silently stop them crossing into WSL.
200
- *
201
- * @param inheritedWslenv - the ambient WSLENV to layer onto. Callers that
202
- * replace the child environment wholesale (the PTY path) must pass
203
- * `process.env.WSLENV` explicitly, because the ambient value is not visible
204
- * through `dshEnv`.
205
- */
206
- export function buildEnv(shell, dshEnv, inheritedWslenv = process.env.WSLENV) {
207
- const env = { ...ENV_OVERRIDES, ...dshEnv };
208
- if (shell === "msys2") {
209
- // Picks the MINGW64 environment, so /mingw64/bin (gcc, make, ...) joins
210
- // PATH via /etc/profile. Without it MSYS2 defaults to the bare MSYS
211
- // environment. An explicit caller-supplied value wins.
212
- if (env.MSYSTEM === undefined)
213
- env.MSYSTEM = "MINGW64";
214
- }
215
- if (shell === "wsl") {
216
- const keys = Object.keys(dshEnv ?? {});
217
- if (keys.length > 0) {
218
- // An explicit WSLENV in dshEnv wins over the inherited one; otherwise the
219
- // inherited value is the base. Either way the base is SPLIT into entries
220
- // (the host value ends with a trailing ":", so string concatenation would
221
- // produce a malformed empty entry) and the WSLENV key itself is excluded
222
- // (it is a key of dshEnv too, and appending it would add a bogus entry).
223
- const declared = Object.prototype.hasOwnProperty.call(dshEnv ?? {}, "WSLENV");
224
- const base = declared
225
- ? env.WSLENV
226
- : (typeof inheritedWslenv === "string" && inheritedWslenv.length > 0 ? inheritedWslenv : env.WSLENV);
227
- const parts = typeof base === "string" ? base.split(":") : [];
228
- env.WSLENV = [...parts, ...keys.filter((k) => k !== "WSLENV").flatMap((k) => k.split(":"))]
229
- .map((p) => p.trim())
230
- .filter((p) => p.length > 0)
231
- .join(":");
232
- }
233
- }
234
- return env;
235
- }
236
- function spawnSpec(resolved, argv, env, signal) {
237
- const collect = (maxBytes) => ({ maxBytes, spill: { maxBytes: DEFAULT_MAX_SPILL_BYTES } });
238
- return {
239
- argv,
240
- cwd: resolved.workdir,
241
- stdio: {
242
- stdin: resolved.stdin !== undefined ? { data: resolved.stdin } : "ignore",
243
- stdout: collect(resolved.stdoutMaxBytes),
244
- stderr: collect(DEFAULT_MAX_OUTPUT_BYTES)
245
- },
246
- graceMs: DEFAULT_GRACE_MS,
247
- signal,
248
- env
249
- };
250
- }
251
- function collectedOutput(handle) {
252
- const { stdout, stderr } = handle.collected;
253
- if (!isCollectedStream(stdout) || !isCollectedStream(stderr)) {
254
- throw new Error("dsh-bash-terminal: subprocess implementation dropped a requested collect stream");
255
- }
256
- return { stdout, stderr };
257
- }
258
- function isCollectedStream(value) {
259
- return typeof value === "object" && value !== null && typeof value.readFrom === "function";
260
- }
261
- function finalOutput(reader) {
262
- const read = reader.readFrom(0);
263
- return {
264
- text: read.text,
265
- truncated: read.lossy,
266
- ...(read.spillPath !== undefined ? { spillPath: read.spillPath } : {})
267
- };
268
- }
269
- async function runForeground(ctx, argv, resolved, env, signal, timeoutMs) {
270
- const subprocess = requireSubprocess(ctx);
271
- const d = deadline(signal, timeoutMs, TIMEOUT_CODE);
272
- try {
273
- const handle = subprocess.spawn(spawnSpec(resolved, argv, env, d.signal));
274
- const outcome = await handle.done;
275
- const collected = collectedOutput(handle);
276
- const timedOut = timeoutOf(d.signal, TIMEOUT_CODE) !== undefined;
277
- const aborted = d.signal.aborted && !timedOut;
278
- return {
279
- exitCode: outcome.exitCode,
280
- signal: outcome.signal,
281
- timedOut,
282
- aborted,
283
- timeoutMs,
284
- stdout: finalOutput(collected.stdout),
285
- stderr: finalOutput(collected.stderr)
286
- };
287
- }
288
- finally {
289
- d[Symbol.dispose]();
290
- }
291
- }
292
- function requireSubprocess(ctx) {
293
- const subprocess = ctx.subprocess;
294
- if (subprocess === null) {
295
- throw new Error("dsh-bash-terminal: ctx.subprocess seam unavailable (missing inject service)");
296
- }
297
- return subprocess;
298
- }
299
- function startBackground(ctx, argv, resolved, env, signal) {
300
- const subprocess = requireSubprocess(ctx);
301
- const running = subprocess.spawn(spawnSpec(resolved, argv, env, signal));
302
- const collected = collectedOutput(running);
303
- let stdoutOffset = 0;
304
- let stderrOffset = 0;
305
- let spawnFailureNote;
306
- const consumeSpawnFailure = () => {
307
- const note = spawnFailureNote ?? "";
308
- spawnFailureNote = undefined;
309
- return note;
310
- };
311
- const proc = {
312
- status: "running",
313
- exitCode: null,
314
- signal: null,
315
- done: running.done.then((outcome) => {
316
- if (proc.status === "running") {
317
- proc.status = signal?.aborted === true || outcome.signal !== null ? "killed" : "completed";
318
- }
319
- proc.exitCode = outcome.exitCode;
320
- proc.signal = outcome.signal;
321
- }, (error) => {
322
- proc.status = "killed";
323
- spawnFailureNote = `spawn failed: ${String(error)}`;
324
- }),
325
- readOutput: () => {
326
- const out = collected.stdout.readFrom(stdoutOffset);
327
- const err = collected.stderr.readFrom(stderrOffset);
328
- stdoutOffset = out.nextOffset;
329
- stderrOffset = err.nextOffset;
330
- const errText = err.text.length > 0 ? err.text : consumeSpawnFailure();
331
- const separator = out.text.length > 0 && !out.text.endsWith("\n") ? "\n" : "";
332
- return {
333
- delta: out.text + (errText.length > 0 ? `${separator}[stderr]\n${errText}` : ""),
334
- lossy: out.lossy || err.lossy,
335
- ...(out.spillPath !== undefined ? { stdoutSpillPath: out.spillPath } : {}),
336
- ...(err.spillPath !== undefined ? { stderrSpillPath: err.spillPath } : {})
337
- };
338
- },
339
- kill: () => {
340
- if (proc.status !== "running")
341
- return false;
342
- proc.status = "killed";
343
- running.terminate();
344
- return true;
345
- }
346
- };
347
- return proc;
348
- }
349
- function processOutcome(proc) {
350
- if (proc.status === "killed") {
351
- return { status: "killed", detail: proc.signal !== null ? `signal: ${proc.signal}` : "killed before exit" };
352
- }
353
- return { status: "completed", detail: `exit code: ${proc.exitCode ?? 0}` };
354
- }
355
- // ---- model-facing rendering ---------------------------------------------------
356
- function streamText(output) {
357
- if (!output.truncated)
358
- return output.text;
359
- return `${output.text}\n[output truncated; full output: ${output.spillPath ?? "(unavailable)"}]`;
360
- }
361
- export function renderResult(result) {
362
- const out = streamText(result.stdout);
363
- const err = streamText(result.stderr);
364
- let body = out;
365
- if (err.length > 0) {
366
- if (body.length > 0 && !body.endsWith("\n"))
367
- body += "\n";
368
- body += `[stderr]\n${err}`;
369
- }
370
- if (body.length === 0)
371
- body = "(no output)";
372
- const markers = [];
373
- if (result.timedOut)
374
- markers.push(`[timed out after ${result.timeoutMs}ms]`);
375
- if (result.signal !== null)
376
- markers.push(`[killed by signal: ${result.signal}]`);
377
- else if (result.exitCode !== 0)
378
- markers.push(`[exit code: ${result.exitCode}]`);
379
- if (markers.length === 0)
380
- return body;
381
- if (!body.endsWith("\n"))
382
- body += "\n";
383
- return body + markers.join("\n");
384
- }
385
- function renderProcessRead(read) {
386
- const notices = [];
387
- if (read.lossy) {
388
- const paths = [read.stdoutSpillPath, read.stderrSpillPath].filter((p) => p !== undefined);
389
- notices.push(`[some output was dropped from memory; full output: ${paths.length > 0 ? paths.join(", ") : "(unavailable)"}]`);
390
- }
391
- if (notices.length === 0)
392
- return read.delta;
393
- return `${read.delta}${read.delta.length > 0 && !read.delta.endsWith("\n") ? "\n" : ""}${notices.join("\n")}`;
394
- }
395
- // ---- tool description / validation --------------------------------------------
396
- /** Model-facing lead sentence for each backend. The user's default terminal is
397
- * stated up front so the model never has to guess which syntax applies. */
398
- export const SHELL_DESCRIPTIONS = {
399
- 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.",
400
- 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.",
401
- 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.",
402
- 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."
403
- };
404
- /**
405
- * Render the model-facing tool description for one backend. The backend is
406
- * whatever the user chose in Settings -> General -> Default terminal; the
407
- * description names it explicitly so the model writes the right syntax.
408
- * @param backgroundEnabled - advertise `run_in_background` controls.
409
- * @param shell - active backend; unknown values fall back to the default.
410
- */
411
- export function toolDescription(backgroundEnabled, shell = DEFAULT_SHELL) {
412
- const active = SHELLS.includes(shell) ? shell : DEFAULT_SHELL;
413
- const lead = SHELL_DESCRIPTIONS[active];
414
- const base = [
415
- `The user's chosen default terminal (Settings -> General -> Default terminal) is ${active}; commands run there.`,
416
- lead,
417
- "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, and WSL run unconfined."
418
- ].join(" ");
419
- if (!backgroundEnabled)
420
- return base;
421
- 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.";
422
- }
423
- export function validateArgs(args) {
424
- if (typeof args.command !== "string" || args.command.trim().length === 0) {
425
- throw new Error("invalid command: expected a non-empty string");
426
- }
427
- if (typeof args.description !== "string" || args.description.trim().length === 0) {
428
- throw new Error("invalid description: expected a non-empty string");
429
- }
430
- if (args.timeoutMs !== undefined && (typeof args.timeoutMs !== "number" || !Number.isFinite(args.timeoutMs) || args.timeoutMs <= 0)) {
431
- throw new Error(`invalid timeoutMs: expected a positive number, got ${JSON.stringify(args.timeoutMs)}`);
432
- }
433
- validateEscalationArgs(args.sandbox_permissions, args.justification);
434
- return args;
435
- }
436
- /**
437
- * Official sandbox seam (mirrors dsh-tool-bash / dsh-pwsh-sandbox): resolve the
438
- * per-call policy from ctx.sandboxPolicy, and — unless the call runs
439
- * danger-full-access — confine the spawn argv through ctx.sandbox. WSL is a
440
- * self-contained Linux VM and is not confined (its isolation IS the sandbox).
441
- * Git Bash and MSYS2 are also not confined: DSH's Windows ACL restricted-token
442
- * runner cannot start Cygwin/MSYS2 (CreateFileMapping Win32 error 5), so
443
- * attempting to wrap them would abort every Git Bash / MSYS2 command. A
444
- * requested confined mode
445
- * with no usable backend throws the fail-closed SandboxUnavailableError,
446
- * exactly like the shipped executors.
447
- */
448
- function confineSpawn(ctx, argv, policy, shell) {
449
- if (policy.mode === "danger-full-access" || shell === "wsl" || shell === "gitbash" || shell === "msys2") {
450
- const sandbox = shell === "wsl"
451
- ? { mode: policy.mode, enforcement: "wsl-isolation" }
452
- : shell === "gitbash"
453
- ? { mode: policy.mode, enforcement: "gitbash-unconfined" }
454
- : shell === "msys2"
455
- ? { mode: policy.mode, enforcement: "msys2-unconfined" }
456
- : undefined;
457
- return { argv, sandbox };
458
- }
459
- const confined = ctx.sandbox.confine(argv, policy);
460
- return {
461
- argv: confined.argv,
462
- sandbox: { mode: policy.mode, enforcement: confined.enforcement, denialSignatures: confined.denialSignatures }
463
- };
464
- }
465
- function resolveWorkdir(modelWorkdir, exec) {
466
- const headerCwd = exec.agent?.session.header.cwd;
467
- if (modelWorkdir === undefined)
468
- return headerCwd;
469
- if (headerCwd !== undefined && !isAbsolute(modelWorkdir))
470
- return resolve(headerCwd, modelWorkdir);
471
- return modelWorkdir;
472
- }
473
- function canonicalResult(result) {
474
- const output = (stream) => ({
475
- text: stream.text,
476
- truncated: stream.truncated,
477
- ...(stream.spillPath !== undefined ? { spillPath: stream.spillPath } : {})
478
- });
479
- return {
480
- kind: "foreground",
481
- exitCode: result.exitCode,
482
- signal: result.signal,
483
- timedOut: result.timedOut,
484
- aborted: result.aborted,
485
- timeoutMs: result.timeoutMs,
486
- stdout: output(result.stdout),
487
- stderr: output(result.stderr),
488
- ...(result.sandbox !== undefined ? { sandbox: result.sandbox } : {})
489
- };
490
- }
491
- const BACKGROUND_OUTPUT_PROPERTIES = {
492
- kind: { type: "string", required: true, const: "background" },
493
- jobId: { type: "string", required: true }
494
- };
495
- // ---- plugin -------------------------------------------------------------------
496
- export function apply(ctx, config = {}) {
497
- if (process.platform !== "win32") {
498
- ctx.logger?.info?.("dsh-bash-terminal: only meaningful on win32; skipping tool registration");
499
- return;
500
- }
501
- const backgroundEnabled = true;
502
- const paths = resolveAllPaths(config);
503
- const defaultShell = config.defaultShell ?? DEFAULT_SHELL;
504
- if (!SHELLS.includes(defaultShell)) {
505
- throw new Error(`dsh-bash-terminal: invalid defaultShell ${JSON.stringify(defaultShell)}`);
506
- }
507
- const settingsScope = ctx.settings.register(SETTINGS_NAMESPACE, z.object({ defaultShell: z.union(SHELLS.map((s) => z.const(s))).default(defaultShell) }), { base: { defaultShell } });
508
- /** Official sandbox-escalation surface (mirrors tool-bash): advertise the
509
- * escalation modes whenever the deployment confines. */
510
- const escalationModes = ESCALATION_TARGETS;
511
- const approveShellEscalation = (mode, justification, exec, standingPolicy) => {
512
- return approveEscalation({
513
- requestedMode: mode,
514
- justification,
515
- effectiveMode: standingPolicy.mode,
516
- subject: "command"
517
- }, {
518
- approver: ctx.get("approval"),
519
- agent: exec.agent,
520
- callId: exec.callId,
521
- toolName: "shell",
522
- signal: exec.signal
523
- });
524
- };
525
- ctx.systemPrompt.section({
526
- name: "tool:bash-terminal",
527
- order: 105,
528
- 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."
529
- });
530
- const toolName = "shell";
531
- const terminalRegistry = createTerminalRegistry(ctx);
532
- ctx.tools.register(terminalTool(ctx, terminalRegistry, paths, () => settingsScope.get().defaultShell));
533
- // The model-facing description must track the user's chosen default
534
- // terminal: a static description listing every backend leaves the model
535
- // guessing which syntax applies. Re-render it on every prompt assembly —
536
- // settings are hot-reloaded, so a change shows up on the next request
537
- // without a restart.
538
- ctx.on("system-prompt/assemble", async (_assembly, _context, next) => {
539
- const assembled = await next();
540
- const description = toolDescription(backgroundEnabled, settingsScope.get().defaultShell);
541
- const tools = Array.isArray(assembled.tools)
542
- ? assembled.tools.map((tool) => (tool.name === toolName ? { ...tool, description } : tool))
543
- : assembled.tools;
544
- return { ...assembled, tools };
545
- });
546
- ctx.tools.register(defineTool({
547
- name: toolName,
548
- description: toolDescription(backgroundEnabled, settingsScope.get().defaultShell),
549
- parameters: {
550
- command: {
551
- type: "string",
552
- required: true,
553
- description: "The command to execute in the selected terminal."
554
- },
555
- description: {
556
- type: "string",
557
- required: true,
558
- 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\"."
559
- },
560
- distro: {
561
- type: "string",
562
- description: "WSL distribution to use (only when the configured default terminal is wsl). Defaults to the system default distribution."
563
- },
564
- sandbox_permissions: {
565
- type: "string",
566
- enum: escalationModes,
567
- 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."
568
- },
569
- justification: {
570
- type: "string",
571
- description: "Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access."
572
- },
573
- workdir: {
574
- type: "string",
575
- description: "Working directory for this command. Defaults to the session workspace; a relative path is resolved against it."
576
- },
577
- timeoutMs: {
578
- type: "number",
579
- description: "Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry."
580
- },
581
- run_in_background: {
582
- type: "boolean",
583
- description: "Run in the background and return a job id immediately (collect with job_output, stop with job_kill). No timeout applies."
584
- }
585
- },
586
- output: {
587
- schema: {
588
- oneOf: [
589
- { type: "object", additionalProperties: false, properties: BACKGROUND_OUTPUT_PROPERTIES },
590
- {
591
- type: "object",
592
- additionalProperties: false,
593
- properties: {
594
- kind: { type: "string", required: true, const: "foreground" },
595
- exitCode: { required: true, oneOf: [{ type: "integer" }, { type: "null" }] },
596
- signal: { required: true, oneOf: [{ type: "string" }, { type: "null" }] },
597
- timedOut: { type: "boolean", required: true },
598
- aborted: { type: "boolean", required: true },
599
- timeoutMs: { type: "number", required: true },
600
- sandbox: {
601
- type: "object",
602
- additionalProperties: false,
603
- properties: {
604
- mode: { type: "string", required: true },
605
- enforcement: { type: "string", required: true },
606
- denied: { type: "boolean" }
607
- }
608
- },
609
- stdout: {
610
- type: "object",
611
- additionalProperties: false,
612
- required: true,
613
- properties: {
614
- text: { type: "string", required: true },
615
- truncated: { type: "boolean", required: true },
616
- spillPath: { type: "string" }
617
- }
618
- },
619
- stderr: {
620
- type: "object",
621
- additionalProperties: false,
622
- required: true,
623
- properties: {
624
- text: { type: "string", required: true },
625
- truncated: { type: "boolean", required: true },
626
- spillPath: { type: "string" }
627
- }
628
- }
629
- }
630
- }
631
- ]
632
- },
633
- render: (_args, value) => {
634
- if (value.kind === "background")
635
- return [{ type: "text", text: `started background job ${value.jobId}` }];
636
- let text = renderResult(value);
637
- if (value.sandbox?.denied === true) {
638
- if (!text.endsWith("\n"))
639
- text += "\n";
640
- text += sandboxDenialMarker(value.sandbox.mode) + "\n" + escalationHintMarker("command");
641
- }
642
- return [{ type: "text", text }];
643
- }
644
- },
645
- async execute(args, exec) {
646
- const v = validateArgs(args);
647
- const shell = settingsScope.get().defaultShell;
648
- const argv0 = buildArgv(shell, v.command, paths, v.distro);
649
- if (argv0[0] === undefined) {
650
- throw new Error(`dsh-bash-terminal: ${shell} backend unavailable - executable not found. Install it or set the corresponding *Path config.`);
651
- }
652
- // Only element 0 (the resolved executable) can be undefined; guarded above.
653
- const argv = argv0;
654
- const workdir = resolveWorkdir(v.workdir, exec);
655
- const timeoutMs = clampTimeout(v.timeoutMs, config.timeoutMs ?? DEFAULT_TIMEOUT_MS, config.maxTimeoutMs ?? MAX_TIMEOUT_MS, "shell timeoutMs");
656
- const dshEnv = ctx.shellEnv.collect(exec);
657
- const env = buildEnv(shell, dshEnv);
658
- let policy = ctx.sandboxPolicy.resolve(exec.agent ? { session: exec.agent.session } : {});
659
- if (v.sandbox_permissions !== undefined && v.justification !== undefined) {
660
- const approvedMode = await approveShellEscalation(v.sandbox_permissions, v.justification, exec, policy);
661
- policy = { ...policy, mode: approvedMode };
662
- }
663
- const { argv: confinedArgv, sandbox } = confineSpawn(ctx, argv, policy, shell);
664
- const resolved = {
665
- command: v.command,
666
- workdir: workdir ?? process.cwd(),
667
- timeoutMs,
668
- stdoutMaxBytes: DEFAULT_MAX_OUTPUT_BYTES,
669
- ...(v.stdin !== undefined ? { stdin: v.stdin } : {})
670
- };
671
- if (v.run_in_background === true) {
672
- const jobs = ctx.get("jobs");
673
- if (jobs === undefined)
674
- throw new Error("background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs");
675
- if (exec.signal.aborted) {
676
- const error = new HarnessError("tool call aborted", TOOL_ABORTED);
677
- error.name = "AbortError";
678
- throw error;
679
- }
680
- return {
681
- kind: "background",
682
- jobId: jobs.start({
683
- kind: `shell/${shell}`,
684
- label: v.command,
685
- ...(exec.agent ? { owner: exec.agent } : {}),
686
- run: () => {
687
- const proc = startBackground(ctx, confinedArgv, resolved, env, exec.signal);
688
- return {
689
- cancel: () => void proc.kill(),
690
- done: proc.done.then(() => processOutcome(proc)),
691
- readOutput: () => renderProcessRead(proc.readOutput())
692
- };
693
- }
694
- })
695
- };
696
- }
697
- const result = await runForeground(ctx, confinedArgv, resolved, env, exec.signal, timeoutMs);
698
- if (result.aborted) {
699
- const error = new HarnessError("tool call aborted", TOOL_ABORTED);
700
- error.name = "AbortError";
701
- throw error;
702
- }
703
- const denied = sandbox?.denialSignatures !== undefined
704
- ? sandbox.denialSignatures.some((sig) => result.stderr.text.toLowerCase().includes(sig.toLowerCase()))
705
- : false;
706
- return canonicalResult({
707
- ...result,
708
- ...(sandbox !== undefined ? { sandbox: { mode: sandbox.mode, enforcement: sandbox.enforcement, denied } } : {})
709
- });
710
- },
711
- presentCall: (args) => {
712
- if (args.run_in_background === true) {
713
- return {
714
- card: "generic",
715
- title: args.command,
716
- kind: "execute",
717
- rawInput: args.command,
718
- content: [{ type: "text", text: args.description }]
719
- };
720
- }
721
- return {
722
- card: "terminal",
723
- title: args.command,
724
- description: args.description,
725
- ...(args.workdir !== undefined ? { cwd: args.workdir } : {})
726
- };
727
- },
728
- presentResult: (args, result) => {
729
- const block = result.content.length === 1 ? result.content[0] : undefined;
730
- if (block === undefined || block.type !== "text")
731
- return undefined;
732
- const raw = block.text ?? "";
733
- if (args.run_in_background === true || result.isError) {
734
- return { card: "generic", content: [{ type: "text", text: "```console\n" + raw.replace(/\n+$/, "") + "\n```" }] };
735
- }
736
- const { body, ...exit } = parseExitStatus(raw);
737
- return { card: "terminal", output: body, ...exit };
738
- }
739
- }));
740
- }
741
- //#region internals for tests
742
- export const internals = {
743
- candidateExists,
744
- resolveAllPaths,
745
- resolveWorkdir,
746
- renderResult,
747
- processOutcome,
748
- startBackground,
749
- runForeground,
750
- spawnSpec,
751
- buildEnv,
752
- buildArgv,
753
- validateArgs,
754
- toolDescription,
755
- SHELL_DESCRIPTIONS,
756
- DEFAULT_TIMEOUT_MS,
757
- MAX_TIMEOUT_MS,
758
- DEFAULT_MAX_OUTPUT_BYTES
759
- };
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
+ import { lstatSync } from "node:fs";
25
+ import { isAbsolute, join, resolve } from "node:path";
26
+ import { ESCALATION_TARGETS, TOOL_ABORTED, approveEscalation, defineTool, escalationHintMarker, clampTimeout, deadline, parseExitStatus, timeoutOf, sandboxDenialMarker, validateEscalationArgs, z, HarnessError } from "./dsh.js";
27
+ import { createTerminalRegistry, terminalTool } from "./terminal.js";
28
+ /** Stable Cordis plugin name. */
29
+ export const name = "bash-terminal";
30
+ /** Services required before the tool can register. */
31
+ export const inject = ["tools", "systemPrompt", "shellEnv", "subprocess", "settings", "sandbox", "sandboxPolicy"];
32
+ /** The terminal backends this tool exposes, in catalog order. */
33
+ export const SHELLS = ["powershell", "gitbash", "msys2", "wsl"];
34
+ /** The backend used when the caller does not name one. */
35
+ export const DEFAULT_SHELL = "powershell";
36
+ /** Settings namespace backing the user-chosen default terminal. */
37
+ export const SETTINGS_NAMESPACE = "bash-terminal";
38
+ /** Default per-command timeout (ms). */
39
+ const DEFAULT_TIMEOUT_MS = 120000;
40
+ /** Upper bound a caller's timeoutMs is capped to. */
41
+ const MAX_TIMEOUT_MS = 600000;
42
+ /** SIGTERM->SIGKILL grace (ms), matching dsh-bash-local's default. */
43
+ const DEFAULT_GRACE_MS = 3000;
44
+ /** Per-stream in-memory cap before spilling (bytes). */
45
+ const DEFAULT_MAX_OUTPUT_BYTES = 64 * 1024;
46
+ /** Per-stream spill file cap (bytes). */
47
+ const DEFAULT_MAX_SPILL_BYTES = 64 * 1024 * 1024;
48
+ /** Timeout code stamped on the deadline's TimeoutReason. */
49
+ const TIMEOUT_CODE = "SHELL_TIMEOUT";
50
+ /** Model-friendly environment overrides (same set dsh-bash-local hardcodes). */
51
+ const ENV_OVERRIDES = {
52
+ NO_COLOR: "1",
53
+ TERM: "dumb",
54
+ PAGER: "cat",
55
+ GIT_PAGER: "cat"
56
+ };
57
+ /** Runtime configuration schema. */
58
+ export const Config = z.object({
59
+ defaultShell: z.string().default(DEFAULT_SHELL),
60
+ timeoutMs: z.number().default(DEFAULT_TIMEOUT_MS),
61
+ maxTimeoutMs: z.number().default(MAX_TIMEOUT_MS),
62
+ pwshPath: z.string().default(""),
63
+ gitBashPath: z.string().default(""),
64
+ msys2Path: z.string().default(""),
65
+ wslPath: z.string().default("")
66
+ });
67
+ // ---- executable resolution ------------------------------------------------
68
+ function candidateExists(candidate) {
69
+ try {
70
+ const stat = lstatSync(candidate);
71
+ return stat.isFile() || stat.isSymbolicLink();
72
+ }
73
+ catch {
74
+ return false;
75
+ }
76
+ }
77
+ function resolveFromCandidates(candidates) {
78
+ for (const candidate of candidates) {
79
+ if (candidateExists(candidate))
80
+ return candidate;
81
+ }
82
+ return undefined;
83
+ }
84
+ /** Well-known PowerShell install locations plus PATH entries, newest first. */
85
+ export function candidatePwshPaths(env = process.env) {
86
+ const programFiles = env.ProgramFiles ?? "C:\\Program Files";
87
+ const systemRoot = env.SystemRoot ?? "C:\\Windows";
88
+ const candidates = [join(programFiles, "PowerShell", "7", "pwsh.exe")];
89
+ for (const entry of (env.PATH ?? "").split(";")) {
90
+ const trimmed = entry.trim().replace(/^"|"$/g, "");
91
+ if (trimmed.length === 0)
92
+ continue;
93
+ candidates.push(join(trimmed, "pwsh.exe"));
94
+ }
95
+ candidates.push(join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"));
96
+ return candidates;
97
+ }
98
+ /**
99
+ * Git for Windows locations, then PATH bash.exe entries EXCLUDING the
100
+ * System32 launcher (c:\\windows\\system32\\bash.exe is the WSL
101
+ * forwarder, not a Git Bash shell).
102
+ */
103
+ export function candidateGitBashPaths(env = process.env) {
104
+ const programFiles = env.ProgramFiles ?? "C:\\Program Files";
105
+ const systemRoot = (env.SystemRoot ?? "C:\\Windows").toLowerCase();
106
+ const localAppData = env.LOCALAPPDATA ?? "";
107
+ const candidates = [
108
+ join(programFiles, "Git", "bin", "bash.exe"),
109
+ join(programFiles, "Git", "usr", "bin", "bash.exe")
110
+ ];
111
+ if (localAppData.length > 0)
112
+ candidates.push(join(localAppData, "Programs", "Git", "bin", "bash.exe"));
113
+ for (const entry of (env.PATH ?? "").split(";")) {
114
+ const trimmed = entry.trim().replace(/^"|"$/g, "");
115
+ if (trimmed.length === 0)
116
+ continue;
117
+ if (trimmed.toLowerCase().includes(systemRoot))
118
+ continue;
119
+ candidates.push(join(trimmed, "bash.exe"));
120
+ }
121
+ return candidates;
122
+ }
123
+ /**
124
+ * MSYS2 locations, in preference order: the real `bash.exe` under usr\bin
125
+ * first, then bin\bash.exe, and `msys2.exe` dead last.
126
+ *
127
+ * msys2.exe is NOT a usable backend for piped execution: it is the console-
128
+ * allocating Cygwin launcher, so a spawn with piped stdio returns exit 0 with
129
+ * zero bytes on both stdout and stderr (measured on this machine against
130
+ * MSYS2 with bash 5.3.15). Keeping it in the list only as a last-resort
131
+ * fallback preserves the path the config docs reference, but a working
132
+ * bash.exe always wins.
133
+ *
134
+ * MSYS2 uses the same Cygwin/MSYS2 runtime as Git Bash, so it cannot run
135
+ * under the DSH Windows ACL restricted-token sandbox.
136
+ */
137
+ export function candidateMsys2Paths(env = process.env) {
138
+ const candidates = [
139
+ "C:\\msys64\\usr\\bin\\bash.exe",
140
+ "C:\\msys64\\bin\\bash.exe"
141
+ ];
142
+ for (const entry of (env.PATH ?? "").split(";")) {
143
+ const trimmed = entry.trim().replace(/^"|"$/g, "");
144
+ if (trimmed.length === 0)
145
+ continue;
146
+ const lower = trimmed.toLowerCase();
147
+ if (lower.includes("msys64") || lower.includes("mingw64")) {
148
+ candidates.push(join(trimmed, "bash.exe"));
149
+ }
150
+ }
151
+ candidates.push("C:\\msys64\\msys2.exe"); // last resort: see the note above
152
+ return candidates;
153
+ }
154
+ export function defaultWslPath(env = process.env) {
155
+ const systemRoot = env.SystemRoot ?? "C:\\Windows";
156
+ return join(systemRoot, "System32", "wsl.exe");
157
+ }
158
+ export function resolveAllPaths(config = {}, env = process.env) {
159
+ const pwsh = config.pwshPath && config.pwshPath.trim().length > 0
160
+ ? config.pwshPath
161
+ : resolveFromCandidates(candidatePwshPaths(env));
162
+ const gitbash = config.gitBashPath && config.gitBashPath.trim().length > 0
163
+ ? config.gitBashPath
164
+ : resolveFromCandidates(candidateGitBashPaths(env));
165
+ const msys2 = config.msys2Path && config.msys2Path.trim().length > 0
166
+ ? config.msys2Path
167
+ : resolveFromCandidates(candidateMsys2Paths(env));
168
+ const wsl = config.wslPath && config.wslPath.trim().length > 0
169
+ ? config.wslPath
170
+ : defaultWslPath(env);
171
+ return { pwsh, gitbash, msys2, wsl };
172
+ }
173
+ // ---- argv / env construction ------------------------------------------------
174
+ export function buildArgv(shell, command, paths, distro) {
175
+ switch (shell) {
176
+ case "powershell":
177
+ return [paths.pwsh, "-NoLogo", "-NoProfile", "-NonInteractive", "-Command", command];
178
+ case "gitbash":
179
+ return [paths.gitbash, "-lc", command];
180
+ case "msys2":
181
+ // -lc, not -c: a login shell sources /etc/profile, which is what puts
182
+ // /usr/bin and /mingw64/bin on PATH. With a bare -c, `tr`, `sed`, `gcc`
183
+ // and friends are all "command not found".
184
+ return [paths.msys2, "-lc", command];
185
+ case "wsl": {
186
+ const distroArg = distro !== undefined && distro.trim().length > 0 ? ["-d", distro.trim()] : [];
187
+ return [paths.wsl, ...distroArg, "-e", "bash", "-lc", command];
188
+ }
189
+ default:
190
+ throw new Error(`invalid shell: ${JSON.stringify(shell)} (expected one of ${SHELLS.join(", ")})`);
191
+ }
192
+ }
193
+ /**
194
+ * Merge the DSH_* environment over the process environment. For WSL, only
195
+ * variables explicitly listed in WSLENV cross the boundary, so every DSH_*
196
+ * key is appended there — and the list is *layered onto* whatever WSLENV the
197
+ * host already had (Windows Terminal exports e.g. `WT_SESSION:WT_PROFILE_ID:`),
198
+ * never rebuilt from scratch: WSLENV is an allow-list, so dropping the
199
+ * inherited entries would silently stop them crossing into WSL.
200
+ *
201
+ * @param inheritedWslenv - the ambient WSLENV to layer onto. Callers that
202
+ * replace the child environment wholesale (the PTY path) must pass
203
+ * `process.env.WSLENV` explicitly, because the ambient value is not visible
204
+ * through `dshEnv`.
205
+ */
206
+ export function buildEnv(shell, dshEnv, inheritedWslenv = process.env.WSLENV) {
207
+ const env = { ...ENV_OVERRIDES, ...dshEnv };
208
+ if (shell === "msys2") {
209
+ // Picks the MINGW64 environment, so /mingw64/bin (gcc, make, ...) joins
210
+ // PATH via /etc/profile. Without it MSYS2 defaults to the bare MSYS
211
+ // environment. An explicit caller-supplied value wins.
212
+ if (env.MSYSTEM === undefined)
213
+ env.MSYSTEM = "MINGW64";
214
+ }
215
+ if (shell === "wsl") {
216
+ const keys = Object.keys(dshEnv ?? {});
217
+ if (keys.length > 0) {
218
+ // An explicit WSLENV in dshEnv wins over the inherited one; otherwise the
219
+ // inherited value is the base. Either way the base is SPLIT into entries
220
+ // (the host value ends with a trailing ":", so string concatenation would
221
+ // produce a malformed empty entry) and the WSLENV key itself is excluded
222
+ // (it is a key of dshEnv too, and appending it would add a bogus entry).
223
+ const declared = Object.prototype.hasOwnProperty.call(dshEnv ?? {}, "WSLENV");
224
+ const base = declared
225
+ ? env.WSLENV
226
+ : (typeof inheritedWslenv === "string" && inheritedWslenv.length > 0 ? inheritedWslenv : env.WSLENV);
227
+ const parts = typeof base === "string" ? base.split(":") : [];
228
+ env.WSLENV = [...parts, ...keys.filter((k) => k !== "WSLENV").flatMap((k) => k.split(":"))]
229
+ .map((p) => p.trim())
230
+ .filter((p) => p.length > 0)
231
+ .join(":");
232
+ }
233
+ }
234
+ return env;
235
+ }
236
+ function spawnSpec(resolved, argv, env, signal) {
237
+ const collect = (maxBytes) => ({ maxBytes, spill: { maxBytes: DEFAULT_MAX_SPILL_BYTES } });
238
+ return {
239
+ argv,
240
+ cwd: resolved.workdir,
241
+ stdio: {
242
+ stdin: resolved.stdin !== undefined ? { data: resolved.stdin } : "ignore",
243
+ stdout: collect(resolved.stdoutMaxBytes),
244
+ stderr: collect(DEFAULT_MAX_OUTPUT_BYTES)
245
+ },
246
+ graceMs: DEFAULT_GRACE_MS,
247
+ signal,
248
+ env
249
+ };
250
+ }
251
+ function collectedOutput(handle) {
252
+ const { stdout, stderr } = handle.collected;
253
+ if (!isCollectedStream(stdout) || !isCollectedStream(stderr)) {
254
+ throw new Error("dsh-bash-terminal-ts: subprocess implementation dropped a requested collect stream");
255
+ }
256
+ return { stdout, stderr };
257
+ }
258
+ function isCollectedStream(value) {
259
+ return typeof value === "object" && value !== null && typeof value.readFrom === "function";
260
+ }
261
+ function finalOutput(reader) {
262
+ const read = reader.readFrom(0);
263
+ return {
264
+ text: read.text,
265
+ truncated: read.lossy,
266
+ ...(read.spillPath !== undefined ? { spillPath: read.spillPath } : {})
267
+ };
268
+ }
269
+ async function runForeground(ctx, argv, resolved, env, signal, timeoutMs) {
270
+ const subprocess = requireSubprocess(ctx);
271
+ const d = deadline(signal, timeoutMs, TIMEOUT_CODE);
272
+ try {
273
+ const handle = subprocess.spawn(spawnSpec(resolved, argv, env, d.signal));
274
+ const outcome = await handle.done;
275
+ const collected = collectedOutput(handle);
276
+ const timedOut = timeoutOf(d.signal, TIMEOUT_CODE) !== undefined;
277
+ const aborted = d.signal.aborted && !timedOut;
278
+ return {
279
+ exitCode: outcome.exitCode,
280
+ signal: outcome.signal,
281
+ timedOut,
282
+ aborted,
283
+ timeoutMs,
284
+ stdout: finalOutput(collected.stdout),
285
+ stderr: finalOutput(collected.stderr)
286
+ };
287
+ }
288
+ finally {
289
+ d[Symbol.dispose]();
290
+ }
291
+ }
292
+ function requireSubprocess(ctx) {
293
+ const subprocess = ctx.subprocess;
294
+ if (subprocess === null) {
295
+ throw new Error("dsh-bash-terminal-ts: ctx.subprocess seam unavailable (missing inject service)");
296
+ }
297
+ return subprocess;
298
+ }
299
+ function startBackground(ctx, argv, resolved, env, signal) {
300
+ const subprocess = requireSubprocess(ctx);
301
+ const running = subprocess.spawn(spawnSpec(resolved, argv, env, signal));
302
+ const collected = collectedOutput(running);
303
+ let stdoutOffset = 0;
304
+ let stderrOffset = 0;
305
+ let spawnFailureNote;
306
+ const consumeSpawnFailure = () => {
307
+ const note = spawnFailureNote ?? "";
308
+ spawnFailureNote = undefined;
309
+ return note;
310
+ };
311
+ const proc = {
312
+ status: "running",
313
+ exitCode: null,
314
+ signal: null,
315
+ done: running.done.then((outcome) => {
316
+ if (proc.status === "running") {
317
+ proc.status = signal?.aborted === true || outcome.signal !== null ? "killed" : "completed";
318
+ }
319
+ proc.exitCode = outcome.exitCode;
320
+ proc.signal = outcome.signal;
321
+ }, (error) => {
322
+ proc.status = "killed";
323
+ spawnFailureNote = `spawn failed: ${String(error)}`;
324
+ }),
325
+ readOutput: () => {
326
+ const out = collected.stdout.readFrom(stdoutOffset);
327
+ const err = collected.stderr.readFrom(stderrOffset);
328
+ stdoutOffset = out.nextOffset;
329
+ stderrOffset = err.nextOffset;
330
+ const errText = err.text.length > 0 ? err.text : consumeSpawnFailure();
331
+ const separator = out.text.length > 0 && !out.text.endsWith("\n") ? "\n" : "";
332
+ return {
333
+ delta: out.text + (errText.length > 0 ? `${separator}[stderr]\n${errText}` : ""),
334
+ lossy: out.lossy || err.lossy,
335
+ ...(out.spillPath !== undefined ? { stdoutSpillPath: out.spillPath } : {}),
336
+ ...(err.spillPath !== undefined ? { stderrSpillPath: err.spillPath } : {})
337
+ };
338
+ },
339
+ kill: () => {
340
+ if (proc.status !== "running")
341
+ return false;
342
+ proc.status = "killed";
343
+ running.terminate();
344
+ return true;
345
+ }
346
+ };
347
+ return proc;
348
+ }
349
+ function processOutcome(proc) {
350
+ if (proc.status === "killed") {
351
+ return { status: "killed", detail: proc.signal !== null ? `signal: ${proc.signal}` : "killed before exit" };
352
+ }
353
+ return { status: "completed", detail: `exit code: ${proc.exitCode ?? 0}` };
354
+ }
355
+ // ---- model-facing rendering ---------------------------------------------------
356
+ function streamText(output) {
357
+ if (!output.truncated)
358
+ return output.text;
359
+ return `${output.text}\n[output truncated; full output: ${output.spillPath ?? "(unavailable)"}]`;
360
+ }
361
+ export function renderResult(result) {
362
+ const out = streamText(result.stdout);
363
+ const err = streamText(result.stderr);
364
+ let body = out;
365
+ if (err.length > 0) {
366
+ if (body.length > 0 && !body.endsWith("\n"))
367
+ body += "\n";
368
+ body += `[stderr]\n${err}`;
369
+ }
370
+ if (body.length === 0)
371
+ body = "(no output)";
372
+ const markers = [];
373
+ if (result.timedOut)
374
+ markers.push(`[timed out after ${result.timeoutMs}ms]`);
375
+ if (result.signal !== null)
376
+ markers.push(`[killed by signal: ${result.signal}]`);
377
+ else if (result.exitCode !== 0)
378
+ markers.push(`[exit code: ${result.exitCode}]`);
379
+ if (markers.length === 0)
380
+ return body;
381
+ if (!body.endsWith("\n"))
382
+ body += "\n";
383
+ return body + markers.join("\n");
384
+ }
385
+ function renderProcessRead(read) {
386
+ const notices = [];
387
+ if (read.lossy) {
388
+ const paths = [read.stdoutSpillPath, read.stderrSpillPath].filter((p) => p !== undefined);
389
+ notices.push(`[some output was dropped from memory; full output: ${paths.length > 0 ? paths.join(", ") : "(unavailable)"}]`);
390
+ }
391
+ if (notices.length === 0)
392
+ return read.delta;
393
+ return `${read.delta}${read.delta.length > 0 && !read.delta.endsWith("\n") ? "\n" : ""}${notices.join("\n")}`;
394
+ }
395
+ // ---- tool description / validation --------------------------------------------
396
+ /** Model-facing lead sentence for each backend. The user's default terminal is
397
+ * stated up front so the model never has to guess which syntax applies. */
398
+ export const SHELL_DESCRIPTIONS = {
399
+ 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.",
400
+ 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.",
401
+ 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.",
402
+ 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."
403
+ };
404
+ /**
405
+ * Render the model-facing tool description for one backend. The backend is
406
+ * whatever the user chose in Settings -> General -> Default terminal; the
407
+ * description names it explicitly so the model writes the right syntax.
408
+ * @param backgroundEnabled - advertise `run_in_background` controls.
409
+ * @param shell - active backend; unknown values fall back to the default.
410
+ */
411
+ export function toolDescription(backgroundEnabled, shell = DEFAULT_SHELL) {
412
+ const active = SHELLS.includes(shell) ? shell : DEFAULT_SHELL;
413
+ const lead = SHELL_DESCRIPTIONS[active];
414
+ const base = [
415
+ `The user's chosen default terminal (Settings -> General -> Default terminal) is ${active}; commands run there.`,
416
+ lead,
417
+ "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, and WSL run unconfined."
418
+ ].join(" ");
419
+ if (!backgroundEnabled)
420
+ return base;
421
+ 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.";
422
+ }
423
+ export function validateArgs(args) {
424
+ if (typeof args.command !== "string" || args.command.trim().length === 0) {
425
+ throw new Error("invalid command: expected a non-empty string");
426
+ }
427
+ if (typeof args.description !== "string" || args.description.trim().length === 0) {
428
+ throw new Error("invalid description: expected a non-empty string");
429
+ }
430
+ if (args.timeoutMs !== undefined && (typeof args.timeoutMs !== "number" || !Number.isFinite(args.timeoutMs) || args.timeoutMs <= 0)) {
431
+ throw new Error(`invalid timeoutMs: expected a positive number, got ${JSON.stringify(args.timeoutMs)}`);
432
+ }
433
+ validateEscalationArgs(args.sandbox_permissions, args.justification);
434
+ return args;
435
+ }
436
+ /**
437
+ * Official sandbox seam (mirrors dsh-tool-bash / dsh-pwsh-sandbox): resolve the
438
+ * per-call policy from ctx.sandboxPolicy, and — unless the call runs
439
+ * danger-full-access — confine the spawn argv through ctx.sandbox. WSL is a
440
+ * self-contained Linux VM and is not confined (its isolation IS the sandbox).
441
+ * Git Bash and MSYS2 are also not confined: DSH's Windows ACL restricted-token
442
+ * runner cannot start Cygwin/MSYS2 (CreateFileMapping Win32 error 5), so
443
+ * attempting to wrap them would abort every Git Bash / MSYS2 command. A
444
+ * requested confined mode
445
+ * with no usable backend throws the fail-closed SandboxUnavailableError,
446
+ * exactly like the shipped executors.
447
+ */
448
+ function confineSpawn(ctx, argv, policy, shell) {
449
+ if (policy.mode === "danger-full-access" || shell === "wsl" || shell === "gitbash" || shell === "msys2") {
450
+ const sandbox = shell === "wsl"
451
+ ? { mode: policy.mode, enforcement: "wsl-isolation" }
452
+ : shell === "gitbash"
453
+ ? { mode: policy.mode, enforcement: "gitbash-unconfined" }
454
+ : shell === "msys2"
455
+ ? { mode: policy.mode, enforcement: "msys2-unconfined" }
456
+ : undefined;
457
+ return { argv, sandbox };
458
+ }
459
+ const confined = ctx.sandbox.confine(argv, policy);
460
+ return {
461
+ argv: confined.argv,
462
+ sandbox: { mode: policy.mode, enforcement: confined.enforcement, denialSignatures: confined.denialSignatures }
463
+ };
464
+ }
465
+ function resolveWorkdir(modelWorkdir, exec) {
466
+ const headerCwd = exec.agent?.session.header.cwd;
467
+ if (modelWorkdir === undefined)
468
+ return headerCwd;
469
+ if (headerCwd !== undefined && !isAbsolute(modelWorkdir))
470
+ return resolve(headerCwd, modelWorkdir);
471
+ return modelWorkdir;
472
+ }
473
+ function canonicalResult(result) {
474
+ const output = (stream) => ({
475
+ text: stream.text,
476
+ truncated: stream.truncated,
477
+ ...(stream.spillPath !== undefined ? { spillPath: stream.spillPath } : {})
478
+ });
479
+ return {
480
+ kind: "foreground",
481
+ exitCode: result.exitCode,
482
+ signal: result.signal,
483
+ timedOut: result.timedOut,
484
+ aborted: result.aborted,
485
+ timeoutMs: result.timeoutMs,
486
+ stdout: output(result.stdout),
487
+ stderr: output(result.stderr),
488
+ ...(result.sandbox !== undefined ? { sandbox: result.sandbox } : {})
489
+ };
490
+ }
491
+ const BACKGROUND_OUTPUT_PROPERTIES = {
492
+ kind: { type: "string", required: true, const: "background" },
493
+ jobId: { type: "string", required: true }
494
+ };
495
+ // ---- plugin -------------------------------------------------------------------
496
+ export function apply(ctx, config = {}) {
497
+ if (process.platform !== "win32") {
498
+ ctx.logger?.info?.("dsh-bash-terminal-ts: only meaningful on win32; skipping tool registration");
499
+ return;
500
+ }
501
+ const backgroundEnabled = true;
502
+ const paths = resolveAllPaths(config);
503
+ const defaultShell = config.defaultShell ?? DEFAULT_SHELL;
504
+ if (!SHELLS.includes(defaultShell)) {
505
+ throw new Error(`dsh-bash-terminal-ts: invalid defaultShell ${JSON.stringify(defaultShell)}`);
506
+ }
507
+ const settingsScope = ctx.settings.register(SETTINGS_NAMESPACE, z.object({ defaultShell: z.union(SHELLS.map((s) => z.const(s))).default(defaultShell) }), { base: { defaultShell } });
508
+ /** Official sandbox-escalation surface (mirrors tool-bash): advertise the
509
+ * escalation modes whenever the deployment confines. */
510
+ const escalationModes = ESCALATION_TARGETS;
511
+ const approveShellEscalation = (mode, justification, exec, standingPolicy) => {
512
+ return approveEscalation({
513
+ requestedMode: mode,
514
+ justification,
515
+ effectiveMode: standingPolicy.mode,
516
+ subject: "command"
517
+ }, {
518
+ approver: ctx.get("approval"),
519
+ agent: exec.agent,
520
+ callId: exec.callId,
521
+ toolName: "shell",
522
+ signal: exec.signal
523
+ });
524
+ };
525
+ ctx.systemPrompt.section({
526
+ name: "tool:bash-terminal",
527
+ order: 105,
528
+ 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."
529
+ });
530
+ const toolName = "shell";
531
+ const terminalRegistry = createTerminalRegistry(ctx);
532
+ ctx.tools.register(terminalTool(ctx, terminalRegistry, paths, () => settingsScope.get().defaultShell));
533
+ // The model-facing description must track the user's chosen default
534
+ // terminal: a static description listing every backend leaves the model
535
+ // guessing which syntax applies. Re-render it on every prompt assembly —
536
+ // settings are hot-reloaded, so a change shows up on the next request
537
+ // without a restart.
538
+ ctx.on("system-prompt/assemble", async (_assembly, _context, next) => {
539
+ const assembled = await next();
540
+ const description = toolDescription(backgroundEnabled, settingsScope.get().defaultShell);
541
+ const tools = Array.isArray(assembled.tools)
542
+ ? assembled.tools.map((tool) => (tool.name === toolName ? { ...tool, description } : tool))
543
+ : assembled.tools;
544
+ return { ...assembled, tools };
545
+ });
546
+ ctx.tools.register(defineTool({
547
+ name: toolName,
548
+ description: toolDescription(backgroundEnabled, settingsScope.get().defaultShell),
549
+ parameters: {
550
+ command: {
551
+ type: "string",
552
+ required: true,
553
+ description: "The command to execute in the selected terminal."
554
+ },
555
+ description: {
556
+ type: "string",
557
+ required: true,
558
+ 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\"."
559
+ },
560
+ distro: {
561
+ type: "string",
562
+ description: "WSL distribution to use (only when the configured default terminal is wsl). Defaults to the system default distribution."
563
+ },
564
+ sandbox_permissions: {
565
+ type: "string",
566
+ enum: escalationModes,
567
+ 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."
568
+ },
569
+ justification: {
570
+ type: "string",
571
+ description: "Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access."
572
+ },
573
+ workdir: {
574
+ type: "string",
575
+ description: "Working directory for this command. Defaults to the session workspace; a relative path is resolved against it."
576
+ },
577
+ timeoutMs: {
578
+ type: "number",
579
+ description: "Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry."
580
+ },
581
+ run_in_background: {
582
+ type: "boolean",
583
+ description: "Run in the background and return a job id immediately (collect with job_output, stop with job_kill). No timeout applies."
584
+ }
585
+ },
586
+ output: {
587
+ schema: {
588
+ oneOf: [
589
+ { type: "object", additionalProperties: false, properties: BACKGROUND_OUTPUT_PROPERTIES },
590
+ {
591
+ type: "object",
592
+ additionalProperties: false,
593
+ properties: {
594
+ kind: { type: "string", required: true, const: "foreground" },
595
+ exitCode: { required: true, oneOf: [{ type: "integer" }, { type: "null" }] },
596
+ signal: { required: true, oneOf: [{ type: "string" }, { type: "null" }] },
597
+ timedOut: { type: "boolean", required: true },
598
+ aborted: { type: "boolean", required: true },
599
+ timeoutMs: { type: "number", required: true },
600
+ sandbox: {
601
+ type: "object",
602
+ additionalProperties: false,
603
+ properties: {
604
+ mode: { type: "string", required: true },
605
+ enforcement: { type: "string", required: true },
606
+ denied: { type: "boolean" }
607
+ }
608
+ },
609
+ stdout: {
610
+ type: "object",
611
+ additionalProperties: false,
612
+ required: true,
613
+ properties: {
614
+ text: { type: "string", required: true },
615
+ truncated: { type: "boolean", required: true },
616
+ spillPath: { type: "string" }
617
+ }
618
+ },
619
+ stderr: {
620
+ type: "object",
621
+ additionalProperties: false,
622
+ required: true,
623
+ properties: {
624
+ text: { type: "string", required: true },
625
+ truncated: { type: "boolean", required: true },
626
+ spillPath: { type: "string" }
627
+ }
628
+ }
629
+ }
630
+ }
631
+ ]
632
+ },
633
+ render: (_args, value) => {
634
+ if (value.kind === "background")
635
+ return [{ type: "text", text: `started background job ${value.jobId}` }];
636
+ let text = renderResult(value);
637
+ if (value.sandbox?.denied === true) {
638
+ if (!text.endsWith("\n"))
639
+ text += "\n";
640
+ text += sandboxDenialMarker(value.sandbox.mode) + "\n" + escalationHintMarker("command");
641
+ }
642
+ return [{ type: "text", text }];
643
+ }
644
+ },
645
+ async execute(args, exec) {
646
+ const v = validateArgs(args);
647
+ const shell = settingsScope.get().defaultShell;
648
+ const argv0 = buildArgv(shell, v.command, paths, v.distro);
649
+ if (argv0[0] === undefined) {
650
+ throw new Error(`dsh-bash-terminal-ts: ${shell} backend unavailable - executable not found. Install it or set the corresponding *Path config.`);
651
+ }
652
+ // Only element 0 (the resolved executable) can be undefined; guarded above.
653
+ const argv = argv0;
654
+ const workdir = resolveWorkdir(v.workdir, exec);
655
+ const timeoutMs = clampTimeout(v.timeoutMs, config.timeoutMs ?? DEFAULT_TIMEOUT_MS, config.maxTimeoutMs ?? MAX_TIMEOUT_MS, "shell timeoutMs");
656
+ const dshEnv = ctx.shellEnv.collect(exec);
657
+ const env = buildEnv(shell, dshEnv);
658
+ let policy = ctx.sandboxPolicy.resolve(exec.agent ? { session: exec.agent.session } : {});
659
+ if (v.sandbox_permissions !== undefined && v.justification !== undefined) {
660
+ const approvedMode = await approveShellEscalation(v.sandbox_permissions, v.justification, exec, policy);
661
+ policy = { ...policy, mode: approvedMode };
662
+ }
663
+ const { argv: confinedArgv, sandbox } = confineSpawn(ctx, argv, policy, shell);
664
+ const resolved = {
665
+ command: v.command,
666
+ workdir: workdir ?? process.cwd(),
667
+ timeoutMs,
668
+ stdoutMaxBytes: DEFAULT_MAX_OUTPUT_BYTES,
669
+ ...(v.stdin !== undefined ? { stdin: v.stdin } : {})
670
+ };
671
+ if (v.run_in_background === true) {
672
+ const jobs = ctx.get("jobs");
673
+ if (jobs === undefined)
674
+ throw new Error("background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs");
675
+ if (exec.signal.aborted) {
676
+ const error = new HarnessError("tool call aborted", TOOL_ABORTED);
677
+ error.name = "AbortError";
678
+ throw error;
679
+ }
680
+ return {
681
+ kind: "background",
682
+ jobId: jobs.start({
683
+ kind: `shell/${shell}`,
684
+ label: v.command,
685
+ ...(exec.agent ? { owner: exec.agent } : {}),
686
+ run: () => {
687
+ const proc = startBackground(ctx, confinedArgv, resolved, env, exec.signal);
688
+ return {
689
+ cancel: () => void proc.kill(),
690
+ done: proc.done.then(() => processOutcome(proc)),
691
+ readOutput: () => renderProcessRead(proc.readOutput())
692
+ };
693
+ }
694
+ })
695
+ };
696
+ }
697
+ const result = await runForeground(ctx, confinedArgv, resolved, env, exec.signal, timeoutMs);
698
+ if (result.aborted) {
699
+ const error = new HarnessError("tool call aborted", TOOL_ABORTED);
700
+ error.name = "AbortError";
701
+ throw error;
702
+ }
703
+ const denied = sandbox?.denialSignatures !== undefined
704
+ ? sandbox.denialSignatures.some((sig) => result.stderr.text.toLowerCase().includes(sig.toLowerCase()))
705
+ : false;
706
+ return canonicalResult({
707
+ ...result,
708
+ ...(sandbox !== undefined ? { sandbox: { mode: sandbox.mode, enforcement: sandbox.enforcement, denied } } : {})
709
+ });
710
+ },
711
+ presentCall: (args) => {
712
+ if (args.run_in_background === true) {
713
+ return {
714
+ card: "generic",
715
+ title: args.command,
716
+ kind: "execute",
717
+ rawInput: args.command,
718
+ content: [{ type: "text", text: args.description }]
719
+ };
720
+ }
721
+ return {
722
+ card: "terminal",
723
+ title: args.command,
724
+ description: args.description,
725
+ ...(args.workdir !== undefined ? { cwd: args.workdir } : {})
726
+ };
727
+ },
728
+ presentResult: (args, result) => {
729
+ const block = result.content.length === 1 ? result.content[0] : undefined;
730
+ if (block === undefined || block.type !== "text")
731
+ return undefined;
732
+ const raw = block.text ?? "";
733
+ if (args.run_in_background === true || result.isError) {
734
+ return { card: "generic", content: [{ type: "text", text: "```console\n" + raw.replace(/\n+$/, "") + "\n```" }] };
735
+ }
736
+ const { body, ...exit } = parseExitStatus(raw);
737
+ return { card: "terminal", output: body, ...exit };
738
+ }
739
+ }));
740
+ }
741
+ //#region internals for tests
742
+ export const internals = {
743
+ candidateExists,
744
+ resolveAllPaths,
745
+ resolveWorkdir,
746
+ renderResult,
747
+ processOutcome,
748
+ startBackground,
749
+ runForeground,
750
+ spawnSpec,
751
+ buildEnv,
752
+ buildArgv,
753
+ validateArgs,
754
+ toolDescription,
755
+ SHELL_DESCRIPTIONS,
756
+ DEFAULT_TIMEOUT_MS,
757
+ MAX_TIMEOUT_MS,
758
+ DEFAULT_MAX_OUTPUT_BYTES
759
+ };