@phren/cli 0.3.66 → 0.3.67

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.
@@ -43,6 +43,13 @@ export interface ApprovalPush {
43
43
  request?: string;
44
44
  requestKind?: RequestKind;
45
45
  }
46
+ export interface MachineHealthPush {
47
+ computer: string;
48
+ id: string;
49
+ title: string;
50
+ detail: string;
51
+ fix: string;
52
+ }
46
53
  export interface FanoutBlockedPush {
47
54
  job: string;
48
55
  label: string;
@@ -72,6 +79,7 @@ export declare function approvalPushPayload(value: ApprovalPush, host?: string):
72
79
  * notification action. */
73
80
  export declare function sudoPushPayload(value: SudoRequestView, host?: string): Record<string, unknown>;
74
81
  export declare function fanoutBlockedPushPayload(value: FanoutBlockedPush): Record<string, unknown>;
82
+ export declare function machineHealthPushPayload(value: MachineHealthPush, host?: string): Record<string, unknown>;
75
83
  export declare function schedulePushPayload(value: SchedulePush): Record<string, unknown>;
76
84
  /** What `phren bridge doctor` prints when the Hook has no APNs sender. */
77
85
  export declare function apnsSetupSteps(configFile?: string): string;
@@ -139,6 +147,8 @@ export declare class ApprovalPushService {
139
147
  * phones already accept agent alerts; the payload carries the reason so the
140
148
  * notification is actionable on its own. */
141
149
  notifyFanoutBlocked(value: FanoutBlockedPush): Promise<boolean>;
150
+ /** A new high-severity machine health finding (machine-health-alerts.ts dedupes). */
151
+ notifyMachineHealth(value: MachineHealthPush): Promise<boolean>;
142
152
  notifySchedule(value: SchedulePush): Promise<SchedulePushResult>;
143
153
  }
144
154
  export {};
@@ -64,6 +64,12 @@ export function fanoutBlockedPushPayload(value) {
64
64
  phren: { kind: "fanoutBlocked", job: value.job, provider: value.provider, label: value.label, reason: value.reason },
65
65
  };
66
66
  }
67
+ export function machineHealthPushPayload(value, host) {
68
+ return {
69
+ aps: { alert: { title: `${value.computer}: ${value.title}`, body: `${value.detail} ${value.fix}`.trim() }, sound: "default", category: "PHREN_HEALTH" },
70
+ phren: { kind: "machineHealth", ...(host ? { host } : {}), computer: value.computer, id: value.id, title: value.title, detail: value.detail, fix: value.fix, route: "resources" },
71
+ };
72
+ }
67
73
  export function schedulePushPayload(value) {
68
74
  const state = value.kind === "scheduleStarted" ? "started" : value.kind === "scheduleFinished" ? (value.status === "needs-you" ? "needs you" : "finished")
69
75
  : value.kind === "scheduleBlocked" ? "blocked" : "failed";
@@ -309,6 +315,15 @@ export class ApprovalPushService {
309
315
  expiration: "0", collapseId: `fanout-${value.job}`,
310
316
  })))).some(Boolean);
311
317
  }
318
+ /** A new high-severity machine health finding (machine-health-alerts.ts dedupes). */
319
+ async notifyMachineHealth(value) {
320
+ const devices = this.reachable.filter(device => device.kinds.includes("approval"));
321
+ if (!devices.length)
322
+ return false;
323
+ return (await Promise.all(devices.map(device => this.send(device, machineHealthPushPayload(value, device.hostID), {
324
+ expiration: "0", collapseId: `health-${value.id}`.slice(0, 64),
325
+ })))).some(Boolean);
326
+ }
312
327
  async notifySchedule(value) {
313
328
  const reachable = this.reachable;
314
329
  if (!reachable.length)
@@ -1,4 +1,5 @@
1
1
  import { type CleanupReport, type JobSource, type ProcessLike, type TrackedJob } from "./job-registry.js";
2
+ import { type HealthFinding } from "./machine-health.js";
2
3
  /**
3
4
  * This computer's live resources for `GET /v1/resources`, the overview
4
5
  * stream's `resources` frames and the memory-free `phren computers` surface:
@@ -74,6 +75,8 @@ export interface ComputerResources {
74
75
  };
75
76
  level: "ok" | "busy" | "stressed";
76
77
  warnings: Array<"load-high" | "memory-low" | "disk-low" | "battery-low">;
78
+ /** Named health findings with severity and a fix (machine-health.ts), worst first. */
79
+ health?: HealthFinding[];
77
80
  }
