trantor 0.18.143 → 0.18.146

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 (61) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +24 -0
  4. package/bin/app.mjs +54 -5
  5. package/bin/canary.mjs +148 -0
  6. package/bin/capacity.mjs +109 -0
  7. package/bin/cli.mjs +5 -0
  8. package/bin/crew-runner.mjs +98 -17
  9. package/bin/disk.mjs +9 -6
  10. package/bin/doctor.mjs +93 -1
  11. package/bin/duty.mjs +5 -2
  12. package/bin/fitness.mjs +15 -0
  13. package/bin/herdr-agent.mjs +8 -2
  14. package/bin/models.mjs +54 -23
  15. package/bin/wake-nudge.mjs +33 -6
  16. package/configs/dispatcher-policy.json +84 -0
  17. package/deploy/com.trantor.hub.plist +15 -3
  18. package/deploy/node-path.sh +11 -4
  19. package/deploy/setup.sh +6 -13
  20. package/docs/FEATURES.md +45 -0
  21. package/hub/auth.mjs +3 -1
  22. package/hub/review-store.mjs +48 -0
  23. package/hub/routes/capacity.mjs +77 -0
  24. package/hub/routes/cards.mjs +7 -2
  25. package/hub/routes/insights.mjs +41 -6
  26. package/hub/routes/messages.mjs +16 -60
  27. package/hub/routes/reviews.mjs +86 -0
  28. package/hub/send-message.mjs +51 -0
  29. package/hub.mjs +5 -1
  30. package/kimi.plugin.json +1 -1
  31. package/lib/app-screenshot.mjs +155 -0
  32. package/lib/canary/canary.mjs +225 -0
  33. package/lib/canary/probes.mjs +197 -0
  34. package/lib/canary/registry.mjs +179 -0
  35. package/lib/capacity-machines.mjs +79 -0
  36. package/lib/capacity.mjs +189 -0
  37. package/lib/classify-failure.mjs +14 -8
  38. package/lib/discovery/SOURCES.md +30 -0
  39. package/lib/discovery/claude.mjs +27 -0
  40. package/lib/discovery/codex.mjs +74 -0
  41. package/lib/discovery/common.mjs +56 -0
  42. package/lib/discovery/gemini.mjs +27 -0
  43. package/lib/discovery/index.mjs +104 -0
  44. package/lib/discovery/kimi.mjs +10 -0
  45. package/lib/discovery/opencode.mjs +19 -0
  46. package/lib/discovery/qwen.mjs +16 -0
  47. package/lib/disk.mjs +14 -4
  48. package/lib/dispatcher/policy.mjs +41 -0
  49. package/lib/dispatcher/schemas.mjs +218 -0
  50. package/lib/dispatcher/snapshot.mjs +70 -0
  51. package/lib/dispatcher/store.mjs +111 -0
  52. package/lib/fitness.mjs +97 -0
  53. package/lib/launch-node.mjs +96 -0
  54. package/lib/launchd.mjs +61 -0
  55. package/lib/machine-health.mjs +80 -1
  56. package/lib/review-hunks.mjs +41 -0
  57. package/lib/seat-liveness.mjs +41 -0
  58. package/lib/session-liveness.mjs +23 -0
  59. package/lib/turn-usage.mjs +154 -27
  60. package/mcp.mjs +14 -1
  61. package/package.json +3 -2
@@ -17,6 +17,7 @@ import { signedHeaders } from "../lib/signed-fetch.mjs";
17
17
  import { ensureEnrolled } from "../lib/enroll.mjs";
18
18
  import { redactKeys } from "../lib/redact.mjs";
19
19
  import { writeTurnState } from "../lib/turnstate.mjs";
20
+ import { NON_RUNNABLE_CARD_STATUSES, TURNLESS_AFTER_MS, stampWakeDelivery, turnlessContract } from "../lib/seat-liveness.mjs";
20
21
  import { completeTurnRow, isTurnRow, shipTurnRows } from "../lib/telemetry-ship.mjs";
21
22
  import { alignSeatWorktree, applyWorktreeDeclaration, ensureSeatWorktree, provisioningLines, readWorktreeDeclaration } from "../lib/seat-worktree.mjs";
22
23
  import {
@@ -35,7 +36,8 @@ import {
35
36
  CUT_CHAIN_PARK_MIN, cutChainEvidence, isBoundedPark, askDuringTurn, askedVerdict,
36
37
  } from "../lib/turn-policy.mjs";
37
38
  import { snapshotBeforeCut } from "./cut-snapshot.mjs";
38
- import { ocTurnUsage, dshTurnUsage, usageTotal, processedInput, codexStepInput, kimiStepInput, claudeStepInput } from "../lib/turn-usage.mjs";
39
+ import { ocTurnUsage, ocSessionId, kimiTurnUsage, dshTurnUsage, usageTotal, processedInput, codexStepInput, kimiStepInput, claudeStepInput, codexTurnModel, kimiTurnModel, claudeTurnModel } from "../lib/turn-usage.mjs";
40
+ import { effortName, isInfraFailure, providerForModel } from "../lib/fitness.mjs";
39
41
  import { capConfig, capDecision, capHandoffPrompt, capPointerLine, capExhaustedNote } from "../lib/context-cap.mjs";
40
42
  import { ocCompactionContent, ocCompactionLogLine, readOpencodeUserConfig, seatMcpOverlay, seatPermissionOverlay, seatConfigContent } from "../lib/seat-compaction.mjs";
41
43
  import { seatSignalPrefix } from "../lib/seat-signal-guard.mjs";
@@ -149,11 +151,7 @@ function ocSid(dir) {
149
151
  // realpath of the /var/... path the runner holds — query both spellings.
150
152
  const dirs = [dir];
151
153
  try { const real = realpathSync(dir); if (real !== dir) dirs.push(real); } catch {}
152
- const list = dirs.map((d) => `'${d.replaceAll("'", "''")}'`).join(", ");
153
- const q = `SELECT id FROM session WHERE directory IN (${list}) ORDER BY time_updated DESC LIMIT 1;`;
154
- const r = spawnSync("sqlite3", ["-readonly", OC_DB, q], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 5000 });
155
- const id = String(r.stdout || "").trim();
156
- return /^ses_[A-Za-z0-9]+$/.test(id) ? id : "";
154
+ return ocSessionId(OC_DB, dirs);
157
155
  } catch { return ""; }
158
156
  }
159
157
  // RUNNER_SESSION override: an orchestrator seat (bin/orchestrate.mjs) runs the same CLI as a crew
