pi-better-harness 0.46.1 → 0.48.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 (94) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/extensions/shared-harness-settings.ts +4 -2
  3. package/node_modules/pi-better-background-tasks/README.md +9 -0
  4. package/node_modules/pi-better-background-tasks/package.json +2 -1
  5. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-arm64.gz +0 -0
  6. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-arm64.json +1 -1
  7. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-x64.gz +0 -0
  8. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-x64.json +1 -1
  9. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-arm64.gz +0 -0
  10. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-arm64.json +1 -1
  11. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-x64.gz +0 -0
  12. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-x64.json +1 -1
  13. package/node_modules/pi-better-background-tasks/runtime-client/src/daemon-owner.mjs +51 -4
  14. package/node_modules/pi-better-background-tasks/runtime-client/src/runtime/client.mjs +1 -0
  15. package/node_modules/pi-better-background-tasks/runtime-client/src/runtime/work-client.mjs +102 -0
  16. package/node_modules/pi-better-background-tasks/src/goal-provider.ts +11 -7
  17. package/node_modules/pi-better-background-tasks/src/index.ts +4 -0
  18. package/node_modules/pi-better-background-tasks/src/observed-waits.ts +255 -37
  19. package/node_modules/pi-better-background-tasks/src/output.ts +16 -13
  20. package/node_modules/pi-better-background-tasks/src/registry.ts +15 -0
  21. package/node_modules/pi-better-background-tasks/src/shared-harness-settings.ts +4 -2
  22. package/node_modules/pi-better-background-tasks/src/shared-log-utils.ts +18 -7
  23. package/node_modules/pi-better-background-tasks/src/shared-navigator.ts +12 -1
  24. package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/assignment-observation.mjs +80 -3
  25. package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/index.ts +2 -0
  26. package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/src/discovery.ts +9 -0
  27. package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/src/errors.ts +2 -0
  28. package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/src/operations.ts +6 -4
  29. package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/src/result-supervision.ts +128 -0
  30. package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/src/schema.ts +39 -1
  31. package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/src/store.ts +55 -0
  32. package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/src/task-cancellation.ts +224 -0
  33. package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/src/types.ts +6 -0
  34. package/node_modules/pi-better-background-tasks/src/shared-work-client.mjs +102 -0
  35. package/node_modules/pi-better-background-tasks/src/tools.ts +87 -59
  36. package/node_modules/pi-better-background-tasks/src/work-observation.ts +117 -0
  37. package/node_modules/pi-better-goal/package.json +1 -1
  38. package/node_modules/pi-better-goal/src/index.ts +10 -1
  39. package/node_modules/pi-better-goal/src/shared-assignment-observation.mjs +80 -3
  40. package/node_modules/pi-better-goal/src/shared-assignment-projection.mjs +12 -4
  41. package/node_modules/pi-better-goal/src/shared-harness-settings.ts +4 -2
  42. package/node_modules/pi-better-goal/src/workflow-gates.ts +77 -11
  43. package/node_modules/pi-better-sandbox/package.json +1 -1
  44. package/node_modules/pi-better-sandbox/shared-harness-settings.ts +4 -2
  45. package/node_modules/pi-better-subagents/agent-catalog.mjs +24 -0
  46. package/node_modules/pi-better-subagents/agent-commands.ts +71 -4
  47. package/node_modules/pi-better-subagents/agent-inspection.ts +2 -1
  48. package/node_modules/pi-better-subagents/agents-catalog-tool.ts +8 -1
  49. package/node_modules/pi-better-subagents/assignment-projection.mjs +12 -4
  50. package/node_modules/pi-better-subagents/catalog-host-admission.ts +69 -0
  51. package/node_modules/pi-better-subagents/catalog-overlay.ts +10 -0
  52. package/node_modules/pi-better-subagents/catalog-runtime.ts +10 -2
  53. package/node_modules/pi-better-subagents/catalog-store.ts +23 -0
  54. package/node_modules/pi-better-subagents/catalog-ui.ts +26 -10
  55. package/node_modules/pi-better-subagents/docs/agent-catalog-operations.md +38 -0
  56. package/node_modules/pi-better-subagents/health-observation.ts +9 -4
  57. package/node_modules/pi-better-subagents/index.ts +61 -68
  58. package/node_modules/pi-better-subagents/launch-abort.ts +21 -0
  59. package/node_modules/pi-better-subagents/list.mjs +1 -1
  60. package/node_modules/pi-better-subagents/output-payload.ts +2 -0
  61. package/node_modules/pi-better-subagents/package.json +1 -1
  62. package/node_modules/pi-better-subagents/parse.ts +7 -6
  63. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-arm64.gz +0 -0
  64. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-arm64.json +1 -1
  65. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-x64.gz +0 -0
  66. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-x64.json +1 -1
  67. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-arm64.gz +0 -0
  68. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-arm64.json +1 -1
  69. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-x64.gz +0 -0
  70. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-x64.json +1 -1
  71. package/node_modules/pi-better-subagents/runtime-client/src/daemon-owner.mjs +51 -4
  72. package/node_modules/pi-better-subagents/runtime-client/src/runtime/client.mjs +1 -0
  73. package/node_modules/pi-better-subagents/runtime-client/src/runtime/work-client.mjs +102 -0
  74. package/node_modules/pi-better-subagents/session-store.ts +27 -14
  75. package/node_modules/pi-better-subagents/shared-catalog.ts +69 -0
  76. package/node_modules/pi-better-subagents/shared-harness-settings.ts +4 -2
  77. package/node_modules/pi-better-subagents/shared-log-utils.ts +18 -7
  78. package/node_modules/pi-better-subagents/shared-navigator.ts +12 -1
  79. package/node_modules/pi-better-subagents/shared-operation-coordinator/assignment-observation.mjs +80 -3
  80. package/node_modules/pi-better-subagents/shared-operation-coordinator/index.ts +2 -0
  81. package/node_modules/pi-better-subagents/shared-operation-coordinator/src/discovery.ts +9 -0
  82. package/node_modules/pi-better-subagents/shared-operation-coordinator/src/errors.ts +2 -0
  83. package/node_modules/pi-better-subagents/shared-operation-coordinator/src/operations.ts +6 -4
  84. package/node_modules/pi-better-subagents/shared-operation-coordinator/src/result-supervision.ts +128 -0
  85. package/node_modules/pi-better-subagents/shared-operation-coordinator/src/schema.ts +39 -1
  86. package/node_modules/pi-better-subagents/shared-operation-coordinator/src/store.ts +55 -0
  87. package/node_modules/pi-better-subagents/shared-operation-coordinator/src/task-cancellation.ts +224 -0
  88. package/node_modules/pi-better-subagents/shared-operation-coordinator/src/types.ts +6 -0
  89. package/node_modules/pi-better-subagents/shared-work-client.d.mts +12 -0
  90. package/node_modules/pi-better-subagents/shared-work-client.mjs +102 -0
  91. package/node_modules/pi-better-subagents/skill-picker.ts +6 -2
  92. package/node_modules/pi-better-subagents/tools.ts +39 -2
  93. package/node_modules/pi-better-subagents/work-observation.ts +177 -0
  94. package/package.json +5 -5
