viewable-one 0.12.2 → 0.12.3
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/CHANGELOG.md +47 -0
- package/README.md +2 -2
- package/SPAWN.md +107 -53
- package/glytch.mjs +41 -10
- package/lib/acp.mjs +110 -148
- package/lib/admission.mjs +25 -5
- package/lib/agents.mjs +59 -16
- package/lib/answerTag.mjs +47 -0
- package/lib/atomic.mjs +1 -16
- package/lib/auth.mjs +25 -9
- package/lib/boardside.mjs +28 -12
- package/lib/child.mjs +89 -116
- package/lib/claudeModels.mjs +168 -0
- package/lib/codex-rpc.mjs +2 -2
- package/lib/codex.mjs +43 -63
- package/lib/codexApps.mjs +5 -3
- package/lib/codexToolInputs.mjs +98 -22
- package/lib/codingChecks.mjs +8 -4
- package/lib/conversationRules.mjs +46 -6
- package/lib/detect.mjs +14 -23
- package/lib/devserver.mjs +6 -6
- package/lib/doctor.mjs +4 -2
- package/lib/folderReads.mjs +96 -0
- package/lib/followUps.mjs +170 -0
- package/lib/hosted.mjs +13 -4
- package/lib/init-connect.mjs +29 -10
- package/lib/lateResume.mjs +135 -0
- package/lib/logindaemon.mjs +113 -33
- package/lib/mcpjson.mjs +35 -2
- package/lib/multiwatch.mjs +25 -38
- package/lib/pagePictures.mjs +14 -11
- package/lib/paths.mjs +0 -1
- package/lib/permissionAsk.mjs +341 -58
- package/lib/procs.mjs +73 -2
- package/lib/refusal.mjs +0 -2
- package/lib/restartPass.mjs +39 -11
- package/lib/rowsAnswers.mjs +18 -34
- package/lib/rowsEvents.mjs +20 -2
- package/lib/runner-health.mjs +26 -2
- package/lib/runner.mjs +106 -1363
- package/lib/runnerAdmission.mjs +6 -12
- package/lib/runnerApi.mjs +20 -11
- package/lib/runnerBeat.mjs +384 -0
- package/lib/runnerCompletion.mjs +5 -2
- package/lib/runnerExecute.mjs +227 -0
- package/lib/runnerGates.mjs +338 -0
- package/lib/runnerLaunch.mjs +351 -0
- package/lib/runnerLease.mjs +31 -9
- package/lib/runnerOps.mjs +217 -0
- package/lib/runnerPace.mjs +10 -6
- package/lib/runnerRecovery.mjs +457 -0
- package/lib/runnerRegister.mjs +28 -7
- package/lib/runnerSettlement.mjs +29 -9
- package/lib/spawn.mjs +0 -5
- package/lib/sync.mjs +26 -14
- package/lib/viewableFolder.mjs +8 -2
- package/lib/worktree.mjs +66 -13
- package/lib/writePolicy.mjs +90 -10
- package/package.json +1 -1
package/lib/runnerPace.mjs
CHANGED
|
@@ -203,9 +203,9 @@ export function makeRegistrar({ ttlMs, failureTtlMs = ttlMs, now = Date.now }) {
|
|
|
203
203
|
* so the hub follows the beat: 10 s while polling, 5 min while the runner is
|
|
204
204
|
* joined to its topic. A failed answer lives `failureTtlMs` (number or
|
|
205
205
|
* function, never longer than `ttlMs`), so a retry 10 s after a blip is a real
|
|
206
|
-
* call and not the cached failure. `invalidate(at)` makes
|
|
207
|
-
*
|
|
208
|
-
* event. Every folder hearing the same event passes the same `at`, so they
|
|
206
|
+
* call and not the cached failure. A newer `invalidate(at)` makes existing answers
|
|
207
|
+
* stale, including one started in the same millisecond, so the next beat really
|
|
208
|
+
* asks: a join, a dropped socket or an op event. Every folder hearing the same event passes the same `at`, so they
|
|
209
209
|
* still share the one call that follows. */
|
|
210
210
|
export function makeHeartbeatHub({ ttlMs, memberTtlMs, failureTtlMs, now = Date.now }) {
|
|
211
211
|
const ttl = () => (typeof ttlMs === "function" ? ttlMs() : ttlMs);
|
|
@@ -215,6 +215,7 @@ export function makeHeartbeatHub({ ttlMs, memberTtlMs, failureTtlMs, now = Date.
|
|
|
215
215
|
const alone = new Set(); // refused inside a batch and alone: beats alone
|
|
216
216
|
let last = null;
|
|
217
217
|
let notBefore = -Infinity;
|
|
218
|
+
let generation = 0;
|
|
218
219
|
let batching = true;
|
|
219
220
|
const covered = (answer, ids) => (answer && typeof answer === "object" ? { ...answer, coveredProjectIds: ids } : answer);
|
|
220
221
|
const single = async (projectId, send) => {
|
|
@@ -233,13 +234,13 @@ export function makeHeartbeatHub({ ttlMs, memberTtlMs, failureTtlMs, now = Date.
|
|
|
233
234
|
if (!batching || alone.has(projectId)) return single(projectId, send);
|
|
234
235
|
const at = now();
|
|
235
236
|
members.set(projectId, at);
|
|
236
|
-
let entry = last && last.
|
|
237
|
+
let entry = last && last.generation === generation && fresh(last, at) && (last.ids.includes(projectId) || last.serverFailed) ? last : null;
|
|
237
238
|
if (!entry) {
|
|
238
239
|
const memberMs = memberTtl();
|
|
239
240
|
for (const [id, seen] of members) if (at - seen > memberMs) members.delete(id);
|
|
240
241
|
const ids = [...members.keys()].sort();
|
|
241
242
|
const ttlNow = ttl();
|
|
242
|
-
entry = Object.assign(shareAnswer(() => send(ids), { at, ttlMs: ttlNow, failureTtlMs: failureTtl() }), { ids });
|
|
243
|
+
entry = Object.assign(shareAnswer(() => send(ids), { at, ttlMs: ttlNow, failureTtlMs: failureTtl() }), { ids, generation });
|
|
243
244
|
last = entry;
|
|
244
245
|
}
|
|
245
246
|
const answer = await entry.promise;
|
|
@@ -262,7 +263,10 @@ export function makeHeartbeatHub({ ttlMs, memberTtlMs, failureTtlMs, now = Date.
|
|
|
262
263
|
if (last?.ids.includes(projectId)) last = null;
|
|
263
264
|
},
|
|
264
265
|
invalidate(at = now()) {
|
|
265
|
-
|
|
266
|
+
if (at > notBefore) {
|
|
267
|
+
notBefore = at;
|
|
268
|
+
generation += 1;
|
|
269
|
+
}
|
|
266
270
|
},
|
|
267
271
|
};
|
|
268
272
|
}
|
|
@@ -0,0 +1,457 @@
|
|
|
1
|
+
// Local evidence for immediate recovery. Server rows remain the authority for
|
|
2
|
+
// ownership; this record only proves the old process on THIS computer died.
|
|
3
|
+
// The admission lock serializes sibling watchers, and the server generation
|
|
4
|
+
// fences a late renewal/receipt even after this machine has restarted.
|
|
5
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
6
|
+
import { mkdirSync, writeFileSync, renameSync, readFileSync, readdirSync, unlinkSync, openSync, fsyncSync, closeSync } from "node:fs";
|
|
7
|
+
import { hostname } from "node:os";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
10
|
+
import { acquireAdmission, selfProcessIdentity } from "./admission.mjs";
|
|
11
|
+
import { completionDirectory } from "./runnerSettlement.mjs";
|
|
12
|
+
import { readProcessIdentity } from "./devserver.mjs";
|
|
13
|
+
import { processTable, processGroups, processSnapshot, descendantPids, sameProcessIdentity } from "./procs.mjs";
|
|
14
|
+
import { killTree } from "./kill.mjs";
|
|
15
|
+
import { agentFor } from "./agents.mjs";
|
|
16
|
+
import { wallClockFor, isChatTurn } from "./spawn.mjs";
|
|
17
|
+
|
|
18
|
+
const key = id => createHash("sha256").update(id).digest("hex");
|
|
19
|
+
export const recoveryPath = (project, id, settings) => join(completionDirectory(project, settings), "active", `${key(id)}.json`);
|
|
20
|
+
const save = (path, record) => {
|
|
21
|
+
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
22
|
+
const fd = openSync(temporary, "wx", 0o600);
|
|
23
|
+
try { writeFileSync(fd, JSON.stringify(record)); fsyncSync(fd); } finally { closeSync(fd); }
|
|
24
|
+
renameSync(temporary, path);
|
|
25
|
+
};
|
|
26
|
+
const alive = pid => {
|
|
27
|
+
if (!Number.isInteger(pid) || pid <= 1) return true;
|
|
28
|
+
try { process.kill(pid, 0); return true; } catch (error) { return error.code !== "ESRCH"; }
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
/** The retained evidence is synchronous at launch boundaries; no HTTP request
|
|
32
|
+
* can prevent its working-time clock or child identity from reaching disk. */
|
|
33
|
+
const ownerAlive = async (record, { isAlive = alive, identity = readProcessIdentity } = {}) => {
|
|
34
|
+
if (!isAlive(record.pid)) return false;
|
|
35
|
+
const current = await identity(record.pid);
|
|
36
|
+
if (!Number.isFinite(current?.startedAt)) return null;
|
|
37
|
+
if (!Number.isFinite(record.ownerStartedAt)) {
|
|
38
|
+
// A process that started after the journal was saved cannot be its owner.
|
|
39
|
+
// Otherwise missing evidence proves neither life nor death: do not count
|
|
40
|
+
// it as active, and do not replay work on the assumption its owner died.
|
|
41
|
+
return Number.isFinite(record.savedAt) && current.startedAt > record.savedAt
|
|
42
|
+
&& record.ownerCommand && current.command && current.command !== record.ownerCommand ? false : null;
|
|
43
|
+
}
|
|
44
|
+
return sameProcessIdentity({ startedAt: record.ownerStartedAt }, current);
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
// Empty groups and a leader with another birth time are positive evidence
|
|
48
|
+
// that the old group ended. Persist retirement during capture/recovery, so a
|
|
49
|
+
// recycled number can neither be signalled nor hold a future recovery pass.
|
|
50
|
+
async function retainGroups(record, snapshot, identity, gone, onChange = () => {}) {
|
|
51
|
+
if (!snapshot) return;
|
|
52
|
+
const retained = [];
|
|
53
|
+
for (const group of record.groups ?? []) {
|
|
54
|
+
let occupied = false;
|
|
55
|
+
for (const [pid, pgid] of snapshot) if (pgid === group.pid && !await gone(pid)) { occupied = true; break; }
|
|
56
|
+
const leader = occupied && snapshot.get(group.pid) === group.pid ? await identity(group.pid) : null;
|
|
57
|
+
const recycled = sameProcessIdentity(group, leader) === false;
|
|
58
|
+
if (occupied && !recycled) retained.push(group);
|
|
59
|
+
}
|
|
60
|
+
if (retained.length !== (record.groups ?? []).length) { record.groups = retained; onChange(); }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export async function trackRun(project, run, settings, receipt, { readIdentity = readProcessIdentity, readTable = processTable, readGroups = processGroups, isAlive = alive, now = () => performance.now(), after = setTimeout, cancel = clearTimeout } = {}) {
|
|
64
|
+
if (!run.lease_generation) return null; // Installed server without fencing.
|
|
65
|
+
const path = recoveryPath(project, run.id, settings);
|
|
66
|
+
const directory = join(completionDirectory(project, settings), "active");
|
|
67
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
68
|
+
const lock = await acquireAdmission(project.path, { directory: join(directory, key(run.id)) });
|
|
69
|
+
if (!lock.ok) { const error = new Error(lock.detail); error.recoveryBusy = true; throw error; }
|
|
70
|
+
const started = performance.now();
|
|
71
|
+
const owner = await selfProcessIdentity(readIdentity);
|
|
72
|
+
const preparedResume = run.request?.recovery === true && Boolean(run.request.resumeSessionId);
|
|
73
|
+
const record = { id: run.id, generation: run.lease_generation, instance: run.runner_instance_id ?? settings.runnerInstanceId,
|
|
74
|
+
host: hostname(), pid: process.pid, ownerStartedAt: owner?.startedAt, ownerCommand: owner?.command, budgetMs: wallClockFor(run.request), workingMs: 0, sidecar: receipt.sidecar,
|
|
75
|
+
...(preparedResume ? { launching: true, preparedResume: true } : {}) };
|
|
76
|
+
let closed = false;
|
|
77
|
+
const write = () => {
|
|
78
|
+
record.workingMs = Math.ceil(performance.now() - started);
|
|
79
|
+
record.savedAt = Date.now(); // Recovery charges a surviving agent from here.
|
|
80
|
+
record.sidecar = receipt.sidecar;
|
|
81
|
+
save(path, record);
|
|
82
|
+
};
|
|
83
|
+
const registering = new Set();
|
|
84
|
+
let capturing;
|
|
85
|
+
const capture = () => capturing ??= (async () => {
|
|
86
|
+
await Promise.all(registering);
|
|
87
|
+
for (const saved of record.roots ?? (record.child ? [record.child] : [])) {
|
|
88
|
+
const pid = saved.pid;
|
|
89
|
+
if (!pid) continue;
|
|
90
|
+
if (!isAlive(pid)) {
|
|
91
|
+
saved.exited = true;
|
|
92
|
+
record.roots = record.roots.filter(root => root !== saved);
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
if (!Number.isFinite(saved.startedAt)) continue;
|
|
96
|
+
const root = await readIdentity(pid);
|
|
97
|
+
if (closed) return;
|
|
98
|
+
if (!root) continue;
|
|
99
|
+
// npm changes its process title after launch. While tracking, the
|
|
100
|
+
// birth time fences PID reuse; recovery still requires both fields.
|
|
101
|
+
if (Number.isFinite(saved.startedAt) && saved.startedAt !== root.startedAt) continue;
|
|
102
|
+
const snapshot = await readTable();
|
|
103
|
+
const members = [];
|
|
104
|
+
for (const member of descendantPids(pid, snapshot)) {
|
|
105
|
+
const identity = await readIdentity(member);
|
|
106
|
+
if (identity) members.push({ pid: member, ...identity });
|
|
107
|
+
}
|
|
108
|
+
const verified = await readIdentity(pid);
|
|
109
|
+
if (closed || verified?.startedAt !== root.startedAt || verified?.command !== root.command) continue;
|
|
110
|
+
Object.assign(saved, root);
|
|
111
|
+
const group = record.groups?.find(group => group.pid === pid && (!Number.isFinite(group.startedAt) || group.startedAt === root.startedAt));
|
|
112
|
+
if (group) Object.assign(group, root);
|
|
113
|
+
// Keep reparented tools as well as every agent/check root.
|
|
114
|
+
const seen = new Set(members.map(member => member.pid));
|
|
115
|
+
record.processes = [...members, ...(record.processes ?? []).filter(member => !seen.has(member.pid))];
|
|
116
|
+
}
|
|
117
|
+
if (closed) return;
|
|
118
|
+
if (record.groups?.length) await retainGroups(record, await readGroups(), readIdentity,
|
|
119
|
+
async pid => !isAlive(pid) || (await readIdentity(pid))?.command?.includes("<defunct>"));
|
|
120
|
+
if (!closed) write();
|
|
121
|
+
})().catch(() => { (settings.stopped ??= new Set()).add(run.id); }).finally(() => { capturing = null; });
|
|
122
|
+
// A trailing capture covers a tool that appears during the throttle window,
|
|
123
|
+
// even if the child produces no further output. Only one capture is in flight.
|
|
124
|
+
let outputTimer, pendingOutput, resolveOutput, lastOutput = -Infinity;
|
|
125
|
+
const output = () => {
|
|
126
|
+
if (closed) return Promise.resolve();
|
|
127
|
+
if (pendingOutput) return pendingOutput;
|
|
128
|
+
const wait = Math.max(0, 1000 - (now() - lastOutput));
|
|
129
|
+
pendingOutput = new Promise(resolve => {
|
|
130
|
+
resolveOutput = resolve;
|
|
131
|
+
const take = async () => {
|
|
132
|
+
outputTimer = null;
|
|
133
|
+
if (!closed) {
|
|
134
|
+
lastOutput = now();
|
|
135
|
+
// Output can describe a child created after an in-flight snapshot.
|
|
136
|
+
// Finish that snapshot, then take the one this event requested.
|
|
137
|
+
if (capturing) await capturing;
|
|
138
|
+
if (!closed) await capture();
|
|
139
|
+
}
|
|
140
|
+
pendingOutput = null;
|
|
141
|
+
resolveOutput = null;
|
|
142
|
+
resolve();
|
|
143
|
+
};
|
|
144
|
+
if (wait) { outputTimer = after(take, wait); outputTimer.unref?.(); }
|
|
145
|
+
else void take();
|
|
146
|
+
});
|
|
147
|
+
return pendingOutput;
|
|
148
|
+
};
|
|
149
|
+
const persist = () => { write(); return capture(); };
|
|
150
|
+
try { persist(); } catch (error) { await lock.release(); throw error; }
|
|
151
|
+
const timer = setInterval(() => {
|
|
152
|
+
try { persist(); } catch { (settings.stopped ??= new Set()).add(run.id); }
|
|
153
|
+
}, 5000);
|
|
154
|
+
timer.unref?.();
|
|
155
|
+
return {
|
|
156
|
+
persist,
|
|
157
|
+
output,
|
|
158
|
+
async session() { if (capturing) await capturing; await capture(); },
|
|
159
|
+
launching({ preparedResume = false } = {}) {
|
|
160
|
+
record.launching = true; record.preparedResume = preparedResume; record.child = null; persist();
|
|
161
|
+
},
|
|
162
|
+
onProcess(pid, { group = false } = {}) {
|
|
163
|
+
record.preparedResume = false;
|
|
164
|
+
record.child = { pid };
|
|
165
|
+
const root = record.child;
|
|
166
|
+
(record.roots ??= []).push(root);
|
|
167
|
+
if (group && Number.isInteger(pid) && pid > 1) (record.groups ??= []).push(root);
|
|
168
|
+
// One launch-time probe only. Periodic capture may refresh an anchored
|
|
169
|
+
// identity, but must never adopt a PID whose first probe missed its exit.
|
|
170
|
+
const registration = Promise.resolve(readIdentity(pid)).then(identity => {
|
|
171
|
+
if (closed) return;
|
|
172
|
+
if (Number.isFinite(identity?.startedAt)) Object.assign(root, identity);
|
|
173
|
+
else if (!isAlive(pid)) {
|
|
174
|
+
root.exited = true;
|
|
175
|
+
record.roots = record.roots.filter(saved => saved !== root);
|
|
176
|
+
}
|
|
177
|
+
write();
|
|
178
|
+
}).catch(() => { (settings.stopped ??= new Set()).add(run.id); })
|
|
179
|
+
.finally(() => registering.delete(registration));
|
|
180
|
+
registering.add(registration);
|
|
181
|
+
try { persist(); void output(); } catch { (settings.stopped ??= new Set()).add(run.id); }
|
|
182
|
+
},
|
|
183
|
+
async close({ keep = false } = {}) {
|
|
184
|
+
closed = true; clearInterval(timer);
|
|
185
|
+
if (outputTimer) { cancel(outputTimer); outputTimer = null; }
|
|
186
|
+
resolveOutput?.(); resolveOutput = null; pendingOutput = null;
|
|
187
|
+
try {
|
|
188
|
+
if (!keep) { try { unlinkSync(path); } catch (error) { if (error.code !== "ENOENT") throw error; } }
|
|
189
|
+
} finally { await lock.release(); }
|
|
190
|
+
},
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** No bare-PID kills. A living child must match BOTH start time and command
|
|
195
|
+
* captured while its owner was alive. Unknown evidence leaves the run alone.
|
|
196
|
+
* `killed` says a verified process was still running, so it worked past the
|
|
197
|
+
* last save and that time counts against the run's wall clock. */
|
|
198
|
+
export async function stopOrphan(record, { identity = readProcessIdentity, kill = killTree, isAlive = alive, table = processTable, groups = processGroups, probe = false, onKilled = () => {}, onChange = () => {} } = {}) {
|
|
199
|
+
const blocked = { stopped: false, killed: false };
|
|
200
|
+
if (!record.launching) return { stopped: true, killed: false };
|
|
201
|
+
const child = record.child;
|
|
202
|
+
if (!child?.pid) return { stopped: record.preparedResume === true, killed: false }; // No spawn intent yet; saved conversation only.
|
|
203
|
+
const matches = (saved, current) => sameProcessIdentity(saved, current) === true && Boolean(saved.command) && current?.command === saved.command;
|
|
204
|
+
const gone = async pid => !isAlive(pid) || (await identity(pid))?.command?.includes("<defunct>");
|
|
205
|
+
let uncertain = false;
|
|
206
|
+
let members = [...(record.processes ?? []), ...(record.roots ?? []).filter(root => root.pid !== child.pid)];
|
|
207
|
+
if (record.groups?.length) {
|
|
208
|
+
const snapshot = await groups();
|
|
209
|
+
if (!snapshot) uncertain = true;
|
|
210
|
+
await retainGroups(record, snapshot, identity, gone, onChange);
|
|
211
|
+
for (const group of snapshot ? record.groups : []) {
|
|
212
|
+
const pids = [];
|
|
213
|
+
for (const [pid, pgid] of snapshot) if (pgid === group.pid && !await gone(pid)) pids.push(pid);
|
|
214
|
+
if (!pids.length) continue;
|
|
215
|
+
const candidates = [group, child, ...members];
|
|
216
|
+
let anchored = false;
|
|
217
|
+
for (const saved of candidates) {
|
|
218
|
+
if (pids.includes(saved.pid) && matches(saved, await identity(saved.pid))) anchored = true;
|
|
219
|
+
}
|
|
220
|
+
// A number alone is not an identity. A late tool with no surviving
|
|
221
|
+
// recorded relative holds recovery until it exits; never kill a reused
|
|
222
|
+
// group, including one from a previous boot.
|
|
223
|
+
if (!anchored) { uncertain = true; continue; }
|
|
224
|
+
for (const pid of pids) {
|
|
225
|
+
if (pid === child.pid || await gone(pid)) continue;
|
|
226
|
+
const current = await identity(pid);
|
|
227
|
+
if (!Number.isFinite(current?.startedAt)) { uncertain = true; continue; }
|
|
228
|
+
members.push({ pid, ...current });
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
if (!child.exited && !await gone(child.pid)) {
|
|
233
|
+
const current = await identity(child.pid);
|
|
234
|
+
if (!matches(child, current)) {
|
|
235
|
+
// A positively different birth time is exit evidence, not uncertainty.
|
|
236
|
+
if (sameProcessIdentity(child, current) !== false) uncertain = true;
|
|
237
|
+
}
|
|
238
|
+
else {
|
|
239
|
+
const snapshot = await table();
|
|
240
|
+
if (!snapshot.has(child.pid)) uncertain = true;
|
|
241
|
+
else {
|
|
242
|
+
const discovered = [];
|
|
243
|
+
for (const pid of descendantPids(child.pid, snapshot)) {
|
|
244
|
+
const current = await identity(pid);
|
|
245
|
+
if (!Number.isFinite(current?.startedAt)) { uncertain = true; continue; }
|
|
246
|
+
discovered.push({ pid, ...current });
|
|
247
|
+
}
|
|
248
|
+
if (!matches(child, await identity(child.pid))) uncertain = true;
|
|
249
|
+
else {
|
|
250
|
+
const seen = new Set(discovered.map(member => member.pid));
|
|
251
|
+
members = [...discovered, ...members.filter(member => !seen.has(member.pid)), child];
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
members = [...new Map(members.map(member => [member.pid, member])).values()];
|
|
257
|
+
if (!probe && members.length) {
|
|
258
|
+
// Keep discovered identities before killing their last saved relative:
|
|
259
|
+
// another bridge crash must not leave surviving tools without an anchor.
|
|
260
|
+
record.processes = members;
|
|
261
|
+
onChange();
|
|
262
|
+
}
|
|
263
|
+
const killed = [];
|
|
264
|
+
for (const member of members) {
|
|
265
|
+
if (member.exited) continue;
|
|
266
|
+
if (!Number.isInteger(member.pid) || member.pid <= 1) { uncertain = true; continue; }
|
|
267
|
+
if (await gone(member.pid)) continue;
|
|
268
|
+
const current = await identity(member.pid);
|
|
269
|
+
if (sameProcessIdentity(member, current) === false) continue; // Reused PID belongs to someone else.
|
|
270
|
+
if (!matches(member, current)) { uncertain = true; continue; }
|
|
271
|
+
if (probe) return { ...blocked, active: true };
|
|
272
|
+
try { await kill(member.pid, { force: true }); }
|
|
273
|
+
catch (error) { if (error.code !== "ESRCH") uncertain = true; continue; }
|
|
274
|
+
killed.push(member);
|
|
275
|
+
// Persist before any later group probe, wait, refusal or timeout can
|
|
276
|
+
// return blocked. A later pass cannot infer this survivor from a dead PID.
|
|
277
|
+
onKilled();
|
|
278
|
+
}
|
|
279
|
+
for (let i = 0; i < 30; i++) {
|
|
280
|
+
let running = false;
|
|
281
|
+
for (const member of killed) {
|
|
282
|
+
if (await gone(member.pid)) continue;
|
|
283
|
+
const current = await identity(member.pid);
|
|
284
|
+
// Missing identity while the PID is still present is not proof of exit.
|
|
285
|
+
if (sameProcessIdentity(member, current) !== false) running = true;
|
|
286
|
+
}
|
|
287
|
+
if (!running) {
|
|
288
|
+
// A child may fork between the first snapshot and its signal. The
|
|
289
|
+
// group must actually be empty before any replacement can launch.
|
|
290
|
+
if (record.groups?.length) {
|
|
291
|
+
const snapshot = await groups();
|
|
292
|
+
if (!snapshot) return blocked;
|
|
293
|
+
await retainGroups(record, snapshot, identity, gone, onChange);
|
|
294
|
+
const retained = new Set(record.groups.map(group => group.pid));
|
|
295
|
+
for (const [pid, pgid] of snapshot) if (retained.has(pgid) && !await gone(pid)) return blocked;
|
|
296
|
+
}
|
|
297
|
+
return { stopped: !uncertain, killed: killed.length > 0 };
|
|
298
|
+
}
|
|
299
|
+
await delay(100);
|
|
300
|
+
}
|
|
301
|
+
return blocked;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** How many recovery records here belong to a dead owner on this computer
|
|
305
|
+
* and to no run this process is working on. Local disk only, no request: the
|
|
306
|
+
* beat asks it every time, and only a nonzero answer earns the prompt pass
|
|
307
|
+
* (#616 keeps an idle folder at its usual pace). */
|
|
308
|
+
export function orphanRecoveries(project, settings, live = new Set()) {
|
|
309
|
+
let names;
|
|
310
|
+
try { names = readdirSync(join(completionDirectory(project, settings), "active")); } catch { return 0; }
|
|
311
|
+
let count = 0;
|
|
312
|
+
for (const name of names) {
|
|
313
|
+
if (!/^[a-f0-9]{64}\.json$/.test(name)) continue;
|
|
314
|
+
try {
|
|
315
|
+
const record = JSON.parse(readFileSync(join(completionDirectory(project, settings), "active", name), "utf8"));
|
|
316
|
+
if (record.host === hostname() && record.pid !== process.pid && !live.has(record.id) && !alive(record.pid)) count += 1;
|
|
317
|
+
} catch { /* A record being replaced or unreadable is recoverLocalRun's to report. */ }
|
|
318
|
+
}
|
|
319
|
+
return count;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/** Live local owners still occupy a slot even after the server reaps their
|
|
323
|
+
* row. Read the existing journal, not a second execution registry. */
|
|
324
|
+
// Unverified evidence holds capacity until the saved working budget would end.
|
|
325
|
+
// Recovery itself still waits for exit evidence or Stop (#1249); known live
|
|
326
|
+
// processes continue to occupy capacity without an expiry (#364).
|
|
327
|
+
export async function activeRecoveryRunIds(project, settings, { readSnapshot = processSnapshot, now = Date.now, log = () => {} } = {}) {
|
|
328
|
+
const directory = join(completionDirectory(project, settings), "active");
|
|
329
|
+
let names;
|
|
330
|
+
try { names = readdirSync(directory); } catch { return []; }
|
|
331
|
+
if (!names.some(name => /^[a-f0-9]{64}\.json$/.test(name))) return [];
|
|
332
|
+
const snapshot = await readSnapshot(settings.platform ?? process.platform);
|
|
333
|
+
if (!snapshot) throw new Error("Cannot read the computer's running processes. Waiting before starting another run.");
|
|
334
|
+
const identity = async pid => snapshot.get(pid);
|
|
335
|
+
const isAlive = pid => snapshot.has(pid);
|
|
336
|
+
const groupSnapshot = new Map([...snapshot].filter(([, row]) => Number.isInteger(row.pgid)).map(([pid, row]) => [pid, row.pgid]));
|
|
337
|
+
const groups = async () => groupSnapshot;
|
|
338
|
+
const checkedAt = now();
|
|
339
|
+
const ids = [];
|
|
340
|
+
for (const name of names) {
|
|
341
|
+
if (!/^[a-f0-9]{64}\.json$/.test(name)) continue;
|
|
342
|
+
try {
|
|
343
|
+
const record = JSON.parse(readFileSync(join(directory, name), "utf8"));
|
|
344
|
+
if (typeof record?.id !== "string" || !record.id.trim() || record.host !== hostname()) continue;
|
|
345
|
+
if (await ownerAlive(record, { identity, isAlive }) === true) { ids.push(record.id); continue; }
|
|
346
|
+
if (!record.child?.pid) continue;
|
|
347
|
+
const orphan = await stopOrphan(record, { probe: true, identity, isAlive, groups, table: async () => snapshot });
|
|
348
|
+
const deadline = Number.isFinite(record.savedAt) && Number.isFinite(record.budgetMs) && Number.isFinite(record.workingMs)
|
|
349
|
+
? record.savedAt + Math.max(0, record.budgetMs - record.workingMs) : Infinity;
|
|
350
|
+
if (orphan.active || (!orphan.stopped && checkedAt < deadline)) ids.push(record.id);
|
|
351
|
+
else if (!orphan.stopped) log(`[${record.id}] Cannot identify an old process. This run is still waiting, but it no longer reserves a place for running work. Stop the run if you do not want to wait.`);
|
|
352
|
+
} catch { /* Match orphanRecoveries: malformed or unreadable records do not block claims. */ }
|
|
353
|
+
}
|
|
354
|
+
return ids;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** Is a recovery record for this run still on disk? None means no process on
|
|
358
|
+
* this computer can carry it on, so the restart pass may end its row. */
|
|
359
|
+
export function hasRecoveryRecord(project, id, settings) {
|
|
360
|
+
try { readFileSync(recoveryPath(project, id, settings)); return true; }
|
|
361
|
+
catch (error) { return error.code !== "ENOENT"; }
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** Returns the recovered run, or null. A null that left the record on disk
|
|
365
|
+
* means "try again" (a live owner, a held lock, an unverified child, the
|
|
366
|
+
* network); a null that removed it means this computer can never carry the
|
|
367
|
+
* run on, and the restart pass ends the row once the server has settled it. */
|
|
368
|
+
export async function recoverLocalRun(project, row, settings, api, opts, log = () => {}, { orphanOptions = {}, readSnapshot } = {}) {
|
|
369
|
+
const path = recoveryPath(project, row.id, settings);
|
|
370
|
+
let record;
|
|
371
|
+
const abandon = (why) => {
|
|
372
|
+
log(`[${row.id}] local recovery gave up: ${why}`);
|
|
373
|
+
try { unlinkSync(path); } catch (error) { if (error.code !== "ENOENT") log(`[${row.id}] recovery cleanup failed: ${error.message}`); }
|
|
374
|
+
return null;
|
|
375
|
+
};
|
|
376
|
+
try { record = JSON.parse(readFileSync(path, "utf8")); }
|
|
377
|
+
catch (error) { return error.code === "ENOENT" ? null : abandon(`the record is unreadable (${error.message})`); }
|
|
378
|
+
if (record.host !== hostname() || await ownerAlive(record) !== false) return null;
|
|
379
|
+
const admission = await acquireAdmission(project.path);
|
|
380
|
+
if (!admission.ok) return null;
|
|
381
|
+
try {
|
|
382
|
+
const lock = await acquireAdmission(project.path, { directory: join(completionDirectory(project, settings), "active", key(row.id)) });
|
|
383
|
+
if (!lock.ok) return null;
|
|
384
|
+
try {
|
|
385
|
+
try { record = JSON.parse(readFileSync(path, "utf8")); }
|
|
386
|
+
catch (error) { return error.code === "ENOENT" ? null : abandon(`the record is unreadable (${error.message})`); }
|
|
387
|
+
if (record.host !== hostname() || await ownerAlive(record) !== false) return null;
|
|
388
|
+
if (record.id !== row.id) return abandon("the record names another run");
|
|
389
|
+
// The owner is dead, so its verified children are orphans whatever happens
|
|
390
|
+
// to the row. Nothing is given up while one may still be running.
|
|
391
|
+
const orphan = await stopOrphan(record, { ...orphanOptions, onChange: () => save(path, record), onKilled: () => {
|
|
392
|
+
const killedAt = Date.now();
|
|
393
|
+
if (Number.isFinite(record.savedAt)) record.workingMs += Math.max(0, killedAt - record.savedAt);
|
|
394
|
+
record.savedAt = killedAt;
|
|
395
|
+
save(path, record);
|
|
396
|
+
} });
|
|
397
|
+
if (!orphan.stopped) { log(`[${row.id}] recovery waits: could not verify the old child has stopped`); return null; }
|
|
398
|
+
const acknowledgedTransfer = record.pending && row.lease_generation === record.pending.nextGeneration && row.runner_instance_id === record.pending.runnerInstanceId;
|
|
399
|
+
const source = acknowledgedTransfer ? { generation: row.lease_generation, instance: row.runner_instance_id } : record;
|
|
400
|
+
if (source.generation !== row.lease_generation || source.instance !== row.runner_instance_id) return abandon("another owner holds the run");
|
|
401
|
+
if (row.stop_requested_at) return abandon("Stop was pressed");
|
|
402
|
+
if (row.result != null) return abandon("the run already has its answer");
|
|
403
|
+
const sidecar = { ...row.sidecar, ...record.sidecar };
|
|
404
|
+
const sessionId = sidecar.resumeSessionId ?? (agentFor(row.request.agent) === "codex" ? sidecar.codexThreadId : sidecar.claudeSessionId) ?? row.request.resumeSessionId ?? row.request.sessionId;
|
|
405
|
+
// An interrupted launch without a saved session must not repeat an unknown
|
|
406
|
+
// outward action. Preparation before launch can safely start the first turn.
|
|
407
|
+
if (record.launching && !sessionId) return abandon("the agent started but saved no conversation to carry on");
|
|
408
|
+
// A verified survivor proves work continued (#364). When all processes
|
|
409
|
+
// exited before recovery, their exit time is unknowable: retain the
|
|
410
|
+
// five-second uncertainty margin, not the entire outage (#1249 says
|
|
411
|
+
// asleep/offline time must not exhaust the working-time budget).
|
|
412
|
+
const remainingMs = Math.max(0, Math.floor(record.budgetMs - record.workingMs - 5000));
|
|
413
|
+
if (!remainingMs) return abandon("no working time is left");
|
|
414
|
+
const room = await runningRoom(project, settings, api, { recoveringId: row.id, log, readSnapshot });
|
|
415
|
+
if (!room.ok) return null;
|
|
416
|
+
const instance = settings.runnerInstanceId ??= randomUUID();
|
|
417
|
+
if (!record.pending || record.pending.runnerInstanceId !== instance || (!acknowledgedTransfer && record.pending.generation !== source.generation)) {
|
|
418
|
+
record.pending = { runId: row.id, previousInstanceId: source.instance, generation: source.generation,
|
|
419
|
+
runnerInstanceId: instance, nextGeneration: randomUUID(), remainingMs, sidecar };
|
|
420
|
+
save(path, record);
|
|
421
|
+
}
|
|
422
|
+
const answer = await api.recover(record.pending, opts);
|
|
423
|
+
if (!answer.ok || !answer.run) return answer.transient === true ? null : abandon(`the server refused the transfer (${answer.error ?? "no run came back"})`);
|
|
424
|
+
const recovered = answer.run;
|
|
425
|
+
// Mark the local transfer before releasing its lock. Another watcher must
|
|
426
|
+
// not see a dead owner between the RPC and the launch callback.
|
|
427
|
+
const owner = await selfProcessIdentity();
|
|
428
|
+
save(path, { ...record, pid: process.pid, ownerStartedAt: owner?.startedAt, ownerCommand: owner?.command, generation: recovered.lease_generation, instance, budgetMs: remainingMs, workingMs: 0, savedAt: Date.now(), sidecar, pending: null });
|
|
429
|
+
const request = { ...recovered.request, maxMs: remainingMs, recovery: true };
|
|
430
|
+
if (!record.launching && sidecar.worktreePath && !isChatTurn(request)) request.worktreePath = sidecar.worktreePath;
|
|
431
|
+
if (sessionId && record.launching && request.planMode !== "draft") {
|
|
432
|
+
request.resumeSessionId = sessionId;
|
|
433
|
+
request.prompt = "Your computer restarted; carrying on. Continue the interrupted request from where you were.";
|
|
434
|
+
if (sidecar.worktreePath && !isChatTurn(request)) request.worktreePath = sidecar.worktreePath;
|
|
435
|
+
if (sidecar.recoveryCwd) request.cwd = sidecar.recoveryCwd;
|
|
436
|
+
}
|
|
437
|
+
return { ...recovered, request };
|
|
438
|
+
} finally { await lock.release(); }
|
|
439
|
+
} finally { await admission.release(); }
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
/** Called under the folder admission lock by fresh claims and recovery.
|
|
444
|
+
* Local journals cover held/reaped runs, including a sibling watcher. IDs
|
|
445
|
+
* are a union so a hosted row and its local process occupy only one slot. */
|
|
446
|
+
export async function runningRoom(project, settings, api, { activeRunIds = [], recoveringId, readSnapshot, now, log } = {}) {
|
|
447
|
+
if (!Number.isFinite(settings.maxConcurrent)) return { ok: true };
|
|
448
|
+
const listed = await api.runs({ projectIds: [project.id], status: "running" }, { env: settings.env, fetchImpl: settings.fetchImpl });
|
|
449
|
+
if (!listed.ok) return { ok: false, transient: listed.transient === true, ...(Number.isFinite(listed.retryAfterMs) ? { retryAfterMs: listed.retryAfterMs } : {}), detail: `Cannot verify running sessions: ${listed.error}` };
|
|
450
|
+
let local;
|
|
451
|
+
try { local = await activeRecoveryRunIds(project, settings, { readSnapshot, now, log }); }
|
|
452
|
+
catch (error) { return { ok: false, transient: true, detail: error.message }; }
|
|
453
|
+
const ids = new Set([...(listed.runs ?? []).map(row => row.id), ...activeRunIds, ...local]);
|
|
454
|
+
ids.delete(recoveringId);
|
|
455
|
+
return ids.size < settings.maxConcurrent ? { ok: true }
|
|
456
|
+
: { ok: false, detail: `${ids.size} session(s) already running, and up to ${settings.maxConcurrent} run at once` };
|
|
457
|
+
}
|
package/lib/runnerRegister.mjs
CHANGED
|
@@ -3,10 +3,11 @@
|
|
|
3
3
|
// watch loop in runner.mjs is the caller; runner.mjs re-exports
|
|
4
4
|
// `registerAndFindProject` for the tests that reach it there.
|
|
5
5
|
|
|
6
|
+
import { statSync } from "node:fs";
|
|
6
7
|
import { basename } from "node:path";
|
|
7
8
|
|
|
8
9
|
import * as runnerApiModule from "./runnerApi.mjs";
|
|
9
|
-
import { addFolder, foldersWithoutGit, isScratchFolder, markFolderRestore, readRegistry, withRegistryLock } from "./registry.mjs";
|
|
10
|
+
import { addFolder, foldersWithoutGit, isScratchFolder, markFolderRestore, readRegistry, readRegistryChecked, withRegistryLock } from "./registry.mjs";
|
|
10
11
|
import { platformMark } from "./platform.mjs";
|
|
11
12
|
|
|
12
13
|
/** `register` every folder this machine knows about, plus `root` itself as
|
|
@@ -33,11 +34,28 @@ import { platformMark } from "./platform.mjs";
|
|
|
33
34
|
*/
|
|
34
35
|
export const presenceBody = (settings) => {
|
|
35
36
|
const { platform: _platform, ...rest } = settings.markExtra?.() ?? {};
|
|
36
|
-
|
|
37
|
+
// A scratch folder is never registered, so it is never reported either:
|
|
38
|
+
// the app would otherwise show an old one still on disk again (#3644).
|
|
39
|
+
const availableFolders = settings.projectPaths?.filter((path) => {
|
|
40
|
+
if (isScratchFolder(path, settings.env ?? process.env)) return false;
|
|
41
|
+
try { return statSync(path).isDirectory(); }
|
|
42
|
+
catch (error) { return error.code !== "ENOENT" && error.code !== "ENOTDIR"; }
|
|
43
|
+
});
|
|
44
|
+
return { ...rest, ...(availableFolders ? { availableFolders } : {}), planApproval: true, computerAppsLook: true, folderReads: true, ...(settings.noGit?.length ? { noGit: settings.noGit } : {}) };
|
|
37
45
|
};
|
|
38
46
|
|
|
39
|
-
|
|
40
|
-
|
|
47
|
+
/** Re-read the machine's folder list into `settings.projectPaths` before a
|
|
48
|
+
* heartbeat (#3644). A watch loop registers once, so without this its beat
|
|
49
|
+
* kept the list from its own start and left out a folder added since; the
|
|
50
|
+
* app then hid that folder until its own loop beat. An unreadable registry
|
|
51
|
+
* keeps the last good list. */
|
|
52
|
+
export async function refreshProjectPaths(root, settings) {
|
|
53
|
+
const { folders, ok } = await readRegistryChecked(settings.env ?? process.env);
|
|
54
|
+
if (ok) settings.projectPaths = [...new Set([...folders, root])];
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export async function registerAndFindProject(root, settings, { readd = false, onlyRoot = false } = {}) {
|
|
58
|
+
if (!readd) return registerProject(root, settings, { onlyRoot });
|
|
41
59
|
const env = settings.env ?? process.env;
|
|
42
60
|
return withRegistryLock(async () => {
|
|
43
61
|
await markFolderRestore(root, env);
|
|
@@ -49,12 +67,15 @@ export async function registerAndFindProject(root, settings, { readd = false } =
|
|
|
49
67
|
}, env);
|
|
50
68
|
}
|
|
51
69
|
|
|
52
|
-
|
|
70
|
+
// `onlyRoot` sends just `root`, like the re-add path, without its restore
|
|
71
|
+
// intent: init's failure note must not overwrite the other folders' rows (#4221).
|
|
72
|
+
async function registerProject(root, settings, { readd = false, onlyRoot = false } = {}) {
|
|
53
73
|
const runnerApi = settings.runnerApi ?? runnerApiModule;
|
|
54
74
|
const env = settings.env ?? process.env;
|
|
55
75
|
const folders = await readRegistry(env);
|
|
56
76
|
// Init only owns this folder; a routine daemon register owns the full list.
|
|
57
|
-
|
|
77
|
+
settings.projectPaths = [...new Set([...folders, root])];
|
|
78
|
+
const paths = readd || onlyRoot ? [root] : folders.length > 0 ? folders : [root];
|
|
58
79
|
const list = paths.filter((path) => !isScratchFolder(path, env));
|
|
59
80
|
if (list.length === 0) return { ok: false, error: `${root} is a temporary folder, and those are never registered. Run the runner in a project folder.` };
|
|
60
81
|
// Only init opts in. Capture the removal it intends to undo before any
|
|
@@ -92,5 +113,5 @@ async function registerProject(root, settings, { readd = false } = {}) {
|
|
|
92
113
|
const out = settings.registrar ? await settings.registrar.register(JSON.stringify(list), send) : await send();
|
|
93
114
|
if (!out.ok) return { ok: false, error: out.error, ...(readd ? { readdRequired: Boolean(readdForgottenAt) } : {}), ...(out.transient ? { transient: true } : {}), ...(Number.isFinite(out.retryAfterMs) ? { retryAfterMs: out.retryAfterMs } : {}) };
|
|
94
115
|
const mine = (out.projects ?? []).find((p) => p.path === root);
|
|
95
|
-
return { ok: true, projects: out.projects ?? [], myProjectId: mine?.id };
|
|
116
|
+
return { ok: true, projects: out.projects ?? [], myProjectId: mine?.id, runnerId };
|
|
96
117
|
}
|
package/lib/runnerSettlement.mjs
CHANGED
|
@@ -22,13 +22,13 @@ export async function prepareCompletionStore(project, settings) {
|
|
|
22
22
|
return dir;
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
-
async function writeReceipt(project, runId, patch, settings) {
|
|
25
|
+
async function writeReceipt(project, runId, patch, settings, events) {
|
|
26
26
|
const dir = await prepareCompletionStore(project, settings);
|
|
27
|
-
const path = join(dir, `${digest(runId)}.json`);
|
|
27
|
+
const path = join(dir, `${digest(runId)}${events ? `-events-${events[0].seq}` : ""}.json`);
|
|
28
28
|
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
29
29
|
const handle = await open(temporary, "wx", 0o600);
|
|
30
30
|
try {
|
|
31
|
-
await handle.writeFile(JSON.stringify({ projectId: project.id, runId, patch }));
|
|
31
|
+
await handle.writeFile(JSON.stringify({ projectId: project.id, runId, ...(settings.runGeneration ? { generation: settings.runGeneration } : {}), ...(events ? { events } : { patch }) }));
|
|
32
32
|
await handle.sync();
|
|
33
33
|
} finally { await handle.close(); }
|
|
34
34
|
try { await rename(temporary, path); }
|
|
@@ -44,9 +44,12 @@ async function deliver(path, record, settings, log, attempts) {
|
|
|
44
44
|
const options = { env: settings.env, fetchImpl: settings.fetchImpl };
|
|
45
45
|
let last;
|
|
46
46
|
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
|
47
|
-
try { last =
|
|
47
|
+
try { last = record.events
|
|
48
|
+
? await api.events({ runId: record.runId, events: record.events }, options)
|
|
49
|
+
: await api.update({ runId: record.runId, patch: record.patch, ...(record.generation ? { generation: record.generation } : {}) }, options); }
|
|
48
50
|
catch (error) { last = { ok: false, error: error.message }; }
|
|
49
|
-
if (last?.ok) {
|
|
51
|
+
if (last?.ok || last?.error === "runner ownership lost") {
|
|
52
|
+
if (!last.ok) log(`[${record.runId}] discarded receipt from an older lease generation`);
|
|
50
53
|
await unlink(path).catch(error => { if (error.code !== "ENOENT") log(`[${record.runId}] completion acknowledged; local cleanup will retry: ${error.message}`); });
|
|
51
54
|
return true;
|
|
52
55
|
}
|
|
@@ -59,9 +62,23 @@ async function deliver(path, record, settings, log, attempts) {
|
|
|
59
62
|
try { return await task; } finally { replaying.delete(path); }
|
|
60
63
|
}
|
|
61
64
|
|
|
65
|
+
/** Persist every queued event before attempting network delivery. Event names
|
|
66
|
+
* retain the server's (run, sequence) idempotency key across process restarts. */
|
|
67
|
+
export async function retainRunEvents(project, runId, events, settings) {
|
|
68
|
+
for (const event of events) await writeReceipt(project, runId, undefined, settings, [event]);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export async function deliverRunEvents(project, runId, events, settings, log = () => {}) {
|
|
72
|
+
for (const event of events) {
|
|
73
|
+
const path = join(completionDirectory(project, settings), `${digest(runId)}-events-${event.seq}.json`);
|
|
74
|
+
if (!await deliver(path, { projectId: project.id, runId, events: [event] }, settings, log, 1)) return { ok: false };
|
|
75
|
+
}
|
|
76
|
+
return { ok: true };
|
|
77
|
+
}
|
|
78
|
+
|
|
62
79
|
export async function settleRun(project, runId, patch, settings, log = () => {}, { deferDelivery = false } = {}) {
|
|
63
80
|
if (!terminal.has(patch.status)) throw new Error("A terminal receipt requires a terminal status.");
|
|
64
|
-
const record = { projectId: project.id, runId, patch };
|
|
81
|
+
const record = { projectId: project.id, runId, patch, ...(settings.runGeneration ? { generation: settings.runGeneration } : {}) };
|
|
65
82
|
const memoryKey = join(completionDirectory(project, settings), digest(runId));
|
|
66
83
|
memoryReceipts.set(memoryKey, record);
|
|
67
84
|
let path;
|
|
@@ -96,17 +113,20 @@ export async function flushCompletions(project, settings, log = () => {}) {
|
|
|
96
113
|
let complete = true;
|
|
97
114
|
for (const [key, record] of [...memoryReceipts]) {
|
|
98
115
|
if (key !== join(dir, digest(record.runId))) continue;
|
|
99
|
-
const result = await settleRun(project, record.runId, record.patch, settings, log);
|
|
116
|
+
const result = await settleRun(project, record.runId, record.patch, { ...settings, runGeneration: record.generation }, log);
|
|
100
117
|
if (result.state === "pending-sync") complete = false;
|
|
101
118
|
}
|
|
102
119
|
let names;
|
|
103
120
|
try { names = await readdir(dir); }
|
|
104
121
|
catch (error) { if (error.code === "ENOENT") return complete; throw error; }
|
|
105
|
-
for (const name of names.filter(name => /^[a-f0-9]{64}
|
|
122
|
+
for (const name of names.filter(name => /^[a-f0-9]{64}(?:-events-[1-9][0-9]*)?\.json$/.test(name)).sort((a, b) => a.localeCompare(b, "en", { numeric: true }))) {
|
|
106
123
|
const path = join(dir, name);
|
|
107
124
|
try {
|
|
108
125
|
const record = JSON.parse(await readFile(path, "utf8"));
|
|
109
|
-
|
|
126
|
+
const event = record.events?.[0];
|
|
127
|
+
const validEvents = Array.isArray(record.events) && record.events.length === 1 && Number.isSafeInteger(event?.seq) && event.seq > 0 && ["log", "cut"].includes(event.kind) && typeof event.text === "string";
|
|
128
|
+
const expected = `${digest(record.runId)}${validEvents ? `-events-${event.seq}` : ""}.json`;
|
|
129
|
+
if (record.projectId !== project.id || typeof record.runId !== "string" || expected !== name || !(validEvents || terminal.has(record.patch?.status))) throw new Error("Invalid saved completion receipt");
|
|
110
130
|
if (!(await deliver(path, record, settings, log, 1))) complete = false;
|
|
111
131
|
} catch (error) {
|
|
112
132
|
if (error.code === "ENOENT") continue;
|