viewable-one 0.12.2 → 0.12.4
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 +79 -0
- package/README.md +2 -2
- package/SPAWN.md +107 -53
- package/glytch.mjs +49 -12
- 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 +80 -45
- 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 +52 -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 +33 -12
- package/lib/runnerApi.mjs +28 -12
- package/lib/runnerBeat.mjs +398 -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 +226 -0
- package/lib/runnerPace.mjs +10 -6
- package/lib/runnerRecovery.mjs +457 -0
- package/lib/runnerRegister.mjs +29 -8
- package/lib/runnerSettlement.mjs +29 -9
- package/lib/selfUninstall.mjs +239 -0
- package/lib/spawn.mjs +0 -5
- package/lib/sync.mjs +26 -14
- package/lib/update.mjs +184 -0
- 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/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/restartPass.mjs
CHANGED
|
@@ -6,8 +6,11 @@
|
|
|
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.
|
|
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";
|
|
13
|
+
import { runGate } from "./runnerAdmission.mjs";
|
|
11
14
|
import { randomUUID } from "node:crypto";
|
|
12
15
|
import { stat } from "node:fs/promises";
|
|
13
16
|
import * as runnerApiModule from "./runnerApi.mjs";
|
|
@@ -28,6 +31,10 @@ export const liveRuns = new Set();
|
|
|
28
31
|
/** The second look: after the lease has run out and the reaper has run. */
|
|
29
32
|
export const RESTART_RECHECK_MS = 7 * 60_000;
|
|
30
33
|
|
|
34
|
+
/** The prompt look, only while a dead owner's recovery record waits on this
|
|
35
|
+
* computer (orphanRecoveries): local recovery need not wait for the lease. */
|
|
36
|
+
export const RECOVERY_RECHECK_MS = 30_000;
|
|
37
|
+
|
|
31
38
|
const timeOf = (value) => (value ? Date.parse(value) : NaN);
|
|
32
39
|
const isReaped = (row) => row.status === "error" && Boolean(row.recovery_reason) && (row.result === null || row.result === undefined);
|
|
33
40
|
|
|
@@ -35,15 +42,21 @@ const isReaped = (row) => row.status === "error" && Boolean(row.recovery_reason)
|
|
|
35
42
|
export function restartCandidate(row, { now = Date.now() } = {}) {
|
|
36
43
|
const request = row?.request;
|
|
37
44
|
if (!request || typeof request !== "object" || liveRuns.has(row.id)) return false;
|
|
45
|
+
if (row.sidecar?.restarted === true) return false;
|
|
46
|
+
// A person pressed Stop and the computer died before it was heard: the
|
|
47
|
+
// stop stands. Nothing is carried on that a person ended.
|
|
48
|
+
if (row.stop_requested_at) return false;
|
|
49
|
+
// A fenced row is local recovery's while it runs. Once the server has
|
|
50
|
+
// settled it, this pass is the only one that ends it, so its card or chat
|
|
51
|
+
// turn never waits forever (#4948), whether or not it was marked
|
|
52
|
+
// restartable; the caller also checks no record keeps it here. It is only
|
|
53
|
+
// ever ended, never resumed (carryOn).
|
|
54
|
+
if (row.lease_generation) return row.status === "error" && (isReaped(row) || row.sidecar?.recoveryPending === true);
|
|
38
55
|
// Older Run-button runs already ended in the app. Never start paid work
|
|
39
56
|
// again for those rows. Older note sessions have always waited for recovery.
|
|
40
57
|
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
58
|
if (isChatTurn(request) || request.planMode === "draft") return false;
|
|
43
59
|
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
60
|
if (row.status === "running") {
|
|
48
61
|
// A lease still running belongs to a live process (the server leases for
|
|
49
62
|
// five minutes and a process renews every thirty seconds); only one that
|
|
@@ -61,7 +74,7 @@ const isDirectory = async (path) => {
|
|
|
61
74
|
|
|
62
75
|
/** One pass over one folder. Returns what it did, for the log and the test:
|
|
63
76
|
* `{resumed: [runId], ended: [runId], skipped: [runId]}`. Never throws. */
|
|
64
|
-
export async function restartPass(project, settings, { log = () => {}, now = Date.now } = {}) {
|
|
77
|
+
export async function restartPass(project, settings, { log = () => {}, now = Date.now, startRun } = {}) {
|
|
65
78
|
const done = { resumed: [], ended: [], skipped: [] };
|
|
66
79
|
const api = settings.runnerApi ?? runnerApiModule;
|
|
67
80
|
const opts = { env: settings.env, fetchImpl: settings.fetchImpl };
|
|
@@ -79,7 +92,28 @@ export async function restartPass(project, settings, { log = () => {}, now = Dat
|
|
|
79
92
|
return done;
|
|
80
93
|
}
|
|
81
94
|
|
|
82
|
-
|
|
95
|
+
// A recovered run is a run start like a claim: it waits while an update
|
|
96
|
+
// waits or installs (#4949 review). Its record stays, so a later pass, or
|
|
97
|
+
// the restarted computer app, carries it on; the loop below never ends a
|
|
98
|
+
// fenced row that still has its record.
|
|
99
|
+
const recoverable = startRun ? rows.filter(row => row.lease_generation && !liveRuns.has(row.id)) : [];
|
|
100
|
+
const endStart = recoverable.length ? runGate(settings.selfUpdate) : null;
|
|
101
|
+
if (recoverable.length && !endStart) {
|
|
102
|
+
log("restart pass: an update is waiting; recovered sessions start after it");
|
|
103
|
+
done.skipped.push(...recoverable.map((row) => row.id));
|
|
104
|
+
}
|
|
105
|
+
if (endStart) try {
|
|
106
|
+
for (const row of recoverable) {
|
|
107
|
+
try {
|
|
108
|
+
const recovered = await recoverLocalRun(project, row, settings, api, opts, log);
|
|
109
|
+
if (recovered) { startRun(recovered); done.resumed.push(row.id); }
|
|
110
|
+
} catch (error) { log(`[${row.id}] local recovery failed: ${error.message}`); }
|
|
111
|
+
}
|
|
112
|
+
} finally { setImmediate(endStart); }
|
|
113
|
+
// A fenced row whose record is still here belongs to a live owner or to a
|
|
114
|
+
// recovery that will try again; only a row nobody here can carry on ends.
|
|
115
|
+
const ours = (row) => !row.lease_generation || (!done.resumed.includes(row.id) && !hasRecoveryRecord(project, row.id, settings));
|
|
116
|
+
for (const row of rows.filter((r) => restartCandidate(r, { now: now() }) && ours(r))) {
|
|
83
117
|
try {
|
|
84
118
|
const outcome = await carryOn(row, { api, opts, log, now });
|
|
85
119
|
done[outcome].push(row.id);
|
|
@@ -97,7 +131,14 @@ async function carryOn(row, { api, opts, log, now }) {
|
|
|
97
131
|
const engine = agentFor(request.agent);
|
|
98
132
|
const sessionId = (engine === "codex" ? [sidecar.codexThreadId, request.resumeSessionId] : [sidecar.claudeSessionId, request.resumeSessionId, request.sessionId])
|
|
99
133
|
.find((v) => typeof v === "string" && v.trim() !== "")?.trim();
|
|
100
|
-
|
|
134
|
+
// Fenced rows reach here only to be ended: local recovery owns carrying
|
|
135
|
+
// them on with the record's own budget, and once it gave up (no time
|
|
136
|
+
// left, no conversation) a resume here would start paid work it refused.
|
|
137
|
+
const resumable = !row.lease_generation && !isChatTurn(request) && request.planMode !== "draft" && Boolean(fromIdOf(request) || row.from_id);
|
|
138
|
+
const canResume = resumable && ["claude", "codex"].includes(engine) && acceptsMessages(request) && treeKept && sessionId !== undefined;
|
|
139
|
+
// The row's own generation: if anyone took it over since the listing, the
|
|
140
|
+
// server refuses these writes instead of ending somebody else's run.
|
|
141
|
+
const fence = row.lease_generation ? { generation: row.lease_generation } : {};
|
|
101
142
|
// A running row without its copy gets a second look after the reaper.
|
|
102
143
|
if (!canResume && acceptsMessages(request) && !treeKept && row.status === "running") {
|
|
103
144
|
log(`[${row.id}] restart pass: no kept worktree to carry on in; leaving it to the reaper`);
|
|
@@ -115,7 +156,7 @@ async function carryOn(row, { api, opts, log, now }) {
|
|
|
115
156
|
const remainingMs = Math.max(0, wallClockFor(request) - workingMs);
|
|
116
157
|
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
158
|
const settled = sidecar.recoveryPending === true ? { ok: true } : await api.update({
|
|
118
|
-
runId: row.id,
|
|
159
|
+
runId: row.id, ...fence,
|
|
119
160
|
patch: {
|
|
120
161
|
sidecar: settledSidecar,
|
|
121
162
|
// No "carried on" claim here (round 2, item 59): the resume does not
|
|
@@ -135,7 +176,7 @@ async function carryOn(row, { api, opts, log, now }) {
|
|
|
135
176
|
const childId = resumed.run?.id ?? resumed.id;
|
|
136
177
|
if (resumed.ok && childId) {
|
|
137
178
|
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)
|
|
179
|
+
await api.update({ runId: row.id, ...fence, patch: { sidecar: { ...settledSidecar, recoveryPending: false, restarted: true, restartedTo: childId } } }, opts)
|
|
139
180
|
.catch(() => {});
|
|
140
181
|
return "resumed";
|
|
141
182
|
}
|
|
@@ -145,7 +186,7 @@ async function carryOn(row, { api, opts, log, now }) {
|
|
|
145
186
|
|
|
146
187
|
// Persist the outcome on the row. Every app tab derives the same ending;
|
|
147
188
|
// 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);
|
|
189
|
+
await api.update({ runId: row.id, ...fence, patch: { sidecar: { ...settledSidecar, recoveryPending: false, restarted: true, recoveryFailed: true } } }, opts);
|
|
149
190
|
log(`[${row.id}] restart pass: this session cannot carry on`);
|
|
150
191
|
return "ended";
|
|
151
192
|
}
|
package/lib/rowsAnswers.mjs
CHANGED
|
@@ -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
|
-
/**
|
|
321
|
-
*
|
|
322
|
-
*
|
|
323
|
-
*
|
|
324
|
-
*
|
|
325
|
-
*
|
|
326
|
-
*
|
|
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
|
-
//
|
|
350
|
-
//
|
|
351
|
-
|
|
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 {
|
package/lib/rowsEvents.mjs
CHANGED
|
@@ -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 =
|
|
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.
|
package/lib/runner-health.mjs
CHANGED
|
@@ -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
|
|
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 &&
|