@cloop/runner 0.2.0 → 0.2.1

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,21 +1,31 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
- deviceLogin
4
- } from "./chunk-CMOMRXTA.js";
3
+ ConnectFailure,
4
+ connectReport,
5
+ deviceLogin,
6
+ newAttempt,
7
+ sendConnectReport
8
+ } from "./chunk-AQGBNKUG.js";
9
+ import {
10
+ getMachine,
11
+ shortMachineName
12
+ } from "./chunk-JX6VG5FE.js";
5
13
  import {
6
14
  VERSION
7
- } from "./chunk-7K5W6ELQ.js";
15
+ } from "./chunk-OKF4BDBH.js";
8
16
  import {
9
17
  CONFIG_DIR,
18
+ STAGING_ORIGIN,
10
19
  getOrigin
11
- } from "./chunk-SQJ7ZO4G.js";
20
+ } from "./chunk-3DIGCVL4.js";
12
21
 
13
22
  // src/commands/connect.ts
14
- import { execFileSync as execFileSync3 } from "child_process";
23
+ import { execFileSync as execFileSync4 } from "child_process";
15
24
  import { randomUUID as randomUUID2 } from "crypto";
16
- import { existsSync, mkdirSync as mkdirSync4, readdirSync, writeFileSync as writeFileSync4 } from "fs";
17
- import { homedir as homedir4, hostname as hostname2 } from "os";
18
- import { basename as basename4, dirname as dirname4, join as join4, resolve as resolve2 } from "path";
25
+ import { existsSync as existsSync2, mkdirSync as mkdirSync4, readdirSync as readdirSync2, rmSync, writeFileSync as writeFileSync4 } from "fs";
26
+ import { homedir as homedir4 } from "os";
27
+ import { basename as basename4, dirname as dirname4, join as join5, resolve as resolve2 } from "path";
28
+ import { createInterface as createInterface2 } from "readline/promises";
19
29
 
20
30
  // src/drivers/driver.ts
21
31
  var RUNTIME_MODES = /* @__PURE__ */ new Set([
@@ -447,6 +457,7 @@ var BoxWatch = class {
447
457
  ...event.kind === "question" ? { question_id: event.question_id } : {},
448
458
  ...summary ? { summary: summary.slice(0, 500) } : {},
449
459
  ..."pr_url" in event && event.pr_url ? { pr_url: event.pr_url } : {},
460
+ ..."error" in event && event.error ? { error: event.error } : {},
450
461
  at: new Date(this.now()).toISOString()
451
462
  };
452
463
  }
@@ -498,19 +509,138 @@ var BoxWatch = class {
498
509
  }
499
510
  };
500
511
 
512
+ // src/device-revoke.ts
513
+ function tokenGone(revoke) {
514
+ return revoke === "revoked" || revoke === "already_revoked" || revoke === "no_device";
515
+ }
516
+ async function revokeOwnDevice(origin, deviceToken, fetchFn = fetch) {
517
+ if (!deviceToken) return "no_device";
518
+ try {
519
+ const res = await fetchFn(`${origin}/api/agent/mesh/device-revoke`, {
520
+ method: "POST",
521
+ headers: { authorization: `Bearer ${deviceToken}` },
522
+ signal: AbortSignal.timeout(1e4)
523
+ });
524
+ const body = await res.json().catch(() => null);
525
+ if (res.ok && body?.outcome === "revoked") return "revoked";
526
+ if (res.ok && body?.outcome === "already_revoked") return "already_revoked";
527
+ if (res.status === 401 && body?.error === "unknown_device") return "unknown_device";
528
+ return "failed";
529
+ } catch {
530
+ return "failed";
531
+ }
532
+ }
533
+
501
534
  // src/drivers/claude-code.ts
502
535
  import { execFile as execFile3 } from "child_process";
503
536
  import { basename as basename2, isAbsolute, relative, resolve } from "path";
504
537
 
505
538
  // src/drivers/local.ts
