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.
Files changed (49) hide show
  1. package/README.md +4 -3
  2. package/package.json +1 -1
  3. package/runtime-client/artifacts/darwin-arm64.gz +0 -0
  4. package/runtime-client/artifacts/darwin-arm64.json +1 -1
  5. package/runtime-client/artifacts/darwin-x64.gz +0 -0
  6. package/runtime-client/artifacts/darwin-x64.json +1 -1
  7. package/runtime-client/artifacts/linux-arm64.gz +0 -0
  8. package/runtime-client/artifacts/linux-arm64.json +1 -1
  9. package/runtime-client/artifacts/linux-x64.gz +0 -0
  10. package/runtime-client/artifacts/linux-x64.json +1 -1
  11. package/runtime-client/src/runtime/client.mjs +30 -3
  12. package/runtime-client/src/runtime/work-client.mjs +150 -7
  13. package/src/adapter-contract.ts +1 -1
  14. package/src/goal-provider.ts +31 -16
  15. package/src/index.ts +6 -9
  16. package/src/managed-authority.ts +5 -3
  17. package/src/managed-client.ts +20 -7
  18. package/src/managed-frontend.ts +62 -17
  19. package/src/navigator-provider.ts +15 -5
  20. package/src/observed-wait-client.ts +10 -0
  21. package/src/observed-waits.ts +154 -30
  22. package/src/process-identity.ts +18 -2
  23. package/src/process.ts +3 -3
  24. package/src/registry.ts +53 -5
  25. package/src/runtime.ts +19 -9
  26. package/src/sandbox.ts +14 -11
  27. package/src/shared-callback-batcher.ts +11 -2
  28. package/src/shared-navigator-panels.ts +26 -4
  29. package/src/shared-navigator.ts +197 -14
  30. package/src/shared-operation-coordinator/assignment-observation.mjs +43 -35
  31. package/src/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  32. package/src/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
  33. package/src/shared-operation-coordinator/src/background-requests.ts +14 -3
  34. package/src/shared-operation-coordinator/src/discovery.ts +5 -3
  35. package/src/shared-operation-coordinator/src/operations.ts +50 -2
  36. package/src/shared-operation-coordinator/src/result-supervision.ts +12 -0
  37. package/src/shared-operation-coordinator/src/rows.ts +2 -0
  38. package/src/shared-operation-coordinator/src/schema.ts +40 -24
  39. package/src/shared-operation-coordinator/src/store.ts +34 -8
  40. package/src/shared-operation-coordinator/src/subagent-launch.ts +24 -1
  41. package/src/shared-operation-coordinator/src/types.ts +5 -1
  42. package/src/shared-sandbox-core.ts +1 -1
  43. package/src/shared-work-client.mjs +150 -7
  44. package/src/supervisor/generated/process-identity.mjs +20 -2
  45. package/src/supervisor/generated/process.mjs +3 -3
  46. package/src/task-diagnostics.ts +1 -1
  47. package/src/tools.ts +41 -38
  48. package/src/types.ts +3 -1
  49. package/src/work-observation.ts +46 -19
package/README.md CHANGED
@@ -185,9 +185,10 @@ missing profile files or current process-tool denials are not confinement proof.
185
185
  Remote execution also reports unknown remote confinement.
186
186
 
187
187
  Use `bg_task_status` with `diagnostics:true` (or either wrapper's `status`
188
- action) for a bounded, current process snapshot. Both Main and Background tasks
189
- must currently permit **Process access: Read**, even when sandbox switches are
190
- Off. The result checks the recorded PID and start identity, then reports process
188
+ action) for a bounded, current process snapshot. An enabled Background tasks
189
+ profile must permit **Process access: Read**. A disabled profile's retained
190
+ setting does not deny access. The adapter is unavailable under Main confinement.
191
+ The result checks the recorded PID and start identity, then reports process
191
192
  state, accumulated CPU time, and available wait evidence. It never reads command
192
193
  arguments or environment values and never probes a remote host or descendants.
