@cloop/runner 0.2.5 → 0.2.6

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.
@@ -1,42 +1,48 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ serveTakeovers
4
+ } from "./chunk-V4IYJUCC.js";
5
+ import "./chunk-UEV7ARIT.js";
2
6
  import {
3
7
  LocalDriver
4
- } from "./chunk-KOOAVO2C.js";
8
+ } from "./chunk-E3V2PRVS.js";
5
9
  import {
6
10
  MeshSocket,
7
11
  defaultSocketFactory
8
12
  } from "./chunk-ZILLDYL4.js";
9
13
  import "./chunk-VK6GV757.js";
10
14
  import {
11
- BoxWatch,
12
15
  DEFAULT_FALLBACK_MODEL,
13
16
  T3Client,
14
17
  claudeDialect,
15
18
  codexDialect,
16
19
  connectCommand,
17
- lockThreadsFile,
18
20
  mintSession,
19
21
  probeClaude,
20
22
  probeClaudePermissions,
21
23
  probeCodex,
22
- runBoxTool,
24
+ runBoxTool
25
+ } from "./chunk-SXV4JF5H.js";
26
+ import {
27
+ BoxWatch,
28
+ lockThreadsFile,
23
29
  threadsFilePath,
24
30
  writeRunnerState
25
- } from "./chunk-2FLM3ESE.js";
31
+ } from "./chunk-MWWA2VH7.js";
26
32
  import {
27
33
  T3Driver,
28
34
  isLocal,
29
35
  readRunnerConfig,
30
36
  writeBoxConfig
31
- } from "./chunk-G6JAEE2Y.js";
37
+ } from "./chunk-H7ZCXBNW.js";
32
38
  import {
33
39
  getMachine
34
40
  } from "./chunk-JX6VG5FE.js";
35
41
  import "./chunk-R3CLO2FB.js";
36
- import "./chunk-53M5DK6D.js";
37
- import "./chunk-4XDYJZLF.js";
42
+ import "./chunk-52VJGOLJ.js";
43
+ import "./chunk-2SZUL2B6.js";
38
44
  import "./chunk-AG6SI6I2.js";
