pi-better-background-tasks 0.18.0 → 0.20.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 (63) hide show
  1. package/README.md +25 -13
  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/root.mjs +5 -2
  13. package/runtime-client/src/runtime/work-client.mjs +150 -7
  14. package/src/adapter-contract.ts +1 -1
  15. package/src/goal-provider.ts +31 -16
  16. package/src/index.ts +25 -9
  17. package/src/managed-authority.ts +5 -3
  18. package/src/managed-client.ts +20 -7
  19. package/src/managed-frontend.ts +135 -19
  20. package/src/navigator-provider.ts +19 -5
  21. package/src/observed-wait-client.ts +10 -0
  22. package/src/observed-waits.ts +321 -53
  23. package/src/process-identity.ts +18 -2
  24. package/src/process.ts +48 -14
  25. package/src/registry.ts +53 -5
  26. package/src/review-settings.ts +18 -0
  27. package/src/runtime.ts +27 -82
  28. package/src/sandbox.ts +14 -11
  29. package/src/shared-callback-batcher.ts +11 -2
  30. package/src/shared-navigator-panels.ts +26 -4
  31. package/src/shared-navigator.ts +244 -40
  32. package/src/shared-operation-coordinator/assignment-observation.mjs +43 -35
  33. package/src/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  34. package/src/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
  35. package/src/shared-operation-coordinator/src/background-requests.ts +14 -3
  36. package/src/shared-operation-coordinator/src/discovery.ts +5 -3
  37. package/src/shared-operation-coordinator/src/operations.ts +50 -2
  38. package/src/shared-operation-coordinator/src/outbox.ts +9 -0
  39. package/src/shared-operation-coordinator/src/result-supervision.ts +12 -0
  40. package/src/shared-operation-coordinator/src/rows.ts +2 -0
  41. package/src/shared-operation-coordinator/src/schema.ts +40 -24
  42. package/src/shared-operation-coordinator/src/store.ts +40 -8
  43. package/src/shared-operation-coordinator/src/subagent-launch.ts +24 -1
  44. package/src/shared-operation-coordinator/src/types.ts +5 -1
  45. package/src/shared-sandbox-core.ts +1 -1
  46. package/src/shared-work-client.mjs +150 -7
  47. package/src/stall.ts +7 -4
  48. package/src/supervised-progress.ts +43 -0
  49. package/src/supervisor/README.md +1 -4
  50. package/src/supervisor/emit-runner.mjs +1 -0
  51. package/src/supervisor/generated/process-identity.mjs +20 -2
  52. package/src/supervisor/generated/process.mjs +52 -14
  53. package/src/supervisor/generated/runner.mjs +47 -4
  54. package/src/supervisor/generated/store.mjs +3 -3
  55. package/src/supervisor/generated/watch-fingerprint.mjs +69 -0
  56. package/src/supervisor/runner.ts +38 -3
  57. package/src/supervisor/store.ts +3 -3
  58. package/src/supervisor/supervisor.ts +6 -3
  59. package/src/task-diagnostics.ts +1 -1
  60. package/src/tools.ts +67 -54
  61. package/src/types.ts +7 -3
  62. package/src/watch-fingerprint.ts +70 -0
  63. package/src/work-observation.ts +46 -19
package/README.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  `pi-better-background-tasks` is a Pi extension for durable background shell tasks, watchers, logs, and status inspection.
4
4
 
