pi-better-server 0.2.4 → 0.3.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 (83) hide show
  1. package/package.json +3 -3
  2. package/scripts/measure-shared-reads/daemon.mjs +7 -0
  3. package/scripts/measure-shared-reads/probe.mjs +10 -0
  4. package/scripts/measure-shared-reads.mjs +145 -0
  5. package/scripts/test-on-pi.sh +19 -2
  6. package/src/cli.ts +39 -2
  7. package/src/client.ts +9 -4
  8. package/src/daemon-owner.ts +47 -6
  9. package/src/handshake.ts +8 -7
  10. package/src/lifecycle-config.ts +4 -0
  11. package/src/paths.ts +1 -11
  12. package/src/protocol.ts +5 -0
  13. package/src/registry.ts +2 -1
  14. package/src/runtime/background-history.ts +241 -0
  15. package/src/runtime/background.ts +173 -0
  16. package/src/runtime/cancellation.ts +95 -0
  17. package/src/runtime/client.ts +111 -0
  18. package/src/runtime/domain/assignment-observation.d.mts +1 -0
  19. package/src/runtime/domain/assignment-observation.mjs +103 -0
  20. package/src/runtime/domain/assignment-projection.d.mts +1 -0
  21. package/src/runtime/domain/assignment-projection.mjs +245 -0
  22. package/src/runtime/domain/background/conditions.mjs +93 -0
  23. package/src/runtime/domain/background/process-identity.mjs +110 -0
  24. package/src/runtime/domain/background/process.mjs +511 -0
  25. package/src/runtime/domain/background/registry.mjs +374 -0
  26. package/src/runtime/domain/background/snapshot.mjs +73 -0
  27. package/src/runtime/domain/background/supervisor/identity.mjs +92 -0
  28. package/src/runtime/domain/background/supervisor/invocation.mjs +29 -0
  29. package/src/runtime/domain/background/supervisor/store.mjs +604 -0
  30. package/src/runtime/domain/background/supervisor/supervisor.mjs +720 -0
  31. package/src/runtime/domain/background/supervisor/types.mjs +47 -0
  32. package/src/runtime/domain/background/terminal-publication.mjs +58 -0
  33. package/src/runtime/domain/background/types.mjs +3 -0
  34. package/src/runtime/domain/coordinator/index.mjs +50 -0
  35. package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +160 -0
  36. package/src/runtime/domain/coordinator/src/discovery.mjs +85 -0
  37. package/src/runtime/domain/coordinator/src/errors.mjs +12 -0
  38. package/src/runtime/domain/coordinator/src/operations.mjs +299 -0
  39. package/src/runtime/domain/coordinator/src/outbox.mjs +282 -0
  40. package/src/runtime/domain/coordinator/src/recovery.mjs +51 -0
  41. package/src/runtime/domain/coordinator/src/rows.mjs +277 -0
  42. package/src/runtime/domain/coordinator/src/schema.mjs +351 -0
  43. package/src/runtime/domain/coordinator/src/sqlite.mjs +193 -0
  44. package/src/runtime/domain/coordinator/src/store.mjs +235 -0
  45. package/src/runtime/domain/coordinator/src/task-cancellation.mjs +187 -0
  46. package/src/runtime/domain/coordinator/src/types.mjs +24 -0
  47. package/src/runtime/domain/coordinator/src/validate.mjs +233 -0
  48. package/src/runtime/domain/coordinator/src/waits.mjs +850 -0
  49. package/src/runtime/domain/health-observation.d.mts +3 -0
  50. package/src/runtime/domain/health-observation.mjs +613 -0
  51. package/src/runtime/domain/health-surface.mjs +279 -0
  52. package/src/runtime/domain/log-cursor.mjs +148 -0
  53. package/src/runtime/domain/log-paths.mjs +13 -0
  54. package/src/runtime/domain/parse.d.mts +2 -0
  55. package/src/runtime/domain/parse.mjs +1173 -0
  56. package/src/runtime/domain/process-status.d.mts +1 -0
  57. package/src/runtime/domain/process-status.mjs +25 -0
  58. package/src/runtime/domain/session-store.d.mts +2 -0
  59. package/src/runtime/domain/session-store.mjs +489 -0
  60. package/src/runtime/domain/shared-harness-settings.d.mts +1 -0
  61. package/src/runtime/domain/shared-harness-settings.mjs +126 -0
  62. package/src/runtime/domain/shared-log-utils.mjs +1223 -0
  63. package/src/runtime/domain/shared-stall-detector.mjs +37 -0
  64. package/src/runtime/domain/widget.d.mts +1 -0
  65. package/src/runtime/domain/widget.mjs +250 -0
  66. package/src/runtime/guardian.ts +189 -0
  67. package/src/runtime/health-config.ts +27 -0
  68. package/src/runtime/local-client.ts +34 -0
  69. package/src/runtime/queries.ts +76 -0
  70. package/src/runtime/query-executor.ts +228 -0
  71. package/src/runtime/query-worker.mjs +118 -0
  72. package/src/runtime/read-model.ts +357 -0
  73. package/src/runtime/root.ts +29 -0
  74. package/src/runtime/socket.ts +10 -0
  75. package/src/runtime/status-cli.ts +11 -0
  76. package/src/runtime/work-client.d.mts +13 -0
  77. package/src/runtime/work-client.mjs +88 -0
  78. package/src/server.ts +136 -12
  79. package/src/session-activity.ts +22 -2
  80. package/src/startup/activation.ts +32 -5
  81. package/src/startup/ensure.ts +13 -1
  82. package/src/startup/install.ts +2 -0
  83. package/src/version.ts +4 -0
