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.
Files changed (59) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +2 -2
  3. package/SPAWN.md +107 -53
  4. package/glytch.mjs +41 -10
  5. package/lib/acp.mjs +110 -148
  6. package/lib/admission.mjs +25 -5
  7. package/lib/agents.mjs +59 -16
  8. package/lib/answerTag.mjs +47 -0
  9. package/lib/atomic.mjs +1 -16
  10. package/lib/auth.mjs +25 -9
  11. package/lib/boardside.mjs +28 -12
  12. package/lib/child.mjs +89 -116
  13. package/lib/claudeModels.mjs +168 -0
  14. package/lib/codex-rpc.mjs +2 -2
  15. package/lib/codex.mjs +43 -63
  16. package/lib/codexApps.mjs +5 -3
  17. package/lib/codexToolInputs.mjs +98 -22
  18. package/lib/codingChecks.mjs +8 -4
  19. package/lib/conversationRules.mjs +46 -6
  20. package/lib/detect.mjs +14 -23
  21. package/lib/devserver.mjs +6 -6
  22. package/lib/doctor.mjs +4 -2
  23. package/lib/folderReads.mjs +96 -0
  24. package/lib/followUps.mjs +170 -0
  25. package/lib/hosted.mjs +13 -4
  26. package/lib/init-connect.mjs +29 -10
  27. package/lib/lateResume.mjs +135 -0
  28. package/lib/logindaemon.mjs +113 -33
  29. package/lib/mcpjson.mjs +35 -2
  30. package/lib/multiwatch.mjs +25 -38
  31. package/lib/pagePictures.mjs +14 -11
  32. package/lib/paths.mjs +0 -1
  33. package/lib/permissionAsk.mjs +341 -58
  34. package/lib/procs.mjs +73 -2
  35. package/lib/refusal.mjs +0 -2
  36. package/lib/restartPass.mjs +39 -11
  37. package/lib/rowsAnswers.mjs +18 -34
  38. package/lib/rowsEvents.mjs +20 -2
  39. package/lib/runner-health.mjs +26 -2
  40. package/lib/runner.mjs +106 -1363
  41. package/lib/runnerAdmission.mjs +6 -12
  42. package/lib/runnerApi.mjs +20 -11
  43. package/lib/runnerBeat.mjs +384 -0
  44. package/lib/runnerCompletion.mjs +5 -2
  45. package/lib/runnerExecute.mjs +227 -0
  46. package/lib/runnerGates.mjs +338 -0
  47. package/lib/runnerLaunch.mjs +351 -0
  48. package/lib/runnerLease.mjs +31 -9
  49. package/lib/runnerOps.mjs +217 -0
  50. package/lib/runnerPace.mjs +10 -6
  51. package/lib/runnerRecovery.mjs +457 -0
  52. package/lib/runnerRegister.mjs +28 -7
  53. package/lib/runnerSettlement.mjs +29 -9
  54. package/lib/spawn.mjs +0 -5
  55. package/lib/sync.mjs +26 -14
  56. package/lib/viewableFolder.mjs +8 -2
  57. package/lib/worktree.mjs +66 -13
  58. package/lib/writePolicy.mjs +90 -10
  59. package/package.json +1 -1
package/lib/procs.mjs CHANGED
@@ -24,6 +24,15 @@ import { join, win32 } from "node:path";
24
24
 
25
25
  import { killTree } from "./kill.mjs";
26
26
 
