@cloop/runner 0.3.8 → 0.3.10

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.
Files changed (32) hide show
  1. package/dist/{box-HUVPOJZK.js → box-4DQFGS7E.js} +78 -46
  2. package/dist/{chunk-5FZAHWPX.js → chunk-6QXNXJ7C.js} +1 -1
  3. package/dist/{chunk-IKCGVBHA.js → chunk-D5UZW42X.js} +1 -0
  4. package/dist/{chunk-NYGELUTR.js → chunk-ES5BRAKJ.js} +1 -1
  5. package/dist/{chunk-E5CKL2Q3.js → chunk-EVIVOEJY.js} +1 -1
  6. package/dist/{chunk-ZILLDYL4.js → chunk-IJH4O27H.js} +8 -1
  7. package/dist/{chunk-3WD7S6VI.js → chunk-LPEDYXWI.js} +132 -73
  8. package/dist/{chunk-4MM5O7TV.js → chunk-NNVHI2C4.js} +1 -1
  9. package/dist/{chunk-NUU4GXGV.js → chunk-NTXQLEMQ.js} +1 -1
  10. package/dist/{chunk-EQTFHMUJ.js → chunk-UAMXZ6YX.js} +11 -10
  11. package/dist/{chunk-OODVBR3F.js → chunk-UST7TWCL.js} +3 -3
  12. package/dist/{chunk-3IP5XIPV.js → chunk-VVKUUNUJ.js} +4 -4
  13. package/dist/{chunk-GUPXSBOJ.js → chunk-W2BHZLOG.js} +355 -229
  14. package/dist/{chunk-WE4KRF7A.js → chunk-X4KNL76Q.js} +3 -3
  15. package/dist/{chunk-3TDL6X5T.js → chunk-XPWFSXPS.js} +1 -1
  16. package/dist/{connect-YJA2CS6L.js → connect-TH2W7C7U.js} +12 -10
  17. package/dist/disconnect-JDBXNTQP.js +30 -0
  18. package/dist/existing-runner-Z3GFUJXD.js +20 -0
  19. package/dist/{hook-activity-I7TV7YG7.js → hook-activity-GAJ5NABA.js} +4 -4
  20. package/dist/{hook-session-start-MFX6HR3W.js → hook-session-start-DJ6W2NCO.js} +3 -3
  21. package/dist/index.js +29 -19
  22. package/dist/{install-EMEZBBK7.js → install-WXKWNTAO.js} +1 -1
  23. package/dist/{login-RAZOAK6J.js → login-6UZCLDYL.js} +4 -4
  24. package/dist/{mcp-server-673BK6ER.js → mcp-server-RWLW6SJI.js} +13 -13
  25. package/dist/runner-TPPZAOE5.js +13 -0
  26. package/dist/{runs-RZL34AFT.js → runs-5UEAFWLJ.js} +3 -3
  27. package/dist/{statusline-KIE2H6EM.js → statusline-MITA5QJF.js} +3 -3
  28. package/dist/{takeover-V2IHVUAB.js → takeover-Z365HOFM.js} +7 -7
  29. package/dist/{use-ZP4SPNI6.js → use-JKRWT2TU.js} +15 -16
  30. package/package.json +1 -1
  31. package/dist/disconnect-S4GR7LCM.js +0 -28
  32. package/dist/runner-NZRNAFEP.js +0 -13
@@ -3,15 +3,18 @@ import {
3
3
  readRunnerState,
4
4
  runnerStatePath,
5
5
  threadsFilePath
6
- } from "./chunk-EQTFHMUJ.js";
6
+ } from "./chunk-UAMXZ6YX.js";
7
7
  import {
8
8
  BoxToolError,
9
9
  CLOOP_THREAD_PREFIX,
10
+ ENVIRONMENTS,
10
11
  RUNTIME_MODES,
11
12
  T3Driver,
12
13
  boxPath,
14
+ cloopCommand,
13
15
  commandFor,
14
16
  defaultT3BinSources,
17
+ environmentOf,
15
18
  isLocal,
16
19
  isYes,
17
20
  localRunsFilePath,
@@ -20,83 +23,59 @@ import {
20
23
  questionLine,
21
24
  readRunnerConfig,
22
25
  runT3,
26
+ runnerDir,
27
+ runnerEnvironment,
28
+ serviceIdentity,
23
29
  t3BaseDirArgs,
24
30
  t3Candidates,
25
31
  writeBoxConfig
26
- } from "./chunk-3WD7S6VI.js";
32
+ } from "./chunk-LPEDYXWI.js";
33
+ import {
34
+ getMachine,
35
+ shortMachineName
36
+ } from "./chunk-NTXQLEMQ.js";
27
37
  import {
28
38
  CLAUDE_FLOOR,
29
39
  claudeTooOld,
30
40
  olderThan
31
41
  } from "./chunk-UBXT5IDU.js";
32
- import {
33
- getMachine,
34
- shortMachineName
35
- } from "./chunk-NUU4GXGV.js";
36
42
  import {
37
43
  READ_TOOLS,
38
44
  readOnlySettings
39
45
  } from "./chunk-R3CLO2FB.js";
