@cloop/runner 0.2.4 → 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-M6U2YVEB.js";
19
+ } from "./chunk-H7ZCXBNW.js";
17
20
  import {
18
21
  getMachine,
19
22
  shortMachineName
@@ -24,30 +27,30 @@ import {
24
27
  } from "./chunk-R3CLO2FB.js";
25
28
  import {
26
29
  connectWebhook
27
- } from "./chunk-KHYA7GEH.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-ZDUKQWKA.js";
37
+ } from "./chunk-2SZUL2B6.js";
35
38
  import {
36
39
  VERSION
37
- } from "./chunk-PBOQMFNN.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";
53
+ import { Writable } from "stream";
51
54
 
52
55
  // src/t3.ts
53
56
  var T3_SCOPE = "orchestration:read orchestration:operate";
@@ -68,7 +71,7 @@ async function exchangePairing(t3Url, credential, label, fetchFn = fetch) {
68
71
  client_device_type: "bot"
69
72
  });
70
73
  const res = await fetchFn(`${t3Url}/oauth/token`, { method: "POST", body: form });
71
- if (!res.ok) throw new Error(`T3 token exchange ${res.status}`);
74
+ if (!res.ok) throw new T3HttpError("token exchange", res.status);
72
75
  const token = await res.json();
73
76
  if (!sameScopes(token.scope, T3_SCOPE))
74
77
  throw new Error(`T3 granted scope "${token.scope}", wanted "${T3_SCOPE}"`);
@@ -269,7 +272,11 @@ function parseSendArgs(args) {
269
272
  };
270
273
  }
