@cloop/runner 0.3.17 → 0.3.21

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.
@@ -3,24 +3,30 @@ import {
3
3
  readRunnerState,
4
4
  runnerStatePath,
5
5
  threadsFilePath
6
- } from "./chunk-K4TU7DBU.js";
6
+ } from "./chunk-S4IN6AX2.js";
7
7
  import {
8
8
  BoxToolError,
9
9
  CLOOP_THREAD_PREFIX,
10
10
  ENVIRONMENTS,
11
+ MIN_PROTOCOL,
11
12
  RUNTIME_MODES,
13
+ T3Client,
12
14
  T3Driver,
15
+ T3HttpError,
13
16
  boxPath,
14
17
  cloopCommand,
15
18
  commandFor,
16
19
  defaultT3BinSources,
17
20
  environmentOf,
21
+ exchangePairing,
18
22
  isLocal,
19
23
  isYes,
20
24
  localRunsFilePath,
21
25
  otherThreadsChoice,
22
26
  pickT3Bin,
23
27
  questionLine,
28
+ quoteWindowsArg,
29
+ readEnvironment,
24
30
  readRunnerConfig,
25
31
  runT3,
26
32
  runnerDir,
@@ -31,7 +37,7 @@ import {
31
37
  windowsExecutable,
32
38
  windowsPowerShellEnv,
33
39
  writeBoxConfig
34
- } from "./chunk-LXRCJTHL.js";
40
+ } from "./chunk-JM5NKNHE.js";
35
41
  import {
36
42
  getMachine,
37
43
  shortMachineName
@@ -49,17 +55,17 @@ import {
49
55
  } from "./chunk-R3CLO2FB.js";
50
56
  import {
51
57
  connectWebhook
52
- } from "./chunk-P46CX6Z7.js";
58
+ } from "./chunk-N7PVNXYU.js";
53
59
  import {
54
60
  ConnectFailure,
55
61
  connectReport,
56
62
  deviceLogin,
57
63
  newAttempt,
58
64
  sendConnectReport
59
- } from "./chunk-44BZ2K5L.js";
65
+ } from "./chunk-TZ3I2IWD.js";
60
66
  import {
61
67
  VERSION
62
- } from "./chunk-QG5HVBJY.js";
68
+ } from "./chunk-3NIDXMUM.js";
63
69
  import {
64
70
  STAGING_ORIGIN,
65
71
  getOrigin,
@@ -78,35 +84,42 @@ import {
78
84
  statSync,
79
85
  writeFileSync
80
86
  } from "fs";
81
- import { homedir as homedir3, userInfo } from "os";
82
- import { basename as basename4, dirname, join as join3, resolve as resolve2 } from "path";
87
+ import { homedir as homedir4, userInfo } from "os";
88
+ import { basename as basename5, dirname as dirname2, join as join3, resolve as resolve2 } from "path";
83
89
  import { createInterface } from "readline/promises";
84
90
  import { Writable } from "stream";
85
91
 
86
92
  // src/agent-install.ts
87
93
  import { spawn } from "child_process";
88
- import { existsSync, readdirSync } from "fs";
89
- import { delimiter, join, posix, win32 } from "path";
94
+ import { existsSync, readdirSync, realpathSync } from "fs";
95
+ import { basename, delimiter, dirname, join, posix, win32 } from "path";
90
96
  var CODEX_RELEASES = "https://github.com/openai/codex/releases/latest/download";
91
97
  var CODEX_TRIPLES = {
92
98
  "darwin-arm64": "aarch64-apple-darwin",
93
99
  "darwin-x64": "x86_64-apple-darwin",
94
100
  "linux-x64": "x86_64-unknown-linux-musl",
95
101
  "linux-arm64": "aarch64-unknown-linux-musl",
96
- "win32-x64": "x86_64-pc-windows-msvc.exe",
97
- "win32-arm64": "aarch64-pc-windows-msvc.exe"
102
+ "win32-x64": "x86_64-pc-windows-msvc",
103
+ "win32-arm64": "aarch64-pc-windows-msvc"
98
104
  };
99
105
  function codexAsset(platform, arch) {
100
106
  const triple = CODEX_TRIPLES[`${platform}-${arch}`];
101
- return triple ? `codex-${triple}` : null;
107
+ return triple ? `codex-package-${triple}` : null;
102
108
  }
103
- var codexBinDir = (home) => join(home, ".cloop", "bin");
109
+ var codexHome = (home) => join(home, ".cloop", "codex");
110
+ var codexBinDir = (home) => join(codexHome(home), "bin");
111
+ var CODE_MODE_HOST = "codex-code-mode-host";
112
+ var exe = (name, platform) => platform === "win32" ? `${name}.exe` : name;
113
+ var oneFileCodex = (home, platform) => join(home, ".cloop", "bin", exe("codex", platform));
104
114
  var psQuote = (value) => `'${value.replace(/'/g, "''")}'`;
115
+ var CODEX_SUMS = `${CODEX_RELEASES}/codex-package_SHA256SUMS`;
105
116
  function codexInstallCommand(home, platform = process.platform, arch = process.arch) {
106
117
  const asset = codexAsset(platform, arch);
107
118
  if (!asset) return null;
108
- const dir = codexBinDir(home);
109
- const url = `${CODEX_RELEASES}/${asset}.tar.gz`;
119
+ const dir = codexHome(home);
120
+ const file = `${asset}.tar.gz`;
121
+ const url = `${CODEX_RELEASES}/${file}`;
122
+ const old = oneFileCodex(home, platform);
110
123
  if (platform === "win32")
111
124
  return [
112
125
  "powershell",
@@ -117,24 +130,60 @@ function codexInstallCommand(home, platform = process.platform, arch = process.a
117
130
  [
118
131
  "$ErrorActionPreference = 'Stop'",
119
132
  `$d = ${psQuote(dir)}`,
120
- "New-Item -ItemType Directory -Force -Path $d | Out-Null",
121
- "$t = Join-Path ([IO.Path]::GetTempPath()) 'codex.tar.gz'",
133
+ "$s = $d + '.new'",
134
+ "$o = $d + '.old'",
135
+ "if (Test-Path $s) { Remove-Item -Recurse -Force $s }",
136
+ "New-Item -ItemType Directory -Force -Path $s | Out-Null",
137
+ "$t = Join-Path $s 'codex-package.tar.gz'",
122
138
  `Invoke-WebRequest -UseBasicParsing ${psQuote(url)} -OutFile $t`,
123
- "tar.exe -xzf $t -C $d",
124
- `Move-Item -Force (Join-Path $d ${psQuote(asset)}) (Join-Path $d 'codex.exe')`,
125
- "Remove-Item -Force $t"
139
+ "$h = Join-Path $s 'codex-package_SHA256SUMS'",
140
+ // GitHub serves the digest list as octet-stream, so .Content would be bytes; a file reads as lines.
141
+ `Invoke-WebRequest -UseBasicParsing ${psQuote(CODEX_SUMS)} -OutFile $h`,
142
+ `$line = Get-Content $h | Where-Object { $_.Trim().EndsWith(${psQuote(` ${file}`)}) } | Select-Object -First 1`,
143
+ `if (-not $line) { throw ${psQuote(`${file} is not in codex-package_SHA256SUMS`)} }`,
144
+ "$want = ($line.Trim() -split '\\s+')[0].ToLower()",
145
+ "$got = (Get-FileHash -Algorithm SHA256 $t).Hash.ToLower()",
146
+ `if ($got -ne $want) { throw ${psQuote(`${file} does not match its SHA-256 in codex-package_SHA256SUMS`)} }`,
147
+ "tar.exe -xzf $t -C $s",
148
+ "Remove-Item -Force $t, $h",
149
+ `foreach ($f in 'codex.exe', '${CODE_MODE_HOST}.exe') { if (-not (Test-Path (Join-Path $s (Join-Path 'bin' $f)))) { throw ($f + ' is not in the Codex package') } }`,
150
+ "if (Test-Path $o) { Remove-Item -Recurse -Force $o }",
151
+ "if (Test-Path $d) { Move-Item $d $o }",
152
+ "Move-Item $s $d",
153
+ "if (Test-Path $o) { Remove-Item -Recurse -Force $o -ErrorAction SilentlyContinue }",
154
+ `Remove-Item -Force -ErrorAction SilentlyContinue ${psQuote(old)}`
126
155
  ].join("; ")
127
156
  ];
128
157
  return [
129
158
  "sh",
130
159
  "-c",
131
- 'mkdir -p "$1" && curl -fsSL "$2" | tar -xz -C "$1" && mv -f "$1/$3" "$1/codex" && chmod 755 "$1/codex"',
160
+ POSIX_INSTALL,
132
161
  "cloop",
133
162
  dir,
134
163
  url,
135
- asset
164
+ CODEX_SUMS,
165
+ file,
166
+ platform === "darwin" ? "shasum -a 256" : "sha256sum",
167
+ CODE_MODE_HOST,
168
+ old
136
169
  ];
137
170
  }
171
+ var POSIX_INSTALL = [
172
+ 'rm -rf "$1.new" "$1.old"',
173
+ 'mkdir -p "$1.new"',
174
+ 'curl -fsSL "$2" -o "$1.new/codex-package.tar.gz"',
175
+ `want=$(curl -fsSL "$3" | awk -v f="$4" '$2 == f { print $1 }')`,
176
+ 'got=$($5 "$1.new/codex-package.tar.gz" | cut -d" " -f1)',
177
+ '{ [ -n "$want" ] && [ "$want" = "$got" ] || { echo "$4 does not match its SHA-256 in codex-package_SHA256SUMS" >&2; exit 1; }; }',
178
+ 'tar -xzf "$1.new/codex-package.tar.gz" -C "$1.new"',
179
+ 'rm -f "$1.new/codex-package.tar.gz"',
180
+ 'test -x "$1.new/bin/codex"',
181
+ 'test -x "$1.new/bin/$6"',
182
+ '{ [ ! -e "$1" ] || mv "$1" "$1.old"; }',
183
+ 'mv "$1.new" "$1"',
184
+ 'rm -rf "$1.old"',
185
+ 'rm -f "$7"'
186
+ ].join(" && ");
138
187
  async function installCodex(home, run = runShown) {
139
188
  const command = codexInstallCommand(home);
140
189
  if (!command || !await run(command)) return false;
@@ -175,6 +224,16 @@ function findIn(folder, name, env) {
175
224
  function findLocalCodex(home, env = process.env) {
176
225
  findIn(codexBinDir(home), "codex", env);
177
226
  }
227
+ function codexHostMissing(path, platform = process.platform) {
228
+ if (!path) return false;
229
+ try {
230
+ const real = realpathSync(path);
231
+ if (basename(real).toLowerCase() !== exe("codex", platform)) return false;
232
+ return !existsSync(join(dirname(real), exe(CODE_MODE_HOST, platform)));
233
+ } catch {
234
+ return false;
235
+ }
236
+ }
178
237
  function findLocalClaude(home, env = process.env) {
179
238
  findIn(join(home, ".local", "bin"), "claude", env);
180
239
  }
@@ -193,175 +252,6 @@ function hasChatGptApp(home, platform = process.platform, env = process.env, fs
193
252
  return false;
194
253
  }
195
254
 
196
- // src/t3.ts
197
- var T3_SCOPE = "orchestration:read orchestration:operate";
198
- var MIN_PROTOCOL = 2;
199
- async function readEnvironment(t3Url, fetchFn = fetch) {
200
- const res = await fetchFn(`${t3Url}/.well-known/t3/environment`);
201
- if (!res.ok) throw new Error(`T3 environment ${res.status} at ${t3Url}`);
202
- return await res.json();
203
- }
204
- async function exchangePairing(t3Url, credential, label, fetchFn = fetch) {
205
- const form = new URLSearchParams({
206
- grant_type: "urn:ietf:params:oauth:grant-type:token-exchange",
207
- subject_token: credential,
208
- subject_token_type: "urn:t3:params:oauth:token-type:environment-bootstrap",
209
- requested_token_type: "urn:ietf:params:oauth:token-type:access_token",
210
- scope: T3_SCOPE,
211
- client_label: label,
212
- client_device_type: "bot"
213
- });
214
- const res = await fetchFn(`${t3Url}/oauth/token`, { method: "POST", body: form });
215
- if (!res.ok) throw new T3HttpError("token exchange", res.status);
216
- const token = await res.json();
217
- if (!sameScopes(token.scope, T3_SCOPE))
218
- throw new Error(`T3 granted scope "${token.scope}", wanted "${T3_SCOPE}"`);
219
- return token;
220
- }
221
- function sameScopes(a, b) {
222
- const set = (s) => [...new Set(s.split(/\s+/).filter(Boolean))].sort().join(" ");
223
- return set(a) === set(b);
224
- }
225
- var T3HttpError = class extends Error {
226
- constructor(path, status) {
227
- super(`T3 ${path} ${status}`);
228
- this.status = status;
229
- this.name = "T3HttpError";
230
- }
231
- status;
232
- };
233
- var T3Client = class {
234
- constructor(t3Url, token, fetchFn = fetch) {
235
- this.t3Url = t3Url;
236
- this.token = token;
237
- this.fetchFn = fetchFn;
238
- }
239
- t3Url;
240
- token;
241
- fetchFn;
242
- async http(path, headers = {}) {
243
- const res = await this.fetchFn(`${this.t3Url}${path}`, {
244
- headers: { authorization: `Bearer ${this.token}`, ...headers }
245
- });
246
- if (!res.ok) throw new T3HttpError(path, res.status);
247
- return await res.json();
248
- }
249
- async openSocket() {
250
- const ticket = await this.fetchFn(`${this.t3Url}/api/auth/websocket-ticket`, {
251
- method: "POST",
252
- headers: { authorization: `Bearer ${this.token}` }
253
- });
254
- if (!ticket.ok) throw new T3HttpError("/api/auth/websocket-ticket", ticket.status);
255
- const { ticket: wsTicket } = await ticket.json();
256
- const { WebSocket } = await import("ws");
257
- const url = `${this.t3Url.replace(/^http/, "ws")}/ws?wsTicket=${encodeURIComponent(wsTicket)}&orchestrationProtocol=2&clientSurface=web&clientAppVersion=cloop-box`;
258
- return new WebSocket(url);
259
- }
260
- /** One request over a fresh /ws socket. The daemon makes a few calls a minute, so a socket per call is simpler than keeping one alive. */
261
- async rpc(tag, payload) {
262
- const ws = await this.openSocket();
263
- return new Promise((resolve3, reject) => {
264
- let settled = false;
265
- const finish = (fn) => {
266
- if (settled) return;
267
- settled = true;
268
- clearTimeout(timer);
269
- fn();
270
- try {
271
- ws.close();
272
- } catch {
273
- }
274
- };
275
- const timer = setTimeout(
276
- () => finish(() => reject(new Error(`T3 rpc ${tag} timed out`))),
277
- 15e3
278
- );
279
- ws.on(
280
- "error",
281
- (err) => finish(() => reject(err instanceof Error ? err : new Error(String(err))))
282
- );
283
- ws.on(
284
- "close",
285
- () => finish(() => reject(new Error(`T3 rpc ${tag}: socket closed before a reply`)))
286
- );
287
- ws.on("open", () => {
288
- ws.send(JSON.stringify({ _tag: "Request", id: 1, tag, payload, headers: [] }));
289
- });
290
- ws.on("message", (data) => {
291
- for (const msg of parseFrames(data)) {
292
- if (msg._tag !== "Exit" || String(msg.requestId) !== "1") continue;
293
- const exit = msg.exit;
294
- if (exit._tag === "Success") finish(() => resolve3(exit.value));
295
- else {
296
- finish(
297
- () => reject(
298
- new Error(`T3 rpc ${tag} failed: ${JSON.stringify(exit.cause).slice(0, 300)}`)
299
- )
300
- );
301
- }
302
- }
303
- });
304
- });
305
- }
306
- /**
307
- * A streaming request, such as `orchestration.subscribeThread`, on its own
308
- * socket. Every item is acked, as Effect RPC requires. `done` resolves with
309
- * the reason the stream ended and never rejects; `close` interrupts it.
310
- */
311
- async stream(tag, payload, onItem) {
312
- const ws = await this.openSocket();
313
- let resolveDone = () => {
314
- };
315
- const done = new Promise((r) => {
316
- resolveDone = r;
317
- });
318
- const end = (reason) => {
319
- resolveDone(reason);
320
- try {
321
- ws.close();
322
- } catch {
323
- }
324
- };
325
- ws.on("error", (err) => end(`error: ${err instanceof Error ? err.message : String(err)}`));
326
- ws.on("close", () => end("closed"));
327
- ws.on("open", () => {
328
- ws.send(JSON.stringify({ _tag: "Request", id: 1, tag, payload, headers: [] }));
329
- });
330
- ws.on("message", (data) => {
331
- for (const msg of parseFrames(data)) {
332
- if (String(msg.requestId) !== "1") continue;
333
- if (msg._tag === "Chunk") {
334
- ws.send(JSON.stringify({ _tag: "Ack", requestId: msg.requestId }));
335
- for (const value of msg.values) onItem(value);
336
- } else if (msg._tag === "Exit") {
337
- const exit = msg.exit;
338
- end(
339
- exit._tag === "Success" ? "exit" : `failed: ${JSON.stringify(exit.cause).slice(0, 300)}`
340
- );
341
- }
342
- }
343
- });
344
- return {
345
- done,
346
- close: () => {
347
- try {
348
- ws.send(JSON.stringify({ _tag: "Interrupt", requestId: "1" }));
349
- } catch {
350
- }
351
- end("closed by client");
352
- }
353
- };
354
- }
355
- };
356
- function parseFrames(data) {
357
- try {
358
- const raw = JSON.parse(String(data));
359
- return Array.isArray(raw) ? raw : [raw];
360
- } catch {
361
- return [];
362
- }
363
- }
364
-
365
255
  // src/box-tools.ts
366
256
  var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
367
257
  function parseLaunchArgs(args) {
@@ -486,7 +376,7 @@ async function revokeOwnDevice(origin, deviceToken, fetchFn = fetch) {
486
376
 
487
377
  // src/drivers/claude-code.ts
488
378
  import { execFile } from "child_process";
489
- import { basename, isAbsolute, relative, resolve } from "path";
379
+ import { basename as basename2, isAbsolute, relative, resolve } from "path";
490
380
  var SUBSCRIPTIONS = {
491
381
  max: "Claude Max",
492
382
  pro: "Claude Pro",
@@ -663,7 +553,7 @@ function parseClaudeLine(raw, run) {
663
553
  {
664
554
  type: "tool",
665
555
  name: block.name,
666
- ...path ? { target: basename(path) } : {},
556
+ ...path ? { target: basename2(path) } : {},
667
557
  ...summary ? { summary } : {},
668
558
  ...detail ? { detail } : {}
669
559
  }
@@ -763,14 +653,14 @@ function claudeDialect(bin = "claude", fallback = DEFAULT_FALLBACK_MODEL, askEve
763
653
  });
764
654
  },
765
655
  parse: parseClaudeLine,
766
- owns: (run, command) => command.includes(basename(bin)) && [run.work_id, run.session_id].some((id) => id !== null && command.includes(id)),
656
+ owns: (run, command) => command.includes(basename2(bin)) && [run.work_id, run.session_id].some((id) => id !== null && command.includes(id)),
767
657
  probe: () => probeClaude(bin)
768
658
  };
769
659
  }
770
660
 
771
661
  // src/drivers/codex.ts
772
662
  import { execFile as execFile2 } from "child_process";
773
- import { basename as basename2 } from "path";
663
+ import { basename as basename3 } from "path";
774
664
  function exec2(bin, args, timeout = 1e4) {
775
665
  const command = commandFor(bin, args);
776
666
  return new Promise(
@@ -856,7 +746,7 @@ function parseCodexLine(raw) {
856
746
  {
857
747
  type: "tool",
858
748
  name: "Edit",
859
- ...typeof path === "string" ? { target: basename2(path) } : {}
749
+ ...typeof path === "string" ? { target: basename3(path) } : {}
860
750
  }
861
751
  ];
862
752
  }
@@ -891,7 +781,7 @@ function codexDialect(bin = "codex") {
891
781
  models: () => codexModels(bin),
892
782
  parse: parseCodexLine,
893
783
  // A fresh run's command line names no id: Codex makes its session id after the start. So a run is also matched by its exact repository, which one open run per repository makes unique.
894
- owns: (run, command) => command.includes(basename2(bin)) && command.includes("exec") && command.includes("--json") && (run.session_id !== null && command.includes(run.session_id) || command.includes(`--cd ${run.repo} `)),
784
+ owns: (run, command) => command.includes(basename3(bin)) && command.includes("exec") && command.includes("--json") && (run.session_id !== null && command.includes(run.session_id) || command.includes(`--cd ${run.repo} `)),
895
785
  probe: () => probeCodex(bin)
896
786
  };
897
787
  }
@@ -905,7 +795,7 @@ import { join as join2 } from "path";
905
795
  import { execFileSync } from "child_process";
906
796
  import { existsSync as existsSync3, readFileSync, rmSync } from "fs";
907
797
  import { homedir } from "os";
908
- import { basename as basename3 } from "path";
798
+ import { basename as basename4 } from "path";
909
799
 
910
800
  // src/existing-runner.ts
911
801
  import { existsSync as existsSync2 } from "fs";
@@ -1008,7 +898,7 @@ async function disconnect(plan, opts) {
1008
898
  ...command[0] === "powershell" ? { env: windowsPowerShellEnv() } : {}
1009
899
  }));
1010
900
  if (plan.isBox && !opts.yes) {
1011
- const unit = plan.services.map((s) => basename3(s.path)).find((n) => n.startsWith("cloop-box"));
901
+ const unit = plan.services.map((s) => basename4(s.path)).find((n) => n.startsWith("cloop-box"));
1012
902
  say(`This computer runs ${unit}, the ${env} Cloop box with T3 Code. Disconnect would:`);
1013
903
  for (const s of plan.services) say(` stop and remove ${s.path}`);
1014
904
  if (plan.deviceToken) say(` revoke its runner device on Cloop (${plan.origin})`);
@@ -1126,6 +1016,219 @@ function movedLine(connecting) {
1126
1016
  return connecting === "staging" ? line2 : `${line2} It is stopped. Start it again with: cloop connect --staging`;
1127
1017
  }
1128
1018
 
1019
+ // src/mcp-registration.ts
1020
+ import { execFile as execFile3, spawn as spawn2 } from "child_process";
1021
+ import { homedir as homedir3 } from "os";
1022
+ var MCP_HARNESS_NAME = {
1023
+ "claude-code": "Claude Code",
1024
+ codex: "Codex"
1025
+ };
1026
+ var LOGIN_MS = 12e4;
1027
+ function mcpServer(env) {
1028
+ return { name: ENVIRONMENTS[env].mcpName, url: ENVIRONMENTS[env].mcpUrl };
1029
+ }
1030
+ var WORDS = {
1031
+ "claude-code": {
1032
+ bin: "claude",
1033
+ add: ({ name, url }) => ["mcp", "add", "-s", "user", "--transport", "http", name, url],
1034
+ remove: (name) => ["mcp", "remove", "-s", "user", name],
1035
+ login: (name) => ["mcp", "login", name]
1036
+ },
1037
+ codex: {
1038
+ bin: "codex",
1039
+ add: ({ name, url }) => ["mcp", "add", name, "--url", url],
1040
+ remove: (name) => ["mcp", "remove", name],
1041
+ login: (name) => ["mcp", "login", name]
1042
+ }
1043
+ };
1044
+ var OFFLINE = {
1045
+ HTTPS_PROXY: "http://127.0.0.1:9",
1046
+ HTTP_PROXY: "http://127.0.0.1:9",
1047
+ ALL_PROXY: "http://127.0.0.1:9",
1048
+ NO_PROXY: "",
1049
+ no_proxy: ""
1050
+ };
1051
+ function loginArgs(platform, env) {
1052
+ return platform === "linux" && !env.DISPLAY && !env.WAYLAND_DISPLAY ? ["--no-browser"] : [];
1053
+ }
1054
+ function complaint(stderr, stdout, fallback) {
1055
+ const lines = `${stderr}
1056
+ ${stdout}`.split("\n").map((line2) => line2.trim()).filter((line2) => line2 && !line2.startsWith("WARNING:"));
1057
+ return lines[0] ?? fallback;
1058
+ }
1059
+ var systemMcpCli = {
1060
+ run: ([bin = "", ...args], env) => {
1061
+ const command = commandFor(bin, args);
1062
+ return new Promise(
1063
+ (resolve3, reject) => execFile3(
1064
+ command.file,
1065
+ command.args,
1066
+ {
1067
+ // A project's own MCP config under the folder connect ran in must not stand in for the user's.
1068
+ cwd: homedir3(),
1069
+ timeout: 45e3,
1070
+ encoding: "utf-8",
1071
+ env: { ...process.env, ...env },
1072
+ ...command.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
1073
+ },
1074
+ (err, stdout, stderr) => err ? reject(new Error(complaint(stderr, stdout, err.message))) : resolve3(stdout)
1075
+ )
1076
+ );
1077
+ },
1078
+ interactive: ([bin = "", ...args], ms) => {
1079
+ const command = commandFor(bin, args);
1080
+ return new Promise((resolve3) => {
1081
+ const ignore = () => {
1082
+ };
1083
+ process.on("SIGINT", ignore);
1084
+ const child = spawn2(command.file, command.args, {
1085
+ cwd: homedir3(),
1086
+ stdio: "inherit",
1087
+ ...command.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
1088
+ });
1089
+ const timer = setTimeout(() => {
1090
+ child.kill();
1091
+ done(false);
1092
+ }, ms);
1093
+ let settled = false;
1094
+ function done(ok) {
1095
+ if (settled) return;
1096
+ settled = true;
1097
+ clearTimeout(timer);
1098
+ process.off("SIGINT", ignore);
1099
+ resolve3(ok);
1100
+ }
1101
+ child.on("error", () => done(false));
1102
+ child.on("exit", (code) => done(code === 0));
1103
+ });
1104
+ }
1105
+ };
1106
+ function sameServer(a, b) {
1107
+ const key = (url) => {
1108
+ try {
1109
+ const { protocol, host, pathname } = new URL(url);
1110
+ return `${protocol}//${host}${pathname.replace(/\/+$/, "")}`;
1111
+ } catch {
1112
+ return null;
1113
+ }
1114
+ };
1115
+ const left = key(a);
1116
+ return left !== null && left === key(b);
1117
+ }
1118
+ function parseClaudeList(text) {
1119
+ const listed = [];
1120
+ for (const line2 of text.split("\n")) {
1121
+ const at = line2.indexOf(": ");
1122
+ if (at <= 0) continue;
1123
+ const rest = line2.slice(at + 2);
1124
+ if (!rest.includes(" - ")) continue;
1125
+ const url = /^(https?:\/\/\S+)/.exec(rest)?.[1] ?? null;
1126
+ listed.push({ name: line2.slice(0, at), url, signedIn: /\bConnected\s*$/.test(rest) });
1127
+ }
1128
+ return listed;
1129
+ }
1130
+ function parseCodexList(json) {
1131
+ const servers = JSON.parse(json);
1132
+ return servers.flatMap(
1133
+ ({ name, transport, auth_status }) => name ? [
1134
+ {
1135
+ name,
1136
+ url: transport?.type === "streamable_http" && transport.url ? transport.url : null,
1137
+ signedIn: auth_status === "o_auth" || auth_status === "bearer_token"
1138
+ }
1139
+ ] : []
1140
+ );
1141
+ }
1142
+ async function listEntries(harness, bin, cli) {
1143
+ return harness === "codex" ? parseCodexList(await cli.run([bin, "mcp", "list", "--json"])) : parseClaudeList(await cli.run([bin, "mcp", "list"]));
1144
+ }
1145
+ async function signedInNow(harness, bin, name, cli) {
1146
+ try {
1147
+ if (harness === "claude-code")
1148
+ return /^\s*Status: .*\bConnected\b/m.test(await cli.run([bin, "mcp", "get", name]));
1149
+ return (await listEntries(harness, bin, cli)).some((e) => e.name === name && e.signedIn);
1150
+ } catch {
1151
+ return false;
1152
+ }
1153
+ }
1154
+ function shellLine(words, platform) {
1155
+ return words.map(
1156
+ (word) => platform === "win32" ? quoteWindowsArg(word) : /^[\w@%+=:,./-]+$/.test(word) ? word : `'${word.replace(/'/g, "'\\''")}'`
1157
+ ).join(" ");
1158
+ }
1159
+ async function addCloopMcp(harness, bin, server, deps) {
1160
+ const platform = deps.platform ?? process.platform;
1161
+ const words = WORDS[harness];
1162
+ const login = (name) => [
1163
+ ...words.login(name),
1164
+ ...loginArgs(platform, deps.env ?? process.env)
1165
+ ];
1166
+ const shown = (args) => shellLine([words.bin, ...args], platform);
1167
+ const result = (registered, signedIn2, reason, byHand, as = server.name) => ({
1168
+ harness,
1169
+ url: server.url,
1170
+ as,
1171
+ found: as !== server.name,
1172
+ registered,
1173
+ signedIn: signedIn2,
1174
+ reason,
1175
+ byHand
1176
+ });
1177
+ const why = (err) => err instanceof Error ? err.message : String(err);
1178
+ let entries;
1179
+ try {
1180
+ entries = await listEntries(harness, bin, deps.cli);
1181
+ } catch (err) {
1182
+ return result(false, false, why(err), [shown(words.add(server)), shown(login(server.name))]);
1183
+ }
1184
+ const own = entries.find((entry) => entry.name === server.name);
1185
+ const ours = (entry) => Boolean(entry?.url && sameServer(entry.url, server.url));
1186
+ let signedIn = ours(own) && Boolean(own?.signedIn);
1187
+ if (!ours(own)) {
1188
+ const other = entries.find((entry) => entry.name !== server.name && ours(entry));
1189
+ if (other)
1190
+ return other.signedIn ? result(true, true, null, [], other.name) : result(true, false, "not signed in", [shown(login(other.name))], other.name);
1191
+ if (own) await deps.cli.run([bin, ...words.remove(server.name)]).catch(() => {
1192
+ });
1193
+ try {
1194
+ await deps.cli.run([bin, ...words.add(server)], harness === "codex" ? OFFLINE : void 0);
1195
+ } catch (err) {
1196
+ return result(false, false, why(err), [
1197
+ ...own ? [shown(words.remove(server.name))] : [],
1198
+ shown(words.add(server)),
1199
+ shown(login(server.name))
1200
+ ]);
1201
+ }
1202
+ signedIn = await signedInNow(harness, bin, server.name, deps.cli);
1203
+ }
1204
+ if (signedIn) return result(true, true, null, []);
1205
+ if (!deps.terminal) return result(true, false, "no terminal here", [shown(login(server.name))]);
1206
+ deps.say(
1207
+ `Sign in to Cloop for ${MCP_HARNESS_NAME[harness]}. Approve the sign-in in your browser within ${LOGIN_MS / 6e4} minutes.`
1208
+ );
1209
+ if (await deps.cli.interactive([bin, ...login(server.name)], LOGIN_MS) && await signedInNow(harness, bin, server.name, deps.cli))
1210
+ return result(true, true, null, []);
1211
+ return result(true, false, "the sign-in did not finish", [shown(login(server.name))]);
1212
+ }
1213
+ function mcpByHand(harness, server, platform = process.platform, env = process.env) {
1214
+ const words = WORDS[harness];
1215
+ return [words.add(server), [...words.login(server.name), ...loginArgs(platform, env)]].map(
1216
+ (args) => shellLine([words.bin, ...args], platform)
1217
+ );
1218
+ }
1219
+ function mcpLine(result) {
1220
+ const name = MCP_HARNESS_NAME[result.harness];
1221
+ const run = result.byHand.length ? ` Run: ${result.byHand.join(", then: ")}` : "";
1222
+ if (!result.registered)
1223
+ return `Could not add the Cloop MCP server to ${name} (${result.reason}).${run}`;
1224
+ if (result.found) {
1225
+ const head = `${name} already has the Cloop MCP server as ${result.as}`;
1226
+ return result.signedIn ? `${head}, signed in.` : `${head}. It is not signed in.${run}`;
1227
+ }
1228
+ if (result.signedIn) return `${name} has the Cloop MCP server at ${result.url}, signed in.`;
1229
+ return `${name} has the Cloop MCP server at ${result.url}. It is not signed in (${result.reason}).${run}`;
1230
+ }
1231
+
1129
1232
  // src/t3-pair-link.ts
1130
1233
  var CODE = /^[A-Za-z0-9_-]{8,256}$/;
1131
1234
  function tokenOf(url) {
@@ -1169,7 +1272,10 @@ function which(bin) {
1169
1272
  }
1170
1273
  function whichPosix(bin) {
1171
1274
  try {
1172
- return execFileSync2("which", [bin], { encoding: "utf-8", env: CLEAN_ENV }).trim() || null;
1275
+ return execFileSync2("which", [bin], {
1276
+ encoding: "utf-8",
1277
+ env: { ...CLEAN_ENV, PATH: process.env.PATH }
1278
+ }).trim() || null;
1173
1279
  } catch {
1174
1280
  return null;
1175
1281
  }
@@ -1200,7 +1306,7 @@ function boxSession(t3Url, t3Bin, env, token) {
1200
1306
  }
1201
1307
  async function mintSession(t3Url, opts = {}) {
1202
1308
  const env = await workstationEnvironment(t3Url, opts.fetchFn);
1203
- const sources = opts.sources ?? defaultT3BinSources(homedir3(), opts.stored);
1309
+ const sources = opts.sources ?? defaultT3BinSources(homedir4(), opts.stored);
1204
1310
  try {
1205
1311
  const t3Bin = opts.bin ?? pickT3Bin(t3Candidates(env.serverVersion, sources), env.serverVersion);
1206
1312
  if (!t3Bin) throw new Error("no t3 binary found; pass --t3-bin or set T3_BIN");
@@ -1322,7 +1428,7 @@ function boxServiceInstalled() {
1322
1428
  platform: process.platform,
1323
1429
  kind: "workstation",
1324
1430
  environment: runnerEnvironment(),
1325
- home: homedir3(),
1431
+ home: homedir4(),
1326
1432
  uid: process.getuid?.() ?? 0,
1327
1433
  ...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
1328
1434
  }).path
@@ -1421,7 +1527,7 @@ function programFor(script, node, npx, version) {
1421
1527
  }
1422
1528
  function findNpx() {
1423
1529
  const name = process.platform === "win32" ? "npx.cmd" : "npx";
1424
- const beside = join3(dirname(process.execPath), name);
1530
+ const beside = join3(dirname2(process.execPath), name);
1425
1531
  return existsSync5(beside) ? beside : which(name);
1426
1532
  }
1427
1533
  async function awaitDaemon(since, read = readRunnerState, { timeoutMs = 15e3, pollMs = 500 } = {}) {
@@ -1612,7 +1718,7 @@ function resolveRepos(paths, toplevel, isFolder = folderAt) {
1612
1718
  if (!isFolder(full))
1613
1719
  return `${p} is not a folder. Pass --repo <path> for each folder Cloop may work in.`;
1614
1720
  const top = toplevel(full) ?? full;
1615
- if (!repos.some((r) => r.path === top)) repos.push({ label: basename4(top), path: top });
1721
+ if (!repos.some((r) => r.path === top)) repos.push({ label: basename5(top), path: top });
1616
1722
  }
1617
1723
  return repos;
1618
1724
  }
@@ -1703,8 +1809,8 @@ async function reposFor(argv) {
1703
1809
  return repos2;
1704
1810
  }
1705
1811
  const here = gitTop(process.cwd());
1706
- if (here) return [{ label: basename4(here), path: here }];
1707
- const home = homedir3();
1812
+ if (here) return [{ label: basename5(here), path: here }];
1813
+ const home = homedir4();
1708
1814
  const work = workFolder(home);
1709
1815
  const found = findCheckouts(home);
1710
1816
  let repos = [work];
@@ -1820,7 +1926,7 @@ async function installService(kind, argv, attempt, services = systemServices) {
1820
1926
  platform: services.platform,
1821
1927
  kind,
1822
1928
  environment,
1823
- home: homedir3(),
1929
+ home: homedir4(),
1824
1930
  program,
1825
1931
  env: serviceEnv(),
1826
1932
  uid: process.getuid?.() ?? 0,
@@ -1974,7 +2080,7 @@ async function connectT3(argv, attempt, fallback, chosen, services) {
1974
2080
  async function connectLocal(driver, found, argv, attempt, chosen, services) {
1975
2081
  attempt.step = "repos";
1976
2082
  const repos = await reposFor(argv);
1977
- const work = workFolder(homedir3()).path;
2083
+ const work = workFolder(homedir4()).path;
1978
2084
  attempt.workFolder = repos.every((r) => r.path === work);
1979
2085
  const harness = driver === "claude-code" ? found.claude : found.codex;
1980
2086
  const bin = which(driver === "claude-code" ? "claude" : "codex") ?? (driver === "claude-code" ? "claude" : "codex");
@@ -2068,8 +2174,8 @@ async function connect(argv, attempt, deps = {}) {
2068
2174
  );
2069
2175
  const t3Url = (flag(argv, "--t3-url") ?? DEFAULT_T3_URL).replace(/\/+$/, "");
2070
2176
  const harnessBin = (name) => process.platform === "win32" ? which(name) ?? name : name;
2071
- findLocalCodex(homedir3());
2072
- findLocalClaude(homedir3());
2177
+ findLocalCodex(homedir4());
2178
+ findLocalClaude(homedir4());
2073
2179
  const readCodex = deps.probes?.codex ?? (() => probeCodex(harnessBin("codex")));
2074
2180
  const readClaude = deps.probes?.claude ?? (() => probeClaude(harnessBin("claude")));
2075
2181
  const found = await detect(
@@ -2082,18 +2188,21 @@ async function connect(argv, attempt, deps = {}) {
2082
2188
  attempt.harnesses = harnessesFound(found);
2083
2189
  const workstation = isWorkstation(previous, boxServiceInstalled());
2084
2190
  const machine = !deps.probes;
2191
+ const terminal = deps.terminal ?? Boolean(process.stdin.isTTY && process.stdout.isTTY);
2085
2192
  const current = await prepareAgents(found, forced, workstation, {
2086
- chatGptApp: deps.chatGptApp ?? (() => machine && hasChatGptApp(homedir3())),
2087
- installCodex: deps.installCodex ?? (async () => machine && installCodex(homedir3())),
2088
- installClaude: deps.installClaude ?? (async () => machine && installClaude(homedir3())),
2193
+ chatGptApp: deps.chatGptApp ?? (() => machine && hasChatGptApp(homedir4())),
2194
+ codexHostMissing: deps.codexHostMissing ?? (() => machine && codexHostMissing(which("codex"))),
2195
+ installCodex: deps.installCodex ?? (async () => machine && installCodex(homedir4())),
2196
+ installClaude: deps.installClaude ?? (async () => machine && installClaude(homedir4())),
2089
2197
  readCodex,
2090
2198
  readClaude,
2091
2199
  updateClaude: deps.updateClaude ?? updateClaude,
2092
2200
  signInCodex: deps.signInCodex ?? (() => signInCodex(harnessBin("codex"))),
2093
2201
  signInClaude: deps.signInClaude ?? (() => signInClaude(harnessBin("claude"))),
2094
- terminal: deps.terminal ?? Boolean(process.stdin.isTTY && process.stdout.isTTY),
2095
- installed: (agent, ok) => {
2202
+ terminal,
2203
+ installed: (agent, ok, reason) => {
2096
2204
  attempt[agent === "codex" ? "codexInstall" : "claudeInstall"] = ok ? "ok" : "failed";
2205
+ if (agent === "codex") attempt.codexInstallReason = reason ?? null;
2097
2206
  }
2098
2207
  });
2099
2208
  attempt.harnesses = harnessesFound(current);
@@ -2106,16 +2215,64 @@ async function connect(argv, attempt, deps = {}) {
2106
2215
  fallback: () => fallbackDriver(current, forced, workstation),
2107
2216
  say: (line2) => out(`${bold("Cloop runner")} ${line2}`)
2108
2217
  });
2218
+ const harnesses = [];
2219
+ if (current.claude) harnesses.push({ harness: "claude-code", bin: harnessBin("claude") });
2220
+ if (current.codex) harnesses.push({ harness: "codex", bin: harnessBin("codex") });
2221
+ const mcp = deps.mcp ?? (machine ? { cli: systemMcpCli } : null);
2222
+ if (mcp) await addCloopMcpLast(harnesses, attempt, mcp, terminal);
2223
+ }
2224
+ var MCP_STEP_MS = 6 * 6e4;
2225
+ async function addCloopMcpLast(found, attempt, mcp, terminal) {
2226
+ if (!found.length) return;
2227
+ const server = mcpServer(runnerEnvironment());
2228
+ const say = (line2) => out(`${bold("Cloop runner")} ${line2}`);
2229
+ const left = new Set(found.map(({ harness }) => harness));
2230
+ const byHand = () => [...left].flatMap((harness) => mcpByHand(harness, server)).join(", then: ");
2231
+ let late = false;
2232
+ const step = (async () => {
2233
+ for (const { harness, bin } of found) {
2234
+ const result = await addCloopMcp(harness, bin, server, { cli: mcp.cli, terminal, say });
2235
+ if (late) return;
2236
+ left.delete(harness);
2237
+ if (result.registered) attempt.mcpRegistered.push(harness);
2238
+ if (result.signedIn) attempt.mcpSignedIn.push(harness);
2239
+ console.error(
2240
+ `[runner:mcp] harness=${harness} registered=${result.registered} signed_in=${result.signedIn} reason=${result.reason ?? "none"}`
2241
+ );
2242
+ out(
2243
+ result.registered ? `${bold("Cloop runner")} ${mcpLine(result)}` : `${red("\u2717")} ${mcpLine(result)}`
2244
+ );
2245
+ }
2246
+ })();
2247
+ let timer;
2248
+ const deadline = new Promise((resolve3) => {
2249
+ timer = setTimeout(() => resolve3("late"), mcp.deadlineMs ?? MCP_STEP_MS);
2250
+ });
2251
+ try {
2252
+ if (await Promise.race([step.then(() => "done"), deadline]) === "late") {
2253
+ late = true;
2254
+ console.error("[runner:mcp] outcome=timeout");
2255
+ out(`${red("\u2717")} Adding the Cloop MCP server took too long. Run: ${byHand()}`);
2256
+ }
2257
+ } catch (err) {
2258
+ late = true;
2259
+ console.error("[runner:mcp] outcome=unexpected");
2260
+ out(
2261
+ `${red("\u2717")} Could not add the Cloop MCP server (${err instanceof Error ? err.message : String(err)}). Run: ${byHand()}`
2262
+ );
2263
+ } finally {
2264
+ clearTimeout(timer);
2265
+ }
2109
2266
  }
2110
2267
  async function prepareAgents(found, forced, workstation, deps) {
2111
2268
  if (workstation || forced === "t3") return found;
2112
2269
  let current = found;
2113
2270
  const say = (line2) => out(`${bold("Cloop runner")} ${line2}`);
2114
2271
  const chatGptApp = forced !== "claude-code" && deps.chatGptApp();
2115
- const getCodex = async (why) => {
2272
+ const getCodex = async (why, reason) => {
2116
2273
  say(`${why} Installing the latest Codex from ${CODEX_RELEASES}.`);
2117
2274
  const codex = await deps.installCodex() ? await deps.readCodex() : null;
2118
- deps.installed("codex", Boolean(codex));
2275
+ deps.installed("codex", Boolean(codex), reason);
2119
2276
  if (codex) say(`Installed Codex${codex.version ? ` ${codex.version}` : ""}.`);
2120
2277
  else
2121
2278
  out(`${red("\u2717")} Codex did not install. Install it yourself: npm install -g @openai/codex`);
@@ -2123,16 +2280,28 @@ async function prepareAgents(found, forced, workstation, deps) {
2123
2280
  };
2124
2281
  const codexVersion = current.codex?.version;
2125
2282
  if (!current.codex && forced === "codex")
2126
- current = { ...current, codex: await getCodex("Codex is not installed here.") };
2283
+ current = { ...current, codex: await getCodex("Codex is not installed here.", "named") };
2127
2284
  else if (!current.codex && chatGptApp)
2128
2285
  current = {
2129
2286
  ...current,
2130
2287
  codex: await getCodex(
2131
- "The ChatGPT app is here, and Codex signs in with your ChatGPT account."
2288
+ "The ChatGPT app is here, and Codex signs in with your ChatGPT account.",
2289
+ "chatgpt_app"
2132
2290
  )
2133
2291
  };
2134
2292
  else if (current.codex && codexVersion && olderThan(codexVersion, CODEX_FLOOR))
2135
- current = { ...current, codex: await getCodex(codexTooOld(codexVersion)) ?? current.codex };
2293
+ current = {
2294
+ ...current,
2295
+ codex: await getCodex(codexTooOld(codexVersion), "floor") ?? current.codex
2296
+ };
2297
+ else if (current.codex && deps.codexHostMissing())
2298
+ current = {
2299
+ ...current,
2300
+ codex: await getCodex(
2301
+ `This Codex has no ${CODE_MODE_HOST} beside it, so none of its tools can run.`,
2302
+ "host_missing"
2303
+ ) ?? current.codex
2304
+ };
2136
2305
  if (!current.claude && (forced === "claude-code" || !current.codex && forced !== "codex")) {
2137
2306
  say(
2138
2307
  `${current.codex || forced ? "Claude Code is not installed here." : "No coding agent here."} Installing Claude Code with Anthropic's installer.`
@@ -2259,7 +2428,6 @@ async function connectCommand(argv) {
2259
2428
  }
2260
2429
 
2261
2430
  export {
2262
- T3Client,
2263
2431
  runBoxTool,
2264
2432
  probeClaudePermissions,
2265
2433
  probeClaude,