package/CHANGELOG.md CHANGED
@@ -1,5 +1,30 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.48.0] - 2026-11-16
4
+
5
+ ### Added
6
+
7
+ - Bundle shared Catalog management and durable Background result supervision from the unified runtime. (#751, #789)
8
+
9
+ ### Fixed
10
+
11
+ - Keep exact-ID reads responsive during large initial inventories and recover failed read workers with a bounded restart budget and a fresh observation epoch.
12
+ - Reuse unpublished parsing work after source changes, observe coordinator writes through a coherent read snapshot, and avoid scheduling another inventory solely because the current scan is slow.
13
+ - Bundle Server 0.4.0, Subagents 0.34.0, Background Tasks 0.17.0 and Goal 0.14.2.
14
+
15
+ ## [0.47.0] - 2026-11-16
16
+
17
+ ### Added
18
+
19
+ - Bundle shared runtime observations for Subagents and Background Tasks, including revisioned history reads, current-scope activity and owner-checked task cancellation. (#771, #772, #773, #774)
20
+
21
+ ### Fixed
22
+
23
+ - Bundle Goal 0.14.1 so overlapping workflow admission requests share one pending scheduler check instead of launching one process per candidate. State changes invalidate admission evidence; later requests obtain a fresh check. (#785, #786)
24
+ - Include bounded Navigator refreshes and settings writes that tolerate brief contention between independent processes.
25
+ - Keep shared runtime status responsive while large history indexes rebuild, without forcing another inventory or terminating the read worker.
26
+ - Bundle Background Tasks 0.16.0, Subagents 0.33.0 and Sandbox 0.14.2.
27
+
3
28
  ## [0.46.1] - 2026-11-15
4
29
 
5
30
  ### Fixed
@@ -34,10 +34,12 @@ function section(settings: Record<string, unknown>): Record<string, unknown> {
34
34
  }
35
35
 
36
36
  function acquire(path: string): () => void {
37
- for (let attempt = 0; attempt < 10; attempt++) {
37
+ // A live writer can be briefly descheduled; allow contention without stealing its lock.
38
+ const maxAttempts = 100;
39
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
38
40
  try { return lockfile.lockSync(path, { realpath: false }); }
39
41
  catch (error) {
40
- if ((error as NodeJS.ErrnoException).code !== "ELOCKED" || attempt === 9) throw error;
42
+ if ((error as NodeJS.ErrnoException).code !== "ELOCKED" || attempt === maxAttempts - 1) throw error;
41
43
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);
42
44
  }
43
45
  }
@@ -320,6 +320,15 @@ keeps observing after the worker or Pi process exits. Status and logs recover
320
320
  from durable evidence; an ambiguous launch becomes `lost` and is not relaunched.
321
321
  SSH tasks and older `bg_` identifiers use the existing runtime.
322
322
 
323
+ The canonical local server owns result supervision for newly admitted local
324
+ tasks. Closing every frontend leaves the independent runner running. The server
325
+ imports matching terminal evidence, advances already-authorized waits, and keeps
326
+ notifications for their recorded recipients. Hosted sessions use the same root
327
+ supervisor rather than starting another discovery loop. A live or unverified
328
+ legacy owner blocks handoff; missing permission authority or execution evidence
329
+ is reported without starting a replacement command. This transfer does not
330
+ authorize a continuation, consume evidence, or start a parent model turn.
331
+
323
332
  Stop and timeout evidence can contain `groupCleanup=unproven` when the command's
324
333
  leader exits before cleanup can be verified. Descendants may remain running;
325
334
  inspect that evidence before interpreting the result.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-background-tasks",
3
- "version": "0.15.4",
3
+ "version": "0.17.0",
4
4
  "description": "Pi extension for durable background shell tasks, watchers, logs, and status inspection.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -47,6 +47,7 @@
47
47
  "runtime-client/**",
48
48
  "src/**/*.ts",
49
49
  "src/shared-operation-coordinator/assignment-observation.mjs",
50
+ "src/shared-work-client.mjs",
50
51
  "src/supervisor/**/*.mjs",
51
52
  "src/supervisor/**/*.js",
52
53
  "!src/**/*.test.ts",
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"4a2331d2ad22ef8c0dcab3df637dbb4ceed9652100bb0e9890bcc40297b33fc9","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-arm64","dependencyLockDigest":"c63ff3a60c411a06ad881d6ae81fbe88402cc1ff3a3447bf54765b090b2c77bb","protocolVersion":1,"serverVersion":"0.2.4","contentId":"229e6dffc9b3028cd9b2e852e01908c95e3c2bf6ca9bb9f38e71ce5930c545b5"},"sha256":"bf389c30f0de82c93dc57987115da4fc9d8f51f5131f6cc39cbcff2fe025f35a"}
1
+ {"build":{"format":1,"sourceDigest":"f1a415e52552342511151e078257a3d81660989f30a684a263fb8f6252ac9e63","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-arm64","dependencyLockDigest":"c63ff3a60c411a06ad881d6ae81fbe88402cc1ff3a3447bf54765b090b2c77bb","protocolVersion":1,"serverVersion":"0.4.0","contentId":"d8babdaa88ccdf11463b69738823e4175a88cb25e1f6b51bd1cde1dc5ebbd6b3"},"sha256":"40cbb55c9f6bcba62ac2fde5d00521d44c627177baede403fdfa9ee53ccec6ce"}
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"4a2331d2ad22ef8c0dcab3df637dbb4ceed9652100bb0e9890bcc40297b33fc9","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-x64","dependencyLockDigest":"c63ff3a60c411a06ad881d6ae81fbe88402cc1ff3a3447bf54765b090b2c77bb","protocolVersion":1,"serverVersion":"0.2.4","contentId":"2ead9dfdf963382452c14e99e806df94869b1cc556ed8270ed8c398cb9984ad6"},"sha256":"fff673607c28a3191299b38558b03b0dfab4593892f569daf959fa4d8733442f"}
1
+ {"build":{"format":1,"sourceDigest":"f1a415e52552342511151e078257a3d81660989f30a684a263fb8f6252ac9e63","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-x64","dependencyLockDigest":"c63ff3a60c411a06ad881d6ae81fbe88402cc1ff3a3447bf54765b090b2c77bb","protocolVersion":1,"serverVersion":"0.4.0","contentId":"0c892582dfd3e78b9f5fc25821dfd6b7c233f7f8b6d31677196dc3aaeda0a909"},"sha256":"61e469f213ae5ef7e379897f03f069b4a8c668a3a338f7fee7cafffeb7c648f3"}
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"4a2331d2ad22ef8c0dcab3df637dbb4ceed9652100bb0e9890bcc40297b33fc9","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-arm64","dependencyLockDigest":"c63ff3a60c411a06ad881d6ae81fbe88402cc1ff3a3447bf54765b090b2c77bb","protocolVersion":1,"serverVersion":"0.2.4","contentId":"a5cc13f3b6d41aa4feb36b52f04988435fa4440078947a1043095a08ca7ff205"},"sha256":"db62852b6e38a406fee2f0b284b7d9fc6e51af875a2cbe51f409b301ed6e9b8e"}
1
+ {"build":{"format":1,"sourceDigest":"f1a415e52552342511151e078257a3d81660989f30a684a263fb8f6252ac9e63","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-arm64","dependencyLockDigest":"c63ff3a60c411a06ad881d6ae81fbe88402cc1ff3a3447bf54765b090b2c77bb","protocolVersion":1,"serverVersion":"0.4.0","contentId":"d71fc0b69c23b6808726d5a971c3ddd1da00985dfb655c79190b83c3997fcb1f"},"sha256":"057130e7109c592068e375f31a5f39297163326bb88f6461d59ae4e7742d7a80"}
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"4a2331d2ad22ef8c0dcab3df637dbb4ceed9652100bb0e9890bcc40297b33fc9","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-x64","dependencyLockDigest":"c63ff3a60c411a06ad881d6ae81fbe88402cc1ff3a3447bf54765b090b2c77bb","protocolVersion":1,"serverVersion":"0.2.4","contentId":"9fe4ad3c210ccc4a20b8ea0b0db485b1f49bb88d7d2f829c7c0a1175df505f85"},"sha256":"a5a6b01ebf90a92c07144e6b12811427a97c128909cb440c95463a394f156d38"}
1
+ {"build":{"format":1,"sourceDigest":"f1a415e52552342511151e078257a3d81660989f30a684a263fb8f6252ac9e63","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-x64","dependencyLockDigest":"c63ff3a60c411a06ad881d6ae81fbe88402cc1ff3a3447bf54765b090b2c77bb","protocolVersion":1,"serverVersion":"0.4.0","contentId":"5e132e98f011fb0eee44a2184ef8d17787a7ac0f1b792b676b08582d248ba19f"},"sha256":"a007cde2962d0b0eb4fe378a3e9d08fd2f20ada6fce2c96b76f849cb6dd62c96"}
@@ -1,12 +1,45 @@
1
1
  import { mkdirSync, readFileSync, readdirSync, renameSync, rmdirSync, unlinkSync, writeFileSync } from "node:fs";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { join } from "node:path";