@@ -189,6 +187,9 @@ const log = (s) => console.log(`\x1b[38;5;43m[runner]\x1b[0m ${redactKeys(String
189
187
  const LOGDIR = join(homedir(), ".agent-bus", "logs");
190
188
  try { mkdirSync(LOGDIR, { recursive: true }); } catch {}
191
189
  let TURN = releaseState?.turn || 0;
190
+ let lastTurnStartedAt = Number(releaseState?.lastTurnStartedAt) || 0;
191
+ const TURNLESS_MS = Math.max(50, Number(process.env.RUNNER_TURNLESS_MS) || TURNLESS_AFTER_MS);
192
+ let turnlessAlertKey = releaseState?.turnlessAlertKey || "";
192
193
  // #13923: when THIS seat instance started. A seat name is reused across instances and the board's
193
194
  // assignee only knows the name, so the my-cards surfaces (relay_board mine, the own-card reroute)
194
195
  // fence assignments against this stamp — cards assigned before it are a predecessor's (#12138).
@@ -365,6 +366,7 @@ let consecFails = 0;
365
366
  // it every retry costs a turn for every live seat (monitoring doctrine: duration, not repetition).
366
367
  let announced = "";
367
368
  let lastErrText = "";
369
+ let lastFailureTail = "";
368
370
  let lastPermissionReject = null;
369
371
  // #5481: the turn exited 0 with a NULL/empty transcript — the Inception/Mercury trap. The provider
370
372
  // burned its whole max_tokens budget on internal reasoning and returned a null completion; the
@@ -675,6 +677,10 @@ async function balanceRows() {
675
677
  // The detached watchdog repeats the working payload once a minute: runTurn blocks this event loop.
676
678
  const PRESENCE_MS = Math.max(100, Number(process.env.RUNNER_PRESENCE_MS) || 60_000);
677
679
  async function registerStatus(status, extra = {}) {
680
+ if (extra.phase === "working") {
681
+ lastTurnStartedAt = Number(extra.phaseSince) || Date.now();
682
+ turnlessAlertKey = "";
683
+ }
678
684
  const url = HUB + "/register";
679
685
  const payload = { session: SESSION, project: PROJ, status, persona: PERSONA, agent: AGENT, llm: AGENT, model: MODEL, ...extra };
680
686
  if (MACHINE_LABEL) payload.machine = MACHINE_LABEL;
@@ -927,7 +933,7 @@ async function runTurn(prompt, isFirst, trigger = "kickoff", opts = {}) {
927
933
  await registerStatus(`working · ${trigger}`, { phase: "working", phaseSince: t0 });
928
934
  // #7749: the same boundary on disk — the watchdog refreshes lastBytesAt/lastTranscriptAt while
929
935
  // the turn runs, so a live reader sees the turn advance without waiting for its end.
930
- writeTurnState(PERSONA, PROJ, { turn: TURN, phase: "working", since: t0, card: sessionCard || 0, lastBytesAt: t0, lastTranscriptAt: 0 });
936
+ writeTurnState(PERSONA, PROJ, { turn: TURN, phase: "working", since: t0, card: sessionCard || 0, lastBytesAt: t0, lastTranscriptAt: 0, fault: "", turnless: null, alertDelivery: "" });
931
937
  const pf = join(homedir(), ".agent-bus", `turn-${PERSONA}-${PROJ}.txt`);
932
938
  appendFileSync(pf, "", { flag: "w" }); // truncate
933
939
  appendFileSync(pf, prompt);
@@ -941,13 +947,14 @@ async function runTurn(prompt, isFirst, trigger = "kickoff", opts = {}) {
941
947
  // #10197: the card status snapshot the turn is judged against at its end — a move to
942
948
  // testing/done under the turn is delivery even without a commit. null = the hub read failed:
943
949
  // the delivery check stands down rather than claim no-delivery on a transport error.
944
- let cardStatusBefore = null, cardLogBefore = [], cardDifficulty = "";
950
+ let cardStatusBefore = null, cardLogBefore = [], cardDifficulty = "", cardKind = "";
945
951
  if (!opts.state && sessionCard > 0) {
946
952
  try {
947
953
  const { task } = await api(`/card?project=${encodeURIComponent(PROJ)}&id=${sessionCard}`);
948
954
  cardStatusBefore = task ? String(task.status || "") : null;
949
955
  cardLogBefore = task?.log || [];
950
956
  cardDifficulty = task?.difficulty || "";
957
+ cardKind = task?.kind || task?.taskKind || task?.task_kind || "";
951
958
  } catch { cardStatusBefore = null; }
952
959
  }
953
960
  // #9778: the docker snapshot the turn is judged against — containers the CLI spawns are recorded
@@ -1203,7 +1210,8 @@ exit $turn_exit`;
1203
1210
  // #5868: a NEW commit since turn start is real work, and an exit-0 turn with real output is
1204
1211
  // never re-labelled auth — the qwen specimen exited 0 with a shipped commit (aa3c340) while a
1205
1212
  // short capture of echoed contract text tripped the regex.
1206
- const newCommit = !!headBefore && gitOut(["rev-parse", "HEAD"], TURN_DIR) !== headBefore;
1213
+ const headAfter = gitOut(["rev-parse", "HEAD"], TURN_DIR);
1214
+ const newCommit = !!headBefore && headAfter !== headBefore;
1207
1215
  if (realExit === 0 && looksLikeAuthDeath(ownOut, newCommit)) {
1208
1216
  effExit = 1;
1209
1217
  authHit = AUTH_MARKER_RE.exec(ownOut)[0];
@@ -1256,10 +1264,12 @@ exit $turn_exit`;
1256
1264
  // actually carried counts.
1257
1265
  if (c) tokens = c.input + c.output + c.cache_read + c.cache_creation;
1258
1266
  } // #8234: the CLIs that print no usage on stdout keep the counts in their own session records —
1259
- // opencode's db, the session resolved for this turn exactly like the `-s` resume id. Sum this
1260
- // turn's window there; null (unknown) leaves the stdout paths above standing — never 0 ("free").
1267
+ // opencode's db, kimi's wire, the dsh session log. Sum this turn's window there; null (unknown)
1268
+ // leaves the stdout paths above standing — never 0 ("free"). #14663: the sqlite reads go through
1269
+ // node's built-in SQLite (netcup has no sqlite3 binary), else every glm/openrouter turn read ~0.
1261
1270
  const usage = cli.pinned && sid ? ocTurnUsage(OC_DB, sid, t0, Date.now())
1262
1271
  : AGENT === "dsh" ? dshTurnUsage(join(homedir(), ".dsh", "sessions"), TURN_DIR, t0, Date.now())
1272
+ : DRIVER === "kimi" ? kimiTurnUsage(join(homedir(), ".kimi-code", "sessions"), sid, t0, Date.now())
1263
1273
  : null;
1264
1274
  if (usage) tokens = usageTotal(usage);
1265
1275
  // #11559: every token this turn spent rides the card it served. A card-0 turn (kickoff, pulse,
@@ -1317,10 +1327,10 @@ exit $turn_exit`;
1317
1327
  lastNoDelivery = noDelivery;
1318
1328
  lastNoDeliveryStatus = cardStatusAtEnd;
1319
1329
  if (noDelivery) log(`\x1b[33mexit 0 but the turn DELIVERED NOTHING on #${sessionCard} — no new commit, card still ${cardStatusAtEnd || "unknown"}\x1b[0m`);
1320
- // #5868: the verdict rides the telemetry row so a classification survives the pane scrolling
1321
- // away — the same "classified X because Y" shape the runner logs. A silent cut names its own
1322
- // verdict (#7752): the exit under it is the sweep's SIGPIPE. A box cut passes `cut` so its 137
1323
- // reads as the sweep's SIGKILL (#7099); a zero-usage turn names its own verdict too (#9724).
1330
+ // #5868/#14662: the verdict rides telemetry; an unrecognized failure also keeps its redacted
1331
+ // stderr tail on the row and card. A silent cut names its own verdict (#7752): the exit under it
1332
+ // is the sweep's SIGPIPE. A box cut passes `cut` so its 137 reads as SIGKILL (#7099); zero usage
1333
+ // names its own verdict too (#9724).
1324
1334
  const verdict = stallCut ? stallVerdict() : zeroUsage ? zeroUsageVerdict()
1325
1335
  : askVerdict ? askVerdict
1326
1336
  : blockedVerdict ? blockedVerdict
@@ -1332,7 +1342,28 @@ exit $turn_exit`;
1332
1342
  // empty/stalled turns to the card that produced nothing. `cut` stays too: the drills read it.
1333
1343
  const outcome = cut ? (stallCut ? "stalled" : "cut") : (effExit !== 0 ? (lastPermissionReject ? "rejected" : "api-error") : noDelivery ? "no-delivery" : lastEmptyTurn ? "empty" : "completed");
1334
1344
  const finalOutcome = askVerdict ? "asked" : blockedVerdict ? "blocked" : outcome;
1335
- const telemetryRow = { ts: Date.now(), persona: PERSONA, agent: AGENT, project: PROJ, turn: TURN, trigger, card: sessionCard || 0, model: MODEL || "cli-default", duration_ms: Date.now() - t0, exit: realExit, effExit, authFailed: effExit !== realExit, emptyOutput: lastEmptyOutput, emptyTurn: lastEmptyTurn, verdict, outcome: finalOutcome, tokens };
1345
+ const failure = effExit !== 0 ? classifyFailure(effExit, ownOut, lastEmptyOutput, lastEmptyTurn, cut) : null;
1346
+ lastFailureTail = failure?.reason === "crashed" ? failure.stderrTail : "";
1347
+ const endedAt = Date.now();
1348
+ const transcriptModel = DRIVER === "codex" ? codexTurnModel(join(homedir(), ".codex", "sessions"), t0, TURN_DIR)
1349
+ : DRIVER === "kimi" ? kimiTurnModel(join(homedir(), ".kimi-code", "sessions"), sid, t0)
1350
+ : DRIVER === "claude" ? claudeTurnModel(TRANSCRIPT_DIR, t0) : null;
1351
+ // #14654: structured transcript metadata, else the pinned model; free-text model: lines are never read.
1352
+ const actualModel = transcriptModel || MODEL || "unknown";
1353
+ const telemetryRow = { ts: endedAt, persona: PERSONA, agent: AGENT, project: PROJ, turn: TURN, trigger, card: sessionCard || 0, model: actualModel, duration_ms: endedAt - t0, exit: realExit, effExit, authFailed: effExit !== realExit, emptyOutput: lastEmptyOutput, emptyTurn: lastEmptyTurn, verdict, outcome: finalOutcome, tokens };
1354
+ if (lastFailureTail) telemetryRow.stderrTail = lastFailureTail;
1355
+ if (sessionCard > 0) {
1356
+ const failureReason = failure?.reason || classifyFailure(effExit, ownOut, lastEmptyOutput, lastEmptyTurn, cut).reason;
1357
+ telemetryRow.attempt = {
1358
+ id: `${SESSION}:${t0}:${TURN}`, card: sessionCard, seat: SESSION, project: PROJ,
1359
+ provider: providerForModel(DRIVER, actualModel), model: actualModel,
1360
+ effort: effortName(turnEffort.effort), harness: DRIVER,
1361
+ taskKind: cardKind || "unknown", difficulty: cardDifficulty || "unknown",
1362
+ machine: MACHINE_LABEL || "unknown", start: new Date(t0).toISOString(), end: new Date(endedAt).toISOString(),
1363
+ commit: newCommit ? headAfter : "", outcome: finalOutcome,
1364
+ infraFailure: isInfraFailure(finalOutcome, failureReason), tokens: Number.isFinite(tokens) ? tokens : null,
1365
+ };
1366
+ }
1336
1367
  if (usage) telemetryRow.usage = usage;
1337
1368
  if (dockerNew.length) telemetryRow.containers = dockerNew.map(c => c.name || c.id);
1338
1369
  if (cut) telemetryRow.cut = true;
@@ -1651,6 +1682,7 @@ async function resolveWakeCard(messages, { session }) {
1651
1682
  const shed = restored.wake.filter(isExpiredHubAlert).length +
1652
1683
  restored.bcast.filter(isExpiredHubAlert).length;
1653
1684
  let pendingWake = restored.wake.filter(shouldWake);
1685
+ stampWakeDelivery(pendingWake);
1654
1686
  let pendingBcast = restored.bcast.filter(m => !isExpiredHubAlert(m) && !isReceipt(m) && !isStatusBroadcast(m));
1655
1687
  if (shed) {
1656
1688
  log(`\x1b[33mdropped ${shed} expired hub staleness alert(s) older than ${Math.round(HUB_ALERT_TTL_MS / 60000)}m — they describe conditions that have long since changed\x1b[0m`);
@@ -1681,6 +1713,49 @@ async function resolveWakeCard(messages, { session }) {
1681
1713
  await api("/send", { from: SESSION, to: "all", project: PROJ, kind: "status", text }).catch(() => {});
1682
1714
  }
1683
1715
  let lastTurnAt = releaseState?.lastTurnAt || Date.now();
1716
+ async function checkTurnless() {
1717
+ const cardStatuses = {};
1718
+ for (;;) {
1719
+ const candidate = turnlessContract({
1720
+ messages: pendingWake, session: SESSION, nowMs: Date.now(), lastTurnStartedAt,
1721
+ awaitingAsk: !!awaitingAsk, parked: !!parkState,
1722
+ pausedCards: budgetStop ? [budgetStop.card] : [], cardStatuses, stuckAfterMs: TURNLESS_MS,
1723
+ });
1724
+ if (!candidate) return;
1725
+ const key = `${candidate.wakeId}:${candidate.deliveredAt}`;
1726
+ if (turnlessAlertKey === key) return;
1727
+ if (candidate.card && cardStatuses[candidate.card] === undefined) {
1728
+ const status = await api(`/card?project=${encodeURIComponent(PROJ)}&id=${candidate.card}`)
1729
+ .then(r => String(r?.task?.status || "")).catch(() => "");
1730
+ cardStatuses[candidate.card] = status;
1731
+ if (NON_RUNNABLE_CARD_STATUSES.has(status)) continue;
1732
+ }
1733
+ turnlessAlertKey = key;
1734
+ const age = candidate.ageMs >= 60e3 ? `${Math.floor(candidate.ageMs / 60e3)}m` : `${Math.floor(candidate.ageMs / 1000)}s`;
1735
+ const card = candidate.card ? ` card #${candidate.card}` : "";
1736
+ const last = candidate.lastTurnStartedAt ? new Date(candidate.lastTurnStartedAt).toISOString() : "never";
1737
+ const text = `⚠️ ${SESSION} alive-but-turnless — wake #${candidate.wakeId}${card} delivered ${age} ago, no turn started; runner pid ${process.pid}, phase idle, last turn start ${last}. Check wake delivery and the runner process.`;
1738
+ const evidence = { wakeId: candidate.wakeId, card: candidate.card, deliveredAt: candidate.deliveredAt, ageMs: candidate.ageMs, pid: process.pid, lastTurnStartedAt: candidate.lastTurnStartedAt };
1739
+ writeTurnState(PERSONA, PROJ, { phase: "idle", fault: "alive-but-turnless", turnless: evidence, alertDelivery: "sending" });
1740
+ await registerStatus(`FAULT alive-but-turnless · wake #${candidate.wakeId}${card}`, { phase: "idle", fault: "alive-but-turnless" });
1741
+ const orch = `${hostId()}:${PROJ}`;
1742
+ const sender = String(candidate.message.from || "");
1743
+ const to = sender && sender !== SESSION && !sender.startsWith("hub:") ? sender : orch;
1744
+ let delivered = false;
1745
+ try {
1746
+ const response = await api("/send", { from: SESSION, to, text, project: PROJ, kind: "alert" });
1747
+ delivered = !!response && response.ok !== false;
1748
+ } catch {}
1749
+ writeTurnState(PERSONA, PROJ, { alertDelivery: delivered ? "delivered" : "failed" });
1750
+ if (!delivered && candidate.card) {
1751
+ await api("/task/update", { id: candidate.card, by: SESSION,
1752
+ note: `alive-but-turnless: wake #${candidate.wakeId} has had no turn start for ${age}; runner pid ${process.pid}. Alert delivery FAILED; this note and the local turn-state file retain the incident.` }).catch(() => {});
1753
+ }
1754
+ cmuxStatus("turnless", "#ef6a6a", "alert", { alert: true, priority: 90 });
1755
+ log(`${text} · alert delivery ${delivered ? "succeeded" : "FAILED"}`);
1756
+ return;
1757
+ }
1758
+ }
1684
1759
  function restartForRelease() {
1685
1760
  const version = installedVersion();
1686
1761
  if (!newerVersion(version, bootVersion) || attemptedVersions.has(version)) return;
@@ -1696,7 +1771,7 @@ async function resolveWakeCard(messages, { session }) {
1696
1771
  writeFileSync(PENDF, JSON.stringify({ persona: PERSONA, agent: AGENT, project: PROJ, ts: Date.now(),
1697
1772
  wake: pendingWake, bcast: pendingBcast, seen: seenLedger, ask: awaitingAsk?.id || 0, askTo: awaitingAsk?.to || "" }));
1698
1773
  const state = { cursor, turn: TURN, sid, sessionCard, retryAt, deliveryFails,
1699
- noDeliveryRetry, askReleased, lastTurnAt, attempted: [...attemptedVersions], bootTs: BOOT_TS,
1774
+ noDeliveryRetry, askReleased, lastTurnAt, lastTurnStartedAt, turnlessAlertKey, attempted: [...attemptedVersions], bootTs: BOOT_TS,
1700
1775
  cardTokens, cardCommits, cardStartedAt, budgetStop, budgetRetryAt,
1701
1776
  capHandoffs, capLogged, capArmed, capFreshTurn };
1702
1777
  process.execve(process.execPath, [process.execPath, ...process.execArgv, ...process.argv.slice(1)],
@@ -1741,6 +1816,7 @@ async function resolveWakeCard(messages, { session }) {
1741
1816
  // is owed but NEVER redelivered. #11559: a budget-paused card paces its own redeliveries on
1742
1817
  // budgetRetryAt - a clock that never delays a poll-delivered contract for a different card.
1743
1818
  if (pendingWake.length && !awaitingAsk && Date.now() >= retryAt && Date.now() >= budgetRetryAt) { await deliverWake(); continue; }
1819
+ await checkTurnless();
1744
1820
  // cap the long-poll hold so neither a due pulse nor a due redelivery waits out a silent 280s window
1745
1821
  const due = [];
1746
1822
  if (PULSE_MS) due.push(PULSE_MS - (Date.now() - lastTurnAt));
@@ -1833,6 +1909,7 @@ async function resolveWakeCard(messages, { session }) {
1833
1909
  if (!wake.length) { if (freshBatch.kept.length) { savePending(pendingWake, pendingBcast); log(`${freshBatch.kept.length} broadcast(s) batched (no wake) — ${pendingBcast.length} pending`); } continue; }
1834
1910
  // Queue BEFORE running the turn, and persist immediately. Everything between here and a clean
1835
1911
  // exit 0 — the CLI dying, the machine losing power — now leaves a record of what this seat owes.
1912
+ stampWakeDelivery(wake);
1836
1913
  pendingWake.push(...wake);
1837
1914
  if (pendingWake.length > PENDING_MAX) {
1838
1915
  const dropped = pendingWake.splice(0, pendingWake.length - PENDING_MAX);
@@ -2203,6 +2280,10 @@ async function resolveWakeCard(messages, { session }) {
2203
2280
  if (reason === "exhausted") quotaReset = quotaResetAt(rows);
2204
2281
  }
2205
2282
  savePending(pendingWake, pendingBcast);
2283
+ if (reason === "crashed" && lastFailureTail && sessionCard > 0) {
2284
+ const note = `turn failed with an unrecognized error (exit ${ec}); redacted stderr tail:\n${lastFailureTail.slice(-1600)}`;
2285
+ await api("/task/update", { id: sessionCard, note, by: SESSION }).catch(() => {});
2286
+ }
2206
2287
  await reportFailure(ec, "message", pendingWake.length, reason);
2207
2288
  // #6289: TWO consecutive failed turns on one contract PARK the seat — "stalled" for a
2208
2289
  // silent chain (#7752), time-box when the chain died to cuts, api-error otherwise —
package/bin/disk.mjs CHANGED
@@ -8,6 +8,7 @@ import { fileURLToPath } from "node:url";
8
8
  import { mkdirSync, writeFileSync } from "node:fs";
9
9
  import { homedir, platform, userInfo } from "node:os";
10
10
  import { runDisk, formatHuman, launchdPlist, diskSummary } from "../lib/disk.mjs";
11
+ import { reloadLaunchAgent } from "../lib/launchd.mjs";
11
12
 
12
13
  const ROOT = dirname(dirname(fileURLToPath(import.meta.url)));
13
14
 
@@ -38,13 +39,15 @@ async function install() {
38
39
  const logPath = join(homedir(), ".agent-bus", "disk-launchd.log");
39
40
  mkdirSync(agentDir, { recursive: true });
40
41
  mkdirSync(dirname(logPath), { recursive: true });
41
- writeFileSync(plistPath, launchdPlist({ nodePath: process.execPath, scriptPath: join(ROOT, "bin", "disk.mjs"), logPath }));
42
+ writeFileSync(plistPath, launchdPlist({ scriptPath: join(ROOT, "bin", "disk.mjs"), logPath }));
42
43
  const uid = userInfo().uid;
43
- exec("launchctl", ["bootout", `gui/${uid}/com.trantor.disk`]);
44
- const r = exec("launchctl", ["bootstrap", `gui/${uid}`, plistPath]);
45
- if (r.status !== 0) {
46
- // bootout+bootstrap can race an existing job; load -w is the legacy fallback.
47
- exec("launchctl", ["load", "-w", plistPath]);
44
+ // #14661: reload through bootout-wait-bootstrap; if launchd still refuses, the legacy load -w is
45
+ // the fallback — and a bootstrap that fails BOTH ways is an error, never a quiet "installed".
46
+ const launchctl = (argv) => { const r = exec("launchctl", argv); return { status: r.status ?? 1, stdout: String(r.stdout || "") }; };
47
+ const reloaded = reloadLaunchAgent({ label: "com.trantor.disk", plist: plistPath, domain: `gui/${uid}`, launchctl });
48
+ if (!reloaded.ok && exec("launchctl", ["load", "-w", plistPath]).status !== 0) {
49
+ console.error(`trantor disk install: launchctl refused ${plistPath} (bootstrap and load -w both failed) — the daily job is NOT installed`);
50
+ process.exit(1);
48
51
  }
49
52
  console.log(`installed: ${plistPath}\nruns every day at 09:00 (safe tier only); result lands as one bus message. Log: ${logPath}`);
50
53
  }
package/bin/doctor.mjs CHANGED
@@ -8,7 +8,7 @@ import { join, dirname, basename } from "node:path";
8
8
  import { homedir } from "node:os";
9
9
  import { execSync } from "node:child_process";
10
10
  import { fileURLToPath } from "node:url";
11
- import { resolveProject, resolveProjectInfo, resolveHub, DEFAULT_HUB_URL, gitRoot, readProjectId, checkoutFor, localCheckoutFor, orchSessionsPath, PROJECT_MARKER } from "../lib/project.mjs";
11
+ import { resolveProject, resolveProjectInfo, resolveHub, DEFAULT_HUB_URL, gitRoot, readProjectId, checkoutFor, localCheckoutFor, orchSessionsPath, PROJECT_MARKER, busDir as resolveBusDir } from "../lib/project.mjs";
12
12
  import { loadOrCreate } from "../lib/identity.mjs";
13
13
  import { sfetchJson } from "../lib/signed-fetch.mjs";
14
14
  import { scan } from "../lib/splitbrain.mjs";
@@ -18,6 +18,8 @@ import { probeClaudeIntegration, HERDR_CLAUDE_INSTALL } from "../lib/herdr-integ
18
18
  import { ensureHerdrSigned, HERDR_SIGN_IDENTIFIER, probeHerdrSigning } from "../lib/herdr-signing.mjs";
19
19
  import { herdrBin } from "./herdr-agent.mjs";
20
20
  import { axeDoctorStatus } from "../lib/sim/axe-status.mjs";
21
+ import { plistPinnedPaths, scriptPinnedPaths, launcherPathFindings } from "../lib/launch-node.mjs";
22
+ import { canaryDoctorRows, readLastRun, CANARY_LABEL } from "../lib/canary/canary.mjs";
21
23
 
22
24
  const H = homedir();
23
25
  const ROOT = dirname(dirname(fileURLToPath(import.meta.url)));
@@ -138,6 +140,39 @@ section("duty seat (the fleet watcher)");
138
140
  const FIX_UP = "trantor duty up (installs the launchd keepalive com.trantor.duty, which relaunches the seat after a crash or reboot)";
139
141
  let pid = 0;
140
142
  try { pid = Number(readFileSync(join(BUSD, "duty.pid"), "utf8")) || 0; if (pid) process.kill(pid, 0); else pid = 0; } catch { pid = 0; }
143
+ // #14646: ALIVE is not AWAKE. The duty process once sat up for three days on a node binary a
144
+ // Homebrew upgrade had deleted mid-flight — it lost the hub, parked, and took no turn while
145
+ // looking healthy. The runner's turn log is on disk and survives the process: the one witness
146
+ // that does not go down with the hub. A seat that is up must have turned within 24h.
147
+ if (pid) {
148
+ let lastTurn = 0, lastBoot = 0;
149
+ try {
150
+ for (const f of readdirSync(join(BUSD, "logs")).filter(n => n.endsWith("-trantor-duty.jsonl"))) {
151
+ for (const line of readFileSync(join(BUSD, "logs", f), "utf8").split("\n")) {
152
+ if (!line) continue;
153
+ try {
154
+ const row = JSON.parse(line);
155
+ if (!Number.isFinite(row.ts)) continue;
156
+ if (row.boot) lastBoot = Math.max(lastBoot, row.ts);
157
+ if (Number.isInteger(row.turn) && row.turn > 0) lastTurn = Math.max(lastTurn, row.ts);
158
+ } catch {}
159
+ }
160
+ }
161
+ } catch {}
162
+ const ago = (ms) => ms < 60e3 ? `${Math.max(1, Math.round(ms / 60e3))}m` : ms < 3600e3 ? `${Math.round(ms / 60e3)}m` : ms < 86400e3 ? `${Math.round(ms / 3600e3)}h` : `${Math.round(ms / 86400e3)}d`;
163
+ const when = (ts) => `${new Date(ts).toISOString().slice(0, 16).replace("T", " ")} UTC`;
164
+ if (lastTurn && Date.now() - lastTurn <= 24 * 3600e3) {
165
+ ok(`duty seat: turned ${ago(Date.now() - lastTurn)} ago (${when(lastTurn)})`);
166
+ } else if (!lastTurn && lastBoot && Date.now() - lastBoot < 10 * 60e3) {
167
+ note(`duty seat: restarted ${ago(Date.now() - lastBoot)} ago — no turn yet (the kickoff lands within minutes)`);
168
+ } else if (lastTurn) {
169
+ warn(`duty seat: ALIVE but turnless — the process is up (pid ${pid}) yet its last turn was ${ago(Date.now() - lastTurn)} ago (${when(lastTurn)}); nothing has triaged the fleet since`,
170
+ "trantor duty up (a seat that is up but not turning is parked or hub-lost; a restart revives it)");
171
+ } else {
172
+ warn(`duty seat: process up (pid ${pid}) but NO turn on record — it has never woken`,
173
+ "trantor duty up (restart it; the kickoff turn should land within minutes)");
174
+ }
175
+ }
141
176
  const keepalive = existsSync(DUTY_PLIST);
142
177
  // The seat watches the FLEET hub — the most common project hub in config, the exact pick
143
178
  // bin/duty.mjs makes — not necessarily THIS project's hub.
@@ -179,6 +214,63 @@ section("duty seat (the fleet watcher)");
179
214
  }
180
215
  }
181
216
 
217
+ // ── launch agents: every com.trantor.* job must still have a program to run ───────────────────
218
+ // #14646: a Homebrew node upgrade deletes the versioned Cellar path older launchers pinned, and
219
+ // launchd restarts the job into exit 126 — the seat dies silently while everything else looks
220
+ // installed. Pinned paths must exist now, and a /Cellar/ path is wrong even while it survives.
221
+ section("launch agents (com.trantor.*)");
222
+ {
223
+ const AGENTS_DIR = join(H, "Library", "LaunchAgents");
224
+ const AGENT_FIX = {
225
+ "com.trantor.duty": "trantor duty up (rewrites the duty launcher to resolve node at exec time)",
226
+ "com.trantor.wake-nudge": "trantor duty up (reinstalls the wake-nudge keepalive)",
227
+ "com.trantor.disk": "trantor disk install (rewrites the daily disk janitor job)",
228
+ "com.trantor.herdr": "trantor herdr install (rewrites herdr's login agent and restore script)",
229
+ "com.trantor.seats": "trantor seats login install (rewrites the seat-restore login job)",
230
+ "com.trantor.hub": "bash deploy/setup.sh (reinstalls the hub service, which resolves node at exec time)",
231
+ };
232
+ const REPORT_FAULT = (name, finding, fix) => {
233
+ const message = finding.kind === "cellar"
234
+ ? `pins a versioned Homebrew Cellar path — ${finding.path} (the next brew upgrade deletes it; launchd restarts the job into exit 126)`
235
+ : `program path does not exist — ${finding.path} (a Homebrew node upgrade deletes versioned paths)`;
236
+ warn(`${name}: ${message}`, fix);
237
+ };
238
+ let agents = 0, faults = 0;
239
+ if (!existsSync(AGENTS_DIR)) {
240
+ note("launch agents: no ~/Library/LaunchAgents on this machine (launchd is macOS-only) — nothing to check");
241
+ } else {
242
+ for (const f of readdirSync(AGENTS_DIR).filter(n => /^com\.trantor\..+\.plist$/.test(n)).sort()) {
243
+ const label = f.replace(/\.plist$/, "");
244
+ const fix = AGENT_FIX[label] || `re-run the command that installed ${label}`;
245
+ let text = "";
246
+ try { text = readFileSync(join(AGENTS_DIR, f), "utf8"); } catch { continue; }
247
+ agents++;
248
+ for (const finding of launcherPathFindings(plistPinnedPaths(text))) { REPORT_FAULT(label, finding, fix); faults++; }
249
+ }
250
+ if (!agents) note("launch agents: no com.trantor.* jobs installed in ~/Library/LaunchAgents (the duty keepalive, disk janitor and hub service each add one)");
251
+ }
252
+ // The two launcher scripts a plist execs carry their node INSIDE, not in ProgramArguments —
253
+ // the plist only proves the script exists; the script must prove its own programs do. They are
254
+ // checked even without LaunchAgents: a --window duty seat has a launcher but no plist.
255
+ const scripts = [
256
+ ["duty launcher (duty-launch.sh)", join(H, ".agent-bus", "duty-launch.sh"), AGENT_FIX["com.trantor.duty"]],
257
+ ["herdr restore script (trantor-herdr-restore.sh)", join(AGENTS_DIR, "trantor-herdr-restore.sh"), AGENT_FIX["com.trantor.herdr"]],
258
+ ];
259
+ for (const [name, path, fix] of scripts) {
260
+ if (!existsSync(path)) continue;
261
+ let text = "";
262
+ try { text = readFileSync(path, "utf8"); } catch { continue; }
263
+ for (const finding of launcherPathFindings(scriptPinnedPaths(text))) { REPORT_FAULT(name, finding, fix); faults++; }
264
+ }
265
+ if (agents && !faults) ok(`every com.trantor.* launch agent's program path exists (${agents} agent${agents === 1 ? "" : "s"})`);
266
+ }
267
+
268
+ // #14655: the feature canary's last run, so a feature that went dark shows up here too.
269
+ section("feature canary");
270
+ for (const row of canaryDoctorRows({ lastRun: readLastRun(resolveBusDir()), installed: existsSync(join(H, "Library", "LaunchAgents", `${CANARY_LABEL}.plist`)) })) {
271
+ row.level === "ok" ? ok(row.message) : row.level === "note" ? note(row.message) : warn(row.message, row.fix);
272
+ }
273
+
182
274
  // claude plugin
183
275
  section("claude (the orchestrator)");
184
276
  if (!has("claude")) warn("claude CLI not found", "install Claude Code: https://claude.com/claude-code");
package/bin/duty.mjs CHANGED
@@ -20,6 +20,7 @@ import { homedir } from "node:os";
20
20
  import { fileURLToPath } from "node:url";
21
21
  import { loadOrCreate } from "../lib/identity.mjs";
22
22
  import { sfetchJson } from "../lib/signed-fetch.mjs";
23
+ import { nodeResolverSnippet } from "../lib/launch-node.mjs";
23
24
 
24
25
  const ROOT = dirname(dirname(fileURLToPath(import.meta.url)));
25
26
  const BUS = process.env.AGENT_BUS_DIR || join(homedir(), ".agent-bus");
@@ -166,11 +167,13 @@ function keepalivePlistBody() {
166
167
  }
167
168
 
168
169
  // A launcher carries the rules because their quotes, backticks and dollar signs cannot safely ride
169
- // a command line. Single-quote every value so bash 3.2 treats them literally.
170
+ // a command line. Single-quote every value so bash 3.2 treats them literally. #14646: the node is
171
+ // resolved at EXEC time (command -v node against the PATH exported above) — a pinned execPath is
172
+ // a versioned Homebrew Cellar path that `brew upgrade node` deletes out from under launchd.
170
173
  function writeLauncher(env) {
171
174
  const shquote = (v) => `'${String(v).replace(/'/g, `'\\''`)}'`;
172
175
  const exports = Object.entries(env).map(([k, v]) => `export ${k}=${shquote(v)}`).join("\n");
173
- writeFileSync(LAUNCHER, `#!/bin/bash\n# written by \`trantor duty up\` — safe to delete when the seat is down\n${exports}\nexec ${JSON.stringify(process.execPath)} ${JSON.stringify(join(ROOT, "bin", "crew-runner.mjs"))} ${AGENT} ${JSON.stringify(DIR)}\n`, { mode: 0o700 });
176
+ writeFileSync(LAUNCHER, `#!/bin/bash\n# written by \`trantor duty up\` — safe to delete when the seat is down\n${exports}\n${nodeResolverSnippet()}\nexec "$NODE_BIN" ${shquote(join(ROOT, "bin", "crew-runner.mjs"))} ${shquote(AGENT)} ${shquote(DIR)}\n`, { mode: 0o700 });
174
177
  }
175
178
 
176
179
  // The old headless start: a detached child of whoever ran `up`. No keepalive — it dies with a
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env node
2
+ import { signedGet } from "../hooks/lib/api.mjs";
3
+ import { aggregateFitness, formatFitness } from "../lib/fitness.mjs";
4
+
5
+ const args = process.argv.slice(2);
6
+ const at = args.indexOf("--project");
7
+ const project = at >= 0 ? String(args[at + 1] || "") : "";
8
+ const query = `?limit=1000${project ? `&project=${encodeURIComponent(project)}` : ""}`;
9
+ const response = await signedGet(`/telemetry/attempts${query}`, { project: project || undefined, timeoutMs: 5000 });
10
+ if (!response.ok || !Array.isArray(response.json?.attempts)) {
11
+ console.error(`fitness unavailable: ${response.json?.error || response.reason || `hub ${response.status}`}`);
12
+ process.exit(1);
13
+ }
14
+ const report = aggregateFitness(response.json.attempts);
15
+ console.log(args.includes("--json") ? JSON.stringify(report, null, 2) : formatFitness(report));
@@ -7,6 +7,7 @@ import { homedir } from "node:os";
7
7
  import { join, dirname } from "node:path";
8
8
  import { fileURLToPath } from "node:url";
9
9
  import { HERDR_SIGN_IDENTIFIER, ensureHerdrSigned } from "../lib/herdr-signing.mjs";
10
+ import { nodeResolverSnippet } from "../lib/launch-node.mjs";
10
11
 
11
12
  const LABEL = "com.trantor.herdr";
12
13
  const PLIST = join(homedir(), "Library", "LaunchAgents", `${LABEL}.plist`);
@@ -30,12 +31,17 @@ export function herdrBin() {
30
31
  return "";
31
32
  }
32
33
 
33
- export function restoreScriptBody({ herdr = "herdr", node = process.execPath, cli = join(dirname(fileURLToPath(import.meta.url)), "cli.mjs"), log = RESTORE_LOG } = {}) {
34
+ // #14646: node is resolved at EXEC time — `command -v node` against the PATH exported below,
35
+ // then the stable Homebrew/Intel symlinks. The old default pinned `process.execPath`, which under
36
+ // Homebrew is a versioned Cellar path that `brew upgrade node` deletes.
37
+ export function restoreScriptBody({ herdr = "herdr", cli = join(dirname(fileURLToPath(import.meta.url)), "cli.mjs"), log = RESTORE_LOG } = {}) {
34
38
  return `#!/bin/bash
39
+ PATH="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin\${PATH:+:\$PATH}"
40
+ export PATH
35
41
  HERDR_BIN=\${TRANTOR_HERDR_BIN:-${shellQuote(herdr)}}
36
- NODE_BIN=\${TRANTOR_NODE_BIN:-${shellQuote(node)}}
37
42
  TRANTOR_CLI=\${TRANTOR_CLI_PATH:-${shellQuote(cli)}}
38
43
  RESTORE_LOG=\${TRANTOR_RESTORE_LOG:-${shellQuote(log)}}
44
+ ${nodeResolverSnippet({ override: "TRANTOR_NODE_BIN" })}
39
45
  MARKER_DIR=\${TRANTOR_RESTORE_MARKER_DIR:-/tmp}
40
46
  BOOT_KEY=\${TRANTOR_RESTORE_BOOT_KEY:-$(/usr/sbin/sysctl -n kern.boottime 2>/dev/null | sed -E 's/.*sec = ([0-9]+).*/\\1/')}
41
47
  WAIT_SECONDS=\${TRANTOR_RESTORE_WAIT_SECONDS:-60}
package/bin/models.mjs CHANGED
@@ -5,7 +5,8 @@ import { dirname, join } from "node:path";
5
5
  import { homedir } from "node:os";
6
6
  import { existsSync, statSync } from "node:fs";
7
7
  import { pathToFileURL, fileURLToPath } from "node:url";
8
- import { buildRoster, loadWorld } from "./advise.mjs";
8
+ import { loadWorld } from "./advise.mjs";
9
+ import { discoverModels } from "../lib/discovery/index.mjs";
9
10
 
10
11
  const H = homedir();
11
12
  const C = { dim: "\x1b[2m", grn: "\x1b[32m", gold: "\x1b[38;5;208m", off: "\x1b[0m" };
@@ -16,11 +17,6 @@ const SCROOGE = (() => {
16
17
  try { return execSync("command -v scrooge", { encoding: "utf8" }).trim(); } catch { return "scrooge"; }
17
18
  })();
18
19
 
19
- const liveModels = (providerOc) => {
20
- try { return execSync(`opencode models ${providerOc} 2>/dev/null`, { encoding: "utf8" }).split("\n").filter(Boolean); }
21
- catch { return []; }
22
- };
23
-
24
20
  function routePick(candList, diff) {
25
21
  const result = spawnSync("python3", [SCROOGE, "route", "--candidates", candList.join(" "),
26
22
  "-t", "code", "-d", diff, "--json"], { encoding: "utf8" });
@@ -28,41 +24,76 @@ function routePick(candList, diff) {
28
24
  catch { return { error: "router unavailable", unpriced: [] }; }
29
25
  }
30
26
 
31
- function listAll() {
32
- const { roster, agents } = loadWorld();
33
- if (!has("opencode")) { console.log("opencode not on PATH — it's the adapter that serves crew models. Install it, then re-run."); return; }
34
- console.log("CREW MODELS — opencode-driven seats (● available now)\n");
27
+ const liveModels = (providerOc) => {
28
+ const result = spawnSync("opencode", ["models", providerOc], { encoding: "utf8" });
29
+ return result.status === 0 ? result.stdout.split("\n").filter(Boolean) : [];
30
+ };
31
+
32
+ function listAll({ roster, agents }, output) {
33
+ if (!has("opencode")) { output("opencode not on PATH — it's the adapter that serves crew models. Install it, then re-run."); return; }
34
+ output("CREW MODELS — opencode-driven seats (● available now)\n");
35
35
  for (const [label, s] of Object.entries(roster)) {
36
36
  if (s.cli !== "opencode") continue;
37
37
  const n = liveModels(s.providerOc).length;
38
38
  const dot = agents.includes(label) ? `${C.grn}●${C.off}` : `${C.dim}○${C.off}`;
39
- console.log(` ${dot} ${label.padEnd(14)} ${C.dim}${s.providerOc}${C.off} ${n} live models ${C.dim}trantor models ${label}${C.off}`);
39
+ output(` ${dot} ${label.padEnd(14)} ${C.dim}${s.providerOc}${C.off} ${n} live models ${C.dim}trantor models ${label}${C.off}`);
40
40
  }
41
- console.log(`\n${C.dim}detail + routing preview:${C.off} trantor models <provider>`);
41
+ output(`\n${C.dim}detail + routing preview:${C.off} trantor models <provider>`);
42
42
  }
43
43
 
44
- function detail(name) {
45
- const { roster } = loadWorld();
44
+ function detail(name, { roster }, output) {
46
45
  const seat = roster[name] || Object.values(roster).find(s => s.providerOc === name);
47
46
  const providerOc = seat?.providerOc || name;
48
47
  const models = liveModels(providerOc);
49
- if (!models.length) { console.log(`No live models for '${providerOc}' (opencode offline / no key / unknown provider).`); return; }
50
- console.log(`${C.gold}${providerOc}${C.off} — ${models.length} live models\n`);
48
+ if (!models.length) { output(`No live models for '${providerOc}' (opencode offline / no key / unknown provider).`); return; }
49
+ output(`${C.gold}${providerOc}${C.off} — ${models.length} live models\n`);
51
50
  const picks = Object.fromEntries(["easy", "medium", "hard"].map(d => [d, routePick(models, d)]));
52
51
  const unpriced = new Set(Object.values(picks).flatMap(p => p.unpriced || []));
53
- for (const m of models.slice(0, 60)) console.log(` ${m}${unpriced.has(m.split("/").at(-1)) ? " (unpriced)" : ""}`);
54
- if (models.length > 60) console.log(` ${C.dim}… +${models.length - 60} more${C.off}`);
52
+ for (const m of models.slice(0, 60)) output(` ${m}${unpriced.has(m.split("/").at(-1)) ? " (unpriced)" : ""}`);
53
+ if (models.length > 60) output(` ${C.dim}… +${models.length - 60} more${C.off}`);
55
54
  if (existsSync(SCROOGE) || has("scrooge")) {
56
- console.log(`\n${C.gold}router picks (code task):${C.off}`);
57
- for (const d of ["easy", "medium", "hard"]) console.log(` ${d.padEnd(7)} → ${picks[d].qualified || picks[d].error}`);
55
+ output(`\n${C.gold}router picks (code task):${C.off}`);
56
+ for (const d of ["easy", "medium", "hard"]) output(` ${d.padEnd(7)} → ${picks[d].qualified || picks[d].error}`);
58
57
  const caps = join(process.env.SCROOGE_HOME || join(H, ".token-scrooge"), "capabilities.json");
59
58
  // only nag when the scores are missing or older than the weekly refresh allows for
60
59
  const ageDays = existsSync(caps) ? (Date.now() - statSync(caps).mtimeMs) / 86400e3 : Infinity;
61
- if (ageDays > 9) console.log(`${C.dim}(scores ${ageDays === Infinity ? "missing" : `${Math.floor(ageDays)}d old`} — run scrooge-capabilities to (re)score the catalog for accurate difficulty routing)${C.off}`);
60
+ if (ageDays > 9) output(`${C.dim}(scores ${ageDays === Infinity ? "missing" : `${Math.floor(ageDays)}d old`} — run scrooge-capabilities to (re)score the catalog for accurate difficulty routing)${C.off}`);
61
+ }
62
+ }
63
+
64
+ export function formatModels(rows) {
65
+ return rows.map(row => {
66
+ const lines = row.models.map(model =>
67
+ ` ${model.id ?? "?"} [${model.state}]\n source: ${model.source}\n checkedAt: ${model.checkedAt}\n ${model.reason}`);
68
+ return `${row.provider}\n${lines.join("\n")}`;
69
+ }).join("\n\n");
70
+ }
71
+
72
+ export async function runModels(args, options = {}) {
73
+ const flags = new Set(["--all", "--json", "--refresh", "--no-cache"]);
74
+ if (args.some(arg => arg.startsWith("-") && !flags.has(arg))) throw new Error("Usage: trantor models [provider | --all] [--json] [--refresh] [--no-cache]");
75
+ const names = args.filter(arg => !flags.has(arg));
76
+ if (names.length > 1 || (names.length && args.includes("--all"))) throw new Error("Choose one provider or --all");
77
+ const world = options.world ?? loadWorld();
78
+ const name = names[0]?.toLowerCase();
79
+ const output = options.output ?? console.log;
80
+ if (!args.includes("--all") && !args.includes("--json")) {
81
+ if (name) detail(name, world, output);
82
+ else listAll(world, output);
83
+ return;
62
84
  }
85
+ const seat = name && (world.roster[name] || Object.values(world.roster).find(item => item.provider === name || item.providerOc === name));
86
+ const provider = seat?.providerOc || seat?.provider || name;
87
+ const roster = provider && !Object.values(world.roster).some(item => item.providerOc === provider || item.provider === provider)
88
+ ? { ...world.roster, [provider]: { providerOc: provider } } : world.roster;
89
+ const rows = await discoverModels(roster, { ...options, refresh: args.includes("--refresh"),
90
+ cachePath: args.includes("--no-cache") ? false : options.cachePath });
91
+ const selected = provider ? rows.filter(row => row.provider === provider) : rows;
92
+ if (args.includes("--json")) { output(JSON.stringify(selected, null, 2)); return selected; }
93
+ output(formatModels(selected));
94
+ return selected;
63
95
  }
64
96
 
65
97
  if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
66
- const arg = process.argv[2];
67
- if (!arg) listAll(); else detail(arg.toLowerCase());
98
+ runModels(process.argv.slice(2)).catch(error => { console.error(error.message); process.exitCode = 1; });
68
99
  }