pi-better-background-tasks 0.15.3 → 0.16.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.
Files changed (38) hide show
  1. package/README.md +13 -0
  2. package/package.json +5 -2
  3. package/runtime-client/artifacts/darwin-arm64.gz +0 -0
  4. package/runtime-client/artifacts/darwin-arm64.json +1 -0
  5. package/runtime-client/artifacts/darwin-x64.gz +0 -0
  6. package/runtime-client/artifacts/darwin-x64.json +1 -0
  7. package/runtime-client/artifacts/linux-arm64.gz +0 -0
  8. package/runtime-client/artifacts/linux-arm64.json +1 -0
  9. package/runtime-client/artifacts/linux-x64.gz +0 -0
  10. package/runtime-client/artifacts/linux-x64.json +1 -0
  11. package/runtime-client/scripts/private-runtime/format.mjs +90 -0
  12. package/runtime-client/src/daemon-owner.mjs +217 -0
  13. package/runtime-client/src/runtime/client.mjs +130 -0
  14. package/runtime-client/src/runtime/root.mjs +41 -0
  15. package/runtime-client/src/runtime/socket.mjs +9 -0
  16. package/runtime-client/src/runtime/status-cli.mjs +14 -0
  17. package/runtime-client/src/runtime/work-client.mjs +88 -0
  18. package/runtime-client/src/startup/artifact.mjs +76 -0
  19. package/runtime-client/src/startup/install.mjs +184 -0
  20. package/runtime-client/src/startup/managed-types.mjs +1 -0
  21. package/runtime-client/src/startup/runtime.mjs +120 -0
  22. package/src/goal-provider.ts +11 -7
  23. package/src/index.ts +3 -0
  24. package/src/observed-waits.ts +88 -26
  25. package/src/output.ts +16 -13
  26. package/src/registry.ts +15 -0
  27. package/src/shared-harness-settings.ts +4 -2
  28. package/src/shared-log-utils.ts +18 -7
  29. package/src/shared-navigator.ts +26 -8
  30. package/src/shared-operation-coordinator/assignment-observation.mjs +63 -3
  31. package/src/shared-operation-coordinator/index.ts +2 -0
  32. package/src/shared-operation-coordinator/src/errors.ts +2 -0
  33. package/src/shared-operation-coordinator/src/schema.ts +20 -0
  34. package/src/shared-operation-coordinator/src/store.ts +35 -0
  35. package/src/shared-operation-coordinator/src/task-cancellation.ts +224 -0
  36. package/src/shared-work-client.mjs +88 -0
  37. package/src/tools.ts +28 -23
  38. package/src/work-observation.ts +117 -0
@@ -8,6 +8,8 @@
8
8
  * and leaves no partial record.
9
9
  */
10
10
  import { StoreError } from "./errors.ts";
11
+ import { acceptTaskCancellation, getTaskCancellation, recordTaskStopRequested, admitTaskCancellation, authorizedTaskCancellation, finishTaskCancellation, cancellationRuntimeEpoch, acceptAuthorizedTaskCancellation, taskCancellationManaged, pendingTaskCancellations, finishTaskCancellationIntent, unknownTaskCancellation } from "./task-cancellation.ts";
12
+ import type { TaskCancellationIntent, TaskCancellationRequest } from "./task-cancellation.ts";
11
13
  import { repairFailedResume, type RepairResumeInput } from "./recovery.ts";
12
14
  import { recordAssignmentOutcome, getAssignmentOutcome, inspectAssignmentOutcome, consumeAssignmentOutcome, registerAssignment, receiptAssignmentOutcome } from "./assignment-outcomes.ts";
13
15
  import type { AssignmentOutcomeInput, AssignmentOutcomeRecord } from "./assignment-outcomes.ts";
@@ -116,6 +118,18 @@ import {
116
118
  } from "./types.ts";
117
119
 