27
+ /** Compare observations of the same PID. Only a known different birth proves
28
+ * replacement; absent evidence is null, never permission to reclaim or kill.
29
+ * Commands can change during a process's life, so signalling callers must
30
+ * additionally check the recorded command before acting. */
31
+ export function sameProcessIdentity(saved, current) {
32
+ if (!Number.isFinite(saved?.startedAt) || !Number.isFinite(current?.startedAt)) return null;
33
+ return saved.startedAt === current.startedAt;
34
+ }
35
+
27
36
  /** argv[0]'s basename, on either slash style. `win32.basename` treats BOTH
28
37
  * "/" and "\" as separators (Windows accepts a forward-slash path too), so
29
38
  * it is a strict superset of the old `argv0.slice(argv0.lastIndexOf("/") +
@@ -167,12 +176,12 @@ export function parseWin32ProcessTable(json) {
167
176
 
168
177
  const runOut = (bin, args, timeout = 15_000) =>
169
178
  new Promise((done) => {
170
- execFile(bin, args, { timeout, maxBuffer: 8 * 1024 * 1024, windowsHide: true }, (error, stdout) =>
179
+ execFile(bin, args, { timeout, maxBuffer: 8 * 1024 * 1024, windowsHide: true, env: { ...process.env, LC_ALL: "C" } }, (error, stdout) =>
171
180
  done(error ? "" : String(stdout ?? "")),
172
181
  );
173
182
  });
174
183
 
175
- async function processTable(platform = process.platform) {
184
+ export async function processTable(platform = process.platform) {
176
185
  if (platform === "win32") return parseWin32ProcessTable(await runOut("powershell.exe", CIM_TABLE_ARGS));
177
186
  return new Promise((done) => {
178
187
  execFile("ps", ["-eo", "pid,ppid,args"], { timeout: 10_000, maxBuffer: 4 * 1024 * 1024 }, (error, stdout) => {
@@ -181,6 +190,68 @@ async function processTable(platform = process.platform) {
181
190
  });
182
191
  }
183
192
 
193
+ /** One identity-bearing listing for admission across every local journal.
194
+ * null is probe failure, not an empty computer. Windows has no POSIX groups. */
195
+ export async function processSnapshot(platform = process.platform, run = runOut) {
196
+ const windows = platform === "win32";
197
+ const output = windows
198
+ ? await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command",
199
+ "Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,CommandLine,Name,@{Name='StartedAt';Expression={([DateTimeOffset]$_.CreationDate).ToUnixTimeMilliseconds()}} | ConvertTo-Json -Compress"])
200
+ : await run("ps", ["-eo", "pid=,ppid=,pgid=,lstart=,args="]);
201
+ if (!output.trim()) return null;
202
+ const snapshot = new Map();
203
+ if (windows) {
204
+ let rows;
205
+ try { rows = JSON.parse(output); } catch { return null; }
206
+ if (!rows) return null;
207
+ for (const row of Array.isArray(rows) ? rows : [rows]) {
208
+ if (!row || !Number.isInteger(row.ProcessId) || row.ProcessId < 0) return null;
209
+ snapshot.set(row.ProcessId, { ppid: Number(row.ParentProcessId), startedAt: row.StartedAt,
210
+ command: String(row.CommandLine ?? row.Name ?? "").trim() });
211
+ }
212
+ } else for (const line of output.trim().split("\n")) {
213
+ const match = line.trim().match(/^(\d+)\s+(\d+)\s+(\d+)\s+(\w{3}\s+\w{3}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2}\s+\d{4})\s+(.*)$/);
214
+ // ps may print argv continuations on separate lines. Keep valid rows.
215
+ if (!match) continue;
216
+ snapshot.set(Number(match[1]), { ppid: Number(match[2]), pgid: Number(match[3]),
217
+ startedAt: Date.parse(match[4]), command: match[5].trim() });
218
+ }
219
+ return snapshot.size ? snapshot : null;
220
+ }
221
+
222
+ /** POSIX groups survive their leader. null means the probe failed, never
223
+ * proof that a group is empty. Windows recovery uses retained identities. */
224
+ export async function processGroups(platform = process.platform) {
225
+ if (platform === "win32") return null;
226
+ const output = await runOut("ps", ["-eo", "pid=,pgid="]);
227
+ if (!output.trim()) return null;
228
+ const groups = new Map();
229
+ for (const line of output.trim().split("\n")) {
230
+ const match = line.trim().match(/^(\d+)\s+(\d+)$/);
231
+ if (!match) return null;
232
+ groups.set(Number(match[1]), Number(match[2]));
233
+ }
234
+ return groups;
235
+ }
236
+
237
+ /** A verified root's descendants, leaves first. Snapshot before killing the
238
+ * parent so reparenting cannot hide its tool processes from recovery. */
239
+ export function descendantPids(pid, table) {
240
+ const children = new Map();
241
+ for (const [id, row] of table) {
242
+ if (id > 1) children.set(row.ppid, [...(children.get(row.ppid) ?? []), id]);
243
+ }
244
+ const visited = new Set([pid]), order = [];
245
+ const visit = parent => {
246
+ for (const child of children.get(parent) ?? []) {
247
+ if (visited.has(child)) continue;
248
+ visited.add(child); visit(child); order.push(child);
249
+ }
250
+ };
251
+ visit(pid);
252
+ return order;
253
+ }
254
+
184
255
  /** May this daemon kill `pid`? Only if it is a session this daemon left
185
256
  * behind, by one of two tests:
186
257
  *
package/lib/refusal.mjs CHANGED
@@ -31,8 +31,6 @@ export class Refusal extends Error {
31
31
  }
32
32
  }
33
33
 
34
- export const isRefusal = (error) => error instanceof Refusal;
35
-
36
34
  /** Collect problems, keep going, refuse once with all of them.
37
35
  *
38
36
  * A caller stops its pass early only when there is genuinely nothing left to
@@ -6,8 +6,10 @@
6
6
  // conversation and copy. Every child can itself be recovered later.
7
7
  // Stop lives in stop_requested_at, including on a reaped row; both the
8
8
  // candidate check and the hosted resume op honour it. The existing SQL
9
- // row lock serializes competing settles. No migration is needed.
9
+ // row lock serializes competing settles. Generation-fenced rows instead use
10
+ // local dead-owner evidence and transfer the original row through recovery.
10
11
 
12
+ import { hasRecoveryRecord, recoverLocalRun } from "./runnerRecovery.mjs";
11
13
  import { randomUUID } from "node:crypto";
12
14
  import { stat } from "node:fs/promises";
13
15
  import * as runnerApiModule from "./runnerApi.mjs";
@@ -28,6 +30,10 @@ export const liveRuns = new Set();
28
30
  /** The second look: after the lease has run out and the reaper has run. */
