pi-better-harness 0.46.0 → 0.47.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 (74) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/extensions/shared-harness-settings.ts +4 -2
  3. package/extensions/task-context/index.ts +2 -0
  4. package/extensions/task-context/workflow-plan-update.ts +11 -0
  5. package/node_modules/pi-better-background-tasks/package.json +2 -1
  6. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-arm64.gz +0 -0
  7. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-arm64.json +1 -1
  8. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-x64.gz +0 -0
  9. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-x64.json +1 -1
  10. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-arm64.gz +0 -0
  11. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-arm64.json +1 -1
  12. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-x64.gz +0 -0
  13. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-x64.json +1 -1
  14. package/node_modules/pi-better-background-tasks/runtime-client/src/daemon-owner.mjs +50 -4
  15. package/node_modules/pi-better-background-tasks/runtime-client/src/runtime/client.mjs +1 -0
  16. package/node_modules/pi-better-background-tasks/runtime-client/src/runtime/work-client.mjs +88 -0
  17. package/node_modules/pi-better-background-tasks/src/goal-provider.ts +11 -7
  18. package/node_modules/pi-better-background-tasks/src/index.ts +3 -0
  19. package/node_modules/pi-better-background-tasks/src/observed-waits.ts +88 -26
  20. package/node_modules/pi-better-background-tasks/src/output.ts +16 -13
  21. package/node_modules/pi-better-background-tasks/src/registry.ts +15 -0
  22. package/node_modules/pi-better-background-tasks/src/shared-harness-settings.ts +4 -2
  23. package/node_modules/pi-better-background-tasks/src/shared-log-utils.ts +18 -7
  24. package/node_modules/pi-better-background-tasks/src/shared-navigator.ts +16 -4
  25. package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/assignment-observation.mjs +63 -3
  26. package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/index.ts +2 -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/schema.ts +20 -0
  29. package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/src/store.ts +35 -0
  30. package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/src/task-cancellation.ts +224 -0
  31. package/node_modules/pi-better-background-tasks/src/shared-work-client.mjs +88 -0
  32. package/node_modules/pi-better-background-tasks/src/tools.ts +28 -23
  33. package/node_modules/pi-better-background-tasks/src/work-observation.ts +117 -0
  34. package/node_modules/pi-better-goal/package.json +1 -1
  35. package/node_modules/pi-better-goal/src/index.ts +10 -1
  36. package/node_modules/pi-better-goal/src/shared-assignment-observation.mjs +63 -3
  37. package/node_modules/pi-better-goal/src/shared-assignment-projection.mjs +12 -4
  38. package/node_modules/pi-better-goal/src/shared-harness-settings.ts +4 -2
  39. package/node_modules/pi-better-goal/src/workflow-gates.ts +77 -11
  40. package/node_modules/pi-better-sandbox/package.json +1 -1
  41. package/node_modules/pi-better-sandbox/shared-harness-settings.ts +4 -2
  42. package/node_modules/pi-better-subagents/assignment-projection.mjs +12 -4
  43. package/node_modules/pi-better-subagents/health-observation.ts +9 -4
  44. package/node_modules/pi-better-subagents/index.ts +49 -61
  45. package/node_modules/pi-better-subagents/list.mjs +1 -1
  46. package/node_modules/pi-better-subagents/output-payload.ts +2 -0
  47. package/node_modules/pi-better-subagents/package.json +1 -1
  48. package/node_modules/pi-better-subagents/parse.ts +7 -6
  49. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-arm64.gz +0 -0
  50. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-arm64.json +1 -1
  51. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-x64.gz +0 -0
  52. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-x64.json +1 -1
  53. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-arm64.gz +0 -0
  54. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-arm64.json +1 -1
  55. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-x64.gz +0 -0
  56. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-x64.json +1 -1
  57. package/node_modules/pi-better-subagents/runtime-client/src/daemon-owner.mjs +50 -4
  58. package/node_modules/pi-better-subagents/runtime-client/src/runtime/client.mjs +1 -0
  59. package/node_modules/pi-better-subagents/runtime-client/src/runtime/work-client.mjs +88 -0
  60. package/node_modules/pi-better-subagents/session-store.ts +27 -14
  61. package/node_modules/pi-better-subagents/shared-harness-settings.ts +4 -2
  62. package/node_modules/pi-better-subagents/shared-log-utils.ts +18 -7
  63. package/node_modules/pi-better-subagents/shared-navigator.ts +16 -4
  64. package/node_modules/pi-better-subagents/shared-operation-coordinator/assignment-observation.mjs +63 -3
  65. package/node_modules/pi-better-subagents/shared-operation-coordinator/index.ts +2 -0
  66. package/node_modules/pi-better-subagents/shared-operation-coordinator/src/errors.ts +2 -0
  67. package/node_modules/pi-better-subagents/shared-operation-coordinator/src/schema.ts +20 -0
  68. package/node_modules/pi-better-subagents/shared-operation-coordinator/src/store.ts +35 -0
  69. package/node_modules/pi-better-subagents/shared-operation-coordinator/src/task-cancellation.ts +224 -0
  70. package/node_modules/pi-better-subagents/shared-work-client.d.mts +9 -0
  71. package/node_modules/pi-better-subagents/shared-work-client.mjs +88 -0
  72. package/node_modules/pi-better-subagents/tools.ts +39 -2
  73. package/node_modules/pi-better-subagents/work-observation.ts +177 -0
  74. package/package.json +5 -5