118
120
  export interface Store {
121
+ unknownTaskCancellation(input: TaskCancellationRequest): TaskCancellationIntent;
122
+ taskCancellationManaged(operationId: string): boolean;
123
+ pendingTaskCancellations(): ReturnType<typeof pendingTaskCancellations>;
124
+ finishTaskCancellationIntent(input: Parameters<typeof finishTaskCancellationIntent>[1]): TaskCancellationIntent;
125
+ cancellationRuntimeEpoch(instanceId?: string): number;
126
+ acceptAuthorizedTaskCancellation(input: { credential: string; runtimeEpoch: number }): TaskCancellationIntent;
127
+ admitTaskCancellation(input: Parameters<typeof admitTaskCancellation>[1]): void;
128
+ authorizedTaskCancellation(credential: string): ReturnType<typeof authorizedTaskCancellation>;
129
+ finishTaskCancellation(input: Parameters<typeof finishTaskCancellation>[1]): TaskCancellationIntent;
130
+ acceptTaskCancellation(input: TaskCancellationRequest): TaskCancellationIntent;
131
+ getTaskCancellation(input: { owner: OwnerIdentity; idempotencyKey: string }): TaskCancellationIntent | null;
132
+ recordTaskStopRequested(input: TaskCancellationRequest): TaskCancellationIntent;
119
133
  registerAssignment(input: Parameters<typeof registerAssignment>[1]): void;
120
134
  receiptAssignmentOutcome(input: Parameters<typeof receiptAssignmentOutcome>[1]): AssignmentOutcomeRecord;
121
135
  recordAssignmentOutcome(input: AssignmentOutcomeInput): AssignmentOutcomeRecord;
@@ -311,6 +325,15 @@ export function openStore(options: StoreOptions): Store {
311
325
  };
312
326
 
313
327
  const store: Store = {
328
+ unknownTaskCancellation(input) { alive(); return unknownTaskCancellation(ctx, input); },
329
+ taskCancellationManaged(operationId) { alive(); return taskCancellationManaged(ctx, operationId); },
330
+ pendingTaskCancellations() { alive(); return pendingTaskCancellations(ctx); },
331
+ finishTaskCancellationIntent(input) { alive(); return finishTaskCancellationIntent(ctx, input); },
332
+ cancellationRuntimeEpoch(instanceId) { alive(); return cancellationRuntimeEpoch(ctx, instanceId); },
333
+ acceptAuthorizedTaskCancellation(input) { alive(); return acceptAuthorizedTaskCancellation(ctx, input); },
334
+ admitTaskCancellation(input) { alive(); admitTaskCancellation(ctx, input); },
335
+ authorizedTaskCancellation(credential) { alive(); return authorizedTaskCancellation(ctx, credential); },
336
+ finishTaskCancellation(input) { alive(); return finishTaskCancellation(ctx, input); },
314
337
  registerAssignment(input) { alive(); registerAssignment(ctx, input); },
315
338
  receiptAssignmentOutcome(input) { alive(); return receiptAssignmentOutcome(ctx, input); },
316
339
  recordAssignmentOutcome(input) { alive(); return recordAssignmentOutcome(ctx, input); },
@@ -380,6 +403,18 @@ export function openStore(options: StoreOptions): Store {
380
403
  alive();
381
404
  return writeWait(ctx, input);
382
405
  },
406
+ acceptTaskCancellation(input) {
407
+ alive();
408
+ return acceptTaskCancellation(ctx, input);
409
+ },
410
+ getTaskCancellation(input) {
411
+ alive();
412
+ return getTaskCancellation(ctx, input);
413
+ },
414
+ recordTaskStopRequested(input) {
415
+ alive();
416
+ return recordTaskStopRequested(ctx, input);
417
+ },
383
418
  transitionWaitPhase(input) {
384
419
  alive();
385
420
  return writePhase(ctx, input);
@@ -0,0 +1,224 @@
1
+ // Generated from packages/operation-coordinator/src/task-cancellation.ts. Do not edit directly.
2
+ /**
3
+ * Durable intent for the fixed cancel_task operation. Admission and process
4
+ * identity checks remain the host's responsibility. An accepted intent is not
5
+ * evidence that a process stopped; recovery must use its original launch token.
6
+ */
7
+ import { StoreError } from "./errors.ts";
8
+ import { createHash, randomBytes } from "node:crypto";
9
+ import { getOperation, recordTerminalOutcome } from "./operations.ts";
10
+ import { columnText, getRow, run, type StoreContext } from "./sqlite.ts";
11
+ import type { OwnerIdentity, RecordTerminalOutcomeInput } from "./types.ts";
12
+ import { normalizeOwner, requireCounter, requireId, requireText, sameOwner } from "./validate.ts";
13
+
14
+ export interface TaskCancellationRequest {
15
+ owner: OwnerIdentity;
16
+ idempotencyKey: string;
17
+ operationId: string;
18
+ expectedLaunchToken: string;
19
+ expectedTerminalRevision: number;
20
+ expectedHostId: string;
21
+ reason: string;
22
+ }
23
+
24
+ export interface TaskCancellationIntent extends TaskCancellationRequest {
25
+ operation: "cancel_task";
26
+ taskId: string;
27
+ state: "accepted" | "stop-requested";
28
+ acceptedAt: number;
29
+ result?: { status: string; terminal: boolean };
30
+ }
31
+
32
+ export interface CancellationAdmission {
33
+ credentialHash: string;
34
+ request: TaskCancellationRequest;
35
+ directory: string;
36
+ runtimeEpoch?: number;
37
+ cancelEpoch?: number;
38
+ revision?: string;
39
+ }
40
+
41
+ export function cancellationRuntimeEpoch(ctx: StoreContext, instanceId?: string): number {
42
+ return ctx.transaction(() => {
43
+ const row = getRow(ctx, "SELECT value FROM coordinator_state WHERE key = 'cancellation-runtime'");
44
+ const current = row ? JSON.parse(columnText(row, "value")) : { epoch: 0 };
45
+ if (!instanceId || current.instanceId === instanceId) return current.epoch;
46
+ const epoch = current.epoch + 1;
47
+ run(ctx, "INSERT INTO coordinator_state (key, value) VALUES ('cancellation-runtime', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value", JSON.stringify({ instanceId, epoch }));
48
+ return epoch;
49
+ });
50
+ }
51
+
52
+ function cancelEpoch(ctx: StoreContext, operationId: string): number {
53
+ const row = getRow(ctx, "SELECT value FROM coordinator_state WHERE key = ?", `cancel:${operationId}`);
54
+ return row ? Number(columnText(row, "value")) : 0;
55
+ }
56
+
57
+ function revision(operation: unknown, epoch: number): string {
58
+ const op = operation as ReturnType<typeof getOperation>;
59
+ return createHash("sha256").update(JSON.stringify([op && {
60
+ operationId: op.operationId, owner: op.owner, launchToken: op.launchToken,
61
+ terminalRevision: op.terminalRevision, phase: op.phase, authorityRef: op.authorityRef,
62
+ hostId: op.supervision?.hostId,
63
+ }, epoch])).digest("hex");
64
+ }
65
+
66
+ export function taskCancellationManaged(ctx: StoreContext, operationId: string): boolean {
67
+ return !!getRow(ctx, "SELECT credential_hash FROM task_cancellation_authorities WHERE json_extract(request_json, '$.request.operationId') = ? LIMIT 1", requireId("operationId", operationId));
68
+ }
69
+
70
+ export function pendingTaskCancellations(ctx: StoreContext): CancellationAdmission[] {
71
+ return ctx.db.prepare("SELECT a.* FROM task_cancellation_authorities a JOIN task_cancellation_requests r ON json_extract(a.request_json, '$.request.operationId') = r.operation_id AND json_extract(a.request_json, '$.request.idempotencyKey') = r.request_key WHERE r.result_json IS NULL").all()
72
+ .map(row => ({ credentialHash: columnText(row, "credential_hash"), ...JSON.parse(columnText(row, "request_json")), directory: columnText(row, "directory") }));
73
+ }
74
+
75
+ export function acceptAuthorizedTaskCancellation(ctx: StoreContext, input: { credential: string; runtimeEpoch: number }): TaskCancellationIntent {
76
+ return ctx.transaction(() => {
77
+ const admission = authorizedTaskCancellation(ctx, input.credential);
78
+ const previous = getTaskCancellation(ctx, admission.request);
79
+ if (previous) return acceptTaskCancellation(ctx, admission.request);
80
+ if (input.runtimeEpoch !== cancellationRuntimeEpoch(ctx) || input.runtimeEpoch !== admission.runtimeEpoch) throw new StoreError("supervision-conflict", "not_accepted: stale-runtime-epoch; query journal before new admission");
81
+ const operation = getOperation(ctx, admission.request.operationId);
82
+ const epoch = cancelEpoch(ctx, admission.request.operationId);
83
+ if (epoch !== admission.cancelEpoch || revision(operation, epoch) !== admission.revision) throw new StoreError("operation-conflict", "not_accepted: stale-revision or cancellation epoch");
84
+ const intent = acceptTaskCancellation(ctx, admission.request);
85
+ run(ctx, "INSERT INTO coordinator_state (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value", `cancel:${intent.operationId}`, String(epoch + 1));
86
+ return intent;
87
+ });
88
+ }
89
+
90
+ export function cancellationCredential(): { credential: string; hash: string } {
91
+ const credential = randomBytes(32).toString("hex");
92
+ return { credential, hash: credentialHash(credential) };
93
+ }
94
+
95
+ function credentialHash(credential: string): string {
96
+ return createHash("sha256").update(requireText("credential", credential, 128)).digest("hex");
97
+ }
98
+
99
+ /** Called only by the existing admitted domain host, never by a socket command. */
100
+ export function admitTaskCancellation(ctx: StoreContext, input: CancellationAdmission): void {
101
+ const normalized = request(input.request);
102
+ const hash = requireId("credentialHash", input.credentialHash);
103
+ const directory = requireText("directory", input.directory, 4096);
104
+ ctx.transaction(() => {
105
+ const operation = getOperation(ctx, normalized.operationId);
106
+ if (!operation || !sameOwner(operation.owner, normalized.owner)) throw new StoreError("foreign-owner", "Cancellation admission requires the recorded owner.");
107
+ const previous = getTaskCancellation(ctx, normalized);
108
+ if (operation.launchToken !== normalized.expectedLaunchToken || (!previous && operation.supervision?.hostId !== normalized.expectedHostId)) {
109
+ throw new StoreError("supervision-conflict", "Cancellation admission requires the current exact launch and host.");
110
+ }
111
+ if (previous && JSON.stringify(request(previous)) !== JSON.stringify(normalized)) throw new StoreError("request-conflict", "Cancellation key is bound to different request content.");
112
+ const original = previous ? request(previous) : normalized;
113
+ const epoch = cancelEpoch(ctx, normalized.operationId);
114
+ run(ctx, "INSERT INTO task_cancellation_authorities (credential_hash, request_json, directory) VALUES (?, ?, ?)", hash,
115
+ JSON.stringify({ request: original, runtimeEpoch: cancellationRuntimeEpoch(ctx), cancelEpoch: epoch, revision: revision(operation, epoch) }), directory);
116
+ });
117
+ }
118
+
119
+ /** A credential binds an already-admitted exact request, not a claimed session ID. */
120
+ export function authorizedTaskCancellation(ctx: StoreContext, credential: string): CancellationAdmission {
121
+ const row = getRow(ctx, "SELECT * FROM task_cancellation_authorities WHERE credential_hash = ?", credentialHash(credential));
122
+ if (!row) throw new StoreError("foreign-owner", "permission-unavailable: cancellation authority is not registered.");
123
+ return { credentialHash: credentialHash(credential), ...JSON.parse(columnText(row, "request_json")), directory: columnText(row, "directory") };
124
+ }
125
+
126
+ export function finishTaskCancellation(ctx: StoreContext, input: { credential: string; status: string; terminal: boolean }): TaskCancellationIntent {
127
+ const admission = authorizedTaskCancellation(ctx, input.credential);
128
+ return finishTaskCancellationIntent(ctx, { request: admission.request, status: input.status, terminal: input.terminal });
129
+ }
130
+
131
+ export function finishTaskCancellationIntent(ctx: StoreContext, input: { request: TaskCancellationRequest; status: string; terminal: boolean; publication?: RecordTerminalOutcomeInput }): TaskCancellationIntent {
132
+ return ctx.transaction(() => {
133
+ const intent = recordTaskStopRequested(ctx, input.request);
134
+ if (intent.result) return intent;
135
+ if (input.publication) {
136
+ if (input.publication.operationId !== intent.operationId || !sameOwner(input.publication.owner, intent.owner)) throw new StoreError("foreign-owner", "Terminal publication does not match the cancellation intent.");
137
+ recordTerminalOutcome(ctx, input.publication);
138
+ }
139
+ const result = { status: requireText("status", input.status, 64), terminal: input.terminal === true };
140
+ run(ctx, "UPDATE task_cancellation_requests SET result_json = ? WHERE owner_key = ? AND request_key = ?", JSON.stringify(result), ownerKey(intent.owner), intent.idempotencyKey);
141
+ return { ...intent, result };
142
+ });
143
+ }
144
+
145
+ export function unknownTaskCancellation(ctx: StoreContext, input: TaskCancellationRequest): TaskCancellationIntent {
146
+ return ctx.transaction(() => {
147
+ const intent = getTaskCancellation(ctx, input);
148
+ if (!intent) throw new StoreError("request-conflict", "Cannot record an unknown outcome without an accepted intent.");
149
+ if (intent.result) return intent;
150
+ const result = { status: "outcome_unknown", terminal: false };
151
+ run(ctx, "UPDATE task_cancellation_requests SET result_json = ? WHERE owner_key = ? AND request_key = ?", JSON.stringify(result), ownerKey(intent.owner), intent.idempotencyKey);
152
+ return { ...intent, result };
153
+ });
154
+ }
155
+
156
+ function ownerKey(owner: OwnerIdentity): string {
157
+ return JSON.stringify([owner.kind, owner.sessionId, owner.workspace, owner.branchId, owner.goalId]);
158
+ }
159
+
160
+ function request(input: TaskCancellationRequest): TaskCancellationRequest {
161
+ return {
162
+ owner: normalizeOwner("owner", input.owner),
163
+ idempotencyKey: requireText("idempotencyKey", input.idempotencyKey, 512),
164
+ operationId: requireId("operationId", input.operationId),
165
+ expectedLaunchToken: requireId("launchToken", input.expectedLaunchToken),
166
+ expectedTerminalRevision: requireCounter("terminalRevision", input.expectedTerminalRevision),
167
+ expectedHostId: requireId("hostId", input.expectedHostId),
168
+ reason: requireText("reason", input.reason, 1024),
169
+ };
170
+ }
171
+
172
+ export function getTaskCancellation(
173
+ ctx: StoreContext,
174
+ input: { owner: OwnerIdentity; idempotencyKey: string },
175
+ ): TaskCancellationIntent | null {
176
+ const owner = normalizeOwner("owner", input.owner);
177
+ const key = requireText("idempotencyKey", input.idempotencyKey, 512);
178
+ const row = getRow(ctx, "SELECT intent_json, state, result_json FROM task_cancellation_requests WHERE owner_key = ? AND request_key = ?", ownerKey(owner), key);
179
+ if (!row) return null;
180
+ return { ...JSON.parse(columnText(row, "intent_json")), state: columnText(row, "state"), ...(row.result_json ? { result: JSON.parse(columnText(row, "result_json")) } : {}) };
181
+ }
182
+
183
+ export function acceptTaskCancellation(ctx: StoreContext, input: TaskCancellationRequest): TaskCancellationIntent {
184
+ const normalized = request(input);
185
+ return ctx.transaction(() => {
186
+ // Journal lookup precedes current object checks: a retry after terminal
187
+ // publication must recover the original receipt, not become a new stop.
188
+ const previous = getTaskCancellation(ctx, normalized);
189
+ if (previous) {
190
+ const { operation: _operation, taskId: _taskId, state: _state, acceptedAt: _at, result: _result, ...original } = previous;
191
+ if (JSON.stringify(original) !== JSON.stringify(normalized)) {
192
+ throw new StoreError("request-conflict", "Cancellation key is already bound to different request content.");
193
+ }
194
+ return previous;
195
+ }
196
+ const operation = getOperation(ctx, normalized.operationId);
197
+ if (!operation) throw new StoreError("unknown-operation", "Cancellation operation does not exist.");
198
+ if (!sameOwner(operation.owner, normalized.owner)) throw new StoreError("foreign-owner", "Cancellation requires the recorded execution owner.");
199
+ if (operation.launchToken !== normalized.expectedLaunchToken || operation.terminalRevision !== normalized.expectedTerminalRevision) {
200
+ throw new StoreError("operation-conflict", "Cancellation launch token or terminal revision changed.");
201
+ }
202
+ if (operation.supervision?.hostId !== normalized.expectedHostId) {
203
+ throw new StoreError("supervision-conflict", "Cancellation supervision host changed.");
204
+ }
205
+ const intent: TaskCancellationIntent = {
206
+ ...normalized, operation: "cancel_task", taskId: operation.taskId, state: "accepted", acceptedAt: ctx.now(),
207
+ };
208
+ run(ctx, "INSERT INTO task_cancellation_requests (owner_key, request_key, operation_id, intent_json, state) VALUES (?, ?, ?, ?, 'accepted')",
209
+ ownerKey(normalized.owner), normalized.idempotencyKey, operation.operationId, JSON.stringify(intent));
210
+ return intent;
211
+ });
212
+ }
213
+
214
+ /** Record durable stop-file publication, never process exit or a terminal verdict. */
215
+ export function recordTaskStopRequested(ctx: StoreContext, input: TaskCancellationRequest): TaskCancellationIntent {
216
+ return ctx.transaction(() => {
217
+ const normalized = request(input);
218
+ if (!getTaskCancellation(ctx, normalized)) throw new StoreError("request-conflict", "Cancellation intent must commit before the stop action.");
219
+ const intent = acceptTaskCancellation(ctx, normalized);
220
+ run(ctx, "UPDATE task_cancellation_requests SET state = 'stop-requested' WHERE owner_key = ? AND request_key = ?",
221
+ ownerKey(normalized.owner), normalized.idempotencyKey);
222
+ return { ...intent, state: "stop-requested" };
223
+ });
224
+ }
@@ -0,0 +1,88 @@
1
+ import { connect } from "node:net";
2
+
3
+ /** SDK-free observation stream. Cached snapshots are the only synchronous read API. */
4
+ export class WorkClient {
5
+ socket;
6
+ snapshot;
7
+ pending = new Map();
8
+ listeners = new Set();
9
+ sequence = 0;
10
+ scope;
11
+ buffer = "";
12
+ closed = false;
13
+
14
+ constructor(socketPath, agentDir, requiredCapabilities = []) {
15
+ this.socket = typeof socketPath === "string" ? connect(socketPath) : socketPath;
16
+ this.socket.setEncoding("utf8");
17
+ this.socket.on("data", chunk => {
18
+ this.buffer += chunk;
19
+ if (Buffer.byteLength(this.buffer) > 4 * 1024 * 1024) return this.fail(new Error("runtime-unhealthy: oversized stream frame"));
20
+ while (this.buffer.includes("\n")) {
21
+ const index = this.buffer.indexOf("\n"), line = this.buffer.slice(0, index);
22
+ this.buffer = this.buffer.slice(index + 1);
23
+ try {
24
+ const message = JSON.parse(line);
25
+ if (message.type === "event") {
26
+ if (message.event.type === "resync_required") { this.degrade(message.event.reason); void this.resync().catch(error => this.degrade(String(error))); }
27
+ else if (message.event.type === "runtime_snapshot") this.accept(message.event.snapshot);
28
+ } else {
29
+ const request = this.pending.get(message.id);
30
+ if (!request) continue;
31
+ this.pending.delete(message.id); clearTimeout(request.timer);
32
+ if (message.success) request.resolve(message.data); else request.reject(new Error(message.error));
33
+ }
34
+ } catch (error) { this.fail(error); }
35
+ }
36
+ });
37
+ this.socket.on("error", error => this.fail(error));
38
+ this.socket.on("close", () => this.fail(new Error("runtime-unavailable: disconnected; resync required")));
39
+ this.ready = this.request("hello", { protocolVersion: 1, runtimeRoot: agentDir, requiredCapabilities: ["runtime-state-v1", "runtime-subscriptions-v1", ...requiredCapabilities] })
40
+ .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; });
41
+ }
42
+ request(type, params = {}) {
43
+ if (this.closed) return Promise.reject(new Error("runtime-unavailable: disconnected; resync required"));
44
+ if (this.pending.size >= 32) return Promise.reject(new Error("runtime-unhealthy: too many in-flight queries"));
45
+ const id = `work-${++this.sequence}`;
46
+ return new Promise((resolve, reject) => {
47
+ const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(`runtime-unhealthy: ${type} timed out`)); }, 5000);
48
+ this.pending.set(id, { resolve, reject, timer });
49
+ this.socket.write(JSON.stringify({ id, type, ...params }) + "\n");
50
+ });
51
+ }
52
+ onChange(listener) { this.listeners.add(listener); return () => this.listeners.delete(listener); }
53
+ notify() { for (const listener of this.listeners) listener(this.snapshot); }
54
+ degrade(reason) {
55
+ this.snapshot = { ...this.snapshot, status: "degraded", reason, rows: this.snapshot?.rows ?? [] };
56
+ this.notify();
57
+ }
58
+ accept(snapshot) {
59
+ if (this.snapshot?.instanceId === snapshot.instanceId && snapshot.seq < this.snapshot.seq) return;
60
+ if (this.snapshot?.instanceId && this.snapshot.instanceId !== snapshot.instanceId) {
61
+ this.degrade("instance-changed: resync required");
62
+ snapshot = { ...snapshot, resyncRequired: true, resyncReason: "instance-changed" };
63
+ } else if (this.snapshot?.seq !== undefined && snapshot.seq > this.snapshot.seq + 1) {
64
+ this.degrade("sequence-gap: replacing with a full authoritative snapshot");
65
+ snapshot = { ...snapshot, resyncRequired: true, resyncReason: "sequence-gap" };
66
+ }
67
+ // Every event contains a complete bounded snapshot; gaps do not require inferred deltas.
68
+ this.snapshot = Object.freeze(snapshot); this.notify();
69
+ }
70
+ async subscribe(scope) {
71
+ await this.ready;
72
+ this.scope = scope;
73
+ const snapshot = await this.request("runtime_subscribe", { scope });
74
+ this.accept(snapshot); return snapshot;
75
+ }
76
+ async resync() {
77
+ const snapshot = await this.request("runtime_subscribe", { scope: this.scope, sinceSeq: this.snapshot?.seq, instanceId: this.snapshot?.instanceId });
78
+ this.accept(snapshot); return snapshot;
79
+ }
80
+ async get(scope) { await this.ready; return this.request("runtime_get_snapshot", { scope }); }
81
+ fail(error) {
82
+ if (this.closed) return;
83
+ this.closed = true;
84
+ for (const request of this.pending.values()) { clearTimeout(request.timer); request.reject(error); }
85
+ this.pending.clear(); this.socket.destroy(); this.degrade(String(error));
86
+ }
87
+ close() { this.fail(new Error("runtime-unavailable: client closed")); this.listeners.clear(); }
88
+ }
package/src/tools.ts CHANGED
@@ -24,6 +24,7 @@ import {
24
24
  type DurableTaskKind,
25
25
  type WaitView,
26
26
  } from "./observed-waits.js";
