pi-better-background-tasks 0.19.0 → 0.20.1
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 +21 -10
- package/package.json +1 -1
- package/runtime-client/artifacts/darwin-arm64.gz +0 -0
- package/runtime-client/artifacts/darwin-arm64.json +1 -1
- package/runtime-client/artifacts/darwin-x64.gz +0 -0
- package/runtime-client/artifacts/darwin-x64.json +1 -1
- package/runtime-client/artifacts/linux-arm64.gz +0 -0
- package/runtime-client/artifacts/linux-arm64.json +1 -1
- package/runtime-client/artifacts/linux-x64.gz +0 -0
- package/runtime-client/artifacts/linux-x64.json +1 -1
- package/runtime-client/src/runtime/root.mjs +5 -2
- package/src/index.ts +19 -0
- package/src/managed-frontend.ts +76 -5
- package/src/navigator-provider.ts +4 -0
- package/src/observed-waits.ts +168 -24
- package/src/process.ts +45 -11
- package/src/review-settings.ts +18 -0
- package/src/runtime.ts +8 -73
- package/src/shared-harness-settings.ts +2 -5
- package/src/shared-navigator.ts +47 -26
- package/src/shared-operation-coordinator/src/outbox.ts +9 -0
- package/src/shared-operation-coordinator/src/store.ts +6 -0
- package/src/shared-ssh-core/index.ts +1 -1
- package/src/stall.ts +7 -4
- package/src/supervised-progress.ts +43 -0
- package/src/supervisor/README.md +1 -4
- package/src/supervisor/emit-runner.mjs +1 -0
- package/src/supervisor/generated/process.mjs +49 -11
- package/src/supervisor/generated/runner.mjs +47 -4
- package/src/supervisor/generated/store.mjs +3 -3
- package/src/supervisor/generated/watch-fingerprint.mjs +69 -0
- package/src/supervisor/runner.ts +38 -3
- package/src/supervisor/store.ts +3 -3
- package/src/supervisor/supervisor.ts +6 -3
- package/src/tools.ts +26 -16
- package/src/types.ts +4 -2
- package/src/watch-fingerprint.ts +70 -0
package/src/supervisor/runner.ts
CHANGED
|
@@ -30,9 +30,10 @@
|
|
|
30
30
|
|
|
31
31
|
import { spawn } from "node:child_process";
|
|
32
32
|
import { closeSync, openSync, realpathSync } from "node:fs";
|
|
33
|
-
import { resolve } from "node:path";
|
|
33
|
+
import { join, resolve } from "node:path";
|
|
34
34
|
import { setTimeout as delay } from "node:timers/promises";
|
|
35
35
|
import { fileURLToPath } from "node:url";
|
|
36
|
+
import { watchOutcomeFingerprint } from "../watch-fingerprint.ts";
|
|
36
37
|
import { evaluateCondition, validateCondition } from "../conditions.ts";
|
|
37
38
|
import { completeUtf8Length, stopProcessGroup, utf8PrefixLength } from "../process.ts";
|
|
38
39
|
import { readProcessStartToken } from "../process-identity.ts";
|
|
@@ -47,6 +48,7 @@ import {
|
|
|
47
48
|
supervisorPaths,
|
|
48
49
|
writeCommandRecord,
|
|
49
50
|
writeTerminalRecord,
|
|
51
|
+
writeTextAtomic,
|
|
50
52
|
} from "./store.ts";
|
|
51
53
|
import {
|
|
52
54
|
DEFAULT_TERMINAL_TAIL_BYTES,
|
|
@@ -88,6 +90,7 @@ interface RunnerContext {
|
|
|
88
90
|
checks: number;
|
|
89
91
|
stdout: StreamSink;
|
|
90
92
|
stderr: StreamSink;
|
|
93
|
+
progress: (observedAt: number, fingerprint?: string) => void;
|
|
91
94
|
stopRequested: boolean;
|
|
92
95
|
finalized: boolean;
|
|
93
96
|
command?: { pid: number; pgid?: number; pidStartTime?: string; startedAt: number; attempt: number };
|
|
@@ -212,6 +215,29 @@ function streamChunk(sink: StreamSink, chunk: Buffer, maxBytes: number): void {
|
|
|
212
215
|
}
|
|
213
216
|
}
|
|
214
217
|
|
|
218
|
+
/** Coalesce stream bursts while retaining the timestamp of the last byte, including discarded output. */
|
|
219
|
+
function progressRecorder(directory: string) {
|
|
220
|
+
const path = join(directory, "progress.json");
|
|
221
|
+
let pending: { observedAt: number; fingerprint?: string } | undefined;
|
|
222
|
+
let timer: NodeJS.Timeout | undefined;
|
|
223
|
+
let lastWrite = 0;
|
|
224
|
+
const flush = () => {
|
|
225
|
+
timer = undefined;
|
|
226
|
+
if (!pending) return;
|
|
227
|
+
try { writeTextAtomic(path, JSON.stringify(pending)); }
|
|
228
|
+
catch (error) { process.stderr.write(`Could not record Background progress: ${String(error)}\n`); }
|
|
229
|
+
lastWrite = Date.now();
|
|
230
|
+
};
|
|
231
|
+
return (observedAt: number, fingerprint?: string) => {
|
|
232
|
+
if (fingerprint !== undefined && pending?.fingerprint === fingerprint) return;
|
|
233
|
+
pending = { observedAt, fingerprint };
|
|
234
|
+
if (timer) return;
|
|
235
|
+
const remaining = lastWrite + 1000 - Date.now();
|
|
236
|
+
if (remaining <= 0) flush();
|
|
237
|
+
else { timer = setTimeout(flush, remaining); timer.unref(); }
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
|
|
215
241
|
function startToken(pid: number | undefined): string | undefined {
|
|
216
242
|
return pid === undefined ? undefined : readProcessStartToken(pid);
|
|
217
243
|
}
|
|
@@ -482,12 +508,18 @@ function runChild(ctx: RunnerContext, plan: ChildPlan): Promise<ChildOutcome> {
|
|
|
482
508
|
|
|
483
509
|
child.stdout?.on("data", (chunk: Buffer | string) => {
|
|
484
510
|
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
485
|
-
if (plan.mode === "stream")
|
|
511
|
+
if (plan.mode === "stream") {
|
|
512
|
+
streamChunk(ctx.stdout, buffer, plan.maxBytes);
|
|
513
|
+
if (buffer.length) ctx.progress(Date.now());
|
|
514
|
+
}
|
|
486
515
|
else captureChunk(stdoutCapture, buffer, plan.maxBytes);
|
|
487
516
|
});
|
|
488
517
|
child.stderr?.on("data", (chunk: Buffer | string) => {
|
|
489
518
|
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
490
|
-
if (plan.mode === "stream")
|
|
519
|
+
if (plan.mode === "stream") {
|
|
520
|
+
streamChunk(ctx.stderr, buffer, plan.maxBytes);
|
|
521
|
+
if (buffer.length) ctx.progress(Date.now());
|
|
522
|
+
}
|
|
491
523
|
else captureChunk(stderrCapture, buffer, plan.maxBytes);
|
|
492
524
|
});
|
|
493
525
|
child.on("error", (error) => {
|
|
@@ -704,6 +736,7 @@ async function runWatch(ctx: RunnerContext): Promise<void> {
|
|
|
704
736
|
});
|
|
705
737
|
if (ctx.finalized) return;
|
|
706
738
|
ctx.checks += 1;
|
|
739
|
+
ctx.progress(outcome.endedAt, watchOutcomeFingerprint({ ...asCommandResult(outcome), ...(outcome.spawnError ? { error: outcome.spawnError } : {}) }));
|
|
707
740
|
// Per-check output keeps the streams apart: stdout bytes in stdout.log, stderr in stderr.log.
|
|
708
741
|
streamChunk(ctx.stdout, Buffer.from(outcome.stdout), ctx.launch.maxLogBytes);
|
|
709
742
|
streamChunk(ctx.stderr, Buffer.from(outcome.stderr), ctx.launch.maxLogBytes);
|
|
@@ -936,9 +969,11 @@ function main(): number {
|
|
|
936
969
|
checks: 0,
|
|
937
970
|
stdout,
|
|
938
971
|
stderr,
|
|
972
|
+
progress: progressRecorder(paths.dir),
|
|
939
973
|
stopRequested: false,
|
|
940
974
|
finalized: false,
|
|
941
975
|
};
|
|
976
|
+
ctx.progress(ctx.startedAt);
|
|
942
977
|
appendEvent(paths.events, `claimed runner_pid=${process.pid} runner_version=${SUPERVISOR_RUNNER_VERSION} kind=${launch.kind} cwd=${launch.command.cwd}`);
|
|
943
978
|
|
|
944
979
|
const onSignal = (signal: NodeJS.Signals): void => {
|
package/src/supervisor/store.ts
CHANGED
|
@@ -397,16 +397,16 @@ function readText(path: string): RecordRead<string> {
|
|
|
397
397
|
return { value: readFileSync(path, "utf8"), missing: false };
|
|
398
398
|
} catch (error) {
|
|
399
399
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") return { missing: true };
|
|
400
|
-
return { missing:
|
|
400
|
+
return { missing: false, error: error instanceof Error ? error.message : String(error) };
|
|
401
401
|
}
|
|
402
402
|
}
|
|
403
403
|
|
|
404
404
|
function readJsonRecord<T>(path: string, problem: (value: unknown) => string | undefined): RecordRead<T> {
|
|
405
405
|
const read = readText(path);
|
|
406
|
-
if (read.
|
|
406
|
+
if (read.value === undefined) return { missing: read.missing, error: read.error };
|
|
407
407
|
let parsed: unknown;
|
|
408
408
|
try {
|
|
409
|
-
parsed = JSON.parse(read.value
|
|
409
|
+
parsed = JSON.parse(read.value);
|
|
410
410
|
} catch (error) {
|
|
411
411
|
return { missing: false, error: `invalid JSON: ${error instanceof Error ? error.message : String(error)}` };
|
|
412
412
|
}
|
|
@@ -527,13 +527,16 @@ class Supervisor implements LocalSupervisor {
|
|
|
527
527
|
options: SupervisorInspectOptions,
|
|
528
528
|
): { status: SupervisorTaskStatus; terminal: boolean; result?: SupervisorTerminalRecord; lost?: SupervisorLostRecord } {
|
|
529
529
|
return withStateFence(this.directory, launch.taskId, () => {
|
|
530
|
-
const result = readTerminalRecord(this.directory, launch.taskId)
|
|
530
|
+
const { value: result, error: resultError } = readTerminalRecord(this.directory, launch.taskId);
|
|
531
|
+
if (resultError) throw new Error(`Unreadable supervisor result record for ${launch.taskId}: ${resultError}`);
|
|
531
532
|
if (result) return { status: result.status as SupervisorTaskStatus, terminal: true, result };
|
|
532
533
|
|
|
533
|
-
const existingLost = readLostRecord(this.directory, launch.taskId)
|
|
534
|
+
const { value: existingLost, error: lostError } = readLostRecord(this.directory, launch.taskId);
|
|
535
|
+
if (lostError) throw new Error(`Unreadable supervisor loss record for ${launch.taskId}: ${lostError}`);
|
|
534
536
|
if (existingLost) return { status: "lost" as const, terminal: true, lost: existingLost };
|
|
535
537
|
|
|
536
|
-
const claim = readClaimRecord(this.directory, launch.taskId)
|
|
538
|
+
const { value: claim, error: claimError } = readClaimRecord(this.directory, launch.taskId);
|
|
539
|
+
if (claimError) throw new Error(`Unreadable supervisor claim record for ${launch.taskId}: ${claimError}`);
|
|
537
540
|
if (claim) {
|
|
538
541
|
if (identityAlive(claim.pid, claim.pidStartTime, claim.claimedAt, this.readToken)) {
|
|
539
542
|
return { status: "running" as const, terminal: false };
|
package/src/tools.ts
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
import { Type } from "typebox";
|
|
2
2
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import {
|
|
4
|
+
truncateToWidth as piTruncateToWidth,
|
|
5
|
+
visibleWidth as piVisibleWidth,
|
|
6
|
+
wrapTextWithAnsi as piWrapTextWithAnsi,
|
|
7
|
+
} from "@earendil-works/pi-tui";
|
|
3
8
|
import { advertiseBackgroundAdapter } from "./adapter-contract.js";
|
|
4
9
|
import { refreshBackgroundTasksNavigator } from "./navigator-provider.js";
|
|
5
10
|
import {
|
|
@@ -1045,29 +1050,34 @@ function renderLines(lines: string[], mode: "truncate" | "wrap" = "truncate") {
|
|
|
1045
1050
|
};
|
|
1046
1051
|
}
|
|
1047
1052
|
|
|
1053
|
+
/**
|
|
1054
|
+
* Split one display line into rows of at most `width` terminal columns.
|
|
1055
|
+
*
|
|
1056
|
+
* Measures columns rather than characters: a CJK grapheme or emoji occupies two,
|
|
1057
|
+
* so counting characters emitted rows wider than the width Pi asked for. Pi
|
|
1058
|
+
* asserts every rendered line fits the terminal and exits the process when one
|
|
1059
|
+
* does not, which turned any log holding double-width text into a crash that
|
|
1060
|
+
* replayed on resume, because the tool result stays in session history.
|
|
1061
|
+
*/
|
|
1048
1062
|
function wrapLineToVisibleWidth(line: string, width: number): string[] {
|
|
1049
1063
|
const str = String(line ?? "");
|
|
1050
1064
|
const max = Math.max(1, Number(width) || 80);
|
|
1051
|
-
if (
|
|
1052
|
-
const
|
|
1053
|
-
|
|
1054
|
-
let visible = 0;
|
|
1055
|
-
for (const char of str) {
|
|
1056
|
-
if (visible >= max) {
|
|
1057
|
-
out.push(current);
|
|
1058
|
-
current = "";
|
|
1059
|
-
visible = 0;
|
|
1060
|
-
}
|
|
1061
|
-
current += char;
|
|
1062
|
-
visible += 1;
|
|
1063
|
-
}
|
|
1064
|
-
out.push(current);
|
|
1065
|
-
return out;
|
|
1065
|
+
if (piVisibleWidth(str) <= max) return [str];
|
|
1066
|
+
const wrapped = piWrapTextWithAnsi(str, max);
|
|
1067
|
+
return (wrapped.length > 0 ? wrapped : [str]).map((row) => fitToVisibleWidth(row, max));
|
|
1066
1068
|
}
|
|
1067
1069
|
|
|
1068
1070
|
function truncateToVisibleWidth(value: string, width: number): string {
|
|
1069
1071
|
const max = Math.max(0, Math.floor(width || 0));
|
|
1070
|
-
return String(value ?? "")
|
|
1072
|
+
return fitToVisibleWidth(String(value ?? ""), max);
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
/** Last resort for anything a wrap missed: never return a line wider than `max`. */
|
|
1076
|
+
function fitToVisibleWidth(value: string, max: number): string {
|
|
1077
|
+
const str = String(value ?? "");
|
|
1078
|
+
const limit = Math.max(0, Math.floor(max || 0));
|
|
1079
|
+
if (piVisibleWidth(str) <= limit) return str;
|
|
1080
|
+
return piTruncateToWidth(str, limit, "");
|
|
1071
1081
|
}
|
|
1072
1082
|
|
|
1073
1083
|
async function formatStop(
|
package/src/types.ts
CHANGED
|
@@ -24,6 +24,8 @@ export interface CommandSpec {
|
|
|
24
24
|
shell?: boolean;
|
|
25
25
|
/** Run the shell as a login shell (`bash -lc`, the default). False runs `bash -c`, skipping profile sourcing. */
|
|
26
26
|
loginShell?: boolean;
|
|
27
|
+
/** Internal executable selected by the host for a Windows shell or log trampoline. */
|
|
28
|
+
resolvedWindowsShell?: string;
|
|
27
29
|
cwd?: string;
|
|
28
30
|
env?: Record<string, string>;
|
|
29
31
|
}
|
|
@@ -160,8 +162,8 @@ export interface BackgroundTaskMeta {
|
|
|
160
162
|
env?: Record<string, string>;
|
|
161
163
|
/**
|
|
162
164
|
* The executable and argv this task was actually launched with, when that
|
|
163
|
-
* differs from `command`/`argv` above
|
|
164
|
-
*
|
|
165
|
+
* differs from `command`/`argv` above, such as an OS write-sandbox wrapper
|
|
166
|
+
* or a Windows watch shell selected at launch. Re-running a watch poll uses
|
|
165
167
|
* it verbatim, which is how a running task keeps the policy it started under
|
|
166
168
|
* even after the foreground policy changes. `command`/`argv` stay the operator's
|
|
167
169
|
* own request, so status, navigator, and goal surfaces read unchanged.
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import type { CommandResult } from "./types.js";
|
|
3
|
+
|
|
4
|
+
/** Version tag of the watch outcome fingerprint. A value from another version is adopted, never compared. */
|
|
5
|
+
export const WATCH_FINGERPRINT_VERSION = "v1";
|
|
6
|
+
/** OSC and CSI control sequences are display markup, not content. */
|
|
7
|
+
const TERMINAL_ESCAPE = /\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)|\u001b\[[0-?]*[ -/]*[@-~]/g;
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Text as the terminal would settle it. Redraw frames and control sequences are
|
|
11
|
+
* display churn: repainting the same visible line is not a new observation.
|
|
12
|
+
*/
|
|
13
|
+
function settledTerminalText(text: string): string {
|
|
14
|
+
return text
|
|
15
|
+
.replace(TERMINAL_ESCAPE, "")
|
|
16
|
+
.split("\n")
|
|
17
|
+
.map((line) => {
|
|
18
|
+
// A CR immediately before LF ends the line; any other CR overwrites it in place.
|
|
19
|
+
const body = line.endsWith("\r") ? line.slice(0, -1) : line;
|
|
20
|
+
return (body.split("\r").at(-1) ?? "").replace(/[ \t]+$/, "");
|
|
21
|
+
})
|
|
22
|
+
.join("\n")
|
|
23
|
+
.replace(/\n+$/, "");
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Objects compare by content regardless of key order, so reordered keys are not progress. */
|
|
27
|
+
function canonicalJsonText(value: unknown): string {
|
|
28
|
+
if (Array.isArray(value)) return `[${value.map(canonicalJsonText).join(",")}]`;
|
|
29
|
+
if (value && typeof value === "object") {
|
|
30
|
+
const record = value as Record<string, unknown>;
|
|
31
|
+
const entries = Object.keys(record).sort()
|
|
32
|
+
.map((key) => `${JSON.stringify(key)}:${canonicalJsonText(record[key])}`);
|
|
33
|
+
return `{${entries.join(",")}}`;
|
|
34
|
+
}
|
|
35
|
+
return JSON.stringify(value) ?? "null";
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** stdout compares as JSON content when it parses, and as settled text otherwise. */
|
|
39
|
+
function canonicalWatchStdout(stdout: string): string {
|
|
40
|
+
const settled = settledTerminalText(stdout);
|
|
41
|
+
try {
|
|
42
|
+
return `json:${canonicalJsonText(JSON.parse(settled))}`;
|
|
43
|
+
} catch {
|
|
44
|
+
return `text:${settled}`;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* What a poll observed, independent of when it ran. Exit status, signal, error,
|
|
50
|
+
* stdout content, and stderr content are included; poll metadata (start time,
|
|
51
|
+
* end time, duration, check count) is deliberately not, so it can never hide a
|
|
52
|
+
* watch that reports the same outcome forever. Watch stdout may carry its own
|
|
53
|
+
* timestamps: projecting meaningful fields is the caller's job, not this
|
|
54
|
+
* fingerprint's guess.
|
|
55
|
+
*/
|
|
56
|
+
export function watchOutcomeFingerprint(result: CommandResult): string {
|
|
57
|
+
// A runner may report why the check itself could not run; that is part of the
|
|
58
|
+
// observed outcome, not poll metadata.
|
|
59
|
+
const reported = (result as CommandResult & { error?: unknown }).error;
|
|
60
|
+
const error = typeof reported === "string" ? settledTerminalText(reported) : null;
|
|
61
|
+
const payload = JSON.stringify([
|
|
62
|
+
result.exitCode,
|
|
63
|
+
result.signal ?? null,
|
|
64
|
+
result.timedOut === true,
|
|
65
|
+
error,
|
|
66
|
+
canonicalWatchStdout(result.stdout),
|
|
67
|
+
settledTerminalText(result.stderr),
|
|
68
|
+
]);
|
|
69
|
+
return `${WATCH_FINGERPRINT_VERSION}:${createHash("sha256").update(payload).digest("hex")}`;
|
|
70
|
+
}
|