@cloop/runner 0.3.39 → 0.3.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  serveTakeovers
4
- } from "./chunk-TFOUFEU3.js";
5
- import "./chunk-EJXCUHHV.js";
4
+ } from "./chunk-TSUDGSA2.js";
5
+ import "./chunk-3N4X2TK2.js";
6
6
  import {
7
7
  CAPTURE_TICK_MS,
8
8
  DEFAULT_FALLBACK_MODEL,
@@ -38,7 +38,7 @@ import {
38
38
  systemServices,
39
39
  unitFor,
40
40
  which
41
- } from "./chunk-6R6XDZKO.js";
41
+ } from "./chunk-JW5GATBV.js";
42
42
  import {
43
43
  MeshSocket,
44
44
  WAKE_TICK_MS,
@@ -46,16 +46,17 @@ import {
46
46
  defaultSocketFactory,
47
47
  runnerLog,
48
48
  wakeWatch
49
- } from "./chunk-KDTPUD2Y.js";
49
+ } from "./chunk-CVVYCLZ6.js";
50
50
  import {
51
51
  BoxWatch,
52
52
  hostedThreadsFilePath,
53
53
  lockThreadsFile,
54
54
  readRunnerState,
55
+ runOutputs,
55
56
  runnerStatePath,
56
57
  threadsFilePath,
57
58
  writeRunnerState
58
- } from "./chunk-A27N773G.js";
59
+ } from "./chunk-PN5CQQVG.js";
59
60
  import {
60
61
  BackgroundReading,
61
62
  BoxToolError,
@@ -100,20 +101,20 @@ import {
100
101
  utcWindow,
101
102
  windowsPowerShellEnv,
102
103
  writeBoxConfig
103
- } from "./chunk-FWAHPPAG.js";
104
+ } from "./chunk-NP5VVHLS.js";
104
105
  import "./chunk-VK6GV757.js";
105
106
  import {
106
107
  olderThan
107
108
  } from "./chunk-365HFCQQ.js";
108
109
  import "./chunk-PKIEWBR7.js";
109
- import "./chunk-DCX2BZPA.js";
110
- import "./chunk-H3NH6NQT.js";
110
+ import "./chunk-OXFFDL26.js";
111
+ import "./chunk-QOYGTYFE.js";
111
112
  import {
112
113
  getMachine
113
114
  } from "./chunk-SBYSVZ7J.js";
