@phren/cli
Version:
Knowledge layer for AI agents - CLI, MCP server, and data layer
59 lines (58 loc) • 3.05 kB
JavaScript
import { createHash } from "node:crypto";
import { existsSync } from "node:fs";
import { readFile } from "node:fs/promises";
import { homedir, userInfo } from "node:os";
import path from "node:path";
import { execProbe } from "./probe-processes.js";
import { BridgeError, bridgeRoot, object, objects } from "./protocol.js";
// Core addresses have a leading nonzero digit and a consonant/digit suffix.
// A qualified address uses a machine already configured in Core.
const ADDRESS = /^(?:[a-z0-9][a-z0-9_.-]{0,31}\/)?t[1-9][0-9bcdfghjkmnpqrstvwxyz]{0,6}$/;
export function isCoreAddress(value) {
return !!value && ADDRESS.exec(value)?.[0] === value;
}
export function coreAddressMachine(address) {
const slash = address.indexOf("/");
return slash < 0 ? undefined : address.slice(0, slash);
}
/** Both Hook processes use the owner's pin or the same OS default. */
export async function coreTerminalEndpoint(base) {
const config = path.join(bridgeRoot(), "herdr-core.json");
const state = path.join(homedir(), ".local/state");
const runtime = process.platform === "linux" ? `/run/user/${userInfo().uid}` : undefined;
let socket = runtime && existsSync(runtime)
? path.join(runtime, "herdr-core/default.sock")
: path.join(state, "herdr-core/default/default.sock");
try {
const pin = object(JSON.parse(await readFile(config, "utf8"))).socket;
if (typeof pin !== "string" || !path.isAbsolute(pin) || /[\x00-\x1f\x7f]/.test(pin))
throw new Error("Invalid socket path.");
socket = path.normalize(pin);
}
catch (error) {
if (error.code !== "ENOENT") {
throw new BridgeError(503, "Set an absolute socket path in the Hook's herdr-core.json.", { code: "terminal-core-unavailable" });
}
}
const env = Object.fromEntries(Object.entries(base).filter(([key]) => !key.startsWith("HC_")));
return { id: createHash("sha256").update(socket).digest("hex"), env: { ...env, HC_SOCKET: socket } };
}
export async function liveCoreTerminal(address, env) {
let list;
try {
const { stdout } = await execProbe("hc", ["ls", "--json"], { env, timeout: 4_000, maxBuffer: 4 * 1024 * 1024 });
list = object(JSON.parse(stdout));
if (!Array.isArray(list.terminals))
throw new Error("Invalid Core terminal list.");
}
catch (error) {
const missing = error.code === "ENOENT";
throw new BridgeError(503, missing ? "Herdr Core (hc) is not installed on this computer." : "Herdr Core could not list its terminals.", { code: "terminal-core-unavailable" });
}
// Exact address, since Core also accepts names. A lost terminal waiting for
// its shell to restart still appears live in Core's list.
const terminal = objects(list.terminals).find(entry => entry.address === address && entry.state === "live" && entry.reason == null);
if (!terminal)
throw new BridgeError(404, "No live terminal matches that address.", { code: "terminal-not-found" });
return terminal;
}