@@ -0,0 +1,37 @@
1
+ // Generated from packages/pi-better-subagents/shared-stall-detector.ts. Do not edit directly.
2
+ export const DEFAULT_STALL_THRESHOLDS = Object.freeze({
3
+ quietMs: 60_000,
4
+ stallMs: 5 * 60_000,
5
+ });
6
+ function positiveMs(value, fallback) {
7
+ const parsed = Number(value);
8
+ return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : fallback;
9
+ }
10
+ /** Normalize caller config and ensure quiet never exceeds the stall threshold. */
11
+ export function resolveStallThresholds(partial) {
12
+ const quietMs = positiveMs(partial?.quietMs, DEFAULT_STALL_THRESHOLDS.quietMs);
13
+ const stallMs = positiveMs(partial?.stallMs, DEFAULT_STALL_THRESHOLDS.stallMs);
14
+ return { quietMs: Math.min(quietMs, stallMs), stallMs: Math.max(quietMs, stallMs) };
15
+ }
16
+ /**
17
+ * Classify the age of observable progress. This is deliberately observational:
18
+ * it does not claim a live process is broken and never performs recovery.
19
+ */
20
+ export function observeStall(input) {
21
+ const thresholds = resolveStallThresholds(input.thresholds);
22
+ const observedAt = input.lastProgressAt ?? input.startedAt;
23
+ if (typeof observedAt !== "number" || !Number.isFinite(observedAt)) {
24
+ return { state: "unknown", thresholds };
25
+ }
26
+ const ageMs = Math.max(0, input.now - observedAt);
27
+ if (input.exempt) {
28
+ return { state: ageMs >= thresholds.quietMs ? "quiet" : "healthy", observedAt, ageMs, thresholds };
29
+ }
30
+ if (ageMs >= thresholds.stallMs) {
31
+ return { state: "stalled", observedAt, ageMs, thresholds };
32
+ }
33
+ if (ageMs >= thresholds.quietMs) {
34
+ return { state: "quiet", observedAt, ageMs, thresholds };
35
+ }
36
+ return { state: "healthy", observedAt, ageMs, thresholds };
37
+ }
@@ -0,0 +1 @@
1
+ export function fmtSpend(usage: any): string;
@@ -0,0 +1,250 @@
1
+ /**
2
+ * Pure helpers for the live subagent status widget.
3
+ *
4
+ * Kept free of TUI / registry I/O so unit tests can pin the flicker-related
5
+ * contracts (dirty-check, fixed-width geometry, undefined clear) without a
6
+ * live pi session.
7
+ *
8
+ * Host note: pi's setWidget(string[]) path disposes + rebuilds the component
9
+ * tree on every call. Callers must skip identical frames and keep line geometry
10
+ * stable so neighboring ▶ job-* rows do not jump.
11
+ */
12
+
13
+ import { formatWidgetHealthSuffix } from "./health-surface.mjs";
14
+
15
+ export const SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
16
+
17
+ /** Default ticker cadence (ms). */
18
+ export const TICK_MS = 1000;
19
+
20
+ /**
21
+ * How often to re-parse a run log for spend/tool on the UI hot path.
22
+ * Elapsed still updates every tick; spend may lag by this much (AC3).
23
+ */
24
+ export const SPEND_REFRESH_MS = 5000;
25
+
26
+ /**
27
+ * Floor on how often any one run's log may be re-read on the UI hot path.
28
+ *
29
+ * The size/mtime freshness rules below correctly re-read a log that changed —
30
+ * but a live child writes continuously, so "changed" is true on every frame and
31
+ * the rules alone degenerate into re-reading each log as fast as the timer
32
+ * fires. This floor bounds that: within the floor a cached parse is reused even
33
+ * though the log grew. It only ever delays new numbers by the floor, and only
34
+ * for a run that is actively writing.
35
+ */
36
+ export const HOT_PATH_REFRESH_FLOOR_MS = 1000;
37
+
38
+ /**
39
+ * Whether a cached parse is inside the hot-path refresh floor and must be
40
+ * reused. Requires an explicit `now` and a `refreshedAt` stamp, so callers that
41
+ * pass neither keep the pure size/mtime semantics.
42
+ *
43
+ * @param {{ refreshedAt?: number }|null|undefined} cached
44
+ * @param {number} [now]
45
+ * @param {number} [floorMs]
46
+ */
47
+ export function withinRefreshFloor(cached, now, floorMs = HOT_PATH_REFRESH_FLOOR_MS) {
48
+ if (!cached || typeof now !== "number" || typeof cached.refreshedAt !== "number") return false;
49
+ if (!(floorMs > 0)) return false;
50
+ // A stamp from the future (clock step) must not pin the cache forever.
51
+ const age = now - cached.refreshedAt;
52
+ return age >= 0 && age < floorMs;
53
+ }
54
+
55
+ /**
56
+ * Value that clears the widget. pi only clears on `undefined`; `[]` leaves an
57
+ * empty residual widget node.
58
+ */
59
+ export const WIDGET_CLEAR = undefined;
60
+
61
+ /** Fixed field widths so line geometry does not jump as values grow. */
62
+ export const ELAPSED_WIDTH = 8; // "999h 59m", "99m 59s", "9999s"
63
+ export const TOKENS_WIDTH = 6; // "999.9k", "99.9M"
64
+ export const COST_WIDTH = 7; // "$999.99", "$0.0000"
65
+
66
+ /** "45s" · "2m 03s" · "1h 04m" — variable width (list/finalize paths). */
67
+ export function fmtElapsed(ms) {
68
+ const s = Math.max(0, Math.round(ms / 1000));
69
+ if (s < 60) return `${s}s`;
70
+ const m = Math.floor(s / 60);
71
+ const rs = s % 60;
72
+ if (m < 60) return `${m}m ${String(rs).padStart(2, "0")}s`;
73
+ const h = Math.floor(m / 60);
74
+ const rm = m % 60;
75
+ return `${h}h ${String(rm).padStart(2, "0")}m`;
76
+ }
77
+
78
+ /** Fixed-width elapsed for the live widget (right-pad to ELAPSED_WIDTH). */
79
+ export function fmtElapsedFixed(ms) {
80
+ return fmtElapsed(ms).padEnd(ELAPSED_WIDTH, " ");
81
+ }
82
+
83
+ /** "412" · "1.2k" · "27.9k" · "1.4M". */
84
+ export function fmtTokens(n) {
85
+ if (n < 1000) return String(n);
86
+ if (n < 1_000_000) return `${(n / 1000).toFixed(1)}k`;
87
+ return `${(n / 1_000_000).toFixed(1)}M`;
88
+ }
89
+
90
+ export function fmtTokensFixed(n) {
91
+ return fmtTokens(n).padStart(TOKENS_WIDTH, " ");
92
+ }
93
+
94
+ /** Compact USD cost, e.g. "$0.0057" or "$1.23". */
95
+ export function fmtCost(usd) {
96
+ if (usd <= 0) return "$0";
97
+ return usd < 1 ? `$${usd.toFixed(4)}` : `$${usd.toFixed(2)}`;
98
+ }
99
+
100
+ /** Compact model label for the widget: drop the provider prefix. */
101
+ export function shortModel(model) {
102
+ return model ? (model.split("/").pop() ?? model) : "?";
103
+ }
104
+
105
+ export function fmtCostFixed(usd) {
106
+ return fmtCost(usd).padStart(COST_WIDTH, " ");
107
+ }
108
+
109
+ /**
110
+ * One-line spend summary, or "" when nothing has been spent yet.
111
+ * Variable-width form used by list/finalize (not the live widget).
112
+ */
113
+ export function fmtSpend(u) {
114
+ if (!u || (u.total <= 0 && u.costUSD <= 0)) return "";
115
+ return `${fmtTokens(u.total)} tok (↑${fmtTokens(u.input)} ↓${fmtTokens(u.output)}) · ${fmtCost(u.costUSD)}`;
116
+ }
117
+
118
+ /**
119
+ * Fixed-width spend for the live widget. Empty string when no spend yet —
120
+ * callers should still reserve geometry via a stable suffix policy if needed;
121
+ * once spend appears, widths stay constant as digits grow within the caps.
122
+ */
123
+ export function fmtSpendFixed(u) {
124
+ if (!u || (u.total <= 0 && u.costUSD <= 0)) return "";
125
+ return (
126
+ `${fmtTokensFixed(u.total)} tok` +
127
+ ` (↑${fmtTokensFixed(u.input)} ↓${fmtTokensFixed(u.output)})` +
128
+ ` · ${fmtCostFixed(u.costUSD)}`
129
+ );
130
+ }
131
+
132
+ /** Deep equality for widget line arrays. */
133
+ export function linesEqual(a, b) {
134
+ if (a === b) return true;
135
+ if (!a || !b) return false;
136
+ if (a.length !== b.length) return false;
137
+ for (let i = 0; i < a.length; i++) {
138
+ if (a[i] !== b[i]) return false;
139
+ }
140
+ return true;
141
+ }
142
+
143
+ /**
144
+ * Decide what setWidget should receive for this frame.
145
+ *
146
+ * @param {string[]|undefined|null} prevLines - last lines sent to setWidget
147
+ * @param {string[]|null} nextLines - newly built lines, or null when idle
148
+ * @returns {{ op: 'skip' } | { op: 'set', lines: string[] } | { op: 'clear' }}
149
+ */
150
+ export function nextWidgetAction(prevLines, nextLines) {
151
+ if (nextLines === null || nextLines === undefined) {
152
+ // Already cleared / never painted — nothing to do.
153
+ if (prevLines === undefined || prevLines === null) return { op: "skip" };
154
+ // Had visible content (or a mistaken [] residual) → clear with undefined.
155
+ return { op: "clear" };
156
+ }
157
+ if (linesEqual(prevLines, nextLines)) return { op: "skip" };
158
+ return { op: "set", lines: nextLines };
159
+ }
160
+
161
+ /**
162
+ * Build the widget lines for currently-running subagents.
163
+ *
164
+ * Healthy/quiet health is silent (issue #67). Degraded observations may append
165
+ * a short suffix via `healthById` without making the widget interactive.
166
+ *
167
+ * @param {object} p
168
+ * @param {Array<{ id: string, name?: string|null, model?: string|null, startedAt: number }>} p.running
169
+ * @param {number} p.frame - spinner frame index
170
+ * @param {number} p.now - Date.now()
171
+ * @param {Record<string, { usage?: object, tool?: string|null }>} [p.spendById]
172
+ * @param {Record<string, object>|undefined} [p.healthById] - optional #66 observations
173
+ * @param {string|null} [p.affordanceHint] - left-arrow affordance shown on the title line
174
+ * @param {string|null} [p.selectedId] - selected run id while the main-window list is focused
175
+ * @returns {string[]}
176
+ */
177
+ export function buildWidgetLines(p) {
178
+ const running = p.running ?? [];
179
+ const frame = p.frame ?? 0;
180
+ const now = p.now ?? Date.now();
181
+ const spendById = p.spendById ?? {};
182
+ const healthById = p.healthById ?? {};
183
+ const selectedId = p.selectedId ?? null;
184
+ const spin = SPINNER[((frame % SPINNER.length) + SPINNER.length) % SPINNER.length];
185
+ const hint = p.affordanceHint ? ` ${p.affordanceHint}` : "";
186
+ const lines = [`Subagents · ${running.length} running${hint}`];
187
+ for (const m of running) {
188
+ const el = fmtElapsedFixed(now - m.startedAt);
189
+ const snap = spendById[m.id] ?? {};
190
+ const spend = fmtSpendFixed(snap.usage);
191
+ const tool = snap.tool ? ` · ${snap.tool}` : "";
192
+ const health = formatWidgetHealthSuffix(healthById[m.id]);
193
+ const nm = m.name ?? m.id;
194
+ const prefix = selectedId === m.id ? "› " : " ";
195
+ // Preserve list-show-model (#14): "name · shortModel" before fixed elapsed.
196
+ // Two spaces before elapsed keep a stable gap; elapsed itself is fixed-width.
197
+ lines.push(`${prefix}${spin} ${nm} · ${shortModel(m.model)} ${el}${tool}${spend ? ` ${spend}` : ""}${health}`);
198
+ }
199
+ return lines;
200
+ }
201
+
202
+ /**
203
+ * Whether a cached spend snapshot is still fresh enough for the UI tick.
204
+ *
205
+ * @param {{ refreshedAt: number, logSize?: number }|null|undefined} cached
206
+ * @param {number} now
207
+ * @param {number} [logSize]
208
+ * @param {number} [ttlMs]
209
+ */
210
+ export function isSpendCacheFresh(cached, now, logSize, ttlMs = SPEND_REFRESH_MS) {
211
+ if (!cached) return false;
212
+ if (typeof logSize === "number" && cached.logSize !== logSize) return false;
213
+ return now - cached.refreshedAt < ttlMs;
214
+ }
215
+
216
+ /**
217
+ * Whether a cached health-log parse is still valid for the widget tick.
218
+ * Invalidates on log size or mtime change so growth/rewrite re-extracts, while
219
+ * unchanged logs skip synchronous full-log reparses across repeated renders.
220
+ *
221
+ * @param {{ logSize?: number, mtimeMs?: number }|null|undefined} cached
222
+ * @param {number} logSize
223
+ * @param {number} [mtimeMs]
224
+ */
225
+ export function isHealthLogCacheFresh(cached, logSize, mtimeMs) {
226
+ if (!cached) return false;
227
+ if (cached.logSize !== logSize) return false;
228
+ if (typeof mtimeMs === "number" && cached.mtimeMs !== mtimeMs) return false;
229
+ return true;
230
+ }
231
+
232
+ /**
233
+ * Resolve child-event facts via the size/mtime cache, under the hot-path
234
+ * refresh floor. Calls `extract` only on miss, so a frame never re-reads a log
235
+ * that has not changed, and never re-reads one that changed more often than
236
+ * `identity.now`/`floorMs` allow.
237
+ *
238
+ * @param {{ facts: unknown, rawLog: unknown, logSize?: number, mtimeMs?: number, refreshedAt?: number }|null|undefined} cached
239
+ * @param {{ logSize: number, mtimeMs?: number, now?: number, floorMs?: number }} identity
240
+ * @param {() => { facts: unknown, rawLog: unknown }} extract
241
+ * @returns {{ facts: unknown, rawLog: unknown, hit: boolean }}
242
+ */
243
+ export function resolveHealthLogExtraction(cached, identity, extract) {
244
+ if (withinRefreshFloor(cached, identity.now, identity.floorMs)
245
+ || isHealthLogCacheFresh(cached, identity.logSize, identity.mtimeMs)) {
246
+ return { facts: cached.facts, rawLog: cached.rawLog, hit: true };
247
+ }
248
+ const { facts, rawLog } = extract();
249
+ return { facts, rawLog, hit: false };
250
+ }
@@ -0,0 +1,189 @@
1
+ import { spawn } from "node:child_process";
2
+ import { closeSync, fstatSync, openSync, readFileSync, realpathSync, renameSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { setTimeout as delay } from "node:timers/promises";
6
+ import { connect } from "node:net";
7
+ import { claimDaemonOwner, inspectDaemonOwner, ownerIdentityVerified, sameOwner, type DaemonOwnerIdentity } from "../daemon-owner.ts";
8
+ import { socketPathFor } from "./socket.ts";
9
+
10
+ function bindServer(serverDir: string, expected: DaemonOwnerIdentity, guardian: DaemonOwnerIdentity): Promise<boolean> {
11
+ return new Promise((resolve, reject) => {
12
+ const socket = connect(socketPathFor(serverDir));
13
+ let buffer = "", bound = false, stopping = false;
14
+ const timeout = setTimeout(() => socket.destroy(new Error("runtime-unhealthy: guardian bind timed out; live owner was not replaced")), 2000);
15
+ socket.setEncoding("utf8");
16
+ socket.on("connect", () => socket.write(JSON.stringify({ id: "hello", type: "hello", protocolVersion: 1, runtimeRoot: realpathSync(process.env.PI_CODING_AGENT_DIR!) }) + "\n"));
17
+ socket.on("error", error => { clearTimeout(timeout); reject(error); });
18
+ socket.on("data", (chunk: string) => {
19
+ buffer += chunk;
20
+ if (buffer.length > 65536) return socket.destroy(new Error("Oversized guardian handshake"));
21
+ while (buffer.includes("\n")) {
22
+ const index = buffer.indexOf("\n"), line = buffer.slice(0, index); buffer = buffer.slice(index + 1);
23
+ try {
24
+ const response = JSON.parse(line);
25
+ if (!response.success) throw new Error(response.error ?? "Guardian bind refused");
26
+ if (response.id === "hello") socket.write(JSON.stringify({ id: "bind", type: "runtime_guardian_bind", server: expected, guardian }) + "\n");
27
+ else if (response.id === "bind" && sameOwner(response.data.server, expected) && sameOwner(response.data.guardian, guardian)) {
28
+ bound = true; clearTimeout(timeout);
29
+ } else throw new Error("Guardian bind identity mismatch");
30
+ } catch (error) { socket.destroy(error as Error); }
31
+ }
32
+ });
33
+ const stop = () => { stopping = true; socket.destroy(); };
34
+ process.once("SIGTERM", stop); process.once("SIGINT", stop);
35
+ socket.on("close", () => {
36
+ clearTimeout(timeout); process.off("SIGTERM", stop); process.off("SIGINT", stop);
37
+ if (bound || stopping) resolve(stopping); else reject(new Error("runtime-unhealthy: guardian disconnected before exact bind acknowledgement"));
38
+ });
39
+ });
40
+ }
41
+
42
+ /** Only the live server owner may ask a replacement to bind; it never spawns another server. */
43
+ export function maintainGuardian(serverDir: string, server: DaemonOwnerIdentity): () => void {
44
+ let stopped = false, launching = false;
45
+ const check = () => {
46
+ if (stopped || launching || !server.start) return;
47
+ const owner = inspectDaemonOwner(serverDir, "guardian-owner");
48
+ const current = inspectDaemonOwner(serverDir);
49
+ if (owner.status === "live" || owner.status === "ambiguous" || current.status !== "live" || !sameOwner(current.owner, server)) return;
50
+ // Count reconstruction attempts durably before spawn, so replacing this server cannot reset a spin.
51
+ const path = join(serverDir, "guardian-rebinds.json");
52
+ let attempts: number[] = [];
53
+ try { attempts = JSON.parse(readFileSync(path, "utf8")); if (!Array.isArray(attempts) || attempts.some(value => !Number.isSafeInteger(value))) return; }
54
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") return; }
55
+ attempts = attempts.filter(time => Date.now() - time < 60000);
56
+ if (attempts.length >= 3) return;
57
+ attempts.push(Date.now());
58
+ const temporary = `${path}.${process.pid}`;
59
+ writeFileSync(temporary, JSON.stringify(attempts), { mode: 0o600 }); renameSync(temporary, path);
60
+ launching = true;
61
+ const child = spawn(process.execPath, [...process.execArgv, fileURLToPath(new URL("../cli.ts", import.meta.url)), "--agent", "pi"], {
62
+ env: { ...process.env, PI_SERVER_GUARDED_CHILD: "", PI_SERVER_GUARDIAN_REBIND: JSON.stringify(server) },
63
+ detached: true, stdio: ["ignore", "inherit", "inherit"],
64
+ });
65
+ child.once("error", () => { launching = false; }); child.once("exit", () => { launching = false; }); child.unref();
66
+ };
67
+ const timer = setInterval(() => { try { check(); } catch { /* Recovery stays degraded; server ownership is unchanged. */ } }, 1000);
68
+ timer.unref();
69
+ return () => { stopped = true; clearInterval(timer); };
70
+ }
71
+
72
+ /** Recovery only: the child retains all session, writer and domain authority. */
73
+ export async function runGuardian(serverDir: string, rebind?: DaemonOwnerIdentity): Promise<void> {
74
+ if (inspectDaemonOwner(serverDir, "guardian-owner").status === "ambiguous") throw new Error("Ambiguous guardian owner; refusing replacement");
75
+ const release = claimDaemonOwner(serverDir, "guardian-owner");
76
+ const budgetPath = join(serverDir, "guardian-restarts.json");
77
+ try {
78
+ let failures: number[] = [];
79
+ try {
80
+ const record = JSON.parse(readFileSync(budgetPath, "utf8"));
81
+ if (!Array.isArray(record) || record.some(value => !Number.isSafeInteger(value) || value < 0)) throw new Error("Invalid guardian restart budget");
82
+ failures = record;
83
+ } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
84
+ const receiptsPath = join(serverDir, "guardian-faults.json");
85
+ let receipts: string[] = [];
86
+ try {
87
+ receipts = JSON.parse(readFileSync(receiptsPath, "utf8"));
88
+ if (!Array.isArray(receipts) || receipts.some(token => typeof token !== "string")) throw new Error("Invalid guardian fault receipts");
89
+ } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
90
+ const fault = (identity?: DaemonOwnerIdentity) => {
91
+ if (identity && receipts.includes(identity.token)) return;
92
+ let idle;
93
+ try { idle = JSON.parse(readFileSync(join(serverDir, "idle-stop-intent.json"), "utf8")); } catch { /* No exact idle-stop intent. */ }
94
+ if (identity && idle?.token === identity.token && idle.pid === identity.pid) {
95
+ const path = join(serverDir, "guardian-idle-restarts.json");
96
+ let attempts: number[] = [];
97
+ try { attempts = JSON.parse(readFileSync(path, "utf8")); if (!Array.isArray(attempts) || attempts.some(value => !Number.isSafeInteger(value))) throw new Error("Invalid idle restart budget"); }
98
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
99
+ attempts = attempts.filter(time => Date.now() - time < 60000);
100
+ if (attempts.length) throw new Error("runtime-unavailable: idle recovery budget exhausted");
101
+ attempts.push(Date.now());
102
+ const temporary = `${path}.${process.pid}`;
103
+ writeFileSync(temporary, JSON.stringify(attempts), { mode: 0o600 }); renameSync(temporary, path);
104
+ }
105
+ failures = failures.filter(time => Date.now() - time < 60000);
106
+ failures.push(Date.now());
107
+ const temporary = `${budgetPath}.${process.pid}`;
108
+ writeFileSync(temporary, JSON.stringify(failures), { mode: 0o600 }); renameSync(temporary, budgetPath);
109
+ if (identity) {
110
+ receipts.push(identity.token);
111
+ const temporary = `${receiptsPath}.${process.pid}`;
112
+ // Budget commits first: interruption can overcount a fault but cannot erase a spent restart.
113
+ writeFileSync(temporary, JSON.stringify(receipts.slice(-64)), { mode: 0o600 }); renameSync(temporary, receiptsPath);
114
+ }
115
+ };
116
+ if (rebind) {
117
+ const current = inspectDaemonOwner(serverDir);
118
+ const guardian = inspectDaemonOwner(serverDir, "guardian-owner");
119
+ if (current.status !== "live" || guardian.status !== "live" || !sameOwner(current.owner, rebind)
120
+ || !ownerIdentityVerified(current.owner) || !ownerIdentityVerified(guardian.owner)) throw new Error("runtime-unhealthy: rebind target changed or identity is unverified");
121
+ if (await bindServer(serverDir, rebind, guardian.owner)) return;
122
+ // Socket loss is not process-death proof. Never signal or replace an adopted live owner.
123
+ while (true) {
124
+ const current = inspectDaemonOwner(serverDir);
125
+ if (current.status === "missing" || current.status === "dead") break;
126
+ if (current.status !== "live" || !sameOwner(current.owner, rebind)) throw new Error("runtime-unhealthy: rebound owner changed or is unverified");
127
+ await delay(100);
128
+ }
129
+ let checkpoint;
130
+ try { checkpoint = JSON.parse(readFileSync(join(serverDir, "clean-stop.json"), "utf8")); } catch { /* Missing proof is a crash. */ }
131
+ if (checkpoint?.token === rebind.token && checkpoint?.pid === rebind.pid) return;
132
+ fault(rebind);
133
+ await delay(1000 * 2 ** Math.min(2, Math.max(0, failures.length - 1)));
134
+ }
135
+ const previous = inspectDaemonOwner(serverDir);
136
+ if (previous.status === "dead") {
137
+ let checkpoint;
138
+ try { checkpoint = JSON.parse(readFileSync(join(serverDir, "clean-stop.json"), "utf8")); } catch { /* Missing proof is a crash. */ }
139
+ if (checkpoint?.token !== previous.owner.token) fault(previous.owner);
140
+ }
141
+ for (;;) {
142
+ failures = failures.filter(time => Date.now() - time < 60_000);
143
+ if (failures.length >= 3) throw new Error("runtime-unavailable: guardian restart budget exhausted (3 failures in 60 seconds)");
144
+ // A live or unverified server cannot be adopted as a new child or replaced.
145
+ const owner = inspectDaemonOwner(serverDir);
146
+ if (owner.status === "live" || owner.status === "ambiguous") throw new Error("runtime-unhealthy: existing server owner was not replaced");
147
+ let cleanToken: string | undefined;
148
+ let ready = false;
149
+ let exitCode: number | null = null;
150
+ // The server survives guardian loss. It must not inherit a caller's pipe,
151
+ // otherwise an exited guardian can leave that caller waiting forever for EOF.
152
+ const inheritedLog = fstatSync(2).isFile();
153
+ const output = inheritedLog ? 2 : openSync(join(serverDir, "daemon.log"), "a", 0o600);
154
+ let child: ReturnType<typeof spawn>;
155
+ try {
156
+ child = spawn(process.execPath, [...process.execArgv, fileURLToPath(new URL("../cli.ts", import.meta.url)), "--agent", "pi"], {
157
+ env: { ...process.env, PI_SERVER_GUARDED_CHILD: "1", PI_SERVER_GUARDIAN_REBIND: "" }, stdio: ["ignore", output, output, "ipc"],
158
+ });
159
+ } finally { if (!inheritedLog) closeSync(output); }
160
+ child.on("message", message => {
161
+ const record = message as { type?: string; token?: string };
162
+ if (record?.type === "runtime-clean-stop" && typeof record.token === "string") cleanToken = record.token;
163
+ if (record?.type === "runtime-ready" && typeof record.token === "string") {
164
+ const owner = inspectDaemonOwner(serverDir);
165
+ ready = owner.status === "live" && owner.owner.pid === child.pid && owner.owner.token === record.token;
166
+ }
167
+ });
168
+ let stopping = false;
169
+ const stop = () => { stopping = true; child.kill("SIGTERM"); };
170
+ process.on("SIGTERM", stop); process.on("SIGINT", stop);
171
+ try {
172
+ await new Promise<void>(resolve => { child.once("error", () => resolve()); child.once("exit", code => { exitCode = code; resolve(); }); });
173
+ } finally { process.off("SIGTERM", stop); process.off("SIGINT", stop); }
174
+ let checkpoint;
175
+ try { checkpoint = JSON.parse(readFileSync(join(serverDir, "clean-stop.json"), "utf8")); } catch { /* Missing proof is a crash. */ }
176
+ if (cleanToken && checkpoint?.token === cleanToken && checkpoint?.pid === child.pid && checkpoint?.reason === "clean-stop") return;
177
+ if (stopping) {
178
+ if (!ready) throw new Error("runtime-unavailable: startup stopped before readiness; no successful start was established");
179
+ return;
180
+ }
181
+ const dead = inspectDaemonOwner(serverDir);
182
+ fault(dead.status === "dead" ? dead.owner : undefined);
183
+ if (!ready && exitCode !== null && exitCode !== 0) {
184
+ throw new Error(`runtime-unavailable: server failed before readiness (exit ${exitCode}); inspect ${join(serverDir, "daemon.log")}`);
185
+ }
186
+ await delay(1000 * 2 ** (failures.length - 1));
187
+ }
188
+ } finally { release(); }
189
+ }
@@ -0,0 +1,27 @@
1
+ import { readFileSync, statSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { createHash } from "node:crypto";
4
+
5
+ const caches = new Map<string, { revision: string; config: any }>();
6
+
7
+ /** Observe user preferences without invoking the legacy settings migration. */
8
+ export async function readHealthConfig(agentDir: string, needed = true) {
9
+ const legacy = join(agentDir, "extensions/pi-better-subagents-config.json");
10
+ const revision = createHash("sha256").update(JSON.stringify([join(agentDir, "settings.json"), legacy].map(path => {
11
+ try { const info = statSync(path, { bigint: true }); return [info.ino, info.size, info.mtimeNs, info.ctimeNs].map(String); }
12
+ catch (error) { return (error as NodeJS.ErrnoException).code; }
13
+ }))).digest("hex");
14
+ // Empty inventories have no health projections; do not initialize the SDK for them.
15
+ if (!needed) return { revision, config: {} };
16
+ if (caches.get(agentDir)?.revision === revision) return caches.get(agentDir)!;
17
+ let config: any = {};
18
+ try {
19
+ const { readHarnessSetting } = await import("./domain/shared-harness-settings.mjs");
20
+ config = readHarnessSetting("subagents", { agentDir: () => agentDir });
21
+ if (config === undefined) config = JSON.parse(readFileSync(legacy, "utf8"));
22
+ if (!config || typeof config !== "object" || Array.isArray(config)) config = {};
23
+ } catch { config = {}; }
24
+ const observation = { revision, config }; caches.set(agentDir, observation);
25
+ if (caches.size > 8) caches.delete(caches.keys().next().value!);
26
+ return observation;
27
+ }
@@ -0,0 +1,34 @@
1
+ import { Duplex } from "node:stream";
2
+ import { checkHello } from "../handshake.ts";
3
+ import { WorkClient } from "./work-client.mjs";
4
+ import type { WorkQueryExecutor } from "./query-executor.ts";
5
+
6
+ /** Hosted reads use the same bounded executor and client sequencing without a socket. */
7
+ export function createLocalWorkClient(executor: WorkQueryExecutor, agentDir: string): WorkClient {
8
+ let connection: ReturnType<WorkQueryExecutor["connect"]>;
9
+ const transport = new Duplex({
10
+ read() {},
11
+ write(chunk, _encoding, done) {
12
+ const command = JSON.parse(String(chunk));
13
+ if (command.type === "hello") {
14
+ const result = checkHello(command, { agentDir, instanceId: executor.instanceId });
15
+ this.push(JSON.stringify({ id: command.id, type: "response", success: result.ok, ...result }) + "\n");
16
+ } else {
17
+ void connection.handle(command).then(
18
+ result => { if (!this.destroyed) this.push(`{"id":${JSON.stringify(command.id)},"success":true,"data":${result.json}}\n`); },
19
+ error => { if (!this.destroyed) this.push(JSON.stringify({ id: command.id, success: false, error: String(error) }) + "\n"); },
20
+ );
21
+ }
22
+ done();
23
+ },
24
+ destroy(error, done) { connection?.close(); done(error); },
25
+ });
26
+ // The worker's event output feeds the readable side; client requests use the writable side.
27
+ const events = new Duplex({
28
+ read() {},
29
+ write(chunk, _encoding, done) { if (!transport.destroyed) transport.push(chunk); done(); },
30
+ });
31
+ connection = executor.connect(events);
32
+ transport.once("close", () => events.destroy());
33
+ return new WorkClient(transport, agentDir, ["runtime-background-state-v1"]);
34
+ }
@@ -0,0 +1,76 @@
1
+ import type { Socket } from "node:net";
2
+ import type { WorkReadModel, WorkScope } from "./read-model.ts";
3
+
4
+ export function workScope(input: unknown): WorkScope {
5
+ if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("A runtime scope object is required");
6
+ const value = input as Record<string, unknown>;
7
+ for (const key of ["cwd", "sessionId", "id", "cursor"]) if (value[key] !== undefined && (typeof value[key] !== "string" || String(value[key]).length > 4096)) throw new Error(`Invalid scope ${key}`);
8
+ if (value.sessionId && !value.cwd) throw new Error("Session scope requires cwd");
9
+ if (value.limit !== undefined && (!Number.isSafeInteger(value.limit) || Number(value.limit) < 1 || Number(value.limit) > 200)) throw new Error("Runtime limit must be from 1 to 200");
10
+ if (value.active !== undefined && typeof value.active !== "boolean") throw new Error("Invalid active scope");
11
+ if (value.endedAfter !== undefined && (typeof value.endedAfter !== "number" || !Number.isFinite(value.endedAfter))) throw new Error("Invalid history deadline");
12
+ if (value.detail !== undefined && (typeof value.detail !== "boolean" || (value.detail && !value.id))) throw new Error("Detail requires an exact run ID");
13
+ const statuses = value.background === true ? ["starting", "running", "succeeded", "failed", "cancelled", "timed_out", "lost"] : ["running", "waiting", "completed", "failed", "cancelled", "killed", "exited", "orphaned", "lost"];
14
+ if (value.statuses !== undefined && (!Array.isArray(value.statuses) || value.statuses.length > statuses.length || value.statuses.some(s => typeof s !== "string" || !statuses.includes(s)))) throw new Error("Invalid assignment status filter");
15
+ if (value.background !== undefined && typeof value.background !== "boolean") throw new Error("Invalid background scope");
16
+ if (value.processId !== undefined && (!Number.isSafeInteger(value.processId) || Number(value.processId) <= 0 || value.background !== true)) throw new Error("Invalid background process identity");
17
+ if (value.backgroundHistory !== undefined && typeof value.backgroundHistory !== "boolean") throw new Error("Invalid background history scope");
18
+ if (value.backgroundAll !== undefined && (typeof value.backgroundAll !== "boolean" || value.backgroundAll && !value.backgroundHistory)) throw new Error("All backgrounds requires an explicit history query");
19
+ return { processId: value.processId as number | undefined, backgroundAll: value.backgroundAll as boolean | undefined, backgroundHistory: value.backgroundHistory as boolean | undefined, background: value.background as boolean | undefined, cwd: value.cwd as string | undefined, sessionId: value.sessionId as string | undefined, id: value.id as string | undefined,
20
+ cursor: value.cursor as string | undefined, limit: value.limit as number | undefined, active: value.active as boolean | undefined, endedAfter: value.endedAfter as number | undefined, detail: value.detail as boolean | undefined, statuses: value.statuses as string[] | undefined };
21
+ }
22
+
23
+ /** Snapshot capture and observer installation execute at one synchronous serial point. */
24
+ export class WorkQueries {
25
+ private dispose?: () => void;
26
+ private paused = false;
27
+ private model: WorkReadModel;
28
+ private socket: Socket;
29
+ private maxQueuedBytes: number;
30
+ constructor(model: WorkReadModel, socket: Socket, maxQueuedBytes = 4 * 1024 * 1024) {
31
+ this.model = model; this.socket = socket; this.maxQueuedBytes = maxQueuedBytes;
32
+ // A failed peer owns no usable subscription; terminate its queued writes too.
33
+ socket.on("error", () => { this.close(); socket.destroy(); });
34
+ socket.once("close", () => this.close());
35
+ socket.on("drain", () => {
36
+ if (!this.paused) return;
37
+ this.paused = false;
38
+ this.event({ type: "resync_required", reason: "slow-reader", instanceId: this.model.instanceId });
39
+ });
40
+ }
41
+ private event(event: unknown) {
42
+ if (this.socket.destroyed || this.paused) return;
43
+ if (this.socket.writableLength > this.maxQueuedBytes) { this.paused = true; return; }
44
+ const line = JSON.stringify({ type: "event", event }) + "\n";
45
+ if (Buffer.byteLength(line) > 4 * 1024 * 1024) {
46
+ this.close();
47
+ this.socket.write(JSON.stringify({ type: "event", event: { type: "resync_required", reason: "snapshot-too-large: narrow the scope or limit" } }) + "\n");
48
+ return;
49
+ }
50
+ this.socket.write(line);
51
+ }
52
+ handle(command: Record<string, unknown>) {
53
+ if (command.type === "runtime_unsubscribe") { this.close(); return { unsubscribed: true }; }
54
+ if (command.type === "runtime_get_metrics") return { ...this.model.metrics };
55
+ const scope = workScope(command.scope);
56
+ const snapshot = this.model.snapshot(scope);
57
+ if (Buffer.byteLength(JSON.stringify(snapshot)) > 4 * 1024 * 1024 - 1024) throw new Error("state-degraded: snapshot exceeds the 4 MiB frame allowance; narrow the scope or limit");
58
+ if (command.type === "runtime_subscribe") {
59
+ this.close();
60
+ this.dispose = this.model.onChange(() => {
61
+ try {
62
+ this.event({ type: "runtime_snapshot", snapshot: this.model.snapshot({ ...scope, cursor: undefined }) });
63
+ } catch (error) {
64
+ // A stale detail or oversized scope must not fail shared reconciliation.
65
+ this.close();
66
+ this.event({ type: "resync_required", reason: String(error).slice(0, 512), instanceId: this.model.instanceId });
67
+ }
68
+ }, scope);
69
+ if (command.sinceSeq !== undefined && (command.instanceId !== snapshot.instanceId || command.sinceSeq !== snapshot.seq)) {
70
+ return { ...snapshot, resyncRequired: true, resyncReason: command.instanceId !== snapshot.instanceId ? "instance-changed" : "replay-truncated" };
71
+ }
72
+ }
73
+ return snapshot;
74
+ }
75
+ close() { this.dispose?.(); this.dispose = undefined; }
76
+ }