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.
- package/package.json +3 -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 +145 -0
- package/scripts/test-on-pi.sh +19 -2
- package/src/cli.ts +39 -2
- package/src/client.ts +9 -4
- package/src/daemon-owner.ts +47 -6
- package/src/handshake.ts +8 -7
- package/src/lifecycle-config.ts +4 -0
- package/src/paths.ts +1 -11
- package/src/protocol.ts +5 -0
- package/src/registry.ts +2 -1
- package/src/runtime/background-history.ts +241 -0
- package/src/runtime/background.ts +173 -0
- package/src/runtime/cancellation.ts +95 -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 +103 -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/coordinator/index.mjs +50 -0
- package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +160 -0
- package/src/runtime/domain/coordinator/src/discovery.mjs +85 -0
- package/src/runtime/domain/coordinator/src/errors.mjs +12 -0
- package/src/runtime/domain/coordinator/src/operations.mjs +299 -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/rows.mjs +277 -0
- package/src/runtime/domain/coordinator/src/schema.mjs +351 -0
- package/src/runtime/domain/coordinator/src/sqlite.mjs +193 -0
- package/src/runtime/domain/coordinator/src/store.mjs +235 -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/queries.ts +76 -0
- package/src/runtime/query-executor.ts +228 -0
- package/src/runtime/query-worker.mjs +118 -0
- package/src/runtime/read-model.ts +357 -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 +13 -0
- package/src/runtime/work-client.mjs +88 -0
- package/src/server.ts +136 -12
- 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,241 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { readdir, stat } from "node:fs/promises";
|
|
3
|
+
import { watch, statSync, type FSWatcher } from "node:fs";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
import { setImmediate as yieldTurn } from "node:timers/promises";
|
|
6
|
+
import type { WorkScope } from "./read-model.ts";
|
|
7
|
+
// @ts-expect-error Generated canonical cursor and scope functions.
|
|
8
|
+
import { rowCursorKey, pageRows, sessionScopeKey } from "./domain/shared-log-utils.mjs";
|
|
9
|
+
// @ts-expect-error Generated canonical passive registry inspection.
|
|
10
|
+
import { inspectMeta, tasksDir } from "./domain/background/registry.mjs";
|
|
11
|
+
|
|
12
|
+
const digest = (value: unknown) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
13
|
+
async function identity(path: string): Promise<string> {
|
|
14
|
+
try { const s = await stat(path, { bigint: true }); return `${s.dev}:${s.ino}:${s.size}:${s.mtimeNs}:${s.ctimeNs}`; }
|
|
15
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return "missing"; throw error; }
|
|
16
|
+
}
|
|
17
|
+
function currentIdentity(path: string): string {
|
|
18
|
+
try { const s = statSync(path, { bigint: true }); return `${s.dev}:${s.ino}:${s.size}:${s.mtimeNs}:${s.ctimeNs}`; }
|
|
19
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return "missing"; throw error; }
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Explicit history builds share the root index; ordinary activity never opens the archive. */
|
|
23
|
+
export class BackgroundHistory {
|
|
24
|
+
private db: any;
|
|
25
|
+
private directory: string;
|
|
26
|
+
private source: () => any;
|
|
27
|
+
private project: (operations: any[]) => any[];
|
|
28
|
+
private changed: () => void;
|
|
29
|
+
private pending?: Promise<void>;
|
|
30
|
+
private completed = 0;
|
|
31
|
+
private version = "";
|
|
32
|
+
private closed = false;
|
|
33
|
+
private generation = 0;
|
|
34
|
+
private watchers = new Map<string, FSWatcher>();
|
|
35
|
+
private activated = false;
|
|
36
|
+
private scheduled = false;
|
|
37
|
+
private timer?: ReturnType<typeof setInterval>;
|
|
38
|
+
private changes = 0;
|
|
39
|
+
private observedVersion = "";
|
|
40
|
+
status: "ready" | "rebuilding" | "degraded" = "rebuilding";
|
|
41
|
+
reason?: string;
|
|
42
|
+
readonly metrics = { inventories: 0, metadataReads: 0, projections: 0 };
|
|
43
|
+
|
|
44
|
+
constructor(db: any, directory: string, source: () => any, project: (operations: any[]) => any[], changed: () => void) {
|
|
45
|
+
this.db = db; this.directory = directory; this.source = source; this.project = project; this.changed = changed;
|
|
46
|
+
db.exec(`CREATE TABLE background_history (key TEXT PRIMARY KEY, id TEXT, workspace TEXT, session TEXT,
|
|
47
|
+
known INTEGER, unreadable INTEGER, state TEXT, started REAL, payload TEXT, signature TEXT, failure TEXT, spawn_pid INTEGER, active INTEGER, context TEXT);
|
|
48
|
+
CREATE INDEX background_history_scope ON background_history(workspace, session, state, started DESC, id DESC);
|
|
49
|
+
CREATE INDEX background_history_process ON background_history(workspace, session, spawn_pid, state, started DESC, id DESC);
|
|
50
|
+
CREATE INDEX background_history_state ON background_history(state, started DESC, id DESC);
|
|
51
|
+
CREATE INDEX background_history_order ON background_history(started DESC, id DESC);
|
|
52
|
+
CREATE TABLE background_history_revisions (workspace TEXT, session TEXT, state TEXT, content INTEGER, failure INTEGER,
|
|
53
|
+
PRIMARY KEY (workspace, session, state));`);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
private sourceVersion() {
|
|
57
|
+
const db = this.source();
|
|
58
|
+
const roots = [tasksDir(), join(this.directory, "observed")].map(path => {
|
|
59
|
+
try { const s = statSync(path, { bigint: true }); return `${s.dev}:${s.ino}:${s.mtimeNs}:${s.ctimeNs}`; }
|
|
60
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return "missing"; throw error; }
|
|
61
|
+
});
|
|
62
|
+
return JSON.stringify([db ? db.prepare("PRAGMA data_version").get().data_version : "absent", roots]);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
private observeSources() {
|
|
66
|
+
for (const path of [dirname(tasksDir()), this.directory]) {
|
|
67
|
+
if (this.watchers.has(path)) continue;
|
|
68
|
+
try {
|
|
69
|
+
const watcher = watch(path, { recursive: true }, (_event, file) => {
|
|
70
|
+
if (!file || /(?:meta|result|lost|launch|claim)\.json$|failures\.jsonl(?:\.observed)?$|^observed[/\\].*\.json$/.test(String(file))) this.invalidate();
|
|
71
|
+
});
|
|
72
|
+
watcher.on("error", () => { this.watchers.delete(path); watcher.close(); this.status = "degraded"; this.reason = "Background history watcher failed; reconciling source signatures"; this.invalidate(); });
|
|
73
|
+
this.watchers.set(path, watcher);
|
|
74
|
+
} catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
invalidate() {
|
|
79
|
+
this.completed = 0; this.generation++;
|
|
80
|
+
if (!this.activated || this.closed || this.scheduled) return;
|
|
81
|
+
this.scheduled = true;
|
|
82
|
+
setImmediate(() => { this.scheduled = false; if (!this.closed && !this.pending) this.startRefresh(); });
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
reconcile() {
|
|
86
|
+
if (!this.activated || this.closed) return;
|
|
87
|
+
const version = this.sourceVersion();
|
|
88
|
+
if (version !== this.observedVersion) { this.observedVersion = version; this.invalidate(); }
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
private startRefresh(version?: string) {
|
|
92
|
+
if (this.closed || this.pending) return;
|
|
93
|
+
const previous = this.status, changes = this.changes;
|
|
94
|
+
this.status = "rebuilding";
|
|
95
|
+
this.pending = Promise.resolve().then(() => this.refresh(version ?? this.sourceVersion())).catch(error => {
|
|
96
|
+
if (!this.closed) { this.status = "degraded"; this.reason = String(error); }
|
|
97
|
+
}).finally(() => {
|
|
98
|
+
this.pending = undefined;
|
|
99
|
+
if (this.closed) return;
|
|
100
|
+
if (changes !== this.changes || previous !== this.status) this.changed();
|
|
101
|
+
if (this.status === "rebuilding") this.invalidate();
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
read(scope: WorkScope) {
|
|
106
|
+
this.observeSources();
|
|
107
|
+
if (!this.activated) {
|
|
108
|
+
this.activated = true;
|
|
109
|
+
this.timer = setInterval(() => this.startRefresh(), 30000); this.timer.unref();
|
|
110
|
+
}
|
|
111
|
+
const version = this.sourceVersion();
|
|
112
|
+
this.observedVersion = version;
|
|
113
|
+
// Legacy writers have no entity notification yet; share one slower signature inventory.
|
|
114
|
+
if (!this.pending && (this.version !== version || Date.now() - this.completed >= 30000)) {
|
|
115
|
+
this.startRefresh(version);
|
|
116
|
+
}
|
|
117
|
+
const resource = `list:${sessionScopeKey({ all: scope.backgroundAll, origin: { cwd: scope.cwd, sessionId: scope.sessionId }, processId: scope.processId })}:${[...(scope.statuses ?? [])].sort().join(",")}`;
|
|
118
|
+
const clauses = ["unreadable = 0"], args: any[] = [];
|
|
119
|
+
if (!scope.backgroundAll) clauses.push("known = 1");
|
|
120
|
+
if (!scope.backgroundAll) { clauses.push("workspace = ? AND session = ?"); args.push(scope.cwd, scope.sessionId ?? ""); }
|
|
121
|
+
if (!scope.backgroundAll && !scope.sessionId) { clauses.push("spawn_pid = ?"); args.push(scope.processId ?? -1); }
|
|
122
|
+
if (scope.statuses?.length) { clauses.push(`(state IN (${scope.statuses.map(() => "?").join(",")})${scope.statuses.includes("running") ? " OR active = 1" : ""})`); args.push(...scope.statuses); }
|
|
123
|
+
if (scope.active !== undefined) { clauses.push("active = ?"); args.push(scope.active ? 1 : 0); }
|
|
124
|
+
const where = clauses.join(" AND ");
|
|
125
|
+
const aggregate = this.db.prepare(`SELECT count(*) AS n FROM background_history WHERE ${where}`).get(...args);
|
|
126
|
+
const anchor = rowCursorKey(scope.cursor, resource);
|
|
127
|
+
const after = anchor ? " AND (started < ? OR (started = ? AND id < ?))" : "";
|
|
128
|
+
const anchorArgs = anchor ? [anchor.time, anchor.time, anchor.id] : [];
|
|
129
|
+
const before = anchor ? Number(this.db.prepare(`SELECT count(*) AS n FROM background_history WHERE ${where} AND (started > ? OR (started = ? AND id >= ?))`).get(...args, ...anchorArgs).n) : 0;
|
|
130
|
+
const selected = this.db.prepare(`SELECT key, id, payload, context FROM background_history WHERE ${where}${after} ORDER BY started DESC, id DESC LIMIT ?`)
|
|
131
|
+
.all(...args, ...anchorArgs, (scope.limit ?? 10) + 1);
|
|
132
|
+
for (const row of selected) {
|
|
133
|
+
const path = row.key.startsWith("d:") ? join(this.directory, "observed", `${row.id}.json`) : join(tasksDir(), row.id, "meta.json");
|
|
134
|
+
if (row.context !== currentIdentity(path)) { this.invalidate(); this.status = "rebuilding"; }
|
|
135
|
+
}
|
|
136
|
+
const records = selected.map((row: any) => JSON.parse(row.payload));
|
|
137
|
+
const page = pageRows(records, { resource, cursor: scope.cursor, limit: scope.limit ?? 10, maxBytes: Number.MAX_SAFE_INTEGER,
|
|
138
|
+
indexed: { total: Number(aggregate.n), before }, keyOf: (meta: any) => ({ time: meta.startedAt, id: meta.id }), render: () => "" });
|
|
139
|
+
const revisionStates = scope.statuses?.length ? [...new Set([...scope.statuses, ...(scope.statuses.includes("running") ? ["starting"] : [])])] : ["*"];
|
|
140
|
+
const revisions = this.db.prepare(`SELECT sum(content) AS content, sum(failure) AS failure FROM background_history_revisions
|
|
141
|
+
WHERE workspace = ? AND session = ? AND state IN (${revisionStates.map(() => "?").join(",")})`)
|
|
142
|
+
.get(scope.backgroundAll ? "" : scope.cwd, scope.backgroundAll ? "" : scope.sessionId || `process:${scope.processId ?? -1}`, ...revisionStates);
|
|
143
|
+
const diagnostics = this.db.prepare("SELECT sum(unreadable) AS unreadable, sum(known = 0 AND unreadable = 0) AS unknown FROM background_history").get();
|
|
144
|
+
return { records: records.slice(0, scope.limit ?? 10).map((meta: any) => ({ id: meta.id, found: true, readable: true, meta })),
|
|
145
|
+
page: { total: Number(aggregate.n), before, nextCursor: page.nextCursor, resource,
|
|
146
|
+
contentRevision: digest([aggregate.n, revisions.content, diagnostics.unreadable, diagnostics.unknown]), failureRevision: digest(revisions.failure),
|
|
147
|
+
unreadable: Number(diagnostics.unreadable ?? 0), unknown: scope.backgroundAll ? 0 : Number(diagnostics.unknown ?? 0) } };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
private async refresh(version: string) {
|
|
151
|
+
const generation = this.generation;
|
|
152
|
+
this.metrics.inventories++;
|
|
153
|
+
const seen = new Set<string>();
|
|
154
|
+
const upsert = this.db.prepare(`INSERT OR REPLACE INTO background_history VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
|
155
|
+
const previous = this.db.prepare("SELECT * FROM background_history WHERE key = ?");
|
|
156
|
+
const bump = (row: any, content: boolean, failure: boolean) => {
|
|
157
|
+
const session = row.session || `process:${row.spawn_pid ?? -1}`;
|
|
158
|
+
const keys = new Map([[JSON.stringify([row.workspace, session, row.state]), [row.workspace, session, row.state]],
|
|
159
|
+
[JSON.stringify([row.workspace, session, "*"]), [row.workspace, session, "*"]],
|
|
160
|
+
[JSON.stringify(["", "", row.state]), ["", "", row.state]], [JSON.stringify(["", "", "*"]), ["", "", "*"]]]);
|
|
161
|
+
for (const key of keys.values()) this.db.prepare(`INSERT INTO background_history_revisions VALUES (?, ?, ?, ?, ?)
|
|
162
|
+
ON CONFLICT(workspace, session, state) DO UPDATE SET content = content + excluded.content, failure = failure + excluded.failure`)
|
|
163
|
+
.run(...key, content ? 1 : 0, failure ? 1 : 0);
|
|
164
|
+
};
|
|
165
|
+
const updateFailure = (key: string, failure: string) => {
|
|
166
|
+
const old = previous.get(key);
|
|
167
|
+
if (old.failure !== failure) { this.changes++; bump(old, false, true); this.db.prepare("UPDATE background_history SET failure = ? WHERE key = ?").run(failure, key); }
|
|
168
|
+
};
|
|
169
|
+
const save = (key: string, meta: any, signature: string, failure: string, unreadable = false, context = signature) => {
|
|
170
|
+
seen.add(key);
|
|
171
|
+
const old = previous.get(key);
|
|
172
|
+
if (old?.signature === signature) { updateFailure(key, failure); return; }
|
|
173
|
+
const origin = meta?.callbackOrigin;
|
|
174
|
+
const known = origin && typeof origin.cwd === "string";
|
|
175
|
+
upsert.run(key, meta?.id ?? key, origin?.cwd ?? "", origin?.sessionId ?? "", known ? 1 : 0, unreadable ? 1 : 0,
|
|
176
|
+
meta?.status ?? "", meta?.startedAt ?? 0, JSON.stringify(meta ?? null), signature, failure, meta?.spawnPid ?? null,
|
|
177
|
+
meta?.durable ? Number(meta.active) : Number(meta?.status === "running"), context);
|
|
178
|
+
this.changes++;
|
|
179
|
+
if (old) bump(old, true, old.failure !== failure);
|
|
180
|
+
bump(previous.get(key), true, old?.failure !== failure);
|
|
181
|
+
};
|
|
182
|
+
const source = this.source();
|
|
183
|
+
let last = "";
|
|
184
|
+
if (source) for (;;) {
|
|
185
|
+
if (this.closed) return;
|
|
186
|
+
const operations = source.prepare(`SELECT * FROM operations WHERE owner_kind = 'parent-session' AND observer_kind = 'local-supervisor'
|
|
187
|
+
AND operation_id > ? ORDER BY operation_id LIMIT 128`).all(last);
|
|
188
|
+
if (!operations.length) break;
|
|
189
|
+
for (const op of operations) {
|
|
190
|
+
if (this.closed) return;
|
|
191
|
+
const key = `d:${op.operation_id}`;
|
|
192
|
+
const waits = source.prepare(`SELECT w.* FROM waits w JOIN wait_dependencies d ON w.wait_id = d.wait_id AND w.generation = d.generation
|
|
193
|
+
WHERE d.operation_id = ? ORDER BY w.wait_id, w.generation`).all(op.operation_id);
|
|
194
|
+
const context = await identity(join(this.directory, "observed", `${op.task_id}.json`));
|
|
195
|
+
const signature = digest([op, waits, context,
|
|
196
|
+
await identity(join(this.directory, "tasks", op.task_id, "result.json")), await identity(join(this.directory, "tasks", op.task_id, "lost.json")),
|
|
197
|
+
// Active runner/wait facts come from the current shared projection.
|
|
198
|
+
op.phase === "running" ? this.project([op]) : null]);
|
|
199
|
+
let meta;
|
|
200
|
+
if (previous.get(key)?.signature !== signature) {
|
|
201
|
+
this.metrics.projections++;
|
|
202
|
+
meta = this.project([op])[0];
|
|
203
|
+
if (meta?.dismissedAt !== undefined) continue;
|
|
204
|
+
meta = { ...meta, callbackOrigin: { cwd: op.owner_workspace, sessionId: op.owner_session_id }, logPath: meta.logPaths?.stdout ?? "" };
|
|
205
|
+
}
|
|
206
|
+
if (meta) save(key, meta, signature, "", false, context);
|
|
207
|
+
else if (previous.get(key)?.signature === signature) seen.add(key);
|
|
208
|
+
}
|
|
209
|
+
last = operations.at(-1).operation_id;
|
|
210
|
+
await yieldTurn();
|
|
211
|
+
}
|
|
212
|
+
let ids: string[] = [];
|
|
213
|
+
try { ids = await readdir(tasksDir()); }
|
|
214
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
|
|
215
|
+
let batch = 0;
|
|
216
|
+
for (const id of ids) {
|
|
217
|
+
if (this.closed) return;
|
|
218
|
+
if (!/^[A-Za-z0-9_-]+$/.test(id)) continue;
|
|
219
|
+
const key = `l:${id}`, path = join(tasksDir(), id);
|
|
220
|
+
const signature = await identity(join(path, "meta.json"));
|
|
221
|
+
const failure = digest([await identity(join(path, "failures.jsonl")), await identity(join(path, "failures.jsonl.observed"))]);
|
|
222
|
+
if (previous.get(key)?.signature === signature) { seen.add(key); updateFailure(key, failure); }
|
|
223
|
+
else {
|
|
224
|
+
this.metrics.metadataReads++;
|
|
225
|
+
const record = inspectMeta(id);
|
|
226
|
+
if (record.found) save(key, record.meta, signature, failure, !record.meta);
|
|
227
|
+
}
|
|
228
|
+
if (++batch % 128 === 0) await yieldTurn();
|
|
229
|
+
}
|
|
230
|
+
if (this.closed) return;
|
|
231
|
+
for (const row of this.db.prepare("SELECT key FROM background_history").all()) {
|
|
232
|
+
if (!seen.has(row.key)) { this.changes++; bump(previous.get(row.key), true, true); this.db.prepare("DELETE FROM background_history WHERE key = ?").run(row.key); }
|
|
233
|
+
}
|
|
234
|
+
this.version = version;
|
|
235
|
+
this.completed = generation === this.generation ? Date.now() : 0;
|
|
236
|
+
this.status = generation === this.generation && version === this.sourceVersion() ? "ready" : "rebuilding";
|
|
237
|
+
this.reason = undefined;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
async close() { this.closed = true; if (this.timer) clearInterval(this.timer); for (const watcher of this.watchers.values()) watcher.close(); this.watchers.clear(); await this.pending; }
|
|
241
|
+
}
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { processMatchesStart } from "../daemon-owner.ts";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { readFileSync, statSync } from "node:fs";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
// @ts-expect-error Generated canonical passive runner observation.
|
|
7
|
+
import { snapshot } from "./domain/background/snapshot.mjs";
|
|
8
|
+
// @ts-expect-error Generated canonical registry queries.
|
|
9
|
+
import { observeMetasForOrigin, belongsToOrigin, readMeta } from "./domain/background/registry.mjs";
|
|
10
|
+
import { BackgroundHistory } from "./background-history.ts";
|
|
11
|
+
import type { WorkScope } from "./read-model.ts";
|
|
12
|
+
|
|
13
|
+
/** Root-owned query connection; never opens a supervisor or mutates source facts. */
|
|
14
|
+
export class BackgroundObservation {
|
|
15
|
+
private db: any;
|
|
16
|
+
private identity?: string;
|
|
17
|
+
private knownCoordinator = false;
|
|
18
|
+
private rows: any[] = [];
|
|
19
|
+
private signature = "";
|
|
20
|
+
private root: string;
|
|
21
|
+
private directory: string;
|
|
22
|
+
private enabled = false;
|
|
23
|
+
private history?: BackgroundHistory;
|
|
24
|
+
private legacy = new Map<string, { origin: { cwd: string; sessionId?: string }; rows: any[]; references: number }>();
|
|
25
|
+
status: "ready" | "degraded" = "ready";
|
|
26
|
+
reason?: string;
|
|
27
|
+
get connectionCount() { return this.db ? 1 : 0; }
|
|
28
|
+
get scopeCount() { return this.legacy.size; }
|
|
29
|
+
livenessReasons(options: { refresh?: boolean } = {}) {
|
|
30
|
+
if (options.refresh !== false) {
|
|
31
|
+
this.enabled = true;
|
|
32
|
+
this.refresh();
|
|
33
|
+
}
|
|
34
|
+
if (!this.db) return [];
|
|
35
|
+
const version = this.db.prepare("SELECT value FROM schema_meta WHERE key = 'schema_version'").get()?.value;
|
|
36
|
+
if (!["1", "2", "3", "4"].includes(version)) return [];
|
|
37
|
+
let operations: any[] = [];
|
|
38
|
+
try { operations = this.db ? this.db.prepare("SELECT * FROM operations WHERE phase = 'running' AND observer_kind = 'local-supervisor' AND terminal_revision = 0").all() : []; }
|
|
39
|
+
catch (error) { this.status = "degraded"; this.reason = String(error); return []; }
|
|
40
|
+
return operations.flatMap((op: any) => {
|
|
41
|
+
try {
|
|
42
|
+
const inspection = snapshot(this.directory, op.task_id);
|
|
43
|
+
const claim = inspection?.claim;
|
|
44
|
+
return claim && !inspection.terminal && inspection.token === op.launch_token && processMatchesStart(claim.pid, claim.pidStartTime)
|
|
45
|
+
? [{ kind: "runner", id: op.task_id, owner: { kind: op.owner_kind, sessionId: op.owner_session_id, workspace: op.owner_workspace }, operationId: op.operation_id,
|
|
46
|
+
lastProgressAt: inspection.command?.startedAt ?? claim.claimedAt,
|
|
47
|
+
nextDeadline: inspection.launch.timeoutSeconds ? inspection.launch.createdAt + inspection.launch.timeoutSeconds * 1000 : null,
|
|
48
|
+
recovery: "observe-existing-runner" }] : [];
|
|
49
|
+
} catch (error) { this.status = "degraded"; this.reason = String(error); return []; }
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
readonly metrics = { runnerSnapshots: 0, activeQueries: 0, historyQueries: 0 };
|
|
53
|
+
constructor(root: string, directory = join(tmpdir(), process.env.VITEST_POOL_ID ? `pi-better-background-tasks-vitest-${process.env.VITEST_POOL_ID}` : "pi-better-background-tasks", "supervisor"), indexDb?: any, changed = () => {}) {
|
|
54
|
+
this.root = root; this.directory = directory;
|
|
55
|
+
if (indexDb) this.history = new BackgroundHistory(indexDb, directory, () => {
|
|
56
|
+
if (this.status === "degraded") throw new Error(this.reason);
|
|
57
|
+
return this.db;
|
|
58
|
+
}, operations => this.project(operations), changed);
|
|
59
|
+
}
|
|
60
|
+
refresh(): boolean {
|
|
61
|
+
if (!this.enabled) return false;
|
|
62
|
+
try {
|
|
63
|
+
const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
|
|
64
|
+
const path = join(this.root, "operation-coordinator.sqlite");
|
|
65
|
+
let identity;
|
|
66
|
+
try { const info = statSync(path, { bigint: true }); identity = `${info.dev}:${info.ino}`; }
|
|
67
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
|
|
68
|
+
if (identity !== this.identity) { this.history?.invalidate(); this.db?.close(); this.db = undefined; this.identity = identity; }
|
|
69
|
+
if (!identity && this.knownCoordinator) throw new Error("Coordinator source disappeared; retaining the previous observation");
|
|
70
|
+
if (identity) {
|
|
71
|
+
this.db ??= new DatabaseSync(path, { readOnly: true });
|
|
72
|
+
this.knownCoordinator = true;
|
|
73
|
+
const version = this.db.prepare("SELECT value FROM schema_meta WHERE key = 'schema_version'").get()?.value;
|
|
74
|
+
if (!["1", "2", "3", "4"].includes(version)) throw new Error("Unsupported coordinator schema");
|
|
75
|
+
}
|
|
76
|
+
this.metrics.activeQueries++;
|
|
77
|
+
const operations = this.db ? this.db.prepare("SELECT * FROM operations WHERE phase = 'running' AND observer_kind = 'local-supervisor'").all() : [];
|
|
78
|
+
// Revisit only known recent terminal identities, never enumerate completed history.
|
|
79
|
+
for (const row of this.rows) {
|
|
80
|
+
if (operations.some((op: any) => op.operation_id === row.operationId)) continue;
|
|
81
|
+
if (row.endedAt && Date.now() - row.endedAt >= 30000) continue;
|
|
82
|
+
const operation = this.db.prepare("SELECT * FROM operations WHERE operation_id = ?").get(row.operationId);
|
|
83
|
+
if (operation) operations.push(operation);
|
|
84
|
+
}
|
|
85
|
+
const rows = this.project(operations);
|
|
86
|
+
for (const entry of this.legacy.values()) {
|
|
87
|
+
const active = observeMetasForOrigin(entry.origin);
|
|
88
|
+
const retained = entry.rows.map(row => readMeta(row.id)).filter((row: any) => row && row.dismissedAt === undefined
|
|
89
|
+
&& row.status !== "running" && (!row.endedAt || Date.now() - row.endedAt < 30000));
|
|
90
|
+
entry.rows = [...active, ...retained];
|
|
91
|
+
}
|
|
92
|
+
const signature = JSON.stringify([rows, [...this.legacy.values()].flatMap(entry => entry.rows).sort((a, b) => a.id.localeCompare(b.id))]);
|
|
93
|
+
const changed = signature !== this.signature || this.status !== "ready";
|
|
94
|
+
if (changed) this.history?.invalidate();
|
|
95
|
+
this.rows = rows; this.signature = signature; this.status = "ready"; this.reason = undefined;
|
|
96
|
+
this.history?.reconcile();
|
|
97
|
+
return changed;
|
|
98
|
+
} catch (error) {
|
|
99
|
+
const reason = String(error);
|
|
100
|
+
const changed = this.status !== "degraded" || this.reason !== reason;
|
|
101
|
+
this.status = "degraded"; this.reason = reason;
|
|
102
|
+
return changed;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
private project(operations: any[]) {
|
|
106
|
+
return operations.map((op: any) => {
|
|
107
|
+
this.metrics.runnerSnapshots++;
|
|
108
|
+
const inspection = snapshot(this.directory, op.task_id);
|
|
109
|
+
let context: any = {};
|
|
110
|
+
try { context = JSON.parse(readFileSync(join(this.directory, "observed", `${op.task_id}.json`), "utf8")); }
|
|
111
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
|
|
112
|
+
const terminal = inspection?.terminal === true || op.terminal_revision > 0;
|
|
113
|
+
const status = inspection?.terminal ? inspection.status : op.terminal_revision > 0 ? op.terminal_outcome : inspection?.status ?? "running";
|
|
114
|
+
const waits = this.db.prepare(`SELECT w.wait_id, w.generation, w.phase FROM waits w JOIN wait_dependencies d
|
|
115
|
+
ON w.wait_id = d.wait_id AND w.generation = d.generation WHERE d.operation_id = ?
|
|
116
|
+
AND w.owner_kind = ? AND w.owner_session_id = ? AND w.owner_workspace = ?
|
|
117
|
+
AND w.phase NOT IN ('consumed', 'cancelled') AND w.dispatch_disarmed = 0`).all(op.operation_id, op.owner_kind, op.owner_session_id, op.owner_workspace)
|
|
118
|
+
.map((w: any) => ({ waitId: w.wait_id, generation: w.generation, phase: w.phase }));
|
|
119
|
+
return { durable: true, id: op.task_id, operationId: op.operation_id, kind: context.kind ?? inspection?.kind ?? "process",
|
|
120
|
+
status, active: !terminal, terminal, attention: terminal && status !== "succeeded", waits,
|
|
121
|
+
owner: { kind: op.owner_kind, sessionId: op.owner_session_id, workspace: op.owner_workspace },
|
|
122
|
+
startedAt: inspection?.result?.startedAt ?? inspection?.launch.createdAt ?? op.created_at,
|
|
123
|
+
endedAt: inspection?.result?.endedAt ?? op.terminal_at ?? undefined,
|
|
124
|
+
cwd: inspection?.launch.cwd ?? op.owner_workspace, name: context.name, command: context.command, argv: context.argv,
|
|
125
|
+
dismissedAt: context.dismissedAt, exitCode: inspection?.result?.exitCode ?? null, logPaths: inspection?.logs ?? {} };
|
|
126
|
+
}).filter(Boolean);
|
|
127
|
+
}
|
|
128
|
+
private legacyScope(scope: { cwd?: string; sessionId?: string }) {
|
|
129
|
+
if (!scope.cwd) throw new Error("Background activity requires an exact workspace");
|
|
130
|
+
const key = JSON.stringify([scope.cwd, scope.sessionId]);
|
|
131
|
+
let entry = this.legacy.get(key);
|
|
132
|
+
if (!entry) {
|
|
133
|
+
if (this.legacy.size >= 128) {
|
|
134
|
+
const oldest = [...this.legacy].find(([, value]) => value.references === 0);
|
|
135
|
+
if (!oldest) throw new Error("runtime-overloaded: Background scope capacity reached; retry later");
|
|
136
|
+
this.legacy.delete(oldest[0]);
|
|
137
|
+
}
|
|
138
|
+
const origin = { cwd: scope.cwd, sessionId: scope.sessionId };
|
|
139
|
+
entry = { origin, rows: observeMetasForOrigin(origin), references: 0 };
|
|
140
|
+
}
|
|
141
|
+
this.legacy.delete(key); this.legacy.set(key, entry);
|
|
142
|
+
return entry;
|
|
143
|
+
}
|
|
144
|
+
retain(scope: { cwd?: string; sessionId?: string }) {
|
|
145
|
+
const entry = this.legacyScope(scope);
|
|
146
|
+
entry.references++;
|
|
147
|
+
let released = false;
|
|
148
|
+
return () => { if (!released) { released = true; entry.references--; } };
|
|
149
|
+
}
|
|
150
|
+
read(scope: WorkScope, index?: any): any[] {
|
|
151
|
+
if (!this.enabled) { this.enabled = true; this.refresh(); }
|
|
152
|
+
const legacy = this.legacyScope(scope);
|
|
153
|
+
if (scope.backgroundHistory) { this.metrics.historyQueries++; return index.records.map((record: any) => record.meta); }
|
|
154
|
+
const legacyRows = legacy.rows;
|
|
155
|
+
const rows = this.rows;
|
|
156
|
+
return [...rows.filter(row => row.owner.kind === "parent-session" && row.dismissedAt === undefined
|
|
157
|
+
&& (scope.backgroundAll || row.owner.workspace === scope.cwd && row.owner.sessionId === scope.sessionId) && (!scope.active || row.active)),
|
|
158
|
+
...legacyRows.filter((row: any) => (scope.backgroundAll || row.callbackOrigin && belongsToOrigin(row, legacy.origin)
|
|
159
|
+
&& (scope.sessionId || row.spawnPid === scope.processId)) && (!scope.active || row.status === "running"))];
|
|
160
|
+
}
|
|
161
|
+
close(): Promise<void> {
|
|
162
|
+
if (this.history) return this.history.close().then(() => { this.db?.close(); });
|
|
163
|
+
this.db?.close(); return Promise.resolve();
|
|
164
|
+
}
|
|
165
|
+
get historyStatus() { return this.history?.status ?? "degraded"; }
|
|
166
|
+
get historyReason() { return this.history?.reason; }
|
|
167
|
+
get historyMetrics() { return this.history?.metrics; }
|
|
168
|
+
historyIndex(scope: WorkScope) {
|
|
169
|
+
this.read({ ...scope, backgroundHistory: false });
|
|
170
|
+
if (!this.history) throw new Error("Background history requires the shared root index");
|
|
171
|
+
return this.history.read(scope);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import { createRequire } from "node:module";
|
|
4
|
+
// @ts-expect-error Generated fixed-version domain implementation.
|
|
5
|
+
import { openStore } from "./domain/coordinator/index.mjs";
|
|
6
|
+
// @ts-expect-error Generated canonical supervisor; only stop is invoked here.
|
|
7
|
+
import { createLocalSupervisor } from "./domain/background/supervisor/supervisor.mjs";
|
|
8
|
+
// @ts-expect-error Generated canonical durable stop records.
|
|
9
|
+
import { readStopRequest, writeStopRequest } from "./domain/background/supervisor/store.mjs";
|
|
10
|
+
// @ts-expect-error Generated canonical host publication contract.
|
|
11
|
+
import { supervisorTerminalPublication } from "./domain/background/terminal-publication.mjs";
|
|
12
|
+
|
|
13
|
+
export type CancellationStage = "accepted" | "before-stop-file" | "after-stop-file" | "after-process-action";
|
|
14
|
+
|
|
15
|
+
/** Startup reads only durable intents, without activating mutation ownership for query clients. */
|
|
16
|
+
export function hasPendingCancellation(root: string): boolean {
|
|
17
|
+
const path = join(root, "operation-coordinator.sqlite");
|
|
18
|
+
if (!existsSync(path)) return false;
|
|
19
|
+
const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
|
|
20
|
+
const db = new DatabaseSync(path, { readOnly: true });
|
|
21
|
+
try {
|
|
22
|
+
const columns = db.prepare("PRAGMA table_info(task_cancellation_requests)").all();
|
|
23
|
+
if (!columns.some((column: any) => column.name === "result_json")) return false;
|
|
24
|
+
return !!db.prepare("SELECT 1 FROM task_cancellation_requests WHERE result_json IS NULL LIMIT 1").get();
|
|
25
|
+
} finally { db.close(); }
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Cancellation only: no arbitrary method, module, launch or wait dispatch. */
|
|
29
|
+
export class RuntimeCancellation {
|
|
30
|
+
private store: any;
|
|
31
|
+
private pending = new Map<string, Promise<unknown>>();
|
|
32
|
+
readonly epoch: number;
|
|
33
|
+
private fault?: (stage: CancellationStage) => void;
|
|
34
|
+
get busy() { return this.pending.size > 0; }
|
|
35
|
+
constructor(root: string, instanceId: string, fault?: (stage: CancellationStage) => void) {
|
|
36
|
+
this.fault = fault;
|
|
37
|
+
this.store = openStore({ path: join(root, "operation-coordinator.sqlite") });
|
|
38
|
+
this.epoch = this.store.cancellationRuntimeEpoch(instanceId);
|
|
39
|
+
for (const admission of this.store.pendingTaskCancellations()) void this.execute(admission);
|
|
40
|
+
}
|
|
41
|
+
async handle(command: Record<string, unknown>) {
|
|
42
|
+
if (Object.keys(command).some(key => !["id", "type", "credential"].includes(key))) throw new Error("not_accepted: unsupported cancellation field");
|
|
43
|
+
if (command.type === "runtime_cancellation_status") return { runtimeEpoch: this.epoch };
|
|
44
|
+
if (typeof command.credential !== "string") throw new Error("not_accepted: permission-unavailable: cancellation credential required");
|
|
45
|
+
let admission;
|
|
46
|
+
try { admission = this.store.authorizedTaskCancellation(command.credential); }
|
|
47
|
+
catch (error) { throw new Error(`not_accepted: ${String(error)}`); }
|
|
48
|
+
const previous = this.store.getTaskCancellation(admission.request);
|
|
49
|
+
if (command.type === "runtime_query_cancellation") return previous?.result?.status === "outcome_unknown" ? { ...previous, state: "outcome_unknown" } : previous ?? { state: "not_accepted" };
|
|
50
|
+
if (command.type !== "runtime_cancel_task") throw new Error("not_accepted: unsupported cancellation operation");
|
|
51
|
+
if (previous?.result) return previous.result.status === "outcome_unknown" ? { ...previous, state: "outcome_unknown" } : previous;
|
|
52
|
+
try { this.store.acceptAuthorizedTaskCancellation({ credential: command.credential, runtimeEpoch: this.epoch }); }
|
|
53
|
+
catch (error) { throw new Error(`not_accepted: ${String(error)}`); }
|
|
54
|
+
this.fault?.("accepted");
|
|
55
|
+
return this.execute(admission);
|
|
56
|
+
}
|
|
57
|
+
private execute(admission: any): Promise<any> {
|
|
58
|
+
const key = JSON.stringify([admission.request.owner, admission.request.idempotencyKey]);
|
|
59
|
+
const running = this.pending.get(key);
|
|
60
|
+
if (running) return running;
|
|
61
|
+
const intent = this.store.getTaskCancellation(admission.request);
|
|
62
|
+
const execution = Promise.resolve().then(async () => {
|
|
63
|
+
try {
|
|
64
|
+
const supervisor = createLocalSupervisor({ directory: admission.directory });
|
|
65
|
+
const stop = readStopRequest(admission.directory, intent.taskId);
|
|
66
|
+
if (stop && stop.token !== intent.expectedLaunchToken) throw new Error("Exact stop token mismatch; refusing recovery");
|
|
67
|
+
let result;
|
|
68
|
+
if (stop) {
|
|
69
|
+
// A durable stop may already have caused a signal before the crash.
|
|
70
|
+
// Observe that exact execution; never repeat an ambiguous process action.
|
|
71
|
+
result = supervisor.inspect(intent.taskId);
|
|
72
|
+
if (result?.token !== intent.expectedLaunchToken) throw new Error("Exact launch token mismatch; refusing recovery");
|
|
73
|
+
} else {
|
|
74
|
+
const inspection = supervisor.snapshot(intent.taskId);
|
|
75
|
+
if (inspection?.token !== intent.expectedLaunchToken) throw new Error("Exact launch token mismatch; refusing action");
|
|
76
|
+
this.fault?.("before-stop-file");
|
|
77
|
+
writeStopRequest(admission.directory, { version: 1, taskId: intent.taskId, token: intent.expectedLaunchToken, requestedAt: Date.now(), reason: intent.reason });
|
|
78
|
+
this.fault?.("after-stop-file");
|
|
79
|
+
result = await supervisor.stop(intent.taskId, { token: intent.expectedLaunchToken, reason: intent.reason });
|
|
80
|
+
this.fault?.("after-process-action");
|
|
81
|
+
}
|
|
82
|
+
if (!result) throw new Error("Exact launch record unavailable; no replacement execution is permitted");
|
|
83
|
+
const inspection = result.inspection ?? result;
|
|
84
|
+
const operation = this.store.getOperation(intent.operationId);
|
|
85
|
+
return this.store.finishTaskCancellationIntent({ request: admission.request, status: result.status, terminal: result.terminal,
|
|
86
|
+
...(result.terminal ? { publication: supervisorTerminalPublication(operation, inspection) } : {}) });
|
|
87
|
+
} catch {
|
|
88
|
+
return { ...this.store.unknownTaskCancellation(admission.request), state: "outcome_unknown" };
|
|
89
|
+
} finally { this.pending.delete(key); }
|
|
90
|
+
});
|
|
91
|
+
this.pending.set(key, execution);
|
|
92
|
+
return execution;
|
|
93
|
+
}
|
|
94
|
+
async close() { await Promise.all(this.pending.values()); this.store.close(); }
|
|
95
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { closeSync, openSync, readFileSync } from "node:fs";
|
|
3
|
+
import { connect } from "node:net";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { stageRuntime } from "../startup/install.ts";
|
|
8
|
+
import { inspectDaemonOwner } from "../daemon-owner.ts";
|
|
9
|
+
import type { RunRemote, ServerArtifact } from "../startup/managed-types.ts";
|
|
10
|
+
import { runtimeRoot } from "./root.ts";
|
|
11
|
+
import { socketPathFor } from "./socket.ts";
|
|
12
|
+
export { WorkClient } from "./work-client.mjs";
|
|
13
|
+
|
|
14
|
+
export interface RuntimeOptions {
|
|
15
|
+
agentDir: string;
|
|
16
|
+
serverDir?: string;
|
|
17
|
+
installRoot?: string;
|
|
18
|
+
timeoutMs?: number;
|
|
19
|
+
signal?: AbortSignal;
|
|
20
|
+
onProgress?: (stage: string) => void;
|
|
21
|
+
offline?: boolean;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** One bounded LF-JSON exchange; importing this module never loads the Pi SDK. */
|
|
25
|
+
export async function runtimeStatus(socketPath: string, agentDir: string, artifact: ServerArtifact, timeoutMs = 2000): Promise<any> {
|
|
26
|
+
return new Promise((resolve, reject) => {
|
|
27
|
+
const socket = connect(socketPath);
|
|
28
|
+
const timer = setTimeout(() => { socket.destroy(); reject(new Error(`runtime-unhealthy: no response at ${socketPath}; inspect the live owner`)); }, timeoutMs);
|
|
29
|
+
let buffer = "", greeted = false;
|
|
30
|
+
const fail = (error: Error) => { clearTimeout(timer); socket.destroy(); reject(error); };
|
|
31
|
+
socket.on("error", fail);
|
|
32
|
+
socket.on("end", () => fail(new Error("runtime-unavailable: server closed the connection")));
|
|
33
|
+
socket.on("connect", () => socket.write(JSON.stringify({ id: "hello", type: "hello", protocolVersion: 1, runtimeRoot: agentDir, requiredCapabilities: ["runtime-status-v1"] }) + "\n"));
|
|
34
|
+
socket.setEncoding("utf8");
|
|
35
|
+
socket.on("data", (chunk: string) => {
|
|
36
|
+
buffer += chunk;
|
|
37
|
+
if (buffer.length > 1024 * 1024) return fail(new Error("runtime-unhealthy: response exceeds 1 MiB"));
|
|
38
|
+
while (buffer.includes("\n")) {
|
|
39
|
+
const index = buffer.indexOf("\n"), line = buffer.slice(0, index); buffer = buffer.slice(index + 1);
|
|
40
|
+
try {
|
|
41
|
+
const reply = JSON.parse(line);
|
|
42
|
+
if (!reply.success) throw new Error(reply.error ?? "runtime-unavailable");
|
|
43
|
+
const data = reply.data;
|
|
44
|
+
if (!greeted) {
|
|
45
|
+
if (reply.id !== "hello" || data?.protocolVersion !== 1 || data.agentDir !== agentDir
|
|
46
|
+
|| data.build?.contentId !== artifact.build.contentId || data.nodeVersion !== artifact.build.nodeVersion
|
|
47
|
+
|| !data.capabilities?.includes("runtime-status-v1") || !data.instanceId) throw new Error("capability-mismatch: root, pinned build, Node or runtime capability differs; update the installed packages together");
|
|
48
|
+
greeted = true;
|
|
49
|
+
socket.write(JSON.stringify({ id: "status", type: "runtime_get_status" }) + "\n");
|
|
50
|
+
} else {
|
|
51
|
+
if (reply.id !== "status") throw new Error("runtime-unhealthy: unexpected response");
|
|
52
|
+
clearTimeout(timer); socket.destroy(); resolve(data);
|
|
53
|
+
}
|
|
54
|
+
} catch (error) { return fail(error as Error); }
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const runLocal: RunRemote = (command, input, timeoutMs) => new Promise((resolve, reject) => {
|
|
61
|
+
const child = spawn("/bin/sh", ["-c", command], { stdio: "pipe", timeout: timeoutMs });
|
|
62
|
+
let stdout = "", stderr = "";
|
|
63
|
+
child.stdout.on("data", chunk => { stdout += chunk; });
|
|
64
|
+
child.stderr.on("data", chunk => { stderr += chunk; });
|
|
65
|
+
child.on("error", reject);
|
|
66
|
+
child.stdin.on("error", () => undefined);
|
|
67
|
+
child.on("close", (exitCode, signal) => resolve({ stdout, stderr, exitCode, timedOut: signal === "SIGTERM" }));
|
|
68
|
+
child.stdin.end(input);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
export async function ensureRuntime(options: RuntimeOptions): Promise<any> {
|
|
72
|
+
options.signal?.throwIfAborted();
|
|
73
|
+
const timeoutMs = options.timeoutMs ?? 15000;
|
|
74
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 120000) throw new Error("Runtime timeout must be from 1 to 120000 ms");
|
|
75
|
+
const platform = `${process.platform}-${process.arch}`;
|
|
76
|
+
const directory = fileURLToPath(new URL("../../artifacts/", import.meta.url));
|
|
77
|
+
let artifact: ServerArtifact;
|
|
78
|
+
try {
|
|
79
|
+
const manifest = JSON.parse(readFileSync(join(directory, `${platform}.json`), "utf8"));
|
|
80
|
+
artifact = { ...manifest, bytes: readFileSync(join(directory, `${platform}.gz`)) };
|
|
81
|
+
} catch (error) { throw new Error(`runtime-unavailable: cannot read pinned artifact for ${platform}; reinstall the standalone package. ${String(error)}`); }
|
|
82
|
+
const { decodeServerArtifact } = await import("../startup/artifact.ts");
|
|
83
|
+
decodeServerArtifact(artifact);
|
|
84
|
+
const root = runtimeRoot(options.agentDir, options.serverDir ?? join(options.agentDir, "server"));
|
|
85
|
+
const socketPath = socketPathFor(root.serverDir);
|
|
86
|
+
const query = () => runtimeStatus(socketPath, root.agentDir, artifact, Math.min(timeoutMs, 2000));
|
|
87
|
+
try { return await query(); }
|
|
88
|
+
catch (error) {
|
|
89
|
+
if (!["ENOENT", "ECONNREFUSED"].includes((error as NodeJS.ErrnoException).code ?? "")) throw error;
|
|
90
|
+
}
|
|
91
|
+
const owner = inspectDaemonOwner(root.serverDir);
|
|
92
|
+
if (owner.status === "live" || owner.status === "ambiguous") throw new Error(`runtime-unhealthy: existing ${owner.status} owner at ${root.serverDir}; no replacement was started`);
|
|
93
|
+
let runtime;
|
|
94
|
+
try { runtime = await stageRuntime({ run: runLocal, artifact, installRoot: options.installRoot ?? join(root.agentDir, "managed-runtime"), signal: options.signal, onProgress: options.onProgress, offline: options.offline }); }
|
|
95
|
+
catch (error) { throw new Error(`runtime-unavailable: ${String(error)}. Connect to the network to cache the pinned runtime, or repair the reported corrupt cache; no fallback manager was started.`); }
|
|
96
|
+
const fd = openSync(join(root.serverDir, "daemon.log"), "a", 0o600);
|
|
97
|
+
try {
|
|
98
|
+
const env = { ...process.env, PI_SERVER_DIR: root.serverDir, PI_CODING_AGENT_DIR: root.agentDir, PI_SERVER_AGENT: "pi" };
|
|
99
|
+
for (const key of ["NODE_OPTIONS", "PI_SERVER_ACTIVATION_ID", "PI_SERVER_ROLLBACK_OPERATION_ID", "PI_SERVER_ROLLBACK_PERMIT"]) delete (env as NodeJS.ProcessEnv)[key];
|
|
100
|
+
const child = spawn(runtime.node, [runtime.entrypoint, "--agent", "pi"], { cwd: root.serverDir, env, detached: true, stdio: ["ignore", fd, fd] });
|
|
101
|
+
child.on("error", () => undefined); child.unref();
|
|
102
|
+
} finally { closeSync(fd); }
|
|
103
|
+
const deadline = Date.now() + timeoutMs;
|
|
104
|
+
while (Date.now() < deadline) {
|
|
105
|
+
options.signal?.throwIfAborted();
|
|
106
|
+
try { return await query(); }
|
|
107
|
+
catch (error) { if (!["ENOENT", "ECONNREFUSED"].includes((error as NodeJS.ErrnoException).code ?? "")) throw error; }
|
|
108
|
+
await delay(50, undefined, { signal: options.signal });
|
|
109
|
+
}
|
|
110
|
+
throw new Error(`runtime-unavailable: startup timed out; inspect ${join(root.serverDir, "daemon.log")}; owner was not replaced`);
|
|
111
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export function createAssignmentReader(path: string): { revision(): string; read(owner: any): any; conversationRevisions(): Map<string, string> | undefined; close(): void };
|