package/CHANGELOG.md CHANGED
@@ -1,5 +1,25 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.47.0] - 2026-11-16
4
+
5
+ ### Added
6
+
7
+ - 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)
8
+
9
+ ### Fixed
10
+
11
+ - 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)
12
+ - Include bounded Navigator refreshes and settings writes that tolerate brief contention between independent processes.
13
+ - Keep shared runtime status responsive while large history indexes rebuild, without forcing another inventory or terminating the read worker.
14
+ - Bundle Background Tasks 0.16.0, Subagents 0.33.0 and Sandbox 0.14.2.
15
+
16
+ ## [0.46.1] - 2026-11-15
17
+
18
+ ### Fixed
19
+
20
+ - Preserve optional answer-file links and source provenance when saving workflow decisions through the Todo tool and atomic plan writer. Legacy decisions, revision checks, profiling and completion guards are unchanged. (#780)
21
+ - Keep Navigator detail paints free of provider I/O, retaining refreshed detail state between paints. (#781)
22
+
3
23
  ## [0.46.0] - 2026-11-15
4
24
 
5
25
  ### Added
@@ -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
  }
@@ -91,6 +91,8 @@ const WorkflowUpdateSchema = Type.Object({
91
91
  humanWords: Type.String({ description: "The human's words, quoted or closely paraphrased." }),
92
92
  changes: Type.String({ description: "What the decision changes: units, validation, forbidden actions." }),
93
93
  supersedes: Type.Optional(Type.String({ description: "Id of the earlier decision this one replaces." })),
94
+ answers: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Answer-file keys resolved by this decision, e.g. results/127-impl-1.json." })),
95
+ source: Type.Optional(Type.String({ minLength: 1, description: "Decision provenance, e.g. agent-recommendation." })),
94
96
  }, { description: "A human decision to record with this transition." })),
