pi-better-background-tasks 0.15.4 → 0.17.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 (42) hide show
  1. package/README.md +22 -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 +218 -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 +102 -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 +4 -0
  24. package/src/observed-waits.ts +255 -37
  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 +16 -4
  30. package/src/shared-operation-coordinator/assignment-observation.mjs +80 -3
  31. package/src/shared-operation-coordinator/index.ts +2 -0
  32. package/src/shared-operation-coordinator/src/discovery.ts +9 -0
  33. package/src/shared-operation-coordinator/src/errors.ts +2 -0
  34. package/src/shared-operation-coordinator/src/operations.ts +6 -4
  35. package/src/shared-operation-coordinator/src/result-supervision.ts +128 -0
  36. package/src/shared-operation-coordinator/src/schema.ts +39 -1
  37. package/src/shared-operation-coordinator/src/store.ts +55 -0
  38. package/src/shared-operation-coordinator/src/task-cancellation.ts +224 -0
  39. package/src/shared-operation-coordinator/src/types.ts +6 -0
  40. package/src/shared-work-client.mjs +102 -0
  41. package/src/tools.ts +87 -59
  42. package/src/work-observation.ts +117 -0
@@ -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
+ }
@@ -83,6 +83,10 @@ export interface ObserverIdentity {
83
83
  * (a replacement host takes over on reload) while launch identity is not.
84
84
  */
85
85
  export interface SupervisionIdentity {
86
+ /** Durable discovery scope, recorded before sidecar creation or runner start. */
87
+ resultScope?: string;
88
+ /** The host uses grant-before-runner result admission and performs no global discovery. */
89
+ resultAdapter?: 1;
86
90
  /** Host that owns supervision, e.g. the Pi process id plus a start token. */
87
91
  hostId: string;
88
92
  /** Runner process identity, when a separate runner owns the operation. */
@@ -112,6 +116,8 @@ export interface RegisterOperationInput {
112
116
  }
113
117
 
114
118
  export interface OperationRecord {
119
+ /** Grant presence in the same snapshot as a bulk operation read. */
120
+ resultManaged?: boolean;
115
121
  operationId: string;
116
122
  taskId: string;
117
123
  launchToken: string;
@@ -0,0 +1,102 @@
1
+ import { connect } from "node:net";
2
+ import { performance } from "node:perf_hooks";
3
+
4
+ /** SDK-free observation stream. Cached snapshots are the only synchronous read API. */
5
+ export class WorkClient {
6
+ socket;
7
+ snapshot;
8
+ pending = new Map();
9
+ listeners = new Set();
10
+ catalogListeners = new Set();
11
+ sequence = 0;
12
+ scope;
13
+ buffer = "";
14
+ closed = false;
15
+
16
+ constructor(socketPath, agentDir, requiredCapabilities = []) {
17
+ this.socket = typeof socketPath === "string" ? connect(socketPath) : socketPath;
18
+ this.socket.setEncoding("utf8");
19
+ this.socket.on("data", chunk => {
20
+ this.buffer += chunk;
21
+ if (Buffer.byteLength(this.buffer) > 4 * 1024 * 1024) return this.fail(new Error("runtime-unhealthy: oversized stream frame"));
22
+ while (this.buffer.includes("\n")) {
23
+ const index = this.buffer.indexOf("\n"), line = this.buffer.slice(0, index);
24
+ this.buffer = this.buffer.slice(index + 1);
25
+ try {
26
+ const message = JSON.parse(line);
27
+ if (message.type === "event") {
28
+ 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); void this.resync().catch(error => this.degrade(String(error))); }
30
+ else if (message.event.type === "runtime_snapshot") this.accept(message.event.snapshot);
31
+ } else {
32
+ const request = this.pending.get(message.id);
33
+ if (!request) continue;
34
+ this.pending.delete(message.id); clearTimeout(request.timer);
35
+ if (message.success) request.resolve(message.data); else request.reject(new Error(message.error));
36
+ }
37
+ } catch (error) { this.fail(error); }
38
+ }
39
+ });
40
+ this.socket.on("error", error => this.fail(error));
41
+ this.socket.on("close", () => this.fail(new Error("runtime-unavailable: disconnected; resync required")));
42
+ this.ready = this.request("hello", { protocolVersion: 1, runtimeRoot: agentDir, requiredCapabilities: ["runtime-state-v1", "runtime-subscriptions-v1", ...requiredCapabilities] })
43
+ .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; });
44
+ }
45
+ request(type, params = {}) {
46
+ if (this.closed) return Promise.reject(new Error("runtime-unavailable: disconnected; resync required"));
47
+ if (this.pending.size >= 32) return Promise.reject(new Error("runtime-unhealthy: too many in-flight queries"));
48
+ const id = `work-${++this.sequence}`;
49
+ return new Promise((resolve, reject) => {
50
+ const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(`runtime-unhealthy: ${type} timed out`)); }, 5000);
51
+ this.pending.set(id, { resolve, reject, timer });
52
+ this.socket.write(JSON.stringify({ id, type, ...params }) + "\n");
53
+ });
54
+ }
55
+ onChange(listener) { this.listeners.add(listener); return () => this.listeners.delete(listener); }
56
+ onCatalog(listener) { this.catalogListeners.add(listener); return () => this.catalogListeners.delete(listener); }
57
+ notify() { for (const listener of this.listeners) listener(this.snapshot); }
58
+ degrade(reason) {
59
+ this.snapshot = { ...this.snapshot, status: "degraded", reason, rows: this.snapshot?.rows ?? [] };
60
+ this.notify();
61
+ }
62
+ accept(snapshot) {
63
+ if (this.snapshot?.instanceId === snapshot.instanceId && snapshot.seq < this.snapshot.seq) return;
64
+ if (this.snapshot?.instanceId && this.snapshot.instanceId !== snapshot.instanceId) {
65
+ this.degrade("instance-changed: resync required");
66
+ snapshot = { ...snapshot, resyncRequired: true, resyncReason: "instance-changed" };
67
+ } else if (this.snapshot?.seq !== undefined && snapshot.seq > this.snapshot.seq + 1) {
68
+ this.degrade("sequence-gap: replacing with a full authoritative snapshot");
69
+ snapshot = { ...snapshot, resyncRequired: true, resyncReason: "sequence-gap" };
70
+ }
71
+ // Every event contains a complete bounded snapshot; gaps do not require inferred deltas.
72
+ this.snapshot = Object.freeze(snapshot); this.notify();
73
+ }
74
+ async subscribe(scope) {
75
+ await this.ready;
76
+ this.scope = scope;
77
+ const snapshot = await this.request("runtime_subscribe", { scope });
78
+ this.accept(snapshot); return snapshot;
79
+ }
80
+ async resync() {
81
+ const snapshot = await this.request("runtime_subscribe", { scope: this.scope, sinceSeq: this.snapshot?.seq, instanceId: this.snapshot?.instanceId });
82
+ this.accept(snapshot); return snapshot;
83
+ }
84
+ async get(scope) {
85
+ await this.ready;
86
+ const until = performance.now() + 3500;
87
+ for (let attempt = 0; ; attempt++) {
88
+ const value = await this.request("runtime_get_snapshot", { scope });
89
+ if (!scope?.id || value.status !== "rebuilding" || value.rows.length || performance.now() >= until) return value;
90
+ // A newly written ID may join an inventory without holding the shared RPC queue.
91
+ await new Promise(resolve => setTimeout(resolve, Math.min(250, 50 * 2 ** attempt, until - performance.now())));
92
+ }
93
+ }
94
+ fail(error) {
95
+ if (this.closed) return;
96
+ this.closed = true;
97
+ for (const request of this.pending.values()) { clearTimeout(request.timer); request.reject(error); }
98
+ this.pending.clear(); this.socket.destroy(); this.degrade(String(error));
99
+ for (const listener of this.catalogListeners) listener({ status: "revoked" });
100
+ }
101
+ close() { this.fail(new Error("runtime-unavailable: client closed")); this.listeners.clear(); this.catalogListeners.clear(); }
102
+ }