@join-pantheon/cli 0.35.0 → 0.35.1-rc.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.
Files changed (51) hide show
  1. package/dist/agent-outage.js +156 -36
  2. package/dist/agent-token.js +5 -3
  3. package/dist/approvals-list.js +87 -0
  4. package/dist/board.js +472 -87
  5. package/dist/brief.js +17 -0
  6. package/dist/cli.js +687 -95
  7. package/dist/client.js +159 -19
  8. package/dist/config.js +3 -2
  9. package/dist/continued.js +56 -1
  10. package/dist/decision-ui.js +5 -3
  11. package/dist/doctor.js +81 -15
  12. package/dist/file-lock.js +39 -4
  13. package/dist/flow-stats.js +18 -1
  14. package/dist/home-guard.js +317 -54
  15. package/dist/home-safety.js +2 -0
  16. package/dist/hud-queue.js +91 -0
  17. package/dist/install.js +15 -1
  18. package/dist/mcp-instructions.js +55 -20
  19. package/dist/mcp.js +114 -24
  20. package/dist/notice-linux.js +15 -4
  21. package/dist/notice-windows.js +2 -2
  22. package/dist/notifier.js +2 -1
  23. package/dist/notify.js +8 -4
  24. package/dist/open-in.js +4 -3
  25. package/dist/pickup.js +17 -0
  26. package/dist/plain.js +139 -3
  27. package/dist/profile.js +12 -8
  28. package/dist/protocol.js +1 -1
  29. package/dist/question-goal.js +74 -0
  30. package/dist/readiness-alert.js +24 -3
  31. package/dist/refusal.js +2 -2
  32. package/dist/relay.js +142 -28
  33. package/dist/removed.js +4 -4
  34. package/dist/run-control.js +4 -3
  35. package/dist/run-failure.js +67 -10
  36. package/dist/setup-changes.js +7 -6
  37. package/dist/signed-out.js +144 -21
  38. package/dist/spend.js +2 -2
  39. package/dist/tray.js +24 -6
  40. package/dist/update-check.js +2 -1
  41. package/dist/uri-handler.js +10 -2
  42. package/dist/which.js +2 -0
  43. package/dist/worker-policy.js +212 -10
  44. package/dist/worker.js +847 -114
  45. package/dist/worklist.js +31 -1
  46. package/helper/macos/main.swift +42 -3
  47. package/helper/macos/menubar.swift +482 -87
  48. package/helper/macos/prebuilt/manifest.json +5 -5
  49. package/helper/macos/prebuilt/pantheon-hud +0 -0
  50. package/helper/macos/prebuilt/pantheon-tray +0 -0
  51. package/package.json +1 -1
@@ -1,34 +1,124 @@
1
- import { readFileSync, renameSync, statSync, writeFileSync, mkdirSync } from "node:fs";
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { renameSync, statSync, writeFileSync, mkdirSync } from "node:fs";
2
3
  import { homedir } from "node:os";
3
4
  import { join } from "node:path";
4
5
  import { CONFIG_DIR } from "./config.js";
5
- import { claudeTokenStamp } from "./agent-token.js";
6
+ import { claudeTokenForRun, claudeTokenStamp } from "./agent-token.js";
6
7
  import { trustWrite } from "./home-guard.js";
7
- import { ownWords } from "./agent-outage.js";
8
- export const SIGNED_OUT_RE = /please run \/login|login expired|not logged in\b|invalid api key|oauth token (?:has )?expired|oauth token refresh failed|failed to authenticate|api error: 401\b|oauth access token is invalid|run `?(?:codex|cursor-agent) login`?/i;
8
+ import { isSet, refusalOf, SIGNIN_REFUSED } from "./agent-outage.js";
9
+ import { RECHECK_FILE } from "./home-guard.js";
10
+ import { readStateText } from "./file-lock.js";
9
11
  export const SIGNED_OUT_RETRY_MS = 3_600_000;
10
12
  export const SIGNED_OUT_MAX_RETRY_MS = 8 * 3_600_000;
11
- const TAIL_LINES = 5;
12
13
  export const SIGNED_OUT_AGENTS = ["claude-code", "codex", "cursor", "copilot"];
13
14
  const FILE = "signed-out.json";
15
+ export const SIGN_IN_VARS = {
16
+ "claude-code": ["ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN"],
17
+ codex: ["CODEX_API_KEY"],
18
+ cursor: ["CURSOR_API_KEY", "CURSOR_AUTH_TOKEN"],
19
+ copilot: ["COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"],
20
+ };
21
+ export const HINT_DEBOUNCE_MS = 3 * 60_000;
22
+ export const HINT_GAP_MAX_MS = 15 * 60_000;
23
+ export const SETTINGS_RETRY_MS = 15 * 60_000;
24
+ export const SETTINGS_MAX_RETRY_MS = 60 * 60_000;
14
25
  const mtime = (p) => { try {
15
26
  return String(statSync(p).mtimeMs);
16
27
  }
17
28
  catch {
18
29
  return "-";
19
30
  } };
