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/terminal.ts CHANGED
@@ -1,612 +1,616 @@
1
- // dsh-bash-terminal-ts: interactive terminal tool over the official PTY seam.
2
- // ctx.subprocess.spawnTerminal (node-pty under the hood) allocates a real
3
- // terminal; this module owns model-facing sessions: open / send / read /
4
- // signal (Ctrl+C etc.) / close. The backend follows the user's default
5
- // terminal setting, exactly like the shell tool.
6
- //
7
- // Windows note: the official seam's process inspector is POSIX-only
8
- // (createProcessInspector throws on win32), so on Windows the PTY is
9
- // allocated directly through node-pty. Session readiness here is
10
- // output-quiet based (waitSettled), which needs no process inspection.
11
-
12
- import { randomUUID } from "node:crypto";
13
- import { isAbsolute, resolve } from "node:path";
14
- import { PassThrough } from "node:stream";
15
- import { TOOL_ABORTED, defineTool, HarnessError } from "./dsh.js";
16
- // Single source of truth for backend env (msys2 MSYSTEM injection, WSL WSLENV).
17
- // The cycle with ./index.js is safe: buildEnv is a hoisted function declaration
18
- // and is only called at tool-execution time, never during module evaluation.
19
- import { buildEnv } from "./index.js";
20
- import type {
21
- BashTerminalContext,
22
- JobsRegistry,
23
- ResolvedPaths,
24
- TerminalHandle,
25
- TerminalSpawnSpec
26
- } from "./dsh-types.js";
27
-
28
- const MAX_BUFFER_BYTES = 1024 * 1024;
29
- const DEFAULT_ROWS = 30;
30
- const DEFAULT_COLS = 110;
31
- const DEFAULT_IDLE_MS = 10 * 60 * 1000;
32
- const MAX_SESSIONS = 8;
33
- const TERMINAL_SIGNALS = ["SIGINT", "SIGTERM", "SIGKILL", "SIGTSTP", "SIGHUP"] as const;
34
-
35
- export type TerminalSignal = (typeof TERMINAL_SIGNALS)[number];
36
-
37
- function delay(ms: number): Promise<void> {
38
- return new Promise((resolveDelay) => setTimeout(resolveDelay, ms));
39
- }
40
-
41
- interface TerminalBufferRead {
42
- delta: string;
43
- nextOffset: number;
44
- truncated: boolean;
45
- }
46
-
47
- interface TerminalBuffer {
48
- append(chunk: string): void;
49
- readFrom(offset: number): TerminalBufferRead;
50
- snapshot(): string;
51
- wasTruncated(): boolean;
52
- lastAppendAt(): number;
53
- }
54
-
55
- /**
56
- * Wait until the terminal output goes quiet (no new bytes for quietMs) or the
57
- * cap elapses. Reads after interactive input then return the complete reply
58
- * instead of a fixed-delay slice.
59
- */
60
- async function waitSettled(buffer: TerminalBuffer, quietMs = 300, timeoutMs = 5000): Promise<void> {
61
- const start = Date.now();
62
- let last = buffer.lastAppendAt();
63
- while (Date.now() - start < timeoutMs) {
64
- await delay(80);
65
- const now = buffer.lastAppendAt();
66
- if (now > last) {
67
- last = now;
68
- continue;
69
- }
70
- if (Date.now() - last >= quietMs) return;
71
- }
72
- }
73
-
74
- /** Interactive-shell argv (no -c: the terminal itself is the session). */
75
- export function terminalArgv(
76
- shell: string,
77
- paths: ResolvedPaths,
78
- distro?: string
79
- ): Array<string | undefined> {
80
- switch (shell) {
81
- case "powershell": return [paths.pwsh, "-NoLogo", "-NoProfile"];
82
- case "gitbash": return [paths.gitbash, "-i"];
83
- case "payload": return [paths.payload, "-i"];
84
- case "msys2":
85
- // -l, NOT -lc: this argv carries no command (the PTY itself is the
86
- // session), and `bash -lc` with no operand dies immediately with
87
- // "-c: option requires an argument" (measured: exit 2). A login shell is
88
- // also what sources /etc/profile, putting /usr/bin and /mingw64/bin on
89
- // PATH for the interactive session.
90
- return [paths.msys2, "-l"];
91
- case "wsl": {
92
- // Verified under ConPTY: 'wsl -e bash -i' on the DEFAULT distro fails with
93
- // a WSL service RPC error (0x8007072c), while 'wsl -- bash -i' works;
94
- // with an explicit -d distro, '-e bash -i' also works.
95
- if (distro !== undefined && distro.trim().length > 0) {
96
- return [paths.wsl, "-d", distro.trim(), "-e", "bash", "-i"];
97
- }
98
- return [paths.wsl, "--", "bash", "-i"];
99
- }
100
- default: throw new Error("invalid shell: " + JSON.stringify(shell));
101
- }
102
- }
103
-
104
- /** In-memory output ring for one session (drop-oldest at the cap). */
105
- function createBuffer(): TerminalBuffer {
106
- let text = "";
107
- let truncated = false;
108
- let lastAppendAt = Date.now();
109
- return {
110
- append(chunk: string) {
111
- text += chunk;
112
- lastAppendAt = Date.now();
113
- if (text.length > MAX_BUFFER_BYTES) {
114
- text = text.slice(text.length - MAX_BUFFER_BYTES);
115
- truncated = true;
116
- }
117
- },
118
- readFrom(offset: number): TerminalBufferRead {
119
- const delta = offset >= text.length ? "" : text.slice(offset);
120
- return { delta, nextOffset: text.length, truncated };
121
- },
122
- snapshot: () => text,
123
- wasTruncated: () => truncated,
124
- lastAppendAt: () => lastAppendAt
125
- };
126
- }
127
-
128
- /** Minimal node-pty face used by the direct-win32 path (shape-cast at import). */
129
- interface NodePtyTerm {
130
- pid: number;
131
- write(data: string): void;
132
- /** Resize the PTY window (ConPTY propagates it to the foreground process). */
133
- resize(cols: number, rows: number): void;
134
- kill(signal?: string): void;
135
- onData(callback: (chunk: string) => void): void;
136
- onExit(callback: (event: { exitCode: number; signal: unknown }) => void): void;
137
- }
138
-
139
- type NodePtySpawn = (
140
- file: string,
141
- args: readonly string[],
142
- options: { name: string; cols: number; rows: number; cwd: string; env: Record<string, string | undefined> }
143
- ) => NodePtyTerm;
144
-
145
- /**
146
- * node-pty >=1.2.0-beta (ConPTY dll path) assigns the inner pid only after the
147
- * agent connects its data pipe; it reads 0 before that. The 1.1.x line reports
148
- * it synchronously, so waiting is a no-op there.
149
- */
150
- async function waitForPid(term: NodePtyTerm, timeoutMs = 5000): Promise<void> {
151
- const deadline = Date.now() + timeoutMs;
152
- while (term.pid <= 0 && Date.now() < deadline) await delay(25);
153
- if (term.pid <= 0) {
154
- try { term.kill(); } catch { /* already dead */ }
155
- throw new Error("terminal: node-pty did not report a process id within " + timeoutMs + "ms (ConPTY agent did not connect)");
156
- }
157
- }
158
-
159
- /** Terminal-emulator options for one PTY allocation. */
160
- export interface PtyStyle {
161
- /** The terminal type the PTY advertises (and the one `$TERM` should say). */
162
- readonly name: string;
163
- /**
164
- * Variables forced into the child environment. The model tool pins
165
- * `TERM=dumb`/`NO_COLOR=1` so output stays parseable; the browser terminal
166
- * passes `{}` because its whole point is a coloured, cursor-controlled screen.
167
- */
168
- readonly forceEnv: Readonly<Record<string, string | undefined>>;
169
- }
170
-
171
- /** The tool's own style: a dumb, colourless, pager-free screen. */
172
- export const TOOL_PTY_STYLE: PtyStyle = { name: "dumb", forceEnv: { TERM: "dumb", NO_COLOR: "1" } };
173
-
174
- /** The browser terminal's style: a real xterm, colours and cursor control on. */
175
- export const UI_PTY_STYLE: PtyStyle = { name: "xterm-256color", forceEnv: {} };
176
-
177
- /**
178
- * Direct node-pty handle with the same surface the official seam returns:
179
- * output (stream), pid, done, write / signalForeground / terminate, plus
180
- * `resize` (which the seam only grew on newer host lines, so callers probe).
181
- * Used on win32, where the official `spawnTerminal`'s process inspector is
182
- * unsupported.
183
- *
184
- * `style` is a parameter rather than a constant because the ConPTY quirks below
185
- * are shared by both consumers: a second copy of this function is how the
186
- * browser terminal would end up with the tool's `TERM=dumb`.
187
- */
188
- export async function spawnPtyHandle(spec: TerminalSpawnSpec, style: PtyStyle = TOOL_PTY_STYLE): Promise<TerminalHandle & { resize(cols: number, rows: number): void }> {
189
- const { argv, cwd, env, rows, cols } = spec;
190
- const mod = (await import("node-pty")) as unknown as { default?: { spawn: NodePtySpawn }; spawn: NodePtySpawn };
191
- const nodePty = mod.default ?? mod;
192
- const term = nodePty.spawn(argv[0]!, argv.slice(1), {
193
- name: style.name,
194
- cols,
195
- rows,
196
- cwd,
197
- env: { ...env, ...style.forceEnv },
198
- });
199
- await waitForPid(term);
200
- const output = new PassThrough();
201
- term.onData((chunk) => output.write(Buffer.from(chunk, "utf8")));
202
- const done = new Promise<{ exitCode: number; signal: string | null }>((resolveDone) => {
203
- term.onExit(({ exitCode, signal }) => resolveDone({ exitCode, signal: typeof signal === "string" ? signal : null }));
204
- });
205
- return {
206
- pid: term.pid,
207
- output,
208
- done,
209
- write: (data) => term.write(data),
210
- // ConPTY honours a real resize; the tool path never calls it, so this is the
211
- // one seam capability the browser terminal adds on top of the same handle.
212
- resize: (nextCols, nextRows) => term.resize(nextCols, nextRows),
213
- // node-pty accepts no named signals on Windows: Ctrl+C is the \x03 byte
214
- // (ConPTY delivers it to the foreground process), other signals degrade
215
- // to terminating the session.
216
- signalForeground: (sig) => {
217
- if (sig === "SIGINT") { term.write("\x03"); return; }
218
- term.kill();
219
- },
220
- terminate: async () => { try { term.kill(); } catch { /* already dead */ } }
221
- };
222
- }
223
-
224
- export interface TerminalSessionInfo {
225
- sessionId: string;
226
- shell: string;
227
- pid: number;
228
- closed: boolean;
229
- }
230
-
231
- interface TerminalSession {
232
- id: string;
233
- handle: TerminalHandle;
234
- buffer: TerminalBuffer;
235
- shell: string;
236
- distro?: string;
237
- closed: boolean;
238
- idleMs: number;
239
- idleTimer?: NodeJS.Timeout;
240
- touch: () => void;
241
- }
242
-
243
- export interface TerminalOpenOptions {
244
- argv: string[];
245
- shell: string;
246
- cwd: string;
247
- env: Record<string, string | undefined>;
248
- rows: number;
249
- cols: number;
250
- distro?: string;
251
- initial?: string;
252
- idleMs?: number;
253
- }
254
-
255
- export interface TerminalRegistry {
256
- open(options: TerminalOpenOptions): Promise<TerminalSession>;
257
- get(id: string): TerminalSession;
258
- send(id: string, input: string): Promise<TerminalBufferRead>;
259
- read(id: string): TerminalBufferRead;
260
- signal(id: string, sig: string): Promise<TerminalBufferRead>;
261
- close(id: string): Promise<boolean>;
262
- list(): TerminalSessionInfo[];
263
- }
264
-
265
- /**
266
- * Terminal-session registry owned by the plugin fiber: opens PTYs through
267
- * the official seam, forwards output into a capped buffer, and tears every
268
- * session down on plugin disposal.
269
- */
270
- export function createTerminalRegistry(ctx: BashTerminalContext): TerminalRegistry {
271
- const sessions = new Map<string, TerminalSession>();
272
- ctx.effect(() => () => {
273
- for (const session of sessions.values()) {
274
- void session.handle.terminate().catch(() => { /* already dead */ });
275
- }
276
- sessions.clear();
277
- }, "bash-terminal: terminal sessions teardown");
278
-
279
- async function open(options: TerminalOpenOptions): Promise<TerminalSession> {
280
- const { argv, shell, cwd, env, rows, cols, distro, initial, idleMs } = options;
281
- if (sessions.size >= MAX_SESSIONS) {
282
- throw new Error("terminal: too many open sessions (" + MAX_SESSIONS + "); close one before opening another");
283
- }
284
- let handle: TerminalHandle;
285
- if (process.platform === "win32") {
286
- handle = await spawnPtyHandle({ argv, cwd, env, rows, cols });
287
- } else {
288
- const spawnTerminal = ctx.subprocess?.spawnTerminal;
289
- if (spawnTerminal === undefined) {
290
- throw new Error("terminal: ctx.subprocess.spawnTerminal seam unavailable");
291
- }
292
- handle = await spawnTerminal({ argv, cwd, env, rows, cols, graceMs: 3000 });
293
- }
294
- const buffer = createBuffer();
295
- handle.output.on("data", (chunk: unknown) => buffer.append(typeof chunk === "string" ? chunk : String(chunk)));
296
- const session: TerminalSession = {
297
- id: randomUUID(),
298
- handle,
299
- buffer,
300
- shell,
301
- distro,
302
- closed: false,
303
- idleMs: idleMs ?? DEFAULT_IDLE_MS,
304
- touch: () => { /* replaced below */ }
305
- };
306
- // Idle guard: any read/send/signal touches the timer; expiry terminates the
307
- // session so an abandoned PTY never leaks a process tree.
308
- const touch = (): void => {
309
- if (session.closed) return;
310
- clearTimeout(session.idleTimer);
311
- session.idleTimer = setTimeout(() => {
312
- if (session.closed) return;
313
- session.closed = true;
314
- sessions.delete(session.id);
315
- void session.handle.terminate().catch(() => { /* already dead */ });
316
- }, session.idleMs);
317
- };
318
- session.touch = touch;
319
- touch();
320
- sessions.set(session.id, session);
321
- if (initial !== undefined && initial.length > 0) {
322
- await handle.write(initial);
323
- await waitSettled(buffer);
324
- }
325
- return session;
326
- }
327
-
328
- function get(id: string): TerminalSession {
329
- const session = sessions.get(id);
330
- if (session === undefined) throw new Error("terminal session not found: " + JSON.stringify(id));
331
- if (session.closed) throw new Error("terminal session is closed: " + JSON.stringify(id));
332
- session.touch();
333
- return session;
334
- }
335
-
336
- async function send(id: string, input: string): Promise<TerminalBufferRead> {
337
- const session = get(id);
338
- await session.handle.write(input);
339
- await waitSettled(session.buffer);
340
- return read(id);
341
- }
342
-
343
- async function signal(id: string, sig: string): Promise<TerminalBufferRead> {
344
- const session = get(id);
345
- if (!(TERMINAL_SIGNALS as readonly string[]).includes(sig)) {
346
- throw new Error("invalid terminal signal: " + JSON.stringify(sig));
347
- }
348
- await session.handle.signalForeground(sig);
349
- await waitSettled(session.buffer);
350
- return read(id);
351
- }
352
-
353
- function read(id: string): TerminalBufferRead {
354
- const session = get(id);
355
- const { delta, nextOffset, truncated } = session.buffer.readFrom(0);
356
- return { delta, nextOffset, truncated };
357
- }
358
-
359
- async function close(id: string): Promise<boolean> {
360
- const session = get(id);
361
- session.closed = true;
362
- clearTimeout(session.idleTimer);
363
- sessions.delete(id);
364
- await session.handle.terminate();
365
- return true;
366
- }
367
-
368
- function list(): TerminalSessionInfo[] {
369
- return [...sessions.values()].map((session) => ({
370
- sessionId: session.id,
371
- shell: session.shell,
372
- pid: session.handle.pid,
373
- closed: session.closed
374
- }));
375
- }
376
-
377
- return { open, get, send, read, signal, close, list };
378
- }
379
-
380
- /** The terminal tool's arguments after runtime validation (discriminated by action). */
381
- export type ValidatedTerminalArgs =
382
- | { action: "open"; sessionId?: string; command?: string; distro?: string; workdir?: string; idleMs?: number }
383
- | { action: "send"; sessionId: string; input: string }
384
- | { action: "read"; sessionId: string }
385
- | { action: "signal"; sessionId: string; signal: TerminalSignal }
386
- | { action: "close"; sessionId: string }
387
- | { action: "list" };
388
-
389
- export function validateArgs(args: Record<string, unknown>): asserts args is ValidatedTerminalArgs {
390
- const action = args.action;
391
- if (typeof action !== "string" || ["open", "send", "read", "signal", "close", "list"].indexOf(action) === -1) {
392
- throw new Error("invalid action: expected open, send, read, signal, close, or list");
393
- }
394
- if ((action === "send" || action === "read" || action === "signal" || action === "close") && (typeof args.sessionId !== "string" || args.sessionId.length === 0)) {
395
- throw new Error("invalid sessionId: required for " + action);
396
- }
397
- if (action === "send" && (typeof args.input !== "string" || args.input.length === 0)) {
398
- throw new Error("invalid input: expected a non-empty string for send");
399
- }
400
- if (action === "signal" && (typeof args.signal !== "string" || (TERMINAL_SIGNALS as readonly string[]).indexOf(args.signal) === -1)) {
401
- throw new Error("invalid signal: expected one of " + TERMINAL_SIGNALS.join(", "));
402
- }
403
- }
404
-
405
- export interface TerminalOpenResult {
406
- kind: "open";
407
- sessionId: string;
408
- jobId?: string;
409
- pid: number;
410
- shell: string;
411
- output: string;
412
- }
413
-
414
- export interface TerminalSessionResult {
415
- kind: "session";
416
- output: string;
417
- truncated?: boolean;
418
- }
419
-
420
- export interface TerminalClosedResult {
421
- kind: "closed";
422
- sessionId: string;
423
- }
424
-
425
- export interface TerminalListResult {
426
- kind: "list";
427
- sessions: TerminalSessionInfo[];
428
- }
429
-
430
- export type TerminalToolResult = TerminalOpenResult | TerminalSessionResult | TerminalClosedResult | TerminalListResult;
431
-
432
- export function terminalTool(
433
- ctx: BashTerminalContext,
434
- registry: TerminalRegistry,
435
- paths: ResolvedPaths,
436
- defaultShell: () => string
437
- ) {
438
- return defineTool<TerminalToolResult>({
439
- name: "terminal",
440
- description: "Interactive terminal session over the user's default terminal (Settings -> General -> Default terminal: powershell / gitbash / msys2 / wsl). A real PTY hosts a persistent shell: open a session, send input and read output across turns, deliver signals (Ctrl+C = SIGINT) to the foreground process, and close when done. Backend and env follow the shell tool exactly; the session survives between calls until closed and is managed as a background job (job_kill / job_output work on it); idle sessions close automatically. Use this for interactive programs (REPLs, ssh, databases, TUI tools) or when you need shell state (cwd, variables, aliases) to persist across calls.",
441
- parameters: {
442
- action: {
443
- type: "string",
444
- enum: ["open", "send", "read", "signal", "close", "list"],
445
- required: true,
446
- description: "open: create a session and return its id. send: write input and read new output. read: read new output without writing. signal: send a signal to the foreground process (SIGINT for Ctrl+C). close: terminate the session. list: list live sessions."
447
- },
448
- sessionId: {
449
- type: "string",
450
- description: "Session id returned by open; required for send/read/signal/close."
451
- },
452
- command: {
453
- type: "string",
454
- description: "With action open: optional command to run immediately in the fresh shell (Enter appended). Default starts an interactive shell."
455
- },
456
- distro: {
457
- type: "string",
458
- description: "WSL distribution (only when the configured default terminal is wsl)."
459
- },
460
- input: {
461
- type: "string",
462
- description: "With action send: the input to write (no implicit newline; append \\n or \\r for Enter)."
463
- },
464
- signal: {
465
- type: "string",
466
- enum: TERMINAL_SIGNALS,
467
- description: "With action signal: signal to the foreground process group (SIGINT = Ctrl+C, SIGKILL, SIGTERM, SIGTSTP, SIGHUP)."
468
- },
469
- workdir: {
470
- type: "string",
471
- description: "Working directory for the session (open only). Defaults to the session workspace."
472
- },
473
- idleMs: {
474
- type: "number",
475
- description: "Idle timeout in ms (open only): the session closes automatically after this long without send/read/signal. Default 600000 (10 min)."
476
- }
477
- },
478
- output: {
479
- schema: {
480
- oneOf: [
481
- {
482
- type: "object",
483
- additionalProperties: false,
484
- properties: {
485
- kind: { type: "string", required: true, const: "open" },
486
- sessionId: { type: "string", required: true },
487
- jobId: { type: "string" },
488
- pid: { type: "integer", required: true },
489
- shell: { type: "string", required: true },
490
- output: { type: "string" }
491
- }
492
- },
493
- {
494
- type: "object",
495
- additionalProperties: false,
496
- properties: {
497
- kind: { type: "string", required: true, const: "session" },
498
- output: { type: "string", required: true },
499
- truncated: { type: "boolean" }
500
- }
501
- },
502
- {
503
- type: "object",
504
- additionalProperties: false,
505
- properties: {
506
- kind: { type: "string", required: true, const: "closed" },
507
- sessionId: { type: "string", required: true }
508
- }
509
- },
510
- {
511
- type: "object",
512
- additionalProperties: false,
513
- properties: {
514
- kind: { type: "string", required: true, const: "list" },
515
- sessions: {
516
- type: "array",
517
- items: {
518
- type: "object",
519
- additionalProperties: false,
520
- properties: {
521
- sessionId: { type: "string", required: true },
522
- shell: { type: "string", required: true },
523
- pid: { type: "integer", required: true },
524
- closed: { type: "boolean" }
525
- }
526
- }
527
- }
528
- }
529
- }
530
- ]
531
- },
532
- render: (_args, value) => [{
533
- type: "text",
534
- text: value.kind === "open"
535
- ? "terminal session " + value.sessionId + " (pid " + value.pid + ", " + value.shell + ")" + (value.output ? "\n" + value.output : "")
536
- : value.kind === "closed"
537
- ? "terminal session " + value.sessionId + " closed"
538
- : value.kind === "list"
539
- ? (value.sessions.length === 0 ? "no open terminal sessions" : value.sessions.map((s) => s.sessionId + " (" + s.shell + ", pid " + s.pid + ")").join("\n"))
540
- : value.truncated === true
541
- ? (value.output.length === 0 ? "[terminal buffer overflowed; oldest output dropped]" : value.output + "\n[terminal buffer overflowed; oldest output dropped]")
542
- : value.output
543
- }]
544
- },
545
- async execute(args, exec): Promise<TerminalToolResult> {
546
- validateArgs(args);
547
- if (exec.signal.aborted) {
548
- const error = new HarnessError("tool call aborted", TOOL_ABORTED);
549
- error.name = "AbortError";
550
- throw error;
551
- }
552
- const headerCwd = exec.agent?.session.header.cwd;
553
- switch (args.action) {
554
- case "open": {
555
- const shell = defaultShell();
556
- const argv0 = terminalArgv(shell, paths, args.distro);
557
- if (argv0[0] === undefined) throw new Error("terminal: " + shell + " backend unavailable - executable not found");
558
- // Only element 0 (the resolved executable) can be undefined; guarded above.
559
- const argv = argv0 as string[];
560
- const cwd = args.workdir !== undefined ? (headerCwd !== undefined && !isAbsolute(args.workdir) ? resolve(headerCwd, args.workdir) : args.workdir) : (headerCwd ?? process.cwd());
561
- // buildEnv, not an inline duplicate: the msys2 backend needs its
562
- // MSYSTEM=MINGW64 injection here too, or the login shell sources
563
- // /etc/profile with the default MSYS environment and /mingw64/bin
564
- // (gcc, make) never joins PATH. It also owns the WSL WSLENV layering,
565
- // so a terminal session's env follows the shell tool exactly.
566
- // process.env.WSLENV is passed explicitly: spawnTerminal replaces the
567
- // child environment wholesale (childEnv(spec.env)), so the ambient
568
- // allow-list is not otherwise visible and inherited entries such as
569
- // WT_SESSION / WT_PROFILE_ID would be dropped.
570
- const env = buildEnv(shell, ctx.shellEnv.collect(exec), process.env.WSLENV);
571
- const session = await registry.open({ argv, shell, cwd, env, rows: DEFAULT_ROWS, cols: DEFAULT_COLS, distro: args.distro, initial: args.command !== undefined ? args.command + "\r" : undefined, idleMs: args.idleMs });
572
- const jobs = ctx.get("jobs") as JobsRegistry | undefined;
573
- const jobId = jobs === undefined ? undefined : jobs.start({
574
- kind: "terminal/session",
575
- label: "terminal " + session.id.slice(0, 8) + " (" + shell + ")",
576
- ...(exec.agent ? { owner: exec.agent } : {}),
577
- run: () => ({
578
- cancel: () => { void session.handle.terminate().catch(() => { /* already dead */ }); },
579
- done: session.handle.done,
580
- readOutput: () => registry.read(session.id).delta
581
- })
582
- });
583
- return { kind: "open", sessionId: session.id, ...(jobId !== undefined ? { jobId } : {}), pid: session.handle.pid, shell, output: session.buffer.snapshot() };
584
- }
585
- case "send": {
586
- const { delta, truncated } = await registry.send(args.sessionId, args.input);
587
- return { kind: "session", output: delta, ...(truncated ? { truncated } : {}) };
588
- }
589
- case "read": {
590
- const { delta, truncated } = registry.read(args.sessionId);
591
- return { kind: "session", output: delta, ...(truncated ? { truncated } : {}) };
592
- }
593
- case "signal": {
594
- const { delta, truncated } = await registry.signal(args.sessionId, args.signal);
595
- return { kind: "session", output: delta, ...(truncated ? { truncated } : {}) };
596
- }
597
- case "close": {
598
- await registry.close(args.sessionId);
599
- return { kind: "closed", sessionId: args.sessionId };
600
- }
601
- case "list": {
602
- return { kind: "list", sessions: registry.list() };
603
- }
604
- }
605
- },
606
- presentCall: (args) => ({
607
- card: "terminal",
608
- title: "terminal " + String(args.action) + (args.sessionId !== undefined ? " " + String(args.sessionId) : ""),
609
- ...(args.input !== undefined ? { description: args.input } : {})
610
- })
611
- });
612
- }
1
+ // dsh-bash-terminal-ts: interactive terminal tool over the official PTY seam.
2
+ // ctx.subprocess.spawnTerminal (node-pty under the hood) allocates a real
3
+ // terminal; this module owns model-facing sessions: open / send / read /
4
+ // signal (Ctrl+C etc.) / close. The backend follows the user's default
5
+ // terminal setting, exactly like the shell tool.
6
+ //
7
+ // Windows note: the official seam's process inspector is POSIX-only
8
+ // (createProcessInspector throws on win32), so on Windows the PTY is
9
+ // allocated directly through node-pty. Session readiness here is
10
+ // output-quiet based (waitSettled), which needs no process inspection.
11
+
12
+ import { randomUUID } from "node:crypto";
13
+ import { isAbsolute, resolve } from "node:path";
14
+ import { PassThrough } from "node:stream";
15
+ import { TOOL_ABORTED, defineTool, HarnessError } from "./dsh.js";
16
+ // Single source of truth for backend env (msys2 MSYSTEM injection, WSL WSLENV).
17
+ // The cycle with ./index.js is safe: buildEnv is a hoisted function declaration
18
+ // and is only called at tool-execution time, never during module evaluation.
19
+ import { buildEnv } from "./index.js";
20
+ import type {
21
+ BashTerminalContext,
22
+ JobsRegistry,
23
+ ResolvedPaths,
24
+ TerminalHandle,
25
+ TerminalSpawnSpec
26
+ } from "./dsh-types.js";
27
+
28
+ const MAX_BUFFER_BYTES = 1024 * 1024;
29
+ const DEFAULT_ROWS = 30;
30
+ const DEFAULT_COLS = 110;
31
+ const DEFAULT_IDLE_MS = 10 * 60 * 1000;
32
+ const MAX_SESSIONS = 8;
33
+ const TERMINAL_SIGNALS = ["SIGINT", "SIGTERM", "SIGKILL", "SIGTSTP", "SIGHUP"] as const;
34
+
35
+ export type TerminalSignal = (typeof TERMINAL_SIGNALS)[number];
36
+
37
+ function delay(ms: number): Promise<void> {
38
+ return new Promise((resolveDelay) => setTimeout(resolveDelay, ms));
39
+ }
40
+
41
+ interface TerminalBufferRead {
42
+ delta: string;
43
+ nextOffset: number;
44
+ truncated: boolean;
45
+ }
46
+
47
+ interface TerminalBuffer {
48
+ append(chunk: string): void;
49
+ readFrom(offset: number): TerminalBufferRead;
50
+ snapshot(): string;
51
+ wasTruncated(): boolean;
52
+ lastAppendAt(): number;
53
+ }
54
+
55
+ /**
56
+ * Wait until the terminal output goes quiet (no new bytes for quietMs) or the
57
+ * cap elapses. Reads after interactive input then return the complete reply
58
+ * instead of a fixed-delay slice.
59
+ */
60
+ async function waitSettled(buffer: TerminalBuffer, quietMs = 300, timeoutMs = 5000): Promise<void> {
61
+ const start = Date.now();
62
+ let last = buffer.lastAppendAt();
63
+ while (Date.now() - start < timeoutMs) {
64
+ await delay(80);
65
+ const now = buffer.lastAppendAt();
66
+ if (now > last) {
67
+ last = now;
68
+ continue;
69
+ }
70
+ if (Date.now() - last >= quietMs) return;
71
+ }
72
+ }
73
+
74
+ /** Interactive-shell argv (no -c: the terminal itself is the session). */
75
+ export function terminalArgv(
76
+ shell: string,
77
+ paths: ResolvedPaths,
78
+ distro?: string
79
+ ): Array<string | undefined> {
80
+ switch (shell) {
81
+ case "powershell": return [paths.pwsh, "-NoLogo", "-NoProfile"];
82
+ case "gitbash": return [paths.gitbash, "-i"];
83
+ case "payload": return [paths.payload, "-i"];
84
+ case "niu":
85
+ // Interactive non-login: reads ~/.niubashrc (the only startup file niu
86
+ // reads on Windows), keeps the user's prompt and colours.
87
+ return [paths.niu, "-i"];
88
+ case "msys2":
89
+ // -l, NOT -lc: this argv carries no command (the PTY itself is the
90
+ // session), and `bash -lc` with no operand dies immediately with
91
+ // "-c: option requires an argument" (measured: exit 2). A login shell is
92
+ // also what sources /etc/profile, putting /usr/bin and /mingw64/bin on
93
+ // PATH for the interactive session.
94
+ return [paths.msys2, "-l"];
95
+ case "wsl": {
96
+ // Verified under ConPTY: 'wsl -e bash -i' on the DEFAULT distro fails with
97
+ // a WSL service RPC error (0x8007072c), while 'wsl -- bash -i' works;
98
+ // with an explicit -d distro, '-e bash -i' also works.
99
+ if (distro !== undefined && distro.trim().length > 0) {
100
+ return [paths.wsl, "-d", distro.trim(), "-e", "bash", "-i"];
101
+ }
102
+ return [paths.wsl, "--", "bash", "-i"];
103
+ }
104
+ default: throw new Error("invalid shell: " + JSON.stringify(shell));
105
+ }
106
+ }
107
+
108
+ /** In-memory output ring for one session (drop-oldest at the cap). */
109
+ function createBuffer(): TerminalBuffer {
110
+ let text = "";
111
+ let truncated = false;
112
+ let lastAppendAt = Date.now();
113
+ return {
114
+ append(chunk: string) {
115
+ text += chunk;
116
+ lastAppendAt = Date.now();
117
+ if (text.length > MAX_BUFFER_BYTES) {
118
+ text = text.slice(text.length - MAX_BUFFER_BYTES);
119
+ truncated = true;
120
+ }
121
+ },
122
+ readFrom(offset: number): TerminalBufferRead {
123
+ const delta = offset >= text.length ? "" : text.slice(offset);
124
+ return { delta, nextOffset: text.length, truncated };
125
+ },
126
+ snapshot: () => text,
127
+ wasTruncated: () => truncated,
128
+ lastAppendAt: () => lastAppendAt
129
+ };
130
+ }
131
+
132
+ /** Minimal node-pty face used by the direct-win32 path (shape-cast at import). */
133
+ interface NodePtyTerm {
134
+ pid: number;
135
+ write(data: string): void;
136
+ /** Resize the PTY window (ConPTY propagates it to the foreground process). */
137
+ resize(cols: number, rows: number): void;
138
+ kill(signal?: string): void;
139
+ onData(callback: (chunk: string) => void): void;
140
+ onExit(callback: (event: { exitCode: number; signal: unknown }) => void): void;
141
+ }
142
+
143
+ type NodePtySpawn = (
144
+ file: string,
145
+ args: readonly string[],
146
+ options: { name: string; cols: number; rows: number; cwd: string; env: Record<string, string | undefined> }
147
+ ) => NodePtyTerm;
148
+
149
+ /**
150
+ * node-pty >=1.2.0-beta (ConPTY dll path) assigns the inner pid only after the
151
+ * agent connects its data pipe; it reads 0 before that. The 1.1.x line reports
152
+ * it synchronously, so waiting is a no-op there.
153
+ */
154
+ async function waitForPid(term: NodePtyTerm, timeoutMs = 5000): Promise<void> {
155
+ const deadline = Date.now() + timeoutMs;
156
+ while (term.pid <= 0 && Date.now() < deadline) await delay(25);
157
+ if (term.pid <= 0) {
158
+ try { term.kill(); } catch { /* already dead */ }
159
+ throw new Error("terminal: node-pty did not report a process id within " + timeoutMs + "ms (ConPTY agent did not connect)");
160
+ }
161
+ }
162
+
163
+ /** Terminal-emulator options for one PTY allocation. */
164
+ export interface PtyStyle {
165
+ /** The terminal type the PTY advertises (and the one `$TERM` should say). */
166
+ readonly name: string;
167
+ /**
168
+ * Variables forced into the child environment. The model tool pins
169
+ * `TERM=dumb`/`NO_COLOR=1` so output stays parseable; the browser terminal
170
+ * passes `{}` because its whole point is a coloured, cursor-controlled screen.
171
+ */
172
+ readonly forceEnv: Readonly<Record<string, string | undefined>>;
173
+ }
174
+
175
+ /** The tool's own style: a dumb, colourless, pager-free screen. */
176
+ export const TOOL_PTY_STYLE: PtyStyle = { name: "dumb", forceEnv: { TERM: "dumb", NO_COLOR: "1" } };
177
+
178
+ /** The browser terminal's style: a real xterm, colours and cursor control on. */
179
+ export const UI_PTY_STYLE: PtyStyle = { name: "xterm-256color", forceEnv: {} };
180
+
181
+ /**
182
+ * Direct node-pty handle with the same surface the official seam returns:
183
+ * output (stream), pid, done, write / signalForeground / terminate, plus
184
+ * `resize` (which the seam only grew on newer host lines, so callers probe).
185
+ * Used on win32, where the official `spawnTerminal`'s process inspector is
186
+ * unsupported.
187
+ *
188
+ * `style` is a parameter rather than a constant because the ConPTY quirks below
189
+ * are shared by both consumers: a second copy of this function is how the
190
+ * browser terminal would end up with the tool's `TERM=dumb`.
191
+ */
192
+ export async function spawnPtyHandle(spec: TerminalSpawnSpec, style: PtyStyle = TOOL_PTY_STYLE): Promise<TerminalHandle & { resize(cols: number, rows: number): void }> {
193
+ const { argv, cwd, env, rows, cols } = spec;
194
+ const mod = (await import("node-pty")) as unknown as { default?: { spawn: NodePtySpawn }; spawn: NodePtySpawn };
195
+ const nodePty = mod.default ?? mod;
196
+ const term = nodePty.spawn(argv[0]!, argv.slice(1), {
197
+ name: style.name,
198
+ cols,
199
+ rows,
200
+ cwd,
201
+ env: { ...env, ...style.forceEnv },
202
+ });
203
+ await waitForPid(term);
204
+ const output = new PassThrough();
205
+ term.onData((chunk) => output.write(Buffer.from(chunk, "utf8")));
206
+ const done = new Promise<{ exitCode: number; signal: string | null }>((resolveDone) => {
207
+ term.onExit(({ exitCode, signal }) => resolveDone({ exitCode, signal: typeof signal === "string" ? signal : null }));
208
+ });
209
+ return {
210
+ pid: term.pid,
211
+ output,
212
+ done,
213
+ write: (data) => term.write(data),
214
+ // ConPTY honours a real resize; the tool path never calls it, so this is the
215
+ // one seam capability the browser terminal adds on top of the same handle.
216
+ resize: (nextCols, nextRows) => term.resize(nextCols, nextRows),
217
+ // node-pty accepts no named signals on Windows: Ctrl+C is the \x03 byte
218
+ // (ConPTY delivers it to the foreground process), other signals degrade
219
+ // to terminating the session.
220
+ signalForeground: (sig) => {
221
+ if (sig === "SIGINT") { term.write("\x03"); return; }
222
+ term.kill();
223
+ },
224
+ terminate: async () => { try { term.kill(); } catch { /* already dead */ } }
225
+ };
226
+ }
227
+
228
+ export interface TerminalSessionInfo {
229
+ sessionId: string;
230
+ shell: string;
231
+ pid: number;
232
+ closed: boolean;
233
+ }
234
+
235
+ interface TerminalSession {
236
+ id: string;
237
+ handle: TerminalHandle;
238
+ buffer: TerminalBuffer;
239
+ shell: string;
240
+ distro?: string;
241
+ closed: boolean;
242
+ idleMs: number;
243
+ idleTimer?: NodeJS.Timeout;
244
+ touch: () => void;
245
+ }
246
+
247
+ export interface TerminalOpenOptions {
248
+ argv: string[];
249
+ shell: string;
250
+ cwd: string;
251
+ env: Record<string, string | undefined>;
252
+ rows: number;
253
+ cols: number;
254
+ distro?: string;
255
+ initial?: string;
256
+ idleMs?: number;
257
+ }
258
+
259
+ export interface TerminalRegistry {
260
+ open(options: TerminalOpenOptions): Promise<TerminalSession>;
261
+ get(id: string): TerminalSession;
262
+ send(id: string, input: string): Promise<TerminalBufferRead>;
263
+ read(id: string): TerminalBufferRead;
264
+ signal(id: string, sig: string): Promise<TerminalBufferRead>;
265
+ close(id: string): Promise<boolean>;
266
+ list(): TerminalSessionInfo[];
267
+ }
268
+
269
+ /**
270
+ * Terminal-session registry owned by the plugin fiber: opens PTYs through
271
+ * the official seam, forwards output into a capped buffer, and tears every
272
+ * session down on plugin disposal.
273
+ */
274
+ export function createTerminalRegistry(ctx: BashTerminalContext): TerminalRegistry {
275
+ const sessions = new Map<string, TerminalSession>();
276
+ ctx.effect(() => () => {
277
+ for (const session of sessions.values()) {
278
+ void session.handle.terminate().catch(() => { /* already dead */ });
279
+ }
280
+ sessions.clear();
281
+ }, "bash-terminal: terminal sessions teardown");
282
+
283
+ async function open(options: TerminalOpenOptions): Promise<TerminalSession> {
284
+ const { argv, shell, cwd, env, rows, cols, distro, initial, idleMs } = options;
285
+ if (sessions.size >= MAX_SESSIONS) {
286
+ throw new Error("terminal: too many open sessions (" + MAX_SESSIONS + "); close one before opening another");
287
+ }
288
+ let handle: TerminalHandle;
289
+ if (process.platform === "win32") {
290
+ handle = await spawnPtyHandle({ argv, cwd, env, rows, cols });
291
+ } else {
292
+ const spawnTerminal = ctx.subprocess?.spawnTerminal;
293
+ if (spawnTerminal === undefined) {
294
+ throw new Error("terminal: ctx.subprocess.spawnTerminal seam unavailable");
295
+ }
296
+ handle = await spawnTerminal({ argv, cwd, env, rows, cols, graceMs: 3000 });
297
+ }
298
+ const buffer = createBuffer();
299
+ handle.output.on("data", (chunk: unknown) => buffer.append(typeof chunk === "string" ? chunk : String(chunk)));
300
+ const session: TerminalSession = {
301
+ id: randomUUID(),
302
+ handle,
303
+ buffer,
304
+ shell,
305
+ distro,
306
+ closed: false,
307
+ idleMs: idleMs ?? DEFAULT_IDLE_MS,
308
+ touch: () => { /* replaced below */ }
309
+ };
310
+ // Idle guard: any read/send/signal touches the timer; expiry terminates the
311
+ // session so an abandoned PTY never leaks a process tree.
312
+ const touch = (): void => {
313
+ if (session.closed) return;
314
+ clearTimeout(session.idleTimer);
315
+ session.idleTimer = setTimeout(() => {
316
+ if (session.closed) return;
317
+ session.closed = true;
318
+ sessions.delete(session.id);
319
+ void session.handle.terminate().catch(() => { /* already dead */ });
320
+ }, session.idleMs);
321
+ };
322
+ session.touch = touch;
323
+ touch();
324
+ sessions.set(session.id, session);
325
+ if (initial !== undefined && initial.length > 0) {
326
+ await handle.write(initial);
327
+ await waitSettled(buffer);
328
+ }
329
+ return session;
330
+ }
331
+
332
+ function get(id: string): TerminalSession {
333
+ const session = sessions.get(id);
334
+ if (session === undefined) throw new Error("terminal session not found: " + JSON.stringify(id));
335
+ if (session.closed) throw new Error("terminal session is closed: " + JSON.stringify(id));
336
+ session.touch();
337
+ return session;
338
+ }
339
+
340
+ async function send(id: string, input: string): Promise<TerminalBufferRead> {
341
+ const session = get(id);
342
+ await session.handle.write(input);
343
+ await waitSettled(session.buffer);
344
+ return read(id);
345
+ }
346
+
347
+ async function signal(id: string, sig: string): Promise<TerminalBufferRead> {
348
+ const session = get(id);
349
+ if (!(TERMINAL_SIGNALS as readonly string[]).includes(sig)) {
350
+ throw new Error("invalid terminal signal: " + JSON.stringify(sig));
351
+ }
352
+ await session.handle.signalForeground(sig);
353
+ await waitSettled(session.buffer);
354
+ return read(id);
355
+ }
356
+
357
+ function read(id: string): TerminalBufferRead {
358
+ const session = get(id);
359
+ const { delta, nextOffset, truncated } = session.buffer.readFrom(0);
360
+ return { delta, nextOffset, truncated };
361
+ }
362
+
363
+ async function close(id: string): Promise<boolean> {
364
+ const session = get(id);
365
+ session.closed = true;
366
+ clearTimeout(session.idleTimer);
367
+ sessions.delete(id);
368
+ await session.handle.terminate();
369
+ return true;
370
+ }
371
+
372
+ function list(): TerminalSessionInfo[] {
373
+ return [...sessions.values()].map((session) => ({
374
+ sessionId: session.id,
375
+ shell: session.shell,
376
+ pid: session.handle.pid,
377
+ closed: session.closed
378
+ }));
379
+ }
380
+
381
+ return { open, get, send, read, signal, close, list };
382
+ }
383
+
384
+ /** The terminal tool's arguments after runtime validation (discriminated by action). */
385
+ export type ValidatedTerminalArgs =
386
+ | { action: "open"; sessionId?: string; command?: string; distro?: string; workdir?: string; idleMs?: number }
387
+ | { action: "send"; sessionId: string; input: string }
388
+ | { action: "read"; sessionId: string }
389
+ | { action: "signal"; sessionId: string; signal: TerminalSignal }
390
+ | { action: "close"; sessionId: string }
391
+ | { action: "list" };
392
+
393
+ export function validateArgs(args: Record<string, unknown>): asserts args is ValidatedTerminalArgs {
394
+ const action = args.action;
395
+ if (typeof action !== "string" || ["open", "send", "read", "signal", "close", "list"].indexOf(action) === -1) {
396
+ throw new Error("invalid action: expected open, send, read, signal, close, or list");
397
+ }
398
+ if ((action === "send" || action === "read" || action === "signal" || action === "close") && (typeof args.sessionId !== "string" || args.sessionId.length === 0)) {
399
+ throw new Error("invalid sessionId: required for " + action);
400
+ }
401
+ if (action === "send" && (typeof args.input !== "string" || args.input.length === 0)) {
402
+ throw new Error("invalid input: expected a non-empty string for send");
403
+ }
404
+ if (action === "signal" && (typeof args.signal !== "string" || (TERMINAL_SIGNALS as readonly string[]).indexOf(args.signal) === -1)) {
405
+ throw new Error("invalid signal: expected one of " + TERMINAL_SIGNALS.join(", "));
406
+ }
407
+ }
408
+
409
+ export interface TerminalOpenResult {
410
+ kind: "open";
411
+ sessionId: string;
412
+ jobId?: string;
413
+ pid: number;
414
+ shell: string;
415
+ output: string;
416
+ }
417
+
418
+ export interface TerminalSessionResult {
419
+ kind: "session";
420
+ output: string;
421
+ truncated?: boolean;
422
+ }
423
+
424
+ export interface TerminalClosedResult {
425
+ kind: "closed";
426
+ sessionId: string;
427
+ }
428
+
429
+ export interface TerminalListResult {
430
+ kind: "list";
431
+ sessions: TerminalSessionInfo[];
432
+ }
433
+
434
+ export type TerminalToolResult = TerminalOpenResult | TerminalSessionResult | TerminalClosedResult | TerminalListResult;
435
+
436
+ export function terminalTool(
437
+ ctx: BashTerminalContext,
438
+ registry: TerminalRegistry,
439
+ paths: ResolvedPaths,
440
+ defaultShell: () => string
441
+ ) {
442
+ return defineTool<TerminalToolResult>({
443
+ name: "terminal",
444
+ description: "Interactive terminal session over the user's default terminal (Settings -> General -> Default terminal: powershell / gitbash / msys2 / wsl). A real PTY hosts a persistent shell: open a session, send input and read output across turns, deliver signals (Ctrl+C = SIGINT) to the foreground process, and close when done. Backend and env follow the shell tool exactly; the session survives between calls until closed and is managed as a background job (job_kill / job_output work on it); idle sessions close automatically. Use this for interactive programs (REPLs, ssh, databases, TUI tools) or when you need shell state (cwd, variables, aliases) to persist across calls.",
445
+ parameters: {
446
+ action: {
447
+ type: "string",
448
+ enum: ["open", "send", "read", "signal", "close", "list"],
449
+ required: true,
450
+ description: "open: create a session and return its id. send: write input and read new output. read: read new output without writing. signal: send a signal to the foreground process (SIGINT for Ctrl+C). close: terminate the session. list: list live sessions."
451
+ },
452
+ sessionId: {
453
+ type: "string",
454
+ description: "Session id returned by open; required for send/read/signal/close."
455
+ },
456
+ command: {
457
+ type: "string",
458
+ description: "With action open: optional command to run immediately in the fresh shell (Enter appended). Default starts an interactive shell."
459
+ },
460
+ distro: {
461
+ type: "string",
462
+ description: "WSL distribution (only when the configured default terminal is wsl)."
463
+ },
464
+ input: {
465
+ type: "string",
466
+ description: "With action send: the input to write (no implicit newline; append \\n or \\r for Enter)."
467
+ },
468
+ signal: {
469
+ type: "string",
470
+ enum: TERMINAL_SIGNALS,
471
+ description: "With action signal: signal to the foreground process group (SIGINT = Ctrl+C, SIGKILL, SIGTERM, SIGTSTP, SIGHUP)."
472
+ },
473
+ workdir: {
474
+ type: "string",
475
+ description: "Working directory for the session (open only). Defaults to the session workspace."
476
+ },
477
+ idleMs: {
478
+ type: "number",
479
+ description: "Idle timeout in ms (open only): the session closes automatically after this long without send/read/signal. Default 600000 (10 min)."
480
+ }
481
+ },
482
+ output: {
483
+ schema: {
484
+ oneOf: [
485
+ {
486
+ type: "object",
487
+ additionalProperties: false,
488
+ properties: {
489
+ kind: { type: "string", required: true, const: "open" },
490
+ sessionId: { type: "string", required: true },
491
+ jobId: { type: "string" },
492
+ pid: { type: "integer", required: true },
493
+ shell: { type: "string", required: true },
494
+ output: { type: "string" }
495
+ }
496
+ },
497
+ {
498
+ type: "object",
499
+ additionalProperties: false,
500
+ properties: {
501
+ kind: { type: "string", required: true, const: "session" },
502
+ output: { type: "string", required: true },
503
+ truncated: { type: "boolean" }
504
+ }
505
+ },
506
+ {
507
+ type: "object",
508
+ additionalProperties: false,
509
+ properties: {
510
+ kind: { type: "string", required: true, const: "closed" },
511
+ sessionId: { type: "string", required: true }
512
+ }
513
+ },
514
+ {
515
+ type: "object",
516
+ additionalProperties: false,
517
+ properties: {
518
+ kind: { type: "string", required: true, const: "list" },
519
+ sessions: {
520
+ type: "array",
521
+ items: {
522
+ type: "object",
523
+ additionalProperties: false,
524
+ properties: {
525
+ sessionId: { type: "string", required: true },
526
+ shell: { type: "string", required: true },
527
+ pid: { type: "integer", required: true },
528
+ closed: { type: "boolean" }
529
+ }
530
+ }
531
+ }
532
+ }
533
+ }
534
+ ]
535
+ },
536
+ render: (_args, value) => [{
537
+ type: "text",
538
+ text: value.kind === "open"
539
+ ? "terminal session " + value.sessionId + " (pid " + value.pid + ", " + value.shell + ")" + (value.output ? "\n" + value.output : "")
540
+ : value.kind === "closed"
541
+ ? "terminal session " + value.sessionId + " closed"
542
+ : value.kind === "list"
543
+ ? (value.sessions.length === 0 ? "no open terminal sessions" : value.sessions.map((s) => s.sessionId + " (" + s.shell + ", pid " + s.pid + ")").join("\n"))
544
+ : value.truncated === true
545
+ ? (value.output.length === 0 ? "[terminal buffer overflowed; oldest output dropped]" : value.output + "\n[terminal buffer overflowed; oldest output dropped]")
546
+ : value.output
547
+ }]
548
+ },
549
+ async execute(args, exec): Promise<TerminalToolResult> {
550
+ validateArgs(args);
551
+ if (exec.signal.aborted) {
552
+ const error = new HarnessError("tool call aborted", TOOL_ABORTED);
553
+ error.name = "AbortError";
554
+ throw error;
555
+ }
556
+ const headerCwd = exec.agent?.session.header.cwd;
557
+ switch (args.action) {
558
+ case "open": {
559
+ const shell = defaultShell();
560
+ const argv0 = terminalArgv(shell, paths, args.distro);
561
+ if (argv0[0] === undefined) throw new Error("terminal: " + shell + " backend unavailable - executable not found");
562
+ // Only element 0 (the resolved executable) can be undefined; guarded above.
563
+ const argv = argv0 as string[];
564
+ const cwd = args.workdir !== undefined ? (headerCwd !== undefined && !isAbsolute(args.workdir) ? resolve(headerCwd, args.workdir) : args.workdir) : (headerCwd ?? process.cwd());
565
+ // buildEnv, not an inline duplicate: the msys2 backend needs its
566
+ // MSYSTEM=MINGW64 injection here too, or the login shell sources
567
+ // /etc/profile with the default MSYS environment and /mingw64/bin
568
+ // (gcc, make) never joins PATH. It also owns the WSL WSLENV layering,
569
+ // so a terminal session's env follows the shell tool exactly.
570
+ // process.env.WSLENV is passed explicitly: spawnTerminal replaces the
571
+ // child environment wholesale (childEnv(spec.env)), so the ambient
572
+ // allow-list is not otherwise visible and inherited entries such as
573
+ // WT_SESSION / WT_PROFILE_ID would be dropped.
574
+ const env = buildEnv(shell, ctx.shellEnv.collect(exec), process.env.WSLENV);
575
+ const session = await registry.open({ argv, shell, cwd, env, rows: DEFAULT_ROWS, cols: DEFAULT_COLS, distro: args.distro, initial: args.command !== undefined ? args.command + "\r" : undefined, idleMs: args.idleMs });
576
+ const jobs = ctx.get("jobs") as JobsRegistry | undefined;
577
+ const jobId = jobs === undefined ? undefined : jobs.start({
578
+ kind: "terminal/session",
579
+ label: "terminal " + session.id.slice(0, 8) + " (" + shell + ")",
580
+ ...(exec.agent ? { owner: exec.agent } : {}),
581
+ run: () => ({
582
+ cancel: () => { void session.handle.terminate().catch(() => { /* already dead */ }); },
583
+ done: session.handle.done,
584
+ readOutput: () => registry.read(session.id).delta
585
+ })
586
+ });
587
+ return { kind: "open", sessionId: session.id, ...(jobId !== undefined ? { jobId } : {}), pid: session.handle.pid, shell, output: session.buffer.snapshot() };
588
+ }
589
+ case "send": {
590
+ const { delta, truncated } = await registry.send(args.sessionId, args.input);
591
+ return { kind: "session", output: delta, ...(truncated ? { truncated } : {}) };
592
+ }
593
+ case "read": {
594
+ const { delta, truncated } = registry.read(args.sessionId);
595
+ return { kind: "session", output: delta, ...(truncated ? { truncated } : {}) };
596
+ }
597
+ case "signal": {
598
+ const { delta, truncated } = await registry.signal(args.sessionId, args.signal);
599
+ return { kind: "session", output: delta, ...(truncated ? { truncated } : {}) };
600
+ }
601
+ case "close": {
602
+ await registry.close(args.sessionId);
603
+ return { kind: "closed", sessionId: args.sessionId };
604
+ }
605
+ case "list": {
606
+ return { kind: "list", sessions: registry.list() };
607
+ }
608
+ }
609
+ },
610
+ presentCall: (args) => ({
611
+ card: "terminal",
612
+ title: "terminal " + String(args.action) + (args.sessionId !== undefined ? " " + String(args.sessionId) : ""),
613
+ ...(args.input !== undefined ? { description: args.input } : {})
614
+ })
615
+ });
616
+ }