@phren/cli 0.3.78 → 0.3.80

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 (39) hide show
  1. package/dist/bridge/dispatch.js +17 -3
  2. package/dist/bridge/files.d.ts +1 -1
  3. package/dist/bridge/housekeeping/command.d.ts +5 -0
  4. package/dist/bridge/housekeeping/command.js +106 -0
  5. package/dist/bridge/housekeeping/housekeeper.d.ts +123 -0
  6. package/dist/bridge/housekeeping/housekeeper.js +459 -0
  7. package/dist/bridge/housekeeping/inventory.d.ts +145 -0
  8. package/dist/bridge/housekeeping/inventory.js +276 -0
  9. package/dist/bridge/housekeeping/report.d.ts +672 -0
  10. package/dist/bridge/housekeeping/report.js +168 -0
  11. package/dist/bridge/housekeeping/safety.d.ts +177 -0
  12. package/dist/bridge/housekeeping/safety.js +466 -0
  13. package/dist/bridge/owner-proof.d.ts +41 -0
  14. package/dist/bridge/owner-proof.js +119 -0
  15. package/dist/bridge/push.js +3 -1
  16. package/dist/bridge/resources.d.ts +8 -0
  17. package/dist/bridge/resources.js +18 -5
  18. package/dist/bridge/server-pane-routes.d.ts +6 -0
  19. package/dist/bridge/server-pane-routes.js +1 -1
  20. package/dist/bridge/server-routes.d.ts +6 -0
  21. package/dist/bridge/server-routes.js +53 -4
  22. package/dist/bridge/server.js +44 -8
  23. package/dist/bridge-hook.mjs +3093 -1219
  24. package/dist/cli-registry.js +18 -1
  25. package/dist/fanout/command.js +42 -15
  26. package/dist/heavy/budget-status.d.ts +26 -0
  27. package/dist/heavy/budget-status.js +26 -0
  28. package/dist/heavy/budget.d.ts +39 -0
  29. package/dist/heavy/budget.js +57 -0
  30. package/dist/heavy/command.d.ts +15 -0
  31. package/dist/heavy/command.js +119 -0
  32. package/dist/heavy/reap.d.ts +70 -0
  33. package/dist/heavy/reap.js +211 -0
  34. package/dist/heavy/slots.d.ts +58 -0
  35. package/dist/heavy/slots.js +142 -0
  36. package/dist/modules/registry.js +5 -4
  37. package/package.json +1 -1
  38. package/starter/global/skills/conductor/SKILL.md +10 -0
  39. package/starter/global/skills/fanout/SKILL.md +30 -0
@@ -949,14 +949,16 @@ async function capacity(host, caller) {
949
949
  // Missing from an older Hook or a slow read: that computer's quota is unknown, so it is never ruled out by it.
950
950
  usage: z.array(z.object({ source: z.string(), account: z.string().optional(), leftPercent: z.number().min(0).max(100).optional(),
951
951
  exhausted: z.boolean().optional(), until: z.string().max(40).optional(), fiveHour: windowRoom, week: windowRoom }).passthrough()).max(64).optional(),
952
- knowsCaller: z.boolean().optional() }).parse(value);
952
+ knowsCaller: z.boolean().optional(),
953
+ // Missing from an older Hook: its memory and load are unknown, never a reason to pass it over.
954
+ overBudget: z.string().max(500).optional() }).parse(value);
953
955
  // This computer places on whichever Herdr server its own Hook runs.
954
956
  if (host.local && !result.servers.includes(host.server) && result.servers[0])
955
957
  host.server = result.servers[0];
956
958
  if (!result.servers.includes(host.server))
957
959
  throw new BridgeError(503, "Herdr is not running on the selected computer. Headless dispatch is not installed yet.");
958
960
  return { working: result.working, computerId: result.computer.id, ...(result.harnesses ? { harnesses: result.harnesses } : {}),
959
- ...(result.usage ? { usage: result.usage } : {}),
961
+ ...(result.usage ? { usage: result.usage } : {}), ...(result.overBudget ? { overBudget: result.overBudget } : {}),
960
962
  ...(caller && result.knowsCaller === false ? { outside: true } : {}) };
961
963
  }
962
964
  /** The account this dispatch would run under there, as its capacity probe reports it: Codex's one, or the named Claude home. */
