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 {
|
||||
|
||||
+4
-8
@@ -14,7 +14,7 @@
|
||||
* is actually reachable on, so it always matches the pairing link.
|
||||
*/
|
||||
import type { NetworkInterfaceInfo } from "node:os";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { defaultStaticDir } from "./core/install.js";
|
||||
import { isLoopbackHost, isWildcardHost, localOrigins } from "./core/network.js";
|
||||
import { daemonTokenPath, dataDir } from "./core/paths.js";
|
||||
|
||||
@@ -36,7 +36,7 @@ export interface Config {
|
||||
host: string;
|
||||
/** TCP port; `0` asks the OS for an ephemeral port (tests). */
|
||||
port: number;
|
||||
/** Built web UI (`<repo>/web/dist` by default). */
|
||||
/** built web UI — PI2_STATIC_DIR wins, else the install layout (<prefix>/share/pi2d/web/dist for the compiled binary, web/dist for an npm/dev checkout). */
|
||||
staticDir: string;
|
||||
corsOrigins: string[];
|
||||
limits: Limits;
|
||||
@@ -53,11 +53,7 @@ export interface ConfigOptions {
|
||||
interfaces?: NodeJS.Dict<NetworkInterfaceInfo[]>;
|
||||
}
|
||||
|
||||
function defaultStaticDir(): string {
|
||||
return fileURLToPath(new URL("../web/dist", import.meta.url));
|
||||
}
|
||||
|
||||
function parsePort(raw: string | undefined): number {
|
||||
export function parsePort(raw: string | undefined): number {
|
||||
if (raw === undefined || raw.trim() === "") return DEFAULT_PORT;
|
||||
if (!/^\d+$/.test(raw.trim())) throw new Error(`PI2_PORT must be an integer, got "${raw}"`);
|
||||
const port = Number(raw);
|
||||
@@ -73,7 +69,7 @@ function normalizeOrigin(raw: string): string | null {
|
||||
return value === "" ? null : value;
|
||||
}
|
||||
|
||||
function normalizePublicUrl(raw: string | undefined): string | null {
|
||||
export function normalizePublicUrl(raw: string | undefined): string | null {
|
||||
if (raw === undefined) return null;
|
||||
return normalizeOrigin(raw);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
/**
|
||||
* Where this process runs from, and what it is allowed to assume about that.
|
||||
*
|
||||
* `pi2` ships in two shapes (ADR 0002):
|
||||
*
|
||||
* 1. an npm package executed by Node (`node …/dist/cli/pi2.js`), where every
|
||||
* asset sits next to the source tree, and
|
||||
* 2. a compiled single binary (`bun build --compile`) installed as
|
||||
* `<prefix>/bin/pi2` with its assets at `<prefix>/share/pi2d/web/dist`.
|
||||
*
|
||||
* The compiled shape has no source tree and no `package.json` on disk, so the
|
||||
* version is injected at build time (`bun build --define`). Everything that
|
||||
* needs to answer "what am I, where are my files" lives here, so that no other
|
||||
* module has to guess from `import.meta.url` alone.
|
||||
*/
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
/**
|
||||
* Replaced textually by `scripts/build-binary.sh` (`bun build --define`).
|
||||
* `typeof` on an undeclared identifier is safe, so an unbundled Node run falls
|
||||
* through to the on-disk `package.json`.
|
||||
*/
|
||||
declare const PI2_BUILD_VERSION: string | undefined;
|
||||
|
||||
/** Fallback when neither the build-time define nor `package.json` is readable. */
|
||||
export const UNKNOWN_VERSION = "0.0.0";
|
||||
|
||||
/** Bun's node-compat version string, when running as a compiled binary. */
|
||||
function bunVersion(): string | undefined {
|
||||
const versions = process.versions as { bun?: string } | undefined;
|
||||
return typeof versions?.bun === "string" ? versions.bun : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* True when this process is a `bun build --compile` artifact.
|
||||
*
|
||||
* The check is deliberately runtime-based rather than build-based: the same
|
||||
* source runs under both shapes, and only the packaging differs.
|
||||
*/
|
||||
export function isBundledRuntime(): boolean {
|
||||
return bunVersion() !== undefined;
|
||||
}
|
||||
|
||||
/** `bundled bun 1.3.14` or `node 22.11.0` — for `pi2 doctor` and logs. */
|
||||
export function runtimeDescription(): string {
|
||||
const bun = bunVersion();
|
||||
if (bun !== undefined) return `bundled bun ${bun}`;
|
||||
return `node ${process.version.replace(/^v/, "")}`;
|
||||
}
|
||||
|
||||
/** Runtime version string only (`22.11.0`, or Bun's compat version). */
|
||||
export function runtimeVersion(): string {
|
||||
return process.version.replace(/^v/, "");
|
||||
}
|
||||
|
||||
/** Absolute path of the running executable (`node`, or the compiled `pi2`). */
|
||||
export function executablePath(): string {
|
||||
return process.execPath;
|
||||
}
|
||||
|
||||
/** `<repo>/package.json` next to `dist/cli/`. Absent inside a compiled binary. */
|
||||
function packageJsonVersion(): string | undefined {
|
||||
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 !== "" ? parsed.version : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Version of the running `pi2`.
|
||||
*
|
||||
* Order: build-time define (compiled binary) → on-disk `package.json` (npm
|
||||
* install, dev checkout) → `UNKNOWN_VERSION`. Never throws: a version probe
|
||||
* must not be able to take the daemon down.
|
||||
*/
|
||||
export function version(): string {
|
||||
if (typeof PI2_BUILD_VERSION === "string" && PI2_BUILD_VERSION !== "") return PI2_BUILD_VERSION;
|
||||
return packageJsonVersion() ?? UNKNOWN_VERSION;
|
||||
}
|
||||
|
||||
/**
|
||||
* Static UI locations, most specific first.
|
||||
*
|
||||
* 1. `<exe>/../share/pi2d/web/dist` — the release layout: `<prefix>/bin/pi2`
|
||||
* plus `<prefix>/share/pi2d/web/dist`, which is what the curl installer,
|
||||
* the Homebrew formula and the AUR `-bin` package all install.
|
||||
* 2. `<exe>/web/dist` — a portable unpacked directory (`pi2` next to its UI).
|
||||
* 3. `<repo>/web/dist` — an npm install or a dev checkout, resolved from this
|
||||
* module's own location.
|
||||
*/
|
||||
export function staticDirCandidates(): string[] {
|
||||
const exeDir = dirname(executablePath());
|
||||
return [
|
||||
resolve(exeDir, "..", "share", "pi2d", "web", "dist"),
|
||||
resolve(exeDir, "web", "dist"),
|
||||
resolve(fileURLToPath(new URL("../../web/dist", import.meta.url))),
|
||||
];
|
||||
}
|
||||
|
||||
function hasIndex(dir: string): boolean {
|
||||
return existsSync(join(dir, "index.html"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The built web UI for the current install shape, or the dev-checkout path when
|
||||
* none of the candidates exists (so diagnostics name a path the user can
|
||||
* create, instead of an arbitrary miss).
|
||||
*/
|
||||
export function defaultStaticDir(): string {
|
||||
for (const candidate of staticDirCandidates()) {
|
||||
if (hasIndex(candidate)) return candidate;
|
||||
}
|
||||
const devPath = staticDirCandidates().at(-1);
|
||||
return devPath ?? resolve("web", "dist");
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the static dir that `defaultStaticDir()` would pick actually holds
|
||||
* a built UI. `PI2_STATIC_DIR` overrides this entirely at the config layer.
|
||||
*/
|
||||
export function hasBundledStaticDir(dir: string): boolean {
|
||||
return hasIndex(dir);
|
||||
}
|
||||
@@ -11,7 +11,7 @@
|
||||
* Do not change these shapes without updating `docs/protocol.md`.
|
||||
*/
|
||||
|
||||
import type { InstanceState, SessionState, WorkspaceInfo } from "../protocol/types.js";
|
||||
import type { InstanceState, RecentSessionInfo, SessionState, WorkspaceInfo } from "../protocol/types.js";
|
||||
|
||||
/** One connected plugin (an nvim process running pi2.nvim). */
|
||||
export interface PluginConnection {
|
||||
@@ -86,6 +86,12 @@ export interface WorkspaceStore {
|
||||
refresh(workspaceId?: string): Promise<void>;
|
||||
/** Ensure a workspace exists for a cwd (used when an instance connects). */
|
||||
ensureForCwd(cwd: string): Promise<WorkspaceInfo>;
|
||||
/**
|
||||
* Newest session files across every known workspace, newest first. Disk
|
||||
* projection only: ids/timestamps from the JSONL header plus file mtime, no
|
||||
* entry parsing, no instance spawn (see docs/protocol.md §3.1).
|
||||
*/
|
||||
recentSessions(limit?: number): RecentSessionInfo[];
|
||||
}
|
||||
|
||||
/** Minimal event bus used by the daemon to fan plugin records out to browsers. */
|
||||
|
||||
+20
-5
@@ -47,13 +47,28 @@ export function instanceSocketPath(workspaceId: string, instanceId: string): str
|
||||
return join(instanceDir(), `${hash}.sock`);
|
||||
}
|
||||
|
||||
/** `~/.pi/agent` or `$PI_CODING_AGENT_DIR`; where pi keeps `sessions/--<cwd>--/`. */
|
||||
export function piAgentDir(): string {
|
||||
return process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
|
||||
export type PathEnv = NodeJS.ProcessEnv | Record<string, string | undefined>;
|
||||
|
||||
/**
|
||||
* Pi session storage directory; where pi keeps `sessions/--<cwd>--/`.
|
||||
*
|
||||
* Resolution order:
|
||||
* 1. `PI2_CODING_AGENT_DIR` — pi2's documented override
|
||||
* 2. `PI_CODING_AGENT_DIR` — pi's own variable (injected by pi when it runs a child)
|
||||
* 3. `~/.pi/agent` — default location
|
||||
*
|
||||
* Empty strings are ignored (fall through to the next candidate).
|
||||
*/
|
||||
export function piAgentDir(env: PathEnv = process.env): string {
|
||||
const pi2 = env.PI2_CODING_AGENT_DIR;
|
||||
if (pi2 !== undefined && pi2 !== "") return pi2;
|
||||
const pi = env.PI_CODING_AGENT_DIR;
|
||||
if (pi !== undefined && pi !== "") return pi;
|
||||
return join(homedir(), ".pi", "agent");
|
||||
}
|
||||
|
||||
export function sessionsRoot(): string {
|
||||
return join(piAgentDir(), "sessions");
|
||||
export function sessionsRoot(env: PathEnv = process.env): string {
|
||||
return join(piAgentDir(env), "sessions");
|
||||
}
|
||||
|
||||
export function readToken(): string | undefined {
|
||||
|
||||
+19
-9
@@ -2,7 +2,6 @@
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { hostname as osHostname, platform as osPlatform, release as osRelease } from "node:os";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { Hono, type Context } from "hono";
|
||||
import type { HttpBindings } from "@hono/node-server";
|
||||
import type { Bus, InstanceManager, Logger, WorkspaceStore } from "../core/interfaces.js";
|
||||
@@ -11,6 +10,7 @@ import { PROTOCOL_VERSION, type CommandRequest } from "../protocol/types.js";
|
||||
import type { Config } from "../config.js";
|
||||
import type { SysinfoSampler } from "../core/sysinfo.js";
|
||||
import { networkBases } from "../core/network.js";
|
||||
import { version } from "../core/install.js";
|
||||
import { encodeQr, fitsQr } from "../core/qr.js";
|
||||
import type { AuthStore, DevicePublic } from "./auth.js";
|
||||
import { isAllowedOrigin, LOCAL_CLI_DEVICE_ID } from "./auth.js";
|
||||
@@ -69,15 +69,15 @@ function normalizeBase(raw: string): string {
|
||||
return raw.trim().replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
/** Daemon package version; falls back to the v1 baseline when package.json is unavailable. */
|
||||
/**
|
||||
* Daemon version, from the shared install probe.
|
||||
*
|
||||
* A compiled binary has no `package.json` on disk, so the version comes from the
|
||||
* build-time define (`core/install`); reading the file here would silently report
|
||||
* a stale baseline instead of the version that was built.
|
||||
*/
|
||||
function daemonVersion(): 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.trim() !== "" ? parsed.version : "0.1.0";
|
||||
} catch {
|
||||
return "0.1.0";
|
||||
}
|
||||
return version();
|
||||
}
|
||||
|
||||
function json(status: number, body: unknown, headers: Record<string, string> = {}): Response {
|
||||
@@ -291,6 +291,16 @@ export function createApp(deps: AppDeps): Hono<Env> {
|
||||
return json(200, ack);
|
||||
});
|
||||
|
||||
// Cross-workspace recent-activity feed. Disk projection only: header ids and
|
||||
// mtimes, no entry parsing and no `instances.ensure()` (that would spawn an
|
||||
// nvim for every idle workspace). The client layers live names/status over
|
||||
// these rows through `/workspaces/:id/sessions` when an instance is connected.
|
||||
app.get("/api/v1/sessions/recent", (c) => {
|
||||
const raw = Number(c.req.query("limit"));
|
||||
const limit = Number.isFinite(raw) && raw > 0 ? Math.min(200, Math.floor(raw)) : 20;
|
||||
return c.json({ sessions: workspaces.recentSessions(limit) });
|
||||
});
|
||||
|
||||
app.get("/api/v1/sessions/:sid/entries", async (c) => {
|
||||
const params: Record<string, unknown> = {};
|
||||
const before = c.req.query("before");
|
||||
|
||||
@@ -318,6 +318,26 @@ export type WorkspaceVisibility = "default" | "secondary";
|
||||
|
||||
export type WorkspaceVisibilityReason = "hidden" | "ghost" | "temp" | "outside-roots" | "stale";
|
||||
|
||||
/**
|
||||
* One disk-projected session row for the cross-workspace recent-activity feed.
|
||||
*
|
||||
* This is file metadata only (header id/timestamp + mtime); the daemon never
|
||||
* parses entries or owns session state (docs/protocol.md §3.1). Live names and
|
||||
* statuses are layered on by the client through `/workspaces/:id/sessions`.
|
||||
*/
|
||||
export interface RecentSessionInfo {
|
||||
sessionId: string;
|
||||
workspaceId: string;
|
||||
/** Workspace display name (alias → basename), for the row's meta line. */
|
||||
workspaceName: string;
|
||||
cwd: string;
|
||||
sessionFile: string;
|
||||
/** Session start, from the JSONL header (or the file name), epoch ms. */
|
||||
timestamp: number;
|
||||
/** File mtime, epoch ms — the recency sort key. */
|
||||
modified: number;
|
||||
}
|
||||
|
||||
export type DaemonCommandMethod =
|
||||
| "instance.ensure"
|
||||
| "instance.shutdown"
|
||||
|
||||
@@ -64,7 +64,7 @@ export interface Discovery {
|
||||
/** Scan every `--*--` directory under the sessions root. */
|
||||
discover(): DiscoveredWorkspace[];
|
||||
/** Session files for a cwd, newest first (header-only, cheap). */
|
||||
listSessions(cwd: string): SessionFile[];
|
||||
listSessions(cwd: string, limit?: number): SessionFile[];
|
||||
/** Drop one directory's cache entry, or the whole cache when omitted. */
|
||||
invalidate(dir?: string): void;
|
||||
/** The encoded directory used for a cwd, when it has been discovered. */
|
||||
@@ -129,7 +129,7 @@ class DiskDiscovery implements Discovery {
|
||||
return out;
|
||||
}
|
||||
|
||||
listSessions(cwd: string): SessionFile[] {
|
||||
listSessions(cwd: string, limit?: number): SessionFile[] {
|
||||
if (typeof cwd !== "string" || cwd.length === 0 || !isAbsolute(cwd)) return [];
|
||||
const workspaceId = workspaceIdForCwd(cwd);
|
||||
const dirs = this.discover()
|
||||
@@ -137,15 +137,21 @@ class DiskDiscovery implements Discovery {
|
||||
.map((entry) => entry.dir);
|
||||
if (dirs.length === 0) return [];
|
||||
|
||||
const sessions: SessionFile[] = [];
|
||||
// Sort the raw file descriptors first so a `limit` reads only the headers
|
||||
// of the newest files instead of every session in the workspace.
|
||||
const infos: SessionFileInfo[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const dir of dirs) {
|
||||
for (const info of this.sessionFiles(dir)) {
|
||||
if (seen.has(info.file)) continue;
|
||||
seen.add(info.file);
|
||||
sessions.push(this.describeSession(info));
|
||||
infos.push(info);
|
||||
}
|
||||
}
|
||||
infos.sort((a, b) => b.mtimeMs - a.mtimeMs || b.size - a.size);
|
||||
const selected = limit !== undefined && limit > 0 ? infos.slice(0, limit) : infos;
|
||||
|
||||
const sessions = selected.map((info) => this.describeSession(info));
|
||||
sessions.sort((a, b) => b.modified - a.modified || b.timestamp - a.timestamp || a.id.localeCompare(b.id));
|
||||
return sessions;
|
||||
}
|
||||
@@ -336,8 +342,8 @@ export function discoverWorkspaces(options: DiscoveryOptions = {}): DiscoveredWo
|
||||
return sharedDiscovery(options.root, options.logger).discover();
|
||||
}
|
||||
|
||||
export function listSessions(cwd: string, options: DiscoveryOptions = {}): SessionFile[] {
|
||||
return sharedDiscovery(options.root, options.logger).listSessions(cwd);
|
||||
export function listSessions(cwd: string, options: DiscoveryOptions = {}, limit?: number): SessionFile[] {
|
||||
return sharedDiscovery(options.root, options.logger).listSessions(cwd, limit);
|
||||
}
|
||||
|
||||
/** Drop cached discovery results for every root (or one directory). */
|
||||
|
||||
@@ -18,6 +18,7 @@ import { dataDir, realpathSafe, workspaceIdForCwd } from "../core/paths.js";
|
||||
import { ERROR_CODES } from "../protocol/errors.js";
|
||||
import type {
|
||||
InstanceState,
|
||||
RecentSessionInfo,
|
||||
WorkspaceInfo,
|
||||
WorkspaceVisibility,
|
||||
WorkspaceVisibilityReason,
|
||||
@@ -241,6 +242,43 @@ class WorkspaceStore implements WorkspaceStoreHandle {
|
||||
return this.requireInfo(record.workspaceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Newest session files across every known workspace (registry ∪ discovery).
|
||||
*
|
||||
* Each workspace asks discovery for at most `limit` rows, so the header scan
|
||||
* stays bounded even on a workspace with a long history. Rows are deduped by
|
||||
* session id (two encoded directories can resolve to the same cwd) and sorted
|
||||
* by file mtime, then header timestamp, then id for a deterministic order.
|
||||
*/
|
||||
recentSessions(limit = 20): RecentSessionInfo[] {
|
||||
const capped = clampLimit(limit);
|
||||
const rows: RecentSessionInfo[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const workspace of this.list()) {
|
||||
if (!workspace.cwd) continue;
|
||||
for (const file of this.discovery.listSessions(workspace.cwd, capped)) {
|
||||
if (file.id === "" || seen.has(file.id)) continue;
|
||||
seen.add(file.id);
|
||||
rows.push({
|
||||
sessionId: file.id,
|
||||
workspaceId: workspace.workspaceId,
|
||||
workspaceName: workspace.name,
|
||||
cwd: workspace.cwd,
|
||||
sessionFile: file.file,
|
||||
timestamp: file.timestamp,
|
||||
modified: file.modified,
|
||||
});
|
||||
}
|
||||
}
|
||||
rows.sort(
|
||||
(a, b) =>
|
||||
b.modified - a.modified ||
|
||||
b.timestamp - a.timestamp ||
|
||||
a.sessionId.localeCompare(b.sessionId),
|
||||
);
|
||||
return rows.slice(0, capped);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
private requireInfo(workspaceId: string): WorkspaceInfo {
|
||||
@@ -567,6 +605,12 @@ function liveCountOf(state: InstanceState): number {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** Keeps a user-supplied recent-session limit in a cheap, predictable range. */
|
||||
function clampLimit(limit: number): number {
|
||||
if (!Number.isFinite(limit) || limit <= 0) return 20;
|
||||
return Math.min(200, Math.max(1, Math.floor(limit)));
|
||||
}
|
||||
|
||||
function mapFsError(error: unknown, path: string): WorkspaceError {
|
||||
const code = (error as NodeJS.ErrnoException | undefined)?.code;
|
||||
const detail = error instanceof Error ? error.message : String(error);
|
||||
|
||||
Reference in new issue
Block a user