pi-background-named 0.0.0-stage → 0.4.11
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 +18 -2
- package/extensions/background.ts +870 -0
- package/extensions/command.ts +22 -0
- package/package.json +33 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Thomas van Dongen
|
|
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
CHANGED
|
@@ -1,3 +1,19 @@
|
|
|
1
|
-
#
|
|
1
|
+
# pi-background-named
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A fork of [pi-background](https://github.com/Pringled/pi-extensions/tree/main/packages/pi-background) by Thomas van Dongen. Same behaviour, with three changes on top of `0.4.11`:
|
|
4
|
+
|
|
5
|
+
1. `bg_run` takes an optional `name`, and the jobs line, `/bg` list, completion cards and wake messages show `● 1 build docs · 12s · …` instead of the command. Without a name, the first words of the command are shown.
|
|
6
|
+
2. The id loses its `bg` prefix wherever it is displayed (`bg1` becomes `1`); commands still accept either.
|
|
7
|
+
3. Card headers drop the `Background` prefix, the jobs line marks live jobs with `●`, silent jobs turn yellow, and the viewer's rules follow the job's state colour.
|
|
8
|
+
|
|
9
|
+
Tools and commands are unchanged: `bg_run`, `bg_status`, `bg_kill`, `/bg`.
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
pi install npm:pi-background-named
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Licence
|
|
18
|
+
|
|
19
|
+
MIT, original copyright Thomas van Dongen.
|
|
@@ -0,0 +1,870 @@
|
|
|
1
|
+
import { closeSync, createWriteStream, fstatSync, mkdirSync, openSync, readSync } from "node:fs";
|
|
2
|
+
import { homedir, tmpdir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import {
|
|
5
|
+
type BashOperations,
|
|
6
|
+
createBashToolDefinition,
|
|
7
|
+
createLocalBashOperations,
|
|
8
|
+
type ExtensionAPI,
|
|
9
|
+
type ExtensionContext,
|
|
10
|
+
type ExtensionToolContext,
|
|
11
|
+
} from "@earendil-works/pi-coding-agent";
|
|
12
|
+
import { Key, type KeyId, matchesKey, stripTerminalSequences, truncateToWidth, type TuiMouseEvent, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
|
|
13
|
+
import { Type } from "typebox";
|
|
14
|
+
import { shortCommand } from "./command.ts";
|
|
15
|
+
|
|
16
|
+
const TAIL_LINES = 20;
|
|
17
|
+
const SCROLL_LINES = 1000;
|
|
18
|
+
const TAIL_BYTES = 64 * 1024;
|
|
19
|
+
// A bash command still running after this long moves to the background, so it no longer blocks the turn
|
|
20
|
+
const AUTO_BACKGROUND_SECS = 120;
|
|
21
|
+
const WAKE_DEBOUNCE_MS = 1000;
|
|
22
|
+
const MAX_WAKES = 10;
|
|
23
|
+
const MAX_SHOWN_JOBS = 3;
|
|
24
|
+
// A running job silent this long shows how long it has been quiet, since it may be stuck, and wakes Pi to check on it
|
|
25
|
+
const SILENT_AFTER_MS = 10 * 60_000;
|
|
26
|
+
// Finished jobs listed by /bg; older ones stay reachable as /bg <id>
|
|
27
|
+
const MAX_LISTED_FINISHED = 10;
|
|
28
|
+
// How long a bash command runs before the jobs line offers ctrl+b, so quick commands don't flash it
|
|
29
|
+
const HINT_AFTER_MS = 3000;
|
|
30
|
+
// How long finished results wait for jobs started alongside them before Pi is woken anyway
|
|
31
|
+
const GROUP_HOLD_MS = 2 * 60_000;
|
|
32
|
+
// Minutes a non-interactive run waits for running jobs before it exits anyway, unless settings.json sets "exitWait"
|
|
33
|
+
const EXIT_WAIT_MINUTES = 30;
|
|
34
|
+
// How often that wait looks again, short enough to notice a finishing job straight away
|
|
35
|
+
const SETTLE_POLL_MS = 250;
|
|
36
|
+
|
|
37
|
+
interface Job {
|
|
38
|
+
id: string;
|
|
39
|
+
name?: string;
|
|
40
|
+
command: string;
|
|
41
|
+
log: string;
|
|
42
|
+
started: number;
|
|
43
|
+
controller: AbortController;
|
|
44
|
+
status: "running" | "exited" | "killed" | "failed";
|
|
45
|
+
exitCode?: number | null;
|
|
46
|
+
ended?: number;
|
|
47
|
+
// The latest output line, shown while the job runs
|
|
48
|
+
lastLine?: string;
|
|
49
|
+
// When the job last printed anything
|
|
50
|
+
lastOutput?: number;
|
|
51
|
+
// The turn that started the job; jobs from the same turn are reported together
|
|
52
|
+
group: number;
|
|
53
|
+
// Started with wake_on, so it may run indefinitely and doesn't hold back the others
|
|
54
|
+
watched: boolean;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Reads up to the last lines from the final TAIL_BYTES of a log file without loading the whole file. */
|
|
58
|
+
function tail(path: string, lines: number): string {
|
|
59
|
+
let fd: number;
|
|
60
|
+
try {
|
|
61
|
+
fd = openSync(path, "r");
|
|
62
|
+
} catch {
|
|
63
|
+
return "(no output)";
|
|
64
|
+
}
|
|
65
|
+
try {
|
|
66
|
+
const size = fstatSync(fd).size;
|
|
67
|
+
if (size === 0) return "(no output)";
|
|
68
|
+
const start = Math.max(0, size - TAIL_BYTES);
|
|
69
|
+
const buf = Buffer.alloc(size - start);
|
|
70
|
+
let text = buf.subarray(0, readSync(fd, buf, 0, buf.length, start)).toString("utf8");
|
|
71
|
+
// Start on a full line when the read began mid-line
|
|
72
|
+
if (start > 0) {
|
|
73
|
+
const nl = text.indexOf("\n");
|
|
74
|
+
if (nl >= 0) text = text.slice(nl + 1);
|
|
75
|
+
}
|
|
76
|
+
return text.trimEnd().split("\n").slice(-lines).join("\n") || "(no output)";
|
|
77
|
+
} finally {
|
|
78
|
+
closeSync(fd);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** 45s, 12m30s, or 1h20m once seconds no longer matter. */
|
|
83
|
+
function duration(ms: number): string {
|
|
84
|
+
const s = Math.round(ms / 1000);
|
|
85
|
+
if (s < 60) return `${s}s`;
|
|
86
|
+
if (s < 3600) return `${Math.floor(s / 60)}m${s % 60}s`;
|
|
87
|
+
return `${Math.floor(s / 3600)}h${Math.floor(s / 60) % 60}m`;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function elapsed(job: Job): string {
|
|
91
|
+
return duration((job.ended ?? Date.now()) - job.started);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function state(job: Job): string {
|
|
95
|
+
return job.status === "exited" ? `exit ${job.exitCode}` : job.status;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function summary(job: Job): string {
|
|
99
|
+
return `${shortId(job)} [${state(job)}, ${elapsed(job)}] ${jobLabel(job)}\n log: ${job.log}`;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** An output line as a terminal would last have shown it: without escape codes or control characters, and a progress bar redrawn with \r in its latest state only. */
|
|
103
|
+
function cleanLine(line: string): string {
|
|
104
|
+
const shown = stripTerminalSequences(line).split("\r").filter((part) => part.trim()).at(-1) ?? "";
|
|
105
|
+
return shown.replace(/\t/g, " ").replace(/[\x00-\x08\x0b-\x1f\x7f]/g, "").trimEnd();
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** The part of a command worth showing: its first line, without a leading cd, with a script path shortened to its name and at most 50 characters. */
|
|
109
|
+
function shownCommand(command: string): string {
|
|
110
|
+
const shown = command
|
|
111
|
+
.split("\n")[0]
|
|
112
|
+
.replace(/^\s*(cd\s+("[^"]*"|'[^']*'|\S+)\s*(&&|;)\s*)+/, "")
|
|
113
|
+
// Leading settings such as PYTHONPATH=/some/src, which the path shortening below would cut at their last /
|
|
114
|
+
.replace(/^(\w+=("[^"]*"|'[^']*'|\S*)\s+)+/, "")
|
|
115
|
+
.replace(/^\S*\/(?=[^\s/]+(\s|$))/, "");
|
|
116
|
+
return shown.length > 50 ? `${shown.slice(0, 49)}…` : shown;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** What a job is called: the name it was given, otherwise the shortened command. */
|
|
120
|
+
const jobLabel = (job: Job) => (job.name ? truncateToWidth(job.name, 24) : shownCommand(job.command));
|
|
121
|
+
|
|
122
|
+
/** Just the number: the bg prefix is noise once every row is a background job. */
|
|
123
|
+
const shortId = (job: Job) => job.id.replace(/^bg/, "");
|
|
124
|
+
|
|
125
|
+
/** Compiles wake_on, accepting Python's (?i) prefix that models often write but JavaScript only takes as a flag. */
|
|
126
|
+
function wakePattern(source: string): RegExp {
|
|
127
|
+
const insensitive = source.startsWith("(?i)");
|
|
128
|
+
return new RegExp(insensitive ? source.slice(4) : source, insensitive ? "i" : "");
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Runs a command through the registered bash tool, such as a sandbox's, which another extension can't reach directly. */
|
|
132
|
+
async function throughBash(ctx: ExtensionToolContext, command: string, signal: AbortSignal, onData: (d: Buffer) => void): Promise<{ exitCode: number | null }> {
|
|
133
|
+
let seen = "";
|
|
134
|
+
let sent = 0;
|
|
135
|
+
let full: string | undefined;
|
|
136
|
+
const pass = (d: Buffer) => {
|
|
137
|
+
sent += d.length;
|
|
138
|
+
if (d.length) onData(d);
|
|
139
|
+
};
|
|
140
|
+
// Once output outgrows the tail an update holds, bash saves all of it to a file, which is read from where the updates left off
|
|
141
|
+
const fromFile = () => {
|
|
142
|
+
if (!full) return;
|
|
143
|
+
let fd: number;
|
|
144
|
+
try {
|
|
145
|
+
fd = openSync(full, "r");
|
|
146
|
+
} catch {
|
|
147
|
+
// Not created yet; a later update or the read at the end gets it
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
try {
|
|
151
|
+
const d = Buffer.alloc(Math.max(0, fstatSync(fd).size - sent));
|
|
152
|
+
pass(d.subarray(0, readSync(fd, d, 0, d.length, sent)));
|
|
153
|
+
} finally {
|
|
154
|
+
closeSync(fd);
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
const outcome = await ctx.executeTool("bash", { command }, {
|
|
158
|
+
signal,
|
|
159
|
+
onUpdate: (partial) => {
|
|
160
|
+
full ??= (partial.details as any)?.fullOutputPath;
|
|
161
|
+
if (full) return fromFile();
|
|
162
|
+
// Each update holds the output so far, or only its tail from a bash without the file; what follows the previous one is new
|
|
163
|
+
const text = partial.content.map((c: any) => c.text ?? "").join("");
|
|
164
|
+
const anchor = seen.slice(-256);
|
|
165
|
+
const found = text.lastIndexOf(anchor);
|
|
166
|
+
const at = text.startsWith(seen) ? seen.length : found < 0 ? 0 : found + anchor.length;
|
|
167
|
+
pass(Buffer.from(text.slice(at)));
|
|
168
|
+
seen = text;
|
|
169
|
+
},
|
|
170
|
+
});
|
|
171
|
+
// The file is complete only once bash has finished
|
|
172
|
+
fromFile();
|
|
173
|
+
if (signal.aborted) throw new Error("killed");
|
|
174
|
+
const text = outcome.result.content.map((c: any) => c.text ?? "").join("");
|
|
175
|
+
const code = (outcome.result.structuredContent as any)?.exit_code ?? /Command exited with code (\d+)$/.exec(text)?.[1];
|
|
176
|
+
if (code !== undefined) return { exitCode: Number(code) };
|
|
177
|
+
if (outcome.isError) throw new Error(text.trimEnd().split("\n").at(-1) || "bash failed");
|
|
178
|
+
return { exitCode: 0 };
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Thrown by the bash operations below when a command moves to the background, carrying the job and its output so far. */
|
|
182
|
+
class MovedToBackground extends Error {
|
|
183
|
+
constructor(readonly job: { id: string; log: string; started: number }, readonly output: string) {
|
|
184
|
+
super(`moved to background as ${job.id}`);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export default function (pi: ExtensionAPI) {
|
|
189
|
+
const jobs = new Map<string, Job>();
|
|
190
|
+
let next = 1;
|
|
191
|
+
|
|
192
|
+
// While Pi is working, the message is steered in before its next step instead of following up after the whole run,
|
|
193
|
+
// which for a long run left results hours late and woke Pi once per stale message when the run ended.
|
|
194
|
+
// triggerWakes counts those that ask for a turn, so a non-interactive run knows one is queued for it
|
|
195
|
+
let triggerWakes = 0;
|
|
196
|
+
// Jobs that have ended but not reported yet: the report waits for the log to close, so the exit wait must too
|
|
197
|
+
let ending = 0;
|
|
198
|
+
const wake = (content: string, details: { headline: string; last: string; error: boolean }, triggerTurn = true) => {
|
|
199
|
+
if (triggerTurn) triggerWakes++;
|
|
200
|
+
return pi.sendMessage({ customType: "background-job", content, display: true, details }, { triggerTurn, deliverAs: "steer" });
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
// Jobs started in the same turn usually belong together, like several benchmarks to compare. While some of them
|
|
204
|
+
// still run, a successful one's result is added to the conversation without waking Pi, so it answers once at the
|
|
205
|
+
// end instead of after each job. A job that runs on too long doesn't hold the others back for more than GROUP_HOLD_MS.
|
|
206
|
+
let turn = 0;
|
|
207
|
+
pi.on("turn_start", async () => {
|
|
208
|
+
turn++;
|
|
209
|
+
});
|
|
210
|
+
const holds = new Map<number, NodeJS.Timeout>();
|
|
211
|
+
const runningInGroup = (job: Job) =>
|
|
212
|
+
[...jobs.values()].filter((other) => other !== job && other.group === job.group && other.status === "running" && !other.watched);
|
|
213
|
+
const report = (job: Job, content: string, details: { headline: string; last: string; error: boolean }) => {
|
|
214
|
+
const others = job.watched ? [] : runningInGroup(job);
|
|
215
|
+
// Only Pi stops jobs, with bg_kill, so it already knows; the message is added without waking it again
|
|
216
|
+
if (job.status === "killed") {
|
|
217
|
+
if (others.length === 0) {
|
|
218
|
+
clearTimeout(holds.get(job.group));
|
|
219
|
+
holds.delete(job.group);
|
|
220
|
+
}
|
|
221
|
+
return wake(content, details, false);
|
|
222
|
+
}
|
|
223
|
+
// A failure wakes Pi straight away, so it can react before the rest of the group finishes
|
|
224
|
+
if (others.length === 0 || details.error) {
|
|
225
|
+
clearTimeout(holds.get(job.group));
|
|
226
|
+
holds.delete(job.group);
|
|
227
|
+
return wake(content, details);
|
|
228
|
+
}
|
|
229
|
+
wake(`${content}\n(Still running from the same turn: ${others.map((other) => other.id).join(", ")}; you'll be woken when they finish.)`, details, false);
|
|
230
|
+
if (holds.has(job.group)) return;
|
|
231
|
+
holds.set(job.group, setTimeout(() => {
|
|
232
|
+
holds.delete(job.group);
|
|
233
|
+
const still = runningInGroup(job);
|
|
234
|
+
if (still.length === 0) return;
|
|
235
|
+
wake(`Background jobs from the same turn are still running after ${GROUP_HOLD_MS / 60_000} minutes: ${still.map((other) => other.id).join(", ")}. The results of the ones that finished are above; you'll get a message when each of these finishes.`, {
|
|
236
|
+
headline: `${still.map((other) => shortId(other)).join(", ")} still running`,
|
|
237
|
+
last: "",
|
|
238
|
+
error: false,
|
|
239
|
+
});
|
|
240
|
+
}, GROUP_HOLD_MS));
|
|
241
|
+
};
|
|
242
|
+
|
|
243
|
+
// Wakes the agent with output lines matching pattern, batched per second and capped per job
|
|
244
|
+
const watcher = (job: Job, pattern: RegExp) => {
|
|
245
|
+
let partial = "";
|
|
246
|
+
let pending: string[] = [];
|
|
247
|
+
let timer: NodeJS.Timeout | undefined;
|
|
248
|
+
let wakes = 0;
|
|
249
|
+
const flush = () => {
|
|
250
|
+
timer = undefined;
|
|
251
|
+
// Once the job has ended, its final message carries the log tail instead
|
|
252
|
+
if (job.status !== "running") return;
|
|
253
|
+
wakes++;
|
|
254
|
+
const capped = wakes === MAX_WAKES ? `\n(Reached ${MAX_WAKES} wake-ups; further matches are ignored, use bg_status to check.)` : "";
|
|
255
|
+
wake(`Background job ${job.id} output matched /${pattern.source}/ (still running):\n${pending.slice(-TAIL_LINES).join("\n")}${capped}`, {
|
|
256
|
+
headline: `${shortId(job)} matched /${pattern.source}/`,
|
|
257
|
+
last: pending[pending.length - 1] ?? "",
|
|
258
|
+
error: false,
|
|
259
|
+
});
|
|
260
|
+
pending = [];
|
|
261
|
+
};
|
|
262
|
+
return (data: Buffer) => {
|
|
263
|
+
if (wakes >= MAX_WAKES) return;
|
|
264
|
+
const lines = (partial + data.toString("utf8")).split(/\r?\n|\r/);
|
|
265
|
+
partial = lines.pop() ?? "";
|
|
266
|
+
const hits = lines.filter((line) => pattern.test(line));
|
|
267
|
+
if (hits.length === 0) return;
|
|
268
|
+
pending.push(...hits);
|
|
269
|
+
timer ??= setTimeout(flush, WAKE_DEBOUNCE_MS);
|
|
270
|
+
};
|
|
271
|
+
};
|
|
272
|
+
|
|
273
|
+
// One line per running job above the input, with its elapsed time and latest output
|
|
274
|
+
const running = () => [...jobs.values()].filter((job) => job.status === "running");
|
|
275
|
+
// The job open in /bg, left out of the jobs line meanwhile so it isn't shown twice
|
|
276
|
+
let viewing: Job | undefined;
|
|
277
|
+
// "full" (the default), "compact" without the output, or "off", set with "background": { "jobs": ... } in pi's settings.json
|
|
278
|
+
const jobsLine = () => (pi.getSettings() as { background?: { jobs?: string } }).background?.jobs ?? "full";
|
|
279
|
+
// Set with "background": { "exitWait": <minutes> }; 0 waits with no limit, for very long jobs, as opencode run does
|
|
280
|
+
const exitWaitMs = () => {
|
|
281
|
+
const minutes = (pi.getSettings() as { background?: { exitWait?: unknown } }).background?.exitWait;
|
|
282
|
+
if (typeof minutes !== "number" || minutes < 0) return EXIT_WAIT_MINUTES * 60_000;
|
|
283
|
+
return minutes === 0 ? Infinity : minutes * 60_000;
|
|
284
|
+
};
|
|
285
|
+
// Shortcut that moves a running bash command to the background, set with "background": { "key": ... } ("off" disables it)
|
|
286
|
+
const moveKey = (): KeyId | undefined => {
|
|
287
|
+
const raw = (pi.getSettings() as { background?: { key?: unknown } }).background?.key;
|
|
288
|
+
if (raw === false) return undefined;
|
|
289
|
+
if (typeof raw !== "string") return Key.ctrl("b");
|
|
290
|
+
const key = raw.trim().toLowerCase();
|
|
291
|
+
if (!key || key === "off") return undefined;
|
|
292
|
+
return key as KeyId;
|
|
293
|
+
};
|
|
294
|
+
// The widget is set once per session and redrawn in place: setting it again would move it below the widgets other
|
|
295
|
+
// extensions added since, while running jobs belong at the top, next to what Pi is doing now
|
|
296
|
+
let redrawJobs = () => {};
|
|
297
|
+
let ticker: NodeJS.Timeout | undefined;
|
|
298
|
+
const showJobs = () => {
|
|
299
|
+
// A running job's elapsed time and latest output change every second
|
|
300
|
+
if (running().length > 0) ticker ??= setInterval(() => redrawJobs(), 1000);
|
|
301
|
+
else {
|
|
302
|
+
clearInterval(ticker);
|
|
303
|
+
ticker = undefined;
|
|
304
|
+
}
|
|
305
|
+
redrawJobs();
|
|
306
|
+
};
|
|
307
|
+
// Running bash commands that the move shortcut can push to the background now, by tool call id, once they have run for
|
|
308
|
+
// HINT_AFTER_MS. Shared so pi-polish can show the hint under the command's row instead of in the jobs line.
|
|
309
|
+
const hinted = new Map<string, () => void>();
|
|
310
|
+
(globalThis as any)[Symbol.for("pi-background.movable")] = hinted;
|
|
311
|
+
// How many jobs are running, so pi-goal-loop waits for them before checking a goal
|
|
312
|
+
(globalThis as any)[Symbol.for("pi-background.running")] = () => running().length;
|
|
313
|
+
(globalThis as any)[Symbol.for("pi-background.moveKey")] = moveKey;
|
|
314
|
+
let stopMoveKey = () => {};
|
|
315
|
+
const jobsWidget = (theme: any, ctx: ExtensionContext) => {
|
|
316
|
+
// Maps each rendered job row index to a job id (or "" for the collapsed summary line) so clicks open /bg
|
|
317
|
+
let rowTargets: string[] = [];
|
|
318
|
+
return {
|
|
319
|
+
invalidate() {},
|
|
320
|
+
handleMouse(event: TuiMouseEvent) {
|
|
321
|
+
if (event.type !== "click" || event.button !== "left" || viewerOpen) return undefined;
|
|
322
|
+
const target = rowTargets[event.y];
|
|
323
|
+
if (target === undefined) return undefined;
|
|
324
|
+
void showJob(target, ctx);
|
|
325
|
+
return { handled: true };
|
|
326
|
+
},
|
|
327
|
+
render(width: number) {
|
|
328
|
+
if (jobsLine() === "off") {
|
|
329
|
+
rowTargets = [];
|
|
330
|
+
return [];
|
|
331
|
+
}
|
|
332
|
+
const live = running().filter((job) => job !== viewing);
|
|
333
|
+
const silentFor = (job: Job) => Date.now() - (job.lastOutput ?? job.started);
|
|
334
|
+
let lines: string[];
|
|
335
|
+
if (live.length <= MAX_SHOWN_JOBS) {
|
|
336
|
+
rowTargets = live.map((job) => job.id);
|
|
337
|
+
lines = live.map((job) => {
|
|
338
|
+
const silent = silentFor(job);
|
|
339
|
+
const detail = silent >= SILENT_AFTER_MS ? theme.fg("warning", ` · no output for ${duration(silent)}`) : jobsLine() === "full" && job.lastLine ? theme.fg("dim", ` · ${job.lastLine}`) : "";
|
|
340
|
+
const text = theme.fg("accent", "● ") + theme.fg("toolTitle", `${shortId(job)} `) + theme.bold(jobLabel(job)) + theme.fg("dim", ` · ${elapsed(job)}`) + detail;
|
|
341
|
+
return truncateToWidth(text, width);
|
|
342
|
+
});
|
|
343
|
+
} else {
|
|
344
|
+
// Past a few jobs, a line each crowds the input, so they share one with just the count, and a warning when
|
|
345
|
+
// some have gone quiet, since they may be stuck; /bg has the rest
|
|
346
|
+
rowTargets = [""];
|
|
347
|
+
const silent = live.filter((job) => silentFor(job) >= SILENT_AFTER_MS).length;
|
|
348
|
+
const warning = silent ? theme.fg("warning", ` · ${silent} silent for ${SILENT_AFTER_MS / 60_000}m+`) : "";
|
|
349
|
+
lines = [truncateToWidth(theme.fg("accent", "● ") + theme.bold(`${live.length} jobs`) + warning, width)];
|
|
350
|
+
}
|
|
351
|
+
const key = moveKey();
|
|
352
|
+
if (key && hinted.size > 0 && !(globalThis as any)[Symbol.for("pi-polish.showsMoveHint")]) lines.push(theme.fg("dim", ` ${key} to run in background`));
|
|
353
|
+
return lines;
|
|
354
|
+
},
|
|
355
|
+
};
|
|
356
|
+
};
|
|
357
|
+
|
|
358
|
+
const find = (id: string): Job => {
|
|
359
|
+
const job = jobs.get(id);
|
|
360
|
+
if (!job) throw new Error(`No background job ${id}; known: ${[...jobs.keys()].join(", ") || "none"}`);
|
|
361
|
+
return job;
|
|
362
|
+
};
|
|
363
|
+
|
|
364
|
+
// Compact, Claude-Code-style rows instead of pi's default boxes: quiet grey once done, with a dot only while running
|
|
365
|
+
// or failed. A branch is " └ text" in dim, with long and extra lines wrapped under the text instead of at the left edge
|
|
366
|
+
const branch = (theme: any, text: string, head?: string) => ({
|
|
367
|
+
invalidate() {},
|
|
368
|
+
render: (width: number) => [
|
|
369
|
+
...(head ? [truncateToWidth(head, width)] : []),
|
|
370
|
+
...wrapTextWithAnsi(text, Math.max(10, width - 4)).map((line, i) => theme.fg("dim", `${i === 0 ? " └ " : " "}${line}`)),
|
|
371
|
+
],
|
|
372
|
+
});
|
|
373
|
+
pi.registerMessageRenderer("background-job", (message, { expanded }, theme) => {
|
|
374
|
+
const d = (message.details ?? {}) as { headline?: string; last?: string; error?: boolean };
|
|
375
|
+
const title = d.headline ?? "";
|
|
376
|
+
const head = d.error ? theme.fg("error", "● ") + theme.fg("toolTitle", title) : ` ${theme.fg("dim", title)}`;
|
|
377
|
+
return branch(theme, expanded ? String(message.content) : (d.last ?? ""), head);
|
|
378
|
+
});
|
|
379
|
+
// One line, like pi-polish's shell rows; expanded (ctrl+o) shows the whole text, wrapped under the row
|
|
380
|
+
const row = (theme: any, text: string, context: any, full = text) => ({
|
|
381
|
+
invalidate() {},
|
|
382
|
+
render(width: number) {
|
|
383
|
+
const color = context.isError ? "error" : context.executionStarted && context.isPartial ? "accent" : undefined;
|
|
384
|
+
const mark = color ? theme.fg(color, "● ") : " ";
|
|
385
|
+
const paint = (line: string) => theme.fg(color ? "toolTitle" : "dim", line);
|
|
386
|
+
if (!context.expanded) return [mark + paint(truncateToWidth(text, Math.max(10, width - 2)))];
|
|
387
|
+
return wrapTextWithAnsi(full, Math.max(10, width - 2)).map((line, i) => (i === 0 ? mark : " ") + paint(line));
|
|
388
|
+
},
|
|
389
|
+
});
|
|
390
|
+
const note = (theme: any, result: any, expanded: boolean) => {
|
|
391
|
+
const text = result.content?.map((c: any) => c.text ?? "").join("\n") ?? "";
|
|
392
|
+
// Collapsed: first sentence only ("Started bg1"), without the log path
|
|
393
|
+
const short = text.split("\n")[0].split(";")[0];
|
|
394
|
+
return branch(theme, expanded ? text : short);
|
|
395
|
+
};
|
|
396
|
+
|
|
397
|
+
// Starts tracking a job: its output goes to a log and the jobs line, and Pi is told when run's promise settles.
|
|
398
|
+
// A bash command that moves to the background brings its start time and the output it printed before.
|
|
399
|
+
const startJob = (
|
|
400
|
+
command: string,
|
|
401
|
+
pattern: RegExp | undefined,
|
|
402
|
+
controller: AbortController,
|
|
403
|
+
run: (onData: (d: Buffer) => void) => Promise<{ exitCode: number | null }>,
|
|
404
|
+
earlier?: { started: number; output: Buffer; lastOutput?: number },
|
|
405
|
+
name?: string,
|
|
406
|
+
) => {
|
|
407
|
+
const id = `bg${next++}`;
|
|
408
|
+
const dir = join(tmpdir(), "pi-bg");
|
|
409
|
+
mkdirSync(dir, { recursive: true });
|
|
410
|
+
const log = join(dir, `${process.pid}-${id}.log`);
|
|
411
|
+
const out = createWriteStream(log);
|
|
412
|
+
const job: Job = { id, name, command, log, started: earlier?.started ?? Date.now(), controller, status: "running", group: turn, watched: Boolean(pattern) };
|
|
413
|
+
jobs.set(id, job);
|
|
414
|
+
|
|
415
|
+
const watch = pattern ? watcher(job, pattern) : undefined;
|
|
416
|
+
// A job that hangs without output would otherwise go unnoticed until the user looks, and pi-goal-loop waits for it.
|
|
417
|
+
// Pi is woken once per quiet spell; output starts the count again
|
|
418
|
+
const silence = setTimeout(() => {
|
|
419
|
+
const quiet = `${SILENT_AFTER_MS / 60_000} minutes`;
|
|
420
|
+
wake(`Background job ${id} is still running but has printed nothing for ${quiet}. Check whether it's stuck, with bg_status or its CPU use in ps: if it is, stop it with bg_kill and fix the cause; if it's working, carry on, and you'll be woken when it exits.`, {
|
|
421
|
+
headline: `${shortId(job)} ${jobLabel(job)} silent for ${quiet}`,
|
|
422
|
+
last: "",
|
|
423
|
+
error: false,
|
|
424
|
+
});
|
|
425
|
+
}, SILENT_AFTER_MS);
|
|
426
|
+
const onData = (d: Buffer) => {
|
|
427
|
+
silence.refresh();
|
|
428
|
+
out.write(d);
|
|
429
|
+
watch?.(d);
|
|
430
|
+
job.lastOutput = Date.now();
|
|
431
|
+
const last = d.toString("utf8").split("\n").map(cleanLine).filter((line) => line.trim()).at(-1)?.trim();
|
|
432
|
+
if (last) job.lastLine = last;
|
|
433
|
+
};
|
|
434
|
+
if (earlier?.output.length) {
|
|
435
|
+
onData(earlier.output);
|
|
436
|
+
job.lastOutput = earlier.lastOutput;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
run(onData)
|
|
440
|
+
.then(({ exitCode }) => {
|
|
441
|
+
job.status = "exited";
|
|
442
|
+
job.exitCode = exitCode;
|
|
443
|
+
})
|
|
444
|
+
.catch((err: Error) => {
|
|
445
|
+
job.status = controller.signal.aborted ? "killed" : "failed";
|
|
446
|
+
out.write(`\n[bg] ${err.message}\n`);
|
|
447
|
+
})
|
|
448
|
+
.finally(() => {
|
|
449
|
+
clearTimeout(silence);
|
|
450
|
+
job.ended = Date.now();
|
|
451
|
+
showJobs();
|
|
452
|
+
ending++;
|
|
453
|
+
out.end(() => {
|
|
454
|
+
ending--;
|
|
455
|
+
// A kill from session shutdown has no session left to notify
|
|
456
|
+
if (job.status === "killed" && !jobs.has(id)) return;
|
|
457
|
+
report(job, `Background job finished: ${summary(job)}\nLast lines:\n${tail(log, TAIL_LINES)}`, {
|
|
458
|
+
headline: `${shortId(job)} ${jobLabel(job)} ${job.status === "exited" ? `exited ${job.exitCode}` : job.status} · ${elapsed(job)}`,
|
|
459
|
+
last: tail(log, 1),
|
|
460
|
+
error: job.status !== "exited" || job.exitCode !== 0,
|
|
461
|
+
});
|
|
462
|
+
});
|
|
463
|
+
});
|
|
464
|
+
|
|
465
|
+
showJobs();
|
|
466
|
+
return job;
|
|
467
|
+
};
|
|
468
|
+
|
|
469
|
+
// Pi's bash, except that a command still running after AUTO_BACKGROUND_SECS becomes a background job
|
|
470
|
+
// instead of blocking the turn until it ends or times out. The command keeps running in the same
|
|
471
|
+
// process; its output so far goes to the job's log, and Pi gets the usual message when it exits.
|
|
472
|
+
const handoff = (local: BashOperations, toolCallId: string): BashOperations => ({
|
|
473
|
+
exec(command, cwd, options) {
|
|
474
|
+
// Pi's own check, which its exec would otherwise have made
|
|
475
|
+
if (options.timeout !== undefined && !(Number.isFinite(options.timeout) && options.timeout > 0)) {
|
|
476
|
+
return Promise.reject(new Error("Invalid timeout: must be a finite number of seconds"));
|
|
477
|
+
}
|
|
478
|
+
const started = Date.now();
|
|
479
|
+
// Its own signal, so a job outlives the turn; until then the turn's abort is passed on
|
|
480
|
+
const controller = new AbortController();
|
|
481
|
+
const forward = () => controller.abort();
|
|
482
|
+
if (options.signal?.aborted) controller.abort();
|
|
483
|
+
options.signal?.addEventListener("abort", forward, { once: true });
|
|
484
|
+
// The output so far goes to the job's log; only its last TAIL_BYTES are kept, like the log tails
|
|
485
|
+
let earlier = Buffer.alloc(0);
|
|
486
|
+
let lastOutput: number | undefined;
|
|
487
|
+
let sink = (d: Buffer) => {
|
|
488
|
+
earlier = Buffer.concat([earlier, d]).subarray(-TAIL_BYTES);
|
|
489
|
+
lastOutput = Date.now();
|
|
490
|
+
options.onData(d);
|
|
491
|
+
};
|
|
492
|
+
const env = { ...(options.env ?? process.env), PYTHONUNBUFFERED: "1" };
|
|
493
|
+
// A timeout moves the command to the background sooner rather than stopping it, so its work isn't lost
|
|
494
|
+
const after = Math.min(options.timeout ?? AUTO_BACKGROUND_SECS, AUTO_BACKGROUND_SECS);
|
|
495
|
+
const running = local.exec(command, cwd, { onData: (d) => sink(d), signal: controller.signal, env });
|
|
496
|
+
return new Promise((resolve, reject) => {
|
|
497
|
+
let timer: NodeJS.Timeout | undefined;
|
|
498
|
+
let hint: NodeJS.Timeout | undefined;
|
|
499
|
+
const settle = () => {
|
|
500
|
+
clearTimeout(timer);
|
|
501
|
+
clearTimeout(hint);
|
|
502
|
+
options.signal?.removeEventListener("abort", forward);
|
|
503
|
+
if (hinted.delete(toolCallId)) redrawJobs();
|
|
504
|
+
};
|
|
505
|
+
const move = () => {
|
|
506
|
+
settle();
|
|
507
|
+
const output = earlier;
|
|
508
|
+
const job = startJob(command, undefined, controller, (onData) => {
|
|
509
|
+
sink = onData;
|
|
510
|
+
return running;
|
|
511
|
+
}, { started, output, lastOutput });
|
|
512
|
+
reject(new MovedToBackground(job, output.toString("utf8")));
|
|
513
|
+
};
|
|
514
|
+
timer = setTimeout(move, after * 1000);
|
|
515
|
+
hint = setTimeout(() => {
|
|
516
|
+
if (!moveKey()) return;
|
|
517
|
+
hinted.set(toolCallId, move);
|
|
518
|
+
redrawJobs();
|
|
519
|
+
}, HINT_AFTER_MS);
|
|
520
|
+
running.then(resolve, reject).finally(settle);
|
|
521
|
+
});
|
|
522
|
+
},
|
|
523
|
+
});
|
|
524
|
+
// Only Pi's own bash is wrapped; one that another extension replaced, such as a sandbox's, is left alone. By
|
|
525
|
+
// session_start every extension has registered its tools, whichever order they loaded in.
|
|
526
|
+
let wrapped = false;
|
|
527
|
+
// bg_run then runs its jobs through that bash, so they stay inside such a sandbox
|
|
528
|
+
let foreignBash = false;
|
|
529
|
+
pi.on("session_start", async () => {
|
|
530
|
+
if (wrapped) return;
|
|
531
|
+
foreignBash = !pi.getAllTools().find((tool) => tool.name === "bash")?.sourceInfo.path.startsWith("builtin:");
|
|
532
|
+
if (foreignBash) return;
|
|
533
|
+
wrapped = true;
|
|
534
|
+
const pisBash = createBashToolDefinition(process.cwd());
|
|
535
|
+
pi.registerTool({
|
|
536
|
+
...pisBash,
|
|
537
|
+
promptGuidelines: [
|
|
538
|
+
...(pisBash.promptGuidelines ?? []),
|
|
539
|
+
`A bash command still running after ${AUTO_BACKGROUND_SECS} seconds, or after its timeout if that is shorter, moves to the background on its own, as if started with bg_run, and you get its job id instead of its output; it is not stopped. Still start a command you expect to take that long with bg_run, so you choose wake_on and the turn isn't held up first.`,
|
|
540
|
+
],
|
|
541
|
+
async execute(toolCallId, params, signal, onUpdate, ctx) {
|
|
542
|
+
// Built per call from the same settings Pi builds its own bash from
|
|
543
|
+
const { shellPath, shellCommandPrefix } = pi.getSettings();
|
|
544
|
+
const bash = createBashToolDefinition(ctx.cwd, { commandPrefix: shellCommandPrefix, operations: handoff(createLocalBashOperations({ shellPath }), toolCallId) });
|
|
545
|
+
try {
|
|
546
|
+
return await bash.execute(toolCallId, params, signal, onUpdate, ctx);
|
|
547
|
+
} catch (err) {
|
|
548
|
+
if (!(err instanceof MovedToBackground)) throw err;
|
|
549
|
+
const { id, log, started } = err.job;
|
|
550
|
+
const soFar = err.output.trimEnd().split("\n").slice(-TAIL_LINES).join("\n") || "(no output)";
|
|
551
|
+
const text = `Still running after ${duration(Date.now() - started)}, so it moved to the background as ${id}. You will be notified when it exits; check it with bg_status, or stop it with bg_kill if it shouldn't take this long.\nOutput so far:\n${soFar}\nlog: ${log}`;
|
|
552
|
+
return { content: [{ type: "text", text }], details: undefined };
|
|
553
|
+
}
|
|
554
|
+
},
|
|
555
|
+
});
|
|
556
|
+
});
|
|
557
|
+
|
|
558
|
+
pi.registerTool({
|
|
559
|
+
name: "bg_run",
|
|
560
|
+
label: "Background",
|
|
561
|
+
description:
|
|
562
|
+
"Start a shell command in the background and return immediately with a job id. Output goes to a log file. " +
|
|
563
|
+
"When the command exits you automatically receive a message with its exit code and the last log lines, so do not poll or sleep waiting for it.",
|
|
564
|
+
promptSnippet: "Run long shell commands (downloads, builds, long test suites) in the background",
|
|
565
|
+
promptGuidelines: [
|
|
566
|
+
"Use bg_run instead of bash for any command that may take longer than about 30 seconds, in particular: downloading large files, datasets, dumps or model weights; " +
|
|
567
|
+
"installing heavy packages (torch, tensorflow, CUDA libraries, transformers, large requirement sets) or creating environments with them; cloning large repositories; " +
|
|
568
|
+
"builds, compiles and docker builds; full test suites of non-trivial projects; training, evaluation, benchmark and data-processing scripts; and anything that sleeps, waits or polls.",
|
|
569
|
+
"Run quick checks, short scripts and test files that likely finish within a minute with bash, even when you're not sure: their result is needed now, and each bg_run job reports back as a separate message.",
|
|
570
|
+
"After bg_run, continue with independent work or end your turn; a message with the exit code and log tail arrives automatically when the job exits, so never sleep, poll or tail the log to wait for it.",
|
|
571
|
+
"Keep using bash for quick commands whose output you need right away, such as git, ls, cat, grep, find, file inspection and short checks.",
|
|
572
|
+
"Pass wake_on only when you must act before a bg_run job ends, such as a server becoming ready to test against, or when the user asked to follow its progress. Make it a pattern for that one event, which matches once, not a line the job prints for every item, file, epoch or step. To report a job's result, leave wake_on out: the exit message already brings the exit code and last lines.",
|
|
573
|
+
"Don't redirect a bg_run command's output to a file (> file, 2>&1, nohup): bg_run already saves all of it to the job's log, and redirecting hides the job's progress from the user and from wake_on. If the output should be kept, tell the user where the job's log is.",
|
|
574
|
+
"bg_run starts only after the other tool calls in the same reply have finished, so editing a file and starting a job that uses it in one reply is safe.",
|
|
575
|
+
"Always pass name with a two or three word label for every bg_run job, so the jobs line reads as what the job is for rather than as its command.",
|
|
576
|
+
"Use bg_status to check progress of a bg_run job and bg_kill to stop one.",
|
|
577
|
+
"Unless the user explicitly asks for that bash command, never wait, poll or sleep in bash (while/until loops with sleep, watch, repeated status checks), not even as part of a larger command; start the wait with bg_run and pass wake_on to be woken when the awaited output appears.",
|
|
578
|
+
"Unless the user explicitly asks otherwise, start long-running processes (training or evaluation runs, servers, watchers) with bg_run, not with & or nohup in bash followed by sleep.",
|
|
579
|
+
],
|
|
580
|
+
// Runs after the edits in the same reply, so the job starts from the code pi just wrote
|
|
581
|
+
executionMode: "sequential",
|
|
582
|
+
renderShell: "self",
|
|
583
|
+
renderCall: (args: any, theme, context) => {
|
|
584
|
+
const command = String(args?.command ?? "");
|
|
585
|
+
// Collapsed, without leading settings such as PYTHONPATH=/some/src, like the jobs line; ctrl+o shows them
|
|
586
|
+
const short = shortCommand(command, args?.cwd ?? process.cwd()).replace(/^(\w+=("[^"]*"|'[^']*'|\S*)\s+)+/, "");
|
|
587
|
+
return row(theme, `Background $ ${short}`, context, `Background $ ${command.trim()}`);
|
|
588
|
+
},
|
|
589
|
+
renderResult: (result, { expanded }, theme) => note(theme, result, expanded),
|
|
590
|
+
parameters: Type.Object({
|
|
591
|
+
command: Type.String({ description: "Shell command to run" }),
|
|
592
|
+
name: Type.Optional(Type.String({ description: "Short label shown in the jobs line and dashboard instead of the command, e.g. 'build docs'" })),
|
|
593
|
+
cwd: Type.Optional(Type.String({ description: "Working directory (defaults to the session cwd)" })),
|
|
594
|
+
wake_on: Type.Optional(
|
|
595
|
+
Type.String({
|
|
596
|
+
description: `Regex; also wake you while the job runs whenever an output line matches, e.g. 'listening on|ready'. Matches within a second are batched; at most ${MAX_WAKES} wake-ups per job.`,
|
|
597
|
+
}),
|
|
598
|
+
),
|
|
599
|
+
}),
|
|
600
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
601
|
+
// Models use a job that sleeps first as a timer, to wait for another job, although they're woken when it exits
|
|
602
|
+
if (/^\s*sleep\s+[\d.]+[smh]?\s*($|;|&&|\n)/.test(params.command)) {
|
|
603
|
+
throw new Error("Don't start a job with sleep to wait: you're woken automatically when a background job exits or its output matches wake_on. Run the command itself, or end your turn to wait.");
|
|
604
|
+
}
|
|
605
|
+
const pattern = params.wake_on ? wakePattern(params.wake_on) : undefined;
|
|
606
|
+
const controller = new AbortController();
|
|
607
|
+
// The same shell and command prefix as Pi's own bash, from settings.json; without shellPath, Windows can pick WSL's bash
|
|
608
|
+
const { shellPath, shellCommandPrefix } = pi.getSettings();
|
|
609
|
+
const ops = createLocalBashOperations({ shellPath });
|
|
610
|
+
// Output goes to a pipe, where Python would buffer prints until it exits; unbuffered, the latest line and wake_on stay live
|
|
611
|
+
const command = `export PYTHONUNBUFFERED=1; ${params.command}`;
|
|
612
|
+
const { id, log } = startJob(params.command, pattern, controller, (onData) =>
|
|
613
|
+
foreignBash
|
|
614
|
+
? throughBash(ctx, params.cwd ? `cd '${params.cwd.replace(/'/g, `'\\''`)}' && ${command}` : command, controller.signal, onData)
|
|
615
|
+
: ops.exec(shellCommandPrefix ? `${shellCommandPrefix}\n${command}` : command, params.cwd ?? ctx.cwd, { onData, signal: controller.signal }),
|
|
616
|
+
undefined,
|
|
617
|
+
params.name,
|
|
618
|
+
);
|
|
619
|
+
return { content: [{ type: "text", text: `Started ${id}; log: ${log}. You will be notified when it exits.` }], details: { id, log } };
|
|
620
|
+
},
|
|
621
|
+
});
|
|
622
|
+
|
|
623
|
+
pi.registerTool({
|
|
624
|
+
name: "bg_status",
|
|
625
|
+
label: "Background status",
|
|
626
|
+
description: "List background jobs, or show one job's state and the tail of its log.",
|
|
627
|
+
renderShell: "self",
|
|
628
|
+
renderCall: (args: any, theme, context) => row(theme, `Background status ${args?.id ?? "(all)"}`, context),
|
|
629
|
+
renderResult: (result, { expanded }, theme) => note(theme, result, expanded),
|
|
630
|
+
parameters: Type.Object({
|
|
631
|
+
id: Type.Optional(Type.String({ description: "Job id such as bg1; omit to list all jobs" })),
|
|
632
|
+
lines: Type.Optional(Type.Number({ description: `Log lines to show (default ${TAIL_LINES})` })),
|
|
633
|
+
}),
|
|
634
|
+
async execute(_toolCallId, params) {
|
|
635
|
+
if (!params.id) {
|
|
636
|
+
const text = [...jobs.values()].map(summary).join("\n") || "No background jobs.";
|
|
637
|
+
return { content: [{ type: "text", text }], details: {} };
|
|
638
|
+
}
|
|
639
|
+
const job = find(params.id);
|
|
640
|
+
return { content: [{ type: "text", text: `${summary(job)}\n${tail(job.log, params.lines ?? TAIL_LINES)}` }], details: {} };
|
|
641
|
+
},
|
|
642
|
+
});
|
|
643
|
+
|
|
644
|
+
pi.registerTool({
|
|
645
|
+
name: "bg_kill",
|
|
646
|
+
label: "Background kill",
|
|
647
|
+
description: "Stop a running background job and its child processes.",
|
|
648
|
+
renderShell: "self",
|
|
649
|
+
renderCall: (args: any, theme, context) => row(theme, `Background kill ${args?.id ?? ""}`, context),
|
|
650
|
+
renderResult: (result, { expanded }, theme) => note(theme, result, expanded),
|
|
651
|
+
parameters: Type.Object({ id: Type.String({ description: "Job id such as bg1" }) }),
|
|
652
|
+
async execute(_toolCallId, params) {
|
|
653
|
+
const job = find(params.id);
|
|
654
|
+
if (job.status !== "running") return { content: [{ type: "text", text: `${job.id} already ${job.status}` }], details: {} };
|
|
655
|
+
job.controller.abort();
|
|
656
|
+
return { content: [{ type: "text", text: `Stopping ${job.id}` }], details: {} };
|
|
657
|
+
},
|
|
658
|
+
});
|
|
659
|
+
|
|
660
|
+
// "/bg 2" works as well as "/bg bg2"
|
|
661
|
+
const normalizeJobId = (raw: string) => raw.trim().toLowerCase().replace(/^(\d+)$/, "bg$1");
|
|
662
|
+
|
|
663
|
+
let viewerOpen = false;
|
|
664
|
+
// Shows a job's output in place of the input until esc, refreshed every second while it runs
|
|
665
|
+
const showJob = async (args: string, ctx: ExtensionContext) => {
|
|
666
|
+
if (!ctx.hasUI || viewerOpen) return;
|
|
667
|
+
const trimmed = args.trim();
|
|
668
|
+
const killMatch = /^kill(?:\s+(.+))?$/i.exec(trimmed);
|
|
669
|
+
if (killMatch) {
|
|
670
|
+
const idArg = killMatch[1]?.trim();
|
|
671
|
+
if (!idArg) return ctx.ui.notify("Usage: /bg kill <id>", "info");
|
|
672
|
+
const target = jobs.get(normalizeJobId(idArg));
|
|
673
|
+
if (!target) return ctx.ui.notify(`No background job ${idArg}; there's ${[...jobs.keys()].join(", ") || "none"}`, "warning");
|
|
674
|
+
if (target.status !== "running") return ctx.ui.notify(`${target.id} already ${target.status}`, "info");
|
|
675
|
+
target.controller.abort();
|
|
676
|
+
return ctx.ui.notify(`Stopping ${target.id}`, "info");
|
|
677
|
+
}
|
|
678
|
+
if (jobs.size === 0) return ctx.ui.notify("No background jobs yet", "info");
|
|
679
|
+
const wanted = trimmed ? normalizeJobId(trimmed) : "";
|
|
680
|
+
let job: Job | undefined = wanted ? jobs.get(wanted) : jobs.size === 1 ? [...jobs.values()][0] : undefined;
|
|
681
|
+
if (wanted && !job) return ctx.ui.notify(`No background job ${trimmed}; there's ${[...jobs.keys()].join(", ")}`, "warning");
|
|
682
|
+
viewerOpen = true;
|
|
683
|
+
try {
|
|
684
|
+
while (true) {
|
|
685
|
+
if (!job) {
|
|
686
|
+
const all = [...jobs.values()].reverse();
|
|
687
|
+
// Running jobs first, then the latest finished ones
|
|
688
|
+
const listed = [...all.filter((other) => other.status === "running"), ...all.filter((other) => other.status !== "running").slice(0, MAX_LISTED_FINISHED)];
|
|
689
|
+
// Matched by position, since the elapsed time in a label changes while the list is open
|
|
690
|
+
// Ids and commands padded to one width, so the states and times line up
|
|
691
|
+
const idWidth = Math.max(...listed.map((other) => shortId(other).length));
|
|
692
|
+
const commandWidth = Math.max(...listed.map((other) => jobLabel(other).length));
|
|
693
|
+
const options = listed.map((other) => `${shortId(other).padEnd(idWidth)} ${jobLabel(other).padEnd(commandWidth)} · ${state(other)} · ${elapsed(other)}`);
|
|
694
|
+
job = listed[options.indexOf((await ctx.ui.select("Background jobs", options)) ?? "")];
|
|
695
|
+
if (!job) return;
|
|
696
|
+
}
|
|
697
|
+
const shown = job;
|
|
698
|
+
viewing = shown;
|
|
699
|
+
redrawJobs();
|
|
700
|
+
const log = shown.log.replace(homedir(), "~");
|
|
701
|
+
const action = await ctx.ui.custom<"back" | "close">((tui, theme, _kb, done) => {
|
|
702
|
+
// null follows the bottom as new output arrives; a number pins the top visible line while scrolling
|
|
703
|
+
let scrollTop: number | null = null;
|
|
704
|
+
let confirmKill = false;
|
|
705
|
+
const readLines = () => {
|
|
706
|
+
const text = tail(shown.log, SCROLL_LINES);
|
|
707
|
+
return text === "(no output)" ? [] : text.split("\n");
|
|
708
|
+
};
|
|
709
|
+
// At most half the terminal, so the conversation above stays in view
|
|
710
|
+
const pageHeight = () => Math.max(3, Math.min(TAIL_LINES, Math.floor(tui.terminal.rows / 2)));
|
|
711
|
+
const scroll = (delta: number) => {
|
|
712
|
+
const maxTop = Math.max(0, readLines().length - pageHeight());
|
|
713
|
+
const current = scrollTop === null ? maxTop : Math.min(scrollTop, maxTop);
|
|
714
|
+
const target = Math.max(0, Math.min(maxTop, current + delta));
|
|
715
|
+
scrollTop = target >= maxTop ? null : target;
|
|
716
|
+
tui.requestRender();
|
|
717
|
+
};
|
|
718
|
+
const timer = setInterval(() => tui.requestRender(), 1000);
|
|
719
|
+
return {
|
|
720
|
+
dispose: () => clearInterval(timer),
|
|
721
|
+
invalidate() {},
|
|
722
|
+
handleInput: (data: string) => {
|
|
723
|
+
if (confirmKill) {
|
|
724
|
+
confirmKill = false;
|
|
725
|
+
if (data === "x" && shown.status === "running") shown.controller.abort();
|
|
726
|
+
return tui.requestRender();
|
|
727
|
+
}
|
|
728
|
+
if (matchesKey(data, Key.escape) || matchesKey(data, Key.ctrl("c")) || data === "q") return done("close");
|
|
729
|
+
if ((matchesKey(data, Key.left) || matchesKey(data, Key.backspace)) && jobs.size > 1) return done("back");
|
|
730
|
+
if (data === "x" && shown.status === "running") {
|
|
731
|
+
confirmKill = true;
|
|
732
|
+
return tui.requestRender();
|
|
733
|
+
}
|
|
734
|
+
const page = pageHeight();
|
|
735
|
+
if (matchesKey(data, Key.up)) return scroll(-1);
|
|
736
|
+
if (matchesKey(data, Key.down)) return scroll(1);
|
|
737
|
+
if (matchesKey(data, Key.pageUp)) return scroll(-page);
|
|
738
|
+
if (matchesKey(data, Key.pageDown)) return scroll(page);
|
|
739
|
+
if (matchesKey(data, Key.home)) {
|
|
740
|
+
scrollTop = readLines().length > page ? 0 : null;
|
|
741
|
+
return tui.requestRender();
|
|
742
|
+
}
|
|
743
|
+
if (matchesKey(data, Key.end)) {
|
|
744
|
+
scrollTop = null;
|
|
745
|
+
return tui.requestRender();
|
|
746
|
+
}
|
|
747
|
+
},
|
|
748
|
+
// Clicking the title row closes it again, like a click opened it from the jobs line
|
|
749
|
+
handleMouse: (event: TuiMouseEvent) => {
|
|
750
|
+
if (event.type === "wheel" && event.wheelDelta) {
|
|
751
|
+
scroll(event.wheelDelta);
|
|
752
|
+
return { handled: true };
|
|
753
|
+
}
|
|
754
|
+
if (event.type !== "click" || event.button !== "left" || event.y !== 1) return undefined;
|
|
755
|
+
done("close");
|
|
756
|
+
return { handled: true };
|
|
757
|
+
},
|
|
758
|
+
render(width: number) {
|
|
759
|
+
if (confirmKill && shown.status !== "running") confirmKill = false;
|
|
760
|
+
const color = shown.status === "running" ? "accent" : shown.status === "exited" && shown.exitCode === 0 ? "success" : "error";
|
|
761
|
+
const title = theme.fg(color, " ● ") + theme.bold(jobLabel(shown)) + theme.fg("dim", ` ${shortId(shown)}`);
|
|
762
|
+
const status = theme.fg("muted", `${state(shown)} · ${elapsed(shown)} `);
|
|
763
|
+
const gap = Math.max(1, width - visibleWidth(title) - visibleWidth(status));
|
|
764
|
+
const lines = readLines();
|
|
765
|
+
const page = pageHeight();
|
|
766
|
+
const maxTop = Math.max(0, lines.length - page);
|
|
767
|
+
const top = scrollTop === null ? maxTop : Math.min(scrollTop, maxTop);
|
|
768
|
+
const slice = lines.slice(top, top + page);
|
|
769
|
+
const output = slice.length === 0 ? [theme.fg("dim", theme.italic(" no output yet"))] : slice.map((line) => ` ${cleanLine(line)}`);
|
|
770
|
+
const footer = confirmKill
|
|
771
|
+
? theme.fg("warning", ` press x again to kill ${shown.id}`)
|
|
772
|
+
: theme.fg(
|
|
773
|
+
"dim",
|
|
774
|
+
` ${[
|
|
775
|
+
maxTop > 0 ? `↑↓ ${top + 1}–${top + slice.length}/${lines.length}` : "",
|
|
776
|
+
shown.status === "running" ? "x kill" : "",
|
|
777
|
+
jobs.size > 1 ? "← list" : "",
|
|
778
|
+
"esc close",
|
|
779
|
+
log,
|
|
780
|
+
]
|
|
781
|
+
.filter(Boolean)
|
|
782
|
+
.join(" · ")}`,
|
|
783
|
+
);
|
|
784
|
+
const rule = theme.fg(color, "─".repeat(width));
|
|
785
|
+
return [rule, title + " ".repeat(gap) + status, ...output, footer, rule].map((line) => truncateToWidth(line, width));
|
|
786
|
+
},
|
|
787
|
+
};
|
|
788
|
+
});
|
|
789
|
+
viewing = undefined;
|
|
790
|
+
redrawJobs();
|
|
791
|
+
if (action !== "back") return;
|
|
792
|
+
job = undefined;
|
|
793
|
+
}
|
|
794
|
+
} finally {
|
|
795
|
+
viewerOpen = false;
|
|
796
|
+
viewing = undefined;
|
|
797
|
+
redrawJobs();
|
|
798
|
+
}
|
|
799
|
+
};
|
|
800
|
+
pi.registerCommand("bg", {
|
|
801
|
+
description: "Show or stop a background job",
|
|
802
|
+
getArgumentCompletions: (prefix) => {
|
|
803
|
+
const lower = prefix.trimStart().toLowerCase();
|
|
804
|
+
if (lower.startsWith("kill ")) {
|
|
805
|
+
const rest = lower.slice(5).trim();
|
|
806
|
+
const matching = running().filter((job) => job.id.startsWith(rest));
|
|
807
|
+
return matching.length ? matching.map((job) => ({ value: `kill ${shortId(job)}`, label: `kill ${shortId(job)}`, description: jobLabel(job) })) : null;
|
|
808
|
+
}
|
|
809
|
+
const matching = [...jobs.values()].filter((job) => job.id.startsWith(lower.trim()));
|
|
810
|
+
const items = matching.map((job) => ({ value: job.id, label: shortId(job), description: `${jobLabel(job)} · ${state(job)}` }));
|
|
811
|
+
if ("kill".startsWith(lower.trim()) && running().length > 0) {
|
|
812
|
+
items.push({ value: "kill ", label: "kill <id>", description: "Stop a running background job" });
|
|
813
|
+
}
|
|
814
|
+
return items.length ? items : null;
|
|
815
|
+
},
|
|
816
|
+
handler: showJob,
|
|
817
|
+
});
|
|
818
|
+
// "/bg3" without the space isn't a command, so pi would send it to the model as a message; open the job instead
|
|
819
|
+
pi.on("input", async (event, ctx) => {
|
|
820
|
+
const id = event.text.trim().match(/^\/(bg\d+)$/i)?.[1];
|
|
821
|
+
if (!id || !jobs.has(id.toLowerCase())) return { action: "continue" };
|
|
822
|
+
await showJob(id, ctx);
|
|
823
|
+
return { action: "handled" };
|
|
824
|
+
});
|
|
825
|
+
|
|
826
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
827
|
+
if (ctx.mode === "tui") {
|
|
828
|
+
ctx.ui.setWidget("background-jobs", (tui, theme) => {
|
|
829
|
+
redrawJobs = () => tui.requestRender();
|
|
830
|
+
return jobsWidget(theme, ctx);
|
|
831
|
+
});
|
|
832
|
+
stopMoveKey();
|
|
833
|
+
stopMoveKey = ctx.ui.onTerminalInput((data) => {
|
|
834
|
+
const key = moveKey();
|
|
835
|
+
if (!key || hinted.size === 0 || !matchesKey(data, key)) return undefined;
|
|
836
|
+
for (const move of [...hinted.values()]) move();
|
|
837
|
+
return { consume: true };
|
|
838
|
+
});
|
|
839
|
+
}
|
|
840
|
+
// After /reload or a resume, carry on after the ids already in the conversation so "bg3" keeps meaning one job
|
|
841
|
+
for (const entry of ctx.sessionManager.getBranch()) {
|
|
842
|
+
const msg = entry.type === "message" ? (entry.message as any) : undefined;
|
|
843
|
+
const n = Number(/^bg(\d+)$/.exec(msg?.role === "toolResult" && msg.toolName === "bg_run" ? String(msg.details?.id) : "")?.[1]);
|
|
844
|
+
if (n >= next) next = n + 1;
|
|
845
|
+
}
|
|
846
|
+
});
|
|
847
|
+
|
|
848
|
+
// pi -p and --mode json exit as soon as the agent settles, and session_shutdown stops the jobs with it, so wait for
|
|
849
|
+
// them here instead: a queued wake makes Pi continue and read the result. RPC waits too when its caller asked for it
|
|
850
|
+
// with PI_BACKGROUND_SETTLE_WAIT=1; the TUI never waits, someone is chatting there
|
|
851
|
+
// Jobs started with wake_on, such as a dev server, may never end, so they never hold the exit
|
|
852
|
+
pi.on("agent_before_settle", async (_event, ctx) => {
|
|
853
|
+
if (ctx.mode !== "print" && ctx.mode !== "json" && !(ctx.mode === "rpc" && process.env.PI_BACKGROUND_SETTLE_WAIT === "1")) return;
|
|
854
|
+
const seen = triggerWakes;
|
|
855
|
+
const until = Date.now() + exitWaitMs();
|
|
856
|
+
while ((running().some((job) => !job.watched) || ending > 0) && triggerWakes === seen && Date.now() < until) {
|
|
857
|
+
await new Promise((resolve) => setTimeout(resolve, SETTLE_POLL_MS));
|
|
858
|
+
}
|
|
859
|
+
});
|
|
860
|
+
|
|
861
|
+
pi.on("session_shutdown", async () => {
|
|
862
|
+
clearInterval(ticker);
|
|
863
|
+
for (const timer of holds.values()) clearTimeout(timer);
|
|
864
|
+
holds.clear();
|
|
865
|
+
for (const job of jobs.values()) {
|
|
866
|
+
if (job.status === "running") job.controller.abort();
|
|
867
|
+
}
|
|
868
|
+
jobs.clear();
|
|
869
|
+
});
|
|
870
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { realpathSync } from "node:fs";
|
|
2
|
+
import { basename, isAbsolute, resolve } from "node:path";
|
|
3
|
+
|
|
4
|
+
// Real paths, so a cd through a symlink such as /tmp still counts as cwd
|
|
5
|
+
const real = (path: string) => {
|
|
6
|
+
try {
|
|
7
|
+
return realpathSync(path);
|
|
8
|
+
} catch {
|
|
9
|
+
return path;
|
|
10
|
+
}
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
/** A shell command's first line, without leading cds into cwd; another folder shows as its last part when the path is absolute. */
|
|
14
|
+
export function shortCommand(command: string, cwd: string): string {
|
|
15
|
+
const rest = command.trim().replace(/^(?:cd\s+(?:"[^"]*"|'[^']*'|\S+)[ \t]*(?:&&|;|\n)\s*)+/, (prefix) => {
|
|
16
|
+
const [, quoted, separator] = [...prefix.matchAll(/cd\s+("[^"]*"|'[^']*'|\S+)[ \t]*(&&|;|\n)/g)].at(-1)!;
|
|
17
|
+
const dir = quoted.replace(/^["']|["']$/g, "");
|
|
18
|
+
if (real(resolve(cwd, dir)) === real(resolve(cwd))) return "";
|
|
19
|
+
return `cd ${isAbsolute(dir) ? `…/${basename(dir)}` : quoted}${separator === ";" ? ";" : " &&"} `;
|
|
20
|
+
});
|
|
21
|
+
return rest.split("\n")[0];
|
|
22
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,35 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-background-named",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.4.11",
|
|
4
|
+
"description": "Runs long commands in the background, labels each job by name, and wakes Pi when a job finishes or goes silent",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "Thomas van Dongen",
|
|
7
|
+
"contributors": [
|
|
8
|
+
"LinXuan"
|
|
9
|
+
],
|
|
10
|
+
"type": "module",
|
|
11
|
+
"files": [
|
|
12
|
+
"extensions",
|
|
13
|
+
"README.md",
|
|
14
|
+
"LICENSE"
|
|
15
|
+
],
|
|
16
|
+
"keywords": [
|
|
17
|
+
"pi-package",
|
|
18
|
+
"pi",
|
|
19
|
+
"pi-coding-agent",
|
|
20
|
+
"background",
|
|
21
|
+
"jobs",
|
|
22
|
+
"timeout",
|
|
23
|
+
"named"
|
|
24
|
+
],
|
|
25
|
+
"pi": {
|
|
26
|
+
"extensions": [
|
|
27
|
+
"./extensions/background.ts"
|
|
28
|
+
]
|
|
29
|
+
},
|
|
30
|
+
"peerDependencies": {
|
|
31
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
32
|
+
"@earendil-works/pi-tui": "*",
|
|
33
|
+
"typebox": "*"
|
|
34
|
+
}
|
|
35
|
+
}
|