95
97
  profiling: Type.Optional(Type.Object({}, {
96
98
  additionalProperties: true,
@@ -21,6 +21,8 @@ export interface RushDecisionInput {
21
21
  humanWords: string;
22
22
  changes: string;
23
23
  supersedes?: string | undefined;
24
+ answers?: string[] | undefined;
25
+ source?: string | undefined;
24
26
  }
25
27
 
26
28
  export interface RushPlanUpdate {
@@ -378,6 +380,13 @@ function appendDecision(plan: Record<string, unknown>, decision: RushDecisionInp
378
380
  for (const field of ["humanWords", "changes"] as const) {
379
381
  if (typeof decision[field] !== "string" || !decision[field].trim()) throw new Error(`workflow.decision.${field} is required.`);
380
382
  }
383
+ if (decision.answers !== undefined && (!Array.isArray(decision.answers) ||
384
+ !decision.answers.every((answer) => typeof answer === "string" && answer.trim().length > 0))) {
385
+ throw new Error("workflow.decision.answers must be a list of non-empty answer-file keys.");
386
+ }
387
+ if (decision.source !== undefined && (typeof decision.source !== "string" || !decision.source.trim())) {
388
+ throw new Error("workflow.decision.source must be non-empty text.");
389
+ }
381
390
  const decisions = plan.decisions === undefined || plan.decisions === null ? [] : plan.decisions;
382
391
  if (!Array.isArray(decisions)) throw new Error("The saved plan's decisions field is not a list.");
383
392
  const known = new Set(decisions.flatMap((entry) => isRecord(entry) && typeof entry.id === "string" ? [entry.id] : []));
@@ -388,6 +397,8 @@ function appendDecision(plan: Record<string, unknown>, decision: RushDecisionInp
388
397
  decisions.push({
389
398
  id, timestamp: ts, humanWords: decision.humanWords, changes: decision.changes,
390
399
  supersedes: decision.supersedes ?? null,
400
+ ...(decision.answers === undefined ? {} : { answers: [...decision.answers] }),
401
+ ...(decision.source === undefined ? {} : { source: decision.source }),
391
402
  });
392
403
  plan.decisions = decisions;
393
404
  return id;
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-background-tasks",
3
- "version": "0.15.4",
3
+ "version": "0.16.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":"3327fd5e74b18926f945db86bb1bc82f6a5f52eaef9ce091cfe45b7537df871c","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-arm64","dependencyLockDigest":"c63ff3a60c411a06ad881d6ae81fbe88402cc1ff3a3447bf54765b090b2c77bb","protocolVersion":1,"serverVersion":"0.3.0","contentId":"4a441dc74b227cdaaeebe9bf93580d18c4773acd30a43df8376205888314877f"},"sha256":"d605829c1323baa03ec1908337950c965d97e7ded4dc24479fff7300be296367"}
@@ -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":"3327fd5e74b18926f945db86bb1bc82f6a5f52eaef9ce091cfe45b7537df871c","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-x64","dependencyLockDigest":"c63ff3a60c411a06ad881d6ae81fbe88402cc1ff3a3447bf54765b090b2c77bb","protocolVersion":1,"serverVersion":"0.3.0","contentId":"217c2fe0b4c39621f2d231c2ee13e675514f5800d3d0f88edd1d640982df1cf8"},"sha256":"cafcd27fc435dd8a94b75154af1e509c0fb649c79423e090755c014c6609296b"}
@@ -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":"3327fd5e74b18926f945db86bb1bc82f6a5f52eaef9ce091cfe45b7537df871c","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-arm64","dependencyLockDigest":"c63ff3a60c411a06ad881d6ae81fbe88402cc1ff3a3447bf54765b090b2c77bb","protocolVersion":1,"serverVersion":"0.3.0","contentId":"ad01e2a4639e88f1919d9aa628d6d5760ab0b8bd34d563f6adf7c81c106e90f6"},"sha256":"0b5c8649a160f17eae208389848f09655d8e77fdf00c606241598c76fb956acd"}
@@ -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":"3327fd5e74b18926f945db86bb1bc82f6a5f52eaef9ce091cfe45b7537df871c","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-x64","dependencyLockDigest":"c63ff3a60c411a06ad881d6ae81fbe88402cc1ff3a3447bf54765b090b2c77bb","protocolVersion":1,"serverVersion":"0.3.0","contentId":"1e311f8fd34ed8dbea8660e1383e128e4f2916b18949cd1288ab5e0682b6a85a"},"sha256":"258a050dfbb9089e3876d2ffcafa85f85e40c9396e041145e43a6d90d2cdf8ab"}
@@ -1,12 +1,44 @@
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
+ }).trim();
33
+ return observed.length > 0 && observed === start.trim();
34
+ }
35
+ catch {
36
+ return false;
37
+ }
38
+ }
39
+ const identity = processIdentity(pid);
40
+ return identity.start !== undefined && identity.start === start && alive({ pid, token: "observation", start: identity.start });
41
+ }
10
42
  /** Read-only, fail-closed inspection using the same PID-reuse checks as claiming. */
11
43
  export function inspectDaemonOwner(serverDir, lockName = "daemon-owner") {
12
44
  const lock = join(serverDir, lockName);
@@ -45,23 +77,37 @@ function validateOwner(previous, name, lock) {
45
77
  throw new Error(`Invalid daemon ownership in ${lock}`);
46
78
  }
47
79
  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) {
80
+ function processIdentity(pid) {
81
+ if (process.platform === "darwin") {
82
+ try {
83
+ const start = execFileSync("/bin/ps", ["-p", String(pid), "-o", "lstart="], { encoding: "utf8", env: { ...process.env, LC_ALL: "C" }, timeout: 1000 }).trim();
84
+ const stamp = Date.parse(start);
85
+ return Number.isFinite(stamp) ? { start: String(stamp) } : {};
86
+ }
87
+ catch {
88
+ return {};
89
+ }
90
+ }
49
91
  if (process.platform !== "linux")
50
92
  return {};
51
93
  try {
52
94
  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] };
95
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
96
+ return { boot: readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim(), start: fields[19], state: fields[0] };
54
97
  }
