@cloop/runner 0.3.29 → 0.3.31

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 (29) hide show
  1. package/README.md +7 -0
  2. package/dist/{box-6TJMXQXM.js → box-RFAHCXZS.js} +239 -69
  3. package/dist/chunk-52CUSFDQ.js +401 -0
  4. package/dist/{chunk-P56EL4D4.js → chunk-7AHYPGSU.js} +2 -2
  5. package/dist/{chunk-65KJPIZC.js → chunk-FKYVJUIR.js} +1 -1
  6. package/dist/{chunk-4FXRG3Q3.js → chunk-GL77IQQE.js} +1 -1
  7. package/dist/{chunk-SVHQXVCH.js → chunk-MEAVT5SJ.js} +986 -205
  8. package/dist/{chunk-AIOOLVM7.js → chunk-R73PVAM2.js} +182 -88
  9. package/dist/{chunk-NTXQLEMQ.js → chunk-SBYSVZ7J.js} +94 -2
  10. package/dist/{chunk-PSA5EC65.js → chunk-UERK5AHI.js} +6 -6
  11. package/dist/{chunk-TWDKR7XV.js → chunk-WYU74GLG.js} +5 -5
  12. package/dist/{chunk-GURADB5L.js → chunk-YLVOEZWH.js} +1 -1
  13. package/dist/{connect-HVUNZ6A2.js → connect-WRTLQW5H.js} +10 -9
  14. package/dist/{disconnect-NXVDABS5.js → disconnect-I44BWWFB.js} +8 -9
  15. package/dist/existing-runner-SP6SNFH4.js +20 -0
  16. package/dist/{hook-activity-GAJ5NABA.js → hook-activity-3T6IMEM6.js} +2 -3
  17. package/dist/{hook-session-start-5JYNMGX4.js → hook-session-start-DLP77G4H.js} +5 -7
  18. package/dist/index.js +20 -17
  19. package/dist/{login-PH2RZNOE.js → login-LH2KF7N2.js} +3 -3
  20. package/dist/{mcp-server-U2H4U4BZ.js → mcp-server-SGIWNLLL.js} +9 -11
  21. package/dist/{runner-YTGTJPPR.js → runner-SXUQH5IU.js} +4 -4
  22. package/dist/{runs-D7XT2PYS.js → runs-3YZO57MX.js} +2 -2
  23. package/dist/{statusline-U4K2IQIT.js → statusline-UHZTCNCB.js} +1 -1
  24. package/dist/{takeover-M2SDWTVK.js → takeover-M4QHMXTZ.js} +5 -6
  25. package/dist/{use-7OUFEREN.js → use-YB75NHTE.js} +8 -9
  26. package/package.json +1 -1
  27. package/dist/chunk-ES5BRAKJ.js +0 -88
  28. package/dist/chunk-KYGYU5G2.js +0 -220
  29. package/dist/existing-runner-7E6RUUJH.js +0 -21
@@ -139,7 +139,8 @@ function runLogPath(dir, workId) {
139
139
  return SAFE_ID.test(workId) ? join3(dir, `${workId}.log`) : null;
140
140
  }
141
141
  var SECRETS = [
142
- [/-----BEGIN [A-Z ]*PRIVATE KEY-----.*/g, "[redacted private key]"],
142
+ // The whole block, to its END line or the end of the text: a cut-off paste still hides its body.
143
+ [/-----BEGIN ([A-Z0-9 ]+)-----[\s\S]*?(?:-----END \1-----|$)/g, "[redacted key block]"],
143
144
  [/\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi, "$1 [redacted]"],
144
145
  [/(:\/\/)[^\s/@:]+:[^\s/@]+@/g, "$1[redacted]@"],
145
146
  [
@@ -154,7 +155,7 @@ var SECRETS = [
154
155
  /(--?[\w-]*(?:token|secret|password|api-key|apikey)[\w-]*[ =])["']?[^\s"']{4,}["']?/gi,
155
156
  "$1[redacted]"
156
157
  ],
157
- [/\b(?:sk|pk|rk)-[A-Za-z0-9_-]{16,}/g, "[redacted]"],
158
+ [/\b(?:sk|pk|rk)[-_][A-Za-z0-9_-]{16,}/g, "[redacted]"],
158
159
  [/\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})/g, "[redacted]"],
159
160
  [/\bxox[abprs]-[A-Za-z0-9-]{10,}/g, "[redacted]"],
160
161
  [/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g, "[redacted]"],
@@ -578,6 +579,7 @@ var RESULT_INSTRUCTION = [
578
579
  "When the ask is to find, compare, summarise or research something, put the whole answer in a doc output with a body, so the owner has one page to read; the summary stays one or two sentences."
579
580
  ].join("\n");
580
581
  var SUMMARY_MAX = 4e3;
582
+ var ASKS_MAX = 1e3;
581
583
  var DOC_BODY_MAX = 8e3;
582
584
  var ITEMS_MAX = 10;
583
585
  var BLOCK = /```cloop-result\s*\n([\s\S]*?)```/g;
