feat(cli): runnable daemon, local CLI, doctor, service files and smoke test

- composition root wiring config/auth/workspaces/instances/http
- singleton lock + daemon.json + port retry + local cli.token (admin scope)
- pi2 attach/status/doctor/pairing/install-service
- systemd user unit + launchd plist rendering (never auto-enabled)
- smoke.sh boots the real daemon on an ephemeral port and asserts auth/static/lifecycle
- 93 new tests (263 total), tsc + build + smoke green
This commit is contained in:
yuez committed 2026-10-21 12:45:11 +08:00
1 parent a495f2ac71
commit 18e3e0ab4e
23 files changed
+4494 -1

No files matched your search

+407
View File
@@ -0,0 +1,407 @@
/**
* `pi2 doctor` — environment checks with injectable probes.
*
* Every input the checks need lives in a `DoctorContext`; `defaultProbes(ctx)`
* turns that context into the check list and `runDoctor()` executes it. Tests
* build a context directly instead of poking at the real machine.
*/
import { execFile } from "node:child_process";
import { existsSync, statSync } from "node:fs";
import { homedir, platform as osPlatform } from "node:os";
import { join } from "node:path";
import { promisify } from "node:util";
import { fileURLToPath } from "node:url";
import { DEFAULT_PORT } from "../config.js";
import { daemonSocketPath, runtimeDir } from "../core/paths.js";
import { PROTOCOL_VERSION } from "../protocol/types.js";
import { formatTable } from "./util.js";
const execFileAsync = promisify(execFile);
export type CheckStatus = "ok" | "warn" | "fail";
export interface DoctorCheck {
name: string;
status: CheckStatus;
detail: string;
}
export interface DoctorProbe {
name: string;
run(): DoctorCheck | Promise<DoctorCheck>;
}
export interface DoctorReport {
ok: boolean;
checks: DoctorCheck[];
}
export interface BinaryProbe {
found: boolean;
path?: string;
version?: string;
error?: string;
}
export interface DoctorContext {
platform: NodeJS.Platform;
nodeVersion: string;
nvim: BinaryProbe;
pi: BinaryProbe;
plugin: { dir: string | undefined; bridgeFound: boolean };
runtime: { path: string; exists: boolean; mode: number | undefined };
cliToken: { path: string; exists: boolean; mode: number | undefined };
socket: { path: string; exists: boolean };
daemon: { reachable: boolean; port?: number; protocolVersion?: number; error?: string };
port: { configured: number; bound: boolean };
serviceManager: { name: "systemd" | "launchd"; available: boolean; detail?: string };
linger: { checked: boolean; enabled?: boolean; detail?: string };
webDist: { path: string; exists: boolean };
}
/** `v22.1.0` / `22.1.0` → `[22,1,0]`. */
export function parseVersion(raw: string | undefined): [number, number, number] | undefined {
if (raw === undefined) return undefined;
const match = /(\d+)\.(\d+)\.(\d+)/.exec(raw);
if (!match) return undefined;
return [Number(match[1]), Number(match[2]), Number(match[3])];
}
export function versionAtLeast(version: readonly [number, number, number], minimum: readonly [number, number, number]): boolean {
for (let index = 0; index < 3; index += 1) {
const left = version[index] ?? 0;
const right = minimum[index] ?? 0;
if (left !== right) return left > right;
}
return true;
}
/** `NVIM v0.10.2` (first line of `nvim --version`) → `0.10.2`. */
export function parseNvimVersion(output: string): string | undefined {
const match = /NVIM v(\d+\.\d+\.\d+)/.exec(output);
return match?.[1];
}
export const MIN_NODE: readonly [number, number, number] = [22, 0, 0];
export const MIN_NVIM: readonly [number, number, number] = [0, 9, 0];
/** `<repo>/web/dist`, matching `loadConfig()`'s default. */
export function defaultWebDist(): string {
return fileURLToPath(new URL("../../web/dist", import.meta.url));
}
export function checkNode(version: string): DoctorCheck {
const parsed = parseVersion(version);
if (parsed === undefined) return { name: "node", status: "fail", detail: `unparsable version "${version}"` };
const ok = versionAtLeast(parsed, MIN_NODE);
return {
name: "node",
status: ok ? "ok" : "fail",
detail: `${version}${ok ? "" : ` (< ${MIN_NODE.join(".")})`}`,
};
}
export function checkNvim(probe: BinaryProbe): DoctorCheck {
if (!probe.found) {
return { name: "nvim", status: "fail", detail: probe.error ?? "nvim not found on PATH" };
}
const version = parseVersion(probe.version);
if (version === undefined) {
return { name: "nvim", status: "warn", detail: `could not parse version of ${probe.path ?? "nvim"}` };
}
const ok = versionAtLeast(version, MIN_NVIM);
return {
name: "nvim",
status: ok ? "ok" : "fail",
detail: `${probe.version?.trim() ?? version.join(".")} (${probe.path ?? "nvim"})${ok ? "" : ` < ${MIN_NVIM.join(".")} for --remote-ui`}`,
};
}
export function checkPi(probe: BinaryProbe): DoctorCheck {
if (!probe.found) return { name: "pi", status: "warn", detail: probe.error ?? "pi not found on PATH (plugin-only sessions still work)" };
return { name: "pi", status: "ok", detail: `${probe.version?.trim() ?? "unknown version"} (${probe.path ?? "pi"})` };
}
export function checkPlugin(probe: DoctorContext["plugin"]): DoctorCheck {
if (probe.bridgeFound) {
return { name: "plugin", status: "ok", detail: `${probe.dir ?? "pi2.nvim"} (lua/pi/web/bridge.lua)` };
}
return {
name: "plugin",
status: "fail",
detail: `pi2.nvim not found (set PI2_PLUGIN_DIR or install it); looked in ${probe.dir ?? "~/.local/share/nvim/lazy/pi2.nvim"}`,
};
}
function permsDetail(mode: number | undefined): string {
return mode === undefined ? "mode unknown" : `mode ${mode.toString(8).padStart(4, "0")}`;
}
export function checkRuntimeDir(probe: DoctorContext["runtime"]): DoctorCheck {
if (!probe.exists) return { name: "runtime-dir", status: "fail", detail: `${probe.path} missing` };
const ok = probe.mode !== undefined && (probe.mode & 0o077) === 0;
return {
name: "runtime-dir",
status: ok ? "ok" : "warn",
detail: `${probe.path} (${permsDetail(probe.mode)}${ok ? "" : ", expected 0700"})`,
};
}
export function checkCliToken(probe: DoctorContext["cliToken"]): DoctorCheck {
if (!probe.exists) {
return { name: "cli-token", status: "warn", detail: `${probe.path} missing (start pi2d to mint it)` };
}
const ok = probe.mode !== undefined && (probe.mode & 0o077) === 0;
return {
name: "cli-token",
status: ok ? "ok" : "fail",
detail: `${probe.path} (${permsDetail(probe.mode)}${ok ? "" : ", expected 0600"})`,
};
}
export function checkSocket(probe: DoctorContext["socket"], daemonReachable: boolean): DoctorCheck {
if (!probe.exists) {
return {
name: "socket",
status: daemonReachable ? "warn" : "fail",
detail: `${probe.path} missing`,
};
}
return { name: "socket", status: "ok", detail: `${probe.path} present` };
}
export function checkDaemon(probe: DoctorContext["daemon"]): DoctorCheck {
if (!probe.reachable) {
return { name: "daemon", status: "fail", detail: probe.error ?? "not reachable (is pi2d running?)" };
}
return { name: "daemon", status: "ok", detail: `http://127.0.0.1:${probe.port ?? "?"} reachable` };
}
export function checkPort(probe: DoctorContext["port"]): DoctorCheck {
if (probe.bound) return { name: "port", status: "ok", detail: `${probe.configured} bound by pi2d` };
return { name: "port", status: "ok", detail: `${probe.configured} free` };
}
export function checkServiceManager(probe: DoctorContext["serviceManager"]): DoctorCheck {
return {
name: "service-manager",
status: probe.available ? "ok" : "warn",
detail: probe.detail ?? (probe.available ? `${probe.name} available` : `${probe.name} not reachable`),
};
}
export function checkLinger(probe: DoctorContext["linger"]): DoctorCheck {
if (!probe.checked) return { name: "linger", status: "ok", detail: "not applicable" };
const detail = probe.detail ?? (probe.enabled === true ? "Linger=yes" : "Linger=no (enable with loginctl enable-linger)");
return { name: "linger", status: probe.enabled === true ? "ok" : "warn", detail };
}
export function checkWebDist(probe: DoctorContext["webDist"]): DoctorCheck {
if (probe.exists) return { name: "web-dist", status: "ok", detail: probe.path };
return { name: "web-dist", status: "warn", detail: `${probe.path} missing (build the web UI for the browser console)` };
}
export function checkProtocol(probe: DoctorContext["daemon"]): DoctorCheck {
if (!probe.reachable) return { name: "protocol", status: "fail", detail: "no daemon to compare against" };
if (probe.protocolVersion === PROTOCOL_VERSION) {
return { name: "protocol", status: "ok", detail: `v${PROTOCOL_VERSION}` };
}
return {
name: "protocol",
status: "fail",
detail: `daemon speaks v${String(probe.protocolVersion)}, CLI expects v${PROTOCOL_VERSION}`,
};
}
/** The canonical check list, in display order. */
export function defaultProbes(ctx: DoctorContext): DoctorProbe[] {
const isLinux = ctx.platform === "linux";
return [
{ name: "node", run: () => checkNode(ctx.nodeVersion) },
{ name: "nvim", run: () => checkNvim(ctx.nvim) },
{ name: "pi", run: () => checkPi(ctx.pi) },
{ name: "plugin", run: () => checkPlugin(ctx.plugin) },
{ name: "runtime-dir", run: () => checkRuntimeDir(ctx.runtime) },
{ name: "cli-token", run: () => checkCliToken(ctx.cliToken) },
{ name: "socket", run: () => checkSocket(ctx.socket, ctx.daemon.reachable) },
{ name: "daemon", run: () => checkDaemon(ctx.daemon) },
{ name: "port", run: () => checkPort(ctx.port) },
{ name: "service-manager", run: () => checkServiceManager(ctx.serviceManager) },
...(isLinux ? [{ name: "linger", run: () => checkLinger(ctx.linger) }] : []),
{ name: "web-dist", run: () => checkWebDist(ctx.webDist) },
{ name: "protocol", run: () => checkProtocol(ctx.daemon) },
];
}
export async function runDoctor(probes: readonly DoctorProbe[]): Promise<DoctorReport> {
const checks: DoctorCheck[] = [];
for (const probe of probes) {
try {
checks.push(await probe.run());
} catch (error) {
checks.push({
name: probe.name,
status: "fail",
detail: error instanceof Error ? error.message : String(error),
});
}
}
return { ok: checks.every((check) => check.status !== "fail"), checks };
}
const MARKS: Record<CheckStatus, string> = { ok: "ok ", warn: "warn", fail: "FAIL" };
export function formatReport(report: DoctorReport): string {
const rows = report.checks.map((check) => [MARKS[check.status], check.name, check.detail]);
return [formatTable(["", "check", "detail"], rows), "", `overall: ${report.ok ? "ok" : "FAILED"}`].join("\n");
}
export function reportToJson(report: DoctorReport): string {
return `${JSON.stringify({ ok: report.ok, checks: report.checks }, null, 2)}`;
}
// ---------------------------------------------------------------------------
// Real-environment context
// ---------------------------------------------------------------------------
export interface RunLike {
(command: string, args: readonly string[]): Promise<{ ok: boolean; stdout: string; stderr: string }>;
}
export interface DoctorOptions {
platform?: NodeJS.Platform;
env?: NodeJS.ProcessEnv;
runtime?: string;
home?: string;
uid?: number;
/** Reachable daemon info (`/api/v1/info`), or the reason it is not reachable. */
daemonInfo?: () => Promise<{ port: number; protocolVersion: number } | { error: string }>;
run?: RunLike;
which?: (command: string) => string | undefined;
now?: () => number;
}
async function defaultRun(command: string, args: readonly string[]): Promise<{ ok: boolean; stdout: string; stderr: string }> {
try {
const { stdout, stderr } = await execFileAsync(command, [...args], { timeout: 5_000, encoding: "utf8" });
return { ok: true, stdout, stderr };
} catch (error) {
const failure = error as NodeJS.ErrnoException & { stdout?: string; stderr?: string };
return { ok: false, stdout: failure.stdout ?? "", stderr: failure.stderr ?? failure.message ?? "" };
}
}
function whichSync(command: string, env: NodeJS.ProcessEnv): string | undefined {
const path = env.PATH ?? "";
for (const dir of path.split(":")) {
if (dir === "") continue;
const candidate = join(dir, command);
if (existsSync(candidate)) return candidate;
}
return undefined;
}
function statOrUndefined(path: string): { exists: boolean; mode: number | undefined } {
try {
return { exists: true, mode: statSync(path).mode & 0o777 };
} catch {
return { exists: false, mode: undefined };
}
}
async function binaryProbe(command: string, args: readonly string[], options: DoctorOptions, env: NodeJS.ProcessEnv): Promise<BinaryProbe> {
const path = (options.which ?? ((name: string) => whichSync(name, env)))(command);
if (path === undefined) return { found: false, error: `${command} not found on PATH` };
const run = options.run ?? defaultRun;
const result = await run(command, args);
if (!result.ok) {
return { found: true, path, ...(result.stderr.trim() === "" ? {} : { error: result.stderr.trim() }) };
}
const version = result.stdout.trim().split("\n")[0] ?? "";
return { found: true, path, version };
}
export async function collectContext(options: DoctorOptions = {}): Promise<DoctorContext> {
const env = options.env ?? process.env;
const platform = options.platform ?? osPlatform();
const runtime = options.runtime ?? runtimeDir();
const home = options.home ?? homedir();
const run = options.run ?? defaultRun;
const uid = options.uid ?? (typeof process.getuid === "function" ? process.getuid() : 0);
const nvim = await binaryProbe("nvim", ["--version"], options, env);
if (nvim.found && nvim.version !== undefined) {
const parsed = parseNvimVersion(nvim.version);
if (parsed !== undefined) nvim.version = `v${parsed}`;
}
const pi = await binaryProbe("pi", ["--version"], options, env);
const pluginDir = env.PI2_PLUGIN_DIR?.trim() || join(home, ".local", "share", "nvim", "lazy", "pi2.nvim");
const bridgeFound = existsSync(join(pluginDir, "lua", "pi", "web", "bridge.lua"));
const runtimeStat = statOrUndefined(runtime);
const cliTokenPath = join(runtime, "cli.token");
const tokenStat = statOrUndefined(cliTokenPath);
const socketPath = daemonSocketPath();
const configuredPort = Number(env.PI2_PORT ?? DEFAULT_PORT) || DEFAULT_PORT;
let daemon: DoctorContext["daemon"];
if (options.daemonInfo !== undefined) {
try {
const info = await options.daemonInfo();
daemon =
"error" in info
? { reachable: false, error: info.error }
: { reachable: true, port: info.port, protocolVersion: info.protocolVersion };
} catch (error) {
daemon = { reachable: false, error: error instanceof Error ? error.message : String(error) };
}
} else {
daemon = { reachable: false, error: "no daemon reachable (is pi2d running?)" };
}
const serviceManager: DoctorContext["serviceManager"] =
platform === "darwin"
? {
name: "launchd",
available: (options.which ?? ((name: string) => whichSync(name, env)))("launchctl") !== undefined,
}
: { name: "systemd", available: (options.which ?? ((name: string) => whichSync(name, env)))("systemctl") !== undefined };
let linger: DoctorContext["linger"] = { checked: false };
if (platform === "linux") {
const result = await run("loginctl", ["show-user", String(uid), "-p", "Linger"]);
if (result.ok) {
const value = /Linger=(\w+)/.exec(result.stdout)?.[1];
linger = {
checked: true,
enabled: value === "yes",
detail: `Linger=${value ?? "unknown"}`,
};
} else {
linger = { checked: true, enabled: undefined, detail: "loginctl unavailable" };
}
}
return {
platform,
nodeVersion: process.version,
nvim,
pi,
plugin: { dir: pluginDir, bridgeFound },
runtime: { path: runtime, exists: runtimeStat.exists, mode: runtimeStat.mode },
cliToken: { path: cliTokenPath, exists: tokenStat.exists, mode: tokenStat.mode },
socket: { path: socketPath, exists: existsSync(socketPath) },
daemon,
port: { configured: daemon.port ?? configuredPort, bound: daemon.reachable },
serviceManager,
linger,
webDist: { path: env.PI2_STATIC_DIR?.trim() || defaultWebDist(), exists: existsSync(env.PI2_STATIC_DIR?.trim() || defaultWebDist()) },
};
}
/** Full run against the real machine (with optional injectable overrides). */
export async function diagnose(options: DoctorOptions = {}): Promise<DoctorReport> {
const ctx = await collectContext(options);
return runDoctor(defaultProbes(ctx));
}
+63
View File
@@ -0,0 +1,63 @@
/**
* Listening with a bounded port retry.
*
* `pi2d` uses the default port 7676; when another process already owns it the
* daemon walks `+1 … +9` instead of failing to start (the browser UI and the
* `pi2` CLI both read the actual port from `runtime/daemon.json`, so a bump is
* invisible to users). An explicitly configured port is never re-mapped: a
* conflict there is a real error.
*/
import type { Config } from "../config.js";
import { startServer, type ServerDeps, type StartedServer } from "../daemon/server.js";
export interface ListenOptions {
/** Extra port attempts after the first failure (0 = no retry). */
retries?: number;
onRetry?: (info: { from: number; to: number; error: Error }) => void;
}
function errorCode(error: unknown): string | undefined {
const code = (error as NodeJS.ErrnoException | undefined)?.code;
return typeof code === "string" ? code : undefined;
}
/** `EADDRINUSE` on either the HTTP server or an earlier await. */
export function isAddressInUse(error: unknown): boolean {
return errorCode(error) === "EADDRINUSE";
}
/**
* Rewrite the derived CORS origins when the effective port changes, mirroring
* what `startServer` does for an ephemeral (`:0`) bind.
*/
export function withPort(config: Config, port: number): Config {
if (port === config.port) return config;
return {
...config,
port,
corsOrigins: config.corsOrigins.map((origin) =>
origin.endsWith(`:${config.port}`) ? `${origin.slice(0, -String(config.port).length)}${port}` : origin,
),
};
}
export async function listenWithRetry(
config: Config,
deps: ServerDeps,
options: ListenOptions = {},
): Promise<StartedServer> {
const retries = config.port === 0 ? 0 : Math.max(0, options.retries ?? 0);
let port = config.port;
for (let attempt = 0; ; attempt += 1) {
try {
return await startServer(withPort(config, port), deps);
} catch (error) {
if (!isAddressInUse(error) || attempt >= retries) throw error;
if (port >= 65535) throw error;
const next = port + 1;
options.onRetry?.({ from: port, to: next, error: error instanceof Error ? error : new Error(String(error)) });
port = next;
}
}
}
+249
View File
@@ -0,0 +1,249 @@
/**
* Daemon singleton lock (`<runtime>/daemon.lock`) and discovery file
* (`<runtime>/daemon.json`).
*
* Both files carry the same payload:
*
* ```jsonc
* {"pid":1234,"bootId":"…","port":7676,"daemonId":"d-…","startedAt":1733,"protocolVersion":1}
* ```
*
* The lock is created with `wx` (atomic: only one daemon wins) and is
* considered **stale** when the pid is gone or the recorded boot id differs
* from the current one (pid reuse after a reboot). `--force` ignores a live
* lock. `daemon.json` is written after `listen()` so other tools can find the
* actual port without parsing arguments.
*/
import { execFileSync } from "node:child_process";
import { existsSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
import { randomBytes } from "node:crypto";
import { dirname, join } from "node:path";
import { daemonLockPath, ensureDir, runtimeDir } from "../core/paths.js";
export const LOCK_FILE = "daemon.lock";
export const DAEMON_JSON_FILE = "daemon.json";
export interface DaemonLock {
pid: number;
bootId: string;
port: number;
daemonId: string;
startedAt: number;
protocolVersion: number;
}
export type LockErrorCode = "E_LOCKED";
export class LockError extends Error {
readonly code: LockErrorCode;
readonly holder: DaemonLock | undefined;
constructor(code: LockErrorCode, message: string, holder?: DaemonLock) {
super(message);
this.name = "LockError";
this.code = code;
this.holder = holder;
}
}
export const defaultLockPath = (): string => join(runtimeDir(), LOCK_FILE);
export const defaultDaemonJsonPath = (): string => join(runtimeDir(), DAEMON_JSON_FILE);
/** Linux boot id; on macOS the boottime; otherwise a stable placeholder. */
export function readBootId(): string {
try {
const value = readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
if (value !== "") return value;
} catch {
// not Linux
}
if (process.platform === "darwin") {
try {
const value = execFileSync("sysctl", ["-n", "kern.boottime"], { encoding: "utf8" }).trim();
if (value !== "") return value;
} catch {
// sysctl missing
}
}
return "unknown";
}
export function isPidAlive(pid: number): boolean {
if (!Number.isInteger(pid) || pid <= 0) return false;
try {
process.kill(pid, 0);
return true;
} catch (error) {
// EPERM means the process exists but belongs to someone else.
return (error as NodeJS.ErrnoException).code === "EPERM";
}
}
function isLock(value: unknown): value is DaemonLock {
if (typeof value !== "object" || value === null) return false;
const candidate = value as Partial<DaemonLock>;
return (
typeof candidate.pid === "number" &&
Number.isInteger(candidate.pid) &&
candidate.pid > 0 &&
typeof candidate.bootId === "string" &&
typeof candidate.port === "number" &&
typeof candidate.daemonId === "string" &&
candidate.daemonId !== "" &&
typeof candidate.startedAt === "number" &&
typeof candidate.protocolVersion === "number"
);
}
/** Parse a lock/daemon.json file; `undefined` when absent or malformed. */
export function parseDaemonFile(raw: string): DaemonLock | undefined {
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch {
return undefined;
}
return isLock(parsed) ? parsed : undefined;
}
export function readLockFile(path: string = defaultLockPath()): DaemonLock | undefined {
if (!existsSync(path)) return undefined;
try {
return parseDaemonFile(readFileSync(path, "utf8"));
} catch {
return undefined;
}
}
export function readDaemonJson(path: string = defaultDaemonJsonPath()): DaemonLock | undefined {
return readLockFile(path);
}
export interface StalenessOptions {
isPidAlive?: (pid: number) => boolean;
bootId?: () => string;
}
export interface Staleness {
live: boolean;
reason: "alive" | "no-pid" | "boot-changed";
}
/** A lock is live only when the pid still exists *and* we are on the same boot. */
export function assessLock(lock: DaemonLock, options: StalenessOptions = {}): Staleness {
const alive = (options.isPidAlive ?? isPidAlive)(lock.pid);
if (!alive) return { live: false, reason: "no-pid" };
const bootId = (options.bootId ?? readBootId)();
if (bootId !== "unknown" && lock.bootId !== "unknown" && bootId !== lock.bootId) {
return { live: false, reason: "boot-changed" };
}
return { live: true, reason: "alive" };
}
function writeAtomic(path: string, payload: DaemonLock, mode = 0o600): void {
ensureDir(dirname(path));
const temporary = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
writeFileSync(temporary, `${JSON.stringify(payload, null, 2)}\n`, { mode });
renameSync(temporary, path);
}
export interface AcquireLockOptions {
lockPath?: string;
force?: boolean;
/** `pid` defaults to the current process. */
payload: Omit<DaemonLock, "pid" | "bootId"> & { pid?: number; bootId?: string };
isPidAlive?: (pid: number) => boolean;
bootId?: () => string;
}
export interface DaemonLockHandle {
readonly path: string;
readonly lock: DaemonLock;
/** Rewrite the lock in place (e.g. once the real port is known). */
update(patch: Partial<DaemonLock>): DaemonLock;
/** Remove the lock (and `daemon.json`) when we still own them. */
release(): void;
}
export function acquireLock(options: AcquireLockOptions): DaemonLockHandle {
const path = options.lockPath ?? daemonLockPath();
ensureDir(dirname(path));
const bootId = options.payload.bootId ?? (options.bootId ?? readBootId)();
const candidate: DaemonLock = {
...options.payload,
pid: options.payload.pid ?? process.pid,
bootId,
};
for (let attempt = 0; attempt < 2; attempt += 1) {
try {
writeFileSync(path, `${JSON.stringify(candidate, null, 2)}\n`, { flag: "wx", mode: 0o600 });
return makeHandle(path, candidate);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
}
const holder = readLockFile(path);
if (holder !== undefined) {
const staleness = assessLock(holder, {
...(options.isPidAlive === undefined ? {} : { isPidAlive: options.isPidAlive }),
bootId: () => bootId,
});
if (staleness.live && options.force !== true) {
throw new LockError(
"E_LOCKED",
`another pi2d is running (pid ${holder.pid}, port ${holder.port}); use --force to override`,
holder,
);
}
}
// Stale, forced, or unreadable (a half-written lock from a crash).
try {
unlinkSync(path);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
}
}
throw new LockError("E_LOCKED", `could not acquire ${path}: another pi2d keeps re-creating it`);
}
function makeHandle(path: string, initial: DaemonLock): DaemonLockHandle {
let current = initial;
return {
path,
get lock(): DaemonLock {
return current;
},
update(patch: Partial<DaemonLock>): DaemonLock {
current = { ...current, ...patch };
writeAtomic(path, current);
return current;
},
release(): void {
const onDisk = readLockFile(path);
if (onDisk === undefined || (onDisk.pid === current.pid && onDisk.daemonId === current.daemonId)) {
try {
unlinkSync(path);
} catch {
// already gone
}
}
// A stale daemon.json would point tools at a dead port.
const daemonJsonPath = join(dirname(path), DAEMON_JSON_FILE);
const discovery = readLockFile(daemonJsonPath);
if (discovery !== undefined && discovery.daemonId === current.daemonId) {
try {
unlinkSync(daemonJsonPath);
} catch {
// already gone
}
}
},
};
}
export function writeDaemonJson(payload: DaemonLock, path: string = defaultDaemonJsonPath()): string {
writeAtomic(path, payload);
return path;
}
+82
View File
@@ -0,0 +1,82 @@
/**
* Console logger for the CLI entry points.
*
* `pi2d` prints exactly one machine-readable line on stdout (`pi2d listening
* on …`); every log record therefore goes to stderr in JSONL so it can be
* piped into a log file or a systemd journal without corrupting stdout.
*/
import type { Logger, LogLevel } from "../core/interfaces.js";
const LEVELS: Record<LogLevel, number> = { debug: 10, info: 20, warn: 30, error: 40 };
export interface ConsoleLoggerOptions {
level?: LogLevel | "silent";
/** Defaults to `process.stderr`. */
write?: (line: string) => void;
now?: () => number;
}
export class ConsoleLogger implements Logger {
private readonly threshold: number;
private readonly write: (line: string) => void;
private readonly now: () => number;
private readonly fields: Record<string, unknown>;
constructor(options: ConsoleLoggerOptions = {}, fields: Record<string, unknown> = {}) {
const level = options.level ?? "info";
this.threshold = level === "silent" ? Number.POSITIVE_INFINITY : LEVELS[level];
this.write = options.write ?? ((line) => process.stderr.write(`${line}\n`));
this.now = options.now ?? Date.now;
this.fields = fields;
}
debug(msg: string, fields?: Record<string, unknown>): void {
this.log("debug", msg, fields);
}
info(msg: string, fields?: Record<string, unknown>): void {
this.log("info", msg, fields);
}
warn(msg: string, fields?: Record<string, unknown>): void {
this.log("warn", msg, fields);
}
error(msg: string, fields?: Record<string, unknown>): void {
this.log("error", msg, fields);
}
child(fields: Record<string, unknown>): Logger {
return new ConsoleLogger(
{ level: this.threshold === Number.POSITIVE_INFINITY ? "silent" : levelFor(this.threshold), now: this.now },
{ ...this.fields, ...fields },
);
}
private log(level: LogLevel, msg: string, fields?: Record<string, unknown>): void {
if (LEVELS[level] < this.threshold) return;
try {
this.write(JSON.stringify({ ts: this.now(), level, msg, ...this.fields, ...(fields ?? {}) }));
} catch {
// A non-serialisable field must never take the daemon down.
this.write(JSON.stringify({ ts: this.now(), level, msg }));
}
}
}
function levelFor(threshold: number): LogLevel {
if (threshold <= LEVELS.debug) return "debug";
if (threshold <= LEVELS.info) return "info";
if (threshold <= LEVELS.warn) return "warn";
return "error";
}
export function createLogger(level?: LogLevel | "silent"): ConsoleLogger {
const envLevel = process.env.PI2_LOG_LEVEL?.trim().toLowerCase();
const resolved = level ?? (isLogLevel(envLevel) ? envLevel : "info");
return new ConsoleLogger({ level: resolved });
}
function isLogLevel(value: string | undefined): value is LogLevel | "silent" {
return value === "debug" || value === "info" || value === "warn" || value === "error" || value === "silent";
}
+591
View File
@@ -0,0 +1,591 @@
#!/usr/bin/env node
/**
* `pi2` — the user-facing CLI.
*
* pi2 attach [path] attach nvim to the workspace instance (or open nvim)
* pi2 status [--json] daemon, instances, resources, health
* pi2 doctor [--json] environment checks
* pi2 pairing create a pairing code for another device
* pi2 install-service render/install a systemd user unit or LaunchAgent
* pi2 uninstall-service remove it again
*
* Everything is discovered from the runtime dir: `daemon.json` carries the
* bound port, `cli.token` the local admin token (see docs/deployment.md).
*/
import { mkdirSync, rmSync, writeFileSync } from "node:fs";
import { spawnSync } from "node:child_process";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { platform as osPlatform } from "node:os";
import { runtimeDir } from "../core/paths.js";
import type { InstanceResourcesSnapshot } from "../core/interfaces.js";
import type { WorkspaceInfo } from "../protocol/types.js";
import { PROTOCOL_VERSION } from "../protocol/types.js";
import { readDaemonJson, type DaemonLock } from "./lock.js";
import { cliTokenPath, readCliToken } from "./token.js";
import {
boolFlag,
errorMessage,
formatBytes,
formatTable,
packageVersion,
parseArgs,
realpathOrSelf,
UsageError,
} from "./util.js";
import {
defaultServicePaths,
renderService,
serviceDir,
type RenderedService,
type ServicePaths,
type ServicePlatform,
} from "./service.js";
import { diagnose, formatReport, reportToJson, type DoctorReport } from "./doctor.js";
export const USAGE = `pi2 — pi2 client
Usage:
pi2 attach [path] attach nvim to the workspace instance, else open nvim
pi2 status [--json] daemon info, instances, resources, health
pi2 doctor [--json] environment checks
pi2 pairing create a pairing code (URL + code + QR payload)
pi2 install-service [--dry-run|--write] systemd user unit / LaunchAgent
pi2 uninstall-service [--dry-run|--write] remove the unit
pi2 --version | --help
The daemon endpoint comes from $PI2_RUNTIME_DIR/daemon.json (port) and
$PI2_RUNTIME_DIR/cli.token (local admin token). Start it with \`pi2d\`.
See docs/deployment.md.`;
/** A user-facing failure: printed as-is, exits with `code`. */
export class CliError extends Error {
readonly code: number;
constructor(message: string, code = 1) {
super(message);
this.name = "CliError";
this.code = code;
}
}
export interface Endpoint {
baseUrl: string;
token: string;
daemon: DaemonLock;
}
export interface DaemonClient {
readonly baseUrl: string;
readonly token: string;
readonly daemon: DaemonLock;
get<T>(path: string): Promise<T>;
post(path: string, body: unknown): Promise<{ status: number; body: Record<string, unknown> }>;
}
/** Read `daemon.json` + `cli.token`; throws a helpful `CliError` when absent. */
export function resolveEndpoint(runtime: string = runtimeDir()): Endpoint {
const daemon = readDaemonJson(resolve(runtime, "daemon.json"));
if (daemon === undefined) {
throw new CliError(
`no running pi2d (${resolve(runtime, "daemon.json")} missing). Start it with \`pi2d --foreground\`.`,
);
}
const token = readCliToken(cliTokenPath(runtime));
if (token === undefined) {
throw new CliError(`missing CLI token (${cliTokenPath(runtime)}). Restart \`pi2d\`.`);
}
return { baseUrl: `http://127.0.0.1:${daemon.port}`, token, daemon };
}
export interface ClientOptions {
endpoint?: Endpoint;
runtime?: string;
timeoutMs?: number;
fetchImpl?: typeof fetch;
}
export function createClient(options: ClientOptions = {}): DaemonClient {
const endpoint = options.endpoint ?? resolveEndpoint(options.runtime);
const fetchImpl = options.fetchImpl ?? fetch;
const timeoutMs = options.timeoutMs ?? 5_000;
async function request(path: string, init: RequestInit): Promise<Response> {
const url = `${endpoint.baseUrl}${path}`;
try {
return await fetchImpl(url, {
...init,
headers: {
authorization: `Bearer ${endpoint.token}`,
"content-type": "application/json",
...(init.headers ?? {}),
},
signal: AbortSignal.timeout(timeoutMs),
});
} catch (error) {
throw new CliError(`cannot reach pi2d at ${endpoint.baseUrl}: ${errorMessage(error)}`);
}
}
return {
baseUrl: endpoint.baseUrl,
token: endpoint.token,
daemon: endpoint.daemon,
async get<T>(path: string): Promise<T> {
const response = await request(path, { method: "GET" });
if (!response.ok) throw new CliError(`${path} failed: HTTP ${response.status} ${await safeText(response)}`);
return (await response.json()) as T;
},
async post(path: string, body: unknown): Promise<{ status: number; body: Record<string, unknown> }> {
const response = await request(path, { method: "POST", body: JSON.stringify(body) });
const text = await safeText(response);
let parsed: Record<string, unknown> = {};
if (text.trim() !== "") {
try {
parsed = JSON.parse(text) as Record<string, unknown>;
} catch {
parsed = { raw: text };
}
}
if (!response.ok) {
const code = typeof parsed.code === "string" ? parsed.code : `HTTP ${response.status}`;
const message = typeof parsed.message === "string" ? parsed.message : text;
throw new CliError(`${path} failed: ${code} ${message}`.trim());
}
return { status: response.status, body: parsed };
},
};
}
async function safeText(response: Response): Promise<string> {
try {
return (await response.text()).trim();
} catch {
return "";
}
}
// ---------------------------------------------------------------------------
// attach
// ---------------------------------------------------------------------------
export interface ExecOptions {
cwd: string;
}
export interface AttachOptions {
/** Directory to attach (defaults to `cwd`). */
path?: string;
cwd?: string;
isTTY?: boolean;
exec?: (command: string, args: string[], options: ExecOptions) => void;
print?: (line: string) => void;
warn?: (line: string) => void;
client?: () => DaemonClient;
}
/** Replace this process with nvim (stdio inherited). */
export function execNvim(command: string, args: string[], options: ExecOptions): void {
const result = spawnSync(command, args, { stdio: "inherit", cwd: options.cwd });
if (result.error !== undefined && result.error !== null) {
throw new CliError(`could not exec ${command}: ${result.error.message}`);
}
process.exit(result.status ?? 0);
}
/**
* `pi2 attach`: if the workspace already has a managed instance with a UI
* socket, attach to it with `--remote-ui`; otherwise start a plain `nvim`.
* Never spawns a headless instance — the plugin registers itself.
*/
export async function runAttach(options: AttachOptions = {}): Promise<number> {
const cwd = options.cwd ?? process.cwd();
const target = realpathOrSelf(options.path === undefined ? cwd : resolve(cwd, options.path));
const exec = options.exec ?? execNvim;
const print = options.print ?? ((line: string) => process.stdout.write(`${line}\n`));
const warn = options.warn ?? ((line: string) => process.stderr.write(`${line}\n`));
const isTTY = options.isTTY ?? process.stdout.isTTY === true;
const openPlainNvim = (): number => {
exec("nvim", [], { cwd: target });
return 0;
};
const factory = options.client ?? (() => createClient());
let client: DaemonClient;
try {
client = factory();
} catch (error) {
// No daemon: nvim still works, the plugin just has nothing to dial.
warn(`pi2: ${errorMessage(error)}`);
return openPlainNvim();
}
let workspaces: WorkspaceInfo[];
try {
workspaces = await client.get<WorkspaceInfo[]>("/api/v1/workspaces");
} catch (error) {
warn(`pi2: ${errorMessage(error)}`);
return openPlainNvim();
}
const workspace = workspaces.find((candidate) => realpathOrSelf(candidate.cwd) === target);
const instance = workspace?.instance ?? null;
if (instance != null && instance.listenAddr !== null && instance.status !== "stopped" && instance.status !== "stopping") {
const args = ["--server", instance.listenAddr, "--remote-ui"];
if (isTTY) {
exec("nvim", args, { cwd: target });
} else {
print(`nvim ${args.join(" ")}`);
}
return 0;
}
return openPlainNvim();
}
// ---------------------------------------------------------------------------
// status
// ---------------------------------------------------------------------------
interface InfoBody {
v: number;
daemonId: string;
machineId: string;
platform: string;
capabilities: string[];
limits: { maxBodyBytes: number; maxFrameBytes: number; maxConnections: number };
}
interface HealthBody {
ok: boolean;
items: { name: string; ok: boolean; detail: string }[];
}
export interface StatusOptions {
json?: boolean;
client: DaemonClient;
print?: (line: string) => void;
}
export async function runStatus(options: StatusOptions): Promise<number> {
const print = options.print ?? ((line: string) => process.stdout.write(`${line}\n`));
const client = options.client;
const [info, workspaces, resources, health] = await Promise.all([
client.get<InfoBody>("/api/v1/info"),
client.get<WorkspaceInfo[]>("/api/v1/workspaces"),
client.get<InstanceResourcesSnapshot>("/api/v1/resources"),
client.get<HealthBody>("/api/v1/health"),
]);
const instances = workspaces
.filter((workspace) => workspace.instance != null)
.map((workspace) => ({
workspaceId: workspace.workspaceId,
name: workspace.alias ?? workspace.name,
cwd: workspace.cwd,
status: workspace.instance?.status ?? "unknown",
hasUI: workspace.instance?.hasUI ?? false,
listenAddr: workspace.instance?.listenAddr ?? null,
nvimPid: workspace.instance?.nvimPid ?? null,
sessions: workspace.liveCount,
}));
if (options.json === true) {
print(
JSON.stringify(
{
daemon: { url: client.baseUrl, ...info },
instances,
resources,
health,
},
null,
2,
),
);
return health.ok ? 0 : 1;
}
print(`daemon ${client.baseUrl} id ${info.daemonId} v${info.v} ${info.platform}`);
print(`machine ${info.machineId} capabilities ${info.capabilities.join(",")}`);
print("");
if (instances.length === 0) {
print("instances (none — open nvim in a workspace to register one)");
} else {
print(
formatTable(
["workspace", "cwd", "status", "ui", "sessions", "pid"],
instances.map((instance) => [
instance.name,
instance.cwd,
instance.status,
instance.hasUI ? "yes" : "no",
String(instance.sessions),
instance.nvimPid === null ? "-" : String(instance.nvimPid),
]),
),
);
}
print("");
const rss = `${formatBytes(resources.totalRssBytes)} of ${formatBytes(resources.physicalMemoryBytes)}`;
print(`resources ${resources.instances.length} instance(s), rss ${rss}${resources.warn ? ` WARN: ${resources.reason ?? ""}` : ""}`);
print(
`health ${health.ok ? "ok" : "degraded"} ${health.items
.map((item) => `${item.name}=${item.ok ? "ok" : "FAIL"}`)
.join(" ")}`,
);
return health.ok ? 0 : 1;
}
// ---------------------------------------------------------------------------
// pairing
// ---------------------------------------------------------------------------
export interface PairingOptions {
client: DaemonClient;
print?: (line: string) => void;
}
export async function runPairing(options: PairingOptions): Promise<number> {
const print = options.print ?? ((line: string) => process.stdout.write(`${line}\n`));
const result = await options.client.post("/api/v1/pair", {});
const code = typeof result.body.code === "string" ? result.body.code : undefined;
if (code === undefined) throw new CliError("pairing failed: daemon returned no code");
const expiresAt = typeof result.body.expiresAt === "number" ? result.body.expiresAt : undefined;
const nonce = typeof result.body.nonce === "string" ? result.body.nonce : undefined;
// Rebuild the URL from the *actual* base URL: the daemon's own `url` field is
// derived from the configured port, which is stale after a retry or `--port 0`.
const url = `${options.client.baseUrl}/pair/${code}`;
const payload = JSON.stringify({ v: PROTOCOL_VERSION, code, url, ...(expiresAt === undefined ? {} : { expiresAt }), ...(nonce === undefined ? {} : { nonce }) });
print(`url ${url}`);
print(`code ${code}`);
if (expiresAt !== undefined) {
print(`expires ${new Date(expiresAt).toISOString()} (${Math.max(0, Math.round((expiresAt - Date.now()) / 1000))}s)`);
}
print(`qr ${payload}`);
return 0;
}
// ---------------------------------------------------------------------------
// doctor
// ---------------------------------------------------------------------------
/** `pi2 doctor`: real probes, plus the live daemon when one is running. */
export async function runDoctorCommand(
options: { runtime?: string; client?: () => DaemonClient } = {},
): Promise<DoctorReport> {
const runtime = options.runtime;
return diagnose({
...(runtime === undefined ? {} : { runtime }),
daemonInfo: async () => {
try {
const client = options.client?.() ?? createClient({ ...(runtime === undefined ? {} : { runtime }) });
const info = await client.get<{ v: number }>("/api/v1/info");
return { port: client.daemon.port, protocolVersion: info.v };
} catch (error) {
return { error: error instanceof CliError ? error.message : errorMessage(error) };
}
},
});
}
// ---------------------------------------------------------------------------
// install-service / uninstall-service
// ---------------------------------------------------------------------------
export interface ServiceCommandOptions {
platform: ServicePlatform;
paths: ServicePaths;
write: boolean;
print?: (line: string) => void;
writeFile?: (path: string, content: string) => void;
removeFile?: (path: string) => void;
}
function defaultWriteFile(path: string, content: string): void {
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, content, { mode: 0o644 });
}
function defaultRemoveFile(path: string): void {
rmSync(path, { force: true });
}
export function runInstallService(options: ServiceCommandOptions): number {
const print = options.print ?? ((line: string) => process.stdout.write(`${line}\n`));
const service = renderService(options.platform, options.paths);
if (!options.write) {
print(service.content);
print(`# dry-run: would write ${service.path} (mode 0644)`);
print(`# then run:\n${service.commands.map((command) => `# ${command}`).join("\n")}`);
return 0;
}
(options.writeFile ?? defaultWriteFile)(service.path, service.content);
print(`wrote ${service.path} (mode 0644)`);
print("enable it with:");
for (const command of service.commands) print(` ${command}`);
return 0;
}
export function runUninstallService(options: ServiceCommandOptions): number {
const print = options.print ?? ((line: string) => process.stdout.write(`${line}\n`));
const service: RenderedService = renderService(options.platform, options.paths);
if (!options.write) {
print(`# dry-run: would remove ${service.path}`);
print(`# then run:\n${service.removeCommands.map((command) => `# ${command}`).join("\n")}`);
return 0;
}
(options.removeFile ?? defaultRemoveFile)(service.path);
print(`removed ${service.path}`);
print("finish with:");
for (const command of service.removeCommands) print(` ${command}`);
return 0;
}
// ---------------------------------------------------------------------------
// main
// ---------------------------------------------------------------------------
export interface Pi2Options {
out?: (line: string) => void;
err?: (line: string) => void;
client?: () => DaemonClient;
exec?: (command: string, args: string[], options: ExecOptions) => void;
cwd?: string;
isTTY?: boolean;
doctor?: () => Promise<DoctorReport>;
servicePaths?: ServicePaths;
platform?: ServicePlatform;
writeFile?: (path: string, content: string) => void;
removeFile?: (path: string) => void;
runtime?: string;
}
export async function main(argv: readonly string[], options: Pi2Options = {}): Promise<number> {
const out = options.out ?? ((line: string) => process.stdout.write(`${line}\n`));
const err = options.err ?? ((line: string) => process.stderr.write(`${line}\n`));
const [command, ...rest] = argv;
if (command === undefined || command === "help" || command === "--help" || command === "-h") {
out(USAGE);
return 0;
}
if (command === "--version" || command === "-V" || command === "version") {
out(`pi2 ${packageVersion()}`);
return 0;
}
try {
switch (command) {
case "attach": {
const parsed = parseArgs(rest, { booleans: ["--help"], aliases: { "-h": "--help" } });
if (boolFlag(parsed.flags, "--help")) {
out(USAGE);
return 0;
}
if (parsed.positionals.length > 1) throw new UsageError("attach takes at most one path");
return await runAttach({
...(parsed.positionals[0] === undefined ? {} : { path: parsed.positionals[0] }),
...(options.cwd === undefined ? {} : { cwd: options.cwd }),
...(options.isTTY === undefined ? {} : { isTTY: options.isTTY }),
...(options.exec === undefined ? {} : { exec: options.exec }),
...(options.client === undefined ? {} : { client: options.client }),
print: out,
warn: err,
});
}
case "status": {
const parsed = parseArgs(rest, { booleans: ["--json", "--help"], aliases: { "-h": "--help" } });
if (boolFlag(parsed.flags, "--help")) {
out(USAGE);
return 0;
}
const client = (options.client ?? (() => createClient({ ...(options.runtime === undefined ? {} : { runtime: options.runtime }) })))();
return await runStatus({ client, json: boolFlag(parsed.flags, "--json"), print: out });
}
case "doctor": {
const parsed = parseArgs(rest, { booleans: ["--json", "--help"], aliases: { "-h": "--help" } });
if (boolFlag(parsed.flags, "--help")) {
out(USAGE);
return 0;
}
const report = await (options.doctor ?? (() => runDoctorCommand(options)))();
out(boolFlag(parsed.flags, "--json") ? reportToJson(report) : formatReport(report));
return report.ok ? 0 : 1;
}
case "pairing":
case "pair": {
parseArgs(rest, { booleans: ["--help"], aliases: { "-h": "--help" } });
const client = (options.client ?? (() => createClient({ ...(options.runtime === undefined ? {} : { runtime: options.runtime }) })))();
return await runPairing({ client, print: out });
}
case "install-service":
case "uninstall-service": {
const parsed = parseArgs(rest, { booleans: ["--dry-run", "--write", "--help"], aliases: { "-h": "--help" } });
if (boolFlag(parsed.flags, "--help")) {
out(USAGE);
return 0;
}
const platform = options.platform ?? (osPlatform() === "darwin" ? "darwin" : "linux");
const paths = options.servicePaths ?? defaultServicePaths();
const serviceOptions: ServiceCommandOptions = {
platform,
paths,
write: boolFlag(parsed.flags, "--write"),
print: out,
...(options.writeFile === undefined ? {} : { writeFile: options.writeFile }),
...(options.removeFile === undefined ? {} : { removeFile: options.removeFile }),
};
return command === "install-service" ? runInstallService(serviceOptions) : runUninstallService(serviceOptions);
}
default:
err(`pi2: unknown command "${command}"`);
err(USAGE);
return 2;
}
} catch (error) {
if (error instanceof UsageError) {
err(`pi2: ${error.message}`);
err(error.usage ?? USAGE);
return 2;
}
if (error instanceof CliError) {
err(`pi2: ${error.message}`);
return error.code;
}
err(`pi2: ${errorMessage(error)}`);
return 1;
}
}
function isDirectRun(): boolean {
const entry = process.argv[1];
if (entry === undefined) return false;
try {
return realpathOrSelf(entry) === realpathOrSelf(fileURLToPath(import.meta.url));
} catch {
return false;
}
}
if (isDirectRun()) {
void main(process.argv.slice(2)).then(
(code) => {
if (code !== 0) process.exitCode = code;
},
(error: unknown) => {
process.stderr.write(`pi2: ${errorMessage(error)}\n`);
process.exitCode = 1;
},
);
}
/** Exposed so `service.test.ts` can check the same rendering the command uses. */
export { renderService, serviceDir };
+262
View File
@@ -0,0 +1,262 @@
#!/usr/bin/env node
/**
* `pi2d` — the pi2 daemon entry point.
*
* Responsibilities (and nothing else):
* 1. parse args / apply `--port|--host|--static-dir` to the config env
* 2. mint `<runtime>/cli.token` (32-byte hex, 0600) for local CLI access
* 3. take the singleton lock (`<runtime>/daemon.lock`, stale-aware, `--force`)
* 4. wire the real dependencies and listen (port 0 allowed, +1..+9 on a busy
* default port), then publish `<runtime>/daemon.json`
* 5. print exactly one line: `pi2d listening on http://host:port`
* 6. on SIGINT/SIGTERM close http + the plugin socket and release the lock —
* **without** stopping nvim instances (they reconnect on the next start)
*/
import { randomUUID } from "node:crypto";
import { fileURLToPath } from "node:url";
import { loadConfig, DEFAULT_PORT, type Config } from "../config.js";
import { ensureDir, runtimeDir } from "../core/paths.js";
import type { Logger } from "../core/interfaces.js";
import { PROTOCOL_VERSION } from "../protocol/types.js";
import { createLogger } from "./logger.js";
import { acquireLock, writeDaemonJson, type DaemonLockHandle } from "./lock.js";
import { cliTokenPath, writeCliToken } from "./token.js";
import {
boolFlag,
errorMessage,
packageVersion,
parseArgs,
realpathOrSelf,
stringFlag,
UsageError,
} from "./util.js";
import { wireDaemon, type WiredDaemon } from "./wiring.js";
/** Extra attempts when the *default* port is taken (7676 → 7677 … 7685). */
export const DEFAULT_PORT_RETRIES = 9;
export const USAGE = `pi2d — pi2 daemon
Usage: pi2d [options]
Options:
--port <n> TCP port (default ${DEFAULT_PORT}; 0 = ephemeral)
--host <addr> bind address (default 127.0.0.1)
--static-dir <p> built web UI (default <repo>/web/dist)
--force override a live daemon.lock
--foreground stay in the foreground (default; kept for unit files)
--version print the version and exit
--help print this help and exit
Environment:
PI2_PORT, PI2_HOST, PI2_STATIC_DIR, PI2_ORIGINS, PI2_RUNTIME_DIR,
PI2_DATA_DIR, PI2_STATE_DIR, PI2_LOG_LEVEL, PI2_WORKSPACE_ROOTS
Runtime files ($PI2_RUNTIME_DIR):
d.sock plugin unix socket (nvim → daemon)
d.sock.token plugin handshake token
daemon.lock singleton lock (pid + bootId)
daemon.json discovery file for the pi2 CLI / tools
cli.token local admin token for the pi2 CLI
See docs/deployment.md.`;
export interface DaemonArgs {
port?: number;
host?: string;
staticDir?: string;
force: boolean;
foreground: boolean;
help: boolean;
version: boolean;
}
export function parseDaemonArgs(argv: readonly string[]): DaemonArgs {
const { flags, positionals } = parseArgs(argv, {
values: ["--port", "--host", "--static-dir"],
booleans: ["--force", "--foreground", "--help", "--version"],
aliases: { "-h": "--help", "-V": "--version", "-p": "--port", "-f": "--force" },
});
if (positionals.length > 0) {
throw new UsageError(`unexpected argument ${positionals[0]}`, USAGE);
}
const args: DaemonArgs = {
force: boolFlag(flags, "--force"),
foreground: boolFlag(flags, "--foreground"),
help: boolFlag(flags, "--help"),
version: boolFlag(flags, "--version"),
};
const port = stringFlag(flags, "--port");
if (port !== undefined) {
if (!/^\d+$/.test(port.trim())) throw new UsageError(`--port must be an integer, got "${port}"`, USAGE);
const value = Number(port);
if (!Number.isSafeInteger(value) || value < 0 || value > 65535) {
throw new UsageError(`--port must be between 0 and 65535, got "${port}"`, USAGE);
}
args.port = value;
}
const host = stringFlag(flags, "--host");
if (host !== undefined) args.host = host;
const staticDir = stringFlag(flags, "--static-dir");
if (staticDir !== undefined) args.staticDir = staticDir;
return args;
}
export interface CliIo {
out(line: string): void;
err(line: string): void;
}
function defaultIo(): CliIo {
return {
out: (line) => process.stdout.write(`${line}\n`),
err: (line) => process.stderr.write(`${line}\n`),
};
}
export interface RunDaemonOptions {
out?: (line: string) => void;
err?: (line: string) => void;
logger?: Logger;
}
/**
* Start the daemon. Resolves `0` once the server is listening (the process then
* stays alive) and `1`/`2` on failure — the caller decides whether to exit.
*/
export async function main(argv: readonly string[], ioOptions: RunDaemonOptions = {}): Promise<number> {
const defaults = defaultIo();
const io: CliIo = { out: ioOptions.out ?? defaults.out, err: ioOptions.err ?? defaults.err };
const options = ioOptions;
let args: DaemonArgs;
try {
args = parseDaemonArgs(argv);
} catch (error) {
if (error instanceof UsageError) {
io.err(`pi2d: ${error.message}`);
io.err(error.usage ?? USAGE);
return 2;
}
throw error;
}
if (args.help) {
io.out(USAGE);
return 0;
}
if (args.version) {
io.out(`pi2d ${packageVersion()}`);
return 0;
}
// The daemon process is the single consumer of these values; child nvim
// instances then inherit a consistent environment.
if (args.port !== undefined) process.env.PI2_PORT = String(args.port);
if (args.host !== undefined) process.env.PI2_HOST = args.host;
if (args.staticDir !== undefined) process.env.PI2_STATIC_DIR = args.staticDir;
const portIsDefault = args.port === undefined && (process.env.PI2_PORT ?? "").trim() === "";
const logger = options.logger ?? createLogger();
let config: Config;
try {
config = loadConfig();
} catch (error) {
io.err(`pi2d: ${errorMessage(error)}`);
return 1;
}
let lock: DaemonLockHandle | undefined;
let wired: WiredDaemon | undefined;
let server: Awaited<ReturnType<WiredDaemon["start"]>> | undefined;
let stopping = false;
try {
const runtime = runtimeDir();
ensureDir(runtime, 0o700);
writeCliToken(cliTokenPath(runtime));
const daemonId = `d-${randomUUID()}`;
lock = acquireLock({
force: args.force,
payload: {
port: config.port,
daemonId,
startedAt: Date.now(),
protocolVersion: PROTOCOL_VERSION,
},
});
wired = await wireDaemon({ config, runtime, logger, daemonId });
server = await wired.start({
retries: portIsDefault ? DEFAULT_PORT_RETRIES : 0,
onRetry: (info) => logger.warn("port busy, trying next", { from: info.from, to: info.to }),
});
lock.update({ port: server.port });
writeDaemonJson(lock.lock);
// One machine-readable line; every log record goes to stderr.
io.out(`pi2d listening on ${server.url}`);
} catch (error) {
io.err(`pi2d: ${errorMessage(error)}`);
lock?.release();
if (wired !== undefined) await wired.close().catch(() => undefined);
return 1;
}
const shutdown = async (signal: string): Promise<void> => {
if (stopping) return;
stopping = true;
logger.info("shutting down", { signal });
try {
if (server !== undefined) await server.close();
} catch (error) {
logger.warn("http close failed", { error: errorMessage(error) });
}
try {
// Only the plugin socket: managed nvim instances must survive a
// daemon restart and reconnect on the next start (protocol §5).
await wired?.instanceManager.pluginServer.close();
} catch (error) {
logger.warn("plugin socket close failed", { error: errorMessage(error) });
}
lock?.release();
process.exit(0);
};
for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"] as const) {
process.once(signal, () => {
void shutdown(signal).catch((error: unknown) => {
io.err(`pi2d: shutdown failed: ${errorMessage(error)}`);
process.exit(1);
});
});
}
return 0;
}
function isDirectRun(): boolean {
const entry = process.argv[1];
if (entry === undefined) return false;
try {
return realpathOrSelf(entry) === realpathOrSelf(fileURLToPath(import.meta.url));
} catch {
return false;
}
}
if (isDirectRun()) {
void main(process.argv.slice(2)).then(
(code) => {
if (code !== 0) process.exitCode = code;
},
(error: unknown) => {
process.stderr.write(`pi2d: ${errorMessage(error)}\n`);
process.exitCode = 1;
},
);
}
+187
View File
@@ -0,0 +1,187 @@
/**
* Service file rendering for `pi2 install-service` / `uninstall-service`.
*
* Pure string generation: nothing here executes a command. `--dry-run` prints
* the rendered file, `--write` writes it (0644) and prints the enable/load
* commands for the user to run — the CLI never talks to systemd or launchd.
*/
import { fileURLToPath } from "node:url";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { stateDir } from "../core/paths.js";
export type ServicePlatform = "linux" | "darwin";
export interface ServicePaths {
/** Absolute node binary (`process.execPath`). */
nodePath: string;
/** Absolute path to `dist/cli/pi2d.js`. */
scriptPath: string;
/** Where logs go (plist StandardOut/ErrPath). */
stateDir: string;
/** Home dir; the unit file lives under it. */
homeDir: string;
/** `XDG_CONFIG_HOME` override for the systemd user dir. */
configHome?: string;
/** PATH the service should see (defaults to `process.env.PATH`). */
pathEnv?: string;
/** Extra `Environment=` entries (e.g. `{PI2_PORT: "7676"}`). */
env?: Record<string, string>;
}
export interface RenderedService {
/** `pi2d.service` on Linux, `com.pi2.pi2d.plist` on macOS. */
name: string;
/** Absolute install path. */
path: string;
content: string;
/** Commands the user must run (printed, never executed). */
commands: string[];
/** Commands that undo the install (printed on uninstall). */
removeCommands: string[];
}
export const SYSTEMD_UNIT_NAME = "pi2d.service";
export const LAUNCHD_LABEL = "com.pi2.pi2d";
export const LAUNCHD_PLIST_NAME = `${LAUNCHD_LABEL}.plist`;
/** `<repo>/dist/cli/pi2d.js`, resolved from either `src/cli/` or `dist/cli/`. */
export function defaultScriptPath(): string {
return fileURLToPath(new URL("../../dist/cli/pi2d.js", import.meta.url));
}
export function defaultServicePaths(overrides: Partial<ServicePaths> = {}): ServicePaths {
return {
nodePath: process.execPath,
scriptPath: defaultScriptPath(),
stateDir: stateDir(),
homeDir: homedir(),
...(process.env.XDG_CONFIG_HOME === undefined ? {} : { configHome: process.env.XDG_CONFIG_HOME }),
pathEnv: process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin",
...overrides,
};
}
export function systemdUserDir(paths: ServicePaths): string {
const configHome = paths.configHome ?? join(paths.homeDir, ".config");
return join(configHome, "systemd", "user");
}
export function launchAgentDir(paths: ServicePaths): string {
return join(paths.homeDir, "Library", "LaunchAgents");
}
function systemdQuote(value: string): string {
if (/[\s"'\\]/.test(value)) return `"${value.replace(/(["\\])/g, "\\$1")}"`;
return value;
}
function xmlEscape(value: string): string {
return value
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&apos;");
}
function environmentEntries(paths: ServicePaths): [string, string][] {
const entries: [string, string][] = [];
if (paths.pathEnv !== undefined && paths.pathEnv !== "") entries.push(["PATH", paths.pathEnv]);
for (const [key, value] of Object.entries(paths.env ?? {})) entries.push([key, value]);
return entries;
}
export function renderSystemdUnit(paths: ServicePaths): string {
const env = environmentEntries(paths).map(([key, value]) => `Environment=${key}=${systemdQuote(value)}`);
return [
"[Unit]",
"Description=pi2 daemon (pi2d)",
"After=network.target",
"",
"[Service]",
"Type=simple",
`ExecStart=${systemdQuote(paths.nodePath)} ${systemdQuote(paths.scriptPath)} --foreground`,
...env,
"Restart=on-failure",
"RestartSec=2",
"KillSignal=SIGTERM",
"TimeoutStopSec=15",
"",
"[Install]",
"WantedBy=default.target",
"",
].join("\n");
}
export function renderLaunchAgent(paths: ServicePaths): string {
const env = environmentEntries(paths);
const envBlock =
env.length === 0
? []
: [
" <key>EnvironmentVariables</key>",
" <dict>",
...env.flatMap(([key, value]) => [
` <key>${xmlEscape(key)}</key>`,
` <string>${xmlEscape(value)}</string>`,
]),
" </dict>",
];
return [
'<?xml version="1.0" encoding="UTF-8"?>',
'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
'<plist version="1.0">',
"<dict>",
` <key>Label</key>`,
` <string>${LAUNCHD_LABEL}</string>`,
" <key>ProgramArguments</key>",
" <array>",
` <string>${xmlEscape(paths.nodePath)}</string>`,
` <string>${xmlEscape(paths.scriptPath)}</string>`,
" <string>--foreground</string>",
" </array>",
...envBlock,
" <key>RunAtLoad</key>",
" <true/>",
" <key>KeepAlive</key>",
" <true/>",
" <key>StandardOutPath</key>",
` <string>${xmlEscape(join(paths.stateDir, "pi2d.log"))}</string>`,
" <key>StandardErrorPath</key>",
` <string>${xmlEscape(join(paths.stateDir, "pi2d.err.log"))}</string>`,
"</dict>",
"</plist>",
"",
].join("\n");
}
export function renderService(platform: ServicePlatform, paths: ServicePaths): RenderedService {
if (platform === "darwin") {
const target = join(launchAgentDir(paths), LAUNCHD_PLIST_NAME);
return {
name: LAUNCHD_PLIST_NAME,
path: target,
content: renderLaunchAgent(paths),
commands: [
`launchctl bootstrap gui/$(id -u) ${target}`,
`launchctl enable gui/$(id -u)/${LAUNCHD_LABEL}`,
`launchctl kickstart -k gui/$(id -u)/${LAUNCHD_LABEL}`,
],
removeCommands: [`launchctl bootout gui/$(id -u)/${LAUNCHD_LABEL}`, `rm -f ${target}`],
};
}
const target = join(systemdUserDir(paths), SYSTEMD_UNIT_NAME);
return {
name: SYSTEMD_UNIT_NAME,
path: target,
content: renderSystemdUnit(paths),
commands: ["systemctl --user daemon-reload", `systemctl --user enable --now ${SYSTEMD_UNIT_NAME}`],
removeCommands: [`systemctl --user disable --now ${SYSTEMD_UNIT_NAME}`, `rm -f ${target}`],
};
}
/** Directory that must exist before writing the file. */
export function serviceDir(service: RenderedService): string {
return dirname(service.path);
}
+54
View File
@@ -0,0 +1,54 @@
/**
* The local CLI token (`<runtime>/cli.token`).
*
* `pi2d` mints a fresh 32-byte hex token on every start and writes it 0600.
* `AuthStore` accepts it as the synthetic `local-cli` admin device, so every
* local `pi2*` command can talk to the daemon without pairing. The token is
* per-daemon-lifetime: restarting `pi2d` rotates it.
*/
import { randomBytes } from "node:crypto";
import { chmodSync, existsSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
import { join, dirname } from "node:path";
import { ensureDir, runtimeDir } from "../core/paths.js";
import { CLI_TOKEN_FILE } from "./wiring.js";
export const CLI_TOKEN_BYTES = 32;
export function cliTokenPath(runtime: string = runtimeDir()): string {
return join(runtime, CLI_TOKEN_FILE);
}
/** Mint a fresh token and write it atomically (mode 0600). */
export function writeCliToken(path: string = cliTokenPath()): string {
const token = randomBytes(CLI_TOKEN_BYTES).toString("hex");
ensureDir(dirname(path), 0o700);
const temporary = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
writeFileSync(temporary, `${token}\n`, { mode: 0o600 });
chmodSync(temporary, 0o600);
renameSync(temporary, path);
chmodSync(path, 0o600);
return token;
}
export function readCliToken(path: string = cliTokenPath()): string | undefined {
try {
const value = readFileSync(path, "utf8").trim();
return value === "" ? undefined : value;
} catch {
return undefined;
}
}
export interface TokenPerms {
exists: boolean;
mode: number | undefined;
}
export function tokenPerms(path: string = cliTokenPath()): TokenPerms {
if (!existsSync(path)) return { exists: false, mode: undefined };
try {
return { exists: true, mode: statSync(path).mode & 0o777 };
} catch {
return { exists: false, mode: undefined };
}
}
+151
View File
@@ -0,0 +1,151 @@
/** Small shared helpers for the `pi2` / `pi2d` command line front ends. */
import { readFileSync, realpathSync } from "node:fs";
import { fileURLToPath } from "node:url";
/** Bad arguments; the CLI prints the usage block and exits 2. */
export class UsageError extends Error {
readonly usage: string | undefined;
constructor(message: string, usage?: string) {
super(message);
this.name = "UsageError";
this.usage = usage;
}
}
export type FlagValue = string | boolean;
export interface FlagSpec {
/** Flags that take a value (`--port 7676` or `--port=7676`). */
values?: readonly string[];
/** Flags that do not (`--force`). */
booleans?: readonly string[];
/** Short aliases: `{ "-h": "--help" }`. */
aliases?: Readonly<Record<string, string>>;
}
export interface ParsedArgs {
positionals: string[];
flags: Record<string, FlagValue>;
}
export function parseArgs(argv: readonly string[], spec: FlagSpec = {}): ParsedArgs {
const values = new Set(spec.values ?? []);
const booleans = new Set(spec.booleans ?? []);
const aliases = spec.aliases ?? {};
const flags: Record<string, FlagValue> = {};
const positionals: string[] = [];
for (let index = 0; index < argv.length; index += 1) {
const raw = argv[index]!;
if (raw === "--") {
positionals.push(...argv.slice(index + 1));
break;
}
if (!raw.startsWith("-") || raw === "-") {
positionals.push(raw);
continue;
}
const [head, inline] = splitFlag(raw);
const name = aliases[head] ?? head;
if (booleans.has(name)) {
if (inline !== undefined) throw new UsageError(`${name} does not take a value`);
flags[name] = true;
continue;
}
if (values.has(name)) {
if (inline !== undefined) {
flags[name] = inline;
continue;
}
const next = argv[index + 1];
if (next === undefined || (next.startsWith("-") && next !== "-")) {
throw new UsageError(`${name} requires a value`);
}
flags[name] = next;
index += 1;
continue;
}
throw new UsageError(`unknown option ${head}`);
}
return { positionals, flags };
}
function splitFlag(raw: string): [string, string | undefined] {
const equals = raw.indexOf("=");
if (equals === -1) return [raw, undefined];
return [raw.slice(0, equals), raw.slice(equals + 1)];
}
export function stringFlag(flags: Record<string, FlagValue>, name: string): string | undefined {
const value = flags[name];
return typeof value === "string" ? value : undefined;
}
export function boolFlag(flags: Record<string, FlagValue>, name: string): boolean {
return flags[name] === true;
}
/** Version of the installed package (`dist/cli/*` sits two levels below it). */
export function packageVersion(): string {
try {
const file = fileURLToPath(new URL("../../package.json", import.meta.url));
const parsed = JSON.parse(readFileSync(file, "utf8")) as { version?: unknown };
return typeof parsed.version === "string" ? parsed.version : "0.0.0";
} catch {
return "0.0.0";
}
}
export function realpathOrSelf(path: string): string {
try {
return realpathSync(path);
} catch {
return path;
}
}
/** Fixed-width text table; the last column is never padded. */
export function formatTable(header: readonly string[], rows: readonly (readonly string[])[]): string {
const widths = header.map((cell, column) =>
Math.max(cell.length, ...rows.map((row) => (row[column] ?? "").length)),
);
const line = (cells: readonly string[]): string =>
cells
.map((cell, column) => (column === cells.length - 1 ? cell : cell.padEnd(widths[column] ?? 0)))
.join(" ")
.trimEnd();
return [line(header), line(header.map((_, column) => "-".repeat(widths[column] ?? 0))), ...rows.map(line)].join(
"\n",
);
}
/** `1234567` → `1.2 MiB`. */
export function formatBytes(bytes: number | null | undefined): string {
if (bytes === null || bytes === undefined || !Number.isFinite(bytes)) return "-";
const units = ["B", "KiB", "MiB", "GiB", "TiB"];
let value = bytes;
let unit = 0;
while (value >= 1024 && unit < units.length - 1) {
value /= 1024;
unit += 1;
}
return `${unit === 0 ? value : value.toFixed(1)} ${units[unit]}`;
}
export function formatDuration(ms: number | null | undefined): string {
if (ms === null || ms === undefined || !Number.isFinite(ms) || ms < 0) return "-";
const seconds = Math.floor(ms / 1000);
if (seconds < 60) return `${seconds}s`;
const minutes = Math.floor(seconds / 60);
if (minutes < 60) return `${minutes}m${seconds % 60}s`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `${hours}h${minutes % 60}m`;
return `${Math.floor(hours / 24)}d${hours % 24}h`;
}
export function errorMessage(error: unknown): string {
if (error instanceof Error) return error.message;
return String(error);
}
+189
View File
@@ -0,0 +1,189 @@
/**
* Composition root: the real dependency graph behind `pi2d`.
*
* Everything the daemon serves is assembled here so that the CLI entry point
* only has to deal with process concerns (args, lock, signals, daemon.json):
*
* config -> `loadConfig()` (env driven, see docs/deployment.md)
* bus -> `InMemoryBus` (WS/SSE fan-out)
* auth -> `AuthStore` over `<dataDir>/devices.json` + `<runtime>/cli.token`
* workspaces -> `createWorkspaceStore({ discovery, registry, instances })`
* instances -> `createInstanceManager()` (starts the plugin unix socket itself)
* http/ws -> `startServer(config, deps)`
*/
import { randomUUID } from "node:crypto";
import { join } from "node:path";
import { loadConfig, type Config, type ConfigEnv } from "../config.js";
import { dataDir, daemonSocketPath, daemonTokenPath, runtimeDir, stateDir } from "../core/paths.js";
import type { Logger } from "../core/interfaces.js";
import { AuthStore } from "../daemon/auth.js";
import { InMemoryBus } from "../daemon/hub.js";
import { startServer, type ServerDeps, type StartedServer } from "../daemon/server.js";
import { createInstanceManager, type InstanceManagerHandle } from "../instances/index.js";
import { createDiscovery, createWorkspaceStore, WorkspaceRegistry, type WorkspaceStoreHandle } from "../workspaces/index.js";
import { listenWithRetry, type ListenOptions } from "./listen.js";
/** File name of the local CLI token inside the runtime dir. */
export const CLI_TOKEN_FILE = "cli.token";
export interface WireOptions {
/** Environment used for `loadConfig`; defaults to `process.env`. */
env?: ConfigEnv;
/** Direct config overrides, applied after the environment. */
config?: Partial<Config>;
logger?: Logger;
daemonId?: string;
machineId?: string;
/** Runtime dir for the plugin socket + CLI token; defaults to `runtimeDir()`. */
runtime?: string;
/** Instance log dir; defaults to `<stateDir>/instances`. */
logDir?: string;
/** Workspace registry file; defaults to `<dataDir>/workspaces.json`. */
registryPath?: string;
/** Discovery override (`sessionsRoot()` by default). */
discoveryRoot?: string;
nvimBin?: string;
nvimInit?: string;
now?: () => number;
/** Extra `ServerDeps` (heartbeat/ws overrides) for tests. */
server?: Pick<ServerDeps, "heartbeatMs" | "ws">;
}
export interface WiredDaemon {
/** Effective config; `config.port` is updated by `start()` to the bound port. */
config: Config;
deps: ServerDeps;
instanceManager: InstanceManagerHandle;
workspaceStore: WorkspaceStoreHandle;
auth: AuthStore;
bus: InMemoryBus;
/** The http+ws server, once `start()` succeeded. */
server: StartedServer | undefined;
/** `<runtime>/cli.token` — the local admin token for this daemon. */
cliTokenPath: string;
runtime: string;
/** Start http+ws (idempotent). `options` is passed to `listenWithRetry`. */
start(options?: ListenOptions): Promise<StartedServer>;
/** Close the http server (if started) and the instance layer. */
close(): Promise<void>;
}
function machineIdFor(host: string): string {
// Stable per host so browsers grouped by machine survive daemon restarts.
let hash = 0;
for (let i = 0; i < host.length; i += 1) hash = (hash * 31 + host.charCodeAt(i)) >>> 0;
return `m-${hash.toString(16).padStart(8, "0")}`;
}
export async function wireDaemon(options: WireOptions = {}): Promise<WiredDaemon> {
const env = options.env ?? process.env;
const now = options.now ?? Date.now;
const runtime = options.runtime ?? runtimeDir();
const daemonId = options.daemonId ?? `d-${randomUUID()}`;
const base = loadConfig(env);
const config: Config = {
...base,
...options.config,
limits: { ...base.limits, ...(options.config?.limits ?? {}) },
corsOrigins: options.config?.corsOrigins ?? base.corsOrigins,
};
const bus = new InMemoryBus(options.logger === undefined ? {} : { logger: options.logger });
const cliTokenPath = join(runtime, CLI_TOKEN_FILE);
const auth = new AuthStore({
path: config.deviceStorePath,
baseUrl: `http://${config.host}:${config.port}`,
localTokenPath: cliTokenPath,
...(options.now === undefined ? {} : { now: options.now }),
});
// `resolveCwd` needs the store, and the store needs the manager: keep one
// late-bound reference instead of duplicating the registry lookup.
let workspaceStore: WorkspaceStoreHandle | undefined;
const instanceManager = await createInstanceManager({
bus,
...(options.logger === undefined ? {} : { logger: options.logger }),
daemonId,
now,
socketPath: daemonSocketPath(),
tokenPath: daemonTokenPath(),
runtime,
logDir: options.logDir ?? join(stateDir(), "instances"),
...(options.nvimBin === undefined ? {} : { nvimBin: options.nvimBin }),
...(options.nvimInit === undefined ? {} : { nvimInit: options.nvimInit }),
resolveCwd: (workspaceId: string): string | undefined => {
const workspace = workspaceStore?.get(workspaceId);
if (workspace === undefined) return undefined;
return workspace.cwd;
},
});
const discovery = createDiscovery({
...(options.discoveryRoot === undefined ? {} : { root: options.discoveryRoot }),
...(options.logger === undefined ? {} : { logger: options.logger }),
});
const registry = new WorkspaceRegistry({
filePath: options.registryPath ?? join(dataDir(), "workspaces.json"),
...(options.logger === undefined ? {} : { logger: options.logger }),
});
workspaceStore = createWorkspaceStore({
discovery,
registry,
instances: instanceManager,
...(options.logger === undefined ? {} : { logger: options.logger }),
});
const startedAt = now();
const deps: ServerDeps = {
auth,
instances: instanceManager,
workspaces: workspaceStore,
bus,
...(options.logger === undefined ? {} : { logger: options.logger }),
daemonId,
machineId: options.machineId ?? machineIdFor(env.HOSTNAME ?? process.env.HOSTNAME ?? "localhost"),
startedAt,
now,
...(options.server?.heartbeatMs === undefined ? {} : { heartbeatMs: options.server.heartbeatMs }),
...(options.server?.ws === undefined ? {} : { ws: options.server.ws }),
};
let server: StartedServer | undefined;
let closing: Promise<void> | undefined;
const wired: WiredDaemon = {
config,
deps,
instanceManager,
workspaceStore,
auth,
bus,
server,
cliTokenPath,
runtime,
async start(listenOptions: ListenOptions = {}): Promise<StartedServer> {
if (server !== undefined) return server;
server = await listenWithRetry(wired.config, deps, listenOptions);
wired.server = server;
wired.config = server.config;
return server;
},
async close(): Promise<void> {
if (closing !== undefined) return closing;
closing = (async () => {
const current = wired.server;
if (current !== undefined) await current.close();
// `instanceManager.close()` also stops the plugin socket server;
// the CLI's SIGTERM path closes the socket without killing nvim.
await instanceManager.close();
})();
return closing;
},
};
return wired;
}
export { startServer };
export type { StartedServer };
+52
View File
@@ -3,6 +3,10 @@
*
* Tokens are bearer credentials for the HTTP/WS surfaces. Only a SHA-256 hash
* is persisted, in `$PI2_DATA_DIR/devices.json` (mode 0600, atomic replace).
*
* A second, non-persisted credential exists for local tooling: the CLI token in
* `<runtime>/cli.token` (written by `pi2d`). It authenticates as the synthetic
* `local-cli` device with every scope; see `docs/deployment.md` §7.
*/
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
@@ -62,6 +66,23 @@ export interface AuthStoreOptions {
baseUrl?: string;
/** `touchDevice` write throttle. */
touchIntervalMs?: number;
/**
* File holding the local CLI token (`<runtime>/cli.token`, written by `pi2d`).
* A bearer token equal to its trimmed contents authenticates as the synthetic
* `local-cli` device with every scope. Checked after the persisted devices.
*/
localTokenPath?: string;
}
/** Synthetic device id used for the local CLI token (never persisted). */
export const LOCAL_CLI_DEVICE_ID = "local-cli";
/** Constant-time string compare; the token length itself is not a secret. */
function tokensEqual(expected: string, candidate: string): boolean {
const left = Buffer.from(expected, "utf8");
const right = Buffer.from(candidate, "utf8");
if (left.length !== right.length) return false;
return timingSafeEqual(left, right);
}
interface PairEntry {
@@ -120,6 +141,7 @@ function pairCode(): string {
export class AuthStore {
readonly path: string;
readonly localTokenPath: string | undefined;
private readonly now: () => number;
private readonly baseUrl: string;
private readonly touchIntervalMs: number;
@@ -131,6 +153,8 @@ export class AuthStore {
this.now = options.now ?? Date.now;
this.baseUrl = (options.baseUrl ?? "http://127.0.0.1:7676").replace(/\/+$/, "");
this.touchIntervalMs = options.touchIntervalMs ?? 60_000;
this.localTokenPath =
options.localTokenPath === undefined || options.localTokenPath === "" ? undefined : options.localTokenPath;
this.load();
}
@@ -162,6 +186,7 @@ export class AuthStore {
verifyToken(rawToken: string): DevicePublic | null {
if (typeof rawToken !== "string" || rawToken.length === 0) return null;
if (this.matchesLocalToken(rawToken)) return this.localCliDevice();
const digest = hashToken(rawToken);
let matched: DeviceRecord | undefined;
// Compare against every record so the timing does not reveal the position.
@@ -236,6 +261,33 @@ export class AuthStore {
return this.pairs.has(code);
}
/** The local CLI token grants every scope; it is not persisted or revocable. */
private localCliDevice(): DevicePublic {
const timestamp = this.now();
return {
id: LOCAL_CLI_DEVICE_ID,
name: "local CLI",
kind: "laptop",
scopes: [...SCOPES],
createdAt: 0,
lastSeenAt: timestamp,
revokedAt: null,
};
}
private matchesLocalToken(candidate: string): boolean {
const path = this.localTokenPath;
if (path === undefined) return false;
let contents: string;
try {
contents = readFileSync(path, "utf8").trim();
} catch {
return false;
}
if (contents === "") return false;
return tokensEqual(contents, candidate);
}
private prunePairs(timestamp: number): void {
for (const [code, entry] of this.pairs) {
if (entry.used || timestamp > entry.expiresAt) this.pairs.delete(code);