271
274
  var BOX_TOOLS = {
272
- 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
+ },
273
280
  "threads.list": ({ driver }, args) => driver.listThreads({
274
281
  scope: args.scope === "all" ? "all" : "unsettled",
275
282
  limit: typeof args.limit === "number" ? Math.min(Math.max(1, args.limit), 50) : 10
@@ -314,217 +321,6 @@ async function runBoxTool(ctx, tool, args) {
314
321
  }
315
322
  }
316
323
 
317
- // src/box-watch.ts
318
- import { randomUUID } from "crypto";
319
- import { chmodSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "fs";
320
- import { homedir } from "os";
321
- import { dirname, join } from "path";
322
- var KEEP_MS = 7 * 24 * 36e5;
323
- function threadsFilePath() {
324
- return process.env.CLOOP_BOX_THREADS_FILE ?? join(homedir(), CONFIG_DIR, "box-threads.json");
325
- }
326
- function runnerStatePath() {
327
- return join(dirname(threadsFilePath()), "runner-state.json");
328
- }
329
- function writeRunnerState(state, path = runnerStatePath()) {
330
- mkdirSync(dirname(path), { recursive: true, mode: 448 });
331
- const tmp = `${path}.tmp`;
332
- writeFileSync(tmp, `${JSON.stringify(state)}
333
- `, { mode: 384 });
334
- renameSync(tmp, path);
335
- }
336
- function readRunnerState(path = runnerStatePath()) {
337
- try {
338
- const raw = JSON.parse(readFileSync(path, "utf-8"));
339
- return typeof raw.pid === "number" && typeof raw.connected_at === "string" ? { pid: raw.pid, connected_at: raw.connected_at } : null;
340
- } catch {
341
- return null;
342
- }
343
- }
344
- function isAlive(pid) {
345
- try {
346
- process.kill(pid, 0);
347
- return true;
348
- } catch (err) {
349
- return err.code === "EPERM";
350
- }
351
- }
352
- function lockThreadsFile(file, pid = process.pid, alive = isAlive) {
353
- const lock = `${file}.lock`;
354
- mkdirSync(dirname(lock), { recursive: true, mode: 448 });
355
- for (let attempt = 0; attempt < 2; attempt++) {
356
- try {
357
- writeFileSync(lock, String(pid), { flag: "wx", mode: 384 });
358
- return {
359
- ok: true,
360
- release: () => {
361
- try {
362
- if (readFileSync(lock, "utf-8") === String(pid)) unlinkSync(lock);
363
- } catch {
364
- }
365
- }
366
- };
367
- } catch (err) {
368
- if (err.code !== "EEXIST") throw err;
369
- let held = 0;
370
- try {
371
- held = Number(readFileSync(lock, "utf-8").trim());
372
- } catch (readErr) {
373
- if (readErr.code !== "ENOENT") throw readErr;
374
- continue;
375
- }
376
- if (Number.isInteger(held) && held > 0 && held !== pid && alive(held)) {
377
- return { ok: false, heldBy: held };
378
- }
379
- try {
380
- unlinkSync(lock);
381
- } catch (unlinkErr) {
382
- if (unlinkErr.code !== "ENOENT") throw unlinkErr;
383
- }
384
- }
385
- }
386
- return { ok: false, heldBy: -1 };
387
- }
388
- var BoxWatch = class {
389
- constructor(deps) {
390
- this.deps = deps;
391
- this.entries = this.load();
392
- }
393
- deps;
394
- entries;
395
- live = /* @__PURE__ */ new Map();
396
- stopped = false;
397
- list() {
398
- return this.entries;
399
- }
400
- start() {
401
- for (const e of this.entries) if (!e.settled_at) this.watch(e);
402
- }
403
- add(workId, threadId) {
404
- if (this.entries.some((e) => e.work_id === workId)) return;
405
- const entry = {
406
- work_id: workId,
407
- thread_id: threadId,
408
- launched_at: new Date(this.now()).toISOString()
409
- };
410
- this.entries.push(entry);
411
- this.save();
412
- this.deps.log(`launch work=${workId} thread=${threadId}`);
413
- this.watch(entry);
414
- }
415
- resume(threadId) {
416
- const entry = this.entries.find((e) => e.thread_id === threadId);
417
- if (!entry?.settled_at) return;
418
- entry.settled_at = void 0;
419
- entry.event = void 0;
420
- entry.sent_at = void 0;
421
- this.save();
422
- this.watch(entry);
423
- }
424
- /** On every socket open and on a timer: send every event the mesh has not acked. */
425
- flush() {
426
- for (const e of this.entries) {
427
- for (const q of e.questions ?? []) if (!q.sent_at) this.trySend(e, q.event);
428
- if (e.event && !e.sent_at) this.trySend(e, e.event);
429
- }
430
- }
431
- /** `ok` false: the app refused the event for good (unknown work_id, bad frame), so it is not sent again either. */
432
- ack(eventId, ok = true) {
433
- for (const e of this.entries) {
434
- const held = [...e.questions ?? [], e].find((x) => x.event?.id === eventId && !x.sent_at);
435
- if (!held) continue;
436
- held.sent_at = new Date(this.now()).toISOString();
437
- this.save();
438
- this.deps.log(
439
- `event ${ok ? "acked" : "refused by the app"} work=${e.work_id} kind=${held.event?.kind}`
440
- );
441
- return;
442
- }
443
- }
444
- stop() {
445
- this.stopped = true;
446
- for (const unwatch of this.live.values()) unwatch();
447
- this.live.clear();
448
- }
449
- now() {
450
- return this.deps.now?.() ?? Date.now();
451
- }
452
- watch(e) {
453
- if (this.stopped || e.settled_at || this.live.has(e.work_id)) return;
454
- const unwatch = this.deps.watch(e.thread_id, (event) => this.onEvent(e, event));
455
- if (e.settled_at) unwatch();
456
- else this.live.set(e.work_id, unwatch);
457
- }
458
- onEvent(e, event) {
459
- if (e.settled_at) return;
460
- if (event.kind === "question") this.ask(e, event.question_id, event.summary);
461
- else if (event.kind === "progress") this.trySend(e, this.frame(e, event));
462
- else this.finish(e, event);
463
- }
464
- frame(e, event) {
465
- const { kind, summary } = event;
466
- return {
467
- type: "event",
468
- id: randomUUID(),
469
- work_id: e.work_id,
470
- thread_id: e.thread_id,
471
- kind,
472
- ...event.kind === "question" ? { question_id: event.question_id } : {},
473
- ...summary ? { summary: summary.slice(0, 500) } : {},
474
- ..."result" in event && event.result ? { result: event.result } : {},
475
- ..."pr_url" in event && event.pr_url ? { pr_url: event.pr_url } : {},
476
- ..."error" in event && event.error ? { error: event.error } : {},
477
- at: new Date(this.now()).toISOString()
478
- };
479
- }
480
- ask(e, questionId, summary) {
481
- if (e.questions?.some((x) => x.event.question_id === questionId)) return;
482
- const event = this.frame(e, { kind: "question", question_id: questionId, summary });
483
- e.questions = [...e.questions ?? [], { event }];
484
- this.save();
485
- this.deps.log(`question work=${e.work_id} thread=${e.thread_id}`);
486
- this.trySend(e, event);
487
- }
488
- finish(e, end) {
489
- this.live.get(e.work_id)?.();
490
- this.live.delete(e.work_id);
491
- e.event = this.frame(e, end);
492
- e.settled_at = e.event.at;
493
- this.save();
494
- this.deps.log(
495
- `settle work=${e.work_id} thread=${e.thread_id} kind=${end.kind} pr=${end.pr_url ? "yes" : "no"}`
496
- );
497
- this.trySend(e, e.event);
498
- }
499
- trySend(e, event) {
500
- const sent = this.deps.send(event);
501
- this.deps.log(
502
- `event ${sent ? "sent" : "held"} work=${e.work_id} kind=${event.kind}${sent ? "" : "; socket down"}`
503
- );
504
- }
505
- load() {
506
- let raw;
507
- try {
508
- raw = JSON.parse(readFileSync(this.deps.file, "utf-8"));
509
- } catch {
510
- return [];
511
- }
512
- if (!Array.isArray(raw)) return [];
513
- const cutoff = this.now() - KEEP_MS;
514
- return raw.filter(
515
- (e) => typeof e?.work_id === "string" && typeof e?.thread_id === "string" && !(e.settled_at && Date.parse(e.settled_at) < cutoff)
516
- );
517
- }
518
- save() {
519
- mkdirSync(dirname(this.deps.file), { recursive: true, mode: 448 });
520
- const tmp = `${this.deps.file}.tmp`;
521
- writeFileSync(tmp, `${JSON.stringify(this.entries, null, 2)}
522
- `, { mode: 384 });
523
- chmodSync(tmp, 384);
524
- renameSync(tmp, this.deps.file);
525
- }
526
- };
527
-
528
324
  // src/device-revoke.ts
529
325
  function tokenGone(revoke) {
530
326
  return revoke === "revoked" || revoke === "already_revoked" || revoke === "no_device";
@@ -938,6 +734,30 @@ function codexDialect(bin = "codex") {
938
734
  };
939
735
  }
940
736
 
737
+ // src/t3-pair-link.ts
738
+ var CODE = /^[A-Za-z0-9_-]{8,256}$/;
739
+ function tokenOf(url) {
740
+ const hash = new URLSearchParams(url.hash.replace(/^#/, "")).get("token")?.trim();
741
+ if (hash) return hash;
742
+ return url.searchParams.get("token")?.trim() || null;
743
+ }
744
+ function pairingCredential(input) {
745
+ const text = input.trim().replace(/^["'<]+|["'>]+$/g, "");
746
+ if (!text) return null;
747
+ if (/^[a-z][a-z\d+.-]*:\/\//i.test(text)) {
748
+ let url;
749
+ try {
750
+ url = new URL(text);
751
+ } catch {
752
+ return null;
753
+ }
754
+ if (!["http:", "https:", "ws:", "wss:"].includes(url.protocol)) return null;
755
+ const token = tokenOf(url);
756
+ return token && CODE.test(token) ? token : null;
757
+ }
758
+ return CODE.test(text) ? text : null;
759
+ }
760
+
941
761
  // src/commands/connect.ts
942
762
  var DEFAULT_T3_URL = "http://127.0.0.1:3773";
943
763
  var CLEAN_ENV = { HOME: process.env.HOME, USER: process.env.USER, PATH: process.env.PATH };
@@ -959,29 +779,20 @@ function which(bin) {
959
779
  return null;
960
780
  }
961
781
  }
962
- async function mintSession(t3Url, opts = {}) {
963
- const env = await readEnvironment(t3Url, opts.fetchFn);
782
+ var T3PairError = class extends Error {
783
+ name = "T3PairError";
784
+ };
785
+ async function workstationEnvironment(t3Url, fetchFn) {
786
+ const env = await readEnvironment(t3Url, fetchFn);
964
787
  const protocol = env.orchestrationProtocolVersion ?? 1;
965
788
  if (protocol < MIN_PROTOCOL) {
966
789
  throw new Error(
967
790
  `T3 ${env.serverVersion} speaks orchestration protocol ${protocol}; a workstation needs ${MIN_PROTOCOL} (the V2 nightly or later).`
968
791
  );
969
792
  }
970
- const sources = opts.sources ?? defaultT3BinSources(homedir2(), opts.stored);
971
- const t3Bin = opts.bin ?? pickT3Bin(t3Candidates(env.serverVersion, sources), env.serverVersion);
972
- if (!t3Bin) throw new Error("no t3 binary found; pass --t3-bin or set T3_BIN");
973
- const pairing = JSON.parse(
974
- runT3(t3Bin, [
975
- "auth",
976
- "pairing",
977
- "create",
978
- ...t3BaseDirArgs(sources.env),
979
- "--ttl",
980
- "5m",
981
- "--json"
982
- ])
983
- );
984
- const token = await exchangePairing(t3Url, pairing.credential, "cloop box", opts.fetchFn);
793
+ return env;
794
+ }
795
+ function boxSession(t3Url, t3Bin, env, token) {
985
796
  return {
986
797
  t3Url,
987
798
  t3Bin,
@@ -992,6 +803,75 @@ async function mintSession(t3Url, opts = {}) {
992
803
  label: env.label
993
804
  };
994
805
  }
806
+ async function mintSession(t3Url, opts = {}) {
807
+ const env = await workstationEnvironment(t3Url, opts.fetchFn);
808
+ const sources = opts.sources ?? defaultT3BinSources(homedir(), opts.stored);
809
+ try {
810
+ const t3Bin = opts.bin ?? pickT3Bin(t3Candidates(env.serverVersion, sources), env.serverVersion);
811
+ if (!t3Bin) throw new Error("no t3 binary found; pass --t3-bin or set T3_BIN");
812
+ const pairing = JSON.parse(
813
+ runT3(t3Bin, [
814
+ "auth",
815
+ "pairing",
816
+ "create",
817
+ ...t3BaseDirArgs(sources.env),
818
+ "--ttl",
819
+ "5m",
820
+ "--json"
821
+ ])
822
+ );
823
+ const token = await exchangePairing(t3Url, pairing.credential, "cloop box", opts.fetchFn);
824
+ return boxSession(t3Url, t3Bin, env, token);
825
+ } catch (err) {
826
+ throw new T3PairError(err instanceof Error ? err.message : String(err));
827
+ }
828
+ }
829
+ async function sessionFromLink(t3Url, link, fetchFn) {
830
+ const credential = pairingCredential(link);
831
+ if (!credential) throw new Error("that is not a T3 pairing link or code");
832
+ const env = await workstationEnvironment(t3Url, fetchFn);
833
+ let token;
834
+ try {
835
+ token = await exchangePairing(t3Url, credential, "cloop box", fetchFn);
836
+ } catch (err) {
837
+ const status = err instanceof T3HttpError ? err.status : null;
838
+ if (status === 401)
839
+ throw new Error(
840
+ "T3 refused the pairing link; a link works once and lasts 5 minutes, so create a new one"
841
+ );
842
+ if (status === 400)
843
+ throw new Error("T3 refused the pairing link; create one with the Standard permission");
844
+ throw err;
845
+ }
846
+ return boxSession(t3Url, "", env, token);
847
+ }
848
+ function pairPrompt(fallback) {
849
+ return `T3 Code is running, but this computer cannot pair with it automatically. In T3 Code, open Settings, then Connections, then Create pairing link. Copy the link and paste it here (or press Enter to ${fallback ? `use ${fallback} instead` : "stop"}): `;
850
+ }
851
+ async function pairT3(steps) {
852
+ if (steps.link !== void 0) return { session: await steps.fromLink(steps.link), byLink: true };
853
+ try {
854
+ return { session: await steps.mint(), byLink: false };
855
+ } catch (err) {
856
+ if (!(err instanceof T3PairError) || !steps.ask) throw err;
857
+ const answer = (await steps.ask(pairPrompt(steps.fallback)).catch(() => "")).trim();
858
+ if (!answer) throw new Error(`${err.message}; no pairing link given`);
859
+ return { session: await steps.fromLink(answer), byLink: true };
860
+ }
861
+ }
862
+ function askHidden(question, input = process.stdin, output = process.stdout) {
863
+ const muted = new Writable({ write: (_chunk, _encoding, done) => done() });
864
+ const prompt = createInterface({ input, output: muted, terminal: true });
865
+ output.write(`${question}
866
+ ${dim("(The link stays hidden while you paste it.)")} `);
867
+ return askOrClosed(
868
+ prompt,
869
+ () => new Error("closed")
870
+ )("").finally(() => {
871
+ prompt.close();
872
+ output.write("\n");
873
+ });
874
+ }
995
875
  async function connectBox(steps) {
996
876
  const environment = await steps.readEnvironment();
997
877
  const session = await steps.mintSession();
@@ -1032,6 +912,7 @@ var HARNESS_NAME = {
1032
912
  "claude-code": "Claude Code",
1033
913
  codex: "Codex"
1034
914
  };
915
+ var DRIVER_NAME = { t3: "T3 Code", ...HARNESS_NAME };
1035
916
  function fallbackDriver(found, forced, workstation) {
1036
917
  if (forced === "t3" || workstation) return null;
1037
918
  const choice = chooseDriver({ ...found, t3: false });
@@ -1045,7 +926,7 @@ function boxServiceInstalled() {
1045
926
  installedService({
1046
927
  platform: process.platform,
1047
928
  kind: "workstation",
1048
- home: homedir2(),
929
+ home: homedir(),
1049
930
  uid: process.getuid?.() ?? 0,
1050
931
  ...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
1051
932
  }).path
@@ -1063,7 +944,7 @@ async function revokeReplaced(previous, kind, revoke, say) {
1063
944
  );
1064
945
  }
1065
946
  function fallbackLine(reason, driver) {
1066
- 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>`;
947
+ return `T3 Code is running but would not pair (${reason}). Connecting ${HARNESS_NAME[driver]} instead. To use T3, create a pairing link in T3 Code (Settings, Connections) and run: cloop connect --t3-pair <link>`;
1067
948
  }
1068
949
  async function connectChosen(driver, attempt, run) {
1069
950
  attempt.driver = driver;
@@ -1123,14 +1004,14 @@ function installedService(opts) {
1123
1004
  if (opts.platform === "darwin") {
1124
1005
  const label = `com.cloop.${name}`;
1125
1006
  return {
1126
- path: join2(opts.dir ?? join2(opts.home, "Library", "LaunchAgents"), `${label}.plist`),
1007
+ path: join(opts.dir ?? join(opts.home, "Library", "LaunchAgents"), `${label}.plist`),
1127
1008
  steps: [{ command: ["launchctl", "bootout", `gui/${opts.uid}/${label}`], mayFail: true }],
1128
1009
  running: ["launchctl", "print", `gui/${opts.uid}/${label}`]
1129
1010
  };
1130
1011
  }
1131
1012
  const unit = `cloop-${name}.service`;
1132
1013
  return {
1133
- path: join2(opts.dir ?? join2(opts.home, ".config", "systemd", "user"), unit),
1014
+ path: join(opts.dir ?? join(opts.home, ".config", "systemd", "user"), unit),
1134
1015
  steps: [{ command: ["systemctl", "--user", "disable", "--now", unit], mayFail: true }],
1135
1016
  running: ["systemctl", "--user", "is-active", "--quiet", unit]
1136
1017
  };
@@ -1144,9 +1025,9 @@ function unitFor(opts) {
1144
1025
  });
1145
1026
  if (opts.platform === "darwin") {
1146
1027
  const label = `com.cloop.${name}`;
1147
- const agents = opts.dir ?? join2(opts.home, "Library", "LaunchAgents");
1148
- const path2 = join2(agents, `${label}.plist`);
1149
- 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`);
1150
1031
  const xml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1151
1032
  const contents2 = [
1152
1033
  '<?xml version="1.0" encoding="UTF-8"?>',
@@ -1183,8 +1064,8 @@ function unitFor(opts) {
1183
1064
  };
1184
1065
  }
1185
1066
  const unit = `cloop-${name}.service`;
1186
- const units = opts.dir ?? join2(opts.home, ".config", "systemd", "user");
1187
- const path = join2(units, unit);
1067
+ const units = opts.dir ?? join(opts.home, ".config", "systemd", "user");
1068
+ const path = join(units, unit);
1188
1069
  const contents = [
1189
1070
  "[Unit]",
1190
1071
  `Description=Cloop ${name}: answers the Cloop Agent over the mesh`,
@@ -1247,13 +1128,13 @@ function findCheckouts(home, limit = 8) {
1247
1128
  for (const root of CHECKOUT_ROOTS) {
1248
1129
  let entries;
1249
1130
  try {
1250
- entries = readdirSync(join2(home, root), { withFileTypes: true });
1131
+ entries = readdirSync(join(home, root), { withFileTypes: true });
1251
1132
  } catch {
1252
1133
  continue;
1253
1134
  }
1254
1135
  for (const entry of entries) {
1255
- const path = join2(home, root, entry.name);
1256
- 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;
1257
1138
  found.push({ repo: { label: entry.name, path }, at: lastCommitAt(path) });
1258
1139
  }
1259
1140
  }
@@ -1303,7 +1184,7 @@ async function reposFor(argv) {
1303
1184
  }
1304
1185
  const here = gitTop(process.cwd());
1305
1186
  if (here) return [{ label: basename3(here), path: here }];
1306
- const home = homedir2();
1187
+ const home = homedir();
1307
1188
  const found = findCheckouts(home);
1308
1189
  const rerun = rerunCommand(argv);
1309
1190
  if (!found.length || !process.stdin.isTTY || !process.stdout.isTTY)
@@ -1370,13 +1251,41 @@ async function runSteps(steps, run = (command) => void execFileSync(command[0],
1370
1251
  }
1371
1252
  }
1372
1253
  }
1373
- 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) {
1374
1283
  if (argv.includes("--no-service")) {
1375
1284
  out(` Run ${dim("cloop box run")} to go live.`);
1376
1285
  return;
1377
1286
  }
1378
1287
  attempt.step = "service_write";
1379
- const npxBeside = join2(dirname2(process.execPath), "npx");
1288
+ const npxBeside = join(dirname(process.execPath), "npx");
1380
1289
  const program = programFor(
1381
1290
  process.argv[1] ?? "cloop",
1382
1291
  process.execPath,
@@ -1385,16 +1294,16 @@ async function installService(kind, argv, attempt) {
1385
1294
  );
1386
1295
  if (typeof program === "string") throw new ConnectFailure("npx_missing", program);
1387
1296
  const unit = unitFor({
1388
- platform: process.platform,
1297
+ platform: services.platform,
1389
1298
  kind,
1390
- home: homedir2(),
1299
+ home: homedir(),
1391
1300
  program,
1392
1301
  env: unitEnv(process.env),
1393
1302
  uid: process.getuid?.() ?? 0,
1394
1303
  ...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
1395
1304
  });
1396
- mkdirSync2(join2(unit.path, ".."), { recursive: true });
1397
- writeFileSync2(unit.path, unit.contents);
1305
+ mkdirSync(join(unit.path, ".."), { recursive: true });
1306
+ writeFileSync(unit.path, unit.contents);
1398
1307
  if (argv.includes("--no-start")) {
1399
1308
  out(
1400
1309
  ` Service: wrote ${unit.path}. Start it with: ${dim(unit.start.map((step) => step.command.join(" ")).join(" && "))}`
@@ -1403,13 +1312,14 @@ async function installService(kind, argv, attempt) {
1403
1312
  }
1404
1313
  attempt.step = "service_start";
1405
1314
  const since = Date.now();
1315
+ const run = (command) => void services.run(command);
1406
1316
  try {
1407
1317
  if (existsSync(unit.retire.path)) {
1408
1318
  out(` This computer is one runner, so connect stops and removes ${unit.retire.path}.`);
1409
- await runSteps(unit.retire.steps);
1319
+ await runSteps(unit.retire.steps, run);
1410
1320
  rmSync(unit.retire.path, { force: true });
1411
1321
  }
1412
- await runSteps(unit.start);
1322
+ await runSteps(unit.start, run);
1413
1323
  } catch (err) {
1414
1324
  throw new ConnectFailure(
1415
1325
  "service_start_failed",
@@ -1417,28 +1327,46 @@ async function installService(kind, argv, attempt) {
1417
1327
  );
1418
1328
  }
1419
1329
  attempt.step = "first_connect";
1420
- if (!await awaitDaemon(since)) {
1330
+ if (!await services.awaitUp(since)) {
1421
1331
  out(
1422
1332
  `${red("\u2717")} ${unit.path} started, but the runner did not reach Cloop within 15 s. Its last log lines:`
1423
1333
  );
1424
1334
  try {
1425
- out(
1426
- execFileSync(unit.tail[0], unit.tail.slice(1), {
1427
- encoding: "utf-8",
1428
- timeout: 5e3
1429
- })
1430
- );
1335
+ out(services.run(unit.tail));
1431
1336
  } catch {
1432
1337
  out(` (no log yet; run ${unit.logs})`);
1433
1338
  }
1434
1339
  throw new ConnectFailure("first_connect_timeout", "the runner did not reach Cloop", true);
1435
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
+ }
1436
1357
  out(` Service: ${unit.path}, started and connected. Logs: ${dim(unit.logs)}`);
1437
1358
  }
1438
- async function connectT3(argv, attempt) {
1359
+ async function connectT3(argv, attempt, fallback, chosen, services) {
1439
1360
  const previous = readRunnerConfig();
1440
1361
  const t3Url = (flag(argv, "--t3-url") ?? DEFAULT_T3_URL).replace(/\/+$/, "");
1441
1362
  const t3Bin = flag(argv, "--t3-bin");
1363
+ const link = flag(argv, "--t3-pair");
1364
+ if (argv.includes("--t3-pair") && !link)
1365
+ throw new ConnectFailure(
1366
+ "bad_flag",
1367
+ "--t3-pair takes the pairing link from T3 Code (Settings, Connections)."
1368
+ );
1369
+ let byLink = false;
1442
1370
  const cfg = await connectBox({
1443
1371
  readEnvironment: async () => {
1444
1372
  const environment = await readEnvironment(t3Url);
@@ -1450,7 +1378,15 @@ async function connectT3(argv, attempt) {
1450
1378
  mintSession: async () => {
1451
1379
  attempt.step = "t3_pair";
1452
1380
  try {
1453
- return await mintSession(t3Url, t3Bin ? { bin: t3Bin } : {});
1381
+ const paired = await pairT3({
1382
+ ...link ? { link } : {},
1383
+ mint: () => mintSession(t3Url, t3Bin ? { bin: t3Bin } : {}),
1384
+ fromLink: (pasted) => sessionFromLink(t3Url, pasted),
1385
+ ask: process.stdin.isTTY && process.stdout.isTTY ? (q) => askHidden(q) : null,
1386
+ fallback
1387
+ });
1388
+ byLink = paired.byLink;
1389
+ return paired.session;
1454
1390
  } catch (err) {
1455
1391
  throw new ConnectFailure(
1456
1392
  "t3_pair_failed",
@@ -1475,13 +1411,18 @@ async function connectT3(argv, attempt) {
1475
1411
  writeBoxConfig: (cfg2) => writeBoxConfig({
1476
1412
  ...cfg2,
1477
1413
  origin: getOrigin(),
1478
- showOtherThreads: argv.includes("--show-other-threads")
1414
+ showOtherThreads: argv.includes("--show-other-threads"),
1415
+ ...chosen ? { chosenDriver: chosen } : {}
1479
1416
  })
1480
1417
  });
1481
1418
  await revokeReplaced(previous, "workstation", (t) => revokeOwnDevice(getOrigin(), t), out);
1482
1419
  out(
1483
1420
  `${bold("Cloop runner")} T3 ${cfg.label} paired with scope ${cfg.scope}, until ${cfg.expiresAt.slice(0, 10)}.`
1484
1421
  );
1422
+ if (byLink)
1423
+ out(
1424
+ ` Paired with a link from T3 Code. This session cannot renew itself: before ${cfg.expiresAt.slice(0, 10)}, run cloop connect again with a new link.`
1425
+ );
1485
1426
  const driver = new T3Driver({
1486
1427
  client: () => new T3Client(cfg.t3Url, cfg.token),
1487
1428
  t3Bin: cfg.t3Bin
@@ -1496,9 +1437,9 @@ async function connectT3(argv, attempt) {
1496
1437
  } else {
1497
1438
  out(`${red("\u2717")} Status failed: ${report.error}`);
1498
1439
  }
1499
- await installService("workstation", argv, attempt);
1440
+ await installService("workstation", argv, attempt, services);
1500
1441
  }
1501
- async function connectLocal(driver, found, argv, attempt) {
1442
+ async function connectLocal(driver, found, argv, attempt, chosen, services) {
1502
1443
  attempt.step = "repos";
1503
1444
  const repos = await reposFor(argv);
1504
1445
  const harness = driver === "claude-code" ? found.claude : found.codex;
@@ -1508,7 +1449,7 @@ async function connectLocal(driver, found, argv, attempt) {
1508
1449
  const fallbackModels = driver === "claude-code" ? flag(argv, "--fallback-model") ?? (previous && isLocal(previous) ? previous.fallbackModels : void 0) ?? DEFAULT_FALLBACK_MODEL : void 0;
1509
1450
  const device = {
1510
1451
  kind: "local",
1511
- environmentId: previous && isLocal(previous) ? previous.environmentId : `local:${randomUUID2()}`,
1452
+ environmentId: previous && isLocal(previous) ? previous.environmentId : `local:${randomUUID()}`,
1512
1453
  label: deviceName,
1513
1454
  version: `${harness.name} ${harness.version ?? ""}`.trim()
1514
1455
  };
@@ -1528,7 +1469,8 @@ async function connectLocal(driver, found, argv, attempt) {
1528
1469
  bin,
1529
1470
  origin: getOrigin(),
1530
1471
  ...fallbackModels ? { fallbackModels } : {},
1531
- ...driver === "claude-code" ? { askEverything: argv.includes("--ask-everything") } : {}
1472
+ ...driver === "claude-code" ? { askEverything: argv.includes("--ask-everything") } : {},
1473
+ ...chosen ? { chosenDriver: chosen } : {}
1532
1474
  };
1533
1475
  writeBoxConfig(cfg);
1534
1476
  await revokeReplaced(previous, "local", (t) => revokeOwnDevice(getOrigin(), t), out);
@@ -1546,7 +1488,7 @@ async function connectLocal(driver, found, argv, attempt) {
1546
1488
  out(
1547
1489
  ` Fallback model: ${fallbackModels}, when Claude Code's default model is at its limit. Change it with --fallback-model.`
1548
1490
  );
1549
- await installService("local", argv, attempt);
1491
+ await installService("local", argv, attempt, services);
1550
1492
  }
1551
1493
  async function detect(probes) {
1552
1494
  const [t3, claude, codex] = await Promise.all([probes.t3(), probes.claude(), probes.codex()]);
@@ -1560,14 +1502,25 @@ function harnessesFound(found) {
1560
1502
  ];
1561
1503
  }
1562
1504
  var MODEL_LIST = /^[A-Za-z0-9][\w.:[\]-]*(,[A-Za-z0-9][\w.:[\]-]*)*$/;
1563
- 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 = {}) {
1564
1511
  if (argv.some((arg) => arg === "--webhook" || arg.startsWith("--webhook="))) {
1565
1512
  await connectWebhook(argv, attempt);
1566
1513
  return;
1567
1514
  }
1568
- const forced = flag(argv, "--driver") ?? process.env.CLOOP_DRIVER;
1569
- 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))
1570
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
+ );
1571
1524
  const fallback = flag(argv, "--fallback-model");
1572
1525
  if (fallback !== void 0 && !MODEL_LIST.test(fallback))
1573
1526
  throw new ConnectFailure(
@@ -1575,27 +1528,30 @@ async function connect(argv, attempt) {
1575
1528
  "--fallback-model takes model names, comma-separated, like opus or opus,sonnet."
1576
1529
  );
1577
1530
  const t3Url = (flag(argv, "--t3-url") ?? DEFAULT_T3_URL).replace(/\/+$/, "");
1578
- const found = await detect({
1579
- t3: () => forced && forced !== "t3" ? Promise.resolve(false) : t3Answers(t3Url),
1580
- claude: () => probeClaude(),
1581
- codex: () => probeCodex()
1582
- });
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
+ );
1583
1538
  attempt.harnesses = harnessesFound(found);
1584
- const workstation = isWorkstation(readRunnerConfig(), boxServiceInstalled());
1539
+ const workstation = isWorkstation(previous, boxServiceInstalled());
1585
1540
  const choice = chooseDriver(found, forced, workstation);
1586
1541
  if (!choice.ok) throw new ConnectFailure(choice.code, choice.line);
1542
+ const local = fallbackDriver(found, forced, workstation);
1587
1543
  await connectChosen(choice.driver, attempt, {
1588
- t3: () => connectT3(argv, attempt),
1589
- 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),
1590
1546
  fallback: () => fallbackDriver(found, forced, workstation),
1591
1547
  say: (line2) => out(`${bold("Cloop runner")} ${line2}`)
1592
1548
  });
1593
1549
  }
1594
- async function connectCommand(argv) {
1550
+ async function runConnect(argv, deps = {}) {
1595
1551
  const attempt = newAttempt();
1596
1552
  let error = null;
1597
1553
  try {
1598
- await connect(argv, attempt);
1554
+ await connect(argv, attempt, deps);
1599
1555
  } catch (err) {
1600
1556
  error = err instanceof ConnectFailure ? err.code : "unexpected";
1601
1557
  if (!(err instanceof ConnectFailure && err.shown))
@@ -1606,17 +1562,15 @@ async function connectCommand(argv) {
1606
1562
  connectReport(attempt, error, getMachine()),
1607
1563
  attempt.deviceToken
1608
1564
  );
1609
- if (error) process.exit(1);
1565
+ return error;
1566
+ }
1567
+ async function connectCommand(argv) {
1568
+ if (await runConnect(argv)) process.exit(1);
1610
1569
  }
1611
1570
 
1612
1571
  export {
1613
1572
  T3Client,
1614
1573
  runBoxTool,
1615
- threadsFilePath,
1616
- runnerStatePath,
1617
- writeRunnerState,
1618
- lockThreadsFile,
1619
- BoxWatch,
1620
1574
  tokenGone,
1621
1575
  revokeOwnDevice,
1622
1576
  probeClaudePermissions,
@@ -1626,9 +1580,15 @@ export {
1626
1580
  probeCodex,
1627
1581
  codexDialect,
1628
1582
  DEFAULT_T3_URL,
1583
+ T3PairError,
1629
1584
  mintSession,
1585
+ sessionFromLink,
1586
+ pairPrompt,
1587
+ pairT3,
1588
+ askHidden,
1630
1589
  connectBox,
1631
1590
  chooseDriver,
1591
+ DRIVER_NAME,
1632
1592
  fallbackDriver,
1633
1593
  isWorkstation,
1634
1594
  revokeReplaced,
@@ -1650,7 +1610,11 @@ export {
1650
1610
  askRepos,
1651
1611
  askOrClosed,
1652
1612
  runSteps,
1613
+ systemServices,
1614
+ ensureLinger,
1653
1615
  detect,
1654
1616
  harnessesFound,
1617
+ rememberedDriver,
1618
+ runConnect,
1655
1619
  connectCommand
1656
1620
  };