@cloop/runner 0.3.29 → 0.3.30

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/README.md CHANGED
@@ -72,3 +72,10 @@ npm install
72
72
  npm run build
73
73
  npm test
74
74
  ```
75
+
76
+ ## OAuth fallback
77
+
78
+ Claude Code and Codex can carry each other's runs after a provider login failure.
79
+ This works for direct CLI runners and T3 runners.
80
+ See [the runbook](../docs/runbooks/runner-oauth-fallback.md) for restrictions and release steps.
81
+ After the release merges, run `bash tools/ops/runner-oauth-fallback-wizard.sh` from the repository root to approve and install it.
@@ -1,14 +1,13 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  serveTakeovers
4
- } from "./chunk-PSA5EC65.js";
5
- import "./chunk-65KJPIZC.js";
4
+ } from "./chunk-DYA2BUDB.js";
5
+ import "./chunk-HGKTPD5Z.js";
6
6
  import {
7
7
  DEFAULT_FALLBACK_MODEL,
8
8
  SUBSCRIPTIONS,
9
9
  answerCall,
10
10
  awaitDaemon,
11
- buildDiag,
12
11
  classifyError,
13
12
  claudeDialect,
14
13
  cmdWord,
@@ -27,19 +26,20 @@ import {
27
26
  programFor,
28
27
  psQuote,
29
28
  runSteps,
30
- runnerLog,
31
29
  serviceEnv,
32
30
  stopService,
33
31
  systemServices,
34
32
  unitFor,
35
33
  which
36
- } from "./chunk-SVHQXVCH.js";
34
+ } from "./chunk-J4YN6KXM.js";
37
35
  import {
38
36
  MeshSocket,
39
37
  WAKE_TICK_MS,
38
+ buildDiag,
40
39
  defaultSocketFactory,
40
+ runnerLog,
41
41
  wakeWatch
42
- } from "./chunk-KYGYU5G2.js";
42
+ } from "./chunk-52CUSFDQ.js";
43
43
  import {
44
44
  BoxWatch,
45
45
  hostedThreadsFilePath,
@@ -48,7 +48,7 @@ import {
48
48
  runnerStatePath,
49
49
  threadsFilePath,
50
50
  writeRunnerState
51
- } from "./chunk-GURADB5L.js";
51
+ } from "./chunk-3YJD6J2N.js";
52
52
  import {
53
53
  BackgroundReading,
54
54
  BoxToolError,
@@ -92,7 +92,7 @@ import {
92
92
  utcWindow,
93
93
  windowsPowerShellEnv,
94
94
  writeBoxConfig
95
- } from "./chunk-AIOOLVM7.js";
95
+ } from "./chunk-EOWS3JIY.js";
96
96
  import {
97
97
  getMachine
98
98
  } from "./chunk-NTXQLEMQ.js";
@@ -101,12 +101,12 @@ import {
101
101
  olderThan
102
102
  } from "./chunk-365HFCQQ.js";
103
103
  import "./chunk-PKIEWBR7.js";
104
- import "./chunk-P56EL4D4.js";
105
- import "./chunk-TWDKR7XV.js";
104
+ import "./chunk-OTZDNYX4.js";
105
+ import "./chunk-IYZLO64O.js";
106
106
  import "./chunk-ES5BRAKJ.js";
107
107
  import {
108
108
  VERSION
109
- } from "./chunk-4FXRG3Q3.js";
109
+ } from "./chunk-JQGHB2EJ.js";
110
110
  import {
111
111
  getMeshUrl,
112
112
  getOrigin,
@@ -1647,6 +1647,32 @@ var LocalUsage = class {
1647
1647
  }
1648
1648
  };
1649
1649
 
1650
+ // src/last-known.ts
1651
+ function lastKnown(read, initial, { ms, what, onFail }) {
1652
+ let last = initial;
1653
+ let out2 = null;
1654
+ return async () => {
1655
+ out2 ??= read().then((value) => {
1656
+ last = value;
1657
+ return value;
1658
+ }).finally(() => {
1659
+ out2 = null;
1660
+ });
1661
+ let timer;
1662
+ const late = new Promise((_, reject) => {
1663
+ timer = setTimeout(() => reject(new Error(`${what} timed out after ${ms / 1e3}s`)), ms);
1664
+ });
1665
+ try {
1666
+ await Promise.race([out2, late]);
1667
+ } catch (err) {
1668
+ onFail(err);
1669
+ } finally {
1670
+ clearTimeout(timer);
1671
+ }
1672
+ return last;
1673
+ };
1674
+ }
1675
+
1650
1676
  // src/outside-sessions.ts
1651
1677
  import { createReadStream as createReadStream2 } from "fs";
1652
1678
  import { readdir as readdir2, stat as stat2 } from "fs/promises";
@@ -2366,6 +2392,7 @@ async function adopt(from, kind, { services: given, script = process.argv[1] ??
2366
2392
 
2367
2393
  // src/commands/box.ts
2368
2394
  var BEAT_MS = 6e4;
2395
+ var DRIVER_READ_MS = 2e4;
2369
2396
  var RESEND_MS = 5 * 6e4;
2370
2397
  var RECENT_CALLS = 20;
2371
2398
  var REPAIR_BEFORE_MS = 2 * 24 * 36e5;
@@ -2587,8 +2614,8 @@ async function run2() {
2587
2614
  resendResults();
2588
2615
  if (wake.unsent && wake.last) wake.unsent = !socket.send({ type: "wake", ...wake.last });
2589
2616
  },
2590
- onClose: (code) => log2(
2591
- code === REVOKED_CLOSE ? "disconnected by Cloop (revoked), checking" : "disconnected, reconnecting"
2617
+ onClose: (code, drop) => log2(
2618
+ drop ? `${drop.reason.replace("_", " ")} ${Math.round(drop.ms / 1e3)}s, reconnecting` : code === REVOKED_CLOSE ? "disconnected by Cloop (revoked), checking" : "disconnected, reconnecting"
2592
2619
  ),
2593
2620
  onRefused: () => void (async () => {
2594
2621
  const fresh = await awaitNewDeviceToken(token ?? "", () => readRunnerConfig()?.deviceToken);
@@ -2644,45 +2671,67 @@ async function run2() {
2644
2671
  process.platform,
2645
2672
  (error, ver) => socket.send(runnerLog("update_failed", { error, ver }))
2646
2673
  );
2647
- const beat = async () => {
2648
- await renewT3();
2649
- const callsBefore = callsStarted;
2650
- let running = 0;
2651
- let outsideThreads = [];
2652
- const shown = showsOtherThreads(readRunnerConfig());
2653
- try {
2674
+ const readDriver = lastKnown(
2675
+ async () => {
2676
+ const shown = showsOtherThreads(readRunnerConfig());
2654
2677
  const own = shown && driver.name === "claude-code";
2655
2678
  const listed = await driver.listThreads({
2656
2679
  scope: own ? "all" : "unsettled",
2657
2680
  limit: own ? 200 : 1
2658
2681
  });
2659
- running = listed.running;
2682
+ let outsideThreads = [];
2660
2683
  if (shown && driver instanceof T3Driver) outsideThreads = await driver.outsideThreads(20);
2661
2684
  if (own)
2662
2685
  outsideThreads = await listOutsideSessions(
2663
2686
  void 0,
2664
2687
  new Set(listed.threads.map((t) => t.id))
2665
2688
  );
2666
- } catch (err) {
2667
- log2(`${driver.name} unreachable: ${err instanceof Error ? err.message : String(err)}`);
2668
- socket.send(runnerLog("driver_unreachable", { error: classifyError(err, driver.name) }));
2689
+ return { shown, running: listed.running, outsideThreads };
2690
+ },
2691
+ { shown: showsOtherThreads(readRunnerConfig()), running: 0, outsideThreads: [] },
2692
+ {
2693
+ ms: DRIVER_READ_MS,
2694
+ what: `${driver.name} read`,
2695
+ onFail: (err) => {
2696
+ log2(`${driver.name} unreachable: ${err instanceof Error ? err.message : String(err)}`);
2697
+ socket.send(runnerLog("driver_unreachable", { error: classifyError(err, driver.name) }));
2698
+ }
2699
+ }
2700
+ );
2701
+ const renew = lastKnown(renewT3, void 0, {
2702
+ ms: DRIVER_READ_MS,
2703
+ what: "T3 session renewal",
2704
+ onFail: (err) => {
2705
+ t3.renewalFailed = true;
2706
+ log2(err instanceof Error ? err.message : String(err));
2707
+ }
2708
+ });
2709
+ let beating = false;
2710
+ const beat = async () => {
2711
+ if (beating) return;
2712
+ beating = true;
2713
+ try {
2714
+ await renew();
2715
+ const callsBefore = callsStarted;
2716
+ const { shown, running, outsideThreads } = await readDriver();
2717
+ lastBeatAt = (/* @__PURE__ */ new Date()).toISOString();
2718
+ socket.sendPresence(
2719
+ boxPresence({
2720
+ sessionKey,
2721
+ driver: driver.name,
2722
+ capabilities: driver.capabilities,
2723
+ machine,
2724
+ outsideThreads,
2725
+ otherThreads: shown,
2726
+ running,
2727
+ t3: cfg && isT3(cfg) ? t3Presence(cfg, t3.renewalFailed) : null,
2728
+ ...hosted ? { hosted: hosted.harness } : {}
2729
+ })
2730
+ );
2731
+ update?.beat({ running, inFlight: inFlight + callsStarted - callsBefore });
2732
+ } finally {
2733
+ beating = false;
2669
2734
  }
2670
- lastBeatAt = (/* @__PURE__ */ new Date()).toISOString();
2671
- socket.ping();
2672
- socket.sendPresence(
2673
- boxPresence({
2674
- sessionKey,
2675
- driver: driver.name,
2676
- capabilities: driver.capabilities,
2677
- machine,
2678
- outsideThreads,
2679
- otherThreads: shown,
2680
- running,
2681
- t3: cfg && isT3(cfg) ? t3Presence(cfg, t3.renewalFailed) : null,
2682
- ...hosted ? { hosted: hosted.harness } : {}
2683
- })
2684
- );
2685
- update?.beat({ running, inFlight: inFlight + callsStarted - callsBefore });
2686
2735
  };
2687
2736
  void beat();
2688
2737
  setInterval(() => void beat(), BEAT_MS);
@@ -3,7 +3,7 @@ import {
3
3
  RUN_TEXT_MAX,
4
4
  boxPath,
5
5
  runnerPath
6
- } from "./chunk-AIOOLVM7.js";
6
+ } from "./chunk-EOWS3JIY.js";
7
7
 
8
8
  // src/box-watch.ts
9
9
  import { randomUUID } from "crypto";
@@ -0,0 +1,401 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/runner-log.ts
4
+ var RUNNER_TOOLS = [
5
+ "status",
6
+ "threads.list",
7
+ "thread.read",
8
+ "thread.launch",
9
+ "thread.send",
10
+ "thread.interrupt",
11
+ "setup.share",
12
+ "diag"
13
+ ];
14
+ var RUNNER_ERRORS = [
15
+ "expired",
16
+ "bad_args",
17
+ "no_project",
18
+ "harness_unavailable",
19
+ "harness_signed_out",
20
+ "runtime_mode_unknown",
21
+ "already_finished",
22
+ "repo_busy",
23
+ "repo_unreachable",
24
+ "cannot_steer",
25
+ "cannot_share",
26
+ "t3_unauthorized",
27
+ "t3_unreachable",
28
+ "t3_error",
29
+ "harness_error",
30
+ "unknown_tool",
31
+ "registry_unreachable",
32
+ "fetch_failed",
33
+ "npx_missing",
34
+ "handover_failed"
35
+ ];
36
+ var HARNESS_IDS = ["claude-code", "codex", "claudeAgent", "opencode"];
37
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
38
+ var VERSION = /^\d{1,4}\.\d{1,4}\.\d{1,4}$/;
39
+ var oneOf = (list) => (value) => list.includes(value) ? value : void 0;
40
+ var toolCode = oneOf(RUNNER_TOOLS);
41
+ var uuid = (value) => typeof value === "string" && UUID.test(value) ? value : void 0;
42
+ var count = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 1e12 ? value : void 0;
43
+ var version = (value) => typeof value === "string" && VERSION.test(value) ? value : void 0;
44
+ function errorCode(value) {
45
+ const code = typeof value === "string" && value.startsWith("unknown_tool:") ? "unknown_tool" : value;
46
+ return oneOf(RUNNER_ERRORS)(code);
47
+ }
48
+ function runnerLog(code, fields = {}) {
49
+ const shaped = {
50
+ call: uuid(fields.call),
51
+ work: uuid(fields.work),
52
+ tool: toolCode(fields.tool),
53
+ ms: count(fields.ms),
54
+ error: errorCode(fields.error),
55
+ n: count(fields.n),
56
+ ver: version(fields.ver)
57
+ };
58
+ const frame = { type: "log", code };
59
+ for (const [key, value] of Object.entries(shaped)) {
60
+ if (value !== void 0) Object.assign(frame, { [key]: value });
61
+ }
62
+ return frame;
63
+ }
64
+ function callOutcome(input) {
65
+ return {
66
+ at: new Date(input.at).toISOString(),
67
+ tool: toolCode(input.tool) ?? "other",
68
+ call: uuid(input.call) ?? null,
69
+ work: uuid(input.work) ?? null,
70
+ ms: count(Math.round(input.ms)) ?? 0,
71
+ ok: input.ok,
72
+ error: input.ok ? null : errorCode(input.error) ?? "other"
73
+ };
74
+ }
75
+ function outcomeLine(o) {
76
+ return `call tool=${o.tool} call=${o.call ?? "-"} work=${o.work ?? "-"} ms=${o.ms} ok=${o.ok}${o.error ? ` error=${o.error}` : ""}`;
77
+ }
78
+ var PLATFORMS = ["darwin", "linux", "win32", "freebsd", "openbsd", "aix", "sunos"];
79
+ var ARCHES = ["arm64", "x64", "arm", "ia32", "ppc64", "s390x"];
80
+ var iso = (value) => typeof value === "string" && !Number.isNaN(Date.parse(value)) && /^\d{4}-\d\d-\d\dT[\d:.]+Z$/.test(value) ? value : null;
81
+ function buildDiag(input) {
82
+ return {
83
+ version: version(input.version) ?? null,
84
+ platform: oneOf(PLATFORMS)(input.platform) ?? "other",
85
+ arch: oneOf(ARCHES)(input.arch) ?? "other",
86
+ uptime_ms: count(Math.round(input.uptimeMs)) ?? 0,
87
+ last_beat_at: iso(input.lastBeatAt),
88
+ last_wake: input.lastWake && iso(input.lastWake.woke_at) ? { slept_ms: count(input.lastWake.slept_ms) ?? 0, woke_at: input.lastWake.woke_at } : null,
89
+ harnesses: input.harnesses.map((h) => ({
90
+ id: oneOf(HARNESS_IDS)(h.id) ?? "other",
91
+ version: typeof h.version === "string" ? h.version.match(/\b\d{1,4}\.\d{1,4}\.\d{1,4}\b/)?.[0] ?? null : null,
92
+ ready: h.ready === true,
93
+ signed_in: h.signedIn === true
94
+ })),
95
+ update: {
96
+ checked_at: iso(input.update.checked_at),
97
+ latest: version(input.update.latest) ?? null,
98
+ error: errorCode(input.update.error) ?? null
99
+ },
100
+ unacked_results: count(input.unacked) ?? 0,
101
+ clock_offset_ms: typeof input.clockOffsetMs === "number" && Number.isInteger(input.clockOffsetMs) && Math.abs(input.clockOffsetMs) <= 1e12 ? input.clockOffsetMs : null,
102
+ // Already shaped: callOutcome is the only way to make one.
103
+ calls: input.calls
104
+ };
105
+ }
106
+
107
+ // src/wake.ts
108
+ var WAKE_TICK_MS = 5e3;
109
+ var SLEEP_GAP_MS = 3e4;
110
+ var PAUSE_GAP_MS = WAKE_TICK_MS;
111
+ function missedMs(last, now, tickMs = WAKE_TICK_MS) {
112
+ return Math.max(0, now - last - tickMs);
113
+ }
114
+ var systemClocks = { wall: () => Date.now(), mono: () => performance.now() };
115
+ function wakeWatch(wall = Date.now, tickMs = WAKE_TICK_MS) {
116
+ let last = wall();
117
+ return () => {
118
+ const now = wall();
119
+ const gap = missedMs(last, now, tickMs);
120
+ last = now;
121
+ return gap > SLEEP_GAP_MS ? { slept_ms: Math.round(gap), woke_at: new Date(now).toISOString() } : null;
122
+ };
123
+ }
124
+
125
+ // src/mesh-socket.ts
126
+ var WS_OPEN = 1;
127
+ function backoffDelay(attempt, { base = 1e3, max = 6e4, jitter = 0.2 } = {}, rand = Math.random) {
128
+ const raw = Math.min(base * 2 ** attempt, max);
129
+ const spread = raw * jitter;
130
+ return Math.round(raw - spread + rand() * spread * 2);
131
+ }
132
+ var CALL_GRACE_MS = 15e3;
133
+ var PING_RTT_MAX_MS = 1e4;
134
+ var PING_CLOCKS_AGREE_MS = 1e3;
135
+ var WATCHDOG_TICK_MS = WAKE_TICK_MS;
136
+ var CONNECT_TIMEOUT_MS = 2e4;
137
+ var KEEPALIVE_MS = 6e4;
138
+ var SILENCE_MS = 9e4;
139
+ var PING_GRACE_MS = 15e3;
140
+ function freshness(deadline, now, offset) {
141
+ if (deadline === void 0 || offset === null) return "fresh";
142
+ const meshNow = now + offset;
143
+ if (meshNow <= deadline) return "fresh";
144
+ return meshNow > deadline + CALL_GRACE_MS ? "expired" : "late";
145
+ }
146
+ function wsUrl(meshUrl, sessionKey, kind) {
147
+ const base = meshUrl.replace(/^http/, "ws").replace(/\/+$/, "");
148
+ const kindParam = kind && kind !== "agent" ? `&kind=${encodeURIComponent(kind)}` : "";
149
+ return `${base}/mesh/agent?session_key=${encodeURIComponent(sessionKey)}${kindParam}`;
150
+ }
151
+ var MeshSocket = class {
152
+ constructor(opts) {
153
+ this.opts = opts;
154
+ this.token = opts.token;
155
+ }
156
+ opts;
157
+ link = { state: "down" };
158
+ attempt = 0;
159
+ timer = null;
160
+ watchdog = null;
161
+ lastTick = 0;
162
+ stopped = false;
163
+ token;
164
+ /** The newest beat the caller gave, sent again each time the socket opens. */
165
+ presence = null;
166
+ offset = null;
167
+ /** A dropped link cannot report itself, so the next one to open does. */
168
+ dropped = null;
169
+ get clocks() {
170
+ return this.opts.clocks ?? systemClocks;
171
+ }
172
+ /** Connect again with a new device token, after a refusal of the old one. */
173
+ restart(token) {
174
+ this.token = token;
175
+ this.attempt = 0;
176
+ this.drop();
177
+ this.start();
178
+ }
179
+ /** Begin connecting (and keep reconnecting until close()). */
180
+ start() {
181
+ this.stopped = false;
182
+ if (!this.watchdog) {
183
+ this.lastTick = this.clocks.wall();
184
+ this.watchdog = setInterval(() => this.watch(), WATCHDOG_TICK_MS);
185
+ this.watchdog.unref?.();
186
+ }
187
+ this.connect();
188
+ }
189
+ owns(ws) {
190
+ return this.link.state !== "down" && this.link.ws === ws;
191
+ }
192
+ connect() {
193
+ if (this.stopped) return;
194
+ let ws;
195
+ try {
196
+ ws = this.opts.factory(wsUrl(this.opts.meshUrl, this.opts.sessionKey, this.opts.kind), [
197
+ "cloop.v1",
198
+ this.token
199
+ ]);
200
+ } catch {
201
+ this.scheduleReconnect();
202
+ return;
203
+ }
204
+ this.link = { state: "connecting", ws, since: this.clocks.wall() };
205
+ ws.on("open", () => {
206
+ if (!this.owns(ws)) return;
207
+ this.link = { state: "open", ws, lastInboundAt: this.clocks.wall(), ping: null };
208
+ this.attempt = 0;
209
+ if (this.presence) this.send({ type: "presence", ...this.presence });
210
+ if (this.opts.kind === "workstation") this.ping();
211
+ if (this.dropped && this.send(runnerLog(this.dropped.reason, { ms: this.dropped.ms })))
212
+ this.dropped = null;
213
+ this.opts.onOpen?.();
214
+ });
215
+ ws.on("message", (data) => {
216
+ if (!this.owns(ws) || this.link.state !== "open") return;
217
+ this.link.lastInboundAt = this.clocks.wall();
218
+ this.handleMessage(data);
219
+ });
220
+ ws.on("close", (code) => {
221
+ if (!this.owns(ws)) return;
222
+ const wasOpen = this.link.state === "open";
223
+ this.link = { state: "down" };
224
+ if (wasOpen) this.opts.onClose?.(typeof code === "number" ? code : void 0);
225
+ this.scheduleReconnect();
226
+ });
227
+ ws.on("error", (err) => {
228
+ if (this.owns(ws) && this.opts.onRefused && /Unexpected server response: 401\b/.test(String(err?.message))) {
229
+ this.stopped = true;
230
+ this.opts.onRefused();
231
+ }
232
+ });
233
+ }
234
+ watch() {
235
+ const now = this.clocks.wall();
236
+ const ran = missedMs(this.lastTick, now, WATCHDOG_TICK_MS) <= PAUSE_GAP_MS;
237
+ this.lastTick = now;
238
+ const link = this.link;
239
+ if (link.state === "connecting") {
240
+ if (!ran) link.since = now;
241
+ else if (now - link.since > CONNECT_TIMEOUT_MS)
242
+ this.abandon({ reason: "connect_hung", ms: now - link.since });
243
+ return;
244
+ }
245
+ if (link.state !== "open" || this.opts.kind !== "workstation") return;
246
+ if (!link.ping) {
247
+ if (now - link.lastInboundAt >= KEEPALIVE_MS) this.ping();
248
+ return;
249
+ }
250
+ if (!ran) link.ping.waitFrom = now;
251
+ else if (now - link.ping.waitFrom > PING_GRACE_MS && now - link.lastInboundAt > SILENCE_MS)
252
+ this.abandon({ reason: "link_silent", ms: now - link.lastInboundAt });
253
+ }
254
+ /**
255
+ * Drop the current socket. Its late events find another link in its place
256
+ * and do nothing. Only a plain close sends the mesh a closing handshake,
257
+ * which a dead link would never finish.
258
+ */
259
+ drop(plain = false) {
260
+ const link = this.link;
261
+ this.link = { state: "down" };
262
+ if (this.timer) {
263
+ clearTimeout(this.timer);
264
+ this.timer = null;
265
+ }
266
+ if (link.state !== "down") {
267
+ try {
268
+ if (link.ws.terminate && !plain) link.ws.terminate();
269
+ else link.ws.close();
270
+ } catch {
271
+ }
272
+ }
273
+ }
274
+ abandon(dropped) {
275
+ this.drop();
276
+ this.dropped = dropped;
277
+ this.opts.onClose?.(void 0, dropped);
278
+ this.scheduleReconnect();
279
+ }
280
+ handleMessage(data) {
281
+ let frame;
282
+ try {
283
+ const text = typeof data === "string" ? data : String(data);
284
+ frame = JSON.parse(text);
285
+ } catch {
286
+ return;
287
+ }
288
+ if (frame.type === "call") {
289
+ if (frame.id && frame.tool) {
290
+ this.opts.onCall?.({
291
+ type: "call",
292
+ id: frame.id,
293
+ tool: frame.tool,
294
+ args: frame.args ?? {},
295
+ ...typeof frame.deadline === "number" && Number.isFinite(frame.deadline) ? { deadline: frame.deadline } : {}
296
+ });
297
+ }
298
+ return;
299
+ }
300
+ if (frame.type === "ack") {
301
+ if (frame.of === "ping") this.measureOffset(frame.now);
302
+ else if (typeof frame.of === "string") this.opts.onAck?.(frame.of, frame.ok !== false);
303
+ return;
304
+ }
305
+ if (frame.type === "result_ack") {
306
+ if (typeof frame.id === "string") this.opts.onResultAck?.(frame.id);
307
+ return;
308
+ }
309
+ if (frame.type !== "delegate" && frame.type !== "dm") return;
310
+ this.opts.onMessage({
311
+ type: frame.type,
312
+ id: frame.id ?? "",
313
+ at: frame.at ?? (/* @__PURE__ */ new Date()).toISOString(),
314
+ ...frame.from ? { from: frame.from } : {},
315
+ ...frame.type === "delegate" ? { task: frame.task } : { body: frame.body ?? "" }
316
+ });
317
+ }
318
+ scheduleReconnect() {
319
+ if (this.stopped || this.timer) return;
320
+ const delay = backoffDelay(this.attempt, this.opts.backoff, this.opts.rand);
321
+ this.attempt++;
322
+ this.timer = setTimeout(() => {
323
+ this.timer = null;
324
+ this.connect();
325
+ }, delay);
326
+ this.timer.unref?.();
327
+ }
328
+ /**
329
+ * Send a ping and time its round trip. Only a ping this socket sent and
330
+ * timed measures the offset, never a queued call frame, whose delay is
331
+ * exactly what the offset must not absorb. One is out at a time, because
332
+ * the mesh's ack does not say which ping it answers.
333
+ */
334
+ ping() {
335
+ const link = this.link;
336
+ if (link.state !== "open" || link.ping) return;
337
+ const sent = { wall: this.clocks.wall(), mono: this.clocks.mono() };
338
+ if (this.send({ type: "ping" })) link.ping = { ...sent, waitFrom: sent.wall };
339
+ }
340
+ /** The mesh's clock minus this machine's, from the latest timed ping. Null until one answers with its clock. */
341
+ clockOffset() {
342
+ return this.offset;
343
+ }
344
+ measureOffset(meshNow) {
345
+ if (this.link.state !== "open") return;
346
+ const sent = this.link.ping;
347
+ this.link.ping = null;
348
+ if (!sent || typeof meshNow !== "number" || !Number.isFinite(meshNow)) return;
349
+ const rtt = this.clocks.mono() - sent.mono;
350
+ const wallRtt = this.clocks.wall() - sent.wall;
351
+ if (rtt < 0 || wallRtt > PING_RTT_MAX_MS || Math.abs(wallRtt - rtt) > PING_CLOCKS_AGREE_MS)
352
+ return;
353
+ this.offset = Math.round(meshNow - (sent.wall + rtt / 2));
354
+ }
355
+ isConnected() {
356
+ return this.link.state === "open" && this.link.ws.readyState === WS_OPEN;
357
+ }
358
+ /**
359
+ * Send a presence beat over the socket. Returns false if not connected;
360
+ * the socket still keeps the beat and sends it when it opens.
361
+ */
362
+ sendPresence(body) {
363
+ this.presence = body;
364
+ return this.send({ type: "presence", ...body });
365
+ }
366
+ /** Send any client frame. Returns false if not connected. */
367
+ send(frame) {
368
+ const link = this.link;
369
+ if (link.state !== "open" || link.ws.readyState !== WS_OPEN) return false;
370
+ try {
371
+ link.ws.send(JSON.stringify(frame));
372
+ return true;
373
+ } catch {
374
+ return false;
375
+ }
376
+ }
377
+ close() {
378
+ this.stopped = true;
379
+ if (this.watchdog) {
380
+ clearInterval(this.watchdog);
381
+ this.watchdog = null;
382
+ }
383
+ this.drop(true);
384
+ }
385
+ };
386
+ async function defaultSocketFactory() {
387
+ const { WebSocket } = await import("ws");
388
+ return (url, protocols) => new WebSocket(url, protocols);
389
+ }
390
+
391
+ export {
392
+ runnerLog,
393
+ callOutcome,
394
+ outcomeLine,
395
+ buildDiag,
396
+ WAKE_TICK_MS,
397
+ wakeWatch,
398
+ freshness,
399
+ MeshSocket,
400
+ defaultSocketFactory
401
+ };
@@ -2,17 +2,17 @@
2
2
  import {
3
3
  findRun,
4
4
  ownHarness
5
- } from "./chunk-65KJPIZC.js";
5
+ } from "./chunk-HGKTPD5Z.js";
6
6
  import {
7
7
  lockThreadsFile,
8
8
  threadsFilePath
9
- } from "./chunk-GURADB5L.js";
9
+ } from "./chunk-3YJD6J2N.js";
10
10
  import {
11
11
  localRunsFilePath,
12
12
  readRunRecords,
13
13
  runHarness,
14
14
  takeoverSummary
15
- } from "./chunk-AIOOLVM7.js";
15
+ } from "./chunk-EOWS3JIY.js";
16
16
  import {
17
17
  shortMachineName
18
18
  } from "./chunk-NTXQLEMQ.js";