78
81
  /** What the computer is, read once per Hook run: "MacBook Pro", "Apple M1 Max",
79
82
  * 32 GB; on Linux the DMI vendor and product ("Dell XPS 13 9310") and the CPU's
@@ -158,6 +161,8 @@ export interface ResourceDeps {
158
161
  } | undefined>;
159
162
  hardware?: () => Promise<ComputerHardware | undefined>;
160
163
  jobs?: JobSource;
164
+ /** Named findings for this read from the numbers and the process table. */
165
+ health?: (value: ComputerResources, rows: ProcessRow[]) => HealthFinding[];
161
166
  }
162
167
  export declare function collectResources(deps: ResourceDeps): Promise<ComputerResources>;
163
168
  /** One collection at a time, reused for `RESOURCES_MAX_AGE_MS`. */
@@ -8,6 +8,8 @@ import { recentServers, sharedSnapshot } from "./herdr.js";
8
8
  import { JobRegistry, jobPgids, paneKey } from "./job-registry.js";
9
9
  import { intervalFromEnv } from "./limits.js";
10
10
  import { objects } from "./protocol.js";
11
+ import { MachineHealth } from "./machine-health.js";
12
+ import { PlatformProbes } from "./machine-probes.js";
11
13
  const exec = promisify(execFile);
12
14
  /**
13
15
  * This computer's live resources for `GET /v1/resources`, the overview
@@ -420,7 +422,17 @@ export async function collectResources(deps) {
420
422
  memory, ...(disk ? { disk } : {}), ...(battery ? { battery } : {}), ...(hardware ? { hardware } : {}),
421
423
  heavy: owners.size || jobs.length ? heavyProcesses(rows, owners, jobs) : preliminary,
422
424
  };
423
- return { ...value, ...assess(value) };
425
+ const result = { ...value, ...assess(value) };
426
+ const check = deps.health;
427
+ if (!check)
428
+ return result;
429
+ const health = (() => { try {
430
+ return check(result, rows);
431
+ }
432
+ catch {
433
+ return undefined;
434
+ } })();
435
+ return health ? { ...result, health } : result;
424
436
  }
425
437
  /** One collection at a time, reused for `RESOURCES_MAX_AGE_MS`. */
