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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 kslamph
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,37 @@
1
+ # pi-lean-bg
2
+
3
+ A lean background shell task runner for [Pi](https://pi.dev) with automatic completion wake-ups, a `Shift+Down` live log dock, and `/reload` survival.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pi install npm:pi-lean-bg
9
+ ```
10
+
11
+ Or add `"npm:pi-lean-bg"` to `packages` in `~/.pi/agent/settings.json`.
12
+
13
+ ## Tools
14
+
15
+ | Tool | Parameters | Behavior |
16
+ |---|---|---|
17
+ | `bg_run` | `name`, `command`, `timeoutSeconds?`, `surviveReload?`, `notify?` | Spawns `/bin/bash -c <command>` in a detached POSIX process group, streams output to `.pi/tasks/`, and returns immediately. `notify`: `"wake"` (default, delivers `<background-task-notification>` and triggers a follow-up turn), `"silent"` (delivers notification without triggering a turn), or `"none"`. |
18
+ | `bg_status` | `taskId?` | Inspects one task by ID/prefix or lists all tasks in the session. |
19
+ | `bg_logs` | `taskId`, `tail?`, `maxBytes?` | Reads a bounded tail (default) or head slice of the task log file (default 16 KiB, max 50 KiB). |
20
+ | `bg_kill` | `taskId` | Stops a running task and its entire process group (`SIGTERM` → 3s grace → `SIGKILL`). |
21
+
22
+ ## Commands & Shortcuts
23
+
24
+ - **`Shift+Down`** — opens the bottom-center task dock overlay (list view + live-tailing log view, `Enter` inspect, `↑`/`↓`/`PgUp`/`PgDn` scroll, `G` resume live tail, `x` stop, `r` rerun, `c` clear finished notices, `Esc`/`q` close).
25
+ - **`/bg [--survive-reload] [--name "Label"] <command>`** — launches a background shell task with `notify: "silent"`.
26
+ - **`/jobs`** — opens the task dock (or prints the task list in non-interactive mode).
27
+
28
+ ## Runtime Behavior
29
+
30
+ - **Logs**: written to `.pi/tasks/<session>-<pid>/<id>.log` with a 20 MiB cap (override via `PI_BG_MAX_OUTPUT_BYTES`) and `fsync` on completion.
31
+ - **Reload survival**: tasks started with `surviveReload: true` (or `/bg --survive-reload`) stay running across Pi `/reload`, reattach to the new extension instance, and flush any notifications that completed during the reload window.
32
+ - **Clean shutdown**: real session exits terminate all running task process groups.
33
+ - **Footer status**: shows running/finished task counts and `Shift↓` in the status line; refreshes every second while tasks are active and clears when idle.
34
+
35
+ ## License
36
+
37
+ MIT
package/index.ts ADDED
@@ -0,0 +1 @@
1
+ export { default } from './src/index.ts';
package/package.json CHANGED
@@ -1 +1,60 @@
1
- {"name":"pi-lean-bg","version":"0.0.0-init","description":"Lean background shell task runner for Pi","license":"MIT","repository":{"type":"git","url":"git+https://github.com/kslamph/pi-lean-bg.git"}}
1
+ {
2
+ "name": "pi-lean-bg",
3
+ "version": "0.1.0",
4
+ "description": "Lean background shell task runner for Pi with Shift+Down dock and reload survival",
5
+ "author": "kslamph",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/kslamph/pi-lean-bg.git"
9
+ },
10
+ "homepage": "https://github.com/kslamph/pi-lean-bg#readme",
11
+ "bugs": {
12
+ "url": "https://github.com/kslamph/pi-lean-bg/issues"
13
+ },
14
+ "keywords": [
15
+ "pi-package",
16
+ "pi",
17
+ "pi-extension",
18
+ "pi-coding-agent",
19
+ "background-tasks",
20
+ "shell",
21
+ "process",
22
+ "coding-agent"
23
+ ],
24
+ "license": "MIT",
25
+ "type": "module",
26
+ "main": "index.ts",
27
+ "engines": {
28
+ "node": ">=22.19"
29
+ },
30
+ "files": [
31
+ "index.ts",
32
+ "src/",
33
+ "README.md",
34
+ "LICENSE"
35
+ ],
36
+ "peerDependencies": {
37
+ "@earendil-works/pi-coding-agent": "*",
38
+ "@earendil-works/pi-tui": "*",
39
+ "typebox": "*"
40
+ },
41
+ "devDependencies": {
42
+ "@earendil-works/pi-coding-agent": "1.7.0",
43
+ "@earendil-works/pi-tui": "1.7.0",
44
+ "@types/node": "^22.20.2",
45
+ "typebox": "^1.0.0",
46
+ "typescript": "5.9.3"
47
+ },
48
+ "scripts": {
49
+ "test": "node --test tests/*.test.ts",
50
+ "typecheck": "tsc --noEmit"
51
+ },
52
+ "pi": {
53
+ "extensions": [
54
+ "./index.ts"
55
+ ]
56
+ },
57
+ "publishConfig": {
58
+ "access": "public"
59
+ }
60
+ }
package/src/dock.ts ADDED
@@ -0,0 +1,394 @@
1
+ import type { Theme } from '@earendil-works/pi-coding-agent';
2
+ import {
3
+ matchesKey,
4
+ truncateToWidth,
5
+ visibleWidth,
6
+ type Component,
7
+ type TUI,
8
+ } from '@earendil-works/pi-tui';
9
+ import { compactCommand, formatBytes, taskDuration } from './format.ts';
10
+ import { boundedRead } from './logs.ts';
11
+ import type { BgTaskSnapshot } from './types.ts';
12
+
13
+ const DETAIL_TAIL_BYTES = 128 * 1024;
14
+ const LIST_ROWS = 12;
15
+ const DETAIL_ROWS = 14;
16
+ const REFRESH_MS = 1000;
17
+ const BLUE_BORDER = '\x1b[38;2;83;160;215m';
18
+ const RESET = '\x1b[0m';
19
+
20
+ export interface DockOptions {
21
+ getTasks: () => BgTaskSnapshot[];
22
+ stopTask: (id: string) => Promise<void>;
23
+ rerunTask: (task: BgTaskSnapshot) => Promise<BgTaskSnapshot>;
24
+ isSeen: (id: string) => boolean;
25
+ markSeen: (id: string) => void;
26
+ markAllFinishedSeen: () => void;
27
+ }
28
+
29
+ function padRight(text: string, width: number): string {
30
+ return text + ' '.repeat(Math.max(0, width - visibleWidth(text)));
31
+ }
32
+
33
+ function border(text: string): string {
34
+ return `${BLUE_BORDER}${text}${RESET}`;
35
+ }
36
+
37
+ function statusBadge(theme: Theme, status: BgTaskSnapshot['status']): string {
38
+ switch (status) {
39
+ case 'completed':
40
+ return theme.fg('success', 'done ');
41
+ case 'failed':
42
+ return theme.fg('error', 'error ');
43
+ case 'killed':
44
+ return theme.fg('warning', 'stopped');
45
+ case 'running':
46
+ return theme.fg('accent', 'running');
47
+ }
48
+ }
49
+
50
+ function sortTasks(tasks: BgTaskSnapshot[]): BgTaskSnapshot[] {
51
+ return [...tasks].sort((a, b) => {
52
+ const aRun = a.status === 'running' ? 0 : 1;
53
+ const bRun = b.status === 'running' ? 0 : 1;
54
+ if (aRun !== bRun) return aRun - bRun;
55
+ return b.startTime - a.startTime;
56
+ });
57
+ }
58
+
59
+ function splitOutputLines(text: string): string[] {
60
+ const raw = text.replace(/\r/g, '').split('\n');
61
+ if (raw.length > 0 && raw[raw.length - 1] === '') raw.pop();
62
+ return raw;
63
+ }
64
+
65
+ export class BgTaskDock implements Component {
66
+ private readonly tui: TUI;
67
+ private readonly theme: Theme;
68
+ private readonly done: () => void;
69
+ private readonly opts: DockOptions;
70
+
71
+ private view: 'list' | 'detail' = 'list';
72
+ private selectedId: string | undefined;
73
+ private scrollOffset = 0;
74
+ private followTail = true;
75
+ private statusMessage = '';
76
+ private timer: NodeJS.Timeout | undefined;
77
+ private busy = false;
78
+
79
+ constructor(tui: TUI, theme: Theme, done: () => void, opts: DockOptions) {
80
+ this.tui = tui;
81
+ this.theme = theme;
82
+ this.done = done;
83
+ this.opts = opts;
84
+
85
+ const initial = sortTasks(this.opts.getTasks());
86
+ if (initial[0]) this.selectedId = initial[0].id;
87
+
88
+ this.timer = setInterval(() => {
89
+ this.tui.requestRender();
90
+ }, REFRESH_MS);
91
+ this.timer.unref();
92
+ }
93
+
94
+ dispose(): void {
95
+ if (this.timer) {
96
+ clearInterval(this.timer);
97
+ this.timer = undefined;
98
+ }
99
+ }
100
+
101
+ invalidate(): void {
102
+ // Stateless per-render.
103
+ }
104
+
105
+ handleInput(data: string): void {
106
+ const tasks = sortTasks(this.opts.getTasks());
107
+ this.ensureValidSelection(tasks);
108
+ const current = tasks.find((t) => t.id === this.selectedId);
109
+
110
+ if (data === 'q' || data === 'Q') {
111
+ this.close();
112
+ return;
113
+ }
114
+
115
+ if (this.view === 'detail') {
116
+ if (matchesKey(data, 'escape') || matchesKey(data, 'left')) {
117
+ this.view = 'list';
118
+ this.statusMessage = '';
119
+ this.tui.requestRender();
120
+ return;
121
+ }
122
+ if (matchesKey(data, 'up') || data === 'k') {
123
+ this.scrollDetail(1, current);
124
+ return;
125
+ }
126
+ if (matchesKey(data, 'down') || data === 'j') {
127
+ this.scrollDetail(-1, current);
128
+ return;
129
+ }
130
+ if (matchesKey(data, 'pageUp')) {
131
+ this.scrollDetail(DETAIL_ROWS - 2, current);
132
+ return;
133
+ }
134
+ if (matchesKey(data, 'pageDown')) {
135
+ this.scrollDetail(-(DETAIL_ROWS - 2), current);
136
+ return;
137
+ }
138
+ if (data === 'G' || data === 'g') {
139
+ this.followTail = true;
140
+ this.scrollOffset = 0;
141
+ this.tui.requestRender();
142
+ return;
143
+ }
144
+ if (data === 'x' && current) {
145
+ void this.handleKill(current);
146
+ return;
147
+ }
148
+ if (data === 'r' && current) {
149
+ void this.handleRerun(current);
150
+ return;
151
+ }
152
+ return;
153
+ }
154
+
155
+ // List view
156
+ if (matchesKey(data, 'escape')) {
157
+ this.close();
158
+ return;
159
+ }
160
+ if (matchesKey(data, 'up') || data === 'k') {
161
+ this.moveSelection(tasks, -1);
162
+ return;
163
+ }
164
+ if (matchesKey(data, 'down') || data === 'j') {
165
+ this.moveSelection(tasks, 1);
166
+ return;
167
+ }
168
+ if (matchesKey(data, 'pageUp')) {
169
+ this.moveSelection(tasks, -LIST_ROWS);
170
+ return;
171
+ }
172
+ if (matchesKey(data, 'pageDown')) {
173
+ this.moveSelection(tasks, LIST_ROWS);
174
+ return;
175
+ }
176
+ if ((matchesKey(data, 'return') || matchesKey(data, 'right')) && current) {
177
+ this.opts.markSeen(current.id);
178
+ this.view = 'detail';
179
+ this.followTail = true;
180
+ this.scrollOffset = 0;
181
+ this.statusMessage = '';
182
+ this.tui.requestRender();
183
+ return;
184
+ }
185
+ if (data === 'x' && current) {
186
+ void this.handleKill(current);
187
+ return;
188
+ }
189
+ if (data === 'r' && current) {
190
+ void this.handleRerun(current);
191
+ return;
192
+ }
193
+ if (data === 'c') {
194
+ this.opts.markAllFinishedSeen();
195
+ this.statusMessage = 'Cleared finished notices.';
196
+ this.tui.requestRender();
197
+ }
198
+ }
199
+
200
+ render(width: number): string[] {
201
+ const innerWidth = Math.max(40, width - 4);
202
+ const tasks = sortTasks(this.opts.getTasks());
203
+ this.ensureValidSelection(tasks);
204
+
205
+ const body =
206
+ this.view === 'detail'
207
+ ? this.renderDetail(tasks.find((t) => t.id === this.selectedId), innerWidth)
208
+ : this.renderList(tasks, innerWidth);
209
+
210
+ const top = border(`╭${'─'.repeat(innerWidth + 2)}╮`);
211
+ const bottom = border(`╰${'─'.repeat(innerWidth + 2)}╯`);
212
+ const framed = body.map((line) => {
213
+ const clipped = truncateToWidth(line, innerWidth);
214
+ return `${border('│')} ${padRight(clipped, innerWidth)} ${border('│')}`;
215
+ });
216
+ return [top, ...framed, bottom];
217
+ }
218
+
219
+ private close(): void {
220
+ this.dispose();
221
+ this.done();
222
+ }
223
+
224
+ private ensureValidSelection(tasks: BgTaskSnapshot[]): void {
225
+ if (tasks.length === 0) {
226
+ this.selectedId = undefined;
227
+ return;
228
+ }
229
+ if (!this.selectedId || !tasks.some((t) => t.id === this.selectedId)) {
230
+ this.selectedId = tasks[0]!.id;
231
+ }
232
+ }
233
+
234
+ private moveSelection(tasks: BgTaskSnapshot[], delta: number): void {
235
+ if (tasks.length === 0) return;
236
+ const idx = Math.max(0, tasks.findIndex((t) => t.id === this.selectedId));
237
+ const next = Math.max(0, Math.min(tasks.length - 1, idx + delta));
238
+ this.selectedId = tasks[next]!.id;
239
+ this.statusMessage = '';
240
+ this.tui.requestRender();
241
+ }
242
+
243
+ private scrollDetail(linesUp: number, task: BgTaskSnapshot | undefined): void {
244
+ if (!task) return;
245
+ const totalLines = splitOutputLines(boundedRead(task.outputAbsPath, DETAIL_TAIL_BYTES, true).text).length;
246
+ const maxOffset = Math.max(0, totalLines - DETAIL_ROWS);
247
+ const next = Math.max(0, Math.min(maxOffset, this.scrollOffset + linesUp));
248
+ this.scrollOffset = next;
249
+ this.followTail = next === 0;
250
+ this.tui.requestRender();
251
+ }
252
+
253
+ private async handleKill(task: BgTaskSnapshot): Promise<void> {
254
+ if (this.busy) return;
255
+ if (task.status !== 'running') {
256
+ this.statusMessage = `Task ${task.id} is already ${task.status}.`;
257
+ this.tui.requestRender();
258
+ return;
259
+ }
260
+ this.busy = true;
261
+ this.statusMessage = `Stopping ${task.name} (${task.id})…`;
262
+ this.tui.requestRender();
263
+ try {
264
+ await this.opts.stopTask(task.id);
265
+ this.statusMessage = `Stopped ${task.name} (${task.id}).`;
266
+ } catch (err) {
267
+ this.statusMessage = `Kill failed: ${err instanceof Error ? err.message : String(err)}`;
268
+ } finally {
269
+ this.busy = false;
270
+ this.tui.requestRender();
271
+ }
272
+ }
273
+
274
+ private async handleRerun(task: BgTaskSnapshot): Promise<void> {
275
+ if (this.busy) return;
276
+ this.busy = true;
277
+ this.statusMessage = `Rerunning ${task.name}…`;
278
+ this.tui.requestRender();
279
+ try {
280
+ const next = await this.opts.rerunTask(task);
281
+ this.selectedId = next.id;
282
+ this.followTail = true;
283
+ this.scrollOffset = 0;
284
+ this.statusMessage = `Started ${next.name} (${next.id}).`;
285
+ } catch (err) {
286
+ this.statusMessage = `Rerun failed: ${err instanceof Error ? err.message : String(err)}`;
287
+ } finally {
288
+ this.busy = false;
289
+ this.tui.requestRender();
290
+ }
291
+ }
292
+
293
+ private renderList(tasks: BgTaskSnapshot[], width: number): string[] {
294
+ const running = tasks.filter((t) => t.status === 'running').length;
295
+ const failed = tasks.filter((t) => t.status === 'failed').length;
296
+ const done = tasks.filter((t) => t.status === 'completed').length;
297
+ const summary = [
298
+ `${running} running`,
299
+ failed > 0 ? `${failed} failed` : null,
300
+ done > 0 ? `${done} done` : null,
301
+ ]
302
+ .filter(Boolean)
303
+ .join(' · ');
304
+
305
+ const lines: string[] = [
306
+ `${this.theme.fg('accent', 'Background Tasks')} ${this.theme.fg('dim', summary)}`,
307
+ this.theme.fg('dim', '─'.repeat(width)),
308
+ ];
309
+
310
+ if (tasks.length === 0) {
311
+ lines.push(this.theme.fg('dim', 'No background tasks in this session. Use bg_run or /bg <cmd>.'));
312
+ } else {
313
+ const selectedIdx = Math.max(0, tasks.findIndex((t) => t.id === this.selectedId));
314
+ const start = Math.max(0, Math.min(selectedIdx - Math.floor(LIST_ROWS / 2), tasks.length - LIST_ROWS));
315
+ const visible = tasks.slice(start, start + LIST_ROWS);
316
+
317
+ for (const task of visible) {
318
+ const selected = task.id === this.selectedId;
319
+ const cursor = selected ? this.theme.fg('accent', '›') : ' ';
320
+ const unseen = task.status !== 'running' && !this.opts.isSeen(task.id) ? this.theme.fg('warning', '•') : ' ';
321
+ const badge = statusBadge(this.theme, task.status);
322
+ const reload = task.surviveReload ? this.theme.fg('accent', ' [reload]') : '';
323
+ const exit = task.exitCode !== null && task.status !== 'running' ? ` exit=${task.exitCode}` : '';
324
+ const meta = this.theme.fg(
325
+ 'dim',
326
+ `${task.id} · ${taskDuration(task)} · ${formatBytes(task.outputBytes)}${exit}`,
327
+ );
328
+ const title = selected ? this.theme.fg('accent', task.name) : task.name;
329
+ lines.push(`${cursor}${unseen} ${badge} ${title}${reload} ${meta}`);
330
+ }
331
+
332
+ const current = tasks[selectedIdx];
333
+ if (current) {
334
+ lines.push(this.theme.fg('dim', '─'.repeat(width)));
335
+ lines.push(this.theme.fg('dim', `$ ${compactCommand(current.command, Math.max(20, width - 2))}`));
336
+ if (current.error) lines.push(this.theme.fg('error', current.error));
337
+ }
338
+ }
339
+
340
+ if (this.statusMessage) {
341
+ lines.push(this.theme.fg('warning', this.statusMessage));
342
+ }
343
+ lines.push(
344
+ this.theme.fg(
345
+ 'dim',
346
+ '↑/↓ select · Enter logs · x stop · r rerun · c clear notices · Esc/q close',
347
+ ),
348
+ );
349
+ return lines;
350
+ }
351
+
352
+ private renderDetail(task: BgTaskSnapshot | undefined, width: number): string[] {
353
+ if (!task) {
354
+ this.view = 'list';
355
+ return this.renderList(sortTasks(this.opts.getTasks()), width);
356
+ }
357
+ const pid = task.pid !== undefined ? ` · pid ${task.pid}` : '';
358
+ const exit = task.exitCode !== null ? ` · exit ${task.exitCode}` : '';
359
+ const reload = task.surviveReload ? ' · surviveReload' : '';
360
+
361
+ const lines: string[] = [
362
+ `${statusBadge(this.theme, task.status)} ${this.theme.fg('accent', task.name)} ${this.theme.fg('dim', `(${task.id}${pid}${exit}${reload})`)}`,
363
+ this.theme.fg('dim', `${taskDuration(task)} · ${formatBytes(task.outputBytes)} · ${task.outputPath}`),
364
+ this.theme.fg('dim', `$ ${compactCommand(task.command, Math.max(20, width - 2))}`),
365
+ ];
366
+ if (task.error) lines.push(this.theme.fg('error', task.error));
367
+ lines.push(this.theme.fg('dim', '─'.repeat(width)));
368
+
369
+ const { text } = boundedRead(task.outputAbsPath, DETAIL_TAIL_BYTES, true);
370
+ const allLines = splitOutputLines(text);
371
+ if (allLines.length === 0) {
372
+ lines.push(this.theme.fg('dim', '(no output yet)'));
373
+ } else {
374
+ const maxOffset = Math.max(0, allLines.length - DETAIL_ROWS);
375
+ const offset = this.followTail ? 0 : Math.min(this.scrollOffset, maxOffset);
376
+ const end = allLines.length - offset;
377
+ const start = Math.max(0, end - DETAIL_ROWS);
378
+ for (const outLine of allLines.slice(start, end)) {
379
+ lines.push(outLine);
380
+ }
381
+ }
382
+
383
+ lines.push(this.theme.fg('dim', '─'.repeat(width)));
384
+ if (this.statusMessage) lines.push(this.theme.fg('warning', this.statusMessage));
385
+ const tailState = this.followTail ? 'live tail' : `paused (+${this.scrollOffset} lines)`;
386
+ lines.push(
387
+ this.theme.fg(
388
+ 'dim',
389
+ `${tailState} · ↑/↓/PgUp/PgDn scroll · G live · x stop · r rerun · Esc back · q close`,
390
+ ),
391
+ );
392
+ return lines;
393
+ }
394
+ }
package/src/format.ts ADDED
@@ -0,0 +1,75 @@
1
+ import type { BgTaskSnapshot } from './types.ts';
2
+
3
+ export function formatBytes(bytes: number): string {
4
+ if (bytes < 1024) return `${bytes} B`;
5
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KiB`;
6
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MiB`;
7
+ }
8
+
9
+ export function formatDuration(ms: number): string {
10
+ const totalSec = Math.max(0, Math.floor(ms / 1000));
11
+ if (totalSec < 60) return `${totalSec}s`;
12
+ const min = Math.floor(totalSec / 60);
13
+ const sec = totalSec % 60;
14
+ if (min < 60) return `${min}m${sec}s`;
15
+ const hr = Math.floor(min / 60);
16
+ const remMin = min % 60;
17
+ return `${hr}h${remMin}m`;
18
+ }
19
+
20
+ export function taskDuration(task: BgTaskSnapshot, now = Date.now()): string {
21
+ return formatDuration((task.endTime ?? now) - task.startTime);
22
+ }
23
+
24
+ export function compactCommand(cmd: string, maxLen = 80): string {
25
+ const oneLine = cmd.replace(/\s+/g, ' ').trim();
26
+ if (oneLine.length <= maxLen) return oneLine;
27
+ return `${oneLine.slice(0, maxLen - 1)}…`;
28
+ }
29
+
30
+ export function formatLaunchReceipt(task: BgTaskSnapshot): string {
31
+ const flags: string[] = [];
32
+ if (task.timeoutSeconds !== undefined) flags.push(`timeout=${task.timeoutSeconds}s`);
33
+ if (task.surviveReload) flags.push('surviveReload=true');
34
+ if (task.notify !== 'wake') flags.push(`notify=${task.notify}`);
35
+ const extra = flags.length > 0 ? ` [${flags.join(', ')}]` : '';
36
+ return [
37
+ `Started "${task.name}" (${task.id})${extra}`,
38
+ `Output: ${task.outputPath}`,
39
+ ].join('\n');
40
+ }
41
+
42
+ export function formatStatusLine(task: BgTaskSnapshot, now = Date.now()): string {
43
+ const exit = task.exitCode !== null ? ` exit=${task.exitCode}` : '';
44
+ const reload = task.surviveReload ? ' [reload]' : '';
45
+ const err = task.error ? ` — ${task.error}` : '';
46
+ return `${task.id} [${task.status}${exit}] "${task.name}" (${taskDuration(task, now)}, ${formatBytes(task.outputBytes)})${reload} · ${task.outputPath}${err}`;
47
+ }
48
+
49
+ export function formatStatusList(tasks: BgTaskSnapshot[], now = Date.now()): string {
50
+ if (tasks.length === 0) return 'No background tasks in this session.';
51
+ return tasks.map((t) => formatStatusLine(t, now)).join('\n');
52
+ }
53
+
54
+ export function formatNotificationXml(task: BgTaskSnapshot): string {
55
+ const lines = [
56
+ '<background-task-notification>',
57
+ `<task-id>${task.id}</task-id>`,
58
+ `<name>${escapeXml(task.name)}</name>`,
59
+ `<status>${task.status}</status>`,
60
+ `<duration>${taskDuration(task)}</duration>`,
61
+ `<exit-code>${task.exitCode === null ? 'null' : String(task.exitCode)}</exit-code>`,
62
+ `<output-path>${escapeXml(task.outputPath)}</output-path>`,
63
+ `<output-bytes>${task.outputBytes}</output-bytes>`,
64
+ ];
65
+ if (task.error) lines.push(`<error>${escapeXml(task.error)}</error>`);
66
+ lines.push('</background-task-notification>');
67
+ return lines.join('\n');
68
+ }
69
+
70
+ function escapeXml(value: string): string {
71
+ return value
72
+ .replace(/&/g, '&amp;')
73
+ .replace(/</g, '&lt;')
74
+ .replace(/>/g, '&gt;');
75
+ }