@phren/cli 0.3.79 → 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 (37) hide show
  1. package/dist/bridge/dispatch.js +17 -3
  2. package/dist/bridge/housekeeping/command.d.ts +5 -0
  3. package/dist/bridge/housekeeping/command.js +106 -0
  4. package/dist/bridge/housekeeping/housekeeper.d.ts +123 -0
  5. package/dist/bridge/housekeeping/housekeeper.js +459 -0
  6. package/dist/bridge/housekeeping/inventory.d.ts +145 -0
  7. package/dist/bridge/housekeeping/inventory.js +276 -0
  8. package/dist/bridge/housekeeping/report.d.ts +672 -0
  9. package/dist/bridge/housekeeping/report.js +168 -0
  10. package/dist/bridge/housekeeping/safety.d.ts +177 -0
  11. package/dist/bridge/housekeeping/safety.js +466 -0
  12. package/dist/bridge/owner-proof.js +1 -0
  13. package/dist/bridge/push.js +3 -1
  14. package/dist/bridge/resources.d.ts +8 -0
  15. package/dist/bridge/resources.js +18 -5
  16. package/dist/bridge/server-pane-routes.d.ts +6 -0
  17. package/dist/bridge/server-pane-routes.js +1 -1
  18. package/dist/bridge/server-routes.d.ts +5 -0
  19. package/dist/bridge/server-routes.js +44 -3
  20. package/dist/bridge/server.js +44 -8
  21. package/dist/bridge-hook.mjs +2980 -1226
  22. package/dist/cli-registry.js +18 -1
  23. package/dist/fanout/command.js +42 -15
  24. package/dist/heavy/budget-status.d.ts +26 -0
  25. package/dist/heavy/budget-status.js +26 -0
  26. package/dist/heavy/budget.d.ts +39 -0
  27. package/dist/heavy/budget.js +57 -0
  28. package/dist/heavy/command.d.ts +15 -0
  29. package/dist/heavy/command.js +119 -0
  30. package/dist/heavy/reap.d.ts +70 -0
  31. package/dist/heavy/reap.js +211 -0
  32. package/dist/heavy/slots.d.ts +58 -0
  33. package/dist/heavy/slots.js +142 -0
  34. package/dist/modules/registry.js +4 -3
  35. package/package.json +1 -1
  36. package/starter/global/skills/conductor/SKILL.md +10 -0
  37. package/starter/global/skills/fanout/SKILL.md +30 -0
@@ -59,6 +59,7 @@ import { conversationSearch } from "./conversation-search.js";
59
59
  import { listUploads, removeUpload, saveUpload, uploadImage } from "./uploads.js";
60
60
  import { currentModel, currentStep } from "./steps.js";
61
61
  import { capacityRoom, usageForCaller } from "./usage.js";
62
+ import { pressureReason, readBudget, readPressure } from "../heavy/budget.js";
62
63
  import { SCHEDULE_EVENT_BODY_CAP } from "./schedule-events.js";
63
64
  import { updateScheduleRoute } from "./schedule-update.js";
64
65
  import { cachedStoreWarnings, healthDetails, listsCaller } from "./health.js";