27
+ import { backgroundObservation } from "./work-observation.js";
27
28
  import { inspectMeta, listMetasForOrigin, readMeta, writeMeta } from "./registry.js";
28
29
  import { awaitFirstWatchCheck, FIRST_WATCH_CHECK_WAIT_MS, resumeRunningTask, spawnTask, startWatchTask, stopTask, type WatchTaskParams, type BackgroundTaskRuntime } from "./runtime.js";
29
30
  import { runTaskMaintenance } from "./maintenance.js";
@@ -198,6 +199,7 @@ const LogParams = Type.Object({
198
199
  });
199
200
 
200
201
  const ActionParams = Type.Object({
202
+ request_id: Type.Optional(Type.String({ description: "Stable cancellation request identity for action:stop. Reuse after disconnect." })),
201
203
  action: Type.Union([
202
204
  Type.Literal("spawn"),
203
205
  Type.Literal("watch"),
@@ -225,6 +227,7 @@ const ActionParams = Type.Object({
225
227
  });
226
228
 
227
229
  const StatusActionParams = Type.Object({
230
+ request_id: Type.Optional(Type.String({ description: "Stable cancellation request identity for action:stop. Reuse after disconnect." })),
228
231
  action: Type.Union([Type.Literal("list"), Type.Literal("status"), Type.Literal("log"), Type.Literal("stop"), Type.Literal("clear")]),
229
232
  id: Type.Optional(Type.String()),
230
233
  status: Type.Optional(Type.Array(Type.String())),
@@ -397,7 +400,7 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
397
400
  parameters: ListParams,
398
401
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
399
402
  activeSession = getCallbackOrigin(ctx);
400
- return text(durableAwareList(pi, params, activeSession));
403
+ return text(await durableAwareList(pi, params, activeSession, ctx));
401
404
  },
402
405
  });
403
406
 
@@ -434,10 +437,10 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
434
437
  name: "bg_task_stop",
435
438
  label: "BG Stop",
436
439
  description: "Cancel a watcher or terminate a background task. Only a task owned by the current session stops; a foreign-session or unverifiable task is refused unless all:true. For a tmux-backed SSH task, stop kills its remote tmux session before marking it cancelled. Direct SSH stop only tears down the local client and may leave the remote process running.",
437
- parameters: IdParams,
438
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
440
+ parameters: Type.Object({ ...IdParams.properties, request_id: Type.Optional(Type.String({ description: "Stable cancellation request identity. Reuse this value after a disconnect." })) }),
441
+ async execute(toolCallId, params, _signal, _onUpdate, ctx) {
439
442
  activeSession = getCallbackOrigin(ctx);
440
- const durable = await durableStopText(pi, params.id, ctx);
443
+ const durable = await durableStopText(pi, params.id, ctx, params.request_id ?? toolCallId);
441
444
  if (durable !== undefined) {
442
445
  refreshNavigator(ctx);
443
446
  return text(durable);
@@ -457,9 +460,9 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
457
460
  renderResult(result: unknown, options: unknown, theme: unknown) {
458
461
  return renderBackgroundTaskLogDisplay(result, options, theme);
459
462
  },
460
- async execute(_toolCallId, params, signal, _onUpdate, ctx) {
463
+ async execute(toolCallId, params, signal, _onUpdate, ctx) {
461
464
  activeSession = getCallbackOrigin(ctx);
462
- return actionText(pi, params, ctx, activeSession, getActiveSession, signal, runtime, refreshNavigator);
465
+ return actionText(pi, { ...params, request_id: params.request_id ?? toolCallId }, ctx, activeSession, getActiveSession, signal, runtime, refreshNavigator);
463
466
  },
464
467
  });
465
468
 
@@ -471,9 +474,9 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
471
474
  renderResult(result: unknown, options: unknown, theme: unknown) {
472
475
  return renderBackgroundTaskLogDisplay(result, options, theme);
473
476
  },
474
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
477
+ async execute(toolCallId, params, _signal, _onUpdate, ctx) {
475
478
  activeSession = getCallbackOrigin(ctx);
476
- return actionText(pi, params, ctx, activeSession, getActiveSession, undefined, runtime, refreshNavigator);
479
+ return actionText(pi, { ...params, request_id: params.request_id ?? toolCallId }, ctx, activeSession, getActiveSession, undefined, runtime, refreshNavigator);
477
480
  },
478
481
  });
479
482
 
@@ -686,7 +689,7 @@ async function runAction(
686
689
  return withNavigatorRefresh(ctx, await launchWatch(pi, params as unknown as WatchTaskParams, ctx.cwd, callbackOrigin, getActiveSession, FIRST_WATCH_CHECK_WAIT_MS, signal, runtime));
687
690
  }
688
691
  case "list":
689
- return durableAwareList(pi, params, callbackOrigin);
692
+ return durableAwareList(pi, params, callbackOrigin, ctx);
690
693
  case "status": {
691
694
  if (!params.id) return "Invalid parameters: status requires id.";
692
695
  const durable = durableStatusText(pi, String(params.id), ctx);
@@ -701,7 +704,7 @@ async function runAction(
701
704
  }
702
705
  case "stop": {
703
706
  if (!params.id) return "Invalid parameters: stop requires id.";
704
- const durable = await durableStopText(pi, String(params.id), ctx);
707
+ const durable = await durableStopText(pi, String(params.id), ctx, typeof params.request_id === "string" ? params.request_id : undefined);
705
708
  if (durable !== undefined) return withNavigatorRefresh(ctx, durable);
706
709
  return withNavigatorRefresh(ctx, await formatStop(pi, String(params.id), ctx, getActiveSession, statusOptions(params, callbackOrigin), runtime));
707
710
  }
@@ -721,25 +724,26 @@ async function runAction(
721
724
  }
722
725
  }
723
726
 
724
- /**
725
- * Durable rows are appended to the legacy list output only when they exist, so
726
- * the legacy surface is byte-for-byte unchanged for sessions that never launch a
727
- * supervised operation. Cursors stay legacy-only; durable rows are all shown on
728
- * the first page.
729
- */
730
- function durableAwareList(
727
+ /** Shared history applies ownership, filters and paging before metadata crosses the socket. */
728
+ async function durableAwareList(
731
729
  pi: ExtensionAPI,
732
730
  params: Record<string, unknown>,
733
731
  origin: BackgroundTaskCallbackOrigin | undefined,
734
- ): string {
735
- const legacy = formatList(listOptions(params, origin));
732
+ ctx: ExtensionContext,
733
+ ): Promise<string> {
734
+ const options = listOptions(params, origin);
735
+ const snapshot = origin && !unavailableSessionOrigins.has(origin) ? await backgroundObservation(pi, ctx, true, params.all === true,
736
+ { limit: options.limit, statuses: options.statuses, cursor: options.cursor }) : undefined;
737
+ if (snapshot && snapshot.status !== "ready") throw new Error(snapshot.reason ?? "Background activity is unverified");
738
+ const legacy = formatList(options, snapshot?.backgroundIndex);
739
+ if (snapshot) return legacy;
736
740
  const host = getObservedWaitHost(pi);
737
- if (!host?.available || !origin || typeof params.cursor === "string") return legacy;
741
+ if ((!snapshot && !host?.available) || !origin || typeof params.cursor === "string") return legacy;
738
742
  const wanted = Array.isArray(params.status) && params.status.length > 0
739
743
  ? new Set(params.status.filter((status): status is string => typeof status === "string"))
740
744
  : undefined;
741
745
  const limit = Math.max(1, Math.min(Math.floor(typeof params.limit === "number" ? params.limit : 10), 100));
742
- const durable = host.listDurableTasks(origin)
746
+ const durable = (snapshot ? snapshot.rows.filter((row: any) => row.meta.durable).map((row: any) => row.meta) as import("./observed-waits.js").DurableTaskProjection[] : host?.listDurableTasks(origin) ?? [])
743
747
  .filter((task) => !wanted || (task.active ? wanted.has("running") : wanted.has(task.status)))
744
748
  .slice(0, limit);
745
749
  if (durable.length === 0) return legacy;
@@ -844,11 +848,12 @@ function durableLogText(
844
848
  }
845
849
  }
846
850
 
847
- async function durableStopText(pi: ExtensionAPI, id: string, ctx: ExtensionContext): Promise<string | undefined> {
851
+ async function durableStopText(pi: ExtensionAPI, id: string, ctx: ExtensionContext, requestId?: string): Promise<string | undefined> {
848
852
  const host = getObservedWaitHost(pi);
849
853
  if (!host?.available || !host.isDurableTask(id)) return undefined;
850
854
  try {
851
- return host.formatStatus(await host.stopForParent(ctx, id));
855
+ const status = host.formatStatus(await host.stopForParent(ctx, id, requestId));
856
+ return requestId ? `Cancellation request: ${requestId}\n${status}` : status;
852
857
  } catch (error) {
853
858
  return readableError(error);
854
859
  }
@@ -0,0 +1,117 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { mkdirSync, readFileSync, realpathSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { homedir } from "node:os";
5
+ import { setTimeout as delay } from "node:timers/promises";
6
+
7
+ const hostedClients = new WeakSet<object>();
8
+ const clients = new WeakMap<object, Promise<any>>();
9
+ const generations = new WeakMap<object, number>();
10
+ const listeners = new WeakMap<object, Set<() => void>>();
11
+ export function onBackgroundObservation(pi: ExtensionAPI, notify: () => void): () => void {
12
+ let set = listeners.get(pi);
13
+ if (!set) { set = new Set(); listeners.set(pi, set); }
14
+ set.add(notify); return () => { set.delete(notify); };
15
+ }
16
+
17
+ /** A query connection grants no supervisor, transcript writer or retention authority. */
18
+ export function backgroundObservation(pi: ExtensionAPI, ctx: ExtensionContext, history = false, all = false, page?: { limit?: number; statuses?: string[]; cursor?: string }): Promise<any> {
19
+ const scope = { background: true, cwd: ctx.cwd, sessionId: ctx.sessionManager?.getSessionId(), processId: process.pid };
20
+ const generation = generations.get(pi) ?? 0;
21
+ const read = async (retry: boolean): Promise<any> => {
22
+ if ((generations.get(pi) ?? 0) !== generation) throw new Error("runtime-unavailable: client closed");
23
+ const connection = observationClient(pi, scope);
24
+ const client = await connection;
25
+ if ((generations.get(pi) ?? 0) !== generation) throw new Error("runtime-unavailable: client closed");
26
+ try {
27
+ const deadline = Date.now() + 20000;
28
+ for (;;) {
29
+ checkGeneration();
30
+ const snapshot = await client.get({ ...scope, backgroundHistory: history, backgroundAll: all, ...page });
31
+ if (!history || snapshot.status !== "rebuilding" || Date.now() >= deadline) return snapshot;
32
+ await delay(20);
33
+ }
34
+ }
35
+ catch (error) {
36
+ if (!retry || hostedClients.has(client) || !client.closed || (generations.get(pi) ?? 0) !== generation) throw error;
37
+ if (clients.get(pi) === connection) clients.delete(pi);
38
+ return read(false);
39
+ }
40
+ };
41
+ const checkGeneration = () => { if ((generations.get(pi) ?? 0) !== generation) throw new Error("runtime-unavailable: client closed"); };
42
+ return read(true);
43
+ }
44
+
45
+ function observationClient(pi: ExtensionAPI, scope: { background: boolean; cwd: string; sessionId?: string }): Promise<any> {
46
+ const generation = generations.get(pi) ?? 0;
47
+ const checkOpen = () => {
48
+ if ((generations.get(pi) ?? 0) !== generation) throw new Error("runtime-unavailable: client closed");
49
+ };
50
+ let pending = clients.get(pi);
51
+ if (!pending) {
52
+ pending = (async () => {
53
+ let hosted: any;
54
+ let rejected: unknown;
55
+ pi.events?.emit("pi-better-runtime:connect", {
56
+ accept: (client: any) => { hosted = client; }, reject: (error: unknown) => { rejected = error; },
57
+ });
58
+ if (rejected) throw rejected;
59
+ if (hosted) {
60
+ hostedClients.add(hosted);
61
+ hosted.onChange(() => { for (const notify of listeners.get(pi) ?? []) notify(); });
62
+ try { await hosted.subscribe(scope); checkOpen(); return hosted; }
63
+ catch (error) { hosted.close(); throw error; }
64
+ }
65
+ const requestedRoot = process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
66
+ mkdirSync(requestedRoot, { recursive: true, mode: 0o700 });
67
+ const root = realpathSync(requestedRoot);
68
+ const ensure = async () => {
69
+ checkOpen();
70
+ const installer = new URL("../runtime-client/src/runtime/client.mjs", import.meta.url).href;
71
+ const { ensureRuntime } = await import(installer);
72
+ checkOpen();
73
+ await ensureRuntime({ agentDir: root, serverDir: process.env.PI_SERVER_DIR });
74
+ };
75
+ let registration;
76
+ try { registration = JSON.parse(readFileSync(join(root, "server-registration-v1.json"), "utf8")); }
77
+ catch (error) {
78
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
79
+ await ensure();
80
+ registration = JSON.parse(readFileSync(join(root, "server-registration-v1.json"), "utf8"));
81
+ }
82
+ if (registration.version !== 1 || registration.agentDir !== root) throw new Error("Invalid canonical runtime registration");
83
+ const module = new URL("./shared-work-client.mjs", import.meta.url).href;
84
+ const { WorkClient } = await import(module);
85
+ const connect = async () => {
86
+ checkOpen();
87
+ const client = new WorkClient(join(registration.serverDir, "pi-server.sock"), root, ["runtime-background-state-v1"]);
88
+ let subscribed = false;
89
+ client.onChange(() => {
90
+ if (!subscribed || clients.get(pi) !== pending) return;
91
+ if (client.closed) clients.delete(pi);
92
+ for (const notify of listeners.get(pi) ?? []) notify();
93
+ });
94
+ try { await client.subscribe(scope); }
95
+ catch (error) { client.close(); throw error; }
96
+ subscribed = true;
97
+ return client;
98
+ };
99
+ try { return await connect(); }
100
+ catch (error) {
101
+ if (!["ENOENT", "ECONNREFUSED"].includes((error as NodeJS.ErrnoException).code ?? "")) throw error;
102
+ // Registration chooses transport; only the owner-safe installer may recover it.
103
+ await ensure();
104
+ return connect();
105
+ }
106
+ })();
107
+ clients.set(pi, pending);
108
+ pending.catch(() => { if (clients.get(pi) === pending) clients.delete(pi); });
109
+ }
110
+ return pending;
111
+ }
112
+
113
+ export function closeBackgroundObservation(pi: ExtensionAPI): void {
114
+ generations.set(pi, (generations.get(pi) ?? 0) + 1);
115
+ const pending = clients.get(pi); clients.delete(pi);
116
+ void pending?.then(client => client.close(), () => {});
117
+ }