@join-pantheon/cli 0.37.3 → 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/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: "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 {
@@ -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
  }
@@ -1,4 +1,4 @@
1
- import { closeSync, fsyncSync, mkdirSync, openSync, renameSync, rmSync, writeFileSync, writeSync } from "node:fs";
1
+ import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, renameSync, rmSync, writeFileSync, writeSync } from "node:fs";
2
2
  import { dirname, join } from "node:path";
3
3
  import { CONFIG_PATH } from "./config.js";
4
4
  import { trustWrite } from "./home-guard.js";
@@ -170,7 +170,7 @@ export function loadPolicy(home) {
170
170
  }
171
171
  catch (e) {
172
172
  if (e.code === "ENOENT")
173
- return { grants: {}, asks: {}, denied: {}, attempts: {} };
173
+ return { grants: {}, asks: {}, denied: {}, attempts: {}, born: Date.now() };
174
174
  if (attempt < 3) {
175
175
  pause(15);
176
176
  continue;
@@ -229,6 +229,9 @@ function parsePolicy(text) {
229
229
  ...(typeof raw.mode === "string" && parseMode(raw.mode) ? { mode: raw.mode } : {}),
230
230
  ...(typeof raw.modeToldAt === "number" ? { modeToldAt: raw.modeToldAt } : {}),
231
231
  ...(isRecord(raw.stuckReports) ? { stuckReports: Object.fromEntries(Object.entries(raw.stuckReports).filter(([, v]) => isRecord(v) && typeof v.ref === "string" && typeof v.team === "string" && typeof v.at === "number")) } : {}),
232
+ ...(isRecord(raw.revoked) ? { revoked: Object.fromEntries(Object.entries(raw.revoked).filter(([, v]) => isTime(v))) } : {}),
233
+ ...(isRecord(raw.usedOnce) ? { usedOnce: Object.fromEntries(Object.entries(raw.usedOnce).filter(([, v]) => isTime(v))) } : {}),
234
+ ...(isTime(raw.born) ? { born: raw.born } : {}),
232
235
  ...(Array.isArray(raw.finalNo) ? { finalNo: raw.finalNo.filter((k) => typeof k === "string") } : {}),
233
236
  ...(isRecord(raw.safetyNotes) ? { safetyNotes: Object.fromEntries(Object.entries(raw.safetyNotes).filter(([, v]) => isRecord(v) && typeof v.says === "string" && typeof v.fix === "string" && typeof v.at === "number" && typeof v.team === "string")) } : {}),
234
237
  };
@@ -457,23 +460,62 @@ function merge3(base, ours, theirs) {
457
460
  }
458
461
  return ours;
459
462
  }
463
+ export function setupMayGrantSelfUpgrade(p, fileExists) {
464
+ if (policyUnreadable(p))
465
+ return false;
466
+ if (fileExists && !p.born)
467
+ return false;
468
+ return !p.grants.self_upgrade && p.denied.self_upgrade === undefined && p.revoked?.self_upgrade === undefined
469
+ && p.usedOnce?.self_upgrade === undefined && !p.asks.self_upgrade;
470
+ }
471
+ export function selfUpgradeSetupDue(home, env = process.env) {
472
+ if (inWokenRun(env))
473
+ return false;
474
+ try {
475
+ return setupMayGrantSelfUpgrade(loadPolicy(home), existsSync(policyPath(home)));
476
+ }
477
+ catch {
478
+ return false;
479
+ }
480
+ }
481
+ export function grantSelfUpgradeAtSetup(home, env = process.env) {
482
+ if (inWokenRun(env))
483
+ return null;
484
+ try {
485
+ const p = loadPolicy(home);
486
+ if (!setupMayGrantSelfUpgrade(p, existsSync(policyPath(home))))
487
+ return null;
488
+ grant(p, "self_upgrade", "always", "setup-default");
489
+ savePolicy(p, home);
490
+ return SELF_UPGRADE_DISCLOSURE;
491
+ }
492
+ catch {
493
+ return null;
494
+ }
495
+ }
496
+ export const SELF_UPGRADE_DISCLOSURE = "The worker keeps pantheon itself current with your team's relay (fast-forward pull + rebuild, reported on the ledger). Revoke: pantheon policy revoke self-upgrade";
460
497
  export function useGrant(p, cap) {
461
498
  const g = p.grants[cap];
462
499
  if (!g)
463
500
  return false;
464
- if (g.mode === "once")
501
+ if (g.mode === "once") {
465
502
  delete p.grants[cap];
503
+ p.usedOnce = { ...(p.usedOnce ?? {}), [cap]: Date.now() };
504
+ }
466
505
  return true;
467
506
  }
468
507
  export function grant(p, cap, mode, by) {
469
508
  p.grants[cap] = { mode, by, at: Date.now() };
470
509
  delete p.asks[cap];
471
510
  delete p.denied[cap];
511
+ if (p.revoked)
512
+ delete p.revoked[cap];
472
513
  if (p.finalNo)
473
514
  p.finalNo = p.finalNo.filter((k) => k !== finalKey.cap(cap));
474
515
  }
475
516
  export function revoke(p, cap) {
476
517
  delete p.grants[cap];
518
+ p.revoked = { ...(p.revoked ?? {}), [cap]: Date.now() };
477
519
  if (cap === "unsandboxed_runs")
478
520
  p.denied[cap] = Date.now();
479
521
  }