193
194
  A snapshot cannot establish useful work or a hang. Watch poll PIDs are not
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-background-tasks",
3
- "version": "0.18.0",
3
+ "version": "0.19.0",
4
4
  "description": "Pi extension for durable background shell tasks, watchers, logs, and status inspection.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"e89627fd959da4e828f709c00fa6b2178ffac42197f95bd118ba7d4625f97a25","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-arm64","dependencyLockDigest":"a104a72371ffce16cf6acd48e6ccbbf36023e4eb0fbe571677bdaeaa4fb84c27","protocolVersion":1,"serverVersion":"0.5.0","contentId":"ff6f0431d44ca8784bb3075ecd23f3f819435df221fa8635def2c05d826a23af"},"sha256":"74642cefa6adb1f02c54e759bd3f9f81ab21c18c27ca05ba09302f5ef12a61f1"}
1
+ {"build":{"format":1,"sourceDigest":"f5be3a2ec16ce4d3d7c8789e3810a8a7d99c156924396d69538180a65911523f","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-arm64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.6.0","contentId":"f12c8ea387ac5ac58f379ea5253db84cd02b3e198bd5825d4057159bf3ce9a29"},"sha256":"cf84d66a122ec48f963230271827969fba919a8fec37fa7e72fca01108452ca6"}
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"e89627fd959da4e828f709c00fa6b2178ffac42197f95bd118ba7d4625f97a25","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-x64","dependencyLockDigest":"a104a72371ffce16cf6acd48e6ccbbf36023e4eb0fbe571677bdaeaa4fb84c27","protocolVersion":1,"serverVersion":"0.5.0","contentId":"9e4de6d9e748e598ebed703c087df5b5bc76f01cd02ecf482c75b7f95ac881d7"},"sha256":"1e9387e6da69c4ba18cdbbc0f70fe01e4700c73e69ea507e4a30db761478b0be"}
1
+ {"build":{"format":1,"sourceDigest":"f5be3a2ec16ce4d3d7c8789e3810a8a7d99c156924396d69538180a65911523f","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-x64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.6.0","contentId":"1323fe9b4a67f276d9fca3bbf569a23809aef9e792e1eb27491da2f8e86441bc"},"sha256":"0db8e7c0947bdcc8cc1db7048474dea6eaeda8a34af328833ea345e8d1da65c3"}
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"e89627fd959da4e828f709c00fa6b2178ffac42197f95bd118ba7d4625f97a25","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-arm64","dependencyLockDigest":"a104a72371ffce16cf6acd48e6ccbbf36023e4eb0fbe571677bdaeaa4fb84c27","protocolVersion":1,"serverVersion":"0.5.0","contentId":"f440118e90639f06127f3f2082a117e8d4aaa137ecde155870192539fc200eaa"},"sha256":"e740abc2b40d3069701ce3540f2881fd836406eb6a66e856c834c967ee8e9e90"}
1
+ {"build":{"format":1,"sourceDigest":"f5be3a2ec16ce4d3d7c8789e3810a8a7d99c156924396d69538180a65911523f","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-arm64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.6.0","contentId":"f27100b28df8d232d02b618575d71c6af5da4444b6f7e117a78f495e341aefe8"},"sha256":"c21dc9ab46e9221a7390135a96235a863f23d6b4ae72c7b27fca0b34618273c7"}
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"e89627fd959da4e828f709c00fa6b2178ffac42197f95bd118ba7d4625f97a25","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-x64","dependencyLockDigest":"a104a72371ffce16cf6acd48e6ccbbf36023e4eb0fbe571677bdaeaa4fb84c27","protocolVersion":1,"serverVersion":"0.5.0","contentId":"d750352fca4145db9e04031a9a8c384ec19c9bd3277dd5139e881d8f0f79fe04"},"sha256":"923e3a45528bd8cb1354ccffe53ca7c8a613d458b2b1914f8e94698146499cc8"}
1
+ {"build":{"format":1,"sourceDigest":"f5be3a2ec16ce4d3d7c8789e3810a8a7d99c156924396d69538180a65911523f","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-x64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.6.0","contentId":"cd25ef6581835707fbce33f9145c602caacbe872132ed4b3630530cde99693da"},"sha256":"2d802769633d26072b47c4389b702cf4e663abcf1b3029fa033ecc2c57512308"}
@@ -92,9 +92,9 @@ export async function ensureRuntime(options) {
92
92
  if (!["ENOENT", "ECONNREFUSED"].includes(error.code ?? ""))
93
93
  throw error;
94
94
  }
