@cloop/runner 0.2.5 → 0.2.7

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,4 +1,7 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ readRunnerState
4
+ } from "./chunk-MWWA2VH7.js";
2
5
  import {
3
6
  BoxToolError,
4
7
  CLOOP_THREAD_PREFIX,
@@ -6,6 +9,7 @@ import {
6
9
  T3Driver,
7
10
  defaultT3BinSources,
8
11
  isLocal,
12
+ isYes,
9
13
  pickT3Bin,
10
14
  questionLine,
11
15
  readRunnerConfig,
@@ -13,7 +17,7 @@ import {
13
17
  t3BaseDirArgs,
14
18
  t3Candidates,
15
19
  writeBoxConfig
16
- } from "./chunk-G6JAEE2Y.js";
20
+ } from "./chunk-LNQLGVYC.js";
17
21
  import {
18
22
  getMachine,
19
23
  shortMachineName
@@ -24,29 +28,28 @@ import {
24
28
  } from "./chunk-R3CLO2FB.js";
25
29
  import {
26
30
  connectWebhook
27
- } from "./chunk-53M5DK6D.js";
31
+ } from "./chunk-JZNBZUPZ.js";
28
32
  import {
29
33
  ConnectFailure,
30
34
  connectReport,
31
35
  deviceLogin,
32
36
  newAttempt,
33
37
  sendConnectReport
34
- } from "./chunk-4XDYJZLF.js";
38
+ } from "./chunk-SANEFNTU.js";
35
39
  import {
36
40
  VERSION
37
- } from "./chunk-BFVL3E2C.js";
41
+ } from "./chunk-KH6FK6UQ.js";
38
42
  import {
39
- CONFIG_DIR,
40
43
  STAGING_ORIGIN,
41
44
  getOrigin
42
45
  } from "./chunk-3DIGCVL4.js";
43
46
 
44
47
  // src/commands/connect.ts
45
48
  import { execFileSync } from "child_process";
46
- import { randomUUID as randomUUID2 } from "crypto";
47
- import { existsSync, mkdirSync as mkdirSync2, readdirSync, rmSync, writeFileSync as writeFileSync2 } from "fs";
48
- import { homedir as homedir2 } from "os";
49
- import { basename as basename3, dirname as dirname2, join as join2, resolve as resolve2 } from "path";
49
+ import { randomUUID } from "crypto";
50
+ import { existsSync, mkdirSync, readdirSync, rmSync, writeFileSync } from "fs";
51
+ import { homedir, userInfo } from "os";
52
+ import { basename as basename3, dirname, join, resolve as resolve2 } from "path";
50
53
  import { createInterface } from "readline/promises";
51
54
  import { Writable } from "stream";
52
55
 
@@ -270,7 +273,11 @@ function parseSendArgs(args) {
270
273
  };
271
274
  }
