feat: session-first workspace activity and installable daemon
Workspaces page: - list the newest sessions across workspaces in the activity column; the daemon exposes GET /api/v1/sessions/recent as a disk projection and the browser enriches live rows from the per-workspace session relay - put recent activity first below 1100px and fix the mobile page-header flex-basis gap Smoke: - pin PI2_HOST=127.0.0.1 in both smoke scripts and make the startup-line assertion follow the configured host; the daemon default stays 0.0.0.0 Install: - standalone binary build/install scripts, packaging templates, CI/release hooks, CLI-first install docs and the supporting config/doctor changes
This commit is contained in:
1 parent
fc51c3be37
commit
d2e20d428a
50 files changed
+5104
-188
No files matched your search
@@ -0,0 +1,255 @@
|
||||
/**
|
||||
* `pi2 config` — print the resolved configuration and the source (environment
|
||||
* variable or default) that produced each value.
|
||||
*
|
||||
* Read-only: no running daemon required, no network, and safe to execute before
|
||||
* any runtime directories have been created on disk.
|
||||
*/
|
||||
import { homedir, platform as osPlatform, tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { DEFAULT_HOST, DEFAULT_PORT, normalizePublicUrl, parsePort } from "../config.js";
|
||||
import { defaultStaticDir, isBundledRuntime, runtimeDescription, version } from "../core/install.js";
|
||||
import { rootsFromEnv } from "../workspaces/index.js";
|
||||
import { formatTable } from "./util.js";
|
||||
|
||||
export const CONFIG_USAGE = `pi2 config — print resolved configuration and sources
|
||||
|
||||
Usage:
|
||||
pi2 config [options]
|
||||
|
||||
Options:
|
||||
--json emit machine-readable JSON object
|
||||
-h, --help print this help and exit`;
|
||||
|
||||
export interface ResolvedConfig {
|
||||
port: number;
|
||||
host: string;
|
||||
publicUrl: string | null;
|
||||
staticDir: string;
|
||||
runtimeDir: string;
|
||||
dataDir: string;
|
||||
stateDir: string;
|
||||
codingAgentDir: string;
|
||||
workspaceRoots: string[];
|
||||
logLevel: string;
|
||||
version: string;
|
||||
platform: string;
|
||||
runtime: string;
|
||||
installShape: string;
|
||||
}
|
||||
|
||||
export type ConfigKey = keyof ResolvedConfig;
|
||||
|
||||
export type ConfigSources = Record<ConfigKey, string>;
|
||||
|
||||
export interface ConfigResolution {
|
||||
config: ResolvedConfig;
|
||||
sources: ConfigSources;
|
||||
}
|
||||
|
||||
export type ConfigJsonOutput = ResolvedConfig & {
|
||||
sources: ConfigSources;
|
||||
};
|
||||
|
||||
export const CONFIG_KEYS: readonly ConfigKey[] = [
|
||||
"port",
|
||||
"host",
|
||||
"publicUrl",
|
||||
"staticDir",
|
||||
"runtimeDir",
|
||||
"dataDir",
|
||||
"stateDir",
|
||||
"codingAgentDir",
|
||||
"workspaceRoots",
|
||||
"logLevel",
|
||||
"version",
|
||||
"platform",
|
||||
"runtime",
|
||||
"installShape",
|
||||
] as const;
|
||||
|
||||
export interface ResolveConfigOptions {
|
||||
env?: Record<string, string | undefined>;
|
||||
platform?: string;
|
||||
home?: string;
|
||||
uid?: number;
|
||||
version?: string;
|
||||
runtime?: string;
|
||||
installShape?: string;
|
||||
staticDir?: string;
|
||||
}
|
||||
|
||||
function resolveRuntimeDir(
|
||||
env: Record<string, string | undefined>,
|
||||
platform: string,
|
||||
home: string,
|
||||
uid: number,
|
||||
): { value: string; source: string } {
|
||||
if (env.PI2_RUNTIME_DIR !== undefined && env.PI2_RUNTIME_DIR.trim() !== "") {
|
||||
return { value: env.PI2_RUNTIME_DIR.trim(), source: "PI2_RUNTIME_DIR" };
|
||||
}
|
||||
if (platform === "darwin") {
|
||||
return { value: join(home, "Library", "Caches", "pi2", "run"), source: "default" };
|
||||
}
|
||||
return { value: join(env.XDG_RUNTIME_DIR ?? join(tmpdir(), `pi2-${uid}`), "pi2"), source: "default" };
|
||||
}
|
||||
|
||||
function resolveDataDir(
|
||||
env: Record<string, string | undefined>,
|
||||
platform: string,
|
||||
home: string,
|
||||
): { value: string; source: string } {
|
||||
if (env.PI2_DATA_DIR !== undefined && env.PI2_DATA_DIR.trim() !== "") {
|
||||
return { value: env.PI2_DATA_DIR.trim(), source: "PI2_DATA_DIR" };
|
||||
}
|
||||
if (platform === "darwin") {
|
||||
return { value: join(home, "Library", "Application Support", "pi2"), source: "default" };
|
||||
}
|
||||
return { value: join(env.XDG_DATA_HOME ?? join(home, ".local", "share"), "pi2"), source: "default" };
|
||||
}
|
||||
|
||||
function resolveStateDir(
|
||||
env: Record<string, string | undefined>,
|
||||
platform: string,
|
||||
home: string,
|
||||
): { value: string; source: string } {
|
||||
if (env.PI2_STATE_DIR !== undefined && env.PI2_STATE_DIR.trim() !== "") {
|
||||
return { value: env.PI2_STATE_DIR.trim(), source: "PI2_STATE_DIR" };
|
||||
}
|
||||
if (platform === "darwin") {
|
||||
return { value: join(home, "Library", "Logs", "pi2"), source: "default" };
|
||||
}
|
||||
return { value: join(env.XDG_STATE_HOME ?? join(home, ".local", "state"), "pi2"), source: "default" };
|
||||
}
|
||||
|
||||
export function resolveConfig(options: ResolveConfigOptions = {}): ConfigResolution {
|
||||
const env = options.env ?? process.env;
|
||||
const platform = options.platform ?? osPlatform();
|
||||
const home = options.home ?? env.HOME ?? homedir();
|
||||
const uid = options.uid ?? (typeof process.getuid === "function" ? process.getuid() : 0);
|
||||
|
||||
const port =
|
||||
env.PI2_PORT !== undefined && env.PI2_PORT.trim() !== ""
|
||||
? { value: parsePort(env.PI2_PORT), source: "PI2_PORT" }
|
||||
: { value: DEFAULT_PORT, source: "default" };
|
||||
|
||||
const host =
|
||||
env.PI2_HOST !== undefined && env.PI2_HOST.trim() !== ""
|
||||
? { value: env.PI2_HOST.trim(), source: "PI2_HOST" }
|
||||
: { value: DEFAULT_HOST, source: "default" };
|
||||
|
||||
const publicUrl =
|
||||
env.PI2_PUBLIC_URL !== undefined && env.PI2_PUBLIC_URL.trim() !== ""
|
||||
? { value: normalizePublicUrl(env.PI2_PUBLIC_URL), source: "PI2_PUBLIC_URL" }
|
||||
: { value: null, source: "default" };
|
||||
|
||||
const staticDir =
|
||||
env.PI2_STATIC_DIR !== undefined && env.PI2_STATIC_DIR.trim() !== ""
|
||||
? { value: env.PI2_STATIC_DIR.trim(), source: "PI2_STATIC_DIR" }
|
||||
: { value: options.staticDir ?? defaultStaticDir(), source: "install layout" };
|
||||
|
||||
const runtimeDir = resolveRuntimeDir(env, platform, home, uid);
|
||||
const dataDir = resolveDataDir(env, platform, home);
|
||||
const stateDir = resolveStateDir(env, platform, home);
|
||||
|
||||
const codingAgentDir =
|
||||
env.PI2_CODING_AGENT_DIR !== undefined && env.PI2_CODING_AGENT_DIR.trim() !== ""
|
||||
? { value: env.PI2_CODING_AGENT_DIR.trim(), source: "PI2_CODING_AGENT_DIR" }
|
||||
: env.PI_CODING_AGENT_DIR !== undefined && env.PI_CODING_AGENT_DIR.trim() !== ""
|
||||
? { value: env.PI_CODING_AGENT_DIR.trim(), source: "PI_CODING_AGENT_DIR" }
|
||||
: { value: join(home, ".pi", "agent"), source: "default" };
|
||||
|
||||
const workspaceRoots =
|
||||
env.PI2_WORKSPACE_ROOTS !== undefined && env.PI2_WORKSPACE_ROOTS.trim() !== ""
|
||||
? { value: rootsFromEnv(env.PI2_WORKSPACE_ROOTS, home), source: "PI2_WORKSPACE_ROOTS" }
|
||||
: { value: rootsFromEnv(undefined, home), source: "default" };
|
||||
|
||||
const logLevel =
|
||||
env.PI2_LOG_LEVEL !== undefined && env.PI2_LOG_LEVEL.trim() !== ""
|
||||
? { value: env.PI2_LOG_LEVEL.trim().toLowerCase(), source: "PI2_LOG_LEVEL" }
|
||||
: { value: "info", source: "default" };
|
||||
|
||||
const versionVal = { value: options.version ?? version(), source: "install layout" };
|
||||
const platformVal = { value: platform, source: "system" };
|
||||
const runtimeVal = { value: options.runtime ?? runtimeDescription(), source: "runtime" };
|
||||
const installShapeVal = {
|
||||
value: options.installShape ?? (isBundledRuntime() ? "bundled" : "node"),
|
||||
source: "install layout",
|
||||
};
|
||||
|
||||
return {
|
||||
config: {
|
||||
port: port.value,
|
||||
host: host.value,
|
||||
publicUrl: publicUrl.value,
|
||||
staticDir: staticDir.value,
|
||||
runtimeDir: runtimeDir.value,
|
||||
dataDir: dataDir.value,
|
||||
stateDir: stateDir.value,
|
||||
codingAgentDir: codingAgentDir.value,
|
||||
workspaceRoots: workspaceRoots.value,
|
||||
logLevel: logLevel.value,
|
||||
version: versionVal.value,
|
||||
platform: platformVal.value,
|
||||
runtime: runtimeVal.value,
|
||||
installShape: installShapeVal.value,
|
||||
},
|
||||
sources: {
|
||||
port: port.source,
|
||||
host: host.source,
|
||||
publicUrl: publicUrl.source,
|
||||
staticDir: staticDir.source,
|
||||
runtimeDir: runtimeDir.source,
|
||||
dataDir: dataDir.source,
|
||||
stateDir: stateDir.source,
|
||||
codingAgentDir: codingAgentDir.source,
|
||||
workspaceRoots: workspaceRoots.source,
|
||||
logLevel: logLevel.source,
|
||||
version: versionVal.source,
|
||||
platform: platformVal.source,
|
||||
runtime: runtimeVal.source,
|
||||
installShape: installShapeVal.source,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function formatTableValue(key: ConfigKey, value: unknown): string {
|
||||
if (value === null || value === undefined) return "-";
|
||||
if (Array.isArray(value)) {
|
||||
return value.length === 0 ? "-" : value.join(", ");
|
||||
}
|
||||
return String(value);
|
||||
}
|
||||
|
||||
export function formatConfigTable(resolution: ConfigResolution): string {
|
||||
const rows = CONFIG_KEYS.map((key) => [
|
||||
key,
|
||||
formatTableValue(key, resolution.config[key]),
|
||||
resolution.sources[key],
|
||||
]);
|
||||
return formatTable(["key", "value", "source"], rows);
|
||||
}
|
||||
|
||||
export function configToJson(resolution: ConfigResolution): string {
|
||||
const jsonOutput: ConfigJsonOutput = {
|
||||
...resolution.config,
|
||||
sources: resolution.sources,
|
||||
};
|
||||
return JSON.stringify(jsonOutput, null, 2);
|
||||
}
|
||||
|
||||
export interface RunConfigOptions extends ResolveConfigOptions {
|
||||
json?: boolean;
|
||||
print?: (line: string) => void;
|
||||
}
|
||||
|
||||
export function runConfig(options: RunConfigOptions = {}): number {
|
||||
const print = options.print ?? ((line: string) => process.stdout.write(`${line}\n`));
|
||||
const resolution = resolveConfig(options);
|
||||
if (options.json) {
|
||||
print(configToJson(resolution));
|
||||
} else {
|
||||
print(formatConfigTable(resolution));
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
+40
-8
@@ -16,7 +16,7 @@
|
||||
* (optionally `pi2 daemon start`) to `main()`.
|
||||
*/
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { loadConfig, DEFAULT_PORT, type Config } from "../config.js";
|
||||
import { loadConfig, DEFAULT_HOST, 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";
|
||||
@@ -24,7 +24,7 @@ import { createLogger } from "./logger.js";
|
||||
import { acquireLock, writeDaemonJson, type DaemonLockHandle } from "./lock.js";
|
||||
import { cliTokenPath, writeCliToken } from "./token.js";
|
||||
import { boolFlag, errorMessage, packageVersion, parseArgs, stringFlag, UsageError } from "./util.js";
|
||||
import { wireDaemon, type WiredDaemon } from "./wiring.js";
|
||||
import { wireDaemon, type StartedServer, type WiredDaemon } from "./wiring.js";
|
||||
|
||||
/** Extra attempts when the *default* port is taken (7676 → 7677 … 7685). */
|
||||
export const DEFAULT_PORT_RETRIES = 9;
|
||||
@@ -35,7 +35,7 @@ Usage: pi2 daemon [start] [options]
|
||||
|
||||
Options:
|
||||
--port <n> TCP port (default ${DEFAULT_PORT}; 0 = ephemeral)
|
||||
--host <addr> bind address (default 127.0.0.1)
|
||||
--host <addr> bind address (default ${DEFAULT_HOST} (all interfaces))
|
||||
--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)
|
||||
@@ -43,9 +43,9 @@ Options:
|
||||
--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,
|
||||
PI2_PUBLIC_URL
|
||||
PI2_PORT, PI2_HOST (${DEFAULT_HOST} (all interfaces)), PI2_STATIC_DIR,
|
||||
PI2_ORIGINS, PI2_RUNTIME_DIR, PI2_DATA_DIR, PI2_STATE_DIR,
|
||||
PI2_LOG_LEVEL, PI2_WORKSPACE_ROOTS, PI2_PUBLIC_URL
|
||||
|
||||
Runtime files ($PI2_RUNTIME_DIR):
|
||||
d.sock plugin unix socket (nvim → daemon)
|
||||
@@ -112,10 +112,15 @@ function defaultIo(): CliIo {
|
||||
};
|
||||
}
|
||||
|
||||
export function startupLine(host: string, port: number): string {
|
||||
return `pi2 daemon listening on http://${host}:${port}`;
|
||||
}
|
||||
|
||||
export interface RunDaemonOptions {
|
||||
out?: (line: string) => void;
|
||||
err?: (line: string) => void;
|
||||
logger?: Logger;
|
||||
onStarted?: (handle: { server: StartedServer; wired: WiredDaemon; close: () => Promise<void> }) => void | Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -198,7 +203,7 @@ 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(`pi2 daemon listening on ${server.url}`);
|
||||
io.out(startupLine(config.host, server.port));
|
||||
} catch (error) {
|
||||
io.err(`pi2: ${errorMessage(error)}`);
|
||||
lock?.release();
|
||||
@@ -226,12 +231,39 @@ export async function main(argv: readonly string[], ioOptions: RunDaemonOptions
|
||||
process.exit(0);
|
||||
};
|
||||
|
||||
const cleanups: (() => void)[] = [];
|
||||
for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"] as const) {
|
||||
process.once(signal, () => {
|
||||
const handler = (): void => {
|
||||
void shutdown(signal).catch((error: unknown) => {
|
||||
io.err(`pi2: shutdown failed: ${errorMessage(error)}`);
|
||||
process.exit(1);
|
||||
});
|
||||
};
|
||||
process.once(signal, handler);
|
||||
cleanups.push(() => process.off(signal, handler));
|
||||
}
|
||||
|
||||
if (options.onStarted !== undefined && server !== undefined && wired !== undefined && lock !== undefined) {
|
||||
const activeLock = lock;
|
||||
const activeServer = server;
|
||||
const activeWired = wired;
|
||||
await options.onStarted({
|
||||
server: activeServer,
|
||||
wired: activeWired,
|
||||
close: async () => {
|
||||
for (const off of cleanups) off();
|
||||
try {
|
||||
await activeServer.close();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
try {
|
||||
await activeWired.close();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
activeLock.release();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+220
-7
@@ -6,15 +6,22 @@
|
||||
* build a context directly instead of poking at the real machine.
|
||||
*/
|
||||
import { execFile } from "node:child_process";
|
||||
import { existsSync, statSync } from "node:fs";
|
||||
import { existsSync, readFileSync, 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_HOST, DEFAULT_PORT, describeHost, loadConfig } from "../config.js";
|
||||
import { defaultStaticDir, executablePath, isBundledRuntime, runtimeDescription } from "../core/install.js";
|
||||
import { isLoopbackHost } from "../core/network.js";
|
||||
import { daemonSocketPath, runtimeDir } from "../core/paths.js";
|
||||
import { PROTOCOL_VERSION } from "../protocol/types.js";
|
||||
import {
|
||||
defaultServicePaths,
|
||||
launchAgentDir,
|
||||
LAUNCHD_PLIST_NAME,
|
||||
systemdUserDir,
|
||||
SYSTEMD_UNIT_NAME,
|
||||
} from "./service.js";
|
||||
import { formatTable } from "./util.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
@@ -50,9 +57,17 @@ export interface BindContext {
|
||||
publicUrl: string | null;
|
||||
}
|
||||
|
||||
export interface UnitProbe {
|
||||
path: string;
|
||||
exists: boolean;
|
||||
content?: string;
|
||||
pathExists?: (path: string) => boolean;
|
||||
}
|
||||
|
||||
export interface DoctorContext {
|
||||
platform: NodeJS.Platform;
|
||||
nodeVersion: string;
|
||||
bundled?: boolean;
|
||||
nvim: BinaryProbe;
|
||||
pi: BinaryProbe;
|
||||
curl: BinaryProbe;
|
||||
@@ -65,6 +80,7 @@ export interface DoctorContext {
|
||||
bind: BindContext;
|
||||
serviceManager: { name: "systemd" | "launchd"; available: boolean; detail?: string };
|
||||
linger: { checked: boolean; enabled?: boolean; detail?: string };
|
||||
unit?: UnitProbe;
|
||||
webDist: { path: string; exists: boolean };
|
||||
}
|
||||
|
||||
@@ -98,15 +114,22 @@ export function parseCurlVersion(output: string | undefined): string | undefined
|
||||
return match?.[1];
|
||||
}
|
||||
|
||||
export const MIN_NODE: readonly [number, number, number] = [22, 0, 0];
|
||||
export const MIN_NODE: readonly [number, number, number] = [20, 0, 0];
|
||||
export const MIN_NVIM: readonly [number, number, number] = [0, 9, 0];
|
||||
|
||||
/** `<repo>/web/dist`, matching `loadConfig()`'s default. */
|
||||
/** Built web UI, matching `loadConfig()`'s default. */
|
||||
export function defaultWebDist(): string {
|
||||
return fileURLToPath(new URL("../../web/dist", import.meta.url));
|
||||
return defaultStaticDir();
|
||||
}
|
||||
|
||||
export function checkNode(version: string): DoctorCheck {
|
||||
export function checkNode(version: string, bundled = false): DoctorCheck {
|
||||
if (bundled) {
|
||||
return {
|
||||
name: "node",
|
||||
status: "ok",
|
||||
detail: `${runtimeDescription()} — bundled runtime, no separate node needed`,
|
||||
};
|
||||
}
|
||||
const parsed = parseVersion(version);
|
||||
if (parsed === undefined) return { name: "node", status: "fail", detail: `unparsable version "${version}"` };
|
||||
const ok = versionAtLeast(parsed, MIN_NODE);
|
||||
@@ -252,6 +275,174 @@ export function checkLinger(probe: DoctorContext["linger"]): DoctorCheck {
|
||||
return { name: "linger", status: probe.enabled === true ? "ok" : "warn", detail };
|
||||
}
|
||||
|
||||
export function defaultUnitPath(platform: NodeJS.Platform, home: string, configHome?: string): string {
|
||||
const paths = defaultServicePaths({ homeDir: home, ...(configHome !== undefined ? { configHome } : {}) });
|
||||
return platform === "darwin"
|
||||
? join(launchAgentDir(paths), LAUNCHD_PLIST_NAME)
|
||||
: join(systemdUserDir(paths), SYSTEMD_UNIT_NAME);
|
||||
}
|
||||
|
||||
export function tokenizeCommandLine(cmd: string): string[] {
|
||||
const tokens: string[] = [];
|
||||
let current = "";
|
||||
let inQuote: '"' | "'" | null = null;
|
||||
let escape = false;
|
||||
|
||||
for (let index = 0; index < cmd.length; index += 1) {
|
||||
const char = cmd[index]!;
|
||||
if (escape) {
|
||||
current += char;
|
||||
escape = false;
|
||||
} else if (char === "\\") {
|
||||
escape = true;
|
||||
} else if (inQuote !== null) {
|
||||
if (char === inQuote) {
|
||||
inQuote = null;
|
||||
} else {
|
||||
current += char;
|
||||
}
|
||||
} else if (char === '"' || char === "'") {
|
||||
inQuote = char;
|
||||
} else if (/\s/.test(char)) {
|
||||
if (current.length > 0) {
|
||||
tokens.push(current);
|
||||
current = "";
|
||||
}
|
||||
} else {
|
||||
current += char;
|
||||
}
|
||||
}
|
||||
if (current.length > 0) {
|
||||
tokens.push(current);
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
export function parsePlistProgramArguments(content: string): string[] {
|
||||
const arrayMatch = /<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/.exec(content);
|
||||
if (!arrayMatch) return [];
|
||||
const strings: string[] = [];
|
||||
const stringRegex = /<string>([\s\S]*?)<\/string>/g;
|
||||
let match: RegExpExecArray | null;
|
||||
while ((match = stringRegex.exec(arrayMatch[1] ?? "")) !== null) {
|
||||
const val = match[1];
|
||||
if (val !== undefined) {
|
||||
const unescaped = val
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, "'")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/&/g, "&");
|
||||
strings.push(unescaped.trim());
|
||||
}
|
||||
}
|
||||
return strings;
|
||||
}
|
||||
|
||||
export function isNodeExecutable(path: string): boolean {
|
||||
return /(?:^|\/)node(?:\.exe)?$/.test(path);
|
||||
}
|
||||
|
||||
export function checkUnit(
|
||||
probe: UnitProbe | undefined,
|
||||
bundled: boolean = isBundledRuntime(),
|
||||
platform: NodeJS.Platform = osPlatform(),
|
||||
): DoctorCheck {
|
||||
if (probe === undefined || !probe.exists) {
|
||||
return {
|
||||
name: "unit",
|
||||
status: "ok",
|
||||
detail: "no service unit installed (run `pi2 install-service --write` to keep the daemon running)",
|
||||
};
|
||||
}
|
||||
|
||||
let content = probe.content;
|
||||
if (content === undefined && probe.path) {
|
||||
try {
|
||||
content = readFileSync(probe.path, "utf8");
|
||||
} catch {
|
||||
content = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
if (content === undefined) {
|
||||
return {
|
||||
name: "unit",
|
||||
status: "warn",
|
||||
detail: `could not read unit file ${probe.path}; re-run \`pi2 install-service --write\``,
|
||||
};
|
||||
}
|
||||
|
||||
const isDarwin = platform === "darwin" || probe.path.endsWith(".plist") || content.includes("<plist");
|
||||
let executable: string | undefined;
|
||||
const pathsToCheck: string[] = [];
|
||||
|
||||
if (isDarwin) {
|
||||
const args = parsePlistProgramArguments(content);
|
||||
executable = args[0];
|
||||
if (executable !== undefined) {
|
||||
pathsToCheck.push(executable);
|
||||
}
|
||||
} else {
|
||||
const lines = content.split("\n");
|
||||
let lastExecStart: string | undefined;
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim();
|
||||
if (trimmed.startsWith("ExecStart=")) {
|
||||
const val = trimmed.slice("ExecStart=".length).trim();
|
||||
if (val.length > 0) {
|
||||
lastExecStart = val;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (lastExecStart !== undefined) {
|
||||
const tokens = tokenizeCommandLine(lastExecStart);
|
||||
const first = tokens[0]?.replace(/^[-+!@]+(?=\/)/, "");
|
||||
if (first !== undefined && first.length > 0) {
|
||||
executable = first;
|
||||
for (const token of tokens) {
|
||||
if (token === "daemon" || token.startsWith("-")) break;
|
||||
pathsToCheck.push(token.replace(/^[-+!@]+(?=\/)/, ""));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (executable === undefined || pathsToCheck.length === 0) {
|
||||
return {
|
||||
name: "unit",
|
||||
status: "warn",
|
||||
detail: `could not parse executable from ${probe.path}; re-run \`pi2 install-service --write\``,
|
||||
};
|
||||
}
|
||||
|
||||
const checkExists = probe.pathExists ?? existsSync;
|
||||
for (const targetPath of pathsToCheck) {
|
||||
if (!checkExists(targetPath)) {
|
||||
return {
|
||||
name: "unit",
|
||||
status: "warn",
|
||||
detail: `${targetPath} missing; re-run \`pi2 install-service --write\``,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const isNode = isNodeExecutable(executable);
|
||||
if ((bundled && isNode) || (!bundled && !isNode)) {
|
||||
return {
|
||||
name: "unit",
|
||||
status: "warn",
|
||||
detail: "unit was rendered for a different install shape; re-run pi2 install-service --write",
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
name: "unit",
|
||||
status: "ok",
|
||||
detail: executable,
|
||||
};
|
||||
}
|
||||
|
||||
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)` };
|
||||
@@ -273,7 +464,7 @@ export function checkProtocol(probe: DoctorContext["daemon"]): DoctorCheck {
|
||||
export function defaultProbes(ctx: DoctorContext): DoctorProbe[] {
|
||||
const isLinux = ctx.platform === "linux";
|
||||
return [
|
||||
{ name: "node", run: () => checkNode(ctx.nodeVersion) },
|
||||
{ name: "node", run: () => checkNode(ctx.nodeVersion, ctx.bundled ?? isBundledRuntime()) },
|
||||
{ name: "nvim", run: () => checkNvim(ctx.nvim) },
|
||||
{ name: "pi", run: () => checkPi(ctx.pi) },
|
||||
{ name: "curl", run: () => checkCurl(ctx.curl) },
|
||||
@@ -286,6 +477,7 @@ export function defaultProbes(ctx: DoctorContext): DoctorProbe[] {
|
||||
{ name: "bind", run: () => checkBind(ctx.bind) },
|
||||
{ name: "service-manager", run: () => checkServiceManager(ctx.serviceManager) },
|
||||
...(isLinux ? [{ name: "linger", run: () => checkLinger(ctx.linger) }] : []),
|
||||
{ name: "unit", run: () => checkUnit(ctx.unit, ctx.bundled ?? isBundledRuntime(), ctx.platform) },
|
||||
{ name: "web-dist", run: () => checkWebDist(ctx.webDist) },
|
||||
{ name: "protocol", run: () => checkProtocol(ctx.daemon) },
|
||||
];
|
||||
@@ -337,6 +529,7 @@ export interface DoctorOptions {
|
||||
run?: RunLike;
|
||||
which?: (command: string) => string | undefined;
|
||||
now?: () => number;
|
||||
unit?: Partial<UnitProbe>;
|
||||
}
|
||||
|
||||
async function defaultRun(command: string, args: readonly string[]): Promise<{ ok: boolean; stdout: string; stderr: string }> {
|
||||
@@ -456,9 +649,28 @@ export async function collectContext(options: DoctorOptions = {}): Promise<Docto
|
||||
}
|
||||
}
|
||||
|
||||
const defaultPath = defaultUnitPath(platform, home, env.XDG_CONFIG_HOME?.trim() || undefined);
|
||||
const unitPath = options.unit?.path ?? defaultPath;
|
||||
const unitExists = options.unit?.exists ?? existsSync(unitPath);
|
||||
let unitContent = options.unit?.content;
|
||||
if (unitContent === undefined && unitExists) {
|
||||
try {
|
||||
unitContent = readFileSync(unitPath, "utf8");
|
||||
} catch {
|
||||
unitContent = undefined;
|
||||
}
|
||||
}
|
||||
const unit: UnitProbe = {
|
||||
path: unitPath,
|
||||
exists: unitExists,
|
||||
...(unitContent !== undefined ? { content: unitContent } : {}),
|
||||
...(options.unit?.pathExists !== undefined ? { pathExists: options.unit.pathExists } : {}),
|
||||
};
|
||||
|
||||
return {
|
||||
platform,
|
||||
nodeVersion: process.version,
|
||||
bundled: isBundledRuntime(),
|
||||
nvim,
|
||||
pi,
|
||||
curl,
|
||||
@@ -471,6 +683,7 @@ export async function collectContext(options: DoctorOptions = {}): Promise<Docto
|
||||
bind: bindContext(env, daemon.port ?? configuredPort),
|
||||
serviceManager,
|
||||
linger,
|
||||
unit,
|
||||
webDist: { path: env.PI2_STATIC_DIR?.trim() || defaultWebDist(), exists: existsSync(env.PI2_STATIC_DIR?.trim() || defaultWebDist()) },
|
||||
};
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
* 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 config [--json] resolved configuration and sources
|
||||
* 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
|
||||
@@ -46,9 +47,11 @@ import {
|
||||
} from "./service.js";
|
||||
import { diagnose, formatReport, reportToJson, type DoctorReport } from "./doctor.js";
|
||||
import { runStop, STOP_USAGE, type StopOptions } from "./stop.js";
|
||||
import { runConfig, CONFIG_USAGE, type RunConfigOptions } from "./config.js";
|
||||
|
||||
export { CliError } from "./util.js";
|
||||
export { runStop, STOP_USAGE, type StopOptions } from "./stop.js";
|
||||
export { runConfig, CONFIG_USAGE, type RunConfigOptions } from "./config.js";
|
||||
|
||||
export const USAGE = `pi2 — pi2 client
|
||||
|
||||
@@ -59,6 +62,7 @@ Usage:
|
||||
pi2 attach [path] attach nvim to the workspace instance, else open nvim
|
||||
pi2 status [--json] daemon info, instances, resources, health
|
||||
pi2 open [--print] [--no-browser] open the web console signed in (local only)
|
||||
pi2 config [--json] resolved configuration and sources
|
||||
pi2 doctor [--json] environment checks
|
||||
pi2 pairing [--base <url>] create a pairing code (URL + code + QR)
|
||||
pi2 install-service [--dry-run|--write] systemd user unit / LaunchAgent
|
||||
@@ -688,6 +692,7 @@ export interface Pi2Options {
|
||||
writeFile?: (path: string, content: string) => void;
|
||||
removeFile?: (path: string) => void;
|
||||
runtime?: string;
|
||||
env?: Record<string, string | undefined>;
|
||||
/** 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>;
|
||||
stopRunner?: (options: StopOptions) => Promise<number>;
|
||||
@@ -769,6 +774,30 @@ export async function main(argv: readonly string[], options: Pi2Options = {}): P
|
||||
noBrowser: boolFlag(parsed.flags, "--no-browser"),
|
||||
});
|
||||
}
|
||||
case "config": {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = parseArgs(rest, { booleans: ["--json", "--help"], aliases: { "-h": "--help" } });
|
||||
} catch (error) {
|
||||
if (error instanceof UsageError) {
|
||||
throw new UsageError(error.message, CONFIG_USAGE);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
if (boolFlag(parsed.flags, "--help")) {
|
||||
out(CONFIG_USAGE);
|
||||
return 0;
|
||||
}
|
||||
if (parsed.positionals.length > 0) {
|
||||
throw new UsageError(`unexpected argument "${parsed.positionals[0]}"`, CONFIG_USAGE);
|
||||
}
|
||||
return runConfig({
|
||||
env: options.env ?? process.env,
|
||||
...(options.platform === undefined ? {} : { platform: options.platform }),
|
||||
json: boolFlag(parsed.flags, "--json"),
|
||||
print: out,
|
||||
});
|
||||
}
|
||||
case "doctor": {
|
||||
const parsed = parseArgs(rest, { booleans: ["--json", "--help"], aliases: { "-h": "--help" } });
|
||||
if (boolFlag(parsed.flags, "--help")) {
|
||||
|
||||
+55
-7
@@ -4,19 +4,41 @@
|
||||
* 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.
|
||||
*
|
||||
* Supports two install shapes:
|
||||
* 1. Bundled binary (`bun build --compile`): invokes the compiled executable directly
|
||||
* (`ExecStart=<execPath> daemon --foreground` or `ProgramArguments = [execPath, "daemon", "--foreground"]`).
|
||||
* 2. Node / script: invokes node with the CLI entrypoint script
|
||||
* (`ExecStart=<nodePath> <scriptPath> daemon --foreground`).
|
||||
*
|
||||
* On systemd (Linux), the service unit supports an optional environment file
|
||||
* (`ServicePaths.envFile`, defaulting to `-%h/.config/pi2/env`, where the leading `-`
|
||||
* instructs systemd to ignore missing files). Setting `envFile: ""` omits the
|
||||
* `EnvironmentFile=` directive. launchd (macOS) ignores this setting as macOS
|
||||
* has no direct launchd equivalent for systemd environment files.
|
||||
*/
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { stateDir } from "../core/paths.js";
|
||||
import { executablePath, isBundledRuntime } from "../core/install.js";
|
||||
|
||||
export type ServicePlatform = "linux" | "darwin";
|
||||
|
||||
export interface ServicePaths {
|
||||
/** True when running as a compiled binary (`bun build --compile`). */
|
||||
bundled?: boolean;
|
||||
/** Absolute path of the running executable (`process.execPath`). */
|
||||
execPath?: string;
|
||||
/** Absolute node binary (`process.execPath`). */
|
||||
nodePath: string;
|
||||
nodePath?: string;
|
||||
/** Absolute path to `dist/cli/pi2.js`. */
|
||||
scriptPath: string;
|
||||
scriptPath?: string;
|
||||
/**
|
||||
* Optional systemd environment file (defaults to `-%h/.config/pi2/env`).
|
||||
* Set to `""` to omit `EnvironmentFile=` entirely. Ignored by launchd.
|
||||
*/
|
||||
envFile?: string;
|
||||
/** Where logs go (plist StandardOut/ErrPath). */
|
||||
stateDir: string;
|
||||
/** Home dir; the unit file lives under it. */
|
||||
@@ -44,6 +66,7 @@ export interface RenderedService {
|
||||
export const SYSTEMD_UNIT_NAME = "pi2.service";
|
||||
export const LAUNCHD_LABEL = "com.pi2.daemon";
|
||||
export const LAUNCHD_PLIST_NAME = `${LAUNCHD_LABEL}.plist`;
|
||||
export const DEFAULT_SYSTEMD_ENV_FILE = "-%h/.config/pi2/env";
|
||||
|
||||
/** `<repo>/dist/cli/pi2.js`, resolved from either `src/cli/` or `dist/cli/`. */
|
||||
export function defaultScriptPath(): string {
|
||||
@@ -52,8 +75,11 @@ export function defaultScriptPath(): string {
|
||||
|
||||
export function defaultServicePaths(overrides: Partial<ServicePaths> = {}): ServicePaths {
|
||||
return {
|
||||
bundled: isBundledRuntime(),
|
||||
execPath: executablePath(),
|
||||
nodePath: process.execPath,
|
||||
scriptPath: defaultScriptPath(),
|
||||
envFile: DEFAULT_SYSTEMD_ENV_FILE,
|
||||
stateDir: stateDir(),
|
||||
homeDir: homedir(),
|
||||
...(process.env.XDG_CONFIG_HOME === undefined ? {} : { configHome: process.env.XDG_CONFIG_HOME }),
|
||||
@@ -93,6 +119,15 @@ function environmentEntries(paths: ServicePaths): [string, string][] {
|
||||
}
|
||||
|
||||
export function renderSystemdUnit(paths: ServicePaths): string {
|
||||
const execStart = paths.bundled
|
||||
? `ExecStart=${systemdQuote(paths.execPath ?? executablePath())} daemon --foreground`
|
||||
: `ExecStart=${systemdQuote(paths.nodePath ?? paths.execPath ?? executablePath())} ${systemdQuote(paths.scriptPath ?? defaultScriptPath())} daemon --foreground`;
|
||||
|
||||
const envFileLine =
|
||||
paths.envFile !== undefined && paths.envFile !== ""
|
||||
? [`EnvironmentFile=${paths.envFile}`]
|
||||
: [];
|
||||
|
||||
const env = environmentEntries(paths).map(([key, value]) => `Environment=${key}=${systemdQuote(value)}`);
|
||||
return [
|
||||
"[Unit]",
|
||||
@@ -101,7 +136,8 @@ export function renderSystemdUnit(paths: ServicePaths): string {
|
||||
"",
|
||||
"[Service]",
|
||||
"Type=simple",
|
||||
`ExecStart=${systemdQuote(paths.nodePath)} ${systemdQuote(paths.scriptPath)} daemon --foreground`,
|
||||
execStart,
|
||||
...envFileLine,
|
||||
...env,
|
||||
"Restart=on-failure",
|
||||
"RestartSec=2",
|
||||
@@ -115,6 +151,21 @@ export function renderSystemdUnit(paths: ServicePaths): string {
|
||||
}
|
||||
|
||||
export function renderLaunchAgent(paths: ServicePaths): string {
|
||||
const programArgs = paths.bundled
|
||||
? [
|
||||
` <string>${xmlEscape(paths.execPath ?? executablePath())}</string>`,
|
||||
" <string>daemon</string>",
|
||||
" <string>--foreground</string>",
|
||||
]
|
||||
: [
|
||||
` <string>${xmlEscape(paths.nodePath ?? paths.execPath ?? executablePath())}</string>`,
|
||||
` <string>${xmlEscape(paths.scriptPath ?? defaultScriptPath())}</string>`,
|
||||
" <string>daemon</string>",
|
||||
" <string>--foreground</string>",
|
||||
];
|
||||
|
||||
// launchd has no direct equivalent for systemd's EnvironmentFile=;
|
||||
// ServicePaths.envFile is ignored on darwin.
|
||||
const env = environmentEntries(paths);
|
||||
const envBlock =
|
||||
env.length === 0
|
||||
@@ -137,10 +188,7 @@ export function renderLaunchAgent(paths: ServicePaths): string {
|
||||
` <string>${LAUNCHD_LABEL}</string>`,
|
||||
" <key>ProgramArguments</key>",
|
||||
" <array>",
|
||||
` <string>${xmlEscape(paths.nodePath)}</string>`,
|
||||
` <string>${xmlEscape(paths.scriptPath)}</string>`,
|
||||
" <string>daemon</string>",
|
||||
" <string>--foreground</string>",
|
||||
...programArgs,
|
||||
" </array>",
|
||||
...envBlock,
|
||||
" <key>RunAtLoad</key>",
|
||||
|
||||
+3
-9
@@ -1,6 +1,6 @@
|
||||
/** Small shared helpers for the `pi2` command line front end (and `pi2 daemon`). */
|
||||
import { readFileSync, realpathSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { realpathSync } from "node:fs";
|
||||
import { version } from "../core/install.js";
|
||||
|
||||
/** Bad arguments; the CLI prints the usage block and exits 2. */
|
||||
export class UsageError extends Error {
|
||||
@@ -100,13 +100,7 @@ export function boolFlag(flags: Record<string, FlagValue>, name: string): boolea
|
||||
|
||||
/** 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";
|
||||
}
|
||||
return version();
|
||||
}
|
||||
|
||||
export function realpathOrSelf(path: string): string {
|
||||
|
||||
Reference in new issue
Block a user