@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,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,
@@ -13,7 +16,7 @@ import {
13
16
  t3BaseDirArgs,
14
17
  t3Candidates,
15
18
  writeBoxConfig
16
- } from "./chunk-G6JAEE2Y.js";
19
+ } from "./chunk-H7ZCXBNW.js";
17
20
  import {
18
21
  getMachine,
19
22
  shortMachineName
@@ -24,29 +27,28 @@ import {
24
27
  } from "./chunk-R3CLO2FB.js";
25
28
  import {
26
29
  connectWebhook
27
- } from "./chunk-53M5DK6D.js";
30
+ } from "./chunk-52VJGOLJ.js";
28
31
  import {
29
32
  ConnectFailure,
30
33
  connectReport,
31
34
  deviceLogin,
32
35
  newAttempt,
33
36
  sendConnectReport
34
- } from "./chunk-4XDYJZLF.js";
37
+ } from "./chunk-2SZUL2B6.js";
35
38
  import {
36
39
  VERSION
37
- } from "./chunk-BFVL3E2C.js";
40
+ } from "./chunk-GTE4QSTR.js";
38
41
  import {
39
- CONFIG_DIR,
40
42
  STAGING_ORIGIN,
41
43
  getOrigin
42
44
  } from "./chunk-3DIGCVL4.js";
43
45
 
44
46
  // src/commands/connect.ts
45
47
  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";
48
+ import { randomUUID } from "crypto";
49
+ import { existsSync, mkdirSync, readdirSync, rmSync, writeFileSync } from "fs";
50
+ import { homedir, userInfo } from "os";
51
+ import { basename as basename3, dirname, join, resolve as resolve2 } from "path";
50
52
  import { createInterface } from "readline/promises";
51
53
  import { Writable } from "stream";
52
54
 
@@ -270,7 +272,11 @@ function parseSendArgs(args) {
270
272
  };
271
273
  }
