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/runnerAdmission.mjs
CHANGED
|
@@ -1,30 +1,52 @@
|
|
|
1
1
|
/** Admission requires durable completion delivery and a free slot. */
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
3
|
import { acquireAdmission } from "./admission.mjs";
|
|
4
|
+
import { runningRoom } from "./runnerRecovery.mjs";
|
|
4
5
|
import { flushCompletions } from "./runnerSettlement.mjs";
|
|
5
6
|
import * as runnerApiModule from "./runnerApi.mjs";
|
|
6
7
|
|
|
7
8
|
const retryHint = (out) => (Number.isFinite(out.retryAfterMs) ? { retryAfterMs: out.retryAfterMs } : {});
|
|
8
9
|
|
|
9
|
-
|
|
10
|
+
/** The update gate every run start passes, a claim or a recovered run (#4949).
|
|
11
|
+
* null while an update waits or installs, so no run starts under it; else
|
|
12
|
+
* the call that says this start has settled. Until then the update counts
|
|
13
|
+
* it, so a request that comes while the start is on its way never installs
|
|
14
|
+
* under it. Call the returned function with setImmediate, after the run is
|
|
15
|
+
* in `liveRuns`. */
|
|
16
|
+
export function runGate(update) {
|
|
17
|
+
if (!update) return () => {};
|
|
18
|
+
if (update.claimStarted) return update.claimStarted();
|
|
19
|
+
return update.holdsRuns() ? null : () => {};
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export async function claimOne(root, project, settings, { activeRunIds = [], log } = {}) {
|
|
10
23
|
const runnerApi = settings.runnerApi ?? runnerApiModule;
|
|
24
|
+
// An update waits for the runs going to end, so no new one starts (#4949).
|
|
25
|
+
const endClaim = runGate(settings.selfUpdate);
|
|
26
|
+
if (!endClaim) return { claimed: false, idle: true, detail: "An update is waiting for runs to finish." };
|
|
27
|
+
try {
|
|
28
|
+
return await claimAdmitted(root, project, settings, runnerApi, { activeRunIds, log });
|
|
29
|
+
} finally {
|
|
30
|
+
// Both callers start the run (runRequest adds it to `liveRuns` before its
|
|
31
|
+
// first await) in the continuation right after this settles. Microtasks
|
|
32
|
+
// run before setImmediate, so the update counts the run before it stops
|
|
33
|
+
// counting the claim.
|
|
34
|
+
setImmediate(endClaim);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function claimAdmitted(root, project, settings, runnerApi, { activeRunIds, log }) {
|
|
11
39
|
const rowsOpts = { env: settings.env, fetchImpl: settings.fetchImpl };
|
|
12
40
|
const admission = await acquireAdmission(root);
|
|
13
|
-
if (!admission.ok) return { claimed: false, detail: admission.detail };
|
|
41
|
+
if (!admission.ok) return { claimed: false, transient: true, detail: admission.detail };
|
|
14
42
|
try {
|
|
15
43
|
// `transient` (ticket e8): the claim loop backs off on these. A saved
|
|
16
44
|
// completion that will not sync is almost always the server failing, and
|
|
17
45
|
// claiming is blocked until it lands either way.
|
|
18
46
|
if (!(await flushCompletions(project, settings))) return { claimed: false, transient: true, detail: "Saved completions are waiting to sync." };
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
const listed = await runnerApi.runs({ projectIds: [project.id], status: "running" }, rowsOpts);
|
|
23
|
-
if (!listed.ok) return { claimed: false, transient: listed.transient === true, ...retryHint(listed), detail: `Cannot verify running sessions: ${listed.error}` };
|
|
24
|
-
const running = (listed.runs ?? []).length;
|
|
25
|
-
if (running >= settings.maxConcurrent) return { claimed: false, detail: `${running} session(s) already running, and up to ${settings.maxConcurrent} run at once` };
|
|
26
|
-
}
|
|
27
|
-
const claimed = await runnerApi.claim({ projectIds: [project.id], runnerInstanceId: settings.runnerInstanceId ??= randomUUID() }, rowsOpts);
|
|
47
|
+
const room = await runningRoom(project, settings, runnerApi, { activeRunIds, log });
|
|
48
|
+
if (!room.ok) return { claimed: false, ...room };
|
|
49
|
+
const claimed = await runnerApi.claim({ projectIds: [project.id], runnerInstanceId: settings.runnerInstanceId ??= randomUUID(), fencing: true }, rowsOpts);
|
|
28
50
|
if (!claimed.ok) return { claimed: false, transient: claimed.transient === true, ...retryHint(claimed), detail: claimed.error };
|
|
29
51
|
if (!claimed.run) return { claimed: false, idle: true, detail: "nothing pending" };
|
|
30
52
|
return { claimed: true, run: claimed.run };
|
|
@@ -32,4 +54,3 @@ export async function claimOne(root, project, settings) {
|
|
|
32
54
|
await admission.release();
|
|
33
55
|
}
|
|
34
56
|
}
|
|
35
|
-
|
package/lib/runnerApi.mjs
CHANGED
|
@@ -122,7 +122,7 @@ async function call(op, body = {}, options = {}) {
|
|
|
122
122
|
// below. A 401 and every refusal leave it unset.
|
|
123
123
|
return { ok: false, transient: true, error: `Could not reach ${url}: ${error instanceof Error ? error.message : String(error)}${cause ? ` (${cause})` : ""}` };
|
|
124
124
|
}
|
|
125
|
-
if (result.authError) return { ok: false, error: result.authError };
|
|
125
|
+
if (result.authError) return { ok: false, unauthorized: true, error: result.authError };
|
|
126
126
|
|
|
127
127
|
const { response, text, payload } = result;
|
|
128
128
|
if (!response.ok) {
|
|
@@ -144,6 +144,9 @@ async function call(op, body = {}, options = {}) {
|
|
|
144
144
|
return {
|
|
145
145
|
ok: false,
|
|
146
146
|
...(transient ? { transient: true } : {}),
|
|
147
|
+
// A refused key. Only a cue to ask the board whether Remove took it
|
|
148
|
+
// away (lib/selfUninstall.mjs); never proof on its own (#4978).
|
|
149
|
+
...(response.status === 401 ? { unauthorized: true } : {}),
|
|
147
150
|
...(wait !== undefined ? { retryAfterMs: wait } : {}),
|
|
148
151
|
error:
|
|
149
152
|
response.status === 401
|
|
@@ -155,7 +158,9 @@ async function call(op, body = {}, options = {}) {
|
|
|
155
158
|
return { ok: false, error: `board-runner answered with unreadable JSON: ${text.slice(0, 400)}` };
|
|
156
159
|
}
|
|
157
160
|
if (payload.ok === false) {
|
|
158
|
-
|
|
161
|
+
// `refused`: the function answered no. `retry` marks the refusals that
|
|
162
|
+
// only hold while other work runs; the rest stay refused.
|
|
163
|
+
return { ok: false, refused: true, ...(payload.retry === true ? { retry: true } : {}), error: errorDetail(payload.error) ?? "board-runner refused the request." };
|
|
159
164
|
}
|
|
160
165
|
if (payload.ok !== true) return { ok: false, error: "board-runner returned an incomplete response." };
|
|
161
166
|
return payload;
|
|
@@ -179,8 +184,8 @@ export function register({ runnerId, host, platform, presence, projects }, optio
|
|
|
179
184
|
* rows), stop signals for every running run on them, and op signals
|
|
180
185
|
* (untaken `run_ops` rows) - replacing `.runner.json`'s beat, `<id>.stop`,
|
|
181
186
|
* and the merge/delete/relaunch/preview signal files all at once. */
|
|
182
|
-
export function heartbeat({ projectIds, presence, runnerInstanceId, activeRunIds } = {}, options = {}) {
|
|
183
|
-
return call("heartbeat", { projectIds, ...(presence !== undefined ? { presence } : {}), ...(runnerInstanceId !== undefined ? { runnerInstanceId } : {}), ...(activeRunIds !== undefined ? { activeRunIds } : {}) }, options);
|
|
187
|
+
export function heartbeat({ projectIds, presence, runnerInstanceId, activeRunIds, leaseGenerations } = {}, options = {}) {
|
|
188
|
+
return call("heartbeat", { projectIds, ...(presence !== undefined ? { presence } : {}), ...(runnerInstanceId !== undefined ? { runnerInstanceId } : {}), ...(activeRunIds !== undefined ? { activeRunIds } : {}), ...(leaseGenerations !== undefined ? { leaseGenerations } : {}) }, options);
|
|
184
189
|
}
|
|
185
190
|
|
|
186
191
|
/** `claim {projectIds}` -> `{run}` or `{run:null}`. The oldest approved,
|
|
@@ -188,8 +193,8 @@ export function heartbeat({ projectIds, presence, runnerInstanceId, activeRunIds
|
|
|
188
193
|
* `listRequests`/`claimRequest`'s exclusive-create-on-disk race. `run.request`
|
|
189
194
|
* is the SpawnRequest a file used to carry; `run.project_id` names which
|
|
190
195
|
* registered project (and therefore which root) it belongs to. */
|
|
191
|
-
export function claim({ projectIds, runnerInstanceId }, options = {}) {
|
|
192
|
-
return call("claim", { projectIds, ...(runnerInstanceId !== undefined ? { runnerInstanceId } : {}) }, options);
|
|
196
|
+
export function claim({ projectIds, runnerInstanceId, fencing }, options = {}) {
|
|
197
|
+
return call("claim", { projectIds, ...(runnerInstanceId !== undefined ? { runnerInstanceId } : {}), ...(fencing === true ? { fencing } : {}) }, options);
|
|
193
198
|
}
|
|
194
199
|
|
|
195
200
|
/** `update {runId, patch}` -> ok, or `{ok:false, error:"result already
|
|
@@ -198,8 +203,8 @@ export function claim({ projectIds, runnerInstanceId }, options = {}) {
|
|
|
198
203
|
* is the one call that replaces `<id>.session.json`, `<id>.server`, and
|
|
199
204
|
* `<id>.result.txt` all at once, plus the `startSession`/`endSession` ops
|
|
200
205
|
* files: the run row IS the start/end stamp now. */
|
|
201
|
-
export function update({ runId, patch }, options = {}) {
|
|
202
|
-
return call("update", { runId, patch }, options);
|
|
206
|
+
export function update({ runId, patch, generation }, options = {}) {
|
|
207
|
+
return call("update", { runId, patch, ...(generation ? { generation } : {}) }, options);
|
|
203
208
|
}
|
|
204
209
|
|
|
205
210
|
/** `events {runId, events:[{seq, kind, text}]}` -> insert, duplicates on
|
|
@@ -228,8 +233,8 @@ export function opResult({ opId, result }, options = {}) {
|
|
|
228
233
|
/** `runs {projectIds, status?}` -> a list, for maintenance: the sweep's
|
|
229
234
|
* equivalent of scanning `inbox/spawn/` for finished ids, and late
|
|
230
235
|
* promotion's equivalent of finding a session's own row to resume. */
|
|
231
|
-
export function runs({ projectIds, status } = {}, options = {}) {
|
|
232
|
-
return call("runs", { projectIds, ...(status !== undefined ? { status } : {}) }, options);
|
|
236
|
+
export function runs({ projectIds, status, lateMessages } = {}, options = {}) {
|
|
237
|
+
return call("runs", { projectIds, ...(status !== undefined ? { status } : {}), ...(lateMessages ? { lateMessages: true } : {}) }, options);
|
|
233
238
|
}
|
|
234
239
|
|
|
235
240
|
/** `resume {runId, message, images?}` -> inserts an APPROVED child run row
|
|
@@ -254,8 +259,8 @@ export function runs({ projectIds, status } = {}, options = {}) {
|
|
|
254
259
|
* function does not destructure is simply absent from `body` there, never
|
|
255
260
|
* a hard failure; the day that worker's change lands, this call needs no
|
|
256
261
|
* edit to start actually delivering pictures. */
|
|
257
|
-
export function resume({ runId, message, images, unlessStopped }, options = {}) {
|
|
258
|
-
return call("resume", { runId, message, ...(images?.length > 0 ? { images } : {}), ...(unlessStopped ? { unlessStopped: true } : {}) }, options);
|
|
262
|
+
export function resume({ runId, message, images, unlessStopped, promotionId }, options = {}) {
|
|
263
|
+
return call("resume", { runId, message, ...(images?.length > 0 ? { images } : {}), ...(unlessStopped ? { unlessStopped: true } : {}), ...(promotionId ? { promotionId } : {}) }, options);
|
|
259
264
|
}
|
|
260
265
|
|
|
261
266
|
/** `presence {paths?}` -> `{projects:[{id, path, host, runner_id,
|
|
@@ -310,3 +315,14 @@ export function realtime(options = {}) {
|
|
|
310
315
|
/** Names-only discovery, requested by the person in Settings (#1132). */
|
|
311
316
|
export function computerAppsTake(body, options = {}) { return call("computerAppsTake", body, options); }
|
|
312
317
|
export function computerAppsResult(body, options = {}) { return call("computerAppsResult", body, options); }
|
|
318
|
+
|
|
319
|
+
/** The Folder panel's file list or one file, asked from the app (#3703). */
|
|
320
|
+
export function folderReadTake(body, options = {}) { return call("folderReadTake", body, options); }
|
|
321
|
+
export function folderReadResult(body, options = {}) { return call("folderReadResult", body, options); }
|
|
322
|
+
|
|
323
|
+
/** Take the board's Update request once no run is going (#4949). Taking
|
|
324
|
+
* deletes it, so Cancel update and the take cannot both win. */
|
|
325
|
+
export function updateTake(body, options = {}) { return call("updateTake", body, options); }
|
|
326
|
+
|
|
327
|
+
/** Recover a locally proven dead owner without waiting for lease expiry. */
|
|
328
|
+
export function recover(body, options = {}) { return call("recover", body, options); }
|
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
// The heartbeat half of `watch()` (runner.mjs), moved out of it (#4668):
|
|
2
|
+
// one beat (register, heartbeat, ops, the restart pass, the server sweep),
|
|
3
|
+
// the pace that schedules the next one, and what the realtime channel's
|
|
4
|
+
// events ask of it. `w` is the watcher's state the beat shares with
|
|
5
|
+
// `watch()`'s claim loop: `project`, `forgotten`, `finished`, `claimHint`,
|
|
6
|
+
// `hintSeq`, and `wake`/`kickClaim` for the loop's two waits.
|
|
7
|
+
|
|
8
|
+
import * as runnerApiModule from "./runnerApi.mjs";
|
|
9
|
+
import { callRunnerTool } from "./hosted.mjs";
|
|
10
|
+
import { DEFAULTS } from "./child.mjs";
|
|
11
|
+
import { presenceBody, refreshProjectPaths, registerAndFindProject } from "./runnerRegister.mjs";
|
|
12
|
+
import { liveRuns, restartPass, RECOVERY_RECHECK_MS, RESTART_RECHECK_MS } from "./restartPass.mjs";
|
|
13
|
+
import { orphanRecoveries } from "./runnerRecovery.mjs";
|
|
14
|
+
import { flushCompletions } from "./runnerSettlement.mjs";
|
|
15
|
+
import { SERVER_SWEEP_INTERVAL_MS, sweepDetachedServers } from "./serverSweep.mjs";
|
|
16
|
+
import { createSharedPreviewService } from "./sharedPreview.mjs";
|
|
17
|
+
import { createMemberPreviewTunnel } from "./memberPreview.mjs";
|
|
18
|
+
import { beatPace } from "./runnerPace.mjs";
|
|
19
|
+
import { resumeLateMessages } from "./lateResume.mjs";
|
|
20
|
+
import { serviceForgetOps, serviceRowOps } from "./runnerOps.mjs";
|
|
21
|
+
import { serviceUninstallOps, uninstallIfRemoved } from "./selfUninstall.mjs";
|
|
22
|
+
|
|
23
|
+
/** How soon the beat looks again for late messages: while one waits, and
|
|
24
|
+
* while none does (a pushed reply brings it forward either way). */
|
|
25
|
+
export const LATE_MESSAGES_BUSY_MS = 60_000;
|
|
26
|
+
export const LATE_MESSAGES_IDLE_MS = 5 * 60_000;
|
|
27
|
+
|
|
28
|
+
/** When the next look for late messages is due, after one listed `waiting`
|
|
29
|
+
* runs (resumeLateMessages's count). */
|
|
30
|
+
export const nextLateLookAt = (waiting, settings = {}, now = Date.now()) =>
|
|
31
|
+
now + (waiting > 0 ? LATE_MESSAGES_BUSY_MS : settings.lateMessagesIdleMs ?? LATE_MESSAGES_IDLE_MS);
|
|
32
|
+
|
|
33
|
+
/** Whether a pushed reply may be a late message: it names a session this
|
|
34
|
+
* process is not running. A live run reads its own replies (rowsAnswers.mjs)
|
|
35
|
+
* and its key is its run id, so every watcher stays still for those. */
|
|
36
|
+
export const replyMayBeLate = (payload, live = liveRuns) =>
|
|
37
|
+
typeof payload?.session_key === "string" && payload.session_key !== "" && !live.has(payload.session_key);
|
|
38
|
+
|
|
39
|
+
/** A wait anyone can end: `wait()` hands out the pending promise (made on
|
|
40
|
+
* first ask), `fire()` resolves it and starts a fresh one next time. */
|
|
41
|
+
export function makeLatch() {
|
|
42
|
+
let pending = null;
|
|
43
|
+
return {
|
|
44
|
+
wait: () => (pending ??= (() => {
|
|
45
|
+
let resolve;
|
|
46
|
+
const promise = new Promise((r) => { resolve = r; });
|
|
47
|
+
return { promise, resolve };
|
|
48
|
+
})()).promise,
|
|
49
|
+
fire: () => {
|
|
50
|
+
pending?.resolve();
|
|
51
|
+
pending = null;
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** The shared preview service a watcher owns, with its one in-flight tick
|
|
57
|
+
* and its one close. */
|
|
58
|
+
export function makeWatchPreview(settings, log, startPreviewTransport) {
|
|
59
|
+
// Both CLI entry points and multiwatch arrive here. Always service preview
|
|
60
|
+
// rows through the member gateway; tests can replace the public transport,
|
|
61
|
+
// but the membership and target-ownership checks stay on this path. Missing
|
|
62
|
+
// access configuration becomes an error on the op, without exposing a port.
|
|
63
|
+
const previewService = createSharedPreviewService({
|
|
64
|
+
runnerApi: settings.runnerApi ?? runnerApiModule,
|
|
65
|
+
hostedCallTool: settings.hostedCallTool ?? callRunnerTool,
|
|
66
|
+
env: settings.env,
|
|
67
|
+
fetchImpl: settings.fetchImpl,
|
|
68
|
+
startTunnel: (origin, context) => createMemberPreviewTunnel(origin, context, {
|
|
69
|
+
env: settings.env, startTransport: startPreviewTransport,
|
|
70
|
+
}),
|
|
71
|
+
});
|
|
72
|
+
let previewClosing;
|
|
73
|
+
const closePreview = () => previewClosing ??= previewService.close().catch((error) => {
|
|
74
|
+
log(`preview shutdown failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
75
|
+
});
|
|
76
|
+
let previewTick;
|
|
77
|
+
const tickPreview = () => {
|
|
78
|
+
if (previewTick || previewClosing) return;
|
|
79
|
+
// Download/connect can take minutes. The preview owns that wait; runner
|
|
80
|
+
// presence, Stop/forget delivery and first-run admission must keep moving.
|
|
81
|
+
previewTick = previewService.tick()
|
|
82
|
+
.catch((error) => log(`preview tick failed: ${error instanceof Error ? error.message : String(error)}`))
|
|
83
|
+
.finally(() => { previewTick = null; });
|
|
84
|
+
};
|
|
85
|
+
return { service: previewService, close: closePreview, tick: tickPreview, closing: () => Boolean(previewClosing) };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** The beat, its schedule, and the handlers for pushed events and asked-for
|
|
89
|
+
* beats. `watch()` starts it with `beat()` then `scheduleBeat()`. */
|
|
90
|
+
export function makeBeatLoop(w) {
|
|
91
|
+
const { root, settings, log, stopped, heartbeats, realtime, beatBase, preview } = w;
|
|
92
|
+
// THE DETACHED DEV SERVERS this folder's finished runs left behind, checked
|
|
93
|
+
// once a day off the beat (lib/serverSweep.mjs). Rows, not files: the
|
|
94
|
+
// record lives on the run row since brief 30.
|
|
95
|
+
let serverSweptAt = 0;
|
|
96
|
+
const sweepServers = async () => {
|
|
97
|
+
if (Date.now() - serverSweptAt < (settings.serverSweepMs ?? SERVER_SWEEP_INTERVAL_MS)) return;
|
|
98
|
+
serverSweptAt = Date.now();
|
|
99
|
+
try {
|
|
100
|
+
await sweepDetachedServers(w.project, settings, { log });
|
|
101
|
+
} catch (error) {
|
|
102
|
+
log(`dev server sweep failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
// Recheck periodically too: the same watcher may lose touch and recover
|
|
106
|
+
// more than once without restarting its own process (#1252).
|
|
107
|
+
let restartDueAt = 0;
|
|
108
|
+
let recoveryDueAt = 0;
|
|
109
|
+
let lateMessagesDueAt = 0;
|
|
110
|
+
// A dead owner's record on this computer (#4948). Disk only; while there is
|
|
111
|
+
// none, the pass and the beat keep the pace they had (#616).
|
|
112
|
+
const orphaned = () => Boolean(w.project) && orphanRecoveries(w.project, settings, liveRuns) > 0;
|
|
113
|
+
|
|
114
|
+
// Ownership misses (including a deleted id) use this exact refusal. After
|
|
115
|
+
// glytch login changes accounts, retry registration on the next beat without
|
|
116
|
+
// letting either shared cache hand back the old account's project id.
|
|
117
|
+
const clearRefusedProject = (answer) => {
|
|
118
|
+
if (!w.project || answer.ok !== false || answer.transient === true || answer.error !== "not yours") return;
|
|
119
|
+
heartbeats.leave(w.project.id);
|
|
120
|
+
realtime?.setFolder(w.project.id, false);
|
|
121
|
+
w.project = null;
|
|
122
|
+
w.claimHint = false;
|
|
123
|
+
settings.registrar.invalidate?.();
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
// A refused key is only a cue: the board decides whether Remove took it
|
|
127
|
+
// away while this computer was off (#4978, lib/selfUninstall.mjs).
|
|
128
|
+
const askIfRemoved = async (answer) => {
|
|
129
|
+
if (answer.unauthorized !== true) return;
|
|
130
|
+
try { await (settings.uninstallIfRemoved ?? uninstallIfRemoved)(settings, log); }
|
|
131
|
+
catch (error) { log(`uninstall check failed: ${error instanceof Error ? error.message : String(error)}`); }
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
// The Retry-After of the last beat that failed, for the beat's own pace.
|
|
135
|
+
let beatRetryAfterMs;
|
|
136
|
+
const runBeat = async () => {
|
|
137
|
+
beatRetryAfterMs = undefined;
|
|
138
|
+
if (w.forgotten) return;
|
|
139
|
+
const registered = w.project !== null;
|
|
140
|
+
// A known folder must hear Remove before register can clear forgotten_at
|
|
141
|
+
// through its link RPC. Only startup needs register to obtain the id.
|
|
142
|
+
if (!registered) {
|
|
143
|
+
const reg = await registerAndFindProject(root, settings);
|
|
144
|
+
if (!reg.ok) {
|
|
145
|
+
log(`could not register with the board: ${reg.error}`);
|
|
146
|
+
await askIfRemoved(reg);
|
|
147
|
+
beatRetryAfterMs = reg.retryAfterMs;
|
|
148
|
+
return reg.transient ? "failed" : "steady";
|
|
149
|
+
}
|
|
150
|
+
if (!reg.myProjectId) {
|
|
151
|
+
log(`this folder is not among the projects the board acknowledged; nothing will be claimed`);
|
|
152
|
+
return "steady";
|
|
153
|
+
}
|
|
154
|
+
w.project = { id: reg.myProjectId, path: root };
|
|
155
|
+
realtime?.setFolder(w.project.id, true);
|
|
156
|
+
}
|
|
157
|
+
const flushed = await flushCompletions(w.project, settings, log);
|
|
158
|
+
const runnerApi = settings.runnerApi ?? runnerApiModule;
|
|
159
|
+
const seen = w.hintSeq;
|
|
160
|
+
await refreshProjectPaths(root, settings);
|
|
161
|
+
const beat = await heartbeats.beat(w.project.id, (projectIds) => runnerApi.heartbeat({ projectIds, presence: presenceBody(settings) }, { env: settings.env, fetchImpl: settings.fetchImpl }));
|
|
162
|
+
if (!beat.ok) {
|
|
163
|
+
clearRefusedProject(beat);
|
|
164
|
+
log(`heartbeat failed: ${beat.error}`);
|
|
165
|
+
await askIfRemoved(beat);
|
|
166
|
+
beatRetryAfterMs = beat.retryAfterMs;
|
|
167
|
+
return beat.transient ? "failed" : "steady";
|
|
168
|
+
}
|
|
169
|
+
// The shared answer holds every folder's ops; keep this folder's. An op
|
|
170
|
+
// naming no project is only taken from an answer for this folder alone.
|
|
171
|
+
const alone = (beat.coveredProjectIds ?? [w.project.id]).every((id) => id === w.project.id);
|
|
172
|
+
const ops = (beat.ops ?? []).filter((op) => (op.project_id ? op.project_id === w.project.id : alone));
|
|
173
|
+
if (Array.isArray(beat.pending)) {
|
|
174
|
+
w.claimHint = beat.pending.includes(w.project.id) || w.hintSeq !== seen;
|
|
175
|
+
if (w.claimHint) w.hintSeq += 1, w.wake();
|
|
176
|
+
} else {
|
|
177
|
+
w.claimHint = null;
|
|
178
|
+
w.hintSeq += 1;
|
|
179
|
+
w.wake();
|
|
180
|
+
}
|
|
181
|
+
try { await settings.onHealthy?.(root); }
|
|
182
|
+
catch (error) { log(`Could not write local connection check: ${error.message}`); }
|
|
183
|
+
// Stops are run ids: another folder's in this set is never acted on.
|
|
184
|
+
for (const runId of beat.stops ?? []) stopped.add(runId);
|
|
185
|
+
let opsFailed = false;
|
|
186
|
+
// Remove on this online computer (#4951): it uninstalls itself, which
|
|
187
|
+
// stops this daemon in a moment, so nothing else on this beat starts.
|
|
188
|
+
if (serviceUninstallOps(ops, settings, log)) return "steady";
|
|
189
|
+
if (ops.length > 0) {
|
|
190
|
+
// FIRST, and it returns early: there is no point merging a worktree or
|
|
191
|
+
// standing a preview up for a folder that is leaving this machine.
|
|
192
|
+
try {
|
|
193
|
+
if (await serviceForgetOps(root, w.project, ops, settings, log)) {
|
|
194
|
+
w.forgotten = true;
|
|
195
|
+
heartbeats.leave(w.project.id);
|
|
196
|
+
realtime?.setFolder(w.project.id, false);
|
|
197
|
+
w.wake();
|
|
198
|
+
await preview.close();
|
|
199
|
+
return "work";
|
|
200
|
+
}
|
|
201
|
+
} catch (error) {
|
|
202
|
+
opsFailed = true;
|
|
203
|
+
log(`forget failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
// Retry retained Look answers even though claimed requests are absent
|
|
207
|
+
// from later heartbeat operations. Forget above always takes priority.
|
|
208
|
+
try { opsFailed = !(await serviceRowOps(root, w.project, ops, settings, log, { updatesUnread: beat.updatesUnread === true })).ok || opsFailed; }
|
|
209
|
+
catch (error) {
|
|
210
|
+
opsFailed = true;
|
|
211
|
+
log(`ops sweep failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
212
|
+
}
|
|
213
|
+
if (ops.length > 0) {
|
|
214
|
+
try { await preview.service.onOps(ops, w.project.id); }
|
|
215
|
+
catch (error) {
|
|
216
|
+
opsFailed = true;
|
|
217
|
+
log(`preview claim failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
// The shared register names ALL folders. If another folder is leaving,
|
|
221
|
+
// let its watcher consume the same forget before refreshing that list.
|
|
222
|
+
// A failed heartbeat or forget never reaches a register that could erase it.
|
|
223
|
+
if (registered && !opsFailed && !(beat.ops ?? []).some((op) => op.kind === "forget")) {
|
|
224
|
+
const reg = await refreshRegistration(root, settings, runnerApi);
|
|
225
|
+
if (!reg.ok) {
|
|
226
|
+
clearRefusedProject(reg);
|
|
227
|
+
log(`could not register with the board: ${reg.error}`);
|
|
228
|
+
beatRetryAfterMs = reg.retryAfterMs;
|
|
229
|
+
return reg.transient ? "failed" : "steady";
|
|
230
|
+
}
|
|
231
|
+
if (!reg.myProjectId) {
|
|
232
|
+
log(`this folder is not among the projects the board acknowledged; nothing will be claimed`);
|
|
233
|
+
return "steady";
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
// THE RESTART PASS (brief 52, ruling 7): sessions the last process left
|
|
237
|
+
// running pick up where they were. Only once receipts that were saved but
|
|
238
|
+
// not yet delivered have gone out, or a run that really finished would be
|
|
239
|
+
// continued over its own ending.
|
|
240
|
+
if (flushed && (Date.now() >= restartDueAt || (Date.now() >= recoveryDueAt && orphaned()))) {
|
|
241
|
+
restartDueAt = Date.now() + (settings.restartRecheckMs ?? RESTART_RECHECK_MS);
|
|
242
|
+
recoveryDueAt = Date.now() + (settings.recoveryRecheckMs ?? RECOVERY_RECHECK_MS);
|
|
243
|
+
try { await restartPass(w.project, settings, { log, startRun: w.startRecovered }); }
|
|
244
|
+
catch (error) { log(`restart pass failed: ${error instanceof Error ? error.message : String(error)}`); }
|
|
245
|
+
}
|
|
246
|
+
// LATE MESSAGES (#5101, #5106): every minute while some finished run has
|
|
247
|
+
// one waiting, every five while none does. A reply pushed for a run this
|
|
248
|
+
// process is not running brings the next look forward (onPush below).
|
|
249
|
+
if (flushed && Date.now() >= lateMessagesDueAt) {
|
|
250
|
+
lateMessagesDueAt = Date.now() + LATE_MESSAGES_BUSY_MS;
|
|
251
|
+
try { lateMessagesDueAt = nextLateLookAt(await resumeLateMessages(w.project, settings, log), settings); }
|
|
252
|
+
catch (error) { opsFailed = true; log(`late answers: ${error.message}`); }
|
|
253
|
+
}
|
|
254
|
+
await sweepServers();
|
|
255
|
+
preview.tick();
|
|
256
|
+
// Use the existing failure backoff while an answer is waiting, rather
|
|
257
|
+
// than the five-minute idle cadence used with realtime connected.
|
|
258
|
+
return opsFailed ? "failed" : "work";
|
|
259
|
+
};
|
|
260
|
+
let beatInFlight;
|
|
261
|
+
// THE PACE OF BOTH LOOPS (ticket e8, lib/runnerPace.mjs). The beat keeps
|
|
262
|
+
// its 10 s while the board answers and backs off to 60 s on 5xx or network
|
|
263
|
+
// failures; the claim loop does the same under errors. While the queue
|
|
264
|
+
// stays empty it makes no call at all when the beat carries `pending`, and
|
|
265
|
+
// slows to 30 s against an older function that does not (#616).
|
|
266
|
+
const beatPacer = beatPace(settings, DEFAULTS.beatMs);
|
|
267
|
+
let beatDelay = beatPacer.work();
|
|
268
|
+
// A failed beat backs off from 10 s whatever the cadence; any other waits
|
|
269
|
+
// the cadence of the moment: 5 minutes while joined, 10 s while not.
|
|
270
|
+
const beat = () => {
|
|
271
|
+
if (w.forgotten || w.finished) return Promise.resolve();
|
|
272
|
+
// Serialize the row sweeps, independently of the long-lived preview work.
|
|
273
|
+
return beatInFlight ??= runBeat()
|
|
274
|
+
.then((outcome) => {
|
|
275
|
+
if (outcome === "failed") beatDelay = beatPacer.failed(beatRetryAfterMs);
|
|
276
|
+
else {
|
|
277
|
+
beatPacer.work();
|
|
278
|
+
beatDelay = beatBase();
|
|
279
|
+
}
|
|
280
|
+
}, (error) => {
|
|
281
|
+
beatPacer.steady();
|
|
282
|
+
beatDelay = beatBase();
|
|
283
|
+
throw error;
|
|
284
|
+
})
|
|
285
|
+
.finally(() => { beatInFlight = null; });
|
|
286
|
+
};
|
|
287
|
+
const beatFailed = (error) => log(`heartbeat failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
288
|
+
// A chain of timeouts rather than an interval, so the wait after each beat
|
|
289
|
+
// can depend on how that beat went. One timer at most: every schedule
|
|
290
|
+
// replaces the last.
|
|
291
|
+
let beating;
|
|
292
|
+
let beatAgain = false;
|
|
293
|
+
const scheduleBeat = () => {
|
|
294
|
+
clearTimeout(beating);
|
|
295
|
+
if (w.forgotten || w.finished) return;
|
|
296
|
+
const delay = beatAgain ? 0 : orphaned() ? Math.min(beatDelay, settings.recoveryRecheckMs ?? RECOVERY_RECHECK_MS) : beatDelay;
|
|
297
|
+
beatAgain = false;
|
|
298
|
+
beating = setTimeout(() => {
|
|
299
|
+
void beat().catch(beatFailed).finally(scheduleBeat);
|
|
300
|
+
}, delay);
|
|
301
|
+
beating.unref?.();
|
|
302
|
+
};
|
|
303
|
+
// A beat now, for an event: after the one in flight if there is one.
|
|
304
|
+
const beatNow = () => {
|
|
305
|
+
if (w.forgotten || w.finished) return;
|
|
306
|
+
if (beatInFlight) {
|
|
307
|
+
beatAgain = true;
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
clearTimeout(beating);
|
|
311
|
+
void beat().catch(beatFailed).finally(scheduleBeat);
|
|
312
|
+
};
|
|
313
|
+
|
|
314
|
+
// WHAT THE CHANNEL SAYS (#813). Each event becomes the call this loop
|
|
315
|
+
// already makes; none of them claims or stops by itself.
|
|
316
|
+
// - joined: one heartbeat now, the catch-up for whatever was sent while
|
|
317
|
+
// the socket was down, then every 5 minutes
|
|
318
|
+
// - left: back to every 10 s, from now
|
|
319
|
+
// - pending (this folder): claim now, through claimOne (#364)
|
|
320
|
+
// - stop: the run id joins `stopped`, which the session checks every 2 s
|
|
321
|
+
// - op (this folder): a heartbeat now, which hands the op over
|
|
322
|
+
// `at` is the same for every folder, so the hub still sends one heartbeat
|
|
323
|
+
// for all of them.
|
|
324
|
+
const onPush = (event) => {
|
|
325
|
+
if (w.forgotten || w.finished) return;
|
|
326
|
+
const payload = event.payload ?? {};
|
|
327
|
+
const mine = () => w.project !== null && (payload.project_id ?? w.project.id) === w.project.id;
|
|
328
|
+
if (event.type === "joined") {
|
|
329
|
+
lateMessagesDueAt = 0;
|
|
330
|
+
heartbeats.invalidate(event.at);
|
|
331
|
+
beatNow();
|
|
332
|
+
} else if (event.type === "left") {
|
|
333
|
+
heartbeats.invalidate(event.at);
|
|
334
|
+
beatDelay = beatBase();
|
|
335
|
+
if (!beatInFlight) scheduleBeat();
|
|
336
|
+
} else if (event.type === "pending" && mine()) {
|
|
337
|
+
w.claimHint = true;
|
|
338
|
+
w.hintSeq += 1;
|
|
339
|
+
w.wake();
|
|
340
|
+
w.kickClaim();
|
|
341
|
+
} else if (event.type === "stop" && typeof payload.run_id === "string") {
|
|
342
|
+
if (w.project === null || mine()) stopped.add(payload.run_id);
|
|
343
|
+
} else if (event.type === "op" && mine()) {
|
|
344
|
+
heartbeats.invalidate(event.at);
|
|
345
|
+
beatNow();
|
|
346
|
+
} else if (event.type === "reply" && w.project !== null && replyMayBeLate(payload)) {
|
|
347
|
+
// A reply names only its session (the runner_reply_push broadcast), so
|
|
348
|
+
// only one for a run not live here brings the next look forward (#5106).
|
|
349
|
+
lateMessagesDueAt = 0;
|
|
350
|
+
beatNow();
|
|
351
|
+
}
|
|
352
|
+
};
|
|
353
|
+
// `glytch init` asking for a fresh beat (multiwatch's beatRequests).
|
|
354
|
+
const onBeatAsk = (at) => {
|
|
355
|
+
if (w.forgotten || w.finished) return;
|
|
356
|
+
heartbeats.invalidate(at);
|
|
357
|
+
beatNow();
|
|
358
|
+
};
|
|
359
|
+
return { beat, scheduleBeat, beatNow, onPush, onBeatAsk, stop: () => clearTimeout(beating), inFlight: () => beatInFlight };
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/** Register again after a beat's ops, through a registrar that first checks
|
|
363
|
+
* no folder removal is pending (a register would erase it). */
|
|
364
|
+
async function refreshRegistration(root, settings, runnerApi) {
|
|
365
|
+
const refreshSettings = {
|
|
366
|
+
...settings,
|
|
367
|
+
registrar: {
|
|
368
|
+
register: (key, send) => settings.registrar.register(key, async () => {
|
|
369
|
+
// Row ops may have awaited a slow merge after the beat snapshot.
|
|
370
|
+
// Bypass the heartbeat cache, only when register is actually due.
|
|
371
|
+
// The remaining read/write gap is closed server-side by
|
|
372
|
+
// https://github.com/glytch-ai/glytch/issues/1065.
|
|
373
|
+
const rowsOpts = { env: settings.env, fetchImpl: settings.fetchImpl };
|
|
374
|
+
// The registrar key is the exact path list captured by send().
|
|
375
|
+
// Presence includes forgotten rows; scope to this register's host.
|
|
376
|
+
const listed = await runnerApi.presence({ paths: JSON.parse(key) }, rowsOpts);
|
|
377
|
+
if (!listed.ok) return listed;
|
|
378
|
+
const projectIds = (listed.projects ?? [])
|
|
379
|
+
.filter((p) => p.host === (settings.host ?? "local"))
|
|
380
|
+
.map((p) => p.id);
|
|
381
|
+
// New paths have no id yet and cannot have a pending forget.
|
|
382
|
+
// This bare heartbeat only bumps last_seen_at: it neither replaces
|
|
383
|
+
// presence nor claims, acknowledges or marks ops delivered.
|
|
384
|
+
const latest = projectIds.length > 0
|
|
385
|
+
? await runnerApi.heartbeat({ projectIds }, rowsOpts)
|
|
386
|
+
: { ok: true, ops: [] };
|
|
387
|
+
if (!latest.ok) return latest;
|
|
388
|
+
if ((latest.ops ?? []).some((op) => op.kind === "forget")) {
|
|
389
|
+
return { ok: false, error: "Registration deferred: a folder removal is pending." };
|
|
390
|
+
}
|
|
391
|
+
return send();
|
|
392
|
+
}),
|
|
393
|
+
},
|
|
394
|
+
};
|
|
395
|
+
const reg = await registerAndFindProject(root, refreshSettings);
|
|
396
|
+
Object.assign(settings, { noGit: refreshSettings.noGit, projectPaths: refreshSettings.projectPaths });
|
|
397
|
+
return reg;
|
|
398
|
+
}
|
package/lib/runnerCompletion.mjs
CHANGED
|
@@ -197,8 +197,9 @@ export async function completeRequest(context, services = defaultServices) {
|
|
|
197
197
|
if (!mayHaveChangedFiles(outcome.log, { dropped: outcome.dropped })) return false;
|
|
198
198
|
try { return !(await inGit(made.cwd)); } catch { return false; }
|
|
199
199
|
};
|
|
200
|
+
let resultLanded = false;
|
|
200
201
|
try {
|
|
201
|
-
await reportOutcomeOnBoard(session, outcome, from, {
|
|
202
|
+
const receipt = await reportOutcomeOnBoard(session, outcome, from, {
|
|
202
203
|
callTool: hostedCallTool,
|
|
203
204
|
env: hostedEnv,
|
|
204
205
|
request,
|
|
@@ -207,6 +208,7 @@ export async function completeRequest(context, services = defaultServices) {
|
|
|
207
208
|
inPlace: await changedNonGitFolder(),
|
|
208
209
|
preview: Number.isFinite(Number(server?.port)) ? `http://localhost:${Number(server.port)}` : undefined,
|
|
209
210
|
});
|
|
211
|
+
resultLanded = receipt?.landed === true;
|
|
210
212
|
} catch (error) {
|
|
211
213
|
log(`[${id}] could not comment the outcome onto the board: ${error instanceof Error ? error.message : String(error)}`);
|
|
212
214
|
}
|
|
@@ -245,7 +247,7 @@ export async function completeRequest(context, services = defaultServices) {
|
|
|
245
247
|
// final sidecar and may retain their early workspace receipt instead.
|
|
246
248
|
// The pictures ride on the closing reply only: two of them on every run
|
|
247
249
|
// row would weigh down each list of runs (#2194).
|
|
248
|
-
sidecar: { ...(sidecar ?? {}), ...(outcome.result ? { result: withoutPictures(outcome.result) } : {}), ...(status === "error" ? agentErrorOf(outcome) : {}) },
|
|
250
|
+
sidecar: { ...(sidecar ?? {}), resultLanded, ...(outcome.result ? { result: withoutPictures(outcome.result) } : {}), ...(status === "error" ? agentErrorOf(outcome) : {}) },
|
|
249
251
|
...(server ? { server } : {}),
|
|
250
252
|
};
|
|
251
253
|
|
|
@@ -260,6 +262,7 @@ export async function completeRequest(context, services = defaultServices) {
|
|
|
260
262
|
root, id,
|
|
261
263
|
{
|
|
262
264
|
poller: rowsPoll, callTool: hostedCallTool, sessionKey: session.key, env: hostedEnv,
|
|
265
|
+
deferMessages: true, // The heartbeat asks after the terminal receipt is saved (#5103).
|
|
263
266
|
promote: async (_root, targetId, reply, _log, promotionId) => {
|
|
264
267
|
// IMAGES, item 6: `reply.images` is the late row's own images
|
|
265
268
|
// (rowsAnswers.mjs's `promoteLateRows`), carried into `resume`
|