39
- import "./chunk-BFVL3E2C.js";
45
+ import "./chunk-GTE4QSTR.js";
40
46
  import {
41
47
  getMeshUrl,
42
48
  getToken,
@@ -275,6 +281,7 @@ async function run() {
275
281
  );
276
282
  watch.start();
277
283
  setInterval(() => watch.flush(), RESEND_MS).unref();
284
+ if (driver instanceof LocalDriver) serveTakeovers(driver, log);
278
285
  const renewT3 = async () => {
279
286
  if (!cfg || isLocal(cfg) || Date.parse(cfg.expiresAt) - Date.now() >= REPAIR_BEFORE_MS) return;
280
287
  try {
@@ -284,6 +291,7 @@ async function run() {
284
291
  // Read from disk: `cloop connect` may have replaced it since.
285
292
  deviceToken: disk?.deviceToken ?? cfg.deviceToken,
286
293
  showOtherThreads: disk?.showOtherThreads ?? false,
294
+ ...disk?.chosenDriver ? { chosenDriver: disk.chosenDriver } : {},
287
295
  ...disk?.origin ?? cfg.origin ? { origin: disk?.origin ?? cfg.origin } : {}
288
296
  };
289
297
  cfg = renewed;
@@ -5,7 +5,7 @@ import {
5
5
  } from "./chunk-AG6SI6I2.js";
6
6
  import {
7
7
  VERSION
8
- } from "./chunk-BFVL3E2C.js";
8
+ } from "./chunk-GTE4QSTR.js";
9
9
  import {
10
10
  getOrigin,
11
11
  readCredentials,
@@ -2,7 +2,7 @@
2
2
  import {
3
3
  ConnectFailure,
4
4
  deviceLogin
5
- } from "./chunk-4XDYJZLF.js";
5
+ } from "./chunk-2SZUL2B6.js";
6
6
  import {
7
7
  ApiError,
8
8
  ReauthError,
@@ -7,7 +7,7 @@ import {
7
7
  RESULT_INSTRUCTION,
8
8
  orderThreads,
9
9
  parseRunResult
10
- } from "./chunk-G6JAEE2Y.js";
10
+ } from "./chunk-H7ZCXBNW.js";
11
11
  import {
12
12
  CONFIG_DIR
13
13
  } from "./chunk-3DIGCVL4.js";
@@ -137,6 +137,10 @@ import { chmodSync as chmodSync2, mkdirSync as mkdirSync2, readFileSync, renameS
137
137
  import { homedir, hostname } from "os";
138
138
  import { basename, dirname as dirname2, join as join2 } from "path";
139
139
  import { createInterface } from "readline";
140
+ var STOPPED = { kind: "failed", summary: STOPPED_SUMMARY };
141
+ function takeoverSummary(machine) {
142
+ return `You took this over on ${machine}.`;
143
+ }
140
144
  var CONTINUE_PROMPT = "Continue the work from where you stopped. If it is already done, say so in one sentence.";
141
145
  var PR_URL = /https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/pull\/\d+/g;
142
146
  var SHARED_BRANCHES = /* @__PURE__ */ new Set(["staging", "main", "master", "HEAD"]);
@@ -325,7 +329,8 @@ var LocalDriver = class {
325
329
  return {
326
330
  thread_id: a.work_id,
327
331
  resumed: true,
328
- permission: existing.used_permission
332
+ permission: existing.used_permission,
333
+ takeover: true
329
334
  };
330
335
  const { dialect } = this.deps;
331
336
  if (a.harness && !dialect.aliases.includes(a.harness))
@@ -338,7 +343,12 @@ var LocalDriver = class {
338
343
  const head = await this.repo.head(repo.path);
339
344
  const concurrent = this.runs.get(a.work_id);
340
345
  if (concurrent)
341
- return { thread_id: a.work_id, resumed: true, permission: concurrent.used_permission };
346
+ return {
347
+ thread_id: a.work_id,
348
+ resumed: true,
349
+ permission: concurrent.used_permission,
350
+ takeover: true
351
+ };
342
352
  this.refuseBusy(repo.path);
343
353
  const record = {
344
354
  work_id: a.work_id,
@@ -353,7 +363,12 @@ var LocalDriver = class {
353
363
  };
354
364
  this.runs.set(a.work_id, record);
355
365
  this.spawnRun(record, a.prompt, false);
356
- return { thread_id: a.work_id, resumed: false, permission: record.used_permission };
366
+ return {
367
+ thread_id: a.work_id,
368
+ resumed: false,
369
+ permission: record.used_permission,
370
+ takeover: true
371
+ };
357
372
  }
358
373
  async send(a) {
359
374
  const r = this.record(a.thread_id);
@@ -415,7 +430,7 @@ ${a.text}` : a.text;
415
430
  this.log(`${delivered} work=${r.work_id}`);
416
431
  return { delivered };
417
432
  }
418
- async interrupt(id) {
433
+ async interrupt(id, _commandId, stop = STOPPED) {
419
434
  const r = this.record(id);
420
435
  const live = this.lives.get(r.work_id);
421
436
  if (!live) {
@@ -427,20 +442,32 @@ ${a.text}` : a.text;
427
442
  } catch {
428
443
  }
429
444
  }
430
- await this.end(r, { kind: "failed", summary: STOPPED_SUMMARY });
445
+ await this.end(r, stop);
431
446
  return { ok: true, was_running: orphan };
432
447
  }
433
- live.interrupted = true;
448
+ live.interrupted = stop;
434
449
  live.child.kill("SIGINT");
435
- this.note(r, "= Stop requested.");
450
+ this.note(r, stop === STOPPED ? "= Stop requested." : `= ${stop.summary}`);
436
451
  const timer = setTimeout(() => {
437
452
  if (live.child.exitCode === null && live.child.signalCode === null)
438
453
  live.child.kill("SIGTERM");
439
454
  }, this.deps.interruptGraceMs ?? 1e4);
440
455
  timer.unref();
441
- this.log(`interrupt work=${r.work_id}`);
456
+ this.log(`interrupt work=${r.work_id}${stop.error ? ` reason=${stop.error}` : ""}`);
442
457
  return { ok: true, was_running: true };
443
458
  }
459
+ /**
460
+ * `cloop takeover`: stop the run so the owner can open its session in
461
+ * their own terminal. It ends as a stop, with the machine in its words, and
462
+ * never resumes by itself: two processes on one session would fight.
463
+ */
464
+ takeOver(id, machine) {
465
+ return this.interrupt(id, void 0, {
466
+ kind: "failed",
467
+ summary: takeoverSummary(machine),
468
+ error: "taken_over"
469
+ });
470
+ }
444
471
  watch(id, onEvent) {
445
472
  const set = this.listeners.get(id) ?? /* @__PURE__ */ new Set();
446
473
  set.add(onEvent);
@@ -510,7 +537,7 @@ ${a.text}` : a.text;
510
537
  outstanding: 1,
511
538
  asks: [],
512
539
  lastProgressAt: 0,
513
- interrupted: false,
540
+ interrupted: null,
514
541
  stderr: ""
515
542
  };
516
543
  this.lives.set(r.work_id, live);
@@ -592,7 +619,7 @@ ${RESULT_INSTRUCTION}`));
592
619
  `exit work=${r.work_id} ${exit} result=${live.result ? live.result.ok ? "ok" : "error" : "none"}`
593
620
  );