@@ -1345,7 +1347,7 @@ export class DispatchService {
1345
1347
  let remoteComputerID;
1346
1348
  const skipped = [];
1347
1349
  let incapable = false, spentSeen = false;
1348
- const pooledOut = [];
1350
+ const pooledOut = [], overBudget = [];
1349
1351
  // Pools and roles (account-policy.ts): which Claude account may run this on each computer.
1350
1352
  const projectPools = projectRule(phrenStoreRoot(), data.project);
1351
1353
  const limits = data.harness === "claude" ? await readAccountLimits() : [];
@@ -1391,6 +1393,12 @@ export class DispatchService {
1391
1393
  pooledOut.push(item.peer.name);
1392
1394
  skipped.push({ computer: item.peer.name, reason: refused.slice(0, 200) });
1393
1395
  }
1396
+ // Out of memory or CPU by its own budget: a worker started there would stall it and every agent on it.
1397
+ if (!refused && item.overBudget) {
1398
+ overBudget.push(item.peer.name);
1399
+ skipped.push({ computer: item.peer.name, reason: `over budget: ${item.overBudget}`.slice(0, 200) });
1400
+ return false;
1401
+ }
1394
1402
  return !refused;
1395
1403
  });
1396
1404
  skipped.sort((a, b) => a.computer.localeCompare(b.computer));
