@join-pantheon/cli 0.33.8 → 0.33.9

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.
@@ -0,0 +1,418 @@
1
+ import { mkdirSync, statSync } from "node:fs";
2
+ import { homedir, platform } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+ import { AGENTS, agentById, claudeInstallSteps, SIGN_IN_CHECK } from "./agents.js";
5
+ import { pidAlive, readStateFile, withFileLock } from "./file-lock.js";
6
+ import { READINESS_ALERT_FILE, trustWrite } from "./home-guard.js";
7
+ import { DEFAULT_REMINDER_MS, MAX_REMINDERS, reminderGap } from "./notifier.js";
8
+ import { BUDGET, fit } from "./notice.js";
9
+ import { writeWhole } from "./pins.js";
10
+ export { READINESS_ALERT_FILE };
11
+ export const PERSON_CODES = new Set(["not_signed_in", "no_agent", "sandbox_unavailable"]);
12
+ export const FRESH_MS = 30 * 60_000;
13
+ export const CONFIRM_MS = 50_000;
14
+ export const PENDING_MAX_MS = 15 * 60_000;
15
+ const REFRESH_MS = 5 * 60_000;
16
+ const DAY_MS = 24 * 3_600_000;
17
+ export const PROBLEM_LEAD = "Unattended work can't run";
18
+ const CODES = new Set(["no_agent", "kiro_only", "not_signed_in", "unsandboxed_off", "no_agent_choice", "sandbox_unavailable"]);
19
+ const AGENT_IDS = new Set(AGENTS.map((a) => a.id));
20
+ const keyOf = (t) => `${t.code ?? ""}|${t.agent ?? ""}`;
21
+ const seenKey = (s) => (s.ok ? "ok" : keyOf(s));
22
+ const label = (agent) => (agent && agentById(agent)?.label) || "Your agent";
23
+ const openShell = (os) => (os === "darwin" ? "Open Terminal" : os === "win32" ? "Open PowerShell" : "Open a terminal");
24
+ const cap = (s) => (/^pantheon\b/.test(s) ? s : s.charAt(0).toUpperCase() + s.slice(1));
25
+ export function signInSteps(agent) {
26
+ return SIGN_IN_CHECK[agent].fix.replace(/^run\s+/, "type ").replace(/`/g, "");
27
+ }
28
+ const SIGN_IN_LINE = {
29
+ "claude-code": "claude auth login", codex: "codex login", cursor: "cursor-agent login", copilot: "copilot login", kiro: "kiro-cli login",
30
+ };
31
+ export const SIGN_IN_COMMANDS = {
32
+ "claude-code": { binary: "claude", args: ["auth", "login"] },
33
+ codex: { binary: "codex", args: ["login"] },
34
+ cursor: { binary: "cursor-agent", args: ["login"] },
35
+ copilot: { binary: "copilot", args: ["login"] },
36
+ kiro: { binary: "kiro-cli", args: ["login"] },
37
+ };
38
+ function notInstalled(agent) {
39
+ if (!agent)
40
+ return "No agent CLI is installed";
41
+ if (agent === "cursor")
42
+ return "Cursor's cursor-agent isn't installed";
43
+ if (agent === "copilot")
44
+ return "The Copilot CLI isn't installed";
45
+ return `${label(agent)} isn't installed`;
46
+ }
47
+ function installSteps(agent, os, gitMissing, short = false) {
48
+ if (!agent || agent === "claude-code")
49
+ return `${os === "win32" ? "" : "Install it: "}${claudeInstallSteps(os, { gitMissing, short })}`;
50
+ if (agent === "codex")
51
+ return "Install it: npm install -g @openai/codex — then type codex login";
52
+ if (agent === "copilot")
53
+ return "Install it: npm install -g @github/copilot — then type copilot login";
54
+ return "pantheon doctor shows how to install it";
55
+ }
56
+ export function problemLine(code, agent, os = platform()) {
57
+ if (code === "not_signed_in")
58
+ return `${label(agent ?? "claude-code")} is signed out — ${openShell(os).replace(/^Open/, "open")}, ${signInSteps(agent ?? "claude-code")}`;
59
+ if (code === "no_agent")
60
+ return `${notInstalled(agent)} — pantheon doctor shows how to install it`;
61
+ if (code === "sandbox_unavailable")
62
+ return `${label(agent ?? "claude-code")}'s sandbox can't start — pantheon doctor shows the fix`;
63
+ return null;
64
+ }
65
+ const forHowLong = (ms) => {
66
+ const h = Math.round(ms / 3_600_000);
67
+ if (h < 1)
68
+ return `${Math.max(1, Math.round(ms / 60_000))}m`;
69
+ return h < 48 ? `${h}h` : `${Math.round(h / 24)}d`;
70
+ };
71
+ const WHO = "Pantheon · this computer";
72
+ export const READINESS_TAG = "pantheon_readiness";
73
+ export function composeReadinessAlert(code, agent, o = {}) {
74
+ const os = o.os ?? platform();
75
+ const who = o.since !== undefined ? `${WHO} · for ${forHowLong((o.now ?? Date.now()) - o.since)} now` : WHO;
76
+ const base = { kind: "worker_failed", who: fit(who, BUDGET.who), context: "", ttl: 0, sound: o.since === undefined, tag: READINESS_TAG };
77
+ const button = (fix) => (os === "win32" ? {} : { fix });
78
+ if (code === "not_signed_in") {
79
+ const a = agent ?? "claude-code";
80
+ return {
81
+ ...base,
82
+ heading: "Your agent is signed out",
83
+ body: fit(`${label(a)} is signed out, so teammates' requests wait. ${openShell(os)}, ${signInSteps(a)}.`, BUDGET.body),
84
+ ...button({ label: "Sign in", kind: "sign_in", agent: a, dir: o.signInDir ?? homedir(), lines: [SIGN_IN_LINE[a]], why: `${label(a)} is signed out, so teammates' requests wait` }),
85
+ };
86
+ }
87
+ if (code === "no_agent") {
88
+ const head = notInstalled(agent);
89
+ const lead = `${head}${agent ? "" : " here"}, so teammates' requests wait. `;
90
+ const full = `${lead}${cap(installSteps(agent, os, !!o.gitMissing))}.`;
91
+ const short = `${lead}${cap(installSteps(agent, os, !!o.gitMissing, true))}.`;
92
+ const body = full.length <= BUDGET.body ? full : short.length <= BUDGET.body ? short
93
+ : `${head}, so teammates' requests wait. ${o.gitMissing ? "Install Git for Windows first, then Claude Code — " : ""}pantheon doctor shows each step.`;
94
+ return {
95
+ ...base,
96
+ heading: fit(head, BUDGET.heading),
97
+ body: fit(body, BUDGET.body),
98
+ ...button({ label: "Show me how", kind: "how", ...(agent ? { agent } : {}), dir: o.signInDir ?? homedir(), lines: [], why: head }),
99
+ };
100
+ }
101
+ const missing = /^install them:/.test(o.fix ?? "");
102
+ return {
103
+ ...base,
104
+ heading: "Your agent's sandbox can't start",
105
+ body: fit(`${label(agent ?? "claude-code")}'s sandbox can't start here, so teammates' requests can't run tests or push code. ${missing ? "Install bubblewrap and socat — pantheon doctor shows the commands." : "Run pantheon doctor: it names the cause and the fix."}`, BUDGET.body),
106
+ ...button({ label: "Show me how", kind: "how", agent: agent ?? "claude-code", dir: o.signInDir ?? homedir(), lines: [], why: "Your agent's sandbox can't start" }),
107
+ };
108
+ }
109
+ export function composeReadyAgain(agent) {
110
+ return {
111
+ kind: "worker", who: WHO, heading: "Your agent can take requests again", context: "",
112
+ body: fit(agent ? `${label(agent)} is ready, so teammates' requests run on this computer again.` : "Teammates' requests run on this computer again.", BUDGET.body),
113
+ ttl: 15, sound: false, tag: READINESS_TAG,
114
+ };
115
+ }
116
+ const num = (x) => (typeof x === "number" && Number.isFinite(x) ? x : null);
117
+ export function parseState(text, now) {
118
+ const out = { teams: {} };
119
+ if (!text)
120
+ return out;
121
+ let raw;
122
+ try {
123
+ raw = JSON.parse(text);
124
+ }
125
+ catch {
126
+ return out;
127
+ }
128
+ if (!raw || typeof raw !== "object")
129
+ return out;
130
+ const r = raw;
131
+ void now;
132
+ const at = (x) => { const n = num(x); return n === null || n <= 0 ? null : n; };
133
+ const seen = (x) => {
134
+ const e = x;
135
+ const t = at(e?.at);
136
+ if (!e || typeof e !== "object" || typeof e.ok !== "boolean" || t === null)
137
+ return undefined;
138
+ return { ok: e.ok, at: t,
139
+ ...(!e.ok && typeof e.code === "string" && CODES.has(e.code) ? { code: e.code } : {}),
140
+ ...(typeof e.agent === "string" && AGENT_IDS.has(e.agent) ? { agent: e.agent } : {}) };
141
+ };
142
+ if (r.teams && typeof r.teams === "object") {
143
+ for (const [k, v] of Object.entries(r.teams).slice(0, 100)) {
144
+ if (k.length > 200 || !v || typeof v !== "object")
145
+ continue;
146
+ const c = seen(v.confirmed), p = seen(v.pending);
147
+ if (c || p)
148
+ out.teams[k] = { ...(c ? { confirmed: c } : {}), ...(p ? { pending: p } : {}) };
149
+ }
150
+ }
151
+ const t = r.told;
152
+ const first = at(t?.first), last = at(t?.last), n = num(t?.reminded);
153
+ if (t && typeof t.code === "string" && PERSON_CODES.has(t.code) && first !== null && last !== null) {
154
+ out.told = { code: t.code, first, last, reminded: n === null ? 0 : Math.max(0, Math.min(MAX_REMINDERS, Math.floor(n))),
155
+ teams: Array.isArray(t.teams) ? t.teams.filter((x) => typeof x === "string" && x.length <= 200).slice(0, 100) : [],
156
+ ...(typeof t.agent === "string" && AGENT_IDS.has(t.agent) ? { agent: t.agent } : {}),
157
+ ...(t.silent === true ? { silent: true } : {}) };
158
+ }
159
+ return out;
160
+ }
161
+ export function stepReadinessAlert(prev, team, reading, o) {
162
+ const now = o.now;
163
+ let changed = false;
164
+ const clamp = (s, maxAge) => {
165
+ if (!s)
166
+ return undefined;
167
+ if (s.at > now) {
168
+ changed = true;
169
+ s = { ...s, at: now };
170
+ }
171
+ if (now - s.at >= maxAge) {
172
+ changed = true;
173
+ return undefined;
174
+ }
175
+ return s;
176
+ };
177
+ const teams = {};
178
+ for (const [k, e] of Object.entries(prev.teams)) {
179
+ const c = clamp(e.confirmed, DAY_MS), p = clamp(e.pending, PENDING_MAX_MS);
180
+ if (c || p)
181
+ teams[k] = { ...(c ? { confirmed: c } : {}), ...(p ? { pending: p } : {}) };
182
+ else
183
+ changed = true;
184
+ }
185
+ let told = prev.told;
186
+ if (told && (told.first > now || told.last > now)) {
187
+ told = { ...told, first: Math.min(told.first, now), last: Math.min(told.last, now) };
188
+ changed = true;
189
+ }
190
+ const legacy = team.includes("#") ? team.slice(0, team.lastIndexOf("#")) : undefined;
191
+ const at = team.lastIndexOf("@"), base = at > 0 ? team.slice(0, at) : null;
192
+ const gone = (k) => {
193
+ if (!base || !o.alive || teams[team] || !k.startsWith(`${base}@`))
194
+ return false;
195
+ const pid = Number(k.slice(base.length + 1));
196
+ return Number.isInteger(pid) && pid > 0 && !o.alive(pid);
197
+ };
198
+ const froms = Object.keys(teams).filter((k) => k !== team && (k === o.replaces || k === legacy || gone(k)))
199
+ .sort((x, y) => (teams[y].confirmed?.at ?? 0) - (teams[x].confirmed?.at ?? 0));
200
+ for (const from of froms) {
201
+ if (!teams[team])
202
+ teams[team] = teams[from];
203
+ delete teams[from];
204
+ if (told?.teams.includes(from))
205
+ told = { ...told, teams: [...new Set(told.teams.map((k) => (k === from ? team : k)))] };
206
+ changed = true;
207
+ }
208
+ const state = { teams, ...(told ? { told } : {}) };
209
+ let asked;
210
+ const canShow = () => (asked ??= typeof o.alerts === "function" ? (() => { try {
211
+ return o.alerts();
212
+ }
213
+ catch {
214
+ return false;
215
+ } })() : o.alerts);
216
+ const none = () => ({ state, notice: null, said: null, changed, pending: !!teams[team]?.pending });
217
+ if (reading.unknown)
218
+ return none();
219
+ const seen = { ok: reading.ok, at: now, ...(!reading.ok && reading.code ? { code: reading.code } : {}), ...(reading.agent ? { agent: reading.agent } : {}) };
220
+ const e = teams[team] ?? {};
221
+ let conf = e.confirmed, pend = e.pending;
222
+ if (conf && seenKey(conf) === seenKey(seen)) {
223
+ if (pend) {
224
+ pend = undefined;
225
+ changed = true;
226
+ }
227
+ if (now - conf.at >= REFRESH_MS || conf.agent !== seen.agent) {
228
+ conf = seen;
229
+ changed = true;
230
+ }
231
+ }
232
+ else if (pend && seenKey(pend) === seenKey(seen)) {
233
+ if (now - pend.at >= CONFIRM_MS) {
234
+ conf = seen;
235
+ pend = undefined;
236
+ changed = true;
237
+ }
238
+ }
239
+ else {
240
+ pend = seen;
241
+ changed = true;
242
+ }
243
+ teams[team] = { ...(conf ? { confirmed: conf } : {}), ...(pend ? { pending: pend } : {}) };
244
+ const result = (r) => ({ ...none(), ...r });
245
+ const fresh = Object.entries(teams).flatMap(([k, v]) => (v.confirmed && (k === team || now - v.confirmed.at < FRESH_MS) ? [[k, v.confirmed]] : []));
246
+ const stuck = fresh.filter(([, c]) => !c.ok && c.code && PERSON_CODES.has(c.code));
247
+ const alertFor = (c, extra = {}) => composeReadinessAlert(c.code, c.agent, { ...(o.os ? { os: o.os } : {}), ...(o.signInDir ? { signInDir: o.signInDir } : {}), ...(o.gitMissing ? { gitMissing: true } : {}),
248
+ ...(conf === c && reading.fix ? { fix: reading.fix } : {}), ...(extra.since !== undefined ? { since: extra.since, now } : {}) });
249
+ const tell = (c) => {
250
+ state.told = { code: c.code, ...(c.agent ? { agent: c.agent } : {}), teams: stuck.filter(([, x]) => keyOf(x) === keyOf(c)).map(([k]) => k), first: now, last: now, reminded: 0, ...(canShow() ? {} : { silent: true }) };
251
+ return result({ changed: true, notice: canShow() ? alertFor(c) : null, said: canShow() ? "alert" : null });
252
+ };
253
+ if (told) {
254
+ const holders = stuck.filter(([, c]) => keyOf(c) === keyOf(told));
255
+ if (holders.length) {
256
+ const names = [...new Set([...told.teams, ...holders.map(([k]) => k)])];
257
+ if (names.length !== told.teams.length) {
258
+ told = state.told = { ...told, teams: names };
259
+ changed = true;
260
+ }
261
+ const c = holders[0][1];
262
+ if (told.silent) {
263
+ if (!canShow())
264
+ return result({});
265
+ state.told = { code: told.code, ...(told.agent ? { agent: told.agent } : {}), teams: told.teams, first: told.first, last: now, reminded: 0 };
266
+ return result({ changed: true, notice: alertFor(c, now - told.first >= CONFIRM_MS * 2 ? { since: told.first } : {}), said: "alert" });
267
+ }
268
+ if (told.reminded < MAX_REMINDERS && now - told.last >= reminderGap(told.reminded, o.reminderMs ?? DEFAULT_REMINDER_MS) && canShow()) {
269
+ state.told = { ...told, last: now, reminded: told.reminded + 1 };
270
+ return result({ changed: true, notice: alertFor(c, { since: told.first }), said: "reminder" });
271
+ }
272
+ return result({ changed });
273
+ }
274
+ if (stuck.length)
275
+ return tell((stuck.find(([k]) => k === team) ?? stuck[0])[1]);
276
+ const theirs = fresh.filter(([k]) => told.teams.includes(k));
277
+ if (theirs.length ? theirs.every(([, c]) => c.ok) : !!conf?.ok) {
278
+ delete state.told;
279
+ const ready = theirs.length ? theirs[0][1] : conf?.ok ? conf : undefined;
280
+ const sayIt = !told.silent && !!ready && canShow();
281
+ return result({ changed: true, notice: sayIt ? composeReadyAgain(ready.agent) : null, said: sayIt ? "ready again" : null, ended: { code: told.code, ...(told.agent ? { agent: told.agent } : {}), first: told.first } });
282
+ }
283
+ return result({ changed });
284
+ }
285
+ if (stuck.length)
286
+ return tell((stuck.find(([k]) => k === team) ?? stuck[0])[1]);
287
+ return result({ changed });
288
+ }
289
+ export const LOCK_FAILURES_BEFORE_MEMORY = 5;
290
+ export class ReadinessAlerts {
291
+ file;
292
+ state = null;
293
+ writeFailed = false;
294
+ lockFailures = 0;
295
+ lockSaid = false;
296
+ shown = new Map();
297
+ constructor(file) {
298
+ this.file = file;
299
+ }
300
+ readDisk(now) {
301
+ try {
302
+ const text = readStateFile(this.file);
303
+ return text === null ? null : parseState(text, now);
304
+ }
305
+ catch {
306
+ return null;
307
+ }
308
+ }
309
+ memory(now) { return this.state ? parseState(JSON.stringify(this.state), now) : null; }
310
+ decide(team, reading, o, write) {
311
+ const now = o.now;
312
+ const loaded = (!write || this.writeFailed ? this.memory(now) ?? this.readDisk(now) : this.readDisk(now) ?? this.memory(now)) ?? { teams: {} };
313
+ if (loaded.told) {
314
+ const mine = this.state?.told;
315
+ if (mine && keyOf(mine) === keyOf(loaded.told) && mine.first === loaded.told.first) {
316
+ loaded.told.reminded = Math.min(loaded.told.reminded, mine.reminded + (loaded.told.last > mine.last ? 1 : 0));
317
+ loaded.told.last = Math.max(loaded.told.last, Math.min(mine.last, now));
318
+ if (!mine.silent)
319
+ delete loaded.told.silent;
320
+ }
321
+ else
322
+ loaded.told.reminded = 0;
323
+ }
324
+ const r = stepReadinessAlert(loaded, team, reading, o);
325
+ this.state = r.state;
326
+ if (write && r.changed) {
327
+ try {
328
+ mkdirSync(dirname(this.file), { recursive: true, mode: 0o700 });
329
+ let plain = true;
330
+ try {
331
+ plain = statSync(this.file).isFile();
332
+ }
333
+ catch { }
334
+ if (!plain)
335
+ throw new Error("not a plain file");
336
+ writeWhole(this.file, JSON.stringify(r.state) + "\n");
337
+ trustWrite(this.file);
338
+ this.writeFailed = false;
339
+ }
340
+ catch {
341
+ this.writeFailed = true;
342
+ }
343
+ }
344
+ return r;
345
+ }
346
+ floor(r, o) {
347
+ if (!r.notice)
348
+ return r;
349
+ const t = r.said === "ready again" ? r.ended : r.state.told;
350
+ const k = t ? `${r.said === "ready again" ? "ready|" : ""}${keyOf(t)}|${t.first}` : null;
351
+ if (!k)
352
+ return r;
353
+ const gap = reminderGap(0, o.reminderMs ?? DEFAULT_REMINDER_MS);
354
+ const at = this.shown.get(k);
355
+ if (at !== undefined && Math.abs(o.now - at) < gap)
356
+ return { ...r, notice: null, said: null };
357
+ this.shown.set(k, o.now);
358
+ if (this.shown.size > 50)
359
+ this.shown.delete(this.shown.keys().next().value);
360
+ return r;
361
+ }
362
+ observe(team, reading, opts) {
363
+ const { log, ...rest } = opts;
364
+ const o = { alive: pidAlive, ...rest, now: opts.now ?? Date.now() };
365
+ const out = (r) => { const f = this.floor(r, o); return { notice: f.notice, said: f.said, pending: f.pending }; };
366
+ const memoryOnly = () => {
367
+ if (!this.lockSaid) {
368
+ this.lockSaid = true;
369
+ log?.(`! ${this.file}.lock cannot be taken: what you are told about this computer is decided from memory and not saved until it can be`);
370
+ }
371
+ this.writeFailed = true;
372
+ try {
373
+ return out(this.decide(team, reading, o, false));
374
+ }
375
+ catch {
376
+ return { notice: null, said: null, pending: false };
377
+ }
378
+ };
379
+ if (this.lockFailures >= LOCK_FAILURES_BEFORE_MEMORY && this.lockFailures % 10 !== 0) {
380
+ this.lockFailures++;
381
+ return memoryOnly();
382
+ }
383
+ try {
384
+ const r = withFileLock(this.file, () => this.decide(team, reading, o, true), 2_000);
385
+ this.lockFailures = 0;
386
+ return out(r);
387
+ }
388
+ catch {
389
+ this.lockFailures++;
390
+ return memoryOnly();
391
+ }
392
+ }
393
+ }
394
+ const byHome = new Map();
395
+ export function readinessAlerts(home) {
396
+ const f = join(home, READINESS_ALERT_FILE);
397
+ let a = byHome.get(f);
398
+ if (!a) {
399
+ a = new ReadinessAlerts(f);
400
+ byHome.set(f, a);
401
+ }
402
+ return a;
403
+ }
404
+ export function forgetReadinessAlerts() { byHome.clear(); }
405
+ export function agentProblem(home, now = Date.now(), os = platform()) {
406
+ let text = null;
407
+ try {
408
+ text = readStateFile(join(home, READINESS_ALERT_FILE));
409
+ }
410
+ catch {
411
+ return null;
412
+ }
413
+ const s = parseState(text, now);
414
+ const stuck = Object.keys(s.teams).sort().map((k) => s.teams[k].confirmed).filter((v) => !!v && now - v.at < FRESH_MS && !v.ok && !!v.code && PERSON_CODES.has(v.code));
415
+ const first = (s.told && stuck.find((v) => keyOf(v) === keyOf(s.told))) || stuck[0];
416
+ return first ? problemLine(first.code, first.agent, os) : null;
417
+ }
418
+ //# sourceMappingURL=readiness-alert.js.map
package/dist/tray.js CHANGED
@@ -15,6 +15,7 @@ import { clearRemoval, recordRemoval, removalFor, removalHolds, removalRefusal }
15
15
  import { pickupEstimate } from "./pickup.js";
16
16
  import { allDecisionsPrompt, decisionPrompt, decisionTitle, owedPrompt, stripCeremony, tidyIds, tidyLead, waitingPrompt, workerSummary } from "./decision-ui.js";
17
17
  import { loadProfile, SURFACE_BUNDLE_IDS } from "./profile.js";
18
+ import { agentProblem, PROBLEM_LEAD } from "./readiness-alert.js";
18
19
  const HERE = dirname(fileURLToPath(import.meta.url));
19
20
  export const trayBinaryPath = (home = CONFIG_DIR) => join(home, "bin", "pantheon-tray");
20
21
  export const traySourcePath = () => resolve(HERE, "..", "helper", "macos", "menubar.swift");
@@ -262,6 +263,12 @@ async function trayStatusOne(cfg) {
262
263
  const surface = profile.agent.primary_surface;
263
264
  const surfaceName = surface === "claude-code" ? "Claude" : surface === "cursor" ? "Cursor" : surface === "copilot" ? "Copilot" : surface === "kiro" ? "Kiro" : "Codex";
264
265
  const rawWorkerState = workerState();
266
+ const problem = (() => { try {
267
+ return agentProblem(CONFIG_DIR);
268
+ }
269
+ catch {
270
+ return null;
271
+ } })();
265
272
  return {
266
273
  configured: true,
267
274
  version: VERSION,
@@ -280,7 +287,7 @@ async function trayStatusOne(cfg) {
280
287
  worker_plist: plistPath("worker"),
281
288
  notifier_running: notifierProc().running,
282
289
  hook_on: agentHookStates().length > 0,
283
- ...(rawWorkerState ? { worker_state: workerSummary(rawWorkerState) } : {}),
290
+ ...(problem ? { agent_problem: problem, agent_problem_lead: PROBLEM_LEAD, worker_state: `${PROBLEM_LEAD}: ${problem}` } : rawWorkerState ? { worker_state: workerSummary(rawWorkerState) } : {}),
284
291
  surface_name: surfaceName,
285
292
  surface_bundle_id: SURFACE_BUNDLE_IDS[surface],
286
293
  decisions_prompt: allDecisionsPrompt(decisions.length),
package/dist/worker.js CHANGED
@@ -15,18 +15,19 @@ import { mkdirInside, writeInside } from "./safe-write.js";
15
15
  import { corruptHeldFiles, MAX_HELD_PER_RUN, remoteTipIs, takeHeldFrames, updateHeldState, verifyHeldFrame, writeHoldConfig } from "./held-delivery.js";
16
16
  import { adoptedCommon, adoptWorktree, gitCallEnv, lfsInUse, repoHooksArgs, safeGitArgs, WorktreeTampered } from "./git-safe.js";
17
17
  import { trusted } from "./verify-act.js";
18
- import { headlessSpawn, materializeSpawnFiles, chooseAgent, agentById, describeChoice, unattendedRefusal, unattendedRefusalOf, SIGN_IN_CHECK, SANDBOXED_FOR_UNATTENDED, NOT_FOR_UNATTENDED_RUNS, claudeSandboxable, unattendedReadiness, anyUnattendedAgentOnPath, forgetMissingBinaries, quarantineRepoAgentConfig, AGENT_EDIT_SUFFIX, REPO_AGENT_CONFIG, COMMAND_GRANT_SCOPE, repoCommands, REPO_COMMANDS_FILE, claudeCommandRules, } from "./agents.js";
18
+ import { headlessSpawn, materializeSpawnFiles, chooseAgent, agentById, describeChoice, unattendedRefusal, unattendedRefusalOf, SIGN_IN_CHECK, SANDBOXED_FOR_UNATTENDED, NOT_FOR_UNATTENDED_RUNS, claudeSandboxable, unattendedReadiness, anyUnattendedAgentOnPath, forgetMissingBinaries, gitMissing, quarantineRepoAgentConfig, AGENT_EDIT_SUFFIX, REPO_AGENT_CONFIG, COMMAND_GRANT_SCOPE, repoCommands, REPO_COMMANDS_FILE, claudeCommandRules, } from "./agents.js";
19
19
  import { activeOutages, detectOutage, earliest, whenAgain } from "./agent-outage.js";
20
20
  import { agentSpawn, CmdLineUnsafe } from "./which.js";
21
21
  import { VERSION } from "./version.js";
22
- import { applyAnswer, CAPABILITY_ARGS, CARRY_REASON, carryOverWakers, dropLedgerGrants, hasWakeOnce, isApprovedWaker, mayAskWake, takeWakeOnce, OLD_RELAY_WAKE, relayKnowsAdmitters, loadPolicy, mayAsk, needsSelfUpgrade, parseGrantAnswer, recordAsk, savePolicy, useGrant, WOKEN_RUN_ENV, takeTeamFlagOnYes, unsandboxedAllowed, policyPath, isNewer, RUN_MINUTES, effectiveRunMinutes, effectiveIdleSeconds, readinessRecheckPath, describeRunMinutes, parseRunMinutes, } from "./worker-policy.js";
22
+ import { applyAnswer, CAPABILITY_ARGS, CARRY_REASON, carryOverWakers, dropLedgerGrants, hasWakeOnce, isApprovedWaker, mayAskWake, takeWakeOnce, OLD_RELAY_WAKE, relayKnowsAdmitters, loadPolicy, mayAsk, needsSelfUpgrade, parseGrantAnswer, recordAsk, savePolicy, useGrant, WOKEN_RUN_ENV, takeTeamFlagOnYes, unsandboxedAllowed, policyPath, isNewer, RUN_MINUTES, effectiveRunMinutes, effectiveIdleSeconds, readinessRecheckPath, policyHome, describeRunMinutes, parseRunMinutes, } from "./worker-policy.js";
23
+ import { readinessAlerts } from "./readiness-alert.js";
23
24
  import { runtimeNodeVersion } from "./managed.js";
24
25
  import { removalWords, removedLine, removedNotice, takeTold } from "./removed.js";
25
26
  import { agentHookStates, repairHook, repairNote } from "./notify.js";
26
27
  import { fence, assess } from "./untrusted.js";
27
28
  import { allowed, closeStartedRun, finishRun, recordRun, startRun } from "./spend.js";
28
29
  import { handledIn, loadContinued, markContinued, unmarkContinued, wakeAlertedKey } from "./continued.js";
29
- import { loadProfile, profileForTeam, reservedDecisionsNote, saveProfile, wakeMode } from "./profile.js";
30
+ import { decisionAlertsOn, loadProfile, profileForTeam, reservedDecisionsNote, saveProfile, wakeMode } from "./profile.js";
30
31
  import { clip } from "./brief.js";
31
32
  import { composeWakeAsk, composeWorker } from "./notice.js";
32
33
  import { diagnoseRun, gitProbe, workNeedsCommands } from "./run-failure.js";
@@ -1179,19 +1180,21 @@ export class Worker {
1179
1180
  }
1180
1181
  tickHold = null;
1181
1182
  readiness = null;
1183
+ alertPending = false;
1182
1184
  readinessAt = 0;
1183
1185
  checkReadiness(force) {
1184
1186
  const now = Date.now();
1185
- const every = this.readiness && !this.readiness.ok ? WORKER_READINESS_RETRY_MS : WORKER_READINESS_MS;
1187
+ const every = (this.readiness && !this.readiness.ok) || this.alertPending ? WORKER_READINESS_RETRY_MS : WORKER_READINESS_MS;
1186
1188
  let marked = false;
1187
1189
  try {
1188
1190
  const t = statSync(readinessRecheckPath(this.opts.home)).mtimeMs;
1189
1191
  marked = t > this.readinessAt && t <= now + 1_000;
1190
1192
  }
1191
1193
  catch { }
1192
- if (!force && !marked && now - this.readinessAt < every)
1194
+ const since = now - this.readinessAt;
1195
+ if (!force && !marked && since >= 0 && since < every)
1193
1196
  return;
1194
- if ((force || marked) && now - this.readinessAt < 15_000)
1197
+ if ((force || marked) && since >= 0 && since < 15_000)
1195
1198
  return;
1196
1199
  this.readinessAt = now;
1197
1200
  if (force || marked)
@@ -1201,26 +1204,76 @@ export class Worker {
1201
1204
  return;
1202
1205
  }
1203
1206
  try {
1204
- const pathOnly = this.readiness && !this.readiness.ok && (this.readiness.code === "no_agent" || this.readiness.code === "kiro_only") && !marked && !force;
1205
- if (pathOnly && !anyUnattendedAgentOnPath())
1207
+ const pathOnly = !this.opts.readinessCheck && this.readiness && !this.readiness.ok && (this.readiness.code === "no_agent" || this.readiness.code === "kiro_only") && !marked && !force;
1208
+ if (pathOnly && !anyUnattendedAgentOnPath()) {
1209
+ this.tellPerson(now);
1206
1210
  return;
1211
+ }
1207
1212
  let commandsOn = false;
1208
1213
  try {
1209
1214
  commandsOn = commandState({ home: this.opts.home, project: this.opts.project, allowBash: this.opts.allowBash }).level !== "off";
1210
1215
  }
1211
1216
  catch { }
1212
- const r = unattendedReadiness({ prefer: loadProfile(this.cfg).agent.primary_surface, unsandboxedOk: this.unsandboxedOk(), pinned: this.opts.agent ?? "auto", ...(this.opts.choose ? { choose: this.opts.choose } : {}),
1217
+ this.readinessCommandsOn = commandsOn;
1218
+ const r = this.opts.readinessCheck ? this.opts.readinessCheck() : unattendedReadiness({ prefer: loadProfile(this.cfg).agent.primary_surface, unsandboxedOk: this.unsandboxedOk(), pinned: this.opts.agent ?? "auto", ...(this.opts.choose ? { choose: this.opts.choose } : {}),
1213
1219
  commandsOn, inContainer: hostEnv().kind === "container", ...(this.opts.sandboxProbe ? { sandboxProbe: this.opts.sandboxProbe } : {}) });
1214
1220
  if (!r.ok && (this.readiness?.ok ?? true))
1215
1221
  this.opts.log(`! teammates are told this machine can't take requests yet: ${r.short} — ${r.fix}`);
1216
1222
  if (r.ok && this.readiness && !this.readiness.ok)
1217
1223
  this.opts.log(` agent ready again — teammates are told this machine takes requests`);
1218
- this.readiness = { ok: r.ok, short: r.short, ...(r.code ? { code: r.code } : {}), ...(r.pinned ? { pinned: true } : {}) };
1224
+ this.readiness = { ok: r.ok, short: r.short, ...(r.code ? { code: r.code } : {}), ...(r.pinned ? { pinned: true } : {}), ...(r.agent ? { agent: r.agent } : {}), ...(r.fix ? { fix: r.fix } : {}), ...(r.unknown ? { unknown: true } : {}) };
1225
+ this.tellPerson(now);
1219
1226
  }
1220
1227
  catch {
1221
1228
  this.readiness = null;
1222
1229
  }
1223
1230
  }
1231
+ readinessCommandsOn = false;
1232
+ lastReadinessKey = null;
1233
+ readinessKey() {
1234
+ const commands = this.readinessCommandsOn && process.platform === "linux";
1235
+ const who = createHash("sha256").update(`${resolve(this.opts.project)}|${this.opts.agent ?? "auto"}|${commands ? "commands" : "-"}`).digest("hex").slice(0, 12);
1236
+ return `${this.spaceKey()}#${who}@${process.pid}`;
1237
+ }
1238
+ tellPerson(now) {
1239
+ const r = this.readiness;
1240
+ if (!r)
1241
+ return;
1242
+ const alerts = () => {
1243
+ if (!this.opts.notify || !decisionAlertsOn())
1244
+ return false;
1245
+ try {
1246
+ return !this.opts.canAlert || this.opts.canAlert();
1247
+ }
1248
+ catch {
1249
+ return false;
1250
+ }
1251
+ };
1252
+ try {
1253
+ let agent = r.agent;
1254
+ if (!agent && r.code === "no_agent") {
1255
+ try {
1256
+ const p = loadProfile(this.cfg).agent.primary_surface;
1257
+ if (p === "claude-code" || p === "codex" || p === "cursor" || p === "copilot")
1258
+ agent = p;
1259
+ }
1260
+ catch { }
1261
+ }
1262
+ const key = this.readinessKey();
1263
+ const replaces = this.lastReadinessKey && this.lastReadinessKey !== key ? this.lastReadinessKey : undefined;
1264
+ this.lastReadinessKey = key;
1265
+ const t = readinessAlerts(policyHome(this.opts.home)).observe(key, { ok: r.ok, ...(r.code ? { code: r.code } : {}), ...(agent ? { agent } : {}), ...(r.fix ? { fix: r.fix } : {}), ...(r.unknown ? { unknown: true } : {}) }, { now, alerts, log: this.opts.log, ...(replaces ? { replaces } : {}), ...(r.code === "no_agent" && gitMissing() ? { gitMissing: true } : {}) });
1266
+ this.alertPending = t.pending;
1267
+ if (!t.notice)
1268
+ return;
1269
+ this.opts.log(`> told you${t.said === "reminder" ? " again" : ""}: ${t.notice.heading} — ${t.notice.body}`);
1270
+ try {
1271
+ this.opts.notify?.(t.notice);
1272
+ }
1273
+ catch { }
1274
+ }
1275
+ catch { }
1276
+ }
1224
1277
  reportStanding(first, held) {
1225
1278
  const now = Date.now();
1226
1279
  this.checkReadiness(first);