@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/bin/hncode +54 -8
- package/package.json +1 -1
- package/src/agent-task.js +14 -12
- package/src/agent.js +1465 -1421
- package/src/animate.js +21 -0
- package/src/colors.js +615 -593
- package/src/config.js +36 -11
- package/src/context-bar.js +280 -277
- package/src/doctor.js +4 -3
- package/src/i18n.js +1438 -1214
- package/src/index.js +822 -730
- package/src/keybindings.js +2 -1
- package/src/markdown.js +37 -10
- package/src/mcp-server.js +409 -0
- package/src/mcp.js +279 -29
- package/src/memory-profile.js +19 -16
- package/src/plan.js +7 -5
- package/src/plugin.js +37 -21
- package/src/registry-browser.js +17 -15
- package/src/rows-tool-result.js +251 -235
- package/src/settings-schema.js +9 -0
- package/src/swarm-progress.js +1 -1
- package/src/tasks-browser.js +28 -28
- package/src/term.js +57 -21
- package/src/text.js +62 -0
- package/src/tools/agent.js +7 -2
- package/src/tools/bash.js +446 -440
- package/src/tools/edit.js +14 -1
- package/src/tui.js +542 -330
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
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
//
|
|
21
|
-
//
|
|
22
|
-
//
|
|
23
|
-
//
|
|
24
|
-
//
|
|
25
|
-
//
|
|
26
|
-
|
|
27
|
-
const
|
|
28
|
-
const
|
|
29
|
-
const
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
.replace(
|
|
37
|
-
.replace(
|
|
38
|
-
.replace(
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
*
|
|
54
|
-
*
|
|
55
|
-
*
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
*
|
|
59
|
-
*
|
|
60
|
-
*
|
|
61
|
-
*
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
//
|
|
84
|
-
// `
|
|
85
|
-
//
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
if (Buffer.
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
*
|
|
102
|
-
*
|
|
103
|
-
*
|
|
104
|
-
*
|
|
105
|
-
*
|
|
106
|
-
*
|
|
107
|
-
*
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
if (
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
//
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
//
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
const
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
const
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
//
|
|
165
|
-
//
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
//
|
|
171
|
-
//
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
//
|
|
183
|
-
|
|
184
|
-
//
|
|
185
|
-
//
|
|
186
|
-
//
|
|
187
|
-
|
|
188
|
-
//
|
|
189
|
-
|
|
190
|
-
//
|
|
191
|
-
//
|
|
192
|
-
//
|
|
193
|
-
//
|
|
194
|
-
//
|
|
195
|
-
//
|
|
196
|
-
//
|
|
197
|
-
//
|
|
198
|
-
//
|
|
199
|
-
//
|
|
200
|
-
//
|
|
201
|
-
//
|
|
202
|
-
//
|
|
203
|
-
//
|
|
204
|
-
//
|
|
205
|
-
//
|
|
206
|
-
//
|
|
207
|
-
//
|
|
208
|
-
//
|
|
209
|
-
//
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
let
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
if (
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
const
|
|
249
|
-
|
|
250
|
-
const
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
//
|
|
277
|
-
//
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
//
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
child,
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
//
|
|
300
|
-
|
|
301
|
-
//
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
//
|
|
342
|
-
//
|
|
343
|
-
//
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
}
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
//
|
|
370
|
-
//
|
|
371
|
-
//
|
|
372
|
-
//
|
|
373
|
-
//
|
|
374
|
-
//
|
|
375
|
-
//
|
|
376
|
-
//
|
|
377
|
-
//
|
|
378
|
-
// detached=
|
|
379
|
-
//
|
|
380
|
-
//
|
|
381
|
-
//
|
|
382
|
-
//
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
//
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
task.
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
}
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
//
|
|
419
|
-
//
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
}
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
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
|
+
}
|