@cloop/runner 0.3.68 → 0.3.69

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 (30) hide show
  1. package/dist/{box-YFGM56QY.js → box-UOJ6ET2B.js} +156 -511
  2. package/dist/{chunk-7LPSTDZE.js → chunk-4JTIWZHB.js} +1 -1
  3. package/dist/{chunk-BVPS6DCH.js → chunk-57E5WOOP.js} +574 -1673
  4. package/dist/{chunk-TCNIRZLU.js → chunk-CLOYOD2X.js} +10 -6
  5. package/dist/{chunk-6LYMSWSB.js → chunk-DN6TQALA.js} +265 -1961
  6. package/dist/{chunk-HWNRORIZ.js → chunk-DTUNRKBC.js} +1 -1
  7. package/dist/chunk-EEG5JOZ7.js +939 -0
  8. package/dist/chunk-GAEZIKCK.js +626 -0
  9. package/dist/chunk-HIBAH65V.js +1178 -0
  10. package/dist/{chunk-7ZL3Z3IO.js → chunk-JI5FWLDU.js} +6 -6
  11. package/dist/chunk-JJWSPBM4.js +40 -0
  12. package/dist/{chunk-L7D3ANPW.js → chunk-KIYCULVE.js} +4 -2
  13. package/dist/{chunk-34VZ5LZI.js → chunk-SJAGZNFF.js} +3 -83
  14. package/dist/chunk-TPKYD3JF.js +43 -0
  15. package/dist/chunk-WCKW2Z2G.js +459 -0
  16. package/dist/chunk-ZHQSGJCE.js +85 -0
  17. package/dist/{connect-D2SXLADA.js → connect-HVOAYXWM.js} +11 -47
  18. package/dist/disconnect-DQ6WSDR7.js +163 -0
  19. package/dist/existing-runner-BSSRQFFP.js +15 -0
  20. package/dist/index.js +14 -14
  21. package/dist/{login-VNDFCJD4.js → login-4HWP4PF4.js} +3 -2
  22. package/dist/{mcp-server-XPHCDBFR.js → mcp-server-DTJVCFRG.js} +10 -10
  23. package/dist/{runner-A3HFZ727.js → runner-4XWS2RJL.js} +4 -3
  24. package/dist/{runs-DOFU45TW.js → runs-TWUGWGNU.js} +4 -2
  25. package/dist/{statusline-VA2DSWVT.js → statusline-C2FH3YQ4.js} +1 -1
  26. package/dist/{takeover-U2EHJ5GW.js → takeover-5QSP6YAG.js} +6 -4
  27. package/dist/{use-7D5GQFGB.js → use-U3E55XBK.js} +20 -13
  28. package/package.json +1 -1
  29. package/dist/disconnect-7SJKPYIN.js +0 -30
  30. package/dist/existing-runner-XT3HLIPM.js +0 -20