4
+ import { execFileSync } from "node:child_process";
4
5
  export function currentOwnerIdentity(token = randomUUID()) {
5
- return { pid: process.pid, token, ...linuxIdentity(process.pid) };
6
+ const { boot, start } = processIdentity(process.pid);
7
+ return { pid: process.pid, token, ...(boot ? { boot } : {}), ...(start ? { start } : {}) };
6
8
  }
7
9
  export function ownerIsAlive(owner) {
8
10
  return alive(owner);
9
11
  }
12
+ export function sameOwner(left, right) {
13
+ return typeof left.start === "string" && left.pid === right.pid && left.token === right.token
14
+ && left.start === right.start && left.boot === right.boot;
15
+ }
16
+ export function ownerIdentityVerified(owner) {
17
+ const observed = processIdentity(owner.pid);
18
+ return typeof owner.start === "string" && observed.start === owner.start
19
+ && (process.platform !== "linux" || typeof owner.boot === "string" && owner.boot === observed.boot)
20
+ && alive(owner);
21
+ }
22
+ /** Matches the existing runner/worker start-token representation, without releasing fences. */
23
+ export function processMatchesStart(pid, start) {
24
+ if (!Number.isSafeInteger(pid) || pid <= 0 || typeof start !== "string")
25
+ return false;
26
+ if (!/^\d+$/.test(start)) {
27
+ // Background runner claims use ps lstart on both supported platforms;
28
+ // Subagent Linux records use /proc ticks. Compare in the recorded format.
29
+ try {
30
+ const observed = execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], {
31
+ encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 2000,
32
+ env: { ...process.env, LC_ALL: "C" },
33
+ }).trim();
34
+ return observed.length > 0 && observed.replace(/\s+/g, " ") === start.trim().replace(/\s+/g, " ");
35
+ }
36
+ catch {
37
+ return false;
38
+ }
39
+ }
40
+ const identity = processIdentity(pid);
41
+ return identity.start !== undefined && identity.start === start && alive({ pid, token: "observation", start: identity.start });
42
+ }
10
43
  /** Read-only, fail-closed inspection using the same PID-reuse checks as claiming. */
