@join-pantheon/cli 0.37.2 → 0.38.0

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.
package/dist/relay.js CHANGED
@@ -9,6 +9,7 @@ import { badRemote, Inbound, isCatchAllDomain, isContinuationFor, LIMITS, newId,
9
9
  import { VERSION } from "./version.js";
10
10
  import { compareVersions, INSTALLER_MIN_CLI, isVersion, installerScript, InstallerGate } from "./installer.js";
11
11
  import { installerLine } from "./managed.js";
12
+ import { GeoIp, InstallStats, summarize } from "./install-stats.js";
12
13
  import { joinMd, onboardJson, onboardMd } from "./onboard-copy.js";
13
14
  import { Ledger, SpaceFull } from "./ledger.js";
14
15
  import { fingerprint, newNonce, verifyChallenge, verifyActivity, verifyAccount, verifyRead, verifyStatus, canonicalKey, actPayload, goalPayload, verifyBytes, verifyDelegate, canonicalJson } from "./identity.js";
@@ -438,9 +439,11 @@ const LOOP_WINDOW_MS = 60_000;
438
439
  function loopMs(ns) {
439
440
  return Math.max(0, Math.round((ns / 1e6 - LOOP_RESOLUTION_MS) * 100) / 100);
440
441
  }
442
+ const LINK_CLOSED = "Different words were typed here, so this link is closed. That's all: the 6-digit code in the same email still works. Give it to your coding agent.";
443
+ const LINK_GONE = "This link has expired (they last 10 minutes), a newer Pantheon email replaced it, or it was already used. Use the code in the newest Pantheon email, or ask your coding agent to send a new one.";
441
444
  const STORAGE_HELD = "the relay received this but has not saved it yet — its disk is refusing writes. It is kept, and reaches the team when the disk recovers; do not send it again.";
442
445
  export function backupExcludes(dir, keep) {
443
- const always = ["--exclude=*.tmp"];
446
+ const always = ["--exclude=*.tmp", "--exclude=./geoip"];
444
447
  if (!keep)
445
448
  return always;
446
449
  let names = [];
@@ -706,6 +709,9 @@ export class Relay {
706
709
  recoveryWaitMs;
707
710
  backupTimer;
708
711
  installerGate;
712
+ installStats = null;
713
+ geo = null;
714
+ geoTimer = null;
709
715
  upgradeHold;
710
716
  get features() { return this.opts.features ?? RELAY_FEATURES; }
711
717
  constructor(opts = {}) {
@@ -773,6 +779,14 @@ export class Relay {
773
779
  }
774
780
  this.upgradeHold = upgradeHoldFrom(opts.upgradeHoldAt ?? process.env.PANTHEON_HOLD_UPGRADES_AT, VERSION, this.log);
775
781
  this.installerGate = opts.installerGate ?? new InstallerGate({ log: this.log, ...(this.upgradeHold ? { version: this.upgradeHold } : {}) });
782
+ try {
783
+ if ((process.env.PANTHEON_GEOIP ?? "").trim().toLowerCase() === "dbip")
784
+ this.geo = new GeoIp(join(this.dataDir, "geoip"), this.log);
785
+ this.installStats = new InstallStats(join(this.dataDir, "install-stats"), this.geo);
786
+ }
787
+ catch (e) {
788
+ this.log(`! installer downloads will not be counted here: ${e.message}`);
789
+ }
776
790
  this.busyTtlMs = opts.activityBusyTtlMs ?? LIMITS.activityBusyTtlMs;
777
791
  this.pruneMs = opts.activityPruneMs ?? LIMITS.activityPruneMs;
778
792
  const readsEnv = (process.env.PANTHEON_READS ?? "").trim().toLowerCase();
@@ -802,6 +816,12 @@ export class Relay {
802
816
  this.loopTimer = setInterval(() => this.rotateLoopWindow(), LOOP_WINDOW_MS);
803
817
  this.loopTimer.unref?.();
804
818
  this.startBackups();
819
+ if (this.geo) {
820
+ const geo = this.geo;
821
+ void geo.start().catch((e) => this.log(`geoip: ${e.message}`));
822
+ this.geoTimer = setInterval(() => { void geo.refresh().catch(() => { }); }, 86_400_000);
823
+ this.geoTimer.unref?.();
824
+ }
805
825
  const addr = this.http.address();
806
826
  const port = typeof addr === "object" && addr ? addr.port : want;
807
827
  resolve({ port, host });
@@ -810,6 +830,10 @@ export class Relay {
810
830
  }
811
831
  async close() {
812
832
  this.closing = true;
833
+ if (this.geoTimer) {
834
+ clearInterval(this.geoTimer);
835
+ this.geoTimer = null;
836
+ }
813
837
  for (const ws of this.wss.clients)
814
838
  ws.terminate();
815
839
  await new Promise((r) => this.wss.close(() => r()));
@@ -954,7 +978,7 @@ export class Relay {
954
978
  if (url.pathname === "/install.sh" || url.pathname === "/install.ps1") {
955
979
  if (req.method !== "GET" && req.method !== "HEAD")
956
980
  return this.json(res, 405, { error: "GET only" });
957
- void this.serveInstaller(req, res, url.pathname.slice(1));
981
+ void this.serveInstaller(req, res, url.pathname.slice(1), ip);
958
982
  return;
959
983
  }
960
984
  if (url.pathname === "/onboard.json" || url.pathname === "/skills/join.md" || url.pathname === "/skills/onboard.md") {
@@ -1361,11 +1385,11 @@ export class Relay {
1361
1385
  }
1362
1386
  const why = r.reason;
1363
1387
  if (why === "empty")
1364
- return this.confirmPage(res, t, { said: "Type the two words your screen or your coding agent shows." });
1365
- return this.confirmPage(res, "", { said: why === "wrong_words" ? "Those words do not match, so this link no longer works. The 6-digit code in the email still does."
1388
+ return this.confirmPage(res, t, { said: "Type the two words in capitals that your coding agent (or terminal) showed you. Don't have them? Give your coding agent the 6-digit code from the email instead." });
1389
+ return this.confirmPage(res, "", { said: why === "wrong_words" ? LINK_CLOSED
1366
1390
  : why === "links_locked" ? "Too many wrong words for this address in the last hour, so links are off for now. Use the 6-digit code from the email."
1367
1391
  : why === "device_other_account" ? DEVICE_OTHER_ACCOUNT
1368
- : "This link has expired or was already used. Use the 6-digit code from the email, or ask for a new one." });
1392
+ : LINK_GONE });
1369
1393
  });
1370
1394
  }
1371
1395
  if (url.pathname === "/auth/status" && req.method === "GET") {
@@ -1655,10 +1679,11 @@ export class Relay {
1655
1679
  <p>Only go on if you started this yourself, just now, on your own computer or through your own coding agent.</p>
1656
1680
  ${o.said ? `<p class="said">${esc(o.said)}</p>` : ""}
1657
1681
  <form method="post" action="/auth/confirm"><input type="hidden" name="t" value="${esc(token)}">
1658
- <label for="w">The two words your screen or your coding agent shows</label>
1682
+ <label for="w">The two words in capitals your coding agent (or terminal) showed you</label>
1659
1683
  <input id="w" name="words" autocomplete="off" autocapitalize="off" spellcheck="false" placeholder="two words">
1660
- <button type="submit">Confirm</button></form>`
1661
- : `<h1>This link does not work.</h1><p>${esc(o.said ?? "It has expired or was already used. Use the 6-digit code from the email, or ask for a new one.")}</p>`;
1684
+ <button type="submit">Confirm</button></form>
1685
+ <p>Don't have the two words? Close this page and give your coding agent the 6-digit code from the same email. It works just as well.</p>`
1686
+ : `<h1>This link does not work.</h1><p>${esc(o.said ?? (token && A.linkGone(token) === "closed" ? LINK_CLOSED : LINK_GONE))}</p>`;
1662
1687
  const html = `<!doctype html><meta charset=utf-8><meta name=viewport content="width=device-width,initial-scale=1"><meta name=referrer content=no-referrer><title>Pantheon sign-in</title>
1663
1688
  <style>body{font:16px/1.6 "Space Mono",Menlo,Consolas,monospace;background:#ece0c8;color:#1b1917;max-width:34rem;margin:10vh auto;padding:0 16px}h1{font:400 28px/1.15 "Archivo Black","Arial Black",Arial,sans-serif}label{display:block;margin:18px 0 6px}input{font:inherit;width:100%;box-sizing:border-box;padding:10px;border:2px solid #1b1917;border-radius:8px;background:#f1e7d3}button{margin-top:12px;font:inherit;font-weight:700;background:#e36f55;color:#1b1917;border:0;border-radius:8px;padding:10px 18px}.said{background:#f1e7d3;border-left:4px solid #b8492f;padding:8px 12px}</style>
1664
1689
  ${body}`;
@@ -3582,6 +3607,7 @@ ${body}`;
3582
3607
  name: e.member, agent: m?.agent ?? e.last_agent ?? "", founder: founder === e.member, admitted: e.admitted, mayWake: e.may_wake,
3583
3608
  online: present.length > 0, windows, busy: work ? work.busy : null,
3584
3609
  worker: w ? { state: w.state, ...(w.reason ? { reason: w.reason } : {}), at: w.at } : null,
3610
+ workerOn: present.some((s) => s.role === "worker"),
3585
3611
  build, behind: !!build && stuckBehind(build, relayPkg, now - this.startedAt),
3586
3612
  lastSeen: present.length ? now : (m?.last_seen || e.last_seen || null), unseen,
3587
3613
  reportsSince: ts.sp ? ts.sp.createdAt : null,
@@ -3866,7 +3892,7 @@ ${body}`;
3866
3892
  const safe = live ? safeName(live.name) : safeName(name);
3867
3893
  const key = safe.toLowerCase();
3868
3894
  const day = new Date(now).toISOString().slice(0, 10);
3869
- const sig = `${day}|${live ? (() => { const all = live.ledger.all(); return `live:${all.length}:${all.length ? all[all.length - 1].seq : 0}`; })() : await this.teamFilesSig(safe)}`;
3895
+ const sig = `${day}|${live ? (() => { const all = live.ledger.all(); return `live:${all.length}:${all.length ? all[all.length - 1].seq : 0}:${live.store.firstClaims.size}`; })() : await this.teamFilesSig(safe)}`;
3870
3896
  const hit = this.teamWeeksCache.get(key);
3871
3897
  if (hit && hit.sig === sig)
3872
3898
  return hit.v;
@@ -3918,7 +3944,7 @@ ${body}`;
3918
3944
  }
3919
3945
  const index = await flowIndexAsync(projected, 10_000);
3920
3946
  const createdAt = ts.allow.all().reduce((min, e) => (min === null || e.first_seen < min ? e.first_seen : min), null);
3921
- const v = await teamWeeksOfAsync({ name: ts.name, now, records: projected, usage: ts.usage, compactedThrough: ts.compactedThrough, createdAt, askers: [...askers], firstAskAt, lastActAt, index });
3947
+ const v = await teamWeeksOfAsync({ name: ts.name, now, records: projected, usage: ts.usage, compactedThrough: ts.compactedThrough, createdAt, askers: [...askers], firstAskAt, lastActAt, index, claims: ts.firstClaims.values() });
3922
3948
  let bytes = 2_000 + v.askers.length * 40;
3923
3949
  for (const w of v.people)
3924
3950
  bytes += w.length * 40;
@@ -4231,6 +4257,7 @@ ${body}`;
4231
4257
  backupAt, backupOkAt, snapshots,
4232
4258
  },
4233
4259
  founder, lastActive: Object.fromEntries(weeks.map((w) => [w.name, w.lastActiveAt])),
4260
+ installs: this.installSummary(now),
4234
4261
  sort: url?.searchParams.get("sort") ?? null, dir: url?.searchParams.get("dir") ?? null,
4235
4262
  accounts: {
4236
4263
  total: accounts.length, paid: Object.entries(planCounts).filter(([n]) => n !== "free").reduce((s, [, v]) => s + v, 0),
@@ -4479,7 +4506,22 @@ pantheon start</code></pre>
4479
4506
  <p>It asks for your email and sends you a 6-digit code (check spam if it does not arrive). Invited to a team? Use the line in your invite.</p>`}`);
4480
4507
  }
4481
4508
  startInstallerCheck() { this.installerGate.start(); }
4482
- async serveInstaller(req, res, name) {
4509
+ installSummary(now) {
4510
+ const st = this.installStats;
4511
+ if (!st)
4512
+ return null;
4513
+ try {
4514
+ const since = now - 30 * 86_400_000;
4515
+ const signIns = (this.accounts?.auditLog({ event: "session_created", sinceMs: since, limit: 20_000 }) ?? [])
4516
+ .filter((r) => !!r.ip).map((r) => ({ at: r.ts, net: st.netOf(r.ip) }));
4517
+ return summarize(st.read(since), signIns, now, !!this.geo?.ready);
4518
+ }
4519
+ catch (e) {
4520
+ this.log(`! installer downloads could not be read: ${e.message}`);
4521
+ return null;
4522
+ }
4523
+ }
4524
+ async serveInstaller(req, res, name, ip = "") {
4483
4525
  const plain = (code, body, extra = {}) => {
4484
4526
  res.writeHead(code, {
4485
4527
  "content-type": "text/plain; charset=utf-8",
@@ -4506,6 +4548,12 @@ pantheon start</code></pre>
4506
4548
  return plain(200, name === "install.sh" ? `#!/bin/sh\nprintf '%s\\n' '${sentence}' >&2\nexit 1\n` : `Write-Host '${sentence}' -ForegroundColor Red\nthrow 'Pantheon was not installed.'\n`, { "x-pantheon-installer": "unavailable" });
4507
4549
  }
4508
4550
  plain(200, body, { "x-pantheon-installs": choice.version });
4551
+ if (this.installStats && ip) {
4552
+ try {
4553
+ void this.installStats.record(this.installStats.event({ ip, file: name, method: req.method ?? "GET", version: choice.version, headers: req.headers }));
4554
+ }
4555
+ catch { }
4556
+ }
4509
4557
  }
4510
4558
  catch (e) {
4511
4559
  this.log(`! ${name} failed: ${e?.message ?? e}`);
@@ -5441,8 +5489,13 @@ pantheon start</code></pre>
5441
5489
  return fail("BAD_ACT_ID", `act id ${m.id} was not made in the last day — check this machine's clock`, m.cid);
5442
5490
  if (m.after_seq !== undefined) {
5443
5491
  const mine = me.id;
5444
- const missed = space.ledger.since(m.after_seq)
5492
+ const unseen = space.ledger.since(m.after_seq);
5493
+ const answered = new Set(unseen.filter((r) => r.from === mine && r.ref).map((r) => r.ref));
5494
+ if (m.ref)
5495
+ answered.add(m.ref);
5496
+ const missed = unseen
5445
5497
  .filter((r) => r.from !== mine && r.act !== "JOIN" && r.act !== "LEAVE")
5498
+ .filter((r) => !answered.has(r.id))
5446
5499
  .filter((r) => (m.goal ? r.goal === m.goal : !r.goal)
5447
5500
  || (r.to?.includes(mine) ?? false)
5448
5501
  || (m.to?.includes(r.from) ?? false)
package/dist/service.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { stopIsExpected } from "./crash-loop.js";
1
2
  import { writeFileSync, mkdirSync, existsSync, lstatSync, unlinkSync, readFileSync, renameSync, rmSync } from "node:fs";
2
3
  import { execFileSync } from "node:child_process";
3
4
  import { homedir, platform, userInfo } from "node:os";
@@ -277,6 +278,7 @@ export function installService(kind, cwd, args, sys = realSys()) {
277
278
  ensurePantheonHome();
278
279
  }
279
280
  catch { }
281
+ stopIsExpected(kind);
280
282
  if (sys.platform === "win32")
281
283
  return installWindows(kind, resolve(cwd), args, sys);
282
284
  const out = [];
@@ -366,6 +368,7 @@ export function installService(kind, cwd, args, sys = realSys()) {
366
368
  }
367
369
  export function uninstallService(kind, sys = realSys()) {
368
370
  const out = [];
371
+ stopIsExpected(kind);
369
372
  if (sys.platform === "win32") {
370
373
  const strays = unitPaths(kind, {}).filter((u) => existsSync(u));
371
374
  for (const u of strays)
@@ -417,6 +420,7 @@ export function uninstallService(kind, sys = realSys()) {
417
420
  return out;
418
421
  }
419
422
  export function disableService(kind, sys = realSys()) {
423
+ stopIsExpected(kind);
420
424
  if (sys.platform === "win32") {
421
425
  disableWindows(kind, sys);
422
426
  return;
@@ -465,6 +469,7 @@ export function restartService(kind, exec = realExec, opts = {}) {
465
469
  const st = serviceState(kind, exec, plat, uid);
466
470
  if (st.disabled)
467
471
  return [` ${kind}: left stopped (you stopped it) — start it again: pantheon service ${plat === "win32" ? "start" : "install"} ${kind}`];
472
+ stopIsExpected(kind);
468
473
  try {
469
474
  if (plat === "win32") {
470
475
  if (hostAlive(readHostState())) {
@@ -246,6 +246,11 @@ export function readChangeLog(home, head) {
246
246
  }
247
247
  return out;
248
248
  }
249
+ export function turnedOff(setting, entries = readChangeLog()) {
250
+ const took = entries.filter((e) => e.setting === setting && (e.outcome === "applied" || e.outcome === "approved" || e.outcome === "stopped"));
251
+ const last = took[took.length - 1];
252
+ return !!last && /^(off|none|stopped)\b/.test(last.to);
253
+ }
249
254
  export function lastChangeLine(home, now = Date.now()) {
250
255
  const done = readChangeLog(home).filter((e) => (e.outcome === "applied" || e.outcome === "approved") && e.setting !== FIRST_SETUP);
251
256
  const e = done[done.length - 1];
@@ -6,7 +6,7 @@ import { join } from "node:path";
6
6
  import { applyProfileInit, dropCatchAllClaims, loadProfile, profilePath, saveProfile, setupChosen, spaceOverride, teamProfile, wakeMode } from "./profile.js";
7
7
  import { isCatchAllDomain } from "./protocol.js";
8
8
  import { installService as realInstall, uninstallService as realUninstall, serviceInstalled as realInstalled, installedServiceArgs, keepServiceFlags } from "./service.js";
9
- import { unsandboxedRisk } from "./setup-changes.js";
9
+ import { turnedOff, unsandboxedRisk } from "./setup-changes.js";
10
10
  import { personaDir } from "./persona.js";
11
11
  import { hudBinaryPath } from "./notifier.js";
12
12
  import { hostEnv } from "./host-env.js";
@@ -33,8 +33,8 @@ export const MODE_OPTIONS = [
33
33
  { id: "here", label: `${MODE_LABELS.here} — requests wait while I'm at my computer, and my agent takes them when I'm away.` },
34
34
  ];
35
35
  export const ALERT_OPTIONS = [
36
- { id: "decisions", label: "Only decisions that need me (recommended) — never for ordinary agent traffic." },
37
- { id: "deliveries", label: "Decisions, and when a teammate delivers work to me." },
36
+ { id: "decisions", label: "Decisions that need me, replies to my own requests, and a teammate's request nothing here has picked up (recommended) — never for other agent traffic." },
37
+ { id: "deliveries", label: "Decisions, replies to my requests, and any work a teammate delivers to me." },
38
38
  { id: "worker", label: "Decisions, deliveries, and when my own worker finishes a run." },
39
39
  { id: "none", label: "None — I will look at pantheon status (and the menu bar, on a Mac)." },
40
40
  ];
@@ -581,6 +581,14 @@ export async function runGuide(io, ctx, deps = {}, preset = {}) {
581
581
  else
582
582
  applied.push("worker stays off");
583
583
  }
584
+ else if (serves && !installed("worker") && (() => { try {
585
+ return turnedOff("worker");
586
+ }
587
+ catch {
588
+ return false;
589
+ } })()) {
590
+ applied.push("worker stays off, as you set it — teammates' requests wait for you. To turn it on: pantheon service install worker");
591
+ }
584
592
  else if (serves) {
585
593
  try {
586
594
  const now = (deps.installedArgs ?? (deps.installService ? () => null : installedServiceArgs))("worker");
@@ -602,7 +610,12 @@ export async function runGuide(io, ctx, deps = {}, preset = {}) {
602
610
  : "wake permission: only people you approve on this machine — you are asked the first time each one needs it (approve ahead: pantheon wake allow <name>)");
603
611
  }
604
612
  else {
605
- applied.push(`worker: nothing is bound to "${ctx.cfg.space}" on this machine yet — from the folder you work in (a repo, or a folder of docs): pantheon use ${ctx.cfg.space} --here, then pantheon setup`);
613
+ applied.push(`worker: nothing is bound to "${ctx.cfg.space}" on this machine yet — this computer can't take teammates' requests until a folder is: from the folder you work in (a repo, or a folder of docs), run pantheon use ${ctx.cfg.space} --here${(() => { try {
614
+ return turnedOff("worker");
615
+ }
616
+ catch {
617
+ return false;
618
+ } })() ? " (your worker stays off, as you set it: pantheon service install worker turns it on)" : ", and the worker comes on with it"}`);
606
619
  }
607
620
  const names = awayAgents.length ? andList(awayAgents) : "Codex, Cursor and Copilot";
608
621
  const one = awayAgents.length === 1;
@@ -653,6 +666,14 @@ export async function runGuide(io, ctx, deps = {}, preset = {}) {
653
666
  else if (!mac && !linuxDesktop && !winDesktop) {
654
667
  applied.push(`alerts: none on this machine — desktop alerts run on macOS, Windows and Linux desktops, and this is ${os}. Decisions wait in ${waitIn} (your choice, ${chosenAlerts.toLowerCase()}, is saved)`);
655
668
  }
669
+ else if (!installed("notifier") && (() => { try {
670
+ return turnedOff("alerts");
671
+ }
672
+ catch {
673
+ return false;
674
+ } })()) {
675
+ applied.push(`alerts stay off, as you set them — decisions wait in ${waitIn}. To turn them on: pantheon service install notifier`);
676
+ }
656
677
  else {
657
678
  if (!installed("notifier") && (linuxDesktop || winDesktop)) {
658
679
  try {
@@ -153,7 +153,7 @@ export class StatusEngine {
153
153
  }
154
154
  export const HOME_FILES = new Set([
155
155
  "worker-state.json", "spend.json", "readiness-alert.json", "setup-pending.json", "worker-policy.json",
156
- "worker-declined.json", "run-control.json", "removed.json", "profile.json", "config.json",
156
+ "worker-declined.json", "run-control.json", "removed.json", "profile.json", "config.json", "service-starts.json",
157
157
  ]);
158
158
  export function watchNudges(o) {
159
159
  const watchers = [];
package/dist/tray.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { crashLoopLine } from "./crash-loop.js";
1
2
  import { effectiveMode, loadPolicy, safetyNotesLine } from "./worker-policy.js";
2
3
  import { loadPersistedGuard } from "./home-guard.js";
3
4
  import { askedByName, changeLabel, consequence, loadPending } from "./setup-changes.js";
@@ -518,8 +519,14 @@ function machineFields(cfg, workerRunning = running("worker")) {
518
519
  catch {
519
520
  return null;
520
521
  } })();
521
- const problem = agentIssue ?? held ?? safety;
522
- const lead = agentIssue ? PROBLEM_LEAD : held ? "Unattended runs are on hold" : "A safety warning could not reach your board";
522
+ const looping = agentIssue || held || safety ? null : (() => { try {
523
+ return crashLoopLine(CONFIG_DIR);
524
+ }
525
+ catch {
526
+ return null;
527
+ } })();
528
+ const problem = agentIssue ?? held ?? safety ?? looping;
529
+ const lead = agentIssue ? PROBLEM_LEAD : held ? "Unattended runs are on hold" : safety ? "A safety warning could not reach your board" : "Pantheon keeps stopping";
523
530
  return {
524
531
  worker_running: workerRunning,
525
532
  worker_installed: serviceInstalled("worker"),
@@ -0,0 +1,288 @@
1
+ import { homedir } from "node:os";
2
+ import { join } from "node:path";
3
+ import { readStateText, withFileLock } from "./file-lock.js";
4
+ import { atomicWrite, isNewer, ASK_EXPIRY_MS } from "./worker-policy.js";
5
+ import { installedVersion } from "./mcp-supervisor.js";
6
+ import { VERSION } from "./version.js";
7
+ import { BUDGET } from "./notice.js";
8
+ export const BEHIND_ALERT_AFTER_MS = 24 * 3_600_000;
9
+ export const GRANTED_STUCK_AFTER_MS = 72 * 3_600_000;
10
+ export const RELAY_PKG_REFRESH_MS = 60 * 60_000;
11
+ export const WORKER_CATCHING_UP_MS = 2 * 3_600_000;
12
+ export const versionHealthPath = (home) => join(home ?? process.env.PANTHEON_HOME ?? join(homedir(), ".pantheon"), "relay-version.json");
13
+ export function relayHttp(relay) {
14
+ return relay.trim().replace(/^ws(s?):/i, "http$1:").replace(/\/+$/, "");
15
+ }
16
+ export function relayKey(relay) { return relayHttp(relay).toLowerCase(); }
17
+ const isTime = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
18
+ const isPkg = (v) => typeof v === "string" && /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(v) && v.length <= 32;
19
+ export function readVersionHealth(home) {
20
+ const out = { relays: {} };
21
+ let raw;
22
+ try {
23
+ raw = JSON.parse(readStateText(versionHealthPath(home)));
24
+ }
25
+ catch {
26
+ return out;
27
+ }
28
+ if (!raw || typeof raw !== "object")
29
+ return out;
30
+ const relays = raw.relays && typeof raw.relays === "object" ? raw.relays : {};
31
+ for (const [k, v] of Object.entries(relays)) {
32
+ const r = v;
33
+ if (!r || !isPkg(r.pkg) || !isTime(r.seen_at))
34
+ continue;
35
+ out.relays[k] = { pkg: r.pkg, seen_at: r.seen_at, ...(isTime(r.behind_since) ? { behind_since: r.behind_since } : {}) };
36
+ }
37
+ if (raw.behind_alerted && typeof raw.behind_alerted === "object") {
38
+ const a = Object.fromEntries(Object.entries(raw.behind_alerted).filter(([k, v]) => isPkg(k) && isTime(v)));
39
+ if (Object.keys(a).length)
40
+ out.behind_alerted = a;
41
+ }
42
+ if (raw.upgrade_failed && typeof raw.upgrade_failed === "object") {
43
+ const f = {};
44
+ for (const [k, v] of Object.entries(raw.upgrade_failed)) {
45
+ const r = v;
46
+ if (isPkg(k) && r && isTime(r.at))
47
+ f[k] = { at: r.at, ...(isTime(r.alerted_at) ? { alerted_at: r.alerted_at } : {}) };
48
+ }
49
+ if (Object.keys(f).length)
50
+ out.upgrade_failed = f;
51
+ }
52
+ return out;
53
+ }
54
+ function update(home, fn) {
55
+ const file = versionHealthPath(home);
56
+ let result;
57
+ const write = () => {
58
+ const s = readVersionHealth(home);
59
+ result = fn(s);
60
+ if (s.behind_alerted)
61
+ s.behind_alerted = Object.fromEntries(Object.entries(s.behind_alerted).sort((a, b) => b[1] - a[1]).slice(0, 20));
62
+ if (s.upgrade_failed)
63
+ s.upgrade_failed = Object.fromEntries(Object.entries(s.upgrade_failed).sort((a, b) => b[1].at - a[1].at).slice(0, 20));
64
+ atomicWrite(file, JSON.stringify(s, null, 2) + "\n");
65
+ };
66
+ let ran = false;
67
+ try {
68
+ withFileLock(file, () => { ran = true; write(); }, 2_000);
69
+ }
70
+ catch (e) {
71
+ if (ran)
72
+ throw e;
73
+ write();
74
+ }
75
+ return result;
76
+ }
77
+ export function localVersion(installed = installedVersion()) {
78
+ return installed && isNewer(installed, VERSION) ? installed : VERSION;
79
+ }
80
+ export async function fetchRelayPkg(relay, timeoutMs = 3000) {
81
+ try {
82
+ const res = await fetch(`${relayHttp(relay)}/health`, { signal: AbortSignal.timeout(timeoutMs) });
83
+ const j = await res.json();
84
+ return typeof j.pkg === "string" && isPkg(j.pkg) ? j.pkg : null;
85
+ }
86
+ catch {
87
+ return null;
88
+ }
89
+ }
90
+ export function recordRelayPkg(relay, pkg, o = {}) {
91
+ if (!pkg || !isPkg(pkg))
92
+ return;
93
+ const now = o.now ?? Date.now();
94
+ const local = o.local ?? localVersion();
95
+ try {
96
+ update(o.home, (s) => {
97
+ const key = relayKey(relay);
98
+ const was = s.relays[key];
99
+ const behind = isNewer(pkg, local);
100
+ s.relays[key] = { pkg, seen_at: now, ...(behind ? { behind_since: was?.behind_since ?? now } : {}) };
101
+ });
102
+ }
103
+ catch { }
104
+ }
105
+ export async function refreshRelayPkg(relay, o = {}) {
106
+ const now = o.now ?? Date.now;
107
+ const seen = readVersionHealth(o.home).relays[relayKey(relay)];
108
+ if (seen && now() - seen.seen_at < (o.maxAgeMs ?? RELAY_PKG_REFRESH_MS))
109
+ return seen.pkg;
110
+ const pkg = await (o.fetchPkg ?? fetchRelayPkg)(relay);
111
+ recordRelayPkg(relay, pkg, { ...(o.home ? { home: o.home } : {}), ...(o.local ? { local: o.local } : {}), now: now() });
112
+ return pkg ?? seen?.pkg ?? null;
113
+ }
114
+ export function relayAhead(relay, o = {}) {
115
+ const seen = readVersionHealth(o.home).relays[relayKey(relay)];
116
+ if (!seen || !isNewer(seen.pkg, o.local ?? localVersion()))
117
+ return null;
118
+ return seen;
119
+ }
120
+ export function upgradeFailedOnce(pkg, o = {}) {
121
+ const now = o.now ?? Date.now();
122
+ try {
123
+ return update(o.home, (s) => {
124
+ const told = s.upgrade_failed?.[pkg]?.alerted_at;
125
+ const say = !told && o.canAlert !== false;
126
+ s.upgrade_failed = { ...(s.upgrade_failed ?? {}), [pkg]: { at: now, ...(told ? { alerted_at: told } : say ? { alerted_at: now } : {}) } };
127
+ return say;
128
+ });
129
+ }
130
+ catch {
131
+ return false;
132
+ }
133
+ }
134
+ export function composeUpgradeFailed(local, pkg, o = {}) {
135
+ const heading = "Pantheon couldn't update itself";
136
+ return {
137
+ kind: "worker_failed", who: "Your worker", heading, context: "",
138
+ body: fit(`Your team is on ${pkg}; this computer is still on ${local}, so teammates' requests can be missed. Run pantheon upgrade in a terminal: it says what stopped it.`),
139
+ ttl: 0, sound: false, tag: "pantheon_upgrade",
140
+ ...((o.os ?? process.platform) === "win32" ? {} : { fix: { label: "Show me how", dir: o.dir ?? homedir(), lines: ["pantheon upgrade"], why: heading } }),
141
+ };
142
+ }
143
+ export function composeBehind(local, pkg, o = {}) {
144
+ const heading = "Pantheon needs an update";
145
+ return {
146
+ kind: "worker", who: "Pantheon · this computer", heading, context: "",
147
+ body: fit(`This computer runs ${local}; your team is on ${pkg}, so teammates' requests can be missed. Run pantheon upgrade in a terminal, or ask your agent to.`),
148
+ ttl: 0, sound: false, tag: "pantheon_version",
149
+ ...((o.os ?? process.platform) === "win32" ? {} : { fix: { label: "Show me how", dir: o.dir ?? homedir(), lines: ["pantheon upgrade"], why: heading } }),
150
+ };
151
+ }
152
+ const fit = (s) => (s.length <= BUDGET.body ? s : `${s.slice(0, BUDGET.body - 1)}…`);
153
+ export function behindVerdict(seen, o) {
154
+ if (!isNewer(seen.pkg, o.local))
155
+ return { due: false, why: "current" };
156
+ if (o.state.behind_alerted?.[seen.pkg])
157
+ return { due: false, why: "said" };
158
+ if (o.state.upgrade_failed?.[seen.pkg]?.alerted_at)
159
+ return { due: false, why: "worker_said" };
160
+ if (o.policy?.upgradeHeld?.version === seen.pkg)
161
+ return { due: false, why: "worker_said" };
162
+ const since = seen.behind_since ?? seen.seen_at;
163
+ if (o.now - since < BEHIND_ALERT_AFTER_MS)
164
+ return { due: false, why: "waiting" };
165
+ const granted = !!o.policy?.grants.self_upgrade;
166
+ if (granted && !o.state.upgrade_failed?.[seen.pkg] && o.now - since < GRANTED_STUCK_AFTER_MS && o.workerRunning())
167
+ return { due: false, why: "worker_on_it" };
168
+ const ask = o.policy?.asks.self_upgrade;
169
+ if (!granted && ask && o.now - ask.at < ASK_EXPIRY_MS)
170
+ return { due: false, why: "asked" };
171
+ return { due: true };
172
+ }
173
+ export function markBehindSaid(pkgs, o = {}) {
174
+ if (!pkgs.length)
175
+ return;
176
+ const now = o.now ?? Date.now();
177
+ try {
178
+ update(o.home, (s) => { s.behind_alerted = { ...(s.behind_alerted ?? {}) }; for (const p of pkgs)
179
+ s.behind_alerted[p] ??= now; });
180
+ }
181
+ catch { }
182
+ }
183
+ export class VersionWatch {
184
+ o;
185
+ timer = null;
186
+ stopped = false;
187
+ constructor(o) {
188
+ this.o = o;
189
+ }
190
+ async tick() {
191
+ const now = this.o.now ?? Date.now;
192
+ const byKey = new Map();
193
+ for (const r of this.o.relays())
194
+ if (!byKey.has(relayKey(r)))
195
+ byKey.set(relayKey(r), r);
196
+ const relays = [...byKey.keys()];
197
+ const local = this.o.local?.() ?? localVersion();
198
+ for (const r of byKey.values())
199
+ await refreshRelayPkg(r, { ...(this.o.home ? { home: this.o.home } : {}), now, local, ...(this.o.fetchPkg ? { fetchPkg: this.o.fetchPkg } : {}) });
200
+ const state = readVersionHealth(this.o.home);
201
+ let policy = null;
202
+ try {
203
+ policy = this.o.policy();
204
+ }
205
+ catch {
206
+ policy = null;
207
+ }
208
+ const due = [];
209
+ const quiet = [];
210
+ let running;
211
+ const workerRunning = () => (running ??= safe(() => false, () => this.o.workerRunning()));
212
+ for (const r of relays) {
213
+ const seen = state.relays[r];
214
+ if (!seen)
215
+ continue;
216
+ const v = behindVerdict(seen, { local, now: now(), state, policy, workerRunning });
217
+ if (v.due)
218
+ due.push(seen.pkg);
219
+ else if (v.why === "worker_said")
220
+ quiet.push(seen.pkg);
221
+ }
222
+ if (quiet.length)
223
+ markBehindSaid(quiet, { ...(this.o.home ? { home: this.o.home } : {}), now: now() });
224
+ const pkgs = [...new Set(due)];
225
+ if (!pkgs.length || !this.o.alertsOn())
226
+ return { shown: [] };
227
+ const newest = pkgs.reduce((a, b) => (isNewer(b, a) ? b : a));
228
+ let ok = false;
229
+ try {
230
+ ok = await this.o.send(composeBehind(local, newest));
231
+ }
232
+ catch {
233
+ ok = false;
234
+ }
235
+ if (!ok) {
236
+ this.o.log(`! could not show the update alert (this computer ${local}, the team ${newest})`);
237
+ return { shown: [] };
238
+ }
239
+ markBehindSaid(pkgs, { ...(this.o.home ? { home: this.o.home } : {}), now: now() });
240
+ this.o.log(`> update alert: this computer runs ${local}, the team's relay ${newest}`);
241
+ return { shown: pkgs };
242
+ }
243
+ start() {
244
+ if (this.timer || this.stopped)
245
+ return;
246
+ const next = (ms) => {
247
+ this.timer = setTimeout(() => {
248
+ this.timer = null;
249
+ void this.tick().catch((e) => this.o.log(`! update check: ${e.message}`)).finally(() => { if (!this.stopped)
250
+ next(this.o.everyMs ?? 10 * 60_000); });
251
+ }, ms);
252
+ this.timer.unref?.();
253
+ };
254
+ next(this.o.firstAfterMs ?? 60_000);
255
+ }
256
+ stop() { this.stopped = true; if (this.timer)
257
+ clearTimeout(this.timer); this.timer = null; }
258
+ }
259
+ const safe = (fallback, fn) => { try {
260
+ return fn();
261
+ }
262
+ catch {
263
+ return fallback();
264
+ } };
265
+ export function behindStatusLine(o) {
266
+ const seen = o.seen;
267
+ if (!seen || !isNewer(seen.pkg, o.local))
268
+ return null;
269
+ const pkg = seen.pkg;
270
+ const held = o.policy?.upgradeHeld?.version === pkg ? o.policy.upgradeHeld : null;
271
+ if (held) {
272
+ return `PANTHEON IS OUT OF DATE HERE: this computer runs ${o.local}, the team's relay ${pkg}, and the update needs something only your human can do: ${held.why} ` +
273
+ `Tell them that in plain words; \`pantheon upgrade\` alone will not finish it.`;
274
+ }
275
+ const since = seen.behind_since ?? seen.seen_at;
276
+ const failed = !!o.state.upgrade_failed?.[pkg];
277
+ if (o.policy?.grants.self_upgrade && !failed && o.now - since < WORKER_CATCHING_UP_MS) {
278
+ return `pantheon ${o.local} here, the team's relay ${pkg}: this computer's worker updates it by itself within minutes — nothing to do unless your human asks.`;
279
+ }
280
+ if (!o.full)
281
+ return `pantheon is out of date here (${o.local}; the team is on ${pkg}) — offer your human the update; run \`pantheon upgrade\` once they say yes.`;
282
+ return [
283
+ `PANTHEON IS OUT OF DATE HERE: this computer runs ${o.local}; your team's relay runs ${pkg}.${failed ? " Its worker tried to update it and could not." : ""} Until it is updated, teammates' requests can be missed or handled wrongly.`,
284
+ `Tell your human in plain words, for example: "Pantheon on this computer is older than your team's (${o.local}, the team is on ${pkg}). Shall I update it? It takes a minute or two."`,
285
+ `If they say yes, run \`pantheon upgrade\` for them and tell them what it printed; then this window needs one reconnect (/mcp → pantheon → Reconnect, or open a new window). Do not update without their yes.`,
286
+ ].join("\n");
287
+ }
288
+ //# sourceMappingURL=version-health.js.map
package/dist/win-host.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { stopIsExpected } from "./crash-loop.js";
1
2
  import { spawn } from "node:child_process";
2
3
  import { appendFileSync, closeSync, existsSync, watch, linkSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
3
4
  import { createHash } from "node:crypto";
@@ -661,6 +662,7 @@ export function realHostIo(o = {}) {
661
662
  },
662
663
  kill: (child, pid) => {
663
664
  if (child !== "tray") {
665
+ stopIsExpected(child, { home });
664
666
  hardKill(pid);
665
667
  return;
666
668
  }