@pify/shell-background 0.4.1 → 0.5.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/README.md +4 -3
- package/extensions/shell-background.ts +35 -8
- package/package.json +1 -1
- package/src/config.ts +8 -0
- package/src/format.ts +33 -15
- package/src/sanitize.ts +10 -4
- package/src/shrink.ts +125 -0
- package/src/tail.ts +3 -1
package/README.md
CHANGED
|
@@ -34,7 +34,7 @@ shell_kill { id: "bg-2" } # stop it and its whole process tree
|
|
|
34
34
|
|
|
35
35
|
## Delivery, and the headless caveat
|
|
36
36
|
|
|
37
|
-
When a backgrounded command finishes in an **interactive** session, its result is pushed into the conversation as the next turn — you do not have to poll. Under headless `pi -p` there is nothing to deliver into (the session tears down when the prompt resolves), so **auto-background is disabled there** and only explicit `background: true` applies; collect it within the same turn with `shell_status { id, wait: N }`, which blocks (up to `N` seconds, 0–300) until the command finishes rather than returning immediately. This is the same delivery rule the rest of the suite lives by.
|
|
37
|
+
When a backgrounded command finishes in an **interactive** session, its result is pushed into the conversation as the next turn — you do not have to poll. Under headless `pi -p` there is nothing to deliver into (the session tears down when the prompt resolves), so **auto-background is disabled there** and only explicit `background: true` applies; collect it within the same turn with `shell_status { id, wait: N }`, which blocks (up to `N` seconds, 0–300) until the command finishes rather than returning immediately. This is the same delivery rule the rest of the suite lives by. A finish that a `shell_status` wait returns is collected there and not delivered a second time, so the model never spends a turn acknowledging a result it has just reported.
|
|
38
38
|
|
|
39
39
|
## How it works
|
|
40
40
|
|
|
@@ -54,17 +54,18 @@ Put these in `.pi/shell-background.json` (project) or `<agentDir>/shell-backgrou
|
|
|
54
54
|
{
|
|
55
55
|
"autoBackgroundMs": 30000,
|
|
56
56
|
"tailBytes": 65536,
|
|
57
|
+
"tailLines": 200,
|
|
57
58
|
"maxBackground": 8
|
|
58
59
|
}
|
|
59
60
|
```
|
|
60
61
|
|
|
61
|
-
`autoBackgroundMs` is how long a foreground command may run before it auto-backgrounds; set it to `0` to disable auto-background (explicit `background: true` still works). `PIFY_SHELL_BG_MS` overrides it for one run or in CI. `tailBytes` bounds how much of a job's log a status result
|
|
62
|
+
`autoBackgroundMs` is how long a foreground command may run before it auto-backgrounds; set it to `0` to disable auto-background (explicit `background: true` still works). `PIFY_SHELL_BG_MS` overrides it for one run or in CI. `tailBytes` bounds how much of a job's log a status result reads; `tailLines` bounds how many lines of it the model is shown (0 disables the line shrink). `maxBackground` bounds how many jobs may be alive at once: over it, a `background: true` request is refused with a message naming the limit (the command can still run in the foreground), and a command that crosses the auto-background threshold simply stays in the foreground instead of moving — a command is never refused, only the decision to background it. Bad values fall back to the defaults with a warning rather than taking the tool down.
|
|
62
63
|
|
|
63
64
|
Since pi 0.99 the bash tool also returns a machine-readable result — `structuredContent` — which codemode scripts and tools calling `ctx.executeTool("bash", …)` receive instead of the text. This package keeps pi's shape so such a script reads either tool unchanged: `output` (the whole log, up to 1 MiB, head and tail around an omission marker), `truncated`, `full_output_path`, `exit_code`, `wall_time_seconds` — plus `status` and `job_id`, because a command here can still be running when the tool returns; then `exit_code` is absent and `shell_status {id}` collects it, with the same structured result.
|
|
64
65
|
|
|
65
66
|
A backgrounded command runs with no one to answer it, so its environment says so: `GIT_TERMINAL_PROMPT=0` and `GIT_EDITOR`/`EDITOR`/`VISUAL=true` are forced (a `git commit` without `-m` fails with "empty message" instead of waiting on an editor that never comes, and an https `git fetch` fails instead of prompting for a password), and pagers default to `cat` unless you set them. `CI` and `TERM` are left alone on purpose — dev servers and watchers read them.
|
|
66
67
|
|
|
67
|
-
The tail a result carries is cleaned the way pi's own bash cleans what the model sees — ANSI escapes
|
|
68
|
+
The tail a result carries is cleaned the way pi's own bash cleans what the model sees — ANSI escapes and control characters stripped — with two improvements borrowed from caveman's log compressors. A carriage-return redraw is **resolved to its last frame** rather than having the `\r` deleted: pi's own cleaning keeps every frame's text, so a 2000-frame progress bar arrives as one line holding all 2000 frames; here it arrives as `1999/2000`. And a long result is **shrunk by lines, not bytes**: the first and last lines are kept, every line that names trouble (`error`, `FAILED`, `Traceback`, `at …`, `File "…"`, `path:12:5:`, `FooError`, `caused by`, `exit status 1`) is kept wherever it sits, and the rest collapses into markers that count what they replaced — `[… 412 lines omitted (INFO ×380, DEBUG ×29) …]` — computed from exactly those lines. A byte window kept the *end* of a build log, where the summary is; a line window with that regex keeps the failing step in the middle too. Runs under three lines are shown as they are (a marker in place of one line only reads as a hole), the markers are recognised on a later poll so a shrunk result re-serialises identically (the provider prefix cache depends on it), and one note names what was left out and where the whole log is. A log that cannot be read says `(log unavailable: …)` rather than `(no output)`, which would send the model polling for output that will never come. The log file on disk keeps every byte.
|
|
68
69
|
|
|
69
70
|
## Coexistence with @pify/pretty
|
|
70
71
|
|
|
@@ -208,7 +208,7 @@ export default function shellBackground(pi: ExtensionAPI) {
|
|
|
208
208
|
|
|
209
209
|
function finished(job: Job): ToolResult {
|
|
210
210
|
return {
|
|
211
|
-
content: [{ type: "text", text: formatResult(job, settings.tailBytes) }],
|
|
211
|
+
content: [{ type: "text", text: formatResult(job, settings.tailBytes, settings.tailLines) }],
|
|
212
212
|
details: { id: job.id, status: job.status, exitCode: job.exitCode, signal: job.signal, background: false },
|
|
213
213
|
structuredContent: structured(job),
|
|
214
214
|
isError: job.status === "failed",
|
|
@@ -221,7 +221,7 @@ export default function shellBackground(pi: ExtensionAPI) {
|
|
|
221
221
|
pi.sendMessage(
|
|
222
222
|
{
|
|
223
223
|
customType: DELIVERY_TYPE,
|
|
224
|
-
content: deliveryMessage(job.id, formatResult(job, settings.tailBytes)),
|
|
224
|
+
content: deliveryMessage(job.id, formatResult(job, settings.tailBytes, settings.tailLines)),
|
|
225
225
|
display: true,
|
|
226
226
|
details: { id: job.id, status: job.status, exitCode: job.exitCode },
|
|
227
227
|
},
|
|
@@ -229,6 +229,18 @@ export default function shellBackground(pi: ExtensionAPI) {
|
|
|
229
229
|
);
|
|
230
230
|
}
|
|
231
231
|
|
|
232
|
+
/**
|
|
233
|
+
* Jobs a shell_status wait is blocking on, by id. Seen on pi 1.0.4 with the
|
|
234
|
+
* TUI captured: a foreground command auto-backgrounds at 30s, the model
|
|
235
|
+
* waits on it with shell_status, the exit handler delivers the finish as a
|
|
236
|
+
* follow-up in the same instant the wait returns it, and the model spends a
|
|
237
|
+
* whole extra turn acknowledging a result it had just reported. While a
|
|
238
|
+
* wait is active the finish is returned there and marked collected; the
|
|
239
|
+
* delivery path stands down.
|
|
240
|
+
*/
|
|
241
|
+
const waiters = new Map<string, number>();
|
|
242
|
+
const awaited = (job: Job): boolean => (waiters.get(job.id) ?? 0) > 0;
|
|
243
|
+
|
|
232
244
|
/** Deliver a finished background job into the conversation, once. */
|
|
233
245
|
function scheduleDelivery(job: Job, exit: Promise<unknown>): void {
|
|
234
246
|
exit
|
|
@@ -241,7 +253,7 @@ export default function shellBackground(pi: ExtensionAPI) {
|
|
|
241
253
|
registry?.persist(job);
|
|
242
254
|
return;
|
|
243
255
|
}
|
|
244
|
-
if (job.delivered) return;
|
|
256
|
+
if (job.delivered || awaited(job)) return;
|
|
245
257
|
job.delivered = true;
|
|
246
258
|
registry?.persist(job);
|
|
247
259
|
deliver(job);
|
|
@@ -420,7 +432,7 @@ export default function shellBackground(pi: ExtensionAPI) {
|
|
|
420
432
|
{
|
|
421
433
|
type: "text",
|
|
422
434
|
text:
|
|
423
|
-
formatResult(job, settings.tailBytes) +
|
|
435
|
+
formatResult(job, settings.tailBytes, settings.tailLines) +
|
|
424
436
|
`\n\n[kill signal sent; process had not exited after 3s — shell_status ${job.id} to confirm]`,
|
|
425
437
|
},
|
|
426
438
|
],
|
|
@@ -434,7 +446,7 @@ export default function shellBackground(pi: ExtensionAPI) {
|
|
|
434
446
|
? `\n\n[killed: exceeded the ${params.timeout}s timeout]`
|
|
435
447
|
: `\n\n[killed: the turn was aborted]`;
|
|
436
448
|
return {
|
|
437
|
-
content: [{ type: "text", text: formatResult(job, settings.tailBytes) + note }],
|
|
449
|
+
content: [{ type: "text", text: formatResult(job, settings.tailBytes, settings.tailLines) + note }],
|
|
438
450
|
details: { id: job.id, status: job.status },
|
|
439
451
|
structuredContent: structured(job),
|
|
440
452
|
isError: true,
|
|
@@ -522,7 +534,22 @@ export default function shellBackground(pi: ExtensionAPI) {
|
|
|
522
534
|
const waitSec = Number.isFinite(params.wait) ? Math.min(300, Math.max(0, Math.floor(params.wait as number))) : 0;
|
|
523
535
|
if (waitSec > 0 && job.status === "running") {
|
|
524
536
|
const deadline = Date.now() + waitSec * 1000;
|
|
525
|
-
|
|
537
|
+
waiters.set(job.id, (waiters.get(job.id) ?? 0) + 1);
|
|
538
|
+
try {
|
|
539
|
+
while (job.status === "running" && Date.now() < deadline && !sig?.aborted) await sleep(250);
|
|
540
|
+
} finally {
|
|
541
|
+
waiters.set(job.id, Math.max(0, (waiters.get(job.id) ?? 1) - 1));
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
if (sig?.aborted) {
|
|
545
|
+
// The model never sees an aborted tool result. If the job finished
|
|
546
|
+
// while this wait held the delivery path back, deliver it now.
|
|
547
|
+
if (isFinished(job) && !job.delivered) {
|
|
548
|
+
job.delivered = true;
|
|
549
|
+
registry.persist(job);
|
|
550
|
+
deliver(job);
|
|
551
|
+
}
|
|
552
|
+
return { content: [{ type: "text", text: `shell_status ${job.id}: wait aborted` }], details: { id: job.id }, isError: true };
|
|
526
553
|
}
|
|
527
554
|
// Reading a finished job marks it collected so it will not also be
|
|
528
555
|
// delivered unasked. A still-running poll must never do this: setting
|
|
@@ -532,7 +559,7 @@ export default function shellBackground(pi: ExtensionAPI) {
|
|
|
532
559
|
registry.persist(job);
|
|
533
560
|
}
|
|
534
561
|
return {
|
|
535
|
-
content: [{ type: "text", text: formatResult(job, settings.tailBytes) }],
|
|
562
|
+
content: [{ type: "text", text: formatResult(job, settings.tailBytes, settings.tailLines) }],
|
|
536
563
|
details: { id: job.id, status: job.status, exitCode: job.exitCode },
|
|
537
564
|
structuredContent: structured(job),
|
|
538
565
|
};
|
|
@@ -614,7 +641,7 @@ export default function shellBackground(pi: ExtensionAPI) {
|
|
|
614
641
|
}
|
|
615
642
|
}
|
|
616
643
|
if (job.status === "running") anyRunning = true;
|
|
617
|
-
else if (!job.delivered) {
|
|
644
|
+
else if (!job.delivered && !awaited(job)) {
|
|
618
645
|
job.delivered = true;
|
|
619
646
|
registry.persist(job);
|
|
620
647
|
deliver(job);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pify/shell-background",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "Long-running bash goes async: background: true launches detached, and any command still running after 30s auto-backgrounds and delivers its result when it finishes",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi-package",
|
package/src/config.ts
CHANGED
|
@@ -14,6 +14,12 @@ export interface ShellBgSettings {
|
|
|
14
14
|
autoBackgroundMs: number;
|
|
15
15
|
/** Bytes of the log tail shown in a status/collect result. */
|
|
16
16
|
tailBytes: number;
|
|
17
|
+
/**
|
|
18
|
+
* Lines a result may carry before it is shrunk: first and last lines kept,
|
|
19
|
+
* every error/warning line kept wherever it sits, the rest collapsed into
|
|
20
|
+
* counted markers. 0 disables shrinking (the byte tail is still the cap).
|
|
21
|
+
*/
|
|
22
|
+
tailLines: number;
|
|
17
23
|
/**
|
|
18
24
|
* How many jobs may be alive at once before a request to background one
|
|
19
25
|
* more is refused and an auto-background transition is skipped. Every live
|
|
@@ -28,6 +34,7 @@ export interface ShellBgSettings {
|
|
|
28
34
|
export const DEFAULT_SETTINGS: ShellBgSettings = {
|
|
29
35
|
autoBackgroundMs: 30_000,
|
|
30
36
|
tailBytes: 64 * 1024,
|
|
37
|
+
tailLines: 200,
|
|
31
38
|
maxBackground: 8,
|
|
32
39
|
};
|
|
33
40
|
|
|
@@ -36,6 +43,7 @@ const LIMITS: Record<keyof ShellBgSettings, { min: number; max: number }> = {
|
|
|
36
43
|
// does not make every command look long-running.
|
|
37
44
|
autoBackgroundMs: { min: 0, max: 3_600_000 },
|
|
38
45
|
tailBytes: { min: 1024, max: 4 * 1024 * 1024 },
|
|
46
|
+
tailLines: { min: 0, max: 5000 },
|
|
39
47
|
maxBackground: { min: 1, max: 64 },
|
|
40
48
|
};
|
|
41
49
|
|
package/src/format.ts
CHANGED
|
@@ -3,8 +3,13 @@
|
|
|
3
3
|
* job and a tail, produce the string — the extension supplies both.
|
|
4
4
|
*/
|
|
5
5
|
import type { Job } from "./types.ts";
|
|
6
|
-
import { readTail
|
|
6
|
+
import { readTail } from "./tail.ts";
|
|
7
7
|
import { sanitizeOutput } from "./sanitize.ts";
|
|
8
|
+
import { DEFAULT_SHRINK, shrinkLines } from "./shrink.ts";
|
|
9
|
+
|
|
10
|
+
function kb(bytes: number): string {
|
|
11
|
+
return bytes < 1024 * 1024 ? `${Math.max(1, Math.round(bytes / 1024))}KB` : `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
|
|
12
|
+
}
|
|
8
13
|
|
|
9
14
|
function secs(ms: number): string {
|
|
10
15
|
if (ms < 1000) return `${ms}ms`;
|
|
@@ -17,12 +22,11 @@ function duration(job: Job): string {
|
|
|
17
22
|
return secs(Math.max(0, end - job.startedAt));
|
|
18
23
|
}
|
|
19
24
|
|
|
20
|
-
/** `[bg-1 · done · exit 0 · 4.2s]` — the one-line header every result carries. */
|
|
25
|
+
/** `[bg-1 · done · exit 0 · 4.2s]` — the one-line header every result carries. A running job has no verdict yet: `[bg-1 · running · 13.2s]`. */
|
|
21
26
|
export function header(job: Job): string {
|
|
27
|
+
if (job.status === "running") return `[${job.id} · running · ${duration(job)}]`;
|
|
22
28
|
const verdict =
|
|
23
|
-
job.status === "
|
|
24
|
-
? "running"
|
|
25
|
-
: job.status === "orphaned"
|
|
29
|
+
job.status === "orphaned"
|
|
26
30
|
? "orphaned (another session)"
|
|
27
31
|
: job.signal
|
|
28
32
|
? `signal ${job.signal}`
|
|
@@ -35,22 +39,36 @@ export function header(job: Job): string {
|
|
|
35
39
|
/**
|
|
36
40
|
* The full result of a finished (or polled) job: the header, then the tail of
|
|
37
41
|
* its output, with an honest note when output was truncated and where the whole
|
|
38
|
-
* log lives.
|
|
42
|
+
* log lives. The tail is read as bytes (`tailBytes`), cleaned, and then shrunk
|
|
43
|
+
* by lines (`tailLines`): first and last lines kept, every error/warning line
|
|
44
|
+
* kept wherever it sits, the rest collapsed into counted markers — so a long
|
|
45
|
+
* build's failing step survives in the middle instead of only its summary at
|
|
46
|
+
* the end. The log on disk keeps every byte, and the note says where it is.
|
|
39
47
|
*/
|
|
40
|
-
export function formatResult(job: Job, tailBytes: number): string {
|
|
48
|
+
export function formatResult(job: Job, tailBytes: number, tailLines: number = DEFAULT_SHRINK.maxLines): string {
|
|
41
49
|
const tail = readTail(job.logPath, tailBytes);
|
|
42
|
-
// Cleaned the way pi's own bash cleans its output for the model; the log on
|
|
43
|
-
// disk (which the truncation note points at) keeps every byte.
|
|
44
|
-
const text = sanitizeOutput(tail.text);
|
|
45
50
|
const lines = [header(job)];
|
|
51
|
+
if (tail.missing) {
|
|
52
|
+
// A log that cannot be read is not a command that printed nothing: say so,
|
|
53
|
+
// or the model keeps polling for output that will never come.
|
|
54
|
+
lines.push(`(log unavailable: ${job.logPath} could not be read)`);
|
|
55
|
+
return lines.join("\n");
|
|
56
|
+
}
|
|
57
|
+
// Cleaned the way pi's own bash cleans its output for the model; the log on
|
|
58
|
+
// disk (which the note points at) keeps every byte.
|
|
59
|
+
const text = sanitizeOutput(tail.text).replace(/\n+$/, "");
|
|
46
60
|
if (text.trim() === "") {
|
|
47
61
|
lines.push(job.status === "running" ? "(no output yet)" : "(no output)");
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
62
|
+
return lines.join("\n");
|
|
63
|
+
}
|
|
64
|
+
const shrunk = shrinkLines(text, { maxLines: tailLines, tail: Math.max(DEFAULT_SHRINK.tail, Math.floor(tailLines / 2)) });
|
|
65
|
+
const notes: string[] = [];
|
|
66
|
+
if (shrunk.omitted > 0) {
|
|
67
|
+
notes.push(`${shrunk.omitted} of ${shrunk.total} lines omitted, none with an error or warning (those are kept wherever they sit)`);
|
|
53
68
|
}
|
|
69
|
+
if (tail.truncated) notes.push(`this is the last ${kb(Buffer.byteLength(tail.text, "utf8"))} of a ${kb(tail.bytes)} log`);
|
|
70
|
+
if (notes.length > 0) lines.push(`… ${notes.join("; ")} — full log: ${job.logPath}`);
|
|
71
|
+
lines.push(shrunk.text);
|
|
54
72
|
return lines.join("\n");
|
|
55
73
|
}
|
|
56
74
|
|
package/src/sanitize.ts
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The
|
|
3
|
-
* (bash-executor.ts: `sanitizeBinaryOutput(stripAnsi(text)).replace(/\r/g, "")`)
|
|
2
|
+
* The cleaning pi's own bash tool applies to what the model sees
|
|
3
|
+
* (bash-executor.ts: `sanitizeBinaryOutput(stripAnsi(text)).replace(/\r/g, "")`),
|
|
4
|
+
* with one improvement: a carriage return is resolved, not deleted. pi drops
|
|
5
|
+
* the `\r` and keeps every progress frame's text, so a 2000-frame webpack bar
|
|
6
|
+
* arrives as one line holding all 2000 frames; here only the last frame of
|
|
7
|
+
* each line survives, which is what the terminal showed (see shrink.ts).
|
|
4
8
|
*
|
|
5
9
|
* This package re-registers `bash`, and a job's log is captured raw on disk on
|
|
6
10
|
* purpose (the detached spawn writes straight to a file; no in-process pipes).
|
|
@@ -12,6 +16,8 @@
|
|
|
12
16
|
* vendored here verbatim.
|
|
13
17
|
*/
|
|
14
18
|
|
|
19
|
+
import { collapseCarriageReturns } from "./shrink.ts";
|
|
20
|
+
|
|
15
21
|
// Valid string terminator sequences are BEL, ESC\, and 0x9c
|
|
16
22
|
const ST = "(?:\\u0007|\\u001B\\u005C|\\u009C)";
|
|
17
23
|
// OSC sequences only: ESC ] ... ST (non-greedy until the first ST)
|
|
@@ -44,7 +50,7 @@ export function sanitizeBinaryOutput(text: string): string {
|
|
|
44
50
|
.join("");
|
|
45
51
|
}
|
|
46
52
|
|
|
47
|
-
/**
|
|
53
|
+
/** What pi's bash gives the model — no ANSI, no control noise — with `\r` redraws collapsed to their last frame. */
|
|
48
54
|
export function sanitizeOutput(text: string): string {
|
|
49
|
-
return sanitizeBinaryOutput(stripAnsi(text))
|
|
55
|
+
return sanitizeBinaryOutput(collapseCarriageReturns(stripAnsi(text)));
|
|
50
56
|
}
|
package/src/shrink.ts
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A long log, shrunk the way a person skims it: the first lines, the last
|
|
3
|
+
* lines, and every line that looks like trouble wherever it sits — the rest
|
|
4
|
+
* collapsed into counted markers. Adapted from caveman's log/terminal
|
|
5
|
+
* compressors (JuliusBrussee/caveman, engine/compressors/{log,terminal}.go):
|
|
6
|
+
* a byte window keeps the END of a build log, which is exactly where the
|
|
7
|
+
* summary is and not where the failing step was; a line window with an
|
|
8
|
+
* importance regex keeps both.
|
|
9
|
+
*
|
|
10
|
+
* Rules that matter, kept from the original:
|
|
11
|
+
* - an important line is never elided, no matter where it sits;
|
|
12
|
+
* - a run of fewer than 3 dropped lines is emitted verbatim — a marker that
|
|
13
|
+
* replaces one line costs about what the line cost and reads as a hole;
|
|
14
|
+
* - a marker states facts computed from exactly the lines it replaces (their
|
|
15
|
+
* log levels, counted), never a guess;
|
|
16
|
+
* - markers are recognised on re-entry and kept, so shrinking a shrunk text
|
|
17
|
+
* is byte-identical — a result that re-serialises differently on a later
|
|
18
|
+
* poll busts the provider's prefix cache.
|
|
19
|
+
* Pure; zero dependencies.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
/** Words that mark trouble, case-insensitive (`error:`, `FAILED`, `Traceback`). */
|
|
23
|
+
const IMPORTANT_WORDS =
|
|
24
|
+
/\b(?:ERROR|FATAL|PANIC|EXCEPTION|TRACEBACK|FAIL|FAILED|FAILURE|WARN|WARNING|CRIT|CRITICAL|ALERT|EMERG|EMERGENCY)\b|^\s+at\s|^\s+File "|:\d+:\d+:|^\s*--->|caused by|\bexit (?:status|code) [1-9]/i;
|
|
25
|
+
/** camelCase error types a bare ERROR never matches: AssertionError, ValueError, NullPointerException. Case-sensitive on purpose (not "terror"). */
|
|
26
|
+
const CAMEL_ERROR = /\b[A-Za-z]+(?:Error|Exception)\b/;
|
|
27
|
+
/** A log level token, for the marker's counts. */
|
|
28
|
+
const LEVEL = /\b(TRACE|DEBUG|INFO|NOTICE|WARN|WARNING|ERROR|FATAL)\b/i;
|
|
29
|
+
/** A marker this module wrote earlier; kept as-is on re-entry. */
|
|
30
|
+
export const MARKER_RE = /^\[… \d+ lines omitted/;
|
|
31
|
+
|
|
32
|
+
export function isImportantLine(line: string): boolean {
|
|
33
|
+
return IMPORTANT_WORDS.test(line) || CAMEL_ERROR.test(line) || MARKER_RE.test(line);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* A bare carriage return rewinds the cursor: `10%\r20%\r100% done` only ever
|
|
38
|
+
* displayed `100% done`, and the earlier frames are visual history. Deleting
|
|
39
|
+
* the `\r` instead (what pi's own bash does) concatenates every frame into
|
|
40
|
+
* one enormous line. Keep the last non-empty segment of each line. A CRLF
|
|
41
|
+
* line ending leaves an empty final segment, so the content before it wins.
|
|
42
|
+
*/
|
|
43
|
+
export function collapseCarriageReturns(text: string): string {
|
|
44
|
+
if (!text.includes("\r")) return text;
|
|
45
|
+
return text
|
|
46
|
+
.split("\n")
|
|
47
|
+
.map((line) => {
|
|
48
|
+
if (!line.includes("\r")) return line;
|
|
49
|
+
let chosen = "";
|
|
50
|
+
for (const segment of line.split("\r")) if (segment.length > 0) chosen = segment;
|
|
51
|
+
return chosen;
|
|
52
|
+
})
|
|
53
|
+
.join("\n");
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface ShrinkOptions {
|
|
57
|
+
/** Lines kept from the start. */
|
|
58
|
+
head?: number;
|
|
59
|
+
/** Lines kept from the end. */
|
|
60
|
+
tail?: number;
|
|
61
|
+
/** Texts of at most this many lines are returned untouched; 0 disables shrinking. */
|
|
62
|
+
maxLines?: number;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface Shrunk {
|
|
66
|
+
text: string;
|
|
67
|
+
/** Lines replaced by markers. */
|
|
68
|
+
omitted: number;
|
|
69
|
+
/** Lines in the input. */
|
|
70
|
+
total: number;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export const DEFAULT_SHRINK: Required<ShrinkOptions> = { head: 3, tail: 100, maxLines: 200 };
|
|
74
|
+
|
|
75
|
+
function levelSummary(lines: string[]): string {
|
|
76
|
+
const counts = new Map<string, number>();
|
|
77
|
+
for (const line of lines) {
|
|
78
|
+
const m = LEVEL.exec(line);
|
|
79
|
+
if (!m) continue;
|
|
80
|
+
const key = m[1]!.toUpperCase();
|
|
81
|
+
counts.set(key, (counts.get(key) ?? 0) + 1);
|
|
82
|
+
}
|
|
83
|
+
if (counts.size === 0) return "";
|
|
84
|
+
// Every level seen, never a partial list; most frequent first, ties by name.
|
|
85
|
+
return [...counts.entries()]
|
|
86
|
+
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
|
|
87
|
+
.map(([level, n]) => `${level} ×${n}`)
|
|
88
|
+
.join(", ");
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function marker(run: number, dropped: string[]): string {
|
|
92
|
+
const summary = levelSummary(dropped);
|
|
93
|
+
return `[… ${run} lines omitted${summary ? ` (${summary})` : ""} …]`;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function shrinkLines(text: string, opts: ShrinkOptions = {}): Shrunk {
|
|
97
|
+
const head = Math.max(0, opts.head ?? DEFAULT_SHRINK.head);
|
|
98
|
+
const tail = Math.max(0, opts.tail ?? DEFAULT_SHRINK.tail);
|
|
99
|
+
const maxLines = opts.maxLines ?? DEFAULT_SHRINK.maxLines;
|
|
100
|
+
const lines = text.split("\n");
|
|
101
|
+
const total = lines.length;
|
|
102
|
+
if (maxLines <= 0 || total <= maxLines) return { text, omitted: 0, total };
|
|
103
|
+
const keep = lines.map((line, i) => i < head || i >= total - tail || isImportantLine(line));
|
|
104
|
+
const out: string[] = [];
|
|
105
|
+
let omitted = 0;
|
|
106
|
+
let i = 0;
|
|
107
|
+
while (i < total) {
|
|
108
|
+
if (keep[i]) {
|
|
109
|
+
out.push(lines[i]!);
|
|
110
|
+
i++;
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
let j = i;
|
|
114
|
+
while (j < total && !keep[j]) j++;
|
|
115
|
+
const run = j - i;
|
|
116
|
+
if (run < 3) {
|
|
117
|
+
for (let k = i; k < j; k++) out.push(lines[k]!);
|
|
118
|
+
} else {
|
|
119
|
+
out.push(marker(run, lines.slice(i, j)));
|
|
120
|
+
omitted += run;
|
|
121
|
+
}
|
|
122
|
+
i = j;
|
|
123
|
+
}
|
|
124
|
+
return { text: out.join("\n"), omitted, total };
|
|
125
|
+
}
|
package/src/tail.ts
CHANGED
|
@@ -20,6 +20,8 @@ export interface Tail {
|
|
|
20
20
|
truncated: boolean;
|
|
21
21
|
/** Total size of the file in bytes. */
|
|
22
22
|
bytes: number;
|
|
23
|
+
/** True when the log could not be opened at all — distinct from a command that printed nothing. */
|
|
24
|
+
missing?: boolean;
|
|
23
25
|
}
|
|
24
26
|
|
|
25
27
|
export const DEFAULT_TAIL_BYTES = 64 * 1024;
|
|
@@ -29,7 +31,7 @@ export function readTail(path: string, maxBytes: number = DEFAULT_TAIL_BYTES): T
|
|
|
29
31
|
try {
|
|
30
32
|
fd = openSync(path, "r");
|
|
31
33
|
} catch {
|
|
32
|
-
return { text: "", truncated: false, bytes: 0 };
|
|
34
|
+
return { text: "", truncated: false, bytes: 0, missing: true };
|
|
33
35
|
}
|
|
34
36
|
try {
|
|
35
37
|
const size = fstatSync(fd).size;
|