95
- const owner = inspectDaemonOwner(root.serverDir);
96
- if (owner.status === "live" || owner.status === "ambiguous")
97
- throw new Error(`runtime-unhealthy: existing ${owner.status} owner at ${root.serverDir}; no replacement was started`);
95
+ const recovered = await waitForRuntimeOwner(root.serverDir, query, timeoutMs, options.signal);
96
+ if (recovered !== undefined)
97
+ return recovered;
98
98
  let runtime;
99
99
  try {
100
100
  runtime = await stageRuntime({ run: runLocal, artifact, installRoot: options.installRoot ?? join(root.agentDir, "managed-runtime"), signal: options.signal, onProgress: options.onProgress, offline: options.offline });
@@ -102,6 +102,7 @@ export async function ensureRuntime(options) {
102
102
  catch (error) {
103
103
  throw new Error(`runtime-unavailable: ${String(error)}. Connect to the network to cache the pinned runtime, or repair the reported corrupt cache; no fallback manager was started.`);
104
104
  }
105
+ options.signal?.throwIfAborted();
105
106
  const fd = openSync(join(root.serverDir, "daemon.log"), "a", 0o600);
106
107
  try {
107
108
  const env = { ...process.env, PI_SERVER_DIR: root.serverDir, PI_CODING_AGENT_DIR: root.agentDir, PI_SERVER_AGENT: "pi" };
@@ -128,3 +129,29 @@ export async function ensureRuntime(options) {
128
129
  }
129
130
  throw new Error(`runtime-unavailable: startup timed out; inspect ${join(root.serverDir, "daemon.log")}; owner was not replaced`);
130
131
  }
132
+ /** Wait for the current owner to listen or release ownership; never replace it. */
133
+ export async function waitForRuntimeOwner(serverDir, query, timeoutMs, signal) {
134
+ // A draining owner can outlive its listening socket. Wait for it rather than
135
+ // treating the handoff window as failure or starting a competing writer.
136
+ const ownerDeadline = Date.now() + timeoutMs;
137
+ let backoff = 100;
138
+ for (;;) {
139
+ const owner = inspectDaemonOwner(serverDir);
140
+ if (owner.status === "ambiguous")
141
+ throw new Error(`runtime-unhealthy: existing ambiguous owner at ${serverDir}; no replacement was started`);
142
+ if (owner.status !== "live")
143
+ return undefined;
144
+ signal?.throwIfAborted();
145
+ if (Date.now() >= ownerDeadline)
146
+ throw new Error("runtime-unavailable: reconnect deadline exceeded waiting for existing live owner");
147
+ await delay(Math.min(backoff, ownerDeadline - Date.now()), undefined, { signal });
148
+ backoff = Math.min(1000, backoff * 2);
149
+ try {
150
+ return await query();
151
+ }
152
+ catch (error) {
153
+ if (!["ENOENT", "ECONNREFUSED"].includes(error.code ?? ""))
154
+ throw error;
155
+ }
156
+ }
157
+ }
@@ -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); void this.resync().catch(error => this.degrade(String(error))); }
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 && snapshot.seq > this.snapshot.seq + 1) {
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
- // Every event contains a complete bounded snapshot; gaps do not require inferred deltas.
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); return 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,5 +1,5 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
- import { getObservedWaitHost } from "./observed-waits.js";
2
+ import { getObservedWaitHost } from "./observed-wait-client.js";
3
3
  import { inspectMeta } from "./registry.js";
4
4
 
5
5
  /** Optional-peer contract, mirrored by pi-better-sandbox/background-admission.ts. */
@@ -1,10 +1,11 @@
1
1
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { listMetas, onMetaChanged } from "./registry.js";
3
- import { getObservedWaitHost, type DurableTaskProjection } from "./observed-waits.js";
3
+ import { getObservedWaitHost } from "./observed-wait-client.js";
4
+ import type { DurableTaskProjection } from "./observed-waits.js";
4
5
  import type { BackgroundTaskMeta } from "./types.js";
5
6
  import { isTerminalStatus } from "./types.js";
6
7
  import { backgroundTaskProgressAt, observeBackgroundTaskStall } from "./stall.js";