55
98
  catch {
56
99
  return {};
57
100
  }
58
101
  }
59
102
  function alive(owner) {
60
- const identity = linuxIdentity(owner.pid);
103
+ const identity = processIdentity(owner.pid);
61
104
  if (owner.boot && identity.boot && owner.boot !== identity.boot)
62
105
  return false;
63
106
  if (owner.start && identity.start && owner.start !== identity.start)
64
107
  return false;
108
+ // A kernel-confirmed exited process cannot own a socket even before its parent reaps it.
109
+ if (identity.state === "Z" || identity.state === "X")
110
+ return false;
65
111
  try {
66
112
  process.kill(owner.pid, 0);
67
113
  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,88 @@
1
+ import { connect } from "node:net";
2
+
3
+ /** SDK-free observation stream. Cached snapshots are the only synchronous read API. */
4
+ export class WorkClient {
5
+ socket;
6
+ snapshot;
7
+ pending = new Map();
8
+ listeners = new Set();
9
+ sequence = 0;
10
+ scope;
11
+ buffer = "";
12
+ closed = false;
13
+
14
+ constructor(socketPath, agentDir, requiredCapabilities = []) {
15
+ this.socket = typeof socketPath === "string" ? connect(socketPath) : socketPath;
16
+ this.socket.setEncoding("utf8");
17
+ this.socket.on("data", chunk => {
18
+ this.buffer += chunk;
19
+ if (Buffer.byteLength(this.buffer) > 4 * 1024 * 1024) return this.fail(new Error("runtime-unhealthy: oversized stream frame"));
20
+ while (this.buffer.includes("\n")) {
21
+ const index = this.buffer.indexOf("\n"), line = this.buffer.slice(0, index);
22
+ this.buffer = this.buffer.slice(index + 1);
23
+ try {
24
+ const message = JSON.parse(line);
25
+ if (message.type === "event") {
26
+ if (message.event.type === "resync_required") { this.degrade(message.event.reason); void this.resync().catch(error => this.degrade(String(error))); }
27
+ else if (message.event.type === "runtime_snapshot") this.accept(message.event.snapshot);
28
+ } else {
29
+ const request = this.pending.get(message.id);
30
+ if (!request) continue;
31
+ this.pending.delete(message.id); clearTimeout(request.timer);
32
+ if (message.success) request.resolve(message.data); else request.reject(new Error(message.error));
33
+ }
34
+ } catch (error) { this.fail(error); }
35
+ }
36
+ });
37
+ this.socket.on("error", error => this.fail(error));
38
+ this.socket.on("close", () => this.fail(new Error("runtime-unavailable: disconnected; resync required")));
39
+ this.ready = this.request("hello", { protocolVersion: 1, runtimeRoot: agentDir, requiredCapabilities: ["runtime-state-v1", "runtime-subscriptions-v1", ...requiredCapabilities] })
40
+ .then(async hello => { if (typeof socketPath === "string" && hello.capabilities?.includes("runtime-client-retention-v1")) await this.request("runtime_register_client", { clientId: `work-${process.pid}` }); return hello; });
41
+ }
42
+ request(type, params = {}) {
43
+ if (this.closed) return Promise.reject(new Error("runtime-unavailable: disconnected; resync required"));
44
+ if (this.pending.size >= 32) return Promise.reject(new Error("runtime-unhealthy: too many in-flight queries"));
45
+ const id = `work-${++this.sequence}`;
46
+ return new Promise((resolve, reject) => {
47
+ const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(`runtime-unhealthy: ${type} timed out`)); }, 5000);
48
+ this.pending.set(id, { resolve, reject, timer });
49
+ this.socket.write(JSON.stringify({ id, type, ...params }) + "\n");
50
+ });
51
+ }
52
+ onChange(listener) { this.listeners.add(listener); return () => this.listeners.delete(listener); }
53
+ notify() { for (const listener of this.listeners) listener(this.snapshot); }
54
+ degrade(reason) {
55
+ this.snapshot = { ...this.snapshot, status: "degraded", reason, rows: this.snapshot?.rows ?? [] };
56
+ this.notify();
57
+ }
58
+ accept(snapshot) {
59
+ if (this.snapshot?.instanceId === snapshot.instanceId && snapshot.seq < this.snapshot.seq) return;
60
+ if (this.snapshot?.instanceId && this.snapshot.instanceId !== snapshot.instanceId) {
61
+ this.degrade("instance-changed: resync required");
62
+ snapshot = { ...snapshot, resyncRequired: true, resyncReason: "instance-changed" };
63
+ } else if (this.snapshot?.seq !== undefined && snapshot.seq > this.snapshot.seq + 1) {
64
+ this.degrade("sequence-gap: replacing with a full authoritative snapshot");
65
+ snapshot = { ...snapshot, resyncRequired: true, resyncReason: "sequence-gap" };
66
+ }
67
+ // Every event contains a complete bounded snapshot; gaps do not require inferred deltas.
68
+ this.snapshot = Object.freeze(snapshot); this.notify();
69
+ }
70
+ async subscribe(scope) {
71
+ await this.ready;
72
+ this.scope = scope;
73
+ const snapshot = await this.request("runtime_subscribe", { scope });
74
+ this.accept(snapshot); return snapshot;
75
+ }
76
+ async resync() {
77
+ const snapshot = await this.request("runtime_subscribe", { scope: this.scope, sinceSeq: this.snapshot?.seq, instanceId: this.snapshot?.instanceId });
78
+ this.accept(snapshot); return snapshot;
79
+ }
80
+ async get(scope) { await this.ready; return this.request("runtime_get_snapshot", { scope }); }
81
+ fail(error) {
82
+ if (this.closed) return;
83
+ this.closed = true;
84
+ for (const request of this.pending.values()) { clearTimeout(request.timer); request.reject(error); }
85
+ this.pending.clear(); this.socket.destroy(); this.degrade(String(error));
86
+ }
87
+ close() { this.fail(new Error("runtime-unavailable: client closed")); this.listeners.clear(); }
88
+ }
@@ -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
@@ -55,10 +56,12 @@ export default function backgroundTasksExtension(pi: ExtensionAPI): void {
55
56
  navigator.ensureBackgroundTasksNavigator(ctx);
56
57
  });