11
44
  export function inspectDaemonOwner(serverDir, lockName = "daemon-owner") {
12
45
  const lock = join(serverDir, lockName);
@@ -45,23 +78,37 @@ function validateOwner(previous, name, lock) {
45
78
  throw new Error(`Invalid daemon ownership in ${lock}`);
46
79
  }
47
80
  const UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
48
- function linuxIdentity(pid) {
81
+ function processIdentity(pid) {
82
+ if (process.platform === "darwin") {
83
+ try {
84
+ const start = execFileSync("/bin/ps", ["-p", String(pid), "-o", "lstart="], { encoding: "utf8", env: { ...process.env, LC_ALL: "C" }, timeout: 1000 }).trim();
85
+ const stamp = Date.parse(start);
86
+ return Number.isFinite(stamp) ? { start: String(stamp) } : {};
87
+ }
88
+ catch {
89
+ return {};
90
+ }
91
+ }
49
92
  if (process.platform !== "linux")
50
93
  return {};
51
94
  try {
52
95
  const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
53
- return { boot: readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim(), start: stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19] };
96
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
97
+ return { boot: readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim(), start: fields[19], state: fields[0] };
54
98
  }
55
99
  catch {
56
100
  return {};
57
101
  }
58
102
  }
59
103
  function alive(owner) {
60
- const identity = linuxIdentity(owner.pid);
104
+ const identity = processIdentity(owner.pid);
61
105
  if (owner.boot && identity.boot && owner.boot !== identity.boot)
62
106
  return false;
63
107
  if (owner.start && identity.start && owner.start !== identity.start)
64
108
  return false;
109
+ // A kernel-confirmed exited process cannot own a socket even before its parent reaps it.
110
+ if (identity.state === "Z" || identity.state === "X")
111
+ return false;
65
112
  try {
66
113
  process.kill(owner.pid, 0);
67
114
  return true;
@@ -8,6 +8,7 @@ import { stageRuntime } from "../startup/install.mjs";
8
8
  import { inspectDaemonOwner } from "../daemon-owner.mjs";
9
9
  import { runtimeRoot } from "./root.mjs";
10
10
  import { socketPathFor } from "./socket.mjs";
11
+ export { WorkClient } from "./work-client.mjs";
11
12
  /** One bounded LF-JSON exchange; importing this module never loads the Pi SDK. */
12
13
  export async function runtimeStatus(socketPath, agentDir, artifact, timeoutMs = 2000) {
13
14
  return new Promise((resolve, reject) => {
@@ -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
+ }
@@ -1,9 +1,10 @@
1
1
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
- import { listMetas, listMetasForOrigin, onMetaChanged } from "./registry.js";
2
+ import { listMetas, onMetaChanged } from "./registry.js";
3
3
  import { getObservedWaitHost, type DurableTaskProjection } from "./observed-waits.js";
4
4
  import type { BackgroundTaskMeta } from "./types.js";
5
5
  import { isTerminalStatus } from "./types.js";
6
6
  import { backgroundTaskProgressAt, observeBackgroundTaskStall } from "./stall.js";
7
+ import { backgroundObservation, onBackgroundObservation } from "./work-observation.js";
7
8
 
8
9
  const GOAL_READY_EVENT = "pi-better-goal:ready";
9
10
  const GOAL_REGISTER_PROVIDER_EVENT = "pi-better-goal:register-provider";
@@ -53,19 +54,22 @@ export function registerBackgroundTasksGoalProvider(pi: ExtensionAPI): void {
53
54
  pi.events?.emit(GOAL_REGISTER_PROVIDER_EVENT, {
54
55
  id: "background-tasks",
55
56
  label: "Background Tasks",
56
- getActivity: (ctx: ExtensionContext) => {
57
- const origin = getGoalActivityOrigin(ctx);
58
- const durable = getObservedWaitHost(pi)?.listDurableTasks(origin, {
59
- retentionMs: TERMINAL_GOAL_ACTIVITY_RETENTION_MS,
60
- }) ?? [];
61
- return collectBackgroundTaskGoalActivity(listMetasForOrigin(origin), ctx, Date.now(), durable);
57
+ scope: "session",
58
+ getActivity: async (ctx: ExtensionContext) => {
59
+ const snapshot = await backgroundObservation(pi, ctx);
60
+ if (snapshot.status !== "ready") throw new Error(snapshot.reason ?? "Background activity is unverified");
61
+ const durable = snapshot.rows.filter((row: any) => row.meta.durable).map((row: any) => row.meta);
62
+ const legacy = snapshot.rows.filter((row: any) => !row.meta.durable).map((row: any) => row.meta);
63
+ return collectBackgroundTaskGoalActivity(legacy, ctx, Date.now(), durable);
62
64
  },
63
65
  // A durable operation change must refresh Goal activity even though it
64
66
  // never writes a mutable legacy registry meta.
65
67
  onActivityChanged: (notify: () => void) => {
68
+ const offRuntime = onBackgroundObservation(pi, notify);
66
69
  const offMeta = onMetaChanged(notify);
67
70
  const offDurable = getObservedWaitHost(pi)?.onDurableTaskChange(notify);
68
71
  return () => {
72
+ offRuntime();
69
73
  offMeta();
70
74
  offDurable?.();
71
75
  };
@@ -8,6 +8,7 @@ import { getCallbackBatcher } from "./shared-callback-batcher.js";
8
8
  import { observeForegroundSandboxPolicy } from "./sandbox.js";
9
9
  import { registerTools } from "./tools.js";
10
10
  import { deliverBackgroundTasksPrompt } from "./prompt.js";
11
+ import { closeBackgroundObservation } from "./work-observation.js";
11
12
 
12
13
  export default function backgroundTasksExtension(pi: ExtensionAPI): void {
13
14
  // Each cached factory invocation owns its runtime, failure timers, navigator
@@ -17,6 +18,7 @@ export default function backgroundTasksExtension(pi: ExtensionAPI): void {
17
18
  // Created before registerTools so the tools can resolve it lazily; the durable
18
19
  // store opens on session activation and closes on switch/unload.
19
20
  const observedWaits = createObservedWaitHost(pi, {
21
+ serverOwnedResults: true,
20
22
  notifyParent: (notification, delivery) => {
21
23
  getCallbackBatcher(pi).enqueue({
22
24
  source: "background-task",
@@ -55,10 +57,12 @@ export default function backgroundTasksExtension(pi: ExtensionAPI): void {
55
57
  navigator.ensureBackgroundTasksNavigator(ctx);
56
58
  });
57
59
  pi.on("session_before_switch", async () => {
60
+ closeBackgroundObservation(pi);
58
61
  observedWaits.close();
59
62
  navigator.clearBackgroundTasksNavigatorSession();
60
63
  });
61
64
  pi.on("session_shutdown", async (_event, ctx) => {
65
+ closeBackgroundObservation(pi);
62
66
  // /reload, session replacement, and quit load a fresh instance; stop this one's timers (#324).
63
67
  observedWaits.close();
64
68
  runtime.suspendScheduledWork();