pi-better-server 0.2.4 → 0.4.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.
- package/package.json +6 -3
- package/scripts/measure-shared-reads/daemon.mjs +7 -0
- package/scripts/measure-shared-reads/probe.mjs +10 -0
- package/scripts/measure-shared-reads.mjs +165 -0
- package/scripts/test-on-pi.sh +21 -3
- package/src/cli.ts +39 -2
- package/src/client.ts +9 -4
- package/src/daemon-owner.ts +48 -6
- package/src/handshake.ts +8 -7
- package/src/lifecycle-config.ts +4 -0
- package/src/paths.ts +1 -11
- package/src/protocol.ts +7 -0
- package/src/registry.ts +2 -1
- package/src/runtime/background-history.ts +241 -0
- package/src/runtime/background.ts +182 -0
- package/src/runtime/cancellation.ts +99 -0
- package/src/runtime/catalog-admission.ts +50 -0
- package/src/runtime/catalog.ts +133 -0
- package/src/runtime/client.ts +111 -0
- package/src/runtime/domain/assignment-observation.d.mts +1 -0
- package/src/runtime/domain/assignment-observation.mjs +120 -0
- package/src/runtime/domain/assignment-projection.d.mts +1 -0
- package/src/runtime/domain/assignment-projection.mjs +245 -0
- package/src/runtime/domain/background/conditions.mjs +93 -0
- package/src/runtime/domain/background/process-identity.mjs +110 -0
- package/src/runtime/domain/background/process.mjs +511 -0
- package/src/runtime/domain/background/registry.mjs +374 -0
- package/src/runtime/domain/background/snapshot.mjs +73 -0
- package/src/runtime/domain/background/supervisor/identity.mjs +92 -0
- package/src/runtime/domain/background/supervisor/invocation.mjs +29 -0
- package/src/runtime/domain/background/supervisor/store.mjs +604 -0
- package/src/runtime/domain/background/supervisor/supervisor.mjs +720 -0
- package/src/runtime/domain/background/supervisor/types.mjs +47 -0
- package/src/runtime/domain/background/terminal-publication.mjs +58 -0
- package/src/runtime/domain/background/types.mjs +3 -0
- package/src/runtime/domain/catalog/agent-session-settings.d.mts +30 -0
- package/src/runtime/domain/catalog/agent-session-settings.mjs +112 -0
- package/src/runtime/domain/catalog/catalog-overlay.d.mts +3 -0
- package/src/runtime/domain/catalog/catalog-overlay.mjs +9 -0
- package/src/runtime/domain/catalog/catalog-preferences.d.mts +17 -0
- package/src/runtime/domain/catalog/catalog-preferences.mjs +164 -0
- package/src/runtime/domain/catalog/catalog-schema.d.mts +265 -0
- package/src/runtime/domain/catalog/catalog-schema.mjs +1331 -0
- package/src/runtime/domain/catalog/catalog-skill-edits.d.mts +42 -0
- package/src/runtime/domain/catalog/catalog-skill-edits.mjs +95 -0
- package/src/runtime/domain/catalog/catalog-store.d.mts +126 -0
- package/src/runtime/domain/catalog/catalog-store.mjs +810 -0
- package/src/runtime/domain/catalog/roles/role.architect.md +13 -0
- package/src/runtime/domain/catalog/roles/role.developer.md +16 -0
- package/src/runtime/domain/catalog/roles/role.explorer.md +13 -0
- package/src/runtime/domain/catalog/roles/role.product-manager.md +13 -0
- package/src/runtime/domain/catalog/roles/role.researcher.md +13 -0
- package/src/runtime/domain/catalog/roles/role.reviewer.md +13 -0
- package/src/runtime/domain/catalog/roles/role.writer.md +12 -0
- package/src/runtime/domain/catalog/thinking.d.mts +8 -0
- package/src/runtime/domain/catalog/thinking.mjs +22 -0
- package/src/runtime/domain/coordinator/index.mjs +50 -0
- package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +160 -0
- package/src/runtime/domain/coordinator/src/discovery.mjs +94 -0
- package/src/runtime/domain/coordinator/src/errors.mjs +12 -0
- package/src/runtime/domain/coordinator/src/operations.mjs +301 -0
- package/src/runtime/domain/coordinator/src/outbox.mjs +282 -0
- package/src/runtime/domain/coordinator/src/recovery.mjs +51 -0
- package/src/runtime/domain/coordinator/src/result-supervision.mjs +101 -0
- package/src/runtime/domain/coordinator/src/rows.mjs +277 -0
- package/src/runtime/domain/coordinator/src/schema.mjs +367 -0
- package/src/runtime/domain/coordinator/src/sqlite.mjs +193 -0
- package/src/runtime/domain/coordinator/src/store.mjs +245 -0
- package/src/runtime/domain/coordinator/src/task-cancellation.mjs +187 -0
- package/src/runtime/domain/coordinator/src/types.mjs +24 -0
- package/src/runtime/domain/coordinator/src/validate.mjs +233 -0
- package/src/runtime/domain/coordinator/src/waits.mjs +850 -0
- package/src/runtime/domain/health-observation.d.mts +3 -0
- package/src/runtime/domain/health-observation.mjs +613 -0
- package/src/runtime/domain/health-surface.mjs +279 -0
- package/src/runtime/domain/log-cursor.mjs +148 -0
- package/src/runtime/domain/log-paths.mjs +13 -0
- package/src/runtime/domain/parse.d.mts +2 -0
- package/src/runtime/domain/parse.mjs +1173 -0
- package/src/runtime/domain/process-status.d.mts +1 -0
- package/src/runtime/domain/process-status.mjs +25 -0
- package/src/runtime/domain/session-store.d.mts +2 -0
- package/src/runtime/domain/session-store.mjs +489 -0
- package/src/runtime/domain/shared-harness-settings.d.mts +1 -0
- package/src/runtime/domain/shared-harness-settings.mjs +126 -0
- package/src/runtime/domain/shared-log-utils.mjs +1223 -0
- package/src/runtime/domain/shared-stall-detector.mjs +37 -0
- package/src/runtime/domain/widget.d.mts +1 -0
- package/src/runtime/domain/widget.mjs +250 -0
- package/src/runtime/guardian.ts +189 -0
- package/src/runtime/health-config.ts +27 -0
- package/src/runtime/local-client.ts +34 -0
- package/src/runtime/mutation-store.ts +34 -0
- package/src/runtime/queries.ts +76 -0
- package/src/runtime/query-executor.ts +277 -0
- package/src/runtime/query-worker.mjs +119 -0
- package/src/runtime/read-model.ts +409 -0
- package/src/runtime/result-supervision.ts +63 -0
- package/src/runtime/root.ts +29 -0
- package/src/runtime/socket.ts +10 -0
- package/src/runtime/status-cli.ts +11 -0
- package/src/runtime/work-client.d.mts +14 -0
- package/src/runtime/work-client.mjs +102 -0
- package/src/server.ts +199 -14
- package/src/session-activity.ts +22 -2
- package/src/startup/activation.ts +32 -5
- package/src/startup/ensure.ts +13 -1
- package/src/startup/install.ts +2 -0
- package/src/version.ts +4 -0
|
@@ -0,0 +1,409 @@
|
|
|
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 { performance } from "node:perf_hooks";
|
|
11
|
+
import { createAssignmentProjector } from "./domain/assignment-projection.mjs";
|
|
12
|
+
import { createAssignmentReader } from "./domain/assignment-observation.mjs";
|
|
13
|
+
import { parseArchivedAttempt, parseArchivedSessionState } from "./domain/session-store.mjs";
|
|
14
|
+
import { parseRun, readRunTranscript } from "./domain/parse.mjs";
|
|
15
|
+
import { fmtSpend } from "./domain/widget.mjs";
|
|
16
|
+
import { effectiveStatus } from "./domain/process-status.mjs";
|
|
17
|
+
import { extractChildEventFactsFromLog, healthThresholdsForConfig } from "./domain/health-observation.mjs";
|
|
18
|
+
import { BackgroundObservation } from "./background.ts";
|
|
19
|
+
import { readHealthConfig } from "./health-config.ts";
|
|
20
|
+
|
|
21
|
+
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 }
|
|
22
|
+
export interface WorkSnapshot {
|
|
23
|
+
instanceId: string; runtimeEpoch: string; scopeRevision: string; seq: number;
|
|
24
|
+
observedRevisionVector: { inventory: number; coordinator: string; healthConfig: string };
|
|
25
|
+
status: "ready" | "rebuilding" | "degraded"; reason?: string;
|
|
26
|
+
rows: Array<{ meta: any; assignment: any; sourceRevision: string }>;
|
|
27
|
+
nextCursor?: string; activity: { active: number }; nextDeadline: number | null;
|
|
28
|
+
totalMatching: number;
|
|
29
|
+
backgroundIndex?: any;
|
|
30
|
+
resyncRequired?: boolean; resyncReason?: string;
|
|
31
|
+
}
|
|
32
|
+
const hash = (value: unknown) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
33
|
+
const safeId = /^[A-Za-z0-9_-]+$/;
|
|
34
|
+
|
|
35
|
+
/** Reconstructable query state. It never authorizes execution or writes source records. */
|
|
36
|
+
export class WorkReadModel {
|
|
37
|
+
private background: BackgroundObservation;
|
|
38
|
+
private db: any;
|
|
39
|
+
private reader: ReturnType<typeof createAssignmentReader>;
|
|
40
|
+
private files = new Map<string, { signature: string; meta: any }>();
|
|
41
|
+
private projected = new Map<string, { meta: any; assignment: any; sourceRevision: string; display?: { spend: string; tool: string }; health?: any }>();
|
|
42
|
+
private logs = new Map<string, string>();
|
|
43
|
+
private processes = new Map<string, string>();
|
|
44
|
+
private staged?: {
|
|
45
|
+
files: WorkReadModel["files"]; projected: WorkReadModel["projected"];
|
|
46
|
+
logs: Map<string, string>; processes: Map<string, string>; healthRevision: string;
|
|
47
|
+
coordinator: string; coordinatorConversations?: Map<string, string>;
|
|
48
|
+
};
|
|
49
|
+
private healthRevision = "";
|
|
50
|
+
private details = new Map<string, { revision: string; value: any }>();
|
|
51
|
+
private watchers: FSWatcher[] = [];
|
|
52
|
+
private listeners = new Set<() => void>();
|
|
53
|
+
private timer?: ReturnType<typeof setInterval>;
|
|
54
|
+
private pending?: Promise<void>;
|
|
55
|
+
private dirty = false;
|
|
56
|
+
private closed = false;
|
|
57
|
+
private inventory = 0;
|
|
58
|
+
private coordinator = "unknown";
|
|
59
|
+
private coordinatorConversations?: Map<string, string>;
|
|
60
|
+
private revision = 0;
|
|
61
|
+
private state: WorkSnapshot["status"] = "rebuilding";
|
|
62
|
+
private reason: string | undefined = "Initial source inventory is rebuilding.";
|
|
63
|
+
readonly metrics = { inventories: 0, metadataReads: 0, projections: 0, coordinatorConnections: 1, indexConnections: 1 };
|
|
64
|
+
readonly runs: string;
|
|
65
|
+
readonly archives: string;
|
|
66
|
+
readonly markers: string;
|
|
67
|
+
readonly agentDir: string;
|
|
68
|
+
readonly instanceId: string;
|
|
69
|
+
|
|
70
|
+
constructor(agentDir: string, instanceId: string, options: { supervisorDirectory?: string; baseDir?: string; durableDir?: string; intervalMs?: number } = {}) {
|
|
71
|
+
this.agentDir = agentDir; this.instanceId = instanceId;
|
|
72
|
+
const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
|
|
73
|
+
this.db = new DatabaseSync(":memory:");
|
|
74
|
+
this.background = new BackgroundObservation(agentDir, options.supervisorDirectory, this.db, () => this.publish());
|
|
75
|
+
this.db.exec(`CREATE TABLE rows (id TEXT PRIMARY KEY, cwd TEXT, origin_cwd TEXT, origin_session TEXT,
|
|
76
|
+
started REAL, state TEXT, active INTEGER, ended REAL, payload TEXT);
|
|
77
|
+
CREATE INDEX work_folder ON rows(cwd, started DESC, id DESC);
|
|
78
|
+
CREATE INDEX work_origin ON rows(origin_cwd, origin_session, started DESC, id DESC);
|
|
79
|
+
CREATE INDEX work_active ON rows(active, started DESC, id DESC);
|
|
80
|
+
CREATE INDEX work_terminal ON rows(active, ended, started DESC, id DESC);
|
|
81
|
+
CREATE INDEX work_state ON rows(state, started DESC, id DESC);`);
|
|
82
|
+
this.reader = createAssignmentReader(join(agentDir, "operation-coordinator.sqlite"));
|
|
83
|
+
this.runs = join(options.baseDir ?? join(realpathSync(tmpdir()), "pi-better-subagents"), "runs");
|
|
84
|
+
this.archives = join(options.durableDir ?? process.env.PI_SUBAGENT_DURABLE_DIR ?? join(agentDir, "subagents"), "attempts");
|
|
85
|
+
this.markers = join(this.archives, "../session-state");
|
|
86
|
+
// Notifications accelerate discovery; a shared bounded inventory repairs lost hints.
|
|
87
|
+
for (const path of [this.runs, this.archives, this.markers]) {
|
|
88
|
+
try {
|
|
89
|
+
const watcher = watch(path, { recursive: true }, () => { void this.reconcile(); });
|
|
90
|
+
watcher.on("error", () => this.invalidate("Watcher overflow or failure; reconciling source inventory."));
|
|
91
|
+
this.watchers.push(watcher);
|
|
92
|
+
} catch { /* Missing roots are discovered by the compatibility inventory. */ }
|
|
93
|
+
}
|
|
94
|
+
this.timer = setInterval(() => { if (!this.pending) void this.reconcile(); }, options.intervalMs ?? 1000);
|
|
95
|
+
this.timer.unref();
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
onChange(listener: () => void, scope?: WorkScope) {
|
|
99
|
+
const release = scope?.background ? this.background.retain(scope) : undefined;
|
|
100
|
+
this.listeners.add(listener);
|
|
101
|
+
return () => { this.listeners.delete(listener); release?.(); };
|
|
102
|
+
}
|
|
103
|
+
get backgroundMetrics() { return { ...this.background.metrics, scopes: this.background.scopeCount, history: this.background.historyMetrics }; }
|
|
104
|
+
observation(reasons = this.livenessReasons({ refresh: false })) {
|
|
105
|
+
return { status: this.state, reason: this.reason, observedAt: Date.now(), reasons };
|
|
106
|
+
}
|
|
107
|
+
livenessReasons(options: { refresh?: boolean } = {}) {
|
|
108
|
+
return [
|
|
109
|
+
...[...this.projected.values()].filter(row => row.meta.status === "running"
|
|
110
|
+
&& processMatchesStart(row.meta.pid, row.meta.pidStartTime))
|
|
111
|
+
.map(row => ({ kind: "worker", id: row.meta.id, owner: row.meta.callbackOrigin,
|
|
112
|
+
lastProgressAt: row.meta.startedAt, nextDeadline: null, recovery: "observe-existing-worker" })),
|
|
113
|
+
...this.background.livenessReasons(options),
|
|
114
|
+
];
|
|
115
|
+
}
|
|
116
|
+
async ensureId(id: string): Promise<boolean> {
|
|
117
|
+
if (!safeId.test(id)) throw new Error("Invalid run ID");
|
|
118
|
+
if (this.state === "rebuilding") return false;
|
|
119
|
+
if (this.db.prepare("SELECT id FROM rows WHERE id = ?").get(id)) return true;
|
|
120
|
+
try { await stat(join(this.runs, id, "meta.json")); }
|
|
121
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return true; throw error; }
|
|
122
|
+
// Repair a newly written ID without letting a global inventory consume its read deadline.
|
|
123
|
+
let timeout: ReturnType<typeof setTimeout> | undefined;
|
|
124
|
+
try {
|
|
125
|
+
return await Promise.race([
|
|
126
|
+
this.reconcile().then(() => !!this.db.prepare("SELECT id FROM rows WHERE id = ?").get(id)),
|
|
127
|
+
new Promise<false>(resolve => { timeout = setTimeout(() => resolve(false), 100); }),
|
|
128
|
+
]);
|
|
129
|
+
} finally {
|
|
130
|
+
if (timeout) clearTimeout(timeout);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
invalidate(reason: string) {
|
|
134
|
+
this.state = "degraded"; this.reason = reason;
|
|
135
|
+
this.publish();
|
|
136
|
+
void this.reconcile();
|
|
137
|
+
}
|
|
138
|
+
private publish() { this.revision++; for (const listener of this.listeners) listener(); }
|
|
139
|
+
|
|
140
|
+
reconcile(): Promise<void> {
|
|
141
|
+
if (this.closed) return Promise.resolve();
|
|
142
|
+
if (this.pending) { this.dirty = true; return this.pending; }
|
|
143
|
+
this.pending = (async () => {
|
|
144
|
+
for (let pass = 0; pass < 2; pass++) {
|
|
145
|
+
this.dirty = false;
|
|
146
|
+
await this.scan();
|
|
147
|
+
if (!this.dirty || this.closed) break;
|
|
148
|
+
}
|
|
149
|
+
})().finally(() => {
|
|
150
|
+
this.pending = undefined;
|
|
151
|
+
if (this.dirty && !this.closed) { this.dirty = false; void this.reconcile(); }
|
|
152
|
+
});
|
|
153
|
+
return this.pending;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
private async scan() {
|
|
157
|
+
this.metrics.inventories++;
|
|
158
|
+
if (this.background.refresh()) this.publish();
|
|
159
|
+
let releaseCoordinator: (() => void) | undefined;
|
|
160
|
+
const baseline = this.staged ?? { files: this.files, projected: this.projected, logs: this.logs, processes: this.processes,
|
|
161
|
+
healthRevision: this.healthRevision, coordinator: this.coordinator, coordinatorConversations: this.coordinatorConversations };
|
|
162
|
+
try {
|
|
163
|
+
const next = new Map<string, { signature: string; meta: any }>();
|
|
164
|
+
let batch = 0;
|
|
165
|
+
let sliceStarted = performance.now();
|
|
166
|
+
for (const [directory, archived] of [[this.markers, true], [this.archives, true], [this.runs, false]] as const) {
|
|
167
|
+
let names: string[];
|
|
168
|
+
try { names = await readdir(directory); }
|
|
169
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; throw error; }
|
|
170
|
+
// Bound filesystem concurrency without serializing every archive round trip.
|
|
171
|
+
const candidates = names.filter(name => safeId.test(archived ? name.replace(/\.json$/, "") : name)
|
|
172
|
+
&& (!archived || name.endsWith(".json")));
|
|
173
|
+
for (let offset = 0; offset < candidates.length; offset += 32) {
|
|
174
|
+
const group = candidates.slice(offset, offset + 32);
|
|
175
|
+
const observations = await Promise.all(group.map(async name => {
|
|
176
|
+
const path = archived ? join(directory, name) : join(directory, name, "meta.json");
|
|
177
|
+
try { return { info: await stat(path, { bigint: true }) }; }
|
|
178
|
+
catch (error) { return { error }; }
|
|
179
|
+
}));
|
|
180
|
+
for (const [index, name] of group.entries()) {
|
|
181
|
+
const id = archived ? name.replace(/\.json$/, "") : name;
|
|
182
|
+
const path = archived ? join(directory, name) : join(directory, name, "meta.json");
|
|
183
|
+
try {
|
|
184
|
+
const observation = observations[index]!;
|
|
185
|
+
if (!observation.info) throw observation.error;
|
|
186
|
+
const info = observation.info;
|
|
187
|
+
const signature = `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
|
|
188
|
+
let entry = baseline.files.get(path);
|
|
189
|
+
if (entry?.signature !== signature) {
|
|
190
|
+
this.metrics.metadataReads++;
|
|
191
|
+
const raw = await readFile(path, "utf8");
|
|
192
|
+
if (directory === this.markers) {
|
|
193
|
+
const marker = parseArchivedSessionState(raw, id);
|
|
194
|
+
if (!marker) throw new Error(`Unusable session marker: ${id}`);
|
|
195
|
+
entry = { signature, meta: marker };
|
|
196
|
+
next.set(path, entry);
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
const meta = archived ? parseArchivedAttempt(raw, id, join(this.archives, "../sessions")) : JSON.parse(raw);
|
|
200
|
+
if (meta?.id !== id || typeof meta.cwd !== "string" || !Number.isFinite(meta.startedAt) || typeof meta.status !== "string") throw new Error(`Unusable run record: ${id}`);
|
|
201
|
+
entry = { signature, meta };
|
|
202
|
+
}
|
|
203
|
+
next.set(path, entry!);
|
|
204
|
+
} catch (error) {
|
|
205
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
206
|
+
}
|
|
207
|
+
if (++batch % 256 === 0 || performance.now() - sliceStarted >= 8) {
|
|
208
|
+
await yieldTurn(); sliceStarted = performance.now();
|
|
209
|
+
}
|
|
210
|
+
if (this.closed) return;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
let coordinator: string;
|
|
215
|
+
try {
|
|
216
|
+
const snapshot = this.reader.beginSnapshot();
|
|
217
|
+
coordinator = snapshot.revision; releaseCoordinator = snapshot.release;
|
|
218
|
+
} catch { coordinator = "unknown"; }
|
|
219
|
+
const coordinatorConversations = coordinator === baseline.coordinator ? baseline.coordinatorConversations : this.reader.conversationRevisions();
|
|
220
|
+
const logs = new Map<string, string>();
|
|
221
|
+
const processes = new Map<string, string>();
|
|
222
|
+
const logFamilies = new Set<string>();
|
|
223
|
+
for (const [path, entry] of next) {
|
|
224
|
+
if (!path.startsWith(this.runs + sep)) continue;
|
|
225
|
+
let signature = baseline.logs.get(entry.meta.id);
|
|
226
|
+
{
|
|
227
|
+
try {
|
|
228
|
+
const info = await stat(join(this.runs, entry.meta.id, "output.log"), { bigint: true });
|
|
229
|
+
signature = `${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
|
|
230
|
+
} catch (error) { signature = (error as NodeJS.ErrnoException).code === "ENOENT" ? "missing" : "unverified"; }
|
|
231
|
+
}
|
|
232
|
+
logs.set(entry.meta.id, signature);
|
|
233
|
+
if (signature !== baseline.logs.get(entry.meta.id)) logFamilies.add(JSON.stringify([entry.meta.sessionId, entry.meta.cwd]));
|
|
234
|
+
const status = effectiveStatus(entry.meta); processes.set(entry.meta.id, status);
|
|
235
|
+
if (status !== baseline.processes.get(entry.meta.id)) logFamilies.add(JSON.stringify([entry.meta.sessionId, entry.meta.cwd]));
|
|
236
|
+
if (performance.now() - sliceStarted >= 8) { await yieldTurn(); sliceStarted = performance.now(); }
|
|
237
|
+
}
|
|
238
|
+
const healthConfig = await readHealthConfig(this.agentDir, next.size > 0);
|
|
239
|
+
const changed = next.size !== baseline.files.size || [...next].some(([path, entry]) => baseline.files.get(path)?.signature !== entry.signature);
|
|
240
|
+
if (!this.staged && !changed && !logFamilies.size && coordinator === this.coordinator && healthConfig.revision === this.healthRevision && this.state === "ready") return;
|
|
241
|
+
const metas = new Map<string, any>();
|
|
242
|
+
const markers = new Map([...next].filter(([path]) => path.startsWith(this.markers + sep)).map(([, entry]) => [entry.meta.sessionId, entry.meta]));
|
|
243
|
+
for (const [path, entry] of next) {
|
|
244
|
+
if (path.startsWith(this.markers + sep)) continue;
|
|
245
|
+
const marker = markers.get(entry.meta.sessionId);
|
|
246
|
+
if (path.startsWith(this.archives + sep) && marker && marker.attemptId !== entry.meta.id && marker.startedAt >= entry.meta.startedAt) continue;
|
|
247
|
+
metas.set(entry.meta.id, entry.meta);
|
|
248
|
+
}
|
|
249
|
+
const attempts = [...metas.values()];
|
|
250
|
+
const affected = new Set<string>(logFamilies);
|
|
251
|
+
const family = (meta: any) => JSON.stringify([meta.sessionId, meta.cwd]);
|
|
252
|
+
for (const [path, entry] of [...baseline.files, ...next]) {
|
|
253
|
+
if (baseline.files.get(path)?.signature !== next.get(path)?.signature) affected.add(family(entry.meta));
|
|
254
|
+
}
|
|
255
|
+
if (coordinator !== baseline.coordinator) for (const meta of attempts) {
|
|
256
|
+
if (!(meta.assignment || meta.operations || meta.park)) continue;
|
|
257
|
+
const owner = JSON.stringify([meta.operations?.conversationId ?? meta.sessionId, meta.operations?.workspace ?? meta.cwd]);
|
|
258
|
+
if (!coordinatorConversations || !baseline.coordinatorConversations ||
|
|
259
|
+
coordinatorConversations.get(owner) !== baseline.coordinatorConversations.get(owner)) affected.add(family(meta));
|
|
260
|
+
}
|
|
261
|
+
const project = createAssignmentProjector({ attempts, observe: (owner: any) => this.reader.read(owner) });
|
|
262
|
+
const rows = [];
|
|
263
|
+
for (const meta of attempts) {
|
|
264
|
+
let row = baseline.projected.get(meta.id);
|
|
265
|
+
if (!row || !row.assignment.verified || healthConfig.revision !== baseline.healthRevision || affected.has(family(meta))) {
|
|
266
|
+
this.metrics.projections++;
|
|
267
|
+
const assignment = project(meta, processes.get(meta.id) ?? meta.status);
|
|
268
|
+
const parsed = logs.get(meta.id) && logs.get(meta.id) !== "missing" ? parseRun(meta.id, { logPath: join(this.runs, meta.id, "output.log") }) : undefined;
|
|
269
|
+
const display = { spend: parsed ? fmtSpend(parsed.usage) : "", tool: parsed?.toolCalls.at(-1) ?? "" };
|
|
270
|
+
const health = logs.has(meta.id) ? { ...extractChildEventFactsFromLog(meta.id, { logPath: join(this.runs, meta.id, "output.log") }), thresholds: healthThresholdsForConfig(healthConfig.config) } : undefined;
|
|
271
|
+
row = { meta, assignment, display, health, sourceRevision: hash([meta, assignment.revision, display, health]) };
|
|
272
|
+
}
|
|
273
|
+
rows.push(row);
|
|
274
|
+
if (++batch % 256 === 0 || performance.now() - sliceStarted >= 8) {
|
|
275
|
+
await yieldTurn(); sliceStarted = performance.now();
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
let after: string;
|
|
279
|
+
try { after = this.reader.revision(); } catch { after = "unknown"; }
|
|
280
|
+
if (after !== coordinator) { this.state = "degraded"; this.reason = "Coordinator changed during observation; retrying."; this.dirty = true; this.publish(); return; }
|
|
281
|
+
// Retry caches are never queryable. Validate all unpublished families again before committing them.
|
|
282
|
+
this.staged = { files: next, projected: new Map(rows.map(row => [row.meta.id, row])), logs, processes,
|
|
283
|
+
healthRevision: healthConfig.revision, coordinator, coordinatorConversations };
|
|
284
|
+
const uncommitted = new Set(affected);
|
|
285
|
+
for (const [path, entry] of [...this.files, ...next]) {
|
|
286
|
+
if (this.files.get(path)?.signature !== next.get(path)?.signature) uncommitted.add(family(entry.meta));
|
|
287
|
+
}
|
|
288
|
+
const verify = [...next].filter(([, entry]) => uncommitted.has(family(entry.meta)));
|
|
289
|
+
for (let offset = 0; offset < verify.length; offset += 32) {
|
|
290
|
+
const group = verify.slice(offset, offset + 32);
|
|
291
|
+
const observations = await Promise.all(group.map(async ([path]) => {
|
|
292
|
+
try { return { info: await stat(path, { bigint: true }) }; }
|
|
293
|
+
catch (error) { return { error }; }
|
|
294
|
+
}));
|
|
295
|
+
for (const [index, [, entry]] of group.entries()) {
|
|
296
|
+
const observation = observations[index]!;
|
|
297
|
+
if (!observation.info) throw observation.error;
|
|
298
|
+
const info = observation.info;
|
|
299
|
+
if (`${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}` !== entry.signature) {
|
|
300
|
+
this.dirty = true;
|
|
301
|
+
throw new Error("Source changed during observation; retaining the previous snapshot while reconciling.");
|
|
302
|
+
}
|
|
303
|
+
if (++batch % 256 === 0 || performance.now() - sliceStarted >= 8) {
|
|
304
|
+
await yieldTurn(); sliceStarted = performance.now();
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
if (this.closed) return;
|
|
309
|
+
this.db.exec("BEGIN");
|
|
310
|
+
const insert = this.db.prepare("INSERT OR REPLACE INTO rows VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
|
|
311
|
+
const remove = this.db.prepare("DELETE FROM rows WHERE id = ?");
|
|
312
|
+
let semanticChange = false;
|
|
313
|
+
try {
|
|
314
|
+
for (const id of this.projected.keys()) if (!metas.has(id)) { remove.run(id); semanticChange = true; }
|
|
315
|
+
for (const row of rows) {
|
|
316
|
+
if (this.projected.get(row.meta.id)?.sourceRevision === row.sourceRevision) continue;
|
|
317
|
+
semanticChange = true;
|
|
318
|
+
const m = row.meta;
|
|
319
|
+
insert.run(m.id, m.cwd, m.callbackOrigin?.cwd ?? m.cwd, m.callbackOrigin?.sessionId ?? null,
|
|
320
|
+
m.startedAt, row.assignment.state, ["running", "waiting"].includes(row.assignment.state) ? 1 : 0, m.endedAt ?? m.lostAt ?? null, JSON.stringify(row));
|
|
321
|
+
}
|
|
322
|
+
this.db.exec("COMMIT");
|
|
323
|
+
} catch (error) { this.db.exec("ROLLBACK"); throw error; }
|
|
324
|
+
this.files = next; this.logs = logs; this.processes = processes; this.healthRevision = healthConfig.revision; this.coordinator = coordinator; this.inventory++;
|
|
325
|
+
this.coordinatorConversations = coordinatorConversations;
|
|
326
|
+
this.projected = new Map(rows.map(row => [row.meta.id, row]));
|
|
327
|
+
this.staged = undefined;
|
|
328
|
+
const previousState = this.state;
|
|
329
|
+
const previousReason = this.reason;
|
|
330
|
+
this.state = rows.some(row => !row.assignment.verified) ? "degraded" : "ready";
|
|
331
|
+
this.reason = this.state === "degraded" ? "Some assignment sources could not be verified." : undefined;
|
|
332
|
+
if (semanticChange || previousState !== this.state || previousReason !== this.reason) this.publish();
|
|
333
|
+
} catch (error) {
|
|
334
|
+
if (this.closed) return;
|
|
335
|
+
this.state = "degraded"; this.reason = String(error).slice(0, 512); this.publish();
|
|
336
|
+
} finally { releaseCoordinator?.(); }
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
snapshot(scope: WorkScope = {}): WorkSnapshot {
|
|
340
|
+
if (scope.background) {
|
|
341
|
+
if (scope.backgroundHistory && this.background.refresh()) this.publish();
|
|
342
|
+
const index = scope.backgroundHistory ? this.background.historyIndex(scope) : undefined;
|
|
343
|
+
const tasks = this.background.read(scope, index);
|
|
344
|
+
const status = this.background.status === "degraded" ? "degraded" : index ? this.background.historyStatus : this.background.status;
|
|
345
|
+
const active = (index ? this.background.read({ ...scope, backgroundHistory: false, active: true }) : tasks).filter(task => task.durable ? task.active : task.status === "running").length;
|
|
346
|
+
this.metrics.coordinatorConnections = 1 + this.background.connectionCount;
|
|
347
|
+
return { instanceId: this.instanceId, runtimeEpoch: this.instanceId, scopeRevision: hash([scope, tasks, status, index?.page, active]), seq: this.revision,
|
|
348
|
+
observedRevisionVector: { inventory: this.inventory, coordinator: this.coordinator, healthConfig: this.healthRevision },
|
|
349
|
+
status, reason: this.background.reason ?? (index ? this.background.historyReason : undefined),
|
|
350
|
+
rows: tasks.map(meta => ({ meta, assignment: null, sourceRevision: hash(meta) })), totalMatching: index?.page.total ?? tasks.length,
|
|
351
|
+
...(index?.page.nextCursor ? { nextCursor: index.page.nextCursor } : {}),
|
|
352
|
+
...(index ? { backgroundIndex: index } : {}),
|
|
353
|
+
activity: { active }, nextDeadline: null };
|
|
354
|
+
}
|
|
355
|
+
const clauses: string[] = [], args: any[] = [];
|
|
356
|
+
if (scope.id) { clauses.push("id = ?"); args.push(scope.id); }
|
|
357
|
+
if (scope.sessionId) { clauses.push("origin_session = ? AND origin_cwd = ?"); args.push(scope.sessionId, scope.cwd); }
|
|
358
|
+
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); }
|
|
359
|
+
// Activity describes the scope, independently of history filters and pagination.
|
|
360
|
+
const active = Number(this.db.prepare(`SELECT count(*) AS n FROM rows WHERE ${[...clauses, "active = 1"].join(" AND ")}`).get(...args).n);
|
|
361
|
+
if (scope.active !== undefined) { clauses.push("active = ?"); args.push(scope.active ? 1 : 0); }
|
|
362
|
+
if (scope.endedAfter !== undefined) { clauses.push("(ended IS NULL OR ended >= ?)"); args.push(scope.endedAfter); }
|
|
363
|
+
if (scope.statuses?.length) { clauses.push(`state IN (${scope.statuses.map(() => "?").join(",")})`); args.push(...scope.statuses); }
|
|
364
|
+
const key = hash({ ...scope, cursor: undefined });
|
|
365
|
+
const totalMatching = Number(this.db.prepare(`SELECT count(*) AS n FROM rows ${clauses.length ? "WHERE " + clauses.join(" AND ") : ""}`).get(...args).n);
|
|
366
|
+
if (scope.cursor) {
|
|
367
|
+
let cursor;
|
|
368
|
+
try { cursor = JSON.parse(Buffer.from(scope.cursor, "base64url").toString()); } catch { throw new Error("Invalid runtime cursor"); }
|
|
369
|
+
if (!Array.isArray(cursor) || cursor[0] !== key || cursor[1] !== this.instanceId || cursor[2] !== this.revision) throw new Error("resync_required: cursor snapshot changed");
|
|
370
|
+
clauses.push("(started < ? OR (started = ? AND id < ?))"); args.push(cursor[3], cursor[3], cursor[4]);
|
|
371
|
+
}
|
|
372
|
+
const limit = Math.max(1, Math.min(200, Number.isSafeInteger(scope.limit) ? scope.limit! : 50));
|
|
373
|
+
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);
|
|
374
|
+
const page = records.slice(0, limit), last = page.at(-1);
|
|
375
|
+
return { instanceId: this.instanceId, runtimeEpoch: this.instanceId, scopeRevision: hash([key, this.revision]), seq: this.revision,
|
|
376
|
+
observedRevisionVector: { inventory: this.inventory, coordinator: this.coordinator, healthConfig: this.healthRevision }, status: this.state, reason: this.reason,
|
|
377
|
+
totalMatching,
|
|
378
|
+
rows: page.map((record: any) => {
|
|
379
|
+
const row = JSON.parse(record.payload);
|
|
380
|
+
if (scope.detail && scope.id) {
|
|
381
|
+
let cached = this.details.get(row.meta.id);
|
|
382
|
+
if (!cached || cached.revision !== row.sourceRevision) {
|
|
383
|
+
const logPath = join(this.runs, row.meta.id, "output.log");
|
|
384
|
+
const expectedLog = this.logs.get(row.meta.id) ?? "missing";
|
|
385
|
+
const signature = () => {
|
|
386
|
+
try { const info = statSync(logPath, { bigint: true }); return `${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`; }
|
|
387
|
+
catch (error) { return (error as NodeJS.ErrnoException).code === "ENOENT" ? "missing" : "unverified"; }
|
|
388
|
+
};
|
|
389
|
+
if (signature() !== expectedLog) throw new Error("state-degraded: log changed since the indexed observation; resync required");
|
|
390
|
+
const value = { parsed: parseRun(row.meta.id, { logPath }), transcript: readRunTranscript(row.meta.id, { logPath }) };
|
|
391
|
+
if (signature() !== expectedLog) throw new Error("state-degraded: log changed during detail observation; resync required");
|
|
392
|
+
if (Buffer.byteLength(JSON.stringify(value)) > 3 * 1024 * 1024) throw new Error("state-degraded: detail exceeds the bounded snapshot allowance");
|
|
393
|
+
cached = { revision: row.sourceRevision, value }; this.details.set(row.meta.id, cached);
|
|
394
|
+
if (this.details.size > 16) this.details.delete(this.details.keys().next().value!);
|
|
395
|
+
}
|
|
396
|
+
row.detail = cached.value;
|
|
397
|
+
}
|
|
398
|
+
return { ...row, cursor: Buffer.from(JSON.stringify([key, this.instanceId, this.revision, record.started, record.id])).toString("base64url") };
|
|
399
|
+
}),
|
|
400
|
+
...(records.length > limit ? { nextCursor: Buffer.from(JSON.stringify([key, this.instanceId, this.revision, last.started, last.id])).toString("base64url") } : {}),
|
|
401
|
+
activity: { active }, nextDeadline: null };
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
async close() {
|
|
405
|
+
this.closed = true; if (this.timer) clearInterval(this.timer);
|
|
406
|
+
for (const watcher of this.watchers) watcher.close();
|
|
407
|
+
await this.pending; this.listeners.clear(); await this.background.close(); this.reader.close(); this.db.close();
|
|
408
|
+
}
|
|
409
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import { createRequire } from "node:module";
|
|
4
|
+
import { acquireMutationStore } from "./mutation-store.ts";
|
|
5
|
+
// @ts-expect-error Generated canonical supervisor.
|
|
6
|
+
import { createLocalSupervisor } from "./domain/background/supervisor/supervisor.mjs";
|
|
7
|
+
// @ts-expect-error Generated canonical terminal evidence rules.
|
|
8
|
+
import { supervisorTerminalPublication } from "./domain/background/terminal-publication.mjs";
|
|
9
|
+
|
|
10
|
+
export function hasResultSupervision(root: string): boolean {
|
|
11
|
+
const path = join(root, "operation-coordinator.sqlite");
|
|
12
|
+
if (!existsSync(path)) return false;
|
|
13
|
+
const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
|
|
14
|
+
const db = new DatabaseSync(path, { readOnly: true });
|
|
15
|
+
try { return !!db.prepare("SELECT 1 FROM coordinator_state WHERE key LIKE 'result-supervision-v1:%' LIMIT 1").get(); }
|
|
16
|
+
finally { db.close(); }
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Mechanical observation only. Never launches, stops, claims resumes or consumes results. */
|
|
20
|
+
export class RuntimeResultSupervision {
|
|
21
|
+
private store: any;
|
|
22
|
+
private releaseStore: () => void;
|
|
23
|
+
private timer: NodeJS.Timeout;
|
|
24
|
+
readonly hostId: string;
|
|
25
|
+
readonly epoch: string;
|
|
26
|
+
reason?: string;
|
|
27
|
+
constructor(root: string, epoch: string) {
|
|
28
|
+
this.epoch = epoch;
|
|
29
|
+
this.hostId = `server:${epoch}`;
|
|
30
|
+
const lease = acquireMutationStore(root);
|
|
31
|
+
this.store = lease.store;
|
|
32
|
+
this.releaseStore = lease.release;
|
|
33
|
+
this.reconcile();
|
|
34
|
+
this.timer = setInterval(() => this.reconcile(), 250);
|
|
35
|
+
this.timer.unref();
|
|
36
|
+
}
|
|
37
|
+
reconcile() {
|
|
38
|
+
try {
|
|
39
|
+
this.reason = undefined;
|
|
40
|
+
for (let grant of this.store.resultSupervisions(true)) {
|
|
41
|
+
const operation = this.store.getOperation(grant.operationId);
|
|
42
|
+
if (!operation || operation.terminalRevision > 0) continue;
|
|
43
|
+
if (grant.capability?.adapter !== "background-results-v1" || !grant.capability.captured || !grant.capability.current) {
|
|
44
|
+
this.reason = "permission-unavailable: captured Background adapter or permission source unavailable";
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
if (grant.epoch !== this.epoch) {
|
|
48
|
+
// Daemon startup has already proved the preceding root owner exited.
|
|
49
|
+
grant = { ...grant, hostId: this.hostId, epoch: this.epoch };
|
|
50
|
+
this.store.recoverResultSupervision(grant);
|
|
51
|
+
}
|
|
52
|
+
const inspection = createLocalSupervisor({ directory: grant.directory }).inspect(operation.taskId);
|
|
53
|
+
if (!inspection || inspection.token !== grant.launchToken) {
|
|
54
|
+
this.reason = "reconciling: exact runner evidence unavailable; no replacement command is permitted";
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
if (inspection.terminal) this.store.publishSupervisedResult({ operationId: operation.operationId,
|
|
58
|
+
epoch: this.epoch, publication: supervisorTerminalPublication(operation, inspection) });
|
|
59
|
+
}
|
|
60
|
+
} catch (error) { this.reason = String(error); }
|
|
61
|
+
}
|
|
62
|
+
close() { clearInterval(this.timer); this.releaseStore(); }
|
|
63
|
+
}
|
|
@@ -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,14 @@
|
|
|
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
|
+
onCatalog(listener: (snapshot: any) => void): () => void;
|
|
13
|
+
close(): void;
|
|
14
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { connect } from "node:net";
|
|
2
|
+
import { performance } from "node:perf_hooks";
|
|
3
|
+
|
|
4
|
+
/** SDK-free observation stream. Cached snapshots are the only synchronous read API. */
|
|
5
|
+
export class WorkClient {
|
|
6
|
+
socket;
|
|
7
|
+
snapshot;
|
|
8
|
+
pending = new Map();
|
|
9
|
+
listeners = new Set();
|
|
10
|
+
catalogListeners = new Set();
|
|
11
|
+
sequence = 0;
|
|
12
|
+
scope;
|
|
13
|
+
buffer = "";
|
|
14
|
+
closed = false;
|
|
15
|
+
|
|
16
|
+
constructor(socketPath, agentDir, requiredCapabilities = []) {
|
|
17
|
+
this.socket = typeof socketPath === "string" ? connect(socketPath) : socketPath;
|
|
18
|
+
this.socket.setEncoding("utf8");
|
|
19
|
+
this.socket.on("data", chunk => {
|
|
20
|
+
this.buffer += chunk;
|
|
21
|
+
if (Buffer.byteLength(this.buffer) > 4 * 1024 * 1024) return this.fail(new Error("runtime-unhealthy: oversized stream frame"));
|
|
22
|
+
while (this.buffer.includes("\n")) {
|
|
23
|
+
const index = this.buffer.indexOf("\n"), line = this.buffer.slice(0, index);
|
|
24
|
+
this.buffer = this.buffer.slice(index + 1);
|
|
25
|
+
try {
|
|
26
|
+
const message = JSON.parse(line);
|
|
27
|
+
if (message.type === "event") {
|
|
28
|
+
if (message.event.type === "runtime_catalog_snapshot") { for (const listener of this.catalogListeners) listener(message.event.snapshot); continue; }
|
|
29
|
+
if (message.event.type === "resync_required") { this.degrade(message.event.reason); void this.resync().catch(error => this.degrade(String(error))); }
|
|
30
|
+
else if (message.event.type === "runtime_snapshot") this.accept(message.event.snapshot);
|
|
31
|
+
} else {
|
|
32
|
+
const request = this.pending.get(message.id);
|
|
33
|
+
if (!request) continue;
|
|
34
|
+
this.pending.delete(message.id); clearTimeout(request.timer);
|
|
35
|
+
if (message.success) request.resolve(message.data); else request.reject(new Error(message.error));
|
|
36
|
+
}
|
|
37
|
+
} catch (error) { this.fail(error); }
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
this.socket.on("error", error => this.fail(error));
|
|
41
|
+
this.socket.on("close", () => this.fail(new Error("runtime-unavailable: disconnected; resync required")));
|
|
42
|
+
this.ready = this.request("hello", { protocolVersion: 1, runtimeRoot: agentDir, requiredCapabilities: ["runtime-state-v1", "runtime-subscriptions-v1", ...requiredCapabilities] })
|
|
43
|
+
.then(async hello => { if (typeof socketPath === "string" && hello.capabilities?.includes("runtime-client-retention-v1")) await this.request("runtime_register_client", { clientId: `work-${process.pid}` }); return hello; });
|
|
44
|
+
}
|
|
45
|
+
request(type, params = {}) {
|
|
46
|
+
if (this.closed) return Promise.reject(new Error("runtime-unavailable: disconnected; resync required"));
|
|
47
|
+
if (this.pending.size >= 32) return Promise.reject(new Error("runtime-unhealthy: too many in-flight queries"));
|
|
48
|
+
const id = `work-${++this.sequence}`;
|
|
49
|
+
return new Promise((resolve, reject) => {
|
|
50
|
+
const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(`runtime-unhealthy: ${type} timed out`)); }, 5000);
|
|
51
|
+
this.pending.set(id, { resolve, reject, timer });
|
|
52
|
+
this.socket.write(JSON.stringify({ id, type, ...params }) + "\n");
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
onChange(listener) { this.listeners.add(listener); return () => this.listeners.delete(listener); }
|
|
56
|
+
onCatalog(listener) { this.catalogListeners.add(listener); return () => this.catalogListeners.delete(listener); }
|
|
57
|
+
notify() { for (const listener of this.listeners) listener(this.snapshot); }
|
|
58
|
+
degrade(reason) {
|
|
59
|
+
this.snapshot = { ...this.snapshot, status: "degraded", reason, rows: this.snapshot?.rows ?? [] };
|
|
60
|
+
this.notify();
|
|
61
|
+
}
|
|
62
|
+
accept(snapshot) {
|
|
63
|
+
if (this.snapshot?.instanceId === snapshot.instanceId && snapshot.seq < this.snapshot.seq) return;
|
|
64
|
+
if (this.snapshot?.instanceId && this.snapshot.instanceId !== snapshot.instanceId) {
|
|
65
|
+
this.degrade("instance-changed: resync required");
|
|
66
|
+
snapshot = { ...snapshot, resyncRequired: true, resyncReason: "instance-changed" };
|
|
67
|
+
} else if (this.snapshot?.seq !== undefined && snapshot.seq > this.snapshot.seq + 1) {
|
|
68
|
+
this.degrade("sequence-gap: replacing with a full authoritative snapshot");
|
|
69
|
+
snapshot = { ...snapshot, resyncRequired: true, resyncReason: "sequence-gap" };
|
|
70
|
+
}
|
|
71
|
+
// Every event contains a complete bounded snapshot; gaps do not require inferred deltas.
|
|
72
|
+
this.snapshot = Object.freeze(snapshot); this.notify();
|
|
73
|
+
}
|
|
74
|
+
async subscribe(scope) {
|
|
75
|
+
await this.ready;
|
|
76
|
+
this.scope = scope;
|
|
77
|
+
const snapshot = await this.request("runtime_subscribe", { scope });
|
|
78
|
+
this.accept(snapshot); return snapshot;
|
|
79
|
+
}
|
|
80
|
+
async resync() {
|
|
81
|
+
const snapshot = await this.request("runtime_subscribe", { scope: this.scope, sinceSeq: this.snapshot?.seq, instanceId: this.snapshot?.instanceId });
|
|
82
|
+
this.accept(snapshot); return snapshot;
|
|
83
|
+
}
|
|
84
|
+
async get(scope) {
|
|
85
|
+
await this.ready;
|
|
86
|
+
const until = performance.now() + 3500;
|
|
87
|
+
for (let attempt = 0; ; attempt++) {
|
|
88
|
+
const value = await this.request("runtime_get_snapshot", { scope });
|
|
89
|
+
if (!scope?.id || value.status !== "rebuilding" || value.rows.length || performance.now() >= until) return value;
|
|
90
|
+
// A newly written ID may join an inventory without holding the shared RPC queue.
|
|
91
|
+
await new Promise(resolve => setTimeout(resolve, Math.min(250, 50 * 2 ** attempt, until - performance.now())));
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
fail(error) {
|
|
95
|
+
if (this.closed) return;
|
|
96
|
+
this.closed = true;
|
|
97
|
+
for (const request of this.pending.values()) { clearTimeout(request.timer); request.reject(error); }
|
|
98
|
+
this.pending.clear(); this.socket.destroy(); this.degrade(String(error));
|
|
99
|
+
for (const listener of this.catalogListeners) listener({ status: "revoked" });
|
|
100
|
+
}
|
|
101
|
+
close() { this.fail(new Error("runtime-unavailable: client closed")); this.listeners.clear(); this.catalogListeners.clear(); }
|
|
102
|
+
}
|