pi-better-server 0.6.0 → 0.7.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/package.json +4 -3
- package/scripts/measure-full-runtime/frontend.ts +10 -2
- package/scripts/measure-full-runtime.mjs +2 -0
- package/src/codex/return.ts +3 -2
- package/src/detach/extension.ts +20 -3
- package/src/event-log.ts +40 -12
- package/src/hosted-session.ts +11 -5
- package/src/remote-client/packages.ts +1 -4
- package/src/runtime/background-tools.ts +54 -8
- package/src/runtime/background.ts +16 -4
- package/src/runtime/domain/background/process.mjs +49 -11
- package/src/runtime/domain/background/supervisor/store.mjs +3 -3
- package/src/runtime/domain/background/supervisor/supervisor.mjs +9 -3
- package/src/runtime/domain/background-service/index.domain.mjs +19 -0
- package/src/runtime/domain/background-service/index.ts +19 -0
- package/src/runtime/domain/background-service/managed-frontend.domain.mjs +87 -5
- package/src/runtime/domain/background-service/managed-frontend.ts +76 -5
- package/src/runtime/domain/background-service/navigator-provider.domain.mjs +5 -0
- package/src/runtime/domain/background-service/navigator-provider.ts +4 -0
- package/src/runtime/domain/background-service/observed-waits.domain.mjs +203 -31
- package/src/runtime/domain/background-service/observed-waits.ts +168 -24
- package/src/runtime/domain/background-service/process.domain.mjs +49 -11
- package/src/runtime/domain/background-service/process.ts +45 -11
- package/src/runtime/domain/background-service/review-settings.domain.mjs +16 -0
- package/src/runtime/domain/background-service/review-settings.ts +18 -0
- package/src/runtime/domain/background-service/runtime.domain.mjs +8 -70
- package/src/runtime/domain/background-service/runtime.ts +8 -73
- package/src/runtime/domain/background-service/shared-harness-settings.domain.mjs +2 -3
- package/src/runtime/domain/background-service/shared-harness-settings.ts +2 -5
- package/src/runtime/domain/background-service/shared-navigator.domain.mjs +55 -28
- package/src/runtime/domain/background-service/shared-navigator.ts +47 -26
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.ts +9 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +5 -1
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +6 -0
- package/src/runtime/domain/background-service/shared-ssh-core/index.domain.mjs +1 -1
- package/src/runtime/domain/background-service/shared-ssh-core/index.ts +1 -1
- package/src/runtime/domain/background-service/stall.domain.mjs +5 -3
- package/src/runtime/domain/background-service/stall.ts +7 -4
- package/src/runtime/domain/background-service/supervised-progress.domain.mjs +42 -0
- package/src/runtime/domain/background-service/supervised-progress.ts +43 -0
- package/src/runtime/domain/background-service/supervisor/README.md +1 -4
- package/src/runtime/domain/background-service/supervisor/emit-runner.mjs +1 -0
- package/src/runtime/domain/background-service/supervisor/generated/process.mjs +49 -11
- package/src/runtime/domain/background-service/supervisor/generated/runner.mjs +47 -4
- package/src/runtime/domain/background-service/supervisor/generated/store.mjs +3 -3
- package/src/runtime/domain/background-service/supervisor/generated/watch-fingerprint.mjs +69 -0
- package/src/runtime/domain/background-service/supervisor/runner.domain.mjs +47 -4
- package/src/runtime/domain/background-service/supervisor/runner.ts +38 -3
- package/src/runtime/domain/background-service/supervisor/store.domain.mjs +3 -3
- package/src/runtime/domain/background-service/supervisor/store.ts +3 -3
- package/src/runtime/domain/background-service/supervisor/supervisor.domain.mjs +9 -3
- package/src/runtime/domain/background-service/supervisor/supervisor.ts +6 -3
- package/src/runtime/domain/background-service/tools.domain.mjs +22 -16
- package/src/runtime/domain/background-service/tools.ts +26 -16
- package/src/runtime/domain/background-service/types.ts +4 -2
- package/src/runtime/domain/background-service/watch-fingerprint.domain.mjs +67 -0
- package/src/runtime/domain/background-service/watch-fingerprint.ts +70 -0
- package/src/runtime/domain/catalog/catalog-preferences.mjs +1 -3
- package/src/runtime/domain/coordinator/src/outbox.mjs +7 -0
- package/src/runtime/domain/coordinator/src/store.mjs +5 -1
- package/src/runtime/domain/log-paths.mjs +8 -1
- package/src/runtime/domain/parse.mjs +9 -5
- package/src/runtime/domain/sandbox-policy/README.md +3 -3
- package/src/runtime/domain/sandbox-policy/package.json +1 -1
- package/src/runtime/domain/sandbox-policy/shared-harness-settings.domain.mjs +2 -3
- package/src/runtime/domain/sandbox-policy/shared-harness-settings.ts +2 -5
- package/src/runtime/domain/session-store.mjs +7 -0
- package/src/runtime/domain/shared-harness-settings.mjs +2 -3
- package/src/runtime/domain/subagents/README.md +12 -10
- package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +2 -5
- package/src/runtime/domain/subagents/assignment-outcomes.ts +2 -5
- package/src/runtime/domain/subagents/assignment-report.domain.mjs +22 -0
- package/src/runtime/domain/subagents/assignment-report.ts +20 -0
- package/src/runtime/domain/subagents/batch.mjs +13 -5
- package/src/runtime/domain/subagents/catalog-preferences.domain.mjs +1 -3
- package/src/runtime/domain/subagents/catalog-preferences.ts +1 -5
- package/src/runtime/domain/subagents/cleanup.domain.mjs +11 -2
- package/src/runtime/domain/subagents/cleanup.ts +10 -2
- package/src/runtime/domain/subagents/config.domain.mjs +5 -0
- package/src/runtime/domain/subagents/config.ts +8 -2
- package/src/runtime/domain/subagents/continuation.domain.mjs +4 -2
- package/src/runtime/domain/subagents/continuation.ts +4 -2
- package/src/runtime/domain/subagents/extensions.mjs +1 -0
- package/src/runtime/domain/subagents/failures.domain.mjs +11 -2
- package/src/runtime/domain/subagents/failures.ts +10 -2
- package/src/runtime/domain/subagents/finalization.domain.mjs +39 -32
- package/src/runtime/domain/subagents/finalization.ts +37 -30
- package/src/runtime/domain/subagents/git-workspace.domain.mjs +51 -6
- package/src/runtime/domain/subagents/git-workspace.ts +48 -6
- package/src/runtime/domain/subagents/index.domain.mjs +208 -75
- package/src/runtime/domain/subagents/index.ts +213 -75
- package/src/runtime/domain/subagents/isolated-workspace.domain.mjs +508 -0
- package/src/runtime/domain/subagents/isolated-workspace.ts +551 -0
- package/src/runtime/domain/subagents/list.mjs +2 -2
- package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +22 -5
- package/src/runtime/domain/subagents/managed-launch-client.ts +23 -6
- package/src/runtime/domain/subagents/output-payload.domain.mjs +24 -9
- package/src/runtime/domain/subagents/output-payload.ts +26 -12
- package/src/runtime/domain/subagents/package.json +4 -2
- package/src/runtime/domain/subagents/parse.domain.mjs +9 -5
- package/src/runtime/domain/subagents/parse.ts +10 -5
- package/src/runtime/domain/subagents/registry.domain.mjs +31 -25
- package/src/runtime/domain/subagents/registry.ts +31 -13
- package/src/runtime/domain/subagents/retained-result.domain.mjs +56 -0
- package/src/runtime/domain/subagents/retained-result.ts +65 -0
- package/src/runtime/domain/subagents/session-selection.domain.mjs +3 -1
- package/src/runtime/domain/subagents/session-selection.ts +2 -1
- package/src/runtime/domain/subagents/session-store.domain.mjs +7 -0
- package/src/runtime/domain/subagents/session-store.ts +9 -0
- package/src/runtime/domain/subagents/settings-page.domain.mjs +151 -107
- package/src/runtime/domain/subagents/settings-page.ts +147 -108
- package/src/runtime/domain/subagents/shared-catalog.domain.mjs +23 -7
- package/src/runtime/domain/subagents/shared-catalog.ts +23 -7
- package/src/runtime/domain/subagents/shared-harness-settings.domain.mjs +2 -3
- package/src/runtime/domain/subagents/shared-harness-settings.ts +2 -5
- package/src/runtime/domain/subagents/shared-navigator.domain.mjs +55 -28
- package/src/runtime/domain/subagents/shared-navigator.ts +47 -26
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.ts +9 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +5 -1
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +6 -0
- package/src/runtime/domain/subagents/task-guard.domain.mjs +14 -1
- package/src/runtime/domain/subagents/task-guard.ts +13 -1
- package/src/runtime/domain/subagents/task-policy.domain.mjs +2 -1
- package/src/runtime/domain/subagents/task-policy.ts +5 -1
- package/src/runtime/domain/subagents/tools.domain.mjs +4 -8
- package/src/runtime/domain/subagents/tools.ts +4 -7
- package/src/runtime/domain/subagents/work-observation.domain.mjs +25 -1
- package/src/runtime/domain/subagents/work-observation.ts +20 -1
- package/src/runtime/domain/subagents/workspace-files.domain.mjs +103 -0
- package/src/runtime/domain/subagents/workspace-files.ts +114 -0
- package/src/runtime/domain/subagents/workspace-prepare-worker.mjs +12 -0
- package/src/runtime/domain/subagents/workspace-scope.domain.d.mts +38 -0
- package/src/runtime/domain/subagents/workspace-scope.domain.mjs +5 -0
- package/src/runtime/domain/subagents/workspace-scope.ts +6 -0
- package/src/runtime/domain/subagents/worktree-feedback.domain.mjs +55 -0
- package/src/runtime/domain/subagents/worktree-feedback.ts +77 -0
- package/src/runtime/read-model.ts +4 -2
- package/src/runtime/root.ts +5 -2
- package/src/shared-ssh-core/index.ts +1 -1
- package/src/version.ts +1 -1
package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs
CHANGED
|
@@ -24,7 +24,7 @@ import { createContext, openDatabase, run } from "./sqlite.domain.mjs";
|
|
|
24
24
|
import { getOperation as readOperationRecord, listAssignmentCleanupOperations as readAssignmentCleanupOperations, listOperations as readOperationRecords, listRunningSupervisedBy as readRunningSupervisedBy, releaseSupervision as writeSupervisionRelease, recordSupervision as writeSupervision, recordTerminalOutcome as writeTerminalOutcome, registerOperation as writeOperation, } from "./operations.domain.mjs";
|
|
25
25
|
import { getChangeRevision as readChangeRevision, readDiscoveryClaim as readClaim, readDiscoveryState, releaseDiscoveryClaim as deleteDiscoveryClaim, tryClaimDiscovery as writeDiscoveryClaim, } from "./discovery.domain.mjs";
|
|
26
26
|
import { acknowledgeResult as writeAcknowledgement, cancelWait as writeCancellation, claimResume as writeClaim, findPendingWaitForOwner, getWait as readWait, listDependencies as readDependencies, listEvidencePins as readPins, listEvidenceReads as readReads, listResumeClaims as readClaims, listUnreconciledClaims, listWaits as readWaits, publishResumeAttempt as writeAttemptPublication, recordEvidencePin as writePin, recordEvidenceRead as writeRead, registerWait as writeWait, releaseEvidencePins as writePinRelease, holdFailedResume as writeHoldFailedResume, releaseResumeClaim as writeClaimRelease, transitionWaitPhase as writePhase, } from "./waits.domain.mjs";
|
|
27
|
-
import { claimOutbox as writeOutboxClaim, listDispatchableOutboxRecipients as readDispatchableOutboxRecipients, listOutbox as readOutbox, markOutboxDelivered as writeOutboxDelivery, releaseOutbox as writeOutboxRelease, } from "./outbox.domain.mjs";
|
|
27
|
+
import { claimOutbox as writeOutboxClaim, hasDeliveredWaitDependency as readDeliveredWaitDependency, listDispatchableOutboxRecipients as readDispatchableOutboxRecipients, listOutbox as readOutbox, markOutboxDelivered as writeOutboxDelivery, releaseOutbox as writeOutboxRelease, } from "./outbox.domain.mjs";
|
|
28
28
|
import { readOperationEvidence } from "./rows.domain.mjs";
|
|
29
29
|
import { SCHEMA_VERSION, } from "./types.domain.mjs";
|
|
30
30
|
export function openStore(options) {
|
|
@@ -250,6 +250,10 @@ export function openStore(options) {
|
|
|
250
250
|
alive();
|
|
251
251
|
return readOutbox(ctx, filter);
|
|
252
252
|
},
|
|
253
|
+
hasDeliveredWaitDependency(operationId, terminalRevision, recipient) {
|
|
254
|
+
alive();
|
|
255
|
+
return readDeliveredWaitDependency(ctx, operationId, terminalRevision, recipient);
|
|
256
|
+
},
|
|
253
257
|
listDispatchableOutboxRecipients() {
|
|
254
258
|
alive();
|
|
255
259
|
return readDispatchableOutboxRecipients(ctx);
|
|
@@ -68,6 +68,7 @@ import {
|
|
|
68
68
|
} from "./waits.ts";
|
|
69
69
|
import {
|
|
70
70
|
claimOutbox as writeOutboxClaim,
|
|
71
|
+
hasDeliveredWaitDependency as readDeliveredWaitDependency,
|
|
71
72
|
listDispatchableOutboxRecipients as readDispatchableOutboxRecipients,
|
|
72
73
|
listOutbox as readOutbox,
|
|
73
74
|
markOutboxDelivered as writeOutboxDelivery,
|
|
@@ -318,6 +319,7 @@ export interface Store {
|
|
|
318
319
|
// ---- outbox ----
|
|
319
320
|
|
|
320
321
|
listOutbox(filter?: OutboxFilter): OutboxEventRecord[];
|
|
322
|
+
hasDeliveredWaitDependency(operationId: string, terminalRevision: number, recipient: OwnerIdentity): boolean;
|
|
321
323
|
/** Lightweight dispatch candidates; evidence is read only after a claim succeeds. */
|
|
322
324
|
listDispatchableOutboxRecipients(): Array<{ recipient: OwnerIdentity; count: number }>;
|
|
323
325
|
/** Claim pending deliveries for a `ready`/`resuming` generation. */
|
|
@@ -559,6 +561,10 @@ export function openStore(options: StoreOptions): Store {
|
|
|
559
561
|
alive();
|
|
560
562
|
return readOutbox(ctx, filter);
|
|
561
563
|
},
|
|
564
|
+
hasDeliveredWaitDependency(operationId, terminalRevision, recipient) {
|
|
565
|
+
alive();
|
|
566
|
+
return readDeliveredWaitDependency(ctx, operationId, terminalRevision, recipient);
|
|
567
|
+
},
|
|
562
568
|
listDispatchableOutboxRecipients() {
|
|
563
569
|
alive();
|
|
564
570
|
return readDispatchableOutboxRecipients(ctx);
|
|
@@ -122,7 +122,7 @@ export function wrapRemoteBashCommand(input) {
|
|
|
122
122
|
}
|
|
123
123
|
export function defaultSshControlPathRoot() {
|
|
124
124
|
const agentDirectory = process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
|
|
125
|
-
const root =
|
|
125
|
+
const root = resolve(agentDirectory, "ssh-control");
|
|
126
126
|
// A long agent directory would push the socket past the unix path limit; fall back to a short per-user root.
|
|
127
127
|
if (Buffer.byteLength(join(root, MUX_CONTROL_PATH_NAME_TEMPLATE)) <= MAX_SSH_CONTROL_PATH_BYTES)
|
|
128
128
|
return root;
|
|
@@ -328,7 +328,7 @@ export function wrapRemoteBashCommand(input: RemoteBashCommandInput): string {
|
|
|
328
328
|
|
|
329
329
|
export function defaultSshControlPathRoot(): string {
|
|
330
330
|
const agentDirectory = process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
|
|
331
|
-
const root =
|
|
331
|
+
const root = resolve(agentDirectory, "ssh-control");
|
|
332
332
|
// A long agent directory would push the socket past the unix path limit; fall back to a short per-user root.
|
|
333
333
|
if (Buffer.byteLength(join(root, MUX_CONTROL_PATH_NAME_TEMPLATE)) <= MAX_SSH_CONTROL_PATH_BYTES) return root;
|
|
334
334
|
return join("/tmp", `pi-ssh-${process.getuid?.() ?? "user"}`);
|
|
@@ -46,12 +46,14 @@ export function observeBackgroundTaskStall(meta, now = Date.now()) {
|
|
|
46
46
|
thresholds: backgroundTaskStallThresholds(),
|
|
47
47
|
});
|
|
48
48
|
}
|
|
49
|
+
export function formatProgressDuration(ms) {
|
|
50
|
+
const seconds = Math.max(0, Math.round(ms / 1000));
|
|
51
|
+
return seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m${(seconds % 60).toString().padStart(2, "0")}s`;
|
|
52
|
+
}
|
|
49
53
|
/** Silence is an observation, not proof that the process is hung. */
|
|
50
54
|
export function formatBackgroundTaskStall(observation) {
|
|
51
55
|
if (observation.state !== "quiet" && observation.state !== "stalled")
|
|
52
56
|
return undefined;
|
|
53
|
-
const seconds = Math.max(0, Math.round((observation.ageMs ?? 0) / 1000));
|
|
54
|
-
const duration = seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m${(seconds % 60).toString().padStart(2, "0")}s`;
|
|
55
57
|
const label = observation.state === "stalled" ? "suspected stall" : "quiet";
|
|
56
|
-
return `${label}; no observed progress for ${
|
|
58
|
+
return `${label}; no observed progress for ${formatProgressDuration(observation.ageMs ?? 0)}`;
|
|
57
59
|
}
|
|
@@ -47,11 +47,14 @@ export function observeBackgroundTaskStall(meta: BackgroundTaskMeta, now = Date.
|
|
|
47
47
|
});
|
|
48
48
|
}
|
|
49
49
|
|
|
50
|
+
export function formatProgressDuration(ms: number): string {
|
|
51
|
+
const seconds = Math.max(0, Math.round(ms / 1000));
|
|
52
|
+
return seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m${(seconds % 60).toString().padStart(2, "0")}s`;
|
|
53
|
+
}
|
|
54
|
+
|
|
50
55
|
/** Silence is an observation, not proof that the process is hung. */
|
|
51
|
-
export function formatBackgroundTaskStall(observation: StallObservation): string | undefined {
|
|
56
|
+
export function formatBackgroundTaskStall(observation: Pick<StallObservation, "state" | "ageMs">): string | undefined {
|
|
52
57
|
if (observation.state !== "quiet" && observation.state !== "stalled") return undefined;
|
|
53
|
-
const seconds = Math.max(0, Math.round((observation.ageMs ?? 0) / 1000));
|
|
54
|
-
const duration = seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m${(seconds % 60).toString().padStart(2, "0")}s`;
|
|
55
58
|
const label = observation.state === "stalled" ? "suspected stall" : "quiet";
|
|
56
|
-
return `${label}; no observed progress for ${
|
|
59
|
+
return `${label}; no observed progress for ${formatProgressDuration(observation.ageMs ?? 0)}`;
|
|
57
60
|
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// Generated fixed launch domain from packages/pi-better-background-tasks/src/supervised-progress.ts. Do not edit directly.
|
|
2
|
+
import { readFileSync, statSync } from "node:fs";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { backgroundTaskStallThresholds, formatBackgroundTaskStall } from "./stall.domain.mjs";
|
|
5
|
+
import { observeStall } from "./shared-stall-detector.domain.mjs";
|
|
6
|
+
export function supervisedProgress(source, now = Date.now()) {
|
|
7
|
+
if (source?.status !== "running" || !source.claim)
|
|
8
|
+
return;
|
|
9
|
+
let observedAt;
|
|
10
|
+
try {
|
|
11
|
+
observedAt = JSON.parse(readFileSync(join(dirname(source.logs.stdout), "progress.json"), "utf8")).observedAt;
|
|
12
|
+
if (!Number.isFinite(observedAt) || observedAt < source.claim.claimedAt)
|
|
13
|
+
return;
|
|
14
|
+
}
|
|
15
|
+
catch (error) {
|
|
16
|
+
// Older process runners still have separate append-only streams. Older watches
|
|
17
|
+
// appended every poll, so their logs cannot establish a meaningful progress time.
|
|
18
|
+
if (error.code !== "ENOENT" || source.kind !== "process")
|
|
19
|
+
return;
|
|
20
|
+
observedAt = source.claim.claimedAt;
|
|
21
|
+
for (const path of [source.logs.stdout, source.logs.stderr]) {
|
|
22
|
+
if (!path)
|
|
23
|
+
continue;
|
|
24
|
+
try {
|
|
25
|
+
const stat = statSync(path, { throwIfNoEntry: false });
|
|
26
|
+
if (stat?.size)
|
|
27
|
+
observedAt = Math.max(observedAt, Math.trunc(stat.mtimeMs));
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
const { state, thresholds } = observeStall({ now, lastProgressAt: observedAt, thresholds: backgroundTaskStallThresholds() });
|
|
35
|
+
const quietAt = observedAt + thresholds.quietMs;
|
|
36
|
+
const stalledAt = observedAt + thresholds.stallMs;
|
|
37
|
+
const alertAt = stalledAt + 60_000;
|
|
38
|
+
return { observedAt, state, alertDue: now >= alertAt, nextDeadline: [quietAt, stalledAt, alertAt].find(time => time > now) };
|
|
39
|
+
}
|
|
40
|
+
export function describeSupervisedProgress(progress, now = Date.now()) {
|
|
41
|
+
return formatBackgroundTaskStall({ ...progress, ageMs: now - progress.observedAt });
|
|
42
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { readFileSync, statSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { backgroundTaskStallThresholds, formatBackgroundTaskStall } from "./stall.js";
|
|
4
|
+
import { observeStall } from "./shared-stall-detector.js";
|
|
5
|
+
|
|
6
|
+
interface ProgressSource {
|
|
7
|
+
status: string;
|
|
8
|
+
kind: string;
|
|
9
|
+
claim?: { claimedAt: number };
|
|
10
|
+
logs: { stdout: string; stderr?: string };
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function supervisedProgress(source: ProgressSource | undefined, now = Date.now()) {
|
|
14
|
+
if (source?.status !== "running" || !source.claim) return;
|
|
15
|
+
let observedAt: number;
|
|
16
|
+
try {
|
|
17
|
+
observedAt = JSON.parse(readFileSync(join(dirname(source.logs.stdout), "progress.json"), "utf8")).observedAt;
|
|
18
|
+
if (!Number.isFinite(observedAt) || observedAt < source.claim.claimedAt) return;
|
|
19
|
+
} catch (error) {
|
|
20
|
+
// Older process runners still have separate append-only streams. Older watches
|
|
21
|
+
// appended every poll, so their logs cannot establish a meaningful progress time.
|
|
22
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT" || source.kind !== "process") return;
|
|
23
|
+
observedAt = source.claim.claimedAt;
|
|
24
|
+
for (const path of [source.logs.stdout, source.logs.stderr]) {
|
|
25
|
+
if (!path) continue;
|
|
26
|
+
try {
|
|
27
|
+
const stat = statSync(path, { throwIfNoEntry: false });
|
|
28
|
+
if (stat?.size) observedAt = Math.max(observedAt, Math.trunc(stat.mtimeMs));
|
|
29
|
+
} catch { return; }
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
const { state, thresholds } = observeStall({ now, lastProgressAt: observedAt, thresholds: backgroundTaskStallThresholds() });
|
|
33
|
+
const quietAt = observedAt + thresholds.quietMs;
|
|
34
|
+
const stalledAt = observedAt + thresholds.stallMs;
|
|
35
|
+
const alertAt = stalledAt + 60_000;
|
|
36
|
+
return { observedAt, state, alertDue: now >= alertAt, nextDeadline: [quietAt, stalledAt, alertAt].find(time => time > now) };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export type SupervisedProgress = NonNullable<ReturnType<typeof supervisedProgress>>;
|
|
40
|
+
|
|
41
|
+
export function describeSupervisedProgress(progress: SupervisedProgress, now = Date.now()) {
|
|
42
|
+
return formatBackgroundTaskStall({ ...progress, ageMs: now - progress.observedAt });
|
|
43
|
+
}
|
|
@@ -1,9 +1,6 @@
|
|
|
1
1
|
# Detached local supervisor
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
[observed-waits design](../../../../docs/plans/observed-waits-design.md): local process and command-watch
|
|
5
|
-
supervision that survives the process that launched it. Nothing in this directory is wired into the
|
|
6
|
-
Background Tasks tools yet; the parent owns that integration.
|
|
3
|
+
The detached supervisor runs local processes and command watches after the launching frontend exits. The coordinator retains the wait and its owner. [Observed waits](https://github.com/1aboveio/pi-better-harness/blob/main/docs/adr/0020-observed-waits-retain-an-owner.md) · [Supervisor design](https://github.com/1aboveio/pi-better-harness/blob/main/docs/plans/observed-waits-design.md)
|
|
7
4
|
|
|
8
5
|
## Contract
|
|
9
6
|
|
|
@@ -36,6 +36,7 @@ const CLOSURE = [
|
|
|
36
36
|
{ source: join(here, "store.ts"), out: "store.mjs" },
|
|
37
37
|
{ source: join(here, "types.ts"), out: "types.mjs" },
|
|
38
38
|
{ source: join(here, "identity.ts"), out: "identity.mjs" },
|
|
39
|
+
{ source: join(here, "..", "watch-fingerprint.ts"), out: "watch-fingerprint.mjs" },
|
|
39
40
|
{ source: join(here, "..", "conditions.ts"), out: "conditions.mjs" },
|
|
40
41
|
{ source: join(here, "..", "process.ts"), out: "process.mjs" },
|
|
41
42
|
{ source: join(here, "..", "process-identity.ts"), out: "process-identity.mjs" },
|
|
@@ -2,8 +2,9 @@
|
|
|
2
2
|
// Generated by src/supervisor/emit-runner.mjs from the TypeScript source.
|
|
3
3
|
// Do not edit: change the source and re-run the emitter (a drift test enforces this).
|
|
4
4
|
import { spawn, spawnSync } from "node:child_process";
|
|
5
|
-
import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, writeSync } from "node:fs";
|
|
6
|
-
import {
|
|
5
|
+
import { accessSync, appendFileSync, closeSync, constants, existsSync, mkdirSync, openSync, readFileSync, writeSync } from "node:fs";
|
|
6
|
+
import { homedir } from "node:os";
|
|
7
|
+
import { dirname, join, win32 } from "node:path";
|
|
7
8
|
/** Known Git for Windows locations; `bash -lc` needs a real bash, not the WSL shim. */
|
|
8
9
|
const WINDOWS_BASH_CANDIDATES = [
|
|
9
10
|
"C:\\Program Files\\Git\\bin\\bash.exe",
|
|
@@ -16,7 +17,8 @@ const WINDOWS_BASH_CANDIDATES = [
|
|
|
16
17
|
* POSIX keeps `/bin/bash`. Windows has no `/bin/bash`, and the `bash.exe` found
|
|
17
18
|
* on PATH is usually the WSL launcher in System32 or the WindowsApps alias,
|
|
18
19
|
* either of which would run the command inside WSL instead of Windows. Prefer
|
|
19
|
-
* an explicit override, then Git for Windows,
|
|
20
|
+
* an explicit override, then Pi's shellPath, Git for Windows, and a non-WSL
|
|
21
|
+
* `bash.exe` on PATH.
|
|
20
22
|
*
|
|
21
23
|
* Resolved lazily at spawn time, not module load: env-injection extensions
|
|
22
24
|
* (e.g. pi-env) may apply settings.json `env` values after this module is
|
|
@@ -24,27 +26,62 @@ const WINDOWS_BASH_CANDIDATES = [
|
|
|
24
26
|
*
|
|
25
27
|
* Exposed for tests and reuse.
|
|
26
28
|
*/
|
|
27
|
-
export function resolveDefaultShell() {
|
|
29
|
+
export function resolveDefaultShell(shellPath) {
|
|
28
30
|
const fromEnv = process.env.PI_BETTER_BACKGROUND_TASKS_SHELL;
|
|
29
31
|
if (fromEnv)
|
|
30
32
|
return fromEnv;
|
|
31
33
|
if (process.platform !== "win32")
|
|
32
34
|
return "/bin/bash";
|
|
33
|
-
|
|
35
|
+
const configured = shellPath ?? readWindowsShellSetting();
|
|
36
|
+
const tried = [];
|
|
37
|
+
if (configured?.trim()) {
|
|
38
|
+
const candidate = /^~[\\/]/.test(configured) ? win32.join(homedir(), configured.slice(2)) : configured;
|
|
39
|
+
tried.push(candidate);
|
|
40
|
+
try {
|
|
41
|
+
accessSync(candidate, constants.F_OK);
|
|
42
|
+
return candidate;
|
|
43
|
+
}
|
|
44
|
+
catch { /* An unavailable setting leaves standard Windows discovery enabled. */ }
|
|
45
|
+
}
|
|
46
|
+
const gitCandidates = [process.env.ProgramFiles, process.env["ProgramFiles(x86)"]]
|
|
47
|
+
.filter((directory) => Boolean(directory))
|
|
48
|
+
.map(directory => win32.join(directory, "Git", "bin", "bash.exe"));
|
|
49
|
+
for (const candidate of new Set([...gitCandidates, ...WINDOWS_BASH_CANDIDATES])) {
|
|
50
|
+
tried.push(candidate);
|
|
34
51
|
if (existsSync(candidate))
|
|
35
52
|
return candidate;
|
|
36
53
|
}
|
|
37
|
-
for (const dir of (process.env.PATH ?? "").split(";")) {
|
|
54
|
+
for (const dir of (process.env.PATH ?? process.env.Path ?? "").split(";")) {
|
|
38
55
|
const trimmed = dir.trim();
|
|
39
56
|
if (!trimmed || /(^|[\\/])(system32|windowsapps)([\\/]|$)/i.test(trimmed))
|
|
40
57
|
continue;
|
|
41
|
-
const candidate = join(trimmed, "bash.exe");
|
|
58
|
+
const candidate = win32.join(trimmed, "bash.exe");
|
|
59
|
+
tried.push(candidate);
|
|
42
60
|
if (existsSync(candidate))
|
|
43
61
|
return candidate;
|
|
44
62
|
}
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
63
|
+
throw new Error("No Bash executable found for Windows Background tasks. Set Pi's shellPath in settings.json or "
|
|
64
|
+
+ "PI_BETTER_BACKGROUND_TASKS_SHELL to a working bash.exe. Searched:\n " + [...new Set(tried)].join("\n "));
|
|
65
|
+
}
|
|
66
|
+
function readWindowsShellSetting() {
|
|
67
|
+
const agentDir = process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
|
|
68
|
+
try {
|
|
69
|
+
const settings = JSON.parse(readFileSync(join(agentDir, "settings.json"), "utf8"));
|
|
70
|
+
return typeof settings?.shellPath === "string" ? settings.shellPath : undefined;
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
return undefined;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
/** Capture effective session settings before dispatching a Windows launch. */
|
|
77
|
+
export function resolveWindowsLaunchShell(pi) {
|
|
78
|
+
if (process.platform !== "win32")
|
|
79
|
+
return undefined;
|
|
80
|
+
const override = process.env.PI_BETTER_BACKGROUND_TASKS_SHELL;
|
|
81
|
+
if (override)
|
|
82
|
+
return override;
|
|
83
|
+
const settings = pi.getSettings?.();
|
|
84
|
+
return resolveDefaultShell(typeof settings?.shellPath === "string" ? settings.shellPath : undefined);
|
|
48
85
|
}
|
|
49
86
|
/** How long a timed-out process group has to exit on SIGTERM before SIGKILL. */
|
|
50
87
|
const TERMINATION_GRACE_MS = 2_000;
|
|
@@ -497,7 +534,8 @@ export function commandExecution(spec) {
|
|
|
497
534
|
const [command, ...args] = spec.argv;
|
|
498
535
|
return { execPath: command, execArgs: args };
|
|
499
536
|
}
|
|
500
|
-
|
|
537
|
+
const resolved = process.platform === "win32" ? spec.resolvedWindowsShell : undefined;
|
|
538
|
+
return { execPath: resolved ?? resolveDefaultShell(), execArgs: [spec.loginShell === false ? "-c" : "-lc", spec.command] };
|
|
501
539
|
}
|
|
502
540
|
function spawnArgs(spec, detached, stdio) {
|
|
503
541
|
const env = { ...process.env, ...spec.env };
|
|
@@ -32,14 +32,15 @@
|
|
|
32
32
|
*/
|
|
33
33
|
import { spawn } from "node:child_process";
|
|
34
34
|
import { closeSync, openSync, realpathSync } from "node:fs";
|
|
35
|
-
import { resolve } from "node:path";
|
|
35
|
+
import { join, resolve } from "node:path";
|
|
36
36
|
import { setTimeout as delay } from "node:timers/promises";
|
|
37
37
|
import { fileURLToPath } from "node:url";
|
|
38
|
+
import { watchOutcomeFingerprint } from "./watch-fingerprint.mjs";
|
|
38
39
|
import { evaluateCondition, validateCondition } from "./conditions.mjs";
|
|
39
40
|
import { completeUtf8Length, stopProcessGroup, utf8PrefixLength } from "./process.mjs";
|
|
40
41
|
import { readProcessStartToken } from "./process-identity.mjs";
|
|
41
42
|
import { processGroupAlive } from "./identity.mjs";
|
|
42
|
-
import { appendEvent, appendStreamBytes, claimLaunch, ensureSupervisorTaskDir, readLaunchRecord, readStopRequest, writeCommandRecord, writeTerminalRecord, } from "./store.mjs";
|
|
43
|
+
import { appendEvent, appendStreamBytes, claimLaunch, ensureSupervisorTaskDir, readLaunchRecord, readStopRequest, writeCommandRecord, writeTerminalRecord, writeTextAtomic, } from "./store.mjs";
|
|
43
44
|
import { DEFAULT_TERMINAL_TAIL_BYTES, DEFAULT_WATCH_INTERVAL_MS, SUPERVISOR_GROUP_CLEANUP_DEADLINE_MS, SUPERVISOR_POLL_MS, SUPERVISOR_RECORD_VERSION, SUPERVISOR_RUNNER_VERSION, SUPERVISOR_TERMINATION_GRACE_MS, } from "./types.mjs";
|
|
44
45
|
/** How long the runner waits for `close` after the child reported `exit`. */
|
|
45
46
|
const PIPE_CLOSE_GRACE_MS = 1_000;
|
|
@@ -117,6 +118,39 @@ function streamChunk(sink, chunk, maxBytes) {
|
|
|
117
118
|
sink.tailBytes = keep.length;
|
|
118
119
|
}
|
|
119
120
|
}
|
|
121
|
+
/** Coalesce stream bursts while retaining the timestamp of the last byte, including discarded output. */
|
|
122
|
+
function progressRecorder(directory) {
|
|
123
|
+
const path = join(directory, "progress.json");
|
|
124
|
+
let pending;
|
|
125
|
+
let timer;
|
|
126
|
+
let lastWrite = 0;
|
|
127
|
+
const flush = () => {
|
|
128
|
+
timer = undefined;
|
|
129
|
+
if (!pending)
|
|
130
|
+
return;
|
|
131
|
+
try {
|
|
132
|
+
writeTextAtomic(path, JSON.stringify(pending));
|
|
133
|
+
}
|
|
134
|
+
catch (error) {
|
|
135
|
+
process.stderr.write(`Could not record Background progress: ${String(error)}\n`);
|
|
136
|
+
}
|
|
137
|
+
lastWrite = Date.now();
|
|
138
|
+
};
|
|
139
|
+
return (observedAt, fingerprint) => {
|
|
140
|
+
if (fingerprint !== undefined && pending?.fingerprint === fingerprint)
|
|
141
|
+
return;
|
|
142
|
+
pending = { observedAt, fingerprint };
|
|
143
|
+
if (timer)
|
|
144
|
+
return;
|
|
145
|
+
const remaining = lastWrite + 1000 - Date.now();
|
|
146
|
+
if (remaining <= 0)
|
|
147
|
+
flush();
|
|
148
|
+
else {
|
|
149
|
+
timer = setTimeout(flush, remaining);
|
|
150
|
+
timer.unref();
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
}
|
|
120
154
|
function startToken(pid) {
|
|
121
155
|
return pid === undefined ? undefined : readProcessStartToken(pid);
|
|
122
156
|
}
|
|
@@ -389,15 +423,21 @@ function runChild(ctx, plan) {
|
|
|
389
423
|
};
|
|
390
424
|
child.stdout?.on("data", (chunk) => {
|
|
391
425
|
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
392
|
-
if (plan.mode === "stream")
|
|
426
|
+
if (plan.mode === "stream") {
|
|
393
427
|
streamChunk(ctx.stdout, buffer, plan.maxBytes);
|
|
428
|
+
if (buffer.length)
|
|
429
|
+
ctx.progress(Date.now());
|
|
430
|
+
}
|
|
394
431
|
else
|
|
395
432
|
captureChunk(stdoutCapture, buffer, plan.maxBytes);
|
|
396
433
|
});
|
|
397
434
|
child.stderr?.on("data", (chunk) => {
|
|
398
435
|
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
399
|
-
if (plan.mode === "stream")
|
|
436
|
+
if (plan.mode === "stream") {
|
|
400
437
|
streamChunk(ctx.stderr, buffer, plan.maxBytes);
|
|
438
|
+
if (buffer.length)
|
|
439
|
+
ctx.progress(Date.now());
|
|
440
|
+
}
|
|
401
441
|
else
|
|
402
442
|
captureChunk(stderrCapture, buffer, plan.maxBytes);
|
|
403
443
|
});
|
|
@@ -596,6 +636,7 @@ async function runWatch(ctx) {
|
|
|
596
636
|
if (ctx.finalized)
|
|
597
637
|
return;
|
|
598
638
|
ctx.checks += 1;
|
|
639
|
+
ctx.progress(outcome.endedAt, watchOutcomeFingerprint({ ...asCommandResult(outcome), ...(outcome.spawnError ? { error: outcome.spawnError } : {}) }));
|
|
599
640
|
// Per-check output keeps the streams apart: stdout bytes in stdout.log, stderr in stderr.log.
|
|
600
641
|
streamChunk(ctx.stdout, Buffer.from(outcome.stdout), ctx.launch.maxLogBytes);
|
|
601
642
|
streamChunk(ctx.stderr, Buffer.from(outcome.stderr), ctx.launch.maxLogBytes);
|
|
@@ -823,9 +864,11 @@ function main() {
|
|
|
823
864
|
checks: 0,
|
|
824
865
|
stdout,
|
|
825
866
|
stderr,
|
|
867
|
+
progress: progressRecorder(paths.dir),
|
|
826
868
|
stopRequested: false,
|
|
827
869
|
finalized: false,
|
|
828
870
|
};
|
|
871
|
+
ctx.progress(ctx.startedAt);
|
|
829
872
|
appendEvent(paths.events, `claimed runner_pid=${process.pid} runner_version=${SUPERVISOR_RUNNER_VERSION} kind=${launch.kind} cwd=${launch.command.cwd}`);
|
|
830
873
|
const onSignal = (signal) => {
|
|
831
874
|
appendEvent(paths.events, `runner received ${signal}`);
|
|
@@ -330,13 +330,13 @@ function readText(path) {
|
|
|
330
330
|
catch (error) {
|
|
331
331
|
if (error.code === "ENOENT")
|
|
332
332
|
return { missing: true };
|
|
333
|
-
return { missing:
|
|
333
|
+
return { missing: false, error: error instanceof Error ? error.message : String(error) };
|
|
334
334
|
}
|
|
335
335
|
}
|
|
336
336
|
function readJsonRecord(path, problem) {
|
|
337
337
|
const read = readText(path);
|
|
338
|
-
if (read.
|
|
339
|
-
return { missing:
|
|
338
|
+
if (read.value === undefined)
|
|
339
|
+
return { missing: read.missing, error: read.error };
|
|
340
340
|
let parsed;
|
|
341
341
|
try {
|
|
342
342
|
parsed = JSON.parse(read.value);
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// Generated fixed launch domain from packages/pi-better-background-tasks/src/supervisor/generated/watch-fingerprint.mjs. Do not edit directly.
|
|
2
|
+
// Generated by src/supervisor/emit-runner.mjs from the TypeScript source.
|
|
3
|
+
// Do not edit: change the source and re-run the emitter (a drift test enforces this).
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
/** Version tag of the watch outcome fingerprint. A value from another version is adopted, never compared. */
|
|
6
|
+
export const WATCH_FINGERPRINT_VERSION = "v1";
|
|
7
|
+
/** OSC and CSI control sequences are display markup, not content. */
|
|
8
|
+
const TERMINAL_ESCAPE = /\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)|\u001b\[[0-?]*[ -/]*[@-~]/g;
|
|
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) {
|
|
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
|
+
/** Objects compare by content regardless of key order, so reordered keys are not progress. */
|
|
26
|
+
function canonicalJsonText(value) {
|
|
27
|
+
if (Array.isArray(value))
|
|
28
|
+
return `[${value.map(canonicalJsonText).join(",")}]`;
|
|
29
|
+
if (value && typeof value === "object") {
|
|
30
|
+
const record = value;
|
|
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
|
+
/** stdout compares as JSON content when it parses, and as settled text otherwise. */
|
|
38
|
+
function canonicalWatchStdout(stdout) {
|
|
39
|
+
const settled = settledTerminalText(stdout);
|
|
40
|
+
try {
|
|
41
|
+
return `json:${canonicalJsonText(JSON.parse(settled))}`;
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return `text:${settled}`;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* What a poll observed, independent of when it ran. Exit status, signal, error,
|
|
49
|
+
* stdout content, and stderr content are included; poll metadata (start time,
|
|
50
|
+
* end time, duration, check count) is deliberately not, so it can never hide a
|
|
51
|
+
* watch that reports the same outcome forever. Watch stdout may carry its own
|
|
52
|
+
* timestamps: projecting meaningful fields is the caller's job, not this
|
|
53
|
+
* fingerprint's guess.
|
|
54
|
+
*/
|
|
55
|
+
export function watchOutcomeFingerprint(result) {
|
|
56
|
+
// A runner may report why the check itself could not run; that is part of the
|
|
57
|
+
// observed outcome, not poll metadata.
|
|
58
|
+
const reported = result.error;
|
|
59
|
+
const error = typeof reported === "string" ? settledTerminalText(reported) : null;
|
|
60
|
+
const payload = JSON.stringify([
|
|
61
|
+
result.exitCode,
|
|
62
|
+
result.signal ?? null,
|
|
63
|
+
result.timedOut === true,
|
|
64
|
+
error,
|
|
65
|
+
canonicalWatchStdout(result.stdout),
|
|
66
|
+
settledTerminalText(result.stderr),
|
|
67
|
+
]);
|
|
68
|
+
return `${WATCH_FINGERPRINT_VERSION}:${createHash("sha256").update(payload).digest("hex")}`;
|
|
69
|
+
}
|
|
@@ -30,14 +30,15 @@
|
|
|
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.domain.mjs";
|
|
36
37
|
import { evaluateCondition, validateCondition } from "../conditions.domain.mjs";
|
|
37
38
|
import { completeUtf8Length, stopProcessGroup, utf8PrefixLength } from "../process.domain.mjs";
|
|
38
39
|
import { readProcessStartToken } from "../process-identity.domain.mjs";
|
|
39
40
|
import { processGroupAlive } from "./identity.domain.mjs";
|
|
40
|
-
import { appendEvent, appendStreamBytes, claimLaunch, ensureSupervisorTaskDir, readLaunchRecord, readStopRequest, writeCommandRecord, writeTerminalRecord, } from "./store.domain.mjs";
|
|
41
|
+
import { appendEvent, appendStreamBytes, claimLaunch, ensureSupervisorTaskDir, readLaunchRecord, readStopRequest, writeCommandRecord, writeTerminalRecord, writeTextAtomic, } from "./store.domain.mjs";
|
|
41
42
|
import { DEFAULT_TERMINAL_TAIL_BYTES, DEFAULT_WATCH_INTERVAL_MS, SUPERVISOR_GROUP_CLEANUP_DEADLINE_MS, SUPERVISOR_POLL_MS, SUPERVISOR_RECORD_VERSION, SUPERVISOR_RUNNER_VERSION, SUPERVISOR_TERMINATION_GRACE_MS, } from "./types.domain.mjs";
|
|
42
43
|
/** How long the runner waits for `close` after the child reported `exit`. */
|
|
43
44
|
const PIPE_CLOSE_GRACE_MS = 1_000;
|
|
@@ -115,6 +116,39 @@ function streamChunk(sink, chunk, maxBytes) {
|
|
|
115
116
|
sink.tailBytes = keep.length;
|
|
116
117
|
}
|
|
117
118
|
}
|
|
119
|
+
/** Coalesce stream bursts while retaining the timestamp of the last byte, including discarded output. */
|
|
120
|
+
function progressRecorder(directory) {
|
|
121
|
+
const path = join(directory, "progress.json");
|
|
122
|
+
let pending;
|
|
123
|
+
let timer;
|
|
124
|
+
let lastWrite = 0;
|
|
125
|
+
const flush = () => {
|
|
126
|
+
timer = undefined;
|
|
127
|
+
if (!pending)
|
|
128
|
+
return;
|
|
129
|
+
try {
|
|
130
|
+
writeTextAtomic(path, JSON.stringify(pending));
|
|
131
|
+
}
|
|
132
|
+
catch (error) {
|
|
133
|
+
process.stderr.write(`Could not record Background progress: ${String(error)}\n`);
|
|
134
|
+
}
|
|
135
|
+
lastWrite = Date.now();
|
|
136
|
+
};
|
|
137
|
+
return (observedAt, fingerprint) => {
|
|
138
|
+
if (fingerprint !== undefined && pending?.fingerprint === fingerprint)
|
|
139
|
+
return;
|
|
140
|
+
pending = { observedAt, fingerprint };
|
|
141
|
+
if (timer)
|
|
142
|
+
return;
|
|
143
|
+
const remaining = lastWrite + 1000 - Date.now();
|
|
144
|
+
if (remaining <= 0)
|
|
145
|
+
flush();
|
|
146
|
+
else {
|
|
147
|
+
timer = setTimeout(flush, remaining);
|
|
148
|
+
timer.unref();
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
}
|
|
118
152
|
function startToken(pid) {
|
|
119
153
|
return pid === undefined ? undefined : readProcessStartToken(pid);
|
|
120
154
|
}
|
|
@@ -387,15 +421,21 @@ function runChild(ctx, plan) {
|
|
|
387
421
|
};
|
|
388
422
|
child.stdout?.on("data", (chunk) => {
|
|
389
423
|
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
390
|
-
if (plan.mode === "stream")
|
|
424
|
+
if (plan.mode === "stream") {
|
|
391
425
|
streamChunk(ctx.stdout, buffer, plan.maxBytes);
|
|
426
|
+
if (buffer.length)
|
|
427
|
+
ctx.progress(Date.now());
|
|
428
|
+
}
|
|
392
429
|
else
|
|
393
430
|
captureChunk(stdoutCapture, buffer, plan.maxBytes);
|
|
394
431
|
});
|
|
395
432
|
child.stderr?.on("data", (chunk) => {
|
|
396
433
|
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
397
|
-
if (plan.mode === "stream")
|
|
434
|
+
if (plan.mode === "stream") {
|
|
398
435
|
streamChunk(ctx.stderr, buffer, plan.maxBytes);
|
|
436
|
+
if (buffer.length)
|
|
437
|
+
ctx.progress(Date.now());
|
|
438
|
+
}
|
|
399
439
|
else
|
|
400
440
|
captureChunk(stderrCapture, buffer, plan.maxBytes);
|
|
401
441
|
});
|
|
@@ -594,6 +634,7 @@ async function runWatch(ctx) {
|
|
|
594
634
|
if (ctx.finalized)
|
|
595
635
|
return;
|
|
596
636
|
ctx.checks += 1;
|
|
637
|
+
ctx.progress(outcome.endedAt, watchOutcomeFingerprint({ ...asCommandResult(outcome), ...(outcome.spawnError ? { error: outcome.spawnError } : {}) }));
|
|
597
638
|
// Per-check output keeps the streams apart: stdout bytes in stdout.log, stderr in stderr.log.
|
|
598
639
|
streamChunk(ctx.stdout, Buffer.from(outcome.stdout), ctx.launch.maxLogBytes);
|
|
599
640
|
streamChunk(ctx.stderr, Buffer.from(outcome.stderr), ctx.launch.maxLogBytes);
|
|
@@ -821,9 +862,11 @@ function main() {
|
|
|
821
862
|
checks: 0,
|
|
822
863
|
stdout,
|
|
823
864
|
stderr,
|
|
865
|
+
progress: progressRecorder(paths.dir),
|
|
824
866
|
stopRequested: false,
|
|
825
867
|
finalized: false,
|
|
826
868
|
};
|
|
869
|
+
ctx.progress(ctx.startedAt);
|
|
827
870
|
appendEvent(paths.events, `claimed runner_pid=${process.pid} runner_version=${SUPERVISOR_RUNNER_VERSION} kind=${launch.kind} cwd=${launch.command.cwd}`);
|
|
828
871
|
const onSignal = (signal) => {
|
|
829
872
|
appendEvent(paths.events, `runner received ${signal}`);
|