@@ -1,56 +1,36 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
- callOutcome,
4
- freshness,
5
- outcomeLine,
6
- runnerLog
7
- } from "./chunk-AZQGERT7.js";
8
- import {
9
- readRunnerState,
10
- runnerStatePath,
11
- threadsFilePath
12
- } from "./chunk-7LPSTDZE.js";
3
+ claudeHome,
4
+ codexHome,
5
+ revokeOwnDevice,
6
+ tokenGone
7
+ } from "./chunk-JJWSPBM4.js";
13
8
  import {
14
- BoxToolError,
15
- CLOOP_THREAD_PREFIX,
16
- ENVIRONMENTS,
17
- HARNESS_SIGNED_OUT,
9
+ BackgroundReading,
10
+ HARNESS_STALE_MS,
18
11
  IMAGE_TYPES,
19
12
  MIN_PROTOCOL,
20
- RUNTIME_MODES,
21
13
  T3Client,
22
14
  T3Driver,
23
15
  T3HttpError,
24
- apiErrorWords,
25
- boxPath,
26
- cloopCommand,
27
- commandFor,
16
+ TOKEN_DAYS,
17
+ TOKEN_SCOPE,
18
+ TOKEN_TTL_MS,
19
+ addTokens,
28
20
  defaultT3BinSources,
29
- environmentOf,
30
21
  exchangePairing,
31
- isHosted,
32
- isLocal,
33
- isYes,
34
- localRunsFilePath,
35
- otherThreadsChoice,
36
- ownHarnessFirst,
37
22
  parseAttachments,
38
23
  pickT3Bin,
39
- questionLine,
40
- quoteWindowsArg,
24
+ quotaFromClaude,
25
+ quotaFromCodex,
41
26
  readEnvironment,
42
- readRunnerConfig,
43
- redactSecrets,
44
27
  runT3Async,
45
- runnerDir,
46
- runnerEnvironment,
47
- serviceIdentity,
28
+ sortedDays,
29
+ sourceKey,
48
30
  t3BaseDirArgs,
49
31
  t3Candidates,
50
- windowsExecutable,
51
- windowsPowerShellEnv,
52
- writeBoxConfig
53
- } from "./chunk-6LYMSWSB.js";
32
+ utcWindow
33
+ } from "./chunk-DN6TQALA.js";
54
34
  import {
55
35
  CLAUDE_FLOOR,
56
36
  CODEX_FLOOR,
@@ -58,20 +38,63 @@ import {
58
38
  codexTooOld,
59
39
  olderThan
60
40
  } from "./chunk-365HFCQQ.js";
41
+ import {
42
+ FIRST_CONNECT_MS,
43
+ findNpx,
44
+ installedService,
45
+ moveLegacyStagingRunnerOnConnect,
46
+ programFor,
47
+ runSteps,
48
+ runnerOrigin,
49
+ serviceEnv,
50
+ systemServices,
51
+ unitFor
52
+ } from "./chunk-WCKW2Z2G.js";
53
+ import {
54
+ BoxToolError,
55
+ CLOOP_THREAD_PREFIX,
56
+ ENVIRONMENTS,
57
+ HARNESS_SIGNED_OUT,
58
+ LOCAL_DRIVERS,
59
+ RUNTIME_MODES,
60
+ apiErrorWords,
61
+ commandFor,
62
+ isHosted,
63
+ isLocal,
64
+ isLocalDriver,
65
+ isYes,
66
+ otherThreadsChoice,
67
+ ownHarnessFirst,
68
+ questionLine,
69
+ quoteWindowsArg,
70
+ readRunnerConfig,
71
+ runnerEnvironment,
72
+ which,
73
+ windowsPowerShellEnv,
74
+ writeBoxConfig
75
+ } from "./chunk-GAEZIKCK.js";
76
+ import {
77
+ callOutcome,
78
+ freshness,
79
+ outcomeLine,
80
+ runnerLog
81
+ } from "./chunk-AZQGERT7.js";
61
82
  import {
62
83
  READ_TOOLS,
63
84
  readOnlySettings
64
85
  } from "./chunk-PKIEWBR7.js";
65
86
  import {
66
87
  connectWebhook
67
- } from "./chunk-L7D3ANPW.js";
88
+ } from "./chunk-KIYCULVE.js";
89
+ import {
90
+ deviceLogin
91
+ } from "./chunk-SJAGZNFF.js";
68
92
  import {
69
93
  ConnectFailure,
70
94
  connectReport,
71
- deviceLogin,
72
95
  newAttempt,
73
96
  sendConnectReport
74
- } from "./chunk-34VZ5LZI.js";
97
+ } from "./chunk-ZHQSGJCE.js";
75
98
  import {
76
99
  defaultDeviceName,
77
100
  getMachine,
@@ -79,7 +102,7 @@ import {
79
102
  } from "./chunk-SBYSVZ7J.js";
80
103
  import {
81
104
  VERSION
82
- } from "./chunk-HWNRORIZ.js";
105
+ } from "./chunk-DTUNRKBC.js";
83
106
  import {
84
107
  STAGING_ORIGIN,
85
108
  getOrigin,
@@ -88,20 +111,19 @@ import {
88
111
  } from "./chunk-D5UZW42X.js";
89
112
 
90
113
  // src/commands/connect.ts
91
- import { execFileSync as execFileSync2, spawnSync } from "child_process";
114
+ import { execFileSync, spawnSync } from "child_process";
92
115
  import { randomUUID } from "crypto";
93
116
  import {
94
- existsSync as existsSync6,
95
- mkdirSync as mkdirSync3,
96
- readdirSync as readdirSync4,
97
- realpathSync as realpathSync2,
98
- rmSync as rmSync3,
99
- statSync as statSync2,
100
- writeFileSync as writeFileSync2
117
+ existsSync as existsSync3,
118
+ mkdirSync,
119
+ readdirSync as readdirSync2,
120
+ rmSync,
121
+ statSync,
122
+ writeFileSync
101
123
  } from "fs";
102
- import { homedir as homedir6, userInfo } from "os";
103
- import { basename as basename5, dirname as dirname3, join as join8, resolve as resolve2 } from "path";
104
- import { createInterface } from "readline/promises";
124
+ import { homedir as homedir3, userInfo } from "os";
125
+ import { basename as basename4, join as join4, resolve as resolve2 } from "path";
126
+ import { createInterface as createInterface2 } from "readline/promises";
105
127
  import { Writable } from "stream";
106
128
 
107
129
  // src/agent-install.ts
@@ -121,8 +143,8 @@ function codexAsset(platform, arch) {
121
143
  const triple = CODEX_TRIPLES[`${platform}-${arch}`];
122
144
  return triple ? `codex-package-${triple}` : null;
123
145
  }
124
- var codexHome = (home) => join(home, ".cloop", "codex");
125
- var codexBinDir = (home) => join(codexHome(home), "bin");
146
+ var codexHome2 = (home) => join(home, ".cloop", "codex");
147
+ var codexBinDir = (home) => join(codexHome2(home), "bin");
126
148
  var CODE_MODE_HOST = "codex-code-mode-host";
127
149
  var exe = (name, platform) => platform === "win32" ? `${name}.exe` : name;
128
150
  var oneFileCodex = (home, platform) => join(home, ".cloop", "bin", exe("codex", platform));
@@ -131,7 +153,7 @@ var CODEX_SUMS = `${CODEX_RELEASES}/codex-package_SHA256SUMS`;
131
153
  function codexInstallCommand(home, platform = process.platform, arch = process.arch) {
132
154
  const asset = codexAsset(platform, arch);
133
155
  if (!asset) return null;
134
- const dir = codexHome(home);
156
+ const dir = codexHome2(home);
135
157
  const file = `${asset}.tar.gz`;
136
158
  const url = `${CODEX_RELEASES}/${file}`;
137
159
  const old = oneFileCodex(home, platform);
@@ -440,20 +462,20 @@ function macChrome(over = {}) {
440
462
  // src/box-tools.ts
441
463
  var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
442
464
  function parseLaunchArgs(args) {
443
- const str2 = (v, max) => typeof v === "string" && v.trim() && v.length <= max ? v.trim() : void 0;
444
- const work_id = str2(args.work_id, 36);
445
- const title = str2(args.title, 200);
446
- const prompt = str2(args.prompt, 1e5);
465
+ const str = (v, max) => typeof v === "string" && v.trim() && v.length <= max ? v.trim() : void 0;
466
+ const work_id = str(args.work_id, 36);
467
+ const title = str(args.title, 200);
468
+ const prompt = str(args.prompt, 1e5);
447
469
  if (!work_id || !UUID.test(work_id) || !title || !prompt) throw new BoxToolError("bad_args");
448
- const runtime_mode = str2(args.runtime_mode, 40);
470
+ const runtime_mode = str(args.runtime_mode, 40);
449
471
  if (runtime_mode && !RUNTIME_MODES.has(runtime_mode)) throw new BoxToolError("bad_args");
450
472
  return {
451
473
  work_id,
452
474
  title: title.startsWith(CLOOP_THREAD_PREFIX) ? title : `${CLOOP_THREAD_PREFIX} ${title}`,
453
475
  prompt,
454
- repository: str2(args.repository, 200),
455
- harness: str2(args.harness, 80),
456
- model: str2(args.model, 120),
476
+ repository: str(args.repository, 200),
477
+ harness: str(args.harness, 80),
478
+ model: str(args.model, 120),
457
479
  runtime_mode,
458
480
  attachments: parseAttachments(args.attachments)
459
481
  };
@@ -608,28 +630,6 @@ async function checkOwnDevice(origin, deviceToken, fetchFn = fetch) {
608
630
  }
609
631
  }
610
632
 
611
- // src/device-revoke.ts
612
- function tokenGone(revoke) {
613
- return revoke === "revoked" || revoke === "already_revoked" || revoke === "no_device";
614
- }
615
- async function revokeOwnDevice(origin, deviceToken, fetchFn = fetch) {
616
- if (!deviceToken) return "no_device";
617
- try {
618
- const res = await fetchFn(`${origin}/api/agent/mesh/device-revoke`, {
619
- method: "POST",
620
- headers: { authorization: `Bearer ${deviceToken}` },
621
- signal: AbortSignal.timeout(1e4)
622
- });
623
- const body = await res.json().catch(() => null);
624
- if (res.ok && body?.outcome === "revoked") return "revoked";
625
- if (res.ok && body?.outcome === "already_revoked") return "already_revoked";
626
- if (res.status === 401 && body?.error === "unknown_device") return "unknown_device";
627
- return "failed";
628
- } catch {
629
- return "failed";
630
- }
631
- }
632
-
633
633
  // src/drivers/claude-code.ts
634
634
  import { execFile as execFile2 } from "child_process";
635
635
  import { readFileSync } from "fs";
@@ -1062,1167 +1062,438 @@ function codexDialect(bin = "codex") {
1062
1062
  };
1063
1063
  }
1064
1064
 
1065
- // src/legacy-staging.ts
1066
- import { existsSync as existsSync5, mkdirSync as mkdirSync2, renameSync as renameSync2, rmSync as rmSync2 } from "fs";
1067
- import { homedir as homedir4 } from "os";
1068
- import { join as join7 } from "path";
1069
-
1070
- // src/commands/disconnect.ts
1071
- import { execFileSync } from "child_process";
1072
- import { existsSync as existsSync4, readFileSync as readFileSync3, rmSync } from "fs";
1073
- import { homedir as homedir3 } from "os";
1074
- import { basename as basename4 } from "path";
1075
-
1076
- // src/existing-runner.ts
1077
- import { existsSync as existsSync3 } from "fs";
1078
- var ALL = Object.keys(ENVIRONMENTS);
1079
- function runnersOnThisComputer() {
1080
- if (legacyStagingRunner()) return ["staging"];
1081
- return ALL.filter((env) => existsSync3(boxPath(env)));
1082
- }
1083
- function existingRunnerEnvironment() {
1084
- const named = process.env.CLOOP_ORIGIN;
1085
- if (named) return environmentOf(named);
1086
- const found = runnersOnThisComputer();
1087
- return found.length === 1 && found[0] ? found[0] : "production";
1088
- }
1089
- var BOTH_RUNNERS_LINE = "This computer is a production machine and a staging machine. This acts on the production machine. Add --staging for the staging machine.";
1090
- function pinExistingRunner() {
1091
- const named = Boolean(process.env.CLOOP_ORIGIN);
1092
- const environment = existingRunnerEnvironment();
1093
- pinRunnerEnvironment(runnerOrigin(environment) ?? ENVIRONMENTS[environment].origin);
1094
- return {
1095
- environment: runnerEnvironment(),
1096
- note: !named && runnersOnThisComputer().length === ALL.length ? BOTH_RUNNERS_LINE : null
1097
- };
1098
- }
1099
-
1100
- // src/threads/capture.ts
1101
- import {
1102
- chmodSync,
1103
- closeSync,
1104
- mkdirSync,
1105
- openSync,
1106
- readFileSync as readFileSync2,
1107
- readSync,
1108
- renameSync,
1109
- statSync,
1110
- unlinkSync,
1111
- writeFileSync
1112
- } from "fs";
1113
- import { dirname as dirname2, join as join6 } from "path";
1114
-
1115
- // src/threads/claude-code.ts
1116
- import { readdirSync as readdirSync2 } from "fs";
1117
- import { join as join4 } from "path";
1118
-
1119
- // src/harness-home.ts
1120
- import { homedir as homedir2 } from "os";
1065
+ // src/drivers/local-usage.ts
1066
+ import { spawn as spawn2 } from "child_process";
1067
+ import { createReadStream } from "fs";
1068
+ import { readdir as readdir2, realpath, stat } from "fs/promises";
1069
+ import { hostname, tmpdir as tmpdir2 } from "os";
1121
1070
  import { join as join3 } from "path";
1122
- function claudeHome() {
1123
- return process.env.CLAUDE_CONFIG_DIR || join3(homedir2(), ".claude");
1124
- }
1125
- function codexHome2() {
1126
- return process.env.CODEX_HOME || join3(homedir2(), ".codex");
1127
- }
1128
-
1129
- // src/threads/turns.ts
1130
- var TURN_TEXT_MAX = 2e4;
1131
- var TURN_ACTIONS_MAX = 100;
1132
- var COMMAND_MAX = 300;
1133
- var PATH_MAX = 1e3;
1134
- var BATCH_TURNS_MAX = 200;
1135
- var CWD_MAX = 1e3;
1136
- var BRANCH_MAX = 300;
1137
- var TITLE_MAX = 300;
1138
- var TASK_TOOL_MAX = 100;
1139
- var HOST_ID_MAX = 300;
1140
- var OWNER_TURNS_HOSTED = 1;
1141
- var OWNER_TURNS_BARE = 2;
1142
- var HOST_NOTICES = [
1143
- "Update on pull request",
1144
- "Delegated task node",
1145
- "Background command completed",
1146
- "T3 Code stopped watching",
1147
- "Note: the T3 server restarted"
1148
- ];
1149
- function isHostNotice(text) {
1150
- return HOST_NOTICES.some((prefix) => text.startsWith(prefix));
1151
- }
1152
- var PR_URL = /https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/pull\/\d+/g;
1153
- var COMMIT_LINE = /^\[(?:[^\]\n]+ )?([0-9a-f]{7,40})\] [^\n]*\n\s*\d+ files? changed/gm;
1154
- function foundActions(text) {
1155
- const actions = [];
1156
- for (const m of text.matchAll(PR_URL)) actions.push({ kind: "pr", url: m[0] });
1157
- for (const m of text.matchAll(COMMIT_LINE)) actions.push({ kind: "commit", sha: m[1] });
1158
- return actions;
1159
- }
1160
- function commandAction(command) {
1161
- const flat = redactSecrets(command.trim());
1162
- if (!flat) return null;
1163
- return {
1164
- kind: "command",
1165
- command: flat.length > COMMAND_MAX ? `${flat.slice(0, COMMAND_MAX - 1)}\u2026` : flat
1166
- };
1167
- }
1168
- function editAction(path) {
1169
- return typeof path === "string" && path && path.length <= PATH_MAX ? { kind: "edit", path } : null;
1170
- }
1171
- var UUID2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1172
- var TASK_ID_KEYS = ["lineage_id", "lineageId", "task_id", "taskId", "item_id", "itemId"];
1173
- function taskAction(tool, input) {
1174
- if (!tool || tool.length > TASK_TOOL_MAX || !isRecord(input)) return null;
1175
- const keys = /task/i.test(tool) ? [...TASK_ID_KEYS, "id"] : TASK_ID_KEYS;
1176
- for (const key of keys) {
1177
- const value = input[key];
1178
- if (typeof value === "string" && UUID2.test(value))
1179
- return { kind: "task", id: value.toLowerCase(), tool };
1180
- }
1181
- return null;
1182
- }
1183
- var NONE = { kind: "none" };
1184
- var ONCE = { kind: "once" };
1185
- function pullRequest(input) {
1186
- if (typeof input.url === "string") return input.url.match(PR_URL)?.[0] ?? str(input.url);
1187
- const repo = str(input.repository);
1188
- const number = input.number;
1189
- return repo && (typeof number === "number" || typeof number === "string") ? `https://github.com/${repo}/pull/${number}` : void 0;
1190
- }
1191
- function background(input) {
1192
- return input.run_in_background === true ? ONCE : NONE;
1193
- }
1194
- var WAKE_TOOLS = {
1195
- t3_background_wait: () => ONCE,
1196
- watch_pull_request: (input) => {
1197
- const url = pullRequest(input);
1198
- return url ? { kind: "watch", url } : NONE;
1199
- },
1200
- unwatch_pull_request: (input) => {
1201
- const url = pullRequest(input);
1202
- return url ? { kind: "unwatch", url } : NONE;
1203
- },
1204
- // `{ stop: true }` ends a /loop: it cancels the wakeup instead.
1205
- ScheduleWakeup: (input) => input.stop === true ? NONE : ONCE,
1206
- Monitor: () => ONCE,
1207
- Bash: background,
1208
- Agent: background
1209
- };
1210
- function toolWake(name, input) {
1211
- const short = name.split("__").at(-1);
1212
- if (!Object.hasOwn(WAKE_TOOLS, short)) return NONE;
1213
- return WAKE_TOOLS[short](
1214
- isRecord(input) ? input : {}
1215
- );
1216
- }
1217
- function isRecord(value) {
1218
- return typeof value === "object" && value !== null && !Array.isArray(value);
1219
- }
1220
- function str(value) {
1221
- return typeof value === "string" && value ? value : void 0;
1222
- }
1223
-
1224
- // src/threads/claude-code.ts
1225
- var UUID3 = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;
1226
- var NOT_TYPED = [
1227
- "<local-command-",
1228
- "<task-notification>",
1229
- "<bash-",
1230
- "<user-memory-input>",
1231
- "<system-reminder>"
1232
- ];
1233
- var CLOOP_TOOL = /^mcp__cloop(?:[-_]staging)?__(.+)$/;
1234
- var EDIT_TOOLS = {
1235
- Edit: "file_path",
1236
- Write: "file_path",
1237
- MultiEdit: "file_path",
1238
- NotebookEdit: "notebook_path"
1239
- };
1240
- function files(home) {
1241
- const root = join4(home, "projects");
1242
- const out2 = [];
1243
- for (const project of safeDir(root)) {
1244
- if (!project.isDirectory()) continue;
1245
- for (const entry of safeDir(join4(root, project.name))) {
1246
- if (!entry.isFile() || !entry.name.endsWith(".jsonl")) continue;
1247
- const sessionId = entry.name.slice(0, -6);
1248
- if (UUID3.test(sessionId)) out2.push({ path: join4(root, project.name, entry.name), sessionId });
1249
- }
1250
- }
1251
- return out2;
1252
- }
1253
- function safeDir(dir) {
1071
+ import { createInterface } from "readline";
1072
+ var PROBE_TIMEOUT_MS = 1e4;
1073
+ var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1074
+ var count = (v) => typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0;
1075
+ var parse = (line2) => {
1254
1076
  try {
1255
- return readdirSync2(dir, { withFileTypes: true });
1077
+ return JSON.parse(line2);
1256
1078
  } catch {
1257
- return [];
1079
+ return void 0;
1258
1080
  }
1259
- }
1260
- function typedText(content) {
1261
- const text = typeof content === "string" ? content : Array.isArray(content) ? content.filter((b) => isRecord(b) && b.type === "text" && typeof b.text === "string").map((b) => b.text).join("\n") : "";
1262
- const trimmed = text.trim();
1263
- if (!trimmed) return null;
1264
- const command = /<command-name>([^<]*)<\/command-name>/.exec(trimmed);
1265
- if (command) {
1266
- const args = /<command-args>([\s\S]*?)<\/command-args>/.exec(trimmed)?.[1] ?? "";
1267
- return `${command[1]?.trim()} ${args.trim()}`.trim();
1268
- }
1269
- if (trimmed.startsWith("<command-message>")) return null;
1270
- return NOT_TYPED.some((prefix) => trimmed.startsWith(prefix)) || isHostNotice(trimmed) ? null : trimmed;
1271
- }
1272
- function resultText(block) {
1273
- const content = block.content;
1274
- if (typeof content === "string") return content;
1275
- if (!Array.isArray(content)) return "";
1276
- return content.filter((b) => isRecord(b) && b.type === "text" && typeof b.text === "string").map((b) => b.text).join("\n");
1277
- }
1278
- function userSignals(r, at) {
1279
- const content = isRecord(r.message) ? r.message.content : void 0;
1280
- if (Array.isArray(content) && content.some((b) => isRecord(b) && b.type === "tool_result")) {
1281
- const actions = content.filter(isRecord).filter((b) => b.type === "tool_result").flatMap((b) => foundActions(resultText(b)));
1282
- return actions.length ? [{ kind: "agent", at, actions }] : [];
1283
- }
1284
- if (r.isMeta === true || r.isCompactSummary === true || r.origin !== void 0) return [];
1285
- const text = typedText(content);
1286
- return text ? [{ kind: "owner", at, text }] : [];
1287
- }
1288
- function toolAction(block) {
1289
- const name = str(block.name);
1290
- const input = isRecord(block.input) ? block.input : {};
1291
- if (!name) return null;
1292
- const field = EDIT_TOOLS[name];
1293
- if (field) return editAction(input[field]);
1294
- if (name === "Bash" && typeof input.command === "string") return commandAction(input.command);
1295
- const cloop = CLOOP_TOOL.exec(name);
1296
- return cloop ? taskAction(cloop[1], input) : null;
1297
- }
1298
- function assistantSignals(r, at) {
1299
- const message = isRecord(r.message) ? r.message : {};
1300
- const blocks = Array.isArray(message.content) ? message.content.filter(isRecord) : [];
1301
- const text = blocks.filter((b) => b.type === "text" && typeof b.text === "string").map((b) => b.text).join("\n\n").trim();
1302
- const uses = blocks.filter((b) => b.type === "tool_use");
1303
- const actions = [
1304
- ...uses.map(toolAction).filter((a) => a !== null),
1305
- ...foundActions(text)
1306
- ];
1307
- const calls = uses.map((b) => toolWake(str(b.name) ?? "", b.input));
1308
- const signals = [];
1309
- if (text || actions.length || calls.length)
1310
- signals.push({
1311
- kind: "agent",
1312
- at,
1313
- ...text ? { text } : {},
1314
- ...actions.length ? { actions } : {},
1315
- ...calls.length ? { calls } : {}
1081
+ };
1082
+ function askHarness(bin, args, requests, answer, timeoutMs = PROBE_TIMEOUT_MS) {
1083
+ const command = commandFor(bin, args);
1084
+ return new Promise((resolve3, reject) => {
1085
+ const child = spawn2(command.file, command.args, {
1086
+ cwd: tmpdir2(),
1087
+ stdio: ["pipe", "pipe", "ignore"],
1088
+ env: process.env,
1089
+ windowsHide: true,
1090
+ ...command.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
1316
1091
  });
1317
- const stop = message.stop_reason;
1318
- if (text && (stop === "end_turn" || stop === "stop_sequence")) signals.push({ kind: "end", at });
1319
- return signals;
1320
- }
1321
- function parse(record) {
1322
- if (!isRecord(record) || record.isSidechain === true) return [];
1323
- const signals = [];
1324
- const cwd = str(record.cwd);
1325
- const branch = str(record.gitBranch);
1326
- if (cwd || branch)
1327
- signals.push({ kind: "thread", ...cwd ? { cwd } : {}, ...branch ? { branch } : {} });
1328
- const at = str(record.timestamp);
1329
- switch (record.type) {
1330
- case "user":
1331
- if (at) signals.push(...userSignals(record, at));
1332
- break;
1333
- case "assistant":
1334
- if (at) signals.push(...assistantSignals(record, at));
1335
- break;
1336
- case "pr-link": {
1337
- const url = str(record.prUrl);
1338
- if (at && url) signals.push({ kind: "agent", at, actions: foundActions(url) });
1339
- break;
1340
- }
1341
- case "summary":
1342
- case "ai-title": {
1343
- const title = str(record.summary) ?? str(record.aiTitle);
1344
- if (title) signals.push({ kind: "thread", title });
1345
- break;
1346
- }
1347
- case "custom-title": {
1348
- const customTitle = str(record.customTitle);
1349
- if (customTitle) signals.push({ kind: "thread", customTitle });
1350
- break;
1351
- }
1352
- }
1353
- return signals;
1354
- }
1355
- var claudeCodeLogs = { home: claudeHome, files, parse };
1356
-
1357
- // src/threads/codex.ts
1358
- import { readdirSync as readdirSync3 } from "fs";
1359
- import { join as join5 } from "path";
1360
- var ROLLOUT = /^rollout-.*([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})\.jsonl$/i;
1361
- var INJECTED = [
1362
- "<environment_context",
1363
- "<user_instructions",
1364
- "# AGENTS.md instructions",
1365
- "<INSTRUCTIONS>",
1366
- "<skill>",
1367
- "<recommended_plugins",
1368
- "<permissions instructions",
1369
- "<turn_aborted",
1370
- "<user_shell_command",
1371
- "<subagent_notification",
1372
- "<model_switch",
1373
- "[Historical user",
1374
- "Context handoff"
1375
- ];
1376
- function files2(home) {
1377
- const out2 = [];
1378
- const walk = (dir, depth) => {
1379
- for (const entry of safeDir2(dir)) {
1380
- const path = join5(dir, entry.name);
1381
- if (entry.isDirectory() && depth < 3) walk(path, depth + 1);
1382
- else if (entry.isFile() && depth === 3) {
1383
- const m = ROLLOUT.exec(entry.name);
1384
- if (m) out2.push({ path, sessionId: m[1].toLowerCase() });
1385
- }
1386
- }
1387
- };
1388
- walk(join5(home, "sessions"), 0);
1389
- return out2;
1092
+ let settled = false;
1093
+ const finish = (err, value) => {
1094
+ if (settled) return;
1095
+ settled = true;
1096
+ clearTimeout(timer);
1097
+ child.stdin?.end();
1098
+ child.kill();
1099
+ setTimeout(() => {
1100
+ if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
1101
+ }, 2e3).unref();
1102
+ if (err) reject(err);
1103
+ else resolve3(value);
1104
+ };
1105
+ const timer = setTimeout(
1106
+ () => finish(new Error(`no answer in ${timeoutMs / 1e3} s`)),
1107
+ timeoutMs
1108
+ );
1109
+ child.on("error", (err) => finish(err));
1110
+ child.on("close", () => finish(new Error("it exited before it answered")));
1111
+ child.stdin?.on("error", () => {
1112
+ });
1113
+ createInterface({ input: child.stdout }).on("line", (line2) => {
1114
+ const msg = parse(line2);
1115
+ const value = isObject(msg) ? answer(msg) : void 0;
1116
+ if (value !== void 0) finish(null, value);
1117
+ });
1118
+ child.stdin?.write(requests.map((r) => `${JSON.stringify(r)}
1119
+ `).join(""));
1120
+ });
1390
1121
  }
1391
- function safeDir2(dir) {
1122
+ var reason = (err) => err?.message ?? "the probe failed";
1123
+ async function probeClaudeQuota(bin = "claude", timeoutMs = PROBE_TIMEOUT_MS) {
1124
+ const args = [
1125
+ "--print",
1126
+ "--verbose",
1127
+ "--output-format",
1128
+ "stream-json",
1129
+ "--input-format",
1130
+ "stream-json",
1131
+ "--settings",
1132
+ JSON.stringify({ disableAllHooks: true }),
1133
+ "--strict-mcp-config",
1134
+ "--no-session-persistence",
1135
+ "--disable-slash-commands"
1136
+ ];
1137
+ const request = (id, request2) => ({
1138
+ type: "control_request",
1139
+ request_id: id,
1140
+ request: request2
1141
+ });
1392
1142
  try {
1393
- return readdirSync3(dir, { withFileTypes: true });
1394
- } catch {
1395
- return [];
1396
- }
1397
- }
1398
- function blockText(content, type) {
1399
- if (!Array.isArray(content)) return "";
1400
- return content.filter((b) => isRecord(b) && b.type === type && typeof b.text === "string").map((b) => b.text).join("\n").trim();
1401
- }
1402
- function ownerText(r, p) {
1403
- const meta = isRecord(r.metadata) ? r.metadata : {};
1404
- if (meta.inherited_user_message === true) return null;
1405
- const passthrough = isRecord(p.internal_chat_message_metadata_passthrough) ? p.internal_chat_message_metadata_passthrough : {};
1406
- const kinds = passthrough.content_item_kinds;
1407
- if (Array.isArray(kinds) && kinds.some((k) => typeof k !== "string" || !k.startsWith("user.")))
1408
- return null;
1409
- const text = blockText(p.content, "input_text");
1410
- if (!text || INJECTED.some((prefix) => text.startsWith(prefix)) || isHostNotice(text))
1411
- return null;
1412
- return text;
1413
- }
1414
- function commandText(command) {
1415
- if (typeof command === "string") return command;
1416
- if (!Array.isArray(command) || !command.every((c) => typeof c === "string")) return null;
1417
- const argv = command;
1418
- if (argv.length >= 3 && (argv[1] === "-lc" || argv[1] === "-c")) return argv[2];
1419
- return argv.join(" ");
1420
- }
1421
- function patchedPaths(patch) {
1422
- return [...patch.matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/gm)].map((m) => editAction(m[1]?.trim())).filter((a) => a !== null);
1423
- }
1424
- function scriptCommands(script) {
1425
- const out2 = [];
1426
- for (const m of script.matchAll(
1427
- /tools\.exec_command\(\s*\{\s*"?cmd"?\s*:\s*("(?:[^"\\]|\\.)*")/g
1428
- )) {
1429
- try {
1430
- const action = commandAction(JSON.parse(m[1]));
1431
- if (action) out2.push(action);
1432
- } catch {
1433
- }
1143
+ const response = await askHarness(
1144
+ bin,
1145
+ args,
1146
+ [
1147
+ request("cloop-init", { subtype: "initialize" }),
1148
+ request("cloop-usage", { subtype: "get_usage", skip_behaviors: true })
1149
+ ],
1150
+ (msg) => {
1151
+ const r = msg.type === "control_response" ? msg.response : void 0;
1152
+ return isObject(r) && r.request_id === "cloop-usage" ? r : void 0;
1153
+ },
1154
+ timeoutMs
1155
+ );
1156
+ return quotaFromClaude(response, (/* @__PURE__ */ new Date()).toISOString());
1157
+ } catch (err) {
1158
+ return quotaFromClaude({ subtype: "error", error: reason(err) }, (/* @__PURE__ */ new Date()).toISOString());
1434
1159
  }
1435
- return [...out2, ...patchedPaths(script)];
1436
- }
1437
- var CLOOP_SERVER = /^cloop(?:[-_]staging)?$/;
1438
- var CLOOP_FUNCTION = /^mcp__cloop(?:[-_]staging)?__(.+)$/;
1439
- function mcpTaskAction(call) {
1440
- const server = str(call.server);
1441
- const tool = str(call.tool);
1442
- if (!server || !tool || !CLOOP_SERVER.test(server)) return [];
1443
- const args = typeof call.arguments === "string" ? parseArgs(call.arguments) : call.arguments;
1444
- const action = taskAction(tool, args);
1445
- return action ? [action] : [];
1446
- }
1447
- function mcpWake(call) {
1448
- return toolWake(
1449
- str(call.tool) ?? "",
1450
- typeof call.arguments === "string" ? parseArgs(call.arguments) : call.arguments
1451
- );
1452
1160
  }
1453
- function parseArgs(raw) {
1454
- if (typeof raw !== "string") return {};
1161
+ async function probeCodexQuota(bin = "codex", timeoutMs = PROBE_TIMEOUT_MS) {
1455
1162
  try {
1456
- const parsed = JSON.parse(raw);
1457
- return isRecord(parsed) ? parsed : {};
1458
- } catch {
1459
- return {};
1460
- }
1461
- }
1462
- function callActions(p) {
1463
- const name = str(p.name);
1464
- if (p.type === "local_shell_call") {
1465
- const action = isRecord(p.action) ? commandText(p.action.command) : null;
1466
- const command = action ? commandAction(action) : null;
1467
- return command ? [command] : [];
1468
- }
1469
- if (p.type === "custom_tool_call") {
1470
- const input = typeof p.input === "string" ? p.input : "";
1471
- if (name === "apply_patch") return patchedPaths(input);
1472
- if (name === "exec") return scriptCommands(input);
1473
- return [];
1474
- }
1475
- const args = parseArgs(p.arguments);
1476
- if (name === "shell" || name === "container.exec" || name === "exec_command") {
1477
- const text = commandText(args.command ?? args.cmd);
1478
- const command = text ? commandAction(text) : null;
1479
- return command ? [command] : [];
1480
- }
1481
- if (name === "apply_patch" && typeof args.input === "string") return patchedPaths(args.input);
1482
- const cloop = name ? CLOOP_FUNCTION.exec(name) : null;
1483
- const task = cloop ? taskAction(cloop[1], args) : null;
1484
- return task ? [task] : [];
1485
- }
1486
- function outputText(output) {
1487
- if (typeof output === "string") return output;
1488
- if (isRecord(output) && typeof output.content === "string") return output.content;
1489
- if (Array.isArray(output))
1490
- return output.filter((b) => isRecord(b) && typeof b.text === "string").map((b) => b.text).join("\n");
1491
- return "";
1492
- }
1493
- function changedPaths(changes) {
1494
- return isRecord(changes) ? Object.keys(changes).map(editAction).filter((a) => a !== null) : [];
1495
- }
1496
- function itemActions(item) {
1497
- if (item.type === "FileChange") return changedPaths(item.changes);
1498
- if (item.type === "McpToolCall") return mcpTaskAction(item);
1499
- if (item.type === "CommandExecution") {
1500
- const text = commandText(item.command);
1501
- const command = text ? commandAction(text) : null;
1502
- const stdout = typeof item.stdout === "string" ? foundActions(item.stdout) : [];
1503
- return [...command ? [command] : [], ...stdout];
1163
+ const answer = await askHarness(
1164
+ bin,
1165
+ ["app-server"],
1166
+ [
1167
+ {
1168
+ id: 1,
1169
+ method: "initialize",
1170
+ params: { clientInfo: { name: "cloop-runner", version: VERSION } }
1171
+ },
1172
+ { method: "initialized" },
1173
+ { id: 2, method: "account/rateLimits/read" }
1174
+ ],
1175
+ (msg) => msg.id === 2 ? msg : void 0,
1176
+ timeoutMs
1177
+ );
1178
+ return quotaFromCodex(answer, (/* @__PURE__ */ new Date()).toISOString());
1179
+ } catch (err) {
1180
+ return quotaFromCodex({ error: { message: reason(err) } }, (/* @__PURE__ */ new Date()).toISOString());
1504
1181
  }
1505
- return [];
1506
- }
1507
- function agent(at, actions, calls = []) {
1508
- return actions.length || calls.length ? [{ kind: "agent", at, actions, ...calls.length ? { calls } : {} }] : [];
1509
1182
  }
1510
- function responseItem(r, p, at) {
1511
- switch (p.type) {
1512
- case "message": {
1513
- if (p.role === "user") {
1514
- const text2 = ownerText(r, p);
1515
- return text2 ? [{ kind: "owner", at, text: text2 }] : [];
1516
- }
1517
- if (p.role !== "assistant") return [];
1518
- const text = blockText(p.content, "output_text");
1519
- if (!text) return [];
1520
- const found = foundActions(text);
1521
- return [{ kind: "agent", at, text, ...found.length ? { actions: found } : {} }];
1522
- }
1523
- case "function_call":
1524
- case "custom_tool_call":
1525
- case "local_shell_call":
1526
- return agent(at, callActions(p), [toolWake(str(p.name) ?? "", parseArgs(p.arguments))]);
1527
- case "function_call_output":
1528
- case "custom_tool_call_output":
1529
- return agent(at, foundActions(outputText(p.output)));
1530
- default:
1531
- return [];
1183
+ async function listLogs(dir, depth, match, found) {
1184
+ for (const entry of await readdir2(dir, { withFileTypes: true })) {
1185
+ const path = join3(dir, entry.name);
1186
+ if (entry.isFile() && match(entry.name)) found.files.push(path);
1187
+ else if (entry.isDirectory() && depth > 1)
1188
+ await listLogs(path, depth - 1, match, found).catch(() => {
1189
+ found.skipped++;
1190
+ });
1532
1191
  }
1533
1192
  }
1534
- function eventMsg(p, at) {
1535
- switch (p.type) {
1536
- case "task_complete":
1537
- case "turn_aborted":
1538
- return [{ kind: "end", at }];
1539
- case "mcp_tool_call_end":
1540
- return isRecord(p.invocation) ? agent(at, mcpTaskAction(p.invocation), [mcpWake(p.invocation)]) : [];
1541
- case "patch_apply_end":
1542
- return agent(at, changedPaths(p.changes));
1543
- case "item_completed":
1544
- if (!isRecord(p.item)) return [];
1545
- return agent(at, itemActions(p.item), p.item.type === "McpToolCall" ? [mcpWake(p.item)] : []);
1546
- default:
1547
- return [];
1193
+ async function readLines(file, read) {
1194
+ let malformed = 0;
1195
+ let lastBad = false;
1196
+ const lines = createInterface({
1197
+ input: createReadStream(file, "utf-8"),
1198
+ crlfDelay: Number.POSITIVE_INFINITY
1199
+ });
1200
+ for await (const line2 of lines) {
1201
+ lastBad = !read(line2);
1202
+ if (lastBad) malformed++;
1548
1203
  }
1204
+ return lastBad ? malformed - 1 : malformed;
1549
1205
  }
1550
- function parse2(record) {
1551
- if (!isRecord(record) || !isRecord(record.payload)) return [];
1552
- const p = record.payload;
1553
- const at = str(record.timestamp);
1554
- switch (record.type) {
1555
- case "session_meta": {
1556
- const source = isRecord(p.source) ? p.source : {};
1557
- if (p.parent_thread_id || source.subagent) return [{ kind: "subagent" }];
1558
- const git = isRecord(p.git) ? p.git : {};
1559
- const cwd = str(p.cwd);
1560
- const branch = str(git.branch);
1561
- return [{ kind: "thread", ...cwd ? { cwd } : {}, ...branch ? { branch } : {} }];
1562
- }
1563
- case "turn_context": {
1564
- const cwd = str(p.cwd);
1565
- return cwd ? [{ kind: "thread", cwd }] : [];
1566
- }
1567
- case "response_item":
1568
- return at ? responseItem(record, p, at) : [];
1569
- case "event_msg":
1570
- return at ? eventMsg(p, at) : [];
1571
- default:
1572
- return [];
1573
- }
1206
+ function dayOf(v) {
1207
+ const ms = typeof v === "string" ? Date.parse(v) : Number.NaN;
1208
+ return Number.isFinite(ms) ? new Date(ms).toISOString().slice(0, 10) : null;
1574
1209
  }
1575
- var codexLogs = { home: codexHome2, files: files2, parse: parse2 };
1576
-
1577
- // src/threads/capture.ts
1578
- var CLOOP_OPENERS = [
1579
- "You are working on a Task from the user's Cloop.",
1580
- "You are running a Routine for the user, from their Cloop."
1581
- ];
1582
- var HARNESS_LOGS = {
1583
- "claude-code": claudeCodeLogs,
1584
- codex: codexLogs
1585
- };
1586
- var CAPTURE_TICK_MS = 6e4;
1587
- var TICK_READ_BYTES = 2 * 1024 * 1024;
1588
- var TICK_TURNS = 500;
1589
- var BASE_SLACK_BYTES = 256 * 1024;
1590
- var PROBE_LINES = 50;
1591
- var REPLY_IDLE_MS = 10 * 6e4;
1592
- var GATE_OFF_PAUSE_MS = 60 * 6e4;
1593
- var BODY_BYTES_MAX = 512 * 1024;
1594
- var READ_CHUNK = 1024 * 1024;
1595
- function captureCursorPath(threadsFile) {
1596
- return join6(dirname2(threadsFile), "thread-capture.json");
1597
- }
1598
- var ThreadCapture = class {
1599
- constructor(deps) {
1600
- this.deps = deps;
1601
- }
1602
- deps;
1603
- running = false;
1604
- pausedUntil = 0;
1605
- /** One tick. Null when nothing ran: opted out, paused, or a tick already running. */
1606
- async tick() {
1607
- if (this.running) return null;
1608
- this.running = true;
1609
- try {
1610
- return await this.run();
1611
- } finally {
1612
- this.running = false;
1613
- }
1614
- }
1615
- now() {
1616
- return this.deps.now?.() ?? Date.now();
1617
- }
1618
- async run() {
1619
- const now = this.now();
1620
- if (now < this.pausedUntil) return null;
1621
- const state = load(this.deps.cursorFile) ?? {
1622
- startedAt: new Date(now).toISOString(),
1623
- files: {}
1624
- };
1625
- const since = Date.parse(state.startedAt);
1626
- const own = new Set(await (this.deps.ownSessions?.() ?? Promise.resolve([])).catch(() => []));
1627
- const hosts = await (this.deps.hostThreads?.() ?? Promise.resolve(/* @__PURE__ */ new Map())).catch(() => /* @__PURE__ */ new Map());
1628
- const listed = /* @__PURE__ */ new Set();
1629
- const candidates = [];
1630
- for (const [harness, logs] of Object.entries(HARNESS_LOGS)) {
1631
- for (const file of logs.files(logs.home())) {
1632
- listed.add(file.path);
1633
- const info = statOrNull(file.path);
1634
- if (!info || info.mtimeMs < since) continue;
1635
- candidates.push({
1636
- ...file,
1637
- harness,
1638
- logs,
1639
- ino: info.ino,
1640
- size: info.size,
1641
- mtimeMs: info.mtimeMs
1642
- });
1210
+ var inWindow = (day, w) => day >= w.sinceDay && day <= w.untilDay;
1211
+ function claudeReader(window, days) {
1212
+ const calls = /* @__PURE__ */ new Map();
1213
+ return {
1214
+ read: (line2) => {
1215
+ if (!line2.includes('"assistant"')) return true;
1216
+ const d = parse(line2);
1217
+ if (d === void 0) return false;
1218
+ if (!isObject(d) || d.type !== "assistant") return true;
1219
+ const m = d.message;
1220
+ const u = isObject(m) ? m.usage : void 0;
1221
+ if (!isObject(m) || !isObject(u) || m.model === "<synthetic>") return true;
1222
+ const day = dayOf(d.timestamp);
1223
+ if (!day) return false;
1224
+ if (!inWindow(day, window)) return true;
1225
+ const details = isObject(u.output_tokens_details) ? u.output_tokens_details : {};
1226
+ const call = {
1227
+ day,
1228
+ uncached: count(u.input_tokens),
1229
+ cached: count(u.cache_read_input_tokens),
1230
+ creation: count(u.cache_creation_input_tokens),
1231
+ output: count(u.output_tokens),
1232
+ reasoning: count(details.thinking_tokens),
1233
+ records: 1
1234
+ };
1235
+ if (typeof m.id !== "string") addTokens(days, day, "claude", call);
1236
+ else {
1237
+ const key = `${m.id} ${String(d.requestId ?? "")}`;
1238
+ const seen = calls.get(key);
1239
+ if (!seen || call.output >= seen.output) calls.set(key, call);
1643
1240
  }
1241
+ return true;
1242
+ },
1243
+ finish: () => {
1244
+ for (const call of calls.values()) addTokens(days, call.day, "claude", call);
1644
1245
  }
1645
- candidates.sort((a, b) => b.mtimeMs - a.mtimeMs);
1646
- for (const file of candidates) {
1647
- const known = state.files[file.path];
1648
- if (!(known && known.ino === file.ino && file.size >= known.offset))
1649
- state.files[file.path] = freshCursor(file, since);
1650
- }
1651
- const budget = { bytes: TICK_READ_BYTES, turns: TICK_TURNS };
1652
- const outgoing = [];
1653
- for (const file of candidates) {
1654
- if (budget.bytes <= 0 || budget.turns <= 0) break;
1655
- const known = state.files[file.path];
1656
- const cursor = structuredClone(known);
1657
- const host = hosts.get(file.sessionId);
1658
- if (own.has(file.sessionId)) cursor.verdict = "cloop";
1659
- const need = host ? OWNER_TURNS_HOSTED : OWNER_TURNS_BARE;
1660
- if (cursor.verdict === "pending" && cursor.ownerTurns >= need) becomeOwner(cursor);
1661
- const idle = now - file.mtimeMs >= REPLY_IDLE_MS;
1662
- const metaOf = () => threadMeta(cursor.thread, host);
1663
- if (cursor.verdict === "cloop" || cursor.verdict === "subagent" || file.size === cursor.offset && !(cursor.open && idle) && !(cursor.verdict === "owner" && JSON.stringify(metaOf()) !== cursor.sentMeta)) {
1664
- state.files[file.path] = cursor;
1665
- continue;
1666
- }
1667
- const turns = [];
1668
- const consumedAll = readInto(file, cursor, budget, turns, need);
1669
- if (consumedAll && cursor.verdict === "owner" && cursor.open && idle) close(cursor, turns);
1670
- const meta = metaOf();
1671
- const metaKey = JSON.stringify(meta);
1672
- const metaChanged = cursor.verdict === "owner" && metaKey !== cursor.sentMeta;
1673
- const send = turns.filter((t) => Date.parse(t.at) >= since);
1674
- budget.turns -= send.length;
1675
- const live = cursor.verdict === "owner" && cursor.live && Date.parse(cursor.live.at) >= since && !sameLive(cursor.live, known?.live) ? cursor.live : void 0;
1676
- if (send.length === 0 && !live && !metaChanged) state.files[file.path] = cursor;
1677
- else
1678
- outgoing.push({
1679
- path: file.path,
1680
- next: { ...cursor, sentMeta: metaKey },
1681
- batch: {
1682
- harness: file.harness,
1683
- session_id: file.sessionId,
1684
- thread: meta,
1685
- turns: send,
1686
- ...live ? { live } : {}
1687
- }
1246
+ };
1247
+ }
1248
+ function codexReader(window, days) {
1249
+ return () => {
1250
+ let prev = { input: 0, cached: 0, write: 0, output: 0, reasoning: 0 };
1251
+ return (line2) => {
1252
+ if (!line2.includes('"token_count"')) return true;
1253
+ const d = parse(line2);
1254
+ if (d === void 0) return false;
1255
+ const p = isObject(d) ? d.payload : void 0;
1256
+ if (!isObject(p) || p.type !== "token_count") return true;
1257
+ if (p.info === null || p.info === void 0) return true;
1258
+ const t = isObject(p.info) ? p.info.total_token_usage : void 0;
1259
+ const day = isObject(d) ? dayOf(d.timestamp) : null;
1260
+ if (!isObject(t) || !day) return false;
1261
+ const cur = {
1262
+ input: count(t.input_tokens),
1263
+ cached: count(t.cached_input_tokens),
1264
+ write: count(t.cache_write_input_tokens),
1265
+ output: count(t.output_tokens),
1266
+ reasoning: count(t.reasoning_output_tokens)
1267
+ };
1268
+ if (cur.input + cur.output <= prev.input + prev.output) return true;
1269
+ const rise = (k) => Math.max(0, cur[k] - prev[k]);
1270
+ if (inWindow(day, window))
1271
+ addTokens(days, day, "codex", {
1272
+ uncached: Math.max(0, rise("input") - rise("cached") - rise("write")),
1273
+ cached: rise("cached"),
1274
+ creation: rise("write"),
1275
+ output: rise("output"),
1276
+ reasoning: rise("reasoning"),
1277
+ records: 1
1688
1278
  });
1689
- }
1690
- const report = {
1691
- sessionsSeen: candidates.length,
1692
- sessionsSent: 0,
1693
- sessionsCloop: candidates.filter((f) => state.files[f.path]?.verdict === "cloop").length,
1694
- sessionsSubagent: candidates.filter((f) => state.files[f.path]?.verdict === "subagent").length,
1695
- turns: 0,
1696
- dropped: 0,
1697
- bytes: 0,
1698
- readBytes: TICK_READ_BYTES - budget.bytes,
1699
- status: null
1279
+ prev = cur;
1280
+ return true;
1700
1281
  };
1701
- for (const out2 of outgoing) {
1702
- const result = await this.send(out2.batch, report);
1703
- if (result.ok || result.drop) state.files[out2.path] = out2.next;
1704
- if (result.ok) {
1705
- report.sessionsSent++;
1706
- report.turns += out2.batch.turns.length;
1707
- report.status = 200;
1708
- continue;
1709
- }
1710
- report.status = result.status;
1711
- if (result.drop) {
1712
- report.dropped += out2.batch.turns.length;
1713
- continue;
1714
- }
1715
- if (result.status === 403) this.pausedUntil = now + GATE_OFF_PAUSE_MS;
1716
- break;
1717
- }
1718
- for (const path of Object.keys(state.files)) if (!listed.has(path)) delete state.files[path];
1719
- if (report.status === 403) forget(this.deps.cursorFile);
1720
- else save(this.deps.cursorFile, state);
1721
- if (outgoing.length)
1722
- this.deps.log(
1723
- `[runner-threads:capture] ${report.status === 200 ? "sent" : "failed"} sessions=${report.sessionsSent}/${outgoing.length} turns=${report.turns} dropped=${report.dropped} bytes=${report.bytes} read=${report.readBytes} status=${report.status}`
1724
- );
1725
- return report;
1726
- }
1727
- /** Every chunk of one session's turns. A 400 or 413 is a refusal for good: the cursor moves on. */
1728
- async send(batch, report) {
1729
- for (const chunk of chunks(batch)) {
1730
- const body = JSON.stringify(chunk);
1731
- let res;
1732
- try {
1733
- res = await (this.deps.fetchFn ?? fetch)(
1734
- `${this.deps.origin}/api/agent/mesh/thread-turns`,
1735
- {
1736
- method: "POST",
1737
- headers: {
1738
- "content-type": "application/json",
1739
- authorization: `Bearer ${this.deps.deviceToken()}`
1740
- },
1741
- body,
1742
- signal: AbortSignal.timeout(3e4)
1743
- }
1744
- );
1745
- } catch {
1746
- return { ok: false, status: "unreachable", drop: false };
1747
- }
1748
- if (!res.ok) {
1749
- return { ok: false, status: res.status, drop: res.status === 400 || res.status === 413 };
1750
- }
1751
- report.bytes += Buffer.byteLength(body);
1752
- }
1753
- return { ok: true };
1754
- }
1755
- };
1756
- function freshCursor(file, since) {
1757
- const base = baseFor(file.path, file.size, since);
1758
- return {
1759
- harness: file.harness,
1760
- sessionId: file.sessionId,
1761
- ino: file.ino,
1762
- offset: 0,
1763
- ...base ? { base } : {},
1764
- seq: 0,
1765
- ownerTurns: 0,
1766
- verdict: "pending",
1767
- thread: {}
1768
1282
  };
1769
1283
  }
1770
- function baseFor(path, size, since) {
1771
- let lo = 0;
1772
- let hi = size;
1773
- while (hi - lo > BASE_SLACK_BYTES) {
1774
- const mid = lo + Math.floor((hi - lo) / 2);
1775
- const probe = datedLineAt(path, mid, hi);
1776
- if (!probe || probe.at >= since) hi = mid;
1777
- else lo = probe.end;
1778
- }
1779
- return lo === 0 ? 0 : lineStartAtOrAfter(path, lo, size);
1780
- }
1781
- function datedLineAt(path, pos, limit) {
1782
- let lines = 0;
1783
- for (const { line: line2, end } of completeLines(path, lineStartAtOrAfter(path, pos, limit), limit)) {
1784
- if (++lines > PROBE_LINES) return null;
1785
- let at = Number.NaN;
1284
+ async function scanSource(source, sinceMs) {
1285
+ const key = sourceKey([
1286
+ hostname(),
1287
+ source.provider,
1288
+ await realpath(source.home).catch(() => source.home)
1289
+ ]);
1290
+ const base = { source_key: key, provider: source.provider };
1291
+ const found = { files: [], skipped: 0 };
1292
+ for (const [i, root] of source.roots.entries()) {
1786
1293
  try {
1787
- const record = JSON.parse(line2);
1788
- if (isRecord(record) && typeof record.timestamp === "string")
1789
- at = Date.parse(record.timestamp);
1790
- } catch {
1791
- }
1792
- if (!Number.isNaN(at)) return { at, end };
1793
- }
1794
- return null;
1795
- }
1796
- function lineStartAtOrAfter(path, pos, size) {
1797
- if (pos <= 0) return 0;
1798
- const fd = openSync(path, "r");
1799
- try {
1800
- for (let at = pos - 1; at < size; at += READ_CHUNK) {
1801
- const chunk = Buffer.alloc(Math.min(READ_CHUNK, size - at));
1802
- const n = readSync(fd, chunk, 0, chunk.length, at);
1803
- if (n <= 0) break;
1804
- const nl = chunk.subarray(0, n).indexOf(10);
1805
- if (nl !== -1) return at + nl + 1;
1806
- }
1807
- return size;
1808
- } finally {
1809
- closeSync(fd);
1810
- }
1811
- }
1812
- function becomeOwner(cursor) {
1813
- const base = cursor.base ?? 0;
1814
- Object.assign(cursor, { offset: base, seq: base, ownerTurns: 0, verdict: "owner" });
1815
- cursor.open = void 0;
1816
- cursor.live = void 0;
1817
- }
1818
- function readInto(file, cursor, budget, out2, need) {
1819
- for (; ; ) {
1820
- let restart = false;
1821
- for (const { line: line2, end } of completeLines(file.path, cursor.offset, file.size)) {
1822
- if (budget.bytes <= 0 || out2.length >= budget.turns) return false;
1823
- budget.bytes -= end - cursor.offset;
1824
- cursor.offset = end;
1825
- let record;
1826
- try {
1827
- record = JSON.parse(line2);
1828
- } catch {
1829
- continue;
1830
- }
1831
- fold(cursor, file.logs.parse(record), out2);
1832
- if (cursor.verdict === "cloop" || cursor.verdict === "subagent") return false;
1833
- if (cursor.verdict === "pending" && cursor.ownerTurns >= need) {
1834
- becomeOwner(cursor);
1835
- restart = true;
1836
- break;
1837
- }
1294
+ await listLogs(root.dir, root.depth, source.match, found);
1295
+ } catch (err) {
1296
+ const code = err.code;
1297
+ if (i > 0 && code === "ENOENT") continue;
1298
+ const empty = { scanned_files: 0, skipped_files: 0, malformed_records: 0 };
1299
+ return code === "ENOENT" ? { ...base, status: "missing", ...empty } : {
1300
+ ...base,
1301
+ status: "failed",
1302
+ ...empty,
1303
+ message: `The log folder could not be read (${code ?? "error"}).`
1304
+ };
1838
1305
  }
1839
- if (!restart) return true;
1840
1306
  }
1841
- }
1842
- function* completeLines(path, from, size) {
1843
- const fd = openSync(path, "r");
1844
- try {
1845
- let pos = from;
1846
- let carry = Buffer.alloc(0);
1847
- while (pos < size) {
1848
- const chunk = Buffer.alloc(Math.min(READ_CHUNK, size - pos));
1849
- const n = readSync(fd, chunk, 0, chunk.length, pos);
1850
- if (n <= 0) break;
1851
- pos += n;
1852
- const data = carry.length ? Buffer.concat([carry, chunk.subarray(0, n)]) : chunk.subarray(0, n);
1853
- const base = pos - data.length;
1854
- let start = 0;
1855
- for (let nl = data.indexOf(10, start); nl !== -1; nl = data.indexOf(10, start)) {
1856
- yield { line: data.toString("utf8", start, nl), end: base + nl + 1 };
1857
- start = nl + 1;
1858
- }
1859
- carry = Buffer.from(data.subarray(start));
1860
- }
1861
- } finally {
1862
- closeSync(fd);
1863
- }
1864
- }
1865
- function clip(text) {
1866
- return text.length > TURN_TEXT_MAX ? `${text.slice(0, TURN_TEXT_MAX - 1)}\u2026` : text;
1867
- }
1868
- function close(cursor, out2) {
1869
- const open = cursor.open;
1870
- if (!open) return;
1871
- out2.push({ seq: open.seq, at: open.at, role: "agent", text: open.text, actions: open.actions });
1872
- cursor.open = void 0;
1873
- }
1874
- function addAction(turn, action) {
1875
- if (turn.actions.length >= TURN_ACTIONS_MAX) return;
1876
- const key = JSON.stringify(action);
1877
- if (!turn.actions.some((a) => JSON.stringify(a) === key)) turn.actions.push(action);
1878
- }
1879
- function follow(cursor, call) {
1880
- cursor.wakeArmed = call.kind === "once";
1881
- if (call.kind !== "watch" && call.kind !== "unwatch") return;
1882
- const others = (cursor.watching ?? []).filter((url) => url !== call.url);
1883
- cursor.watching = call.kind === "watch" ? [...others, call.url] : others;
1884
- }
1885
- function fold(cursor, signals, out2) {
1886
- for (const signal of signals) {
1887
- switch (signal.kind) {
1888
- case "subagent":
1889
- cursor.verdict = "subagent";
1890
- return;
1891
- case "thread":
1892
- if (signal.cwd) cursor.thread.cwd = signal.cwd;
1893
- if (signal.branch) cursor.thread.branch = signal.branch;
1894
- if (signal.title) cursor.thread.title = signal.title;
1895
- if (signal.customTitle) cursor.thread.customTitle = signal.customTitle;
1896
- break;
1897
- case "owner":
1898
- cursor.live = { at: signal.at, state: "working" };
1899
- cursor.wakeArmed = false;
1900
- cursor.ownerTurns++;
1901
- if (cursor.ownerTurns === 1 && CLOOP_OPENERS.some((o) => signal.text.startsWith(o))) {
1902
- cursor.verdict = "cloop";
1903
- return;
1904
- }
1905
- if (!cursor.thread.firstAsk) {
1906
- const ask = askTitle(signal.text);
1907
- if (ask) cursor.thread.firstAsk = ask;
1908
- }
1909
- if (cursor.verdict !== "owner") break;
1910
- close(cursor, out2);
1911
- out2.push({
1912
- seq: cursor.seq++,
1913
- at: signal.at,
1914
- role: "owner",
1915
- text: clip(redactSecrets(signal.text)),
1916
- actions: []
1917
- });
1918
- break;
1919
- case "agent": {
1920
- for (const call of signal.calls ?? []) follow(cursor, call);
1921
- if (!signal.text && !signal.actions?.length) break;
1922
- if (signal.text || signal.calls?.length) cursor.live = { at: signal.at, state: "working" };
1923
- if (cursor.verdict !== "owner") break;
1924
- if (!cursor.open) cursor.open = { seq: cursor.seq++, at: signal.at, text: "", actions: [] };
1925
- const open = cursor.open;
1926
- if (signal.text) {
1927
- const said = redactSecrets(signal.text);
1928
- open.text = clip(open.text ? `${open.text}
1929
-
1930
- ${said}` : said);
1931
- }
1932
- for (const action of signal.actions ?? []) addAction(open, action);
1933
- break;
1934
- }
1935
- case "end": {
1936
- const at = signal.at ?? cursor.live?.at;
1937
- const waits = cursor.wakeArmed || (cursor.watching?.length ?? 0) > 0;
1938
- if (at) cursor.live = { at, state: waits ? "waiting" : "your_turn" };
1939
- cursor.wakeArmed = false;
1940
- if (cursor.verdict === "owner") close(cursor, out2);
1941
- break;
1942
- }
1307
+ let scanned = 0;
1308
+ let skipped = found.skipped;
1309
+ let malformed = 0;
1310
+ for (const file of found.files) {
1311
+ try {
1312
+ if ((await stat(file)).mtimeMs < sinceMs) continue;
1313
+ malformed += await readLines(file, source.reader());
1314
+ scanned++;
1315
+ } catch {
1316
+ skipped++;
1943
1317
  }
1944
1318
  }
1945
- }
1946
- var ASK_TITLE_MAX = 80;
1947
- function askTitle(text) {
1948
- const line2 = redactSecrets(text).split("\n").map((l) => l.replace(/\s+/g, " ").trim()).find((l) => l && !/^\/\S+$/.test(l));
1949
- if (!line2) return void 0;
1950
- if (line2.length <= ASK_TITLE_MAX) return line2;
1951
- const cut2 = line2.slice(0, ASK_TITLE_MAX - 1);
1952
- const space = cut2.lastIndexOf(" ");
1953
- return `${space > ASK_TITLE_MAX / 2 ? cut2.slice(0, space) : cut2}\u2026`;
1954
- }
1955
- function threadMeta(thread, host) {
1956
- const title = host?.title ?? thread.customTitle ?? thread.title ?? thread.firstAsk;
1957
1319
  return {
1958
- ...thread.cwd ? { cwd: thread.cwd.slice(0, CWD_MAX) } : {},
1959
- ...thread.branch ? { branch: thread.branch.slice(0, BRANCH_MAX) } : {},
1960
- ...title ? { title: title.slice(0, TITLE_MAX) } : {},
1961
- ...host?.delegated ? { delegated: true } : {},
1962
- ...host ? {
1963
- host: host.host,
1964
- host_thread_id: host.threadId,
1965
- ...host.parentId ? { host_parent_id: host.parentId } : {},
1966
- settled: host.settled
1967
- } : {}
1320
+ ...base,
1321
+ status: skipped || malformed ? "partial" : "ok",
1322
+ scanned_files: scanned,
1323
+ skipped_files: skipped,
1324
+ malformed_records: malformed
1968
1325
  };
1969
1326
  }
1970
- function sameLive(a, b) {
1971
- return a?.at === b?.at && a?.state === b?.state;
1972
- }
1973
- function* chunks(batch) {
1974
- const { live, ...rest } = batch;
1975
- let turns = [];
1976
- let bytes = 0;
1977
- for (const turn of batch.turns) {
1978
- const size = Buffer.byteLength(JSON.stringify(turn));
1979
- if (turns.length && (turns.length >= BATCH_TURNS_MAX || bytes + size > BODY_BYTES_MAX)) {
1980
- yield { ...rest, turns };
1981
- turns = [];
1982
- bytes = 0;
1983
- }
1984
- turns.push(turn);
1985
- bytes += size;
1986
- }
1987
- yield { ...rest, turns, ...live ? { live } : {} };
1988
- }
1989
- function statOrNull(path) {
1990
- try {
1991
- return statSync(path);
1992
- } catch {
1993
- return null;
1994
- }
1995
- }
1996
- function load(file) {
1997
- try {
1998
- const raw = JSON.parse(readFileSync2(file, "utf-8"));
1999
- if (typeof raw.startedAt !== "string" || Number.isNaN(Date.parse(raw.startedAt))) return null;
2000
- return {
2001
- startedAt: raw.startedAt,
2002
- files: typeof raw.files === "object" && raw.files ? raw.files : {}
2003
- };
2004
- } catch {
2005
- return null;
2006
- }
2007
- }
2008
- function save(file, state) {
2009
- mkdirSync(dirname2(file), { recursive: true, mode: 448 });
2010
- const tmp = `${file}.tmp`;
2011
- writeFileSync(tmp, `${JSON.stringify(state)}
2012
- `, { mode: 384 });
2013
- chmodSync(tmp, 384);
2014
- renameSync(tmp, file);
2015
- }
2016
- function forget(file) {
2017
- try {
2018
- unlinkSync(file);
2019
- } catch {
2020
- }
2021
- }
2022
-
2023
- // src/commands/disconnect.ts
2024
- function doneLine(env) {
2025
- return `This computer is no longer a ${env} Cloop machine. To connect it again: ${["npx -y @cloop/runner@latest connect", ENVIRONMENTS[env].flag].filter(Boolean).join(" ")}`;
2026
- }
2027
- function unitOrigin(contents) {
2028
- const plist = /<key>CLOOP_ORIGIN<\/key><string>([^<]+)<\/string>/.exec(contents)?.[1];
2029
- if (plist) return plist.replace(/&amp;/g, "&");
2030
- const unit = /Environment="CLOOP_ORIGIN=([^"]+)"/.exec(contents)?.[1];
2031
- if (unit) return unit.replace(/%%/g, "%");
2032
- const launcher = /^set "CLOOP_ORIGIN=(.+)"\r?$/m.exec(contents)?.[1];
2033
- return launcher ? launcher.replace(/%%/g, "%") : null;
2034
- }
2035
- function disconnectPlan(opts) {
2036
- const exists = opts.exists ?? existsSync4;
2037
- const read = opts.read ?? ((path) => readFileSync3(path, "utf-8"));
2038
- const installed = ["local", "workstation"].map((kind) => ({ kind, service: installedService({ ...opts, kind }) })).filter(({ service }) => exists(service.path));
2039
- const services = installed.map(({ service }) => service);
2040
- const fromUnit = services.map((service) => {
2041
- try {
2042
- return unitOrigin(read(service.path));
2043
- } catch {
2044
- return null;
2045
- }
2046
- }).find(Boolean);
1327
+ async function scanTokenUsage(opts = {}) {
1328
+ const window = utcWindow(opts.now ?? Date.now(), TOKEN_DAYS);
1329
+ const sinceMs = Date.parse(`${window.sinceDay}T00:00:00Z`);
1330
+ const days = /* @__PURE__ */ new Map();
1331
+ const claudeHome2 = opts.claudeHome ?? claudeHome();
1332
+ const codexHome3 = opts.codexHome ?? codexHome();
1333
+ const claude = claudeReader(window, days);
1334
+ const sources = [
1335
+ await scanSource(
1336
+ {
1337
+ provider: "claude",
1338
+ home: claudeHome2,
1339
+ // projects/<project>/<session>.jsonl and projects/<project>/<session>/subagents/agent-*.jsonl
1340
+ roots: [{ dir: join3(claudeHome2, "projects"), depth: 4 }],
1341
+ match: (name) => name.endsWith(".jsonl"),
1342
+ reader: () => claude.read
1343
+ },
1344
+ sinceMs
1345
+ ),
1346
+ await scanSource(
1347
+ {
1348
+ provider: "codex",
1349
+ home: codexHome3,
1350
+ roots: [
1351
+ { dir: join3(codexHome3, "sessions"), depth: 4 },
1352
+ { dir: join3(codexHome3, "archived_sessions"), depth: 1 }
1353
+ ],
1354
+ match: (name) => name.startsWith("rollout-") && name.endsWith(".jsonl"),
1355
+ reader: codexReader(window, days)
1356
+ },
1357
+ sinceMs
1358
+ )
1359
+ ];
1360
+ claude.finish();
1361
+ const partial = sources.some((s) => s.status === "partial" || s.status === "failed");
2047
1362
  return {
2048
- origin: opts.boxOrigin ?? fromUnit ?? opts.fallbackOrigin,
2049
- deviceToken: opts.deviceToken,
2050
- services,
2051
- box: exists(opts.box) ? opts.box : null,
2052
- files: opts.files.filter((file) => exists(file)),
2053
- isBox: opts.platform !== "darwin" && opts.platform !== "win32" && installed.some(({ kind }) => kind === "workstation")
1363
+ status: partial ? "partial" : "ok",
1364
+ scope: TOKEN_SCOPE,
1365
+ window: { since_day: window.sinceDay, until_day: window.untilDay, time_zone: "UTC" },
1366
+ read_at: (/* @__PURE__ */ new Date()).toISOString(),
1367
+ by_day: sortedDays(days),
1368
+ sources
2054
1369
  };
2055
1370
  }
2056
- async function stopService(service, run2, waitMs = 1e4) {
2057
- await runSteps(service.steps, run2);
2058
- const until = Date.now() + waitMs;
2059
- for (; ; ) {
2060
- try {
2061
- run2(service.running);
2062
- } catch {
2063
- return true;
2064
- }
2065
- if (Date.now() >= until) return false;
2066
- await new Promise((resolve3) => setTimeout(resolve3, 250));
2067
- }
2068
- }
2069
- function revokeLine(revoke, origin, box) {
2070
- const env = environmentOf(origin);
2071
- const keep = box ? ` Kept ${box}, which holds the device token, so you can try again.` : "";
2072
- switch (revoke) {
2073
- case "revoked":
2074
- return [`Revoked this computer on Cloop (${origin}).`];
2075
- case "already_revoked":
2076
- return [`Cloop (${origin}) had already revoked this computer.`];
2077
- case "no_device":
2078
- return ["No machine device on this computer to revoke."];
2079
- case "unknown_device":
2080
- return [
2081
- `Cloop at ${origin} never issued this computer's device token, so it belongs to the other environment.${keep}`,
2082
- "Run `cloop disconnect --staging` for a staging machine, or `cloop disconnect` for production."
2083
- ];
2084
- case "failed":
2085
- return [
2086
- `Could not revoke this computer at ${origin}: Cloop did not answer as expected.${keep}`,
2087
- `Run \`${cloopCommand(env, "disconnect")}\` again when Cloop answers, or press Disconnect on its card on the Threads page and then delete that file.`
2088
- ];
1371
+ var LocalUsage = class {
1372
+ constructor(deps) {
1373
+ this.deps = deps;
1374
+ this.tokens = new BackgroundReading({
1375
+ ttlMs: TOKEN_TTL_MS,
1376
+ read: () => this.scan(),
1377
+ now: deps.now
1378
+ });
2089
1379
  }
2090
- }
2091
- async function disconnect(plan, opts) {
2092
- const { say } = opts;
2093
- const env = environmentOf(plan.origin);
2094
- const run2 = opts.run ?? ((command) => void execFileSync(command[0], command.slice(1), {
2095
- stdio: "ignore",
2096
- timeout: 15e3,
2097
- ...command[0] === "powershell" ? { env: windowsPowerShellEnv() } : {}
2098
- }));
2099
- if (plan.isBox && !opts.yes) {
2100
- const unit = plan.services.map((s) => basename4(s.path)).find((n) => n.startsWith("cloop-box"));
2101
- say(`This computer runs ${unit}, the ${env} Cloop box with T3 Code. Disconnect would:`);
2102
- for (const s of plan.services) say(` stop and remove ${s.path}`);
2103
- if (plan.deviceToken) say(` revoke its machine device on Cloop (${plan.origin})`);
2104
- for (const f of [...plan.box ? [plan.box] : [], ...plan.files]) say(` delete ${f}`);
2105
- say(`Run \`${cloopCommand(env, "disconnect --yes")}\` to do this.`);
2106
- return 1;
2107
- }
2108
- for (const service of plan.services) {
2109
- if (!await stopService(service, run2, opts.stopWaitMs)) {
2110
- say(
2111
- `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.`
2112
- );
2113
- return 1;
1380
+ deps;
1381
+ quotas = /* @__PURE__ */ new Map();
1382
+ tokens;
1383
+ /** The quota of a signed-in harness, probed at most once per harness check period. */
1384
+ quota(harness) {
1385
+ const probe = this.deps.probes[harness];
1386
+ if (!probe) return { status: "not_reported" };
1387
+ let reading = this.quotas.get(harness);
1388
+ if (!reading) {
1389
+ reading = new BackgroundReading({
1390
+ ttlMs: HARNESS_STALE_MS,
1391
+ read: async () => {
1392
+ const q = await probe();
1393
+ if (q.status === "probe_failed")
1394
+ this.deps.log?.(`quota probe failed harness=${harness}: ${q.message ?? ""}`);
1395
+ return q;
1396
+ },
1397
+ now: this.deps.now
1398
+ });
1399
+ this.quotas.set(harness, reading);
1400
+ }
1401
+ return reading.get();
1402
+ }
1403
+ /** Each report with its quota. A signed-out harness has no account to ask. */
1404
+ withQuota(harnesses) {
1405
+ return harnesses.map((h) => ({
1406
+ ...h,
1407
+ quota: h.signedIn ? this.quota(h.id) : { status: "not_reported" }
1408
+ }));
1409
+ }
1410
+ /** Token counts from the last log scan, rescanned at most every TOKEN_TTL_MS. */
1411
+ tokenUsage() {
1412
+ return this.tokens.get();
1413
+ }
1414
+ async scan() {
1415
+ const now = this.deps.now ?? Date.now;
1416
+ const started = now();
1417
+ try {
1418
+ const usage = await (this.deps.scan ?? scanTokenUsage)();
1419
+ this.deps.log?.(`token scan took ${now() - started} ms status=${usage.status}`);
1420
+ return usage;
1421
+ } catch (err) {
1422
+ this.deps.log?.(`token scan failed: ${err?.message}`);
1423
+ return { status: "unavailable", reason: "The agent logs could not be read" };
2114
1424
  }
2115
- say(`Stopped the service in ${service.path}`);
2116
- }
2117
- const revoked = await opts.revoke(plan.origin, plan.deviceToken);
2118
- const gone = tokenGone(revoked);
2119
- for (const service of plan.services) {
2120
- rmSync(service.path, { force: true });
2121
- say(`Removed ${service.path}`);
2122
- }
2123
- for (const file of [...gone && plan.box ? [plan.box] : [], ...plan.files]) {
2124
- rmSync(file, { force: true });
2125
- say(`Deleted ${file}`);
2126
1425
  }
2127
- for (const line2 of revokeLine(revoked, plan.origin, plan.box)) say(line2);
2128
- if (!gone) return 1;
2129
- say(doneLine(env));
2130
- return 0;
2131
- }
2132
- function runnerOrigin(env) {
2133
- return disconnectPlan(thisComputer(env, "")).origin || void 0;
2134
- }
2135
- function thisComputer(env, fallbackOrigin) {
2136
- const cfg = readRunnerConfig(env);
2137
- return {
2138
- platform: process.platform,
2139
- environment: env,
2140
- home: homedir3(),
2141
- uid: process.getuid?.() ?? 0,
2142
- ...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {},
2143
- box: boxPath(env),
2144
- deviceToken: cfg?.deviceToken ?? null,
2145
- ...cfg?.origin ? { boxOrigin: cfg.origin } : {},
2146
- fallbackOrigin,
2147
- files: [
2148
- localRunsFilePath(env),
2149
- runnerStatePath(env),
2150
- threadsFilePath(env),
2151
- captureCursorPath(threadsFilePath(env))
2152
- ]
2153
- };
2154
- }
2155
- async function disconnectCommand(argv) {
2156
- const { environment, note } = pinExistingRunner();
2157
- if (note) console.log(note);
2158
- const plan = disconnectPlan(
2159
- thisComputer(legacyStagingRunner() ? "production" : environment, getOrigin())
2160
- );
2161
- process.exitCode = await disconnect(plan, {
2162
- yes: argv.includes("--yes"),
2163
- revoke: (origin, token) => revokeOwnDevice(origin, token),
2164
- say: (line2) => console.log(line2)
2165
- });
2166
- }
1426
+ };
2167
1427
 
2168
- // src/legacy-staging.ts
2169
- var MOVED = [
2170
- "box-threads.json",
2171
- "runner-state.json",
2172
- "local-runs.json",
2173
- "runs",
2174
- "takeover",
2175
- "update.json",
2176
- "update.log",
2177
- "box.json"
2178
- ];
2179
- function legacyStagingRunner() {
2180
- if (existsSync5(boxPath("staging"))) return false;
2181
- const origin = runnerOrigin("production");
2182
- return origin !== void 0 && environmentOf(origin) === "staging";
2183
- }
2184
- function moveRunnerFiles(from, to) {
2185
- mkdirSync2(to, { recursive: true, mode: 448 });
2186
- for (const name of MOVED) {
2187
- const source = join7(from, name);
2188
- const target = join7(to, name);
2189
- if (existsSync5(source) && !existsSync5(target)) renameSync2(source, target);
2190
- }
2191
- }
2192
- function legacyServices(platform) {
2193
- return ["local", "workstation"].map(
2194
- (kind) => installedService({
2195
- platform,
2196
- kind,
2197
- environment: "production",
2198
- home: homedir4(),
2199
- uid: process.getuid?.() ?? 0,
2200
- ...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
2201
- })
2202
- ).filter((service) => existsSync5(service.path));
2203
- }
2204
- async function moveLegacyStagingRunner(services) {
2205
- if (!legacyStagingRunner()) return false;
2206
- const run2 = (command) => void services.run(command);
2207
- const units = legacyServices(services.platform);
2208
- for (const unit of units)
2209
- if (!await stopService(unit, run2))
2210
- throw new Error(
2211
- `Could not stop the staging machine in ${unit.path}. Stop it with \`${unit.steps.map((s) => s.command.join(" ")).join(" && ")}\`, then run this again.`
2212
- );
2213
- for (const unit of units) rmSync2(unit.path, { force: true });
2214
- moveRunnerFiles(runnerDir("production"), runnerDir("staging"));
2215
- console.error("[runner:environment] moved staging runner from ~/.cloop to ~/.cloop/staging");
2216
- return true;
2217
- }
2218
- function movedLine(connecting) {
2219
- const line2 = "Moved the staging machine from ~/.cloop to ~/.cloop/staging, so a production machine can run beside it.";
2220
- return connecting === "staging" ? line2 : `${line2} It is stopped. Start it again with: cloop connect --staging`;
1428
+ // src/drivers/agents.ts
1429
+ var claudeCode = {
1430
+ id: "claude-code",
1431
+ name: "Claude Code",
1432
+ kind: "local",
1433
+ bin: "claude",
1434
+ signedOutLine: "Claude Code is installed but not signed in. Run `claude` once and sign in, then run `cloop connect` again.",
1435
+ signInLine: "Sign in to Claude Code; your browser opens.",
1436
+ /** `claude auth login` opens the browser, or prints a URL and takes the code pasted back. */
1437
+ signIn: (bin) => [bin, "auth", "login"],
1438
+ probe: (bin) => probeClaude(bin),
1439
+ quota: (bin) => probeClaudeQuota(bin),
1440
+ dialect: async (options, bin) => claudeDialect(
1441
+ bin,
1442
+ options.fallbackModels ?? DEFAULT_FALLBACK_MODEL,
1443
+ options.askEverything,
1444
+ await probeClaudePermissions(bin)
1445
+ ),
1446
+ handsOverTo: "codex",
1447
+ accessLine: (askEverything) => askEverything ? "Asks before actions except allowlisted reads." : "Full access: every Task runs without permission checks. Add --ask-everything to approve each step.",
1448
+ takesOptions: true,
1449
+ ownSessions: true,
1450
+ install: (home) => installClaude(home),
1451
+ reportField: "claudeInstall"
1452
+ };
1453
+ var codex = {
1454
+ id: "codex",
1455
+ name: "Codex",
1456
+ kind: "local",
1457
+ bin: "codex",
1458
+ signedOutLine: "Codex is installed but not signed in. Run `codex login`, then run `cloop connect` again.",
1459
+ signInLine: "Sign in to Codex with your ChatGPT account; your browser opens.",
1460
+ /** `codex login` opens the browser; a headless Linux machine gets a device code to type at a URL. */
1461
+ signIn: (bin, platform) => [bin, "login", ...platform === "linux" ? ["--device-auth"] : []],
1462
+ probe: (bin) => probeCodex(bin),
1463
+ quota: (bin) => probeCodexQuota(bin),
1464
+ dialect: async (_options, bin) => codexDialect(bin),
1465
+ handsOverTo: "claude-code",
1466
+ accessLine: () => "Full access: Codex always runs every Task without permission checks. --ask-everything applies to Claude Code only.",
1467
+ takesOptions: false,
1468
+ ownSessions: false,
1469
+ models: (bin) => codexModels(bin),
1470
+ install: (home) => installCodex(home),
1471
+ reportField: "codexInstall"
1472
+ };
1473
+ var AGENTS = {
1474
+ t3: { id: "t3", name: "T3 Code", kind: "workstation" },
1475
+ "claude-code": claudeCode,
1476
+ codex
1477
+ };
1478
+ var LOCAL_AGENTS = LOCAL_DRIVERS.map((id) => AGENTS[id]);
1479
+ function localAgent(name) {
1480
+ return isLocalDriver(name) ? AGENTS[name] : void 0;
1481
+ }
1482
+ function configuredBin(cfg, agent) {
1483
+ return cfg.driver === agent.id ? cfg.bin : void 0;
1484
+ }
1485
+ function quotaProbes(cfg) {
1486
+ return Object.fromEntries(
1487
+ LOCAL_AGENTS.map((agent) => [
1488
+ agent.id,
1489
+ () => agent.quota(cfg ? configuredBin(cfg, agent) : void 0)
1490
+ ])
1491
+ );
2221
1492
  }
2222
1493
 
2223
1494
  // src/mcp-registration.ts
2224
- import { execFile as execFile4, spawn as spawn2 } from "child_process";
2225
- import { homedir as homedir5 } from "os";
1495
+ import { execFile as execFile4, spawn as spawn3 } from "child_process";
1496
+ import { homedir as homedir2 } from "os";
2226
1497
  var MCP_HARNESS_NAME = {
2227
1498
  "claude-code": "Claude Code",
2228
1499
  codex: "Codex"
@@ -2269,7 +1540,7 @@ var systemMcpCli = {
2269
1540
  command.args,
2270
1541
  {
2271
1542
  // A project's own MCP config under the folder connect ran in must not stand in for the user's.
2272
- cwd: homedir5(),
1543
+ cwd: homedir2(),
2273
1544
  timeout: 45e3,
2274
1545
  encoding: "utf-8",
2275
1546
  env: { ...process.env, ...env },
@@ -2285,8 +1556,8 @@ var systemMcpCli = {
2285
1556
  const ignore = () => {
2286
1557
  };
2287
1558
  process.on("SIGINT", ignore);
2288
- const child = spawn2(command.file, command.args, {
2289
- cwd: homedir5(),
1559
+ const child = spawn3(command.file, command.args, {
1560
+ cwd: homedir2(),
2290
1561
  stdio: "inherit",
2291
1562
  ...command.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
2292
1563
  });
@@ -2368,14 +1639,14 @@ async function addCloopMcp(harness, bin, server, deps) {
2368
1639
  ...loginArgs(platform, deps.env ?? process.env)
2369
1640
  ];
2370
1641
  const shown = (args) => shellLine([words.bin, ...args], platform);
2371
- const result = (registered, signedIn2, reason, byHand, as = server.name) => ({
1642
+ const result = (registered, signedIn2, reason2, byHand, as = server.name) => ({
2372
1643
  harness,
2373
1644
  url: server.url,
2374
1645
  as,
2375
1646
  found: as !== server.name,
2376
1647
  registered,
2377
1648
  signedIn: signedIn2,
2378
- reason,
1649
+ reason: reason2,
2379
1650
  byHand
2380
1651
  });
2381
1652
  const why = (err) => err instanceof Error ? err.message : String(err);
@@ -2459,7 +1730,6 @@ function pairingCredential(input) {
2459
1730
 
2460
1731
  // src/commands/connect.ts
2461
1732
  var DEFAULT_T3_URL = "http://127.0.0.1:3773";
2462
- var CLEAN_ENV = { HOME: process.env.HOME, USER: process.env.USER, PATH: process.env.PATH };
2463
1733
  var out = (line2) => console.log(line2);
2464
1734
  var bold = (s) => `\x1B[1m${s}\x1B[0m`;
2465
1735
  var dim = (s) => `\x1B[2m${s}\x1B[0m`;
@@ -2471,19 +1741,6 @@ function flag(argv, name) {
2471
1741
  function flags(argv, name) {
2472
1742
  return argv.flatMap((a, i) => a === name && argv[i + 1] ? [argv[i + 1]] : []);
2473
1743
  }
2474
- function which(bin) {
2475
- return process.platform === "win32" ? windowsExecutable(bin) : whichPosix(bin);
2476
- }
2477
- function whichPosix(bin) {
2478
- try {
2479
- return execFileSync2("which", [bin], {
2480
- encoding: "utf-8",
2481
- env: { ...CLEAN_ENV, PATH: process.env.PATH }
2482
- }).trim() || null;
2483
- } catch {
2484
- return null;
2485
- }
2486
- }
2487
1744
  var T3PairError = class extends Error {
2488
1745
  name = "T3PairError";
2489
1746
  };
@@ -2510,7 +1767,7 @@ function boxSession(t3Url, t3Bin, env, token) {
2510
1767
  }
2511
1768
  async function mintSession(t3Url, opts = {}) {
2512
1769
  const env = await workstationEnvironment(t3Url, opts.fetchFn);
2513
- const sources = opts.sources ?? defaultT3BinSources(homedir6(), opts.stored);
1770
+ const sources = opts.sources ?? defaultT3BinSources(homedir3(), opts.stored);
2514
1771
  try {
2515
1772
  const t3Bin = opts.bin ?? pickT3Bin(t3Candidates(env.serverVersion, sources), env.serverVersion);
2516
1773
  if (!t3Bin) throw new Error("no t3 binary found; pass --t3-bin or set T3_BIN");
@@ -2566,7 +1823,7 @@ async function pairT3(steps) {
2566
1823
  }
2567
1824
  function askHidden(question, input = process.stdin, output = process.stdout) {
2568
1825
  const muted = new Writable({ write: (_chunk, _encoding, done) => done() });
2569
- const prompt = createInterface({ input, output: muted, terminal: true });
1826
+ const prompt = createInterface2({ input, output: muted, terminal: true });
2570
1827
  output.write(`${question}
2571
1828
  ${dim("(The link stays hidden while you paste it.)")} `);
2572
1829
  return askOrClosed(
@@ -2585,39 +1842,24 @@ async function connectBox(steps) {
2585
1842
  steps.writeBoxConfig(cfg);
2586
1843
  return cfg;
2587
1844
  }
2588
- var NONE2 = "No coding agent found on this machine. Install Claude Code or the ChatGPT desktop app, sign in, then run `cloop connect` again.";
2589
- var SIGNED_OUT = {
2590
- "claude-code": "Claude Code is installed but not signed in. Run `claude` once and sign in, then run `cloop connect` again.",
2591
- codex: "Codex is installed but not signed in. Run `codex login`, then run `cloop connect` again."
2592
- };
1845
+ var NONE = "No coding agent found on this machine. Install Claude Code or the ChatGPT desktop app, sign in, then run `cloop connect` again.";
2593
1846
  var T3_DOWN = "T3 Code is not answering; start it, or pass --driver claude-code.";
2594
1847
  function chooseDriver(found, forced, workstation = false) {
2595
1848
  const local = (driver) => {
2596
- const harness = driver === "claude-code" ? found.claude : found.codex;
1849
+ const agent = AGENTS[driver];
1850
+ const harness = found[agent.bin];
2597
1851
  if (!harness)
2598
- return {
2599
- ok: false,
2600
- code: "no_harness",
2601
- line: `${driver === "codex" ? "Codex" : "Claude Code"} is not installed here.`
2602
- };
2603
- return harness.signedIn ? { ok: true, driver, kind: "local" } : { ok: false, code: "signed_out", line: SIGNED_OUT[driver] };
1852
+ return { ok: false, code: "no_harness", line: `${agent.name} is not installed here.` };
1853
+ return harness.signedIn ? { ok: true, driver, kind: "local" } : { ok: false, code: "signed_out", line: agent.signedOutLine };
2604
1854
  };
2605
1855
  if (forced === "t3")
2606
1856
  return found.t3 ? { ok: true, driver: "t3", kind: "workstation" } : { ok: false, code: "no_harness", line: `No T3 Code server answers at ${DEFAULT_T3_URL}.` };
2607
1857
  if (forced) return local(forced);
2608
1858
  if (found.t3) return { ok: true, driver: "t3", kind: "workstation" };
2609
1859
  if (workstation) return { ok: false, code: "t3_unreachable", line: T3_DOWN };
2610
- if (found.claude?.signedIn) return local("claude-code");
2611
- if (found.codex?.signedIn) return local("codex");
2612
- if (found.claude) return local("claude-code");
2613
- if (found.codex) return local("codex");
2614
- return { ok: false, code: "no_harness", line: NONE2 };
1860
+ const here = LOCAL_AGENTS.find((agent) => found[agent.bin]?.signedIn) ?? LOCAL_AGENTS.find((agent) => found[agent.bin]);
1861
+ return here ? local(here.id) : { ok: false, code: "no_harness", line: NONE };
2615
1862
  }
2616
- var HARNESS_NAME = {
2617
- "claude-code": "Claude Code",
2618
- codex: "Codex"
2619
- };
2620
- var DRIVER_NAME = { t3: "T3 Code", ...HARNESS_NAME };
2621
1863
  function fallbackDriver(found, forced, workstation) {
2622
1864
  if (forced === "t3" || workstation) return null;
2623
1865
  const choice = chooseDriver({ ...found, t3: false });
@@ -2627,12 +1869,12 @@ function isWorkstation(previous, boxServiceInstalled2) {
2627
1869
  return boxServiceInstalled2 || Boolean(previous && !isLocal(previous));
2628
1870
  }
2629
1871
  function boxServiceInstalled() {
2630
- return existsSync6(
1872
+ return existsSync3(
2631
1873
  installedService({
2632
1874
  platform: process.platform,
2633
1875
  kind: "workstation",
2634
1876
  environment: runnerEnvironment(),
2635
- home: homedir6(),
1877
+ home: homedir3(),
2636
1878
  uid: process.getuid?.() ?? 0,
2637
1879
  ...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
2638
1880
  }).path
@@ -2676,8 +1918,8 @@ var RELINK_LINE = {
2676
1918
  expiring: `The device token on this computer ends within ${RELINK_WITHIN_MS / 864e5} days, so approve it again in the browser to renew it.`,
2677
1919
  unchecked: "Could not reach Cloop to check the device token on this computer, so approve it again in the browser."
2678
1920
  };
2679
- function relinkLine(reason) {
2680
- return RELINK_LINE[reason];
1921
+ function relinkLine(reason2) {
1922
+ return RELINK_LINE[reason2];
2681
1923
  }
2682
1924
  function keptLine(expiresAt) {
2683
1925
  return `${bold("Cloop machine")} Cloop still accepts this computer, until ${expiresAt.slice(0, 10)}. No browser step. To approve it again, run: cloop connect --relink`;
@@ -2710,8 +1952,8 @@ async function deviceFor(argv, attempt, previous, login) {
2710
1952
  attempt.deviceLogin = "approved";
2711
1953
  return attempt.deviceToken;
2712
1954
  }
2713
- function fallbackLine(reason, driver) {
2714
- 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>`;
1955
+ function fallbackLine(reason2, driver) {
1956
+ return `T3 Code is running but would not pair (${reason2}). Connecting ${AGENTS[driver].name} instead. To use T3, create a pairing link in T3 Code (Settings, Connections) and run: cloop connect --t3-pair <link>`;
2715
1957
  }
2716
1958
  async function connectChosen(driver, attempt, run2) {
2717
1959
  attempt.driver = driver;
@@ -2728,272 +1970,6 @@ async function connectChosen(driver, attempt, run2) {
2728
1970
  await run2.local(local);
2729
1971
  }
2730
1972
  }
2731
- function systemdAssignment(assignment) {
2732
- return `"${assignment.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%")}"`;
2733
- }
2734
- function systemdWord(arg) {
2735
- const escaped = arg.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%").replace(/\$/g, "$$$$");
2736
- return `"${escaped}"`;
2737
- }
2738
- function cmdValue(value) {
2739
- return value.replace(/%/g, "%%");
2740
- }
2741
- function cmdWord(arg) {
2742
- return `"${cmdValue(arg)}"`;
2743
- }
2744
- var psQuote2 = (value) => `'${value.replace(/'/g, "''")}'`;
2745
- function registerTaskScript(task, launcher) {
2746
- return [
2747
- "$ErrorActionPreference = 'Stop'",
2748
- "$user = [Security.Principal.WindowsIdentity]::GetCurrent().Name",
2749
- `$launcher = ${psQuote2(launcher)}`,
2750
- [
2751
- "try {",
2752
- `Register-ScheduledTask -TaskName ${psQuote2(task)} -Force`,
2753
- "-Action (New-ScheduledTaskAction -Execute (Join-Path $env:WINDIR 'System32\\conhost.exe') -Argument ('--headless ' + (Join-Path $env:WINDIR 'System32\\cmd.exe') + ' /d /c ' + [char]34 + $launcher + [char]34))",
2754
- "-Trigger (New-ScheduledTaskTrigger -AtLogOn -User $user)",
2755
- "-Principal (New-ScheduledTaskPrincipal -UserId $user -LogonType Interactive -RunLevel Limited)",
2756
- "-Settings (New-ScheduledTaskSettingsSet -ExecutionTimeLimit ([TimeSpan]::Zero) -MultipleInstances IgnoreNew -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable)",
2757
- "| Out-Null",
2758
- "} catch {",
2759
- `$kept = Get-ScheduledTask -TaskName ${psQuote2(task)} -ErrorAction SilentlyContinue;`,
2760
- "if (-not ($kept.Actions | Where-Object { ($_.Execute + ' ' + $_.Arguments).Contains($launcher) })) { throw }",
2761
- "}"
2762
- ].join(" ")
2763
- ].join("; ");
2764
- }
2765
- function endDaemonScript(statePath) {
2766
- return [
2767
- `$f = ${psQuote2(statePath)}`,
2768
- [
2769
- "if (Test-Path -LiteralPath $f) {",
2770
- "$id = [int](Get-Content -Raw -LiteralPath $f | ConvertFrom-Json).pid;",
2771
- "$p = Get-CimInstance Win32_Process -Filter ('ProcessId=' + $id);",
2772
- "if ($p -and $p.CommandLine -match 'box run') { taskkill /pid $id /t /f | Out-Null }",
2773
- "}"
2774
- ].join(" ")
2775
- ].join("; ");
2776
- }
2777
- var endDaemonStep = (environment) => ({
2778
- command: [
2779
- "powershell",
2780
- "-NoProfile",
2781
- "-NonInteractive",
2782
- "-Command",
2783
- endDaemonScript(runnerStatePath(environment))
2784
- ],
2785
- mayFail: true
2786
- });
2787
- function programFor(script, node, npx, version) {
2788
- if (!isRelease(script)) return [node, script, "box", "run"];
2789
- if (!npx)
2790
- return "npx is not on PATH, so the service cannot run Cloop. Install Node.js with npm, which ships npx, and run `cloop connect` again.";
2791
- return [npx, "-y", `@cloop/runner@${version}`, "box", "run"];
2792
- }
2793
- function isRelease(script) {
2794
- const published = (path) => /[\\/](_npx|node_modules)[\\/]/.test(path);
2795
- try {
2796
- return published(realpathSync2(script));
2797
- } catch {
2798
- return published(script);
2799
- }
2800
- }
2801
- var NPX = process.platform === "win32" ? "npx.cmd" : "npx";
2802
- function findNpx(execPath = process.execPath, onPath = which(NPX)) {
2803
- const beside = join8(dirname3(execPath), NPX);
2804
- if (!existsSync6(beside)) return onPath;
2805
- const opt = beside.replace(/\/Cellar\/([^/]+)\/[^/]+\//, "/opt/$1/");
2806
- return [onPath, opt].find((path) => path && path !== beside && sameFile(path, beside)) ?? beside;
2807
- }
2808
- function sameFile(a, b) {
2809
- try {
2810
- return realpathSync2(a) === realpathSync2(b);
2811
- } catch {
2812
- return false;
2813
- }
2814
- }
2815
- var FIRST_CONNECT_MS = 9e4;
2816
- async function awaitDaemon(since, read = readRunnerState, { timeoutMs = FIRST_CONNECT_MS, pollMs = 500 } = {}) {
2817
- for (let waited = 0; ; waited += pollMs) {
2818
- const state = read();
2819
- if (state && Date.parse(state.connected_at) >= since) return true;
2820
- if (waited >= timeoutMs) return false;
2821
- await new Promise((r) => setTimeout(r, pollMs));
2822
- }
2823
- }
2824
- var UNIT_ENV = [
2825
- "PATH",
2826
- "CLOOP_BOX_FILE",
2827
- "CLOOP_BOX_THREADS_FILE",
2828
- "CLOOP_LOCAL_RUNS_FILE",
2829
- "CLOOP_UPDATE_DIR",
2830
- "CLOOP_MESH_URL",
2831
- "CLOOP_ORIGIN",
2832
- "T3CODE_HOME"
2833
- ];
2834
- function unitEnv(env) {
2835
- const picked = { PATH: "/usr/bin:/bin" };
2836
- const byName = new Map(Object.entries(env).map(([key, value]) => [key.toUpperCase(), value]));
2837
- for (const key of UNIT_ENV) {
2838
- const value = env[key] ?? byName.get(key);
2839
- if (value) picked[key] = value;
2840
- }
2841
- return picked;
2842
- }
2843
- function serviceEnv(env = process.env) {
2844
- const origin = getOrigin();
2845
- return unitEnv({ ...env, CLOOP_ORIGIN: origin, CLOOP_MESH_URL: env.CLOOP_MESH_URL || origin });
2846
- }
2847
- function installedService(opts) {
2848
- const { label, unit, task, file } = serviceIdentity(opts.kind, opts.environment);
2849
- if (opts.platform === "darwin") {
2850
- return {
2851
- path: join8(opts.dir ?? join8(opts.home, "Library", "LaunchAgents"), `${label}.plist`),
2852
- steps: [{ command: ["launchctl", "bootout", `gui/${opts.uid}/${label}`], mayFail: true }],
2853
- running: ["launchctl", "print", `gui/${opts.uid}/${label}`]
2854
- };
2855
- }
2856
- if (opts.platform === "win32") {
2857
- return {
2858
- path: join8(opts.dir ?? join8(opts.home, "AppData", "Local", "Cloop"), `${file}.cmd`),
2859
- steps: [
2860
- { command: ["schtasks", "/end", "/tn", task], mayFail: true },
2861
- endDaemonStep(opts.environment),
2862
- { command: ["schtasks", "/delete", "/tn", task, "/f"], mayFail: true }
2863
- ],
2864
- running: ["schtasks", "/query", "/tn", task]
2865
- };
2866
- }
2867
- return {
2868
- path: join8(opts.dir ?? join8(opts.home, ".config", "systemd", "user"), unit),
2869
- steps: [{ command: ["systemctl", "--user", "disable", "--now", unit], mayFail: true }],
2870
- running: ["systemctl", "--user", "is-active", "--quiet", unit]
2871
- };
2872
- }
2873
- function unitFor(opts) {
2874
- const env = Object.entries(opts.env);
2875
- const { label, unit, task, file } = serviceIdentity(opts.kind, opts.environment);
2876
- const retire = installedService({
2877
- ...opts,
2878
- kind: opts.kind === "workstation" ? "local" : "workstation"
2879
- });
2880
- if (opts.platform === "darwin") {
2881
- const agents = opts.dir ?? join8(opts.home, "Library", "LaunchAgents");
2882
- const path2 = join8(agents, `${label}.plist`);
2883
- const log = join8(opts.home, "Library", "Logs", `${file}.log`);
2884
- const xml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
2885
- const contents2 = [
2886
- '<?xml version="1.0" encoding="UTF-8"?>',
2887
- '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
2888
- '<plist version="1.0">',
2889
- "<dict>",
2890
- ` <key>Label</key><string>${label}</string>`,
2891
- " <key>ProgramArguments</key>",
2892
- " <array>",
2893
- ...opts.program.map((arg) => ` <string>${xml(arg)}</string>`),
2894
- " </array>",
2895
- " <key>EnvironmentVariables</key>",
2896
- ` <dict>${env.map(([key, value]) => `<key>${key}</key><string>${xml(value)}</string>`).join("")}</dict>`,
2897
- " <key>RunAtLoad</key><true/>",
2898
- " <key>KeepAlive</key><true/>",
2899
- " <key>ThrottleInterval</key><integer>10</integer>",
2900
- ` <key>StandardOutPath</key><string>${xml(log)}</string>`,
2901
- ` <key>StandardErrorPath</key><string>${xml(log)}</string>`,
2902
- "</dict>",
2903
- "</plist>",
2904
- ""
2905
- ].join("\n");
2906
- const domain = `gui/${opts.uid}`;
2907
- return {
2908
- path: path2,
2909
- contents: contents2,
2910
- start: [
2911
- { command: ["launchctl", "bootout", `${domain}/${label}`], mayFail: true },
2912
- { command: ["launchctl", "bootstrap", domain, path2], tries: 5 }
2913
- ],
2914
- retire,
2915
- logs: `tail -f ${log}`,
2916
- tail: ["tail", "-n", "20", log]
2917
- };
2918
- }
2919
- if (opts.platform === "win32") {
2920
- const dir = opts.dir ?? join8(opts.home, "AppData", "Local", "Cloop");
2921
- const path2 = join8(dir, `${file}.cmd`);
2922
- const log = join8(dir, `${file}.log`);
2923
- const psLog = log.replace(/'/g, "''");
2924
- const contents2 = [
2925
- "@echo off",
2926
- ...env.map(([key, value]) => `set "${key}=${cmdValue(value)}"`),
2927
- ":run",
2928
- `call ${opts.program.map(cmdWord).join(" ")} >> ${cmdWord(log)} 2>&1`,
2929
- "rem timeout needs a console, and a scheduled task has none.",
2930
- "ping -n 6 127.0.0.1 >nul",
2931
- "goto run",
2932
- ""
2933
- ].join("\r\n");
2934
- return {
2935
- path: path2,
2936
- contents: contents2,
2937
- start: [
2938
- { command: ["schtasks", "/end", "/tn", task], mayFail: true },
2939
- endDaemonStep(opts.environment),
2940
- {
2941
- command: [
2942
- "powershell",
2943
- "-NoProfile",
2944
- "-NonInteractive",
2945
- "-Command",
2946
- registerTaskScript(task, path2)
2947
- ]
2948
- },
2949
- { command: ["schtasks", "/run", "/tn", task] }
2950
- ],
2951
- retire,
2952
- logs: `Get-Content -Wait '${psLog}'`,
2953
- tail: [
2954
- "powershell",
2955
- "-NoProfile",
2956
- "-NonInteractive",
2957
- "-Command",
2958
- `Get-Content -Tail 20 '${psLog}'`
2959
- ]
2960
- };
2961
- }
2962
- const units = opts.dir ?? join8(opts.home, ".config", "systemd", "user");
2963
- const path = join8(units, unit);
2964
- const contents = [
2965
- "[Unit]",
2966
- `Description=${task}: answers the Cloop Agent over the mesh`,
2967
- "After=network-online.target",
2968
- // A disconnected runner exits 1 on every start. Three in ten minutes and
2969
- // systemd marks the unit failed instead of restarting it forever.
2970
- "StartLimitIntervalSec=600",
2971
- "StartLimitBurst=3",
2972
- "",
2973
- "[Service]",
2974
- ...env.map(([key, value]) => `Environment=${systemdAssignment(`${key}=${value}`)}`),
2975
- `ExecStart=${opts.program.map(systemdWord).join(" ")}`,
2976
- "Restart=always",
2977
- "RestartSec=5",
2978
- "",
2979
- "[Install]",
2980
- "WantedBy=default.target",
2981
- ""
2982
- ].join("\n");
2983
- return {
2984
- path,
2985
- contents,
2986
- start: [
2987
- { command: ["systemctl", "--user", "reset-failed", unit], mayFail: true },
2988
- { command: ["systemctl", "--user", "daemon-reload"] },
2989
- { command: ["systemctl", "--user", "enable", unit] },
2990
- { command: ["systemctl", "--user", "restart", unit] }
2991
- ],
2992
- retire,
2993
- logs: `journalctl --user -u ${unit} -f`,
2994
- tail: ["journalctl", "--user", "-u", unit, "-n", "20", "--no-pager"]
2995
- };
2996
- }
2997
1973
  function resolveRepos(paths, toplevel, isFolder = folderAt) {
2998
1974
  const repos = [];
2999
1975
  for (const p of paths) {
@@ -3001,13 +1977,13 @@ function resolveRepos(paths, toplevel, isFolder = folderAt) {
3001
1977
  if (!isFolder(full))
3002
1978
  return `${p} is not a folder. Pass --repo <path> for each folder Cloop may work in.`;
3003
1979
  const top = toplevel(full) ?? full;
3004
- if (!repos.some((r) => r.path === top)) repos.push({ label: basename5(top), path: top });
1980
+ if (!repos.some((r) => r.path === top)) repos.push({ label: basename4(top), path: top });
3005
1981
  }
3006
1982
  return repos;
3007
1983
  }
3008
1984
  function folderAt(path) {
3009
1985
  try {
3010
- return statSync2(path).isDirectory();
1986
+ return statSync(path).isDirectory();
3011
1987
  } catch {
3012
1988
  return false;
3013
1989
  }
@@ -3016,7 +1992,7 @@ var CHECKOUT_ROOTS = ["projects", "code", "repos", "src", "Developer", "dev", "w
3016
1992
  function lastCommitAt(path) {
3017
1993
  try {
3018
1994
  return Number(
3019
- execFileSync2("git", ["-C", path, "log", "-1", "--format=%ct"], {
1995
+ execFileSync("git", ["-C", path, "log", "-1", "--format=%ct"], {
3020
1996
  encoding: "utf-8",
3021
1997
  stdio: ["ignore", "pipe", "ignore"],
3022
1998
  timeout: 5e3
@@ -3031,13 +2007,13 @@ function findCheckouts(home, limit = 8) {
3031
2007
  for (const root of CHECKOUT_ROOTS) {
3032
2008
  let entries;
3033
2009
  try {
3034
- entries = readdirSync4(join8(home, root), { withFileTypes: true });
2010
+ entries = readdirSync2(join4(home, root), { withFileTypes: true });
3035
2011
  } catch {
3036
2012
  continue;
3037
2013
  }
3038
2014
  for (const entry of entries) {
3039
- const path = join8(home, root, entry.name);
3040
- if (!entry.isDirectory() || !existsSync6(join8(path, ".git"))) continue;
2015
+ const path = join4(home, root, entry.name);
2016
+ if (!entry.isDirectory() || !existsSync3(join4(path, ".git"))) continue;
3041
2017
  found.push({ repo: { label: entry.name, path }, at: lastCommitAt(path) });
3042
2018
  }
3043
2019
  }
@@ -3057,7 +2033,7 @@ function rerunCommand(argv, script = process.argv[1] ?? "") {
3057
2033
  return [base, "connect", ...staging, ...argv].join(" ");
3058
2034
  }
3059
2035
  function workFolder(home) {
3060
- return { label: "Cloop", path: join8(home, "Cloop") };
2036
+ return { label: "Cloop", path: join4(home, "Cloop") };
3061
2037
  }
3062
2038
  function workFolderLine(found, home, argv, terminal) {
3063
2039
  const rerun = rerunCommand(argv.filter((a) => a !== "--ask"));
@@ -3092,14 +2068,14 @@ async function reposFor(argv) {
3092
2068
  return repos2;
3093
2069
  }
3094
2070
  const here = gitTop(process.cwd());
3095
- if (here) return [{ label: basename5(here), path: here }];
3096
- const home = homedir6();
2071
+ if (here) return [{ label: basename4(here), path: here }];
2072
+ const home = homedir3();
3097
2073
  const work = workFolder(home);
3098
2074
  const found = findCheckouts(home);
3099
2075
  let repos = [work];
3100
2076
  const terminal = Boolean(process.stdin.isTTY && process.stdout.isTTY);
3101
2077
  if (asksForFolders(argv, found, terminal)) {
3102
- const prompt = createInterface({ input: process.stdin, output: process.stdout });
2078
+ const prompt = createInterface2({ input: process.stdin, output: process.stdout });
3103
2079
  const closed = () => new ConnectFailure(
3104
2080
  "no_repo",
3105
2081
  `No folder chosen. Run ${rerunCommand(argv)} --repo <path> to name one.`
@@ -3110,7 +2086,7 @@ async function reposFor(argv) {
3110
2086
  prompt.close();
3111
2087
  }
3112
2088
  } else out(`${bold("Cloop machine")} ${workFolderLine(found, home, argv, terminal)}`);
3113
- if (repos.some((r) => r.path === work.path)) mkdirSync3(work.path, { recursive: true });
2089
+ if (repos.some((r) => r.path === work.path)) mkdirSync(work.path, { recursive: true });
3114
2090
  return repos;
3115
2091
  }
3116
2092
  function askOrClosed(prompt, closed) {
@@ -3131,7 +2107,7 @@ function askOrClosed(prompt, closed) {
3131
2107
  }
3132
2108
  function gitTop(path) {
3133
2109
  try {
3134
- return execFileSync2("git", ["-C", path, "rev-parse", "--show-toplevel"], {
2110
+ return execFileSync("git", ["-C", path, "rev-parse", "--show-toplevel"], {
3135
2111
  encoding: "utf-8",
3136
2112
  stdio: ["ignore", "pipe", "ignore"]
3137
2113
  }).trim();
@@ -3152,31 +2128,6 @@ function harnessLine(h) {
3152
2128
  const account = h.signedIn ? h.account ?? "signed in" : "signed out";
3153
2129
  return `${h.name}${version}, ${account}${h.experimental ? " (experimental)" : ""}`;
3154
2130
  }
3155
- async function runSteps(steps, run2 = (command) => void execFileSync2(command[0], command.slice(1), { stdio: "ignore", timeout: 15e3 }), wait = (ms) => new Promise((r) => setTimeout(r, ms))) {
3156
- for (const step of steps) {
3157
- const tries = step.tries ?? 1;
3158
- for (let attempt = 1; ; attempt++) {
3159
- try {
3160
- run2(step.command);
3161
- break;
3162
- } catch (err) {
3163
- if (step.mayFail) break;
3164
- if (attempt >= tries) throw err;
3165
- await wait(1e3);
3166
- }
3167
- }
3168
- }
3169
- }
3170
- var systemServices = {
3171
- platform: process.platform,
3172
- run: (command) => execFileSync2(command[0], command.slice(1), {
3173
- encoding: "utf-8",
3174
- stdio: ["ignore", "pipe", "ignore"],
3175
- timeout: 15e3,
3176
- ...command[0] === "powershell" ? { env: windowsPowerShellEnv() } : {}
3177
- }),
3178
- awaitUp: (since) => awaitDaemon(since)
3179
- };
3180
2131
  function ensureLinger(user, run2) {
3181
2132
  try {
3182
2133
  if (/Linger=yes/.test(run2(["loginctl", "show-user", user, "-p", "Linger"]))) {
@@ -3209,14 +2160,14 @@ async function installService(kind, argv, attempt, services = systemServices) {
3209
2160
  platform: services.platform,
3210
2161
  kind,
3211
2162
  environment,
3212
- home: homedir6(),
2163
+ home: homedir3(),
3213
2164
  program,
3214
2165
  env: serviceEnv(),
3215
2166
  uid: process.getuid?.() ?? 0,
3216
2167
  ...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
3217
2168
  });
3218
- mkdirSync3(join8(unit.path, ".."), { recursive: true });
3219
- writeFileSync2(unit.path, unit.contents);
2169
+ mkdirSync(join4(unit.path, ".."), { recursive: true });
2170
+ writeFileSync(unit.path, unit.contents);
3220
2171
  if (argv.includes("--no-start")) {
3221
2172
  out(
3222
2173
  ` Service: wrote ${unit.path}. Start it with: ${dim(unit.start.map((step) => step.command.join(" ")).join(" && "))}`
@@ -3227,12 +2178,12 @@ async function installService(kind, argv, attempt, services = systemServices) {
3227
2178
  const since = Date.now();
3228
2179
  const run2 = (command) => void services.run(command);
3229
2180
  try {
3230
- if (existsSync6(unit.retire.path)) {
2181
+ if (existsSync3(unit.retire.path)) {
3231
2182
  out(
3232
2183
  ` This computer is already a ${environment} machine, so connect stops and removes ${unit.retire.path}.`
3233
2184
  );
3234
2185
  await runSteps(unit.retire.steps, run2);
3235
- rmSync3(unit.retire.path, { force: true });
2186
+ rmSync(unit.retire.path, { force: true });
3236
2187
  }
3237
2188
  await runSteps(unit.start, run2);
3238
2189
  } catch (err) {
@@ -3361,13 +2312,14 @@ async function connectT3(argv, attempt, fallback, chosen, services) {
3361
2312
  async function connectLocal(driver, found, argv, attempt, chosen, services) {
3362
2313
  attempt.step = "repos";
3363
2314
  const repos = await reposFor(argv);
3364
- const work = workFolder(homedir6()).path;
2315
+ const work = workFolder(homedir3()).path;
3365
2316
  attempt.workFolder = repos.every((r) => r.path === work);
3366
- const harness = driver === "claude-code" ? found.claude : found.codex;
3367
- const bin = which(driver === "claude-code" ? "claude" : "codex") ?? (driver === "claude-code" ? "claude" : "codex");
2317
+ const agent = AGENTS[driver];
2318
+ const harness = found[agent.bin];
2319
+ const bin = which(agent.bin) ?? agent.bin;
3368
2320
  const previous = readRunnerConfig();
3369
2321
  const deviceName = flag(argv, "--name") ?? defaultDeviceName();
3370
- const fallbackModels = driver === "claude-code" ? flag(argv, "--fallback-model") ?? (previous && isLocal(previous) ? previous.fallbackModels : void 0) ?? DEFAULT_FALLBACK_MODEL : void 0;
2322
+ const fallbackModels = agent.takesOptions ? flag(argv, "--fallback-model") ?? (previous && isLocal(previous) ? previous.fallbackModels : void 0) ?? DEFAULT_FALLBACK_MODEL : void 0;
3371
2323
  const device = {
3372
2324
  kind: "local",
3373
2325
  environmentId: previous && isLocal(previous) ? previous.environmentId : `local:${randomUUID()}`,
@@ -3388,7 +2340,7 @@ async function connectLocal(driver, found, argv, attempt, chosen, services) {
3388
2340
  bin,
3389
2341
  origin: getOrigin(),
3390
2342
  ...fallbackModels ? { fallbackModels } : {},
3391
- ...driver === "claude-code" ? { askEverything: argv.includes("--ask-everything") } : {},
2343
+ ...agent.takesOptions ? { askEverything: argv.includes("--ask-everything") } : {},
3392
2344
  ...chosen ? { chosenDriver: chosen } : {}
3393
2345
  };
3394
2346
  writeBoxConfig(cfg);
@@ -3398,16 +2350,14 @@ async function connectLocal(driver, found, argv, attempt, chosen, services) {
3398
2350
  (t) => revokeOwnDevice(attempt.replacedOrigin ?? getOrigin(), t),
3399
2351
  out
3400
2352
  );
3401
- const others = [found.claude, found.codex].filter(
2353
+ const others = LOCAL_AGENTS.map((other) => found[other.bin]).filter(
3402
2354
  (h) => Boolean(h) && h !== harness
3403
2355
  );
3404
2356
  out(
3405
2357
  `${bold("Cloop machine")} ${deviceName} is a local machine: ${[harness, ...others].map(harnessLine).join("; ")}.`
3406
2358
  );
3407
2359
  out(` Folders: ${repos.map((r) => `${r.label} (${r.path})`).join(", ")}`);
3408
- out(
3409
- ` ${driver === "codex" ? "Full access: Codex always runs every Task without permission checks. --ask-everything applies to Claude Code only." : cfg.askEverything ? "Asks before actions except allowlisted reads." : "Full access: every Task runs without permission checks. Add --ask-everything to approve each step."}`
3410
- );
2360
+ out(` ${agent.accessLine(Boolean(cfg.askEverything))}`);
3411
2361
  if (fallbackModels)
3412
2362
  out(
3413
2363
  ` Fallback model: ${fallbackModels}, when Claude Code's default model is at its limit. Change it with --fallback-model.`
@@ -3415,14 +2365,13 @@ async function connectLocal(driver, found, argv, attempt, chosen, services) {
3415
2365
  await installService("local", argv, attempt, services);
3416
2366
  }
3417
2367
  async function detect(probes) {
3418
- const [t3, claude, codex] = await Promise.all([probes.t3(), probes.claude(), probes.codex()]);
3419
- return { t3, claude, codex };
2368
+ const [t3, claude, codex2] = await Promise.all([probes.t3(), probes.claude(), probes.codex()]);
2369
+ return { t3, claude, codex: codex2 };
3420
2370
  }
3421
2371
  function harnessesFound(found) {
3422
2372
  return [
3423
2373
  ...found.t3 ? ["t3"] : [],
3424
- ...found.claude ? ["claude-code"] : [],
3425
- ...found.codex ? ["codex"] : []
2374
+ ...LOCAL_AGENTS.filter((agent) => found[agent.bin]).map((agent) => agent.id)
3426
2375
  ];
3427
2376
  }
3428
2377
  var MODEL_LIST = /^[A-Za-z0-9][\w.:[\]-]*(,[A-Za-z0-9][\w.:[\]-]*)*$/;
@@ -3430,7 +2379,7 @@ function rememberedDriver(previous) {
3430
2379
  const chosen = previous && !isHosted(previous) ? previous.chosenDriver : void 0;
3431
2380
  return chosen && DRIVERS.includes(chosen) ? chosen : void 0;
3432
2381
  }
3433
- var DRIVERS = ["t3", "claude-code", "codex"];
2382
+ var DRIVERS = Object.keys(AGENTS);
3434
2383
  async function connect(argv, attempt, deps = {}) {
3435
2384
  if (argv.some((arg) => arg === "--webhook" || arg.startsWith("--webhook="))) {
3436
2385
  await connectWebhook(argv, attempt);
@@ -3443,7 +2392,7 @@ async function connect(argv, attempt, deps = {}) {
3443
2392
  const forced = named ?? rememberedDriver(previous);
3444
2393
  if (forced && !named)
3445
2394
  out(
3446
- `${bold("Cloop machine")} This machine runs Cloop work in ${DRIVER_NAME[forced]}, as you chose. Change it with: cloop use <t3|claude-code|codex>`
2395
+ `${bold("Cloop machine")} This machine runs Cloop work in ${AGENTS[forced].name}, as you chose. Change it with: cloop use <t3|claude-code|codex>`
3447
2396
  );
3448
2397
  const fallback = flag(argv, "--fallback-model");
3449
2398
  if (fallback !== void 0 && !MODEL_LIST.test(fallback))
@@ -3453,10 +2402,10 @@ async function connect(argv, attempt, deps = {}) {
3453
2402
  );
3454
2403
  const t3Url = (flag(argv, "--t3-url") ?? DEFAULT_T3_URL).replace(/\/+$/, "");
3455
2404
  const harnessBin = (name) => process.platform === "win32" ? which(name) ?? name : name;
3456
- findLocalCodex(homedir6());
3457
- findLocalClaude(homedir6());
3458
- const readCodex = deps.probes?.codex ?? (() => probeCodex(harnessBin("codex")));
3459
- const readClaude = deps.probes?.claude ?? (() => probeClaude(harnessBin("claude")));
2405
+ findLocalCodex(homedir3());
2406
+ findLocalClaude(homedir3());
2407
+ const readCodex = deps.probes?.codex ?? (() => AGENTS.codex.probe(harnessBin("codex")));
2408
+ const readClaude = deps.probes?.claude ?? (() => AGENTS["claude-code"].probe(harnessBin("claude")));
3460
2409
  const found = await detect(
3461
2410
  deps.probes ?? {
3462
2411
  t3: () => forced && forced !== "t3" ? Promise.resolve(false) : t3Answers(t3Url),
@@ -3469,19 +2418,21 @@ async function connect(argv, attempt, deps = {}) {
3469
2418
  const machine = !deps.probes;
3470
2419
  const terminal = deps.terminal ?? Boolean(process.stdin.isTTY && process.stdout.isTTY);
3471
2420
  const current = await prepareAgents(found, forced, workstation, {
3472
- chatGptApp: deps.chatGptApp ?? (() => machine && hasChatGptApp(homedir6())),
2421
+ chatGptApp: deps.chatGptApp ?? (() => machine && hasChatGptApp(homedir3())),
3473
2422
  codexHostMissing: deps.codexHostMissing ?? (() => machine && codexHostMissing(which("codex"))),
3474
- installCodex: deps.installCodex ?? (async () => machine && installCodex(homedir6())),
3475
- installClaude: deps.installClaude ?? (async () => machine && installClaude(homedir6())),
2423
+ installCodex: deps.installCodex ?? (async () => machine && AGENTS.codex.install(homedir3())),
2424
+ installClaude: deps.installClaude ?? (async () => machine && AGENTS["claude-code"].install(homedir3())),
3476
2425
  readCodex,
3477
2426
  readClaude,
3478
2427
  updateClaude: deps.updateClaude ?? updateClaude,
3479
- signInCodex: deps.signInCodex ?? (() => signInCodex(harnessBin("codex"))),
3480
- signInClaude: deps.signInClaude ?? (() => signInClaude(harnessBin("claude"))),
2428
+ signIn: {
2429
+ codex: deps.signInCodex ?? (() => signIn(AGENTS.codex, harnessBin("codex"))),
2430
+ "claude-code": deps.signInClaude ?? (() => signIn(AGENTS["claude-code"], harnessBin("claude")))
2431
+ },
3481
2432
  terminal,
3482
- installed: (agent2, ok, reason) => {
3483
- attempt[agent2 === "codex" ? "codexInstall" : "claudeInstall"] = ok ? "ok" : "failed";
3484
- if (agent2 === "codex") attempt.codexInstallReason = reason ?? null;
2433
+ installed: (agent, ok, reason2) => {
2434
+ attempt[agent.reportField] = ok ? "ok" : "failed";
2435
+ if (reason2) attempt.codexInstallReason = reason2;
3485
2436
  }
3486
2437
  });
3487
2438
  attempt.harnesses = harnessesFound(current);
@@ -3489,20 +2440,23 @@ async function connect(argv, attempt, deps = {}) {
3489
2440
  if (!choice.ok) throw new ConnectFailure(choice.code, choice.line);
3490
2441
  const local = fallbackDriver(current, forced, workstation);
3491
2442
  await connectChosen(choice.driver, attempt, {
3492
- t3: () => connectT3(argv, attempt, local ? HARNESS_NAME[local] : null, forced, deps.services),
2443
+ t3: () => connectT3(argv, attempt, local ? AGENTS[local].name : null, forced, deps.services),
3493
2444
  local: (driver) => connectLocal(driver, current, argv, attempt, forced, deps.services),
3494
2445
  fallback: () => fallbackDriver(current, forced, workstation),
3495
2446
  say: (line2) => out(`${bold("Cloop machine")} ${line2}`)
3496
2447
  });
3497
2448
  const harnesses = mcpHarnesses(current, attempt.driver).map((harness) => ({
3498
2449
  harness,
3499
- bin: harnessBin(harness === "codex" ? "codex" : "claude")
2450
+ bin: harnessBin(AGENTS[harness].bin)
3500
2451
  }));
3501
2452
  const mcp = deps.mcp ?? (machine ? { cli: systemMcpCli } : null);
3502
2453
  if (mcp) await addCloopMcpLast(harnesses, attempt, mcp, terminal);
3503
2454
  }
3504
2455
  function mcpHarnesses(found, driver) {
3505
- return ownHarnessFirst([found.claude, found.codex], driver).map((h) => h.id).filter((id) => id === "claude-code" || id === "codex");
2456
+ return ownHarnessFirst(
2457
+ LOCAL_AGENTS.map((agent) => found[agent.bin]),
2458
+ driver
2459
+ ).map((h) => h.id).filter((id) => isLocalDriver(id));
3506
2460
  }
3507
2461
  var MCP_STEP_MS = 6 * 6e4;
3508
2462
  async function addCloopMcpLast(found, attempt, mcp, terminal) {
@@ -3552,14 +2506,14 @@ async function prepareAgents(found, forced, workstation, deps) {
3552
2506
  let current = found;
3553
2507
  const say = (line2) => out(`${bold("Cloop machine")} ${line2}`);
3554
2508
  const chatGptApp = forced !== "claude-code" && deps.chatGptApp();
3555
- const getCodex = async (why, reason) => {
2509
+ const getCodex = async (why, reason2) => {
3556
2510
  say(`${why} Installing the latest Codex from ${CODEX_RELEASES}.`);
3557
- const codex = await deps.installCodex() ? await deps.readCodex() : null;
3558
- deps.installed("codex", Boolean(codex), reason);
3559
- if (codex) say(`Installed Codex${codex.version ? ` ${codex.version}` : ""}.`);
2511
+ const codex2 = await deps.installCodex() ? await deps.readCodex() : null;
2512
+ deps.installed(AGENTS.codex, Boolean(codex2), reason2);
2513
+ if (codex2) say(`Installed Codex${codex2.version ? ` ${codex2.version}` : ""}.`);
3560
2514
  else
3561
2515
  out(`${red("\u2717")} Codex did not install. Install it yourself: npm install -g @openai/codex`);
3562
- return codex;
2516
+ return codex2;
3563
2517
  };
3564
2518
  const codexVersion = current.codex?.version;
3565
2519
  if (!current.codex && forced === "codex")
@@ -3590,7 +2544,7 @@ async function prepareAgents(found, forced, workstation, deps) {
3590
2544
  `${current.codex || forced ? "Claude Code is not installed here." : "No coding agent here."} Installing Claude Code with Anthropic's installer.`
3591
2545
  );
3592
2546
  const claude = await deps.installClaude() ? await deps.readClaude() : null;
3593
- deps.installed("claude", Boolean(claude));
2547
+ deps.installed(AGENTS["claude-code"], Boolean(claude));
3594
2548
  if (claude) say(`Installed Claude Code ${claude.version}.`);
3595
2549
  else
3596
2550
  out(
@@ -3601,30 +2555,21 @@ async function prepareAgents(found, forced, workstation, deps) {
3601
2555
  current = await claudeAtFloor(current, forced, deps.updateClaude);
3602
2556
  if (!deps.terminal) return current;
3603
2557
  const driver = forced ?? (current.claude?.signedIn ? "claude-code" : current.codex?.signedIn ? "codex" : current.codex && (chatGptApp || !current.claude) ? "codex" : current.claude ? "claude-code" : null);
3604
- if (driver === "codex" && current.codex && !current.codex.signedIn) {
3605
- say("Sign in to Codex with your ChatGPT account; your browser opens.");
3606
- current = { ...current, codex: await deps.signInCodex() ?? current.codex };
3607
- }
3608
- if (driver === "claude-code" && current.claude && !current.claude.signedIn) {
3609
- say("Sign in to Claude Code; your browser opens.");
3610
- current = { ...current, claude: await deps.signInClaude() ?? current.claude };
2558
+ const agent = localAgent(driver ?? void 0);
2559
+ const harness = agent && current[agent.bin];
2560
+ if (agent && harness && !harness.signedIn) {
2561
+ say(agent.signInLine);
2562
+ current = { ...current, [agent.bin]: await deps.signIn[agent.id]() ?? harness };
3611
2563
  }
3612
2564
  return current;
3613
2565
  }
3614
- function signInCodex(bin) {
3615
- const login = runShown2(
3616
- [bin, "login", ...process.platform === "linux" ? ["--device-auth"] : []],
3617
- true
3618
- );
3619
- return login.status === 0 ? probeCodex(bin) : Promise.resolve(null);
3620
- }
3621
- function signInClaude(bin) {
3622
- return runShown2([bin, "auth", "login"], true).status === 0 ? probeClaude(bin) : Promise.resolve(null);
2566
+ function signIn(agent, bin) {
2567
+ return runShown2(agent.signIn(bin, process.platform), true).status === 0 ? agent.probe(bin) : Promise.resolve(null);
3623
2568
  }
3624
2569
  async function claudeAtFloor(found, forced, update) {
3625
2570
  const version = found.claude?.version;
3626
- const codex = forced === "codex" || !forced && !found.claude?.signedIn && Boolean(found.codex?.signedIn);
3627
- if (!version || codex || !olderThan(version, CLAUDE_FLOOR)) return found;
2571
+ const codex2 = forced === "codex" || !forced && !found.claude?.signedIn && Boolean(found.codex?.signedIn);
2572
+ if (!version || codex2 || !olderThan(version, CLAUDE_FLOOR)) return found;
3628
2573
  out(`${bold("Cloop machine")} ${claudeTooOld(version)} Updating it.`);
3629
2574
  const claude = await update();
3630
2575
  if (!claude?.version || olderThan(claude.version, CLAUDE_FLOOR))
@@ -3677,16 +2622,12 @@ async function runConnect(argv, deps = {}) {
3677
2622
  const attempt = newAttempt();
3678
2623
  let error = null;
3679
2624
  try {
3680
- attempt.step = "legacy_move";
3681
- try {
3682
- if (await moveLegacyStagingRunner(deps.services ?? systemServices))
3683
- out(`${bold("Cloop machine")} ${movedLine(environment)}`);
3684
- } catch (err) {
3685
- throw new ConnectFailure(
3686
- "legacy_move_failed",
3687
- err instanceof Error ? err.message : String(err)
3688
- );
3689
- }
2625
+ await moveLegacyStagingRunnerOnConnect(
2626
+ attempt,
2627
+ deps.services ?? systemServices,
2628
+ environment,
2629
+ (line2) => out(`${bold("Cloop machine")} ${line2}`)
2630
+ );
3690
2631
  attempt.step = "detect";
3691
2632
  const replacedOrigin = runnerOrigin(environment);
3692
2633
  console.error(
@@ -3714,15 +2655,13 @@ export {
3714
2655
  classifyError,
3715
2656
  answerCall,
3716
2657
  SUBSCRIPTIONS,
3717
- probeClaudePermissions,
3718
- probeClaude,
3719
- DEFAULT_FALLBACK_MODEL,
3720
- claudeDialect,
3721
- probeCodex,
3722
- codexModels,
3723
- codexDialect,
2658
+ LocalUsage,
2659
+ AGENTS,
2660
+ LOCAL_AGENTS,
2661
+ localAgent,
2662
+ configuredBin,
2663
+ quotaProbes,
3724
2664
  DEFAULT_T3_URL,
3725
- which,
3726
2665
  T3PairError,
3727
2666
  mintSession,
3728
2667
  sessionFromLink,
@@ -3731,7 +2670,6 @@ export {
3731
2670
  askHidden,
3732
2671
  connectBox,
3733
2672
  chooseDriver,
3734
- DRIVER_NAME,
3735
2673
  fallbackDriver,
3736
2674
  isWorkstation,
3737
2675
  revokeReplaced,
@@ -3739,22 +2677,6 @@ export {
3739
2677
  relinkLine,
3740
2678
  fallbackLine,
3741
2679
  connectChosen,
3742
- systemdAssignment,
3743
- systemdWord,
3744
- cmdValue,
3745
- cmdWord,
3746
- psQuote2 as psQuote,
3747
- registerTaskScript,
3748
- endDaemonScript,
3749
- programFor,
3750
- isRelease,
3751
- findNpx,
3752
- FIRST_CONNECT_MS,
3753
- awaitDaemon,
3754
- unitEnv,
3755
- serviceEnv,
3756
- installedService,
3757
- unitFor,
3758
2680
  resolveRepos,
3759
2681
  findCheckouts,
3760
2682
  tilde,
@@ -3765,8 +2687,6 @@ export {
3765
2687
  askRepos,
3766
2688
  asksForFolders,
3767
2689
  askOrClosed,
3768
- runSteps,
3769
- systemServices,
3770
2690
  ensureLinger,
3771
2691
  detect,
3772
2692
  harnessesFound,
@@ -3777,24 +2697,5 @@ export {
3777
2697
  WINGET_UPDATE,
3778
2698
  updateClaude,
3779
2699
  runConnect,
3780
- connectCommand,
3781
- legacyStagingRunner,
3782
- moveRunnerFiles,
3783
- moveLegacyStagingRunner,
3784
- claudeHome,
3785
- codexHome2 as codexHome,
3786
- TITLE_MAX,
3787
- HOST_ID_MAX,
3788
- CAPTURE_TICK_MS,
3789
- captureCursorPath,
3790
- ThreadCapture,
3791
- doneLine,
3792
- unitOrigin,
3793
- disconnectPlan,
3794
- stopService,
3795
- disconnect,
3796
- runnerOrigin,
3797
- disconnectCommand,
3798
- existingRunnerEnvironment,
3799
- pinExistingRunner
2700
+ connectCommand
3800
2701
  };