40
46
  import {
41
47
  connectWebhook
42
- } from "./chunk-OODVBR3F.js";
48
+ } from "./chunk-UST7TWCL.js";
43
49
  import {
44
50
  ConnectFailure,
45
51
  connectReport,
46
52
  deviceLogin,
47
53
  newAttempt,
48
54
  sendConnectReport
49
- } from "./chunk-WE4KRF7A.js";
55
+ } from "./chunk-X4KNL76Q.js";
50
56
  import {
51
57
  VERSION
52
- } from "./chunk-4MM5O7TV.js";
58
+ } from "./chunk-NNVHI2C4.js";
53
59
  import {
54
60
  STAGING_ORIGIN,
55
61
  getOrigin,
56
62
  pinRunnerEnvironment,
57
63
  pinnedOriginSource
58
- } from "./chunk-IKCGVBHA.js";
59
-
60
- // src/commands/disconnect.ts
61
- import { execFileSync as execFileSync2 } from "child_process";
62
- import { existsSync as existsSync2, readFileSync, rmSync as rmSync2 } from "fs";
63
- import { homedir as homedir2 } from "os";
64
-
65
- // src/device-revoke.ts
66
- function tokenGone(revoke) {
67
- return revoke === "revoked" || revoke === "already_revoked" || revoke === "no_device";
68
- }
69
- async function revokeOwnDevice(origin, deviceToken, fetchFn = fetch) {
70
- if (!deviceToken) return "no_device";
71
- try {
72
- const res = await fetchFn(`${origin}/api/agent/mesh/device-revoke`, {
73
- method: "POST",
74
- headers: { authorization: `Bearer ${deviceToken}` },
75
- signal: AbortSignal.timeout(1e4)
76
- });
77
- const body = await res.json().catch(() => null);
78
- if (res.ok && body?.outcome === "revoked") return "revoked";
79
- if (res.ok && body?.outcome === "already_revoked") return "already_revoked";
80
- if (res.status === 401 && body?.error === "unknown_device") return "unknown_device";
81
- return "failed";
82
- } catch {
83
- return "failed";
84
- }
85
- }
64
+ } from "./chunk-D5UZW42X.js";
86
65
 
87
66
  // src/commands/connect.ts
88
- import { execFileSync } from "child_process";
67
+ import { execFileSync as execFileSync2 } from "child_process";
89
68
  import { randomUUID } from "crypto";
90
69
  import {
91
- existsSync,
92
- mkdirSync,
70
+ existsSync as existsSync4,
71
+ mkdirSync as mkdirSync2,
93
72
  readdirSync,
94
- rmSync,
73
+ rmSync as rmSync3,
95
74
  statSync,
96
75
  writeFileSync
97
76
  } from "fs";
98
- import { homedir, userInfo } from "os";
99
- import { basename as basename3, dirname, join, resolve as resolve2 } from "path";
77
+ import { homedir as homedir3, userInfo } from "os";
78
+ import { basename as basename4, dirname, join as join2, resolve as resolve2 } from "path";
100
79
  import { createInterface } from "readline/promises";
101
80
  import { Writable } from "stream";
102
81
 
@@ -369,6 +348,28 @@ async function runBoxTool(ctx, tool, args) {
369
348
  }
370
349
  }
371
350
 
351
+ // src/device-revoke.ts
352
+ function tokenGone(revoke) {
353
+ return revoke === "revoked" || revoke === "already_revoked" || revoke === "no_device";
354
+ }
355
+ async function revokeOwnDevice(origin, deviceToken, fetchFn = fetch) {
356
+ if (!deviceToken) return "no_device";
357
+ try {
358
+ const res = await fetchFn(`${origin}/api/agent/mesh/device-revoke`, {
359
+ method: "POST",
360
+ headers: { authorization: `Bearer ${deviceToken}` },
361
+ signal: AbortSignal.timeout(1e4)
362
+ });
363
+ const body = await res.json().catch(() => null);
364
+ if (res.ok && body?.outcome === "revoked") return "revoked";
365
+ if (res.ok && body?.outcome === "already_revoked") return "already_revoked";
366
+ if (res.status === 401 && body?.error === "unknown_device") return "unknown_device";
367
+ return "failed";
368
+ } catch {
369
+ return "failed";
370
+ }
371
+ }
372
+
372
373
  // src/drivers/claude-code.ts
373
374
  import { execFile } from "child_process";
374
375
  import { basename, isAbsolute, relative, resolve } from "path";
@@ -756,6 +757,235 @@ function codexDialect(bin = "codex") {
756
757
  };
757
758
  }
758
759
 