@@ -1404,6 +1412,8 @@ export class DispatchService {
1404
1412
  // Pools ruled some computers out: say so whatever ruled out the rest, with each computer's reason in `skipped`.
1405
1413
  if (!peer && pooledOut.length)
1406
1414
  throw new BridgeError(409, `No connected computer has a Claude account that may do this work: pools and roles rule out ${pooledOut.join(", ")}${spentSeen || incapable ? ", and the others are out of quota or can't run it" : ""}.`.slice(0, 500), { code: "account_pool", skipped });
1415
+ if (!peer && overBudget.length)
1416
+ throw new BridgeError(503, `Every connected computer that could run this is over its memory or load budget (${overBudget.join(", ")}); try again when one has room.`.slice(0, 500), { code: "over_budget", skipped });
1407
1417
  if (!peer && spentSeen)
1408
1418
  throw new BridgeError(503, `No connected computer has ${data.harness}${data.harness === "claude" ? ` account ${data.account ?? "default"}` : ""} quota left right now.`, { code: "out_of_quota", skipped });
1409
1419
  if (!peer)
@@ -1425,6 +1435,10 @@ export class DispatchService {
1425
1435
  const refused = poolCheck(peer, reported);
1426
1436
  if (refused)
1427
1437
  throw new BridgeError(409, `${peer.name}: ${refused}`, { code: "account_pool" });
1438
+ // An agent naming a computer past its budget waits; the owner's own dispatch is never held back.
1439
+ if (reported.overBudget && originPaneSchema.safeParse(originValue).success) {
1440
+ throw new BridgeError(503, `${peer.name} is over its memory or load budget: ${reported.overBudget}. Try again when it has room, or dispatch to anywhere.`.slice(0, 500), { code: "over_budget" });
1441
+ }
1428
1442
  }
1429
1443
  // Chosen here by pools and roles, the account goes in the launch; otherwise that computer picks, as before.
1430
1444
  // Keyed work is gitboy's runner: its clone and token never leave this Hook.
@@ -1,6 +1,5 @@
1
1
  /** Read-only browsing beneath a root selected and verified by the server. */
2
2
  export declare function browseFiles(root: string, relative: string): Promise<{
3
- size?: undefined;
4
3
  path: string;
5
4
  kind: string;
6
5
  truncated: boolean;
@@ -9,6 +8,7 @@ export declare function browseFiles(root: string, relative: string): Promise<{
9
8
  path: string;
10
9
  kind: string;
11
10
  }[];
11
+ size?: undefined;
12
12
  data?: undefined;
13
13
  } | {
14
14
  truncated?: undefined;
@@ -0,0 +1,5 @@
1
+ import type { HousekeepingView } from "./report.js";
2
+ export declare function formatView(name: string, view: HousekeepingView | undefined): string;
3
+ /** The inventory, one line per row with its approve id. */
4
+ export declare function formatInventory(inv: NonNullable<HousekeepingView["inventory"]>): string;
5
+ export declare function runHousekeeping(args: string[]): Promise<number>;
@@ -0,0 +1,106 @@
1
+ import { hostname } from "node:os";
2
+ import { hookRequest } from "../client.js";
3
+ /**
4
+ * `phren housekeeping`: the newest housekeeping view from this computer's
5
+ * Hook and every linked computer. `--dry-run` runs a pass here, in this
6
+ * process, without the Hook: it stores nothing and acts on nothing.
7
+ */
8
+ const GB = 1024 ** 3;
9
+ const size = (bytes) => bytes >= GB ? `${(bytes / GB).toFixed(1)} GB` : `${Math.round(bytes / 1024 ** 2)} MB`;
10
+ export function formatView(name, view) {
11
+ if (!view)
12
+ return `${name}\n No housekeeping report.`;
13
+ const h = view.health;
14
+ const lines = [`${name} ${view.generatedAt} load ${h.load1.toFixed(1)}/${h.cores} cores, ${size(h.diskFreeBytes)} free, memory ${h.memoryPressure}`];
15
+ for (const w of view.warnings)
16
+ lines.push(` ${w.severity.padEnd(4)} ${w.title} (${w.area}, ${w.id})${w.notify ? " notify" : ""}`, ` ${w.detail}`);
17
+ for (const s of view.suggestions)
18
+ lines.push(` suggest ${s.actionLabel}: ${s.title}${s.sizeBytes !== undefined ? ` (${size(s.sizeBytes)})` : ""} ${s.id}`, ` ${s.reason}`);
19
+ for (const k of view.kept)
20
+ lines.push(` kept ${k.title}: ${k.reason}`);
21
+ const freed = view.cleaned.reduce((sum, c) => sum + c.freedBytes, 0);
22
+ if (view.cleaned.length)
23
+ lines.push(` cleaned ${view.cleaned.length} item(s) in 14 days, ${size(freed)} freed`);
24
+ if (lines.length === 1)
25
+ lines.push(" Nothing to do.");
26
+ for (const error of view.errors ?? [])
27
+ lines.push(` check ${error.check} failed: ${error.message}`);
28
+ return lines.join("\n");
29
+ }
30
+ /** The inventory, one line per row with its approve id. */
31
+ export function formatInventory(inv) {
32
+ const mark = (a) => !a ? "" : a.allowed ? ` [${a.label}]` : ` [kept: ${a.reason}]`;
33
+ const lines = [` inventory ${inv.collectedAt}${inv.scanning ? " (measuring)" : ""}${inv.stale ? " (stale)" : ""}`];
34
+ for (const w of inv.worktrees)
35
+ lines.push(` ${w.path}${w.branch ? ` [${w.branch}]` : ""}${w.sizeBytes !== undefined ? ` ${size(w.sizeBytes)}` : ""}${mark(w.action)} ${w.action.id}`);
36
+ for (const r of inv.space.slice(0, 20))
37
+ lines.push(` ${size(r.sizeBytes).padStart(9)} ${r.title}${mark(r.action)}${r.action ? ` ${r.action.id}` : r.note ? ` (${r.note})` : ""}`);
38
+ for (const p of inv.sessions)
39
+ lines.push(` pane ${p.pane.label ?? p.pane.target.pane} ${p.agent ?? ""} ${p.status ?? ""}${p.idleSeconds !== undefined ? ` idle ${Math.round(p.idleSeconds / 60)}m` : ""}${mark(p.action)} ${p.action.id}`);
40
+ return lines.join("\n");
41
+ }
42
+ const flag = (args, name) => args.includes(name);
43
+ export async function runHousekeeping(args) {
44
+ const json = flag(args, "--json");
45
+ if (flag(args, "--dry-run")) {
46
+ const { Housekeeper } = await import("./housekeeper.js");
47
+ const { ResourceMonitor } = await import("../resources.js");
48
+ const { liveProcessCwds } = await import("./safety.js");
49
+ const resources = new ResourceMonitor();
50
+ // Panes are the Hook's to list; a dry run without it sees processes only.
51
+ const report = await new Housekeeper({ computer: hostname(), resources: () => resources.read(), processes: () => liveProcessCwds(), panes: async () => [] })
52
+ .run("manual", false);
53
+ const { viewOf } = await import("./report.js");
54
+ const view = viewOf(report, { cleaned: [], dismissed: new Map() });
55
+ console.log(json ? JSON.stringify(view, null, 2) : formatView(hostname(), view));
56
+ return 0;
57
+ }
58
+ const apply = args.includes("--apply") ? args[args.indexOf("--apply") + 1] : undefined;
59
+ if (args.includes("--apply") || flag(args, "--scan")) {
60
+ if (args.includes("--apply") && (!apply || apply.startsWith("-"))) {
61
+ console.error("--apply takes comma-separated action ids.");
62
+ return 1;
63
+ }
64
+ try {
65
+ const result = flag(args, "--scan") ? await hookRequest("/v1/housekeeping/scan", {}, undefined, 30_000)
66
+ : await hookRequest("/v1/housekeeping/approve", { ids: apply.split(",").filter(Boolean), by: "cli" }, undefined, 90_000);
67
+ if (json || flag(args, "--scan")) {
68
+ console.log(flag(args, "--scan") ? "Scan started; `phren housekeeping` shows it when it lands." : JSON.stringify(result, null, 2));
69
+ return 0;
70
+ }
71
+ for (const row of Array.isArray(result.results) ? result.results : [])
72
+ console.log(`${row.id} ${row.status}${row.reason ? `: ${row.reason}` : ""}${typeof row.freedBytes === "number" && row.freedBytes ? ` (${size(row.freedBytes)} freed)` : ""}`);
73
+ return 0;
74
+ }
75
+ catch (error) {
76
+ console.error(error instanceof Error ? error.message : String(error));
77
+ return 1;
78
+ }
79
+ }
80
+ let answer;
81
+ try {
82
+ answer = await hookRequest(`/v1/housekeeping?inventory=1${flag(args, "--local") ? "" : "&peers=1"}`, undefined, undefined, 30_000);
83
+ }
84
+ catch (error) {
85
+ const code = error?.code;
86
+ const message = code === "ENOENT" || code === "ECONNREFUSED" ? "Phren Hook is not running on this computer (phren bridge status). `phren housekeeping --dry-run` runs a pass without it."
87
+ : error?.status === 404 ? "This computer's Phren Hook predates housekeeping; update it with phren bridge update."
88
+ : error instanceof Error ? error.message : "Phren Hook did not answer.";
89
+ console.error(message);
90
+ return 1;
91
+ }
92
+ if (json) {
93
+ console.log(JSON.stringify(answer, null, 2));
94
+ return 0;
95
+ }
96
+ const name = (value, fallback) => typeof value?.name === "string" ? String(value.name) : fallback;
97
+ const local = answer;
98
+ const blocks = [formatView(name(answer.computer, hostname()), local)
99
+ + (local.inventory ? `\n${formatInventory(local.inventory)}` : "\n Inventory: the first scan is still running.")];
100
+ for (const peer of Array.isArray(answer.peers) ? answer.peers : []) {
101
+ const peerName = name(peer.computer, String(peer.name ?? "peer"));
102
+ blocks.push(typeof peer.error === "string" ? `${peerName}\n unavailable: ${peer.error}` : formatView(peerName, peer));
103
+ }
104
+ console.log(blocks.join("\n\n"));
105
+ return 0;
106
+ }
@@ -0,0 +1,123 @@
1
+ import type { InboxSource } from "../owner-inbox.js";
2
+ import type { ComputerResources } from "../resources.js";
3
+ import { type ApproveResult, type Badge, type Cleaned, type HousekeepingView, type ItemDraft, type StoredReport, type Trigger } from "./report.js";
4
+ import { type Inventory, type InventoryOptions } from "./inventory.js";
5
+ import { type InUseSources } from "./safety.js";
6
+ /**
7
+ * The Hook's housekeeping pass: every TICK_MS, and at once when free disk
8
+ * drops below the floor or the computer becomes stressed, run each check,
9
+ * store the report for RETAIN_DAYS, and serve the phone's view of it. Checks
10
+ * only observe and propose. Acting happens in `approve` (the owner) or, in a
11
+ * later slice, for allow-listed caches; both go through safety.ts against
12
+ * fresh state, never the stored report.
13
+ */
14
+ export declare const TICK_MS: number;
15
+ export declare const RETAIN_DAYS = 14;
16
+ /** Below this the RC suites fail; the audit's floor for warning and cleaning. */
17
+ export declare const DISK_FLOOR_BYTES: number;
18
+ /** Approve answers within this; later work comes back `started` and lands in `cleaned`. */
19
+ export declare const APPROVE_BUDGET_MS = 45000;
20
+ /** The inventory scan (sizes are slow) runs hourly and on request. */
21
+ export declare const SCAN_MS: number;
22
+ export interface CheckContext extends InUseSources {
23
+ resources: ComputerResources;
24
+ now: number;
25
+ }
26
+ export interface Check {
27
+ name: string;
28
+ run: (context: CheckContext) => Promise<ItemDraft[]>;
29
+ }
30
+ /** Warnings are machine-health findings, with their ids and wording, so the
31
+ * phone and the conductor's `machine_health` name the same thing the same way. */
32
+ export declare const healthCheck: Check;
33
+ export declare const DEFAULT_CHECKS: Check[];
34
+ /** `<bridge>/housekeeping/`: reports/ (one file per pass), cleaned.json, dismissed.json. */
35
+ export declare class HousekeepingStore {
36
+ readonly dir: string;
37
+ readonly reports: string;
38
+ constructor(dir?: string);
39
+ private names;
40
+ save(report: StoredReport, now: number): Promise<void>;
41
+ latest(): Promise<StoredReport | undefined>;
42
+ cleaned(now: number): Promise<Cleaned[]>;
43
+ addCleaned(entry: Cleaned, now: number): Promise<void>;
44
+ inventory(): Promise<Inventory | undefined>;
45
+ setInventory(inventory: Inventory): Promise<void>;
46
+ dismissed(): Promise<Map<string, {
47
+ fingerprint: string;
48
+ at: string;
49
+ }>>;
50
+ setDismissed(marks: Map<string, {
51
+ fingerprint: string;
52
+ at: string;
53
+ }>, now: number): Promise<void>;
54
+ }
55
+ export interface HousekeeperOptions extends InUseSources {
56
+ computer: string;
57
+ resources: () => Promise<ComputerResources>;
58
+ checks?: Check[];
59
+ store?: HousekeepingStore;
60
+ now?: () => number;
61
+ /** Free bytes on the volume actions free space on; statfs of the home folder by default. */
62
+ freeBytes?: () => Promise<number>;
63
+ /** Inventory sources beyond processes and panes (sessions, dispatches, simulators, docker, roots). */
64
+ inventory?: Omit<InventoryOptions, "processes" | "panes">;
65
+ /** Close a pane through the terminal provider. */
66
+ closePane?: (server: string, pane: string) => Promise<void>;
67
+ /** Runs simctl and docker for approved actions; execFile by default. */
68
+ command?: (file: string, args: string[]) => Promise<void>;
69
+ }
70
+ export declare class Housekeeper {
71
+ private readonly options;
72
+ private current;
73
+ private loaded;
74
+ private running;
75
+ private queue;
76
+ private cachedView;
77
+ private lastEdge;
78
+ private inventory;
79
+ private inventoryLoaded;
80
+ private scanning;
81
+ private readonly store;
82
+ private readonly now;
83
+ constructor(options: HousekeeperOptions);
84
+ private latest;
85
+ /** One pass. Concurrent callers share the pass in flight. */
86
+ run(trigger?: Trigger, persist?: boolean): Promise<StoredReport>;
87
+ private pass;
88
+ private latestInventory;
89
+ /** Scan the inventory in the background; concurrent callers share the scan. */
90
+ scan(): Promise<Inventory>;
91
+ /** The phone's view of the newest report; undefined before the first pass. */
92
+ view(includeDismissed?: boolean, includeInventory?: boolean): Promise<HousekeepingView | undefined>;
93
+ /** The overview badge, from the cached view: no pass, no git. */
94
+ badge(): Promise<Badge | undefined>;
95
+ /** Called with each resource read: a fresh drop below the disk floor or a
96
+ * fresh stressed state runs a pass now rather than at the next tick. */
97
+ observe(resources: ComputerResources): Promise<StoredReport> | undefined;
98
+ /** Warnings worth waking the owner for, as owner-inbox sources keyed by item
99
+ * id: a reworded finding stays one row, which resolves itself when it goes. */
100
+ inboxSources(): InboxSource[];
101
+ private serial;
102
+ /** Hide items until their state changes. Unknown ids are ignored. */
103
+ dismiss(ids: string[]): Promise<{
104
+ revision: string;
105
+ }>;
106
+ restore(ids: string[]): Promise<{
107
+ revision: string;
108
+ }>;
109
+ /**
110
+ * Apply the owner's approval. A fresh pass runs first and each id is judged
111
+ * against it: an id that is no longer there (its state changed) is `gone`,
112
+ * a kept item or a warning is `refused`, and an action re-checks safety
113
+ * against the disk itself as it runs. Work past APPROVE_BUDGET_MS comes back
114
+ * `started` and finishes in the background, landing in `cleaned`.
115
+ */
116
+ approve(ids: string[], by: Cleaned["by"]): Promise<ApproveResult>;
117
+ private freeBytes;
118
+ private apply;
119
+ /** An inventory row (prefixed id) as an approvable item; it is re-checked live by its executor. */
120
+ private inventoryItem;
121
+ /** Live state for executors: fresh sessions and dispatches, never the scan's copy. */
122
+ private fresh;
123
+ }