272
274
  var BOX_TOOLS = {
273
- status: ({ driver }) => driver.status(),
275
+ // The runner version tells the app which keys this machine answers: `cloop use` arrived in 0.2.6.
276
+ status: async ({ driver }) => {
277
+ const report = await driver.status();
278
+ return { ...report, box: { ...report.box, version: VERSION } };
279
+ },
274
280
  "threads.list": ({ driver }, args) => driver.listThreads({
275
281
  scope: args.scope === "all" ? "all" : "unsettled",
276
282
  limit: typeof args.limit === "number" ? Math.min(Math.max(1, args.limit), 50) : 10
@@ -315,217 +321,6 @@ async function runBoxTool(ctx, tool, args) {
315
321
  }
316
322
  }
317
323
 
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
324
  // src/device-revoke.ts
530
325
  function tokenGone(revoke) {
531
326
  return revoke === "revoked" || revoke === "already_revoked" || revoke === "no_device";
@@ -1010,7 +805,7 @@ function boxSession(t3Url, t3Bin, env, token) {
1010
805
  }
1011
806
  async function mintSession(t3Url, opts = {}) {
1012
807
  const env = await workstationEnvironment(t3Url, opts.fetchFn);
1013
- const sources = opts.sources ?? defaultT3BinSources(homedir2(), opts.stored);
808
+ const sources = opts.sources ?? defaultT3BinSources(homedir(), opts.stored);
1014
809
  try {
1015
810
  const t3Bin = opts.bin ?? pickT3Bin(t3Candidates(env.serverVersion, sources), env.serverVersion);
1016
811
  if (!t3Bin) throw new Error("no t3 binary found; pass --t3-bin or set T3_BIN");
@@ -1117,6 +912,7 @@ var HARNESS_NAME = {
1117
912
  "claude-code": "Claude Code",
1118
913
  codex: "Codex"
1119
914
  };
915
+ var DRIVER_NAME = { t3: "T3 Code", ...HARNESS_NAME };
1120
916
  function fallbackDriver(found, forced, workstation) {
1121
917
  if (forced === "t3" || workstation) return null;
1122
918
  const choice = chooseDriver({ ...found, t3: false });
@@ -1130,7 +926,7 @@ function boxServiceInstalled() {
1130
926
  installedService({
1131
927
  platform: process.platform,
1132
928
  kind: "workstation",
1133
- home: homedir2(),
929
+ home: homedir(),
1134
930
  uid: process.getuid?.() ?? 0,
1135
931
  ...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
1136
932
  }).path
@@ -1208,14 +1004,14 @@ function installedService(opts) {
1208
1004
  if (opts.platform === "darwin") {
1209
1005
  const label = `com.cloop.${name}`;
1210
1006
  return {
1211
- path: join2(opts.dir ?? join2(opts.home, "Library", "LaunchAgents"), `${label}.plist`),
1007
+ path: join(opts.dir ?? join(opts.home, "Library", "LaunchAgents"), `${label}.plist`),
1212
1008
  steps: [{ command: ["launchctl", "bootout", `gui/${opts.uid}/${label}`], mayFail: true }],
1213
1009
  running: ["launchctl", "print", `gui/${opts.uid}/${label}`]
1214
1010
  };
1215
1011
  }
1216
1012
  const unit = `cloop-${name}.service`;
1217
1013
  return {
1218
- path: join2(opts.dir ?? join2(opts.home, ".config", "systemd", "user"), unit),
1014
+ path: join(opts.dir ?? join(opts.home, ".config", "systemd", "user"), unit),
1219
1015
  steps: [{ command: ["systemctl", "--user", "disable", "--now", unit], mayFail: true }],
1220
1016
  running: ["systemctl", "--user", "is-active", "--quiet", unit]
1221
1017
  };
@@ -1229,9 +1025,9 @@ function unitFor(opts) {
1229
1025
  });
1230
1026
  if (opts.platform === "darwin") {
1231
1027
  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`);
1028
+ const agents = opts.dir ?? join(opts.home, "Library", "LaunchAgents");
1029
+ const path2 = join(agents, `${label}.plist`);
1030
+ const log = join(opts.home, "Library", "Logs", `cloop-${name}.log`);
1235
1031
  const xml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1236
1032
  const contents2 = [
1237
1033
  '<?xml version="1.0" encoding="UTF-8"?>',
@@ -1268,8 +1064,8 @@ function unitFor(opts) {
1268
1064
  };
1269
1065
  }
1270
1066
  const unit = `cloop-${name}.service`;
1271
- const units = opts.dir ?? join2(opts.home, ".config", "systemd", "user");
1272
- const path = join2(units, unit);
1067
+ const units = opts.dir ?? join(opts.home, ".config", "systemd", "user");
1068
+ const path = join(units, unit);
1273
1069
  const contents = [
1274
1070
  "[Unit]",
1275
1071
  `Description=Cloop ${name}: answers the Cloop Agent over the mesh`,
@@ -1332,13 +1128,13 @@ function findCheckouts(home, limit = 8) {
1332
1128
  for (const root of CHECKOUT_ROOTS) {
1333
1129
  let entries;
1334
1130
  try {
1335
- entries = readdirSync(join2(home, root), { withFileTypes: true });
1131
+ entries = readdirSync(join(home, root), { withFileTypes: true });
1336
1132
  } catch {
1337
1133
  continue;
1338
1134
  }
1339
1135
  for (const entry of entries) {
1340
- const path = join2(home, root, entry.name);
1341
- if (!entry.isDirectory() || !existsSync(join2(path, ".git"))) continue;
1136
+ const path = join(home, root, entry.name);
1137
+ if (!entry.isDirectory() || !existsSync(join(path, ".git"))) continue;
1342
1138
  found.push({ repo: { label: entry.name, path }, at: lastCommitAt(path) });
1343
1139
  }
1344
1140
  }
@@ -1388,7 +1184,7 @@ async function reposFor(argv) {
1388
1184
  }
1389
1185
  const here = gitTop(process.cwd());
1390
1186
  if (here) return [{ label: basename3(here), path: here }];
1391
- const home = homedir2();
1187
+ const home = homedir();
1392
1188
  const found = findCheckouts(home);
1393
1189
  const rerun = rerunCommand(argv);
1394
1190
  if (!found.length || !process.stdin.isTTY || !process.stdout.isTTY)
@@ -1455,13 +1251,41 @@ async function runSteps(steps, run = (command) => void execFileSync(command[0],
1455
1251
  }
1456
1252
  }
1457
1253
  }
1458
- async function installService(kind, argv, attempt) {
1254
+ var systemServices = {
1255
+ platform: process.platform,
1256
+ run: (command) => execFileSync(command[0], command.slice(1), {
1257
+ encoding: "utf-8",
1258
+ stdio: ["ignore", "pipe", "ignore"],
1259
+ timeout: 15e3
1260
+ }),
1261
+ awaitUp: (since) => awaitDaemon(since)
1262
+ };
1263
+ function ensureLinger(user, run) {
1264
+ try {
1265
+ if (/Linger=yes/.test(run(["loginctl", "show-user", user, "-p", "Linger"]))) {
1266
+ return { ok: true, changed: false };
1267
+ }
1268
+ } catch {
1269
+ }
1270
+ for (const command of [
1271
+ ["loginctl", "enable-linger", user],
1272
+ ["sudo", "-n", "loginctl", "enable-linger", user]
1273
+ ]) {
1274
+ try {
1275
+ run(command);
1276
+ return { ok: true, changed: true };
1277
+ } catch {
1278
+ }
1279
+ }
1280
+ return { ok: false, command: `sudo loginctl enable-linger ${user}` };
1281
+ }
1282
+ async function installService(kind, argv, attempt, services = systemServices) {
1459
1283
  if (argv.includes("--no-service")) {
1460
1284
  out(` Run ${dim("cloop box run")} to go live.`);
1461
1285
  return;
1462
1286
  }
1463
1287
  attempt.step = "service_write";
1464
- const npxBeside = join2(dirname2(process.execPath), "npx");
1288
+ const npxBeside = join(dirname(process.execPath), "npx");
1465
1289
  const program = programFor(
1466
1290
  process.argv[1] ?? "cloop",
1467
1291
  process.execPath,
@@ -1470,16 +1294,16 @@ async function installService(kind, argv, attempt) {
1470
1294
  );
1471
1295
  if (typeof program === "string") throw new ConnectFailure("npx_missing", program);
1472
1296
  const unit = unitFor({
1473
- platform: process.platform,
1297
+ platform: services.platform,
1474
1298
  kind,
1475
- home: homedir2(),
1299
+ home: homedir(),
1476
1300
  program,
1477
1301
  env: unitEnv(process.env),
1478
1302
  uid: process.getuid?.() ?? 0,
1479
1303
  ...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
1480
1304
  });
1481
- mkdirSync2(join2(unit.path, ".."), { recursive: true });
1482
- writeFileSync2(unit.path, unit.contents);
1305
+ mkdirSync(join(unit.path, ".."), { recursive: true });
1306
+ writeFileSync(unit.path, unit.contents);
1483
1307
  if (argv.includes("--no-start")) {
1484
1308
  out(
1485
1309
  ` Service: wrote ${unit.path}. Start it with: ${dim(unit.start.map((step) => step.command.join(" ")).join(" && "))}`
@@ -1488,13 +1312,14 @@ async function installService(kind, argv, attempt) {
1488
1312
  }
1489
1313
  attempt.step = "service_start";
1490
1314
  const since = Date.now();
1315
+ const run = (command) => void services.run(command);
1491
1316
  try {
1492
1317
  if (existsSync(unit.retire.path)) {
1493
1318
  out(` This computer is one runner, so connect stops and removes ${unit.retire.path}.`);
1494
- await runSteps(unit.retire.steps);
1319
+ await runSteps(unit.retire.steps, run);
1495
1320
  rmSync(unit.retire.path, { force: true });
1496
1321
  }
1497
- await runSteps(unit.start);
1322
+ await runSteps(unit.start, run);
1498
1323
  } catch (err) {
1499
1324
  throw new ConnectFailure(
1500
1325
  "service_start_failed",
@@ -1502,25 +1327,36 @@ async function installService(kind, argv, attempt) {
1502
1327
  );
1503
1328
  }
1504
1329
  attempt.step = "first_connect";
1505
- if (!await awaitDaemon(since)) {
1330
+ if (!await services.awaitUp(since)) {
1506
1331
  out(
1507
1332
  `${red("\u2717")} ${unit.path} started, but the runner did not reach Cloop within 15 s. Its last log lines:`
1508
1333
  );
1509
1334
  try {
1510
- out(
1511
- execFileSync(unit.tail[0], unit.tail.slice(1), {
1512
- encoding: "utf-8",
1513
- timeout: 5e3
1514
- })
1515
- );
1335
+ out(services.run(unit.tail));
1516
1336
  } catch {
1517
1337
  out(` (no log yet; run ${unit.logs})`);
1518
1338
  }
1519
1339
  throw new ConnectFailure("first_connect_timeout", "the runner did not reach Cloop", true);
1520
1340
  }
1341
+ if (services.platform === "linux") {
1342
+ const user = userInfo().username;
1343
+ const linger = ensureLinger(user, services.run);
1344
+ if (!linger.ok) {
1345
+ out(
1346
+ `${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)}`
1347
+ );
1348
+ throw new ConnectFailure(
1349
+ "service_start_failed",
1350
+ "linger is off and could not be turned on",
1351
+ true
1352
+ );
1353
+ }
1354
+ if (linger.changed)
1355
+ out(` Linger: turned on for ${user}, so the runner keeps running after you log out.`);
1356
+ }
1521
1357
  out(` Service: ${unit.path}, started and connected. Logs: ${dim(unit.logs)}`);
1522
1358
  }
1523
- async function connectT3(argv, attempt, fallback) {
1359
+ async function connectT3(argv, attempt, fallback, chosen, services) {
1524
1360
  const previous = readRunnerConfig();
1525
1361
  const t3Url = (flag(argv, "--t3-url") ?? DEFAULT_T3_URL).replace(/\/+$/, "");
1526
1362
  const t3Bin = flag(argv, "--t3-bin");
@@ -1575,7 +1411,8 @@ async function connectT3(argv, attempt, fallback) {
1575
1411
  writeBoxConfig: (cfg2) => writeBoxConfig({
1576
1412
  ...cfg2,
1577
1413
  origin: getOrigin(),
1578
- showOtherThreads: argv.includes("--show-other-threads")
1414
+ showOtherThreads: argv.includes("--show-other-threads"),
1415
+ ...chosen ? { chosenDriver: chosen } : {}
1579
1416
  })
1580
1417
  });
1581
1418
  await revokeReplaced(previous, "workstation", (t) => revokeOwnDevice(getOrigin(), t), out);
@@ -1600,9 +1437,9 @@ async function connectT3(argv, attempt, fallback) {
1600
1437
  } else {
1601
1438
  out(`${red("\u2717")} Status failed: ${report.error}`);
1602
1439
  }
1603
- await installService("workstation", argv, attempt);
1440
+ await installService("workstation", argv, attempt, services);
1604
1441
  }
1605
- async function connectLocal(driver, found, argv, attempt) {
1442
+ async function connectLocal(driver, found, argv, attempt, chosen, services) {
1606
1443
  attempt.step = "repos";
1607
1444
  const repos = await reposFor(argv);
1608
1445
  const harness = driver === "claude-code" ? found.claude : found.codex;
@@ -1612,7 +1449,7 @@ async function connectLocal(driver, found, argv, attempt) {
1612
1449
  const fallbackModels = driver === "claude-code" ? flag(argv, "--fallback-model") ?? (previous && isLocal(previous) ? previous.fallbackModels : void 0) ?? DEFAULT_FALLBACK_MODEL : void 0;
1613
1450
  const device = {
1614
1451
  kind: "local",
1615
- environmentId: previous && isLocal(previous) ? previous.environmentId : `local:${randomUUID2()}`,
1452
+ environmentId: previous && isLocal(previous) ? previous.environmentId : `local:${randomUUID()}`,
1616
1453
  label: deviceName,
1617
1454
  version: `${harness.name} ${harness.version ?? ""}`.trim()
1618
1455
  };
@@ -1632,7 +1469,8 @@ async function connectLocal(driver, found, argv, attempt) {
1632
1469
  bin,
1633
1470
  origin: getOrigin(),
1634
1471
  ...fallbackModels ? { fallbackModels } : {},
1635
- ...driver === "claude-code" ? { askEverything: argv.includes("--ask-everything") } : {}
1472
+ ...driver === "claude-code" ? { askEverything: argv.includes("--ask-everything") } : {},
1473
+ ...chosen ? { chosenDriver: chosen } : {}
1636
1474
  };
1637
1475
  writeBoxConfig(cfg);
1638
1476
  await revokeReplaced(previous, "local", (t) => revokeOwnDevice(getOrigin(), t), out);
@@ -1650,7 +1488,7 @@ async function connectLocal(driver, found, argv, attempt) {
1650
1488
  out(
1651
1489
  ` Fallback model: ${fallbackModels}, when Claude Code's default model is at its limit. Change it with --fallback-model.`
1652
1490
  );
1653
- await installService("local", argv, attempt);
1491
+ await installService("local", argv, attempt, services);
1654
1492
  }
1655
1493
  async function detect(probes) {
1656
1494
  const [t3, claude, codex] = await Promise.all([probes.t3(), probes.claude(), probes.codex()]);
@@ -1664,14 +1502,25 @@ function harnessesFound(found) {
1664
1502
  ];
1665
1503
  }
1666
1504
  var MODEL_LIST = /^[A-Za-z0-9][\w.:[\]-]*(,[A-Za-z0-9][\w.:[\]-]*)*$/;
1667
- async function connect(argv, attempt) {
1505
+ function rememberedDriver(previous) {
1506
+ const chosen = previous?.chosenDriver;
1507
+ return chosen && DRIVERS.includes(chosen) ? chosen : void 0;
1508
+ }
1509
+ var DRIVERS = ["t3", "claude-code", "codex"];
1510
+ async function connect(argv, attempt, deps = {}) {
1668
1511
  if (argv.some((arg) => arg === "--webhook" || arg.startsWith("--webhook="))) {
1669
1512
  await connectWebhook(argv, attempt);
1670
1513
  return;
1671
1514
  }
1672
- const forced = flag(argv, "--driver") ?? process.env.CLOOP_DRIVER;
1673
- if (forced && !["t3", "claude-code", "codex"].includes(forced))
1515
+ const named = flag(argv, "--driver") || process.env.CLOOP_DRIVER || void 0;
1516
+ if (named && !DRIVERS.includes(named))
1674
1517
  throw new ConnectFailure("bad_flag", "--driver is t3, claude-code, or codex.");
1518
+ const previous = readRunnerConfig();
1519
+ const forced = named ?? rememberedDriver(previous);
1520
+ if (forced && !named)
1521
+ out(
1522
+ `${bold("Cloop runner")} This machine runs Cloop work in ${DRIVER_NAME[forced]}, as you chose. Change it with: cloop use <t3|claude-code|codex>`
1523
+ );
1675
1524
  const fallback = flag(argv, "--fallback-model");
1676
1525
  if (fallback !== void 0 && !MODEL_LIST.test(fallback))
1677
1526
  throw new ConnectFailure(
@@ -1679,28 +1528,30 @@ async function connect(argv, attempt) {
1679
1528
  "--fallback-model takes model names, comma-separated, like opus or opus,sonnet."
1680
1529
  );
1681
1530
  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
- });
1531
+ const found = await detect(
1532
+ deps.probes ?? {
1533
+ t3: () => forced && forced !== "t3" ? Promise.resolve(false) : t3Answers(t3Url),
1534
+ claude: () => probeClaude(),
1535
+ codex: () => probeCodex()
1536
+ }
1537
+ );
1687
1538
  attempt.harnesses = harnessesFound(found);
1688
- const workstation = isWorkstation(readRunnerConfig(), boxServiceInstalled());
1539
+ const workstation = isWorkstation(previous, boxServiceInstalled());
1689
1540
  const choice = chooseDriver(found, forced, workstation);
1690
1541
  if (!choice.ok) throw new ConnectFailure(choice.code, choice.line);
1691
1542
  const local = fallbackDriver(found, forced, workstation);
1692
1543
  await connectChosen(choice.driver, attempt, {
1693
- t3: () => connectT3(argv, attempt, local ? HARNESS_NAME[local] : null),
1694
- local: (driver) => connectLocal(driver, found, argv, attempt),
1544
+ t3: () => connectT3(argv, attempt, local ? HARNESS_NAME[local] : null, forced, deps.services),
1545
+ local: (driver) => connectLocal(driver, found, argv, attempt, forced, deps.services),
1695
1546
  fallback: () => fallbackDriver(found, forced, workstation),
1696
1547
  say: (line2) => out(`${bold("Cloop runner")} ${line2}`)
1697
1548
  });
1698
1549
  }
1699
- async function connectCommand(argv) {
1550
+ async function runConnect(argv, deps = {}) {
1700
1551
  const attempt = newAttempt();
1701
1552
  let error = null;
1702
1553
  try {
1703
- await connect(argv, attempt);
1554
+ await connect(argv, attempt, deps);
1704
1555
  } catch (err) {
1705
1556
  error = err instanceof ConnectFailure ? err.code : "unexpected";
1706
1557
  if (!(err instanceof ConnectFailure && err.shown))
@@ -1711,17 +1562,15 @@ async function connectCommand(argv) {
1711
1562
  connectReport(attempt, error, getMachine()),
1712
1563
  attempt.deviceToken
1713
1564
  );
1714
- if (error) process.exit(1);
1565
+ return error;
1566
+ }
1567
+ async function connectCommand(argv) {
1568
+ if (await runConnect(argv)) process.exit(1);
1715
1569
  }
1716
1570
 
1717
1571
  export {
1718
1572
  T3Client,
1719
1573
  runBoxTool,
1720
- threadsFilePath,
1721
- runnerStatePath,
1722
- writeRunnerState,
1723
- lockThreadsFile,
1724
- BoxWatch,
1725
1574
  tokenGone,
1726
1575
  revokeOwnDevice,
1727
1576
  probeClaudePermissions,
@@ -1739,6 +1588,7 @@ export {
1739
1588
  askHidden,
1740
1589
  connectBox,
1741
1590
  chooseDriver,
1591
+ DRIVER_NAME,
1742
1592
  fallbackDriver,
1743
1593
  isWorkstation,
1744
1594
  revokeReplaced,
@@ -1760,7 +1610,11 @@ export {
1760
1610
  askRepos,
1761
1611
  askOrClosed,
1762
1612
  runSteps,
1613
+ systemServices,
1614
+ ensureLinger,
1763
1615
  detect,
1764
1616
  harnessesFound,
1617
+ rememberedDriver,
1618
+ runConnect,
1765
1619
  connectCommand
1766
1620
  };