viewable-one 0.12.1 → 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 (71) hide show
  1. package/CHANGELOG.md +71 -1
  2. package/README.md +31 -48
  3. package/SPAWN.md +136 -79
  4. package/glytch.mjs +41 -10
  5. package/lib/acp.mjs +152 -150
  6. package/lib/admission.mjs +25 -5
  7. package/lib/agent-selection.mjs +5 -4
  8. package/lib/agents.mjs +68 -24
  9. package/lib/answerTag.mjs +47 -0
  10. package/lib/atomic.mjs +1 -16
  11. package/lib/auth.mjs +172 -52
  12. package/lib/authenticatedHttp.mjs +10 -3
  13. package/lib/boardside.mjs +28 -12
  14. package/lib/child.mjs +129 -116
  15. package/lib/claudeModels.mjs +168 -0
  16. package/lib/codex-rpc.mjs +2 -2
  17. package/lib/codex.mjs +50 -50
  18. package/lib/codexApps.mjs +17 -3
  19. package/lib/codexToolInputs.mjs +98 -22
  20. package/lib/codingChecks.mjs +8 -4
  21. package/lib/conversationRules.mjs +47 -7
  22. package/lib/detect.mjs +39 -24
  23. package/lib/devserver.mjs +30 -19
  24. package/lib/doctor.mjs +10 -8
  25. package/lib/folderReads.mjs +96 -0
  26. package/lib/followUps.mjs +170 -0
  27. package/lib/hosted.mjs +13 -4
  28. package/lib/init-connect.mjs +29 -10
  29. package/lib/lateResume.mjs +135 -0
  30. package/lib/logindaemon.mjs +129 -49
  31. package/lib/logs.mjs +2 -2
  32. package/lib/mcpjson.mjs +35 -2
  33. package/lib/memberPreview.mjs +22 -14
  34. package/lib/multiwatch.mjs +28 -41
  35. package/lib/pagePictures.mjs +15 -12
  36. package/lib/pageRoutes.mjs +5 -2
  37. package/lib/paths.mjs +3 -3
  38. package/lib/permissionAsk.mjs +344 -61
  39. package/lib/previewGateway.mjs +4 -3
  40. package/lib/procs.mjs +73 -2
  41. package/lib/refusal.mjs +0 -2
  42. package/lib/registry.mjs +7 -7
  43. package/lib/repomap.mjs +4 -3
  44. package/lib/restartPass.mjs +39 -11
  45. package/lib/rowsAnswers.mjs +52 -69
  46. package/lib/rowsEvents.mjs +20 -2
  47. package/lib/runner-health.mjs +29 -5
  48. package/lib/runner.mjs +161 -1347
  49. package/lib/runnerAdmission.mjs +6 -12
  50. package/lib/runnerApi.mjs +20 -11
  51. package/lib/runnerBeat.mjs +384 -0
  52. package/lib/runnerCompletion.mjs +5 -2
  53. package/lib/runnerExecute.mjs +227 -0
  54. package/lib/runnerGates.mjs +338 -0
  55. package/lib/runnerLaunch.mjs +351 -0
  56. package/lib/runnerLease.mjs +31 -9
  57. package/lib/runnerOps.mjs +217 -0
  58. package/lib/runnerPace.mjs +10 -6
  59. package/lib/runnerRecovery.mjs +457 -0
  60. package/lib/runnerRegister.mjs +29 -8
  61. package/lib/runnerSettlement.mjs +43 -16
  62. package/lib/runnerWorkspace.mjs +19 -4
  63. package/lib/spawn.mjs +0 -5
  64. package/lib/sync.mjs +28 -16
  65. package/lib/uninstall-project.mjs +12 -11
  66. package/lib/uninstall.mjs +32 -25
  67. package/lib/update.mjs +4 -4
  68. package/lib/{glytchFolder.mjs → viewableFolder.mjs} +22 -16
  69. package/lib/worktree.mjs +83 -26
  70. package/lib/writePolicy.mjs +90 -10
  71. package/package.json +2 -2
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
package/lib/registry.mjs CHANGED
@@ -9,7 +9,7 @@
9
9
  //
10
10
  // GLYTCH_HOME EXISTS FOR THE TESTS, and only for them. Every path in this
11
11
  // package that would otherwise land in the real ~/.glytch goes through