29
31
  export const RESTART_RECHECK_MS = 7 * 60_000;
30
32
 
33
+ /** The prompt look, only while a dead owner's recovery record waits on this
34
+ * computer (orphanRecoveries): local recovery need not wait for the lease. */
35
+ export const RECOVERY_RECHECK_MS = 30_000;
36
+
31
37
  const timeOf = (value) => (value ? Date.parse(value) : NaN);
32
38
  const isReaped = (row) => row.status === "error" && Boolean(row.recovery_reason) && (row.result === null || row.result === undefined);
33
39
 
@@ -35,15 +41,21 @@ const isReaped = (row) => row.status === "error" && Boolean(row.recovery_reason)
35
41
  export function restartCandidate(row, { now = Date.now() } = {}) {
36
42
  const request = row?.request;
37
43
  if (!request || typeof request !== "object" || liveRuns.has(row.id)) return false;
44
+ if (row.sidecar?.restarted === true) return false;
45
+ // A person pressed Stop and the computer died before it was heard: the
46
+ // stop stands. Nothing is carried on that a person ended.
47
+ if (row.stop_requested_at) return false;
48
+ // A fenced row is local recovery's while it runs. Once the server has
49
+ // settled it, this pass is the only one that ends it, so its card or chat
50
+ // turn never waits forever (#4948), whether or not it was marked
51
+ // restartable; the caller also checks no record keeps it here. It is only
52
+ // ever ended, never resumed (carryOn).
53
+ if (row.lease_generation) return row.status === "error" && (isReaped(row) || row.sidecar?.recoveryPending === true);
38
54
  // Older Run-button runs already ended in the app. Never start paid work
39
55
  // again for those rows. Older note sessions have always waited for recovery.
40
56
  if (row.sidecar?.restartable !== true && !(typeof request.note?.noteId === "string" && request.note.noteId.length > 0)) return false;
41
- if (row.sidecar?.restarted === true) return false;
42
57
  if (isChatTurn(request) || request.planMode === "draft") return false;
43
58
  if (!fromIdOf(request) && !row.from_id) return false;
44
- // A person pressed Stop and the computer died before it was heard: the
45
- // stop stands. Nothing is carried on that a person ended.
46
- if (row.stop_requested_at) return false;
47
59
  if (row.status === "running") {
48
60
  // A lease still running belongs to a live process (the server leases for
49
61
  // five minutes and a process renews every thirty seconds); only one that
@@ -61,7 +73,7 @@ const isDirectory = async (path) => {
61
73
 
62
74
  /** One pass over one folder. Returns what it did, for the log and the test:
63
75
  * `{resumed: [runId], ended: [runId], skipped: [runId]}`. Never throws. */
64
- export async function restartPass(project, settings, { log = () => {}, now = Date.now } = {}) {
76
+ export async function restartPass(project, settings, { log = () => {}, now = Date.now, startRun } = {}) {
65
77
  const done = { resumed: [], ended: [], skipped: [] };
66
78
  const api = settings.runnerApi ?? runnerApiModule;
67
79
  const opts = { env: settings.env, fetchImpl: settings.fetchImpl };
@@ -79,7 +91,16 @@ export async function restartPass(project, settings, { log = () => {}, now = Dat
79
91
  return done;
80
92
  }
81
93
 
82
- for (const row of rows.filter((r) => restartCandidate(r, { now: now() }))) {
94
+ if (startRun) for (const row of rows.filter(row => row.lease_generation && !liveRuns.has(row.id))) {
95
+ try {
96
+ const recovered = await recoverLocalRun(project, row, settings, api, opts, log);
97
+ if (recovered) { startRun(recovered); done.resumed.push(row.id); }
98
+ } catch (error) { log(`[${row.id}] local recovery failed: ${error.message}`); }
99
+ }
100
+ // A fenced row whose record is still here belongs to a live owner or to a
101
+ // recovery that will try again; only a row nobody here can carry on ends.
102
+ const ours = (row) => !row.lease_generation || (!done.resumed.includes(row.id) && !hasRecoveryRecord(project, row.id, settings));
103
+ for (const row of rows.filter((r) => restartCandidate(r, { now: now() }) && ours(r))) {
83
104
  try {
84
105
  const outcome = await carryOn(row, { api, opts, log, now });
85
106
  done[outcome].push(row.id);
@@ -97,7 +118,14 @@ async function carryOn(row, { api, opts, log, now }) {
97
118
  const engine = agentFor(request.agent);
98
119
  const sessionId = (engine === "codex" ? [sidecar.codexThreadId, request.resumeSessionId] : [sidecar.claudeSessionId, request.resumeSessionId, request.sessionId])
99
120
  .find((v) => typeof v === "string" && v.trim() !== "")?.trim();
100
- const canResume = ["claude", "codex"].includes(engine) && acceptsMessages(request) && treeKept && sessionId !== undefined;
121
+ // Fenced rows reach here only to be ended: local recovery owns carrying
122
+ // them on with the record's own budget, and once it gave up (no time
123
+ // left, no conversation) a resume here would start paid work it refused.
124
+ const resumable = !row.lease_generation && !isChatTurn(request) && request.planMode !== "draft" && Boolean(fromIdOf(request) || row.from_id);
125
+ const canResume = resumable && ["claude", "codex"].includes(engine) && acceptsMessages(request) && treeKept && sessionId !== undefined;
126
+ // The row's own generation: if anyone took it over since the listing, the
127
+ // server refuses these writes instead of ending somebody else's run.
128
+ const fence = row.lease_generation ? { generation: row.lease_generation } : {};
101
129
  // A running row without its copy gets a second look after the reaper.
102
130
  if (!canResume && acceptsMessages(request) && !treeKept && row.status === "running") {
103
131
  log(`[${row.id}] restart pass: no kept worktree to carry on in; leaving it to the reaper`);
@@ -115,7 +143,7 @@ async function carryOn(row, { api, opts, log, now }) {
115
143
  const remainingMs = Math.max(0, wallClockFor(request) - workingMs);
116
144
  const settledSidecar = sidecar.recoveryPending === true ? sidecar : { ...sidecar, recoveryPending: true, ...(!canResume || remainingMs <= 0 ? { recoveryFailed: true } : {}), remainingWorkingMs: remainingMs, ...(canResume ? { [engine === "codex" ? "codexThreadId" : "claudeSessionId"]: sessionId } : {}), restartedAt: new Date(now()).toISOString(), restartAttempt: randomUUID() };
117
145
  const settled = sidecar.recoveryPending === true ? { ok: true } : await api.update({
118
- runId: row.id,
146
+ runId: row.id, ...fence,
119
147
  patch: {
120
148
  sidecar: settledSidecar,
121
149
  // No "carried on" claim here (round 2, item 59): the resume does not
@@ -135,7 +163,7 @@ async function carryOn(row, { api, opts, log, now }) {
135
163
  const childId = resumed.run?.id ?? resumed.id;
136
164
  if (resumed.ok && childId) {
137
165
  log(`[${row.id}] restart pass: carried on as ${childId}`);
138
- await api.update({ runId: row.id, patch: { sidecar: { ...settledSidecar, recoveryPending: false, restarted: true, restartedTo: childId } } }, opts)
166
+ await api.update({ runId: row.id, ...fence, patch: { sidecar: { ...settledSidecar, recoveryPending: false, restarted: true, restartedTo: childId } } }, opts)
139
167
  .catch(() => {});
140
168
  return "resumed";
141
169
  }
@@ -145,7 +173,7 @@ async function carryOn(row, { api, opts, log, now }) {
145
173
 
146
174
  // Persist the outcome on the row. Every app tab derives the same ending;
147
175
  // there is no racing generic comment with different words or missing chips.
148
- await api.update({ runId: row.id, patch: { sidecar: { ...settledSidecar, recoveryPending: false, restarted: true, recoveryFailed: true } } }, opts);
176
+ await api.update({ runId: row.id, ...fence, patch: { sidecar: { ...settledSidecar, recoveryPending: false, restarted: true, recoveryFailed: true } } }, opts);
149
177
  log(`[${row.id}] restart pass: this session cannot carry on`);
150
178
  return "ended";
151
179
  }
@@ -317,40 +317,19 @@ export function createRowsAnswerPoll({ callTool = hostedCallTool, sessionKey, en
317
317
  export const lateRowRequestId = (requestId, tag) =>
318
318
  `spawn-reply-${createHash("sha256").update(`${requestId} ${tag}`).digest("hex")}`;
319
319
 
320
- /** After the child has exited, ONE more collect_session call - the row
321
- * equivalent of `promoteLateReplies` sweeping a `.reply-*.json` written
322
- * after stdin closed. A late ANSWER or MESSAGE for a PERSISTENT session
323
- * becomes a resume request through the exact function a late reply file
324
- * already uses (`promoteReplyToRequest`, fed a row instead of a file) -
325
- * the worktree, the resume session id, and "was this ever approved" are
326
- * all its, unchanged; it already refuses (returns null) for a one-shot
327
- * session via its own `acceptsMessages` check, which is what makes "log
328
- * and drop, same as today" the natural result of calling it here too
329
- * rather than a second branch to keep in sync with the first.
330
- *
331
- * KNOWN GAP, spelled out rather than hidden: a MESSAGE that arrived WHILE
332
- * the child was still running, in the same poll tick the child happened to
333
- * exit on, is marked delivered server-side by that poll (collect_session's
334
- * own `takeMessages` stamps `delivered_at` on fetch, not on successful
335
- * delivery to a pipe) whether or not `sendToChild` actually got to write
336
- * it - `child.mjs`'s `watchAnswers` breaks out of its delivery loop the
337
- * moment the child is settled, before calling `onDelivered`. Such a
338
- * message will not be seen again by THIS poll (it is no longer
339
- * undelivered on the server) or by this sweep (it is not "late" - it was
340
- * already fetched). It is the one situation this design does not recover,
341
- * and it is symmetric with why a message needs no in-memory delivered set
342
- * at all: the same field that makes redelivery impossible also makes this
343
- * one narrow race unrecoverable. An ANSWERED QUESTION has no such gap - it
344
- * carries no delivered_at, so it is simply asked for again next time,
345
- * here or on the next live poll. */
320
+ /** Sweep after exit, or revisit finished sessions from the heartbeat.
321
+ * The final sweep acknowledges live deliveries but defers messages until the
322
+ * terminal receipt is saved. The heartbeat's permission callback returns
323
+ * waiting, declined, or the durable child id. A message stays undelivered
324
+ * until declined or filed, so network failures can safely retry. Question
325
+ * answers retain their caller's delivered-set; permission answers belong to
326
+ * their own consumer, never the resumed model. */
346
327
  export async function promoteLateRows(
347
328
  root,
348
329
  id,
349
- // `promote` has no default: the only caller left, `runnerCompletion.mjs`,
350
- // always passes `runnerApi.resume` (item 6 of brief 30 Move 2b) - there is
351
- // no file-based request to fall back to promoting any more
352
- // (`lateReplies.mjs`, deleted the same pass).
353
- { poller, callTool = hostedCallTool, sessionKey, env, promote } = {},
330
+ // Both completion and the late-message heartbeat supply the resume path.
331
+ // There is no file-based request fallback.
332
+ { poller, callTool = hostedCallTool, sessionKey, env, promote, deferMessages = false, messageLimit = Infinity } = {},
354
333
  log = () => {},
355
334
  ) {
356
335
  // THE LAST ACKS GO WITH THE SWEEP (item 75): what the child took is
@@ -364,10 +343,10 @@ export async function promoteLateRows(
364
343
  if (poller.hasDelivered(a.id)) continue;
365
344
  late.push({ tag: `q:${a.id}`, text: formatAnswer(a) });
366
345
  }
367
- for (const m of collected.messages) {
346
+ for (const m of (deferMessages ? [] : collected.messages.slice(0, messageLimit))) {
368
347
  const hash = createHash("sha256").update(`${m.from} ${m.text}`).digest("hex").slice(0, 16);
369
348
  const delivery = deliverable(m, collected.messages.length === 1 ? collected.images : []);
370
- late.push({ tag: `m:${hash}`, text: delivery.text, images: delivery.images, message: { from: m.from, text: m.text } });
349
+ late.push({ tag: `m:${m.id ?? hash}`, messageId: m.id, text: delivery.text, images: delivery.images, message: { from: m.from, text: m.text } });
371
350
  }
372
351
  const filed = [];
373
352
  // The messages no run will carry (item 75): completion records them on
@@ -375,8 +354,13 @@ export async function promoteLateRows(
375
354
  const dropped = [];
376
355
  for (const item of late) {
377
356
  const promotionId = lateRowRequestId(id, item.tag);
378
- const newId = await promote(root, id, { text: item.text, attributed: item.text, images: item.images }, log, promotionId);
357
+ const newId = await promote(root, id, { text: item.text, attributed: item.text, images: item.images, message: item.message }, log, promotionId);
358
+ if (newId?.waiting) continue;
379
359
  if (newId) {
360
+ if (item.messageId !== undefined) {
361
+ await pollCollectSession({ callTool, sessionKey, since: poller.since(), env, log, delivered: [item.messageId] });
362
+ }
363
+ if (newId.declined) continue;
380
364
  filed.push(newId);
381
365
  log(`[${id}] a late row (${item.tag}) arrived after the session ended; filed ${newId} to continue it`);
382
366
  } else {
@@ -6,8 +6,8 @@ import { createHash } from "node:crypto";
6
6
  /** Stream a run's log to hosted rows. tick() is safe to call without awaiting
7
7
  * it; settle() closes input and drains all earlier sends before returning.
8
8
  * Failed events remain queued for the next tick or settlement retry. */
9
- export function makeRowEventStreamer({ send, log = () => {} } = {}) {
10
- let seq = 0;
9
+ export function makeRowEventStreamer({ send, retain, initialSeq = 0, log = () => {} } = {}) {
10
+ let seq = initialSeq;
11
11
  let pending = "";
12
12
  let closed = false;
13
13
  let received = 0;
@@ -23,11 +23,27 @@ export function makeRowEventStreamer({ send, log = () => {} } = {}) {
23
23
  enqueue("log", pending);
24
24
  pending = "";
25
25
  };
26
+ let retainedThrough = 0;
27
+ let retention = Promise.resolve();
28
+ const save = () => {
29
+ const snapshot = [...queue];
30
+ const task = retention.then(async () => {
31
+ const rows = snapshot.filter(row => row.seq > retainedThrough);
32
+ if (rows.length) {
33
+ await retain(rows);
34
+ retainedThrough = rows.at(-1).seq;
35
+ }
36
+ return true;
37
+ }).catch(error => { log(`events retention failed: ${error?.message ?? error}`); return false; });
38
+ retention = task;
39
+ return task;
40
+ };
26
41
  const drain = () => {
27
42
  if (inFlight) return inFlight;
28
43
  inFlight = (async () => {
29
44
  while (queue.length > 0) {
30
45
  const row = queue[0];
46
+ if (retain && row.seq > retainedThrough && !await save()) return false;
31
47
  try {
32
48
  const outcome = await send([row]);
33
49
  if (!outcome.ok) throw new Error(outcome.error ?? "unknown error");
@@ -52,6 +68,7 @@ export function makeRowEventStreamer({ send, log = () => {} } = {}) {
52
68
  async tick() {
53
69
  if (closed) return;
54
70
  flushPending();
71
+ if (retain && !await save()) return false;
55
72
  return drain();
56
73
  },
57
74
  settle(finalText, { dropped = 0 } = {}) {
@@ -74,6 +91,7 @@ export function makeRowEventStreamer({ send, log = () => {} } = {}) {
74
91
  settlement = (async () => {
75
92
  // An earlier drain may already have observed an empty queue before
76
93
  // its promise settled; run a fresh drain for the closing rows too.
94
+ if (retain && !await save()) return { ok: false };
77
95
  if (inFlight) await inFlight;
78
96
  let ok = await drain();
79
97
  // Retry once at exit, using the same immutable rows and sequence ids.
@@ -36,14 +36,38 @@ export function makeRunnerHealth({ env = process.env, version, now = Date.now, i
36
36
  };
37
37
  }
38
38
 
39
+ /** How long setup waits for its first fresh beat (#4206). A new computer's
40
+ * service checks its agents and folders before it beats, and one slow check
41
+ * there used to miss the old 45 s and end setup with an error while the
42
+ * computer was fine. 90 s still ends inside the 2 minutes a coding agent
43
+ * gives one command by default. */
44
+ export const SETUP_HEALTH_WAIT_MS = 90_000;
45
+ /** When setup says it is still waiting, so a slow start is not silence. */
46
+ export const SETUP_HEALTH_SLOW_MS = 20_000;
47
+
48
+ /** True when the service at `version` has beat for `root` inside the last 30 s.
49
+ * This proves service liveness, not successful setup checks. Setup may use
50
+ * it to preserve a good beat only after those checks pass (#4221, #5047). */
51
+ export function hasFreshBeat({ env = process.env, version, root, after = 0, read = () => readRunnerHealth(env), now = Date.now } = {}) {
52
+ const health = read();
53
+ const at = root ? health?.paths?.[root] : undefined;
54
+ return health?.version === version && Boolean(health.instance) && typeof at === "number" && at > after && now() - at < 30_000;
55
+ }
56
+
39
57
  export async function waitForRunnerHealth({
40
58
  env = process.env, version, after = 0, previousInstance, root,
41
59
  read = () => readRunnerHealth(env), now = Date.now,
42
60
  pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
43
- timeoutMs = 45_000, requireStartedAfter = true,
61
+ timeoutMs = 45_000, requireStartedAfter = true, slowMs, onSlow,
44
62
  } = {}) {
45
- const deadline = now() + timeoutMs;
63
+ const started = now();
64
+ const deadline = started + timeoutMs;
65
+ let saidSlow = false;
46
66
  do {
67
+ if (!saidSlow && onSlow && slowMs !== undefined && now() - started >= slowMs) {
68
+ saidSlow = true;
69
+ onSlow();
70
+ }
47
71
  const health = read();
48
72
  const beats = root ? [health?.paths?.[root]] : Object.values(health?.paths ?? {});
49
73
  if (health?.version === version && health.instance && health.instance !== previousInstance &&