From bdcab3ce290f6cdf5ec486a5349e07de2d2333dc Mon Sep 17 00:00:00 2001 From: yuez Date: Wed, 21 Oct 2026 10:59:43 +0800 Subject: [PATCH] feat(core): frozen internal interfaces and platform paths - PluginConnection / InstanceManager / WorkspaceStore / Bus contracts - Linux+macOS runtime/data/state dirs, hashed unix socket paths, pi agent dir --- src/core/interfaces.ts | 102 +++++++++++++++++++++++++++++++++++++++++ src/core/paths.ts | 78 +++++++++++++++++++++++++++++++ 2 files changed, 180 insertions(+) create mode 100644 src/core/interfaces.ts create mode 100644 src/core/paths.ts diff --git a/src/core/interfaces.ts b/src/core/interfaces.ts new file mode 100644 index 0000000..d99a573 --- /dev/null +++ b/src/core/interfaces.ts @@ -0,0 +1,102 @@ +/** + * Frozen internal interfaces between the daemon surfaces. + * + * Owners: + * - `src/core/**` (orchestrator, frozen) + * - `src/daemon/**` W1 (HTTP/WS/SSE/auth/static/router) + * - `src/instances/**` W2 (supervisor: one managed nvim per workspace) + * - `src/workspaces/**` W3 (registry + disk discovery) + * - `src/cli/**` W8 (pi2d / pi2 commands) + * + * Do not change these shapes without updating `docs/protocol.md`. + */ + +import type { InstanceState, SessionState, WorkspaceInfo } from "../protocol/types.js"; + +/** One connected plugin (an nvim process running pi2.nvim). */ +export interface PluginConnection { + readonly instanceId: string; + readonly workspaceId: string; + readonly cwd: string; + readonly pid: number; + readonly hasUI: boolean; + readonly listenAddr: string | null; + readonly pluginVersion: string; + /** Send one JSONL record to the plugin. */ + send(record: Record): void; + /** Forward a command; resolves with the plugin `ack` payload. */ + command( + cmd: { id: string; sessionId?: string; method: string; params?: Record; clientRequestId?: string }, + timeoutMs?: number, + ): Promise<{ seq?: number; disposition?: string }>; + subscribe(sessionId: string): void; + unsubscribe(sessionId: string): void; + /** Last snapshot received for a session (render cache, may be undefined). */ + snapshot(sessionId: string): SessionState | undefined; + /** Last seq received for a session. */ + lastSeq(sessionId: string): number; + close(reason: string): void; +} + +export interface InstanceManager { + /** Idempotently make the workspace instance ready; resolves once `hello` arrived. */ + ensure(workspaceId: string, opts?: { timeoutMs?: number }): Promise; + shutdown(workspaceId: string, mode: "drain" | "stop"): Promise; + /** Currently connected instance for a workspace, if any. */ + get(workspaceId: string): PluginConnection | undefined; + list(): InstanceState[]; + /** Workspaces that currently have a managed instance. */ + instanceStates(): InstanceState[]; + /** Find the workspace that owns a session according to live instances. */ + findWorkspaceBySession(sessionId: string): string | undefined; + /** Resources for `/api/v1/resources`. */ + resources(): Promise; + /** Called by the daemon when the last browser subscriber for a session goes away. */ + maybeUnsubscribe(workspaceId: string, sessionId: string): void; + onInstanceChange(handler: (state: InstanceState) => void): void; +} + +export interface InstanceResourcesSnapshot { + instances: { + workspaceId: string; + instanceId: string; + nvimPid: number | null; + rssBytes: number | null; + sessions: number; + hasUI: boolean; + }[]; + totalRssBytes: number; + physicalMemoryBytes: number; + /** Soft warning threshold reached (instances > 8 or RSS > 60%). */ + warn: boolean; + reason?: string; +} + +export interface WorkspaceStore { + /** Registry entries merged with disk discovery and instance state. */ + list(): WorkspaceInfo[]; + get(workspaceId: string): WorkspaceInfo | undefined; + byCwd(cwd: string): WorkspaceInfo | undefined; + add(input: { cwd: string; alias?: string; trust?: boolean }): Promise; + update(workspaceId: string, patch: Partial<{ alias: string | null; pinned: boolean; hidden: boolean; trusted: boolean }>): Promise; + /** Removes the registry entry only; never touches session files. */ + remove(workspaceId: string): Promise; + refresh(workspaceId?: string): Promise; + /** Ensure a workspace exists for a cwd (used when an instance connects). */ + ensureForCwd(cwd: string): Promise; +} + +/** Minimal event bus used by the daemon to fan plugin records out to browsers. */ +export interface Bus { + publish(record: Record): void; + subscribe(handler: (record: Record) => void): () => void; +} + +export type LogLevel = "debug" | "info" | "warn" | "error"; +export interface Logger { + debug(msg: string, fields?: Record): void; + info(msg: string, fields?: Record): void; + warn(msg: string, fields?: Record): void; + error(msg: string, fields?: Record): void; + child(fields: Record): Logger; +} diff --git a/src/core/paths.ts b/src/core/paths.ts new file mode 100644 index 0000000..5a935ce --- /dev/null +++ b/src/core/paths.ts @@ -0,0 +1,78 @@ +/** + * Platform paths (Linux + macOS). Frozen — used by the daemon, the instance + * supervisor and the CLI. + */ + +import { createHash } from "node:crypto"; +import { existsSync, mkdirSync, readFileSync, realpathSync } from "node:fs"; +import { homedir, platform, tmpdir } from "node:os"; +import { join } from "node:path"; + +export const IS_MAC = platform() === "darwin"; + +export function dataDir(): string { + if (process.env.PI2_DATA_DIR) return process.env.PI2_DATA_DIR; + if (IS_MAC) return join(homedir(), "Library", "Application Support", "pi2"); + return join(process.env.XDG_DATA_HOME ?? join(homedir(), ".local", "share"), "pi2"); +} + +export function runtimeDir(): string { + if (process.env.PI2_RUNTIME_DIR) return process.env.PI2_RUNTIME_DIR; + if (IS_MAC) return join(homedir(), "Library", "Caches", "pi2", "run"); + return join(process.env.XDG_RUNTIME_DIR ?? join(tmpdir(), `pi2-${process.getuid?.() ?? 0}`), "pi2"); +} + +export function stateDir(): string { + if (process.env.PI2_STATE_DIR) return process.env.PI2_STATE_DIR; + if (IS_MAC) return join(homedir(), "Library", "Logs", "pi2"); + return join(process.env.XDG_STATE_HOME ?? join(homedir(), ".local", "state"), "pi2"); +} + +export function ensureDir(path: string, mode = 0o700): string { + if (!existsSync(path)) mkdirSync(path, { recursive: true, mode }); + return path; +} + +export const daemonSocketPath = () => join(ensureDir(runtimeDir()), "d.sock"); +export const daemonTokenPath = () => join(runtimeDir(), "d.sock.token"); +export const daemonLockPath = () => join(runtimeDir(), "daemon.lock"); + +export function instanceDir(): string { + return ensureDir(join(runtimeDir(), "i")); +} + +/** Unix socket paths are capped at ~104 bytes (macOS); always hash long ids. */ +export function instanceSocketPath(workspaceId: string, instanceId: string): string { + const hash = createHash("sha256").update(`${workspaceId}:${instanceId}`).digest("hex").slice(0, 16); + return join(instanceDir(), `${hash}.sock`); +} + +/** `~/.pi/agent` or `$PI_CODING_AGENT_DIR`; where pi keeps `sessions/----/`. */ +export function piAgentDir(): string { + return process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent"); +} + +export function sessionsRoot(): string { + return join(piAgentDir(), "sessions"); +} + +export function readToken(): string | undefined { + try { + return readFileSync(daemonTokenPath(), "utf8").trim(); + } catch { + return undefined; + } +} + +/** Best-effort realpath that never throws. */ +export function realpathSafe(path: string): string { + try { + return realpathSync(path); + } catch { + return path; + } +} + +export function workspaceIdForCwd(cwd: string): string { + return createHash("sha256").update(realpathSafe(cwd)).digest("hex").slice(0, 16); +}