pi-background-tasks 0.1.0 → 0.3.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.
@@ -0,0 +1,507 @@
1
+ import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext, Theme, ThemeColor, ToolRenderResultOptions } from "@earendil-works/pi-coding-agent";
2
+ import { formatSize } from "@earendil-works/pi-coding-agent";
3
+ import { Text, type KeyId } from "@earendil-works/pi-tui";
4
+ import { Type, type Static } from "typebox";
5
+ import {
6
+ DEFAULT_LOG_BYTES,
7
+ MAX_LOG_BYTES,
8
+ deriveTaskNameFromCommand,
9
+ formatSnapshotList,
10
+ normalizeMaxBytes,
11
+ normalizeTaskName,
12
+ parseBgCommandArgs,
13
+ taskDisplayName,
14
+ truncateChars,
15
+ type BgKillDetails,
16
+ type BgLogsDetails,
17
+ type BgRunDetails,
18
+ type BgStatusDetails,
19
+ type BgTask,
20
+ type BgTaskSnapshot,
21
+ type StartTaskOptions,
22
+ } from "./core/common.js";
23
+ import { BackgroundTaskRegistry } from "./core/registry.js";
24
+ import { BackgroundTasksManager, type BackgroundTaskForUi, type TaskManagerResult } from "./ui/background-tasks-manager.js";
25
+
26
+ /**
27
+ * Project-local Pi background task manager.
28
+ *
29
+ * Scope:
30
+ * - Explicit background shell jobs only: /bg and bg_run spawn commands directly.
31
+ * - No Ctrl+B support for backgrounding an already-running built-in bash tool.
32
+ * - No detached/restart reattachment: live child processes belong to this Pi
33
+ * extension runtime and are killed on session shutdown/reload.
34
+ */
35
+
36
+ const STATUS_INTERVAL_MS = 1000;
37
+ const COMMAND_PREVIEW_CHARS = 90;
38
+ const LIGHT_BLUE_BG = "\x1b[48;2;183;223;255m";
39
+ const LIGHT_BLUE_FG = "\x1b[38;2;11;70;110m";
40
+ const ANSI_RESET = "\x1b[0m";
41
+
42
+ function lightBlue(value: string): string {
43
+ return `${LIGHT_BLUE_BG}${LIGHT_BLUE_FG}${value}${ANSI_RESET}`;
44
+ }
45
+
46
+ function textContent(text: string) {
47
+ return [{ type: "text" as const, text }];
48
+ }
49
+
50
+ type TextToolResult = { content?: readonly { type: string; text?: string }[] };
51
+
52
+ const BgRunParams = Type.Object({
53
+ name: Type.String({ description: "Short human-readable task name shown in the bg footer dock. Required; use 2-6 words, not the raw command." }),
54
+ command: Type.String({ description: "Shell command to start in the background" }),
55
+ isAgent: Type.Boolean({ description: "Required. Set true only when this background task launches an LLM/agent process, such as a child `pi -p ...` or `pi --mode json ...`, so Pi-agent telemetry can be collected. Set false for scripts, tests, servers, sleeps, and ordinary shell commands." }),
56
+ description: Type.Optional(Type.String({ description: "Optional longer human-readable context for the task" })),
57
+ timeoutSeconds: Type.Optional(Type.Number({ description: "Optional timeout; task is failed and killed when exceeded" })),
58
+ notifyOnCompletion: Type.Optional(Type.Boolean({ description: "Whether to show a completion notification. Default: true." })),
59
+ triggerOnCompletion: Type.Optional(Type.Boolean({ description: "Whether completion should trigger a follow-up agent turn. Default: true for bg_run." })),
60
+ });
61
+
62
+ const BgStatusParams = Type.Object({
63
+ taskId: Type.Optional(Type.String({ description: "Optional task ID or unambiguous prefix. If omitted, all running/recent tasks are returned." })),
64
+ });
65
+
66
+ const BgLogsParams = Type.Object({
67
+ taskId: Type.String({ description: "Task ID or unambiguous prefix" }),
68
+ maxBytes: Type.Optional(Type.Number({ description: `Maximum bytes to return, capped at ${formatSize(MAX_LOG_BYTES)}. Default: ${formatSize(DEFAULT_LOG_BYTES)}.` })),
69
+ tail: Type.Optional(Type.Boolean({ description: "Read the tail of the log when true, head when false. Default: true." })),
70
+ });
71
+
72
+ const BgKillParams = Type.Object({
73
+ taskId: Type.String({ description: "Task ID or unambiguous prefix to stop" }),
74
+ });
75
+
76
+ type BgRunParamsValue = Static<typeof BgRunParams>;
77
+ type BgStatusParamsValue = Static<typeof BgStatusParams>;
78
+ type BgLogsParamsValue = Static<typeof BgLogsParams>;
79
+ type BgKillParamsValue = Static<typeof BgKillParams>;
80
+
81
+ function renderPlainResult(result: TextToolResult, _options: ToolRenderResultOptions, _theme: Theme) {
82
+ const text = result.content?.map((part) => part.type === "text" ? (part.text ?? "") : "").join("\n") ?? "";
83
+ return new Text(text, 0, 0);
84
+ }
85
+
86
+ export default function backgroundTasksExtension(pi: ExtensionAPI): void {
87
+ const seenTaskIds = new Set<string>();
88
+ let currentCtx: ExtensionContext | undefined;
89
+ let dockOpen = false;
90
+ let statusInterval: NodeJS.Timeout | undefined;
91
+
92
+ const registry = new BackgroundTaskRegistry({
93
+ onChange: () => updateUi(),
94
+ sendCompletionNotification: (message, options) => {
95
+ pi.sendMessage(message, options);
96
+ },
97
+ });
98
+
99
+ function unseenFinishedTasks(): BgTask[] {
100
+ return registry.allTasks().filter((task) => task.status !== "running" && !seenTaskIds.has(task.id));
101
+ }
102
+
103
+ function clearFinishedNotices(ctx = currentCtx): number {
104
+ const unseen = unseenFinishedTasks();
105
+ for (const task of unseen) seenTaskIds.add(task.id);
106
+ updateUi(ctx);
107
+ return unseen.length;
108
+ }
109
+
110
+ function notifyClearFinishedNotices(ctx: ExtensionContext): void {
111
+ currentCtx = ctx;
112
+ const cleared = clearFinishedNotices(ctx);
113
+ if (!ctx.hasUI) return;
114
+ ctx.ui.notify(
115
+ cleared > 0
116
+ ? `Cleared ${cleared} finished background task notice${cleared === 1 ? "" : "s"}.`
117
+ : "No finished background task notices to clear.",
118
+ cleared > 0 ? "info" : "warning",
119
+ );
120
+ }
121
+
122
+ function updateUi(ctx = currentCtx): void {
123
+ if (registry.isShuttingDown() || !ctx) return;
124
+ try {
125
+ if (!ctx.hasUI) return;
126
+ const allTasks = registry.allTasks();
127
+ const running = allTasks.filter((task) => task.status === "running");
128
+ const unseenFailed = allTasks.filter((task) => task.status === "failed" && !seenTaskIds.has(task.id));
129
+ const unseenStopped = allTasks.filter((task) => task.status === "killed" && !seenTaskIds.has(task.id));
130
+ const unseenDone = allTasks.filter((task) => task.status === "completed" && !seenTaskIds.has(task.id));
131
+ const unseenFinishedCount = unseenFailed.length + unseenStopped.length + unseenDone.length;
132
+ ctx.ui.setWidget("background-tasks", undefined);
133
+ if (running.length === 0 && unseenFinishedCount === 0) {
134
+ ctx.ui.setStatus("background-tasks", undefined);
135
+ return;
136
+ }
137
+
138
+ const parts: string[] = [];
139
+ if (running.length > 0) parts.push(`${running.length} running`);
140
+ if (unseenFailed.length > 0) parts.push(`${unseenFailed.length} failed`);
141
+ if (unseenStopped.length > 0) parts.push(`${unseenStopped.length} stopped`);
142
+ if (unseenDone.length > 0) parts.push(`${unseenDone.length} done`);
143
+ const entryHint = dockOpen ? "focused" : `Shift↓${unseenFinishedCount > 0 ? " · /bg-clear" : ""}`;
144
+ const label = ` bg ${parts.join(" · ")} · ${entryHint} `;
145
+ ctx.ui.setStatus("background-tasks", lightBlue(label));
146
+ } catch (error) {
147
+ console.error(`[background-tasks] UI update failed: ${error instanceof Error ? error.message : String(error)}`);
148
+ currentCtx = undefined;
149
+ }
150
+ }
151
+
152
+ async function startTask(ctx: ExtensionContext, command: string, options: StartTaskOptions = {}): Promise<BgTask> {
153
+ currentCtx = ctx;
154
+ return registry.startTask(ctx, command, options);
155
+ }
156
+
157
+ async function openTaskManager(ctx: ExtensionCommandContext | ExtensionContext, initialTaskId?: string): Promise<void> {
158
+ currentCtx = ctx;
159
+ if (!ctx.hasUI) {
160
+ ctx.ui.notify("Background task manager requires an interactive Pi UI. Use /jobs, /logs, or the bg_status/bg_logs tools in non-interactive mode.", "error");
161
+ return;
162
+ }
163
+ dockOpen = true;
164
+ updateUi(ctx);
165
+ try {
166
+ await ctx.ui.custom<TaskManagerResult>(
167
+ (tui, theme, _keybindings, done) => {
168
+ const managerOptions = {
169
+ getTasks: () => registry.allTasks(),
170
+ stopTask: async (task: BackgroundTaskForUi) => {
171
+ await registry.stopTask(registry.resolveTask(task.id), "user");
172
+ updateUi(ctx);
173
+ },
174
+ stopAllRunning: async () => {
175
+ const result = await registry.stopAllRunning("user");
176
+ updateUi(ctx);
177
+ return result;
178
+ },
179
+ rerunTask: async (task: BackgroundTaskForUi) => {
180
+ const rerunOptions: StartTaskOptions = {
181
+ name: taskDisplayName(task),
182
+ isAgent: task.isAgent,
183
+ notifyOnCompletion: true,
184
+ triggerOnCompletion: false,
185
+ };
186
+ if (task.description !== undefined) rerunOptions.description = task.description;
187
+ if (task.timeoutSeconds !== undefined) rerunOptions.timeoutSeconds = task.timeoutSeconds;
188
+ const rerun = await startTask(ctx, task.command, rerunOptions);
189
+ updateUi(ctx);
190
+ return rerun;
191
+ },
192
+ showOutputPath: (task: BackgroundTaskForUi) => {
193
+ ctx.ui.notify(`Output path for ${taskDisplayName(task)} (${task.id}):\n${task.outputPath}`, "info");
194
+ },
195
+ markSeen: (taskId: string) => {
196
+ seenTaskIds.add(taskId);
197
+ updateUi(ctx);
198
+ },
199
+ markFinishedSeen: (taskIds: string[]) => {
200
+ for (const taskId of taskIds) seenTaskIds.add(taskId);
201
+ updateUi(ctx);
202
+ },
203
+ isSeen: (taskId: string) => seenTaskIds.has(taskId),
204
+ };
205
+ if (initialTaskId) return new BackgroundTasksManager(tui, theme, done, { ...managerOptions, initialTaskId });
206
+ return new BackgroundTasksManager(tui, theme, done, managerOptions);
207
+ },
208
+ {
209
+ overlay: true,
210
+ overlayOptions: { anchor: "bottom-center", width: "96%", minWidth: 64, maxHeight: "60%", margin: { bottom: 1, left: 1, right: 1 } },
211
+ },
212
+ );
213
+ } finally {
214
+ dockOpen = false;
215
+ updateUi(ctx);
216
+ }
217
+ }
218
+
219
+ pi.registerMessageRenderer<BgTaskSnapshot>("background-task-notification", (message, _options, theme) => {
220
+ const task = message.details;
221
+ const status = task?.status ?? "completed";
222
+ const color: ThemeColor = status === "completed" ? "success" : status === "failed" ? "error" : status === "killed" ? "warning" : "accent";
223
+ const id = task?.id ?? "background task";
224
+ const name = task ? taskDisplayName(task) : "Background task";
225
+ const output = task?.outputPath ? `\n${theme.fg("dim", `Output: ${task.outputPath}`)}` : "";
226
+ const error = task?.error ? `\n${theme.fg("error", task.error)}` : "";
227
+ return new Text(`${theme.fg(color, `[bg ${status}]`)} ${theme.fg("accent", name)} ${theme.fg("dim", `(${id})`)}${output}${error}`, 0, 0);
228
+ });
229
+
230
+ pi.on("session_start", async (_event, ctx) => {
231
+ registry.setShuttingDown(false);
232
+ currentCtx = ctx;
233
+ await registry.ensureRuntimeDir(ctx);
234
+ updateUi(ctx);
235
+ if (statusInterval) clearInterval(statusInterval);
236
+ statusInterval = setInterval(() => updateUi(), STATUS_INTERVAL_MS);
237
+ });
238
+
239
+ pi.on("session_shutdown", async (_event, ctx) => {
240
+ registry.setShuttingDown(true);
241
+ currentCtx = undefined;
242
+ if (statusInterval) {
243
+ clearInterval(statusInterval);
244
+ statusInterval = undefined;
245
+ }
246
+ const running = registry.allTasks().filter((task) => task.status === "running");
247
+ if (running.length === 0) return;
248
+
249
+ const failures: string[] = [];
250
+ await Promise.all(
251
+ running.map(async (task) => {
252
+ try {
253
+ await registry.stopTask(task, "shutdown", "Killed during Pi session shutdown/reload");
254
+ } catch (error) {
255
+ const message = `${task.id}: ${error instanceof Error ? error.message : String(error)}`;
256
+ failures.push(message);
257
+ console.error(`[background-tasks] shutdown cleanup failed for ${message}`);
258
+ }
259
+ }),
260
+ );
261
+ if (failures.length > 0 && ctx.hasUI) {
262
+ ctx.ui.notify(`Background task cleanup failed:\n${failures.join("\n")}`, "error");
263
+ }
264
+ });
265
+
266
+ pi.registerCommand("bg", {
267
+ description: "Start a shell command as a tracked background task: /bg [--agent] [--name \"Task name\"] <command>",
268
+ handler: async (args, ctx) => {
269
+ try {
270
+ const parsed = parseBgCommandArgs(args);
271
+ const taskOptions: StartTaskOptions = { isAgent: parsed.isAgent, notifyOnCompletion: true, triggerOnCompletion: false };
272
+ if (parsed.name !== undefined) taskOptions.name = parsed.name;
273
+ const task = await startTask(ctx, parsed.command, taskOptions);
274
+ ctx.ui.notify(`Started ${taskDisplayName(task)} (${task.id})\nOutput: ${task.outputPath}\nCommand: ${task.command}`, "info");
275
+ } catch (error) {
276
+ ctx.ui.notify(`Background task failed to start: ${error instanceof Error ? error.message : String(error)}`, "error");
277
+ }
278
+ },
279
+ });
280
+
281
+ pi.registerCommand("tasks", {
282
+ description: "Open the Claude-like background task manager UI",
283
+ handler: async (args, ctx) => {
284
+ const taskId = args.trim() || undefined;
285
+ await openTaskManager(ctx, taskId);
286
+ },
287
+ });
288
+
289
+ pi.registerCommand("bg-tasks", {
290
+ description: "Open the background task manager UI",
291
+ handler: async (args, ctx) => {
292
+ const taskId = args.trim() || undefined;
293
+ await openTaskManager(ctx, taskId);
294
+ },
295
+ });
296
+
297
+ pi.registerCommand("bg-clear", {
298
+ description: "Clear finished background task footer notices",
299
+ handler: async (_args, ctx) => {
300
+ notifyClearFinishedNotices(ctx);
301
+ },
302
+ });
303
+
304
+ pi.registerShortcut("shift+down" satisfies KeyId, {
305
+ description: "Open focused background task footer dock",
306
+ handler: async (ctx) => {
307
+ await openTaskManager(ctx);
308
+ },
309
+ });
310
+
311
+ pi.registerShortcut("ctrl+alt+c" satisfies KeyId, {
312
+ description: "Clear finished background task footer notices (terminal-dependent fallback for /bg-clear)",
313
+ handler: (ctx) => notifyClearFinishedNotices(ctx),
314
+ });
315
+
316
+ pi.registerCommand("jobs", {
317
+ description: "List running and recent background tasks",
318
+ handler: async (_args, ctx) => {
319
+ currentCtx = ctx;
320
+ ctx.ui.notify(formatSnapshotList(registry.allTasks().map((task) => registry.snapshot(task))), "info");
321
+ updateUi(ctx);
322
+ },
323
+ });
324
+
325
+ pi.registerCommand("logs", {
326
+ description: "Show bounded output from a background task: /logs <id> [maxBytes]",
327
+ getArgumentCompletions: (prefix) => {
328
+ const matches = registry.allTasks()
329
+ .filter((task) => task.id.startsWith(prefix.trim()))
330
+ .slice(0, 20)
331
+ .map((task) => ({ value: task.id, label: `${task.id} ${taskDisplayName(task)}`, description: `${task.status} — ${truncateChars(task.command, 60)}` }));
332
+ return matches.length > 0 ? matches : null;
333
+ },
334
+ handler: async (args, ctx) => {
335
+ try {
336
+ currentCtx = ctx;
337
+ const [id, bytes] = args.trim().split(/\s+/, 2);
338
+ const task = registry.resolveTask(id || "");
339
+ const maxBytes = normalizeMaxBytes(Number(bytes), DEFAULT_LOG_BYTES);
340
+ const logs = await registry.getTaskLogs(task, maxBytes, true);
341
+ ctx.ui.notify(logs.text, "info");
342
+ } catch (error) {
343
+ ctx.ui.notify(`Background logs error: ${error instanceof Error ? error.message : String(error)}`, "error");
344
+ }
345
+ },
346
+ });
347
+
348
+ pi.registerCommand("kill", {
349
+ description: "Stop a running background task: /kill <id>",
350
+ getArgumentCompletions: (prefix) => {
351
+ const matches = registry.allTasks()
352
+ .filter((task) => task.status === "running" && task.id.startsWith(prefix.trim()))
353
+ .slice(0, 20)
354
+ .map((task) => ({ value: task.id, label: `${task.id} ${taskDisplayName(task)}`, description: truncateChars(task.command, 70) }));
355
+ return matches.length > 0 ? matches : null;
356
+ },
357
+ handler: async (args, ctx) => {
358
+ try {
359
+ currentCtx = ctx;
360
+ const task = registry.resolveTask(args.trim());
361
+ await registry.stopTask(task, "user");
362
+ ctx.ui.notify(`Killed ${taskDisplayName(task)} (${task.id}). Output: ${task.outputPath}`, "info");
363
+ updateUi(ctx);
364
+ } catch (error) {
365
+ ctx.ui.notify(`Background kill error: ${error instanceof Error ? error.message : String(error)}`, "error");
366
+ }
367
+ },
368
+ });
369
+
370
+ pi.registerTool<typeof BgRunParams, BgRunDetails>({
371
+ name: "bg_run",
372
+ label: "Background Run",
373
+ description: `Start a named long-running shell command in the background and return immediately with a task ID and output path. Output is written to .pi/tasks and model-visible logs are bounded to ${formatSize(MAX_LOG_BYTES)}.`,
374
+ promptSnippet: "Start named long-running shell commands in the background and return a task ID plus output file path",
375
+ promptGuidelines: [
376
+ "Use bg_run instead of bash for commands expected to run for a long time, such as test suites, dev servers, watchers, builds, or sleeps.",
377
+ "Always set isAgent: true only when the background task launches an LLM/agent process; set isAgent: false for scripts, tests, dev servers, sleeps, and ordinary shell commands.",
378
+ "When using bg_run, always set name to a concise 2-6 word human-readable label for the footer task dock; do not use the raw command as the name unless it is already short and meaningful.",
379
+ "After bg_run, use bg_status and bg_logs to inspect progress; do not assume the background task completed until status says completed, failed, or killed.",
380
+ "When a <background-task-notification> appears, react to it: inspect bg_status/bg_logs as needed, then report completion, failure, or next steps to the user.",
381
+ ],
382
+ parameters: BgRunParams,
383
+ prepareArguments(args): BgRunParamsValue {
384
+ if (!args || typeof args !== "object") throw new Error("bg_run arguments must be an object");
385
+ const input = args as Record<string, unknown>;
386
+ if (typeof input["command"] !== "string") throw new Error("bg_run requires command string");
387
+ if (typeof input["isAgent"] !== "boolean") {
388
+ throw new Error("bg_run requires isAgent boolean. Set true only for LLM/agent tasks; set false for scripts, tests, servers, sleeps, and ordinary shell commands.");
389
+ }
390
+ const prepared: BgRunParamsValue = {
391
+ command: input["command"],
392
+ name: normalizeTaskName(input["name"]) ?? normalizeTaskName(input["description"]) ?? deriveTaskNameFromCommand(input["command"]),
393
+ isAgent: input["isAgent"],
394
+ };
395
+ if (typeof input["description"] === "string") prepared.description = input["description"];
396
+ if (typeof input["timeoutSeconds"] === "number") prepared.timeoutSeconds = input["timeoutSeconds"];
397
+ if (typeof input["notifyOnCompletion"] === "boolean") prepared.notifyOnCompletion = input["notifyOnCompletion"];
398
+ if (typeof input["triggerOnCompletion"] === "boolean") prepared.triggerOnCompletion = input["triggerOnCompletion"];
399
+ return prepared;
400
+ },
401
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
402
+ if (typeof params.isAgent !== "boolean") {
403
+ throw new Error("bg_run requires isAgent boolean. Set true only for LLM/agent tasks; set false for scripts, tests, servers, sleeps, and ordinary shell commands.");
404
+ }
405
+ const taskOptions: StartTaskOptions = {
406
+ name: params.name,
407
+ isAgent: params.isAgent,
408
+ notifyOnCompletion: params.notifyOnCompletion ?? true,
409
+ triggerOnCompletion: params.triggerOnCompletion ?? true,
410
+ };
411
+ if (params.description !== undefined) taskOptions.description = params.description;
412
+ if (params.timeoutSeconds !== undefined) taskOptions.timeoutSeconds = params.timeoutSeconds;
413
+ const task = await startTask(ctx, params.command, taskOptions);
414
+ return {
415
+ content: textContent(`Started background task ${taskDisplayName(task)} (${task.id})\nStatus: ${task.status}\nPID: ${task.pid ?? "unknown"}\nOutput: ${task.outputPath}`),
416
+ details: { task: registry.snapshot(task) },
417
+ };
418
+ },
419
+ renderCall(args, theme) {
420
+ return new Text(`${theme.fg("toolTitle", theme.bold("bg_run "))}${theme.fg("muted", truncateChars(taskDisplayName(args), COMMAND_PREVIEW_CHARS))}`, 0, 0);
421
+ },
422
+ renderResult(result, _options, theme) {
423
+ const task = result.details?.task;
424
+ if (!task) return renderPlainResult(result, _options, theme);
425
+ return new Text(`${theme.fg("success", "✓ started")} ${theme.fg("accent", taskDisplayName(task))} ${theme.fg("dim", `(${task.id})`)}\n${theme.fg("dim", `Output: ${task.outputPath}`)}`, 0, 0);
426
+ },
427
+ });
428
+
429
+ pi.registerTool<typeof BgStatusParams, BgStatusDetails>({
430
+ name: "bg_status",
431
+ label: "Background Status",
432
+ description: "Inspect one background task or list all running/recent background tasks.",
433
+ promptSnippet: "Inspect status for one or all background tasks",
434
+ promptGuidelines: ["Use bg_status before bg_logs when you need to know whether a background task is still running or has finished."],
435
+ parameters: BgStatusParams,
436
+ async execute(_toolCallId, params) {
437
+ const selected = params.taskId ? [registry.resolveTask(params.taskId)] : registry.allTasks();
438
+ const snapshots = selected.map((task) => registry.snapshot(task));
439
+ return {
440
+ content: textContent(formatSnapshotList(snapshots)),
441
+ details: { tasks: snapshots },
442
+ };
443
+ },
444
+ renderCall(args, theme) {
445
+ return new Text(`${theme.fg("toolTitle", theme.bold("bg_status"))}${args.taskId ? ` ${theme.fg("accent", args.taskId)}` : ""}`, 0, 0);
446
+ },
447
+ renderResult: renderPlainResult,
448
+ });
449
+
450
+ pi.registerTool<typeof BgLogsParams, BgLogsDetails>({
451
+ name: "bg_logs",
452
+ label: "Background Logs",
453
+ description: `Read bounded output from a background task. Output is capped at ${formatSize(MAX_LOG_BYTES)} for model safety and points to the full output file when truncated.`,
454
+ promptSnippet: "Read bounded output from a background task log",
455
+ promptGuidelines: ["Use bg_logs with a modest maxBytes value to inspect background task progress without flooding context."],
456
+ parameters: BgLogsParams,
457
+ async execute(_toolCallId, params) {
458
+ const task = registry.resolveTask(params.taskId);
459
+ const logs = await registry.getTaskLogs(task, normalizeMaxBytes(params.maxBytes), params.tail ?? true);
460
+ return {
461
+ content: textContent(logs.text),
462
+ details: logs.details,
463
+ };
464
+ },
465
+ renderCall(args, theme) {
466
+ return new Text(`${theme.fg("toolTitle", theme.bold("bg_logs "))}${theme.fg("accent", args.taskId)}`, 0, 0);
467
+ },
468
+ renderResult(result, { expanded }, theme) {
469
+ const details = result.details;
470
+ if (!details) return renderPlainResult(result, { expanded, isPartial: false }, theme);
471
+ let text = `${theme.fg("accent", taskDisplayName(details.task))} ${theme.fg("dim", `(${details.task.id})`)} ${theme.fg("muted", details.tail ? "tail" : "head")} ${formatSize(details.bytesRead)}`;
472
+ if (details.truncated) text += theme.fg("warning", " (truncated)");
473
+ text += `\n${theme.fg("dim", `Full output: ${details.path}`)}`;
474
+ if (expanded) {
475
+ const content = result.content?.[0];
476
+ if (content?.type === "text") text += `\n${theme.fg("toolOutput", content.text.split("\n").slice(0, 30).join("\n"))}`;
477
+ }
478
+ return new Text(text, 0, 0);
479
+ },
480
+ });
481
+
482
+ pi.registerTool<typeof BgKillParams, BgKillDetails>({
483
+ name: "bg_kill",
484
+ label: "Background Kill",
485
+ description: "Stop a running background task by ID. Fails loudly if the task is unknown or already finished.",
486
+ promptSnippet: "Stop a running background task by ID",
487
+ promptGuidelines: ["Use bg_kill when the user asks to stop a background task or when a bg_run command is no longer needed."],
488
+ parameters: BgKillParams,
489
+ async execute(_toolCallId, params) {
490
+ const task = registry.resolveTask(params.taskId);
491
+ await registry.stopTask(task, "user");
492
+ const message = `Killed background task ${taskDisplayName(task)} (${task.id}). Output: ${task.outputPath}`;
493
+ return {
494
+ content: textContent(message),
495
+ details: { task: registry.snapshot(task), message },
496
+ };
497
+ },
498
+ renderCall(args, theme) {
499
+ return new Text(`${theme.fg("toolTitle", theme.bold("bg_kill "))}${theme.fg("accent", args.taskId)}`, 0, 0);
500
+ },
501
+ renderResult(result, _options, theme) {
502
+ const task = result.details?.task;
503
+ if (!task) return renderPlainResult(result, _options, theme);
504
+ return new Text(`${theme.fg("warning", "■ killed")} ${theme.fg("accent", taskDisplayName(task))} ${theme.fg("dim", `(${task.id})`)}\n${theme.fg("dim", `Output: ${task.outputPath}`)}`, 0, 0);
505
+ },
506
+ });
507
+ }
@@ -0,0 +1,3 @@
1
+ export const isolatedTestEnv = { PI_OFFLINE: "1", PI_SKIP_VERSION_CHECK: "1", PI_TELEMETRY: "0", CI: "1" } as const;
2
+ export function stripAnsi(value: string): string { return value.replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, ""); }
3
+ export function normalizeVolatile(value: string): string { return value.replace(/b[0-9a-f]{8}/g,"<TASK_ID>").replace(/[0-9a-f]{8}-[0-9a-f-]{27,}/gi,"<UUID>").replace(/pid=?\s*\d+/gi,"pid=<PID>").replace(/\.pi\/tasks\/[^\s)]+/g,".pi/tasks/<RUN>/<FILE>").replace(/\/tmp\/[^\s)]+/g,"/tmp/<TEMP>"); }