@phren/cli 0.3.9 → 0.3.11
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.
- package/dist/bridge/fanout-messages.js +2 -2
- package/dist/bridge/fanouts.js +1 -1
- package/dist/bridge/resources.d.ts +119 -0
- package/dist/bridge/resources.js +298 -0
- package/dist/bridge/server-overview.d.ts +8 -2
- package/dist/bridge/server-overview.js +16 -3
- package/dist/bridge/server-routes.d.ts +4 -1
- package/dist/bridge/server-routes.js +34 -3
- package/dist/bridge/server.js +5 -2
- package/dist/bridge/transcript-claude.js +5 -0
- package/dist/bridge/transcript-codex.d.ts +20 -0
- package/dist/bridge/transcript-codex.js +177 -2
- package/dist/bridge/transcripts.js +6 -1
- package/dist/bridge/usage.d.ts +36 -20
- package/dist/bridge/usage.js +163 -301
- package/dist/bridge-hook.mjs +1132 -800
- package/dist/cli-registry.d.ts +2 -0
- package/dist/cli-registry.js +13 -0
- package/dist/computers/command.d.ts +6 -0
- package/dist/computers/command.js +152 -0
- package/dist/computers/mcp.d.ts +1 -0
- package/dist/computers/mcp.js +97 -0
- package/dist/computers/read.d.ts +85 -0
- package/dist/computers/read.js +177 -0
- package/dist/entrypoint.js +10 -0
- package/dist/fanout/adapters/claude.js +15 -2
- package/dist/fanout/adapters/types.d.ts +6 -0
- package/dist/fanout/launcher.d.ts +5 -1
- package/dist/fanout/launcher.js +34 -3
- package/dist/fanout/picker.js +3 -2
- package/dist/fanout/usage.js +1 -1
- package/dist/modules/registry.js +3 -3
- package/package.json +1 -1
- package/starter/global/skills/conductor/SKILL.md +4 -0
- package/starter/global/skills/fanout/SKILL.md +9 -0
|
@@ -60,7 +60,7 @@ export class FanoutMessages {
|
|
|
60
60
|
throw new BridgeError(404, "That resumable worker is not part of this conversation.");
|
|
61
61
|
const root = await containedFanoutRoot(this.env);
|
|
62
62
|
const job = (await this.jobs()).find(job => root && fanoutChildID(root, job.manifest) === child);
|
|
63
|
-
if (!job || !job.manifest.session || !["codex", "opencode"].includes(job.manifest.provider)) {
|
|
63
|
+
if (!job || !job.manifest.session || !["codex", "opencode", "claude"].includes(job.manifest.provider)) {
|
|
64
64
|
throw new BridgeError(404, "That worker does not belong to this store.");
|
|
65
65
|
}
|
|
66
66
|
return job;
|
|
@@ -154,7 +154,7 @@ export class FanoutMessages {
|
|
|
154
154
|
const fresh = (await this.jobs()).find(candidate => candidate.directory === job.directory);
|
|
155
155
|
if (!fresh || ["queued", "running"].includes(fresh.manifest.status))
|
|
156
156
|
return;
|
|
157
|
-
if (!fresh.manifest.session || !["codex", "opencode"].includes(fresh.manifest.provider))
|
|
157
|
+
if (!fresh.manifest.session || !["codex", "opencode", "claude"].includes(fresh.manifest.provider))
|
|
158
158
|
return;
|
|
159
159
|
const next = (await this.records(fresh)).find(row => row.message.status === "queued");
|
|
160
160
|
if (!next)
|
package/dist/bridge/fanouts.js
CHANGED
|
@@ -219,7 +219,7 @@ export async function fanoutChildren(parentProvider, parentSession, env = proces
|
|
|
219
219
|
path: manifest.taskLabel, callId: `fanout:${id}`,
|
|
220
220
|
state: blocked || manifest.status === "failed" || manifest.status === "cancelled" ? "failed" : ["queued", "running"].includes(manifest.status) ? "running" : "completed",
|
|
221
221
|
...(blocked ? { reason: blockedReason(blocked) } : asking ? { reason: `needs-you: ${String(asking.message ?? asking.type)}`.slice(0, 500) } : {}), ...(finishedAt ? { finishedAt } : {}), transcript,
|
|
222
|
-
fanout: { resumable:
|
|
222
|
+
fanout: { resumable: manifest.session !== undefined }, children: [] });
|
|
223
223
|
}
|
|
224
224
|
catch { /* Torn, old, or untrusted manifests do not become child agents. */ }
|
|
225
225
|
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This computer's live resources for `GET /v1/resources`, the overview
|
|
3
|
+
* stream's `resources` frames and the memory-free `phren computers` surface:
|
|
4
|
+
* load against cores, memory, free disk on the home volume, battery, uptime
|
|
5
|
+
* and the heavy jobs (simulators, emulators, xcodebuild, Gradle, agent
|
|
6
|
+
* workers) with the pane that started them where one did; any other program
|
|
7
|
+
* holding half a core or more across its processes shows as `busy`. macOS reads
|
|
8
|
+
* sysctl, pmset and ps; Linux reads /proc, /sys and ps. Nothing here needs a
|
|
9
|
+
* permission the Hook does not already have.
|
|
10
|
+
*/
|
|
11
|
+
export declare const RESOURCES_MAX_AGE_MS: number;
|
|
12
|
+
/** Below this much free disk, or above twice the cores in load, a computer is stressed. */
|
|
13
|
+
export declare const LOW_DISK_BYTES: number;
|
|
14
|
+
export type HeavyKind = "simulator" | "emulator" | "xcodebuild" | "gradle" | "java" | "codex" | "opencode" | "claude" | "busy";
|
|
15
|
+
export interface PaneRef {
|
|
16
|
+
server: string;
|
|
17
|
+
workspace?: string;
|
|
18
|
+
pane: string;
|
|
19
|
+
agent?: string;
|
|
20
|
+
label?: string;
|
|
21
|
+
}
|
|
22
|
+
export interface HeavyProcess {
|
|
23
|
+
kind: HeavyKind;
|
|
24
|
+
name: string;
|
|
25
|
+
pid: number;
|
|
26
|
+
/** Processes counted under this one: itself and descendants no nearer heavy job claims. */
|
|
27
|
+
processes: number;
|
|
28
|
+
cpuPercent: number;
|
|
29
|
+
memoryBytes: number;
|
|
30
|
+
pane?: PaneRef;
|
|
31
|
+
}
|
|
32
|
+
export interface ComputerResources {
|
|
33
|
+
collectedAt: string;
|
|
34
|
+
platform: string;
|
|
35
|
+
uptimeSeconds: number;
|
|
36
|
+
cpu: {
|
|
37
|
+
cores: number;
|
|
38
|
+
load1: number;
|
|
39
|
+
load5: number;
|
|
40
|
+
load15: number;
|
|
41
|
+
loadPerCore: number;
|
|
42
|
+
};
|
|
43
|
+
memory: {
|
|
44
|
+
totalBytes: number;
|
|
45
|
+
availablePercent?: number;
|
|
46
|
+
pressure?: "normal" | "warn" | "critical";
|
|
47
|
+
swapUsedBytes?: number;
|
|
48
|
+
};
|
|
49
|
+
disk?: {
|
|
50
|
+
path: string;
|
|
51
|
+
totalBytes: number;
|
|
52
|
+
freeBytes: number;
|
|
53
|
+
};
|
|
54
|
+
battery?: {
|
|
55
|
+
percent: number;
|
|
56
|
+
charging: boolean;
|
|
57
|
+
onAC: boolean;
|
|
58
|
+
};
|
|
59
|
+
heavy: HeavyProcess[];
|
|
60
|
+
/** 0 idle to 1 saturated, per resource and overall (the highest), so every client fills its gauge the same way. */
|
|
61
|
+
pressure: {
|
|
62
|
+
cpu: number;
|
|
63
|
+
memory: number;
|
|
64
|
+
disk: number;
|
|
65
|
+
overall: number;
|
|
66
|
+
};
|
|
67
|
+
level: "ok" | "busy" | "stressed";
|
|
68
|
+
warnings: Array<"load-high" | "memory-low" | "disk-low" | "battery-low">;
|
|
69
|
+
}
|
|
70
|
+
export interface ProcessRow {
|
|
71
|
+
pid: number;
|
|
72
|
+
ppid: number;
|
|
73
|
+
cpu: number;
|
|
74
|
+
rssKB: number;
|
|
75
|
+
command: string;
|
|
76
|
+
args: string;
|
|
77
|
+
}
|
|
78
|
+
/** `ps -axo pid=,ppid=,pcpu=,rss=,comm=` paired with the `args=` listing by pid. */
|
|
79
|
+
export declare function parsePs(stats: string, args: string): ProcessRow[];
|
|
80
|
+
/** What kind of heavy job a process is, if any. */
|
|
81
|
+
export declare function heavyKind(row: ProcessRow): {
|
|
82
|
+
kind: HeavyKind;
|
|
83
|
+
name: string;
|
|
84
|
+
} | undefined;
|
|
85
|
+
/**
|
|
86
|
+
* The heavy jobs in a process table. Every process counts toward its nearest
|
|
87
|
+
* heavy ancestor-or-self, so a Codex worker running xcodebuild shows both,
|
|
88
|
+
* each with only its own share. Any other program shows as `busy` when its
|
|
89
|
+
* processes together hold half a core. Agents idling at no cost are left
|
|
90
|
+
* out: only jobs that cost something (a core's tenth or 200 MB) make the list.
|
|
91
|
+
*/
|
|
92
|
+
export declare function heavyProcesses(rows: ProcessRow[], owners?: Map<number, PaneRef>, limit?: number): HeavyProcess[];
|
|
93
|
+
/** `pmset -g batt`: "Now drawing from 'AC Power'" then " -InternalBattery-0 (id=…) 87%; charging; …". */
|
|
94
|
+
export declare function parsePmset(output: string): ComputerResources["battery"];
|
|
95
|
+
/** `sysctl vm.swapusage`: "total = 2048.00M used = 798.50M free = …". */
|
|
96
|
+
export declare function parseSwap(output: string): number | undefined;
|
|
97
|
+
/** /proc/meminfo: MemTotal, MemAvailable and swap, in kB. */
|
|
98
|
+
export declare function parseMeminfo(text: string): ComputerResources["memory"];
|
|
99
|
+
/** Gauge fill and warnings from the numbers. */
|
|
100
|
+
export declare function assess(value: Omit<ComputerResources, "pressure" | "level" | "warnings">): Pick<ComputerResources, "pressure" | "level" | "warnings">;
|
|
101
|
+
/** Every pid a Herdr or tmux pane holds (its shell and foreground), for naming a job's pane. */
|
|
102
|
+
export declare function paneOwners(): Promise<Map<number, PaneRef>>;
|
|
103
|
+
export interface ResourceDeps {
|
|
104
|
+
platform: NodeJS.Platform;
|
|
105
|
+
now: () => number;
|
|
106
|
+
home: () => string;
|
|
107
|
+
processes: () => Promise<ProcessRow[]>;
|
|
108
|
+
owners: () => Promise<Map<number, PaneRef>>;
|
|
109
|
+
}
|
|
110
|
+
export declare function collectResources(deps: ResourceDeps): Promise<ComputerResources>;
|
|
111
|
+
/** One collection at a time, reused for `RESOURCES_MAX_AGE_MS`. */
|
|
112
|
+
export declare class ResourceMonitor {
|
|
113
|
+
private maxAgeMs;
|
|
114
|
+
private cached?;
|
|
115
|
+
private pending?;
|
|
116
|
+
private readonly deps;
|
|
117
|
+
constructor(deps?: Partial<ResourceDeps>, maxAgeMs?: number);
|
|
118
|
+
read(): Promise<ComputerResources>;
|
|
119
|
+
}
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { readdir, readFile, statfs } from "node:fs/promises";
|
|
3
|
+
import { cpus, loadavg, totalmem, uptime } from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { promisify } from "node:util";
|
|
6
|
+
import { homeDir } from "../home-paths.js";
|
|
7
|
+
import { recentServers, sharedSnapshot } from "./herdr.js";
|
|
8
|
+
import { intervalFromEnv } from "./limits.js";
|
|
9
|
+
import { objects } from "./protocol.js";
|
|
10
|
+
const exec = promisify(execFile);
|
|
11
|
+
/**
|
|
12
|
+
* This computer's live resources for `GET /v1/resources`, the overview
|
|
13
|
+
* stream's `resources` frames and the memory-free `phren computers` surface:
|
|
14
|
+
* load against cores, memory, free disk on the home volume, battery, uptime
|
|
15
|
+
* and the heavy jobs (simulators, emulators, xcodebuild, Gradle, agent
|
|
16
|
+
* workers) with the pane that started them where one did; any other program
|
|
17
|
+
* holding half a core or more across its processes shows as `busy`. macOS reads
|
|
18
|
+
* sysctl, pmset and ps; Linux reads /proc, /sys and ps. Nothing here needs a
|
|
19
|
+
* permission the Hook does not already have.
|
|
20
|
+
*/
|
|
21
|
+
export const RESOURCES_MAX_AGE_MS = intervalFromEnv("PHREN_RESOURCES_MAX_AGE_MS", 10_000, 1_000, 60_000);
|
|
22
|
+
/** Below this much free disk, or above twice the cores in load, a computer is stressed. */
|
|
23
|
+
export const LOW_DISK_BYTES = 10 * 1024 ** 3;
|
|
24
|
+
const GB = 1024 ** 3;
|
|
25
|
+
/** `ps -axo pid=,ppid=,pcpu=,rss=,comm=` paired with the `args=` listing by pid. */
|
|
26
|
+
export function parsePs(stats, args) {
|
|
27
|
+
const argv = new Map();
|
|
28
|
+
for (const line of args.split("\n")) {
|
|
29
|
+
const match = /^\s*(\d+)\s+(.*)$/.exec(line);
|
|
30
|
+
if (match)
|
|
31
|
+
argv.set(Number(match[1]), match[2]);
|
|
32
|
+
}
|
|
33
|
+
const rows = [];
|
|
34
|
+
for (const line of stats.split("\n")) {
|
|
35
|
+
const match = /^\s*(\d+)\s+(\d+)\s+([\d.]+)\s+(\d+)\s+(.*)$/.exec(line);
|
|
36
|
+
if (!match)
|
|
37
|
+
continue;
|
|
38
|
+
const pid = Number(match[1]);
|
|
39
|
+
rows.push({ pid, ppid: Number(match[2]), cpu: Number(match[3]), rssKB: Number(match[4]), command: match[5].trim(), args: argv.get(pid) ?? match[5].trim() });
|
|
40
|
+
}
|
|
41
|
+
return rows;
|
|
42
|
+
}
|
|
43
|
+
/** What kind of heavy job a process is, if any. */
|
|
44
|
+
export function heavyKind(row) {
|
|
45
|
+
const base = path.basename(row.command);
|
|
46
|
+
const args = row.args;
|
|
47
|
+
if (base === "launchd_sim") {
|
|
48
|
+
return { kind: "simulator", name: /XCTestDevices|Clone \d+ of /.test(args) ? "Simulator test clone" : "Simulator" };
|
|
49
|
+
}
|
|
50
|
+
if (/^qemu-system/.test(base) || base === "emulator" || /^emulator\d*-/.test(base) || /(?:^|\/)emulator\/qemu\//.test(args))
|
|
51
|
+
return { kind: "emulator", name: "Android emulator" };
|
|
52
|
+
if (base === "xcodebuild")
|
|
53
|
+
return { kind: "xcodebuild", name: "xcodebuild" };
|
|
54
|
+
if (base === "java") {
|
|
55
|
+
if (/Gradle(?:Daemon|Worker|Main)|gradle-launcher|org\.gradle\./.test(args))
|
|
56
|
+
return { kind: "gradle", name: /Kotlin/.test(args) ? "Kotlin daemon" : "Gradle" };
|
|
57
|
+
if (/KotlinCompileDaemon/.test(args))
|
|
58
|
+
return { kind: "gradle", name: "Kotlin daemon" };
|
|
59
|
+
return { kind: "java", name: "Java" };
|
|
60
|
+
}
|
|
61
|
+
if (base === "codex" || base === "node" && /^\S*node\s+\S*\/codex(?:\.js)?(?:\s|$)/.test(args))
|
|
62
|
+
return { kind: "codex", name: "Codex" };
|
|
63
|
+
if (base === "opencode" || base === ".opencode")
|
|
64
|
+
return { kind: "opencode", name: "OpenCode" };
|
|
65
|
+
if (base === "claude" || /^\d+\.\d+\.\d+$/.test(base) && /(?:^|\/)claude(?:\s|$)/.test(args))
|
|
66
|
+
return { kind: "claude", name: "Claude Code" };
|
|
67
|
+
return undefined;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* The heavy jobs in a process table. Every process counts toward its nearest
|
|
71
|
+
* heavy ancestor-or-self, so a Codex worker running xcodebuild shows both,
|
|
72
|
+
* each with only its own share. Any other program shows as `busy` when its
|
|
73
|
+
* processes together hold half a core. Agents idling at no cost are left
|
|
74
|
+
* out: only jobs that cost something (a core's tenth or 200 MB) make the list.
|
|
75
|
+
*/
|
|
76
|
+
export function heavyProcesses(rows, owners = new Map(), limit = 12) {
|
|
77
|
+
const byPid = new Map(rows.map(row => [row.pid, row]));
|
|
78
|
+
const kinds = new Map();
|
|
79
|
+
for (const row of rows) {
|
|
80
|
+
const kind = heavyKind(row);
|
|
81
|
+
if (kind)
|
|
82
|
+
kinds.set(row.pid, kind);
|
|
83
|
+
}
|
|
84
|
+
const totals = new Map();
|
|
85
|
+
const busy = new Map();
|
|
86
|
+
const claim = (row) => {
|
|
87
|
+
for (let at = row, hops = 0; at && hops < 64; at = byPid.get(at.ppid), hops++) {
|
|
88
|
+
if (kinds.has(at.pid))
|
|
89
|
+
return at.pid;
|
|
90
|
+
if (at.ppid === at.pid || at.ppid <= 1)
|
|
91
|
+
break;
|
|
92
|
+
}
|
|
93
|
+
return undefined;
|
|
94
|
+
};
|
|
95
|
+
const owner = (row) => {
|
|
96
|
+
for (let at = row, hops = 0; at && hops < 64; at = byPid.get(at.ppid), hops++) {
|
|
97
|
+
const pane = owners.get(at.pid);
|
|
98
|
+
if (pane)
|
|
99
|
+
return pane;
|
|
100
|
+
if (at.ppid === at.pid || at.ppid <= 1)
|
|
101
|
+
break;
|
|
102
|
+
}
|
|
103
|
+
return undefined;
|
|
104
|
+
};
|
|
105
|
+
for (const row of rows) {
|
|
106
|
+
const root = claim(row);
|
|
107
|
+
if (root === undefined) {
|
|
108
|
+
// Unclaimed work groups by program: twelve swift-frontends at 40% each are one busy job.
|
|
109
|
+
const name = path.basename(row.command).slice(0, 60);
|
|
110
|
+
const group = busy.get(name);
|
|
111
|
+
if (!group)
|
|
112
|
+
busy.set(name, { kind: "busy", name, pid: row.pid, processes: 1, cpuPercent: row.cpu, memoryBytes: row.rssKB * 1024, top: row.cpu, row });
|
|
113
|
+
else {
|
|
114
|
+
group.processes++;
|
|
115
|
+
group.cpuPercent += row.cpu;
|
|
116
|
+
group.memoryBytes += row.rssKB * 1024;
|
|
117
|
+
if (row.cpu > group.top) {
|
|
118
|
+
group.top = row.cpu;
|
|
119
|
+
group.pid = row.pid;
|
|
120
|
+
group.row = row;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
let total = totals.get(root);
|
|
126
|
+
if (!total) {
|
|
127
|
+
const { kind, name } = kinds.get(root);
|
|
128
|
+
const pane = owner(byPid.get(root));
|
|
129
|
+
total = { kind, name, pid: root, processes: 0, cpuPercent: 0, memoryBytes: 0, ...(pane ? { pane } : {}) };
|
|
130
|
+
totals.set(root, total);
|
|
131
|
+
}
|
|
132
|
+
total.processes++;
|
|
133
|
+
total.cpuPercent += row.cpu;
|
|
134
|
+
total.memoryBytes += row.rssKB * 1024;
|
|
135
|
+
}
|
|
136
|
+
for (const { top: _top, row, ...group } of busy.values()) {
|
|
137
|
+
if (group.cpuPercent < 50)
|
|
138
|
+
continue;
|
|
139
|
+
const pane = owner(row);
|
|
140
|
+
totals.set(group.pid, { ...group, ...(pane ? { pane } : {}) });
|
|
141
|
+
}
|
|
142
|
+
return [...totals.values()]
|
|
143
|
+
.filter(item => item.kind === "simulator" || item.kind === "emulator" || item.kind === "busy" || item.cpuPercent >= 10 || item.memoryBytes >= 200 * 1024 ** 2)
|
|
144
|
+
.map(item => ({ ...item, cpuPercent: Math.round(item.cpuPercent * 10) / 10 }))
|
|
145
|
+
.sort((a, b) => b.cpuPercent - a.cpuPercent || b.memoryBytes - a.memoryBytes)
|
|
146
|
+
.slice(0, limit);
|
|
147
|
+
}
|
|
148
|
+
/** `pmset -g batt`: "Now drawing from 'AC Power'" then " -InternalBattery-0 (id=…) 87%; charging; …". */
|
|
149
|
+
export function parsePmset(output) {
|
|
150
|
+
const match = /(\d{1,3})%;\s*([^;]+);/.exec(output);
|
|
151
|
+
if (!match)
|
|
152
|
+
return undefined;
|
|
153
|
+
const state = match[2].trim().toLowerCase();
|
|
154
|
+
return { percent: Math.min(100, Number(match[1])), charging: state === "charging" || state === "charged" || state === "finishing charge",
|
|
155
|
+
onAC: /'AC Power'/.test(output) };
|
|
156
|
+
}
|
|
157
|
+
/** `sysctl vm.swapusage`: "total = 2048.00M used = 798.50M free = …". */
|
|
158
|
+
export function parseSwap(output) {
|
|
159
|
+
const match = /used\s*=\s*([\d.]+)([KMG])/.exec(output);
|
|
160
|
+
if (!match)
|
|
161
|
+
return undefined;
|
|
162
|
+
return Math.round(Number(match[1]) * { K: 1024, M: 1024 ** 2, G: GB }[match[2]]);
|
|
163
|
+
}
|
|
164
|
+
/** /proc/meminfo: MemTotal, MemAvailable and swap, in kB. */
|
|
165
|
+
export function parseMeminfo(text) {
|
|
166
|
+
const field = (name) => { const match = new RegExp(`^${name}:\\s+(\\d+)`, "m").exec(text); return match ? Number(match[1]) * 1024 : undefined; };
|
|
167
|
+
const total = field("MemTotal") ?? totalmem(), available = field("MemAvailable");
|
|
168
|
+
const swapTotal = field("SwapTotal"), swapFree = field("SwapFree");
|
|
169
|
+
const availablePercent = available !== undefined && total ? Math.round(available / total * 100) : undefined;
|
|
170
|
+
return { totalBytes: total, ...(availablePercent !== undefined ? { availablePercent, pressure: availablePercent < 5 ? "critical" : availablePercent < 15 ? "warn" : "normal" } : {}),
|
|
171
|
+
...(swapTotal !== undefined && swapFree !== undefined ? { swapUsedBytes: swapTotal - swapFree } : {}) };
|
|
172
|
+
}
|
|
173
|
+
/** Gauge fill and warnings from the numbers. */
|
|
174
|
+
export function assess(value) {
|
|
175
|
+
const cpu = Math.min(1, value.cpu.loadPerCore / 2);
|
|
176
|
+
const memory = value.memory.pressure === "critical" ? 1
|
|
177
|
+
: Math.max(value.memory.pressure === "warn" ? 0.75 : 0, value.memory.availablePercent === undefined ? 0 : 1 - value.memory.availablePercent / 100);
|
|
178
|
+
const free = value.disk?.freeBytes, total = value.disk?.totalBytes;
|
|
179
|
+
// Plenty of room reads by fraction used; under 50 GB it climbs to full at 10 GB.
|
|
180
|
+
const disk = free === undefined || !total ? 0
|
|
181
|
+
: free >= 50 * GB ? 0.5 * (1 - free / total) : Math.min(1, 0.5 + (50 * GB - free) / (80 * GB));
|
|
182
|
+
const round = (n) => Math.round(Math.max(0, n) * 100) / 100;
|
|
183
|
+
const warnings = [];
|
|
184
|
+
if (value.cpu.loadPerCore > 2)
|
|
185
|
+
warnings.push("load-high");
|
|
186
|
+
if (value.memory.pressure === "critical" || (value.memory.availablePercent ?? 100) < 5)
|
|
187
|
+
warnings.push("memory-low");
|
|
188
|
+
if (free !== undefined && free < LOW_DISK_BYTES)
|
|
189
|
+
warnings.push("disk-low");
|
|
190
|
+
if (value.battery && !value.battery.onAC && value.battery.percent < 15)
|
|
191
|
+
warnings.push("battery-low");
|
|
192
|
+
const overall = Math.max(cpu, memory, disk);
|
|
193
|
+
return { pressure: { cpu: round(cpu), memory: round(memory), disk: round(disk), overall: round(overall) },
|
|
194
|
+
level: warnings.some(w => w !== "battery-low") || overall >= 0.9 ? "stressed" : overall >= 0.6 ? "busy" : "ok", warnings };
|
|
195
|
+
}
|
|
196
|
+
async function run(file, args) {
|
|
197
|
+
return (await exec(file, args, { timeout: 4_000, maxBuffer: 8 * 1024 * 1024, env: { ...process.env, LC_ALL: "C" } })).stdout;
|
|
198
|
+
}
|
|
199
|
+
async function darwinMemory() {
|
|
200
|
+
const [level, pressure, swap] = await Promise.all([
|
|
201
|
+
run("/usr/sbin/sysctl", ["-n", "kern.memorystatus_level"]).catch(() => ""),
|
|
202
|
+
run("/usr/sbin/sysctl", ["-n", "kern.memorystatus_vm_pressure_level"]).catch(() => ""),
|
|
203
|
+
run("/usr/sbin/sysctl", ["-n", "vm.swapusage"]).catch(() => ""),
|
|
204
|
+
]);
|
|
205
|
+
const available = Number(level.trim()), code = Number(pressure.trim()), swapUsedBytes = parseSwap(swap);
|
|
206
|
+
return { totalBytes: totalmem(),
|
|
207
|
+
...(level.trim() && Number.isFinite(available) ? { availablePercent: available } : {}),
|
|
208
|
+
...(pressure.trim() && Number.isFinite(code) ? { pressure: code >= 4 ? "critical" : code >= 2 ? "warn" : "normal" } : {}),
|
|
209
|
+
...(swapUsedBytes !== undefined ? { swapUsedBytes } : {}) };
|
|
210
|
+
}
|
|
211
|
+
async function linuxBattery() {
|
|
212
|
+
const root = "/sys/class/power_supply";
|
|
213
|
+
const names = await readdir(root).catch(() => []);
|
|
214
|
+
const battery = names.find(name => /^BAT/.test(name));
|
|
215
|
+
if (!battery)
|
|
216
|
+
return undefined;
|
|
217
|
+
const read = (name, field) => readFile(path.join(root, name, field), "utf8").then(text => text.trim()).catch(() => "");
|
|
218
|
+
const [capacity, status] = await Promise.all([read(battery, "capacity"), read(battery, "status")]);
|
|
219
|
+
const online = await Promise.all(names.filter(name => !/^BAT/.test(name)).map(name => read(name, "online")));
|
|
220
|
+
const percent = Number(capacity);
|
|
221
|
+
if (!capacity || !Number.isFinite(percent))
|
|
222
|
+
return undefined;
|
|
223
|
+
return { percent, charging: status === "Charging" || status === "Full", onAC: online.includes("1") };
|
|
224
|
+
}
|
|
225
|
+
async function processTable() {
|
|
226
|
+
const [stats, args] = await Promise.all([run("/bin/ps", ["-axo", "pid=,ppid=,pcpu=,rss=,comm="]), run("/bin/ps", ["-axo", "pid=,args="])]);
|
|
227
|
+
return parsePs(stats, args);
|
|
228
|
+
}
|
|
229
|
+
/** Every pid a Herdr or tmux pane holds (its shell and foreground), for naming a job's pane. */
|
|
230
|
+
export async function paneOwners() {
|
|
231
|
+
const owners = new Map();
|
|
232
|
+
const { terminalProvider } = await import("./terminal.js");
|
|
233
|
+
const provider = terminalProvider();
|
|
234
|
+
for (const server of (await recentServers()).slice(0, 8)) {
|
|
235
|
+
const name = String(server.session);
|
|
236
|
+
const s = await sharedSnapshot(name, RESOURCES_MAX_AGE_MS).catch(() => undefined);
|
|
237
|
+
if (!s)
|
|
238
|
+
continue;
|
|
239
|
+
const workspaces = new Map(objects(s.workspaces).map(w => [String(w.workspace_id), typeof w.label === "string" ? w.label : undefined]));
|
|
240
|
+
await Promise.all(objects(s.panes).slice(0, 64).map(async (pane) => {
|
|
241
|
+
const processes = await provider.processes(name, String(pane.pane_id)).catch(() => undefined);
|
|
242
|
+
if (!processes)
|
|
243
|
+
return;
|
|
244
|
+
const ref = { server: name, pane: String(pane.pane_id),
|
|
245
|
+
...(workspaces.get(String(pane.workspace_id)) ? { workspace: workspaces.get(String(pane.workspace_id)) } : {}),
|
|
246
|
+
...(typeof pane.agent === "string" ? { agent: pane.agent } : {}),
|
|
247
|
+
...(typeof pane.label === "string" && pane.label ? { label: pane.label } : {}) };
|
|
248
|
+
for (const pid of [processes.shellPid, ...processes.foregroundPids])
|
|
249
|
+
if (typeof pid === "number" && pid > 0)
|
|
250
|
+
owners.set(pid, ref);
|
|
251
|
+
}));
|
|
252
|
+
}
|
|
253
|
+
return owners;
|
|
254
|
+
}
|
|
255
|
+
export async function collectResources(deps) {
|
|
256
|
+
const [one, five, fifteen] = loadavg();
|
|
257
|
+
const cores = cpus().length || 1;
|
|
258
|
+
const platform = deps.platform;
|
|
259
|
+
const [memory, disk, battery, rows] = await Promise.all([
|
|
260
|
+
platform === "darwin" ? darwinMemory()
|
|
261
|
+
: platform === "linux" ? readFile("/proc/meminfo", "utf8").then(parseMeminfo).catch(() => ({ totalBytes: totalmem() }))
|
|
262
|
+
: Promise.resolve({ totalBytes: totalmem() }),
|
|
263
|
+
statfs(deps.home()).then(info => ({ path: "~", totalBytes: info.blocks * info.bsize, freeBytes: info.bavail * info.bsize })).catch(() => undefined),
|
|
264
|
+
platform === "darwin" ? run("/usr/bin/pmset", ["-g", "batt"]).then(parsePmset).catch(() => undefined)
|
|
265
|
+
: platform === "linux" ? linuxBattery() : Promise.resolve(undefined),
|
|
266
|
+
deps.processes().catch(() => []),
|
|
267
|
+
]);
|
|
268
|
+
// Pane pids cost one terminal call per pane: only when there is a job to name.
|
|
269
|
+
const preliminary = heavyProcesses(rows);
|
|
270
|
+
const owners = preliminary.length ? await deps.owners().catch(() => new Map()) : new Map();
|
|
271
|
+
const round = (n) => Math.round(n * 100) / 100;
|
|
272
|
+
const value = {
|
|
273
|
+
collectedAt: new Date(deps.now()).toISOString(), platform, uptimeSeconds: Math.round(uptime()),
|
|
274
|
+
cpu: { cores, load1: round(one), load5: round(five), load15: round(fifteen), loadPerCore: round(one / cores) },
|
|
275
|
+
memory, ...(disk ? { disk } : {}), ...(battery ? { battery } : {}),
|
|
276
|
+
heavy: owners.size ? heavyProcesses(rows, owners) : preliminary,
|
|
277
|
+
};
|
|
278
|
+
return { ...value, ...assess(value) };
|
|
279
|
+
}
|
|
280
|
+
/** One collection at a time, reused for `RESOURCES_MAX_AGE_MS`. */
|
|
281
|
+
export class ResourceMonitor {
|
|
282
|
+
maxAgeMs;
|
|
283
|
+
cached;
|
|
284
|
+
pending;
|
|
285
|
+
deps;
|
|
286
|
+
constructor(deps = {}, maxAgeMs = RESOURCES_MAX_AGE_MS) {
|
|
287
|
+
this.maxAgeMs = maxAgeMs;
|
|
288
|
+
this.deps = { platform: process.platform, now: Date.now, home: homeDir, processes: processTable, owners: paneOwners, ...deps };
|
|
289
|
+
}
|
|
290
|
+
async read() {
|
|
291
|
+
if (this.cached && this.deps.now() - this.cached.at < this.maxAgeMs)
|
|
292
|
+
return this.cached.value;
|
|
293
|
+
this.pending ??= collectResources(this.deps)
|
|
294
|
+
.then(value => { this.cached = { at: this.deps.now(), value }; return value; })
|
|
295
|
+
.finally(() => { this.pending = undefined; });
|
|
296
|
+
return this.pending;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
@@ -14,22 +14,28 @@ import type { WorkspacesReader } from "./server-routes.js";
|
|
|
14
14
|
* overview it holds is still current.
|
|
15
15
|
*
|
|
16
16
|
* Frames: `{ type: "overview", ...workspaces, phren }` and
|
|
17
|
-
* `{ type: "heartbeat", phren }`.
|
|
17
|
+
* `{ type: "heartbeat", phren }`. A phone that asks with `resources=1` also
|
|
18
|
+
* gets `{ type: "resources", resources }` first and every
|
|
19
|
+
* `OVERVIEW_RESOURCES_MS` after (an older phone never asks, so never meets it).
|
|
18
20
|
*/
|
|
19
21
|
export declare const OVERVIEW_TICK_MS: number;
|
|
20
22
|
export declare const OVERVIEW_REFRESH_MS: number;
|
|
21
23
|
export declare const OVERVIEW_HEARTBEAT_MS: number;
|
|
24
|
+
export declare const OVERVIEW_RESOURCES_MS: number;
|
|
22
25
|
export interface OverviewStreamOptions {
|
|
23
26
|
read: WorkspacesReader;
|
|
24
27
|
/** The Hook's info, as `/v1/health` reports it. */
|
|
25
28
|
info: () => Json;
|
|
26
29
|
/** Renews the approval watch lease `watchApprovals=1` asks for. */
|
|
27
30
|
renew: (server: string) => void;
|
|
31
|
+
/** This computer's resources (`GET /v1/resources`), for phones that ask. */
|
|
32
|
+
resources?: () => Promise<unknown>;
|
|
28
33
|
snapshot?: (server: string, maxAgeMs: number) => Promise<Json>;
|
|
29
34
|
now?: () => number;
|
|
30
35
|
tickMs?: number;
|
|
31
36
|
refreshMs?: number;
|
|
32
37
|
heartbeatMs?: number;
|
|
38
|
+
resourcesMs?: number;
|
|
33
39
|
}
|
|
34
40
|
/** A socket-like peer: the `ws` client, or a test double. */
|
|
35
41
|
export interface OverviewClient {
|
|
@@ -39,7 +45,7 @@ export interface OverviewClient {
|
|
|
39
45
|
close(code?: number, reason?: string): void;
|
|
40
46
|
once(event: "close" | "error", listener: () => void): unknown;
|
|
41
47
|
}
|
|
42
|
-
export declare function overviewStream(options: OverviewStreamOptions): (client: OverviewClient, server: string, watchApprovals: boolean) => {
|
|
48
|
+
export declare function overviewStream(options: OverviewStreamOptions): (client: OverviewClient, server: string, watchApprovals: boolean, withResources?: boolean) => {
|
|
43
49
|
tick: () => Promise<void>;
|
|
44
50
|
stop: () => void;
|
|
45
51
|
};
|
|
@@ -19,17 +19,21 @@ import { streamCloseReason } from "./server-stream.js";
|
|
|
19
19
|
* overview it holds is still current.
|
|
20
20
|
*
|
|
21
21
|
* Frames: `{ type: "overview", ...workspaces, phren }` and
|
|
22
|
-
* `{ type: "heartbeat", phren }`.
|
|
22
|
+
* `{ type: "heartbeat", phren }`. A phone that asks with `resources=1` also
|
|
23
|
+
* gets `{ type: "resources", resources }` first and every
|
|
24
|
+
* `OVERVIEW_RESOURCES_MS` after (an older phone never asks, so never meets it).
|
|
23
25
|
*/
|
|
24
26
|
export const OVERVIEW_TICK_MS = intervalFromEnv("PHREN_OVERVIEW_TICK_MS", 5_000, 250, 60_000);
|
|
25
27
|
export const OVERVIEW_REFRESH_MS = intervalFromEnv("PHREN_OVERVIEW_REFRESH_MS", 10_000, 1_000, 120_000);
|
|
26
28
|
export const OVERVIEW_HEARTBEAT_MS = intervalFromEnv("PHREN_OVERVIEW_HEARTBEAT_MS", 20_000, 1_000, 60_000);
|
|
29
|
+
export const OVERVIEW_RESOURCES_MS = intervalFromEnv("PHREN_OVERVIEW_RESOURCES_MS", 12_000, 1_000, 120_000);
|
|
27
30
|
export function overviewStream(options) {
|
|
28
31
|
const snapshot = options.snapshot ?? sharedSnapshot;
|
|
29
32
|
const now = options.now ?? Date.now;
|
|
30
33
|
const tickMs = options.tickMs ?? OVERVIEW_TICK_MS;
|
|
31
34
|
const refreshMs = options.refreshMs ?? OVERVIEW_REFRESH_MS;
|
|
32
35
|
const heartbeatMs = options.heartbeatMs ?? OVERVIEW_HEARTBEAT_MS;
|
|
36
|
+
const resourcesMs = options.resourcesMs ?? OVERVIEW_RESOURCES_MS;
|
|
33
37
|
function send(client, frame) {
|
|
34
38
|
if (client.readyState !== WebSocket.OPEN)
|
|
35
39
|
return false;
|
|
@@ -43,9 +47,9 @@ export function overviewStream(options) {
|
|
|
43
47
|
}
|
|
44
48
|
/** Streams one server's overview until the client closes. Returns the
|
|
45
49
|
* tick function, for tests that drive time themselves. */
|
|
46
|
-
return function stream(client, server, watchApprovals) {
|
|
50
|
+
return function stream(client, server, watchApprovals, withResources = false) {
|
|
47
51
|
let closed = false, busy = false, first = true;
|
|
48
|
-
let snapshotKey = "", builtAt = 0, sentKey = "", sentAt = 0;
|
|
52
|
+
let snapshotKey = "", builtAt = 0, sentKey = "", sentAt = 0, resourcesAt = -Infinity;
|
|
49
53
|
const tick = async () => {
|
|
50
54
|
if (busy || closed)
|
|
51
55
|
return;
|
|
@@ -53,6 +57,15 @@ export function overviewStream(options) {
|
|
|
53
57
|
try {
|
|
54
58
|
countTick("overview-stream");
|
|
55
59
|
const at = now();
|
|
60
|
+
// Resources ride their own frame and clock; a failed read waits for the next.
|
|
61
|
+
if (withResources && options.resources && at - resourcesAt >= resourcesMs) {
|
|
62
|
+
resourcesAt = at;
|
|
63
|
+
const resources = await options.resources().catch(() => undefined);
|
|
64
|
+
if (closed)
|
|
65
|
+
return;
|
|
66
|
+
if (resources)
|
|
67
|
+
send(client, { type: "resources", resources });
|
|
68
|
+
}
|
|
56
69
|
// The first frame reads a fresh snapshot, as a poll would.
|
|
57
70
|
const held = await snapshot(server, first ? 0 : tickMs);
|
|
58
71
|
if (closed)
|
|
@@ -13,7 +13,8 @@ import type { TabActivityStore } from "./tab-activity.js";
|
|
|
13
13
|
import type { ModelCatalog } from "./models.js";
|
|
14
14
|
import type { ModelSwitcher } from "./model-switch.js";
|
|
15
15
|
import type { SideQuestions } from "./side-questions.js";
|
|
16
|
-
import type
|
|
16
|
+
import { type AccountUsageReader } from "./usage.js";
|
|
17
|
+
import type { ResourceMonitor } from "./resources.js";
|
|
17
18
|
import type { Scheduler } from "./schedules.js";
|
|
18
19
|
import type { TranscriptStreams } from "./server-stream.js";
|
|
19
20
|
/** The Hook's HTTP API over its Unix socket: module gating, the GET routes,
|
|
@@ -56,6 +57,7 @@ export interface RouteContext {
|
|
|
56
57
|
modelSwitcher: ModelSwitcher;
|
|
57
58
|
sideQuestions: SideQuestions;
|
|
58
59
|
accountUsage: AccountUsageReader;
|
|
60
|
+
resources: ResourceMonitor;
|
|
59
61
|
codexQuestions: CodexQuestions;
|
|
60
62
|
launches: LaunchLimiter;
|
|
61
63
|
locatedDirectories: Set<string>;
|
|
@@ -96,6 +98,7 @@ export declare const capabilities: {
|
|
|
96
98
|
transcribe: boolean;
|
|
97
99
|
memoryStore: boolean;
|
|
98
100
|
promptOnce: boolean;
|
|
101
|
+
resources: boolean;
|
|
99
102
|
};
|
|
100
103
|
export declare function capabilitiesForModules(snapshot: ModuleSnapshot): Record<string, unknown>;
|
|
101
104
|
export declare function requireRoute(snapshot: ModuleSnapshot, method: string, route: string): void;
|
|
@@ -22,6 +22,7 @@ import { bootedSimulators, simulatorAct, simulatorApps, simulatorScreenshot } fr
|
|
|
22
22
|
import { childAgentTree, historicalImage, publicChildAgents, refreshTranscript, transcriptPath } from "./transcripts.js";
|
|
23
23
|
import { listUploads, saveUpload, uploadImage } from "./uploads.js";
|
|
24
24
|
import { currentModel, currentStep } from "./steps.js";
|
|
25
|
+
import { usageForCaller } from "./usage.js";
|
|
25
26
|
import { healthDetails, listsCaller } from "./health.js";
|
|
26
27
|
import { defaultPhrenPath } from "../shared.js";
|
|
27
28
|
import { loadCodePackage, loadedFrom } from "../modules/code-package.js";
|
|
@@ -51,7 +52,7 @@ async function childActivity(source, session) {
|
|
|
51
52
|
export const capabilities = { transcript: true, progress: true, images: true, prompt: true, stop: true,
|
|
52
53
|
terminal: "ssh-pty", shell: "ssh-pty", herdr: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
|
|
53
54
|
approvals: true, questions: false, accountUsage: true, providers: ["codex", "claude", "copilot", "opencode"],
|
|
54
|
-
files: true, repositoryFiles: true, subagents: true, sideQuestions: true, dispatch: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, overviewStream: true, speech: true, speechTimestamps: true, transcribe: true, memoryStore: true, promptOnce: true };
|
|
55
|
+
files: true, repositoryFiles: true, subagents: true, sideQuestions: true, dispatch: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, overviewStream: true, speech: true, speechTimestamps: true, transcribe: true, memoryStore: true, promptOnce: true, resources: true };
|
|
55
56
|
export function capabilitiesForModules(snapshot) {
|
|
56
57
|
const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
|
|
57
58
|
const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
|
|
@@ -170,8 +171,23 @@ export function workspacesReader(ctx) {
|
|
|
170
171
|
return { ...workspaces, phren: info };
|
|
171
172
|
};
|
|
172
173
|
}
|
|
174
|
+
/** One read-only GET to every linked peer, each answer or its error by computer name. */
|
|
175
|
+
async function fromPeers(route) {
|
|
176
|
+
const { peers, peerError } = await optionalHookPeers();
|
|
177
|
+
const answers = await Promise.all(peers.map(async (peer) => {
|
|
178
|
+
try {
|
|
179
|
+
return { name: peer.name, ...await peerRequest(peer, route, undefined, 15_000) };
|
|
180
|
+
}
|
|
181
|
+
catch (error) {
|
|
182
|
+
const code = error instanceof BridgeError && typeof error.details?.code === "string" ? error.details.code : undefined;
|
|
183
|
+
const older = error instanceof BridgeError && error.status === 404;
|
|
184
|
+
return { name: peer.name, error: older ? "This computer's Hook predates this report; update it with phren bridge update." : error instanceof Error ? error.message.slice(0, 300) : "Unavailable", ...(code ? { code } : {}) };
|
|
185
|
+
}
|
|
186
|
+
}));
|
|
187
|
+
return { peers: answers, ...(peerError ? { peerError } : {}) };
|
|
188
|
+
}
|
|
173
189
|
export function createRouteHandler(ctx) {
|
|
174
|
-
const { version, modules, info, computerID, scheduleStore, scheduler, dispatches, agentHooks, journal, modelCatalog, accountUsage, launches, locatedDirectories, fanoutMessages, canary } = ctx;
|
|
190
|
+
const { version, modules, info, computerID, scheduleStore, scheduler, dispatches, agentHooks, journal, modelCatalog, accountUsage, resources, launches, locatedDirectories, fanoutMessages, canary } = ctx;
|
|
175
191
|
const { conversationReader, childConversationReader, emptyPage } = ctx.streams;
|
|
176
192
|
const readWorkspaces = workspacesReader(ctx);
|
|
177
193
|
return async (request, response) => {
|
|
@@ -294,8 +310,23 @@ export function createRouteHandler(ctx) {
|
|
|
294
310
|
// meets a source it does not know, so a client names the sources it
|
|
295
311
|
// understands and an older one gets the original four.
|
|
296
312
|
const known = new Set((url.searchParams.get("sources") ?? "codex,claude,opencode,openrouter").split(",").map(s => s.trim()).filter(Boolean));
|
|
313
|
+
// A phone built before Go's plan windows rejects a Go window with a
|
|
314
|
+
// percentage and no dollar limit (and the whole answer with it), so
|
|
315
|
+
// they go only to callers that ask with `goPlan=1`; others keep the
|
|
316
|
+
// Go account and its message without windows.
|
|
317
|
+
const goPlan = url.searchParams.get("goPlan") === "1";
|
|
297
318
|
const usage = await accountUsage.read();
|
|
298
|
-
result = { ...usage, accounts: usage.accounts
|
|
319
|
+
result = { ...usage, accounts: usageForCaller(usage.accounts, known, goPlan) };
|
|
320
|
+
// `peers=1` (the memory-free `phren usage`): each linked computer's own answer too.
|
|
321
|
+
if (url.searchParams.get("peers") === "1")
|
|
322
|
+
result = { ...result, computer: info.computer,
|
|
323
|
+
...await fromPeers(`/v1/usage?${new URLSearchParams({ sources: [...known].join(","), ...(goPlan ? { goPlan: "1" } : {}) })}`) };
|
|
324
|
+
break;
|
|
325
|
+
}
|
|
326
|
+
case "/v1/resources": {
|
|
327
|
+
result = { computer: info.computer, resources: await resources.read() };
|
|
328
|
+
if (url.searchParams.get("peers") === "1")
|
|
329
|
+
result = { ...result, ...await fromPeers("/v1/resources") };
|
|
299
330
|
break;
|
|
300
331
|
}
|
|
301
332
|
case "/v1/push/status":
|