57
58
  pi.on("session_before_switch", async () => {
59
+ closeBackgroundObservation(pi);
58
60
  observedWaits.close();
59
61
  navigator.clearBackgroundTasksNavigatorSession();
60
62
  });
61
63
  pi.on("session_shutdown", async (_event, ctx) => {
64
+ closeBackgroundObservation(pi);
62
65
  // /reload, session replacement, and quit load a fresh instance; stop this one's timers (#324).
63
66
  observedWaits.close();
64
67
  runtime.suspendScheduledWork();
@@ -49,6 +49,7 @@ import {
49
49
  } from "./sandbox.js";
50
50
  import {
51
51
  openStore,
52
+ cancellationCredential,
52
53
  type AcknowledgeDisposition,
53
54
  type EvidenceKind,
54
55
  type OperationEvidenceRecord,
@@ -835,6 +836,20 @@ function mapEvidence(
835
836
  }));
836
837
  }
837
838
 
839
+ /** Shared terminal publication contract for the host and fixed server cancel adapter. */
840
+ export function supervisorTerminalPublication(operation: OperationRecord, inspection: SupervisorInspection, refs = evidenceFor(inspection)) {
841
+ const status = inspection.status;
842
+ const outcome = terminalOutcome(status);
843
+ return {
844
+ operationId: operation.operationId,
845
+ eventId: `${operation.taskId}:${inspection.result?.endedAt ?? inspection.lost?.recordedAt ?? inspection.observedAt}:${status}`,
846
+ outcome, owner: operation.owner,
847
+ evidence: refs.map(ref => ({ kind: ref.kind, ref: ref.ref, ...(ref.summary ? { summary: ref.summary } : {}), detailLost: ref.detailLost })),
848
+ ...(outcome === "lost" ? { detailLost: true } : {}),
849
+ reason: inspection.result ? `supervisor ${status} exit=${inspection.result.exitCode ?? "null"}` : "supervisor lost: no terminal evidence",
850
+ };
851
+ }
852
+
838
853
  export class ObservedWaitHost {
839
854
  readonly service: BackgroundOperationService;
840
855
  private store?: Store;
@@ -880,6 +895,7 @@ export class ObservedWaitHost {
880
895
  private continuation?: ContinuationAdapter;
881
896
  private continuationError?: string;
882
897
  private readonly launches = new Map<string, LaunchContext>();
898
+ private readonly localCancels = new Set<string>();
883
899
  private readonly rpcRuns = new Map<string, RpcRunBinding>();
884
900
  private readonly waitOwners = new Map<string, OwnerIdentity>();
885
901
  private readonly stagedCheckpoints = new Map<string, { evidence: JsonRecord; toolCallId: string; checkpointRecorded: boolean }>();
@@ -1470,11 +1486,68 @@ export class ObservedWaitHost {
1470
1486
  return this.log(taskId, this.ownerFor(ctx), options);
1471
1487
  }
1472
1488
 
1473
- async stopForParent(ctx: ExtensionContext, taskId: string): Promise<StatusView> {
1489
+ async stopForParent(ctx: ExtensionContext, taskId: string, requestId?: string): Promise<StatusView> {
1474
1490
  this.noteParentContext(ctx);
1491
+ if (requestId) {
1492
+ try { return await this.stopThroughRuntime(ctx, taskId, requestId); }
1493
+ catch (error) {
1494
+ if (/not_accepted|accepted:|outcome_unknown/.test(String(error))) throw error;
1495
+ throw new Error(`not_accepted: ${String(error)}`);
1496
+ }
1497
+ }
1475
1498
  return this.stop(taskId, this.ownerFor(ctx));
1476
1499
  }
1477
1500
 
1501
+ /** Called from an actual admitted parent tool context, not a wire owner claim. */
1502
+ authorizeCancellationForParent(ctx: ExtensionContext, taskId: string, requestId: string): string {
1503
+ if (this.localCancels.has(taskId)) throw new Error("not_accepted: old cancellation admission is still draining");
1504
+ const operation = this.ownedOperation(taskId, this.ownerFor(ctx));
1505
+ if (this.supervisionAuthority(operation) === "foreign") throw new Error("permission-unavailable: live legacy or unknown supervisor prevents cancellation handoff");
1506
+ const proof = cancellationCredential();
1507
+ const previous = this.requireStore().getTaskCancellation({ owner: operation.owner, idempotencyKey: requestId });
1508
+ if (previous && previous.operationId !== operation.operationId) throw new Error("not_accepted: request-conflict: cancellation key belongs to another task");
1509
+ this.requireStore().admitTaskCancellation({ credentialHash: proof.hash, directory: this.directory, request: previous ?? {
1510
+ owner: operation.owner, idempotencyKey: requestId, operationId: operation.operationId,
1511
+ expectedLaunchToken: operation.launchToken, expectedTerminalRevision: operation.terminalRevision,
1512
+ expectedHostId: operation.supervision?.hostId ?? "unavailable", reason: "explicit stop",
1513
+ } });
1514
+ return proof.credential;
1515
+ }
1516
+
1517
+ private async stopThroughRuntime(ctx: ExtensionContext, taskId: string, requestId: string): Promise<StatusView> {
1518
+ this.ownedOperation(taskId, this.ownerFor(ctx));
1519
+ const root = realpathSync(dirname(this.storePath));
1520
+ const registrationPath = join(root, "server-registration-v1.json");
1521
+ if (!existsSync(registrationPath)) {
1522
+ const installer = "../runtime-client/src/runtime/client.mjs";
1523
+ await (await import(installer)).ensureRuntime({ agentDir: root });
1524
+ }
1525
+ const registration = JSON.parse(readFileSync(registrationPath, "utf8"));
1526
+ if (registration.agentDir !== root || registration.version !== 1) throw new Error("not_accepted: invalid canonical runtime registration");
1527
+ const module = "./shared-work-client.mjs";
1528
+ const { WorkClient } = await import(module);
1529
+ const client = new WorkClient(join(registration.serverDir, "pi-server.sock"), root, ["runtime-cancellation-v1"]);
1530
+ let submitted = false;
1531
+ try {
1532
+ await client.ready;
1533
+ await client.request("runtime_cancellation_status");
1534
+ const credential = this.authorizeCancellationForParent(ctx, taskId, requestId);
1535
+ const previous = await client.request("runtime_query_cancellation", { credential });
1536
+ let receipt = previous;
1537
+ if (previous.state === "not_accepted") {
1538
+ submitted = true;
1539
+ receipt = await client.request("runtime_cancel_task", { credential });
1540
+ }
1541
+ if (receipt.state === "outcome_unknown" || !receipt.result) throw new Error(`${receipt.state}: cancellation ${requestId}; query the same request before retrying`);
1542
+ return this.statusForParent(ctx, taskId);
1543
+ } catch (error) {
1544
+ const message = String(error);
1545
+ if (/not_accepted|accepted:|outcome_unknown/.test(message)) throw error;
1546
+ if (!submitted) throw new Error(`not_accepted: cancellation ${requestId}: ${message}`);
1547
+ throw new Error(`outcome_unknown: cancellation ${requestId}; reconnect and query the same request before retrying: ${message}`);
1548
+ } finally { client.close(); }
1549
+ }
1550
+
1478
1551
  // ---- read-only projections for list, navigator and Goal -----------------
1479
1552
 
1480
1553
  /**
@@ -1794,14 +1867,19 @@ export class ObservedWaitHost {
1794
1867
  private async stop(taskId: string, owner: OwnerIdentity): Promise<StatusView> {
1795
1868
  const store = this.requireStore();
1796
1869
  const operation = this.ownedOperation(taskId, owner);
1797
- const result = await this.supervisor.stop(taskId);
1798
- const inspection = result?.inspection ?? this.supervisor.inspect(taskId);
1799
- this.reconcileInspection(operation, inspection);
1800
- const current = store.getOperation(operation.operationId) ?? operation;
1801
- if (current.terminalRevision === 0 && inspection?.terminal) {
1802
- this.recordTerminal(current, inspection);
1803
- }
1804
- return this.status(taskId, owner);
1870
+ if (store.taskCancellationManaged(operation.operationId)) throw new Error("not_accepted: cancellation admission transferred to server; use the registered stop tool with the original request_id");
1871
+ if (this.localCancels.has(taskId)) throw new Error("not_accepted: old cancellation is already in flight");
1872
+ this.localCancels.add(taskId);
1873
+ try {
1874
+ const result = await this.supervisor.stop(taskId, { token: operation.launchToken });
1875
+ const inspection = result?.inspection ?? this.supervisor.inspect(taskId);
1876
+ this.reconcileInspection(operation, inspection);
1877
+ const current = store.getOperation(operation.operationId) ?? operation;
1878
+ if (current.terminalRevision === 0 && inspection?.terminal) {
1879
+ this.recordTerminal(current, inspection);
1880
+ }
1881
+ return this.status(taskId, owner);
1882
+ } finally { this.localCancels.delete(taskId); }
1805
1883
  }
1806
1884
 
1807
1885
  formatStatus(view: StatusView): string {
@@ -3003,26 +3081,10 @@ export class ObservedWaitHost {
3003
3081
  const store = this.requireStore();
3004
3082
  const status = inspection.status;
3005
3083
  const outcome = terminalOutcome(status);
3006
- const eventId = `${operation.taskId}:${inspection.result?.endedAt ?? inspection.lost?.recordedAt ?? inspection.observedAt}:${status}`;
3007
3084
  const refs = evidenceFor(inspection);
3008
3085
  let recorded;
3009
3086
  try {
3010
- recorded = store.recordTerminalOutcome({
3011
- operationId: operation.operationId,
3012
- eventId,
3013
- outcome,
3014
- owner: operation.owner,
3015
- evidence: refs.map((ref) => ({
3016
- kind: ref.kind,
3017
- ref: ref.ref,
3018
- ...(ref.summary ? { summary: ref.summary } : {}),
3019
- detailLost: ref.detailLost,
3020
- })),
3021
- ...(outcome === "lost" ? { detailLost: true } : {}),
3022
- reason: inspection.result
3023
- ? `supervisor ${status} exit=${inspection.result.exitCode ?? "null"}`
3024
- : "supervisor lost: no terminal evidence",
3025
- });
3087
+ recorded = store.recordTerminalOutcome(supervisorTerminalPublication(operation, inspection, refs));
3026
3088
  } catch (error) {
3027
3089
  // A timer and a tool call can observe the same terminal record. The store
3028
3090
  // keeps the first revision; a replay is never a second execution.