pi-better-background-tasks 0.18.0 → 0.19.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/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/client.mjs +30 -3
- package/runtime-client/src/runtime/work-client.mjs +150 -7
- package/src/adapter-contract.ts +1 -1
- package/src/goal-provider.ts +31 -16
- package/src/index.ts +6 -9
- package/src/managed-authority.ts +5 -3
- package/src/managed-client.ts +20 -7
- package/src/managed-frontend.ts +62 -17
- package/src/navigator-provider.ts +15 -5
- package/src/observed-wait-client.ts +10 -0
- package/src/observed-waits.ts +154 -30
- package/src/process-identity.ts +18 -2
- package/src/process.ts +3 -3
- package/src/registry.ts +53 -5
- package/src/runtime.ts +19 -9
- package/src/sandbox.ts +14 -11
- package/src/shared-callback-batcher.ts +11 -2
- package/src/shared-navigator-panels.ts +26 -4
- package/src/shared-navigator.ts +197 -14
- package/src/shared-operation-coordinator/assignment-observation.mjs +43 -35
- package/src/shared-operation-coordinator/src/assignment-changes.ts +73 -0
- package/src/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
- package/src/shared-operation-coordinator/src/background-requests.ts +14 -3
- package/src/shared-operation-coordinator/src/discovery.ts +5 -3
- package/src/shared-operation-coordinator/src/operations.ts +50 -2
- package/src/shared-operation-coordinator/src/result-supervision.ts +12 -0
- package/src/shared-operation-coordinator/src/rows.ts +2 -0
- package/src/shared-operation-coordinator/src/schema.ts +40 -24
- package/src/shared-operation-coordinator/src/store.ts +34 -8
- package/src/shared-operation-coordinator/src/subagent-launch.ts +24 -1
- package/src/shared-operation-coordinator/src/types.ts +5 -1
- package/src/shared-sandbox-core.ts +1 -1
- package/src/shared-work-client.mjs +150 -7
- package/src/supervisor/generated/process-identity.mjs +20 -2
- package/src/supervisor/generated/process.mjs +3 -3
- package/src/task-diagnostics.ts +1 -1
- package/src/tools.ts +41 -38
- package/src/types.ts +3 -1
- package/src/work-observation.ts +46 -19
|
@@ -12,7 +12,7 @@ import { setParentCallbackPending, listPendingParentCallbacks, listRecentBackgro
|
|
|
12
12
|
import { BackgroundRequests } from "./background-requests.ts";
|
|
13
13
|
import { StoreError } from "./errors.ts";
|
|
14
14
|
import { SubagentLaunchJournal } from "./subagent-launch.ts";
|
|
15
|
-
import { resultSupervision, resultSupervisions, resultScopeManaged, handoffResultScope, handoffResultSupervision, handoffResultSupervisions, recoverResultSupervision, publishSupervisedResult } from "./result-supervision.ts";
|
|
15
|
+
import { resultSupervisionChanges, resultSupervision, resultSupervisions, resultScopeManaged, handoffResultScope, handoffResultSupervision, handoffResultSupervisions, recoverResultSupervision, publishSupervisedResult } from "./result-supervision.ts";
|
|
16
16
|
import { acceptTaskCancellation, getTaskCancellation, recordTaskStopRequested, admitTaskCancellation, authorizedTaskCancellation, finishTaskCancellation, cancellationRuntimeEpoch, acceptAuthorizedTaskCancellation, taskCancellationManaged, pendingTaskCancellations, finishTaskCancellationIntent, unknownTaskCancellation } from "./task-cancellation.ts";
|
|
17
17
|
import type { TaskCancellationIntent, TaskCancellationRequest } from "./task-cancellation.ts";
|
|
18
18
|
import { repairFailedResume, type RepairResumeInput } from "./recovery.ts";
|
|
@@ -26,9 +26,11 @@ import {
|
|
|
26
26
|
requirePath,
|
|
27
27
|
} from "./validate.ts";
|
|
28
28
|
import { ensureSchema } from "./schema.ts";
|
|
29
|
-
import {
|
|
29
|
+
import { ensureAssignmentChanges } from "./assignment-changes.ts";
|
|
30
|
+
import { createContext, openDatabase, run, type StoreContext } from "./sqlite.ts";
|
|
30
31
|
import {
|
|
31
32
|
getOperation as readOperationRecord,
|
|
33
|
+
listAssignmentCleanupOperations as readAssignmentCleanupOperations,
|
|
32
34
|
listOperations as readOperationRecords,
|
|
33
35
|
listRunningSupervisedBy as readRunningSupervisedBy,
|
|
34
36
|
releaseSupervision as writeSupervisionRelease,
|
|
@@ -124,6 +126,8 @@ import {
|
|
|
124
126
|
} from "./types.ts";
|
|
125
127
|
|
|
126
128
|
export interface Store {
|
|
129
|
+
hasSubagentManagement(): boolean;
|
|
130
|
+
resultSupervisionChanges(after?: Parameters<typeof resultSupervisionChanges>[1]): ReturnType<typeof resultSupervisionChanges>;
|
|
127
131
|
subagentLaunchJournal(): SubagentLaunchJournal;
|
|
128
132
|
resultScopeManaged(scope: string): boolean;
|
|
129
133
|
handoffResultScope(input: Parameters<typeof handoffResultScope>[1]): ReturnType<typeof handoffResultScope>;
|
|
@@ -160,18 +164,17 @@ export interface Store {
|
|
|
160
164
|
|
|
161
165
|
// ---- operations ----
|
|
162
166
|
|
|
163
|
-
/**
|
|
164
|
-
* Register a durable operation for one task launch. The owner, task id,
|
|
165
|
-
* launch token and observer are immutable: a replay of the same launch
|
|
166
|
-
* returns `created: false`, and any difference is refused with
|
|
167
|
-
* `operation-conflict` or `task-ownership`.
|
|
168
|
-
*/
|
|
169
167
|
backgroundRequests(): BackgroundRequests;
|
|
170
168
|
setParentCallbackPending(taskId: string, pending: boolean): boolean;
|
|
171
169
|
listPendingParentCallbacks(scope: ParentCallbackScope, options?: ParentCallbackPage): OperationRecord[];
|
|
172
170
|
listRecentBackgroundTerminals(options: RecentBackgroundTerminalPage): OperationRecord[];
|
|
173
171
|
seedPendingParentCallbacks(options?: { limit?: number }): { done: boolean; seeded: number };
|
|
174
172
|
setUpgradeFence(epoch: string | null): void;
|
|
173
|
+
/**
|
|
174
|
+
* Register a durable launch. Owner, task id, launch token, observer, and
|
|
175
|
+
* assignment attempt provenance are immutable. An exact replay returns
|
|
176
|
+
* `created: false`, even after assignment end, and admits no new work.
|
|
177
|
+
*/
|
|
175
178
|
registerOperation(input: RegisterOperationInput): RegisterOperationResult;
|
|
176
179
|
/**
|
|
177
180
|
* Replace supervision identity and/or report observer health
|
|
@@ -196,6 +199,12 @@ export interface Store {
|
|
|
196
199
|
recordTerminalOutcome(input: RecordTerminalOutcomeInput): RecordTerminalOutcomeResult;
|
|
197
200
|
getOperation(operationId: string): OperationRecord | null;
|
|
198
201
|
listOperations(filter?: OperationFilter): OperationRecord[];
|
|
202
|
+
/**
|
|
203
|
+
* Read up to 256 unfinished cleanup obligations in operation id order.
|
|
204
|
+
* The cursor is exclusive. Start each new sweep without a cursor.
|
|
205
|
+
*/
|
|
206
|
+
listAssignmentCleanupOperations(limit: number, afterOperationId?: string): OperationRecord[];
|
|
207
|
+
verifyAssignmentCleanup(operationId: string, launchToken: string, terminalRevision: number): boolean;
|
|
199
208
|
/** Running operations currently assigned to this supervising host. */
|
|
200
209
|
listRunningSupervisedBy(hostId: string): OperationRecord[];
|
|
201
210
|
listOperationEvidence(operationId: string, terminalRevision?: number): OperationEvidenceRecord[];
|
|
@@ -327,6 +336,7 @@ export function openStore(options: StoreOptions): Store {
|
|
|
327
336
|
const ctx: StoreContext = createContext(db, options.now ? { now: options.now } : {});
|
|
328
337
|
try {
|
|
329
338
|
ensureSchema(ctx);
|
|
339
|
+
ensureAssignmentChanges(ctx);
|
|
330
340
|
} catch (error) {
|
|
331
341
|
try {
|
|
332
342
|
db.close();
|
|
@@ -351,6 +361,8 @@ export function openStore(options: StoreOptions): Store {
|
|
|
351
361
|
resultScopeManaged(scope) { alive(); return resultScopeManaged(ctx, scope); },
|
|
352
362
|
handoffResultScope(input) { alive(); return handoffResultScope(ctx, input); },
|
|
353
363
|
resultSupervision(id) { alive(); return resultSupervision(ctx, id); },
|
|
364
|
+
hasSubagentManagement() { alive(); return Boolean(ctx.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='subagent_management'").get()); },
|
|
365
|
+
resultSupervisionChanges(after) { alive(); return resultSupervisionChanges(ctx, after); },
|
|
354
366
|
resultSupervisions(activeOnly) { alive(); return resultSupervisions(ctx, activeOnly); },
|
|
355
367
|
handoffResultSupervision(input) { alive(); return handoffResultSupervision(ctx, input); },
|
|
356
368
|
handoffResultSupervisions(input) { alive(); return handoffResultSupervisions(ctx, input); },
|
|
@@ -408,6 +420,20 @@ export function openStore(options: StoreOptions): Store {
|
|
|
408
420
|
alive();
|
|
409
421
|
return readOperationRecords(ctx, filter);
|
|
410
422
|
},
|
|
423
|
+
listAssignmentCleanupOperations(limit, afterOperationId) {
|
|
424
|
+
alive();
|
|
425
|
+
return readAssignmentCleanupOperations(ctx, limit, afterOperationId);
|
|
426
|
+
},
|
|
427
|
+
verifyAssignmentCleanup(operationId, launchToken, terminalRevision) {
|
|
428
|
+
alive();
|
|
429
|
+
if (!Number.isSafeInteger(terminalRevision) || terminalRevision < 1) return false;
|
|
430
|
+
return run(ctx, `INSERT OR IGNORE INTO coordinator_state (key, value)
|
|
431
|
+
SELECT 'assignment-cleanup-verified:' || op.operation_id, op.launch_token
|
|
432
|
+
FROM operations op JOIN assignment_attempts a ON a.attempt_id = op.assignment_attempt_id
|
|
433
|
+
JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
|
|
434
|
+
WHERE op.operation_id = ? AND op.launch_token = ? AND op.terminal_revision = ?`,
|
|
435
|
+
operationId, launchToken, terminalRevision) > 0;
|
|
436
|
+
},
|
|
411
437
|
listRunningSupervisedBy(hostId) {
|
|
412
438
|
alive();
|
|
413
439
|
return readRunningSupervisedBy(ctx, hostId);
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// Generated from packages/operation-coordinator/src/subagent-launch.ts. Do not edit directly.
|
|
2
|
-
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
3
3
|
import type { StoreContext } from "./sqlite.ts";
|
|
4
4
|
|
|
5
5
|
export interface LaunchAttempt {
|
|
@@ -67,6 +67,26 @@ export class SubagentLaunchJournal {
|
|
|
67
67
|
pendingIntents(): LaunchIntent[] {
|
|
68
68
|
return this.db.prepare("SELECT * FROM subagent_launch_intents WHERE state='accepted'").all() as unknown as LaunchIntent[];
|
|
69
69
|
}
|
|
70
|
+
private progressKey(owner: string, key: string) { return `launch-progress:${createHash('sha256').update(JSON.stringify([owner, key])).digest('hex')}`; }
|
|
71
|
+
private progress(owner: string, key: string) {
|
|
72
|
+
const row = this.db.prepare('SELECT value FROM coordinator_state WHERE key=?').get(this.progressKey(owner, key));
|
|
73
|
+
return row ? JSON.parse(String(row.value)) as { acceptedAt: number; lastProgressAt: number } : undefined;
|
|
74
|
+
}
|
|
75
|
+
private noteProgress(owner: string, key: string) {
|
|
76
|
+
const previous = this.progress(owner, key), now = Date.now();
|
|
77
|
+
this.db.prepare('INSERT OR REPLACE INTO coordinator_state (key,value) VALUES (?,?)').run(this.progressKey(owner, key),
|
|
78
|
+
JSON.stringify({ acceptedAt: previous?.acceptedAt ?? now, lastProgressAt: now }));
|
|
79
|
+
}
|
|
80
|
+
lifecycleReasons(owner?: string, key?: string) {
|
|
81
|
+
const exact = owner !== undefined && key !== undefined ? this.read(owner, key) : undefined;
|
|
82
|
+
const intents = owner !== undefined ? exact?.state === 'accepted' ? [exact] : [] : this.pendingIntents();
|
|
83
|
+
return intents.map(intent => ({ kind: 'task', id: this.progressKey(intent.owner, intent.request_key),
|
|
84
|
+
owner: intent.owner, management: { epoch: intent.epoch }, acceptedAt: this.progress(intent.owner, intent.request_key)?.acceptedAt ?? null,
|
|
85
|
+
lastProgressAt: this.progress(intent.owner, intent.request_key)?.lastProgressAt ?? null, executionDeadline: null, nextDeadline: null,
|
|
86
|
+
attempts: (JSON.parse(intent.attempts) as LaunchAttempt[]).map(attempt => ({ id: attempt.id, sessionId: attempt.sessionId,
|
|
87
|
+
state: attempt.state, writer: { pid: attempt.writerPid ?? attempt.pid, start: attempt.writerStartTime ?? attempt.pidStartTime } })),
|
|
88
|
+
recovery: 'drain-accepted-launch-until-journal-return-or-authoritative-handoff' }));
|
|
89
|
+
}
|
|
70
90
|
finishRecovery(owner: string, key: string, epoch: number, result: unknown) {
|
|
71
91
|
this.transaction(() => {
|
|
72
92
|
this.current(epoch);
|
|
@@ -83,6 +103,7 @@ export class SubagentLaunchJournal {
|
|
|
83
103
|
return { prior: true, ...prior };
|
|
84
104
|
}
|
|
85
105
|
this.db.prepare("INSERT INTO subagent_launch_intents VALUES (?, ?, ?, ?, 'accepted', '[]', NULL)").run(owner, key, digest, epoch);
|
|
106
|
+
this.noteProgress(owner, key);
|
|
86
107
|
return this.read(owner, key);
|
|
87
108
|
});
|
|
88
109
|
}
|
|
@@ -96,6 +117,7 @@ export class SubagentLaunchJournal {
|
|
|
96
117
|
const attempt: LaunchAttempt = { ...input, token: randomBytes(32).toString("hex"), state: "prepared" };
|
|
97
118
|
attempts.push(attempt);
|
|
98
119
|
this.db.prepare("UPDATE subagent_launch_intents SET attempts=? WHERE owner=? AND request_key=?").run(JSON.stringify(attempts), owner, key);
|
|
120
|
+
this.noteProgress(owner, key);
|
|
99
121
|
return attempt;
|
|
100
122
|
});
|
|
101
123
|
}
|
|
@@ -108,6 +130,7 @@ export class SubagentLaunchJournal {
|
|
|
108
130
|
if (attempt.writerPid && attempt.writerPid !== pid) throw new Error("Launch writer does not match spawned process");
|
|
109
131
|
Object.assign(attempt, { state: "spawned", pid, pidStartTime });
|
|
110
132
|
this.db.prepare("UPDATE subagent_launch_intents SET attempts=? WHERE owner=? AND request_key=?").run(JSON.stringify(attempts), owner, key);
|
|
133
|
+
this.noteProgress(owner, key);
|
|
111
134
|
});
|
|
112
135
|
}
|
|
113
136
|
finish(owner: string, key: string, epoch: number, result: unknown) {
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
* spawned, so a crash is reconciled instead of relaunched.
|
|
20
20
|
*/
|
|
21
21
|
|
|
22
|
-
/** Schema version this build writes
|
|
22
|
+
/** Schema version this build writes after creating or migrating a store. */
|
|
23
23
|
export const SCHEMA_VERSION = 4;
|
|
24
24
|
|
|
25
25
|
/** Who receives an operation's result and decides what happens next. */
|
|
@@ -107,6 +107,8 @@ export interface RegisterOperationInput {
|
|
|
107
107
|
*/
|
|
108
108
|
launchToken: string;
|
|
109
109
|
owner: OwnerIdentity;
|
|
110
|
+
/** Exact registered worker attempt for this launch. Omit when no binding is known. */
|
|
111
|
+
assignmentAttemptId?: string;
|
|
110
112
|
observer: ObserverIdentity;
|
|
111
113
|
supervision?: SupervisionIdentity | null;
|
|
112
114
|
/** Reference to the permission/authority snapshot. Never credential material. */
|
|
@@ -122,6 +124,8 @@ export interface OperationRecord {
|
|
|
122
124
|
taskId: string;
|
|
123
125
|
launchToken: string;
|
|
124
126
|
owner: OwnerIdentity;
|
|
127
|
+
/** Immutable launch provenance. Absent on unbound and legacy operations. */
|
|
128
|
+
assignmentAttemptId?: string;
|
|
125
129
|
observer: ObserverIdentity;
|
|
126
130
|
supervision: SupervisionIdentity | null;
|
|
127
131
|
authorityRef: string | null;
|
|
@@ -69,7 +69,7 @@ export type SandboxPermissions = {
|
|
|
69
69
|
*/
|
|
70
70
|
commandTimeoutSeconds?: number | null;
|
|
71
71
|
network: boolean;
|
|
72
|
-
/** Fixed
|
|
72
|
+
/** Fixed process adapters (inventory and Darwin identity compatibility); omitted legacy profiles keep it Off. */
|
|
73
73
|
processAccess?: "off" | "read";
|
|
74
74
|
};
|
|
75
75
|
|
|
@@ -1,5 +1,17 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
1
2
|
import { connect } from "node:net";
|
|
2
3
|
import { performance } from "node:perf_hooks";
|
|
4
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
5
|
+
|
|
6
|
+
/** A persisted session can own work even when its selected branch is empty. */
|
|
7
|
+
export function shouldRestoreWorkObservation(event, session) {
|
|
8
|
+
if (event?.piBetterObserveWork) return true;
|
|
9
|
+
const reason = event?.reason;
|
|
10
|
+
if (reason === "new") return false;
|
|
11
|
+
if (reason !== "startup" || typeof session?.getSessionFile !== "function") return true;
|
|
12
|
+
const file = session.getSessionFile();
|
|
13
|
+
return file ? existsSync(file) : Boolean(session.getLeafId?.());
|
|
14
|
+
}
|
|
3
15
|
|
|
4
16
|
/** SDK-free observation stream. Cached snapshots are the only synchronous read API. */
|
|
5
17
|
export class WorkClient {
|
|
@@ -12,6 +24,11 @@ export class WorkClient {
|
|
|
12
24
|
scope;
|
|
13
25
|
buffer = "";
|
|
14
26
|
closed = false;
|
|
27
|
+
recoveryTimer;
|
|
28
|
+
recoveryActive = false;
|
|
29
|
+
recoveryAgain = false;
|
|
30
|
+
recoveryDelay = 100;
|
|
31
|
+
scopeGeneration = 0;
|
|
15
32
|
|
|
16
33
|
constructor(socketPath, agentDir, requiredCapabilities = []) {
|
|
17
34
|
this.socket = typeof socketPath === "string" ? connect(socketPath) : socketPath;
|
|
@@ -26,8 +43,8 @@ export class WorkClient {
|
|
|
26
43
|
const message = JSON.parse(line);
|
|
27
44
|
if (message.type === "event") {
|
|
28
45
|
if (message.event.type === "runtime_catalog_snapshot") { for (const listener of this.catalogListeners) listener(message.event.snapshot); continue; }
|
|
29
|
-
if (message.event.type === "resync_required") { this.degrade(message.event.reason);
|
|
30
|
-
else if (message.event.type === "runtime_snapshot") this.accept(message.event.snapshot);
|
|
46
|
+
if (message.event.type === "resync_required") { this.degrade(message.event.reason); this.scheduleRecovery(); }
|
|
47
|
+
else if (message.event.type === "runtime_snapshot") this.accept(message.event.snapshot, message.event.previousSeq);
|
|
31
48
|
} else {
|
|
32
49
|
const request = this.pending.get(message.id);
|
|
33
50
|
if (!request) continue;
|
|
@@ -37,7 +54,9 @@ export class WorkClient {
|
|
|
37
54
|
} catch (error) { this.fail(error); }
|
|
38
55
|
}
|
|
39
56
|
});
|
|
40
|
-
this.socket.on("error", error => this.fail(error)
|
|
57
|
+
this.socket.on("error", error => this.fail(["ECONNRESET", "EPIPE"].includes(error.code)
|
|
58
|
+
? Object.assign(new Error(`runtime-unavailable: disconnected (${error.code}); resync required`, { cause: error }), { code: error.code })
|
|
59
|
+
: error));
|
|
41
60
|
this.socket.on("close", () => this.fail(new Error("runtime-unavailable: disconnected; resync required")));
|
|
42
61
|
this.ready = this.request("hello", { protocolVersion: 1, runtimeRoot: agentDir, requiredCapabilities: ["runtime-state-v1", "runtime-subscriptions-v1", ...requiredCapabilities] })
|
|
43
62
|
.then(async hello => { if (typeof socketPath === "string" && hello.capabilities?.includes("runtime-client-retention-v1")) await this.request("runtime_register_client", { clientId: `work-${process.pid}` }); return hello; });
|
|
@@ -59,27 +78,63 @@ export class WorkClient {
|
|
|
59
78
|
this.snapshot = { ...this.snapshot, status: "degraded", reason, rows: this.snapshot?.rows ?? [] };
|
|
60
79
|
this.notify();
|
|
61
80
|
}
|
|
62
|
-
accept(snapshot) {
|
|
81
|
+
accept(snapshot, previousSeq) {
|
|
63
82
|
if (this.snapshot?.instanceId === snapshot.instanceId && snapshot.seq < this.snapshot.seq) return;
|
|
64
83
|
if (this.snapshot?.instanceId && this.snapshot.instanceId !== snapshot.instanceId) {
|
|
65
84
|
this.degrade("instance-changed: resync required");
|
|
66
85
|
snapshot = { ...snapshot, resyncRequired: true, resyncReason: "instance-changed" };
|
|
67
|
-
} else if (this.snapshot?.seq !== undefined &&
|
|
86
|
+
} else if (this.snapshot?.seq !== undefined && Number.isSafeInteger(previousSeq) && previousSeq > this.snapshot.seq) {
|
|
68
87
|
this.degrade("sequence-gap: replacing with a full authoritative snapshot");
|
|
69
88
|
snapshot = { ...snapshot, resyncRequired: true, resyncReason: "sequence-gap" };
|
|
70
89
|
}
|
|
71
|
-
//
|
|
90
|
+
// Global seq may skip unrelated changes; only a missing subscription
|
|
91
|
+
// predecessor indicates loss. The received snapshot is still complete.
|
|
72
92
|
this.snapshot = Object.freeze(snapshot); this.notify();
|
|
73
93
|
}
|
|
94
|
+
scheduleRecovery(delay = 0) {
|
|
95
|
+
if (this.closed) return;
|
|
96
|
+
if (this.recoveryActive) { this.recoveryAgain = true; return; }
|
|
97
|
+
if (this.recoveryTimer) return;
|
|
98
|
+
this.recoveryTimer = setTimeout(() => {
|
|
99
|
+
this.recoveryTimer = undefined;
|
|
100
|
+
void this.recover();
|
|
101
|
+
}, delay);
|
|
102
|
+
this.recoveryTimer.unref?.();
|
|
103
|
+
}
|
|
104
|
+
async recover() {
|
|
105
|
+
const generation = this.scopeGeneration;
|
|
106
|
+
this.recoveryActive = true;
|
|
107
|
+
let retry = false;
|
|
108
|
+
try { await this.resync(); this.recoveryDelay = 100; }
|
|
109
|
+
catch (error) {
|
|
110
|
+
if (!this.closed && generation === this.scopeGeneration) {
|
|
111
|
+
this.degrade(String(error));
|
|
112
|
+
retry = /runtime-(?:timeout|overloaded|unhealthy)/.test(String(error));
|
|
113
|
+
}
|
|
114
|
+
} finally {
|
|
115
|
+
this.recoveryActive = false;
|
|
116
|
+
const again = this.recoveryAgain;
|
|
117
|
+
this.recoveryAgain = false;
|
|
118
|
+
if (!this.closed && (again || retry && generation === this.scopeGeneration)) {
|
|
119
|
+
this.scheduleRecovery(again ? 0 : this.recoveryDelay);
|
|
120
|
+
this.recoveryDelay = Math.min(1000, this.recoveryDelay * 2);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
74
124
|
async subscribe(scope) {
|
|
75
125
|
await this.ready;
|
|
126
|
+
this.scopeGeneration++;
|
|
127
|
+
clearTimeout(this.recoveryTimer); this.recoveryTimer = undefined;
|
|
128
|
+
this.recoveryAgain = false; this.recoveryDelay = 100;
|
|
76
129
|
this.scope = scope;
|
|
77
130
|
const snapshot = await this.request("runtime_subscribe", { scope });
|
|
78
131
|
this.accept(snapshot); return snapshot;
|
|
79
132
|
}
|
|
80
133
|
async resync() {
|
|
134
|
+
const generation = this.scopeGeneration;
|
|
81
135
|
const snapshot = await this.request("runtime_subscribe", { scope: this.scope, sinceSeq: this.snapshot?.seq, instanceId: this.snapshot?.instanceId });
|
|
82
|
-
this.accept(snapshot);
|
|
136
|
+
if (!this.closed && generation === this.scopeGeneration) this.accept(snapshot);
|
|
137
|
+
return snapshot;
|
|
83
138
|
}
|
|
84
139
|
async get(scope) {
|
|
85
140
|
await this.ready;
|
|
@@ -94,9 +149,97 @@ export class WorkClient {
|
|
|
94
149
|
fail(error) {
|
|
95
150
|
if (this.closed) return;
|
|
96
151
|
this.closed = true;
|
|
152
|
+
this.scopeGeneration++;
|
|
153
|
+
clearTimeout(this.recoveryTimer); this.recoveryTimer = undefined;
|
|
97
154
|
for (const request of this.pending.values()) { clearTimeout(request.timer); request.reject(error); }
|
|
98
155
|
this.pending.clear(); this.socket.destroy(); this.degrade(String(error));
|
|
99
156
|
for (const listener of this.catalogListeners) listener({ status: "revoked" });
|
|
100
157
|
}
|
|
101
158
|
close() { this.fail(new Error("runtime-unavailable: client closed")); this.listeners.clear(); this.catalogListeners.clear(); }
|
|
102
159
|
}
|
|
160
|
+
|
|
161
|
+
// Shared across the standalone extension copies, but never across agent roots.
|
|
162
|
+
const recoveryKey = Symbol.for("pi-better-runtime.connection-recovery.v2");
|
|
163
|
+
const recoveries = globalThis[recoveryKey] ??= new Map();
|
|
164
|
+
const connectionDemands = globalThis[Symbol.for("pi-better-runtime.connection-demand.v2")] ??= new Map();
|
|
165
|
+
|
|
166
|
+
/** Establish a transport only. Never replay an application request after dispatch. */
|
|
167
|
+
export async function connectWorkClient(socketPath, agentDir, capabilities = [], options = {}) {
|
|
168
|
+
const timeoutMs = options.timeoutMs ?? 60000;
|
|
169
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new Error("Invalid connection timeout");
|
|
170
|
+
const deadline = performance.now() + timeoutMs;
|
|
171
|
+
const started = performance.now();
|
|
172
|
+
let backoff = 100, recovered = false, lastError, recoveryError, ownedRecovery;
|
|
173
|
+
const remaining = () => Math.max(1, deadline - performance.now());
|
|
174
|
+
const key = JSON.stringify([agentDir, socketPath]);
|
|
175
|
+
connectionDemands.set(key, (connectionDemands.get(key) ?? 0) + 1);
|
|
176
|
+
try {
|
|
177
|
+
while (performance.now() < deadline) {
|
|
178
|
+
options.signal?.throwIfAborted();
|
|
179
|
+
const client = new WorkClient(socketPath, agentDir, capabilities);
|
|
180
|
+
const abort = () => client.close();
|
|
181
|
+
options.signal?.addEventListener("abort", abort, { once: true });
|
|
182
|
+
const timer = setTimeout(() => client.close(), remaining());
|
|
183
|
+
try {
|
|
184
|
+
await client.ready;
|
|
185
|
+
options.signal?.throwIfAborted();
|
|
186
|
+
return client;
|
|
187
|
+
} catch (error) {
|
|
188
|
+
client.close();
|
|
189
|
+
options.signal?.throwIfAborted();
|
|
190
|
+
lastError = error;
|
|
191
|
+
if (recoveryError) throw recoveryError;
|
|
192
|
+
if (!["ENOENT", "ECONNREFUSED", "ECONNRESET", "EPIPE"].includes(error?.code)
|
|
193
|
+
&& !/runtime-unavailable: (?:disconnected|server closed)/.test(String(error))) throw error;
|
|
194
|
+
} finally {
|
|
195
|
+
clearTimeout(timer);
|
|
196
|
+
options.signal?.removeEventListener("abort", abort);
|
|
197
|
+
}
|
|
198
|
+
// Most replacement gaps need only a reconnect. Startup remains owner-safe.
|
|
199
|
+
if (!recovered && options.recover && performance.now() - started >= 250 && performance.now() < deadline) {
|
|
200
|
+
recovered = true;
|
|
201
|
+
let recovery = recoveries.get(key);
|
|
202
|
+
if (!recovery) {
|
|
203
|
+
const controller = new AbortController();
|
|
204
|
+
const budget = Math.ceil(remaining());
|
|
205
|
+
const timer = setTimeout(() => {
|
|
206
|
+
controller.abort(new Error("runtime-unavailable: reconnect deadline exceeded during recovery"));
|
|
207
|
+
}, budget);
|
|
208
|
+
const promise = waitForRecovery(Promise.resolve().then(() => options.recover({ timeoutMs: budget, signal: controller.signal })), controller.signal)
|
|
209
|
+
.finally(() => clearTimeout(timer));
|
|
210
|
+
recovery = { promise, controller, key };
|
|
211
|
+
recoveries.set(key, recovery);
|
|
212
|
+
void recovery.promise.finally(() => { if (recoveries.get(key) === recovery) recoveries.delete(key); }).catch(() => {});
|
|
213
|
+
}
|
|
214
|
+
// A caller can cancel its wait without cancelling another caller's recovery.
|
|
215
|
+
// Keep trying the transport while the owner-safe installer waits.
|
|
216
|
+
// A replacement can accept compatible clients before the pinned
|
|
217
|
+
// installer finishes; waiting for it would stall all subscribers.
|
|
218
|
+
ownedRecovery = recovery;
|
|
219
|
+
void recovery.promise.catch(error => { recoveryError = error; });
|
|
220
|
+
}
|
|
221
|
+
if (performance.now() >= deadline) break;
|
|
222
|
+
await delay(Math.min(backoff, remaining()), undefined, { signal: options.signal });
|
|
223
|
+
backoff = Math.min(1000, backoff * 2);
|
|
224
|
+
}
|
|
225
|
+
throw new Error("runtime-unavailable: reconnect deadline exceeded; task state is unknown, retry after recovery", { cause: lastError });
|
|
226
|
+
} finally {
|
|
227
|
+
const remainingDemand = connectionDemands.get(key) - 1;
|
|
228
|
+
if (remainingDemand) connectionDemands.set(key, remainingDemand);
|
|
229
|
+
else {
|
|
230
|
+
connectionDemands.delete(key);
|
|
231
|
+
const recovery = recoveries.get(key) ?? ownedRecovery;
|
|
232
|
+
if (recovery) { recoveries.delete(key); recovery.controller.abort(); }
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function waitForRecovery(recovery, signal) {
|
|
238
|
+
return new Promise((resolve, reject) => {
|
|
239
|
+
const finish = (callback, value) => { signal.removeEventListener("abort", abort); callback(value); };
|
|
240
|
+
const abort = () => finish(reject, signal.reason);
|
|
241
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
242
|
+
recovery.then(value => finish(resolve, value), error => finish(reject, error));
|
|
243
|
+
if (signal.aborted) abort();
|
|
244
|
+
});
|
|
245
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// Generated by src/supervisor/emit-runner.mjs from the TypeScript source.
|
|
2
2
|
// Do not edit: change the source and re-run the emitter (a drift test enforces this).
|
|
3
3
|
|
|
4
|
+
import { readFileSync } from "node:fs";
|
|
4
5
|
import { execFileSync } from "node:child_process";
|
|
5
6
|
/**
|
|
6
7
|
* Process start-token reads.
|
|
@@ -23,11 +24,12 @@ const TOKEN_MEMO_TTL_MS = 1_000;
|
|
|
23
24
|
/** Bound on memo entries; the panel is small, but a long session is not. */
|
|
24
25
|
const TOKEN_MEMO_MAX_ENTRIES = 512;
|
|
25
26
|
const tokenMemo = new Map();
|
|
26
|
-
function readTokenUncached(pid) {
|
|
27
|
+
function readTokenUncached(pid, admission = false) {
|
|
27
28
|
if (!Number.isInteger(pid) || pid <= 0 || process.platform === "win32")
|
|
28
29
|
return undefined;
|
|
29
30
|
try {
|
|
30
|
-
const output = execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], {
|
|
31
|
+
const output = execFileSync(admission ? "/bin/ps" : "ps", ["-o", "lstart=", "-p", String(pid)], {
|
|
32
|
+
env: admission ? { LC_ALL: "C", TZ: "UTC0", PATH: "/usr/bin:/bin" } : process.env,
|
|
31
33
|
encoding: "utf8",
|
|
32
34
|
stdio: ["ignore", "pipe", "ignore"],
|
|
33
35
|
timeout: 2_000,
|
|
@@ -38,6 +40,22 @@ function readTokenUncached(pid) {
|
|
|
38
40
|
return undefined;
|
|
39
41
|
}
|
|
40
42
|
}
|
|
43
|
+
// Admission crosses process environments; stored task tokens retain their original format.
|
|
44
|
+
export function readAdmissionStartToken(pid) {
|
|
45
|
+
if (process.platform !== "linux")
|
|
46
|
+
return readTokenUncached(pid, true);
|
|
47
|
+
if (!Number.isInteger(pid) || pid <= 0)
|
|
48
|
+
return undefined;
|
|
49
|
+
try {
|
|
50
|
+
const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
|
|
51
|
+
// Fields after the parenthesized command start at field 3. Start time is field 22.
|
|
52
|
+
const start = stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
|
|
53
|
+
return start && /^\d+$/.test(start) ? start : undefined;
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return undefined;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
41
59
|
function remember(pid, token, now) {
|
|
42
60
|
if (tokenMemo.size >= TOKEN_MEMO_MAX_ENTRIES) {
|
|
43
61
|
// Drop expired entries first; only evict live ones if that was not enough.
|
|
@@ -62,8 +62,8 @@ export function validateCommandSpec(spec) {
|
|
|
62
62
|
/** Convert a Windows path to the `/c/...` form MSYS bash resolves in redirections. Exposed for tests and reuse. */
|
|
63
63
|
export function toMsysPath(path) {
|
|
64
64
|
const forward = path.replace(/\\/g, "/");
|
|
65
|
-
const drive = /^([A-Za-z]):(\/.+)$/.exec(forward);
|
|
66
|
-
return drive ? `/${drive
|
|
65
|
+
const [, drive, rest] = /^([A-Za-z]):(\/.+)$/.exec(forward) ?? [];
|
|
66
|
+
return drive && rest ? `/${drive.toLowerCase()}${rest}` : forward;
|
|
67
67
|
}
|
|
68
68
|
/** Single-quote a value for safe literal use in a bash script line. Exposed for tests and reuse. */
|
|
69
69
|
export function bashSingleQuote(value) {
|
|
@@ -147,7 +147,7 @@ export function parseStepGateFailure(logText, id) {
|
|
|
147
147
|
if (!line.startsWith(marker) || !line.endsWith(" ---"))
|
|
148
148
|
continue;
|
|
149
149
|
const match = /^--- step gate \[[^\]]+\]: first failing step exit=(-?\d+); shell exit=(-?\d+): (.*) ---$/.exec(line);
|
|
150
|
-
if (!match)
|
|
150
|
+
if (!match || match[3] === undefined)
|
|
151
151
|
continue;
|
|
152
152
|
const stepExitCode = Number(match[1]);
|
|
153
153
|
const shellExitCode = Number(match[2]);
|
package/src/task-diagnostics.ts
CHANGED
|
@@ -52,7 +52,7 @@ export function inspectTaskProcess(
|
|
|
52
52
|
({ availability: "unavailable", reason, ...(identity ? { identity } : {}), limit: LIMIT });
|
|
53
53
|
if (access === "confined") return unavailable("Process activity adapter is unavailable under Main confinement; no unconfined process probe was run. Process access Read does not bypass kernel rules.");
|
|
54
54
|
if (access !== "read") return { availability: "blocked", reason: access === "off"
|
|
55
|
-
? "
|
|
55
|
+
? "An active Main or Background tasks profile denies process reads. Check Process access in /sandbox; this does not describe task confinement."
|
|
56
56
|
: "Current process-access policy is unavailable; no process probe was run.", limit: LIMIT };
|
|
57
57
|
if (meta.ssh) return unavailable("Remote activity is unavailable; no remote diagnostic command was run.");
|
|
58
58
|
if (meta.kind !== "process") return unavailable("Watch poll PID is not retained; last completed check is progress evidence only.");
|