@@ -660,6 +662,7 @@ function readRunResult(message) {
660
662
  const summary = typeof value?.summary === "string" ? value.summary.trim() : "";
661
663
  if (!summary) return none;
662
664
  const list = (v) => Array.isArray(v) ? v : [];
665
+ const asks = typeof value?.asks === "string" ? value.asks.trim() : "";
663
666
  const outputs = list(value?.outputs).flatMap((o) => readOutput(o) ?? []);
664
667
  const checks = list(value?.checks).flatMap((c) => readCheck(c) ?? []);
665
668
  return {
@@ -667,7 +670,8 @@ function readRunResult(message) {
667
670
  summary: summary.length > SUMMARY_MAX ? `${summary.slice(0, SUMMARY_MAX - 1)}\u2026` : summary,
668
671
  outputs: outputs.slice(0, ITEMS_MAX),
669
672
  checks: checks.slice(0, ITEMS_MAX),
670
- ...value?.nothing_new === true ? { nothing_new: true } : {}
673
+ ...value?.nothing_new === true ? { nothing_new: true } : {},
674
+ ...asks ? { asks: asks.length > ASKS_MAX ? `${asks.slice(0, ASKS_MAX - 1)}\u2026` : asks } : {}
671
675
  },
672
676
  dropped: { outputs: list(value?.outputs).length - outputs.length, checks: list(value?.checks).length - checks.length }
673
677
  };
@@ -864,11 +868,27 @@ function limitedModel(said) {
864
868
  function refusedModel(said) {
865
869
  return /The '([^']+)' model is not supported/i.exec(said ?? "")?.[1] ?? null;
866
870
  }
871
+ var HARNESS_SIGNED_OUT = /^\s*(Failed to authenticate:\s*OAuth session expired and could not be refreshed\b|Your access token could not be refreshed\b|Your authentication session could not be refreshed\b|Not signed in\. Please run 'codex login'|unexpected status 401\b)/i;
867
872
  var LIMIT_HOLD_MS = 60 * 6e4;
