@cloop/runner 0.3.29 → 0.3.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/README.md +7 -0
  2. package/dist/{box-6TJMXQXM.js → box-RFAHCXZS.js} +239 -69
  3. package/dist/chunk-52CUSFDQ.js +401 -0
  4. package/dist/{chunk-P56EL4D4.js → chunk-7AHYPGSU.js} +2 -2
  5. package/dist/{chunk-65KJPIZC.js → chunk-FKYVJUIR.js} +1 -1
  6. package/dist/{chunk-4FXRG3Q3.js → chunk-GL77IQQE.js} +1 -1
  7. package/dist/{chunk-SVHQXVCH.js → chunk-MEAVT5SJ.js} +986 -205
  8. package/dist/{chunk-AIOOLVM7.js → chunk-R73PVAM2.js} +182 -88
  9. package/dist/{chunk-NTXQLEMQ.js → chunk-SBYSVZ7J.js} +94 -2
  10. package/dist/{chunk-PSA5EC65.js → chunk-UERK5AHI.js} +6 -6
  11. package/dist/{chunk-TWDKR7XV.js → chunk-WYU74GLG.js} +5 -5
  12. package/dist/{chunk-GURADB5L.js → chunk-YLVOEZWH.js} +1 -1
  13. package/dist/{connect-HVUNZ6A2.js → connect-WRTLQW5H.js} +10 -9
  14. package/dist/{disconnect-NXVDABS5.js → disconnect-I44BWWFB.js} +8 -9
  15. package/dist/existing-runner-SP6SNFH4.js +20 -0
  16. package/dist/{hook-activity-GAJ5NABA.js → hook-activity-3T6IMEM6.js} +2 -3
  17. package/dist/{hook-session-start-5JYNMGX4.js → hook-session-start-DLP77G4H.js} +5 -7
  18. package/dist/index.js +20 -17
  19. package/dist/{login-PH2RZNOE.js → login-LH2KF7N2.js} +3 -3
  20. package/dist/{mcp-server-U2H4U4BZ.js → mcp-server-SGIWNLLL.js} +9 -11
  21. package/dist/{runner-YTGTJPPR.js → runner-SXUQH5IU.js} +4 -4
  22. package/dist/{runs-D7XT2PYS.js → runs-3YZO57MX.js} +2 -2
  23. package/dist/{statusline-U4K2IQIT.js → statusline-UHZTCNCB.js} +1 -1
  24. package/dist/{takeover-M2SDWTVK.js → takeover-M4QHMXTZ.js} +5 -6
  25. package/dist/{use-7OUFEREN.js → use-YB75NHTE.js} +8 -9
  26. package/package.json +1 -1
  27. package/dist/chunk-ES5BRAKJ.js +0 -88
  28. package/dist/chunk-KYGYU5G2.js +0 -220
  29. package/dist/existing-runner-7E6RUUJH.js +0 -21
@@ -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,12 +2,12 @@
2
2
  import {
3
3
  ConnectFailure,
4
4
  deviceLogin
5
- } from "./chunk-TWDKR7XV.js";
5
+ } from "./chunk-WYU74GLG.js";
6
6
  import {
7
7
  ApiError,
8
8
  ReauthError,
9
9
  api
10
- } from "./chunk-ES5BRAKJ.js";
10
+ } from "./chunk-SBYSVZ7J.js";
11
11
  import {
12
12
  CONFIG_DIR,
13
13
  getOrigin,
@@ -9,7 +9,7 @@ import {
9
9
  runHarness,
10
10
  runLogDir,
11
11
  runLogPath
12
- } from "./chunk-AIOOLVM7.js";
12
+ } from "./chunk-R73PVAM2.js";
13
13
  import {
14
14
  sanitizeLabel,
15
15
  stripControl
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/version.ts
4
- var VERSION = true ? "0.3.29" : "0.0.0-dev";
4
+ var VERSION = true ? "0.3.31" : "0.0.0-dev";
5
5
 
6
6
  export {
7
7
  VERSION