@pify/shell-background 0.4.2 → 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 CHANGED
@@ -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 shows. `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
+ `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, control characters and carriage-return progress frames stripped — so a chatty build or dev server does not spend tokens on colour codes and thousands of overwritten progress lines. The log file on disk keeps every byte.
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
  },
@@ -432,7 +432,7 @@ export default function shellBackground(pi: ExtensionAPI) {
432
432
  {
433
433
  type: "text",
434
434
  text:
435
- formatResult(job, settings.tailBytes) +
435
+ formatResult(job, settings.tailBytes, settings.tailLines) +
436
436
  `\n\n[kill signal sent; process had not exited after 3s — shell_status ${job.id} to confirm]`,
437
437
  },
438
438
  ],
@@ -446,7 +446,7 @@ export default function shellBackground(pi: ExtensionAPI) {
446
446
  ? `\n\n[killed: exceeded the ${params.timeout}s timeout]`
447
447
  : `\n\n[killed: the turn was aborted]`;
448
448
  return {
449
- content: [{ type: "text", text: formatResult(job, settings.tailBytes) + note }],
449
+ content: [{ type: "text", text: formatResult(job, settings.tailBytes, settings.tailLines) + note }],
450
450
  details: { id: job.id, status: job.status },
451
451
  structuredContent: structured(job),
452
452
  isError: true,
@@ -559,7 +559,7 @@ export default function shellBackground(pi: ExtensionAPI) {
559
559
  registry.persist(job);
560
560
  }
561
561
  return {
562
- content: [{ type: "text", text: formatResult(job, settings.tailBytes) }],
562
+ content: [{ type: "text", text: formatResult(job, settings.tailBytes, settings.tailLines) }],
563
563
  details: { id: job.id, status: job.status, exitCode: job.exitCode },
564
564
  structuredContent: structured(job),
565
565
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pify/shell-background",
3
- "version": "0.4.2",
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, countLines } from "./tail.ts";
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`;
@@ -34,22 +39,36 @@ export function header(job: Job): string {
34
39
  /**
35
40
  * The full result of a finished (or polled) job: the header, then the tail of
36
41
  * its output, with an honest note when output was truncated and where the whole
37
- * 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.
38
47
  */
39
- export function formatResult(job: Job, tailBytes: number): string {
48
+ export function formatResult(job: Job, tailBytes: number, tailLines: number = DEFAULT_SHRINK.maxLines): string {
40
49
  const tail = readTail(job.logPath, tailBytes);
41
- // Cleaned the way pi's own bash cleans its output for the model; the log on
42
- // disk (which the truncation note points at) keeps every byte.
43
- const text = sanitizeOutput(tail.text);
44
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+$/, "");
45
60
  if (text.trim() === "") {
46
61
  lines.push(job.status === "running" ? "(no output yet)" : "(no output)");
47
- } else {
48
- if (tail.truncated) {
49
- lines.push(`… showing the last ${countLines(text)} lines — full log: ${job.logPath}`);
50
- }
51
- lines.push(text.replace(/\n+$/, ""));
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)`);
52
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);
53
72
  return lines.join("\n");
54
73
  }
55
74
 
package/src/sanitize.ts CHANGED
@@ -1,6 +1,10 @@
1
1
  /**
2
- * The same cleaning pi's own bash tool applies to what the model sees
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
- /** Exactly what pi's bash gives the model: no ANSI, no control noise, no `\r`. */
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)).replace(/\r/g, "");
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;