12
- // glytchHome(), so a test suite that sets GLYTCH_HOME to a temp directory
12
+ // viewableHome(), so a test suite that sets GLYTCH_HOME to a temp directory
13
13
  // cannot touch the machine it runs on - which matters more here than usual,
14
14
  // because the other half of this feature loads a LaunchAgent.
15
15
 
@@ -22,17 +22,17 @@ import { writeFileAtomic } from "./atomic.mjs";
22
22
  import { acquireAdmission } from "./admission.mjs";
23
23
 
24
24
  /** ~/.glytch, or GLYTCH_HOME when set. */
25
- export const glytchHome = (env = process.env) =>
25
+ export const viewableHome = (env = process.env) =>
26
26
  (env.VIEWABLE_HOME ?? env.GLYTCH_HOME)?.trim() || join(homedir(), ".glytch");
27
27
 
28
- export const registryPath = (env = process.env) => join(glytchHome(env), "folders.json");
28
+ export const registryPath = (env = process.env) => join(viewableHome(env), "folders.json");
29
29
 
30
30
  // Restore and Remove run in different processes. Reuse admission's exclusive
31
31
  // file lock and dead-owner recovery, in a directory separate from run claims.
32
32
  export async function withRegistryLock(fn, env = process.env) {
33
33
  const deadline = Date.now() + 10_000;
34
34
  for (;;) {
35
- const held = await acquireAdmission(glytchHome(env), { directory: join(glytchHome(env), "registry") });
35
+ const held = await acquireAdmission(viewableHome(env), { directory: join(viewableHome(env), "registry") });
36
36
  if (held.ok) {
37
37
  try { return await fn(); }
38
38
  finally { await held.release(); }
@@ -42,7 +42,7 @@ export async function withRegistryLock(fn, env = process.env) {
42
42
  }
43
43
  }
44
44
 
45
- const restorePath = (folder, env) => join(glytchHome(env), "registry", `${createHash("sha256").update(resolve(folder)).digest("hex")}.restore`);
45
+ const restorePath = (folder, env) => join(viewableHome(env), "registry", `${createHash("sha256").update(resolve(folder)).digest("hex")}.restore`);
46
46
 
47
47
  export async function folderRestoreGeneration(folder, env = process.env) {
48
48
  try { return await readFile(restorePath(folder, env), "utf8"); }
@@ -65,7 +65,7 @@ export async function markFolderRestore(folder, env = process.env) {
65
65
  const tempRoots = () => [tmpdir(), "/tmp", "/private/tmp", "/var/folders", "/private/var/folders"].map((p) => resolve(p));
66
66
  const underTemp = (path) => tempRoots().some((root) => path === root || path.startsWith(`${root}${sep}`));
67
67
  export const isScratchFolder = (folder, env = process.env) =>
68
- underTemp(resolve(folder)) && !underTemp(resolve(glytchHome(env)));
68
+ underTemp(resolve(folder)) && !underTemp(resolve(viewableHome(env)));
69
69
 
70
70
  /** The folders with no git repo, for the presence body (QA 2026-10-01,
71
71
  * ticket e2). Such a folder runs IN PLACE - `makeWorktree` finds no repo - so
@@ -143,7 +143,7 @@ export async function readRegistryChecked(env = process.env) {
143
143
  }
144
144
 
145
145
  async function writeRegistry(folders, env = process.env) {
146
- await mkdir(glytchHome(env), { recursive: true });
146
+ await mkdir(viewableHome(env), { recursive: true });
147
147
  await writeFileAtomic(registryPath(env), `${JSON.stringify(folders, null, 2)}\n`);
148
148
  }
149
149
 
package/lib/repomap.mjs CHANGED
@@ -12,11 +12,11 @@
12
12
  // Cached keyed to HEAD sha in a dotfile beside the spawn dir; regenerate when
13
13
  // HEAD moved, reuse otherwise.
14
14
 
15
- import { readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
15
+ import { mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
16
16
  import { join, relative, sep } from "node:path";
17
17
  import { execFile } from "node:child_process";
18
18
  import { promisify } from "node:util";
19
- import { SPAWN_DIR, segmentsOf } from "./paths.mjs";
19
+ import { BOARD_DIR, segmentsOf } from "./paths.mjs";
20
20
 
21
21
  const execFileAsync = promisify(execFile);
22
22
 
@@ -222,7 +222,7 @@ export async function getRepoMap(root, log = () => {}) {
222
222
  return null;
223
223
  }
224
224
 
225
- const cacheDir = join(root, ...segmentsOf(SPAWN_DIR));
225
+ const cacheDir = join(root, ...segmentsOf(`${BOARD_DIR}/inbox/spawn`));
226
226
  const cacheFile = join(cacheDir, `.repomap-${headSha}.txt`);
227
227
 
228
228
  // Try to read cached version
@@ -239,6 +239,7 @@ export async function getRepoMap(root, log = () => {}) {
239
239
 
240
240
  // Write to cache (best effort; don't fail if we can't write)
241
241
  try {
242
+ await mkdir(cacheDir, { recursive: true });
242
243
  await writeFile(cacheFile, map, "utf8");
243
244
  log(`Repo map cached (${map.length} chars)`);
244
245
  await pruneRepoMapCache(cacheDir, log);
@@ -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
  }
@@ -39,13 +39,12 @@
39
39
  // reply, one line below the message they belong to - a bare JSON object,
40
40
  // the same "put a JSON block in a text result" idiom get_node already uses
41
41
  // for a node's own body. `parseCollected` below reads it back onto the
42
- // message object as `images`, and `deliverable` checks them with
43
- // `imageAttachments` so `child.mjs`'s `userMessage` can turn them into image
44
- // blocks. A picture that cannot be read never drops its message.
42
+ // message object as `images`. Keep the payload intact so each transport
43
+ // validates it before delivery; invalid pictures must not become text-only
44
+ // success or disappear from late-reply recovery.
45
45
 
46
46
  import { createHash } from "node:crypto";
47
47
  import { callTool as hostedCallTool } from "./hosted.mjs";
48
- import { imageAttachments } from "./imageAttachments.mjs";
49
48
 
50
49
  /** Parse collect_session's reply into rows a poller can act on. Tolerant of
51
50
  * every shape the tool actually writes: the "Nothing collected" sentence
@@ -108,7 +107,7 @@ export function parseCollected(text) {
108
107
  const parsed = JSON.parse(imagesLine[1]);
109
108
  // The row's id (item 75): what the next call's `delivered` names.
110
109
  if (typeof parsed.id === "number" || typeof parsed.id === "string") messages[messages.length - 1].id = parsed.id;
111
- if (Array.isArray(parsed.images) && parsed.images.length > 0) {
110
+ if (Object.hasOwn(parsed, "images")) {
112
111
  messages[messages.length - 1].images = parsed.images;
113
112
  }
114
113
  } catch {
@@ -171,25 +170,11 @@ export const formatAnswer = (a) =>
171
170
  * whichever door delivered it. */
172
171
  export const formatMessage = (m) => `[message from ${m.from}] ${m.text}`;
173
172
 
174
- /** What a polled message hands the child: its words and its pictures. The
175
- * pictures are the message's own (the line `parseCollected` folded onto it),
176
- * else `fallback` (native image blocks on the reply). A picture the child's
177
- * door would refuse (not an image, bad bytes) must not cost the message: the
178
- * server has already marked it delivered, so the words go in with one line
179
- * saying a picture was left out. */
173
+ /** Preserve the complete attachment payload for transport validation and
174
+ * late-reply recovery. Presence, not validity, chooses the per-message
175
+ * payload over the legacy single-message fallback. */
180
176
  function deliverable(message, fallback = []) {
181
- const text = formatMessage(message);
182
- const images = message.images?.length > 0 ? message.images : fallback ?? [];
183
- if (images.length === 0) return { text, images: [] };
184
- try {
185
- imageAttachments(images);
186
- return { text, images };
187
- } catch (error) {
188
- return {
189
- text: `${text}\n\n[${images.length === 1 ? "A picture" : `${images.length} pictures`} came with this message and could not be read: ${error instanceof Error ? error.message : String(error)}]`,
190
- images: [],
191
- };
192
- }
177
+ return { text: formatMessage(message), images: message.images !== undefined ? message.images : fallback };
193
178
  }
194
179
 
195
180
  /** A stateful poller: one `since` watermark plus one delivered-question set,
@@ -236,11 +221,15 @@ export function createRowsAnswerPoll({ callTool = hostedCallTool, sessionKey, en
236
221
  // tab delivers). The same sender, words and pictures again within
237
222
  // REPEAT_WINDOW_MS is that second copy, and is dropped.
238
223
  let last = null;
239
- const repeats = (m) => {
240
- const key = JSON.stringify([m.from, m.text, m.images ?? []]);
224
+ const repeats = (m, images) => {
225
+ const key = JSON.stringify([m.from, m.text, images]);
241
226
  const at = now();
242
- if (last !== null && last.key === key && at - last.at <= REPEAT_WINDOW_MS) return true;
243
- last = { key, at };
227
+ if (last !== null && last.key === key && at - last.at <= REPEAT_WINDOW_MS) {
228
+ if (last.accepted) took(m);
229
+ else last.copies.push(m);
230
+ return true;
231
+ }
232
+ last = { key, at, accepted: false, copies: [] };
244
233
  return false;
245
234
  };
246
235
  const poll = async () => {
@@ -249,7 +238,9 @@ export function createRowsAnswerPoll({ callTool = hostedCallTool, sessionKey, en
249
238
  if (realtime?.joined && !dirty && toAck.length === 0 && now() - lastPoll < pushPollMs) return [];
250
239
  dirty = false;
251
240
  lastPoll = now();
252
- const acking = toAck;
241
+ // Only retire IDs serialized into this request, not deliveries that
242
+ // arrive while collect_session is in flight.
243
+ const acking = toAck.slice();
253
244
  const collected = await pollCollectSession({ callTool, sessionKey, since, env, log, delivered: acking });
254
245
  if (!collected.ok) { dirty = true; return []; }
255
246
  toAck = toAck.filter((id) => !acking.includes(id));
@@ -258,6 +249,7 @@ export function createRowsAnswerPoll({ callTool = hostedCallTool, sessionKey, en
258
249
  for (const a of collected.answered) {
259
250
  if (delivered.has(a.id)) continue;
260
251
  out.push({
252
+ deliveryKey: `answer:${a.id}`,
261
253
  text: formatAnswer(a),
262
254
  onDelivered: async () => {
263
255
  delivered.add(a.id);
@@ -273,18 +265,25 @@ export function createRowsAnswerPoll({ callTool = hostedCallTool, sessionKey, en
273
265
  for (const m of collected.messages) {
274
266
  if (m.id !== undefined && offered.has(m.id)) continue;
275
267
  if (m.id !== undefined) offered.add(m.id);
276
- if (repeats(m)) {
277
- // The copy was delivered in substance, so it is acked too; left
278
- // unacked it would come back as a late row and continue the session.
279
- took(m);
268
+ const delivery = deliverable(m, collected.messages.length === 1 ? collected.images : []);
269
+ if (repeats(m, delivery.images)) {
270
+ // A copy is acknowledged only after the original was accepted.
271
+ // In particular, invalid images must leave every source row unacked.
280
272
  log(`dropped a repeat of the last message from ${m.from}`);
281
273
  continue;
282
274
  }
283
- const delivery = deliverable(m, collected.messages.length === 1 ? collected.images : []);
275
+ const pending = last;
284
276
  out.push({
285
277
  text: delivery.text,
286
- ...(delivery.images.length > 0 ? { images: delivery.images } : {}),
287
- onDelivered: async () => { took(m); log(`delivered a message from ${m.from}`); },
278
+ ...(!(Array.isArray(delivery.images) && delivery.images.length === 0) ? { images: delivery.images } : {}),
279
+ onDelivered: async () => {
280
+ if (pending.accepted) return;
281
+ pending.accepted = true;
282
+ took(m);
283
+ for (const copy of pending.copies) took(copy);
284
+ pending.copies.length = 0;
285
+ log(`delivered a message from ${m.from}`);
286
+ },
288
287
  });
289
288
  }
290
289
  return out;
@@ -318,40 +317,19 @@ export function createRowsAnswerPoll({ callTool = hostedCallTool, sessionKey, en
318
317
  export const lateRowRequestId = (requestId, tag) =>
319
318
  `spawn-reply-${createHash("sha256").update(`${requestId} ${tag}`).digest("hex")}`;
320
319
 
321
- /** After the child has exited, ONE more collect_session call - the row
322
- * equivalent of `promoteLateReplies` sweeping a `.reply-*.json` written
323
- * after stdin closed. A late ANSWER or MESSAGE for a PERSISTENT session
324
- * becomes a resume request through the exact function a late reply file
325
- * already uses (`promoteReplyToRequest`, fed a row instead of a file) -
326
- * the worktree, the resume session id, and "was this ever approved" are
327
- * all its, unchanged; it already refuses (returns null) for a one-shot
328
- * session via its own `acceptsMessages` check, which is what makes "log
329
- * and drop, same as today" the natural result of calling it here too
330
- * rather than a second branch to keep in sync with the first.
331
- *
332
- * KNOWN GAP, spelled out rather than hidden: a MESSAGE that arrived WHILE
333
- * the child was still running, in the same poll tick the child happened to
334
- * exit on, is marked delivered server-side by that poll (collect_session's
335
- * own `takeMessages` stamps `delivered_at` on fetch, not on successful
336
- * delivery to a pipe) whether or not `sendToChild` actually got to write
337
- * it - `child.mjs`'s `watchAnswers` breaks out of its delivery loop the
338
- * moment the child is settled, before calling `onDelivered`. Such a
339
- * message will not be seen again by THIS poll (it is no longer
340
- * undelivered on the server) or by this sweep (it is not "late" - it was
341
- * already fetched). It is the one situation this design does not recover,
342
- * and it is symmetric with why a message needs no in-memory delivered set
343
- * at all: the same field that makes redelivery impossible also makes this
344
- * one narrow race unrecoverable. An ANSWERED QUESTION has no such gap - it
345
- * carries no delivered_at, so it is simply asked for again next time,
346
- * 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. */
347
327
  export async function promoteLateRows(
348
328
  root,
349
329
  id,
350
- // `promote` has no default: the only caller left, `runnerCompletion.mjs`,
351
- // always passes `runnerApi.resume` (item 6 of brief 30 Move 2b) - there is
352
- // no file-based request to fall back to promoting any more
353
- // (`lateReplies.mjs`, deleted the same pass).
354
- { 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 } = {},
355
333
  log = () => {},
356
334
  ) {
357
335
  // THE LAST ACKS GO WITH THE SWEEP (item 75): what the child took is
@@ -365,10 +343,10 @@ export async function promoteLateRows(
365
343
  if (poller.hasDelivered(a.id)) continue;
366
344
  late.push({ tag: `q:${a.id}`, text: formatAnswer(a) });
367
345
  }
368
- for (const m of collected.messages) {
346
+ for (const m of (deferMessages ? [] : collected.messages.slice(0, messageLimit))) {
369
347
  const hash = createHash("sha256").update(`${m.from} ${m.text}`).digest("hex").slice(0, 16);
370
348
  const delivery = deliverable(m, collected.messages.length === 1 ? collected.images : []);
371
- 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 } });
372
350
  }
373
351
  const filed = [];
374
352
  // The messages no run will carry (item 75): completion records them on
@@ -376,8 +354,13 @@ export async function promoteLateRows(
376
354
  const dropped = [];
377
355
  for (const item of late) {
378
356
  const promotionId = lateRowRequestId(id, item.tag);
379
- 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;
380
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;
381
364
  filed.push(newId);
382
365
  log(`[${id}] a late row (${item.tag}) arrived after the session ended; filed ${newId} to continue it`);
383
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.
@@ -5,15 +5,15 @@ import { readFileSync } from "node:fs";
5
5
  import { mkdir } from "node:fs/promises";
6
6
  import { writeFileAtomic } from "./atomic.mjs";
7
7
  import { join } from "node:path";
8
- import { glytchHome } from "./registry.mjs";
8
+ import { viewableHome } from "./registry.mjs";
9
9
 
10
10
  export function readRunnerHealth(env = process.env, name = "health") {
11
- try { return JSON.parse(readFileSync(join(glytchHome(env), `${name}.json`), "utf8")); }
11
+ try { return JSON.parse(readFileSync(join(viewableHome(env), `${name}.json`), "utf8")); }
12
12
  catch { return null; }
13
13
  }
14
14
 
15
15
  export async function writeRunnerHealth(value, env = process.env, name = "health") {
16
- const home = glytchHome(env);
16
+ const home = viewableHome(env);
17
17
  await mkdir(home, { recursive: true });
18
18
  await writeFileAtomic(join(home, `${name}.json`), JSON.stringify(value), "utf8", { mode: 0o600 });
19
19
  }
@@ -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 &&