@hncode/hncode 0.7.6 → 0.7.8

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,420 +1,427 @@
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 } from './utils.js';
9
- import { createTask, appendTaskOutput, settleTask } from '../agent-task.js';
10
- import { shellSpawnArgs } 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
- description: 'Run a shell command via pwsh. Returns combined stdout+stderr. timeout default 60s (max 300s); run_in_background detaches and returns a task id.',
131
- parameters: {
132
- type: 'object',
133
- properties: {
134
- command: { type: 'string', description: 'Shell command to execute.' },
135
- description: { type: 'string', description: 'Short description (shown in task lists; required for background tasks).' },
136
- timeout: { type: 'integer', minimum: 1, description: 'Seconds before the command is killed. Foreground default 60s/max 300s; background default 600s/max 86400s.' },
137
- cwd: { type: 'string', description: 'Working directory (default: workspace/project root).' },
138
- run_in_background: { type: 'boolean', default: false, description: 'Run detached and return a task id instead of waiting.' },
139
- interactive: { type: 'boolean', default: false, description: 'With run_in_background: keep stdin open so TaskInput can write to it — for a command that prompts.' },
140
- disable_timeout: { type: 'boolean', default: false, description: 'Disable the timeout (background only).' },
141
- },
142
- required: ['command'],
143
- },
144
- async execute(args, ctx) {
145
- if (!args.command || !String(args.command).length) return 'Command cannot be empty.';
146
- const cwdRaw = args.cwd || ctx.workspace;
147
- let cwd;
148
- try { cwd = resolvePath(cwdRaw, ctx); } catch (e) { return e.message; }
149
- if (!fs.existsSync(cwd)) return `Error: cwd does not exist: ${cwdRaw}`;
150
-
151
- if (args.run_in_background) return spawnBackground(args, cwd, ctx);
152
-
153
- const bg = false;
154
- const cap = bg ? MAX_BACKGROUND_TIMEOUT_S : MAX_TIMEOUT_S;
155
- const def = bg ? DEFAULT_BACKGROUND_TIMEOUT_S : DEFAULT_TIMEOUT_S;
156
- const timeoutMs = args.disable_timeout ? undefined : Math.min(args.timeout ?? def, cap) * 1000;
157
- const command = args.command;
158
- // stdin is 'ignore' by default (NUL / /dev/null): leaving it as an open pipe made any command that
159
- // reads stdin (`cat`, `npm init`, …) block until the timeout.
160
- //
161
- // `interactive` OPTS INTO A PIPE, and only for a background run: a foreground command has nobody to
162
- // type at it, while a background one can be fed through TaskInput. The pipe is closed by that tool
163
- // when it is done, which is what keeps `cat` and friends from hanging.
164
- if (args.interactive && !args.run_in_background) {
165
- return 'Error: `interactive` requires `run_in_background: true` — a foreground run has no way to receive input.';
166
- }
167
- let shell;
168
- try { shell = shellSpawnArgs(command); } catch (e) { return `Error: ${e.message}`; }
169
- // Check the turn's signal BEFORE spawning. The check below ran only after the
170
- // child existed: an abort landing in that window returned "Interrupted by user"
171
- // while leaving the child RUNNING with open pipes until the timeout timer fired,
172
- // and Esc could not stop it.
173
- if (ctx.signal && ctx.signal.aborted) return 'Interrupted by user';
174
- const child = cp.spawn(shell.bin, shell.args, {
175
- cwd, stdio: [args.interactive ? 'pipe' : 'ignore', 'pipe', 'pipe'], env: { ...process.env },
176
- });
177
-
178
- const chunks = [];
179
- let settled = false;
180
- // Bytes shed by the live ring, reported on the finished result so a trimmed
181
- // run does not look like a short one.
182
- let chunksDropped = 0;
183
- // Live stream sink: hand decoded output to the agent (ctx.onOutput) so the UI
184
- // can show a running command's output in real time, exactly like the
185
- // finished "Used Bash" row does. Foreground runs only — a background task's
186
- // output is read through TaskOutput.
187
- //
188
-
189
- //
190
- // Decoding is STREAMING (a multi-byte char can be split across chunks), and
191
- // sanitizing runs over complete LINES rather than the whole accumulated text.
192
- // The old form re-ran the escape regexes over everything received so far on
193
- // EVERY chunk — O(n²) over the run, plus a fresh full-length string per chunk
194
- // — which is what made a chatty command slow the process down and double its
195
- // peak memory.
196
- //
197
- // Line-by-line is also what keeps an escape sequence from being cut in half:
198
- // a sequence never contains a newline, so a complete line is always safe to
199
- // sanitize, and the trailing partial line waits for more input.
200
- // THE LIVE STREAM MUST DECODE EXACTLY THE WAY THE FINAL RESULT DOES.
201
- //
202
- // The finished output goes through `decodeBuffer`, which tries strict UTF-8 and FALLS BACK TO GBK. The
203
- // live sink used a plain non-fatal UTF-8 decoder, so a command whose output is not UTF-8 — PowerShell on a
204
- // Chinese Windows writes GBK for native tools — streamed as replacement characters while it ran and then
205
- // turned correct the moment it finished. That is the "garbled while running, fine afterwards" report.
206
- //
207
- // The live path cannot buffer the whole run, so it decides from the first chunk that proves itself: valid
208
- // UTF-8 keeps the UTF-8 decoder, anything else pins GBK for the rest of the stream. A chunk boundary
209
- // through the middle of a multi-byte character looks invalid too, so a failed probe is retried once with
210
- // the remaining bytes before the encoding is pinned.
211
- const sink = typeof ctx.onOutput === 'function' ? ctx.onOutput : null;
212
- let liveDecoder = sink ? new TextDecoder('utf-8') : null;
213
- let livePending = '';
214
- let liveUndecided = !!sink; // the probe has not committed yet
215
- const push = (d) => {
216
- chunks.push(d);
217
- const dropped = trimChunkRing(chunks, LIVE_RING_BYTES);
218
- if (dropped) chunksDropped += dropped;
219
-
220
- if (!sink || settled) return;
221
- try {
222
- const buf = Buffer.isBuffer(d) ? d : Buffer.from(String(d));
223
- if (liveUndecided) {
224
- // A trailing partial character makes a valid UTF-8 chunk look invalid. Only a chunk that still
225
- // fails after its own tail is set aside is evidence.
226
- let valid = false;
227
- try {
228
- new TextDecoder('utf-8', { fatal: true }).decode(buf);
229
- valid = true;
230
- } catch {
231
- // Trim up to three trailing bytes and try once more: that is the longest an incomplete UTF-8
232
- // sequence can be.
233
- for (let cut = 1; cut <= 3 && cut < buf.length; cut++) {
234
- try {
235
- new TextDecoder('utf-8', { fatal: true }).decode(buf.subarray(0, buf.length - cut));
236
- valid = true;
237
- break;
238
- } catch { /* keep trimming */ }
239
- }
240
- }
241
- if (!valid) liveDecoder = new TextDecoder('gbk');
242
- liveUndecided = false;
243
- }
244
- // One decoder for the whole stream, in streaming mode: a GBK character is two bytes and will be split
245
- // across chunks just as often as a UTF-8 one.
246
- livePending += liveDecoder.decode(buf, { stream: true });
247
- const nl = livePending.lastIndexOf('\n');
248
- if (nl < 0) return;
249
- const complete = livePending.slice(0, nl + 1);
250
- livePending = livePending.slice(nl + 1);
251
- const clean = sanitizeShellOutput(complete);
252
- if (clean) sink(clean);
253
- } catch { /* display is best-effort; the result below is authoritative */ }
254
- };
255
- if (child.stdout) child.stdout.on('data', push);
256
- if (child.stderr) child.stderr.on('data', push);
257
-
258
- let timer = null;
259
- if (timeoutMs) timer = setTimeout(() => { killTree(child); }, timeoutMs);
260
-
261
- // Esc / Ctrl-C in the TUI aborts the turn: kill the running command too,
262
- // otherwise a long command keeps running after the user interrupted.
263
- const signal = ctx.signal;
264
- const onAbort = () => { killTree(child); };
265
- if (signal) {
266
- if (signal.aborted) return 'Interrupted by user';
267
- signal.addEventListener('abort', onAbort, { once: true });
268
- }
269
- const cleanup = () => {
270
- if (timer) clearTimeout(timer);
271
- if (signal) signal.removeEventListener('abort', onAbort);
272
- };
273
-
274
- return new Promise((resolve) => {
275
- // Expose a detach hook so the TUI's ctrl+b can move a long-running
276
- // foreground command into the background WITHOUT killing it: the child
277
- // keeps running, gets registered as a task, and this promise resolves
278
- // immediately with a "moved to background" note so the agent continues.
279
- if (ctx) {
280
- ctx._foreground = {
281
- command: args.command,
282
- description: args.description || args.command,
283
- child, chunks,
284
- detach: () => {
285
- if (settled) return null;
286
- settled = true;
287
- cleanup();
288
- // Stop treating this as foreground: drop the abort listener so an
289
- // Esc after detaching does not kill the now-background task.
290
- if (signal) signal.removeEventListener('abort', onAbort);
291
- const id = registerBackgroundTask(args, child, ctx, chunks);
292
- resolve(`Moved to background as task #${id}. It keeps running; inspect with TaskList / TaskOutput {task_id: "${id}"}.`);
293
- return id;
294
- },
295
- };
296
- }
297
- child.on('close', (code) => {
298
- cleanup();
299
- if (ctx) ctx._foreground = null;
300
- if (settled) return;
301
- settled = true;
302
- // Flush the last partial line the live sink was holding back.
303
- if (sink && livePending) {
304
- try { sink(sanitizeShellOutput(livePending)); } catch { /* best-effort */ }
305
- livePending = '';
306
- }
307
- if (signal && signal.aborted) { resolve('Interrupted by user'); return; }
308
- let out = truncateBuf(sanitizeShellOutput(decodeChunks(chunks)));
309
- // A trimmed run says so; otherwise the result would look complete while
310
- // quietly missing its head.
311
- if (chunksDropped) out = `...[dropped ${chunksDropped} bytes of earlier output]\n` + out;
312
- out += `\n[exit code: ${code === null ? 'killed' : code}]`;
313
- resolve(out);
314
- });
315
- child.on('error', (e) => {
316
-
317
- cleanup();
318
- if (ctx) ctx._foreground = null;
319
- if (settled) return;
320
- settled = true;
321
- resolve(truncateBuf(sanitizeShellOutput(decodeChunks(chunks))) + `\n[error: ${e.message}]`);
322
- });
323
- });
324
- },
325
- };
326
-
327
- // Register an already-spawned child (foreground -> background detach) as a task.
328
- // Reuses the same task shape and lazy output decoding as spawnBackground. The
329
- // foreground path's existing stdout/stderr listeners keep writing into the SAME
330
- // `existingChunks` array the task reads, so we must NOT add new listeners here
331
- // (doing so doubled every line of output).
332
- function registerBackgroundTask(args, child, ctx, existingChunks) {
333
- const task = createTask(ctx, 'process', {
334
- description: args.description || args.command,
335
- command: args.command,
336
- pid: child.pid,
337
- detached: true,
338
- _chunks: existingChunks || [],
339
- });
340
- defineOutput(task);
341
- child.on('close', (code) => {
342
- // A task already settled (TaskStop -> 'killed') keeps its status; the
343
- // process's non-zero kill exit must not relabel a deliberate stop.
344
- if (task.status === 'running') {
345
- settleTask(task, code === 0 ? 'completed' : 'failed', { exitCode: code });
346
- } else {
347
- task.exitCode = code;
348
- }
349
- });
350
- return task.taskId;
351
- }
352
-
353
- function spawnBackground(args, cwd, ctx) {
354
- const command = args.command;
355
- // Detached + piped stdio is not a real detach: when the parent exits, the
356
- // pipes close and the child gets SIGPIPE. Redirect stdout/stderr to the
357
- // task's output file instead, so the process survives and TaskOutput can
358
- // still read it. (In the TUI the parent rarely exits, but headless -p mode
359
- // does, and a background job should outlive the prompt.)
360
- //
361
- // AN INTERACTIVE RUN CANNOT BE DETACHED. Measured on Windows: `detached: true` with piped stdout
362
- // returns exit 0 and NO output, while the same command not detached returns its output normally — the
363
- // detached process gets no working pipe back to us. Interactive needs that pipe in both directions, so
364
- // it stays attached. The trade: it will not outlive the parent, which is the same lifetime its stdin
365
- // already has.
366
- let shell;
367
- try { shell = shellSpawnArgs(command, { interactive: args.interactive }); } catch (e) { return `Error: ${e.message}`; }
368
- const child = cp.spawn(shell.bin, shell.args, {
369
- cwd, detached: !args.interactive, stdio: [args.interactive ? 'pipe' : 'ignore', 'pipe', 'pipe'], env: { ...process.env },
370
- });
371
- const task = createTask(ctx, 'process', {
372
- description: args.description || args.command,
373
- command: args.command,
374
- pid: child.pid,
375
- detached: !args.interactive,
376
- });
377
- // The stdin pipe, when the caller asked for one. Kept on the TASK so `TaskInput` can reach it from a
378
- // task id alone — a tool receives an id, not a handle. Only `interactive` gets here, so a plain
379
- // background job is unaffected and cannot be fed input by accident.
380
- if (args.interactive && child.stdin) {
381
- task.stdin = child.stdin;
382
- task.interactive = true;
383
- // A closed pipe is normal at the end of a run; writing afterwards would throw EPIPE.
384
- child.stdin.on('error', () => { task.stdin = null; });
385
- child.on('close', () => { task.stdin = null; });
386
- }
387
- defineOutput(task);
388
- const push = (d) => appendTaskOutput(task, d);
389
- if (child.stdout) child.stdout.on('data', push);
390
- if (child.stderr) child.stderr.on('data', push);
391
- child.on('close', (code) => {
392
- if (task.status === 'running') {
393
- settleTask(task, code === 0 ? 'completed' : 'failed', { exitCode: code });
394
- } else {
395
- task.exitCode = code;
396
- }
397
- });
398
- // Background timeout: default 600s, capped at 86400s; `disable_timeout` removes
399
- // it. The timer is unref'd so it never keeps the process alive on its own.
400
- if (!args.disable_timeout) {
401
- const bgTimeoutMs = Math.min(args.timeout ?? DEFAULT_BACKGROUND_TIMEOUT_S, MAX_BACKGROUND_TIMEOUT_S) * 1000;
402
- const t = setTimeout(() => {
403
- killTree(child);
404
- settleTask(task, 'timed_out', { stopReason: 'timed out' });
405
- }, bgTimeoutMs);
406
- if (t.unref) t.unref();
407
- }
408
- child.unref();
409
- return `Background task ${task.taskId} started (pid ${child.pid}): ${args.description || args.command}
410
- Inspect with TaskList (running tasks) and TaskOutput {task_id: "${task.taskId}"} (output).`;
411
- }
412
-
413
- // Lazy output: the accumulated bytes are decoded only when actually read, so a
414
- // chatty background task costs nothing until queried.
415
- function defineOutput(task) {
416
- Object.defineProperty(task, 'output', {
417
- enumerable: true,
418
- get() { return sanitizeShellOutput(decodeChunks(this._chunks)); },
419
- });
420
- }
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 } from './utils.js';
9
+ import { createTask, appendTaskOutput, settleTask } from '../agent-task.js';
10
+ import { shellSpawnArgs } 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
+ description: 'Run a shell command via pwsh. Returns combined stdout+stderr. timeout default 60s (max 300s); run_in_background detaches and returns a task id.',
131
+ parameters: {
132
+ type: 'object',
133
+ properties: {
134
+ command: { type: 'string', description: 'Shell command to execute.' },
135
+ description: { type: 'string', description: 'Short description (shown in task lists; required for background tasks).' },
136
+ timeout: { type: 'integer', minimum: 1, description: 'Seconds before the command is killed. Foreground default 60s/max 300s; background default 600s/max 86400s.' },
137
+ cwd: { type: 'string', description: 'Working directory (default: workspace/project root).' },
138
+ run_in_background: { type: 'boolean', default: false, description: 'Run detached and return a task id instead of waiting.' },
139
+ interactive: { type: 'boolean', default: false, description: 'With run_in_background: keep stdin open so TaskInput can write to it — for a command that prompts.' },
140
+ disable_timeout: { type: 'boolean', default: false, description: 'Disable the timeout (background only).' },
141
+ },
142
+ required: ['command'],
143
+ },
144
+ async execute(args, ctx) {
145
+ if (!args.command || !String(args.command).length) return 'Command cannot be empty.';
146
+ const cwdRaw = args.cwd || ctx.workspace;
147
+ let cwd;
148
+ try { cwd = resolvePath(cwdRaw, ctx); } catch (e) { return e.message; }
149
+ if (!fs.existsSync(cwd)) return `Error: cwd does not exist: ${cwdRaw}`;
150
+
151
+ if (args.run_in_background) return spawnBackground(args, cwd, ctx);
152
+
153
+ const bg = false;
154
+ const cap = bg ? MAX_BACKGROUND_TIMEOUT_S : MAX_TIMEOUT_S;
155
+ const def = bg ? DEFAULT_BACKGROUND_TIMEOUT_S : DEFAULT_TIMEOUT_S;
156
+ const timeoutMs = args.disable_timeout ? undefined : Math.min(args.timeout ?? def, cap) * 1000;
157
+ const command = args.command;
158
+ // stdin is 'ignore' by default (NUL / /dev/null): leaving it as an open pipe made any command that
159
+ // reads stdin (`cat`, `npm init`, …) block until the timeout.
160
+ //
161
+ // `interactive` OPTS INTO A PIPE, and only for a background run: a foreground command has nobody to
162
+ // type at it, while a background one can be fed through TaskInput. The pipe is closed by that tool
163
+ // when it is done, which is what keeps `cat` and friends from hanging.
164
+ if (args.interactive && !args.run_in_background) {
165
+ return 'Error: `interactive` requires `run_in_background: true` — a foreground run has no way to receive input.';
166
+ }
167
+ let shell;
168
+ try { shell = shellSpawnArgs(command); } catch (e) { return `Error: ${e.message}`; }
169
+ // Check the turn's signal BEFORE spawning. The check below ran only after the
170
+ // child existed: an abort landing in that window returned "Interrupted by user"
171
+ // while leaving the child RUNNING with open pipes until the timeout timer fired,
172
+ // and Esc could not stop it.
173
+ if (ctx.signal && ctx.signal.aborted) return 'Interrupted by user';
174
+ const child = cp.spawn(shell.bin, shell.args, {
175
+ cwd, stdio: [args.interactive ? 'pipe' : 'ignore', 'pipe', 'pipe'], env: { ...process.env },
176
+ });
177
+
178
+ const chunks = [];
179
+ let settled = false;
180
+ // Bytes shed by the live ring, reported on the finished result so a trimmed
181
+ // run does not look like a short one.
182
+ let chunksDropped = 0;
183
+ // Live stream sink: hand decoded output to the agent (ctx.onOutput) so the UI
184
+ // can show a running command's output in real time, exactly like the
185
+ // finished "Used Bash" row does. Foreground runs only — a background task's
186
+ // output is read through TaskOutput.
187
+ //
188
+
189
+ //
190
+ // Decoding is STREAMING (a multi-byte char can be split across chunks), and
191
+ // sanitizing runs over complete LINES rather than the whole accumulated text.
192
+ // The old form re-ran the escape regexes over everything received so far on
193
+ // EVERY chunk — O(n²) over the run, plus a fresh full-length string per chunk
194
+ // — which is what made a chatty command slow the process down and double its
195
+ // peak memory.
196
+ //
197
+ // Line-by-line is also what keeps an escape sequence from being cut in half:
198
+ // a sequence never contains a newline, so a complete line is always safe to
199
+ // sanitize, and the trailing partial line waits for more input.
200
+ // THE LIVE STREAM MUST DECODE EXACTLY THE WAY THE FINAL RESULT DOES.
201
+ //
202
+ // The finished output goes through `decodeBuffer`, which tries strict UTF-8 and FALLS BACK TO GBK. The
203
+ // live sink used a plain non-fatal UTF-8 decoder, so a command whose output is not UTF-8 — PowerShell on a
204
+ // Chinese Windows writes GBK for native tools — streamed as replacement characters while it ran and then
205
+ // turned correct the moment it finished. That is the "garbled while running, fine afterwards" report.
206
+ //
207
+ // The live path cannot buffer the whole run, so it decides from the first chunk that proves itself: valid
208
+ // UTF-8 keeps the UTF-8 decoder, anything else pins GBK for the rest of the stream. A chunk boundary
209
+ // through the middle of a multi-byte character looks invalid too, so a failed probe is retried once with
210
+ // the remaining bytes before the encoding is pinned.
211
+ const sink = typeof ctx.onOutput === 'function' ? ctx.onOutput : null;
212
+ let liveDecoder = sink ? new TextDecoder('utf-8') : null;
213
+ let livePending = '';
214
+ let liveUndecided = !!sink; // the probe has not committed yet
215
+ const push = (d) => {
216
+ chunks.push(d);
217
+ const dropped = trimChunkRing(chunks, LIVE_RING_BYTES);
218
+ if (dropped) chunksDropped += dropped;
219
+
220
+ if (!sink || settled) return;
221
+ try {
222
+ const buf = Buffer.isBuffer(d) ? d : Buffer.from(String(d));
223
+ if (liveUndecided) {
224
+ // A trailing partial character makes a valid UTF-8 chunk look invalid. Only a chunk that still
225
+ // fails after its own tail is set aside is evidence.
226
+ let valid = false;
227
+ try {
228
+ new TextDecoder('utf-8', { fatal: true }).decode(buf);
229
+ valid = true;
230
+ } catch {
231
+ // Trim up to three trailing bytes and try once more: that is the longest an incomplete UTF-8
232
+ // sequence can be.
233
+ for (let cut = 1; cut <= 3 && cut < buf.length; cut++) {
234
+ try {
235
+ new TextDecoder('utf-8', { fatal: true }).decode(buf.subarray(0, buf.length - cut));
236
+ valid = true;
237
+ break;
238
+ } catch { /* keep trimming */ }
239
+ }
240
+ }
241
+ if (!valid) liveDecoder = new TextDecoder('gbk');
242
+ liveUndecided = false;
243
+ }
244
+ // One decoder for the whole stream, in streaming mode: a GBK character is two bytes and will be split
245
+ // across chunks just as often as a UTF-8 one.
246
+ livePending += liveDecoder.decode(buf, { stream: true });
247
+ const nl = livePending.lastIndexOf('\n');
248
+ if (nl < 0) return;
249
+ const complete = livePending.slice(0, nl + 1);
250
+ livePending = livePending.slice(nl + 1);
251
+ const clean = sanitizeShellOutput(complete);
252
+ if (clean) sink(clean);
253
+ } catch { /* display is best-effort; the result below is authoritative */ }
254
+ };
255
+ if (child.stdout) child.stdout.on('data', push);
256
+ if (child.stderr) child.stderr.on('data', push);
257
+
258
+ let timer = null;
259
+ if (timeoutMs) timer = setTimeout(() => { killTree(child); }, timeoutMs);
260
+
261
+ // Esc / Ctrl-C in the TUI aborts the turn: kill the running command too,
262
+ // otherwise a long command keeps running after the user interrupted.
263
+ const signal = ctx.signal;
264
+ const onAbort = () => { killTree(child); };
265
+ if (signal) {
266
+ if (signal.aborted) return 'Interrupted by user';
267
+ signal.addEventListener('abort', onAbort, { once: true });
268
+ }
269
+ const cleanup = () => {
270
+ if (timer) clearTimeout(timer);
271
+ if (signal) signal.removeEventListener('abort', onAbort);
272
+ };
273
+
274
+ return new Promise((resolve) => {
275
+ // Expose a detach hook so the TUI's ctrl+b can move a long-running
276
+ // foreground command into the background WITHOUT killing it: the child
277
+ // keeps running, gets registered as a task, and this promise resolves
278
+ // immediately with a "moved to background" note so the agent continues.
279
+ if (ctx) {
280
+ // THE HOOK BELONGS TO THE NEWEST FOREGROUND COMMAND. Replacing it here is what makes the identity check
281
+ // above correct: a command that finishes later compares `ctx._foreground.child` against its own child and
282
+ // leaves someone else's hook alone.
283
+ ctx._foreground = {
284
+ command: args.command,
285
+ description: args.description || args.command,
286
+ child, chunks,
287
+ detach: () => {
288
+ if (settled) return null;
289
+ settled = true;
290
+ cleanup();
291
+ // Stop treating this as foreground: drop the abort listener so an
292
+ // Esc after detaching does not kill the now-background task.
293
+ if (signal) signal.removeEventListener('abort', onAbort);
294
+ // AND DROP THE HOOK. `child.on('close')` clears it for a command that finishes on its own, but a
295
+ // detached one resolves HERE and never reaches that path — so the hook stayed set, and a second Ctrl+B
296
+ // called `detach` again, got null, and did nothing at all.
297
+ if (ctx && ctx._foreground && ctx._foreground.child === child) ctx._foreground = null;
298
+ const id = registerBackgroundTask(args, child, ctx, chunks);
299
+ resolve(`Moved to background as task #${id}. It keeps running; inspect with TaskList / TaskOutput {task_id: "${id}"}.`);
300
+ return id;
301
+ },
302
+ };
303
+ }
304
+ child.on('close', (code) => {
305
+ cleanup();
306
+ if (ctx && ctx._foreground && ctx._foreground.child === child) ctx._foreground = null;
307
+ if (settled) return;
308
+ settled = true;
309
+ // Flush the last partial line the live sink was holding back.
310
+ if (sink && livePending) {
311
+ try { sink(sanitizeShellOutput(livePending)); } catch { /* best-effort */ }
312
+ livePending = '';
313
+ }
314
+ if (signal && signal.aborted) { resolve('Interrupted by user'); return; }
315
+ let out = truncateBuf(sanitizeShellOutput(decodeChunks(chunks)));
316
+ // A trimmed run says so; otherwise the result would look complete while
317
+ // quietly missing its head.
318
+ if (chunksDropped) out = `...[dropped ${chunksDropped} bytes of earlier output]\n` + out;
319
+ out += `\n[exit code: ${code === null ? 'killed' : code}]`;
320
+ resolve(out);
321
+ });
322
+ child.on('error', (e) => {
323
+ cleanup();
324
+ // Same identity check as `close`: a failing command must not take another command's hook with it.
325
+ if (ctx && ctx._foreground && ctx._foreground.child === child) ctx._foreground = null;
326
+ if (settled) return;
327
+ settled = true;
328
+ resolve(truncateBuf(sanitizeShellOutput(decodeChunks(chunks))) + `\n[error: ${e.message}]`);
329
+ });
330
+ });
331
+ },
332
+ };
333
+
334
+ // Register an already-spawned child (foreground -> background detach) as a task.
335
+ // Reuses the same task shape and lazy output decoding as spawnBackground. The
336
+ // foreground path's existing stdout/stderr listeners keep writing into the SAME
337
+ // `existingChunks` array the task reads, so we must NOT add new listeners here
338
+ // (doing so doubled every line of output).
339
+ function registerBackgroundTask(args, child, ctx, existingChunks) {
340
+ const task = createTask(ctx, 'process', {
341
+ description: args.description || args.command,
342
+ command: args.command,
343
+ pid: child.pid,
344
+ detached: true,
345
+ _chunks: existingChunks || [],
346
+ });
347
+ defineOutput(task);
348
+ child.on('close', (code) => {
349
+ // A task already settled (TaskStop -> 'killed') keeps its status; the
350
+ // process's non-zero kill exit must not relabel a deliberate stop.
351
+ if (task.status === 'running') {
352
+ settleTask(task, code === 0 ? 'completed' : 'failed', { exitCode: code });
353
+ } else {
354
+ task.exitCode = code;
355
+ }
356
+ });
357
+ return task.taskId;
358
+ }
359
+
360
+ function spawnBackground(args, cwd, ctx) {
361
+ const command = args.command;
362
+ // Detached + piped stdio is not a real detach: when the parent exits, the
363
+ // pipes close and the child gets SIGPIPE. Redirect stdout/stderr to the
364
+ // task's output file instead, so the process survives and TaskOutput can
365
+ // still read it. (In the TUI the parent rarely exits, but headless -p mode
366
+ // does, and a background job should outlive the prompt.)
367
+ //
368
+ // AN INTERACTIVE RUN CANNOT BE DETACHED. Measured on Windows: `detached: true` with piped stdout
369
+ // returns exit 0 and NO output, while the same command not detached returns its output normally — the
370
+ // detached process gets no working pipe back to us. Interactive needs that pipe in both directions, so
371
+ // it stays attached. The trade: it will not outlive the parent, which is the same lifetime its stdin
372
+ // already has.
373
+ let shell;
374
+ try { shell = shellSpawnArgs(command, { interactive: args.interactive }); } catch (e) { return `Error: ${e.message}`; }
375
+ const child = cp.spawn(shell.bin, shell.args, {
376
+ cwd, detached: !args.interactive, stdio: [args.interactive ? 'pipe' : 'ignore', 'pipe', 'pipe'], env: { ...process.env },
377
+ });
378
+ const task = createTask(ctx, 'process', {
379
+ description: args.description || args.command,
380
+ command: args.command,
381
+ pid: child.pid,
382
+ detached: !args.interactive,
383
+ });
384
+ // The stdin pipe, when the caller asked for one. Kept on the TASK so `TaskInput` can reach it from a
385
+ // task id alone — a tool receives an id, not a handle. Only `interactive` gets here, so a plain
386
+ // background job is unaffected and cannot be fed input by accident.
387
+ if (args.interactive && child.stdin) {
388
+ task.stdin = child.stdin;
389
+ task.interactive = true;
390
+ // A closed pipe is normal at the end of a run; writing afterwards would throw EPIPE.
391
+ child.stdin.on('error', () => { task.stdin = null; });
392
+ child.on('close', () => { task.stdin = null; });
393
+ }
394
+ defineOutput(task);
395
+ const push = (d) => appendTaskOutput(task, d);
396
+ if (child.stdout) child.stdout.on('data', push);
397
+ if (child.stderr) child.stderr.on('data', push);
398
+ child.on('close', (code) => {
399
+ if (task.status === 'running') {
400
+ settleTask(task, code === 0 ? 'completed' : 'failed', { exitCode: code });
401
+ } else {
402
+ task.exitCode = code;
403
+ }
404
+ });
405
+ // Background timeout: default 600s, capped at 86400s; `disable_timeout` removes
406
+ // it. The timer is unref'd so it never keeps the process alive on its own.
407
+ if (!args.disable_timeout) {
408
+ const bgTimeoutMs = Math.min(args.timeout ?? DEFAULT_BACKGROUND_TIMEOUT_S, MAX_BACKGROUND_TIMEOUT_S) * 1000;
409
+ const t = setTimeout(() => {
410
+ killTree(child);
411
+ settleTask(task, 'timed_out', { stopReason: 'timed out' });
412
+ }, bgTimeoutMs);
413
+ if (t.unref) t.unref();
414
+ }
415
+ child.unref();
416
+ return `Background task ${task.taskId} started (pid ${child.pid}): ${args.description || args.command}
417
+ Inspect with TaskList (running tasks) and TaskOutput {task_id: "${task.taskId}"} (output).`;
418
+ }
419
+
420
+ // Lazy output: the accumulated bytes are decoded only when actually read, so a
421
+ // chatty background task costs nothing until queried.
422
+ function defineOutput(task) {
423
+ Object.defineProperty(task, 'output', {
424
+ enumerable: true,
425
+ get() { return sanitizeShellOutput(decodeChunks(this._chunks)); },
426
+ });
427
+ }