7
- import { backgroundObservation, onBackgroundObservation } from "./work-observation.js";
8
+ import { backgroundGoalObservation, onBackgroundObservation } from "./work-observation.js";
8
9
 
9
10
  const GOAL_READY_EVENT = "pi-better-goal:ready";
10
11
  const GOAL_REGISTER_PROVIDER_EVENT = "pi-better-goal:register-provider";
@@ -27,6 +28,7 @@ export interface GoalBackgroundProviderSnapshot {
27
28
  providerId: string;
28
29
  label?: string;
29
30
  items: GoalBackgroundWorkItem[];
31
+ nextDeadline?: number | null;
30
32
  }
31
33
 
32
34
  export function collectBackgroundTaskGoalActivity(
@@ -35,17 +37,17 @@ export function collectBackgroundTaskGoalActivity(
35
37
  now = Date.now(),
36
38
  durable: readonly DurableTaskProjection[] = [],
37
39
  ): GoalBackgroundProviderSnapshot {
40
+ const items = [
41
+ ...metas.filter((meta) => isVisibleGoalActivity(meta, ctx, now)).map(backgroundTaskToGoalItem),
42
+ ...durable.filter((task) => isVisibleDurableGoalActivity(task, ctx, now)).map(durableTaskToGoalItem),
43
+ ];
44
+ const deadlines = items.filter(item => item.terminal && typeof item.endedAt === "number")
45
+ .map(item => item.endedAt! + TERMINAL_GOAL_ACTIVITY_RETENTION_MS).filter(deadline => deadline > now);
38
46
  return {
39
47
  providerId: "background-tasks",
40
48
  label: "Background Tasks",
41
- items: [
42
- ...metas
43
- .filter((meta) => isVisibleGoalActivity(meta, ctx, now))
44
- .map(backgroundTaskToGoalItem),
45
- ...durable
46
- .filter((task) => isVisibleDurableGoalActivity(task, ctx, now))
47
- .map(durableTaskToGoalItem),
48
- ],
49
+ items,
50
+ nextDeadline: deadlines.length ? Math.min(...deadlines) : null,
49
51
  };
50
52
  }
51
53
 
@@ -55,19 +57,30 @@ export function registerBackgroundTasksGoalProvider(pi: ExtensionAPI): void {
55
57
  id: "background-tasks",
56
58
  label: "Background Tasks",
57
59
  scope: "session",
58
- getActivity: async (ctx: ExtensionContext) => {
59
- const snapshot = await backgroundObservation(pi, ctx);
60
+ activityVersion: 1,
61
+ getActivity: async (ctx: ExtensionContext, options?: { cachedOnly?: boolean }) => {
62
+ const snapshot = await backgroundGoalObservation(pi, ctx, options?.cachedOnly);
63
+ if (!snapshot && options?.cachedOnly) return { providerId: "background-tasks", coverage: "unverified", items: [], nextDeadline: null };
60
64
  if (snapshot.status !== "ready") throw new Error(snapshot.reason ?? "Background activity is unverified");
61
65
  const durable = snapshot.rows.filter((row: any) => row.meta.durable).map((row: any) => row.meta);
62
66
  const legacy = snapshot.rows.filter((row: any) => !row.meta.durable).map((row: any) => row.meta);
63
- return collectBackgroundTaskGoalActivity(legacy, ctx, Date.now(), durable);
67
+ const activity = collectBackgroundTaskGoalActivity(legacy, ctx, Date.now(), durable);
68
+ const deadlines = [activity.nextDeadline, snapshot.nextDeadline].filter((value): value is number => typeof value === "number" && value > Date.now());
69
+ return { ...activity, nextDeadline: deadlines.length ? Math.min(...deadlines) : null };
64
70
  },
65
71
  // A durable operation change must refresh Goal activity even though it
66
72
  // never writes a mutable legacy registry meta.
67
- onActivityChanged: (notify: () => void) => {
73
+ onActivityChanged: (notify: () => void, ctx?: ExtensionContext) => {
68
74
  const offRuntime = onBackgroundObservation(pi, notify);
69
- const offMeta = onMetaChanged(notify);
70
- const offDurable = getObservedWaitHost(pi)?.onDurableTaskChange(notify);
75
+ const offMeta = onMetaChanged(meta => {
76
+ if (ctx && meta && !belongsToGoalActivitySession(meta, ctx)) return;
77
+ notify();
78
+ });
79
+ const offDurable = getObservedWaitHost(pi)?.onDurableTaskChange(change => {
80
+ if (ctx && (change.workspace !== ctx.cwd || change.sessionId !== ctx.sessionManager.getSessionId())) return;
81
+ if (ctx && change.branchId && !ctx.sessionManager.getBranch().some(entry => entry.id === change.branchId)) return;
82
+ notify();
83
+ });
71
84
  return () => {
72
85
  offRuntime();
73
86
  offMeta();
@@ -100,6 +113,7 @@ function belongsToGoalActivitySession(meta: BackgroundTaskMeta, ctx: ExtensionCo
100
113
  const origin = meta.callbackOrigin;
101
114
  if (origin) {
102
115
  if (origin.cwd !== active.cwd) return false;
116
+ if (origin.branchId && !ctx.sessionManager.getBranch().some(entry => entry.id === origin.branchId)) return false;
103
117
  if (origin.sessionId || active.sessionId) return origin.sessionId === active.sessionId;
104
118
  return true;
105
119
  }
@@ -126,6 +140,7 @@ function isVisibleDurableGoalActivity(
126
140
  if (ctx) {
127
141
  const active = getGoalActivityOrigin(ctx);
128
142
  if (task.owner.workspace !== active.cwd) return false;
143
+ if (task.owner.branchId && !ctx.sessionManager.getBranch().some(entry => entry.id === task.owner.branchId)) return false;
129
144
  if (active.sessionId || task.owner.sessionId) {
130
145
  if (task.owner.sessionId !== active.sessionId) return false;
131
146
  }
package/src/index.ts CHANGED
@@ -1,8 +1,8 @@
1
+ import { shouldRestoreWorkObservation } from "./shared-work-client.mjs";
1
2
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
3
  import { initializeNavigatorPanels } from "./shared-navigator-panels.ts";
3
4
  import { registerBackgroundTasksGoalProvider } from "./goal-provider.js";
4
5
  import { createBackgroundTasksNavigator } from "./navigator-provider.js";
5
- import { createBackgroundTaskRuntime } from "./runtime.js";
6
6
  import { createManagedBackgroundFrontend } from "./managed-frontend.js";
7
7
  import { observeForegroundSandboxPolicy } from "./sandbox.js";
8
8
  import { registerTools } from "./tools.js";
@@ -11,10 +11,9 @@ import { closeBackgroundObservation } from "./work-observation.js";
11
11
 
12
12
  export default function backgroundTasksExtension(pi: ExtensionAPI): void {
13
13
  // The frontend owns native UI/delivery only. Mechanical tools run in the
14
- // fixed server service; this runtime supplies registration metadata only.
15
- const runtime = createBackgroundTaskRuntime();
14
+ // fixed server service. Register their native definitions before the first turn.
16
15
  const {host: observedWaits, proxy, ui} = createManagedBackgroundFrontend(pi);
17
- const navigator = createBackgroundTasksNavigator(runtime, ui);
16
+ const navigator = createBackgroundTasksNavigator(undefined, ui);
18
17
  initializeNavigatorPanels(pi);
19
18
  // Sections on a host that renders them; text only where it renders none.
20
19
  // Returning a prompt on modern pi would set forceSystemPrompt, and the request
@@ -27,7 +26,6 @@ export default function backgroundTasksExtension(pi: ExtensionAPI): void {
27
26
  observeForegroundSandboxPolicy(pi);
28
27
  // Registered before registerTools(pi), so this runs before running tasks are resumed.
29
28
  pi.on("session_start", async (_event, ctx) => {
30
- runtime.resumeScheduledWork();
31
29
  registerBackgroundTasksGoalProvider(pi);
32
30
  navigator.ensureBackgroundTasksNavigator(ctx);
33
31
  });
@@ -40,14 +38,13 @@ export default function backgroundTasksExtension(pi: ExtensionAPI): void {
40
38
  closeBackgroundObservation(pi);
41
39
  // /reload, session replacement, and quit load a fresh instance; stop this one's timers (#324).
42
40
  observedWaits.close();
43
- runtime.suspendScheduledWork();
44
41
  navigator.clearBackgroundTasksNavigatorSession();
45
42
  });
46
- registerTools(proxy, runtime, navigator.refreshBackgroundTasksNavigator, {resumeLocal:false});
43
+ registerTools(proxy, undefined, navigator.refreshBackgroundTasksNavigator, {resumeLocal:false});
47
44
  // Registered after registerTools so the callback batcher has its session
48
45
  // context before a reconciled delivery can enqueue a parent notification.
49
- pi.on("session_start", async (_event, ctx) => {
50
- observedWaits.start(ctx);
46
+ pi.on("session_start", (event, ctx) => {
47
+ observedWaits.start(ctx, shouldRestoreWorkObservation(event, ctx.sessionManager));
51
48
  });
52
49
  // A fork or branch navigation does not restart the session, but it changes
53
50
  // which continuation may receive a queued callback. Update the host snapshot
@@ -1,7 +1,7 @@
1
1
  import { createHash, timingSafeEqual } from 'node:crypto';
2
2
  import { lstatSync, readFileSync, realpathSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
- import { readProcessStartTokenFresh } from './process-identity.js';
4
+ import { readAdmissionStartToken, readProcessStartTokenFresh } from './process-identity.js';
5
5
  const ordered = (value: any): any => value === null || typeof value !== 'object' ? value : Array.isArray(value) ? value.map(ordered) : Object.fromEntries(Object.keys(value).sort().map(key => [key, ordered(value[key])]));
6
6
  export const backgroundDigest = (value: unknown) => createHash('sha256').update(JSON.stringify(ordered(value))).digest('hex');
7
7
  export function readBackgroundAuthority(root: string, instance: string, authority: any, requireLive = true): any {
@@ -13,14 +13,16 @@ export function readBackgroundAuthority(root: string, instance: string, authorit
13
13
  || !stat.isFile() || stat.isSymbolicLink() || stat.uid !== dir.uid || (stat.mode & 0o077) || stat.size > 1024 * 1024)
14
14
  throw new Error('background-authority-refused');
15
15
  const record = JSON.parse(readFileSync(path, 'utf8')), digest = createHash('sha256').update(authority.secret).digest('hex');
16
- if (record.version !== 1 || record.instanceId !== instance || record.id !== authority.id || typeof record.secretHash !== 'string'
16
+ if ((record.version !== 1 && record.version !== 2) || record.instanceId !== instance || record.id !== authority.id || typeof record.secretHash !== 'string'
17
17
  || record.secretHash.length !== digest.length || !timingSafeEqual(Buffer.from(record.secretHash), Buffer.from(digest))
18
18
  || typeof record.key !== 'string' || !record.key || typeof record.tool !== 'string' || !record.owner?.sessionId
19
19
  || record.owner.workspace !== realpathSync(record.owner.workspace) || !Number.isSafeInteger(record.pid) || !record.start
20
20
  || !Array.isArray(record.branchIds) || record.branchIds.some((id: unknown) => typeof id !== 'string'))
21
21
  throw new Error('background-authority-refused');
22
22
  if (requireLive) {
23
- if (readProcessStartTokenFresh(record.pid) !== record.start)
23
+ const start = record.version === 2 ? readAdmissionStartToken(record.pid) : readProcessStartTokenFresh(record.pid);
24
+ if (!start) throw new Error('background-authority-refused: cannot verify host start time');
25
+ if (start !== record.start)
24
26
  throw new Error('background-authority-refused: host identity changed');
25
27
  process.kill(record.pid, 0);
26
28
  }
@@ -3,25 +3,36 @@ import { lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, w
3
3
  import { join } from 'node:path';
4
4
  import { getAgentDir, type ExtensionAPI, type ExtensionContext } from '@earendil-works/pi-coding-agent';
5
5
  import { backgroundDigest } from './managed-authority.js';
6
- import { readProcessStartTokenFresh } from './process-identity.js';
6
+ import { readAdmissionStartToken, readProcessStartTokenFresh } from './process-identity.js';
7
7
  import { currentForegroundSandboxPolicy, FOREGROUND_SANDBOX_POLICY_CHANNEL } from './sandbox.js';
8
- import { backgroundObservation } from './work-observation.js';
8
+ import { backgroundListNeedsHistory, backgroundObservation } from './work-observation.js';
9
9
  /** Native host proof carries scope and captured policy, never a transcript or module path. */
10
10
  export async function requestBackgroundTool(pi: ExtensionAPI, ctx: ExtensionContext, key: string, tool: string, params: unknown, parameters?: unknown, signal?: AbortSignal): Promise<any> {
11
11
  if (signal?.aborted)
12
12
  throw new Error('Background request cancelled before admission');
13
- await backgroundObservation(pi, ctx);
13
+ const input = params && typeof params === 'object' ? params as Record<string, unknown> : {};
14
+ const list = tool === 'bg_task_list' || (tool === 'bg_task' && input.action === 'list');
15
+ if (list && backgroundListNeedsHistory(input)) {
16
+ // The root history index is shared. Wait on its read plane before acquiring
17
+ // a grant or entering the serialized tool queue, even for an all-session list.
18
+ const snapshot = await backgroundObservation(pi, ctx, true, false, { limit: 1 }, { timeoutMs: 60000, signal });
19
+ if (snapshot.status !== 'ready')
20
+ throw new Error(snapshot.reason ?? `Background history is ${snapshot.status}`);
21
+ } else {
22
+ await backgroundObservation(pi, ctx);
23
+ }
24
+ signal?.throwIfAborted();
14
25
  const root = realpathSync(getAgentDir()), registration = JSON.parse(readFileSync(join(root, 'server-registration-v1.json'), 'utf8'));
15
26
  if (registration.version !== 1 || registration.agentDir !== root)
16
27
  throw new Error('Invalid runtime registration');
17
28
  const module = new URL('./shared-work-client.mjs', import.meta.url).href;
18
- const { WorkClient } = await import(module);
29
+ const { connectWorkClient } = await import(module);
19
30
  const directory = join(root, 'background-tool-admission');
20
31
  mkdirSync(directory, { recursive: true, mode: 0o700 });
21
32
  const stat = lstatSync(directory);
22
33
  if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid?.() || (stat.mode & 0o077))
23
34
  throw new Error('Unsafe Background admission directory');
24
- const client = new WorkClient(join(registration.serverDir, 'pi-server.sock'), root, ['runtime-background-execution-v1']);
35
+ const client = await connectWorkClient(join(registration.serverDir, 'pi-server.sock'), root, ['runtime-background-execution-v1'], { signal });
25
36
  const id = randomUUID(), secret = randomBytes(32).toString('hex'), path = join(directory, `${id}.json`);
26
37
  let off: unknown;
27
38
  const abort = () => client.close();
@@ -33,9 +44,11 @@ export async function requestBackgroundTool(pi: ExtensionAPI, ctx: ExtensionCont
33
44
  const sessionId = ctx.sessionManager.getSessionId();
34
45
  if (!sessionId)
35
46
  throw new Error('Background tools require a native session identity');
36
- const record = { version: 1, id, secretHash: createHash('sha256').update(secret).digest('hex'), instanceId: hello.instanceId,
47
+ const version = hello.capabilities?.includes("runtime-background-admission-v2") ? 2 : 1;
48
+ const start = version === 2 ? readAdmissionStartToken(process.pid) : readProcessStartTokenFresh(process.pid);
49
+ const record = { version, id, secretHash: createHash('sha256').update(secret).digest('hex'), instanceId: hello.instanceId,
37
50
  owner: { kind: 'parent-session', sessionId, workspace: realpathSync(ctx.cwd) }, branchIds, projectTrusted: ctx.isProjectTrusted(),
38
- pid: process.pid, start: readProcessStartTokenFresh(process.pid), key, tool, params, parametersDigest: parameters === undefined ? undefined : backgroundDigest(parameters), policy };
51
+ pid: process.pid, start, key, tool, params, parametersDigest: parameters === undefined ? undefined : backgroundDigest(parameters), policy };
39
52
  const staged = `${path}.tmp`;
40
53
  writeFileSync(staged, JSON.stringify(record), { flag: 'wx', mode: 0o600 });
41
54
  renameSync(staged, path);