114
115
  import {
115
116
  VERSION
116
- } from "./chunk-6TW44BUM.js";
117
+ } from "./chunk-7B53CL3W.js";
117
118
  import {
118
119
  getMeshUrl,
119
120
  getOrigin,
@@ -122,6 +123,10 @@ import {
122
123
  readCredentials
123
124
  } from "./chunk-D5UZW42X.js";
124
125
 
126
+ // src/commands/box.ts
127
+ import { homedir as homedir3 } from "os";
128
+ import { join as join6 } from "path";
129
+
125
130
  // src/cloudroom-core.ts
126
131
  var CoreError = class extends Error {
127
132
  constructor(status, code, message) {
@@ -1007,9 +1012,11 @@ var CloudroomDriver = class {
1007
1012
  * working in the folder, keeps it. A
1008
1013
  * failure here is logged and the end is reported as it was.
1009
1014
  */
1010
- async tidy(id, end) {
1015
+ async tidy(id, ended) {
1016
+ let end = ended;
1011
1017
  try {
1012
1018
  const s = await this.core.session(id);
1019
+ if (s?.workspace_path && end.kind === "settled") end = { ...end, cwd: s.workspace_path };
1013
1020
  const tree = worktreeOf(s?.workspace ?? null);
1014
1021
  if (!s || !tree) return end;
1015
1022
  const path = folder(s);
@@ -2573,11 +2580,21 @@ async function run2() {
2573
2580
  return e && { thread_id: e.thread_id, settled: Boolean(e.settled_at) };
2574
2581
  }
2575
2582
  });
2583
+ const outputs = runOutputs({
2584
+ origin: cfg.origin ?? getOrigin(),
2585
+ deviceToken: () => token,
2586
+ log: log2,
2587
+ dir: runnerDir(),
2588
+ awakeDir: hosted ? join6(homedir3(), ".cloop", "awake") : null
2589
+ });
2590
+ const previews = outputs.connector;
2591
+ void previews.resume();
2576
2592
  const watch = new BoxWatch({
2577
2593
  file: threadsFile,
2578
2594
  watch: (id, onEvent) => driver.watch(id, onEvent),
2579
2595
  send: (frame) => socket.send({ ...frame }),
2580
- log: log2
2596
+ log: log2,
2597
+ attach: outputs.attach
2581
2598
  });
2582
2599
  const setup = hosted ? void 0 : new SetupShare({
2583
2600
  origin: cfg.origin ?? getOrigin(),
@@ -2820,6 +2837,7 @@ async function run2() {
2820
2837
  const stop = (code = 0) => {
2821
2838
  log2("stopping");
2822
2839
  watch.stop();
2840
+ previews.stop();
2823
2841
  unfollow?.();
2824
2842
  if (driver instanceof LocalDriver) driver.stop();
2825
2843
  lock.release();
@@ -9,7 +9,7 @@ import {
9
9
  runHarness,
10
10
  runLogDir,
11
11
  runLogPath
12
- } from "./chunk-FWAHPPAG.js";
12
+ } from "./chunk-NP5VVHLS.js";
13
13
  import {
14
14
  sanitizeLabel,
15
15
  stripControl
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/version.ts
4
- var VERSION = true ? "0.3.39" : "0.0.0-dev";
4
+ var VERSION = true ? "0.3.42" : "0.0.0-dev";
5
5
 
6
6
  export {
7
7
  VERSION
@@ -8,6 +8,7 @@ var RUNNER_TOOLS = [
8
8
  "thread.launch",
9
9
  "thread.send",
10
10
  "thread.interrupt",
11
+ "thread.settle",
11
12
  "setup.share",
12
13
  "diag"
13
14
  ];
@@ -4,12 +4,12 @@ import {
4
4
  freshness,
5
5
  outcomeLine,
6
6
  runnerLog
7
- } from "./chunk-KDTPUD2Y.js";
7
+ } from "./chunk-CVVYCLZ6.js";
8
8
  import {
9
9
  readRunnerState,
10
10
  runnerStatePath,
11
11
  threadsFilePath
12
- } from "./chunk-A27N773G.js";
12
+ } from "./chunk-PN5CQQVG.js";
13
13
  import {
14
14
  BoxToolError,
15
15
  CLOOP_THREAD_PREFIX,
@@ -48,7 +48,7 @@ import {
48
48
  windowsExecutable,
49
49
  windowsPowerShellEnv,
50
50
  writeBoxConfig
51
- } from "./chunk-FWAHPPAG.js";
51
+ } from "./chunk-NP5VVHLS.js";
52
52
  import {
53
53
  CLAUDE_FLOOR,
54
54
  CODEX_FLOOR,
@@ -62,14 +62,14 @@ import {
62
62
  } from "./chunk-PKIEWBR7.js";
63
63
  import {
64
64
  connectWebhook
65
- } from "./chunk-DCX2BZPA.js";
65
+ } from "./chunk-OXFFDL26.js";
66
66
  import {
67
67
  ConnectFailure,
68
68
  connectReport,
69
69
  deviceLogin,
70
70
  newAttempt,
71
71
  sendConnectReport
72
- } from "./chunk-H3NH6NQT.js";
72
+ } from "./chunk-QOYGTYFE.js";
73
73
  import {
74
74
  defaultDeviceName,
75
75
  getMachine,
@@ -77,7 +77,7 @@ import {
77
77
  } from "./chunk-SBYSVZ7J.js";
78
78
  import {
79
79
  VERSION
80
- } from "./chunk-6TW44BUM.js";
80
+ } from "./chunk-7B53CL3W.js";
81
81
  import {
82
82
  STAGING_ORIGIN,
83
83
  getOrigin,
@@ -344,6 +344,8 @@ var BOX_TOOLS = {
344
344
  return result;
345
345
  },
346
346
  "thread.interrupt": ({ driver }, args) => driver.interrupt(parseThreadId(args), parseCommandId(args)),
347
+ // The app calls it once a run is Done with nothing to review. A driver with no thread list says so.
348
+ "thread.settle": async ({ driver }, args) => driver.settle ? driver.settle(parseThreadId(args), parseCommandId(args)) : { settled: false, refused: "unsupported" },
347
349
  // Codes, ids, versions and counts only (runner-log.ts), so ops can read it without the owner.
348
350
  diag: async ({ diag }) => diag ? diag() : null,
349
351
  // Packs the skills before it answers, so an empty or oversized set is refused now; the upload runs on.
@@ -63,6 +63,61 @@ function serviceIdentity(kind, env) {
63
63
  };
64
64
  }
65
65
 
66
+ // src/spawn-command.ts
67
+ import { execFileSync } from "child_process";
68
+ function commandFor(bin, args, platform = process.platform, comspec = process.env.ComSpec) {
69
+ if (platform !== "win32") return { file: bin, args };
70
+ const executable = windowsExecutable(bin) ?? bin;
71
+ if (!/\.(cmd|bat)$/i.test(executable)) return { file: executable, args };
72
+ return {
73
+ file: comspec ?? "cmd.exe",
74
+ args: ["/d", "/s", "/c", `"${[executable, ...args].map(quoteWindowsArg).join(" ")}"`],
75
+ windowsVerbatimArguments: true
76
+ };
77
+ }
78
+ function quoteWindowsArg(arg) {
79
+ if (arg && !/[ \t"]/.test(arg)) return arg;
80
+ let quoted = '"';
81
+ let backslashes = 0;
82
+ for (const ch of arg) {
83
+ if (ch === "\\") {
84
+ backslashes++;
85
+ continue;
86
+ }
87
+ quoted += "\\".repeat(ch === '"' ? backslashes * 2 + 1 : backslashes) + ch;
88
+ backslashes = 0;
89
+ }
90
+ return `${quoted}${"\\".repeat(backslashes * 2)}"`;
91
+ }
92
+ function preferExecutable(lines) {
93
+ return lines.find((line) => /\.exe$/i.test(line)) ?? lines.find((line) => /\.(cmd|bat)$/i.test(line)) ?? null;
94
+ }
95
+ var windowsExecutables = /* @__PURE__ */ new Map();
96
+ function windowsExecutable(bin) {
97
+ if (/[\\/]/.test(bin)) return bin;
98
+ if (process.platform !== "win32") return null;
99
+ const key = JSON.stringify([bin, process.env.PATH, process.env.PATHEXT]);
100
+ if (windowsExecutables.has(key)) return windowsExecutables.get(key) ?? null;
101
+ let resolved = null;
102
+ try {
103
+ resolved = preferExecutable(
104
+ execFileSync("where.exe", [bin], { encoding: "utf-8", timeout: 5e3 }).split(/\r?\n/).map((line) => line.trim()).filter(Boolean)
105
+ );
106
+ } catch {
107
+ }
108
+ windowsExecutables.set(key, resolved);
109
+ if (!resolved)
110
+ console.error(
111
+ `[runner:spawn] Could not resolve ${bin} to an executable on PATH. Install the agent and reconnect the runner.`
112
+ );
113
+ return resolved;
114
+ }
115
+ function windowsPowerShellEnv(env = process.env) {
116
+ return Object.fromEntries(
117
+ Object.entries(env).filter(([key]) => key.toLowerCase() !== "psmodulepath")
118
+ );
119
+ }
120
+
66
121
  // src/runner-config.ts
67
122
  import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "fs";
68
123
  import { dirname, join as join2 } from "path";
@@ -432,61 +487,6 @@ function stamp(now) {
432
487
  return [d.getHours(), d.getMinutes(), d.getSeconds()].map((n) => String(n).padStart(2, "0")).join(":");
433
488
  }
434
489
 
435
- // src/spawn-command.ts
436
- import { execFileSync } from "child_process";
437
- function commandFor(bin, args, platform = process.platform, comspec = process.env.ComSpec) {
438
- if (platform !== "win32") return { file: bin, args };
439
- const executable = windowsExecutable(bin) ?? bin;
440
- if (!/\.(cmd|bat)$/i.test(executable)) return { file: executable, args };
441
- return {
442
- file: comspec ?? "cmd.exe",
443
- args: ["/d", "/s", "/c", `"${[executable, ...args].map(quoteWindowsArg).join(" ")}"`],
444
- windowsVerbatimArguments: true
445
- };
446
- }
447
- function quoteWindowsArg(arg) {
448
- if (arg && !/[ \t"]/.test(arg)) return arg;
449
- let quoted = '"';
450
- let backslashes = 0;
451
- for (const ch of arg) {
452
- if (ch === "\\") {
453
- backslashes++;
454
- continue;
455
- }
456
- quoted += "\\".repeat(ch === '"' ? backslashes * 2 + 1 : backslashes) + ch;
457
- backslashes = 0;
458
- }
459
- return `${quoted}${"\\".repeat(backslashes * 2)}"`;
460
- }
461
- function preferExecutable(lines) {
462
- return lines.find((line) => /\.exe$/i.test(line)) ?? lines.find((line) => /\.(cmd|bat)$/i.test(line)) ?? null;
463
- }
464
- var windowsExecutables = /* @__PURE__ */ new Map();
465
- function windowsExecutable(bin) {
466
- if (/[\\/]/.test(bin)) return bin;
467
- if (process.platform !== "win32") return null;
468
- const key = JSON.stringify([bin, process.env.PATH, process.env.PATHEXT]);
469
- if (windowsExecutables.has(key)) return windowsExecutables.get(key) ?? null;
470
- let resolved = null;
471
- try {
472
- resolved = preferExecutable(
473
- execFileSync("where.exe", [bin], { encoding: "utf-8", timeout: 5e3 }).split(/\r?\n/).map((line) => line.trim()).filter(Boolean)
474
- );
475
- } catch {
476
- }
477
- windowsExecutables.set(key, resolved);
478
- if (!resolved)
479
- console.error(
480
- `[runner:spawn] Could not resolve ${bin} to an executable on PATH. Install the agent and reconnect the runner.`
481
- );
482
- return resolved;
483
- }
484
- function windowsPowerShellEnv(env = process.env) {
485
- return Object.fromEntries(
486
- Object.entries(env).filter(([key]) => key.toLowerCase() !== "psmodulepath")
487
- );
488
- }
489
-
490
490
  // src/t3-bin.ts
491
491
  import { execFile, execFileSync as execFileSync2 } from "child_process";
492
492
  import { existsSync, readdirSync as readdirSync2, statSync as statSync2 } from "fs";
@@ -791,12 +791,36 @@ var WIZARD_FOR = "steps only the user can do by hand: a sign-in, an app permissi
791
791
  var CHECK_BACK_MIN_MINUTES = 5;
792
792
  var CHECK_BACK_MAX_MINUTES = 3 * 24 * 60;
793
793
  var CHECK_BACK_WHY_MAX = 300;
794
+ var RUN_IMAGES_MAX = 6;
795
+ var RUN_IMAGE_MAX_BYTES = 5 * 1024 * 1024;
796
+ var RUN_IMAGE_TYPES = { png: "image/png", jpg: "image/jpeg", webp: "image/webp" };
797
+ function imageExt(bytes) {
798
+ const at = (i, ...want) => want.every((b, j) => bytes[i + j] === b);
799
+ if (at(0, 137, 80, 78, 71, 13, 10, 26, 10)) return "png";
800
+ if (at(0, 255, 216, 255)) return "jpg";
801
+ if (at(0, 82, 73, 70, 70) && at(8, 87, 69, 66, 80)) return "webp";
802
+ return null;
803
+ }
804
+ var RUN_MEDIA_KEY = runMediaPattern("[0-9a-f-]{36}\\/[0-9a-f-]{36}\\/");
805
+ var RUN_MEDIA_FILE = runMediaPattern("");
806
+ var RUN_PREVIEWS_MAX = 3;
807
+ var PREVIEW_HOURS = 24;
808
+ var PREVIEW_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
809
+ function isPort(v) {
810
+ return typeof v === "number" && Number.isInteger(v) && v >= 1 && v <= 65535;
811
+ }
812
+ function isPreviewPath(v) {
813
+ return typeof v === "string" && v.length <= 400 && v.startsWith("/") && !v.startsWith("//") && !/[\s\\]/.test(v);
814
+ }
815
+ function runMediaPattern(folder) {
816
+ return new RegExp(`^${folder}[0-9a-f-]{36}\\.(${Object.keys(RUN_IMAGE_TYPES).join("|")})$`);
817
+ }
794
818
  var RESULT_INSTRUCTION = [
795
819
  "When you finish, end your final message with a fenced block tagged cloop-result containing JSON, for example:",
796
820
  "```cloop-result",
797
821
  '{"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"}]}',
798
822
  "```",
799
- "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), wizard (title, steps). A check outcome is passed, failed or skipped.",
823
+ "An output kind is one of: pr or link (title, url), draft (title, body, optional to, optional url), doc (title, optional url or body), wizard (title, steps). A check outcome is passed, failed or skipped.",
800
824
  "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.",
801
825
  `A wizard is for ${WIZARD_FOR}. When the work needs such a step, return a wizard for it, not only words. A wizard has 1 to ${WIZARD_STEPS_MAX} steps in order, each {"title", "body" in Markdown, optional https "url"}. Never ask the user to paste a password, key or other secret anywhere. The user sees a wizard as a walkthrough: in your own words, call it a walkthrough, never a wizard.`,
802
826
  "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.",
@@ -804,6 +828,8 @@ var RESULT_INSTRUCTION = [
804
828
  ].join("\n");
805
829
  var MACHINE_RESULT_INSTRUCTION = [
806
830
  RESULT_INSTRUCTION,
831
+ `To show the owner a picture, such as a screenshot of a UI change or a result a picture explains better than words, save it as a PNG, JPEG or WebP file outside the repository (for example in /tmp) and list it as an output: {"kind": "image", "title": "The new sign-in page", "path": "/tmp/sign-in.png"}, with the file's absolute path. Cloop uploads the file and shows it on the run. At most ${RUN_IMAGES_MAX} images, each under ${RUN_IMAGE_MAX_BYTES / (1024 * 1024)} MB. On a Cloop Box, the Playwright browser tool takes a screenshot of any page, a local server's page too.`,
832
+ `To let the owner open a web app or page you are running on this machine, such as a dev server, leave the server running after your turn ends: start it in the background, detached from your shell (for example \`nohup npm run dev -- --port 5173 > /tmp/dev.log 2>&1 &\`), and check it answers on its port. Then list it as an output: {"kind": "preview", "title": "The new sign-in page", "port": 5173, "path": "/sign-in"}, with the port it listens on and an optional path to open first. Cloop gives the owner a private link to it for ${PREVIEW_HOURS} hours, while this machine is on. At most ${RUN_PREVIEWS_MAX} previews a run.`,
807
833
  `When you started something that keeps running after this turn (a build, a deploy, a long job) or you wait on something outside, do not wait in the turn: add "check_back": {"in_minutes": 120, "why": "Read the training log and report the score."} to the block. Cloop sends you a message in this conversation then, with your why, and you carry on from there. Give ${CHECK_BACK_MIN_MINUTES} to ${CHECK_BACK_MAX_MINUTES} minutes. Leave it out when the work is done.`
808
834
  ].join("\n");
809
835
  var SUMMARY_MAX = 4e3;
@@ -858,8 +884,23 @@ function readOutput(o) {
858
884
  ...body !== void 0 ? { body } : {}
859
885
  };
860
886
  }
861
- case "file":
862
- return text(out.path, 400) ? { kind: "file", title, path: out.path } : null;
887
+ case "image":
888
+ if (!text(out.path, 400)) return null;
889
+ return {
890
+ kind: "image",
891
+ title,
892
+ path: out.path,
893
+ ...typeof out.media === "string" && RUN_MEDIA_KEY.test(out.media) ? { media: out.media } : {}
894
+ };
895
+ case "preview":
896
+ if (!isPort(out.port) || out.path !== void 0 && !isPreviewPath(out.path)) return null;
897
+ return {
898
+ kind: "preview",
899
+ title,
900
+ port: out.port,
901
+ ...out.path !== void 0 ? { path: out.path } : {},
902
+ ...typeof out.preview === "string" && PREVIEW_ID.test(out.preview) ? { preview: out.preview } : {}
903
+ };
863
904
  case "wizard":
864
905
  return Array.isArray(out.steps) && out.steps.length ? { kind: "wizard", title, steps: out.steps } : null;
865
906
  default:
@@ -1525,13 +1566,14 @@ function providerName(instanceId, cfg) {
1525
1566
  if (displayName) return displayName;
1526
1567
  return instanceId && PROVIDER_NAMES[instanceId] || instanceId || "The harness";
1527
1568
  }
1528
- function readyProvider(cfg, driver) {
1569
+ function readyProvider(cfg, driver, skip = () => false) {
1529
1570
  const candidates = [...cfg.providers].sort(
1530
1571
  (a, b) => Number(b.instanceId === driver) - Number(a.instanceId === driver)
1531
1572
  );
1532
1573
  for (const p of candidates) {
1533
1574
  if ((p.driver ?? p.instanceId) !== driver || !p.enabled || !p.installed) continue;
1534
1575
  if (p.auth && p.auth.status !== "authenticated") continue;
1576
+ if (skip(p)) continue;
1535
1577
  const model = p.models?.find((m) => m.isDefault)?.slug ?? p.models?.[0]?.slug;
1536
1578
  if (model) return { instanceId: p.instanceId, model };
1537
1579
  }
@@ -1553,9 +1595,43 @@ function signedOutWords(p, run2) {
1553
1595
  const signedOut = failure.code === "unauthorized" || /^Claude could not authenticate\b/.test(message) || HARNESS_SIGNED_OUT.test(message);
1554
1596
  return signedOut ? words ?? (message || null) : null;
1555
1597
  }
1556
- function launchMove(cfg, own, permission, held) {
1557
- const codex = held && own !== CODEX_PROVIDER ? readyProvider(cfg, CODEX_PROVIDER) : null;
1558
- if (codex) return { to: codex, reason: "limit" };
1598
+ function planSpentUntil(p, now) {
1599
+ const quota = quotaFromT3(p.usageLimits);
1600
+ if (quota.status !== "ok") return 0;
1601
+ let until = 0;
1602
+ for (const w of quota.windows) {
1603
+ const reset = w.resetsAt ? Date.parse(w.resetsAt) : Number.NaN;
1604
+ if (w.usedPercent >= 100 && !w.label.includes("\xB7") && reset > now)
1605
+ until = Math.max(until, reset);
1606
+ }
1607
+ return until;
1608
+ }
1609
+ var PLAN_AUTH = /* @__PURE__ */ new Set(["CLAUDE_CODE_OAUTH_TOKEN"]);
1610
+ var BUILT_IN = /* @__PURE__ */ new Set([CLAUDE_PROVIDER, CODEX_PROVIDER]);
1611
+ function overridesAuth(cfg, instanceId) {
1612
+ const entry = cfg.settings?.providerInstances?.[instanceId];
1613
+ if (!entry) return !BUILT_IN.has(instanceId);
1614
+ const env = entry.environment ?? [];
1615
+ return env.some(
1616
+ (e) => !PLAN_AUTH.has(e.name) && /KEY|TOKEN|SECRET|BEDROCK|VERTEX|FOUNDRY|AZURE|BASE_URL|PROVIDER/i.test(e.name)
1617
+ );
1618
+ }
1619
+ function limitMove(cfg, from, a) {
1620
+ const p = cfg.providers.find((x) => x.instanceId === from);
1621
+ const own = p?.driver ?? p?.instanceId ?? from;
1622
+ const other = otherDriver(cfg, from);
1623
+ const skip = (x) => a.tried.has(x.instanceId) || a.spent(x) || overridesAuth(cfg, x.instanceId);
1624
+ for (const driver of [own, other]) {
1625
+ if (!driver || driver === CODEX_PROVIDER && a.permission !== "full") continue;
1626
+ const to = readyProvider(cfg, driver, skip);
1627
+ if (to) return to;
1628
+ }
1629
+ return null;
1630
+ }
1631
+ function launchMove(cfg, own, permission, spent) {
1632
+ const ownProvider = cfg.providers.find((p) => p.instanceId === own && p.enabled);
1633
+ const free = ownProvider && spent(ownProvider) ? limitMove(cfg, own, { tried: /* @__PURE__ */ new Set([own]), permission, spent }) : null;
1634
+ if (free) return { to: free, reason: "limit" };
1559
1635
  const auth = cfg.providers.find((p) => p.instanceId === own && p.enabled)?.auth;
1560
1636
  if (!auth || auth.status === "authenticated") return null;
1561
1637
  const driver = otherDriver(cfg, own);
@@ -1664,8 +1740,8 @@ var T3Driver = class {
1664
1740
  launched = /* @__PURE__ */ new Map();
1665
1741
  /** The box's providers as last read, so a run's end names a custom provider by its driver. */
1666
1742
  providers = [];
1667
- /** Until then, a launch that names no harness starts on Codex: the Claude account is at its limit. */
1668
- limitedUntil = 0;
1743
+ /** Until when each instance is held at its usage limit, by the runs that stopped there. */
1744
+ limitedUntil = /* @__PURE__ */ new Map();
1669
1745
  get capabilities() {
1670
1746
  return boxCapabilities(this.deps.scope?.());
1671
1747
  }
@@ -1849,9 +1925,8 @@ var T3Driver = class {
1849
1925
  throw new BoxToolError("runtime_mode_unknown");
1850
1926
  const permission = permissionOf(runtimeMode);
1851
1927
  const named = Boolean(a.harness || a.model);
1852
- const held = !named && permission === "full" && this.now() < this.limitedUntil;
1853
1928
  const own = cfg.settings?.defaultModelSelection?.instanceId ?? CLAUDE_PROVIDER;
1854
- const move = named ? null : launchMove(cfg, own, permission, held);
1929
+ const move = named ? null : launchMove(cfg, own, permission, this.spent);
1855
1930
  const fallback = move?.to ?? cfg.settings?.defaultModelSelection;
1856
1931
  const harness = a.harness ?? fallback?.instanceId ?? "claudeAgent";
1857
1932
  const provider = cfg.providers.find((p) => p.instanceId === harness && p.enabled);
@@ -1893,8 +1968,8 @@ var T3Driver = class {
1893
1968
  this.launched.set(launched.threadId, {
1894
1969
  named,
1895
1970
  permission,
1971
+ tried: /* @__PURE__ */ new Set([modelSelection.instanceId, ...move ? [own] : []]),
1896
1972
  ...move ? {
1897
- movedFrom: "",
1898
1973
  switched: movedLine(
1899
1974
  move.reason,
1900
1975
  providerName(own, cfg),
@@ -2037,6 +2112,25 @@ var T3Driver = class {
2037
2112
  }
2038
2113
  return { ok: true, was_running: true };
2039
2114
  }
2115
+ /**
2116
+ * T3's Settle, for a thread this runner started (`cloop:` title) whose
2117
+ * latest run completed and that waits on nothing. Routine runs left a
2118
+ * "cloop: ..." thread on the owner's list after every run (3 Nov 2026).
2119
+ * A thread a person started or adopted keeps its own title and stays.
2120
+ */
2121
+ async settle(threadId, commandId) {
2122
+ const p = await this.readProjection(threadId);
2123
+ if (!(p.thread.title ?? "").startsWith(CLOOP_THREAD_PREFIX))
2124
+ return { settled: false, refused: "not_cloop" };
2125
+ if (p.thread.settledAt) return { settled: true, already: true };
2126
+ if (latestRun(p.runs ?? [])?.status !== "completed")
2127
+ return { settled: false, refused: "not_finished" };
2128
+ if ((p.runtimeRequests ?? []).some((r) => r.status === "pending"))
2129
+ return { settled: false, refused: "waiting" };
2130
+ await this.dispatch({ type: "thread.settle", commandId, threadId });
2131
+ this.log(`settled thread=${threadId}`);
2132
+ return { settled: true, already: false };
2133
+ }
2040
2134
  async readThread(id) {
2041
2135
  const projection = await this.readProjection(id);
2042
2136
  const { status, settled, pr_url, last_assistant_text } = outcomeOf(projection);
@@ -2225,7 +2319,7 @@ var T3Driver = class {
2225
2319
  const said = outcome.last_assistant_text?.replace(/\s+/g, " ").trim();
2226
2320
  const limited = outcome.status === "failed" && HARNESS_LIMIT.test(said ?? "");
2227
2321
  const signedOut = !limited && turn ? signedOutWords(p, turn) : null;
2228
- const quoted = (words) => `${opening}${providerName(turn?.providerInstanceId)} said: "${words}"`.slice(
2322
+ const quoted = (words) => `${opening}${providerName(turn?.providerInstanceId, { providers: this.providers })} said: "${words}"`.slice(
2229
2323
  0,
2230
2324
  RUN_TEXT_MAX
2231
2325
  );
@@ -2331,14 +2425,16 @@ var T3Driver = class {
2331
2425
  };
2332
2426
  }
2333
2427
  /**
2334
- * Once per thread: a run that failed at a Claude usage limit carries on in
2335
- * the same thread on Codex, and a run whose harness could not sign in
2336
- * carries on with the other harness, Claude Code or Codex, either way. T3
2428
+ * A run that failed at a usage limit carries on in the same thread on the
2429
+ * next instance with usage (`limitMove`): another Claude subscription, then
2430
+ * Codex. A run whose harness could not sign in carries on with the other
2431
+ * harness, Claude Code or Codex, either way. Each thread moves to an
2432
+ * instance once at most, so the chain ends when every option is out. T3
2337
2433
  * switches the thread's provider and hands it the thread so far; the
2338
- * worktree, with any edits, stays. A limit that names no model holds the
2339
- * account, so launches start on Codex for LIMIT_HOLD_MS; a sign-in failure
2340
- * holds nothing. A thread whose Task named its harness or model stays, and
2341
- * so does one without full access that would move to Codex, because Codex
2434
+ * worktree, with any edits, stays. A limit that names no model holds that
2435
+ * instance, so launches skip it for LIMIT_HOLD_MS; a sign-in failure holds
2436
+ * nothing. A thread whose Task named its harness or model stays, and so
2437
+ * does one without full access that would move to Codex, because Codex
2342
2438
  * asks nothing. So does a thread this daemon did not launch: a restart
2343
2439
  * forgets what the Task named. Returns the progress line of the move.
2344
2440
  */
@@ -2348,12 +2444,11 @@ var T3Driver = class {
2348
2444
  const reason = HARNESS_LIMIT.test(said) ? "limit" : signedOutWords(p, turn) ? "signed_out" : null;
2349
2445
  if (!reason) return null;
2350
2446
  const from = turn.providerInstanceId;
2351
- if (reason === "limit") {
2352
- if (from === CODEX_PROVIDER) return null;
2353
- if (!limitedModel(said)) this.limitedUntil = this.now() + LIMIT_HOLD_MS;
2354
- }
2447
+ if (reason === "limit" && from && !limitedModel(said))
2448
+ this.limitedUntil.set(from, this.now() + LIMIT_HOLD_MS);
2355
2449
  const entry = this.launched.get(threadId);
2356
- if (!entry || entry.named || entry.movedFrom !== void 0) return null;
2450
+ if (!entry || entry.named) return null;
2451
+ if (from) entry.tried.add(from);
2357
2452
  try {
2358
2453
  return await this.dispatchHandover(threadId, turn, entry, reason);
2359
2454
  } catch (err) {
@@ -2366,13 +2461,16 @@ var T3Driver = class {
2366
2461
  async dispatchHandover(threadId, turn, entry, reason) {
2367
2462
  const cfg = await this.t3.rpc("server.getConfig", {});
2368
2463
  this.providers = cfg.providers;
2369
- const driver = reason === "limit" ? CODEX_PROVIDER : otherDriver(cfg, turn.providerInstanceId);
2370
- if (!driver || driver === CODEX_PROVIDER && entry.permission !== "full") return null;
2371
- const to = readyProvider(cfg, driver);
2464
+ const from = turn.providerInstanceId ?? CLAUDE_PROVIDER;
2372
2465
  const name = providerName(turn.providerInstanceId, cfg);
2466
+ const to = reason === "limit" ? limitMove(cfg, from, {
2467
+ tried: entry.tried,
2468
+ permission: entry.permission,
2469
+ spent: this.spent
2470
+ }) : this.signedOutMove(cfg, from, entry);
2373
2471
  if (!to) {
2374
2472
  this.log(
2375
- `${reason} thread=${threadId}: ${providerName(driver)} is not on or not signed in; the run fails`
2473
+ `${reason} thread=${threadId}: no other instance on this box is on, signed in and free; the run fails`
2376
2474
  );
2377
2475
  return null;
2378
2476
  }
@@ -2394,6 +2492,7 @@ ${MACHINE_RESULT_INSTRUCTION}`
2394
2492
  creationSource: "mcp"
2395
2493
  });
2396
2494
  const toName = providerName(to.instanceId, cfg);
2495
+ entry.tried.add(to.instanceId);
2397
2496
  entry.movedFrom = turn.id;
2398
2497
  entry.switched = movedLine(reason, name, toName, "was");
2399
2498
  this.log(
@@ -2404,6 +2503,17 @@ ${MACHINE_RESULT_INSTRUCTION}`
2404
2503
  now() {
2405
2504
  return this.deps.now?.() ?? Date.now();
2406
2505
  }
2506
+ /** An instance at its usage limit now: a run stopped there within the hold, or T3 reads its plan as spent. */
2507
+ spent = (p) => {
2508
+ const now = this.now();
2509
+ return (this.limitedUntil.get(p.instanceId) ?? 0) > now || planSpentUntil(p, now) > now;
2510
+ };
2511
+ /** The other harness a signed-out run moves to, never one it already ran on. */
2512
+ signedOutMove(cfg, from, entry) {
2513
+ const driver = otherDriver(cfg, from);
2514
+ if (!driver || driver === CODEX_PROVIDER && entry.permission !== "full") return null;
2515
+ return readyProvider(cfg, driver, (p) => entry.tried.has(p.instanceId));
2516
+ }
2407
2517
  readProjection(threadId) {
2408
2518
  return this.t3.rpc("orchestration.getThreadProjection", { threadId });
2409
2519
  }
@@ -2573,6 +2683,9 @@ function pickRepo(repos, repository) {
2573
2683
  if (!picked) throw new BoxToolError("no_project");
2574
2684
  return picked;
2575
2685
  }
2686
+ function withFolder(r, end) {
2687
+ return end.kind === "settled" ? { ...end, cwd: r.repo } : end;
2688
+ }
2576
2689
  function run(cmd, args, cwd) {
2577
2690
  return new Promise(
2578
2691
  (resolve, reject) => execFile3(
@@ -2993,7 +3106,7 @@ ${a.text}` : a.text;
2993
3106
  }
2994
3107
  if (r.end) {
2995
3108
  const { at: _at, ...end } = r.end;
2996
- onEvent(end);
3109
+ onEvent(withFolder(r, end));
2997
3110
  return unwatch;
2998
3111
  }
2999
3112
  const live = this.lives.get(id);
@@ -3366,7 +3479,7 @@ ${MACHINE_RESULT_INSTRUCTION}`, images));
3366
3479
  r.pid = null;
3367
3480
  this.save();
3368
3481
  this.note(r, endNote(end));
3369
- this.emit(r.work_id, end);
3482
+ this.emit(r.work_id, withFolder(r, end));
3370
3483
  }
3371
3484
  emit(id, event) {
3372
3485
  for (const listener of [...this.listeners.get(id) ?? []]) listener(event);
@@ -3416,6 +3529,11 @@ function readRunRecords(file = localRunsFilePath()) {
3416
3529
  }
3417
3530
 
3418
3531
  export {
3532
+ RUN_IMAGES_MAX,
3533
+ RUN_IMAGE_MAX_BYTES,
3534
+ RUN_IMAGE_TYPES,
3535
+ imageExt,
3536
+ RUN_PREVIEWS_MAX,
3419
3537
  MACHINE_RESULT_INSTRUCTION,
3420
3538
  readRunResult,
3421
3539
  hasResultBlock,
@@ -3438,6 +3556,10 @@ export {
3438
3556
  runnerPath,
3439
3557
  cloopCommand,
3440
3558
  serviceIdentity,
3559
+ commandFor,
3560
+ quoteWindowsArg,
3561
+ windowsExecutable,
3562
+ windowsPowerShellEnv,
3441
3563
  boxPath,
3442
3564
  isLocal,
3443
3565
  isHosted,
@@ -3453,10 +3575,6 @@ export {
3453
3575
  redactSecrets,
3454
3576
  STOPPED_SUMMARY,
3455
3577
  isEndLogLine,
3456
- commandFor,
3457
- quoteWindowsArg,
3458
- windowsExecutable,
3459
- windowsPowerShellEnv,
3460
3578
  parseAttachments,
3461
3579
  fetchImages,
3462
3580
  delivery,