pi-better-server 0.2.2 → 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 (84) 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/shared-ssh-core/index.ts +30 -1
  81. package/src/startup/activation.ts +32 -5
  82. package/src/startup/ensure.ts +13 -1
  83. package/src/startup/install.ts +2 -0
  84. package/src/version.ts +4 -0
@@ -0,0 +1,357 @@
1
+ import { processMatchesStart } from "../daemon-owner.ts";
2
+ import { createHash } from "node:crypto";
3
+ import { readdir, readFile, stat } from "node:fs/promises";
4
+ import { watch, type FSWatcher } from "node:fs";
5
+ import { join, resolve, sep } from "node:path";
6
+ import { realpathSync, statSync } from "node:fs";
7
+ import { tmpdir } from "node:os";
8
+ import { createRequire } from "node:module";
9
+ import { setImmediate as yieldTurn } from "node:timers/promises";
10
+ import { createAssignmentProjector } from "./domain/assignment-projection.mjs";
11
+ import { createAssignmentReader } from "./domain/assignment-observation.mjs";
12
+ import { parseArchivedAttempt, parseArchivedSessionState } from "./domain/session-store.mjs";
13
+ import { parseRun, readRunTranscript } from "./domain/parse.mjs";
14
+ import { fmtSpend } from "./domain/widget.mjs";
15
+ import { effectiveStatus } from "./domain/process-status.mjs";
16
+ import { extractChildEventFactsFromLog, healthThresholdsForConfig } from "./domain/health-observation.mjs";
17
+ import { BackgroundObservation } from "./background.ts";
18
+ import { readHealthConfig } from "./health-config.ts";
19
+
20
+ export interface WorkScope { processId?: number; backgroundAll?: boolean; background?: boolean; backgroundHistory?: boolean; cwd?: string; sessionId?: string; id?: string; statuses?: string[]; active?: boolean; endedAfter?: number; detail?: boolean; limit?: number; cursor?: string }
21
+ export interface WorkSnapshot {
22
+ instanceId: string; runtimeEpoch: string; scopeRevision: string; seq: number;
23
+ observedRevisionVector: { inventory: number; coordinator: string; healthConfig: string };
24
+ status: "ready" | "rebuilding" | "degraded"; reason?: string;
25
+ rows: Array<{ meta: any; assignment: any; sourceRevision: string }>;
26
+ nextCursor?: string; activity: { active: number }; nextDeadline: number | null;
27
+ totalMatching: number;
28
+ backgroundIndex?: any;
29
+ resyncRequired?: boolean; resyncReason?: string;
30
+ }
31
+ const hash = (value: unknown) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
32
+ const safeId = /^[A-Za-z0-9_-]+$/;
33
+
34
+ /** Reconstructable query state. It never authorizes execution or writes source records. */
35
+ export class WorkReadModel {
36
+ private background: BackgroundObservation;
37
+ private db: any;
38
+ private reader: ReturnType<typeof createAssignmentReader>;
39
+ private files = new Map<string, { signature: string; meta: any }>();
40
+ private projected = new Map<string, { meta: any; assignment: any; sourceRevision: string; display?: { spend: string; tool: string }; health?: any }>();
41
+ private logs = new Map<string, string>();
42
+ private processes = new Map<string, string>();
43
+ private healthRevision = "";
44
+ private details = new Map<string, { revision: string; value: any }>();
45
+ private watchers: FSWatcher[] = [];
46
+ private listeners = new Set<() => void>();
47
+ private timer?: ReturnType<typeof setInterval>;
48
+ private pending?: Promise<void>;
49
+ private dirty = false;
50
+ private closed = false;
51
+ private inventory = 0;
52
+ private coordinator = "unknown";
53
+ private coordinatorConversations?: Map<string, string>;
54
+ private revision = 0;
55
+ private state: WorkSnapshot["status"] = "rebuilding";
56
+ private reason: string | undefined = "Initial source inventory is rebuilding.";
57
+ readonly metrics = { inventories: 0, metadataReads: 0, projections: 0, coordinatorConnections: 1, indexConnections: 1 };
58
+ readonly runs: string;
59
+ readonly archives: string;
60
+ readonly markers: string;
61
+ readonly agentDir: string;
62
+ readonly instanceId: string;
63
+
64
+ constructor(agentDir: string, instanceId: string, options: { supervisorDirectory?: string; baseDir?: string; durableDir?: string; intervalMs?: number } = {}) {
65
+ this.agentDir = agentDir; this.instanceId = instanceId;
66
+ const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
67
+ this.db = new DatabaseSync(":memory:");
68
+ this.background = new BackgroundObservation(agentDir, options.supervisorDirectory, this.db, () => this.publish());
69
+ this.db.exec(`CREATE TABLE rows (id TEXT PRIMARY KEY, cwd TEXT, origin_cwd TEXT, origin_session TEXT,
70
+ started REAL, state TEXT, active INTEGER, ended REAL, payload TEXT);
71
+ CREATE INDEX work_folder ON rows(cwd, started DESC, id DESC);
72
+ CREATE INDEX work_origin ON rows(origin_cwd, origin_session, started DESC, id DESC);
73
+ CREATE INDEX work_active ON rows(active, started DESC, id DESC);
74
+ CREATE INDEX work_terminal ON rows(active, ended, started DESC, id DESC);
75
+ CREATE INDEX work_state ON rows(state, started DESC, id DESC);`);
76
+ this.reader = createAssignmentReader(join(agentDir, "operation-coordinator.sqlite"));
77
+ this.runs = join(options.baseDir ?? join(realpathSync(tmpdir()), "pi-better-subagents"), "runs");
78
+ this.archives = join(options.durableDir ?? process.env.PI_SUBAGENT_DURABLE_DIR ?? join(agentDir, "subagents"), "attempts");
79
+ this.markers = join(this.archives, "../session-state");
80
+ // Notifications accelerate discovery; a shared bounded inventory repairs lost hints.
81
+ for (const path of [this.runs, this.archives, this.markers]) {
82
+ try {
83
+ const watcher = watch(path, { recursive: true }, () => { void this.reconcile(); });
84
+ watcher.on("error", () => this.invalidate("Watcher overflow or failure; reconciling source inventory."));
85
+ this.watchers.push(watcher);
86
+ } catch { /* Missing roots are discovered by the compatibility inventory. */ }
87
+ }
88
+ this.timer = setInterval(() => { void this.reconcile(); }, options.intervalMs ?? 1000);
89
+ this.timer.unref();
90
+ }
91
+
92
+ onChange(listener: () => void, scope?: WorkScope) {
93
+ const release = scope?.background ? this.background.retain(scope) : undefined;
94
+ this.listeners.add(listener);
95
+ return () => { this.listeners.delete(listener); release?.(); };
96
+ }
97
+ get backgroundMetrics() { return { ...this.background.metrics, scopes: this.background.scopeCount, history: this.background.historyMetrics }; }
98
+ observation(reasons = this.livenessReasons({ refresh: false })) {
99
+ return { status: this.state, reason: this.reason, observedAt: Date.now(), reasons };
100
+ }
101
+ livenessReasons(options: { refresh?: boolean } = {}) {
102
+ return [
103
+ ...[...this.projected.values()].filter(row => row.meta.status === "running"
104
+ && processMatchesStart(row.meta.pid, row.meta.pidStartTime))
105
+ .map(row => ({ kind: "worker", id: row.meta.id, owner: row.meta.callbackOrigin,
106
+ lastProgressAt: row.meta.startedAt, nextDeadline: null, recovery: "observe-existing-worker" })),
107
+ ...this.background.livenessReasons(options),
108
+ ];
109
+ }
110
+ async ensureId(id: string) {
111
+ if (!safeId.test(id)) throw new Error("Invalid run ID");
112
+ if (this.state === "rebuilding") await this.reconcile();
113
+ if (this.db.prepare("SELECT id FROM rows WHERE id = ?").get(id)) return;
114
+ try { await stat(join(this.runs, id, "meta.json")); }
115
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return; throw error; }
116
+ // An exact-ID read may race the writer's atomic replacement during inventory.
117
+ // Join the bounded repair passes before treating that freshly written ID as absent.
118
+ for (let attempt = 0; attempt < 3; attempt++) {
119
+ await this.reconcile();
120
+ if (this.db.prepare("SELECT id FROM rows WHERE id = ?").get(id) || !this.dirty && !this.pending) break;
121
+ await yieldTurn();
122
+ }
123
+ }
124
+ invalidate(reason: string) {
125
+ this.state = "degraded"; this.reason = reason;
126
+ this.publish();
127
+ void this.reconcile();
128
+ }
129
+ private publish() { this.revision++; for (const listener of this.listeners) listener(); }
130
+
131
+ reconcile(): Promise<void> {
132
+ if (this.closed) return Promise.resolve();
133
+ if (this.pending) { this.dirty = true; return this.pending; }
134
+ this.pending = (async () => {
135
+ for (let pass = 0; pass < 2; pass++) {
136
+ this.dirty = false;
137
+ await this.scan();
138
+ if (!this.dirty || this.closed) break;
139
+ }
140
+ })().finally(() => {
141
+ this.pending = undefined;
142
+ if (this.dirty && !this.closed) { this.dirty = false; void this.reconcile(); }
143
+ });
144
+ return this.pending;
145
+ }
146
+
147
+ private async scan() {
148
+ this.metrics.inventories++;
149
+ if (this.background.refresh()) this.publish();
150
+ try {
151
+ const next = new Map<string, { signature: string; meta: any }>();
152
+ let batch = 0;
153
+ for (const [directory, archived] of [[this.markers, true], [this.archives, true], [this.runs, false]] as const) {
154
+ let names: string[];
155
+ try { names = await readdir(directory); }
156
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; throw error; }
157
+ for (const name of names) {
158
+ const id = archived ? name.replace(/\.json$/, "") : name;
159
+ if (!safeId.test(id) || (archived && !name.endsWith(".json"))) continue;
160
+ const path = archived ? join(directory, name) : join(directory, name, "meta.json");
161
+ try {
162
+ const info = await stat(path, { bigint: true });
163
+ const signature = `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
164
+ let entry = this.files.get(path);
165
+ if (entry?.signature !== signature) {
166
+ this.metrics.metadataReads++;
167
+ const raw = await readFile(path, "utf8");
168
+ if (directory === this.markers) {
169
+ const marker = parseArchivedSessionState(raw, id);
170
+ if (!marker) throw new Error(`Unusable session marker: ${id}`);
171
+ entry = { signature, meta: marker };
172
+ next.set(path, entry);
173
+ continue;
174
+ }
175
+ const meta = archived ? parseArchivedAttempt(raw, id, join(this.archives, "../sessions")) : JSON.parse(raw);
176
+ if (meta?.id !== id || typeof meta.cwd !== "string" || !Number.isFinite(meta.startedAt) || typeof meta.status !== "string") throw new Error(`Unusable run record: ${id}`);
177
+ entry = { signature, meta };
178
+ }
179
+ next.set(path, entry!);
180
+ } catch (error) {
181
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
182
+ }
183
+ if (++batch % 256 === 0) await yieldTurn();
184
+ if (this.closed) return;
185
+ }
186
+ }
187
+ let coordinator: string;
188
+ try { coordinator = this.reader.revision(); } catch { coordinator = "unknown"; }
189
+ const coordinatorConversations = coordinator === this.coordinator ? this.coordinatorConversations : this.reader.conversationRevisions();
190
+ const logs = new Map<string, string>();
191
+ const processes = new Map<string, string>();
192
+ const logFamilies = new Set<string>();
193
+ for (const [path, entry] of next) {
194
+ if (!path.startsWith(this.runs + sep)) continue;
195
+ let signature = this.logs.get(entry.meta.id);
196
+ {
197
+ try {
198
+ const info = await stat(join(this.runs, entry.meta.id, "output.log"), { bigint: true });
199
+ signature = `${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
200
+ } catch (error) { signature = (error as NodeJS.ErrnoException).code === "ENOENT" ? "missing" : "unverified"; }
201
+ }
202
+ logs.set(entry.meta.id, signature);
203
+ if (signature !== this.logs.get(entry.meta.id)) logFamilies.add(JSON.stringify([entry.meta.sessionId, entry.meta.cwd]));
204
+ const status = effectiveStatus(entry.meta); processes.set(entry.meta.id, status);
205
+ if (status !== this.processes.get(entry.meta.id)) logFamilies.add(JSON.stringify([entry.meta.sessionId, entry.meta.cwd]));
206
+ }
207
+ const healthConfig = await readHealthConfig(this.agentDir, next.size > 0);
208
+ const changed = next.size !== this.files.size || [...next].some(([path, entry]) => this.files.get(path)?.signature !== entry.signature);
209
+ if (!changed && !logFamilies.size && coordinator === this.coordinator && healthConfig.revision === this.healthRevision && this.state === "ready") return;
210
+ const metas = new Map<string, any>();
211
+ const markers = new Map([...next].filter(([path]) => path.startsWith(this.markers + sep)).map(([, entry]) => [entry.meta.sessionId, entry.meta]));
212
+ for (const [path, entry] of next) {
213
+ if (path.startsWith(this.markers + sep)) continue;
214
+ const marker = markers.get(entry.meta.sessionId);
215
+ if (path.startsWith(this.archives + sep) && marker && marker.attemptId !== entry.meta.id && marker.startedAt >= entry.meta.startedAt) continue;
216
+ metas.set(entry.meta.id, entry.meta);
217
+ }
218
+ const attempts = [...metas.values()];
219
+ const affected = new Set<string>(logFamilies);
220
+ const family = (meta: any) => JSON.stringify([meta.sessionId, meta.cwd]);
221
+ for (const [path, entry] of [...this.files, ...next]) {
222
+ if (this.files.get(path)?.signature !== next.get(path)?.signature) affected.add(family(entry.meta));
223
+ }
224
+ if (coordinator !== this.coordinator) for (const meta of attempts) {
225
+ if (!(meta.assignment || meta.operations || meta.park)) continue;
226
+ const owner = JSON.stringify([meta.operations?.conversationId ?? meta.sessionId, meta.operations?.workspace ?? meta.cwd]);
227
+ if (!coordinatorConversations || !this.coordinatorConversations ||
228
+ coordinatorConversations.get(owner) !== this.coordinatorConversations.get(owner)) affected.add(family(meta));
229
+ }
230
+ const project = createAssignmentProjector({ attempts, observe: (owner: any) => this.reader.read(owner) });
231
+ const rows = [];
232
+ for (const meta of attempts) {
233
+ let row = this.projected.get(meta.id);
234
+ if (!row || !row.assignment.verified || healthConfig.revision !== this.healthRevision || affected.has(family(meta))) {
235
+ this.metrics.projections++;
236
+ const assignment = project(meta, processes.get(meta.id) ?? meta.status);
237
+ const parsed = logs.get(meta.id) && logs.get(meta.id) !== "missing" ? parseRun(meta.id, { logPath: join(this.runs, meta.id, "output.log") }) : undefined;
238
+ const display = { spend: parsed ? fmtSpend(parsed.usage) : "", tool: parsed?.toolCalls.at(-1) ?? "" };
239
+ const health = logs.has(meta.id) ? { ...extractChildEventFactsFromLog(meta.id, { logPath: join(this.runs, meta.id, "output.log") }), thresholds: healthThresholdsForConfig(healthConfig.config) } : undefined;
240
+ row = { meta, assignment, display, health, sourceRevision: hash([meta, assignment.revision, display, health]) };
241
+ }
242
+ rows.push(row);
243
+ if (++batch % 256 === 0) await yieldTurn();
244
+ }
245
+ let after: string;
246
+ try { after = this.reader.revision(); } catch { after = "unknown"; }
247
+ if (after !== coordinator) { this.state = "degraded"; this.reason = "Coordinator changed during observation; retrying."; this.dirty = true; this.publish(); return; }
248
+ for (const [path, entry] of next) {
249
+ if (!affected.has(family(entry.meta))) continue;
250
+ const info = await stat(path, { bigint: true });
251
+ if (`${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}` !== entry.signature) {
252
+ this.dirty = true;
253
+ throw new Error("Source changed during observation; retaining the previous snapshot while reconciling.");
254
+ }
255
+ if (++batch % 256 === 0) await yieldTurn();
256
+ }
257
+ if (this.closed) return;
258
+ this.db.exec("BEGIN");
259
+ const insert = this.db.prepare("INSERT OR REPLACE INTO rows VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
260
+ const remove = this.db.prepare("DELETE FROM rows WHERE id = ?");
261
+ let semanticChange = false;
262
+ try {
263
+ for (const id of this.projected.keys()) if (!metas.has(id)) { remove.run(id); semanticChange = true; }
264
+ for (const row of rows) {
265
+ if (this.projected.get(row.meta.id)?.sourceRevision === row.sourceRevision) continue;
266
+ semanticChange = true;
267
+ const m = row.meta;
268
+ insert.run(m.id, m.cwd, m.callbackOrigin?.cwd ?? m.cwd, m.callbackOrigin?.sessionId ?? null,
269
+ m.startedAt, row.assignment.state, ["running", "waiting"].includes(row.assignment.state) ? 1 : 0, m.endedAt ?? m.lostAt ?? null, JSON.stringify(row));
270
+ }
271
+ this.db.exec("COMMIT");
272
+ } catch (error) { this.db.exec("ROLLBACK"); throw error; }
273
+ this.files = next; this.logs = logs; this.processes = processes; this.healthRevision = healthConfig.revision; this.coordinator = coordinator; this.inventory++;
274
+ this.coordinatorConversations = coordinatorConversations;
275
+ this.projected = new Map(rows.map(row => [row.meta.id, row]));
276
+ const previousState = this.state;
277
+ const previousReason = this.reason;
278
+ this.state = rows.some(row => !row.assignment.verified) ? "degraded" : "ready";
279
+ this.reason = this.state === "degraded" ? "Some assignment sources could not be verified." : undefined;
280
+ if (semanticChange || previousState !== this.state || previousReason !== this.reason) this.publish();
281
+ } catch (error) {
282
+ if (this.closed) return;
283
+ this.state = "degraded"; this.reason = String(error).slice(0, 512); this.publish();
284
+ }
285
+ }
286
+
287
+ snapshot(scope: WorkScope = {}): WorkSnapshot {
288
+ if (scope.background) {
289
+ if (scope.backgroundHistory && this.background.refresh()) this.publish();
290
+ const index = scope.backgroundHistory ? this.background.historyIndex(scope) : undefined;
291
+ const tasks = this.background.read(scope, index);
292
+ const status = this.background.status === "degraded" ? "degraded" : index ? this.background.historyStatus : this.background.status;
293
+ const active = (index ? this.background.read({ ...scope, backgroundHistory: false, active: true }) : tasks).filter(task => task.durable ? task.active : task.status === "running").length;
294
+ this.metrics.coordinatorConnections = 1 + this.background.connectionCount;
295
+ return { instanceId: this.instanceId, runtimeEpoch: this.instanceId, scopeRevision: hash([scope, tasks, status, index?.page, active]), seq: this.revision,
296
+ observedRevisionVector: { inventory: this.inventory, coordinator: this.coordinator, healthConfig: this.healthRevision },
297
+ status, reason: this.background.reason ?? (index ? this.background.historyReason : undefined),
298
+ rows: tasks.map(meta => ({ meta, assignment: null, sourceRevision: hash(meta) })), totalMatching: index?.page.total ?? tasks.length,
299
+ ...(index?.page.nextCursor ? { nextCursor: index.page.nextCursor } : {}),
300
+ ...(index ? { backgroundIndex: index } : {}),
301
+ activity: { active }, nextDeadline: null };
302
+ }
303
+ const clauses: string[] = [], args: any[] = [];
304
+ if (scope.id) { clauses.push("id = ?"); args.push(scope.id); }
305
+ if (scope.sessionId) { clauses.push("origin_session = ? AND origin_cwd = ?"); args.push(scope.sessionId, scope.cwd); }
306
+ else if (scope.cwd) { const cwd = resolve(scope.cwd); clauses.push("(cwd = ? OR substr(cwd, 1, ?) = ?)"); args.push(cwd, (cwd.endsWith(sep) ? cwd : cwd + sep).length, cwd.endsWith(sep) ? cwd : cwd + sep); }
307
+ // Activity describes the scope, independently of history filters and pagination.
308
+ const active = Number(this.db.prepare(`SELECT count(*) AS n FROM rows WHERE ${[...clauses, "active = 1"].join(" AND ")}`).get(...args).n);
309
+ if (scope.active !== undefined) { clauses.push("active = ?"); args.push(scope.active ? 1 : 0); }
310
+ if (scope.endedAfter !== undefined) { clauses.push("(ended IS NULL OR ended >= ?)"); args.push(scope.endedAfter); }
311
+ if (scope.statuses?.length) { clauses.push(`state IN (${scope.statuses.map(() => "?").join(",")})`); args.push(...scope.statuses); }
312
+ const key = hash({ ...scope, cursor: undefined });
313
+ const totalMatching = Number(this.db.prepare(`SELECT count(*) AS n FROM rows ${clauses.length ? "WHERE " + clauses.join(" AND ") : ""}`).get(...args).n);
314
+ if (scope.cursor) {
315
+ let cursor;
316
+ try { cursor = JSON.parse(Buffer.from(scope.cursor, "base64url").toString()); } catch { throw new Error("Invalid runtime cursor"); }
317
+ if (!Array.isArray(cursor) || cursor[0] !== key || cursor[1] !== this.instanceId || cursor[2] !== this.revision) throw new Error("resync_required: cursor snapshot changed");
318
+ clauses.push("(started < ? OR (started = ? AND id < ?))"); args.push(cursor[3], cursor[3], cursor[4]);
319
+ }
320
+ const limit = Math.max(1, Math.min(200, Number.isSafeInteger(scope.limit) ? scope.limit! : 50));
321
+ const records = this.db.prepare(`SELECT payload, started, id FROM rows ${clauses.length ? "WHERE " + clauses.join(" AND ") : ""} ORDER BY started DESC, id DESC LIMIT ?`).all(...args, limit + 1);
322
+ const page = records.slice(0, limit), last = page.at(-1);
323
+ return { instanceId: this.instanceId, runtimeEpoch: this.instanceId, scopeRevision: hash([key, this.revision]), seq: this.revision,
324
+ observedRevisionVector: { inventory: this.inventory, coordinator: this.coordinator, healthConfig: this.healthRevision }, status: this.state, reason: this.reason,
325
+ totalMatching,
326
+ rows: page.map((record: any) => {
327
+ const row = JSON.parse(record.payload);
328
+ if (scope.detail && scope.id) {
329
+ let cached = this.details.get(row.meta.id);
330
+ if (!cached || cached.revision !== row.sourceRevision) {
331
+ const logPath = join(this.runs, row.meta.id, "output.log");
332
+ const expectedLog = this.logs.get(row.meta.id) ?? "missing";
333
+ const signature = () => {
334
+ try { const info = statSync(logPath, { bigint: true }); return `${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`; }
335
+ catch (error) { return (error as NodeJS.ErrnoException).code === "ENOENT" ? "missing" : "unverified"; }
336
+ };
337
+ if (signature() !== expectedLog) throw new Error("state-degraded: log changed since the indexed observation; resync required");
338
+ const value = { parsed: parseRun(row.meta.id, { logPath }), transcript: readRunTranscript(row.meta.id, { logPath }) };
339
+ if (signature() !== expectedLog) throw new Error("state-degraded: log changed during detail observation; resync required");
340
+ if (Buffer.byteLength(JSON.stringify(value)) > 3 * 1024 * 1024) throw new Error("state-degraded: detail exceeds the bounded snapshot allowance");
341
+ cached = { revision: row.sourceRevision, value }; this.details.set(row.meta.id, cached);
342
+ if (this.details.size > 16) this.details.delete(this.details.keys().next().value!);
343
+ }
344
+ row.detail = cached.value;
345
+ }
346
+ return { ...row, cursor: Buffer.from(JSON.stringify([key, this.instanceId, this.revision, record.started, record.id])).toString("base64url") };
347
+ }),
348
+ ...(records.length > limit ? { nextCursor: Buffer.from(JSON.stringify([key, this.instanceId, this.revision, last.started, last.id])).toString("base64url") } : {}),
349
+ activity: { active }, nextDeadline: null };
350
+ }
351
+
352
+ async close() {
353
+ this.closed = true; if (this.timer) clearInterval(this.timer);
354
+ for (const watcher of this.watchers) watcher.close();
355
+ await this.pending; this.listeners.clear(); await this.background.close(); this.reader.close(); this.db.close();
356
+ }
357
+ }
@@ -0,0 +1,29 @@
1
+ import { linkSync, mkdirSync, readFileSync, realpathSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+
5
+ /** Transport selection is durable and independent of installation or package version. */
6
+ export function runtimeRoot(agentDir: string, requestedServerDir: string): { agentDir: string; serverDir: string } {
7
+ mkdirSync(agentDir, { recursive: true, mode: 0o700 });
8
+ agentDir = realpathSync(agentDir);
9
+ const path = join(agentDir, "server-registration-v1.json");
10
+ const read = () => {
11
+ const registration = JSON.parse(readFileSync(path, "utf8"));
12
+ if (registration.version !== 1 || registration.agentDir !== agentDir || typeof registration.serverDir !== "string"
13
+ || resolve(registration.serverDir) !== registration.serverDir || realpathSync(registration.serverDir) !== registration.serverDir) {
14
+ throw new Error(`runtime-unavailable: invalid registration at ${path}; inspect it before retrying`);
15
+ }
16
+ return { agentDir, serverDir: registration.serverDir as string };
17
+ };
18
+ try { return read(); }
19
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
20
+ const temporary = `${path}.${randomUUID()}`;
21
+ mkdirSync(requestedServerDir, { recursive: true, mode: 0o700 });
22
+ const proposed = { version: 1, agentDir, serverDir: realpathSync(requestedServerDir) };
23
+ writeFileSync(temporary, JSON.stringify(proposed), { mode: 0o600, flag: "wx" });
24
+ try {
25
+ try { linkSync(temporary, path); }
26
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; }
27
+ } finally { unlinkSync(temporary); }
28
+ return read();
29
+ }
@@ -0,0 +1,10 @@
1
+ import { join } from "node:path";
2
+
3
+ /** sockaddr_un.sun_path is 104 bytes on macOS; leave room for the NUL. */
4
+ export function socketPathFor(serverDir: string): string {
5
+ const path = join(serverDir, "pi-server.sock");
6
+ if (Buffer.byteLength(path) > 103) {
7
+ throw new Error(`Socket path is too long for a unix socket (${Buffer.byteLength(path)} > 103 bytes): ${path}. Set PI_SERVER_DIR to a shorter directory.`);
8
+ }
9
+ return path;
10
+ }
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { ensureRuntime } from "./client.ts";
5
+
6
+ try {
7
+ const status = await ensureRuntime({ agentDir: process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent"), serverDir: process.env.PI_SERVER_DIR,
8
+ offline: process.env.PI_OFFLINE === "1",
9
+ onProgress: stage => process.stderr.write(`Runtime: ${stage}\n`) });
10
+ process.stdout.write(JSON.stringify(status) + "\n");
11
+ } catch (error) { process.stderr.write(`${String(error)}\n`); process.exitCode = 1; }
@@ -0,0 +1,13 @@
1
+ import type { WorkScope, WorkSnapshot } from "./read-model.ts";
2
+ export class WorkClient {
3
+ readonly closed: boolean;
4
+ constructor(socketPath: string | import("node:stream").Duplex, agentDir: string, requiredCapabilities?: string[]);
5
+ snapshot?: WorkSnapshot;
6
+ ready: Promise<any>;
7
+ request(type: string, params?: object): Promise<any>;
8
+ subscribe(scope: WorkScope): Promise<WorkSnapshot>;
9
+ resync(): Promise<WorkSnapshot>;
10
+ get(scope: WorkScope): Promise<WorkSnapshot>;
11
+ onChange(listener: (snapshot: WorkSnapshot) => void): () => void;
12
+ close(): void;
13
+ }
@@ -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
+ }