5
+ For the decisions governing execution, progress, waits, and notifications, see the [Background task policy (ADR 0028)](https://github.com/1aboveio/pi-better-harness/blob/main/docs/adr/0028-background-task-policy.md).
6
+
5
7
  ## Quick Answer
6
8
 
7
9
  Use `pi-better-background-tasks` when a command should keep running while the foreground Pi session stays free. It is best for dev servers, long scripts, queue watchers, deploy checks, log tails, and other command-driven work.
@@ -110,10 +112,10 @@ timeouts, and v1 non-goals.
110
112
 
111
113
  ## Reloads and session switches
112
114
 
113
- Tasks belong to the Pi session that started them. After `/reload`, the same
114
- session picks every task back up: watches keep polling, remote tmux output keeps
115
- being collected, and a task that finished during the reload (or exits later) gets
116
- its completion callback exactly once.
115
+ SSH and legacy tasks belong to the Pi session that started them. After `/reload`,
116
+ that session resumes polling watches and collecting remote tmux output. The
117
+ runtime checks delivery receipts and recovers pending callbacks. For supervised
118
+ local tasks (`bgs_`), see [Observed operations and waits](#observed-operations-and-waits).
117
119
 
118
120
  After `/new`, `/resume`, fork, or switching to another session, the previous
119
121
  session's tasks keep running but are paused from Pi's side: watches do not poll,
@@ -127,9 +129,16 @@ new Pi process, a task whose process is gone is marked lost.
127
129
 
128
130
  ## Progress And Suspected Stalls
129
131
 
132
+ Supervised local tasks (`bgs_`) can notify their owning session while a wait
133
+ is pending. The alert includes available output and the state of the other wait
134
+ dependencies. The wait delivers its completion once all dependencies finish.
135
+ The server recovers a pending alert on the owning branch after a reconnect and
136
+ checks the runner for fresh progress before delivery. [Background task policy](../../docs/adr/0028-background-task-policy.md)
137
+
130
138
  A task can remain `running` without recent progress evidence. Compact status and
131
- navigator use the same observation. Process tasks use recorded progress and the
132
- log's modification time. A watch advances only when a poll observes a changed
139
+ navigator use the same observation. Supervised processes record the time of new output, including bytes beyond the
140
+ log retention limit. SSH and legacy processes use recorded progress and the log's
141
+ modification time. A watch advances only when a poll observes a changed
133
142
  outcome: running a poll, appending its result to the watch log, or polling on
134
143
  schedule is activity, not progress. Before any progress, the task's launch time
135
144
  anchors the silence duration. This does not measure CPU activity, network waits,
@@ -163,9 +172,11 @@ records an observation, not a process failure. After the existing 60-second
163
172
  attention grace, callback-enabled tasks wake the parent once per silent spell.
164
173
  New progress closes the observation and a later spell can notify again. Quiet
165
174
  work does not alert, `callback:false` suppresses notification, and no silence
166
- threshold stops a task or changes its lifecycle. The active session's runtime
167
- checks observations once per second, including an in-flight watch poll. Reload
168
- restores monitoring and the persisted attention receipts. Log-retention writes
175
+ threshold stops a task or changes its lifecycle. For supervised tasks the server
176
+ schedules the next silence threshold, including during an in-flight watch poll.
177
+ A supervised watch launched by an older runner lacks the progress checkpoint
178
+ needed to classify silence. Its next launch uses the new runner. Reload restores
179
+ monitoring and persisted delivery receipts. Log-retention writes
169
180
  are excluded from task progress.
170
181
 
171
182
  ## Launch Policy And Diagnostics
@@ -185,9 +196,10 @@ missing profile files or current process-tool denials are not confinement proof.
185
196
  Remote execution also reports unknown remote confinement.
186
197
 
187
198
  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
199
+ action) for a bounded, current process snapshot. An enabled Background tasks
200
+ profile must permit **Process access: Read**. A disabled profile's retained
201
+ setting does not deny access. The adapter is unavailable under Main confinement.
202
+ The result checks the recorded PID and start identity, then reports process
191
203
  state, accumulated CPU time, and available wait evidence. It never reads command
192
204
  arguments or environment values and never probes a remote host or descendants.
193
205
  A snapshot cannot establish useful work or a hang. Watch poll PIDs are not
@@ -334,7 +346,7 @@ leader exits before cleanup can be verified. Descendants may remain running;
334
346
  inspect that evidence before interpreting the result.
335
347
 
336
348
  Call `wait_for_operations` with `task_ids` and an optional `continuation_note` to
337
- register an all-settled wait. The parent remains responsive. A notification means
349
+ register an all-settled wait. The parent remains responsive. A wait completion notification means
338
350
  every dependency is terminal, including failed, cancelled, timed-out or lost
339
351
  operations; it does not mean the command succeeded.
340
352
 
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.20.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":"5bd2e8ad130e4ee494caf40bb7129c5c9c1f787d486de66304ec9a7fa5fcb45e","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-arm64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.7.0","contentId":"be4b4f5c05d403d84c98a0e34f407fbf65fb8f90e4e9d07930404c8f408665eb"},"sha256":"701e694c1047bcb5ef4652c6a05cfbee0798eb90a4a1e57574118c0b3df59d18"}
@@ -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":"5bd2e8ad130e4ee494caf40bb7129c5c9c1f787d486de66304ec9a7fa5fcb45e","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-x64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.7.0","contentId":"3db710d017c57fdc43d18531bcd3144de15767b9021223fcc262d39107db55f6"},"sha256":"4f88a4c1bf931f4af0805f227f5d473336f796f74cacad45020bad79e3962232"}
@@ -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":"5bd2e8ad130e4ee494caf40bb7129c5c9c1f787d486de66304ec9a7fa5fcb45e","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-arm64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.7.0","contentId":"93a5ca8f14a1667ff653465e5844577f34c3f48c79b1ac87daea77f52eba65e3"},"sha256":"24938d0af26379b8b068e09e1e92d3a4c87d88ea04894a676100a4ed19d90649"}
@@ -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":"5bd2e8ad130e4ee494caf40bb7129c5c9c1f787d486de66304ec9a7fa5fcb45e","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-x64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.7.0","contentId":"71973a617087e76c008eb1eb0b6e50d4ec51f2e6617af432828dba6bdf4baaa1"},"sha256":"b5f918fde231b83e9351dc194ec10bd60f5d8641c452c4925f0bbbffa5eeebd9"}
@@ -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,6 +1,7 @@
1
1
  import { linkSync, mkdirSync, readFileSync, realpathSync, unlinkSync, writeFileSync } from "node:fs";
2
2
  import { join, resolve } from "node:path";
3
3
  import { randomUUID } from "node:crypto";
4
+ import { socketPathFor } from "./socket.mjs";
4
5
  /** Transport selection is durable and independent of installation or package version. */
5
6
  export function runtimeRoot(agentDir, requestedServerDir) {
6
7
  mkdirSync(agentDir, { recursive: true, mode: 0o700 });
@@ -21,9 +22,11 @@ export function runtimeRoot(agentDir, requestedServerDir) {
21
22
  if (error.code !== "ENOENT")
22
23
  throw error;
23
24
  }
24
- const temporary = `${path}.${randomUUID()}`;
25
25
  mkdirSync(requestedServerDir, { recursive: true, mode: 0o700 });
26
- const proposed = { version: 1, agentDir, serverDir: realpathSync(requestedServerDir) };
26
+ const serverDir = realpathSync(requestedServerDir);
27
+ socketPathFor(serverDir);
28
+ const proposed = { version: 1, agentDir, serverDir };
29
+ const temporary = `${path}.${randomUUID()}`;
27
30
  writeFileSync(temporary, JSON.stringify(proposed), { mode: 0o600, flag: "wx" });
28
31
  try {
29
32
  try {
@@ -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,21 +1,35 @@
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";
9
9
  import { deliverBackgroundTasksPrompt } from "./prompt.js";
10
10
  import { closeBackgroundObservation } from "./work-observation.js";
11
+ import { readBackgroundReviewInterval, saveBackgroundReviewInterval } from "./review-settings.js";
11
12
 
12
13
  export default function backgroundTasksExtension(pi: ExtensionAPI): void {
13
14
  // 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();
15
+ // fixed server service. Register their native definitions before the first turn.
16
16
  const {host: observedWaits, proxy, ui} = createManagedBackgroundFrontend(pi);
17
- const navigator = createBackgroundTasksNavigator(runtime, ui);
17
+ const navigator = createBackgroundTasksNavigator(undefined, ui);
18
18
  initializeNavigatorPanels(pi);
19
+ const intervalLabel = (minutes: number) => `${minutes} minute${minutes === 1 ? "" : "s"}`;
20
+ const reviewSetting = {
21
+ id: "background-review-interval",
22
+ label: "Background wait review interval",
23
+ values: [1, 5, 10, 15, 30, 60].map(intervalLabel),
24
+ get: () => intervalLabel(readBackgroundReviewInterval()),
25
+ change(value: string) {
26
+ saveBackgroundReviewInterval(Number.parseInt(value, 10));
27
+ void observedWaits.reconcileNow().catch(() => undefined);
28
+ },
29
+ };
30
+ const registerReviewSetting = () => pi.events.emit("harness-settings:register", reviewSetting);
31
+ let stopReviewSettings: (() => void) | undefined = pi.events.on("harness-settings:request", registerReviewSetting);
32
+ registerReviewSetting();
19
33
  // Sections on a host that renders them; text only where it renders none.
20
34
  // Returning a prompt on modern pi would set forceSystemPrompt, and the request
21
35
  // would then carry a snapshot, so sections published after it never arrive.
@@ -27,7 +41,8 @@ export default function backgroundTasksExtension(pi: ExtensionAPI): void {
27
41
  observeForegroundSandboxPolicy(pi);
28
42
  // Registered before registerTools(pi), so this runs before running tasks are resumed.
29
43
  pi.on("session_start", async (_event, ctx) => {
30
- runtime.resumeScheduledWork();
44
+ stopReviewSettings ??= pi.events.on("harness-settings:request", registerReviewSetting);
45
+ registerReviewSetting();
31
46
  registerBackgroundTasksGoalProvider(pi);
32
47
  navigator.ensureBackgroundTasksNavigator(ctx);
33
48
  });
@@ -37,17 +52,18 @@ export default function backgroundTasksExtension(pi: ExtensionAPI): void {
37
52
  navigator.clearBackgroundTasksNavigatorSession();
38
53
  });
39
54
  pi.on("session_shutdown", async (_event, ctx) => {
55
+ stopReviewSettings?.();
56
+ stopReviewSettings = undefined;
40
57
  closeBackgroundObservation(pi);
41
58
  // /reload, session replacement, and quit load a fresh instance; stop this one's timers (#324).
42
59
  observedWaits.close();
43
- runtime.suspendScheduledWork();
44
60
  navigator.clearBackgroundTasksNavigatorSession();
45
61
  });
46
- registerTools(proxy, runtime, navigator.refreshBackgroundTasksNavigator, {resumeLocal:false});
62
+ registerTools(proxy, undefined, navigator.refreshBackgroundTasksNavigator, {resumeLocal:false});
47
63
  // Registered after registerTools so the callback batcher has its session
48
64
  // context before a reconciled delivery can enqueue a parent notification.
49
- pi.on("session_start", async (_event, ctx) => {
50
- observedWaits.start(ctx);
65
+ pi.on("session_start", (event, ctx) => {
66
+ observedWaits.start(ctx, shouldRestoreWorkObservation(event, ctx.sessionManager));
51
67
  });
52
68
  // A fork or branch navigation does not restart the session, but it changes
53
69
  // 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
  }