@cloop/runner 0.3.1 → 0.3.7

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.
@@ -12,7 +12,8 @@ var RESULT_INSTRUCTION = [
12
12
  "```cloop-result",
13
13
  '{"summary": "One or two sentences on what you did.", "outputs": [{"kind": "pr", "title": "fix: the thing", "url": "https://github.com/org/repo/pull/1"}], "checks": [{"name": "Tests", "outcome": "passed"}]}',
14
14
  "```",
15
- "An output kind is one of: pr or link (title, url), draft (title, body, optional to), doc (title, optional url or body), file (title, path). A check outcome is passed, failed or skipped.",
15
+ "An output kind is one of: pr or link (title, url), draft (title, body, optional to, optional url), doc (title, optional url or body), file (title, path). A check outcome is passed, failed or skipped.",
16
+ "A draft's body is the message itself, as the recipient will read it; if you saved it somewhere (a Gmail draft), put that link in url, never in body. A doc's body is the whole page in GitHub Markdown: headings, lists, bold and tables all show; a table suits one row per item. Give every product, page or source you mention as a full https link.",
16
17
  "List as outputs only what this run made. A PR or page you only read, checked or cited goes in the summary, never in outputs."
17
18
  ].join("\n");
18
19
  var text = (v, max) => typeof v === "string" && v.length <= max;