272
275
  var BOX_TOOLS = {
273
- status: ({ driver }) => driver.status(),
276
+ // The runner version tells the app which keys this machine answers: `cloop use` arrived in 0.2.6.
277
+ status: async ({ driver }) => {
278
+ const report = await driver.status();
279
+ return { ...report, box: { ...report.box, version: VERSION } };
280
+ },
274
281
  "threads.list": ({ driver }, args) => driver.listThreads({
275
282
  scope: args.scope === "all" ? "all" : "unsettled",
276
283
  limit: typeof args.limit === "number" ? Math.min(Math.max(1, args.limit), 50) : 10
@@ -315,217 +322,6 @@ async function runBoxTool(ctx, tool, args) {
315
322
  }
316
323
  }
317
324
 
318
- // src/box-watch.ts
319
- import { randomUUID } from "crypto";
320
- import { chmodSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "fs";
321
- import { homedir } from "os";
322
- import { dirname, join } from "path";
323
- var KEEP_MS = 7 * 24 * 36e5;
324
- function threadsFilePath() {
325
- return process.env.CLOOP_BOX_THREADS_FILE ?? join(homedir(), CONFIG_DIR, "box-threads.json");
326
- }
327
- function runnerStatePath() {
328
- return join(dirname(threadsFilePath()), "runner-state.json");
329
- }
330
- function writeRunnerState(state, path = runnerStatePath()) {
331
- mkdirSync(dirname(path), { recursive: true, mode: 448 });
332
- const tmp = `${path}.tmp`;
333
- writeFileSync(tmp, `${JSON.stringify(state)}
334
- `, { mode: 384 });
335
- renameSync(tmp, path);
336
- }
337
- function readRunnerState(path = runnerStatePath()) {
338
- try {
339
- const raw = JSON.parse(readFileSync(path, "utf-8"));
340
- return typeof raw.pid === "number" && typeof raw.connected_at === "string" ? { pid: raw.pid, connected_at: raw.connected_at } : null;
341
- } catch {
342
- return null;
343
- }
344
- }
345
- function isAlive(pid) {
346
- try {
347
- process.kill(pid, 0);
348
- return true;
349
- } catch (err) {
350
- return err.code === "EPERM";
351
- }
352
- }
353
- function lockThreadsFile(file, pid = process.pid, alive = isAlive) {
354
- const lock = `${file}.lock`;
355
- mkdirSync(dirname(lock), { recursive: true, mode: 448 });
356
- for (let attempt = 0; attempt < 2; attempt++) {
357
- try {
358
- writeFileSync(lock, String(pid), { flag: "wx", mode: 384 });
359
- return {
360
- ok: true,
361
- release: () => {
362
- try {
363
- if (readFileSync(lock, "utf-8") === String(pid)) unlinkSync(lock);
364
- } catch {
365
- }
366
- }
367
- };
368
- } catch (err) {
369
- if (err.code !== "EEXIST") throw err;
370
- let held = 0;
371
- try {
372
- held = Number(readFileSync(lock, "utf-8").trim());
373
- } catch (readErr) {
374
- if (readErr.code !== "ENOENT") throw readErr;
375
- continue;
376
- }
377
- if (Number.isInteger(held) && held > 0 && held !== pid && alive(held)) {
378
- return { ok: false, heldBy: held };
379
- }
380
- try {
381
- unlinkSync(lock);
382
- } catch (unlinkErr) {
383
- if (unlinkErr.code !== "ENOENT") throw unlinkErr;
384
- }
385
- }
386
- }
387
- return { ok: false, heldBy: -1 };
388
- }
389
- var BoxWatch = class {
390
- constructor(deps) {
391
- this.deps = deps;
392
- this.entries = this.load();
393
- }
394
- deps;
395
- entries;
396
- live = /* @__PURE__ */ new Map();
397
- stopped = false;
398
- list() {
399
- return this.entries;
400
- }
401
- start() {
402
- for (const e of this.entries) if (!e.settled_at) this.watch(e);
403
- }
404
- add(workId, threadId) {
405
- if (this.entries.some((e) => e.work_id === workId)) return;
406
- const entry = {
407
- work_id: workId,
408
- thread_id: threadId,
409
- launched_at: new Date(this.now()).toISOString()
410
- };
411
- this.entries.push(entry);
412
- this.save();
413
- this.deps.log(`launch work=${workId} thread=${threadId}`);
414
- this.watch(entry);
415
- }
416
- resume(threadId) {
417
- const entry = this.entries.find((e) => e.thread_id === threadId);
418
- if (!entry?.settled_at) return;
419
- entry.settled_at = void 0;
420
- entry.event = void 0;
421
- entry.sent_at = void 0;
422
- this.save();
423
- this.watch(entry);
424
- }
425
- /** On every socket open and on a timer: send every event the mesh has not acked. */
426
- flush() {
427
- for (const e of this.entries) {
428
- for (const q of e.questions ?? []) if (!q.sent_at) this.trySend(e, q.event);
429
- if (e.event && !e.sent_at) this.trySend(e, e.event);
430
- }
431
- }
432
- /** `ok` false: the app refused the event for good (unknown work_id, bad frame), so it is not sent again either. */
433
- ack(eventId, ok = true) {
434
- for (const e of this.entries) {
435
- const held = [...e.questions ?? [], e].find((x) => x.event?.id === eventId && !x.sent_at);
436
- if (!held) continue;
437
- held.sent_at = new Date(this.now()).toISOString();
438
- this.save();
439
- this.deps.log(
440
- `event ${ok ? "acked" : "refused by the app"} work=${e.work_id} kind=${held.event?.kind}`
441
- );
442
- return;
443
- }
444
- }
445
- stop() {
446
- this.stopped = true;
447
- for (const unwatch of this.live.values()) unwatch();
448
- this.live.clear();
449
- }
450
- now() {
451
- return this.deps.now?.() ?? Date.now();
452
- }
453
- watch(e) {
454
- if (this.stopped || e.settled_at || this.live.has(e.work_id)) return;
455
- const unwatch = this.deps.watch(e.thread_id, (event) => this.onEvent(e, event));
456
- if (e.settled_at) unwatch();
457
- else this.live.set(e.work_id, unwatch);
458
- }
459
- onEvent(e, event) {
460
- if (e.settled_at) return;
461
- if (event.kind === "question") this.ask(e, event.question_id, event.summary);
462
- else if (event.kind === "progress") this.trySend(e, this.frame(e, event));
463
- else this.finish(e, event);
464
- }
465
- frame(e, event) {
466
- const { kind, summary } = event;
467
- return {
468
- type: "event",
469
- id: randomUUID(),
470
- work_id: e.work_id,
471
- thread_id: e.thread_id,
472
- kind,
473
- ...event.kind === "question" ? { question_id: event.question_id } : {},
474
- ...summary ? { summary: summary.slice(0, 500) } : {},
475
- ..."result" in event && event.result ? { result: event.result } : {},
476
- ..."pr_url" in event && event.pr_url ? { pr_url: event.pr_url } : {},
477
- ..."error" in event && event.error ? { error: event.error } : {},
478
- at: new Date(this.now()).toISOString()
479
- };
480
- }
481
- ask(e, questionId, summary) {
482
- if (e.questions?.some((x) => x.event.question_id === questionId)) return;
483
- const event = this.frame(e, { kind: "question", question_id: questionId, summary });
484
- e.questions = [...e.questions ?? [], { event }];
485
- this.save();
486
- this.deps.log(`question work=${e.work_id} thread=${e.thread_id}`);
487
- this.trySend(e, event);
488
- }
489
- finish(e, end) {
490
- this.live.get(e.work_id)?.();
491
- this.live.delete(e.work_id);
492
- e.event = this.frame(e, end);
493
- e.settled_at = e.event.at;
494
- this.save();
495
- this.deps.log(
496
- `settle work=${e.work_id} thread=${e.thread_id} kind=${end.kind} pr=${end.pr_url ? "yes" : "no"}`
497
- );
498
- this.trySend(e, e.event);
499
- }
500
- trySend(e, event) {
501
- const sent = this.deps.send(event);
502
- this.deps.log(
503
- `event ${sent ? "sent" : "held"} work=${e.work_id} kind=${event.kind}${sent ? "" : "; socket down"}`
504
- );
505
- }
506
- load() {
507
- let raw;
508
- try {
509
- raw = JSON.parse(readFileSync(this.deps.file, "utf-8"));
510
- } catch {
511
- return [];
512
- }
513
- if (!Array.isArray(raw)) return [];
514
- const cutoff = this.now() - KEEP_MS;
515
- return raw.filter(
516
- (e) => typeof e?.work_id === "string" && typeof e?.thread_id === "string" && !(e.settled_at && Date.parse(e.settled_at) < cutoff)
517
- );
518
- }
519
- save() {
520
- mkdirSync(dirname(this.deps.file), { recursive: true, mode: 448 });
521
- const tmp = `${this.deps.file}.tmp`;
522
- writeFileSync(tmp, `${JSON.stringify(this.entries, null, 2)}
523
- `, { mode: 384 });
524
- chmodSync(tmp, 384);
525
- renameSync(tmp, this.deps.file);
526
- }
527
- };
528
-
529
325
  // src/device-revoke.ts
530
326
  function tokenGone(revoke) {
531
327
  return revoke === "revoked" || revoke === "already_revoked" || revoke === "no_device";
@@ -557,26 +353,6 @@ var SUBSCRIPTIONS = {
557
353
  team: "Claude Team",
558
354
  enterprise: "Claude Enterprise"
559
355
  };
560
- var YES_WORDS = /* @__PURE__ */ new Set([
561
- "y",
562
- "yes",
563
- "yep",
564
- "yeah",
565
- "allow",
566
- "allow it",
567
- "ok",
568
- "okay",
569
- "approve",
570
- "approved",
571
- "go ahead",
572
- "sure",
573
- "do it"
574
- ]);
575
- function isYes(reply) {
576
- return YES_WORDS.has(
577
- reply.trim().toLowerCase().replace(/[.!\s]+$/, "")
578
- );
579
- }
580
356
  function exec(bin, args) {
581
357
  return new Promise(
582
358
  (resolve3) => execFile(
@@ -1010,7 +786,7 @@ function boxSession(t3Url, t3Bin, env, token) {
1010
786
  }
1011
787
  async function mintSession(t3Url, opts = {}) {
1012
788
  const env = await workstationEnvironment(t3Url, opts.fetchFn);
1013
- const sources = opts.sources ?? defaultT3BinSources(homedir2(), opts.stored);
789
+ const sources = opts.sources ?? defaultT3BinSources(homedir(), opts.stored);
1014
790
  try {
1015
791
  const t3Bin = opts.bin ?? pickT3Bin(t3Candidates(env.serverVersion, sources), env.serverVersion);
1016
792
  if (!t3Bin) throw new Error("no t3 binary found; pass --t3-bin or set T3_BIN");
@@ -1117,6 +893,7 @@ var HARNESS_NAME = {
1117
893
  "claude-code": "Claude Code",
1118
894
  codex: "Codex"
1119
895
  };
896
+ var DRIVER_NAME = { t3: "T3 Code", ...HARNESS_NAME };
1120
897
  function fallbackDriver(found, forced, workstation) {
1121
898
  if (forced === "t3" || workstation) return null;
1122
899
  const choice = chooseDriver({ ...found, t3: false });
@@ -1130,7 +907,7 @@ function boxServiceInstalled() {
1130
907
  installedService({
1131
908
  platform: process.platform,
1132
909
  kind: "workstation",
1133
- home: homedir2(),
910
+ home: homedir(),
1134
911
  uid: process.getuid?.() ?? 0,
1135
912
  ...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
1136
913
  }).path
@@ -1208,14 +985,14 @@ function installedService(opts) {
1208
985
  if (opts.platform === "darwin") {
1209
986
  const label = `com.cloop.${name}`;
1210
987
  return {
1211
- path: join2(opts.dir ?? join2(opts.home, "Library", "LaunchAgents"), `${label}.plist`),
988
+ path: join(opts.dir ?? join(opts.home, "Library", "LaunchAgents"), `${label}.plist`),
1212
989
  steps: [{ command: ["launchctl", "bootout", `gui/${opts.uid}/${label}`], mayFail: true }],
1213
990
  running: ["launchctl", "print", `gui/${opts.uid}/${label}`]
1214
991
  };
1215
992
  }
1216
993
  const unit = `cloop-${name}.service`;
1217
994
  return {
1218
- path: join2(opts.dir ?? join2(opts.home, ".config", "systemd", "user"), unit),
995
+ path: join(opts.dir ?? join(opts.home, ".config", "systemd", "user"), unit),
1219
996
  steps: [{ command: ["systemctl", "--user", "disable", "--now", unit], mayFail: true }],
1220
997
  running: ["systemctl", "--user", "is-active", "--quiet", unit]
1221
998
  };
@@ -1229,9 +1006,9 @@ function unitFor(opts) {
1229
1006
  });
1230
1007
  if (opts.platform === "darwin") {
1231
1008
  const label = `com.cloop.${name}`;
1232
- const agents = opts.dir ?? join2(opts.home, "Library", "LaunchAgents");
1233
- const path2 = join2(agents, `${label}.plist`);
1234
- const log = join2(opts.home, "Library", "Logs", `cloop-${name}.log`);
1009
+ const agents = opts.dir ?? join(opts.home, "Library", "LaunchAgents");
1010
+ const path2 = join(agents, `${label}.plist`);
1011
+ const log = join(opts.home, "Library", "Logs", `cloop-${name}.log`);
1235
1012
  const xml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1236
1013
  const contents2 = [
1237
1014
  '<?xml version="1.0" encoding="UTF-8"?>',
@@ -1268,8 +1045,8 @@ function unitFor(opts) {
1268
1045
  };
1269
1046
  }
1270
1047
  const unit = `cloop-${name}.service`;
1271
- const units = opts.dir ?? join2(opts.home, ".config", "systemd", "user");
1272
- const path = join2(units, unit);
1048
+ const units = opts.dir ?? join(opts.home, ".config", "systemd", "user");
1049
+ const path = join(units, unit);
1273
1050
  const contents = [
1274
1051
  "[Unit]",
1275
1052
  `Description=Cloop ${name}: answers the Cloop Agent over the mesh`,
@@ -1332,13 +1109,13 @@ function findCheckouts(home, limit = 8) {
1332
1109
  for (const root of CHECKOUT_ROOTS) {
1333
1110
  let entries;
1334
1111
  try {
1335
- entries = readdirSync(join2(home, root), { withFileTypes: true });
1112
+ entries = readdirSync(join(home, root), { withFileTypes: true });
1336
1113
  } catch {
1337
1114
  continue;
1338
1115
  }
1339
1116
  for (const entry of entries) {
1340
- const path = join2(home, root, entry.name);
1341
- if (!entry.isDirectory() || !existsSync(join2(path, ".git"))) continue;
1117
+ const path = join(home, root, entry.name);
1118
+ if (!entry.isDirectory() || !existsSync(join(path, ".git"))) continue;
1342
1119
  found.push({ repo: { label: entry.name, path }, at: lastCommitAt(path) });
1343
1120
  }
1344
1121
  }
@@ -1388,7 +1165,7 @@ async function reposFor(argv) {
1388
1165
  }
1389
1166
  const here = gitTop(process.cwd());
1390
1167
  if (here) return [{ label: basename3(here), path: here }];
1391
- const home = homedir2();
1168
+ const home = homedir();
1392
1169
  const found = findCheckouts(home);
1393
1170
  const rerun = rerunCommand(argv);
1394
1171
  if (!found.length || !process.stdin.isTTY || !process.stdout.isTTY)
@@ -1455,13 +1232,41 @@ async function runSteps(steps, run = (command) => void execFileSync(command[0],
1455
1232
  }
1456
1233
  }
1457
1234
  }
1458
- async function installService(kind, argv, attempt) {
1235
+ var systemServices = {
1236
+ platform: process.platform,
1237
+ run: (command) => execFileSync(command[0], command.slice(1), {
1238
+ encoding: "utf-8",
1239
+ stdio: ["ignore", "pipe", "ignore"],
1240
+ timeout: 15e3
1241
+ }),
1242
+ awaitUp: (since) => awaitDaemon(since)
1243
+ };
1244
+ function ensureLinger(user, run) {
1245
+ try {
1246
+ if (/Linger=yes/.test(run(["loginctl", "show-user", user, "-p", "Linger"]))) {
1247
+ return { ok: true, changed: false };
1248
+ }
1249
+ } catch {
1250
+ }
1251
+ for (const command of [
1252
+ ["loginctl", "enable-linger", user],
1253
+ ["sudo", "-n", "loginctl", "enable-linger", user]
1254
+ ]) {
1255
+ try {
1256
+ run(command);
1257
+ return { ok: true, changed: true };
1258
+ } catch {
1259
+ }
1260
+ }
1261
+ return { ok: false, command: `sudo loginctl enable-linger ${user}` };
1262
+ }
1263
+ async function installService(kind, argv, attempt, services = systemServices) {
1459
1264
  if (argv.includes("--no-service")) {
1460
1265
  out(` Run ${dim("cloop box run")} to go live.`);
1461
1266
  return;
1462
1267
  }
1463
1268
  attempt.step = "service_write";
1464
- const npxBeside = join2(dirname2(process.execPath), "npx");
1269
+ const npxBeside = join(dirname(process.execPath), "npx");
1465
1270
  const program = programFor(
1466
1271
  process.argv[1] ?? "cloop",
1467
1272
  process.execPath,
@@ -1470,16 +1275,16 @@ async function installService(kind, argv, attempt) {
1470
1275
  );
1471
1276
  if (typeof program === "string") throw new ConnectFailure("npx_missing", program);
1472
1277
  const unit = unitFor({
1473
- platform: process.platform,
1278
+ platform: services.platform,
1474
1279
  kind,
1475
- home: homedir2(),
1280
+ home: homedir(),
1476
1281
  program,
1477
1282
  env: unitEnv(process.env),
1478
1283
  uid: process.getuid?.() ?? 0,
1479
1284
  ...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
1480
1285
  });
1481
- mkdirSync2(join2(unit.path, ".."), { recursive: true });
1482
- writeFileSync2(unit.path, unit.contents);
1286
+ mkdirSync(join(unit.path, ".."), { recursive: true });
1287
+ writeFileSync(unit.path, unit.contents);
1483
1288
  if (argv.includes("--no-start")) {
1484
1289
  out(
1485
1290
  ` Service: wrote ${unit.path}. Start it with: ${dim(unit.start.map((step) => step.command.join(" ")).join(" && "))}`
@@ -1488,13 +1293,14 @@ async function installService(kind, argv, attempt) {
1488
1293
  }
1489
1294
  attempt.step = "service_start";
1490
1295
  const since = Date.now();
1296
+ const run = (command) => void services.run(command);
1491
1297
  try {
1492
1298
  if (existsSync(unit.retire.path)) {
1493
1299
  out(` This computer is one runner, so connect stops and removes ${unit.retire.path}.`);
1494
- await runSteps(unit.retire.steps);
1300
+ await runSteps(unit.retire.steps, run);
1495
1301
  rmSync(unit.retire.path, { force: true });
1496
1302
  }
1497
- await runSteps(unit.start);
1303
+ await runSteps(unit.start, run);
1498
1304
  } catch (err) {
1499
1305
  throw new ConnectFailure(
1500
1306
  "service_start_failed",
@@ -1502,25 +1308,36 @@ async function installService(kind, argv, attempt) {
1502
1308
  );
1503
1309
  }
1504
1310
  attempt.step = "first_connect";
1505
- if (!await awaitDaemon(since)) {
1311
+ if (!await services.awaitUp(since)) {
1506
1312
  out(
1507
1313
  `${red("\u2717")} ${unit.path} started, but the runner did not reach Cloop within 15 s. Its last log lines:`
1508
1314
  );
1509
1315
  try {
1510
- out(
1511
- execFileSync(unit.tail[0], unit.tail.slice(1), {
1512
- encoding: "utf-8",
1513
- timeout: 5e3
1514
- })
1515
- );
1316
+ out(services.run(unit.tail));
1516
1317
  } catch {
1517
1318
  out(` (no log yet; run ${unit.logs})`);
1518
1319
  }
1519
1320
  throw new ConnectFailure("first_connect_timeout", "the runner did not reach Cloop", true);
1520
1321
  }
1322
+ if (services.platform === "linux") {
1323
+ const user = userInfo().username;
1324
+ const linger = ensureLinger(user, services.run);
1325
+ if (!linger.ok) {
1326
+ out(
1327
+ `${red("\u2717")} The runner is up, but it stops when you log out of this machine. Run this, then run cloop connect again: ${bold(linger.command)}`
1328
+ );
1329
+ throw new ConnectFailure(
1330
+ "service_start_failed",
1331
+ "linger is off and could not be turned on",
1332
+ true
1333
+ );
1334
+ }
1335
+ if (linger.changed)
1336
+ out(` Linger: turned on for ${user}, so the runner keeps running after you log out.`);
1337
+ }
1521
1338
  out(` Service: ${unit.path}, started and connected. Logs: ${dim(unit.logs)}`);
1522
1339
  }
1523
- async function connectT3(argv, attempt, fallback) {
1340
+ async function connectT3(argv, attempt, fallback, chosen, services) {
1524
1341
  const previous = readRunnerConfig();
1525
1342
  const t3Url = (flag(argv, "--t3-url") ?? DEFAULT_T3_URL).replace(/\/+$/, "");
1526
1343
  const t3Bin = flag(argv, "--t3-bin");
@@ -1575,7 +1392,8 @@ async function connectT3(argv, attempt, fallback) {
1575
1392
  writeBoxConfig: (cfg2) => writeBoxConfig({
1576
1393
  ...cfg2,
1577
1394
  origin: getOrigin(),
1578
- showOtherThreads: argv.includes("--show-other-threads")
1395
+ showOtherThreads: argv.includes("--show-other-threads"),
1396
+ ...chosen ? { chosenDriver: chosen } : {}
1579
1397
  })
1580
1398
  });
1581
1399
  await revokeReplaced(previous, "workstation", (t) => revokeOwnDevice(getOrigin(), t), out);
@@ -1600,9 +1418,9 @@ async function connectT3(argv, attempt, fallback) {
1600
1418
  } else {
1601
1419
  out(`${red("\u2717")} Status failed: ${report.error}`);
1602
1420
  }
1603
- await installService("workstation", argv, attempt);
1421
+ await installService("workstation", argv, attempt, services);
1604
1422
  }
1605
- async function connectLocal(driver, found, argv, attempt) {
1423
+ async function connectLocal(driver, found, argv, attempt, chosen, services) {
1606
1424
  attempt.step = "repos";
1607
1425
  const repos = await reposFor(argv);
1608
1426
  const harness = driver === "claude-code" ? found.claude : found.codex;
@@ -1612,7 +1430,7 @@ async function connectLocal(driver, found, argv, attempt) {
1612
1430
  const fallbackModels = driver === "claude-code" ? flag(argv, "--fallback-model") ?? (previous && isLocal(previous) ? previous.fallbackModels : void 0) ?? DEFAULT_FALLBACK_MODEL : void 0;
1613
1431
  const device = {
1614
1432
  kind: "local",
1615
- environmentId: previous && isLocal(previous) ? previous.environmentId : `local:${randomUUID2()}`,
1433
+ environmentId: previous && isLocal(previous) ? previous.environmentId : `local:${randomUUID()}`,
1616
1434
  label: deviceName,
1617
1435
  version: `${harness.name} ${harness.version ?? ""}`.trim()
1618
1436
  };
@@ -1632,7 +1450,8 @@ async function connectLocal(driver, found, argv, attempt) {
1632
1450
  bin,
1633
1451
  origin: getOrigin(),
1634
1452
  ...fallbackModels ? { fallbackModels } : {},
1635
- ...driver === "claude-code" ? { askEverything: argv.includes("--ask-everything") } : {}
1453
+ ...driver === "claude-code" ? { askEverything: argv.includes("--ask-everything") } : {},
1454
+ ...chosen ? { chosenDriver: chosen } : {}
1636
1455
  };
1637
1456
  writeBoxConfig(cfg);
1638
1457
  await revokeReplaced(previous, "local", (t) => revokeOwnDevice(getOrigin(), t), out);
@@ -1650,7 +1469,7 @@ async function connectLocal(driver, found, argv, attempt) {
1650
1469
  out(
1651
1470
  ` Fallback model: ${fallbackModels}, when Claude Code's default model is at its limit. Change it with --fallback-model.`
1652
1471
  );
1653
- await installService("local", argv, attempt);
1472
+ await installService("local", argv, attempt, services);
1654
1473
  }
1655
1474
  async function detect(probes) {
1656
1475
  const [t3, claude, codex] = await Promise.all([probes.t3(), probes.claude(), probes.codex()]);
@@ -1664,14 +1483,25 @@ function harnessesFound(found) {
1664
1483
  ];
1665
1484
  }
1666
1485
  var MODEL_LIST = /^[A-Za-z0-9][\w.:[\]-]*(,[A-Za-z0-9][\w.:[\]-]*)*$/;
1667
- async function connect(argv, attempt) {
1486
+ function rememberedDriver(previous) {
1487
+ const chosen = previous?.chosenDriver;
1488
+ return chosen && DRIVERS.includes(chosen) ? chosen : void 0;
1489
+ }
1490
+ var DRIVERS = ["t3", "claude-code", "codex"];
1491
+ async function connect(argv, attempt, deps = {}) {
1668
1492
  if (argv.some((arg) => arg === "--webhook" || arg.startsWith("--webhook="))) {
1669
1493
  await connectWebhook(argv, attempt);
1670
1494
  return;
1671
1495
  }
1672
- const forced = flag(argv, "--driver") ?? process.env.CLOOP_DRIVER;
1673
- if (forced && !["t3", "claude-code", "codex"].includes(forced))
1496
+ const named = flag(argv, "--driver") || process.env.CLOOP_DRIVER || void 0;
1497
+ if (named && !DRIVERS.includes(named))
1674
1498
  throw new ConnectFailure("bad_flag", "--driver is t3, claude-code, or codex.");
1499
+ const previous = readRunnerConfig();
1500
+ const forced = named ?? rememberedDriver(previous);
1501
+ if (forced && !named)
1502
+ out(
1503
+ `${bold("Cloop runner")} This machine runs Cloop work in ${DRIVER_NAME[forced]}, as you chose. Change it with: cloop use <t3|claude-code|codex>`
1504
+ );
1675
1505
  const fallback = flag(argv, "--fallback-model");
1676
1506
  if (fallback !== void 0 && !MODEL_LIST.test(fallback))
1677
1507
  throw new ConnectFailure(
@@ -1679,28 +1509,30 @@ async function connect(argv, attempt) {
1679
1509
  "--fallback-model takes model names, comma-separated, like opus or opus,sonnet."
1680
1510
  );
1681
1511
  const t3Url = (flag(argv, "--t3-url") ?? DEFAULT_T3_URL).replace(/\/+$/, "");
1682
- const found = await detect({
1683
- t3: () => forced && forced !== "t3" ? Promise.resolve(false) : t3Answers(t3Url),
1684
- claude: () => probeClaude(),
1685
- codex: () => probeCodex()
1686
- });
1512
+ const found = await detect(
1513
+ deps.probes ?? {
1514
+ t3: () => forced && forced !== "t3" ? Promise.resolve(false) : t3Answers(t3Url),
1515
+ claude: () => probeClaude(),
1516
+ codex: () => probeCodex()
1517
+ }
1518
+ );
1687
1519
  attempt.harnesses = harnessesFound(found);
1688
- const workstation = isWorkstation(readRunnerConfig(), boxServiceInstalled());
1520
+ const workstation = isWorkstation(previous, boxServiceInstalled());
1689
1521
  const choice = chooseDriver(found, forced, workstation);
1690
1522
  if (!choice.ok) throw new ConnectFailure(choice.code, choice.line);
1691
1523
  const local = fallbackDriver(found, forced, workstation);
1692
1524
  await connectChosen(choice.driver, attempt, {
1693
- t3: () => connectT3(argv, attempt, local ? HARNESS_NAME[local] : null),
1694
- local: (driver) => connectLocal(driver, found, argv, attempt),
1525
+ t3: () => connectT3(argv, attempt, local ? HARNESS_NAME[local] : null, forced, deps.services),
1526
+ local: (driver) => connectLocal(driver, found, argv, attempt, forced, deps.services),
1695
1527
  fallback: () => fallbackDriver(found, forced, workstation),
1696
1528
  say: (line2) => out(`${bold("Cloop runner")} ${line2}`)
1697
1529
  });
1698
1530
  }
1699
- async function connectCommand(argv) {
1531
+ async function runConnect(argv, deps = {}) {
1700
1532
  const attempt = newAttempt();
1701
1533
  let error = null;
1702
1534
  try {
1703
- await connect(argv, attempt);
1535
+ await connect(argv, attempt, deps);
1704
1536
  } catch (err) {
1705
1537
  error = err instanceof ConnectFailure ? err.code : "unexpected";
1706
1538
  if (!(err instanceof ConnectFailure && err.shown))
@@ -1711,17 +1543,15 @@ async function connectCommand(argv) {
1711
1543
  connectReport(attempt, error, getMachine()),
1712
1544
  attempt.deviceToken
1713
1545
  );
1714
- if (error) process.exit(1);
1546
+ return error;
1547
+ }
1548
+ async function connectCommand(argv) {
1549
+ if (await runConnect(argv)) process.exit(1);
1715
1550
  }
1716
1551
 
1717
1552
  export {
1718
1553
  T3Client,
1719
1554
  runBoxTool,
1720
- threadsFilePath,
1721
- runnerStatePath,
1722
- writeRunnerState,
1723
- lockThreadsFile,
1724
- BoxWatch,
1725
1555
  tokenGone,
1726
1556
  revokeOwnDevice,
1727
1557
  probeClaudePermissions,
@@ -1739,6 +1569,7 @@ export {
1739
1569
  askHidden,
1740
1570
  connectBox,
1741
1571
  chooseDriver,
1572
+ DRIVER_NAME,
1742
1573
  fallbackDriver,
1743
1574
  isWorkstation,
1744
1575
  revokeReplaced,
@@ -1760,7 +1591,11 @@ export {
1760
1591
  askRepos,
1761
1592
  askOrClosed,
1762
1593
  runSteps,
1594
+ systemServices,
1595
+ ensureLinger,
1763
1596
  detect,
1764
1597
  harnessesFound,
1598
+ rememberedDriver,
1599
+ runConnect,
1765
1600
  connectCommand
1766
1601
  };