426
438
  export class ResourceMonitor {
@@ -432,7 +444,9 @@ export class ResourceMonitor {
432
444
  constructor(deps = {}, maxAgeMs = RESOURCES_MAX_AGE_MS) {
433
445
  this.maxAgeMs = maxAgeMs;
434
446
  this.registry = deps.jobs ?? new JobRegistry();
435
- this.deps = { platform: process.platform, now: Date.now, home: homeDir, processes: processTable, owners: paneOwners, panes: livePanes, ...deps, jobs: this.registry };
447
+ const health = new MachineHealth(process.env.PHREN_HEALTH_PROBES === "off" ? undefined : new PlatformProbes());
448
+ this.deps = { platform: process.platform, now: Date.now, home: homeDir, processes: processTable, owners: paneOwners, panes: livePanes,
449
+ health: (value, rows) => health.assess(value, rows, this.deps.now()), ...deps, jobs: this.registry };
436
450
  }
437
451
  async read() {
438
452
  if (this.cached && this.deps.now() - this.cached.at < this.maxAgeMs)
@@ -152,7 +152,7 @@ async function launchInHerdr(server, context, launchHerdr, signal) {
152
152
  // The prompt goes with the launch where the harness takes one (Claude,
153
153
  // Codex); otherwise it is typed once the agent is ready.
154
154
  const brief = context.schedule.prompt.trim() ? { brief: { id: context.runId, text: context.schedule.prompt } } : {};
155
- const launched = await launchHerdr(server, { cwd: context.cwd, label: context.schedule.name, kind: context.schedule.harness, model: context.schedule.model, ...(context.schedule.account ? { account: context.schedule.account } : {}), ...brief });
155
+ const launched = await launchHerdr(server, { cwd: context.cwd, label: context.schedule.name, kind: context.schedule.harness, model: context.schedule.model, project: context.project, ...(context.schedule.account ? { account: context.schedule.account } : {}), ...brief });
156
156
  const workspaceId = String(launched.workspaceId), tabId = String(launched.tabId), paneId = String(launched.paneId);
157
157
  if (launched.briefLaunched !== true)
158
158
  await promptWhenReady(server, paneId, context.schedule.prompt, signal);
@@ -202,7 +202,7 @@ export function headlessEnv(schedule, env = process.env) {
202
202
  async function launchHeadless(context, store, started) {
203
203
  // A Claude schedule that names no account runs under the one with the most room, as a Herdr launch does.
204
204
  const choice = context.schedule.harness === "claude" && !context.schedule.account
205
- ? await pickClaudeAccount(`Schedule "${context.schedule.name}"`).catch(() => undefined) : undefined;
205
+ ? await pickClaudeAccount(`Schedule "${context.schedule.name}"`, { project: context.project, cwd: context.cwd }) : undefined;
206
206
  const env = headlessEnv(choice ? { ...context.schedule, account: choice.account } : context.schedule);
207
207
  const root = fanoutRoot({ ...process.env, PHREN_PATH: store }), jobDir = path.join(root, context.runId);
208
208
  await mkdir(jobDir, { recursive: true, mode: 0o700 });
@@ -426,7 +426,9 @@ async function startSession(server, data, options) {
426
426
  const timeout = Math.min(120_000, Math.max(3_001, data.timeoutMs === undefined ? 45_000 : z.number().int().parse(data.timeoutMs)));
427
427
  // Checked before anything is created, so a refusal leaves no pane, worktree or brief file behind.
428
428
  // A Claude launch that names no account runs under the signed-in one with the most room left.
429
- const choice = kind === "claude" && named === undefined ? await pickClaudeAccount(`Launch "${label}"`).catch(() => undefined) : undefined;
429
+ // Pools and roles apply as in dispatch: a 409 account_pool when no account may do this project's work.
430
+ const project = typeof data.project === "string" && data.project ? data.project : undefined;
431
+ const choice = kind === "claude" && named === undefined ? await pickClaudeAccount(`Launch "${label}"`, { project, cwd: projectDirectory }) : undefined;
430
432
  const account = named ?? choice?.account;
431
433
  await requireAvailable(kind, account);
432
434
  const home = kind === "claude" && account && account !== DEFAULT_ACCOUNT ? claudeHome(account) : undefined;
@@ -49,6 +49,7 @@ import { PermissionModeSwitcher } from "./permission-mode.js";
49
49
  import { SideQuestions } from "./side-questions.js";
50
50
  import { AccountUsageReader } from "./usage.js";
51
51
  import { ResourceMonitor } from "./resources.js";
52
+ import { ALERT_CHECK_MS, HealthAlerts } from "./machine-health-alerts.js";
52
53
  import { createScheduleLauncher, Scheduler, scheduleRunsFile } from "./schedules.js";
53
54
  import { dailyCanaryDue, runCanary } from "./canary.js";
54
55
  import { defaultPhrenPath } from "../shared.js";
@@ -343,6 +344,9 @@ export async function serve(version, options = {}) {
343
344
  // Every store converges with its remote even when no agent session runs here (store-sync.ts).
344
345
  const storeSync = startStoreSyncLoop(scheduleStore);
345
346
  const canaryTimer = setInterval(() => { countTick("canary"); void dailyCanaryDue().then(due => due ? canary("daily") : undefined).catch(() => { }); }, 10 * 60_000);
347
+ // A new high machine health finding reaches the phone once (machine-health-alerts.ts).
348
+ const healthAlerts = new HealthAlerts(finding => agentHooks.push.notifyMachineHealth({ computer: hostname(), ...finding }));
349
+ const healthTimer = setInterval(() => { countTick("health"); void resources.read().then(value => healthAlerts.observe(value.health, Date.now())).catch(() => { }); }, ALERT_CHECK_MS);
346
350
  let recording = false;
347
351
  const activityTimer = setInterval(() => {
348
352
  countTick("activity");
@@ -391,7 +395,7 @@ export async function serve(version, options = {}) {
391
395
  })().finally(() => { recording = false; }).catch(() => { });
392
396
  }, 5000);
393
397
  await new Promise(resolve => {
394
- const stop = () => { gitboyWebhooks.stop(); storePulls.stop(); storeSync.stop(); fanoutMessages.close(); stopRetention(); clearInterval(scheduleTimer); clearInterval(canaryTimer); clearInterval(codexAuthTimer); clearInterval(activityTimer); scheduler?.close(); codeReindexer?.close(); codexServers.close(); agentHooks.close(); ws.clients.forEach(c => c.terminate()); ws.close(); http.close(() => resolve()); http.closeAllConnections(); };
398
+ const stop = () => { gitboyWebhooks.stop(); storePulls.stop(); storeSync.stop(); fanoutMessages.close(); stopRetention(); clearInterval(scheduleTimer); clearInterval(canaryTimer); clearInterval(healthTimer); clearInterval(codexAuthTimer); clearInterval(activityTimer); scheduler?.close(); codeReindexer?.close(); codexServers.close(); agentHooks.close(); ws.clients.forEach(c => c.terminate()); ws.close(); http.close(() => resolve()); http.closeAllConnections(); };
395
399
  process.once("SIGTERM", stop);
396
400
  process.once("SIGINT", stop);
397
401
  });