dsh-bash-terminal-ts 0.9.1 → 0.9.3

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