@hncode/hncode 0.8.2 → 0.8.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/tools/bash.js CHANGED
@@ -1,440 +1,446 @@
1
- // Bash tool — mirrors the kimi-code Bash tool schema & behavior.
2
- // Runs commands via PowerShell (pwsh). Supports
3
- // timeout/cwd/run_in_background/disable_timeout. Background tasks are tracked so
4
- // TaskList/TaskOutput can inspect them.
5
-
6
- import fs from 'node:fs';
7
- import cp from 'node:child_process';
8
- import { resolvePath, truncateBuf , similarFileHint } from './utils.js';
9
- import { createTask, appendTaskOutput, settleTask } from '../agent-task.js';
10
- import { shellSpawnArgs, getShell } from './shell.js';
11
-
12
- // kimi-code's timeout policy (agent-core-v2/agent/tools/os/bash/bash.ts).
13
- export const DEFAULT_TIMEOUT_S = 60;
14
- export const MAX_TIMEOUT_S = 5 * 60;
15
- export const DEFAULT_BACKGROUND_TIMEOUT_S = 10 * 60;
16
- export const MAX_BACKGROUND_TIMEOUT_S = 24 * 60 * 60;
17
-
18
-
19
-
20
- // ---- output sanitizing -------------------------------------------------------
21
- // Captured output can contain terminal control sequences (colours, cursor
22
- // moves, `\r` spinners, bells, …). hncode's renderer passes result strings to
23
- // the terminal verbatim, so a surviving escape fights the differential
24
- // renderer ("text bleeding onto the next row"). It also inflates the token
25
- // count of what we send back to the model. Strip everything a terminal would
26
- // interpret as a command, keeping only `\n` and `\t`.
27
- const OSC_RE = /\u001B\][\s\S]*?(?:\u0007|\u001B\\)/g;
28
- const CSI_RE = /\u001B\[[0-9:;<=>?]*[ -/]*[@-~]/g;
29
- const ESC_SINGLE_RE = /\u001B(?:[ -/][0-~]|[0-~])/g;
30
- const C0_RE = /[\u0000-\u0008\u000B-\u001F]/g;
31
-
32
- export function sanitizeShellOutput(text) {
33
- const s = String(text ?? '');
34
- if (!s) return s;
35
- return s
36
- .replace(OSC_RE, '')
37
- .replace(CSI_RE, '')
38
- .replace(ESC_SINGLE_RE, '')
39
- .replace(C0_RE, '');
40
- }
41
-
42
- // PowerShell emits UTF-8 by default, so decode output as UTF-8.
43
- function decodeBuffer(buf) {
44
- if (buf.length === 0) return '';
45
- try {
46
- return new TextDecoder('utf-8', { fatal: true }).decode(buf);
47
- } catch {
48
- try { return new TextDecoder('gbk').decode(buf); } catch { return buf.toString('utf8'); }
49
- }
50
- }
51
-
52
- /**
53
- * Byte budget for a RUNNING command's captured output.
54
- *
55
- * `truncateBuf` only runs when the command FINISHES, so the whole run's output
56
- * sits in memory until then — and a build or a full test suite emits hundreds of
57
- * megabytes. The ring below keeps only a bounded TAIL while the command runs,
58
- * which is also the part a reader wants.
59
- *
60
- * The HEAD is dropped rather than the tail, and the dropped count is remembered
61
- * so the finished result can still report it instead of silently looking like a
62
- * short run.
63
- */
64
- const LIVE_RING_BYTES = 512 * 1024;
65
-
66
- /** Keep only the LAST `limit` bytes of an array of Buffers, in place. Returns
67
- how many bytes were dropped. */
68
- function trimChunkRing(chunks, limit) {
69
- let total = 0;
70
- for (const c of chunks) total += c.length;
71
- if (total <= limit) return 0;
72
- const dropped = total - limit;
73
- let drop = dropped;
74
- while (drop > 0 && chunks.length) {
75
- const head = chunks[0];
76
- if (head.length <= drop) { chunks.shift(); drop -= head.length; }
77
- else { chunks[0] = head.subarray(drop); drop = 0; }
78
- }
79
- return dropped;
80
- }
81
-
82
- function decodeChunks(chunks) {
83
- // Tolerant of a restored task: after a session round-trip the chunks are
84
- // `{type:'Buffer',data:[…]}` objects (JSON has no Buffer) or absent entirely.
85
- // `Buffer.concat` would throw on either, and this getter runs while the output
86
- // panel is being drawn — i.e. a throw here takes the TUI down too.
87
- if (chunks == null) return '';
88
- const list = Array.isArray(chunks) ? chunks : [chunks];
89
- if (!list.length) return '';
90
- const items = list.map((c) => {
91
- if (Buffer.isBuffer(c)) return c;
92
- if (c && c.type === 'Buffer' && Array.isArray(c.data)) return Buffer.from(c.data);
93
- return Buffer.from(String(c));
94
- });
95
- try { return decodeBuffer(items.length === 1 ? items[0] : Buffer.concat(items)); }
96
- catch { return items.map((c) => c.toString('utf8')).join(''); }
97
- }
98
-
99
-
100
- /**
101
- * Kill a child.
102
- *
103
- * `tree` is OFF for an interactive run, and that is not a style choice: a non-detached interactive child
104
- * lives INSIDE our process tree, so `taskkill /t` walks up and kills the parent too — the TUI would die
105
- * while stopping a background command. Both halves are pinned by `test/task-input.test.mjs`.
106
- *
107
- * A detached background job has no such risk: it was started as its own tree root, so `/t` reaches its
108
- * children and nothing above it.
109
- */
110
- function killTree(child, opts = {}) {
111
- try {
112
- const exit = child.exitCode !== null || child.signalCode !== null;
113
- if (exit || child.killed) return;
114
- if (process.platform === 'win32') {
115
- const args = ['/pid', String(child.pid), '/f'];
116
- if (opts.tree !== false) args.splice(2, 0, '/t');
117
- try { cp.spawnSync('taskkill', args, { stdio: 'ignore' }); } catch {}
118
- } else {
119
- child.kill('SIGTERM');
120
- }
121
- } catch {}
122
- // The SIGKILL follow-up must not keep the process alive on its own: unref it,
123
- // so a child that exits politely still lets the process quit on time.
124
- const followUp = setTimeout(() => { try { child.kill('SIGKILL'); } catch {} }, 1000);
125
- if (followUp.unref) followUp.unref();
126
- }
127
-
128
- export const spec = {
129
- name: 'Bash',
130
- // The shell is named at runtime, not baked in: the model is told which syntax it is writing against, and on a POSIX
131
- // box "via pwsh" was both wrong and an invitation to emit PowerShell.
132
- get description() {
133
- const shell = getShell();
134
- const which = shell ? (shell.edition === 'posix' ? 'the POSIX shell' : shell.name) : 'the system shell';
135
- return `Run a shell command via ${which}. Returns combined stdout+stderr. timeout default 60s (max 300s); run_in_background detaches and returns a task id.`;
136
- },
137
- parameters: {
138
- type: 'object',
139
- properties: {
140
- command: { type: 'string', description: 'Shell command to execute.' },
141
- description: { type: 'string', description: 'Short description (shown in task lists; required for background tasks).' },
142
- timeout: { type: 'integer', minimum: 1, description: 'Seconds before the command is killed. Foreground default 60s/max 300s; background default 600s/max 86400s.' },
143
- cwd: { type: 'string', description: 'Working directory (default: workspace/project root).' },
144
- run_in_background: { type: 'boolean', default: false, description: 'Run detached and return a task id instead of waiting.' },
145
- interactive: { type: 'boolean', default: false, description: 'With run_in_background: keep stdin open so TaskInput can write to it — for a command that prompts.' },
146
- disable_timeout: { type: 'boolean', default: false, description: 'Disable the timeout (background only).' },
147
- },
148
- required: ['command'],
149
- },
150
- async execute(args, ctx) {
151
- if (!args.command || !String(args.command).length) return 'Command cannot be empty.';
152
- const cwdRaw = args.cwd || ctx.workspace;
153
- let cwd;
154
- try { cwd = resolvePath(cwdRaw, ctx); } catch (e) { return e.message; }
155
- if (!fs.existsSync(cwd)) return `Error: cwd does not exist: ${cwdRaw}${similarFileHint(cwd)}. Omit cwd to use the workspace root.`;
156
-
157
- if (args.run_in_background) return spawnBackground(args, cwd, ctx);
158
-
159
- const bg = false;
160
- const cap = bg ? MAX_BACKGROUND_TIMEOUT_S : MAX_TIMEOUT_S;
161
- const def = bg ? DEFAULT_BACKGROUND_TIMEOUT_S : DEFAULT_TIMEOUT_S;
162
- const timeoutMs = args.disable_timeout ? undefined : Math.min(args.timeout ?? def, cap) * 1000;
163
- const command = args.command;
164
- // STDIN IS A PIPE FOR EVERY RUN. The agent never types into it, but the USER can: a program that prompts
165
- // (`npm init`, a REPL, a script reading a line) used to sit on /dev/null until the timeout killed it, with
166
- // no way to answer. A background run is fed through TaskInput, a foreground one through the composer's
167
- // Ctrl+G mode. When nobody writes, the command blocks exactly as it would in a terminal.
168
- let shell;
169
- try { shell = shellSpawnArgs(command); } catch (e) { return `Error: ${e.message}`; }
170
- // Check the turn's signal BEFORE spawning. The check below ran only after the
171
- // child existed: an abort landing in that window returned "Interrupted by user"
172
- // while leaving the child RUNNING with open pipes until the timeout timer fired,
173
- // and Esc could not stop it.
174
- if (ctx.signal && ctx.signal.aborted) return 'Interrupted by user';
175
- const child = cp.spawn(shell.bin, shell.args, {
176
- cwd, stdio: ['pipe', 'pipe', 'pipe'], env: { ...process.env },
177
- });
178
-
179
- const chunks = [];
180
- let settled = false;
181
- // Bytes shed by the live ring, reported on the finished result so a trimmed
182
- // run does not look like a short one.
183
- let chunksDropped = 0;
184
- // Live stream sink: hand decoded output to the agent (ctx.onOutput) so the UI
185
- // can show a running command's output in real time, exactly like the
186
- // finished "Used Bash" row does. Foreground runs only — a background task's
187
- // output is read through TaskOutput.
188
- //
189
-
190
- //
191
- // Decoding is STREAMING (a multi-byte char can be split across chunks), and
192
- // sanitizing runs over complete LINES rather than the whole accumulated text.
193
- // The old form re-ran the escape regexes over everything received so far on
194
- // EVERY chunk — O(n²) over the run, plus a fresh full-length string per chunk
195
- // — which is what made a chatty command slow the process down and double its
196
- // peak memory.
197
- //
198
- // Line-by-line is also what keeps an escape sequence from being cut in half:
199
- // a sequence never contains a newline, so a complete line is always safe to
200
- // sanitize, and the trailing partial line waits for more input.
201
- // THE LIVE STREAM MUST DECODE EXACTLY THE WAY THE FINAL RESULT DOES.
202
- //
203
- // The finished output goes through `decodeBuffer`, which tries strict UTF-8 and FALLS BACK TO GBK. The
204
- // live sink used a plain non-fatal UTF-8 decoder, so a command whose output is not UTF-8 — PowerShell on a
205
- // Chinese Windows writes GBK for native tools — streamed as replacement characters while it ran and then
206
- // turned correct the moment it finished. That is the "garbled while running, fine afterwards" report.
207
- //
208
- // The live path cannot buffer the whole run, so it decides from the first chunk that proves itself: valid
209
- // UTF-8 keeps the UTF-8 decoder, anything else pins GBK for the rest of the stream. A chunk boundary
210
- // through the middle of a multi-byte character looks invalid too, so a failed probe is retried once with
211
- // the remaining bytes before the encoding is pinned.
212
- const sink = typeof ctx.onOutput === 'function' ? ctx.onOutput : null;
213
- let liveDecoder = sink ? new TextDecoder('utf-8') : null;
214
- let livePending = '';
215
- let liveUndecided = !!sink; // the probe has not committed yet
216
- const push = (d) => {
217
- chunks.push(d);
218
- const dropped = trimChunkRing(chunks, LIVE_RING_BYTES);
219
- if (dropped) chunksDropped += dropped;
220
-
221
- if (!sink || settled) return;
222
- try {
223
- const buf = Buffer.isBuffer(d) ? d : Buffer.from(String(d));
224
- if (liveUndecided) {
225
- // A trailing partial character makes a valid UTF-8 chunk look invalid. Only a chunk that still
226
- // fails after its own tail is set aside is evidence.
227
- let valid = false;
228
- try {
229
- new TextDecoder('utf-8', { fatal: true }).decode(buf);
230
- valid = true;
231
- } catch {
232
- // Trim up to three trailing bytes and try once more: that is the longest an incomplete UTF-8
233
- // sequence can be.
234
- for (let cut = 1; cut <= 3 && cut < buf.length; cut++) {
235
- try {
236
- new TextDecoder('utf-8', { fatal: true }).decode(buf.subarray(0, buf.length - cut));
237
- valid = true;
238
- break;
239
- } catch { /* keep trimming */ }
240
- }
241
- }
242
- if (!valid) liveDecoder = new TextDecoder('gbk');
243
- liveUndecided = false;
244
- }
245
- // One decoder for the whole stream, in streaming mode: a GBK character is two bytes and will be split
246
- // across chunks just as often as a UTF-8 one.
247
- livePending += liveDecoder.decode(buf, { stream: true });
248
- const nl = livePending.lastIndexOf('\n');
249
- if (nl < 0) return;
250
- const complete = livePending.slice(0, nl + 1);
251
- livePending = livePending.slice(nl + 1);
252
- const clean = sanitizeShellOutput(complete);
253
- if (clean) sink(clean);
254
- } catch { /* display is best-effort; the result below is authoritative */ }
255
- };
256
- if (child.stdout) child.stdout.on('data', push);
257
- if (child.stderr) child.stderr.on('data', push);
258
-
259
- let timer = null;
260
- if (timeoutMs) timer = setTimeout(() => { killTree(child); }, timeoutMs);
261
-
262
- // Esc / Ctrl-C in the TUI aborts the turn: kill the running command too,
263
- // otherwise a long command keeps running after the user interrupted.
264
- const signal = ctx.signal;
265
- const onAbort = () => { killTree(child); };
266
- if (signal) {
267
- if (signal.aborted) return 'Interrupted by user';
268
- signal.addEventListener('abort', onAbort, { once: true });
269
- }
270
- const cleanup = () => {
271
- if (timer) clearTimeout(timer);
272
- if (signal) signal.removeEventListener('abort', onAbort);
273
- };
274
-
275
- return new Promise((resolve) => {
276
- // Expose a detach hook so the TUI's ctrl+b can move a long-running
277
- // foreground command into the background WITHOUT killing it: the child
278
- // keeps running, gets registered as a task, and this promise resolves
279
- // immediately with a "moved to background" note so the agent continues.
280
- if (ctx) {
281
- // THE HOOK BELONGS TO THE NEWEST FOREGROUND COMMAND. Replacing it here is what makes the identity check
282
- // above correct: a command that finishes later compares `ctx._foreground.child` against its own child and
283
- // leaves someone else's hook alone.
284
- ctx._foreground = {
285
- command: args.command,
286
- description: args.description || args.command,
287
- child, chunks,
288
- // The TUI reaches this to answer a prompt the command is waiting on.
289
- stdin: child.stdin,
290
- write: (s) => {
291
- if (settled || !child.stdin || child.stdin.destroyed || !child.stdin.writable) return false;
292
- try { child.stdin.write(s); return true; } catch { return false; }
293
- },
294
- detach: () => {
295
- if (settled) return null;
296
- settled = true;
297
- cleanup();
298
- // Stop treating this as foreground: drop the abort listener so an
299
- // Esc after detaching does not kill the now-background task.
300
- if (signal) signal.removeEventListener('abort', onAbort);
301
- // AND DROP THE HOOK. `child.on('close')` clears it for a command that finishes on its own, but a
302
- // detached one resolves HERE and never reaches that path — so the hook stayed set, and a second Ctrl+B
303
- // called `detach` again, got null, and did nothing at all.
304
- if (ctx && ctx._foreground && ctx._foreground.child === child) ctx._foreground = null;
305
- const id = registerBackgroundTask(args, child, ctx, chunks);
306
- resolve(`Moved to background as task #${id}. It keeps running; inspect with TaskList / TaskOutput {task_id: "${id}"}.`);
307
- return id;
308
- },
309
- };
310
- }
311
- child.on('close', (code) => {
312
- cleanup();
313
- if (ctx && ctx._foreground && ctx._foreground.child === child) ctx._foreground = null;
314
- if (settled) return;
315
- settled = true;
316
- // Flush the last partial line the live sink was holding back.
317
- if (sink && livePending) {
318
- try { sink(sanitizeShellOutput(livePending)); } catch { /* best-effort */ }
319
- livePending = '';
320
- }
321
- if (signal && signal.aborted) { resolve('Interrupted by user'); return; }
322
- let out = truncateBuf(sanitizeShellOutput(decodeChunks(chunks)));
323
- // A trimmed run says so; otherwise the result would look complete while
324
- // quietly missing its head.
325
- if (chunksDropped) out = `...[dropped ${chunksDropped} bytes of earlier output]\n` + out;
326
- out += `\n[exit code: ${code === null ? 'killed' : code}]`;
327
- resolve(out);
328
- });
329
- child.on('error', (e) => {
330
- cleanup();
331
- // Same identity check as `close`: a failing command must not take another command's hook with it.
332
- if (ctx && ctx._foreground && ctx._foreground.child === child) ctx._foreground = null;
333
- if (settled) return;
334
- settled = true;
335
- resolve(truncateBuf(sanitizeShellOutput(decodeChunks(chunks))) + `\n[error: ${e.message}]`);
336
- });
337
- });
338
- },
339
- };
340
-
341
- // Register an already-spawned child (foreground -> background detach) as a task.
342
- // Reuses the same task shape and lazy output decoding as spawnBackground. The
343
- // foreground path's existing stdout/stderr listeners keep writing into the SAME
344
- // `existingChunks` array the task reads, so we must NOT add new listeners here
345
- // (doing so doubled every line of output).
346
- function registerBackgroundTask(args, child, ctx, existingChunks) {
347
- const task = createTask(ctx, 'process', {
348
- description: args.description || args.command,
349
- command: args.command,
350
- pid: child.pid,
351
- detached: true,
352
- _chunks: existingChunks || [],
353
- });
354
- defineOutput(task);
355
- child.on('close', (code) => {
356
- // A task already settled (TaskStop -> 'killed') keeps its status; the
357
- // process's non-zero kill exit must not relabel a deliberate stop.
358
- if (task.status === 'running') {
359
- settleTask(task, code === 0 ? 'completed' : 'failed', { exitCode: code });
360
- } else {
361
- task.exitCode = code;
362
- }
363
- });
364
- return task.taskId;
365
- }
366
-
367
- function spawnBackground(args, cwd, ctx) {
368
- const command = args.command;
369
- // Detached + piped stdio is not a real detach: when the parent exits, the
370
- // pipes close and the child gets SIGPIPE. Redirect stdout/stderr to the
371
- // task's output file instead, so the process survives and TaskOutput can
372
- // still read it. (In the TUI the parent rarely exits, but headless -p mode
373
- // does, and a background job should outlive the prompt.)
374
- //
375
- // AND NOT ON WINDOWS AT ALL. The note above says `detached: true` with piped stdout returns exit 0 and no output; the
376
- // same is true for a NON-interactive background command, which is the ordinary Ctrl+B case. Measured with pwsh:
377
- //
378
- // detached=false "exit 3" -> exit 3, output intact
379
- // detached=true "exit 3" -> exit 0, output EMPTY
380
- // detached=true "echo hello" -> exit 0, output EMPTY
381
- //
382
- // So on Windows the process stays attached: its output and its exit code are the whole point of a background task, and
383
- // a task that reports success whatever happened is worse than one that dies with its parent. Elsewhere the detach is
384
- // what makes a job outlive headless `-p`, so it is kept.
385
- const canDetach = process.platform !== 'win32' && !args.interactive;
386
- let shell;
387
- try { shell = shellSpawnArgs(command, { interactive: args.interactive }); } catch (e) { return `Error: ${e.message}`; }
388
- const child = cp.spawn(shell.bin, shell.args, {
389
- cwd, detached: canDetach, stdio: [args.interactive ? 'pipe' : 'ignore', 'pipe', 'pipe'], env: { ...process.env },
390
- });
391
- const task = createTask(ctx, 'process', {
392
- description: args.description || args.command,
393
- command: args.command,
394
- pid: child.pid,
395
- detached: canDetach,
396
- });
397
- // The stdin pipe, when the caller asked for one. Kept on the TASK so `TaskInput` can reach it from a
398
- // task id alone — a tool receives an id, not a handle. Only `interactive` gets here, so a plain
399
- // background job is unaffected and cannot be fed input by accident.
400
- if (args.interactive && child.stdin) {
401
- task.stdin = child.stdin;
402
- task.interactive = true;
403
- // A closed pipe is normal at the end of a run; writing afterwards would throw EPIPE.
404
- child.stdin.on('error', () => { task.stdin = null; });
405
- child.on('close', () => { task.stdin = null; });
406
- }
407
- defineOutput(task);
408
- const push = (d) => appendTaskOutput(task, d);
409
- if (child.stdout) child.stdout.on('data', push);
410
- if (child.stderr) child.stderr.on('data', push);
411
- child.on('close', (code) => {
412
- if (task.status === 'running') {
413
- settleTask(task, code === 0 ? 'completed' : 'failed', { exitCode: code });
414
- } else {
415
- task.exitCode = code;
416
- }
417
- });
418
- // Background timeout: default 600s, capped at 86400s; `disable_timeout` removes
419
- // it. The timer is unref'd so it never keeps the process alive on its own.
420
- if (!args.disable_timeout) {
421
- const bgTimeoutMs = Math.min(args.timeout ?? DEFAULT_BACKGROUND_TIMEOUT_S, MAX_BACKGROUND_TIMEOUT_S) * 1000;
422
- const t = setTimeout(() => {
423
- killTree(child);
424
- settleTask(task, 'timed_out', { stopReason: 'timed out' });
425
- }, bgTimeoutMs);
426
- if (t.unref) t.unref();
427
- }
428
- child.unref();
429
- return `Background task ${task.taskId} started (pid ${child.pid}): ${args.description || args.command}
430
- Inspect with TaskList (running tasks) and TaskOutput {task_id: "${task.taskId}"} (output).`;
431
- }
432
-
433
- // Lazy output: the accumulated bytes are decoded only when actually read, so a
434
- // chatty background task costs nothing until queried.
435
- function defineOutput(task) {
436
- Object.defineProperty(task, 'output', {
437
- enumerable: true,
438
- get() { return sanitizeShellOutput(decodeChunks(this._chunks)); },
439
- });
440
- }
1
+ // Bash tool — mirrors the kimi-code Bash tool schema & behavior.
2
+ // Runs commands via PowerShell (pwsh). Supports
3
+ // timeout/cwd/run_in_background/disable_timeout. Background tasks are tracked so
4
+ // TaskList/TaskOutput can inspect them.
5
+
6
+ import fs from 'node:fs';
7
+ import cp from 'node:child_process';
8
+ import { resolvePath, truncateBuf , similarFileHint } from './utils.js';
9
+ import { createTask, appendTaskOutput, settleTask } from '../agent-task.js';
10
+ import { shellSpawnArgs, getShell } from './shell.js';
11
+
12
+ // kimi-code's timeout policy (agent-core-v2/agent/tools/os/bash/bash.ts).
13
+ export const DEFAULT_TIMEOUT_S = 60;
14
+ export const MAX_TIMEOUT_S = 5 * 60;
15
+ export const MAX_BACKGROUND_TIMEOUT_S = 24 * 60 * 60;
16
+
17
+
18
+
19
+ // ---- output sanitizing -------------------------------------------------------
20
+ // Captured output can contain terminal control sequences (colours, cursor
21
+ // moves, `\r` spinners, bells, …). hncode's renderer passes result strings to
22
+ // the terminal verbatim, so a surviving escape fights the differential
23
+ // renderer ("text bleeding onto the next row"). It also inflates the token
24
+ // count of what we send back to the model. Strip everything a terminal would
25
+ // interpret as a command, keeping only `\n` and `\t`.
26
+ const OSC_RE = /\u001B\][\s\S]*?(?:\u0007|\u001B\\)/g;
27
+ const CSI_RE = /\u001B\[[0-9:;<=>?]*[ -/]*[@-~]/g;
28
+ const ESC_SINGLE_RE = /\u001B(?:[ -/][0-~]|[0-~])/g;
29
+ const C0_RE = /[\u0000-\u0008\u000B-\u001F]/g;
30
+
31
+ export function sanitizeShellOutput(text) {
32
+ const s = String(text ?? '');
33
+ if (!s) return s;
34
+ return s
35
+ .replace(OSC_RE, '')
36
+ .replace(CSI_RE, '')
37
+ .replace(ESC_SINGLE_RE, '')
38
+ .replace(C0_RE, '');
39
+ }
40
+
41
+ // PowerShell emits UTF-8 by default, so decode output as UTF-8.
42
+ function decodeBuffer(buf) {
43
+ if (buf.length === 0) return '';
44
+ try {
45
+ return new TextDecoder('utf-8', { fatal: true }).decode(buf);
46
+ } catch {
47
+ try { return new TextDecoder('gbk').decode(buf); } catch { return buf.toString('utf8'); }
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Byte budget for a RUNNING command's captured output.
53
+ *
54
+ * `truncateBuf` only runs when the command FINISHES, so the whole run's output
55
+ * sits in memory until then — and a build or a full test suite emits hundreds of
56
+ * megabytes. The ring below keeps only a bounded TAIL while the command runs,
57
+ * which is also the part a reader wants.
58
+ *
59
+ * The HEAD is dropped rather than the tail, and the dropped count is remembered
60
+ * so the finished result can still report it instead of silently looking like a
61
+ * short run.
62
+ */
63
+ const LIVE_RING_BYTES = 512 * 1024;
64
+
65
+ /** Keep only the LAST `limit` bytes of an array of Buffers, in place. Returns
66
+ how many bytes were dropped. */
67
+ function trimChunkRing(chunks, limit) {
68
+ let total = 0;
69
+ for (const c of chunks) total += c.length;
70
+ if (total <= limit) return 0;
71
+ const dropped = total - limit;
72
+ let drop = dropped;
73
+ while (drop > 0 && chunks.length) {
74
+ const head = chunks[0];
75
+ if (head.length <= drop) { chunks.shift(); drop -= head.length; }
76
+ else { chunks[0] = head.subarray(drop); drop = 0; }
77
+ }
78
+ return dropped;
79
+ }
80
+
81
+ function decodeChunks(chunks) {
82
+ // Tolerant of a restored task: after a session round-trip the chunks are
83
+ // `{type:'Buffer',data:[…]}` objects (JSON has no Buffer) or absent entirely.
84
+ // `Buffer.concat` would throw on either, and this getter runs while the output
85
+ // panel is being drawn — i.e. a throw here takes the TUI down too.
86
+ if (chunks == null) return '';
87
+ const list = Array.isArray(chunks) ? chunks : [chunks];
88
+ if (!list.length) return '';
89
+ const items = list.map((c) => {
90
+ if (Buffer.isBuffer(c)) return c;
91
+ if (c && c.type === 'Buffer' && Array.isArray(c.data)) return Buffer.from(c.data);
92
+ return Buffer.from(String(c));
93
+ });
94
+ try { return decodeBuffer(items.length === 1 ? items[0] : Buffer.concat(items)); }
95
+ catch { return items.map((c) => c.toString('utf8')).join(''); }
96
+ }
97
+
98
+
99
+ /**
100
+ * Kill a child.
101
+ *
102
+ * `tree` is OFF for an interactive run, and that is not a style choice: a non-detached interactive child
103
+ * lives INSIDE our process tree, so `taskkill /t` walks up and kills the parent too — the TUI would die
104
+ * while stopping a background command. Both halves are pinned by `test/task-input.test.mjs`.
105
+ *
106
+ * A detached background job has no such risk: it was started as its own tree root, so `/t` reaches its
107
+ * children and nothing above it.
108
+ */
109
+ function killTree(child, opts = {}) {
110
+ try {
111
+ const exit = child.exitCode !== null || child.signalCode !== null;
112
+ if (exit || child.killed) return;
113
+ if (process.platform === 'win32') {
114
+ const args = ['/pid', String(child.pid), '/f'];
115
+ if (opts.tree !== false) args.splice(2, 0, '/t');
116
+ try { cp.spawnSync('taskkill', args, { stdio: 'ignore' }); } catch {}
117
+ } else {
118
+ child.kill('SIGTERM');
119
+ }
120
+ } catch {}
121
+ // The SIGKILL follow-up must not keep the process alive on its own: unref it,
122
+ // so a child that exits politely still lets the process quit on time.
123
+ const followUp = setTimeout(() => { try { child.kill('SIGKILL'); } catch {} }, 1000);
124
+ if (followUp.unref) followUp.unref();
125
+ }
126
+
127
+ export const spec = {
128
+ name: 'Bash',
129
+ // The shell is named at runtime, not baked in: the model is told which syntax it is writing against, and on a POSIX
130
+ // box "via pwsh" was both wrong and an invitation to emit PowerShell.
131
+ get description() {
132
+ const shell = getShell();
133
+ const which = shell ? (shell.edition === 'posix' ? 'the POSIX shell' : shell.name) : 'the system shell';
134
+ return `Run a shell command via ${which}. Returns combined stdout+stderr. timeout default 60s (max 300s); run_in_background detaches and returns a task id.`;
135
+ },
136
+ parameters: {
137
+ type: 'object',
138
+ properties: {
139
+ command: { type: 'string', description: 'Shell command to execute.' },
140
+ description: { type: 'string', description: 'Short description (shown in task lists; required for background tasks).' },
141
+ timeout: { type: 'integer', minimum: 1, description: 'Seconds before the command is killed. Foreground default 60s/max 300s. A BACKGROUND command has NO default limit — it runs until it finishes or is stopped — so pass this only when the job really must be cut short (max 86400s).' },
142
+ cwd: { type: 'string', description: 'Working directory (default: workspace/project root).' },
143
+ run_in_background: { type: 'boolean', default: false, description: 'Run detached and return a task id instead of waiting.' },
144
+ interactive: { type: 'boolean', default: false, description: 'With run_in_background: keep stdin open so TaskInput can write to it — for a command that prompts.' },
145
+ disable_timeout: { type: 'boolean', default: false, description: 'Disable the timeout (background only).' },
146
+ },
147
+ required: ['command'],
148
+ },
149
+ async execute(args, ctx) {
150
+ if (!args.command || !String(args.command).length) return 'Command cannot be empty.';
151
+ const cwdRaw = args.cwd || ctx.workspace;
152
+ let cwd;
153
+ try { cwd = resolvePath(cwdRaw, ctx); } catch (e) { return e.message; }
154
+ if (!fs.existsSync(cwd)) return `Error: cwd does not exist: ${cwdRaw}${similarFileHint(cwd)}. Omit cwd to use the workspace root.`;
155
+
156
+ if (args.run_in_background) return spawnBackground(args, cwd, ctx);
157
+
158
+ // A FOREGROUND run has a default limit: the user is waiting, and a command that hangs
159
+ // would hang the turn with it. A BACKGROUND run has none (see spawnBackground).
160
+ const timeoutMs = args.disable_timeout ? undefined : Math.min(args.timeout ?? DEFAULT_TIMEOUT_S, MAX_TIMEOUT_S) * 1000;
161
+ const command = args.command;
162
+ // STDIN IS A PIPE FOR EVERY RUN. The agent never types into it, but the USER can: a program that prompts
163
+ // (`npm init`, a REPL, a script reading a line) used to sit on /dev/null until the timeout killed it, with
164
+ // no way to answer. A background run is fed through TaskInput, a foreground one through the composer's
165
+ // Ctrl+G mode. When nobody writes, the command blocks exactly as it would in a terminal.
166
+ let shell;
167
+ try { shell = shellSpawnArgs(command); } catch (e) { return `Error: ${e.message}`; }
168
+ // Check the turn's signal BEFORE spawning. The check below ran only after the
169
+ // child existed: an abort landing in that window returned "Interrupted by user"
170
+ // while leaving the child RUNNING with open pipes until the timeout timer fired,
171
+ // and Esc could not stop it.
172
+ if (ctx.signal && ctx.signal.aborted) return 'Interrupted by user';
173
+ const child = cp.spawn(shell.bin, shell.args, {
174
+ cwd, stdio: ['pipe', 'pipe', 'pipe'], env: { ...process.env },
175
+ });
176
+
177
+ const chunks = [];
178
+ let settled = false;
179
+ // Bytes shed by the live ring, reported on the finished result so a trimmed
180
+ // run does not look like a short one.
181
+ let chunksDropped = 0;
182
+ // Live stream sink: hand decoded output to the agent (ctx.onOutput) so the UI
183
+ // can show a running command's output in real time, exactly like the
184
+ // finished "Used Bash" row does. Foreground runs only — a background task's
185
+ // output is read through TaskOutput.
186
+ //
187
+
188
+ //
189
+ // Decoding is STREAMING (a multi-byte char can be split across chunks), and
190
+ // sanitizing runs over complete LINES rather than the whole accumulated text.
191
+ // The old form re-ran the escape regexes over everything received so far on
192
+ // EVERY chunk — O(n²) over the run, plus a fresh full-length string per chunk
193
+ // — which is what made a chatty command slow the process down and double its
194
+ // peak memory.
195
+ //
196
+ // Line-by-line is also what keeps an escape sequence from being cut in half:
197
+ // a sequence never contains a newline, so a complete line is always safe to
198
+ // sanitize, and the trailing partial line waits for more input.
199
+ // THE LIVE STREAM MUST DECODE EXACTLY THE WAY THE FINAL RESULT DOES.
200
+ //
201
+ // The finished output goes through `decodeBuffer`, which tries strict UTF-8 and FALLS BACK TO GBK. The
202
+ // live sink used a plain non-fatal UTF-8 decoder, so a command whose output is not UTF-8 — PowerShell on a
203
+ // Chinese Windows writes GBK for native tools — streamed as replacement characters while it ran and then
204
+ // turned correct the moment it finished. That is the "garbled while running, fine afterwards" report.
205
+ //
206
+ // The live path cannot buffer the whole run, so it decides from the first chunk that proves itself: valid
207
+ // UTF-8 keeps the UTF-8 decoder, anything else pins GBK for the rest of the stream. A chunk boundary
208
+ // through the middle of a multi-byte character looks invalid too, so a failed probe is retried once with
209
+ // the remaining bytes before the encoding is pinned.
210
+ const sink = typeof ctx.onOutput === 'function' ? ctx.onOutput : null;
211
+ let liveDecoder = sink ? new TextDecoder('utf-8') : null;
212
+ let livePending = '';
213
+ let liveUndecided = !!sink; // the probe has not committed yet
214
+ const push = (d) => {
215
+ chunks.push(d);
216
+ const dropped = trimChunkRing(chunks, LIVE_RING_BYTES);
217
+ if (dropped) chunksDropped += dropped;
218
+
219
+ if (!sink || settled) return;
220
+ try {
221
+ const buf = Buffer.isBuffer(d) ? d : Buffer.from(String(d));
222
+ if (liveUndecided) {
223
+ // A trailing partial character makes a valid UTF-8 chunk look invalid. Only a chunk that still
224
+ // fails after its own tail is set aside is evidence.
225
+ let valid = false;
226
+ try {
227
+ new TextDecoder('utf-8', { fatal: true }).decode(buf);
228
+ valid = true;
229
+ } catch {
230
+ // Trim up to three trailing bytes and try once more: that is the longest an incomplete UTF-8
231
+ // sequence can be.
232
+ for (let cut = 1; cut <= 3 && cut < buf.length; cut++) {
233
+ try {
234
+ new TextDecoder('utf-8', { fatal: true }).decode(buf.subarray(0, buf.length - cut));
235
+ valid = true;
236
+ break;
237
+ } catch { /* keep trimming */ }
238
+ }
239
+ }
240
+ if (!valid) liveDecoder = new TextDecoder('gbk');
241
+ liveUndecided = false;
242
+ }
243
+ // One decoder for the whole stream, in streaming mode: a GBK character is two bytes and will be split
244
+ // across chunks just as often as a UTF-8 one.
245
+ livePending += liveDecoder.decode(buf, { stream: true });
246
+ const nl = livePending.lastIndexOf('\n');
247
+ if (nl < 0) return;
248
+ const complete = livePending.slice(0, nl + 1);
249
+ livePending = livePending.slice(nl + 1);
250
+ const clean = sanitizeShellOutput(complete);
251
+ if (clean) sink(clean);
252
+ } catch { /* display is best-effort; the result below is authoritative */ }
253
+ };
254
+ if (child.stdout) child.stdout.on('data', push);
255
+ if (child.stderr) child.stderr.on('data', push);
256
+
257
+ let timer = null;
258
+ if (timeoutMs) timer = setTimeout(() => { killTree(child); }, timeoutMs);
259
+
260
+ // Esc / Ctrl-C in the TUI aborts the turn: kill the running command too,
261
+ // otherwise a long command keeps running after the user interrupted.
262
+ const signal = ctx.signal;
263
+ const onAbort = () => { killTree(child); };
264
+ if (signal) {
265
+ if (signal.aborted) return 'Interrupted by user';
266
+ signal.addEventListener('abort', onAbort, { once: true });
267
+ }
268
+ const cleanup = () => {
269
+ if (timer) clearTimeout(timer);
270
+ if (signal) signal.removeEventListener('abort', onAbort);
271
+ };
272
+
273
+ return new Promise((resolve) => {
274
+ // Expose a detach hook so the TUI's ctrl+b can move a long-running
275
+ // foreground command into the background WITHOUT killing it: the child
276
+ // keeps running, gets registered as a task, and this promise resolves
277
+ // immediately with a "moved to background" note so the agent continues.
278
+ if (ctx) {
279
+ // THE HOOK BELONGS TO THE NEWEST FOREGROUND COMMAND. Replacing it here is what makes the identity check
280
+ // above correct: a command that finishes later compares `ctx._foreground.child` against its own child and
281
+ // leaves someone else's hook alone.
282
+ ctx._foreground = {
283
+ command: args.command,
284
+ description: args.description || args.command,
285
+ child, chunks,
286
+ // The TUI reaches this to answer a prompt the command is waiting on.
287
+ stdin: child.stdin,
288
+ write: (s) => {
289
+ if (settled || !child.stdin || child.stdin.destroyed || !child.stdin.writable) return false;
290
+ try { child.stdin.write(s); return true; } catch { return false; }
291
+ },
292
+ detach: () => {
293
+ if (settled) return null;
294
+ settled = true;
295
+ cleanup();
296
+ // Stop treating this as foreground: drop the abort listener so an
297
+ // Esc after detaching does not kill the now-background task.
298
+ if (signal) signal.removeEventListener('abort', onAbort);
299
+ // AND DROP THE HOOK. `child.on('close')` clears it for a command that finishes on its own, but a
300
+ // detached one resolves HERE and never reaches that path — so the hook stayed set, and a second Ctrl+B
301
+ // called `detach` again, got null, and did nothing at all.
302
+ if (ctx && ctx._foreground && ctx._foreground.child === child) ctx._foreground = null;
303
+ const id = registerBackgroundTask(args, child, ctx, chunks);
304
+ resolve(`Moved to background as task #${id}. It keeps running; inspect with TaskList / TaskOutput {task_id: "${id}"}.`);
305
+ return id;
306
+ },
307
+ };
308
+ }
309
+ child.on('close', (code) => {
310
+ cleanup();
311
+ if (ctx && ctx._foreground && ctx._foreground.child === child) ctx._foreground = null;
312
+ if (settled) return;
313
+ settled = true;
314
+ // Flush the last partial line the live sink was holding back.
315
+ if (sink && livePending) {
316
+ try { sink(sanitizeShellOutput(livePending)); } catch { /* best-effort */ }
317
+ livePending = '';
318
+ }
319
+ if (signal && signal.aborted) { resolve('Interrupted by user'); return; }
320
+ let out = truncateBuf(sanitizeShellOutput(decodeChunks(chunks)));
321
+ // A trimmed run says so; otherwise the result would look complete while
322
+ // quietly missing its head.
323
+ if (chunksDropped) out = `...[dropped ${chunksDropped} bytes of earlier output]\n` + out;
324
+ out += `\n[exit code: ${code === null ? 'killed' : code}]`;
325
+ resolve(out);
326
+ });
327
+ child.on('error', (e) => {
328
+ cleanup();
329
+ // Same identity check as `close`: a failing command must not take another command's hook with it.
330
+ if (ctx && ctx._foreground && ctx._foreground.child === child) ctx._foreground = null;
331
+ if (settled) return;
332
+ settled = true;
333
+ resolve(truncateBuf(sanitizeShellOutput(decodeChunks(chunks))) + `\n[error: ${e.message}]`);
334
+ });
335
+ });
336
+ },
337
+ };
338
+
339
+ // Register an already-spawned child (foreground -> background detach) as a task.
340
+ // Reuses the same task shape and lazy output decoding as spawnBackground. The
341
+ // foreground path's existing stdout/stderr listeners keep writing into the SAME
342
+ // `existingChunks` array the task reads, so we must NOT add new listeners here
343
+ // (doing so doubled every line of output).
344
+ function registerBackgroundTask(args, child, ctx, existingChunks) {
345
+ const task = createTask(ctx, 'process', {
346
+ description: args.description || args.command,
347
+ command: args.command,
348
+ pid: child.pid,
349
+ detached: true,
350
+ _chunks: existingChunks || [],
351
+ });
352
+ defineOutput(task);
353
+ child.on('close', (code) => {
354
+ // A task already settled (TaskStop -> 'killed') keeps its status; the
355
+ // process's non-zero kill exit must not relabel a deliberate stop.
356
+ if (task.status === 'running') {
357
+ settleTask(task, code === 0 ? 'completed' : 'failed', { exitCode: code });
358
+ } else {
359
+ task.exitCode = code;
360
+ }
361
+ });
362
+ return task.taskId;
363
+ }
364
+
365
+ function spawnBackground(args, cwd, ctx) {
366
+ const command = args.command;
367
+ // Detached + piped stdio is not a real detach: when the parent exits, the
368
+ // pipes close and the child gets SIGPIPE. Redirect stdout/stderr to the
369
+ // task's output file instead, so the process survives and TaskOutput can
370
+ // still read it. (In the TUI the parent rarely exits, but headless -p mode
371
+ // does, and a background job should outlive the prompt.)
372
+ //
373
+ // AND NOT ON WINDOWS AT ALL. The note above says `detached: true` with piped stdout returns exit 0 and no output; the
374
+ // same is true for a NON-interactive background command, which is the ordinary Ctrl+B case. Measured with pwsh:
375
+ //
376
+ // detached=false "exit 3" -> exit 3, output intact
377
+ // detached=true "exit 3" -> exit 0, output EMPTY
378
+ // detached=true "echo hello" -> exit 0, output EMPTY
379
+ //
380
+ // So on Windows the process stays attached: its output and its exit code are the whole point of a background task, and
381
+ // a task that reports success whatever happened is worse than one that dies with its parent. Elsewhere the detach is
382
+ // what makes a job outlive headless `-p`, so it is kept.
383
+ const canDetach = process.platform !== 'win32' && !args.interactive;
384
+ let shell;
385
+ try { shell = shellSpawnArgs(command, { interactive: args.interactive }); } catch (e) { return `Error: ${e.message}`; }
386
+ const child = cp.spawn(shell.bin, shell.args, {
387
+ cwd, detached: canDetach, stdio: [args.interactive ? 'pipe' : 'ignore', 'pipe', 'pipe'], env: { ...process.env },
388
+ });
389
+ const task = createTask(ctx, 'process', {
390
+ description: args.description || args.command,
391
+ command: args.command,
392
+ pid: child.pid,
393
+ detached: canDetach,
394
+ });
395
+ // The stdin pipe, when the caller asked for one. Kept on the TASK so `TaskInput` can reach it from a
396
+ // task id alone — a tool receives an id, not a handle. Only `interactive` gets here, so a plain
397
+ // background job is unaffected and cannot be fed input by accident.
398
+ if (args.interactive && child.stdin) {
399
+ task.stdin = child.stdin;
400
+ task.interactive = true;
401
+ // A closed pipe is normal at the end of a run; writing afterwards would throw EPIPE.
402
+ child.stdin.on('error', () => { task.stdin = null; });
403
+ child.on('close', () => { task.stdin = null; });
404
+ }
405
+ defineOutput(task);
406
+ const push = (d) => appendTaskOutput(task, d);
407
+ if (child.stdout) child.stdout.on('data', push);
408
+ if (child.stderr) child.stderr.on('data', push);
409
+ child.on('close', (code) => {
410
+ if (task.status === 'running') {
411
+ settleTask(task, code === 0 ? 'completed' : 'failed', { exitCode: code });
412
+ } else {
413
+ task.exitCode = code;
414
+ }
415
+ });
416
+ // THE BACKGROUND TIMEOUT IS OPT-IN.
417
+ //
418
+ // A background task was started precisely because it takes a while — a build, a test
419
+ // suite, a deploy. Killing it after ten minutes because nobody happened to say
420
+ // otherwise meant the job the user deliberately put in the background died on a clock
421
+ // they never asked for, and the work was simply lost.
422
+ //
423
+ // So there is no default limit: the task runs until it finishes or until someone stops
424
+ // it. A limit applies only when the caller asked for one, and even then it is capped so
425
+ // a mistyped number cannot leave a process running for a week.
426
+ if (!args.disable_timeout && args.timeout != null) {
427
+ const bgTimeoutMs = Math.min(args.timeout, MAX_BACKGROUND_TIMEOUT_S) * 1000;
428
+ const t = setTimeout(() => {
429
+ killTree(child);
430
+ settleTask(task, 'timed_out', { stopReason: 'timed out' });
431
+ }, bgTimeoutMs);
432
+ if (t.unref) t.unref();
433
+ }
434
+ child.unref();
435
+ return `Background task ${task.taskId} started (pid ${child.pid}): ${args.description || args.command}
436
+ Inspect with TaskList (running tasks) and TaskOutput {task_id: "${task.taskId}"} (output).`;
437
+ }
438
+
439
+ // Lazy output: the accumulated bytes are decoded only when actually read, so a
440
+ // chatty background task costs nothing until queried.
441
+ function defineOutput(task) {
442
+ Object.defineProperty(task, 'output', {
443
+ enumerable: true,
444
+ get() { return sanitizeShellOutput(decodeChunks(this._chunks)); },
445
+ });
446
+ }