@hncode/hncode 0.8.0 → 0.8.2
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/README.md +18 -0
- package/README_CN.md +14 -0
- package/package.json +1 -1
- package/src/agent-task.js +354 -337
- package/src/agent.js +19 -3
- package/src/animate.js +35 -0
- package/src/clipboard.js +54 -5
- package/src/config.js +25 -7
- package/src/file-tree.js +4 -3
- package/src/highlight.js +20 -6
- package/src/i18n.js +825 -0
- package/src/image-row.js +11 -2
- package/src/index.js +730 -610
- package/src/llm.js +146 -21
- package/src/log-file.js +112 -0
- package/src/markdown.js +619 -567
- package/src/migrate-index.js +175 -0
- package/src/migrate.js +392 -0
- package/src/panels.js +9 -7
- package/src/rows-plan-bg.js +3 -2
- package/src/rows-status.js +20 -6
- package/src/rows-tool-result.js +35 -8
- package/src/screen-paint.js +153 -128
- package/src/session-recover.js +317 -0
- package/src/session.js +203 -13
- package/src/swarm-progress.js +5 -1
- package/src/tasks-browser.js +9 -8
- package/src/team-panel.js +12 -11
- package/src/text.js +192 -149
- package/src/tool-line.js +7 -2
- package/src/tool-result.js +400 -327
- package/src/tools/ask-user-question.js +1 -2
- package/src/tools/bash.js +23 -11
- package/src/tools/edit.js +640 -665
- package/src/tools/goal.js +130 -93
- package/src/tools/read.js +141 -133
- package/src/tools/shell.js +28 -2
- package/src/tools/tasks.js +214 -214
- package/src/tools/utils.js +143 -104
- package/src/tui.js +20689 -19943
package/src/agent-task.js
CHANGED
|
@@ -1,337 +1,354 @@
|
|
|
1
|
-
// Background task registry — the single place tasks are created, listed, stopped
|
|
2
|
-
// and read. Mirrors kimi-code's task model:
|
|
3
|
-
//
|
|
4
|
-
// TaskInfo = base fields + a `kind`-discriminated payload
|
|
5
|
-
// kind 'process' -> { command, pid, exitCode } (Bash run_in_background)
|
|
6
|
-
// kind 'agent' -> { agentId, subagentType, model, thinkingEffort } (Agent)
|
|
7
|
-
// kind 'question' -> { questionCount, toolCallId } (AskUserQuestion bg)
|
|
8
|
-
//
|
|
9
|
-
// Statuses match kimi exactly so the UI can share one vocabulary:
|
|
10
|
-
// running | completed | failed | timed_out | killed | lost
|
|
11
|
-
//
|
|
12
|
-
// Bash used to keep its own ad-hoc objects ('done'/'failed', `id`, `start`), which
|
|
13
|
-
// is why the task panel could not show the same fields as kimi's. Everything now
|
|
14
|
-
// goes through `createTask`, so a task always has the same shape no matter which
|
|
15
|
-
// tool spawned it.
|
|
16
|
-
|
|
17
|
-
export const TERMINAL_STATUSES = new Set(['completed', 'failed', 'timed_out', 'killed', 'lost']);
|
|
18
|
-
|
|
19
|
-
export function isTerminal(status) {
|
|
20
|
-
return TERMINAL_STATUSES.has(status);
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
// `{prefix}-{8 chars}` like kimi's VALID_TASK_ID. Unique even for two tasks
|
|
24
|
-
// created in the same millisecond (a bare Date.now() collided).
|
|
25
|
-
let seq = 0;
|
|
26
|
-
export function newTaskId(prefix = 'task') {
|
|
27
|
-
seq = (seq + 1) % 1e9;
|
|
28
|
-
const rand = Math.random().toString(36).slice(2, 10).padEnd(8, '0');
|
|
29
|
-
const s = String(seq).padStart(4, '0');
|
|
30
|
-
return `${prefix}-${(Date.now().toString(36) + s).slice(-8)}-${rand}`;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
// Decode a task's buffered chunks for display. Buffer chunks (Bash) are UTF-8;
|
|
34
|
-
// string chunks (Agent/AgentSwarm) are already text.
|
|
35
|
-
//
|
|
36
|
-
// Tolerant of a RESTORED task: after a session round-trip the chunks may be
|
|
37
|
-
// strings, Buffers, `{type:'Buffer',data:[…]}` objects (what JSON.stringify does
|
|
38
|
-
// to a Buffer), or nothing at all. Anything unrecognisable is stringified rather
|
|
39
|
-
// than thrown on — a display helper must never be able to take the TUI down, and
|
|
40
|
-
// the output panel is exactly where a half-restored task shows up.
|
|
41
|
-
function decodeTaskOutput(chunks) {
|
|
42
|
-
if (chunks == null) return '';
|
|
43
|
-
const list = Array.isArray(chunks) ? chunks : [chunks];
|
|
44
|
-
if (!list.length) return '';
|
|
45
|
-
const normalize = (c) => {
|
|
46
|
-
if (Buffer.isBuffer(c)) return c;
|
|
47
|
-
if (c && c.type === 'Buffer' && Array.isArray(c.data)) return Buffer.from(c.data);
|
|
48
|
-
if (typeof c === 'string') return c;
|
|
49
|
-
return String(c);
|
|
50
|
-
};
|
|
51
|
-
const items = list.map(normalize);
|
|
52
|
-
try { return Buffer.concat(items.map((c) => (Buffer.isBuffer(c) ? c : Buffer.from(c)))).toString('utf8'); }
|
|
53
|
-
catch { return items.map((c) => String(c)).join(''); }
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
// The task store lives on the agent ctx (`ctx.tasks`), so every tool and the TUI
|
|
57
|
-
// see the same map.
|
|
58
|
-
function store(ctx) {
|
|
59
|
-
if (!ctx) return {};
|
|
60
|
-
if (!ctx.tasks) ctx.tasks = {};
|
|
61
|
-
return ctx.tasks;
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
/**
|
|
65
|
-
* Register a task. `kind` selects the payload group; the returned object is the
|
|
66
|
-
* live record (mutate `status`/`endedAt`/`stopReason` as it runs).
|
|
67
|
-
*
|
|
68
|
-
* options:
|
|
69
|
-
* description short human label
|
|
70
|
-
* detached true when it runs in the background (Ctrl+B or run_in_background)
|
|
71
|
-
* timeoutMs optional cap
|
|
72
|
-
* command/pid/exitCode (kind 'process')
|
|
73
|
-
* agentId/subagentType/model/thinkingEffort (kind 'agent')
|
|
74
|
-
* questionCount/toolCallId (kind 'question')
|
|
75
|
-
* output initial output text
|
|
76
|
-
*/
|
|
77
|
-
export function createTask(ctx, kind, options = {}) {
|
|
78
|
-
const tasks = store(ctx);
|
|
79
|
-
// A teammate is its own kind rather than falling through to 'question': the id prefix is
|
|
80
|
-
// what a reader of a task list uses to tell at a glance what kind of work it is.
|
|
81
|
-
const PREFIX = { process: 'bash', agent: 'agent', teammate: 'mate' };
|
|
82
|
-
const prefix = PREFIX[kind] || 'question';
|
|
83
|
-
const task = {
|
|
84
|
-
taskId: newTaskId(prefix),
|
|
85
|
-
kind,
|
|
86
|
-
description: String(options.description || ''),
|
|
87
|
-
status: 'running',
|
|
88
|
-
detached: options.detached !== false,
|
|
89
|
-
startedAt: Date.now(),
|
|
90
|
-
endedAt: null,
|
|
91
|
-
stopReason: undefined,
|
|
92
|
-
timeoutMs: options.timeoutMs,
|
|
93
|
-
// Output is buffered here and exposed through `output` below. Kept as chunks
|
|
94
|
-
// so the decoder can run lazily (a chatty task costs nothing until read).
|
|
95
|
-
_chunks: options._chunks || [],
|
|
96
|
-
_bytes: 0,
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
task.
|
|
105
|
-
task.
|
|
106
|
-
task.
|
|
107
|
-
} else if (kind === '
|
|
108
|
-
task.
|
|
109
|
-
task.
|
|
110
|
-
task.
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
task.
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
//
|
|
121
|
-
//
|
|
122
|
-
//
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
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
|
-
//
|
|
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
|
-
|
|
214
|
-
if (
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
task.
|
|
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
|
-
export
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
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
|
-
|
|
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
|
-
|
|
1
|
+
// Background task registry — the single place tasks are created, listed, stopped
|
|
2
|
+
// and read. Mirrors kimi-code's task model:
|
|
3
|
+
//
|
|
4
|
+
// TaskInfo = base fields + a `kind`-discriminated payload
|
|
5
|
+
// kind 'process' -> { command, pid, exitCode } (Bash run_in_background)
|
|
6
|
+
// kind 'agent' -> { agentId, subagentType, model, thinkingEffort } (Agent)
|
|
7
|
+
// kind 'question' -> { questionCount, toolCallId } (AskUserQuestion bg)
|
|
8
|
+
//
|
|
9
|
+
// Statuses match kimi exactly so the UI can share one vocabulary:
|
|
10
|
+
// running | completed | failed | timed_out | killed | lost
|
|
11
|
+
//
|
|
12
|
+
// Bash used to keep its own ad-hoc objects ('done'/'failed', `id`, `start`), which
|
|
13
|
+
// is why the task panel could not show the same fields as kimi's. Everything now
|
|
14
|
+
// goes through `createTask`, so a task always has the same shape no matter which
|
|
15
|
+
// tool spawned it.
|
|
16
|
+
|
|
17
|
+
export const TERMINAL_STATUSES = new Set(['completed', 'failed', 'timed_out', 'killed', 'lost']);
|
|
18
|
+
|
|
19
|
+
export function isTerminal(status) {
|
|
20
|
+
return TERMINAL_STATUSES.has(status);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// `{prefix}-{8 chars}` like kimi's VALID_TASK_ID. Unique even for two tasks
|
|
24
|
+
// created in the same millisecond (a bare Date.now() collided).
|
|
25
|
+
let seq = 0;
|
|
26
|
+
export function newTaskId(prefix = 'task') {
|
|
27
|
+
seq = (seq + 1) % 1e9;
|
|
28
|
+
const rand = Math.random().toString(36).slice(2, 10).padEnd(8, '0');
|
|
29
|
+
const s = String(seq).padStart(4, '0');
|
|
30
|
+
return `${prefix}-${(Date.now().toString(36) + s).slice(-8)}-${rand}`;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// Decode a task's buffered chunks for display. Buffer chunks (Bash) are UTF-8;
|
|
34
|
+
// string chunks (Agent/AgentSwarm) are already text.
|
|
35
|
+
//
|
|
36
|
+
// Tolerant of a RESTORED task: after a session round-trip the chunks may be
|
|
37
|
+
// strings, Buffers, `{type:'Buffer',data:[…]}` objects (what JSON.stringify does
|
|
38
|
+
// to a Buffer), or nothing at all. Anything unrecognisable is stringified rather
|
|
39
|
+
// than thrown on — a display helper must never be able to take the TUI down, and
|
|
40
|
+
// the output panel is exactly where a half-restored task shows up.
|
|
41
|
+
function decodeTaskOutput(chunks) {
|
|
42
|
+
if (chunks == null) return '';
|
|
43
|
+
const list = Array.isArray(chunks) ? chunks : [chunks];
|
|
44
|
+
if (!list.length) return '';
|
|
45
|
+
const normalize = (c) => {
|
|
46
|
+
if (Buffer.isBuffer(c)) return c;
|
|
47
|
+
if (c && c.type === 'Buffer' && Array.isArray(c.data)) return Buffer.from(c.data);
|
|
48
|
+
if (typeof c === 'string') return c;
|
|
49
|
+
return String(c);
|
|
50
|
+
};
|
|
51
|
+
const items = list.map(normalize);
|
|
52
|
+
try { return Buffer.concat(items.map((c) => (Buffer.isBuffer(c) ? c : Buffer.from(c)))).toString('utf8'); }
|
|
53
|
+
catch { return items.map((c) => String(c)).join(''); }
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// The task store lives on the agent ctx (`ctx.tasks`), so every tool and the TUI
|
|
57
|
+
// see the same map.
|
|
58
|
+
function store(ctx) {
|
|
59
|
+
if (!ctx) return {};
|
|
60
|
+
if (!ctx.tasks) ctx.tasks = {};
|
|
61
|
+
return ctx.tasks;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Register a task. `kind` selects the payload group; the returned object is the
|
|
66
|
+
* live record (mutate `status`/`endedAt`/`stopReason` as it runs).
|
|
67
|
+
*
|
|
68
|
+
* options:
|
|
69
|
+
* description short human label
|
|
70
|
+
* detached true when it runs in the background (Ctrl+B or run_in_background)
|
|
71
|
+
* timeoutMs optional cap
|
|
72
|
+
* command/pid/exitCode (kind 'process')
|
|
73
|
+
* agentId/subagentType/model/thinkingEffort (kind 'agent')
|
|
74
|
+
* questionCount/toolCallId (kind 'question')
|
|
75
|
+
* output initial output text
|
|
76
|
+
*/
|
|
77
|
+
export function createTask(ctx, kind, options = {}) {
|
|
78
|
+
const tasks = store(ctx);
|
|
79
|
+
// A teammate is its own kind rather than falling through to 'question': the id prefix is
|
|
80
|
+
// what a reader of a task list uses to tell at a glance what kind of work it is.
|
|
81
|
+
const PREFIX = { process: 'bash', agent: 'agent', teammate: 'mate' };
|
|
82
|
+
const prefix = PREFIX[kind] || 'question';
|
|
83
|
+
const task = {
|
|
84
|
+
taskId: newTaskId(prefix),
|
|
85
|
+
kind,
|
|
86
|
+
description: String(options.description || ''),
|
|
87
|
+
status: 'running',
|
|
88
|
+
detached: options.detached !== false,
|
|
89
|
+
startedAt: Date.now(),
|
|
90
|
+
endedAt: null,
|
|
91
|
+
stopReason: undefined,
|
|
92
|
+
timeoutMs: options.timeoutMs,
|
|
93
|
+
// Output is buffered here and exposed through `output` below. Kept as chunks
|
|
94
|
+
// so the decoder can run lazily (a chatty task costs nothing until read).
|
|
95
|
+
_chunks: options._chunks || [],
|
|
96
|
+
_bytes: 0,
|
|
97
|
+
// THE NOTIFICATION CALLBACK TRAVELS WITH THE TASK.
|
|
98
|
+
//
|
|
99
|
+
// `settleTask` is called from the tool that owns the process and has no ctx to look one up on, so the callback is
|
|
100
|
+
// captured here, where the ctx still is. Absent in a headless run, which is why every use of it is guarded.
|
|
101
|
+
_onDone: ctx && typeof ctx._onBackgroundTaskDone === 'function' ? ctx._onBackgroundTaskDone : null,
|
|
102
|
+
};
|
|
103
|
+
if (kind === 'process') {
|
|
104
|
+
task.command = String(options.command || '');
|
|
105
|
+
task.pid = options.pid || 0;
|
|
106
|
+
task.exitCode = null;
|
|
107
|
+
} else if (kind === 'agent') {
|
|
108
|
+
task.agentId = options.agentId;
|
|
109
|
+
task.subagentType = options.subagentType;
|
|
110
|
+
task.model = options.model;
|
|
111
|
+
task.thinkingEffort = options.thinkingEffort;
|
|
112
|
+
} else if (kind === 'teammate') {
|
|
113
|
+
task.teamName = options.teamName;
|
|
114
|
+
task.memberName = options.memberName;
|
|
115
|
+
task.agentId = options.agentId;
|
|
116
|
+
} else if (kind === 'question') {
|
|
117
|
+
task.questionCount = options.questionCount || 0;
|
|
118
|
+
task.toolCallId = options.toolCallId;
|
|
119
|
+
}
|
|
120
|
+
// WHICH TASK THIS ONE BELONGS TO. A swarm's subagents are tasks of their own so /tasks can show
|
|
121
|
+
// what each is doing, and this is what groups them under the swarm that launched them. Absent
|
|
122
|
+
// for a top-level task, which is the common case.
|
|
123
|
+
if (options.parentTaskId) task.parentTaskId = String(options.parentTaskId);
|
|
124
|
+
// Every task exposes its buffered output through `output`. The chunks are
|
|
125
|
+
// stored raw and decoded lazily:
|
|
126
|
+
// * a process appends Buffer chunks -> decode as UTF-8
|
|
127
|
+
// * an agent/swarm appends strings -> join
|
|
128
|
+
// Callers may override this getter when they need a different decoding.
|
|
129
|
+
defineOutputGetter(task);
|
|
130
|
+
tasks[task.taskId] = task;
|
|
131
|
+
return task;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// Install the lazy `output` getter. Extracted so a RESTORED task can have it
|
|
135
|
+
// reinstalled: JSON.stringify resolves the getter into a plain string property, so
|
|
136
|
+
// a reloaded record carries a frozen snapshot instead of a live view (see
|
|
137
|
+
// appendTaskOutput, which repairs both `_chunks` and the getter). `configurable`
|
|
138
|
+
// must stay true or the reinstall would throw on an already-defined property.
|
|
139
|
+
export function defineOutputGetter(task) {
|
|
140
|
+
Object.defineProperty(task, 'output', {
|
|
141
|
+
enumerable: true,
|
|
142
|
+
configurable: true,
|
|
143
|
+
get() { return decodeTaskOutput(this._chunks); },
|
|
144
|
+
});
|
|
145
|
+
return task;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// Cap retained output per task; a runaway command must not exhaust memory.
|
|
149
|
+
export const MAX_TASK_OUTPUT_BYTES = 2 * 1024 * 1024;
|
|
150
|
+
|
|
151
|
+
// Append raw bytes/chunks to a task, trimming the oldest past the cap.
|
|
152
|
+
//
|
|
153
|
+
// `_chunks` is repaired rather than assumed. The task store is reachable from
|
|
154
|
+
// three directions — created in-process, restored with a SESSION
|
|
155
|
+
// (`state.tasks`/`ctx.tasks` are copied verbatim into the session JSON and read
|
|
156
|
+
// back), and handed around between tools — so a record can arrive here without an
|
|
157
|
+
// array. A session round-trip also turns Buffers into `{type:'Buffer',data:[…]}`
|
|
158
|
+
// plain objects (JSON has no Buffer), and a record that never produced output can
|
|
159
|
+
// come back with no `_chunks` at all.
|
|
160
|
+
//
|
|
161
|
+
// This matters beyond tidiness: the only production callers are stdout/stderr
|
|
162
|
+
// 'data' listeners on a ChildProcess, and a throw inside an event listener is NOT
|
|
163
|
+
// caught by the surrounding tool. A missing array therefore surfaces as an
|
|
164
|
+
// unhandledRejection that kills the whole TUI mid-tool-call, with nothing printed
|
|
165
|
+
// (the exit handler wipes the alternate screen). Both observed shapes —
|
|
166
|
+
// "undefined.push" and "null.push" — come from exactly this line.
|
|
167
|
+
export function appendTaskOutput(task, chunk) {
|
|
168
|
+
if (!task || chunk == null) return;
|
|
169
|
+
if (!Array.isArray(task._chunks)) {
|
|
170
|
+
// Salvage whatever the old value held: a single chunk, an array-like, or a
|
|
171
|
+
// serialized Buffer object. A Buffer must be revived from its JSON form or the
|
|
172
|
+
// decoder would later try to concat a plain object.
|
|
173
|
+
const prev = task._chunks;
|
|
174
|
+
const revived = [];
|
|
175
|
+
if (prev != null) {
|
|
176
|
+
const items = Array.isArray(prev) ? prev : [prev];
|
|
177
|
+
for (const item of items) {
|
|
178
|
+
if (item && item.type === 'Buffer' && Array.isArray(item.data)) revived.push(Buffer.from(item.data));
|
|
179
|
+
else if (item != null) revived.push(item);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
task._chunks = revived;
|
|
183
|
+
// `_bytes` may be missing too on a restored record; recount from what we kept
|
|
184
|
+
// so the size cap works from here on instead of comparing against undefined.
|
|
185
|
+
task._bytes = revived.reduce((n, c) => n + (c.length || 0), 0);
|
|
186
|
+
}
|
|
187
|
+
// `JSON.stringify` does not preserve the `output` GETTER: it reads the getter and
|
|
188
|
+
// stores the resulting STRING as an ordinary own property. A restored task's
|
|
189
|
+
// `_chunks` is still an array, so the repair above does NOT run for it — but its
|
|
190
|
+
// `output` is a frozen snapshot that no longer tracks `_chunks`, and would keep
|
|
191
|
+
// reporting the pre-save text (or `undefined`) for the rest of the session.
|
|
192
|
+
// Reinstall the live getter whenever the property is a data value rather than an
|
|
193
|
+
// accessor. Checked on every append; after the first repair it is an accessor and
|
|
194
|
+
// this is a cheap no-op.
|
|
195
|
+
try {
|
|
196
|
+
const desc = Object.getOwnPropertyDescriptor(task, 'output');
|
|
197
|
+
if (!desc || !desc.get) {
|
|
198
|
+
if (desc) delete task.output;
|
|
199
|
+
defineOutputGetter(task);
|
|
200
|
+
}
|
|
201
|
+
} catch { /* a frozen record still appends correctly, only its display lags */ }
|
|
202
|
+
task._chunks.push(chunk);
|
|
203
|
+
task._bytes = (task._bytes || 0) + (chunk.length || 0);
|
|
204
|
+
while (task._bytes > MAX_TASK_OUTPUT_BYTES && task._chunks.length > 1) {
|
|
205
|
+
task._bytes -= task._chunks[0].length || 0;
|
|
206
|
+
task._chunks.shift();
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// Settle a task. `status` is one of the kimi statuses; a task that was already
|
|
211
|
+
// stopped keeps 'killed' (mirrors kimi: a deliberate stop must not be relabelled
|
|
212
|
+
// as a failure by the process's non-zero exit).
|
|
213
|
+
export function settleTask(task, status, extra = {}) {
|
|
214
|
+
if (!task) return;
|
|
215
|
+
// A task that already reached a TERMINAL state must not be relabelled: a
|
|
216
|
+
// deliberate stop ('killed') must not turn into 'failed' when the killed
|
|
217
|
+
// process reports a non-zero exit, and a 'completed' task must not be
|
|
218
|
+
// downgraded by a late error. Only a still-running task settles.
|
|
219
|
+
if (isTerminal(task.status)) {
|
|
220
|
+
if (extra.exitCode !== undefined && task.kind === 'process') task.exitCode = extra.exitCode;
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
task.status = status;
|
|
224
|
+
task.endedAt = Date.now();
|
|
225
|
+
if (extra.stopReason !== undefined) task.stopReason = extra.stopReason;
|
|
226
|
+
if (extra.exitCode !== undefined && task.kind === 'process') task.exitCode = extra.exitCode;
|
|
227
|
+
// NOTIFY — A TASK THAT FINISHES IN THE BACKGROUND MUST SAY SO.
|
|
228
|
+
//
|
|
229
|
+
// Only the subagent path called a callback (`ctx._onBackgroundTaskDone`); a Bash task settled through here and nothing
|
|
230
|
+
// was told. The row sat in /tasks and the transcript never changed, so a command the user backgrounded with Ctrl+B
|
|
231
|
+
// finished silently — they could not tell success from a crash, and the model was never handed the output.
|
|
232
|
+
//
|
|
233
|
+
// The callback lives on the ctx the tools were given, so it is installed by the TUI and absent in a headless run.
|
|
234
|
+
const cb = typeof task._onDone === 'function' ? task._onDone : null;
|
|
235
|
+
if (cb) {
|
|
236
|
+
// After the state is final, and guarded: a broken callback must not undo a settled task.
|
|
237
|
+
try { cb(task); } catch { /* a notification is not worth failing the settle for */ }
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
export function listTasks(ctx) {
|
|
242
|
+
return Object.values(store(ctx));
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
export function getTask(ctx, id) {
|
|
246
|
+
return store(ctx)[id] || null;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// Newest-first for display (mirrors kimi's compareTasks: running first, then by
|
|
250
|
+
// most recent activity).
|
|
251
|
+
export function sortedTasks(ctx) {
|
|
252
|
+
const tasks = listTasks(ctx);
|
|
253
|
+
return tasks.slice().sort((a, b) => {
|
|
254
|
+
const at = isTerminal(a.status), bt = isTerminal(b.status);
|
|
255
|
+
if (at !== bt) return at ? 1 : -1;
|
|
256
|
+
if (!at) return a.startedAt - b.startedAt;
|
|
257
|
+
return (b.endedAt || b.startedAt) - (a.endedAt || a.startedAt);
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// Human label for a status, matching kimi's STATUS_LABEL.
|
|
262
|
+
export const STATUS_LABEL = {
|
|
263
|
+
running: 'running',
|
|
264
|
+
completed: 'completed',
|
|
265
|
+
failed: 'failed',
|
|
266
|
+
timed_out: 'timed out',
|
|
267
|
+
killed: 'killed',
|
|
268
|
+
lost: 'lost',
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
// Colour token for a status (the TUI maps it to a theme colour).
|
|
272
|
+
export function statusColor(status) {
|
|
273
|
+
if (status === 'running') return 'green';
|
|
274
|
+
if (status === 'completed') return 'gray';
|
|
275
|
+
return 'red';
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// ---- background-task transcript card (mirrors kimi-code) --------------------
|
|
279
|
+
// A background task reports its lifecycle as a one-line card in the transcript:
|
|
280
|
+
//
|
|
281
|
+
// ● agent task completed in background (review the diff)
|
|
282
|
+
// ✗ bash task failed in background (npm test · exit 1)
|
|
283
|
+
//
|
|
284
|
+
// `phase` drives the bullet colour (started / completed / failed); `headline`
|
|
285
|
+
// and the dim `detail` carry the rest. Ported from kimi-code's
|
|
286
|
+
// formatBackgroundTaskTranscript (apps/kimi-code/src/tui/utils/background-task-status.ts)
|
|
287
|
+
// so the two tools read the same way.
|
|
288
|
+
|
|
289
|
+
const BG_DETAIL_MAX = 240;
|
|
290
|
+
|
|
291
|
+
function bgTruncate(value) {
|
|
292
|
+
if (value === undefined || value === null) return undefined;
|
|
293
|
+
const collapsed = String(value).trim().replace(/\s+/g, ' ');
|
|
294
|
+
if (!collapsed) return undefined;
|
|
295
|
+
return collapsed.length <= BG_DETAIL_MAX ? collapsed : collapsed.slice(0, BG_DETAIL_MAX - 1) + '…';
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
export function backgroundTaskPhase(status) {
|
|
299
|
+
if (status === 'running') return 'started';
|
|
300
|
+
if (status === 'completed') return 'completed';
|
|
301
|
+
return 'failed'; // failed / timed_out / killed / lost
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function bgSubject(kind) {
|
|
305
|
+
if (kind === 'agent') return 'agent task';
|
|
306
|
+
if (kind === 'question') return 'question task';
|
|
307
|
+
return 'bash task';
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
function bgHeadline(status, kind) {
|
|
311
|
+
const subject = bgSubject(kind);
|
|
312
|
+
switch (status) {
|
|
313
|
+
case 'running': return `${subject} started in background`;
|
|
314
|
+
case 'completed': return `${subject} completed in background`;
|
|
315
|
+
case 'failed': return `${subject} failed in background`;
|
|
316
|
+
case 'timed_out': return `${subject} timed out`;
|
|
317
|
+
case 'killed': return `${subject} stopped`;
|
|
318
|
+
case 'lost': return `${subject} lost`;
|
|
319
|
+
default: return `${subject} ${status}`;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function bgDetail(task) {
|
|
324
|
+
const parts = [];
|
|
325
|
+
const description = bgTruncate(task.description);
|
|
326
|
+
if (description !== undefined) parts.push(description);
|
|
327
|
+
|
|
328
|
+
if (task.status === 'completed' || task.status === 'failed') {
|
|
329
|
+
if (task.kind === 'process' && task.exitCode !== null && task.exitCode !== undefined) {
|
|
330
|
+
parts.push(`exit ${task.exitCode}`);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
if (task.status === 'killed') {
|
|
334
|
+
const reason = bgTruncate(task.stopReason);
|
|
335
|
+
parts.push(reason !== undefined ? `stopped — ${reason}` : 'stopped');
|
|
336
|
+
}
|
|
337
|
+
if (task.status === 'failed') {
|
|
338
|
+
const reason = bgTruncate(task.stopReason);
|
|
339
|
+
if (reason !== undefined) parts.push(reason);
|
|
340
|
+
}
|
|
341
|
+
if (task.status === 'timed_out') parts.push('timed out');
|
|
342
|
+
if (task.status === 'lost') parts.push('session restarted before completion');
|
|
343
|
+
|
|
344
|
+
return parts.length ? parts.join(' · ') : undefined;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// Build the card payload for a task snapshot.
|
|
348
|
+
export function backgroundTaskCard(task) {
|
|
349
|
+
return {
|
|
350
|
+
phase: backgroundTaskPhase(task.status),
|
|
351
|
+
headline: bgHeadline(task.status, task.kind),
|
|
352
|
+
detail: bgDetail(task),
|
|
353
|
+
};
|
|
354
|
+
}
|