760
+ // src/legacy-staging.ts
761
+ import { existsSync as existsSync3, mkdirSync, renameSync, rmSync as rmSync2 } from "fs";
762
+ import { homedir as homedir2 } from "os";
763
+ import { join } from "path";
764
+
765
+ // src/commands/disconnect.ts
766
+ import { execFileSync } from "child_process";
767
+ import { existsSync as existsSync2, readFileSync, rmSync } from "fs";
768
+ import { homedir } from "os";
769
+ import { basename as basename3 } from "path";
770
+
771
+ // src/existing-runner.ts
772
+ import { existsSync } from "fs";
773
+ var ALL = Object.keys(ENVIRONMENTS);
774
+ function runnersOnThisComputer() {
775
+ if (legacyStagingRunner()) return ["staging"];
776
+ return ALL.filter((env) => existsSync(boxPath(env)));
777
+ }
778
+ function existingRunnerEnvironment() {
779
+ const named = process.env.CLOOP_ORIGIN;
780
+ if (named) return environmentOf(named);
781
+ const found = runnersOnThisComputer();
782
+ return found.length === 1 && found[0] ? found[0] : "production";
783
+ }
784
+ var BOTH_RUNNERS_LINE = "This computer has a production runner and a staging runner. This acts on the production runner. Add --staging for the staging runner.";
785
+ function pinExistingRunner() {
786
+ const named = Boolean(process.env.CLOOP_ORIGIN);
787
+ const environment = existingRunnerEnvironment();
788
+ pinRunnerEnvironment(runnerOrigin(environment) ?? ENVIRONMENTS[environment].origin);
789
+ return {
790
+ environment: runnerEnvironment(),
791
+ note: !named && runnersOnThisComputer().length === ALL.length ? BOTH_RUNNERS_LINE : null
792
+ };
793
+ }
794
+
795
+ // src/commands/disconnect.ts
796
+ function doneLine(env) {
797
+ return `This computer is no longer a ${env} Cloop runner. To connect it again: ${["npx -y @cloop/runner@latest connect", ENVIRONMENTS[env].flag].filter(Boolean).join(" ")}`;
798
+ }
799
+ function unitOrigin(contents) {
800
+ const plist = /<key>CLOOP_ORIGIN<\/key><string>([^<]+)<\/string>/.exec(contents)?.[1];
801
+ if (plist) return plist.replace(/&amp;/g, "&");
802
+ const unit = /Environment="CLOOP_ORIGIN=([^"]+)"/.exec(contents)?.[1];
803
+ if (unit) return unit.replace(/%%/g, "%");
804
+ const launcher = /^set "CLOOP_ORIGIN=(.+)"\r?$/m.exec(contents)?.[1];
805
+ return launcher ? launcher.replace(/%%/g, "%") : null;
806
+ }
807
+ function disconnectPlan(opts) {
808
+ const exists = opts.exists ?? existsSync2;
809
+ const read = opts.read ?? ((path) => readFileSync(path, "utf-8"));
810
+ const installed = ["local", "workstation"].map((kind) => ({ kind, service: installedService({ ...opts, kind }) })).filter(({ service }) => exists(service.path));
811
+ const services = installed.map(({ service }) => service);
812
+ const fromUnit = services.map((service) => {
813
+ try {
814
+ return unitOrigin(read(service.path));
815
+ } catch {
816
+ return null;
817
+ }
818
+ }).find(Boolean);
819
+ return {
820
+ origin: opts.boxOrigin ?? fromUnit ?? opts.fallbackOrigin,
821
+ deviceToken: opts.deviceToken,
822
+ services,
823
+ box: exists(opts.box) ? opts.box : null,
824
+ files: opts.files.filter((file) => exists(file)),
825
+ isBox: opts.platform !== "darwin" && opts.platform !== "win32" && installed.some(({ kind }) => kind === "workstation")
826
+ };
827
+ }
828
+ async function stopService(service, run, waitMs = 1e4) {
829
+ await runSteps(service.steps, run);
830
+ const until = Date.now() + waitMs;
831
+ for (; ; ) {
832
+ try {
833
+ run(service.running);
834
+ } catch {
835
+ return true;
836
+ }
837
+ if (Date.now() >= until) return false;
838
+ await new Promise((resolve3) => setTimeout(resolve3, 250));
839
+ }
840
+ }
841
+ function revokeLine(revoke, origin, box) {
842
+ const env = environmentOf(origin);
843
+ const keep = box ? ` Kept ${box}, which holds the device token, so you can try again.` : "";
844
+ switch (revoke) {
845
+ case "revoked":
846
+ return [`Revoked this computer on Cloop (${origin}).`];
847
+ case "already_revoked":
848
+ return [`Cloop (${origin}) had already revoked this computer.`];
849
+ case "no_device":
850
+ return ["No runner device on this computer to revoke."];
851
+ case "unknown_device":
852
+ return [
853
+ `Cloop at ${origin} never issued this computer's device token, so it belongs to the other environment.${keep}`,
854
+ "Run `cloop disconnect --staging` for a staging runner, or `cloop disconnect` for production."
855
+ ];
856
+ case "failed":
857
+ return [
858
+ `Could not revoke this computer at ${origin}: Cloop did not answer as expected.${keep}`,
859
+ `Run \`${cloopCommand(env, "disconnect")}\` again when Cloop answers, or press Disconnect on its card on the Threads page and then delete that file.`
860
+ ];
861
+ }
862
+ }
863
+ async function disconnect(plan, opts) {
864
+ const { say } = opts;
865
+ const env = environmentOf(plan.origin);
866
+ const run = opts.run ?? ((command) => void execFileSync(command[0], command.slice(1), {
867
+ stdio: "ignore",
868
+ timeout: 15e3
869
+ }));
870
+ if (plan.isBox && !opts.yes) {
871
+ const unit = plan.services.map((s) => basename3(s.path)).find((n) => n.startsWith("cloop-box"));
872
+ say(`This computer runs ${unit}, the ${env} Cloop box with T3 Code. Disconnect would:`);
873
+ for (const s of plan.services) say(` stop and remove ${s.path}`);
874
+ if (plan.deviceToken) say(` revoke its runner device on Cloop (${plan.origin})`);
875
+ for (const f of [...plan.box ? [plan.box] : [], ...plan.files]) say(` delete ${f}`);
876
+ say(`Run \`${cloopCommand(env, "disconnect --yes")}\` to do this.`);
877
+ return 1;
878
+ }
879
+ for (const service of plan.services) {
880
+ if (!await stopService(service, run, opts.stopWaitMs)) {
881
+ say(
882
+ `Could not stop the service in ${service.path}. Nothing was removed. Stop it with \`${service.steps.map((s) => s.command.join(" ")).join(" && ")}\`, then run \`${cloopCommand(env, "disconnect")}\` again.`
883
+ );
884
+ return 1;
885
+ }
886
+ say(`Stopped the service in ${service.path}`);
887
+ }
888
+ const revoked = await opts.revoke(plan.origin, plan.deviceToken);
889
+ const gone = tokenGone(revoked);
890
+ for (const service of plan.services) {
891
+ rmSync(service.path, { force: true });
892
+ say(`Removed ${service.path}`);
893
+ }
894
+ for (const file of [...gone && plan.box ? [plan.box] : [], ...plan.files]) {
895
+ rmSync(file, { force: true });
896
+ say(`Deleted ${file}`);
897
+ }
898
+ for (const line2 of revokeLine(revoked, plan.origin, plan.box)) say(line2);
899
+ if (!gone) return 1;
900
+ say(doneLine(env));
901
+ return 0;
902
+ }
903
+ function runnerOrigin(env) {
904
+ return disconnectPlan(thisComputer(env, "")).origin || void 0;
905
+ }
906
+ function thisComputer(env, fallbackOrigin) {
907
+ const cfg = readRunnerConfig(env);
908
+ return {
909
+ platform: process.platform,
910
+ environment: env,
911
+ home: homedir(),
912
+ uid: process.getuid?.() ?? 0,
913
+ ...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {},
914
+ box: boxPath(env),
915
+ deviceToken: cfg?.deviceToken ?? null,
916
+ ...cfg?.origin ? { boxOrigin: cfg.origin } : {},
917
+ fallbackOrigin,
918
+ files: [localRunsFilePath(env), runnerStatePath(env), threadsFilePath(env)]
919
+ };
920
+ }
921
+ async function disconnectCommand(argv) {
922
+ const { environment, note } = pinExistingRunner();
923
+ if (note) console.log(note);
924
+ const plan = disconnectPlan(
925
+ thisComputer(legacyStagingRunner() ? "production" : environment, getOrigin())
926
+ );
927
+ process.exitCode = await disconnect(plan, {
928
+ yes: argv.includes("--yes"),
929
+ revoke: (origin, token) => revokeOwnDevice(origin, token),
930
+ say: (line2) => console.log(line2)
931
+ });
932
+ }
933
+
934
+ // src/legacy-staging.ts
935
+ var MOVED = [
936
+ "box-threads.json",
937
+ "runner-state.json",
938
+ "local-runs.json",
939
+ "runs",
940
+ "takeover",
941
+ "update.json",
942
+ "update.log",
943
+ "box.json"
944
+ ];
945
+ function legacyStagingRunner() {
946
+ if (existsSync3(boxPath("staging"))) return false;
947
+ const origin = runnerOrigin("production");
948
+ return origin !== void 0 && environmentOf(origin) === "staging";
949
+ }
950
+ function moveRunnerFiles(from, to) {
951
+ mkdirSync(to, { recursive: true, mode: 448 });
952
+ for (const name of MOVED) {
953
+ const source = join(from, name);
954
+ const target = join(to, name);
955
+ if (existsSync3(source) && !existsSync3(target)) renameSync(source, target);
956
+ }
957
+ }
958
+ function legacyServices(platform) {
959
+ return ["local", "workstation"].map(
960
+ (kind) => installedService({
961
+ platform,
962
+ kind,
963
+ environment: "production",
964
+ home: homedir2(),
965
+ uid: process.getuid?.() ?? 0,
966
+ ...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
967
+ })
968
+ ).filter((service) => existsSync3(service.path));
969
+ }
970
+ async function moveLegacyStagingRunner(services) {
971
+ if (!legacyStagingRunner()) return false;
972
+ const run = (command) => void services.run(command);
973
+ const units = legacyServices(services.platform);
974
+ for (const unit of units)
975
+ if (!await stopService(unit, run))
976
+ throw new Error(
977
+ `Could not stop the staging runner in ${unit.path}. Stop it with \`${unit.steps.map((s) => s.command.join(" ")).join(" && ")}\`, then run this again.`
978
+ );
979
+ for (const unit of units) rmSync2(unit.path, { force: true });
980
+ moveRunnerFiles(runnerDir("production"), runnerDir("staging"));
981
+ console.error("[runner:environment] moved staging runner from ~/.cloop to ~/.cloop/staging");
982
+ return true;
983
+ }
984
+ function movedLine(connecting) {
985
+ const line2 = "Moved the staging runner from ~/.cloop to ~/.cloop/staging, so a production runner can run beside it.";
986
+ return connecting === "staging" ? line2 : `${line2} It is stopped. Start it again with: cloop connect --staging`;
987
+ }
988
+
759
989
  // src/t3-pair-link.ts