868
- function handoverPrompt(prompt, from) {
873
+ var HARNESS_STATE = {
874
+ limit: "at its usage limit",
875
+ signed_out: "signed out here",
876
+ missing: "not installed here"
877
+ };
878
+ function movedLine(reason, from, to, tense) {
879
+ return `${from} ${tense} ${HARNESS_STATE[reason]}, so ${to} did this run.`;
880
+ }
881
+ function movingLine(reason, from, to) {
882
+ return `${from} is ${HARNESS_STATE[reason]}, so I moved this to ${to}`;
883
+ }
884
+ var STOPPED_BECAUSE = {
885
+ limit: "stopped at its usage limit",
886
+ signed_out: "could not sign in"
887
+ };
888
+ function handoverPrompt(prompt, from, reason = "limit") {
869
889
  return `${prompt}
870
890
 
871
- ${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.`;
891
+ ${from} started this work and ${STOPPED_BECAUSE[reason]}. Its changes, if any, are in this checkout. Read \`git status\` and \`git log\` first, and carry on from there.`;
872
892
  }
873
893
 
874
894
  // src/drivers/usage.ts
@@ -1268,22 +1288,60 @@ function permissionOf(runtimeMode) {
1268
1288
  return runtimeMode === "full-access" ? "full" : "ask";
1269
1289
  }
1270
1290
  var CODEX_PROVIDER = "codex";
1291
+ var CLAUDE_PROVIDER = "claudeAgent";
1271
1292
  var PROVIDER_NAMES = { claudeAgent: "Claude Code", codex: "Codex" };
1272
- function providerName(instanceId) {
1293
+ function providerName(instanceId, cfg) {
1294
+ const displayName = cfg?.providers.find((p) => p.instanceId === instanceId)?.displayName;
1295
+ if (displayName) return displayName;
1273
1296
  return instanceId && PROVIDER_NAMES[instanceId] || instanceId || "The harness";
1274
1297
  }
1298
+ function readyProvider(cfg, driver) {
1299
+ const candidates = [...cfg.providers].sort(
1300
+ (a, b) => Number(b.instanceId === driver) - Number(a.instanceId === driver)
1301
+ );
1302
+ for (const p of candidates) {
1303
+ if ((p.driver ?? p.instanceId) !== driver || !p.enabled || !p.installed) continue;
1304
+ if (p.auth && p.auth.status !== "authenticated") continue;
1305
+ const model = p.models?.find((m) => m.isDefault)?.slug ?? p.models?.[0]?.slug;
1306
+ if (model) return { instanceId: p.instanceId, model };
1307
+ }
1308
+ return null;
1309
+ }
1310
+ function otherDriver(cfg, instanceId) {
1311
+ const p = cfg.providers.find((x) => x.instanceId === instanceId);
1312
+ const driver = p?.driver ?? p?.instanceId ?? instanceId;
1313
+ return driver === CODEX_PROVIDER ? CLAUDE_PROVIDER : driver === CLAUDE_PROVIDER ? CODEX_PROVIDER : null;
1314
+ }
1315
+ function signedOutWords(p, run2) {
1316
+ if (run2.status !== "failed") return null;
1317
+ const said = (p.messages ?? []).filter((m) => m.role === "assistant" && m.runId === run2.id && m.text?.trim()).at(-1)?.text?.trim();
1318
+ const words = said && HARNESS_SIGNED_OUT.test(said) ? said : null;
1319
+ const failure = (p.turnItems ?? []).filter((i) => i.type === "error" && i.runId === run2.id).at(-1)?.failure;
1320
+ if (!failure) return words;
1321
+ if (failure.class && failure.class !== "provider_error") return null;
1322
+ const message = failure.message?.trim() ?? "";
1323
+ const signedOut = failure.code === "unauthorized" || /^Claude could not authenticate\b/.test(message) || HARNESS_SIGNED_OUT.test(message);
1324
+ return signedOut ? words ?? (message || null) : null;
1325
+ }
1326
+ function launchMove(cfg, own, permission, held) {
1327
+ const codex = held && own !== CODEX_PROVIDER ? readyProvider(cfg, CODEX_PROVIDER) : null;
1328
+ if (codex) return { to: codex, reason: "limit" };
1329
+ const auth = cfg.providers.find((p) => p.instanceId === own && p.enabled)?.auth;
1330
+ if (!auth || auth.status === "authenticated") return null;
1331
+ const driver = otherDriver(cfg, own);
1332
+ if (!driver || driver === CODEX_PROVIDER && permission !== "full") return null;
1333
+ const to = readyProvider(cfg, driver);
1334
+ return to ? { to, reason: "signed_out" } : null;
1335
+ }
1275
1336
  var PROVIDER_HARNESS = {
1276
1337
  claudeAgent: "claude-code",
1277
1338
  codex: "codex"
1278
1339
  };
1279
- function providerHarness(instanceId) {
1280
- return instanceId ? { harness: PROVIDER_HARNESS[instanceId] ?? instanceId } : {};
1281
- }
1282
- function codexProvider(cfg) {
1283
- const p = cfg.providers.find((x) => (x.driver ?? x.instanceId) === CODEX_PROVIDER && x.enabled);
1284
- if (!p || p.auth && p.auth.status !== "authenticated") return null;
1285
- const model = p.models?.find((m) => m.isDefault)?.slug ?? p.models?.[0]?.slug;
1286
- return model ? { instanceId: p.instanceId, model } : null;
1340
+ function providerHarness(instanceId, cfg) {
1341
+ if (!instanceId) return {};
1342
+ const p = cfg?.providers.find((x) => x.instanceId === instanceId);
1343
+ const id = p?.driver ?? instanceId;
1344
+ return { harness: PROVIDER_HARNESS[id] ?? id };
1287
1345
  }
1288
1346
  function pickProject(projects, repository) {
1289
1347
  if (!repository) {
@@ -1374,6 +1432,8 @@ var T3Driver = class {
1374
1432
  held = /* @__PURE__ */ new Map();
1375
1433
  /** Threads this daemon launched. A restart forgets them, and a forgotten thread is not moved. */
1376
1434
  launched = /* @__PURE__ */ new Map();
1435
+ /** The box's providers as last read, so a run's end names a custom provider by its driver. */
1436
+ providers = [];
1377
1437
  /** Until then, a launch that names no harness starts on Codex: the Claude account is at its limit. */
1378
1438
  limitedUntil = 0;
1379
1439
  get capabilities() {
@@ -1503,6 +1563,7 @@ var T3Driver = class {
1503
1563
  this.t3.rpc("server.getConfig", {}),
1504
1564
  this.t3.http("/api/orchestration/shell", SHELL_HEADERS)
1505
1565
  ]);
1566
+ this.providers = cfg.providers;
1506
1567
  const project = pickProject(shell.projects ?? [], a.repository);
1507
1568
  const runtimeMode = a.runtime_mode ?? cfg.settings?.defaultRuntimeMode;
1508
1569
  if (!runtimeMode || !RUNTIME_MODES.has(runtimeMode))
@@ -1510,9 +1571,9 @@ var T3Driver = class {
1510
1571
  const permission = permissionOf(runtimeMode);
1511
1572
  const named = Boolean(a.harness || a.model);
1512
1573
  const held = !named && permission === "full" && this.now() < this.limitedUntil;
1513
- const own = cfg.settings?.defaultModelSelection?.instanceId ?? "claudeAgent";
1514
- const codex = held && own !== CODEX_PROVIDER ? codexProvider(cfg) : null;
1515
- const fallback = codex ?? cfg.settings?.defaultModelSelection;
1574
+ const own = cfg.settings?.defaultModelSelection?.instanceId ?? CLAUDE_PROVIDER;
1575
+ const move = named ? null : launchMove(cfg, own, permission, held);
1576
+ const fallback = move?.to ?? cfg.settings?.defaultModelSelection;
1516
1577
  const harness = a.harness ?? fallback?.instanceId ?? "claudeAgent";
1517
1578
  const provider = cfg.providers.find((p) => p.instanceId === harness && p.enabled);
1518
1579
  if (!provider) throw new BoxToolError("harness_unavailable");
@@ -1521,7 +1582,10 @@ var T3Driver = class {
1521
1582
  const model = a.model ?? (fallback?.instanceId === harness ? fallback.model : void 0) ?? provider.models?.find((m) => m.isDefault)?.slug;
1522
1583
  if (!model) throw new BoxToolError("harness_unavailable");
1523
1584
  const modelSelection = !a.model && fallback?.instanceId === harness ? fallback : { instanceId: harness, model };
1524
- if (codex) this.log(`limit hold: launch work=${a.work_id} starts on ${codex.instanceId}`);
1585
+ if (move)
1586
+ this.log(
1587
+ `${move.reason === "limit" ? "limit hold" : "signed out"}: launch work=${a.work_id} starts on ${move.to.instanceId}`
1588
+ );
1525
1589
  const photos2 = await this.photos(a);
1526
1590
  const launched = await this.t3.rpc(
1527
1591
  "orchestration.launchThread",
@@ -1547,16 +1611,21 @@ var T3Driver = class {
1547
1611
  this.launched.set(launched.threadId, {
1548
1612
  named,
1549
1613
  permission,
1550
- ...codex ? {
1614
+ ...move ? {
1551
1615
  movedFrom: "",
1552
- switched: `${providerName(own)} is at its usage limit, so Codex did this run.`
1616
+ switched: movedLine(
1617
+ move.reason,
1618
+ providerName(own, cfg),
1619
+ providerName(move.to.instanceId, cfg),
1620
+ "is"
1621
+ )
1553
1622
  } : {}
1554
1623
  });
1555
1624
  return {
1556
1625
  thread_id: launched.threadId,
1557
1626
  resumed: launched.resumed,
1558
1627
  permission,
1559
- ...providerHarness(modelSelection.instanceId),
1628
+ ...providerHarness(modelSelection.instanceId, cfg),
1560
1629
  // A resumed thread kept its first message: these photos did not go in.
1561
1630
  ...launched.resumed ? {} : delivery(a.attachments, photos2.attachments.length)
1562
1631
  };
@@ -1838,13 +1907,11 @@ var T3Driver = class {
1838
1907
  finishing = false;
1839
1908
  return;
1840
1909
  }
1841
- if (outcome.kind === "failed" && turn && await this.moveToCodex(threadId, turn, outcome)) {
1910
+ const moving = outcome.kind === "failed" && turn ? await this.handOver(threadId, turn, outcome, p) : null;
1911
+ if (moving) {
1842
1912
  finishing = false;
1843
1913
  if (stopped) return;
1844
- onEvent({
1845
- kind: "progress",
1846
- summary: `${providerName(turn.providerInstanceId)} is at its usage limit, so I moved this to Codex`
1847
- });
1914
+ onEvent({ kind: "progress", summary: moving });
1848
1915
  if (!live) void follow();
1849
1916
  return;
1850
1917
  }
@@ -1857,25 +1924,24 @@ var T3Driver = class {
1857
1924
  if (outcome.kind === "failed") {
1858
1925
  const said = outcome.last_assistant_text?.replace(/\s+/g, " ").trim();
1859
1926
  const limited = outcome.status === "failed" && HARNESS_LIMIT.test(said ?? "");
1860
- const end = limited ? {
1861
- summary: `${opening}${providerName(turn?.providerInstanceId)} said: "${said}"`.slice(
1862
- 0,
1863
- RUN_TEXT_MAX
1864
- ),
1865
- error: "harness_limit"
1866
- } : outcome.status === "interrupted" ? { summary: STOPPED_IN_T3, error: "interrupted" } : { summary: `${opening}The run ended ${outcome.status}.` };
1927
+ const signedOut = !limited && turn ? signedOutWords(p, turn) : null;
1928
+ const quoted = (words) => `${opening}${providerName(turn?.providerInstanceId)} said: "${words}"`.slice(
1929
+ 0,
1930
+ RUN_TEXT_MAX
1931
+ );
1932
+ const end = limited ? { summary: quoted(said), error: "harness_limit" } : signedOut ? { summary: quoted(signedOut.replace(/\s+/g, " ")), error: "harness_signed_out" } : outcome.status === "interrupted" ? { summary: STOPPED_IN_T3, error: "interrupted" } : { summary: `${opening}The run ended ${outcome.status}.` };
1867
1933
  onEvent({
1868
1934
  kind: "failed",
1869
1935
  ...end,
1870
1936
  ...outcome.result ? pr : {},
1871
- ...providerHarness(turn?.providerInstanceId)
1937
+ ...providerHarness(turn?.providerInstanceId, { providers: this.providers })
1872
1938
  });
1873
1939
  } else {
1874
1940
  const lost = outcome.dropped ? droppedLine(outcome.dropped, threadId) : null;
1875
1941
  if (lost) this.log(lost);
1876
1942
  onEvent({
1877
1943
  kind: "settled",
1878
- ...providerHarness(turn?.providerInstanceId),
1944
+ ...providerHarness(turn?.providerInstanceId, { providers: this.providers }),
1879
1945
  ...outcome.result ? { result: outcome.result } : {},
1880
1946
  ...outcome.last_assistant_text ? { summary: `${opening}${outcome.last_assistant_text}`.slice(0, RUN_TEXT_MAX) } : {},
1881
1947
  ...pr
@@ -1966,59 +2032,74 @@ var T3Driver = class {
1966
2032
  }
1967
2033
  /**
1968
2034
  * Once per thread: a run that failed at a Claude usage limit carries on in
1969
- * the same thread on Codex. T3 switches the thread's provider and hands
1970
- * Codex the thread so far; the worktree, with any edits, stays. A limit
1971
- * that names no model holds the account, so launches start on Codex for
1972
- * LIMIT_HOLD_MS. A thread whose Task named its harness or model stays, and
1973
- * so does one without full access, because Codex asks nothing. So does a
1974
- * thread this daemon did not launch: a restart forgets what the Task named.
2035
+ * the same thread on Codex, and a run whose harness could not sign in
2036
+ * carries on with the other harness, Claude Code or Codex, either way. T3
2037
+ * switches the thread's provider and hands it the thread so far; the
2038
+ * worktree, with any edits, stays. A limit that names no model holds the
2039
+ * account, so launches start on Codex for LIMIT_HOLD_MS; a sign-in failure
2040
+ * holds nothing. A thread whose Task named its harness or model stays, and
2041
+ * so does one without full access that would move to Codex, because Codex
2042
+ * asks nothing. So does a thread this daemon did not launch: a restart
2043
+ * forgets what the Task named. Returns the progress line of the move.
1975
2044
  */
1976
- async moveToCodex(threadId, turn, outcome) {
2045
+ async handOver(threadId, turn, outcome, p) {
2046
+ if (outcome.status !== "failed") return null;
1977
2047
  const said = outcome.last_assistant_text ?? "";
1978
- if (outcome.status !== "failed" || !HARNESS_LIMIT.test(said)) return false;
2048
+ const reason = HARNESS_LIMIT.test(said) ? "limit" : signedOutWords(p, turn) ? "signed_out" : null;
2049
+ if (!reason) return null;
1979
2050
  const from = turn.providerInstanceId;
1980
- if (from === CODEX_PROVIDER) return false;
1981
- if (!limitedModel(said)) this.limitedUntil = this.now() + LIMIT_HOLD_MS;
2051
+ if (reason === "limit") {
2052
+ if (from === CODEX_PROVIDER) return null;
2053
+ if (!limitedModel(said)) this.limitedUntil = this.now() + LIMIT_HOLD_MS;
2054
+ }
1982
2055
  const entry = this.launched.get(threadId);
1983
- if (!entry || entry.named || entry.permission !== "full" || entry.movedFrom !== void 0)
1984
- return false;
2056
+ if (!entry || entry.named || entry.movedFrom !== void 0) return null;
1985
2057
  try {
1986
- return await this.dispatchToCodex(threadId, turn, entry);
2058
+ return await this.dispatchHandover(threadId, turn, entry, reason);
1987
2059
  } catch (err) {
1988
2060
  this.log(
1989
2061
  `fallback failed thread=${threadId}: ${err instanceof Error ? err.message : String(err)}`
1990
2062
  );
1991
- return false;
2063
+ return null;
1992
2064
  }
1993
2065
  }
1994
- async dispatchToCodex(threadId, turn, entry) {
1995
- const codex = codexProvider(await this.t3.rpc("server.getConfig", {}));
1996
- if (!codex) {
1997
- this.log(`limit thread=${threadId}: Codex is not on or not signed in; the run fails`);
1998
- return false;
2066
+ async dispatchHandover(threadId, turn, entry, reason) {
2067
+ const cfg = await this.t3.rpc("server.getConfig", {});
2068
+ this.providers = cfg.providers;
2069
+ const driver = reason === "limit" ? CODEX_PROVIDER : otherDriver(cfg, turn.providerInstanceId);
2070
+ if (!driver || driver === CODEX_PROVIDER && entry.permission !== "full") return null;
2071
+ const to = readyProvider(cfg, driver);
2072
+ const name = providerName(turn.providerInstanceId, cfg);
2073
+ if (!to) {
2074
+ this.log(
2075
+ `${reason} thread=${threadId}: ${providerName(driver)} is not on or not signed in; the run fails`
2076
+ );
2077
+ return null;
1999
2078
  }
2000
- const name = providerName(turn.providerInstanceId);
2001
2079
  const id = randomUUID();
2002
2080
  await this.dispatch({
2003
2081
  type: "message.dispatch",
2004
2082
  commandId: id,
2005
2083
  threadId,
2006
2084
  messageId: id,
2007
- text: handoverPrompt("Carry on with the task in this thread.", name).concat(
2085
+ text: handoverPrompt("Carry on with the task in this thread.", name, reason).concat(
2008
2086
  `
2009
2087
 
2010
2088
  ${RESULT_INSTRUCTION}`
2011
2089
  ),
2012
2090
  attachments: [],
2013
- modelSelection: codex,
2091
+ modelSelection: to,
2014
2092
  dispatchMode: { type: "start_immediately" },
2015
2093
  createdBy: "user",
2016
2094
  creationSource: "mcp"
2017
2095
  });
2096
+ const toName = providerName(to.instanceId, cfg);
2018
2097
  entry.movedFrom = turn.id;
2019
- entry.switched = `${name} was at its usage limit, so Codex did this run.`;
2020
- this.log(`fallback thread=${threadId} provider=${codex.instanceId} model=${codex.model}`);
2021
- return true;
2098
+ entry.switched = movedLine(reason, name, toName, "was");
2099
+ this.log(
2100
+ `fallback thread=${threadId} provider=${to.instanceId} model=${to.model} reason=${reason}`
2101
+ );
2102
+ return movingLine(reason, name, toName);
2022
2103
  }
2023
2104
  now() {
2024
2105
  return this.deps.now?.() ?? Date.now();
@@ -2162,13 +2243,7 @@ function runHarness(run2, own) {
2162
2243
  const bin = harness === driver && own?.bin ? own.bin : harness === "codex" ? "codex" : "claude";
2163
2244
  return { harness, bin };
2164
2245
  }
2165
- var MOVE_STATE = {
2166
- limit: "at its usage limit",
2167
- signed_out: "signed out here",
2168
- missing: "not installed here"
2169
- };
2170
- var movedLine = (move, from, to) => `${harnessName(from)} ${move.at === "run" ? "was" : "is"} ${MOVE_STATE[move.reason]}, so ${harnessName(to)} did this run.`;
2171
- var movingLine = (move, from, to) => `${harnessName(from)} is ${MOVE_STATE[move.reason]}, so I moved this to ${harnessName(to)}`;
2246
+ var switchedLine = (move, from, to) => movedLine(move.reason, harnessName(from), harnessName(to), move.at === "run" ? "was" : "is");
2172
2247
  function failedEnd(harness, run2) {
2173
2248
  const said = run2.result?.text?.trim() || run2.lastText;
2174
2249
  const limited = HARNESS_LIMIT.test(run2.result?.text ?? "");
@@ -2413,7 +2488,8 @@ ${photos2.line}` : a.prompt,
2413
2488
  ...a.model && !moved ? { model: a.model } : {},
2414
2489
  ...a.runtime_mode ? { runtime_mode: a.runtime_mode } : {},
2415
2490
  ...a.harness ? { harness_named: true } : {},
2416
- ...moved ? { harness: dialect.name, moved, switched: movedLine(moved, own.name, dialect.name) } : {},
2491
+ ...a.model ? { model_named: true } : {},
2492
+ ...moved ? { harness: dialect.name, moved, switched: switchedLine(moved, own.name, dialect.name) } : {},
2417
2493
  pid: null,
2418
2494
  started_at: new Date(this.now()).toISOString(),
2419
2495
  head_at_launch: head
@@ -2575,7 +2651,8 @@ ${a.text}` : a.text;
2575
2651
  /**
2576
2652
  * A Task that names its harness stays on it. Otherwise a run starts on the
2577
2653
  * fallback while the runner's own harness is held at its limit, or when the
2578
- * own harness is signed out or not installed and the fallback is signed in.
2654
+ * own harness is signed out or not installed and the fallback is signed in,
2655
+ * unless the Task named its model.
2579
2656
  */
2580
2657
  async route(a) {
2581
2658
  const own = this.deps.dialect;
@@ -2586,7 +2663,7 @@ ${a.text}` : a.text;
2586
2663
  return { dialect: to, moved: { reason: "limit", at: "launch" } };
2587
2664
  const harness = await own.probe();
2588
2665
  if (harness?.signedIn) return { dialect: own };
2589
- if (to && await ready())
2666
+ if (to && !a.model && await ready())
2590
2667
  return {
2591
2668
  dialect: to,
2592
2669
  moved: { reason: harness ? "signed_out" : "missing", at: "launch" }
@@ -2717,6 +2794,9 @@ ${RESULT_INSTRUCTION}`, images));
2717
2794
  if (wasAsked) this.askNext(r, live);
2718
2795
  return;
2719
2796
  }
2797
+ case "signed_out":
2798
+ live.signedOut = true;
2799
+ return;
2720
2800
  case "result":
2721
2801
  live.outstanding--;
2722
2802
  live.result = { ok: item.ok, ...item.text ? { text: item.text } : {} };
@@ -2771,9 +2851,14 @@ ${RESULT_INSTRUCTION}`, images));
2771
2851
  if (end.error) this.log(`limit work=${r.work_id} error=${end.error}`);
2772
2852
  if (end.error === "harness_limit") {
2773
2853
  if (this.fallBack(r, live.result?.text)) return;
2774
- if (await this.moveHarness(r, live.result?.text)) return;
2854
+ if (await this.moveHarness(r, live.result?.text, "limit")) return;
2775
2855
  }
2776
- await this.end(r, { kind: "failed", ...end });
2856
+ if (live.signedOut) {
2857
+ this.log(`signed_out work=${r.work_id} harness=${this.dialectOf(r).name}`);
2858
+ if (await this.moveHarness(r, live.result?.text, "signed_out")) return;
2859
+ }
2860
+ const signedOut = !end.error && live.signedOut ? { error: "harness_signed_out" } : {};
2861
+ await this.end(r, { kind: "failed", ...end, ...signedOut });
2777
2862
  }
2778
2863
  /**
2779
2864
  * Once per run: a run stopped by its model's usage limit resumes its own
@@ -2825,7 +2910,7 @@ ${RESULT_INSTRUCTION}`, images));
2825
2910
  if (!next)
2826
2911
  this.log(`model work=${r.work_id} refused=${refused} next=none catalog=${listed.length}`);
2827
2912
  if (!next || this.stopping || r.end) return false;
2828
- const moved = r.harness && r.moved ? movedLine(r.moved, this.deps.dialect.name, r.harness) : null;
2913
+ const moved = r.harness && r.moved ? switchedLine(r.moved, this.deps.dialect.name, r.harness) : null;
2829
2914
  r.refused = tried;
2830
2915
  r.model = next;
2831
2916
  r.session_id = null;
@@ -2837,24 +2922,28 @@ ${RESULT_INSTRUCTION}`, images));
2837
2922
  this.log(`model work=${r.work_id} refused=${refused} next=${next}`);
2838
2923
  this.spawnRun(
2839
2924
  r,
2840
- r.moved?.at === "run" ? handoverPrompt(r.prompt, harnessName(this.deps.dialect.name)) : r.prompt,
2925
+ r.moved?.at === "run" ? handoverPrompt(r.prompt, harnessName(this.deps.dialect.name), r.moved.reason) : r.prompt,
2841
2926
  false
2842
2927
  );
2843
2928
  return true;
2844
2929
  }
2845
2930
  /**
2846
- * Once per run: a run its own harness cannot carry on starts again on the
2847
- * fallback harness, in the same checkout, so the edits so far carry over.
2848
- * The session does not: the prompt goes again, with a note to read the
2849
- * checkout first. A limit that names no model holds the account, so new
2850
- * runs start on the fallback for LIMIT_HOLD_MS. It does not move a run
2851
- * whose Task named its harness, nor one the fallback may not carry.
2931
+ * Once per run: a run its own harness cannot carry on, at its usage limit
2932
+ * or signed out, starts again on the fallback harness, in the same
2933
+ * checkout, so the edits so far carry over. The session does not: the
2934
+ * prompt goes again, with a note to read the checkout first. A limit that
2935
+ * names no model holds the account, so new runs start on the fallback for
2936
+ * LIMIT_HOLD_MS; a sign-in failure holds nothing, because the next run's
2937
+ * check may find the harness signed in again. It does not move a run whose
2938
+ * Task named its harness, a signed-out run whose Task named its model, nor
2939
+ * one the fallback may not carry.
2852
2940
  */
2853
- async moveHarness(r, said) {
2941
+ async moveHarness(r, said, reason) {
2854
2942
  const to = this.deps.fallbackHarness;
2855
2943
  if (!to || r.harness) return false;
2856
- if (!limitedModel(said)) this.limitedUntil = this.now() + LIMIT_HOLD_MS;
2857
- if (r.harness_named || !this.carrier(r, r.used_permission) || !r.prompt) return false;
2944
+ if (reason === "limit" && !limitedModel(said)) this.limitedUntil = this.now() + LIMIT_HOLD_MS;
2945
+ if (r.harness_named || reason === "signed_out" && r.model_named) return false;
2946
+ if (!this.carrier(r, r.used_permission) || !r.prompt) return false;
2858
2947
  this.recovering.add(r.work_id);
2859
2948
  try {
2860
2949
  const probe = await to.probe().catch(() => null);
@@ -2863,16 +2952,19 @@ ${RESULT_INSTRUCTION}`, images));
2863
2952
  this.recovering.delete(r.work_id);
2864
2953
  }
2865
2954
  const from = this.deps.dialect.name;
2866
- const move = { reason: "limit", at: "run" };
2955
+ const move = { reason, at: "run" };
2867
2956
  r.harness = to.name;
2868
2957
  r.moved = move;
2869
2958
  r.session_id = null;
2870
2959
  r.model = void 0;
2871
- r.switched = movedLine(move, from, to.name);
2960
+ r.switched = switchedLine(move, from, to.name);
2872
2961
  this.save();
2873
- this.log(`fallback work=${r.work_id} harness=${to.name} reason=limit`);
2874
- this.emit(r.work_id, { kind: "progress", summary: movingLine(move, from, to.name) });
2875
- this.spawnRun(r, handoverPrompt(r.prompt, harnessName(from)), false);
2962
+ this.log(`fallback work=${r.work_id} harness=${to.name} reason=${reason}`);
2963
+ this.emit(r.work_id, {
2964
+ kind: "progress",
2965
+ summary: movingLine(reason, harnessName(from), harnessName(to.name))
2966
+ });
2967
+ this.spawnRun(r, handoverPrompt(r.prompt, harnessName(from), reason), false);
2876
2968
  return true;
2877
2969
  }
2878
2970
  /**
@@ -2962,6 +3054,7 @@ export {
2962
3054
  nextProgress,
2963
3055
  isYes,
2964
3056
  HARNESS_LIMIT,
3057
+ HARNESS_SIGNED_OUT,
2965
3058
  ENVIRONMENTS,
2966
3059
  environmentOf,
2967
3060
  runnerEnvironment,
@@ -2979,6 +3072,7 @@ export {
2979
3072
  writeBoxConfig,
2980
3073
  runLogDir,
2981
3074
  runLogPath,
3075
+ redactSecrets,
2982
3076
  STOPPED_SUMMARY,
2983
3077
  isEndLogLine,
2984
3078
  commandFor,
@@ -1,7 +1,85 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
- api
4
- } from "./chunk-ES5BRAKJ.js";
3
+ getOrigin,
4
+ getToken
5
+ } from "./chunk-D5UZW42X.js";
6
+
7
+ // src/api.ts
8
+ var REAUTH_MESSAGE = "Cloop session expired or unauthenticated. Run `cloop login`.";
9
+ var ReauthError = class extends Error {
10
+ constructor(message = REAUTH_MESSAGE) {
11
+ super(message);
12
+ this.name = "ReauthError";
13
+ }
14
+ };
15
+ var ApiError = class extends Error {
16
+ constructor(status, message, body = "") {
17
+ super(message);
18
+ this.status = status;
19
+ this.body = body;
20
+ this.name = "ApiError";
21
+ }
22
+ status;
23
+ body;
24
+ };
25
+ function buildUrl(origin, path, query) {
26
+ const url = new URL(path, `${origin}/`);
27
+ if (query) {
28
+ for (const [key, value] of Object.entries(query)) {
29
+ if (value !== void 0) url.searchParams.set(key, value);
30
+ }
31
+ }
32
+ return url.toString();
33
+ }
34
+ async function api(path, opts = {}) {
35
+ const {
36
+ method = "GET",
37
+ body,
38
+ query,
39
+ auth = true,
40
+ fetchFn = fetch,
41
+ origin = getOrigin(),
42
+ timeoutMs
43
+ } = opts;
44
+ const headers = { accept: "application/json" };
45
+ if (auth) {
46
+ const token = getToken();
47
+ if (!token) throw new ReauthError();
48
+ headers.authorization = `Bearer ${token}`;
49
+ }
50
+ if (body !== void 0) headers["content-type"] = "application/json";
51
+ const url = buildUrl(origin, path, query);
52
+ const init = {
53
+ method,
54
+ headers,
55
+ ...body !== void 0 ? { body: JSON.stringify(body) } : {}
56
+ };
57
+ const attempt = () => fetchFn(url, timeoutMs ? { ...init, signal: AbortSignal.timeout(timeoutMs) } : init);
58
+ let res;
59
+ try {
60
+ res = await attempt();
61
+ } catch (err) {
62
+ try {
63
+ res = await attempt();
64
+ } catch {
65
+ const detail = err instanceof Error ? err.message : String(err);
66
+ throw new ApiError(0, `Network error reaching ${url}: ${detail}`);
67
+ }
68
+ }
69
+ if (res.status === 401) throw new ReauthError();
70
+ if (!res.ok) {
71
+ const text2 = await res.text().catch(() => "");
72
+ throw new ApiError(
73
+ res.status,
74
+ `Cloop API ${res.status} for ${path}: ${text2.slice(0, 300)}`,
75
+ text2
76
+ );
77
+ }
78
+ if (res.status === 204) return void 0;
79
+ const text = await res.text();
80
+ if (!text) return void 0;
81
+ return JSON.parse(text);
82
+ }
5
83
 
6
84
  // src/presence.ts
7
85
  import { execFileSync as execFileSync2 } from "child_process";
@@ -73,6 +151,16 @@ function resolveMachine() {
73
151
  function shortMachineName(machine = getMachine()) {
74
152
  return machine.split(".")[0] || machine;
75
153
  }
154
+ function defaultDeviceName() {
155
+ if (osPlatform() === "darwin") {
156
+ try {
157
+ const name = execFileSync2("scutil", ["--get", "ComputerName"], SCUTIL_OPTS).trim();
158
+ if (name) return name;
159
+ } catch {
160
+ }
161
+ }
162
+ return shortMachineName();
163
+ }
76
164
  var PLATFORM_LABELS = {
77
165
  claude: "Claude Code",
78
166
  codex: "Codex",
@@ -139,8 +227,12 @@ var HeartbeatClient = class {
139
227
  };
140
228
 
141
229
  export {
230
+ ReauthError,
231
+ ApiError,
232
+ api,
142
233
  getMachine,
143
234
  shortMachineName,
235
+ defaultDeviceName,
144
236
  getName,
145
237
  getSurface,
146
238
  detectPlatform,
@@ -2,23 +2,23 @@
2
2
  import {
3
3
  findRun,
4
4
  ownHarness
5
- } from "./chunk-65KJPIZC.js";
5
+ } from "./chunk-FKYVJUIR.js";
6
6
  import {
7
7
  lockThreadsFile,
8
8
  threadsFilePath
9
- } from "./chunk-GURADB5L.js";
9
+ } from "./chunk-YLVOEZWH.js";
10
10
  import {
11
11
  localRunsFilePath,
12
12
  readRunRecords,
13
13
  runHarness,
14
14
  takeoverSummary
15
- } from "./chunk-AIOOLVM7.js";
16
- import {
17
- shortMachineName
18
- } from "./chunk-NTXQLEMQ.js";
15
+ } from "./chunk-R73PVAM2.js";
19
16
  import {
20
17
  sanitizeLabel
21
18
  } from "./chunk-VK6GV757.js";
19
+ import {
20
+ shortMachineName
21
+ } from "./chunk-SBYSVZ7J.js";
22
22
 
23
23
  // src/commands/takeover.ts
24
24
  import { spawnSync } from "child_process";