@phren/cli 0.3.10 → 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/usage.d.ts +36 -20
- package/dist/bridge/usage.js +163 -301
- package/dist/bridge-hook.mjs +974 -793
- 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/fanout/SKILL.md +3 -0
package/dist/cli-registry.d.ts
CHANGED
|
@@ -34,6 +34,8 @@ export interface Command {
|
|
|
34
34
|
subcommands?: Subcommand[];
|
|
35
35
|
featured?: boolean;
|
|
36
36
|
hidden?: boolean;
|
|
37
|
+
/** Runs without a Phren store: dispatch never finds, activates or tracks one. */
|
|
38
|
+
standalone?: boolean;
|
|
37
39
|
run: RunFn;
|
|
38
40
|
}
|
|
39
41
|
export declare const ENV_HELP = "Environment variables:\n PHREN_PATH Override phren directory (default: ~/.phren)\n PHREN_PROFILE Active profile name\n PHREN_DEBUG Enable debug logging (set to 1)\n PHREN_PULL_INTERVAL_SECONDS Remote check interval in seconds (default: off; 0 disables)\n\n Embeddings:\n PHREN_OLLAMA_URL Ollama base URL (default: http://localhost:11434, 'off' to disable)\n PHREN_EMBEDDING_API_URL OpenAI-compatible /embeddings endpoint\n PHREN_EMBEDDING_API_KEY API key for embedding endpoint\n PHREN_EMBEDDING_MODEL Embedding model (default: nomic-embed-text)\n\n Context injection:\n PHREN_CONTEXT_TOKEN_BUDGET Max tokens injected per prompt (default: 550)\n PHREN_MAX_INJECT_TOKENS Hard cap on total injected tokens (default: 2000)\n PHREN_HOOK_TIMEOUT_MS Hook subprocess timeout in ms (default: 14000)\n\n Feature flags:\n PHREN_FEATURE_AGENTS=1 Show running coding agents on the graph\n PHREN_FEATURE_TOOL_HOOK=0 Skip the PostToolUse subprocess (perf)\n PHREN_FEATURE_AUTO_EXTRACT=0 Disable auto memory extraction\n PHREN_FEATURE_AUTO_CAPTURE=1 Extract insights from conversations\n PHREN_FEATURE_SEMANTIC_DEDUP=1 LLM-based dedup on add_finding\n PHREN_FEATURE_HYBRID_SEARCH=0 Disable TF-IDF cosine fallback\n\n Run 'phren help all' to see everything.\n";
|
package/dist/cli-registry.js
CHANGED
|
@@ -164,6 +164,19 @@ export const REGISTRY = [
|
|
|
164
164
|
{ name: "sessions", usage: "phren dispatch sessions", summary: "List live agent sessions on this and every enrolled computer" }],
|
|
165
165
|
run: async (args) => (await import("./bridge/dispatch-command.js")).runDispatch(args),
|
|
166
166
|
},
|
|
167
|
+
{
|
|
168
|
+
name: "computers", topic: "core", standalone: true,
|
|
169
|
+
usage: "phren computers [<name>] [--resources] [--pick [mac|linux|any]] [--exclude a,b] [--local] [--json] | phren computers mcp",
|
|
170
|
+
summary: "Each computer's load, memory, disk, battery and heavy jobs from Phren Hook, without Phren memory; `mcp` serves them read-only to agents",
|
|
171
|
+
subcommands: [{ name: "mcp", usage: "phren computers mcp", summary: "Stdio MCP server: list_computers, get_resources, pick_computer, get_usage (read-only, no memory)" }],
|
|
172
|
+
run: async (args) => (await import("./computers/command.js")).runComputers(args),
|
|
173
|
+
},
|
|
174
|
+
{
|
|
175
|
+
name: "usage", topic: "core", standalone: true,
|
|
176
|
+
usage: "phren usage [--per-computer] [--computer <name>] [--local] [--json]",
|
|
177
|
+
summary: "Agent usage per harness (limits, resets, spend) across computers from Phren Hook, without Phren memory",
|
|
178
|
+
run: async (args) => (await import("./computers/command.js")).runUsage(args),
|
|
179
|
+
},
|
|
167
180
|
{
|
|
168
181
|
name: "hand-off", topic: "core", usage: "phren hand-off <computer|local> --session <id> --text <prompt>",
|
|
169
182
|
summary: "Send work to an existing agent session through Phren Hook",
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { type HarnessUsage } from "./read.js";
|
|
2
|
+
import type { ComputerResources } from "../bridge/resources.js";
|
|
3
|
+
export declare function formatResources(name: string, r: ComputerResources, detail: boolean): string[];
|
|
4
|
+
export declare function formatHarness(h: HarnessUsage): string[];
|
|
5
|
+
export declare function runComputers(args: string[]): Promise<number>;
|
|
6
|
+
export declare function runUsage(args: string[]): Promise<number>;
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { combineUsage, describe, findComputer, pickComputer, readComputers, readUsage } from "./read.js";
|
|
2
|
+
/**
|
|
3
|
+
* `phren computers` and `phren usage`: read-only, answered by the Phren Hook
|
|
4
|
+
* alone. They run without a Phren store (the registry marks them
|
|
5
|
+
* standalone), so someone with no memory, findings or tasks can use them.
|
|
6
|
+
*/
|
|
7
|
+
const GB = 1024 ** 3;
|
|
8
|
+
const flag = (args, name) => args.includes(name);
|
|
9
|
+
function option(args, name) {
|
|
10
|
+
const at = args.indexOf(name);
|
|
11
|
+
if (at >= 0)
|
|
12
|
+
return args[at + 1];
|
|
13
|
+
const inline = args.find(arg => arg.startsWith(`${name}=`));
|
|
14
|
+
return inline?.slice(name.length + 1);
|
|
15
|
+
}
|
|
16
|
+
function gauge(value) {
|
|
17
|
+
const filled = Math.round(Math.max(0, Math.min(1, value)) * 5);
|
|
18
|
+
return "▰".repeat(filled) + "▱".repeat(5 - filled);
|
|
19
|
+
}
|
|
20
|
+
function durationText(seconds) {
|
|
21
|
+
const days = Math.floor(seconds / 86400), hours = Math.floor(seconds % 86400 / 3600);
|
|
22
|
+
return days ? `${days}d ${hours}h` : `${hours}h ${Math.floor(seconds % 3600 / 60)}m`;
|
|
23
|
+
}
|
|
24
|
+
export function formatResources(name, r, detail) {
|
|
25
|
+
const lines = [`${name} ${gauge(r.pressure.overall)} ${r.level}${r.warnings.length ? ` (${r.warnings.join(", ")})` : ""}`];
|
|
26
|
+
lines.push(` cpu load ${r.cpu.load1} / ${r.cpu.load5} / ${r.cpu.load15} on ${r.cpu.cores} cores (${r.cpu.loadPerCore}× per core)`);
|
|
27
|
+
const memory = [r.memory.availablePercent !== undefined ? `${r.memory.availablePercent}% free` : "", r.memory.pressure ? `pressure ${r.memory.pressure}` : "",
|
|
28
|
+
`${(r.memory.totalBytes / GB).toFixed(0)} GB`, r.memory.swapUsedBytes ? `swap ${(r.memory.swapUsedBytes / GB).toFixed(1)} GB` : ""].filter(Boolean);
|
|
29
|
+
lines.push(` memory ${memory.join(", ")}`);
|
|
30
|
+
if (r.disk)
|
|
31
|
+
lines.push(` disk ${(r.disk.freeBytes / GB).toFixed(1)} GB free of ${(r.disk.totalBytes / GB).toFixed(0)} GB (home volume)`);
|
|
32
|
+
if (r.battery)
|
|
33
|
+
lines.push(` battery ${r.battery.percent}%${r.battery.charging ? ", charging" : ""}${r.battery.onAC ? ", on AC" : ", on battery"}`);
|
|
34
|
+
lines.push(` uptime ${durationText(r.uptimeSeconds)}`);
|
|
35
|
+
if (detail || r.heavy.length) {
|
|
36
|
+
const heavy = detail ? r.heavy : r.heavy.slice(0, 4);
|
|
37
|
+
if (heavy.length)
|
|
38
|
+
lines.push(" heavy");
|
|
39
|
+
for (const job of heavy) {
|
|
40
|
+
const pane = job.pane ? ` ${[job.pane.workspace, job.pane.pane, job.pane.agent].filter(Boolean).join(" · ")}` : "";
|
|
41
|
+
lines.push(` ${job.name.padEnd(22)} ${String(job.cpuPercent).padStart(6)}% cpu ${(job.memoryBytes / GB).toFixed(1).padStart(5)} GB${job.processes > 1 ? ` ×${job.processes}` : ""}${pane}`);
|
|
42
|
+
}
|
|
43
|
+
if (!detail && r.heavy.length > heavy.length)
|
|
44
|
+
lines.push(` … ${r.heavy.length - heavy.length} more (phren computers --resources <name>)`);
|
|
45
|
+
}
|
|
46
|
+
return lines;
|
|
47
|
+
}
|
|
48
|
+
export function formatHarness(h) {
|
|
49
|
+
const lines = [` ${h.harness}`];
|
|
50
|
+
for (const w of h.windows) {
|
|
51
|
+
const used = w.usedPercent !== undefined ? `${w.usedPercent}% used` : w.usedUSD !== undefined ? `$${w.usedUSD.toFixed(2)}${w.limitUSD !== undefined ? ` of $${w.limitUSD.toFixed(2)}` : ""}` : "";
|
|
52
|
+
lines.push(` ${w.name.padEnd(30)} ${used.padEnd(18)}${w.resetsIn ? `resets in ${w.resetsIn}` : ""}`);
|
|
53
|
+
}
|
|
54
|
+
if (h.spend)
|
|
55
|
+
lines.push(` spend ${h.spend.period.replace(/_/g, " ").padEnd(24)} $${h.spend.amountUSD.toFixed(2)}`);
|
|
56
|
+
if (h.message)
|
|
57
|
+
lines.push(` ${h.message}`);
|
|
58
|
+
return lines;
|
|
59
|
+
}
|
|
60
|
+
export async function runComputers(args) {
|
|
61
|
+
if (args[0] === "mcp") {
|
|
62
|
+
await (await import("./mcp.js")).serveComputersMcp();
|
|
63
|
+
return 0;
|
|
64
|
+
}
|
|
65
|
+
const json = flag(args, "--json");
|
|
66
|
+
const pick = flag(args, "--pick") ? (option(args, "--pick") && !option(args, "--pick").startsWith("-") ? option(args, "--pick") : "mac") : undefined;
|
|
67
|
+
const named = args.find((arg, index) => !arg.startsWith("-") && !["--pick", "--exclude"].includes(args[index - 1] ?? ""));
|
|
68
|
+
const report = await readComputers({ peers: !flag(args, "--local") });
|
|
69
|
+
if (pick) {
|
|
70
|
+
if (!["mac", "linux", "any"].includes(pick)) {
|
|
71
|
+
console.error("--pick takes mac, linux or any.");
|
|
72
|
+
return 1;
|
|
73
|
+
}
|
|
74
|
+
const result = pickComputer(report.computers, pick, (option(args, "--exclude") ?? "").split(",").filter(Boolean));
|
|
75
|
+
if (json)
|
|
76
|
+
console.log(JSON.stringify({ pick: result.pick?.name ?? null, reason: result.reason, ranked: result.ranked }, null, 2));
|
|
77
|
+
else {
|
|
78
|
+
console.log(result.reason);
|
|
79
|
+
for (const item of result.ranked.slice(1))
|
|
80
|
+
console.log(` then ${item.name}: ${item.why}`);
|
|
81
|
+
}
|
|
82
|
+
return result.pick ? 0 : 1;
|
|
83
|
+
}
|
|
84
|
+
const chosen = named ? findComputer(report.computers, named) : undefined;
|
|
85
|
+
if (named && !chosen) {
|
|
86
|
+
console.error(`No computer named ${named}. Known: ${report.computers.map(c => c.name).join(", ")}`);
|
|
87
|
+
return 1;
|
|
88
|
+
}
|
|
89
|
+
const list = chosen ? [chosen] : report.computers;
|
|
90
|
+
if (json) {
|
|
91
|
+
console.log(JSON.stringify({ computers: list, ...(report.hookError ? { hookError: report.hookError } : {}), ...(report.peerError ? { peerError: report.peerError } : {}) }, null, 2));
|
|
92
|
+
return 0;
|
|
93
|
+
}
|
|
94
|
+
const detail = Boolean(chosen) || flag(args, "--resources") && list.length === 1;
|
|
95
|
+
if (report.hookError)
|
|
96
|
+
console.log(`${report.hookError} Showing this computer only.\n`);
|
|
97
|
+
for (const computer of list) {
|
|
98
|
+
if (!computer.resources) {
|
|
99
|
+
console.log(`${computer.name} offline: ${computer.error ?? "unavailable"}\n`);
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
if (!flag(args, "--resources") && !chosen)
|
|
103
|
+
console.log(`${computer.name.padEnd(28)} ${gauge(computer.resources.pressure.overall)} ${computer.resources.level.padEnd(9)} ${describe(computer.resources)}`);
|
|
104
|
+
else
|
|
105
|
+
console.log(formatResources(computer.name, computer.resources, detail).join("\n") + "\n");
|
|
106
|
+
}
|
|
107
|
+
if (report.peerError)
|
|
108
|
+
console.log(`\nLinked computers unavailable: ${report.peerError}`);
|
|
109
|
+
return 0;
|
|
110
|
+
}
|
|
111
|
+
export async function runUsage(args) {
|
|
112
|
+
if (args[0] === "mcp") {
|
|
113
|
+
await (await import("./mcp.js")).serveComputersMcp();
|
|
114
|
+
return 0;
|
|
115
|
+
}
|
|
116
|
+
const json = flag(args, "--json");
|
|
117
|
+
const report = await readUsage({ peers: !flag(args, "--local") });
|
|
118
|
+
const named = option(args, "--computer");
|
|
119
|
+
const computers = named ? report.computers.filter(c => c.name.toLowerCase().startsWith(named.toLowerCase())) : report.computers;
|
|
120
|
+
if (named && !computers.length) {
|
|
121
|
+
console.error(`No computer named ${named}. Known: ${report.computers.map(c => c.name).join(", ")}`);
|
|
122
|
+
return 1;
|
|
123
|
+
}
|
|
124
|
+
const combined = named ? combineUsage(computers.flatMap(c => c.harnesses ? [c.harnesses] : [])) : report.combined;
|
|
125
|
+
if (json) {
|
|
126
|
+
console.log(JSON.stringify({ computers, combined, ...(report.hookError ? { hookError: report.hookError } : {}) }, null, 2));
|
|
127
|
+
return report.hookError ? 1 : 0;
|
|
128
|
+
}
|
|
129
|
+
if (report.hookError) {
|
|
130
|
+
console.error(report.hookError);
|
|
131
|
+
return 1;
|
|
132
|
+
}
|
|
133
|
+
if (!flag(args, "--per-computer")) {
|
|
134
|
+
console.log(`Usage across ${computers.filter(c => c.harnesses).length} computer(s)`);
|
|
135
|
+
for (const h of combined)
|
|
136
|
+
console.log(formatHarness(h).join("\n"));
|
|
137
|
+
const offline = computers.filter(c => c.error);
|
|
138
|
+
if (offline.length)
|
|
139
|
+
console.log(`\nNot reporting: ${offline.map(c => `${c.name} (${c.error})`).join("; ")}`);
|
|
140
|
+
return 0;
|
|
141
|
+
}
|
|
142
|
+
for (const computer of computers) {
|
|
143
|
+
console.log(computer.name);
|
|
144
|
+
if (computer.error) {
|
|
145
|
+
console.log(` ${computer.error}`);
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
for (const h of computer.harnesses ?? [])
|
|
149
|
+
console.log(formatHarness(h).join("\n"));
|
|
150
|
+
}
|
|
151
|
+
return 0;
|
|
152
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function serveComputersMcp(): Promise<void>;
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { VERSION } from "../package-metadata.js";
|
|
2
|
+
import { combineUsage, describe, findComputer, pickComputer, readComputers, readUsage } from "./read.js";
|
|
3
|
+
/**
|
|
4
|
+
* `phren computers mcp`: a stdio MCP server with four read-only tools over
|
|
5
|
+
* the Phren Hook: list computers, one computer's resources, the least-loaded
|
|
6
|
+
* computer, and agent usage. It never opens a Phren store and has no memory,
|
|
7
|
+
* finding or task tools, so it can be handed to an agent that must not see
|
|
8
|
+
* them. Register it with `claude mcp add phren-computers -- phren computers mcp`.
|
|
9
|
+
*/
|
|
10
|
+
const INSTRUCTIONS = [
|
|
11
|
+
"Read-only view of the owner's computers and agent usage, answered by the Phren Hook.",
|
|
12
|
+
"Before a heavy job (Xcode or simulator tests, emulators, Gradle), call pick_computer and run it there; check get_resources before starting a second heavy job on a computer.",
|
|
13
|
+
"A computer whose level is 'stressed' (load above twice its cores, under 10 GB free disk, or critical memory) should not get new heavy work.",
|
|
14
|
+
"get_usage shows each harness's limits, windows and time until reset; a harness that reports nothing says so.",
|
|
15
|
+
].join(" ");
|
|
16
|
+
const text = (value) => ({ content: [{ type: "text", text: JSON.stringify(value, null, 2) }] });
|
|
17
|
+
const failure = (message) => ({ content: [{ type: "text", text: message }], isError: true });
|
|
18
|
+
const readOnly = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
|
|
19
|
+
export async function serveComputersMcp() {
|
|
20
|
+
const [{ McpServer }, { StdioServerTransport }, { z }] = await Promise.all([
|
|
21
|
+
import("@modelcontextprotocol/sdk/server/mcp.js"),
|
|
22
|
+
import("@modelcontextprotocol/sdk/server/stdio.js"),
|
|
23
|
+
import("zod"),
|
|
24
|
+
]);
|
|
25
|
+
const server = new McpServer({ name: "phren-computers", version: VERSION }, { instructions: INSTRUCTIONS });
|
|
26
|
+
server.registerTool("list_computers", {
|
|
27
|
+
title: "List computers",
|
|
28
|
+
description: "Every computer this Hook knows (this one and each linked one): online, platform, load level, CPU load against cores, free memory and disk, warnings. Read-only.",
|
|
29
|
+
inputSchema: z.object({}),
|
|
30
|
+
annotations: readOnly,
|
|
31
|
+
}, async () => {
|
|
32
|
+
const report = await readComputers();
|
|
33
|
+
return text({
|
|
34
|
+
computers: report.computers.map(c => c.resources ? {
|
|
35
|
+
name: c.name, local: c.local, online: true, platform: c.resources.platform, level: c.resources.level, warnings: c.resources.warnings,
|
|
36
|
+
pressure: c.resources.pressure.overall, cores: c.resources.cpu.cores, load1: c.resources.cpu.load1,
|
|
37
|
+
memoryFreePercent: c.resources.memory.availablePercent, diskFreeGB: c.resources.disk ? Math.round(c.resources.disk.freeBytes / 1024 ** 3 * 10) / 10 : undefined,
|
|
38
|
+
heavyJobs: c.resources.heavy.length, summary: describe(c.resources),
|
|
39
|
+
} : { name: c.name, local: c.local, online: false, error: c.error }),
|
|
40
|
+
...(report.hookError ? { hookError: report.hookError } : {}), ...(report.peerError ? { peerError: report.peerError } : {}),
|
|
41
|
+
});
|
|
42
|
+
});
|
|
43
|
+
server.registerTool("get_resources", {
|
|
44
|
+
title: "Get a computer's resources",
|
|
45
|
+
description: "One computer's live resources: load averages and cores, memory, free disk on the home volume, battery, uptime, and heavy jobs (simulators, emulators, xcodebuild, Gradle, agent workers) with the terminal pane that started each where known. Omit computer for this one. Read-only.",
|
|
46
|
+
inputSchema: z.object({ computer: z.string().max(253).optional().describe("Computer name (or prefix) from list_computers; omit for this computer.") }),
|
|
47
|
+
annotations: readOnly,
|
|
48
|
+
}, async ({ computer }) => {
|
|
49
|
+
const report = await readComputers({ peers: Boolean(computer) });
|
|
50
|
+
const found = findComputer(report.computers, computer);
|
|
51
|
+
if (!found)
|
|
52
|
+
return failure(`No computer named ${computer}. Known: ${report.computers.map(c => c.name).join(", ")}`);
|
|
53
|
+
return text(found.resources ? { name: found.name, local: found.local, ...found.resources } : { name: found.name, online: false, error: found.error });
|
|
54
|
+
});
|
|
55
|
+
server.registerTool("pick_computer", {
|
|
56
|
+
title: "Pick the least-loaded computer",
|
|
57
|
+
description: "The least-loaded online computer for a heavy job, with the ranking and why. Defaults to Macs (Xcode, simulators). Read-only; it starts nothing.",
|
|
58
|
+
inputSchema: z.object({
|
|
59
|
+
platform: z.enum(["mac", "linux", "any"]).optional().describe("mac (default), linux or any."),
|
|
60
|
+
exclude: z.array(z.string().max(253)).max(32).optional().describe("Computer names to leave out."),
|
|
61
|
+
}),
|
|
62
|
+
annotations: readOnly,
|
|
63
|
+
}, async ({ platform, exclude }) => {
|
|
64
|
+
const result = pickComputer((await readComputers()).computers, platform ?? "mac", exclude ?? []);
|
|
65
|
+
return text({ pick: result.pick?.name ?? null, reason: result.reason, ranked: result.ranked });
|
|
66
|
+
});
|
|
67
|
+
server.registerTool("get_usage", {
|
|
68
|
+
title: "Get agent usage",
|
|
69
|
+
description: "Agent usage per harness (Claude, Codex, GitHub Copilot, OpenCode incl. DeepSeek via its local spend, OpenCode Go, OpenRouter): limits and windows with percent used and time until reset, and recent spend where the harness reports it. Per computer and combined. A harness that reports nothing says so. No credentials are ever included. Read-only.",
|
|
70
|
+
inputSchema: z.object({
|
|
71
|
+
computer: z.string().max(253).optional().describe("Only this computer (name or prefix)."),
|
|
72
|
+
view: z.enum(["combined", "per-computer", "both"]).optional().describe("combined (default), per-computer or both."),
|
|
73
|
+
}),
|
|
74
|
+
annotations: readOnly,
|
|
75
|
+
}, async ({ computer, view }) => {
|
|
76
|
+
const report = await readUsage();
|
|
77
|
+
if (report.hookError)
|
|
78
|
+
return failure(report.hookError);
|
|
79
|
+
const computers = computer ? report.computers.filter(c => c.name.toLowerCase().startsWith(computer.toLowerCase())) : report.computers;
|
|
80
|
+
if (computer && !computers.length)
|
|
81
|
+
return failure(`No computer named ${computer}. Known: ${report.computers.map(c => c.name).join(", ")}`);
|
|
82
|
+
const combined = computer ? combineUsage(computers.flatMap(c => c.harnesses ? [c.harnesses] : [])) : report.combined;
|
|
83
|
+
const mode = view ?? "combined";
|
|
84
|
+
return text({
|
|
85
|
+
...(mode !== "per-computer" ? { combined } : {}),
|
|
86
|
+
...(mode !== "combined" ? { computers } : { computersReporting: computers.map(c => c.error ? `${c.name} (not reporting: ${c.error})` : c.name) }),
|
|
87
|
+
});
|
|
88
|
+
});
|
|
89
|
+
const transport = new StdioServerTransport();
|
|
90
|
+
// The CLI exits once a command returns, so serve until the client hangs up.
|
|
91
|
+
let hangUp = () => { };
|
|
92
|
+
const closed = new Promise(resolve => { hangUp = resolve; process.stdin.once("end", resolve); });
|
|
93
|
+
await server.connect(transport);
|
|
94
|
+
server.server.onclose = hangUp;
|
|
95
|
+
console.error("phren-computers MCP server running (read-only, no memory)");
|
|
96
|
+
await closed;
|
|
97
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import type { ComputerResources } from "../bridge/resources.js";
|
|
2
|
+
import type { AccountUsage, UsageWindow } from "../bridge/usage.js";
|
|
3
|
+
import type { Json } from "../bridge/protocol.js";
|
|
4
|
+
/**
|
|
5
|
+
* The memory-free computers surface: every read goes to the local Hook's
|
|
6
|
+
* socket (`GET /v1/resources?peers=1`, `GET /v1/usage?peers=1`), which answers
|
|
7
|
+
* for itself and asks each linked computer over its pinned SSH pipe. Nothing
|
|
8
|
+
* here opens, needs or reports a Phren store, findings or tasks, and nothing
|
|
9
|
+
* writes: `phren computers`, `phren usage` and `phren computers mcp` share it.
|
|
10
|
+
*/
|
|
11
|
+
export interface ComputerReport {
|
|
12
|
+
name: string;
|
|
13
|
+
/** This computer, the one whose Hook answered. */
|
|
14
|
+
local: boolean;
|
|
15
|
+
online: boolean;
|
|
16
|
+
resources?: ComputerResources;
|
|
17
|
+
error?: string;
|
|
18
|
+
}
|
|
19
|
+
/** Every harness the Hook reads usage for, in the order people look for them. */
|
|
20
|
+
export declare const USAGE_SOURCES: readonly ["claude", "codex", "copilot", "opencode", "opencode-go", "openrouter"];
|
|
21
|
+
export declare const HARNESS_NAMES: Record<string, string>;
|
|
22
|
+
export interface HarnessUsage {
|
|
23
|
+
source: string;
|
|
24
|
+
harness: string;
|
|
25
|
+
windows: Array<UsageWindow & {
|
|
26
|
+
resetsIn?: string;
|
|
27
|
+
}>;
|
|
28
|
+
spend?: AccountUsage["spend"];
|
|
29
|
+
updatedAt?: string;
|
|
30
|
+
/** What the harness said, or why it gave nothing. Never a guess. */
|
|
31
|
+
message?: string;
|
|
32
|
+
}
|
|
33
|
+
export interface UsageReport {
|
|
34
|
+
computers: Array<{
|
|
35
|
+
name: string;
|
|
36
|
+
local: boolean;
|
|
37
|
+
harnesses?: HarnessUsage[];
|
|
38
|
+
error?: string;
|
|
39
|
+
}>;
|
|
40
|
+
/** Across computers: account limits from the freshest report, local spend summed. */
|
|
41
|
+
combined: HarnessUsage[];
|
|
42
|
+
}
|
|
43
|
+
type Request = (route: string) => Promise<Json>;
|
|
44
|
+
export declare function readComputers(options?: {
|
|
45
|
+
peers?: boolean;
|
|
46
|
+
request?: Request;
|
|
47
|
+
localFallback?: () => Promise<ComputerResources>;
|
|
48
|
+
}): Promise<{
|
|
49
|
+
computers: ComputerReport[];
|
|
50
|
+
hookError?: string;
|
|
51
|
+
peerError?: string;
|
|
52
|
+
}>;
|
|
53
|
+
export declare function findComputer(computers: ComputerReport[], name: string | undefined): ComputerReport | undefined;
|
|
54
|
+
export type PlatformChoice = "mac" | "linux" | "any";
|
|
55
|
+
/**
|
|
56
|
+
* The least-loaded online computer: stressed ones last, then by overall
|
|
57
|
+
* pressure, then load per core, then free disk. Each candidate carries why.
|
|
58
|
+
*/
|
|
59
|
+
export declare function pickComputer(computers: ComputerReport[], platform?: PlatformChoice, exclude?: string[]): {
|
|
60
|
+
pick?: ComputerReport;
|
|
61
|
+
reason: string;
|
|
62
|
+
ranked: Array<{
|
|
63
|
+
name: string;
|
|
64
|
+
score: number;
|
|
65
|
+
level: string;
|
|
66
|
+
why: string;
|
|
67
|
+
}>;
|
|
68
|
+
};
|
|
69
|
+
export declare function describe(r: ComputerResources): string;
|
|
70
|
+
export declare function resetsIn(resetsAt: string | undefined, now?: number): string | undefined;
|
|
71
|
+
/**
|
|
72
|
+
* Account limits are the same account seen from each computer, so the
|
|
73
|
+
* freshest report with windows stands. OpenCode's cost ledger is per
|
|
74
|
+
* computer, so its spend adds up; OpenRouter's is one key, reported once.
|
|
75
|
+
*/
|
|
76
|
+
export declare function combineUsage(perComputer: HarnessUsage[][]): HarnessUsage[];
|
|
77
|
+
export declare function readUsage(options?: {
|
|
78
|
+
peers?: boolean;
|
|
79
|
+
request?: Request;
|
|
80
|
+
now?: number;
|
|
81
|
+
}): Promise<UsageReport & {
|
|
82
|
+
hookError?: string;
|
|
83
|
+
peerError?: string;
|
|
84
|
+
}>;
|
|
85
|
+
export {};
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { hostname } from "node:os";
|
|
2
|
+
import { hookRequest } from "../bridge/client.js";
|
|
3
|
+
/** Every harness the Hook reads usage for, in the order people look for them. */
|
|
4
|
+
export const USAGE_SOURCES = ["claude", "codex", "copilot", "opencode", "opencode-go", "openrouter"];
|
|
5
|
+
export const HARNESS_NAMES = {
|
|
6
|
+
claude: "Claude", codex: "Codex", copilot: "GitHub Copilot",
|
|
7
|
+
opencode: "OpenCode (local spend, any provider incl. DeepSeek)", "opencode-go": "OpenCode Go", openrouter: "OpenRouter",
|
|
8
|
+
};
|
|
9
|
+
const defaultRequest = route => hookRequest(route, undefined, undefined, 30_000);
|
|
10
|
+
function hookMissing(error) {
|
|
11
|
+
const code = error?.code;
|
|
12
|
+
if (code === "ENOENT" || code === "ECONNREFUSED")
|
|
13
|
+
return "Phren Hook is not running on this computer (phren bridge status).";
|
|
14
|
+
if (error?.status === 404)
|
|
15
|
+
return "This computer's Phren Hook predates this report; update it with phren bridge update.";
|
|
16
|
+
return error instanceof Error ? error.message.slice(0, 300) : "Phren Hook did not answer.";
|
|
17
|
+
}
|
|
18
|
+
function computerName(value, fallback) {
|
|
19
|
+
const name = value?.name;
|
|
20
|
+
return typeof name === "string" && name ? name : fallback;
|
|
21
|
+
}
|
|
22
|
+
export async function readComputers(options = {}) {
|
|
23
|
+
const request = options.request ?? defaultRequest;
|
|
24
|
+
let answer;
|
|
25
|
+
try {
|
|
26
|
+
answer = await request(`/v1/resources${options.peers === false ? "" : "?peers=1"}`);
|
|
27
|
+
}
|
|
28
|
+
catch (error) {
|
|
29
|
+
const hookError = hookMissing(error);
|
|
30
|
+
// Without a Hook this computer can still report itself; peers need the Hook.
|
|
31
|
+
const fallback = options.localFallback ?? (async () => new (await import("../bridge/resources.js")).ResourceMonitor().read());
|
|
32
|
+
const resources = await fallback().catch(() => undefined);
|
|
33
|
+
return { hookError, computers: [{ name: hostname(), local: true, online: Boolean(resources), ...(resources ? { resources } : { error: hookError }) }] };
|
|
34
|
+
}
|
|
35
|
+
const computers = [{ name: computerName(answer.computer, hostname()), local: true, online: true, resources: answer.resources }];
|
|
36
|
+
for (const peer of Array.isArray(answer.peers) ? answer.peers : []) {
|
|
37
|
+
const name = computerName(peer.computer, String(peer.name ?? "peer"));
|
|
38
|
+
computers.push(peer.resources && !peer.error
|
|
39
|
+
? { name, local: false, online: true, resources: peer.resources }
|
|
40
|
+
: { name, local: false, online: false, error: typeof peer.error === "string" ? peer.error : "Unavailable" });
|
|
41
|
+
}
|
|
42
|
+
return { computers, ...(typeof answer.peerError === "string" ? { peerError: answer.peerError } : {}) };
|
|
43
|
+
}
|
|
44
|
+
export function findComputer(computers, name) {
|
|
45
|
+
if (!name || name === "local" || name === "this")
|
|
46
|
+
return computers.find(c => c.local);
|
|
47
|
+
const wanted = name.toLowerCase().replace(/\.local$/, "");
|
|
48
|
+
return computers.find(c => c.name.toLowerCase().replace(/\.local$/, "") === wanted)
|
|
49
|
+
?? computers.find(c => c.name.toLowerCase().startsWith(wanted));
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* The least-loaded online computer: stressed ones last, then by overall
|
|
53
|
+
* pressure, then load per core, then free disk. Each candidate carries why.
|
|
54
|
+
*/
|
|
55
|
+
export function pickComputer(computers, platform = "mac", exclude = []) {
|
|
56
|
+
const skip = new Set(exclude.map(name => name.toLowerCase()));
|
|
57
|
+
const wanted = (r) => platform === "any" || (platform === "mac" ? r.platform === "darwin" : r.platform === platform);
|
|
58
|
+
const candidates = computers.filter(c => c.online && c.resources && wanted(c.resources) && !skip.has(c.name.toLowerCase()));
|
|
59
|
+
const rank = (c) => {
|
|
60
|
+
const r = c.resources;
|
|
61
|
+
return [r.level === "stressed" ? 1 : 0, r.pressure.overall, r.cpu.loadPerCore, -(r.disk?.freeBytes ?? 0)];
|
|
62
|
+
};
|
|
63
|
+
candidates.sort((a, b) => {
|
|
64
|
+
const x = rank(a), y = rank(b);
|
|
65
|
+
for (let i = 0; i < x.length; i++)
|
|
66
|
+
if (x[i] !== y[i])
|
|
67
|
+
return x[i] - y[i];
|
|
68
|
+
return 0;
|
|
69
|
+
});
|
|
70
|
+
const ranked = candidates.map(c => ({ name: c.name, score: c.resources.pressure.overall, level: c.resources.level, why: describe(c.resources) }));
|
|
71
|
+
const pick = candidates[0];
|
|
72
|
+
const label = platform === "mac" ? "Mac" : platform === "linux" ? "Linux computer" : "computer";
|
|
73
|
+
if (!pick)
|
|
74
|
+
return { reason: `No online ${label} reported resources.`, ranked };
|
|
75
|
+
const stressedNote = pick.resources.level === "stressed" ? " Every candidate is stressed; expect slow runs." : "";
|
|
76
|
+
return { pick, reason: `${pick.name} is the least-loaded ${label}: ${describe(pick.resources)}.${stressedNote}`, ranked };
|
|
77
|
+
}
|
|
78
|
+
const GB = 1024 ** 3;
|
|
79
|
+
export function describe(r) {
|
|
80
|
+
const parts = [`load ${r.cpu.load1} on ${r.cpu.cores} cores`];
|
|
81
|
+
if (r.memory.availablePercent !== undefined)
|
|
82
|
+
parts.push(`${r.memory.availablePercent}% memory free`);
|
|
83
|
+
if (r.disk)
|
|
84
|
+
parts.push(`${(r.disk.freeBytes / GB).toFixed(0)} GB disk free`);
|
|
85
|
+
if (r.warnings.length)
|
|
86
|
+
parts.push(`warnings: ${r.warnings.join(", ")}`);
|
|
87
|
+
return parts.join(", ");
|
|
88
|
+
}
|
|
89
|
+
export function resetsIn(resetsAt, now = Date.now()) {
|
|
90
|
+
const at = resetsAt ? Date.parse(resetsAt) : NaN;
|
|
91
|
+
if (!Number.isFinite(at))
|
|
92
|
+
return undefined;
|
|
93
|
+
const minutes = Math.max(0, Math.round((at - now) / 60_000));
|
|
94
|
+
const days = Math.floor(minutes / 1440), hours = Math.floor(minutes % 1440 / 60), rest = minutes % 60;
|
|
95
|
+
return days ? `${days}d ${hours}h` : hours ? `${hours}h ${rest}m` : `${rest}m`;
|
|
96
|
+
}
|
|
97
|
+
function harness(account, now) {
|
|
98
|
+
return { source: account.source, harness: HARNESS_NAMES[account.source] ?? account.source,
|
|
99
|
+
// Only the numbers a person budgets by; no key identity, no origin.
|
|
100
|
+
windows: account.windows.map(({ id, name, usedPercent, usedUSD, limitUSD, usedTokens, resetsAt, asOf }) => {
|
|
101
|
+
const window = { id, name };
|
|
102
|
+
if (usedPercent !== undefined)
|
|
103
|
+
window.usedPercent = usedPercent;
|
|
104
|
+
if (usedUSD !== undefined)
|
|
105
|
+
window.usedUSD = usedUSD;
|
|
106
|
+
if (limitUSD !== undefined)
|
|
107
|
+
window.limitUSD = limitUSD;
|
|
108
|
+
if (usedTokens !== undefined)
|
|
109
|
+
window.usedTokens = usedTokens;
|
|
110
|
+
if (resetsAt) {
|
|
111
|
+
window.resetsAt = resetsAt;
|
|
112
|
+
const left = resetsIn(resetsAt, now);
|
|
113
|
+
if (left)
|
|
114
|
+
window.resetsIn = left;
|
|
115
|
+
}
|
|
116
|
+
if (asOf)
|
|
117
|
+
window.asOf = asOf;
|
|
118
|
+
return window;
|
|
119
|
+
}),
|
|
120
|
+
...(account.spend ? { spend: account.spend } : {}),
|
|
121
|
+
...(account.updatedAt ? { updatedAt: account.updatedAt } : {}),
|
|
122
|
+
...(account.message ? { message: account.message } : !account.windows.length && !account.spend ? { message: "No usage data reported." } : {}) };
|
|
123
|
+
}
|
|
124
|
+
const NOT_REPORTED = "This computer's Hook did not report this harness; it may predate it (phren bridge update).";
|
|
125
|
+
function harnesses(accounts, now) {
|
|
126
|
+
const list = Array.isArray(accounts) ? accounts : [];
|
|
127
|
+
const bySource = new Map(list.map(account => [account.source, account]));
|
|
128
|
+
// Every harness the Hook knows appears, saying so when it had nothing.
|
|
129
|
+
return USAGE_SOURCES.map(source => bySource.get(source) ? harness(bySource.get(source), now)
|
|
130
|
+
: { source, harness: HARNESS_NAMES[source], windows: [], message: source === "openrouter"
|
|
131
|
+
? "No OpenRouter key is configured on this computer." : NOT_REPORTED });
|
|
132
|
+
}
|
|
133
|
+
const fresher = (a, b) => Date.parse(b.updatedAt ?? "") > Date.parse(a.updatedAt ?? "") ? b : a;
|
|
134
|
+
/**
|
|
135
|
+
* Account limits are the same account seen from each computer, so the
|
|
136
|
+
* freshest report with windows stands. OpenCode's cost ledger is per
|
|
137
|
+
* computer, so its spend adds up; OpenRouter's is one key, reported once.
|
|
138
|
+
*/
|
|
139
|
+
export function combineUsage(perComputer) {
|
|
140
|
+
return USAGE_SOURCES.map(source => {
|
|
141
|
+
const reports = perComputer.map(list => list.find(item => item.source === source)).filter((item) => Boolean(item));
|
|
142
|
+
const withData = reports.filter(item => item.windows.length || item.spend);
|
|
143
|
+
// With no numbers anywhere, a Hook's own explanation beats "did not report".
|
|
144
|
+
if (!withData.length)
|
|
145
|
+
return reports.find(item => item.message !== NOT_REPORTED) ?? reports[0] ?? { source, harness: HARNESS_NAMES[source], windows: [], message: "No usage data reported." };
|
|
146
|
+
if (source === "opencode") {
|
|
147
|
+
const spends = withData.filter(item => item.spend);
|
|
148
|
+
const amount = spends.reduce((sum, item) => sum + item.spend.amountUSD, 0);
|
|
149
|
+
return { ...withData.reduce(fresher), ...(spends.length ? { spend: { amountUSD: Math.round(amount * 100) / 100, period: spends[0].spend.period } } : {}),
|
|
150
|
+
message: `Local spend summed across ${spends.length} computer${spends.length === 1 ? "" : "s"}.` };
|
|
151
|
+
}
|
|
152
|
+
const best = withData.filter(item => item.windows.length).reduce((a, b) => a ? fresher(a, b) : b, undefined) ?? withData.reduce(fresher);
|
|
153
|
+
return best;
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
export async function readUsage(options = {}) {
|
|
157
|
+
const request = options.request ?? defaultRequest, now = options.now ?? Date.now();
|
|
158
|
+
const query = new URLSearchParams({ sources: USAGE_SOURCES.join(","), goPlan: "1" });
|
|
159
|
+
if (options.peers !== false)
|
|
160
|
+
query.set("peers", "1");
|
|
161
|
+
let answer;
|
|
162
|
+
try {
|
|
163
|
+
answer = await request(`/v1/usage?${query}`);
|
|
164
|
+
}
|
|
165
|
+
catch (error) {
|
|
166
|
+
return { hookError: hookMissing(error), computers: [{ name: hostname(), local: true, error: hookMissing(error) }], combined: [] };
|
|
167
|
+
}
|
|
168
|
+
const computers = [{ name: computerName(answer.computer, hostname()), local: true, harnesses: harnesses(answer.accounts, now) }];
|
|
169
|
+
for (const peer of Array.isArray(answer.peers) ? answer.peers : []) {
|
|
170
|
+
const name = computerName(peer.computer, String(peer.name ?? "peer"));
|
|
171
|
+
computers.push(peer.error || !Array.isArray(peer.accounts)
|
|
172
|
+
? { name, local: false, error: typeof peer.error === "string" ? peer.error : "Unavailable" }
|
|
173
|
+
: { name, local: false, harnesses: harnesses(peer.accounts, now) });
|
|
174
|
+
}
|
|
175
|
+
const combined = combineUsage(computers.flatMap(c => c.harnesses ? [c.harnesses] : []));
|
|
176
|
+
return { computers, combined, ...(typeof answer.peerError === "string" ? { peerError: answer.peerError } : {}) };
|
|
177
|
+
}
|
package/dist/entrypoint.js
CHANGED
|
@@ -148,6 +148,16 @@ export async function runTopLevelCommand(argv, opts = {}) {
|
|
|
148
148
|
const cmd = lookupCommand(argvCommand);
|
|
149
149
|
if (!cmd)
|
|
150
150
|
return false;
|
|
151
|
+
// Hook-only commands never find, activate or track a store.
|
|
152
|
+
if (cmd.standalone && !argv.includes("--help") && !argv.includes("-h")) {
|
|
153
|
+
try {
|
|
154
|
+
return finish(await cmd.run(argv.slice(1), buildCliContext()) ?? undefined);
|
|
155
|
+
}
|
|
156
|
+
catch (err) {
|
|
157
|
+
console.error(errorMessage(err));
|
|
158
|
+
return finish(1);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
151
161
|
let snapshot;
|
|
152
162
|
try {
|
|
153
163
|
const store = findPhrenPath() ?? defaultPhrenPath();
|
|
@@ -1,7 +1,20 @@
|
|
|
1
1
|
import { uuid } from "./types.js";
|
|
2
|
+
// `claude -p` asks nothing headless: a build worker accepts edits, and a
|
|
3
|
+
// command the brief needs comes through `--extra --allowedTools`. A manifest
|
|
4
|
+
// model of "default" means the configured one, so no --model is passed.
|
|
2
5
|
export const claude = {
|
|
3
6
|
command: "claude",
|
|
4
|
-
argv: o => ["-p", "--output-format", "stream-json", "--verbose", "--model", o.model,
|
|
5
|
-
|
|
7
|
+
argv: o => ["-p", "--output-format", "stream-json", "--verbose", ...(o.model && o.model !== "default" ? ["--model", o.model] : []),
|
|
8
|
+
"--permission-mode", o.review ? "plan" : "acceptEdits", ...(o.resume ? ["--resume", o.resume] : []), ...(o.extra ?? [])],
|
|
6
9
|
session: event => uuid(event.session_id),
|
|
10
|
+
// It exits 0 after refusing a tool; the result row lists what it refused.
|
|
11
|
+
refusal: event => {
|
|
12
|
+
const denials = event.type === "result" && Array.isArray(event.permission_denials) ? event.permission_denials : [];
|
|
13
|
+
const first = denials[0] && typeof denials[0] === "object" ? denials[0] : undefined;
|
|
14
|
+
if (!first)
|
|
15
|
+
return undefined;
|
|
16
|
+
const tool = String(first.tool_name ?? "tool").slice(0, 200), input = (first.tool_input && typeof first.tool_input === "object" ? first.tool_input : {});
|
|
17
|
+
const target = String(input.command ?? input.file_path ?? input.path ?? "").slice(0, 500);
|
|
18
|
+
return { type: "permission", pattern: `${tool} ${target}`.trim(), message: `${denials.length} tool call(s) refused; first: ${tool}` };
|
|
19
|
+
},
|
|
7
20
|
};
|
|
@@ -14,6 +14,12 @@ export interface Adapter {
|
|
|
14
14
|
command: Provider;
|
|
15
15
|
argv(options: LaunchOptions): string[];
|
|
16
16
|
session(event: Record<string, unknown>): string | undefined;
|
|
17
|
+
/** A tool the worker was refused, when the harness reports it in its events. */
|
|
18
|
+
refusal?(event: Record<string, unknown>): {
|
|
19
|
+
type: string;
|
|
20
|
+
pattern: string;
|
|
21
|
+
message: string;
|
|
22
|
+
} | undefined;
|
|
17
23
|
/** A harness that serves an API instead of printing events: the launcher
|
|
18
24
|
* spawns `argv` and this drives the worker, returning its exit code. */
|
|
19
25
|
drive?(child: ChildProcess, options: DriveOptions): Promise<number>;
|
|
@@ -16,8 +16,12 @@ export declare function jobsRoot(store: string): string;
|
|
|
16
16
|
export declare function readJob(store: string, id: string): FanoutManifest;
|
|
17
17
|
export declare function listJobs(store: string): FanoutManifest[];
|
|
18
18
|
export declare function swiftBuildCount(): number;
|
|
19
|
+
/** The nearest codex or claude process above this one. Each agent sets its
|
|
20
|
+
* own id for the commands it runs and inherits the other's, so a Claude
|
|
21
|
+
* started from Codex has both; the process tree says which one launched. */
|
|
22
|
+
export declare function nearestAgent(pid?: number): "codex" | "claude" | undefined;
|
|
19
23
|
export declare function writeManifest(job: string, manifest: FanoutManifest): void;
|
|
20
|
-
export declare function createJob(options: JobOptions, env?: NodeJS.ProcessEnv): {
|
|
24
|
+
export declare function createJob(options: JobOptions, env?: NodeJS.ProcessEnv, nearest?: typeof nearestAgent): {
|
|
21
25
|
job: string;
|
|
22
26
|
manifest: FanoutManifest;
|
|
23
27
|
};
|