@@ -58,11 +59,12 @@ function cleanOutput(o) {
58
59
  case "link":
59
60
  return https(out.url) ? { kind: out.kind, title, url: out.url } : null;
60
61
  case "draft":
61
- return text(out.body, 4e3) && optionalText(out.to, 200) ? {
62
+ return text(out.body, 4e3) && optionalText(out.to, 200) && (out.url === void 0 || https(out.url)) ? {
62
63
  kind: "draft",
63
64
  title,
64
65
  body: out.body,
65
- ...out.to !== void 0 ? { to: out.to } : {}
66
+ ...out.to !== void 0 ? { to: out.to } : {},
67
+ ...out.url !== void 0 ? { url: out.url } : {}
66
68
  } : null;
67
69
  case "doc": {
68
70
  const body = typeof out.body === "string" && out.body.length > DOC_BODY_MAX ? `${out.body.slice(0, DOC_BODY_MAX - 1)}\u2026` : out.body;
@@ -177,6 +179,17 @@ function isYes(reply) {
177
179
  reply.trim().toLowerCase().replace(/[.!\s]+$/, "")
178
180
  );
179
181
  }
182
+ var HARNESS_LIMIT = /usage limit|reached your [\w .-]{0,40}limit|hit your [\w .-]{0,40}limit|out of (usage )?credits/i;
183
+ function limitedModel(said) {
184
+ const name = /reached your ([\w .-]{1,40}?) limit/i.exec(said ?? "")?.[1];
185
+ return name && !/usage|weekly|daily|session|hour|month/i.test(name) ? name : null;
186
+ }
187
+ var LIMIT_HOLD_MS = 60 * 6e4;
188
+ function handoverPrompt(prompt, from) {
189
+ return `${prompt}
190
+
191
+ ${from} started this work and stopped at its usage limit. Its changes, if any, are in this checkout. Read \`git status\` and \`git log\` first, and carry on from there.`;
192
+ }
180
193
 
181
194
  // src/run-log.ts
182
195
  import {
@@ -395,6 +408,7 @@ function whichAll(bin) {
395
408
 
396
409
  // src/drivers/t3.ts
397
410
  import { execFile, execFileSync as execFileSync2 } from "child_process";
411
+ import { randomUUID } from "crypto";
398
412
  function isUnsettled(t) {
399
413
  return !t.settledAt && !t.archivedAt && !isChild(t);
400
414
  }
@@ -404,6 +418,7 @@ function isChild(t) {
404
418
  var SESSIONS_TTL_MS = 5 * 6e4;
405
419
  var STATUS_TTL_MS = 3e4;
406
420
  var TERMINAL_RUN = /* @__PURE__ */ new Set(["completed", "interrupted", "failed", "cancelled", "rolled_back"]);
421
+ var STOPPED_IN_T3 = "You stopped this in T3.";
407
422
  var IDLE_SETTLE_MS = 20 * 6e4;
408
423
  var APPROVAL_WORDS = {
409
424
  command: "run a command",
@@ -484,6 +499,17 @@ function outcomeOf(p) {
484
499
  function permissionOf(runtimeMode) {
485
500
  return runtimeMode === "full-access" ? "full" : "ask";
486
501
  }
502
+ var CODEX_PROVIDER = "codex";
503
+ var PROVIDER_NAMES = { claudeAgent: "Claude Code", codex: "Codex" };
504
+ function providerName(instanceId) {
505
+ return instanceId && PROVIDER_NAMES[instanceId] || instanceId || "The harness";
506
+ }
507
+ function codexProvider(cfg) {
508
+ const p = cfg.providers.find((x) => (x.driver ?? x.instanceId) === CODEX_PROVIDER && x.enabled);
509
+ if (!p || p.auth && p.auth.status !== "authenticated") return null;
510
+ const model = p.models?.find((m) => m.isDefault)?.slug ?? p.models?.[0]?.slug;
511
+ return model ? { instanceId: p.instanceId, model } : null;
512
+ }
487
513
  function pickProject(projects, repository) {
488
514
  if (!repository) {
489
515
  const repos = projects.filter((p) => p.repositoryIdentity);
@@ -570,6 +596,10 @@ var T3Driver = class {
570
596
  name = "t3";
571
597
  /** Threads whose turn ended without a result block, by id: ends the held run on a stop. */
572
598
  held = /* @__PURE__ */ new Map();
599
+ /** Threads this daemon launched. A restart forgets them, and a forgotten thread is not moved. */
600
+ launched = /* @__PURE__ */ new Map();
601
+ /** Until then, a launch that names no harness starts on Codex: the Claude account is at its limit. */
602
+ limitedUntil = 0;
573
603
  get capabilities() {
574
604
  return boxCapabilities(this.deps.scope?.());
575
605
  }
@@ -668,7 +698,15 @@ var T3Driver = class {
668
698
  this.t3.http("/api/orchestration/shell", SHELL_HEADERS)
669
699
  ]);
670
700
  const project = pickProject(shell.projects ?? [], a.repository);
671
- const fallback = cfg.settings?.defaultModelSelection;
701
+ const runtimeMode = a.runtime_mode ?? cfg.settings?.defaultRuntimeMode;
702
+ if (!runtimeMode || !RUNTIME_MODES.has(runtimeMode))
703
+ throw new BoxToolError("runtime_mode_unknown");
704
+ const permission = permissionOf(runtimeMode);
705
+ const named = Boolean(a.harness || a.model);
706
+ const held = !named && permission === "full" && this.now() < this.limitedUntil;
707
+ const own = cfg.settings?.defaultModelSelection?.instanceId ?? "claudeAgent";
708
+ const codex = held && own !== CODEX_PROVIDER ? codexProvider(cfg) : null;
709
+ const fallback = codex ?? cfg.settings?.defaultModelSelection;
672
710
  const harness = a.harness ?? fallback?.instanceId ?? "claudeAgent";
673
711
  const provider = cfg.providers.find((p) => p.instanceId === harness && p.enabled);
674
712
  if (!provider) throw new BoxToolError("harness_unavailable");
@@ -677,9 +715,7 @@ var T3Driver = class {
677
715
  const model = a.model ?? (fallback?.instanceId === harness ? fallback.model : void 0) ?? provider.models?.find((m) => m.isDefault)?.slug;
678
716
  if (!model) throw new BoxToolError("harness_unavailable");
679
717
  const modelSelection = !a.model && fallback?.instanceId === harness ? fallback : { instanceId: harness, model };
680
- const runtimeMode = a.runtime_mode ?? cfg.settings?.defaultRuntimeMode;
681
- if (!runtimeMode || !RUNTIME_MODES.has(runtimeMode))
682
- throw new BoxToolError("runtime_mode_unknown");
718
+ if (codex) this.log(`limit hold: launch work=${a.work_id} starts on ${codex.instanceId}`);
683
719
  const launched = await this.t3.rpc(
684
720
  "orchestration.launchThread",
685
721
  {
@@ -699,11 +735,16 @@ var T3Driver = class {
699
735
  ${RESULT_INSTRUCTION}`, attachments: [] }
700
736
  }
701
737
  );
702
- return {
703
- thread_id: launched.threadId,
704
- resumed: launched.resumed,
705
- permission: permissionOf(runtimeMode)
706
- };
738
+ if (!this.launched.has(launched.threadId))
739
+ this.launched.set(launched.threadId, {
740
+ named,
741
+ permission,
742
+ ...codex ? {
743
+ movedFrom: "",
744
+ switched: `${providerName(own)} is at its usage limit, so Codex did this run.`
745
+ } : {}
746
+ });
747
+ return { thread_id: launched.threadId, resumed: launched.resumed, permission };
707
748
  }
708
749
  /**
709
750
  * Say something to a thread. While the thread waits on a question, only
@@ -959,23 +1000,45 @@ ${RESULT_INSTRUCTION}`, attachments: [] }
959
1000
  );
960
1001
  return;
961
1002
  }
1003
+ const entry = this.launched.get(threadId);
1004
+ if (turn && entry?.movedFrom === turn.id) {
1005
+ finishing = false;
1006
+ return;
1007
+ }
1008
+ if (outcome.kind === "failed" && turn && await this.moveToCodex(threadId, turn, outcome)) {
1009
+ finishing = false;
1010
+ if (stopped) return;
1011
+ onEvent({
1012
+ kind: "progress",
1013
+ summary: `${providerName(turn.providerInstanceId)} is at its usage limit, so I moved this to Codex`
1014
+ });
1015
+ if (!live) void follow();
1016
+ return;
1017
+ }
1018
+ if (stopped) return;
962
1019
  wake();
963
1020
  stopped = true;
964
1021
  live?.close();
965
1022
  const pr = outcome.pr_url ? { pr_url: outcome.pr_url } : {};
1023
+ const opening = entry?.switched ? `${entry.switched} ` : "";
966
1024
  if (outcome.kind === "failed") {
967
- onEvent({
968
- kind: "failed",
969
- summary: `The run ended ${outcome.status}.`,
970
- ...outcome.result ? pr : {}
971
- });
1025
+ const said = outcome.last_assistant_text?.replace(/\s+/g, " ").trim();
1026
+ const limited = outcome.status === "failed" && HARNESS_LIMIT.test(said ?? "");
1027
+ const end = limited ? {
1028
+ summary: `${opening}${providerName(turn?.providerInstanceId)} said: "${said}"`.slice(
1029
+ 0,
1030
+ RUN_TEXT_MAX
1031
+ ),
1032
+ error: "harness_limit"
1033
+ } : outcome.status === "interrupted" ? { summary: STOPPED_IN_T3, error: "interrupted" } : { summary: `${opening}The run ended ${outcome.status}.` };
1034
+ onEvent({ kind: "failed", ...end, ...outcome.result ? pr : {} });
972
1035
  } else {
973
1036
  const lost = outcome.dropped ? droppedLine(outcome.dropped, threadId) : null;
974
1037
  if (lost) this.log(lost);
975
1038
  onEvent({
976
1039
  kind: "settled",
977
1040
  ...outcome.result ? { result: outcome.result } : {},
978
- ...outcome.last_assistant_text ? { summary: outcome.last_assistant_text } : {},
1041
+ ...outcome.last_assistant_text ? { summary: `${opening}${outcome.last_assistant_text}`.slice(0, RUN_TEXT_MAX) } : {},
979
1042
  ...pr
980
1043
  });
981
1044
  }
@@ -1062,6 +1125,65 @@ ${RESULT_INSTRUCTION}`, attachments: [] }
1062
1125
  live?.close();
1063
1126
  };
1064
1127
  }
1128
+ /**
1129
+ * Once per thread: a run that failed at a Claude usage limit carries on in
1130
+ * the same thread on Codex. T3 switches the thread's provider and hands
1131
+ * Codex the thread so far; the worktree, with any edits, stays. A limit
1132
+ * that names no model holds the account, so launches start on Codex for
1133
+ * LIMIT_HOLD_MS. A thread whose Task named its harness or model stays, and
1134
+ * so does one without full access, because Codex asks nothing. So does a
1135
+ * thread this daemon did not launch: a restart forgets what the Task named.
1136
+ */
1137
+ async moveToCodex(threadId, turn, outcome) {
1138
+ const said = outcome.last_assistant_text ?? "";
1139
+ if (outcome.status !== "failed" || !HARNESS_LIMIT.test(said)) return false;
1140
+ const from = turn.providerInstanceId;
1141
+ if (from === CODEX_PROVIDER) return false;
1142
+ if (!limitedModel(said)) this.limitedUntil = this.now() + LIMIT_HOLD_MS;
1143
+ const entry = this.launched.get(threadId);
1144
+ if (!entry || entry.named || entry.permission !== "full" || entry.movedFrom !== void 0)
1145
+ return false;
1146
+ try {
1147
+ return await this.dispatchToCodex(threadId, turn, entry);
1148
+ } catch (err) {
1149
+ this.log(
1150
+ `fallback failed thread=${threadId}: ${err instanceof Error ? err.message : String(err)}`
1151
+ );
1152
+ return false;
1153
+ }
1154
+ }
1155
+ async dispatchToCodex(threadId, turn, entry) {
1156
+ const codex = codexProvider(await this.t3.rpc("server.getConfig", {}));
1157
+ if (!codex) {
1158
+ this.log(`limit thread=${threadId}: Codex is not on or not signed in; the run fails`);
1159
+ return false;
1160
+ }
1161
+ const name = providerName(turn.providerInstanceId);
1162
+ const id = randomUUID();
1163
+ await this.dispatch({
1164
+ type: "message.dispatch",
1165
+ commandId: id,
1166
+ threadId,
1167
+ messageId: id,
1168
+ text: handoverPrompt("Carry on with the task in this thread.", name).concat(
1169
+ `
1170
+
1171
+ ${RESULT_INSTRUCTION}`
1172
+ ),
1173
+ attachments: [],
1174
+ modelSelection: codex,
1175
+ dispatchMode: { type: "start_immediately" },
1176
+ createdBy: "user",
1177
+ creationSource: "mcp"
1178
+ });
1179
+ entry.movedFrom = turn.id;
1180
+ entry.switched = `${name} was at its usage limit, so Codex did this run.`;
1181
+ this.log(`fallback thread=${threadId} provider=${codex.instanceId} model=${codex.model}`);
1182
+ return true;
1183
+ }
1184
+ now() {
1185
+ return this.deps.now?.() ?? Date.now();
1186
+ }
1065
1187
  readProjection(threadId) {
1066
1188
  return this.t3.rpc("orchestration.getThreadProjection", { threadId });
1067
1189
  }
@@ -1135,13 +1257,80 @@ ${RESULT_INSTRUCTION}`, attachments: [] }
1135
1257
  }
1136
1258
  };
1137
1259
 
1260
+ // src/runner-config.ts
1261
+ import { chmodSync as chmodSync2, mkdirSync as mkdirSync2, readFileSync, renameSync as renameSync2, writeFileSync } from "fs";
1262
+ import { homedir } from "os";
1263
+ import { dirname as dirname2, join as join3 } from "path";
1264
+ var BOX_FILE = "box.json";
1265
+ function boxPath() {
1266
+ return process.env.CLOOP_BOX_FILE ?? join3(homedir(), CONFIG_DIR, BOX_FILE);
1267
+ }
1268
+ function isLocal(cfg) {
1269
+ return cfg.driver === "claude-code" || cfg.driver === "codex";
1270
+ }
1271
+ function showsOtherThreads(cfg) {
1272
+ return cfg?.hideOtherThreads !== true;
1273
+ }
1274
+ function otherThreadsChoice(argv, previous) {
1275
+ if (argv.includes("--hide-other-threads")) return true;
1276
+ if (argv.includes("--show-other-threads")) return false;
1277
+ return previous?.hideOtherThreads === true;
1278
+ }
1279
+ function readRunnerConfig() {
1280
+ let parsed;
1281
+ try {
1282
+ parsed = JSON.parse(readFileSync(boxPath(), "utf-8"));
1283
+ } catch {
1284
+ return null;
1285
+ }
1286
+ if (parsed.driver === "claude-code" || parsed.driver === "codex") {
1287
+ const ok = typeof parsed.deviceToken === "string" && typeof parsed.environmentId === "string" && typeof parsed.bin === "string" && Array.isArray(parsed.repos);
1288
+ return ok ? parsed : null;
1289
+ }
1290
+ if (typeof parsed.t3Url !== "string" || typeof parsed.token !== "string") return null;
1291
+ return parsed;
1292
+ }
1293
+ function writeBoxConfig(cfg) {
1294
+ const path = boxPath();
1295
+ mkdirSync2(dirname2(path), { recursive: true, mode: 448 });
1296
+ const temp = `${path}.${process.pid}.tmp`;
1297
+ writeFileSync(temp, `${JSON.stringify(cfg, null, 2)}
1298
+ `, { mode: 384 });
1299
+ chmodSync2(temp, 384);
1300
+ renameSync2(temp, path);
1301
+ }
1302
+
1138
1303
  // src/drivers/local.ts
1139
1304
  import { execFile as execFile2, execFileSync as execFileSync3, spawn } from "child_process";
1140
- import { chmodSync as chmodSync2, mkdirSync as mkdirSync2, readFileSync, renameSync as renameSync2, writeFileSync } from "fs";
1141
- import { homedir, hostname } from "os";
1142
- import { basename, dirname as dirname2, join as join3 } from "path";
1305
+ import { chmodSync as chmodSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync2, renameSync as renameSync3, writeFileSync as writeFileSync2 } from "fs";
1306
+ import { homedir as homedir2, hostname } from "os";
1307
+ import { basename, dirname as dirname3, join as join4 } from "path";
1143
1308
  import { createInterface } from "readline";
1144
1309
 
1310
+ // src/spawn-command.ts
1311
+ function commandFor(bin, args, platform = process.platform, comspec = process.env.ComSpec) {
1312
+ if (platform !== "win32" || !/\.(cmd|bat)$/i.test(bin)) return { file: bin, args };
1313
+ return {
1314
+ file: comspec ?? "cmd.exe",
1315
+ args: ["/d", "/s", "/c", `"${[bin, ...args].map(quoteWindowsArg).join(" ")}"`],
1316
+ windowsVerbatimArguments: true
1317
+ };
1318
+ }
1319
+ function quoteWindowsArg(arg) {
1320
+ if (arg && !/[ \t"]/.test(arg)) return arg;
1321
+ let quoted = '"';
1322
+ let backslashes = 0;
1323
+ for (const ch of arg) {
1324
+ if (ch === "\\") {
1325
+ backslashes++;
1326
+ continue;
1327
+ }
1328
+ quoted += "\\".repeat(ch === '"' ? backslashes * 2 + 1 : backslashes) + ch;
1329
+ backslashes = 0;
1330
+ }
1331
+ return `${quoted}${"\\".repeat(backslashes * 2)}"`;
1332
+ }
1333
+
1145
1334
  // src/drivers/harness-check.ts
1146
1335
  var HARNESS_STALE_MS = 5 * 6e4;
1147
1336
  var FIRST_CHECK_WAIT_MS = 3e3;
@@ -1194,7 +1383,6 @@ var SHARED_BRANCHES = /* @__PURE__ */ new Set(["staging", "main", "master", "HEA
1194
1383
  var COMMANDS_KEPT = 50;
1195
1384
  var SUMMARY_MAX2 = 200;
1196
1385
  var HARNESS_NAMES = { "claude-code": "Claude Code", codex: "Codex" };
1197
- var HARNESS_LIMIT = /usage limit|reached your [\w .-]{0,40}limit|hit your [\w .-]{0,40}limit|out of (usage )?credits/i;
1198
1386
  function failedEnd(harness, run2) {
1199
1387
  const said = run2.result?.text?.trim() || run2.lastText;
1200
1388
  const limited = HARNESS_LIMIT.test(run2.result?.text ?? "");
@@ -1212,7 +1400,7 @@ function failedEnd(harness, run2) {
1212
1400
  return { summary: `${lead}${quoted}"`, ...error };
1213
1401
  }
1214
1402
  function localRunsFilePath() {
1215
- return process.env.CLOOP_LOCAL_RUNS_FILE ?? join3(homedir(), CONFIG_DIR, "local-runs.json");
1403
+ return process.env.CLOOP_LOCAL_RUNS_FILE ?? join4(homedir2(), CONFIG_DIR, "local-runs.json");
1216
1404
  }
1217
1405
  function pickRepo(repos, repository) {
1218
1406
  if (!repository) {
@@ -1252,6 +1440,17 @@ var gitProbe = {
1252
1440
  }
1253
1441
  }
1254
1442
  };
1443
+ function processCommandLine(pid, platform = process.platform) {
1444
+ if (platform === "win32")
1445
+ return [
1446
+ "powershell",
1447
+ "-NoProfile",
1448
+ "-NonInteractive",
1449
+ "-Command",
1450
+ `(Get-CimInstance Win32_Process -Filter 'ProcessId = ${pid}').CommandLine`
1451
+ ];
1452
+ return ["ps", "-ww", "-o", "command=", "-p", String(pid)];
1453
+ }
1255
1454
  function harnessAlive(pid, r, dialect) {
1256
1455
  try {
1257
1456
  process.kill(pid, 0);
@@ -1259,7 +1458,8 @@ function harnessAlive(pid, r, dialect) {
1259
1458
  if (err.code !== "EPERM") return false;
1260
1459
  }
1261
1460
  try {
1262
- const command = execFileSync3("ps", ["-ww", "-o", "command=", "-p", String(pid)], {
1461
+ const [file, ...args] = processCommandLine(pid);
1462
+ const command = execFileSync3(file, args, {
1263
1463
  encoding: "utf-8",
1264
1464
  timeout: 2e3
1265
1465
  });
@@ -1299,6 +1499,8 @@ var LocalDriver = class {
1299
1499
  logDir;
1300
1500
  logFailed = false;
1301
1501
  harnessCheck;
1502
+ /** Until then, the runner's own harness is at an account-wide limit and new runs start on the fallback. */
1503
+ limitedUntil = 0;
1302
1504
  get repo() {
1303
1505
  return this.deps.repo ?? gitProbe;
1304
1506
  }
@@ -1375,7 +1577,7 @@ var LocalDriver = class {
1375
1577
  settled: Boolean(r.end),
1376
1578
  pr_url: r.end?.pr_url ?? null,
1377
1579
  last_assistant_text: r.end?.summary ?? r.last_text ?? null,
1378
- resume: this.deps.dialect.name === "claude-code" && r.session_id ? { cwd: r.repo, session_id: r.session_id } : null
1580
+ resume: this.dialectOf(r).name === "claude-code" && r.session_id ? { cwd: r.repo, session_id: r.session_id } : null
1379
1581
  };
1380
1582
  }
1381
1583
  async launch(a) {
@@ -1387,11 +1589,13 @@ var LocalDriver = class {
1387
1589
  permission: existing.used_permission,
1388
1590
  takeover: true
1389
1591
  };
1390
- const { dialect } = this.deps;
1391
- if (a.harness && !dialect.aliases.includes(a.harness))
1592
+ const own = this.deps.dialect;
1593
+ if (a.harness && !own.aliases.includes(a.harness))
1392
1594
  throw new BoxToolError("harness_unavailable");
1393
1595
  const repo = pickRepo(this.deps.repos, a.repository);
1394
1596
  this.refuseBusy(repo.path);
1597
+ const moved = a.harness ? null : await this.heldOver(a);
1598
+ const dialect = moved ?? own;
1395
1599
  const harness = await dialect.probe();
1396
1600
  if (!harness) throw new BoxToolError("harness_unavailable");
1397
1601
  if (!harness.signedIn) throw new BoxToolError("harness_signed_out");
@@ -1410,8 +1614,14 @@ var LocalDriver = class {
1410
1614
  session_id: dialect.name === "claude-code" ? a.work_id : null,
1411
1615
  repo: repo.path,
1412
1616
  title: a.title,
1413
- ...a.model ? { model: a.model } : {},
1617
+ prompt: a.prompt,
1618
+ ...a.model && !moved ? { model: a.model } : {},
1414
1619
  ...a.runtime_mode ? { runtime_mode: a.runtime_mode } : {},
1620
+ ...a.harness ? { harness_named: true } : {},
1621
+ ...moved ? {
1622
+ harness: moved.name,
1623
+ switched: `${HARNESS_NAMES[own.name]} is at its usage limit, so ${HARNESS_NAMES[moved.name]} did this run.`
1624
+ } : {},
1415
1625
  pid: null,
1416
1626
  started_at: new Date(this.now()).toISOString(),
1417
1627
  head_at_launch: head
@@ -1447,7 +1657,7 @@ var LocalDriver = class {
1447
1657
  questions: live.asks.length
1448
1658
  };
1449
1659
  }
1450
- const line2 = this.deps.dialect.answerLine?.(ask, a.text);
1660
+ const line2 = this.dialectOf(r).answerLine?.(ask, a.text);
1451
1661
  if (!line2) throw new BoxToolError("cannot_steer");
1452
1662
  live.asks = live.asks.slice(1);
1453
1663
  this.write(live, line2);
@@ -1475,7 +1685,7 @@ ${a.text}` : a.text;
1475
1685
  this.remember(r, a.command_id, "queue");
1476
1686
  return { delivered: "queue" };
1477
1687
  }
1478
- const line = this.deps.dialect.userLine?.(r, a.text, a.mode);
1688
+ const line = this.dialectOf(r).userLine?.(r, a.text, a.mode);
1479
1689
  if (!line) throw new BoxToolError("cannot_steer");
1480
1690
  live.outstanding++;
1481
1691
  this.write(live, line);
@@ -1550,7 +1760,25 @@ ${a.text}` : a.text;
1550
1760
  for (const live of this.lives.values()) live.child.kill("SIGTERM");
1551
1761
  }
1552
1762
  alive(pid, r) {
1553
- return this.deps.alive ? this.deps.alive(pid, r) : harnessAlive(pid, r, this.deps.dialect);
1763
+ return this.deps.alive ? this.deps.alive(pid, r) : harnessAlive(pid, r, this.dialectOf(r));
1764
+ }
1765
+ /** The harness a run is on: the fallback once it took the run over. */
1766
+ dialectOf(r) {
1767
+ const fallback = this.deps.fallbackHarness;
1768
+ return fallback && r.harness === fallback.name ? fallback : this.deps.dialect;
1769
+ }
1770
+ /**
1771
+ * The fallback harness, while the runner's own one is at an account-wide
1772
+ * limit and the fallback is signed in. Codex asks nothing, so it takes only
1773
+ * runs that would have had full access anyway.
1774
+ */
1775
+ async heldOver(a) {
1776
+ const fallback = this.deps.fallbackHarness;
1777
+ if (!fallback || this.now() >= this.limitedUntil) return null;
1778
+ const mode = a.runtime_mode ? { runtime_mode: a.runtime_mode } : {};
1779
+ if (this.deps.dialect.permission?.(mode) !== "full") return null;
1780
+ const probe = await fallback.probe().catch(() => null);
1781
+ return probe?.signedIn ? fallback : null;
1554
1782
  }
1555
1783
  /** One checkout, one run: two harnesses editing the same files at once would undo each other. */
1556
1784
  refuseBusy(repo) {
@@ -1580,12 +1808,14 @@ ${a.text}` : a.text;
1580
1808
  }
1581
1809
  }
1582
1810
  spawnRun(r, prompt, resume) {
1583
- const { dialect } = this.deps;
1811
+ const dialect = this.dialectOf(r);
1584
1812
  r.used_permission = dialect.permission?.(r);
1585
- const child = spawn(dialect.bin, dialect.args(r, resume), {
1813
+ const command = commandFor(dialect.bin, dialect.args(r, resume));
1814
+ const child = spawn(command.file, command.args, {
1586
1815
  cwd: r.repo,
1587
1816
  stdio: ["pipe", "pipe", "pipe"],
1588
- env: process.env
1817
+ env: process.env,
1818
+ ...command.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
1589
1819
  });
1590
1820
  const live = {
1591
1821
  child,
@@ -1694,31 +1924,35 @@ ${RESULT_INSTRUCTION}`));
1694
1924
  }
1695
1925
  if (live.stderr)
1696
1926
  this.log(`stderr work=${r.work_id}: ${live.stderr.trim().split("\n").at(-1)?.slice(0, 200)}`);
1697
- const end = failedEnd(this.name, {
1927
+ const end = failedEnd(this.dialectOf(r).name, {
1698
1928
  result: live.result,
1699
1929
  lastText: r.last_text,
1700
1930
  exit,
1701
1931
  ...r.switched ? { switched: r.switched } : {}
1702
1932
  });
1703
1933
  if (end.error) this.log(`limit work=${r.work_id} error=${end.error}`);
1704
- if (end.error === "harness_limit" && this.fallBack(r, live.result?.text)) return;
1934
+ if (end.error === "harness_limit") {
1935
+ if (this.fallBack(r, live.result?.text)) return;
1936
+ if (await this.moveHarness(r, live.result?.text)) return;
1937
+ }
1705
1938
  await this.end(r, { kind: "failed", ...end });
1706
1939
  }
1707
1940
  /**
1708
1941
  * Once per run: a run stopped by its model's usage limit resumes its own
1709
1942
  * session on the first fallback model, with the continue prompt, so its
1710
1943
  * steers, answers and edits carry over. It does not when the Task named its
1711
- * model, when the limit is the fallback model's own, or after one switch.
1712
- * `--fallback-model` may already cover this; it is not documented whether a
1713
- * plan's limit counts. The switch opens the end summary, because a progress
1714
- * line is dropped while the socket is down.
1944
+ * model, when the limit is the fallback model's own or names no model, or
1945
+ * after one switch. `--fallback-model` may already cover this; it is not
1946
+ * documented whether a plan's limit counts. The switch opens the end
1947
+ * summary, because a progress line is dropped while the socket is down.
1715
1948
  */
1716
1949
  fallBack(r, said) {
1717
- const model = this.deps.dialect.fallback?.split(",")[0]?.trim();
1950
+ const model = this.dialectOf(r).fallback?.split(",")[0]?.trim();
1718
1951
  if (!model || !r.session_id || r.switched || r.model) return false;
1719
1952
  const named = new RegExp(`\\b${model.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`, "i");
1720
1953
  if (named.test(said ?? "")) return false;
1721
- const from = /reached your ([\w .-]{1,40}?) limit/i.exec(said ?? "")?.[1] ?? "The default model";
1954
+ const from = limitedModel(said);
1955
+ if (!from) return false;
1722
1956
  const to = `${model.charAt(0).toUpperCase()}${model.slice(1)}`;
1723
1957
  r.switched = `${from} was at its usage limit, so this ran on ${to}.`;
1724
1958
  r.model = model;
@@ -1731,6 +1965,42 @@ ${RESULT_INSTRUCTION}`));
1731
1965
  this.spawnRun(r, CONTINUE_PROMPT, true);
1732
1966
  return true;
1733
1967
  }
1968
+ /**
1969
+ * Once per run: a run its own harness cannot carry on starts again on the
1970
+ * fallback harness, in the same checkout, so the edits so far carry over.
1971
+ * The session does not: the prompt goes again, with a note to read the
1972
+ * checkout first. A limit that names no model holds the account, so new
1973
+ * runs start on the fallback for LIMIT_HOLD_MS. It does not move a run
1974
+ * whose Task named its harness, nor one without full access, because
1975
+ * Codex asks nothing.
1976
+ */
1977
+ async moveHarness(r, said) {
1978
+ const to = this.deps.fallbackHarness;
1979
+ if (!to || r.harness) return false;
1980
+ if (!limitedModel(said)) this.limitedUntil = this.now() + LIMIT_HOLD_MS;
1981
+ if (r.harness_named || r.used_permission !== "full" || !r.prompt) return false;
1982
+ this.recovering.add(r.work_id);
1983
+ try {
1984
+ const probe = await to.probe().catch(() => null);
1985
+ if (!probe?.signedIn || this.stopping || r.end) return false;
1986
+ } finally {
1987
+ this.recovering.delete(r.work_id);
1988
+ }
1989
+ const from = HARNESS_NAMES[this.deps.dialect.name] ?? this.deps.dialect.name;
1990
+ const name = HARNESS_NAMES[to.name] ?? to.name;
1991
+ r.harness = to.name;
1992
+ r.session_id = null;
1993
+ r.model = void 0;
1994
+ r.switched = `${from} was at its usage limit, so ${name} did this run.`;
1995
+ this.save();
1996
+ this.log(`fallback work=${r.work_id} harness=${to.name}`);
1997
+ this.emit(r.work_id, {
1998
+ kind: "progress",
1999
+ summary: `${from} is at its usage limit, so I moved this to ${name}`
2000
+ });
2001
+ this.spawnRun(r, handoverPrompt(r.prompt, from), false);
2002
+ return true;
2003
+ }
1734
2004
  /**
1735
2005
  * The PR a run produced: one its last text names, else the PR of the
1736
2006
  * branch, but only when the run moved HEAD. A run that left HEAD where it
@@ -1783,17 +2053,17 @@ ${RESULT_INSTRUCTION}`));
1783
2053
  return readRunRecords(this.file).filter((r) => !(r.end && Date.parse(r.end.at) < cutoff));
1784
2054
  }
1785
2055
  save() {
1786
- mkdirSync2(dirname2(this.file), { recursive: true, mode: 448 });
2056
+ mkdirSync3(dirname3(this.file), { recursive: true, mode: 448 });
1787
2057
  const tmp = `${this.file}.tmp`;
1788
- writeFileSync(tmp, `${JSON.stringify([...this.runs.values()], null, 2)}
2058
+ writeFileSync2(tmp, `${JSON.stringify([...this.runs.values()], null, 2)}
1789
2059
  `, { mode: 384 });
1790
- chmodSync2(tmp, 384);
1791
- renameSync2(tmp, this.file);
2060
+ chmodSync3(tmp, 384);
2061
+ renameSync3(tmp, this.file);
1792
2062
  }
1793
2063
  };
1794
2064
  function readRunRecords(file = localRunsFilePath()) {
1795
2065
  try {
1796
- const raw = JSON.parse(readFileSync(file, "utf-8"));
2066
+ const raw = JSON.parse(readFileSync2(file, "utf-8"));
1797
2067
  return Array.isArray(raw) ? raw.filter(
1798
2068
  (r) => typeof r?.work_id === "string" && typeof r?.repo === "string"
1799
2069
  ) : [];
@@ -1802,49 +2072,6 @@ function readRunRecords(file = localRunsFilePath()) {
1802
2072
  }
1803
2073
  }
1804
2074
 
1805
- // src/runner-config.ts
1806
- import { chmodSync as chmodSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync2, renameSync as renameSync3, writeFileSync as writeFileSync2 } from "fs";
1807
- import { homedir as homedir2 } from "os";
1808
- import { dirname as dirname3, join as join4 } from "path";
1809
- var BOX_FILE = "box.json";
1810
- function boxPath() {
1811
- return process.env.CLOOP_BOX_FILE ?? join4(homedir2(), CONFIG_DIR, BOX_FILE);
1812
- }
1813
- function isLocal(cfg) {
1814
- return cfg.driver === "claude-code" || cfg.driver === "codex";
1815
- }
1816
- function showsOtherThreads(cfg) {
1817
- return cfg?.hideOtherThreads !== true;
1818
- }
1819
- function otherThreadsChoice(argv, previous) {
1820
- if (argv.includes("--hide-other-threads")) return true;
1821
- if (argv.includes("--show-other-threads")) return false;
1822
- return previous?.hideOtherThreads === true;
1823
- }
1824
- function readRunnerConfig() {
1825
- let parsed;
1826
- try {
1827
- parsed = JSON.parse(readFileSync2(boxPath(), "utf-8"));
1828
- } catch {
1829
- return null;
1830
- }
1831
- if (parsed.driver === "claude-code" || parsed.driver === "codex") {
1832
- const ok = typeof parsed.deviceToken === "string" && typeof parsed.environmentId === "string" && typeof parsed.bin === "string" && Array.isArray(parsed.repos);
1833
- return ok ? parsed : null;
1834
- }
1835
- if (typeof parsed.t3Url !== "string" || typeof parsed.token !== "string") return null;
1836
- return parsed;
1837
- }
1838
- function writeBoxConfig(cfg) {
1839
- const path = boxPath();
1840
- mkdirSync3(dirname3(path), { recursive: true, mode: 448 });
1841
- const temp = `${path}.${process.pid}.tmp`;
1842
- writeFileSync2(temp, `${JSON.stringify(cfg, null, 2)}
1843
- `, { mode: 384 });
1844
- chmodSync3(temp, 384);
1845
- renameSync3(temp, path);
1846
- }
1847
-
1848
2075
  export {
1849
2076
  RUNTIME_MODES,
1850
2077
  BoxToolError,
@@ -1852,6 +2079,7 @@ export {
1852
2079
  questionLine,
1853
2080
  RUN_TEXT_MAX,
1854
2081
  isYes,
2082
+ commandFor,
1855
2083
  runLogDir,
1856
2084
  runLogPath,
1857
2085
  STOPPED_SUMMARY,
@@ -1862,14 +2090,14 @@ export {
1862
2090
  t3BaseDirArgs,
1863
2091
  runT3,
1864
2092
  T3Driver,
1865
- takeoverSummary,
1866
- localRunsFilePath,
1867
- LocalDriver,
1868
- readRunRecords,
1869
2093
  boxPath,
1870
2094
  isLocal,
1871
2095
  showsOtherThreads,
1872
2096
  otherThreadsChoice,
1873
2097
  readRunnerConfig,
1874
- writeBoxConfig
2098
+ writeBoxConfig,
2099
+ takeoverSummary,
2100
+ localRunsFilePath,
2101
+ LocalDriver,
2102
+ readRunRecords
1875
2103
  };
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/version.ts
4
- var VERSION = true ? "0.3.1" : "0.0.0-dev";
4
+ var VERSION = true ? "0.3.7" : "0.0.0-dev";
5
5
 
6
6
  export {
7
7
  VERSION