760
990
  var CODE = /^[A-Za-z0-9_-]{8,256}$/;
761
991
  function tokenOf(url) {
@@ -799,14 +1029,14 @@ function which(bin) {
799
1029
  }
800
1030
  function whichPosix(bin) {
801
1031
  try {
802
- return execFileSync("which", [bin], { encoding: "utf-8", env: CLEAN_ENV }).trim() || null;
1032
+ return execFileSync2("which", [bin], { encoding: "utf-8", env: CLEAN_ENV }).trim() || null;
803
1033
  } catch {
804
1034
  return null;
805
1035
  }
806
1036
  }
807
1037
  function where(bin) {
808
1038
  try {
809
- const found = execFileSync("where", [bin], {
1039
+ const found = execFileSync2("where", [bin], {
810
1040
  encoding: "utf-8",
811
1041
  // `where` matches extensions through PATHEXT, which CLEAN_ENV alone drops.
812
1042
  env: { ...CLEAN_ENV, PATHEXT: process.env.PATHEXT, SystemRoot: process.env.SystemRoot }
@@ -847,7 +1077,7 @@ function boxSession(t3Url, t3Bin, env, token) {
847
1077
  }
848
1078
  async function mintSession(t3Url, opts = {}) {
849
1079
  const env = await workstationEnvironment(t3Url, opts.fetchFn);
850
- const sources = opts.sources ?? defaultT3BinSources(homedir(), opts.stored);
1080
+ const sources = opts.sources ?? defaultT3BinSources(homedir3(), opts.stored);
851
1081
  try {
852
1082
  const t3Bin = opts.bin ?? pickT3Bin(t3Candidates(env.serverVersion, sources), env.serverVersion);
853
1083
  if (!t3Bin) throw new Error("no t3 binary found; pass --t3-bin or set T3_BIN");
@@ -964,11 +1194,12 @@ function isWorkstation(previous, boxServiceInstalled2) {
964
1194
  return boxServiceInstalled2 || Boolean(previous && !isLocal(previous));
965
1195
  }
966
1196
  function boxServiceInstalled() {
967
- return existsSync(
1197
+ return existsSync4(
968
1198
  installedService({
969
1199
  platform: process.platform,
970
1200
  kind: "workstation",
971
- home: homedir(),
1201
+ environment: runnerEnvironment(),
1202
+ home: homedir3(),
972
1203
  uid: process.getuid?.() ?? 0,
973
1204
  ...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
974
1205
  }).path
@@ -1024,8 +1255,8 @@ function programFor(script, node, npx, version) {
1024
1255
  }
1025
1256
  function findNpx() {
1026
1257
  const name = process.platform === "win32" ? "npx.cmd" : "npx";
1027
- const beside = join(dirname(process.execPath), name);
1028
- return existsSync(beside) ? beside : which(name);
1258
+ const beside = join2(dirname(process.execPath), name);
1259
+ return existsSync4(beside) ? beside : which(name);
1029
1260
  }
1030
1261
  async function awaitDaemon(since, read = readRunnerState, { timeoutMs = 15e3, pollMs = 500 } = {}) {
1031
1262
  for (let waited = 0; ; waited += pollMs) {
@@ -1053,20 +1284,22 @@ function unitEnv(env) {
1053
1284
  }
1054
1285
  return picked;
1055
1286
  }
1287
+ function serviceEnv(env = process.env) {
1288
+ const origin = getOrigin();
1289
+ return unitEnv({ ...env, CLOOP_ORIGIN: origin, CLOOP_MESH_URL: env.CLOOP_MESH_URL || origin });
1290
+ }
1056
1291
  function installedService(opts) {
1057
- const name = opts.kind === "workstation" ? "box" : "runner";
1292
+ const { label, unit, task, file } = serviceIdentity(opts.kind, opts.environment);
1058
1293
  if (opts.platform === "darwin") {
1059
- const label = `com.cloop.${name}`;
1060
1294
  return {
1061
- path: join(opts.dir ?? join(opts.home, "Library", "LaunchAgents"), `${label}.plist`),
1295
+ path: join2(opts.dir ?? join2(opts.home, "Library", "LaunchAgents"), `${label}.plist`),
1062
1296
  steps: [{ command: ["launchctl", "bootout", `gui/${opts.uid}/${label}`], mayFail: true }],
1063
1297
  running: ["launchctl", "print", `gui/${opts.uid}/${label}`]
1064
1298
  };
1065
1299
  }
1066
1300
  if (opts.platform === "win32") {
1067
- const task = name === "box" ? "Cloop Box" : "Cloop Runner";
1068
1301
  return {
1069
- path: join(opts.dir ?? join(opts.home, "AppData", "Local", "Cloop"), `cloop-${name}.cmd`),
1302
+ path: join2(opts.dir ?? join2(opts.home, "AppData", "Local", "Cloop"), `${file}.cmd`),
1070
1303
  steps: [
1071
1304
  { command: ["schtasks", "/end", "/tn", task], mayFail: true },
1072
1305
  { command: ["schtasks", "/delete", "/tn", task, "/f"], mayFail: true }
@@ -1074,25 +1307,23 @@ function installedService(opts) {
1074
1307
  running: ["schtasks", "/query", "/tn", task]
1075
1308
  };
1076
1309
  }
1077
- const unit = `cloop-${name}.service`;
1078
1310
  return {
1079
- path: join(opts.dir ?? join(opts.home, ".config", "systemd", "user"), unit),
1311
+ path: join2(opts.dir ?? join2(opts.home, ".config", "systemd", "user"), unit),
1080
1312
  steps: [{ command: ["systemctl", "--user", "disable", "--now", unit], mayFail: true }],
1081
1313
  running: ["systemctl", "--user", "is-active", "--quiet", unit]
1082
1314
  };
1083
1315
  }
1084
1316
  function unitFor(opts) {
1085
1317
  const env = Object.entries(opts.env);
1086
- const name = opts.kind === "workstation" ? "box" : "runner";
1318
+ const { label, unit, task, file } = serviceIdentity(opts.kind, opts.environment);
1087
1319
  const retire = installedService({
1088
1320
  ...opts,
1089
1321
  kind: opts.kind === "workstation" ? "local" : "workstation"
1090
1322
  });
1091
1323
  if (opts.platform === "darwin") {
1092
- const label = `com.cloop.${name}`;
1093
- const agents = opts.dir ?? join(opts.home, "Library", "LaunchAgents");
1094
- const path2 = join(agents, `${label}.plist`);
1095
- const log = join(opts.home, "Library", "Logs", `cloop-${name}.log`);
1324
+ const agents = opts.dir ?? join2(opts.home, "Library", "LaunchAgents");
1325
+ const path2 = join2(agents, `${label}.plist`);
1326
+ const log = join2(opts.home, "Library", "Logs", `${file}.log`);
1096
1327
  const xml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1097
1328
  const contents2 = [
1098
1329
  '<?xml version="1.0" encoding="UTF-8"?>',
@@ -1129,10 +1360,9 @@ function unitFor(opts) {
1129
1360
  };
1130
1361
  }
1131
1362
  if (opts.platform === "win32") {
1132
- const task = name === "box" ? "Cloop Box" : "Cloop Runner";
1133
- const dir = opts.dir ?? join(opts.home, "AppData", "Local", "Cloop");
1134
- const path2 = join(dir, `cloop-${name}.cmd`);
1135
- const log = join(dir, `cloop-${name}.log`);
1363
+ const dir = opts.dir ?? join2(opts.home, "AppData", "Local", "Cloop");
1364
+ const path2 = join2(dir, `${file}.cmd`);
1365
+ const log = join2(dir, `${file}.log`);
1136
1366
  const psLog = log.replace(/'/g, "''");
1137
1367
  const contents2 = [
1138
1368
  "@echo off",
@@ -1187,12 +1417,11 @@ function unitFor(opts) {
1187
1417
  ]
1188
1418
  };
1189
1419
  }
1190
- const unit = `cloop-${name}.service`;
1191
- const units = opts.dir ?? join(opts.home, ".config", "systemd", "user");
1192
- const path = join(units, unit);
1420
+ const units = opts.dir ?? join2(opts.home, ".config", "systemd", "user");
1421
+ const path = join2(units, unit);
1193
1422
  const contents = [
1194
1423
  "[Unit]",
1195
- `Description=Cloop ${name}: answers the Cloop Agent over the mesh`,
1424
+ `Description=${task}: answers the Cloop Agent over the mesh`,
1196
1425
  "After=network-online.target",
1197
1426
  // A disconnected runner exits 1 on every start. Three in ten minutes and
1198
1427
  // systemd marks the unit failed instead of restarting it forever.
@@ -1230,7 +1459,7 @@ function resolveRepos(paths, toplevel, isFolder = folderAt) {
1230
1459
  if (!isFolder(full))
1231
1460
  return `${p} is not a folder. Pass --repo <path> for each folder Cloop may work in.`;
1232
1461
  const top = toplevel(full) ?? full;
1233
- if (!repos.some((r) => r.path === top)) repos.push({ label: basename3(top), path: top });
1462
+ if (!repos.some((r) => r.path === top)) repos.push({ label: basename4(top), path: top });
1234
1463
  }
1235
1464
  return repos;
1236
1465
  }
@@ -1245,7 +1474,7 @@ var CHECKOUT_ROOTS = ["projects", "code", "repos", "src", "Developer", "dev", "w
1245
1474
  function lastCommitAt(path) {
1246
1475
  try {
1247
1476
  return Number(
1248
- execFileSync("git", ["-C", path, "log", "-1", "--format=%ct"], {
1477
+ execFileSync2("git", ["-C", path, "log", "-1", "--format=%ct"], {
1249
1478
  encoding: "utf-8",
1250
1479
  stdio: ["ignore", "pipe", "ignore"],
1251
1480
  timeout: 5e3
@@ -1260,13 +1489,13 @@ function findCheckouts(home, limit = 8) {
1260
1489
  for (const root of CHECKOUT_ROOTS) {
1261
1490
  let entries;
1262
1491
  try {
1263
- entries = readdirSync(join(home, root), { withFileTypes: true });
1492
+ entries = readdirSync(join2(home, root), { withFileTypes: true });
1264
1493
  } catch {
1265
1494
  continue;
1266
1495
  }
1267
1496
  for (const entry of entries) {
1268
- const path = join(home, root, entry.name);
1269
- if (!entry.isDirectory() || !existsSync(join(path, ".git"))) continue;
1497
+ const path = join2(home, root, entry.name);
1498
+ if (!entry.isDirectory() || !existsSync4(join2(path, ".git"))) continue;
1270
1499
  found.push({ repo: { label: entry.name, path }, at: lastCommitAt(path) });
1271
1500
  }
1272
1501
  }
@@ -1286,7 +1515,7 @@ function rerunCommand(argv, script = process.argv[1] ?? "") {
1286
1515
  return [base, "connect", ...staging, ...argv].join(" ");
1287
1516
  }
1288
1517
  function workFolder(home) {
1289
- return { label: "Cloop", path: join(home, "Cloop") };
1518
+ return { label: "Cloop", path: join2(home, "Cloop") };
1290
1519
  }
1291
1520
  function workFolderLine(found, home, argv, terminal) {
1292
1521
  const rerun = rerunCommand(argv.filter((a) => a !== "--ask"));
@@ -1321,8 +1550,8 @@ async function reposFor(argv) {
1321
1550
  return repos2;
1322
1551
  }
1323
1552
  const here = gitTop(process.cwd());
1324
- if (here) return [{ label: basename3(here), path: here }];
1325
- const home = homedir();
1553
+ if (here) return [{ label: basename4(here), path: here }];
1554
+ const home = homedir3();
1326
1555
  const work = workFolder(home);
1327
1556
  const found = findCheckouts(home);
1328
1557
  let repos = [work];
@@ -1339,7 +1568,7 @@ async function reposFor(argv) {
1339
1568
  prompt.close();
1340
1569
  }
1341
1570
  } else out(`${bold("Cloop runner")} ${workFolderLine(found, home, argv, terminal)}`);
1342
- if (repos.some((r) => r.path === work.path)) mkdirSync(work.path, { recursive: true });
1571
+ if (repos.some((r) => r.path === work.path)) mkdirSync2(work.path, { recursive: true });
1343
1572
  return repos;
1344
1573
  }
1345
1574
  function askOrClosed(prompt, closed) {
@@ -1360,7 +1589,7 @@ function askOrClosed(prompt, closed) {
1360
1589
  }
1361
1590
  function gitTop(path) {
1362
1591
  try {
1363
- return execFileSync("git", ["-C", path, "rev-parse", "--show-toplevel"], {
1592
+ return execFileSync2("git", ["-C", path, "rev-parse", "--show-toplevel"], {
1364
1593
  encoding: "utf-8",
1365
1594
  stdio: ["ignore", "pipe", "ignore"]
1366
1595
  }).trim();
@@ -1381,7 +1610,7 @@ function harnessLine(h) {
1381
1610
  const account = h.signedIn ? h.account ?? "signed in" : "signed out";
1382
1611
  return `${h.name}${version}, ${account}${h.experimental ? " (experimental)" : ""}`;
1383
1612
  }
1384
- async function runSteps(steps, run = (command) => void execFileSync(command[0], command.slice(1), { stdio: "ignore", timeout: 15e3 }), wait = (ms) => new Promise((r) => setTimeout(r, ms))) {
1613
+ async function runSteps(steps, run = (command) => void execFileSync2(command[0], command.slice(1), { stdio: "ignore", timeout: 15e3 }), wait = (ms) => new Promise((r) => setTimeout(r, ms))) {
1385
1614
  for (const step of steps) {
1386
1615
  const tries = step.tries ?? 1;
1387
1616
  for (let attempt = 1; ; attempt++) {
@@ -1398,7 +1627,7 @@ async function runSteps(steps, run = (command) => void execFileSync(command[0],
1398
1627
  }
1399
1628
  var systemServices = {
1400
1629
  platform: process.platform,
1401
- run: (command) => execFileSync(command[0], command.slice(1), {
1630
+ run: (command) => execFileSync2(command[0], command.slice(1), {
1402
1631
  encoding: "utf-8",
1403
1632
  stdio: ["ignore", "pipe", "ignore"],
1404
1633
  timeout: 15e3
@@ -1432,16 +1661,18 @@ async function installService(kind, argv, attempt, services = systemServices) {
1432
1661
  attempt.step = "service_write";
1433
1662
  const program = programFor(process.argv[1] ?? "cloop", process.execPath, findNpx(), VERSION);
1434
1663
  if (typeof program === "string") throw new ConnectFailure("npx_missing", program);
1664
+ const environment = runnerEnvironment();
1435
1665
  const unit = unitFor({
1436
1666
  platform: services.platform,
1437
1667
  kind,
1438
- home: homedir(),
1668
+ environment,
1669
+ home: homedir3(),
1439
1670
  program,
1440
- env: unitEnv(process.env),
1671
+ env: serviceEnv(),
1441
1672
  uid: process.getuid?.() ?? 0,
1442
1673
  ...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
1443
1674
  });
1444
- mkdirSync(join(unit.path, ".."), { recursive: true });
1675
+ mkdirSync2(join2(unit.path, ".."), { recursive: true });
1445
1676
  writeFileSync(unit.path, unit.contents);
1446
1677
  if (argv.includes("--no-start")) {
1447
1678
  out(
@@ -1453,10 +1684,12 @@ async function installService(kind, argv, attempt, services = systemServices) {
1453
1684
  const since = Date.now();
1454
1685
  const run = (command) => void services.run(command);
1455
1686
  try {
1456
- if (existsSync(unit.retire.path)) {
1457
- out(` This computer is one runner, so connect stops and removes ${unit.retire.path}.`);
1687
+ if (existsSync4(unit.retire.path)) {
1688
+ out(
1689
+ ` This computer has one ${environment} runner, so connect stops and removes ${unit.retire.path}.`
1690
+ );
1458
1691
  await runSteps(unit.retire.steps, run);
1459
- rmSync(unit.retire.path, { force: true });
1692
+ rmSync3(unit.retire.path, { force: true });
1460
1693
  }
1461
1694
  await runSteps(unit.start, run);
1462
1695
  } catch (err) {
@@ -1494,6 +1727,7 @@ async function installService(kind, argv, attempt, services = systemServices) {
1494
1727
  out(` Linger: turned on for ${user}, so the runner keeps running after you log out.`);
1495
1728
  }
1496
1729
  out(` Service: ${unit.path}, started and connected. Logs: ${dim(unit.logs)}`);
1730
+ out(`${bold("Cloop runner")} Connected the ${environment} runner.`);
1497
1731
  }
1498
1732
  async function connectT3(argv, attempt, fallback, chosen, services) {
1499
1733
  const previous = readRunnerConfig();
@@ -1586,7 +1820,7 @@ async function connectT3(argv, attempt, fallback, chosen, services) {
1586
1820
  async function connectLocal(driver, found, argv, attempt, chosen, services) {
1587
1821
  attempt.step = "repos";
1588
1822
  const repos = await reposFor(argv);
1589
- const work = workFolder(homedir()).path;
1823
+ const work = workFolder(homedir3()).path;
1590
1824
  attempt.workFolder = repos.every((r) => r.path === work);
1591
1825
  const harness = driver === "claude-code" ? found.claude : found.codex;
1592
1826
  const bin = which(driver === "claude-code" ? "claude" : "codex") ?? (driver === "claude-code" ? "claude" : "codex");
@@ -1718,7 +1952,7 @@ async function claudeAtFloor(found, forced, deps) {
1718
1952
  }
1719
1953
  async function updateClaude() {
1720
1954
  try {
1721
- execFileSync("claude", ["update"], { stdio: "inherit", timeout: 3e5 });
1955
+ execFileSync2("claude", ["update"], { stdio: "inherit", timeout: 3e5 });
1722
1956
  } catch {
1723
1957
  return null;
1724
1958
  }
@@ -1739,15 +1973,27 @@ function terminalYesNo() {
1739
1973
  };
1740
1974
  }
1741
1975
  async function runConnect(argv, deps = {}) {
1742
- const replacedOrigin = runnerOrigin();
1743
1976
  pinRunnerEnvironment();
1744
- console.error(
1745
- `[runner:connect] origin=${getOrigin()} source=${pinnedOriginSource()} replaced_origin=${replacedOrigin ?? "none"}`
1746
- );
1977
+ const environment = runnerEnvironment();
1747
1978
  const attempt = newAttempt();
1748
- if (replacedOrigin) attempt.replacedOrigin = replacedOrigin;
1749
1979
  let error = null;
1750
1980
  try {
1981
+ attempt.step = "legacy_move";
1982
+ try {
1983
+ if (await moveLegacyStagingRunner(deps.services ?? systemServices))
1984
+ out(`${bold("Cloop runner")} ${movedLine(environment)}`);
1985
+ } catch (err) {
1986
+ throw new ConnectFailure(
1987
+ "legacy_move_failed",
1988
+ err instanceof Error ? err.message : String(err)
1989
+ );
1990
+ }
1991
+ attempt.step = "detect";
1992
+ const replacedOrigin = runnerOrigin(environment);
1993
+ console.error(
1994
+ `[runner:connect] origin=${getOrigin()} source=${pinnedOriginSource()} replaced_origin=${replacedOrigin ?? "none"}`
1995
+ );
1996
+ if (replacedOrigin) attempt.replacedOrigin = replacedOrigin;
1751
1997
  await connect(argv, attempt, deps);
1752
1998
  } catch (err) {
1753
1999
  error = err instanceof ConnectFailure ? err.code : "unexpected";
@@ -1765,133 +2011,6 @@ async function connectCommand(argv) {
1765
2011
  if (await runConnect(argv)) process.exit(1);
1766
2012
  }
1767
2013
 
1768
- // src/commands/disconnect.ts
1769
- var DONE_LINE = "This computer is no longer a Cloop runner. To connect it again: npx -y @cloop/runner@latest connect";
1770
- function unitOrigin(contents) {
1771
- const plist = /<key>CLOOP_ORIGIN<\/key><string>([^<]+)<\/string>/.exec(contents)?.[1];
1772
- if (plist) return plist.replace(/&amp;/g, "&");
1773
- const unit = /Environment="CLOOP_ORIGIN=([^"]+)"/.exec(contents)?.[1];
1774
- if (unit) return unit.replace(/%%/g, "%");
1775
- const launcher = /^set "CLOOP_ORIGIN=(.+)"\r?$/m.exec(contents)?.[1];
1776
- return launcher ? launcher.replace(/%%/g, "%") : null;
1777
- }
1778
- function disconnectPlan(opts) {
1779
- const exists = opts.exists ?? existsSync2;
1780
- const read = opts.read ?? ((path) => readFileSync(path, "utf-8"));
1781
- const services = ["local", "workstation"].map((kind) => installedService({ ...opts, kind })).filter((service) => exists(service.path));
1782
- const fromUnit = services.map((service) => {
1783
- try {
1784
- return unitOrigin(read(service.path));
1785
- } catch {
1786
- return null;
1787
- }
1788
- }).find(Boolean);
1789
- return {
1790
- origin: opts.boxOrigin ?? fromUnit ?? opts.fallbackOrigin,
1791
- deviceToken: opts.deviceToken,
1792
- services,
1793
- box: exists(opts.box) ? opts.box : null,
1794
- files: opts.files.filter((file) => exists(file)),
1795
- isBox: opts.platform !== "darwin" && services.some((s) => s.path.endsWith("/cloop-box.service"))
1796
- };
1797
- }
1798
- function revokeLine(revoke, origin, box) {
1799
- const keep = box ? ` Kept ${box}, which holds the device token, so you can try again.` : "";
1800
- switch (revoke) {
1801
- case "revoked":
1802
- return [`Revoked this computer on Cloop (${origin}).`];
1803
- case "already_revoked":
1804
- return [`Cloop (${origin}) had already revoked this computer.`];
1805
- case "no_device":
1806
- return ["No runner device on this computer to revoke."];
1807
- case "unknown_device":
1808
- return [
1809
- `Cloop at ${origin} never issued this computer's device token, so it belongs to the other environment.${keep}`,
1810
- "Run `cloop disconnect --staging` for a staging runner, or `cloop disconnect` for production."
1811
- ];
1812
- case "failed":
1813
- return [
1814
- `Could not revoke this computer at ${origin}: Cloop did not answer as expected.${keep}`,
1815
- "Run `cloop disconnect` again when Cloop answers, or press Disconnect on its card on the Threads page and then delete that file."
1816
- ];
1817
- }
1818
- }
1819
- async function disconnect(plan, opts) {
1820
- const { say } = opts;
1821
- const run = opts.run ?? ((command) => void execFileSync2(command[0], command.slice(1), {
1822
- stdio: "ignore",
1823
- timeout: 15e3
1824
- }));
1825
- if (plan.isBox && !opts.yes) {
1826
- say("This computer runs cloop-box.service, a Cloop box with T3 Code. Disconnect would:");
1827
- for (const s of plan.services) say(` stop and remove ${s.path}`);
1828
- if (plan.deviceToken) say(` revoke its runner device on Cloop (${plan.origin})`);
1829
- for (const f of [...plan.box ? [plan.box] : [], ...plan.files]) say(` delete ${f}`);
1830
- say("Run `cloop disconnect --yes` to do this.");
1831
- return 1;
1832
- }
1833
- for (const service of plan.services) {
1834
- await runSteps(service.steps, run);
1835
- const stillRunning = async () => {
1836
- const until = Date.now() + (opts.stopWaitMs ?? 1e4);
1837
- for (; ; ) {
1838
- try {
1839
- run(service.running);
1840
- } catch {
1841
- return false;
1842
- }
1843
- if (Date.now() >= until) return true;
1844
- await new Promise((resolve3) => setTimeout(resolve3, 250));
1845
- }
1846
- };
1847
- if (await stillRunning()) {
1848
- say(
1849
- `Could not stop the service in ${service.path}. Nothing was removed. Stop it with \`${service.steps.map((s) => s.command.join(" ")).join(" && ")}\`, then run \`cloop disconnect\` again.`
1850
- );
1851
- return 1;
1852
- }
1853
- say(`Stopped the service in ${service.path}`);
1854
- }
1855
- const revoked = await opts.revoke(plan.origin, plan.deviceToken);
1856
- const gone = tokenGone(revoked);
1857
- for (const service of plan.services) {
1858
- rmSync2(service.path, { force: true });
1859
- say(`Removed ${service.path}`);
1860
- }
1861
- for (const file of [...gone && plan.box ? [plan.box] : [], ...plan.files]) {
1862
- rmSync2(file, { force: true });
1863
- say(`Deleted ${file}`);
1864
- }
1865
- for (const line2 of revokeLine(revoked, plan.origin, plan.box)) say(line2);
1866
- if (!gone) return 1;
1867
- say(DONE_LINE);
1868
- return 0;
1869
- }
1870
- function runnerOrigin() {
1871
- return disconnectPlan(thisComputer(readRunnerConfig(), "")).origin || void 0;
1872
- }
1873
- function thisComputer(cfg, fallbackOrigin) {
1874
- return {
1875
- platform: process.platform,
1876
- home: homedir2(),
1877
- uid: process.getuid?.() ?? 0,
1878
- ...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {},
1879
- box: boxPath(),
1880
- deviceToken: cfg?.deviceToken ?? null,
1881
- ...cfg?.origin ? { boxOrigin: cfg.origin } : {},
1882
- fallbackOrigin,
1883
- files: [localRunsFilePath(), runnerStatePath(), threadsFilePath()]
1884
- };
1885
- }
1886
- async function disconnectCommand(argv) {
1887
- const plan = disconnectPlan(thisComputer(readRunnerConfig(), getOrigin()));
1888
- process.exitCode = await disconnect(plan, {
1889
- yes: argv.includes("--yes"),
1890
- revoke: (origin, token) => revokeOwnDevice(origin, token),
1891
- say: (line2) => console.log(line2)
1892
- });
1893
- }
1894
-
1895
2014
  export {
1896
2015
  T3Client,
1897
2016
  runBoxTool,
@@ -1901,12 +2020,6 @@ export {
1901
2020
  claudeDialect,
1902
2021
  probeCodex,
1903
2022
  codexDialect,
1904
- DONE_LINE,
1905
- unitOrigin,
1906
- disconnectPlan,
1907
- disconnect,
1908
- runnerOrigin,
1909
- disconnectCommand,
1910
2023
  DEFAULT_T3_URL,
1911
2024
  which,
1912
2025
  preferExecutable,
@@ -1932,6 +2045,7 @@ export {
1932
2045
  findNpx,
1933
2046
  awaitDaemon,
1934
2047
  unitEnv,
2048
+ serviceEnv,
1935
2049
  installedService,
1936
2050
  unitFor,
1937
2051
  resolveRepos,
@@ -1952,5 +2066,17 @@ export {
1952
2066
  rememberedDriver,
1953
2067
  claudeAtFloor,
1954
2068
  runConnect,
1955
- connectCommand
2069
+ connectCommand,
2070
+ legacyStagingRunner,
2071
+ moveRunnerFiles,
2072
+ moveLegacyStagingRunner,
2073
+ doneLine,
2074
+ unitOrigin,
2075
+ disconnectPlan,
2076
+ stopService,
2077
+ disconnect,
2078
+ runnerOrigin,
2079
+ disconnectCommand,
2080
+ existingRunnerEnvironment,
2081
+ pinExistingRunner
1956
2082
  };