pi-lean-bg 0.0.0-init → 0.1.0
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/LICENSE +21 -0
- package/README.md +37 -0
- package/index.ts +1 -0
- package/package.json +60 -1
- package/src/dock.ts +394 -0
- package/src/format.ts +75 -0
- package/src/index.ts +417 -0
- package/src/logs.ts +104 -0
- package/src/registry.ts +512 -0
- package/src/reload-hub.ts +82 -0
- package/src/schemas.ts +54 -0
- package/src/types.ts +54 -0
package/src/registry.ts
ADDED
|
@@ -0,0 +1,512 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { randomBytes } from 'node:crypto';
|
|
3
|
+
import {
|
|
4
|
+
boundedRead,
|
|
5
|
+
clampModelLogBytes,
|
|
6
|
+
closeAndFsyncStream,
|
|
7
|
+
ensureTaskDir,
|
|
8
|
+
openLogStream,
|
|
9
|
+
resolveMaxOutputBytes,
|
|
10
|
+
taskLogPaths,
|
|
11
|
+
type BoundedReadResult,
|
|
12
|
+
} from './logs.ts';
|
|
13
|
+
import {
|
|
14
|
+
claimReloadTasks,
|
|
15
|
+
clearReloadStash,
|
|
16
|
+
makeReloadKey,
|
|
17
|
+
stashReloadTasks,
|
|
18
|
+
} from './reload-hub.ts';
|
|
19
|
+
import {
|
|
20
|
+
DEFAULT_LOG_BYTES,
|
|
21
|
+
MAX_RECENT_TASKS,
|
|
22
|
+
type BgTaskRecord,
|
|
23
|
+
type BgTaskSnapshot,
|
|
24
|
+
type KillKind,
|
|
25
|
+
type StartTaskOptions,
|
|
26
|
+
} from './types.ts';
|
|
27
|
+
|
|
28
|
+
const KILL_GRACE_MS = 3_000;
|
|
29
|
+
const KILL_VERIFY_MS = 1_500;
|
|
30
|
+
const KILL_POLL_MS = 25;
|
|
31
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
32
|
+
|
|
33
|
+
export interface RegistryCallbacks {
|
|
34
|
+
onChange?: () => void;
|
|
35
|
+
onNotify?: (snapshot: BgTaskSnapshot) => void;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface RegistryOptions {
|
|
39
|
+
callbacks?: RegistryCallbacks;
|
|
40
|
+
maxOutputBytes?: number;
|
|
41
|
+
killGraceMs?: number;
|
|
42
|
+
killVerifyMs?: number;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function sleep(ms: number): Promise<void> {
|
|
46
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function isPosixGroupAlive(pgid: number): boolean {
|
|
50
|
+
try {
|
|
51
|
+
process.kill(-pgid, 0);
|
|
52
|
+
return true;
|
|
53
|
+
} catch (err) {
|
|
54
|
+
const code = (err as NodeJS.ErrnoException).code;
|
|
55
|
+
return code === 'EPERM';
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function signalPosixGroup(pgid: number, signal: NodeJS.Signals): boolean {
|
|
60
|
+
try {
|
|
61
|
+
process.kill(-pgid, signal);
|
|
62
|
+
return true;
|
|
63
|
+
} catch (err) {
|
|
64
|
+
const code = (err as NodeJS.ErrnoException).code;
|
|
65
|
+
if (code === 'ESRCH') return false;
|
|
66
|
+
throw err;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function snapshotTask(task: BgTaskRecord): BgTaskSnapshot {
|
|
71
|
+
return {
|
|
72
|
+
id: task.id,
|
|
73
|
+
name: task.name,
|
|
74
|
+
command: task.command,
|
|
75
|
+
cwd: task.cwd,
|
|
76
|
+
status: task.status,
|
|
77
|
+
pid: task.pid,
|
|
78
|
+
exitCode: task.exitCode,
|
|
79
|
+
signal: task.signal,
|
|
80
|
+
startTime: task.startTime,
|
|
81
|
+
endTime: task.endTime,
|
|
82
|
+
outputPath: task.outputPath,
|
|
83
|
+
outputAbsPath: task.outputAbsPath,
|
|
84
|
+
outputBytes: task.outputBytes,
|
|
85
|
+
outputTruncated: task.outputTruncated,
|
|
86
|
+
timeoutSeconds: task.timeoutSeconds,
|
|
87
|
+
surviveReload: task.surviveReload,
|
|
88
|
+
notify: task.notify,
|
|
89
|
+
killKind: task.killKind,
|
|
90
|
+
error: task.error,
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export class TaskRegistry {
|
|
95
|
+
private readonly tasks = new Map<string, BgTaskRecord>();
|
|
96
|
+
private readonly callbacks: RegistryCallbacks;
|
|
97
|
+
private readonly maxOutputBytes: number;
|
|
98
|
+
private readonly killGraceMs: number;
|
|
99
|
+
private readonly killVerifyMs: number;
|
|
100
|
+
private shuttingDown = false;
|
|
101
|
+
|
|
102
|
+
constructor(options: RegistryOptions = {}) {
|
|
103
|
+
this.callbacks = options.callbacks ?? {};
|
|
104
|
+
this.maxOutputBytes = options.maxOutputBytes ?? resolveMaxOutputBytes();
|
|
105
|
+
this.killGraceMs = options.killGraceMs ?? KILL_GRACE_MS;
|
|
106
|
+
this.killVerifyMs = options.killVerifyMs ?? KILL_VERIFY_MS;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
isShuttingDown(): boolean {
|
|
110
|
+
return this.shuttingDown;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
allTasks(): BgTaskSnapshot[] {
|
|
114
|
+
return Array.from(this.tasks.values()).map(snapshotTask);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
runningCount(): number {
|
|
118
|
+
let count = 0;
|
|
119
|
+
for (const t of this.tasks.values()) {
|
|
120
|
+
if (t.status === 'running') count++;
|
|
121
|
+
}
|
|
122
|
+
return count;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
resolveTask(idOrPrefix: string): BgTaskRecord {
|
|
126
|
+
const query = idOrPrefix.trim();
|
|
127
|
+
if (!query) throw new Error('Task ID is required.');
|
|
128
|
+
const exact = this.tasks.get(query);
|
|
129
|
+
if (exact) return exact;
|
|
130
|
+
|
|
131
|
+
const matches: BgTaskRecord[] = [];
|
|
132
|
+
for (const task of this.tasks.values()) {
|
|
133
|
+
if (task.id.startsWith(query)) matches.push(task);
|
|
134
|
+
}
|
|
135
|
+
if (matches.length === 1) return matches[0]!;
|
|
136
|
+
if (matches.length > 1) {
|
|
137
|
+
throw new Error(
|
|
138
|
+
`Ambiguous task ID prefix "${query}" (matches: ${matches.map((m) => m.id).join(', ')}).`,
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
if (UUID_RE.test(query)) {
|
|
142
|
+
throw new Error(
|
|
143
|
+
`Unknown background task ID "${query}". That looks like a pi-subagents run UUID — use subagent / bg_wait for subagent runs.`,
|
|
144
|
+
);
|
|
145
|
+
}
|
|
146
|
+
throw new Error(`Unknown background task ID "${query}".`);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
async startTask(
|
|
150
|
+
cwd: string,
|
|
151
|
+
sessionId: string,
|
|
152
|
+
command: string,
|
|
153
|
+
options: StartTaskOptions,
|
|
154
|
+
): Promise<BgTaskSnapshot> {
|
|
155
|
+
if (this.shuttingDown) {
|
|
156
|
+
throw new Error('Cannot start background task during session shutdown.');
|
|
157
|
+
}
|
|
158
|
+
const trimmedCmd = command.trim();
|
|
159
|
+
if (!trimmedCmd) throw new Error('Command must not be empty.');
|
|
160
|
+
|
|
161
|
+
const taskDir = await ensureTaskDir(cwd, sessionId);
|
|
162
|
+
const id = this.generateId();
|
|
163
|
+
const { outputAbsPath, outputPath } = taskLogPaths(cwd, taskDir, id);
|
|
164
|
+
const stream = openLogStream(outputAbsPath);
|
|
165
|
+
|
|
166
|
+
const task: BgTaskRecord = {
|
|
167
|
+
id,
|
|
168
|
+
name: options.name.trim() || trimmedCmd.slice(0, 40),
|
|
169
|
+
command: trimmedCmd,
|
|
170
|
+
cwd,
|
|
171
|
+
status: 'running',
|
|
172
|
+
exitCode: null,
|
|
173
|
+
startTime: Date.now(),
|
|
174
|
+
outputPath,
|
|
175
|
+
outputAbsPath,
|
|
176
|
+
outputBytes: 0,
|
|
177
|
+
outputTruncated: false,
|
|
178
|
+
timeoutSeconds: options.timeoutSeconds,
|
|
179
|
+
surviveReload: options.surviveReload ?? false,
|
|
180
|
+
notify: options.notify ?? 'wake',
|
|
181
|
+
stream,
|
|
182
|
+
finalized: false,
|
|
183
|
+
notified: false,
|
|
184
|
+
pendingNotification: false,
|
|
185
|
+
streamClosed: false,
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
this.bindTaskCallbacks(task);
|
|
189
|
+
this.tasks.set(id, task);
|
|
190
|
+
this.pruneRecent();
|
|
191
|
+
|
|
192
|
+
const child = spawn('/bin/bash', ['-c', trimmedCmd], {
|
|
193
|
+
cwd,
|
|
194
|
+
detached: process.platform !== 'win32',
|
|
195
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
196
|
+
env: process.env,
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
task.child = child;
|
|
200
|
+
if (typeof child.pid === 'number') {
|
|
201
|
+
task.pid = child.pid;
|
|
202
|
+
task.pgid = child.pid;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const onChunk = (chunk: Buffer) => this.appendOutput(task, chunk);
|
|
206
|
+
child.stdout?.on('data', onChunk);
|
|
207
|
+
child.stderr?.on('data', onChunk);
|
|
208
|
+
|
|
209
|
+
child.once('error', (err) => {
|
|
210
|
+
task.error = `Spawn failed: ${err.message}`;
|
|
211
|
+
void this.finalizeTask(task, null, null, true);
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
child.once('close', (code, signal) => {
|
|
215
|
+
void this.finalizeTask(task, code, signal, false);
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
if (task.timeoutSeconds !== undefined) {
|
|
219
|
+
task.timeoutTimer = setTimeout(() => {
|
|
220
|
+
if (task.finalized || task.status !== 'running') return;
|
|
221
|
+
this.writeNotice(task, `\n[bgtask] Timed out after ${task.timeoutSeconds}s; terminating.\n`);
|
|
222
|
+
void this.stopTaskRecord(
|
|
223
|
+
task,
|
|
224
|
+
'timeout',
|
|
225
|
+
`Timed out after ${task.timeoutSeconds}s`,
|
|
226
|
+
);
|
|
227
|
+
}, task.timeoutSeconds * 1000);
|
|
228
|
+
task.timeoutTimer.unref();
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
task.onChange?.();
|
|
232
|
+
return snapshotTask(task);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
async stopTask(idOrPrefix: string, kind: KillKind = 'user', reason?: string): Promise<BgTaskSnapshot> {
|
|
236
|
+
const task = this.resolveTask(idOrPrefix);
|
|
237
|
+
if (task.status !== 'running') {
|
|
238
|
+
throw new Error(`Task "${task.name}" (${task.id}) is already ${task.status}, not running.`);
|
|
239
|
+
}
|
|
240
|
+
await this.stopTaskRecord(task, kind, reason);
|
|
241
|
+
return snapshotTask(task);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
async stopAllRunning(kind: KillKind = 'user', reason?: string): Promise<number> {
|
|
245
|
+
const running = Array.from(this.tasks.values()).filter((t) => t.status === 'running');
|
|
246
|
+
await Promise.allSettled(running.map((t) => this.stopTaskRecord(t, kind, reason)));
|
|
247
|
+
return running.length;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
readLogs(
|
|
251
|
+
idOrPrefix: string,
|
|
252
|
+
options: { maxBytes?: number; tail?: boolean; clampModelCap?: boolean } = {},
|
|
253
|
+
): { task: BgTaskSnapshot; logs: BoundedReadResult } {
|
|
254
|
+
const task = this.resolveTask(idOrPrefix);
|
|
255
|
+
const maxBytes =
|
|
256
|
+
options.clampModelCap === false
|
|
257
|
+
? (options.maxBytes ?? DEFAULT_LOG_BYTES)
|
|
258
|
+
: clampModelLogBytes(options.maxBytes, DEFAULT_LOG_BYTES);
|
|
259
|
+
const logs = boundedRead(task.outputAbsPath, maxBytes, options.tail ?? true);
|
|
260
|
+
return { task: snapshotTask(task), logs };
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
adoptReloadTasks(sessionId: string, cwd: string): { adopted: number; seenIds: Set<string> } {
|
|
264
|
+
const key = makeReloadKey(sessionId, cwd);
|
|
265
|
+
const claimed = claimReloadTasks(key);
|
|
266
|
+
if (!claimed) return { adopted: 0, seenIds: new Set() };
|
|
267
|
+
|
|
268
|
+
const pendingToFlush: BgTaskRecord[] = [];
|
|
269
|
+
for (const task of claimed.tasks) {
|
|
270
|
+
this.bindTaskCallbacks(task);
|
|
271
|
+
this.tasks.set(task.id, task);
|
|
272
|
+
if (task.pendingNotification && !task.notified && task.status !== 'running') {
|
|
273
|
+
pendingToFlush.push(task);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
this.pruneRecent();
|
|
277
|
+
|
|
278
|
+
for (const task of pendingToFlush) {
|
|
279
|
+
task.pendingNotification = false;
|
|
280
|
+
this.emitNotification(task);
|
|
281
|
+
}
|
|
282
|
+
this.callbacks.onChange?.();
|
|
283
|
+
return { adopted: claimed.tasks.length, seenIds: claimed.seenIds };
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
async shutdown(reason: string, sessionId: string, cwd: string, seenIds: Set<string>): Promise<void> {
|
|
287
|
+
if (this.shuttingDown) return;
|
|
288
|
+
this.shuttingDown = true;
|
|
289
|
+
|
|
290
|
+
const key = makeReloadKey(sessionId, cwd);
|
|
291
|
+
const isReload = reason === 'reload';
|
|
292
|
+
|
|
293
|
+
const toKill: BgTaskRecord[] = [];
|
|
294
|
+
const toStash: BgTaskRecord[] = [];
|
|
295
|
+
|
|
296
|
+
for (const task of this.tasks.values()) {
|
|
297
|
+
if (isReload && task.surviveReload) {
|
|
298
|
+
toStash.push(task);
|
|
299
|
+
} else if (task.status === 'running') {
|
|
300
|
+
toKill.push(task);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
if (isReload && toStash.length > 0) {
|
|
305
|
+
stashReloadTasks(key, toStash, seenIds, (orphans) => {
|
|
306
|
+
for (const orphan of orphans) {
|
|
307
|
+
if (orphan.status === 'running') {
|
|
308
|
+
void this.stopTaskRecord(orphan, 'shutdown', 'Reload handoff expired');
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
});
|
|
312
|
+
} else if (!isReload) {
|
|
313
|
+
const stale = clearReloadStash(key);
|
|
314
|
+
for (const task of stale) {
|
|
315
|
+
if (task.status === 'running') toKill.push(task);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
if (toKill.length > 0) {
|
|
320
|
+
await Promise.allSettled(
|
|
321
|
+
toKill.map((task) =>
|
|
322
|
+
this.stopTaskRecord(task, 'shutdown', `Killed during Pi session shutdown (${reason})`),
|
|
323
|
+
),
|
|
324
|
+
);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
private bindTaskCallbacks(task: BgTaskRecord): void {
|
|
329
|
+
task.onChange = () => this.callbacks.onChange?.();
|
|
330
|
+
task.onNotify = (t) => this.callbacks.onNotify?.(snapshotTask(t));
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
private generateId(): string {
|
|
334
|
+
for (let i = 0; i < 8; i++) {
|
|
335
|
+
const id = randomBytes(4).toString('hex');
|
|
336
|
+
if (!this.tasks.has(id)) return id;
|
|
337
|
+
}
|
|
338
|
+
return randomBytes(6).toString('hex');
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
private appendOutput(task: BgTaskRecord, chunk: Buffer): void {
|
|
342
|
+
if (task.finalized || task.streamClosed || !task.stream) return;
|
|
343
|
+
const remaining = this.maxOutputBytes - task.outputBytes;
|
|
344
|
+
if (remaining <= 0) return;
|
|
345
|
+
|
|
346
|
+
if (chunk.length <= remaining) {
|
|
347
|
+
task.outputBytes += chunk.length;
|
|
348
|
+
task.stream.write(chunk);
|
|
349
|
+
return;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
// Overflow: write up to the cap, mark truncated, and kill task.
|
|
353
|
+
const head = chunk.subarray(0, remaining);
|
|
354
|
+
task.outputBytes += head.length;
|
|
355
|
+
task.outputTruncated = true;
|
|
356
|
+
task.stream.write(head);
|
|
357
|
+
this.writeNotice(
|
|
358
|
+
task,
|
|
359
|
+
`\n[bgtask] Output exceeded ${this.maxOutputBytes} byte cap; terminating.\n`,
|
|
360
|
+
);
|
|
361
|
+
void this.stopTaskRecord(
|
|
362
|
+
task,
|
|
363
|
+
'output_cap',
|
|
364
|
+
`Output exceeded ${this.maxOutputBytes} byte cap`,
|
|
365
|
+
);
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
private writeNotice(task: BgTaskRecord, text: string): void {
|
|
369
|
+
if (!task.stream || task.streamClosed || task.stream.closed || task.stream.destroyed) return;
|
|
370
|
+
try {
|
|
371
|
+
task.stream.write(text);
|
|
372
|
+
} catch {
|
|
373
|
+
// Ignore stream write errors during teardown.
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
private async stopTaskRecord(task: BgTaskRecord, kind: KillKind, reason?: string): Promise<void> {
|
|
378
|
+
if (task.killPromise) return task.killPromise;
|
|
379
|
+
|
|
380
|
+
task.killKind = kind;
|
|
381
|
+
if (reason && !task.error) task.error = reason;
|
|
382
|
+
|
|
383
|
+
const run = async () => {
|
|
384
|
+
const pgid = task.pgid;
|
|
385
|
+
if (process.platform !== 'win32' && pgid !== undefined) {
|
|
386
|
+
if (signalPosixGroup(pgid, 'SIGTERM')) {
|
|
387
|
+
const deadline = Date.now() + this.killGraceMs;
|
|
388
|
+
while (Date.now() < deadline && !task.finalized && isPosixGroupAlive(pgid)) {
|
|
389
|
+
await sleep(KILL_POLL_MS);
|
|
390
|
+
}
|
|
391
|
+
if (isPosixGroupAlive(pgid)) {
|
|
392
|
+
signalPosixGroup(pgid, 'SIGKILL');
|
|
393
|
+
const verifyDeadline = Date.now() + this.killVerifyMs;
|
|
394
|
+
while (Date.now() < verifyDeadline && isPosixGroupAlive(pgid)) {
|
|
395
|
+
await sleep(KILL_POLL_MS);
|
|
396
|
+
}
|
|
397
|
+
if (isPosixGroupAlive(pgid)) {
|
|
398
|
+
task.error = `Process group -${pgid} did not exit after SIGKILL (descendants may have leaked)`;
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
} else if (task.child && !task.child.killed) {
|
|
403
|
+
task.child.kill('SIGTERM');
|
|
404
|
+
const deadline = Date.now() + this.killGraceMs;
|
|
405
|
+
while (Date.now() < deadline && !task.finalized) {
|
|
406
|
+
await sleep(KILL_POLL_MS);
|
|
407
|
+
}
|
|
408
|
+
if (!task.finalized) task.child.kill('SIGKILL');
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
// Wait briefly for child 'close' to finalize, or force-finalize if needed.
|
|
412
|
+
const closeDeadline = Date.now() + 500;
|
|
413
|
+
while (!task.finalized && Date.now() < closeDeadline) {
|
|
414
|
+
await sleep(KILL_POLL_MS);
|
|
415
|
+
}
|
|
416
|
+
if (!task.finalized) {
|
|
417
|
+
await this.finalizeTask(task, null, 'SIGKILL', false);
|
|
418
|
+
}
|
|
419
|
+
};
|
|
420
|
+
|
|
421
|
+
task.killPromise = run();
|
|
422
|
+
try {
|
|
423
|
+
await task.killPromise;
|
|
424
|
+
} finally {
|
|
425
|
+
task.killPromise = undefined;
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
private async finalizeTask(
|
|
430
|
+
task: BgTaskRecord,
|
|
431
|
+
exitCode: number | null,
|
|
432
|
+
signal: NodeJS.Signals | null,
|
|
433
|
+
spawnFailed: boolean,
|
|
434
|
+
): Promise<void> {
|
|
435
|
+
if (task.finalized) return;
|
|
436
|
+
task.finalized = true;
|
|
437
|
+
|
|
438
|
+
if (task.timeoutTimer) {
|
|
439
|
+
clearTimeout(task.timeoutTimer);
|
|
440
|
+
task.timeoutTimer = undefined;
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
task.exitCode = exitCode;
|
|
444
|
+
task.signal = signal;
|
|
445
|
+
task.endTime = Date.now();
|
|
446
|
+
|
|
447
|
+
// Ensure no stray descendants remain if the lead shell exited while a kill was requested.
|
|
448
|
+
if (
|
|
449
|
+
process.platform !== 'win32' &&
|
|
450
|
+
task.pgid !== undefined &&
|
|
451
|
+
task.killKind !== undefined &&
|
|
452
|
+
isPosixGroupAlive(task.pgid)
|
|
453
|
+
) {
|
|
454
|
+
signalPosixGroup(task.pgid, 'SIGKILL');
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
task.streamClosed = true;
|
|
458
|
+
await closeAndFsyncStream(task.stream, task.outputAbsPath);
|
|
459
|
+
task.stream = undefined;
|
|
460
|
+
task.child = undefined;
|
|
461
|
+
|
|
462
|
+
if (spawnFailed) {
|
|
463
|
+
task.status = 'failed';
|
|
464
|
+
} else if (task.killKind === 'timeout' || task.killKind === 'output_cap') {
|
|
465
|
+
task.status = 'failed';
|
|
466
|
+
} else if (task.killKind === 'user' || task.killKind === 'shutdown') {
|
|
467
|
+
task.status = task.error?.includes('did not exit after SIGKILL') ? 'failed' : 'killed';
|
|
468
|
+
} else if (exitCode === 0) {
|
|
469
|
+
task.status = 'completed';
|
|
470
|
+
} else {
|
|
471
|
+
task.status = 'failed';
|
|
472
|
+
if (!task.error) {
|
|
473
|
+
task.error =
|
|
474
|
+
signal !== null
|
|
475
|
+
? `Exited with signal ${signal}`
|
|
476
|
+
: `Exited with code ${String(exitCode)}`;
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
task.onChange?.();
|
|
481
|
+
this.emitNotification(task);
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
private emitNotification(task: BgTaskRecord): void {
|
|
485
|
+
if (task.notified) return;
|
|
486
|
+
if (task.notify === 'none') return;
|
|
487
|
+
if (task.killKind === 'shutdown') return;
|
|
488
|
+
|
|
489
|
+
if (!task.onNotify) {
|
|
490
|
+
// Task finished while detached mid-reload; buffer for the new activation.
|
|
491
|
+
task.pendingNotification = true;
|
|
492
|
+
return;
|
|
493
|
+
}
|
|
494
|
+
task.notified = true;
|
|
495
|
+
try {
|
|
496
|
+
task.onNotify(task);
|
|
497
|
+
} catch {
|
|
498
|
+
task.notified = false;
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
private pruneRecent(): void {
|
|
503
|
+
if (this.tasks.size <= MAX_RECENT_TASKS) return;
|
|
504
|
+
const finished = Array.from(this.tasks.values())
|
|
505
|
+
.filter((t) => t.status !== 'running')
|
|
506
|
+
.sort((a, b) => (a.endTime ?? a.startTime) - (b.endTime ?? b.startTime));
|
|
507
|
+
for (const t of finished) {
|
|
508
|
+
if (this.tasks.size <= MAX_RECENT_TASKS) break;
|
|
509
|
+
this.tasks.delete(t.id);
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { realpathSync } from 'node:fs';
|
|
2
|
+
import type { BgTaskRecord } from './types.ts';
|
|
3
|
+
|
|
4
|
+
const HUB_SYMBOL = Symbol.for('pi-bgtask.reload-hub.v1');
|
|
5
|
+
const DEFAULT_HANDOFF_TIMEOUT_MS = 30_000;
|
|
6
|
+
|
|
7
|
+
interface StashedEntry {
|
|
8
|
+
tasks: BgTaskRecord[];
|
|
9
|
+
seenIds: Set<string>;
|
|
10
|
+
orphanTimer: NodeJS.Timeout;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
type HubMap = Map<string, StashedEntry>;
|
|
14
|
+
|
|
15
|
+
function getHub(): HubMap {
|
|
16
|
+
const g = globalThis as Record<symbol, unknown>;
|
|
17
|
+
let hub = g[HUB_SYMBOL] as HubMap | undefined;
|
|
18
|
+
if (!hub) {
|
|
19
|
+
hub = new Map<string, StashedEntry>();
|
|
20
|
+
g[HUB_SYMBOL] = hub;
|
|
21
|
+
}
|
|
22
|
+
return hub;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function makeReloadKey(sessionId: string, cwd: string): string {
|
|
26
|
+
let realCwd = cwd;
|
|
27
|
+
try {
|
|
28
|
+
realCwd = realpathSync(cwd);
|
|
29
|
+
} catch {
|
|
30
|
+
// Fall back to raw cwd if path cannot be resolved.
|
|
31
|
+
}
|
|
32
|
+
return `${sessionId}\0${realCwd}`;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function stashReloadTasks(
|
|
36
|
+
key: string,
|
|
37
|
+
tasks: BgTaskRecord[],
|
|
38
|
+
seenIds: Set<string>,
|
|
39
|
+
onOrphanExpire: (tasks: BgTaskRecord[]) => void,
|
|
40
|
+
timeoutMs = DEFAULT_HANDOFF_TIMEOUT_MS,
|
|
41
|
+
): void {
|
|
42
|
+
if (tasks.length === 0) return;
|
|
43
|
+
const hub = getHub();
|
|
44
|
+
const existing = hub.get(key);
|
|
45
|
+
if (existing) {
|
|
46
|
+
clearTimeout(existing.orphanTimer);
|
|
47
|
+
hub.delete(key);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
for (const task of tasks) {
|
|
51
|
+
task.onChange = undefined;
|
|
52
|
+
task.onNotify = undefined;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const orphanTimer = setTimeout(() => {
|
|
56
|
+
const current = hub.get(key);
|
|
57
|
+
if (!current) return;
|
|
58
|
+
hub.delete(key);
|
|
59
|
+
onOrphanExpire(current.tasks);
|
|
60
|
+
}, timeoutMs);
|
|
61
|
+
orphanTimer.unref();
|
|
62
|
+
|
|
63
|
+
hub.set(key, { tasks, seenIds: new Set(seenIds), orphanTimer });
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function claimReloadTasks(key: string): { tasks: BgTaskRecord[]; seenIds: Set<string> } | undefined {
|
|
67
|
+
const hub = getHub();
|
|
68
|
+
const entry = hub.get(key);
|
|
69
|
+
if (!entry) return undefined;
|
|
70
|
+
clearTimeout(entry.orphanTimer);
|
|
71
|
+
hub.delete(key);
|
|
72
|
+
return { tasks: entry.tasks, seenIds: entry.seenIds };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function clearReloadStash(key: string): BgTaskRecord[] {
|
|
76
|
+
const hub = getHub();
|
|
77
|
+
const entry = hub.get(key);
|
|
78
|
+
if (!entry) return [];
|
|
79
|
+
clearTimeout(entry.orphanTimer);
|
|
80
|
+
hub.delete(key);
|
|
81
|
+
return entry.tasks;
|
|
82
|
+
}
|
package/src/schemas.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { Type, type Static } from 'typebox';
|
|
2
|
+
import { MAX_LOG_BYTES } from './types.ts';
|
|
3
|
+
|
|
4
|
+
export const BgRunParams = Type.Object(
|
|
5
|
+
{
|
|
6
|
+
name: Type.String({ description: '2-6 word label for the task dock.' }),
|
|
7
|
+
command: Type.String({ description: 'Bash command run via /bin/bash -c.' }),
|
|
8
|
+
timeoutSeconds: Type.Optional(
|
|
9
|
+
Type.Number({ minimum: 1, description: 'Kill and mark failed after N seconds.' }),
|
|
10
|
+
),
|
|
11
|
+
surviveReload: Type.Optional(
|
|
12
|
+
Type.Boolean({ description: 'Keep running across Pi /reload (default false).' }),
|
|
13
|
+
),
|
|
14
|
+
notify: Type.Optional(
|
|
15
|
+
Type.Union([Type.Literal('wake'), Type.Literal('silent'), Type.Literal('none')], {
|
|
16
|
+
description: 'Completion mode: wake (default), silent (notify only), or none.',
|
|
17
|
+
}),
|
|
18
|
+
),
|
|
19
|
+
},
|
|
20
|
+
{ additionalProperties: false },
|
|
21
|
+
);
|
|
22
|
+
export type BgRunParamsValue = Static<typeof BgRunParams>;
|
|
23
|
+
|
|
24
|
+
export const BgStatusParams = Type.Object(
|
|
25
|
+
{
|
|
26
|
+
taskId: Type.Optional(Type.String({ description: 'Task ID or prefix; omit to list all.' })),
|
|
27
|
+
},
|
|
28
|
+
{ additionalProperties: false },
|
|
29
|
+
);
|
|
30
|
+
export type BgStatusParamsValue = Static<typeof BgStatusParams>;
|
|
31
|
+
|
|
32
|
+
export const BgLogsParams = Type.Object(
|
|
33
|
+
{
|
|
34
|
+
taskId: Type.String({ description: 'Task ID or prefix.' }),
|
|
35
|
+
tail: Type.Optional(Type.Boolean({ description: 'Read tail (default true) or head (false).' })),
|
|
36
|
+
maxBytes: Type.Optional(
|
|
37
|
+
Type.Number({
|
|
38
|
+
minimum: 1,
|
|
39
|
+
maximum: MAX_LOG_BYTES,
|
|
40
|
+
description: 'Max bytes (default 16 KiB, max 50 KiB).',
|
|
41
|
+
}),
|
|
42
|
+
),
|
|
43
|
+
},
|
|
44
|
+
{ additionalProperties: false },
|
|
45
|
+
);
|
|
46
|
+
export type BgLogsParamsValue = Static<typeof BgLogsParams>;
|
|
47
|
+
|
|
48
|
+
export const BgKillParams = Type.Object(
|
|
49
|
+
{
|
|
50
|
+
taskId: Type.String({ description: 'Task ID or prefix to stop.' }),
|
|
51
|
+
},
|
|
52
|
+
{ additionalProperties: false },
|
|
53
|
+
);
|
|
54
|
+
export type BgKillParamsValue = Static<typeof BgKillParams>;
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { ChildProcess } from 'node:child_process';
|
|
2
|
+
import type { WriteStream } from 'node:fs';
|
|
3
|
+
|
|
4
|
+
export type TaskStatus = 'running' | 'completed' | 'failed' | 'killed';
|
|
5
|
+
export type KillKind = 'user' | 'shutdown' | 'timeout' | 'output_cap';
|
|
6
|
+
export type NotifyMode = 'wake' | 'silent' | 'none';
|
|
7
|
+
|
|
8
|
+
export const DEFAULT_MAX_OUTPUT_BYTES = 20 * 1024 * 1024; // 20 MiB
|
|
9
|
+
export const DEFAULT_LOG_BYTES = 16 * 1024; // 16 KiB
|
|
10
|
+
export const MAX_LOG_BYTES = 50 * 1024; // 50 KiB
|
|
11
|
+
export const MAX_RECENT_TASKS = 100;
|
|
12
|
+
|
|
13
|
+
export interface BgTaskSnapshot {
|
|
14
|
+
id: string;
|
|
15
|
+
name: string;
|
|
16
|
+
command: string;
|
|
17
|
+
cwd: string;
|
|
18
|
+
status: TaskStatus;
|
|
19
|
+
pid?: number;
|
|
20
|
+
exitCode: number | null;
|
|
21
|
+
signal?: NodeJS.Signals | null;
|
|
22
|
+
startTime: number;
|
|
23
|
+
endTime?: number;
|
|
24
|
+
outputPath: string;
|
|
25
|
+
outputAbsPath: string;
|
|
26
|
+
outputBytes: number;
|
|
27
|
+
outputTruncated: boolean;
|
|
28
|
+
timeoutSeconds?: number;
|
|
29
|
+
surviveReload: boolean;
|
|
30
|
+
notify: NotifyMode;
|
|
31
|
+
killKind?: KillKind;
|
|
32
|
+
error?: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface BgTaskRecord extends BgTaskSnapshot {
|
|
36
|
+
child?: ChildProcess;
|
|
37
|
+
pgid?: number;
|
|
38
|
+
stream?: WriteStream;
|
|
39
|
+
timeoutTimer?: NodeJS.Timeout;
|
|
40
|
+
killPromise?: Promise<void>;
|
|
41
|
+
finalized: boolean;
|
|
42
|
+
notified: boolean;
|
|
43
|
+
pendingNotification: boolean;
|
|
44
|
+
streamClosed: boolean;
|
|
45
|
+
onChange?: () => void;
|
|
46
|
+
onNotify?: (task: BgTaskRecord) => void;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface StartTaskOptions {
|
|
50
|
+
name: string;
|
|
51
|
+
timeoutSeconds?: number;
|
|
52
|
+
surviveReload?: boolean;
|
|
53
|
+
notify?: NotifyMode;
|
|
54
|
+
}
|