@join-pantheon/cli 0.37.3 → 0.38.1

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";
@@ -442,7 +443,7 @@ const LINK_CLOSED = "Different words were typed here, so this link is closed. Th
442
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.";
443
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.";
444
445
  export function backupExcludes(dir, keep) {
445
- const always = ["--exclude=*.tmp"];
446
+ const always = ["--exclude=*.tmp", "--exclude=./geoip"];
446
447
  if (!keep)
447
448
  return always;
448
449
  let names = [];
@@ -708,6 +709,9 @@ export class Relay {
708
709
  recoveryWaitMs;
709
710
  backupTimer;
710
711
  installerGate;
712
+ installStats = null;
713
+ geo = null;
714
+ geoTimer = null;
711
715
  upgradeHold;
712
716
  get features() { return this.opts.features ?? RELAY_FEATURES; }
713
717
  constructor(opts = {}) {
@@ -775,6 +779,14 @@ export class Relay {
775
779
  }
776
780
  this.upgradeHold = upgradeHoldFrom(opts.upgradeHoldAt ?? process.env.PANTHEON_HOLD_UPGRADES_AT, VERSION, this.log);
777
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
+ }
778
790
  this.busyTtlMs = opts.activityBusyTtlMs ?? LIMITS.activityBusyTtlMs;
779
791
  this.pruneMs = opts.activityPruneMs ?? LIMITS.activityPruneMs;
780
792
  const readsEnv = (process.env.PANTHEON_READS ?? "").trim().toLowerCase();
@@ -804,6 +816,12 @@ export class Relay {
804
816
  this.loopTimer = setInterval(() => this.rotateLoopWindow(), LOOP_WINDOW_MS);
805
817
  this.loopTimer.unref?.();
806
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
+ }
807
825
  const addr = this.http.address();
808
826
  const port = typeof addr === "object" && addr ? addr.port : want;
809
827
  resolve({ port, host });
@@ -812,6 +830,10 @@ export class Relay {
812
830
  }
813
831
  async close() {
814
832
  this.closing = true;
833
+ if (this.geoTimer) {
834
+ clearInterval(this.geoTimer);
835
+ this.geoTimer = null;
836
+ }
815
837
  for (const ws of this.wss.clients)
816
838
  ws.terminate();
817
839
  await new Promise((r) => this.wss.close(() => r()));
@@ -956,7 +978,7 @@ export class Relay {
956
978
  if (url.pathname === "/install.sh" || url.pathname === "/install.ps1") {
957
979
  if (req.method !== "GET" && req.method !== "HEAD")
958
980
  return this.json(res, 405, { error: "GET only" });
959
- void this.serveInstaller(req, res, url.pathname.slice(1));
981
+ void this.serveInstaller(req, res, url.pathname.slice(1), ip);
960
982
  return;
961
983
  }
962
984
  if (url.pathname === "/onboard.json" || url.pathname === "/skills/join.md" || url.pathname === "/skills/onboard.md") {
@@ -1045,7 +1067,9 @@ export class Relay {
1045
1067
  .filter((g) => isSettled(g, owedIn, now))
1046
1068
  .map((g) => ({ id: g.id, title: g.title, last_at: g.last_at }))
1047
1069
  : [];
1048
- return this.json(res, 200, { obligations: owed, closed_goals: closed, settled_goals, seq: space.ledger.head, worker_online, space_id: space.allow.spaceId(), members: this.members(space),
1070
+ const with_human = member ? [...space.obligations.values()].filter((o) => o.kind === "HUMAN" && o.owner === `human:${member}` && !!o.about).map((o) => o.about) : [];
1071
+ const worklist_goals = [...space.goals.values()].filter((g) => g.kind === "worklist" && g.state !== "CLOSED").map((g) => g.id);
1072
+ return this.json(res, 200, { obligations: owed, closed_goals: closed, settled_goals, with_human, worklist_goals, seq: space.ledger.head, worker_online, space_id: space.allow.spaceId(), members: this.members(space),
1049
1073
  ...(gate.reader ? { roster: this.roster(space), now: Date.now() } : {}) });
1050
1074
  }
1051
1075
  if (url.pathname === "/activity") {
@@ -3585,6 +3609,7 @@ ${body}`;
3585
3609
  name: e.member, agent: m?.agent ?? e.last_agent ?? "", founder: founder === e.member, admitted: e.admitted, mayWake: e.may_wake,
3586
3610
  online: present.length > 0, windows, busy: work ? work.busy : null,
3587
3611
  worker: w ? { state: w.state, ...(w.reason ? { reason: w.reason } : {}), at: w.at } : null,
3612
+ workerOn: present.some((s) => s.role === "worker"),
3588
3613
  build, behind: !!build && stuckBehind(build, relayPkg, now - this.startedAt),
3589
3614
  lastSeen: present.length ? now : (m?.last_seen || e.last_seen || null), unseen,
3590
3615
  reportsSince: ts.sp ? ts.sp.createdAt : null,
@@ -3869,7 +3894,7 @@ ${body}`;
3869
3894
  const safe = live ? safeName(live.name) : safeName(name);
3870
3895
  const key = safe.toLowerCase();
3871
3896
  const day = new Date(now).toISOString().slice(0, 10);
3872
- 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)}`;
3897
+ 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)}`;
3873
3898
  const hit = this.teamWeeksCache.get(key);
3874
3899
  if (hit && hit.sig === sig)
3875
3900
  return hit.v;
@@ -3921,7 +3946,7 @@ ${body}`;
3921
3946
  }
3922
3947
  const index = await flowIndexAsync(projected, 10_000);
3923
3948
  const createdAt = ts.allow.all().reduce((min, e) => (min === null || e.first_seen < min ? e.first_seen : min), null);
3924
- const v = await teamWeeksOfAsync({ name: ts.name, now, records: projected, usage: ts.usage, compactedThrough: ts.compactedThrough, createdAt, askers: [...askers], firstAskAt, lastActAt, index });
3949
+ 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() });
3925
3950
  let bytes = 2_000 + v.askers.length * 40;
3926
3951
  for (const w of v.people)
3927
3952
  bytes += w.length * 40;
@@ -4234,6 +4259,7 @@ ${body}`;
4234
4259
  backupAt, backupOkAt, snapshots,
4235
4260
  },
4236
4261
  founder, lastActive: Object.fromEntries(weeks.map((w) => [w.name, w.lastActiveAt])),
4262
+ installs: this.installSummary(now),
4237
4263
  sort: url?.searchParams.get("sort") ?? null, dir: url?.searchParams.get("dir") ?? null,
4238
4264
  accounts: {
4239
4265
  total: accounts.length, paid: Object.entries(planCounts).filter(([n]) => n !== "free").reduce((s, [, v]) => s + v, 0),
@@ -4482,7 +4508,22 @@ pantheon start</code></pre>
4482
4508
  <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>`}`);
4483
4509
  }
4484
4510
  startInstallerCheck() { this.installerGate.start(); }
4485
- async serveInstaller(req, res, name) {
4511
+ installSummary(now) {
4512
+ const st = this.installStats;
4513
+ if (!st)
4514
+ return null;
4515
+ try {
4516
+ const since = now - 30 * 86_400_000;
4517
+ const signIns = (this.accounts?.auditLog({ event: "session_created", sinceMs: since, limit: 20_000 }) ?? [])
4518
+ .filter((r) => !!r.ip).map((r) => ({ at: r.ts, net: st.netOf(r.ip) }));
4519
+ return summarize(st.read(since), signIns, now, !!this.geo?.ready);
4520
+ }
4521
+ catch (e) {
4522
+ this.log(`! installer downloads could not be read: ${e.message}`);
4523
+ return null;
4524
+ }
4525
+ }
4526
+ async serveInstaller(req, res, name, ip = "") {
4486
4527
  const plain = (code, body, extra = {}) => {
4487
4528
  res.writeHead(code, {
4488
4529
  "content-type": "text/plain; charset=utf-8",
@@ -4509,6 +4550,12 @@ pantheon start</code></pre>
4509
4550
  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" });
4510
4551
  }
4511
4552
  plain(200, body, { "x-pantheon-installs": choice.version });
4553
+ if (this.installStats && ip) {
4554
+ try {
4555
+ void this.installStats.record(this.installStats.event({ ip, file: name, method: req.method ?? "GET", version: choice.version, headers: req.headers }));
4556
+ }
4557
+ catch { }
4558
+ }
4512
4559
  }
4513
4560
  catch (e) {
4514
4561
  this.log(`! ${name} failed: ${e?.message ?? e}`);
@@ -5444,8 +5491,13 @@ pantheon start</code></pre>
5444
5491
  return fail("BAD_ACT_ID", `act id ${m.id} was not made in the last day — check this machine's clock`, m.cid);
5445
5492
  if (m.after_seq !== undefined) {
5446
5493
  const mine = me.id;
5447
- const missed = space.ledger.since(m.after_seq)
5494
+ const unseen = space.ledger.since(m.after_seq);
5495
+ const answered = new Set(unseen.filter((r) => r.from === mine && r.ref).map((r) => r.ref));
5496
+ if (m.ref)
5497
+ answered.add(m.ref);
5498
+ const missed = unseen
5448
5499
  .filter((r) => r.from !== mine && r.act !== "JOIN" && r.act !== "LEAVE")
5500
+ .filter((r) => !answered.has(r.id))
5449
5501
  .filter((r) => (m.goal ? r.goal === m.goal : !r.goal)
5450
5502
  || (r.to?.includes(mine) ?? false)
5451
5503
  || (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())) {
@@ -93,6 +93,13 @@ export const CONSEQUENCES = {
93
93
  "run-minutes": (c) => Number(c.to) > Number(c.from)
94
94
  ? `Right now one piece of work may take up to ${c.from} minutes. After this change it may take up to ${c.to} minutes, so bigger requests can finish in one go (a longer run uses more of your agent plan).`
95
95
  : `Right now one piece of work may take up to ${c.from} minutes, so bigger requests can finish in one go. After this change it stops after ${c.to} minutes, and bigger requests may come back to you unfinished.`,
96
+ model: (c) => {
97
+ const said = (m) => (m === "own" ? `your own default model${c.about === "claude-code" || !c.about ? " (for many people, Opus)" : ""}` : m);
98
+ return `Right now ${agentLabel(c.about ?? "claude-code")} runs for teammates use ${said(c.from)}. After this change they use ${said(c.to)}${c.to === "own" || /opus/i.test(c.to) ? ", which uses more of your agent plan for each request" : ""}.`;
99
+ },
100
+ "goal-runs": (c) => Number(c.to) > Number(c.from)
101
+ ? `Right now one goal may start up to ${c.from} runs a day here, so two agents answering each other can't use up your plan. After this change it may start up to ${c.to}.`
102
+ : `Right now one goal may start up to ${c.from} runs a day here. After this change it stops at ${c.to}, and that goal's requests wait for you past it.`,
96
103
  "idle-seconds": (c) => {
97
104
  const quiet = (x) => (Number(x) === 0 ? "as soon as you stop typing" : `after you've been quiet for ${describeIdleSeconds(Number(x))}`);
98
105
  return Number(c.to) < Number(c.from)
@@ -186,6 +193,7 @@ const SETTING_NAMES = {
186
193
  mode: "Mode", persona: "Playbook", decides: "Decided by", wake: "Who may hand you work", waker: "May hand you work", commands: "Commands in runs",
187
194
  unsandboxed: "Codex, Cursor and Copilot runs", "self-upgrade": "Keeping Pantheon up to date", "run-minutes": "Longest run", "idle-seconds": "Wait while you type",
188
195
  alerts: "Alerts", agent: "Agent for requests", hooks: "Agent window hooks", worker: "Worker", folder: "Folder", base: "Base branch",
196
+ model: "Model for requests", "goal-runs": "Runs per goal a day",
189
197
  };
190
198
  export function changeLabel(c) {
191
199
  return `${settingName(c)}: ${valueWords(c, c.from)} → ${valueWords(c, c.to)}`;
@@ -246,6 +254,11 @@ export function readChangeLog(home, head) {
246
254
  }
247
255
  return out;
248
256
  }
257
+ export function turnedOff(setting, entries = readChangeLog()) {
258
+ const took = entries.filter((e) => e.setting === setting && (e.outcome === "applied" || e.outcome === "approved" || e.outcome === "stopped"));
259
+ const last = took[took.length - 1];
260
+ return !!last && /^(off|none|stopped)\b/.test(last.to);
261
+ }
249
262
  export function lastChangeLine(home, now = Date.now()) {
250
263
  const done = readChangeLog(home).filter((e) => (e.outcome === "applied" || e.outcome === "approved") && e.setting !== FIRST_SETUP);
251
264
  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: "Decisions that need me, and a teammate's request nothing here has picked up (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 {
package/dist/spend.js CHANGED
@@ -149,6 +149,18 @@ export function allowed(caps, home) {
149
149
  }
150
150
  return { ok: true };
151
151
  }
152
+ export function goalAllowed(goal, cap, home, now = Date.now()) {
153
+ if (!goal)
154
+ return { ok: true };
155
+ const book = read(home);
156
+ if (book.broken)
157
+ return { ok: true };
158
+ const from = now - 86_400_000;
159
+ const ats = book.runs.filter((r) => r.goal === goal && r.at > from).map((r) => r.at).sort((a, b) => a - b);
160
+ if (ats.length < cap)
161
+ return { ok: true };
162
+ return { ok: false, n: ats.length, freeAt: ats[ats.length - cap] + 86_400_000 };
163
+ }
152
164
  export function report(home) {
153
165
  const h = since(3_600_000, home);
154
166
  const d = since(86_400_000, home);
@@ -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
  }