20
- export function signInSignature(agent, o = {}) {
31
+ const set = (v) => (v && v.trim() ? v : undefined);
32
+ export function signInFiles(agent, o = {}) {
21
33
  const h = o.userHome ?? homedir();
22
- if (agent === "claude-code")
23
- return [mtime(join(h, ".claude", ".credentials.json")), mtime(join(h, ".claude.json")), claudeTokenStamp(o.pantheonHome ?? CONFIG_DIR)].join("|");
34
+ const env = o.env ?? process.env;
35
+ const plat = o.platform ?? process.platform;
36
+ const appData = set(env.APPDATA) ?? join(h, "AppData", "Roaming");
37
+ const xdg = set(env.XDG_CONFIG_HOME);
38
+ if (agent === "claude-code") {
39
+ const dir = set(env.CLAUDE_CONFIG_DIR);
40
+ return {
41
+ cred: [mtime(join(dir ?? join(h, ".claude"), ".credentials.json")), claudeTokenStamp(o.pantheonHome ?? CONFIG_DIR)].join("|"),
42
+ hint: mtime(dir ? join(dir, ".claude.json") : join(h, ".claude.json")),
43
+ };
44
+ }
24
45
  if (agent === "codex")
25
- return mtime(join(h, ".codex", "auth.json"));
26
- return "";
46
+ return { cred: mtime(join(set(env.CODEX_HOME) ?? join(h, ".codex"), "auth.json")), hint: "" };
47
+ if (agent === "cursor") {
48
+ const auth = plat === "win32" ? join(appData, "Cursor", "auth.json")
49
+ : plat === "darwin" ? join(h, ".cursor", "auth.json")
50
+ : join(xdg ?? join(h, ".config"), "cursor", "auth.json");
51
+ const cfg = set(env.CURSOR_CONFIG_DIR) ?? (xdg ? join(xdg, "cursor") : join(h, ".cursor"));
52
+ return { cred: mtime(auth), hint: mtime(join(cfg, "cli-config.json")) };
53
+ }
54
+ if (agent === "copilot") {
55
+ const gh = set(env.GH_CONFIG_DIR) ?? (plat === "win32" ? join(appData, "GitHub CLI") : join(xdg ?? join(h, ".config"), "gh"));
56
+ return { cred: mtime(join(gh, "hosts.yml")), hint: mtime(join(set(env.COPILOT_HOME) ?? join(h, ".copilot"), "config.json")) };
57
+ }
58
+ return { cred: "", hint: "" };
59
+ }
60
+ export function signInVarsSig(agent, env, pantheonHome, only) {
61
+ const all = SIGN_IN_VARS[agent] ?? [];
62
+ const at = only ? all.indexOf(only) : -1;
63
+ const set = (only ? (at >= 0 ? all.slice(0, at + 1) : [only]) : all).filter((k) => isSet(env[k]));
64
+ if (!set.length)
65
+ return "";
66
+ const h = createHash("sha256").update(salt(pantheonHome));
67
+ for (const k of set)
68
+ h.update(`\0${k}=${env[k]}`);
69
+ return h.digest("hex").slice(0, 16);
70
+ }
71
+ function salt(home) {
72
+ const f = join(home, "signed-out.salt");
73
+ try {
74
+ const v = readStateText(f).trim();
75
+ if (/^[0-9a-f]{64}$/.test(v))
76
+ return v;
77
+ }
78
+ catch { }
79
+ const v = randomBytes(32).toString("hex");
80
+ try {
81
+ mkdirSync(home, { recursive: true, mode: 0o700 });
82
+ writeFileSync(f, v + "\n", { mode: 0o600 });
83
+ trustWrite(f);
84
+ }
85
+ catch { }
86
+ return v;
87
+ }
88
+ function basisSig(agent, basis, o, home) {
89
+ if (basis === "token")
90
+ return claudeTokenStamp(home);
91
+ if (basis === "var" || basis === "settings")
92
+ return "";
93
+ return signInFiles(agent, o).cred;
94
+ }
95
+ function basisHint(agent, basis, o) {
96
+ if (basis === "var" || basis === "token")
97
+ return undefined;
98
+ if (basis === "settings") {
99
+ const dir = set((o.env ?? process.env).CLAUDE_CONFIG_DIR) ?? join(o.userHome ?? homedir(), ".claude");
100
+ return mtime(join(dir, "settings.json"));
101
+ }
102
+ return signInFiles(agent, o).hint || undefined;
103
+ }
104
+ export function claudeSettingsAuth(o = {}) {
105
+ const dir = set((o.env ?? process.env).CLAUDE_CONFIG_DIR) ?? join(o.userHome ?? homedir(), ".claude");
106
+ try {
107
+ const j = JSON.parse(readStateText(join(dir, "settings.json")));
108
+ const env = j.env && typeof j.env === "object" ? j.env : {};
109
+ return { env: SIGN_IN_VARS["claude-code"].filter((k) => typeof env[k] === "string" && isSet(env[k])), apiKeyHelper: typeof j.apiKeyHelper === "string" && j.apiKeyHelper.trim() !== "" };
110
+ }
111
+ catch {
112
+ return { env: [], apiKeyHelper: false };
113
+ }
114
+ }
115
+ export function signInSignature(agent, o = {}) {
116
+ return signInFiles(agent, o).cred;
27
117
  }
28
118
  const file = (home) => join(home, FILE);
29
119
  function read(home) {
30
120
  try {
31
- const j = JSON.parse(readFileSync(file(home), "utf8"));
121
+ const j = JSON.parse(readStateText(file(home)));
32
122
  return j && typeof j === "object" ? j : {};
33
123
  }
34
124
  catch {
@@ -45,18 +135,28 @@ function write(home, m) {
45
135
  }
46
136
  catch { }
47
137
  }
48
- export const retryAfter = (m) => Math.min(SIGNED_OUT_RETRY_MS * 2 ** Math.max(0, m.tries ?? 0), SIGNED_OUT_MAX_RETRY_MS);
138
+ export const retryAfter = (m) => m.basis === "settings" ? Math.min(SETTINGS_RETRY_MS * 2 ** Math.max(0, m.tries ?? 0), SETTINGS_MAX_RETRY_MS) : Math.min(SIGNED_OUT_RETRY_MS * 2 ** Math.max(0, m.tries ?? 0), SIGNED_OUT_MAX_RETRY_MS);
49
139
  export function markSignedOut(agent, output, o = {}) {
50
- const tail = output.split("\n").map((l) => l.trim()).filter(Boolean).slice(-TAIL_LINES);
51
- const line = tail.find((l) => ownWords(l, SIGNED_OUT_RE));
52
- if (!line)
140
+ const refused = refusalOf(agent, output, SIGNIN_REFUSED, o.env, agent === "claude-code" && o.env ? claudeSettingsAuth(o) : undefined);
141
+ if (!refused)
53
142
  return false;
143
+ const line = refused.line;
54
144
  const home = o.pantheonHome ?? CONFIG_DIR;
55
145
  const m = read(home);
56
- const sig = signInSignature(agent, o);
146
+ const tokenUsed = agent === "claude-code" && (o.env ? claudeTokenForRun(home, o.env) !== null : claudeTokenStamp(home) !== "");
147
+ const varUsed = refused.env && !refused.settings ? refused.env : undefined;
148
+ const basis = varUsed ? "var" : refused.settings ? "settings" : tokenUsed ? "token" : undefined;
149
+ const via = varUsed ?? (refused.settings ? refused.env : undefined);
150
+ const sig = basisSig(agent, basis, o, home);
151
+ const hint = basisHint(agent, basis, o);
152
+ const envSig = o.env && basis !== "settings" ? signInVarsSig(agent, o.env, home, basis === "var" ? varUsed : undefined) : undefined;
57
153
  const prev = m[agent];
58
- const tries = prev && prev.sig === sig ? (prev.tries ?? 0) + 1 : 0;
59
- m[agent] = { at: o.now ?? Date.now(), sig, says: line.slice(0, 160), ...(tries ? { tries } : {}) };
154
+ const same = !!prev && prev.basis === basis && prev.via === via && prev.sig === sig && (envSig === undefined || prev.envSig === undefined || prev.envSig === envSig);
155
+ const hintLed = same && prev.at === 0 && prev.lifted === "hint";
156
+ const tries = same ? (prev.tries ?? 0) + (prev.at === 0 && prev.lifted !== "hint" && prev.lifted !== "now" ? 1 : 0) : 0;
157
+ const hintAt = same ? prev.hintAt : undefined;
158
+ const hintGap = !same ? undefined : hintLed ? Math.min((prev.hintGap ?? HINT_DEBOUNCE_MS) * 2, HINT_GAP_MAX_MS) : prev.hintGap;
159
+ m[agent] = { at: o.now ?? Date.now(), sig, says: line.slice(0, 160), ...(tries ? { tries } : {}), ...(hint ? { hint } : {}), ...(envSig !== undefined ? { envSig } : {}), ...(hintAt ? { hintAt } : {}), ...(hintGap ? { hintGap } : {}), ...(via ? { via } : {}), ...(basis ? { basis } : {}), ...(refused.helper ? { helper: true } : {}) };
60
160
  write(home, m);
61
161
  return true;
62
162
  }
@@ -67,17 +167,40 @@ export function signedOutNow(agent, o = {}) {
67
167
  if (!mark || typeof mark.at !== "number" || mark.at === 0)
68
168
  return null;
69
169
  const now = o.now ?? Date.now();
70
- const changed = signInSignature(agent, o) !== mark.sig;
170
+ const varsChanged = !!o.env && mark.basis !== "settings" && mark.envSig !== undefined && signInVarsSig(agent, o.env, home, mark.basis === "var" ? mark.via : undefined) !== mark.envSig;
171
+ const signedIn = basisSig(agent, mark.basis, o, home) !== mark.sig || varsChanged;
172
+ const hint = basisHint(agent, mark.basis, o);
173
+ const gap = Math.min(mark.hintGap ?? HINT_DEBOUNCE_MS, HINT_GAP_MAX_MS);
174
+ const hinted = hint !== undefined && mark.hint !== undefined && hint !== mark.hint && (mark.hintAt === undefined || now - mark.hintAt >= gap || now < mark.hintAt);
71
175
  const due = now - mark.at >= retryAfter(mark) || now < mark.at;
72
- if (!changed && !due)
176
+ const asked = (() => { try {
177
+ const t = statSync(join(home, RECHECK_FILE)).mtimeMs;
178
+ return t > mark.at && t <= now + 1_000;
179
+ }
180
+ catch {
181
+ return false;
182
+ } })();
183
+ if (!signedIn && !hinted && !due && !asked)
73
184
  return mark;
74
185
  if (o.lift) {
75
186
  const { tries: _t, ...rest } = mark;
76
- m[agent] = changed ? { ...rest, at: 0 } : { ...mark, at: 0 };
187
+ const { hintGap: _g, ...fresh } = rest;
188
+ m[agent] = signedIn ? { ...fresh, at: 0, lifted: "signin" } : due ? { ...mark, at: 0, lifted: "due" } : asked ? { ...mark, at: 0, lifted: "now" } : { ...mark, at: 0, lifted: "hint", hintAt: now };
77
189
  write(home, m);
78
190
  }
79
191
  return null;
80
192
  }
193
+ export function signedOutVia(agent, o = {}) {
194
+ const v = read(o.pantheonHome ?? CONFIG_DIR)[agent]?.via;
195
+ return typeof v === "string" && /^[A-Z][A-Z0-9_]{1,40}$/.test(v) ? v : null;
196
+ }
197
+ export function signedOutRefusal(agent, o = {}) {
198
+ const m = read(o.pantheonHome ?? CONFIG_DIR)[agent];
199
+ if (!m || typeof m.says !== "string")
200
+ return null;
201
+ const env = signedOutVia(agent, o);
202
+ return { line: m.says, ...(env ? { env } : {}), ...(m.basis === "settings" ? { settings: true } : {}), ...(m.helper ? { helper: true } : {}), ...(m.basis === "token" ? { savedToken: true } : {}) };
203
+ }
81
204
  export function signedOutChecking(agent, o = {}) {
82
205
  const mark = read(o.pantheonHome ?? CONFIG_DIR)[agent];
83
206
  return mark && mark.at === 0 ? mark : null;
package/dist/spend.js CHANGED
@@ -65,7 +65,7 @@ export function finishRun(id, end, home) {
65
65
  b.runs[i] = { ...was, ...end, ...(typeof was.at === "number" && was.at <= end.at ? { started_at: was.started_at ?? was.at } : {}) };
66
66
  write(b, home);
67
67
  }
68
- export function closeStartedRun(id, summary, fallback, home) {
68
+ export function closeStartedRun(id, summary, fallback, home, ok = false) {
69
69
  const b = read(home);
70
70
  if (b.broken)
71
71
  return;
@@ -77,7 +77,7 @@ export function closeStartedRun(id, summary, fallback, home) {
77
77
  if (!b.runs[i].started)
78
78
  return;
79
79
  const { started: _s, ...was } = b.runs[i];
80
- b.runs[i] = { ...was, ok: false, summary };
80
+ b.runs[i] = { ...was, ok, summary };
81
81
  write(b, home);
82
82
  }
83
83
  export function runsToday(own, o = {}) {
package/dist/tray.js CHANGED
@@ -1,4 +1,5 @@
1
- import { effectiveMode, loadPolicy } from "./worker-policy.js";
1
+ import { effectiveMode, loadPolicy, safetyNotesLine } from "./worker-policy.js";
2
+ import { loadPersistedGuard } from "./home-guard.js";
2
3
  import { askedByName, changeLabel, consequence, loadPending } from "./setup-changes.js";
3
4
  import { buildUri, uriKey } from "./uri-handler.js";
4
5
  import { stopFor } from "./run-control.js";
@@ -16,7 +17,7 @@ import { VERSION } from "./version.js";
16
17
  import { LIMITS } from "./protocol.js";
17
18
  import { signedRead } from "./reads.js";
18
19
  import { clearRemoval, goneLine, goneOf, recordGone, recordRemoval, removalFor, removalHolds, removalRefusal, REMOVED_CHECK_MS, teamRef } from "./removed.js";
19
- import { pickupEstimate } from "./pickup.js";
20
+ import { awaitingDecision, pickupEstimate } from "./pickup.js";
20
21
  import { allDecisionsPrompt, decisionPrompt, decisionTitle, owedPrompt, stripCeremony, tidyIds, tidyLead, waitingPrompt, workerSummary } from "./decision-ui.js";
21
22
  import { loadProfile, SURFACE_BUNDLE_IDS } from "./profile.js";
22
23
  import { agentProblem, agentProblemFix, PROBLEM_LEAD } from "./readiness-alert.js";
@@ -348,6 +349,8 @@ async function trayStatusOne(cfg, membershipId) {
348
349
  return {};
349
350
  } })() : {};
350
351
  const waiting = all.filter((o) => o.owner !== cfg.member && o.owner !== `human:${cfg.member}`);
352
+ const wakeAskedOf = (who, ref) => !!ref && all.some((h) => h.owner === `human:${who}` && h.about === ref &&
353
+ new RegExp(`\\bLet ${cfg.member.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")} start work on this machine while you are away\\?`).test(h.body));
351
354
  const items = [
352
355
  ...mineHuman.map((o) => {
353
356
  const from = senderOf(o);
@@ -369,7 +372,7 @@ async function trayStatusOne(cfg, membershipId) {
369
372
  const who = o.owner.replace(/^human:/, "");
370
373
  const r0 = row(o, "waiting", who, waitingPrompt(who, decisionTitle(o.body), o.goal));
371
374
  const r = roster && !o.owner.startsWith("human:") && o.kind !== "DELIVER"
372
- ? { ...r0, pickup: pickupEstimate(roster.find((m) => m.id === who) ?? { id: who, sessions: [] }, { now: relayNow, about: { ref: o.ref ?? null, goal: o.goal ?? null }, ...(myMayWake !== undefined ? { mayWake: myMayWake } : {}) }).says }
375
+ ? { ...r0, pickup: pickupEstimate(roster.find((m) => m.id === who) ?? { id: who, sessions: [] }, { now: relayNow, about: { ref: o.ref ?? null, goal: o.goal ?? null }, claimedBy: o.claimed_by ?? null, wakeAsked: wakeAskedOf(who, o.ref), deciding: awaitingDecision(all, { owner: who, ref: o.ref ?? null, goal: o.goal ?? null, ...(o.created_at !== undefined ? { created_at: o.created_at } : {}) }), ...(myMayWake !== undefined ? { mayWake: myMayWake } : {}) }).says }
373
376
  : r0;
374
377
  return o.owner.startsWith("human:")
375
378
  ? { ...r, title: `${who} decides: ${r.title}`, headline: `${who} decides: ${r.headline}`, decider: who }
@@ -432,20 +435,35 @@ function machineFields(cfg, workerRunning = running("worker")) {
432
435
  } })();
433
436
  const surfaceName = openIn === "app" ? "Claude app" : surface === "claude-code" ? "Claude" : surface === "cursor" ? "Cursor" : surface === "copilot" ? "Copilot" : surface === "kiro" ? "Kiro" : "Codex";
434
437
  const rawWorkerState = workerState();
435
- const problem = (() => { try {
438
+ const agentIssue = (() => { try {
436
439
  return agentProblem(CONFIG_DIR);
437
440
  }
438
441
  catch {
439
442
  return null;
440
443
  } })();
444
+ const held = agentIssue ? null : (() => { try {
445
+ const p = loadPersistedGuard(CONFIG_DIR)?.pending;
446
+ return p?.length ? `a teammate's request locked ${p.join(", ")} while it ran, so Pantheon could not put back what it changed — make ${p.length === 1 ? "it" : "them"} writable again (pantheon doctor says how)` : null;
447
+ }
448
+ catch {
449
+ return null;
450
+ } })();
451
+ const safety = agentIssue || held ? null : (() => { try {
452
+ return safetyNotesLine(CONFIG_DIR);
453
+ }
454
+ catch {
455
+ return null;
456
+ } })();
457
+ const problem = agentIssue ?? held ?? safety;
458
+ const lead = agentIssue ? PROBLEM_LEAD : held ? "Unattended runs are on hold" : "A safety warning could not reach your board";
441
459
  return {
442
460
  worker_running: workerRunning,
443
461
  worker_installed: serviceInstalled("worker"),
444
462
  worker_plist: plistPath("worker"),
445
463
  notifier_running: running("notifier"),
446
464
  hook_on: agentHookStates().length > 0,
447
- ...(problem ? { agent_problem: problem, agent_problem_lead: PROBLEM_LEAD, worker_state: `${PROBLEM_LEAD}: ${problem}` } : rawWorkerState ? { worker_state: workerSummary(rawWorkerState) } : {}),
448
- ...(problem ? (() => { try {
465
+ ...(problem ? { agent_problem: problem, agent_problem_lead: lead, worker_state: `${lead}: ${problem}` } : rawWorkerState ? { worker_state: workerSummary(rawWorkerState) } : {}),
466
+ ...(agentIssue ? (() => { try {
449
467
  const fix = agentProblemFix(CONFIG_DIR);
450
468
  return fix ? { agent_problem_fix: fix } : {};
451
469
  }
@@ -20,7 +20,7 @@ export function updateStatus(deps) {
20
20
  if (cache && deps.now() - cache.checkedAt < deps.throttleMs) {
21
21
  return { behind: cache.behind, refreshed: false, latest: cache.latest };
22
22
  }
23
- if (process.env["PANTHEON_NO_UPDATE_CHECK"])
23
+ if (deps.optedOut?.())
24
24
  return { behind: cache?.behind ?? 0, refreshed: false, latest: cache?.latest };
25
25
  if (deps.isGit()) {
26
26
  try {
@@ -57,6 +57,7 @@ const cachePath = (home) => join(home ?? CONFIG_DIR, "update-check.json");
57
57
  export function defaultDeps(home) {
58
58
  return {
59
59
  now: () => Date.now(),
60
+ optedOut: () => !!process.env["PANTHEON_NO_UPDATE_CHECK"],
60
61
  throttleMs: 6 * 60 * 60 * 1000,
61
62
  readCache: () => {
62
63
  try {
@@ -5,7 +5,7 @@ import { join, win32 } from "node:path";
5
5
  export const URI_SCHEME = "pantheon";
6
6
  export const URI_HOSTS = ["board", "done", "explain", "details", "change", "work", "changes"];
7
7
  const FORMS = {
8
- board: { required: [], optional: ["focus"] },
8
+ board: { required: [], optional: ["focus", "space"] },
9
9
  done: { required: ["decision", "k"], optional: ["act", "space"] },
10
10
  explain: { required: ["decision", "k"], optional: ["act", "space"] },
11
11
  details: { required: ["act", "k"], optional: ["decision", "space"] },
@@ -219,7 +219,7 @@ export async function handleUri(args, d) {
219
219
  if (d.openBoard) {
220
220
  let ok = false;
221
221
  try {
222
- ok = await d.openBoard(p.params.focus);
222
+ ok = await d.openBoard(p.params.focus, p.params.focus ? p.params.space : undefined);
223
223
  }
224
224
  catch {
225
225
  ok = false;
@@ -250,6 +250,14 @@ export async function handleUri(args, d) {
250
250
  await d.pause();
251
251
  return code;
252
252
  }
253
+ export function outcomeLines(out) {
254
+ return out.split("\n").filter((l) => l.trim() && !/^action [0-9a-f]+$/.test(l.trim())).map((l) => {
255
+ const m = /^(unconfirmed|not sent): ?(.*)$/.exec(l.trim());
256
+ if (!m)
257
+ return l;
258
+ return m[1] === "unconfirmed" ? `Not confirmed — check the thread.\n ${m[2]}` : `Not sent — ${m[2]}`;
259
+ });
260
+ }
253
261
  export const PROTOCOL_KEY = "HKCU\\Software\\Classes\\pantheon";
254
262
  export const COMMAND_KEY = `${PROTOCOL_KEY}\\shell\\open\\command`;
255
263
  export const PANTHEON_AUMID = "JoinPantheon.Pantheon";
package/dist/which.js CHANGED
@@ -117,6 +117,8 @@ export function parseLoginAnswer(out, mark) {
117
117
  return { found, path };
118
118
  }
119
119
  function runLoginShell(script, args, timeoutMs = 15_000) {
120
+ if (process.env["PANTHEON_LOGIN_SHELL"] === "off")
121
+ throw new Error("login-shell lookups are off (PANTHEON_LOGIN_SHELL=off)");
120
122
  try {
121
123
  return execFileSync("sh", ["-lc", script, "sh", ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: timeoutMs, killSignal: "SIGKILL", env: loginShellEnv() });
122
124
  }
@@ -1,9 +1,10 @@
1
- import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
1
+ import { closeSync, 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";
5
5
  import { parseJsonText } from "./text-file.js";
6
6
  import { compareVersions, isVersion } from "./installer.js";
7
+ import { readStateText, readStateBytes, withFileLock } from "./file-lock.js";
7
8
  export const WORK_MODES = ["autopilot", "here"];
8
9
  export const MODE_LABELS = {
9
10
  autopilot: "My agent handles everything",
@@ -145,13 +146,69 @@ function notAfterNow(m) {
145
146
  const now = Date.now();
146
147
  return Object.fromEntries(Object.entries(m).map(([k, v]) => [k, typeof v === "number" && v > now ? now : v]));
147
148
  }
149
+ const isTime = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
150
+ function deniedOf(v) {
151
+ if (!isRecord(v))
152
+ return {};
153
+ const out = {};
154
+ for (const [k, at] of Object.entries(v)) {
155
+ if (isTime(at))
156
+ out[k] = at;
157
+ else if (k === "unsandboxed_runs" && at !== undefined && at !== null && at !== false)
158
+ out[k] = 1;
159
+ }
160
+ return out;
161
+ }
162
+ const readFrom = new WeakMap();
163
+ const closed = new WeakSet();
148
164
  export function loadPolicy(home) {
165
+ const file = policyPath(home);
166
+ for (let attempt = 0;; attempt++) {
167
+ let text;
168
+ try {
169
+ text = readStateText(file);
170
+ }
171
+ catch (e) {
172
+ if (e.code === "ENOENT")
173
+ return { grants: {}, asks: {}, denied: {}, attempts: {} };
174
+ if (attempt < 3) {
175
+ pause(15);
176
+ continue;
177
+ }
178
+ return closedPolicy();
179
+ }
180
+ const p = parsePolicy(text);
181
+ if (p) {
182
+ readFrom.set(p, text);
183
+ return p;
184
+ }
185
+ if (attempt < 3) {
186
+ pause(15);
187
+ continue;
188
+ }
189
+ return closedPolicy();
190
+ }
191
+ }
192
+ const pause = (ms) => { try {
193
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
194
+ }
195
+ catch { } };
196
+ function closedPolicy() {
197
+ const now = Date.now();
198
+ const p = { grants: {}, asks: {}, denied: { run_commands: now, self_upgrade: now, unsandboxed_runs: now }, attempts: {}, finalNo: ["cap:run_commands"], wakers: {} };
199
+ closed.add(p);
200
+ return p;
201
+ }
202
+ export function policyUnreadable(p) { return closed.has(p); }
203
+ function parsePolicy(text) {
149
204
  try {
150
- const raw = parseJsonText(readFileSync(policyPath(home), "utf8"));
205
+ const raw = parseJsonText(text);
206
+ if (!isRecord(raw))
207
+ return null;
151
208
  const obj = (v) => (isRecord(v) ? v : {});
152
209
  const wakers = readWakers(raw.wakers);
153
210
  return {
154
- grants: obj(raw.grants), asks: obj(raw.asks), denied: notAfterNow(obj(raw.denied)), attempts: obj(raw.attempts),
211
+ grants: obj(raw.grants), asks: obj(raw.asks), denied: notAfterNow(deniedOf(raw.denied)), attempts: obj(raw.attempts),
155
212
  ...(wakers ? { wakers } : {}),
156
213
  ...(isRecord(raw.wakersCarried) ? { wakersCarried: raw.wakersCarried } : {}),
157
214
  ...(isRecord(raw.wakersDeferred) ? { wakersDeferred: raw.wakersDeferred } : {}),
@@ -163,7 +220,7 @@ export function loadPolicy(home) {
163
220
  return [k, Array.isArray(refs) ? { ...rest, refs: refs.filter((r) => typeof r === "string") } : rest];
164
221
  })) } : {}),
165
222
  ...(isRecord(raw.wakeOnce) ? { wakeOnce: Object.fromEntries(Object.entries(raw.wakeOnce).filter(([, v]) => typeof v === "number" && v > 0 && v < 100)) } : {}),
166
- ...(isRecord(raw.wakeNo) ? { wakeNo: notAfterNow(Object.fromEntries(Object.entries(raw.wakeNo).filter(([, v]) => typeof v === "number"))) } : {}),
223
+ ...(isRecord(raw.wakeNo) ? { wakeNo: notAfterNow(Object.fromEntries(Object.entries(raw.wakeNo).filter(([, v]) => isTime(v)))) } : {}),
167
224
  ...(isRecord(raw.wakeTeamFlag) ? { wakeTeamFlag: Object.fromEntries(Object.entries(raw.wakeTeamFlag).filter(([, v]) => typeof v === "number")) } : {}),
168
225
  ...(isRecord(raw.upgradeHeld) && typeof raw.upgradeHeld.version === "string" && typeof raw.upgradeHeld.node === "string"
169
226
  ? { upgradeHeld: { version: raw.upgradeHeld.version, node: raw.upgradeHeld.node, at: Number(raw.upgradeHeld.at) || 0, why: String(raw.upgradeHeld.why ?? "") } } : {}),
@@ -173,10 +230,11 @@ export function loadPolicy(home) {
173
230
  ...(typeof raw.modeToldAt === "number" ? { modeToldAt: raw.modeToldAt } : {}),
174
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")) } : {}),
175
232
  ...(Array.isArray(raw.finalNo) ? { finalNo: raw.finalNo.filter((k) => typeof k === "string") } : {}),
233
+ ...(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")) } : {}),
176
234
  };
177
235
  }
178
236
  catch {
179
- return { grants: {}, asks: {}, denied: {}, attempts: {} };
237
+ return null;
180
238
  }
181
239
  }
182
240
  export function clearWakeNo(p, teams, member) {
@@ -303,15 +361,101 @@ export function isApprovedWaker(p, teams, member) {
303
361
  return teams.some((t) => { const list = t ? p.wakers?.[t] : undefined; return Array.isArray(list) && list.includes(member); });
304
362
  }
305
363
  export function savePolicy(p, home) {
364
+ if (closed.has(p))
365
+ throw new Error(`${policyPath(home)} could not be read, so nothing was saved over it — run pantheon policy repair`);
306
366
  const file = policyPath(home);
307
367
  mkdirSync(dirname(file), { recursive: true });
308
- let prev = null;
368
+ const write = () => {
369
+ let prev = null;
370
+ try {
371
+ prev = readStateBytes(file);
372
+ }
373
+ catch { }
374
+ const base = readFrom.get(p);
375
+ let next = p;
376
+ if (base !== undefined && prev && prev.toString("utf8") !== base) {
377
+ const theirs = parsePolicy(prev.toString("utf8"));
378
+ const was = parsePolicy(base);
379
+ if (theirs && was)
380
+ next = merge3(was, p, theirs);
381
+ }
382
+ const text = JSON.stringify(next, null, 2) + "\n";
383
+ atomicWrite(file, text);
384
+ readFrom.set(p, text);
385
+ if (next !== p) {
386
+ for (const k of Object.keys(p))
387
+ if (!(k in next))
388
+ delete p[k];
389
+ Object.assign(p, next);
390
+ }
391
+ trustWrite(file, prev);
392
+ };
393
+ let ran = false;
309
394
  try {
310
- prev = readFileSync(file);
395
+ withFileLock(file, () => { ran = true; write(); }, 3_000);
396
+ }
397
+ catch (e) {
398
+ if (ran)
399
+ throw e;
400
+ write();
311
401
  }
312
- catch { }
313
- writeFileSync(file, JSON.stringify(p, null, 2) + "\n", { mode: 0o600 });
314
- trustWrite(file, prev);
402
+ }
403
+ export function atomicWrite(file, text, o = {}) {
404
+ const tmp = `${file}.${process.pid}.${Date.now().toString(36)}.tmp`;
405
+ const rename = o.rename ?? renameSync;
406
+ const win = (o.platform ?? process.platform) === "win32";
407
+ try {
408
+ const fd = openSync(tmp, "wx", 0o600);
409
+ try {
410
+ writeSync(fd, text);
411
+ fsyncSync(fd);
412
+ }
413
+ finally {
414
+ closeSync(fd);
415
+ }
416
+ for (let i = 0;; i++) {
417
+ try {
418
+ rename(tmp, file);
419
+ break;
420
+ }
421
+ catch (e) {
422
+ const code = e.code;
423
+ if (!win || i >= 6 || !(code === "EPERM" || code === "EBUSY" || code === "EACCES"))
424
+ throw e;
425
+ pause(10 * 2 ** i);
426
+ }
427
+ }
428
+ }
429
+ catch (e) {
430
+ try {
431
+ rmSync(tmp, { force: true });
432
+ }
433
+ catch { }
434
+ throw e;
435
+ }
436
+ }
437
+ function merge3(base, ours, theirs) {
438
+ const eq = (a, b) => JSON.stringify(a) === JSON.stringify(b);
439
+ if (eq(ours, base))
440
+ return theirs;
441
+ if (eq(theirs, base))
442
+ return ours;
443
+ if (isRecord(base) && isRecord(ours) && isRecord(theirs)) {
444
+ const out = {};
445
+ for (const k of new Set([...Object.keys(base), ...Object.keys(ours), ...Object.keys(theirs)])) {
446
+ const v = merge3(base[k], ours[k], theirs[k]);
447
+ if (v !== undefined)
448
+ out[k] = v;
449
+ }
450
+ return out;
451
+ }
452
+ const flat = (v) => Array.isArray(v) && v.every((x) => typeof x !== "object" || x === null);
453
+ if (flat(ours) && flat(theirs) && (base === undefined || flat(base))) {
454
+ const b = base ?? [], o = ours, t = theirs;
455
+ const dropped = b.filter((x) => !o.includes(x));
456
+ return [...t, ...o.filter((x) => !b.includes(x) && !t.includes(x))].filter((x) => !dropped.includes(x));
457
+ }
458
+ return ours;
315
459
  }
316
460
  export function useGrant(p, cap) {
317
461
  const g = p.grants[cap];
@@ -376,6 +520,8 @@ export function applyLocalAnswer(refActId, body, home, env = process.env) {
376
520
  const verdict = parseGrantAnswer(body);
377
521
  if (!verdict)
378
522
  return null;
523
+ if (verdict === "allow-once" && p.finalNo?.includes(finalKey.wake(wa.team, wa.member)))
524
+ return { applied: false, why: supersededWords(wa.member) };
379
525
  const k = wakeKey(wa.team, wa.member);
380
526
  if (verdict === "allow-always")
381
527
  setWaker(p, wa.team, wa.member, true);
@@ -404,6 +550,45 @@ export function applyLocalAnswer(refActId, body, home, env = process.env) {
404
550
  savePolicy(p, home);
405
551
  return { applied: true, ...r };
406
552
  }
553
+ const supersededWords = (m) => `you said no to ${m} on this computer since this was asked (pantheon wake deny ${m}), and that stands — "just this once" would not change it. To let ${m} start work here: pantheon wake allow ${m}`;
554
+ export function supersededAnswer(pending, body, home) {
555
+ if (!pending || !("wake" in pending) || parseGrantAnswer(body) !== "allow-once")
556
+ return null;
557
+ const { team, member } = pending.wake;
558
+ return loadPolicy(home).finalNo?.includes(finalKey.wake(team, member)) ? supersededWords(member) : null;
559
+ }
560
+ export function wakeSettled(p, teams, member) {
561
+ const keys = teams.filter((t) => !!t);
562
+ if (keys.some((t) => p.finalNo?.includes(finalKey.wake(t, member))))
563
+ return "no";
564
+ return isApprovedWaker(p, keys, member) ? "yes" : null;
565
+ }
566
+ export function pendingLocalQuestion(refActId, home) {
567
+ if (!refActId)
568
+ return null;
569
+ const p = loadPolicy(home);
570
+ const wa = p.wakeAsks?.[refActId];
571
+ if (wa)
572
+ return { wake: { ...wa } };
573
+ const ask = Object.entries(p.asks).find(([, a]) => a?.act === refActId);
574
+ return ask?.[1] ? { ask: [ask[0], { ...ask[1] }] } : null;
575
+ }
576
+ export function applyLocalAnswerAfterSend(refActId, body, before, home, env = process.env) {
577
+ const g = applyLocalAnswer(refActId, body, home, env);
578
+ if (g || !before || !refActId || inWokenRun(env) || !parseGrantAnswer(body))
579
+ return g;
580
+ const p = loadPolicy(home);
581
+ if ("wake" in before)
582
+ (p.wakeAsks ??= {})[refActId] = before.wake;
583
+ else {
584
+ const [cap, ask] = before.ask;
585
+ if (p.asks[cap])
586
+ return applyLocalAnswer(p.asks[cap].act, body, home, env);
587
+ p.asks[cap] = ask;
588
+ }
589
+ savePolicy(p, home);
590
+ return applyLocalAnswer(refActId, body, home, env);
591
+ }
407
592
  export function describeLocalAnswer(g) {
408
593
  if (!g.applied)
409
594
  return `not granted: ${g.why}`;
@@ -462,4 +647,21 @@ export function isNewer(a, b) {
462
647
  }
463
648
  return false;
464
649
  }
650
+ export function safetyNotesLine(home) {
651
+ const notes = Object.values(loadPolicy(home).safetyNotes ?? {});
652
+ if (!notes.length)
653
+ return null;
654
+ const first = notes.sort((a, b) => a.at - b.at)[0];
655
+ return `${first.says}. What to do: ${first.fix}${notes.length > 1 ? ` (and ${notes.length - 1} more: pantheon status)` : ""} — once handled: pantheon status --clear-safety`;
656
+ }
657
+ export function salvagePolicyText(text) {
658
+ const out = [];
659
+ for (const m of text.matchAll(/"cap:([a-z_]+)"/g))
660
+ out.push(`no to ${CAPABILITY_ARGS[m[1]] ?? m[1]} — pantheon policy revoke ${CAPABILITY_ARGS[m[1]] ?? m[1]}`);
661
+ for (const m of text.matchAll(/"wake:[^"|]+\|([^"]+)"/g))
662
+ out.push(`no to ${m[1]} waking this machine — pantheon wake deny ${m[1]}`);
663
+ for (const m of text.matchAll(/"(run_commands|self_upgrade|unsandboxed_runs)":\s*\{\s*"mode"/g))
664
+ out.push(`allowed ${CAPABILITY_ARGS[m[1]]} — pantheon policy grant ${CAPABILITY_ARGS[m[1]]}`);
665
+ return [...new Set(out)];
666
+ }
465
667
  //# sourceMappingURL=worker-policy.js.map