@@ -119,7 +120,7 @@ export async function effectiveStatusRows(server, s, budgetMs = STATUS_ENRICH_BU
119
120
  export const capabilities = { browsers: true, turnCheckpoints: true, transcript: true, progress: true, images: true, prompt: true, stop: true,
120
121
  terminal: "ssh-pty", shell: "ssh-pty", paneTerminal: "ssh-pty", paneLayout: true, deskPresence: true, herdr: true, sessionRename: true, sessionSeen: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
121
122
  approvals: true, questions: false, accountUsage: true, providers: ["codex", "claude", "copilot", "opencode"],
122
- files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, setLink: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", simulatorStream: process.platform === "darwin", simulatorDevices: process.platform === "darwin", simulatorDrag: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, afterTurnQueue: true, queuedMessageActions: ["claude"], deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, secretExec: true, ownerProof: 1, previewDeltas: true, quickChat: true, agentFolder: true, launchPermissionMode: true, sessionMove: true, moveNewChat: true, moveConductor: true, moveToComputer: true, moveConductorToComputer: true, moveResume: true, moveSummaryByTarget: true, moveConversationCopy: true, claudeAccountAdd: true, accountPools: true, workerRelocation: 1, projectMemory: true, fileWrite: true, fileSearch: true, gitReview: true, memoryStoreBatch: true, gitHosts: true, projectHostToken: true, gitRemoteIdentity: true, gitWatch: true, worktreeRemove: true, terminalResolve: true, conversationSearch: true };
123
+ files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, setLink: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", simulatorStream: process.platform === "darwin", simulatorDevices: process.platform === "darwin", simulatorDrag: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, afterTurnQueue: true, queuedMessageActions: ["claude"], deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, secretExec: true, ownerProof: 1, previewDeltas: true, quickChat: true, agentFolder: true, launchPermissionMode: true, sessionMove: true, moveNewChat: true, moveConductor: true, moveToComputer: true, moveConductorToComputer: true, moveResume: true, moveSummaryByTarget: true, moveConversationCopy: true, claudeAccountAdd: true, accountPools: true, workerRelocation: 1, projectMemory: true, fileWrite: true, fileSearch: true, gitReview: true, memoryStoreBatch: true, gitHosts: true, projectHostToken: true, gitRemoteIdentity: true, gitWatch: true, worktreeRemove: true, terminalResolve: true, conversationSearch: true, housekeeping: 1, housekeepingInventory: 1 };
123
124
  export function capabilitiesForModules(snapshot) {
124
125
  const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
125
126
  const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
@@ -701,10 +702,14 @@ export function createRouteHandler(ctx) {
701
702
  // Both bounded so a peer's capacity probe never waits on a cold `claude auth status` or usage read; missing means unknown.
702
703
  // PHREN_LAUNCH_CHECK=off turns this Hook's availability checks off, including what it advertises to dispatch.
703
704
  // `usage` is the room left per Codex and Claude account, so `anywhere` can break a tie by it.
704
- const [inventory, limits] = await Promise.all([launchCheckOff() ? undefined : harnessInventoryWithin(2_500), within(2_500, accountUsage.limits(true))]);
705
+ const [inventory, limits, pressure] = await Promise.all([launchCheckOff() ? undefined : harnessInventoryWithin(2_500), within(2_500, accountUsage.limits(true)),
706
+ within(2_500, readPressure())]);
707
+ // Memory or load past this computer's budget (heavy/budget.ts): `anywhere` passes it over, and an agent may not name it.
708
+ const overBudget = pressure ? pressureReason(pressure, readBudget(pressure.totalBytes)) : undefined;
705
709
  result = { product: "phren-hook", protocol: PROTOCOL, computer: info.computer, servers: live.map(server => server.session), ...linksBack,
706
710
  working: snapshots.reduce((sum, value) => sum + objects(value.panes).filter(pane => pane.agent && pane.agent_status === "working").length, 0),
707
- ...(inventory ? { harnesses: inventory.harnesses } : {}), ...(limits ? { usage: capacityRoom(limits, Date.now()) } : {}) };
711
+ ...(inventory ? { harnesses: inventory.harnesses } : {}), ...(limits ? { usage: capacityRoom(limits, Date.now()) } : {}),
712
+ ...(overBudget ? { overBudget } : {}) };
708
713
  break;
709
714
  }
710
715
  case "/v1/speech/voices": {
@@ -831,6 +836,22 @@ export function createRouteHandler(ctx) {
831
836
  result = { ...result, ...await fromPeers("/v1/resources") };
832
837
  break;
833
838
  }
839
+ case "/v1/housekeeping": {
840
+ // The newest housekeeping report (docs/housekeeping.md); null before the first pass.
841
+ // This computer only; the phone asks each computer itself. `peers=1` is for `phren housekeeping`.
842
+ if (!ctx.housekeeper)
843
+ throw new BridgeError(404, "Housekeeping is not running on this Hook.");
844
+ const dismissed = url.searchParams.get("dismissed") === "1", inventory = url.searchParams.get("inventory") === "1";
845
+ // Before the first scheduled pass, run one now so the answer always has the full shape.
846
+ const view = await ctx.housekeeper.view(dismissed, inventory) ?? (await ctx.housekeeper.run("manual"), await ctx.housekeeper.view(dismissed, inventory));
847
+ // No scan yet: start one; `inventory` appears once it lands (the revision changes).
848
+ if (inventory && !view?.inventory)
849
+ void ctx.housekeeper.scan().catch(() => { });
850
+ result = { computer: info.computer, ...view };
851
+ if (url.searchParams.get("peers") === "1")
852
+ result = { ...result, ...await fromPeers("/v1/housekeeping") };
853
+ break;
854
+ }
834
855
  case "/v1/push/status":
835
856
  result = agentHooks.push.status;
836
857
  break;
@@ -1204,6 +1225,26 @@ export function createRouteHandler(ctx) {
1204
1225
  else if (url.pathname === "/v1/sessions/seen") {
1205
1226
  result = await markSessionSeen(data);
1206
1227
  }
1228
+ else if (url.pathname === "/v1/housekeeping/scan") {
1229
+ // Owner-only: a fresh inventory (sizes take a while); the answer comes back through the view's revision.
1230
+ if (!ownerRequest(request, data))
1231
+ throw new BridgeError(403, "Only the owner starts a housekeeping scan.");
1232
+ if (!ctx.housekeeper)
1233
+ throw new BridgeError(404, "Housekeeping is not running on this Hook.");
1234
+ void ctx.housekeeper.scan().catch(() => { });
1235
+ result = { started: true };
1236
+ }
1237
+ else if (url.pathname === "/v1/housekeeping/approve" || url.pathname === "/v1/housekeeping/dismiss" || url.pathname === "/v1/housekeeping/restore") {
1238
+ // Owner-only, and owner-proof signed once the phone signs (owner-proof.ts): agents and peers never apply housekeeping.
1239
+ if (!ownerRequest(request, data))
1240
+ throw new BridgeError(403, "Only the owner applies or dismisses housekeeping.");
1241
+ if (!ctx.housekeeper)
1242
+ throw new BridgeError(404, "Housekeeping is not running on this Hook.");
1243
+ const input = z.object({ ids: z.array(z.string().regex(/^[\w:.-]{1,200}$/)).min(1).max(200), revision: z.string().max(64).optional(),
1244
+ by: z.enum(["phone", "cli"]).optional() }).strict().parse(data);
1245
+ result = url.pathname.endsWith("/approve") ? await ctx.housekeeper.approve(input.ids, input.by ?? "phone")
1246
+ : url.pathname.endsWith("/dismiss") ? await ctx.housekeeper.dismiss(input.ids) : await ctx.housekeeper.restore(input.ids);
1247
+ }
1207
1248
  else if (url.pathname === "/v1/jobs/cleanup") {
1208
1249
  // Ends only registered worker process groups whose pane is gone.
1209
1250
  result = { ok: true, ...await ctx.resources.cleanupJobs() };
@@ -8,6 +8,9 @@ import { setChoiceReaders } from "./account-choice.js";
8
8
  import { AccountFailover } from "./account-failover.js";
9
9
  import { ownerInboxSources } from "./owner-inbox-sources.js";
10
10
  import { OwnerInbox } from "./owner-inbox.js";
11
+ import { Housekeeper, SCAN_MS as HOUSEKEEPING_SCAN_MS, TICK_MS as HOUSEKEEPING_TICK_MS } from "./housekeeping/housekeeper.js";
12
+ import { liveProcessCwds } from "./housekeeping/safety.js";
13
+ import { dockerUsage, listSimulators, sessionRowsFromOverview, xcodebuildRunning } from "./housekeeping/inventory.js";
11
14
  import { closeFinishedWorker } from "./worker-close.js";
12
15
  import { cleanupIdempotencyLocks, markHookServerProcess } from "./dispatch-idempotency.js";
13
16
  import { isLocalComputer } from "./dispatch-hosts.js";
@@ -17,7 +20,7 @@ import { sessionStalls } from "./stalls.js";
17
20
  import { TurnQueue } from "./turn-queue.js";
18
21
  import { turnQueuePaneReader } from "./turn-queue-pane.js";
19
22
  import { HandOffQueue } from "./hand-off-queue.js";
20
- import { paneRouteOnce, promptGuards } from "./server-pane-routes.js";
23
+ import { allPaneSessions, paneRouteOnce, promptGuards } from "./server-pane-routes.js";
21
24
  import { FanoutMessages } from "./fanout-messages.js";
22
25
  import { activateModules as moduleSnapshot } from "../modules/runtime.js";
23
26
  import { disabledHint } from "../modules/registry.js";
@@ -38,7 +41,7 @@ import { approvalPushCapability } from "./push.js";
38
41
  import { startChangeRetention } from "./changes.js";
39
42
  import { CodeReindexer, CodeRoutes } from "./code-routes.js";
40
43
  import { WorkspaceContextUsage } from "./context.js";
41
- import { DispatchService, reconcileInterruptedDispatches } from "./dispatch.js";
44
+ import { DispatchService, dispatchStatus, reconcileInterruptedDispatches } from "./dispatch.js";
42
45
  import { DispatchReturns, hookWorkers } from "./dispatch-returns.js";
43
46
  import { findPane, paneChatState, paneIdentity, recentServers, sharedSnapshot, snapshot, validateTarget } from "./herdr.js";
44
47
  import { LaunchLimiter } from "./limits.js";
@@ -156,7 +159,12 @@ export async function serve(version, options = {}) {
156
159
  if ("approvalPush" in activeCapabilities) {
157
160
  Object.defineProperty(activeCapabilities, "approvalPush", { enumerable: true, get: () => approvalPushCapability(agentHooks.push.status) });
158
161
  }
159
- const inbox = dispatches ? new OwnerInbox(() => ownerInboxSources(agentHooks)) : undefined;
162
+ // Assigned once resources exist below; the inbox only reads it on its ticks.
163
+ let housekeeper;
164
+ const inbox = dispatches ? new OwnerInbox(async () => {
165
+ const observed = await ownerInboxSources(agentHooks);
166
+ return { ...observed, sources: [...observed.sources, ...housekeeper?.inboxSources() ?? []] };
167
+ }) : undefined;
160
168
  const modelCatalog = options.modelCatalog ?? new ModelCatalog();
161
169
  const modelSwitcher = new ModelSwitcher(agentHooks, modelCatalog);
162
170
  const settingsSwitcher = new SettingsSwitcher(agentHooks);
@@ -227,6 +235,20 @@ export async function serve(version, options = {}) {
227
235
  // A Claude launch that names no account runs under the one with the most room (account-choice.ts).
228
236
  setChoiceReaders({ usage: () => accountUsage.limits(true) });
229
237
  const resources = new ResourceMonitor();
238
+ // Housekeeping (housekeeping/): a report every 15 minutes and on a fresh low-disk or stressed edge.
239
+ housekeeper = new Housekeeper({ computer: hostname(), resources: () => resources.read(), processes: () => liveProcessCwds(),
240
+ panes: async () => (await allPaneSessions()).map(session => ({ pane: session.pane, cwd: session.cwd, title: session.title })),
241
+ inventory: {
242
+ sessions: async () => (await Promise.all((await recentServers()).map(async (server) => {
243
+ const name = String(server.session);
244
+ return sessionRowsFromOverview(await readWorkspaces(name, await sharedSnapshot(name, 4000), false));
245
+ }))).flat(),
246
+ dispatches: async () => (await dispatchStatus()).flatMap(receipt => receipt.target ? [{ id: receipt.id, server: receipt.target.server, pane: receipt.target.pane,
247
+ ...(receipt.returned ? { returned: { read: receipt.returned.read } } : {}), ...(receipt.closedAt ? { closedAt: receipt.closedAt } : {}) }] : []),
248
+ ...(process.platform === "darwin" ? { simulators: () => listSimulators(), xcodebuildRunning } : {}),
249
+ docker: dockerUsage,
250
+ },
251
+ closePane: (server, pane) => terminalProvider().closePane(server, pane) });
230
252
  const tabActivity = new TabActivityStore();
231
253
  const codexQuestions = new CodexQuestions(undefined, codexServers);
232
254
  const scheduleStore = defaultPhrenPath();
@@ -292,19 +314,22 @@ export async function serve(version, options = {}) {
292
314
  await rm(path.join(root, "changes-scratch"), { recursive: true, force: true });
293
315
  const streams = transcriptStreams({ modules, agentHooks, codexQuestions, sideQuestions, settingsSwitcher, info, activeCapabilities });
294
316
  const { stream } = streams;
317
+ // One workspaces reader for the overview stream and the housekeeping inventory's sessions.
318
+ const readWorkspaces = workspacesReader({ modules, info, agentHooks, journal, tabActivity, contextUsage, turnQueue });
295
319
  // The phone's overview, pushed over a WebSocket when it changes.
296
320
  const overview = overviewStream({
297
- read: workspacesReader({ modules, info, agentHooks, journal, tabActivity, contextUsage, turnQueue }),
321
+ read: readWorkspaces,
298
322
  info: () => ({ ...info, capabilities: info.capabilities }),
299
323
  renew: server => agentHooks.overview.renew(server),
300
- resources: () => resources.read(),
324
+ // The overview's resources frame carries the housekeeping badge; the phone re-fetches /v1/housekeeping when its revision changes.
325
+ resources: async () => { const value = await resources.read(); const badge = await housekeeper?.badge().catch(() => undefined); return badge ? { ...value, housekeeping: badge } : value; },
301
326
  sudo: agentHooks.sudo,
302
327
  secrets: agentHooks.secrets,
303
328
  });
304
329
  const gitWatch = new GitWatch();
305
330
  // 256 KiB: gitboy's /memory/files asks about up to 500 paths in one query string.
306
331
  const http = createServer({ maxHeaderSize: 256 * 1024 }, createRouteHandler({ version, modules, info, computerID, scheduleStore, scheduler, dispatches, agentHooks,
307
- journal, tabActivity, contextUsage, modelCatalog, modelSwitcher, settingsSwitcher, permissionModeSwitcher, sideQuestions, accountUsage, resources, codexQuestions, launches, locatedDirectories,
332
+ journal, tabActivity, contextUsage, modelCatalog, modelSwitcher, settingsSwitcher, permissionModeSwitcher, sideQuestions, accountUsage, resources, housekeeper, codexQuestions, launches, locatedDirectories,
308
333
  fanoutMessages, canary, streams, returns, handOffs, inbox, mover, succession, storePulls, gitboyWebhooks, turnQueue, browsers }));
309
334
  http.requestTimeout = 20_000;
310
335
  http.headersTimeout = 10_000;
@@ -394,7 +419,18 @@ export async function serve(version, options = {}) {
394
419
  const canaryTimer = setInterval(() => { countTick("canary"); void dailyCanaryDue().then(due => due ? canary("daily") : undefined).catch(() => { }); }, 10 * 60_000);
395
420
  // A new high machine health finding reaches the phone once (machine-health-alerts.ts).
396
421
  const healthAlerts = new HealthAlerts(finding => agentHooks.push.notifyMachineHealth({ computer: hostname(), ...finding }));
397
- const healthTimer = setInterval(() => { countTick("health"); void resources.read().then(value => healthAlerts.observe(value.health, Date.now())).catch(() => { }); }, ALERT_CHECK_MS);
422
+ const healthTimer = setInterval(() => {
423
+ countTick("health");
424
+ void resources.read().then(value => {
425
+ healthAlerts.observe(value.health, Date.now());
426
+ void housekeeper?.observe(value)?.catch(() => { });
427
+ }).catch(() => { });
428
+ }, ALERT_CHECK_MS);
429
+ const housekeepingTimer = setInterval(() => { countTick("housekeeping"); void housekeeper?.run().catch(() => { }); }, HOUSEKEEPING_TICK_MS);
430
+ setTimeout(() => { void housekeeper?.run().catch(() => { }); }, 60_000).unref();
431
+ // The inventory (sizes are slow, niced): hourly, the first a few minutes after start.
432
+ const inventoryTimer = setInterval(() => { countTick("housekeeping-scan"); void housekeeper?.scan().catch(() => { }); }, HOUSEKEEPING_SCAN_MS);
433
+ setTimeout(() => { void housekeeper?.scan().catch(() => { }); }, 3 * 60_000).unref();
398
434
  let recording = false;
399
435
  const activityTimer = setInterval(() => {
400
436
  countTick("activity");
@@ -445,7 +481,7 @@ export async function serve(version, options = {}) {
445
481
  })().finally(() => { recording = false; }).catch(() => { });
446
482
  }, 5000);
447
483
  await new Promise(resolve => {
448
- const stop = () => { browsers.close(); gitboyWebhooks.stop(); storePulls.stop(); storeSync.stop(); fanoutMessages.close(); stopRetention(); clearInterval(scheduleTimer); clearInterval(dreamTimer); clearInterval(canaryTimer); clearInterval(healthTimer); clearInterval(codexAuthTimer); clearInterval(activityTimer); scheduler?.close(); codeReindexer?.close(); codexServers.close(); gitWatch.close(); agentHooks.close(); ws.clients.forEach(c => c.terminate()); ws.close(); http.close(() => resolve()); http.closeAllConnections(); };
484
+ const stop = () => { browsers.close(); gitboyWebhooks.stop(); storePulls.stop(); storeSync.stop(); fanoutMessages.close(); stopRetention(); clearInterval(scheduleTimer); clearInterval(dreamTimer); clearInterval(canaryTimer); clearInterval(healthTimer); clearInterval(housekeepingTimer); clearInterval(inventoryTimer); clearInterval(codexAuthTimer); clearInterval(activityTimer); scheduler?.close(); codeReindexer?.close(); codexServers.close(); gitWatch.close(); agentHooks.close(); ws.clients.forEach(c => c.terminate()); ws.close(); http.close(() => resolve()); http.closeAllConnections(); };
449
485
  process.once("SIGTERM", stop);
450
486
  process.once("SIGINT", stop);
451
487
  });