594
621
  if (live.interrupted) {
595
- await this.end(r, { kind: "failed", summary: STOPPED_SUMMARY });
622
+ await this.end(r, live.interrupted);
596
623
  return;
597
624
  }
598
625
  if (live.next) {
@@ -730,6 +757,7 @@ export {
730
757
  runLogPath,
731
758
  STOPPED_SUMMARY,
732
759
  isEndLogLine,
760
+ takeoverSummary,
733
761
  localRunsFilePath,
734
762
  LocalDriver,
735
763
  readRunRecords
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/version.ts
4
- var VERSION = true ? "0.2.5" : "0.0.0-dev";
4
+ var VERSION = true ? "0.2.6" : "0.0.0-dev";
5
5
 
6
6
  export {
7
7
  VERSION
@@ -270,8 +270,10 @@ function outcomeOf(p) {
270
270
  };
271
271
  }
272
272
  function pickProject(projects, repository) {
273
- const only = projects.length === 1 ? projects[0] : void 0;
274
273
  if (!repository) {
274
+ const repos = projects.filter((p) => p.repositoryIdentity);
275
+ const pool = repos.length > 0 ? repos : projects;
276
+ const only = pool.length === 1 ? pool[0] : void 0;
275
277
  if (only) return only;
276
278
  throw new BoxToolError("no_project");
277
279
  }
@@ -306,6 +308,45 @@ function orderThreads(threads, limit) {
306
308
  return [...running, ...rest].slice(0, limit);
307
309
  }
308
310
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
311
+ function t3ThreadUrl(base, environmentId, threadId) {
312
+ return `${base.replace(/\/+$/, "")}/${encodeURIComponent(environmentId)}/${encodeURIComponent(threadId)}`;
313
+ }
314
+ var LOOPBACK_HOST = /^(127\.0\.0\.1|localhost|\[::1\])$/;
315
+ function isLoopback(url) {
316
+ try {
317
+ return LOOPBACK_HOST.test(new URL(url).hostname);
318
+ } catch {
319
+ return false;
320
+ }
321
+ }
322
+ function tailscaleServed(statusJson, t3Url) {
323
+ let web;
324
+ let port;
325
+ try {
326
+ web = JSON.parse(statusJson).Web ?? {};
327
+ port = new URL(t3Url).port || "80";
328
+ } catch {
329
+ return null;
330
+ }
331
+ for (const [hostPort, served] of Object.entries(web)) {
332
+ const proxy = served?.Handlers?.["/"]?.Proxy;
333
+ if (!proxy) continue;
334
+ let target;
335
+ try {
336
+ target = new URL(proxy);
337
+ } catch {
338
+ continue;
339
+ }
340
+ if (!LOOPBACK_HOST.test(target.hostname) || (target.port || "80") !== port) continue;
341
+ return hostPort.endsWith(":443") ? `https://${hostPort.slice(0, -4)}` : `https://${hostPort}`;
342
+ }
343
+ return null;
344
+ }
345
+ function reachableBase(t3Url, direct, served) {
346
+ if (!isLoopback(t3Url)) return t3Url;
347
+ const endpoint = direct?.find((e) => e.kind === "tailnet") ?? direct?.find((e) => e.kind === "lan");
348
+ return endpoint?.httpBaseUrl ?? served;
349
+ }
309
350
  var T3Driver = class {
310
351
  constructor(deps) {
311
352
  this.deps = deps;
@@ -529,10 +570,49 @@ ${RESULT_INSTRUCTION}`, attachments: [] }
529
570
  return { ok: true, was_running: true };
530
571
  }
531
572
  async readThread(id) {
532
- const { status, settled, pr_url, last_assistant_text } = outcomeOf(
533
- await this.readProjection(id)
534
- );
535
- return { status, settled, pr_url, last_assistant_text };
573
+ const projection = await this.readProjection(id);
574
+ const { status, settled, pr_url, last_assistant_text } = outcomeOf(projection);
575
+ const open = await this.openTarget(id, projection).catch(() => null);
576
+ return { status, settled, pr_url, last_assistant_text, open };
577
+ }
578
+ /** Where the owner opens this thread: the T3 web app's page for it, or its title and project. */
579
+ async openTarget(id, p) {
580
+ const [cfg, shell] = await this.readT3State();
581
+ const listed = shell.threads?.find((t) => t.id === id);
582
+ const title = p.thread.title ?? listed?.title;
583
+ if (!title) return null;
584
+ const base = this.t3.t3Url;
585
+ const projectId = p.thread.projectId;
586
+ const project = shell.projects?.find((x) => x.id === projectId)?.title ?? null;
587
+ const web = base ? reachableBase(base, cfg.directEndpoints, this.servedBase(base)) : null;
588
+ return {
589
+ url: web ? t3ThreadUrl(web, cfg.environment.environmentId, id) : null,
590
+ base,
591
+ title,
592
+ project
593
+ };
594
+ }
595
+ served = null;
596
+ /** `tailscale serve` changes rarely, and the CLI takes a moment, so its answer is kept 5 minutes. */
597
+ servedBase(t3Url) {
598
+ const kept = this.served;
599
+ if (kept && kept.base === t3Url && Date.now() - kept.at < SESSIONS_TTL_MS) return kept.value;
600
+ let value = null;
601
+ try {
602
+ value = tailscaleServed(
603
+ String(
604
+ (this.deps.exec ?? execFileSync2)("tailscale", ["serve", "status", "--json"], {
605
+ encoding: "utf-8",
606
+ stdio: ["ignore", "pipe", "ignore"],
607
+ timeout: 3e3
608
+ })
609
+ ),
610
+ t3Url
611
+ );
612
+ } catch {
613
+ }
614
+ this.served = { base: t3Url, value, at: Date.now() };
615
+ return value;
536
616
  }
537
617
  /**
538
618
  * Subscribe to the thread and resubscribe whenever the stream ends. A thread
@@ -0,0 +1,224 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ CONFIG_DIR
4
+ } from "./chunk-3DIGCVL4.js";
5
+
6
+ // src/box-watch.ts
7
+ import { randomUUID } from "crypto";
8
+ import { chmodSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "fs";
9
+ import { homedir } from "os";
10
+ import { dirname, join } from "path";
11
+ var KEEP_MS = 7 * 24 * 36e5;
12
+ function threadsFilePath() {
13
+ return process.env.CLOOP_BOX_THREADS_FILE ?? join(homedir(), CONFIG_DIR, "box-threads.json");
14
+ }
15
+ function runnerStatePath() {
16
+ return join(dirname(threadsFilePath()), "runner-state.json");
17
+ }
18
+ function writeRunnerState(state, path = runnerStatePath()) {
19
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
20
+ const tmp = `${path}.tmp`;
21
+ writeFileSync(tmp, `${JSON.stringify(state)}
22
+ `, { mode: 384 });
23
+ renameSync(tmp, path);
24
+ }
25
+ function readRunnerState(path = runnerStatePath()) {
26
+ try {
27
+ const raw = JSON.parse(readFileSync(path, "utf-8"));
28
+ return typeof raw.pid === "number" && typeof raw.connected_at === "string" ? { pid: raw.pid, connected_at: raw.connected_at } : null;
29
+ } catch {
30
+ return null;
31
+ }
32
+ }
33
+ function isAlive(pid) {
34
+ try {
35
+ process.kill(pid, 0);
36
+ return true;
37
+ } catch (err) {
38
+ return err.code === "EPERM";
39
+ }
40
+ }
41
+ function lockThreadsFile(file, pid = process.pid, alive = isAlive) {
42
+ const lock = `${file}.lock`;
43
+ mkdirSync(dirname(lock), { recursive: true, mode: 448 });
44
+ for (let attempt = 0; attempt < 2; attempt++) {
45
+ try {
46
+ writeFileSync(lock, String(pid), { flag: "wx", mode: 384 });
47
+ return {
48
+ ok: true,
49
+ release: () => {
50
+ try {
51
+ if (readFileSync(lock, "utf-8") === String(pid)) unlinkSync(lock);
52
+ } catch {
53
+ }
54
+ }
55
+ };
56
+ } catch (err) {
57
+ if (err.code !== "EEXIST") throw err;
58
+ let held = 0;
59
+ try {
60
+ held = Number(readFileSync(lock, "utf-8").trim());
61
+ } catch (readErr) {
62
+ if (readErr.code !== "ENOENT") throw readErr;
63
+ continue;
64
+ }
65
+ if (Number.isInteger(held) && held > 0 && held !== pid && alive(held)) {
66
+ return { ok: false, heldBy: held };
67
+ }
68
+ try {
69
+ unlinkSync(lock);
70
+ } catch (unlinkErr) {
71
+ if (unlinkErr.code !== "ENOENT") throw unlinkErr;
72
+ }
73
+ }
74
+ }
75
+ return { ok: false, heldBy: -1 };
76
+ }
77
+ var BoxWatch = class {
78
+ constructor(deps) {
79
+ this.deps = deps;
80
+ this.entries = this.load();
81
+ }
82
+ deps;
83
+ entries;
84
+ live = /* @__PURE__ */ new Map();
85
+ stopped = false;
86
+ list() {
87
+ return this.entries;
88
+ }
89
+ start() {
90
+ for (const e of this.entries) if (!e.settled_at) this.watch(e);
91
+ }
92
+ add(workId, threadId) {
93
+ if (this.entries.some((e) => e.work_id === workId)) return;
94
+ const entry = {
95
+ work_id: workId,
96
+ thread_id: threadId,
97
+ launched_at: new Date(this.now()).toISOString()
98
+ };
99
+ this.entries.push(entry);
100
+ this.save();
101
+ this.deps.log(`launch work=${workId} thread=${threadId}`);
102
+ this.watch(entry);
103
+ }
104
+ resume(threadId) {
105
+ const entry = this.entries.find((e) => e.thread_id === threadId);
106
+ if (!entry?.settled_at) return;
107
+ entry.settled_at = void 0;
108
+ entry.event = void 0;
109
+ entry.sent_at = void 0;
110
+ this.save();
111
+ this.watch(entry);
112
+ }
113
+ /** On every socket open and on a timer: send every event the mesh has not acked. */
114
+ flush() {
115
+ for (const e of this.entries) {
116
+ for (const q of e.questions ?? []) if (!q.sent_at) this.trySend(e, q.event);
117
+ if (e.event && !e.sent_at) this.trySend(e, e.event);
118
+ }
119
+ }
120
+ /** `ok` false: the app refused the event for good (unknown work_id, bad frame), so it is not sent again either. */
121
+ ack(eventId, ok = true) {
122
+ for (const e of this.entries) {
123
+ const held = [...e.questions ?? [], e].find((x) => x.event?.id === eventId && !x.sent_at);
124
+ if (!held) continue;
125
+ held.sent_at = new Date(this.now()).toISOString();
126
+ this.save();
127
+ this.deps.log(
128
+ `event ${ok ? "acked" : "refused by the app"} work=${e.work_id} kind=${held.event?.kind}`
129
+ );
130
+ return;
131
+ }
132
+ }
133
+ stop() {
134
+ this.stopped = true;
135
+ for (const unwatch of this.live.values()) unwatch();
136
+ this.live.clear();
137
+ }
138
+ now() {
139
+ return this.deps.now?.() ?? Date.now();
140
+ }
141
+ watch(e) {
142
+ if (this.stopped || e.settled_at || this.live.has(e.work_id)) return;
143
+ const unwatch = this.deps.watch(e.thread_id, (event) => this.onEvent(e, event));
144
+ if (e.settled_at) unwatch();
145
+ else this.live.set(e.work_id, unwatch);
146
+ }
147
+ onEvent(e, event) {
148
+ if (e.settled_at) return;
149
+ if (event.kind === "question") this.ask(e, event.question_id, event.summary);
150
+ else if (event.kind === "progress") this.trySend(e, this.frame(e, event));
151
+ else this.finish(e, event);
152
+ }
153
+ frame(e, event) {
154
+ const { kind, summary } = event;
155
+ return {
156
+ type: "event",
157
+ id: randomUUID(),
158
+ work_id: e.work_id,
159
+ thread_id: e.thread_id,
160
+ kind,
161
+ ...event.kind === "question" ? { question_id: event.question_id } : {},
162
+ ...summary ? { summary: summary.slice(0, 500) } : {},
163
+ ..."result" in event && event.result ? { result: event.result } : {},
164
+ ..."pr_url" in event && event.pr_url ? { pr_url: event.pr_url } : {},
165
+ ..."error" in event && event.error ? { error: event.error } : {},
166
+ at: new Date(this.now()).toISOString()
167
+ };
168
+ }
169
+ ask(e, questionId, summary) {
170
+ if (e.questions?.some((x) => x.event.question_id === questionId)) return;
171
+ const event = this.frame(e, { kind: "question", question_id: questionId, summary });
172
+ e.questions = [...e.questions ?? [], { event }];
173
+ this.save();
174
+ this.deps.log(`question work=${e.work_id} thread=${e.thread_id}`);
175
+ this.trySend(e, event);
176
+ }
177
+ finish(e, end) {
178
+ this.live.get(e.work_id)?.();
179
+ this.live.delete(e.work_id);
180
+ e.event = this.frame(e, end);
181
+ e.settled_at = e.event.at;
182
+ this.save();
183
+ this.deps.log(
184
+ `settle work=${e.work_id} thread=${e.thread_id} kind=${end.kind} pr=${end.pr_url ? "yes" : "no"}`
185
+ );
186
+ this.trySend(e, e.event);
187
+ }
188
+ trySend(e, event) {
189
+ const sent = this.deps.send(event);
190
+ this.deps.log(
191
+ `event ${sent ? "sent" : "held"} work=${e.work_id} kind=${event.kind}${sent ? "" : "; socket down"}`
192
+ );
193
+ }
194
+ load() {
195
+ let raw;
196
+ try {
197
+ raw = JSON.parse(readFileSync(this.deps.file, "utf-8"));
198
+ } catch {
199
+ return [];
200
+ }
201
+ if (!Array.isArray(raw)) return [];
202
+ const cutoff = this.now() - KEEP_MS;
203
+ return raw.filter(
204
+ (e) => typeof e?.work_id === "string" && typeof e?.thread_id === "string" && !(e.settled_at && Date.parse(e.settled_at) < cutoff)
205
+ );
206
+ }
207
+ save() {
208
+ mkdirSync(dirname(this.deps.file), { recursive: true, mode: 448 });
209
+ const tmp = `${this.deps.file}.tmp`;
210
+ writeFileSync(tmp, `${JSON.stringify(this.entries, null, 2)}
211
+ `, { mode: 384 });
212
+ chmodSync(tmp, 384);
213
+ renameSync(tmp, this.deps.file);
214
+ }
215
+ };
216
+
217
+ export {
218
+ threadsFilePath,
219
+ runnerStatePath,
220
+ writeRunnerState,
221
+ readRunnerState,
222
+ lockThreadsFile,
223
+ BoxWatch
224
+ };