feat(cli)!: merge the daemon into pi2 as the daemon subcommand
`pi2 daemon [start] [flags]` now starts the web-console daemon. The `pi2d` executable, its bin entry and its entry module are removed: the daemon keeps its lock -> token -> plugin socket -> listen -> daemon.json lifecycle, its single stdout line (`pi2 daemon listening on ...`) and the signal handling that leaves managed nvim instances running. Service files are renamed to `pi2.service` / `com.pi2.daemon`, and the smoke and e2e harnesses start the daemon through `pi2 daemon`. BREAKING CHANGE: the `pi2d` command no longer exists; use `pi2 daemon` (or `pi2 daemon start`). Existing systemd/launchd units installed under the old names must be reinstalled with `pi2 install-service --write`.
This commit is contained in:
1 parent
b02f4e9070
commit
7e780515ac
38 files changed
+295
-232
No files matched your search
@@ -1,6 +1,5 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* `pi2d` — the pi2 daemon entry point.
|
||||
* `pi2 daemon` — the pi2 web-console daemon entry point.
|
||||
*
|
||||
* Responsibilities (and nothing else):
|
||||
* 1. parse args / apply `--port|--host|--static-dir` to the config env
|
||||
@@ -9,12 +8,14 @@
|
||||
* for local CLI access — a second daemon must never rotate the live token
|
||||
* 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`
|
||||
* 5. print exactly one line: `pi2 daemon 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)
|
||||
*
|
||||
* This module is not an entry point: `src/cli/pi2.ts` dispatches `pi2 daemon`
|
||||
* (optionally `pi2 daemon start`) to `main()`.
|
||||
*/
|
||||
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";
|
||||
@@ -22,23 +23,15 @@ 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 { boolFlag, errorMessage, packageVersion, parseArgs, 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
|
||||
export const USAGE = `pi2 daemon — pi2 daemon
|
||||
|
||||
Usage: pi2d [options]
|
||||
Usage: pi2 daemon [start] [options]
|
||||
|
||||
Options:
|
||||
--port <n> TCP port (default ${DEFAULT_PORT}; 0 = ephemeral)
|
||||
@@ -137,7 +130,7 @@ export async function main(argv: readonly string[], ioOptions: RunDaemonOptions
|
||||
args = parseDaemonArgs(argv);
|
||||
} catch (error) {
|
||||
if (error instanceof UsageError) {
|
||||
io.err(`pi2d: ${error.message}`);
|
||||
io.err(`pi2: ${error.message}`);
|
||||
io.err(error.usage ?? USAGE);
|
||||
return 2;
|
||||
}
|
||||
@@ -149,7 +142,7 @@ export async function main(argv: readonly string[], ioOptions: RunDaemonOptions
|
||||
return 0;
|
||||
}
|
||||
if (args.version) {
|
||||
io.out(`pi2d ${packageVersion()}`);
|
||||
io.out(`pi2 ${packageVersion()}`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -166,7 +159,7 @@ export async function main(argv: readonly string[], ioOptions: RunDaemonOptions
|
||||
try {
|
||||
config = loadConfig();
|
||||
} catch (error) {
|
||||
io.err(`pi2d: ${errorMessage(error)}`);
|
||||
io.err(`pi2: ${errorMessage(error)}`);
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -202,9 +195,9 @@ export async function main(argv: readonly string[], ioOptions: RunDaemonOptions
|
||||
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}`);
|
||||
io.out(`pi2 daemon listening on ${server.url}`);
|
||||
} catch (error) {
|
||||
io.err(`pi2d: ${errorMessage(error)}`);
|
||||
io.err(`pi2: ${errorMessage(error)}`);
|
||||
lock?.release();
|
||||
if (wired !== undefined) await wired.close().catch(() => undefined);
|
||||
return 1;
|
||||
@@ -233,7 +226,7 @@ export async function main(argv: readonly string[], ioOptions: RunDaemonOptions
|
||||
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)}`);
|
||||
io.err(`pi2: shutdown failed: ${errorMessage(error)}`);
|
||||
process.exit(1);
|
||||
});
|
||||
});
|
||||
@@ -241,25 +234,3 @@ export async function main(argv: readonly string[], ioOptions: RunDaemonOptions
|
||||
|
||||
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;
|
||||
},
|
||||
);
|
||||
}
|
||||
+4
-4
@@ -149,7 +149,7 @@ export function checkRuntimeDir(probe: DoctorContext["runtime"]): DoctorCheck {
|
||||
|
||||
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)` };
|
||||
return { name: "cli-token", status: "warn", detail: `${probe.path} missing (start the daemon with \`pi2 daemon\`)` };
|
||||
}
|
||||
const ok = probe.mode !== undefined && (probe.mode & 0o077) === 0;
|
||||
return {
|
||||
@@ -172,13 +172,13 @@ export function checkSocket(probe: DoctorContext["socket"], daemonReachable: boo
|
||||
|
||||
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: "fail", detail: probe.error ?? "not reachable (is the daemon 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` };
|
||||
if (probe.bound) return { name: "port", status: "ok", detail: `${probe.configured} bound by the daemon` };
|
||||
return { name: "port", status: "ok", detail: `${probe.configured} free` };
|
||||
}
|
||||
|
||||
@@ -357,7 +357,7 @@ export async function collectContext(options: DoctorOptions = {}): Promise<Docto
|
||||
daemon = { reachable: false, error: error instanceof Error ? error.message : String(error) };
|
||||
}
|
||||
} else {
|
||||
daemon = { reachable: false, error: "no daemon reachable (is pi2d running?)" };
|
||||
daemon = { reachable: false, error: "no daemon reachable (is the daemon running?)" };
|
||||
}
|
||||
|
||||
const serviceManager: DoctorContext["serviceManager"] =
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Listening with a bounded port retry.
|
||||
*
|
||||
* `pi2d` uses the default port 7676; when another process already owns it the
|
||||
* `pi2 daemon` 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
|
||||
|
||||
+2
-2
@@ -192,7 +192,7 @@ export function acquireLock(options: AcquireLockOptions): DaemonLockHandle {
|
||||
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`,
|
||||
`another pi2 daemon is running (pid ${holder.pid}, port ${holder.port}); use --force to override`,
|
||||
holder,
|
||||
);
|
||||
}
|
||||
@@ -205,7 +205,7 @@ export function acquireLock(options: AcquireLockOptions): DaemonLockHandle {
|
||||
}
|
||||
}
|
||||
|
||||
throw new LockError("E_LOCKED", `could not acquire ${path}: another pi2d keeps re-creating it`);
|
||||
throw new LockError("E_LOCKED", `could not acquire ${path}: another pi2 daemon keeps re-creating it`);
|
||||
}
|
||||
|
||||
function makeHandle(path: string, initial: DaemonLock): DaemonLockHandle {
|
||||
|
||||
+2
-2
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* 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
|
||||
* `pi2 daemon` prints exactly one machine-readable line on stdout (`pi2 daemon
|
||||
* 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";
|
||||
|
||||
+16
-4
@@ -2,6 +2,7 @@
|
||||
/**
|
||||
* `pi2` — the user-facing CLI.
|
||||
*
|
||||
* pi2 daemon [start] run the web-console daemon (foreground)
|
||||
* pi2 attach [path] attach nvim to the workspace instance (or open nvim)
|
||||
* pi2 status [--json] daemon, instances, resources, health
|
||||
* pi2 doctor [--json] environment checks
|
||||
@@ -21,6 +22,7 @@ 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 { main as runDaemonMain } from "./daemon.js";
|
||||
import { readDaemonJson, type DaemonLock } from "./lock.js";
|
||||
import { cliTokenPath, readCliToken } from "./token.js";
|
||||
import {
|
||||
@@ -46,6 +48,7 @@ import { diagnose, formatReport, reportToJson, type DoctorReport } from "./docto
|
||||
export const USAGE = `pi2 — pi2 client
|
||||
|
||||
Usage:
|
||||
pi2 daemon [start] [options] run the web-console daemon (foreground)
|
||||
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
|
||||
@@ -55,7 +58,7 @@ Usage:
|
||||
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\`.
|
||||
$PI2_RUNTIME_DIR/cli.token (local admin token). Start it with \`pi2 daemon\`.
|
||||
See docs/deployment.md.`;
|
||||
|
||||
/** A user-facing failure: printed as-is, exits with `code`. */
|
||||
@@ -88,12 +91,12 @@ 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\`.`,
|
||||
`no running pi2 daemon (${resolve(runtime, "daemon.json")} missing). Start it with \`pi2 daemon\`.`,
|
||||
);
|
||||
}
|
||||
const token = readCliToken(cliTokenPath(runtime));
|
||||
if (token === undefined) {
|
||||
throw new CliError(`missing CLI token (${cliTokenPath(runtime)}). Restart \`pi2d\`.`);
|
||||
throw new CliError(`missing CLI token (${cliTokenPath(runtime)}). Restart the daemon (\`pi2 daemon\`).`);
|
||||
}
|
||||
return { baseUrl: `http://127.0.0.1:${daemon.port}`, token, daemon };
|
||||
}
|
||||
@@ -123,7 +126,7 @@ export function createClient(options: ClientOptions = {}): DaemonClient {
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
});
|
||||
} catch (error) {
|
||||
throw new CliError(`cannot reach pi2d at ${endpoint.baseUrl}: ${errorMessage(error)}`);
|
||||
throw new CliError(`cannot reach the pi2 daemon at ${endpoint.baseUrl}: ${errorMessage(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -466,6 +469,8 @@ export interface Pi2Options {
|
||||
writeFile?: (path: string, content: string) => void;
|
||||
removeFile?: (path: string) => void;
|
||||
runtime?: string;
|
||||
/** Injected `pi2 daemon` runner (defaults to `src/cli/daemon.ts:main`). */
|
||||
daemonMain?: (argv: readonly string[], io: { out: (line: string) => void; err: (line: string) => void }) => Promise<number>;
|
||||
}
|
||||
|
||||
export async function main(argv: readonly string[], options: Pi2Options = {}): Promise<number> {
|
||||
@@ -484,6 +489,13 @@ export async function main(argv: readonly string[], options: Pi2Options = {}): P
|
||||
|
||||
try {
|
||||
switch (command) {
|
||||
case "daemon": {
|
||||
// `pi2 daemon` and `pi2 daemon start` are the same thing; the
|
||||
// optional `start` word is consumed here so the daemon parser
|
||||
// only ever sees flags.
|
||||
const argv = rest[0] === "start" ? rest.slice(1) : rest;
|
||||
return await (options.daemonMain ?? runDaemonMain)(argv, { out, err });
|
||||
}
|
||||
case "attach": {
|
||||
const parsed = parseArgs(rest, { booleans: ["--help"], aliases: { "-h": "--help" } });
|
||||
if (boolFlag(parsed.flags, "--help")) {
|
||||
|
||||
+11
-10
@@ -15,7 +15,7 @@ export type ServicePlatform = "linux" | "darwin";
|
||||
export interface ServicePaths {
|
||||
/** Absolute node binary (`process.execPath`). */
|
||||
nodePath: string;
|
||||
/** Absolute path to `dist/cli/pi2d.js`. */
|
||||
/** Absolute path to `dist/cli/pi2.js`. */
|
||||
scriptPath: string;
|
||||
/** Where logs go (plist StandardOut/ErrPath). */
|
||||
stateDir: string;
|
||||
@@ -30,7 +30,7 @@ export interface ServicePaths {
|
||||
}
|
||||
|
||||
export interface RenderedService {
|
||||
/** `pi2d.service` on Linux, `com.pi2.pi2d.plist` on macOS. */
|
||||
/** `pi2.service` on Linux, `com.pi2.daemon.plist` on macOS. */
|
||||
name: string;
|
||||
/** Absolute install path. */
|
||||
path: string;
|
||||
@@ -41,13 +41,13 @@ export interface RenderedService {
|
||||
removeCommands: string[];
|
||||
}
|
||||
|
||||
export const SYSTEMD_UNIT_NAME = "pi2d.service";
|
||||
export const LAUNCHD_LABEL = "com.pi2.pi2d";
|
||||
export const SYSTEMD_UNIT_NAME = "pi2.service";
|
||||
export const LAUNCHD_LABEL = "com.pi2.daemon";
|
||||
export const LAUNCHD_PLIST_NAME = `${LAUNCHD_LABEL}.plist`;
|
||||
|
||||
/** `<repo>/dist/cli/pi2d.js`, resolved from either `src/cli/` or `dist/cli/`. */
|
||||
/** `<repo>/dist/cli/pi2.js`, resolved from either `src/cli/` or `dist/cli/`. */
|
||||
export function defaultScriptPath(): string {
|
||||
return fileURLToPath(new URL("../../dist/cli/pi2d.js", import.meta.url));
|
||||
return fileURLToPath(new URL("../../dist/cli/pi2.js", import.meta.url));
|
||||
}
|
||||
|
||||
export function defaultServicePaths(overrides: Partial<ServicePaths> = {}): ServicePaths {
|
||||
@@ -96,12 +96,12 @@ export function renderSystemdUnit(paths: ServicePaths): string {
|
||||
const env = environmentEntries(paths).map(([key, value]) => `Environment=${key}=${systemdQuote(value)}`);
|
||||
return [
|
||||
"[Unit]",
|
||||
"Description=pi2 daemon (pi2d)",
|
||||
"Description=pi2 daemon",
|
||||
"After=network.target",
|
||||
"",
|
||||
"[Service]",
|
||||
"Type=simple",
|
||||
`ExecStart=${systemdQuote(paths.nodePath)} ${systemdQuote(paths.scriptPath)} --foreground`,
|
||||
`ExecStart=${systemdQuote(paths.nodePath)} ${systemdQuote(paths.scriptPath)} daemon --foreground`,
|
||||
...env,
|
||||
"Restart=on-failure",
|
||||
"RestartSec=2",
|
||||
@@ -139,6 +139,7 @@ export function renderLaunchAgent(paths: ServicePaths): string {
|
||||
" <array>",
|
||||
` <string>${xmlEscape(paths.nodePath)}</string>`,
|
||||
` <string>${xmlEscape(paths.scriptPath)}</string>`,
|
||||
" <string>daemon</string>",
|
||||
" <string>--foreground</string>",
|
||||
" </array>",
|
||||
...envBlock,
|
||||
@@ -147,9 +148,9 @@ export function renderLaunchAgent(paths: ServicePaths): string {
|
||||
" <key>KeepAlive</key>",
|
||||
" <true/>",
|
||||
" <key>StandardOutPath</key>",
|
||||
` <string>${xmlEscape(join(paths.stateDir, "pi2d.log"))}</string>`,
|
||||
` <string>${xmlEscape(join(paths.stateDir, "pi2-daemon.log"))}</string>`,
|
||||
" <key>StandardErrorPath</key>",
|
||||
` <string>${xmlEscape(join(paths.stateDir, "pi2d.err.log"))}</string>`,
|
||||
` <string>${xmlEscape(join(paths.stateDir, "pi2-daemon.err.log"))}</string>`,
|
||||
"</dict>",
|
||||
"</plist>",
|
||||
"",
|
||||
|
||||
+2
-2
@@ -1,10 +1,10 @@
|
||||
/**
|
||||
* The local CLI token (`<runtime>/cli.token`).
|
||||
*
|
||||
* `pi2d` mints a fresh 32-byte hex token on every start and writes it 0600.
|
||||
* `pi2 daemon` 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.
|
||||
* per-daemon-lifetime: restarting `pi2 daemon` rotates it.
|
||||
*/
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { chmodSync, existsSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
/** Small shared helpers for the `pi2` / `pi2d` command line front ends. */
|
||||
/** Small shared helpers for the `pi2` command line front end (and `pi2 daemon`). */
|
||||
import { readFileSync, realpathSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* Composition root: the real dependency graph behind `pi2d`.
|
||||
* Composition root: the real dependency graph behind `pi2 daemon`.
|
||||
*
|
||||
* 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):
|
||||
|
||||
Reference in new issue
Block a user