506
- import { execFile as execFile2, execFileSync as execFileSync2, spawn } from "child_process";
539
+ import { execFile as execFile2, execFileSync as execFileSync3, spawn } from "child_process";
507
540
  import { chmodSync as chmodSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "fs";
508
541
  import { homedir as homedir2, hostname } from "os";
509
- import { basename, dirname as dirname2, join as join2 } from "path";
542
+ import { basename, dirname as dirname2, join as join3 } from "path";
510
543
  import { createInterface } from "readline";
511
544
 
512
545
  // src/drivers/t3.ts
513
- import { execFile, execFileSync } from "child_process";
546
+ import { execFile, execFileSync as execFileSync2 } from "child_process";
547
+
548
+ // src/t3-bin.ts
549
+ import { execFileSync } from "child_process";
550
+ import { existsSync, readdirSync, statSync } from "fs";
551
+ import { join as join2 } from "path";
552
+ var CLEAN_ENV = () => ({
553
+ HOME: process.env.HOME,
554
+ USER: process.env.USER,
555
+ PATH: process.env.PATH
556
+ });
557
+ function defaultT3BinSources(home, stored) {
558
+ return {
559
+ env: process.env,
560
+ home,
561
+ appDirs: process.platform === "darwin" ? ["/Applications", join2(home, "Applications")] : [],
562
+ onPath: () => whichAll("t3"),
563
+ ...stored ? { stored } : {}
564
+ };
565
+ }
566
+ function isExecutable(path) {
567
+ try {
568
+ const s = statSync(path);
569
+ return s.isFile() && (s.mode & 73) !== 0;
570
+ } catch {
571
+ return false;
572
+ }
573
+ }
574
+ function bundleBinaries(appDir) {
575
+ let bundles;
576
+ try {
577
+ bundles = readdirSync(appDir).filter((name) => /^T3 Code.*\.app$/.test(name));
578
+ } catch {
579
+ return [];
580
+ }
581
+ return bundles.flatMap((bundle) => {
582
+ const root = join2(appDir, bundle);
583
+ try {
584
+ return readdirSync(root, { recursive: true }).filter((rel) => rel === "t3" || rel.endsWith("/t3")).map((rel) => join2(root, rel)).filter(isExecutable);
585
+ } catch {
586
+ return [];
587
+ }
588
+ });
589
+ }
590
+ function t3Candidates(serverVersion, sources) {
591
+ const ordered = [
592
+ sources.env.T3_BIN,
593
+ join2(sources.home, ".t3", "runtime", "versions", serverVersion, "t3"),
594
+ ...sources.appDirs.flatMap(bundleBinaries),
595
+ ...sources.onPath(),
596
+ sources.stored
597
+ ];
598
+ return [...new Set(ordered.filter((p) => Boolean(p) && existsSync(p)))];
599
+ }
600
+ function parseT3Version(output) {
601
+ return output.trim().split(/\s+/).at(-1)?.replace(/^v/, "") || null;
602
+ }
603
+ function t3Version(bin) {
604
+ try {
605
+ return parseT3Version(runT3(bin, ["--version"], 1e4));
606
+ } catch {
607
+ return null;
608
+ }
609
+ }
610
+ function pickT3Bin(candidates, serverVersion, versionOf = t3Version) {
611
+ return candidates.find((bin) => versionOf(bin) === serverVersion) ?? candidates[0] ?? null;
612
+ }
613
+ function t3BaseDirArgs(env = process.env) {
614
+ return env.T3CODE_HOME ? ["--base-dir", env.T3CODE_HOME] : [];
615
+ }
616
+ function runT3(bin, args, timeout = 15e3) {
617
+ try {
618
+ return execFileSync(bin, args, {
619
+ encoding: "utf-8",
620
+ env: CLEAN_ENV(),
621
+ timeout,
622
+ stdio: ["ignore", "pipe", "pipe"]
623
+ });
624
+ } catch (err) {
625
+ const stderr = String(err.stderr ?? "").trim().split("\n").filter((line2) => line2 && !/ExperimentalWarning|--trace-warnings/.test(line2)).at(-1);
626
+ throw new Error(
627
+ `t3 ${args.slice(0, 3).join(" ")} failed${stderr ? `: ${stderr.slice(0, 200)}` : ""}`
628
+ );
629
+ }
630
+ }
631
+ function whichAll(bin) {
632
+ try {
633
+ return execFileSync("which", ["-a", bin], {
634
+ encoding: "utf-8",
635
+ env: CLEAN_ENV(),
636
+ stdio: ["ignore", "pipe", "ignore"]
637
+ }).split("\n").map((line2) => line2.trim()).filter(Boolean);
638
+ } catch {
639
+ return [];
640
+ }
641
+ }
642
+
643
+ // src/drivers/t3.ts
514
644
  function isUnsettled(t) {
515
645
  return !t.settledAt && !t.archivedAt && !isChild(t);
516
646
  }
@@ -971,7 +1101,7 @@ var T3Driver = class {
971
1101
  };
972
1102
  (this.deps.execAsync ?? execFile)(
973
1103
  bin,
974
- ["auth", "session", "list", "--json"],
1104
+ ["auth", "session", "list", ...t3BaseDirArgs(), "--json"],
975
1105
  {
976
1106
  encoding: "utf-8",
977
1107
  env: { HOME: process.env.HOME, USER: process.env.USER, PATH: process.env.PATH },
@@ -989,7 +1119,7 @@ var T3Driver = class {
989
1119
  */
990
1120
  baseRefFor(root) {
991
1121
  const git = (args) => String(
992
- (this.deps.exec ?? execFileSync)("git", ["-C", root, ...args], {
1122
+ (this.deps.exec ?? execFileSync2)("git", ["-C", root, ...args], {
993
1123
  encoding: "utf-8",
994
1124
  env: { HOME: process.env.HOME, USER: process.env.USER, PATH: process.env.PATH },
995
1125
  timeout: 5e3
@@ -1017,6 +1147,24 @@ var PR_URL = /https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/pull\/\d+/g;
1017
1147
  var SHARED_BRANCHES2 = /* @__PURE__ */ new Set(["staging", "main", "master", "HEAD"]);
1018
1148
  var COMMANDS_KEPT = 50;
1019
1149
  var SUMMARY_MAX = 200;
1150
+ var HARNESS_NAMES = { "claude-code": "Claude Code", codex: "Codex" };
1151
+ var HARNESS_LIMIT = /usage limit|reached your [\w .-]{0,40}limit|hit your [\w .-]{0,40}limit|out of (usage )?credits/i;
1152
+ function failedEnd(harness, run2) {
1153
+ const said = run2.result?.text?.trim() || run2.lastText;
1154
+ const limited = HARNESS_LIMIT.test(run2.result?.text ?? "");
1155
+ const words = said?.replace(/\s+/g, " ").trim();
1156
+ const error = limited ? { error: "harness_limit" } : {};
1157
+ const opening = run2.switched ? `${run2.switched} ` : "";
1158
+ if (!words)
1159
+ return {
1160
+ summary: `${opening}${run2.result ? "The run ended with an error." : `The run exited with ${run2.exit}.`}`,
1161
+ ...error
1162
+ };
1163
+ const lead = `${opening}${HARNESS_NAMES[harness] ?? harness} said: "`;
1164
+ const room = SUMMARY_MAX - lead.length - 1;
1165
+ const quoted = words.length > room ? `${words.slice(0, room - 1)}\u2026` : words;
1166
+ return { summary: `${lead}${quoted}"`, ...error };
1167
+ }
1020
1168
  var PERMISSION_MODES = {
1021
1169
  "approval-required": "default",
1022
1170
  "auto-accept-edits": "acceptEdits",
@@ -1027,7 +1175,7 @@ function permissionMode(mode) {
1027
1175
  return PERMISSION_MODES[mode ?? "auto-accept-edits"];
1028
1176
  }
1029
1177
  function localRunsFilePath() {
1030
- return process.env.CLOOP_LOCAL_RUNS_FILE ?? join2(homedir2(), CONFIG_DIR, "local-runs.json");
1178
+ return process.env.CLOOP_LOCAL_RUNS_FILE ?? join3(homedir2(), CONFIG_DIR, "local-runs.json");
1031
1179
  }
1032
1180
  function pickRepo(repos, repository) {
1033
1181
  if (!repository) {
@@ -1077,7 +1225,7 @@ function harnessAlive(pid, r, dialect) {
1077
1225
  if (err.code !== "EPERM") return false;
1078
1226
  }
1079
1227
  try {
1080
- const command = execFileSync2("ps", ["-ww", "-o", "command=", "-p", String(pid)], {
1228
+ const command = execFileSync3("ps", ["-ww", "-o", "command=", "-p", String(pid)], {
1081
1229
  encoding: "utf-8",
1082
1230
  timeout: 2e3
1083
1231
  });
@@ -1425,7 +1573,7 @@ ${a.text}` : a.text;
1425
1573
  if (code === 0 && live.result?.ok) {
1426
1574
  const text = live.result.text?.trim() || r.last_text;
1427
1575
  const { pr, note } = await this.outcome(r, text);
1428
- const summary = [note, text].filter(Boolean).join(" ").replace(/\s+/g, " ");
1576
+ const summary = [r.switched, note, text].filter(Boolean).join(" ").replace(/\s+/g, " ");
1429
1577
  await this.end(r, {
1430
1578
  kind: "settled",
1431
1579
  ...summary ? { summary: summary.slice(0, SUMMARY_MAX) } : {},
@@ -1435,10 +1583,42 @@ ${a.text}` : a.text;
1435
1583
  }
1436
1584
  if (live.stderr)
1437
1585
  this.log(`stderr work=${r.work_id}: ${live.stderr.trim().split("\n").at(-1)?.slice(0, 200)}`);
1438
- await this.end(r, {
1439
- kind: "failed",
1440
- summary: live.result ? "The run ended with an error." : `The run exited with ${exit}.`
1586
+ const end = failedEnd(this.name, {
1587
+ result: live.result,
1588
+ lastText: r.last_text,
1589
+ exit,
1590
+ ...r.switched ? { switched: r.switched } : {}
1591
+ });
1592
+ if (end.error) this.log(`limit work=${r.work_id} error=${end.error}`);
1593
+ if (end.error === "harness_limit" && this.fallBack(r, live.result?.text)) return;
1594
+ await this.end(r, { kind: "failed", ...end });
1595
+ }
1596
+ /**
1597
+ * Once per run: a run stopped by its model's usage limit resumes its own
1598
+ * session on the first fallback model, with the continue prompt, so its
1599
+ * steers, answers and edits carry over. It does not when the Task named its
1600
+ * model, when the limit is the fallback model's own, or after one switch.
1601
+ * `--fallback-model` may already cover this; it is not documented whether a
1602
+ * plan's limit counts. The switch opens the end summary, because a progress
1603
+ * line is dropped while the socket is down.
1604
+ */
1605
+ fallBack(r, said) {
1606
+ const model = this.deps.dialect.fallback?.split(",")[0]?.trim();
1607
+ if (!model || !r.session_id || r.switched || r.model) return false;
1608
+ const named = new RegExp(`\\b${model.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`, "i");
1609
+ if (named.test(said ?? "")) return false;
1610
+ const from = /reached your ([\w .-]{1,40}?) limit/i.exec(said ?? "")?.[1] ?? "The default model";
1611
+ const to = `${model.charAt(0).toUpperCase()}${model.slice(1)}`;
1612
+ r.switched = `${from} was at its usage limit, so this ran on ${to}.`;
1613
+ r.model = model;
1614
+ this.save();
1615
+ this.log(`fallback work=${r.work_id} model=${model}`);
1616
+ this.emit(r.work_id, {
1617
+ kind: "progress",
1618
+ summary: `${from} is at its usage limit, so I switched to ${to}`
1441
1619
  });
1620
+ this.spawnRun(r, CONTINUE_PROMPT, true);
1621
+ return true;
1442
1622
  }
1443
1623
  /**
1444
1624
  * The PR a run produced: one its last text names, else the PR of the
@@ -1669,9 +1849,11 @@ function parseClaudeLine(raw, run2) {
1669
1849
  }
1670
1850
  return [];
1671
1851
  }
1672
- function claudeDialect(bin = "claude") {
1852
+ var DEFAULT_FALLBACK_MODEL = "opus";
1853
+ function claudeDialect(bin = "claude", fallback = DEFAULT_FALLBACK_MODEL) {
1673
1854
  return {
1674
1855
  name: "claude-code",
1856
+ fallback,
1675
1857
  aliases: ["claude-code", "claudeAgent", "claude"],
1676
1858
  bin,
1677
1859
  capabilities: ["view", "start", "steer", "report"],
@@ -1690,8 +1872,8 @@ function claudeDialect(bin = "claude") {
1690
1872
  permissionMode(run2.runtime_mode),
1691
1873
  "--add-dir",
1692
1874
  run2.repo,
1693
- ...resume ? ["--resume", run2.session_id ?? run2.work_id] : ["--session-id", run2.work_id],
1694
- ...run2.model ? ["--model", run2.model] : []
1875
+ ...resume ? ["--resume", run2.session_id ?? run2.work_id] : ["--session-id", run2.session_id ?? run2.work_id],
1876
+ ...run2.model ? ["--model", run2.model] : fallback ? ["--fallback-model", fallback] : []
1695
1877
  ];
1696
1878
  },
1697
1879
  opening(run2, prompt) {
@@ -1790,7 +1972,12 @@ function parseCodexLine(raw) {
1790
1972
  ];
1791
1973
  }
1792
1974
  if (msg.type === "turn.completed") return [{ type: "result", ok: true }];
1793
- if (msg.type === "turn.failed") return [{ type: "result", ok: false }];
1975
+ if (msg.type === "turn.failed") {
1976
+ const message = msg.error?.message;
1977
+ return [
1978
+ { type: "result", ok: false, ...typeof message === "string" ? { text: message } : {} }
1979
+ ];
1980
+ }
1794
1981
  return [];
1795
1982
  }
1796
1983
  function codexDialect(bin = "codex") {
@@ -1825,10 +2012,10 @@ function codexDialect(bin = "codex") {
1825
2012
  // src/runner-config.ts
1826
2013
  import { chmodSync as chmodSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync3, renameSync as renameSync3, writeFileSync as writeFileSync3 } from "fs";
1827
2014
  import { homedir as homedir3 } from "os";
1828
- import { dirname as dirname3, join as join3 } from "path";
2015
+ import { dirname as dirname3, join as join4 } from "path";
1829
2016
  var BOX_FILE = "box.json";
1830
2017
  function boxPath() {
1831
- return process.env.CLOOP_BOX_FILE ?? join3(homedir3(), CONFIG_DIR, BOX_FILE);
2018
+ return process.env.CLOOP_BOX_FILE ?? join4(homedir3(), CONFIG_DIR, BOX_FILE);
1832
2019
  }
1833
2020
  function isLocal(cfg) {
1834
2021
  return cfg.driver === "claude-code" || cfg.driver === "codex";
@@ -1859,7 +2046,7 @@ function writeBoxConfig(cfg) {
1859
2046
 
1860
2047
  // src/commands/connect.ts
1861
2048
  var DEFAULT_T3_URL = "http://127.0.0.1:3773";
1862
- var CLEAN_ENV = { HOME: process.env.HOME, USER: process.env.USER, PATH: process.env.PATH };
2049
+ var CLEAN_ENV2 = { HOME: process.env.HOME, USER: process.env.USER, PATH: process.env.PATH };
1863
2050
  var out = (line2) => console.log(line2);
1864
2051
  var bold = (s) => `\x1B[1m${s}\x1B[0m`;
1865
2052
  var dim = (s) => `\x1B[2m${s}\x1B[0m`;
@@ -1871,43 +2058,36 @@ function flag(argv, name) {
1871
2058
  function flags(argv, name) {
1872
2059
  return argv.flatMap((a, i) => a === name && argv[i + 1] ? [argv[i + 1]] : []);
1873
2060
  }
1874
- function compareVersions(a, b) {
1875
- return a.localeCompare(b, void 0, { numeric: true });
1876
- }
1877
- function resolveT3Bin(explicit) {
1878
- if (explicit) return explicit;
1879
- if (process.env.T3_BIN) return process.env.T3_BIN;
1880
- const versions = join4(homedir4(), ".t3", "runtime", "versions");
1881
- try {
1882
- const newest = readdirSync(versions).sort(compareVersions).at(-1);
1883
- if (newest && existsSync(join4(versions, newest, "t3"))) return join4(versions, newest, "t3");
1884
- } catch {
1885
- }
1886
- return which("t3");
1887
- }
1888
2061
  function which(bin) {
1889
2062
  try {
1890
- return execFileSync3("which", [bin], { encoding: "utf-8", env: CLEAN_ENV }).trim() || null;
2063
+ return execFileSync4("which", [bin], { encoding: "utf-8", env: CLEAN_ENV2 }).trim() || null;
1891
2064
  } catch {
1892
2065
  return null;
1893
2066
  }
1894
2067
  }
1895
- async function mintSession(t3Url, t3Bin) {
1896
- const env = await readEnvironment(t3Url);
2068
+ async function mintSession(t3Url, opts = {}) {
2069
+ const env = await readEnvironment(t3Url, opts.fetchFn);
1897
2070
  const protocol = env.orchestrationProtocolVersion ?? 1;
1898
2071
  if (protocol < MIN_PROTOCOL) {
1899
2072
  throw new Error(
1900
2073
  `T3 ${env.serverVersion} speaks orchestration protocol ${protocol}; a workstation needs ${MIN_PROTOCOL} (the V2 nightly or later).`
1901
2074
  );
1902
2075
  }
2076
+ const sources = opts.sources ?? defaultT3BinSources(homedir4(), opts.stored);
2077
+ const t3Bin = opts.bin ?? pickT3Bin(t3Candidates(env.serverVersion, sources), env.serverVersion);
2078
+ if (!t3Bin) throw new Error("no t3 binary found; pass --t3-bin or set T3_BIN");
1903
2079
  const pairing = JSON.parse(
1904
- execFileSync3(t3Bin, ["auth", "pairing", "create", "--ttl", "5m", "--json"], {
1905
- encoding: "utf-8",
1906
- env: CLEAN_ENV,
1907
- timeout: 15e3
1908
- })
2080
+ runT3(t3Bin, [
2081
+ "auth",
2082
+ "pairing",
2083
+ "create",
2084
+ ...t3BaseDirArgs(sources.env),
2085
+ "--ttl",
2086
+ "5m",
2087
+ "--json"
2088
+ ])
1909
2089
  );
1910
- const token = await exchangePairing(t3Url, pairing.credential, "cloop box");
2090
+ const token = await exchangePairing(t3Url, pairing.credential, "cloop box", opts.fetchFn);
1911
2091
  return {
1912
2092
  t3Url,
1913
2093
  t3Bin,
@@ -1931,25 +2111,80 @@ var SIGNED_OUT = {
1931
2111
  "claude-code": "Claude Code is installed but not signed in. Run `claude` once and sign in, then run `cloop connect` again.",
1932
2112
  codex: "Codex is installed but not signed in. Run `codex login`, then run `cloop connect` again."
1933
2113
  };
1934
- function chooseDriver(found, forced) {
2114
+ var T3_DOWN = "T3 Code is not answering; start it, or pass --driver claude-code.";
2115
+ function chooseDriver(found, forced, workstation = false) {
1935
2116
  const local = (driver) => {
1936
2117
  const harness = driver === "claude-code" ? found.claude : found.codex;
1937
2118
  if (!harness)
1938
2119
  return {
1939
2120
  ok: false,
2121
+ code: "no_harness",
1940
2122
  line: `${driver === "codex" ? "Codex" : "Claude Code"} is not installed here.`
1941
2123
  };
1942
- return harness.signedIn ? { ok: true, driver, kind: "local" } : { ok: false, line: SIGNED_OUT[driver] };
2124
+ return harness.signedIn ? { ok: true, driver, kind: "local" } : { ok: false, code: "signed_out", line: SIGNED_OUT[driver] };
1943
2125
  };
1944
2126
  if (forced === "t3")
1945
- return found.t3 ? { ok: true, driver: "t3", kind: "workstation" } : { ok: false, line: `No T3 Code server answers at ${DEFAULT_T3_URL}.` };
2127
+ return found.t3 ? { ok: true, driver: "t3", kind: "workstation" } : { ok: false, code: "no_harness", line: `No T3 Code server answers at ${DEFAULT_T3_URL}.` };
1946
2128
  if (forced) return local(forced);
1947
2129
  if (found.t3) return { ok: true, driver: "t3", kind: "workstation" };
2130
+ if (workstation) return { ok: false, code: "t3_unreachable", line: T3_DOWN };
1948
2131
  if (found.claude?.signedIn) return local("claude-code");
1949
2132
  if (found.codex?.signedIn) return local("codex");
1950
2133
  if (found.claude) return local("claude-code");
1951
2134
  if (found.codex) return local("codex");
1952
- return { ok: false, line: NONE };
2135
+ return { ok: false, code: "no_harness", line: NONE };
2136
+ }
2137
+ var HARNESS_NAME = {
2138
+ "claude-code": "Claude Code",
2139
+ codex: "Codex"
2140
+ };
2141
+ function fallbackDriver(found, forced, workstation) {
2142
+ if (forced === "t3" || workstation) return null;
2143
+ const choice = chooseDriver({ ...found, t3: false });
2144
+ return choice.ok && choice.driver !== "t3" ? choice.driver : null;
2145
+ }
2146
+ function isWorkstation(previous, boxServiceInstalled2) {
2147
+ return boxServiceInstalled2 || Boolean(previous && !isLocal(previous));
2148
+ }
2149
+ function boxServiceInstalled() {
2150
+ return existsSync2(
2151
+ installedService({
2152
+ platform: process.platform,
2153
+ kind: "workstation",
2154
+ home: homedir4(),
2155
+ uid: process.getuid?.() ?? 0,
2156
+ ...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
2157
+ }).path
2158
+ );
2159
+ }
2160
+ var KIND_NAME = { workstation: "a Cloop box with T3 Code", local: "a Local runner" };
2161
+ async function revokeReplaced(previous, kind, revoke, say) {
2162
+ if (!previous?.deviceToken || isLocal(previous) === (kind === "local")) return;
2163
+ const was = isLocal(previous) ? "local" : "workstation";
2164
+ say(
2165
+ `${bold("Cloop runner")} This computer was ${KIND_NAME[was]}. It becomes ${KIND_NAME[kind]}, so its old device goes.`
2166
+ );
2167
+ say(
2168
+ tokenGone(await revoke(previous.deviceToken)) ? " Revoked the old device on Cloop." : " Could not revoke the old device. Press Disconnect on its card on the Threads page."
2169
+ );
2170
+ }
2171
+ function fallbackLine(reason, driver) {
2172
+ return `T3 Code is running but would not pair (${reason}). Connecting ${HARNESS_NAME[driver]} instead. To use T3: cloop connect --driver t3 --t3-bin <path>`;
2173
+ }
2174
+ async function connectChosen(driver, attempt, run2) {
2175
+ attempt.driver = driver;
2176
+ if (driver !== "t3") return run2.local(driver);
2177
+ try {
2178
+ await run2.t3();
2179
+ } catch (err) {
2180
+ if (!(err instanceof ConnectFailure) || err.code !== "t3_pair_failed") throw err;
2181
+ const local = run2.fallback();
2182
+ if (!local) throw err;
2183
+ run2.say(fallbackLine(err.message, local));
2184
+ attempt.fellBack = true;
2185
+ attempt.driver = local;
2186
+ await run2.local(local);
2187
+ }
1953
2188
  }
1954
2189
  function systemdAssignment(assignment) {
1955
2190
  return `"${assignment.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%")}"`;
@@ -1978,7 +2213,8 @@ var UNIT_ENV = [
1978
2213
  "CLOOP_BOX_THREADS_FILE",
1979
2214
  "CLOOP_LOCAL_RUNS_FILE",
1980
2215
  "CLOOP_MESH_URL",
1981
- "CLOOP_ORIGIN"
2216
+ "CLOOP_ORIGIN",
2217
+ "T3CODE_HOME"
1982
2218
  ];
1983
2219
  function unitEnv(env) {
1984
2220
  const picked = { PATH: "/usr/bin:/bin" };
@@ -1988,13 +2224,35 @@ function unitEnv(env) {
1988
2224
  }
1989
2225
  return picked;
1990
2226
  }
2227
+ function installedService(opts) {
2228
+ const name = opts.kind === "workstation" ? "box" : "runner";
2229
+ if (opts.platform === "darwin") {
2230
+ const label = `com.cloop.${name}`;
2231
+ return {
2232
+ path: join5(opts.dir ?? join5(opts.home, "Library", "LaunchAgents"), `${label}.plist`),
2233
+ steps: [{ command: ["launchctl", "bootout", `gui/${opts.uid}/${label}`], mayFail: true }],
2234
+ running: ["launchctl", "print", `gui/${opts.uid}/${label}`]
2235
+ };
2236
+ }
2237
+ const unit = `cloop-${name}.service`;
2238
+ return {
2239
+ path: join5(opts.dir ?? join5(opts.home, ".config", "systemd", "user"), unit),
2240
+ steps: [{ command: ["systemctl", "--user", "disable", "--now", unit], mayFail: true }],
2241
+ running: ["systemctl", "--user", "is-active", "--quiet", unit]
2242
+ };
2243
+ }
1991
2244
  function unitFor(opts) {
1992
2245
  const env = Object.entries(opts.env);
1993
2246
  const name = opts.kind === "workstation" ? "box" : "runner";
2247
+ const retire = installedService({
2248
+ ...opts,
2249
+ kind: opts.kind === "workstation" ? "local" : "workstation"
2250
+ });
1994
2251
  if (opts.platform === "darwin") {
1995
2252
  const label = `com.cloop.${name}`;
1996
- const path2 = join4(opts.dir ?? join4(opts.home, "Library", "LaunchAgents"), `${label}.plist`);
1997
- const log = join4(opts.home, "Library", "Logs", `cloop-${name}.log`);
2253
+ const agents = opts.dir ?? join5(opts.home, "Library", "LaunchAgents");
2254
+ const path2 = join5(agents, `${label}.plist`);
2255
+ const log = join5(opts.home, "Library", "Logs", `cloop-${name}.log`);
1998
2256
  const xml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1999
2257
  const contents2 = [
2000
2258
  '<?xml version="1.0" encoding="UTF-8"?>',
@@ -2025,12 +2283,14 @@ function unitFor(opts) {
2025
2283
  { command: ["launchctl", "bootout", `${domain}/${label}`], mayFail: true },
2026
2284
  { command: ["launchctl", "bootstrap", domain, path2], tries: 5 }
2027
2285
  ],
2286
+ retire,
2028
2287
  logs: `tail -f ${log}`,
2029
2288
  tail: ["tail", "-n", "20", log]
2030
2289
  };
2031
2290
  }
2032
2291
  const unit = `cloop-${name}.service`;
2033
- const path = join4(opts.dir ?? join4(opts.home, ".config", "systemd", "user"), unit);
2292
+ const units = opts.dir ?? join5(opts.home, ".config", "systemd", "user");
2293
+ const path = join5(units, unit);
2034
2294
  const contents = [
2035
2295
  "[Unit]",
2036
2296
  `Description=Cloop ${name}: answers the Cloop Agent over the mesh`,
@@ -2059,6 +2319,7 @@ function unitFor(opts) {
2059
2319
  { command: ["systemctl", "--user", "enable", unit] },
2060
2320
  { command: ["systemctl", "--user", "restart", unit] }
2061
2321
  ],
2322
+ retire,
2062
2323
  logs: `journalctl --user -u ${unit} -f`,
2063
2324
  tail: ["journalctl", "--user", "-u", unit, "-n", "20", "--no-pager"]
2064
2325
  };
@@ -2073,9 +2334,113 @@ function resolveRepos(paths, toplevel) {
2073
2334
  }
2074
2335
  return repos;
2075
2336
  }
2337
+ var CHECKOUT_ROOTS = ["projects", "code", "repos", "src", "Developer", "dev", "work"];
2338
+ function lastCommitAt(path) {
2339
+ try {
2340
+ return Number(
2341
+ execFileSync4("git", ["-C", path, "log", "-1", "--format=%ct"], {
2342
+ encoding: "utf-8",
2343
+ stdio: ["ignore", "pipe", "ignore"],
2344
+ timeout: 5e3
2345
+ }).trim()
2346
+ ) || 0;
2347
+ } catch {
2348
+ return 0;
2349
+ }
2350
+ }
2351
+ function findCheckouts(home, limit = 8) {
2352
+ const found = [];
2353
+ for (const root of CHECKOUT_ROOTS) {
2354
+ let entries;
2355
+ try {
2356
+ entries = readdirSync2(join5(home, root), { withFileTypes: true });
2357
+ } catch {
2358
+ continue;
2359
+ }
2360
+ for (const entry of entries) {
2361
+ const path = join5(home, root, entry.name);
2362
+ if (!entry.isDirectory() || !existsSync2(join5(path, ".git"))) continue;
2363
+ found.push({ repo: { label: entry.name, path }, at: lastCommitAt(path) });
2364
+ }
2365
+ }
2366
+ return found.sort((a, b) => b.at - a.at).slice(0, limit).map((f) => f.repo);
2367
+ }
2368
+ function tilde(path, home) {
2369
+ return path === home || path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path;
2370
+ }
2371
+ function parsePicks(answer, max) {
2372
+ const picks = answer.split(/[\s,]+/).filter(Boolean).map(Number);
2373
+ if (!picks.length || picks.some((n) => !Number.isInteger(n) || n < 1 || n > max)) return null;
2374
+ return [...new Set(picks)];
2375
+ }
2376
+ function rerunCommand(argv, script = process.argv[1] ?? "") {
2377
+ const base = script.includes("/_npx/") ? "npx -y @cloop/runner" : "cloop";
2378
+ const staging = process.env.CLOOP_ORIGIN === STAGING_ORIGIN ? ["--staging"] : [];
2379
+ return [base, "connect", ...staging, ...argv].join(" ");
2380
+ }
2381
+ function notACheckoutLine(cwd, found, home, rerun) {
2382
+ const here = `${tilde(cwd, home)} is not a git checkout.`;
2383
+ if (!found.length)
2384
+ return `${here} Run it again with --repo <path> for each repository Cloop may work in: ${rerun} --repo <path>`;
2385
+ const list = found.map((r) => `${r.label} (${tilde(r.path, home)})`).join(", ");
2386
+ return `${here} Recent checkouts: ${list}. Run it again with a --repo for each one Cloop may work in, for example: ${rerun} --repo ${tilde(found[0]?.path ?? "", home)}`;
2387
+ }
2388
+ async function askRepos(found, home, rerun, ask, say) {
2389
+ say(`${bold("Cloop runner")} This folder is not a git checkout. Recent ones:`);
2390
+ found.forEach((r, i) => say(` ${i + 1} ${r.label} ${dim(tilde(r.path, home))}`));
2391
+ for (; ; ) {
2392
+ const answer = (await ask("Which folders may Cloop work in? (numbers, comma-separated) ")).trim();
2393
+ if (!answer)
2394
+ throw new ConnectFailure(
2395
+ "no_repo",
2396
+ `No folder chosen. Run ${rerun} --repo <path> to name one.`
2397
+ );
2398
+ const picks = parsePicks(answer, found.length);
2399
+ if (picks) return picks.map((n) => found[n - 1]);
2400
+ say(` Type numbers from 1 to ${found.length}, like 1,3.`);
2401
+ }
2402
+ }
2403
+ async function reposFor(argv) {
2404
+ const given = flags(argv, "--repo");
2405
+ if (given.length) {
2406
+ const repos = resolveRepos(given, gitTop);
2407
+ if (typeof repos === "string") throw new ConnectFailure("no_repo", repos);
2408
+ return repos;
2409
+ }
2410
+ const here = gitTop(process.cwd());
2411
+ if (here) return [{ label: basename4(here), path: here }];
2412
+ const home = homedir4();
2413
+ const found = findCheckouts(home);
2414
+ const rerun = rerunCommand(argv);
2415
+ if (!found.length || !process.stdin.isTTY || !process.stdout.isTTY)
2416
+ throw new ConnectFailure("no_repo", notACheckoutLine(process.cwd(), found, home, rerun));
2417
+ const prompt = createInterface2({ input: process.stdin, output: process.stdout });
2418
+ const closed = () => new ConnectFailure("no_repo", `No folder chosen. Run ${rerun} --repo <path> to name one.`);
2419
+ try {
2420
+ return await askRepos(found, home, rerun, askOrClosed(prompt, closed), out);
2421
+ } finally {
2422
+ prompt.close();
2423
+ }
2424
+ }
2425
+ function askOrClosed(prompt, closed) {
2426
+ return (question) => new Promise((resolve3, reject) => {
2427
+ const onClose = () => reject(closed());
2428
+ prompt.once("close", onClose);
2429
+ prompt.question(question).then(
2430
+ (answer) => {
2431
+ prompt.off("close", onClose);
2432
+ resolve3(answer);
2433
+ },
2434
+ (err) => {
2435
+ prompt.off("close", onClose);
2436
+ reject(err);
2437
+ }
2438
+ );
2439
+ });
2440
+ }
2076
2441
  function gitTop(path) {
2077
2442
  try {
2078
- return execFileSync3("git", ["-C", path, "rev-parse", "--show-toplevel"], {
2443
+ return execFileSync4("git", ["-C", path, "rev-parse", "--show-toplevel"], {
2079
2444
  encoding: "utf-8",
2080
2445
  stdio: ["ignore", "pipe", "ignore"]
2081
2446
  }).trim();
@@ -2096,8 +2461,8 @@ function harnessLine(h) {
2096
2461
  const account = h.signedIn ? h.account ?? "signed in" : "signed out";
2097
2462
  return `${h.name}${version}, ${account}${h.experimental ? " (experimental)" : ""}`;
2098
2463
  }
2099
- async function startService(unit, run2 = (command) => void execFileSync3(command[0], command.slice(1), { stdio: "ignore", timeout: 15e3 }), wait = (ms) => new Promise((r) => setTimeout(r, ms))) {
2100
- for (const step of unit.start) {
2464
+ async function runSteps(steps, run2 = (command) => void execFileSync4(command[0], command.slice(1), { stdio: "ignore", timeout: 15e3 }), wait = (ms) => new Promise((r) => setTimeout(r, ms))) {
2465
+ for (const step of steps) {
2101
2466
  const tries = step.tries ?? 1;
2102
2467
  for (let attempt = 1; ; attempt++) {
2103
2468
  try {
@@ -2111,22 +2476,20 @@ async function startService(unit, run2 = (command) => void execFileSync3(command
2111
2476
  }
2112
2477
  }
2113
2478
  }
2114
- async function installService(kind, argv) {
2479
+ async function installService(kind, argv, attempt) {
2115
2480
  if (argv.includes("--no-service")) {
2116
2481
  out(` Run ${dim("cloop box run")} to go live.`);
2117
2482
  return;
2118
2483
  }
2119
- const npxBeside = join4(dirname4(process.execPath), "npx");
2484
+ attempt.step = "service_write";
2485
+ const npxBeside = join5(dirname4(process.execPath), "npx");
2120
2486
  const program = programFor(
2121
2487
  process.argv[1] ?? "cloop",
2122
2488
  process.execPath,
2123
- existsSync(npxBeside) ? npxBeside : which("npx"),
2489
+ existsSync2(npxBeside) ? npxBeside : which("npx"),
2124
2490
  VERSION
2125
2491
  );
2126
- if (typeof program === "string") {
2127
- out(`${red("\u2717")} ${program}`);
2128
- process.exit(1);
2129
- }
2492
+ if (typeof program === "string") throw new ConnectFailure("npx_missing", program);
2130
2493
  const unit = unitFor({
2131
2494
  platform: process.platform,
2132
2495
  kind,
@@ -2136,7 +2499,7 @@ async function installService(kind, argv) {
2136
2499
  uid: process.getuid?.() ?? 0,
2137
2500
  ...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
2138
2501
  });
2139
- mkdirSync4(join4(unit.path, ".."), { recursive: true });
2502
+ mkdirSync4(join5(unit.path, ".."), { recursive: true });
2140
2503
  writeFileSync4(unit.path, unit.contents);
2141
2504
  if (argv.includes("--no-start")) {
2142
2505
  out(
@@ -2144,22 +2507,29 @@ async function installService(kind, argv) {
2144
2507
  );
2145
2508
  return;
2146
2509
  }
2510
+ attempt.step = "service_start";
2147
2511
  const since = Date.now();
2148
2512
  try {
2149
- await startService(unit);
2513
+ if (existsSync2(unit.retire.path)) {
2514
+ out(` This computer is one runner, so connect stops and removes ${unit.retire.path}.`);
2515
+ await runSteps(unit.retire.steps);
2516
+ rmSync(unit.retire.path, { force: true });
2517
+ }
2518
+ await runSteps(unit.start);
2150
2519
  } catch (err) {
2151
- out(
2152
- `${red("\u2717")} Wrote ${unit.path} but could not start it: ${err instanceof Error ? err.message : String(err)}`
2520
+ throw new ConnectFailure(
2521
+ "service_start_failed",
2522
+ `Wrote ${unit.path} but could not start it: ${err instanceof Error ? err.message : String(err)}`
2153
2523
  );
2154
- process.exit(1);
2155
2524
  }
2525
+ attempt.step = "first_connect";
2156
2526
  if (!await awaitDaemon(since)) {
2157
2527
  out(
2158
2528
  `${red("\u2717")} ${unit.path} started, but the runner did not reach Cloop within 15 s. Its last log lines:`
2159
2529
  );
2160
2530
  try {
2161
2531
  out(
2162
- execFileSync3(unit.tail[0], unit.tail.slice(1), {
2532
+ execFileSync4(unit.tail[0], unit.tail.slice(1), {
2163
2533
  encoding: "utf-8",
2164
2534
  timeout: 5e3
2165
2535
  })
@@ -2167,42 +2537,57 @@ async function installService(kind, argv) {
2167
2537
  } catch {
2168
2538
  out(` (no log yet; run ${unit.logs})`);
2169
2539
  }
2170
- process.exit(1);
2540
+ throw new ConnectFailure("first_connect_timeout", "the runner did not reach Cloop", true);
2171
2541
  }
2172
2542
  out(` Service: ${unit.path}, started and connected. Logs: ${dim(unit.logs)}`);
2173
2543
  }
2174
- async function connectT3(argv) {
2544
+ async function connectT3(argv, attempt) {
2545
+ const previous = readRunnerConfig();
2175
2546
  const t3Url = (flag(argv, "--t3-url") ?? DEFAULT_T3_URL).replace(/\/+$/, "");
2176
- const t3Bin = resolveT3Bin(flag(argv, "--t3-bin"));
2177
- if (!t3Bin) {
2178
- out(`${red("\u2717")} No t3 binary found. Pass --t3-bin or set T3_BIN.`);
2179
- process.exit(1);
2180
- }
2547
+ const t3Bin = flag(argv, "--t3-bin");
2181
2548
  const cfg = await connectBox({
2182
2549
  readEnvironment: async () => {
2183
2550
  const environment = await readEnvironment(t3Url);
2184
2551
  out(
2185
- `${bold("Cloop box")} Connecting ${environment.label} (T3 ${environment.serverVersion}) to Cloop.`
2552
+ `${bold("Cloop runner")} Connecting ${environment.label} (T3 ${environment.serverVersion}) to Cloop.`
2186
2553
  );
2187
2554
  return environment;
2188
2555
  },
2189
- mintSession: () => mintSession(t3Url, t3Bin),
2190
- deviceLogin: (environment) => deviceLogin({
2191
- origin: getOrigin(),
2192
- deviceName: flag(argv, "--name") ?? hostname2(),
2193
- device: {
2194
- kind: "workstation",
2195
- environmentId: environment.environmentId,
2196
- label: environment.label,
2197
- version: environment.serverVersion
2556
+ mintSession: async () => {
2557
+ attempt.step = "t3_pair";
2558
+ try {
2559
+ return await mintSession(t3Url, t3Bin ? { bin: t3Bin } : {});
2560
+ } catch (err) {
2561
+ throw new ConnectFailure(
2562
+ "t3_pair_failed",
2563
+ err instanceof Error ? err.message : String(err)
2564
+ );
2198
2565
  }
2199
- }),
2200
- writeBoxConfig
2566
+ },
2567
+ deviceLogin: async (environment) => {
2568
+ attempt.step = "login";
2569
+ attempt.deviceToken = await deviceLogin({
2570
+ origin: getOrigin(),
2571
+ deviceName: flag(argv, "--name") ?? shortMachineName(),
2572
+ device: {
2573
+ kind: "workstation",
2574
+ environmentId: environment.environmentId,
2575
+ label: environment.label,
2576
+ version: environment.serverVersion
2577
+ }
2578
+ });
2579
+ return attempt.deviceToken;
2580
+ },
2581
+ writeBoxConfig: (cfg2) => writeBoxConfig({ ...cfg2, origin: getOrigin() })
2201
2582
  });
2583
+ await revokeReplaced(previous, "workstation", (t) => revokeOwnDevice(getOrigin(), t), out);
2202
2584
  out(
2203
- `${bold("Cloop box")} T3 ${cfg.label} paired with scope ${cfg.scope}, until ${cfg.expiresAt.slice(0, 10)}.`
2585
+ `${bold("Cloop runner")} T3 ${cfg.label} paired with scope ${cfg.scope}, until ${cfg.expiresAt.slice(0, 10)}.`
2204
2586
  );
2205
- const driver = new T3Driver({ client: () => new T3Client(cfg.t3Url, cfg.token), t3Bin });
2587
+ const driver = new T3Driver({
2588
+ client: () => new T3Client(cfg.t3Url, cfg.token),
2589
+ t3Bin: cfg.t3Bin
2590
+ });
2206
2591
  const report = await runBoxTool({ driver }, "status", {});
2207
2592
  if (report.ok) {
2208
2593
  const value = report.value;
@@ -2213,21 +2598,16 @@ async function connectT3(argv) {
2213
2598
  } else {
2214
2599
  out(`${red("\u2717")} Status failed: ${report.error}`);
2215
2600
  }
2216
- await installService("workstation", argv);
2601
+ await installService("workstation", argv, attempt);
2217
2602
  }
2218
- async function connectLocal(driver, found, argv) {
2219
- const repos = resolveRepos(
2220
- flags(argv, "--repo").length ? flags(argv, "--repo") : [process.cwd()],
2221
- gitTop
2222
- );
2223
- if (typeof repos === "string") {
2224
- out(`${red("\u2717")} ${repos}`);
2225
- process.exit(1);
2226
- }
2603
+ async function connectLocal(driver, found, argv, attempt) {
2604
+ attempt.step = "repos";
2605
+ const repos = await reposFor(argv);
2227
2606
  const harness = driver === "claude-code" ? found.claude : found.codex;
2228
2607
  const bin = which(driver === "claude-code" ? "claude" : "codex") ?? (driver === "claude-code" ? "claude" : "codex");
2229
2608
  const previous = readRunnerConfig();
2230
- const deviceName = flag(argv, "--name") ?? hostname2();
2609
+ const deviceName = flag(argv, "--name") ?? shortMachineName();
2610
+ const fallbackModels = driver === "claude-code" ? flag(argv, "--fallback-model") ?? (previous && isLocal(previous) ? previous.fallbackModels : void 0) ?? DEFAULT_FALLBACK_MODEL : void 0;
2231
2611
  const device = {
2232
2612
  kind: "local",
2233
2613
  environmentId: previous && isLocal(previous) ? previous.environmentId : `local:${randomUUID2()}`,
@@ -2237,16 +2617,21 @@ async function connectLocal(driver, found, argv) {
2237
2617
  out(
2238
2618
  `${bold("Cloop runner")} Connecting ${deviceName} as a Local runner with ${harnessLine(harness)}.`
2239
2619
  );
2620
+ attempt.step = "login";
2240
2621
  const deviceToken = await deviceLogin({ origin: getOrigin(), deviceName, device });
2622
+ attempt.deviceToken = deviceToken;
2241
2623
  const cfg = {
2242
2624
  driver,
2243
2625
  environmentId: device.environmentId,
2244
2626
  label: deviceName,
2245
2627
  deviceToken,
2246
2628
  repos,
2247
- bin
2629
+ bin,
2630
+ origin: getOrigin(),
2631
+ ...fallbackModels ? { fallbackModels } : {}
2248
2632
  };
2249
2633
  writeBoxConfig(cfg);
2634
+ await revokeReplaced(previous, "local", (t) => revokeOwnDevice(getOrigin(), t), out);
2250
2635
  const others = [found.claude, found.codex].filter(
2251
2636
  (h) => Boolean(h) && h !== harness
2252
2637
  );
@@ -2254,63 +2639,117 @@ async function connectLocal(driver, found, argv) {
2254
2639
  `${bold("Cloop runner")} ${deviceName} is a Local runner: ${[harness, ...others].map(harnessLine).join("; ")}.`
2255
2640
  );
2256
2641
  out(` Repos: ${repos.map((r) => `${r.label} (${r.path})`).join(", ")}`);
2257
- await installService("local", argv);
2642
+ if (fallbackModels)
2643
+ out(
2644
+ ` Fallback model: ${fallbackModels}, when Claude Code's default model is at its limit. Change it with --fallback-model.`
2645
+ );
2646
+ await installService("local", argv, attempt);
2258
2647
  }
2259
2648
  async function detect(probes) {
2260
2649
  const [t3, claude, codex] = await Promise.all([probes.t3(), probes.claude(), probes.codex()]);
2261
2650
  return { t3, claude, codex };
2262
2651
  }
2263
- async function connectCommand(argv) {
2652
+ function harnessesFound(found) {
2653
+ return [
2654
+ ...found.t3 ? ["t3"] : [],
2655
+ ...found.claude ? ["claude-code"] : [],
2656
+ ...found.codex ? ["codex"] : []
2657
+ ];
2658
+ }
2659
+ var MODEL_LIST = /^[A-Za-z0-9][\w.:[\]-]*(,[A-Za-z0-9][\w.:[\]-]*)*$/;
2660
+ async function connect(argv, attempt) {
2264
2661
  const forced = flag(argv, "--driver") ?? process.env.CLOOP_DRIVER;
2265
- if (forced && !["t3", "claude-code", "codex"].includes(forced)) {
2266
- out(`${red("\u2717")} --driver is t3, claude-code, or codex.`);
2267
- process.exit(1);
2268
- }
2662
+ if (forced && !["t3", "claude-code", "codex"].includes(forced))
2663
+ throw new ConnectFailure("bad_flag", "--driver is t3, claude-code, or codex.");
2664
+ const fallback = flag(argv, "--fallback-model");
2665
+ if (fallback !== void 0 && !MODEL_LIST.test(fallback))
2666
+ throw new ConnectFailure(
2667
+ "bad_flag",
2668
+ "--fallback-model takes model names, comma-separated, like opus or opus,sonnet."
2669
+ );
2269
2670
  const t3Url = (flag(argv, "--t3-url") ?? DEFAULT_T3_URL).replace(/\/+$/, "");
2270
2671
  const found = await detect({
2271
2672
  t3: () => forced && forced !== "t3" ? Promise.resolve(false) : t3Answers(t3Url),
2272
2673
  claude: () => probeClaude(),
2273
2674
  codex: () => probeCodex()
2274
2675
  });
2275
- const choice = chooseDriver(found, forced);
2276
- if (!choice.ok) {
2277
- out(`${red("\u2717")} ${choice.line}`);
2278
- process.exit(1);
2279
- }
2280
- if (choice.driver === "t3") await connectT3(argv);
2281
- else await connectLocal(choice.driver, found, argv);
2676
+ attempt.harnesses = harnessesFound(found);
2677
+ const workstation = isWorkstation(readRunnerConfig(), boxServiceInstalled());
2678
+ const choice = chooseDriver(found, forced, workstation);
2679
+ if (!choice.ok) throw new ConnectFailure(choice.code, choice.line);
2680
+ await connectChosen(choice.driver, attempt, {
2681
+ t3: () => connectT3(argv, attempt),
2682
+ local: (driver) => connectLocal(driver, found, argv, attempt),
2683
+ fallback: () => fallbackDriver(found, forced, workstation),
2684
+ say: (line2) => out(`${bold("Cloop runner")} ${line2}`)
2685
+ });
2686
+ }
2687
+ async function connectCommand(argv) {
2688
+ const attempt = newAttempt();
2689
+ let error = null;
2690
+ try {
2691
+ await connect(argv, attempt);
2692
+ } catch (err) {
2693
+ error = err instanceof ConnectFailure ? err.code : "unexpected";
2694
+ if (!(err instanceof ConnectFailure && err.shown))
2695
+ out(`${red("\u2717")} ${err instanceof Error ? err.message : String(err)}`);
2696
+ }
2697
+ await sendConnectReport(
2698
+ getOrigin(),
2699
+ connectReport(attempt, error, getMachine()),
2700
+ attempt.deviceToken
2701
+ );
2702
+ if (error) process.exit(1);
2282
2703
  }
2283
2704
 
2284
2705
  export {
2285
2706
  T3Client,
2286
2707
  runBoxTool,
2287
2708
  threadsFilePath,
2709
+ runnerStatePath,
2288
2710
  writeRunnerState,
2289
2711
  lockThreadsFile,
2290
2712
  BoxWatch,
2713
+ tokenGone,
2714
+ revokeOwnDevice,
2291
2715
  T3Driver,
2716
+ localRunsFilePath,
2292
2717
  LocalDriver,
2293
2718
  probeClaude,
2719
+ DEFAULT_FALLBACK_MODEL,
2294
2720
  claudeDialect,
2295
2721
  probeCodex,
2296
2722
  codexDialect,
2723
+ boxPath,
2297
2724
  isLocal,
2298
2725
  readRunnerConfig,
2299
2726
  writeBoxConfig,
2300
2727
  DEFAULT_T3_URL,
2301
- compareVersions,
2302
- resolveT3Bin,
2303
2728
  mintSession,
2304
2729
  connectBox,
2305
2730
  chooseDriver,
2731
+ fallbackDriver,
2732
+ isWorkstation,
2733
+ revokeReplaced,
2734
+ fallbackLine,
2735
+ connectChosen,
2306
2736
  systemdAssignment,
2307
2737
  systemdWord,
2308
2738
  programFor,
2309
2739
  awaitDaemon,
2310
2740
  unitEnv,
2741
+ installedService,
2311
2742
  unitFor,
2312
2743
  resolveRepos,
2313
- startService,
2744
+ findCheckouts,
2745
+ tilde,
2746
+ parsePicks,
2747
+ rerunCommand,
2748
+ notACheckoutLine,
2749
+ askRepos,
2750
+ askOrClosed,
2751
+ runSteps,
2314
2752
  detect,
2753
+ harnessesFound,
2315
2754
  connectCommand
2316
2755
  };