diff options
| author | user <user@clank> | 2026-08-12 22:24:55 +0200 |
|---|---|---|
| committer | user <user@clank> | 2026-08-12 22:24:55 +0200 |
| commit | 2cd247828d863cdc779c7178c988152835096ca2 (patch) | |
| tree | 867b63f58057e81ac8ab4d242e73b733b8372c9e /cli/src/core | |
| parent | docs(cli): record the fork gap the design turned up (diff) | |
| download | sl0ppi-2cd247828d863cdc779c7178c988152835096ca2.tar.gz sl0ppi-2cd247828d863cdc779c7178c988152835096ca2.tar.xz sl0ppi-2cd247828d863cdc779c7178c988152835096ca2.zip | |
cli: up, ls, open, close
Slice 2 of docs/cli-design.md. The commands read the world (discovery +
list-tabs), compute a plan, then apply it -- never mutating while walking, which
is how `up` stays idempotent.
sl0ppij.ts process wrapper; every piece of state comes back out of
list-tabs/list-panes, so there is nothing to desync
layout.ts composes the tab node around a project's fragment
root.ts root resolution, session naming, the root registry
workspace.ts up / ls / open / close
index.ts dispatch + the fail-open wrapper
Four things this turned up that reading the code would not have:
- `attach --create-background` fails with "There is no active session!" when
the caller is itself inside a session -- which sl0ppi almost always is,
being run from the user's daily-driver terminal. Session creation now runs
with the SL0PPIJ*/ZELLIJ* markers stripped: we are creating a new detached
session, not nesting.
- falling open by passing our own argv to sl0ppij just produces "unrecognized
subcommand: up" and still leaves the user without a terminal. Our verbs and
flags are stripped first, so what is handed over is something sl0ppij
actually understands.
- attaching panics in the client when stdin is not a tty, so `up` from a
script or CI step died. It now reports the session is ready and exits.
- a start_suspended pane reports `is_held`, not `exited`. Conflating them made
`ls` claim every agent was running when none had started. Plugin panes (the
status bar, the link handler) also inflated pane counts and are now excluded
as chrome.
Index conventions were verified against a live session rather than inferred,
because guessing closes the wrong tab: list-tabs `position` and
`close-tab --tab-id` are 0-based, `go-to-tab` is 1-based, and closing renumbers
every tab after it, so batched closes run in descending position order.
Verified end to end against a real session (three projects, one shipping a
custom fragment): up creates the session with all tabs and their purposes; up
again reports "up to date" with tabs unchanged; ls reports panes and
agent:suspended correctly; open creates-and-focuses and resolves unique
prefixes; close removes a tab; deleting a project auto-closes its tab; and with
the root itself missing, nothing is closed at all.
64 tests green.
Diffstat (limited to 'cli/src/core')
| -rw-r--r-- | cli/src/core/layout.ts | 68 | ||||
| -rw-r--r-- | cli/src/core/root.ts | 116 | ||||
| -rw-r--r-- | cli/src/core/sl0ppij.ts | 205 |
3 files changed, 389 insertions, 0 deletions
diff --git a/cli/src/core/layout.ts b/cli/src/core/layout.ts new file mode 100644 index 0000000..a1bf0bb --- /dev/null +++ b/cli/src/core/layout.ts @@ -0,0 +1,68 @@ +/** + * KDL composition. + * + * A project ships a *fragment* (pane nodes only); sl0ppi wraps it in the tab + * node that carries identity and cwd. Pure string composition, so there is no + * KDL parser to keep in step with the fork's dialect, and sl0ppi keeps sole + * control of the purpose. + * + * ALWAYS emit multi-line KDL. On a single line, KDL requires `;` terminators + * between nodes: `tab x { pane }` is a parse error, which is a genuinely + * confusing way to lose an afternoon. + */ + +import { projectPurpose } from "./purpose.ts"; + +/** Quote a value for a KDL string property. */ +export function kdlString(value: string): string { + return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`; +} + +/** + * What a project gets when it has a `.sl0ppi/` marker but no `layout.kdl`. + * + * One suspended agent: every project wants a main agent (agreed), and + * `start_suspended` is what stops `up` on a twelve-project root from launching + * twelve of them. The pane exists, focused-and-keypress runs it. + */ +export const DEFAULT_FRAGMENT = `pane purpose="agent:main" start_suspended=true command="pi"`; + +export interface TabSpec { + /** Tab name, shown in the tab bar. Cosmetic; identity is the purpose. */ + name: string; + /** Project path relative to the root, which the purpose encodes. */ + relPath: string; + /** Absolute path used as the tab's cwd. */ + cwd: string; + /** Pane nodes, verbatim from `.sl0ppi/layout.kdl`. */ + fragment?: string; +} + +function indent(text: string, spaces: number): string { + const pad = " ".repeat(spaces); + return text + .split("\n") + .map((line) => (line.trim() === "" ? "" : pad + line)) + .join("\n"); +} + +/** A single `tab { ... }` node, indented for embedding in a `layout` block. */ +export function tabKdl(spec: TabSpec, indentBy = 4): string { + const fragment = (spec.fragment ?? DEFAULT_FRAGMENT).trimEnd(); + const head = + `tab name=${kdlString(spec.name)} ` + + `purpose=${kdlString(projectPurpose(spec.relPath))} ` + + `cwd=${kdlString(spec.cwd)} {`; + return indent(`${head}\n${indent(fragment, 4)}\n}`, indentBy); +} + +/** A whole-session layout: what `up` passes to `--layout` when creating. */ +export function sessionLayoutKdl(specs: TabSpec[]): string { + const tabs = specs.map((spec) => tabKdl(spec)).join("\n"); + return `layout {\n${tabs}\n}\n`; +} + +/** A one-tab layout: what `up` passes to `new-tab --layout-string`. */ +export function singleTabLayoutKdl(spec: TabSpec): string { + return `layout {\n${tabKdl(spec)}\n}\n`; +} diff --git a/cli/src/core/root.ts b/cli/src/core/root.ts new file mode 100644 index 0000000..8e91d7f --- /dev/null +++ b/cli/src/core/root.ts @@ -0,0 +1,116 @@ +/** + * Roots and session names. + * + * One root directory = one sl0ppij session. The session name is derived from + * the root's basename so that typing `sl0ppi` in ~/dev always lands in the same + * session instead of minting another randomly-named one. + * + * The registry (session name -> root path) exists because a tab purpose stores + * a path *relative to the root*, and `list-panes --json` exposes no cwd, so + * without it there is no way back from a session to a directory. It is a + * rebuildable index, not a source of truth: delete it and the next `up --root` + * writes it again. It doubles as the record of which sessions are ours, which + * is how sl0ppi avoids touching sessions it did not create. + */ + +import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { basename, dirname, join, resolve } from "node:path"; +import { homedir } from "node:os"; +import { createHash } from "node:crypto"; +import { isProjectDir } from "./discover.ts"; + +export function configDir(env: NodeJS.ProcessEnv = process.env): string { + return env.SL0PPI_CONFIG_DIR ?? join(env.XDG_CONFIG_HOME ?? join(homedir(), ".config"), "sl0ppi"); +} + +export function registryPath(env?: NodeJS.ProcessEnv): string { + return join(configDir(env), "roots.json"); +} + +export type Registry = Record<string, string>; + +export function loadRegistry(env?: NodeJS.ProcessEnv): Registry { + const path = registryPath(env); + try { + const parsed = JSON.parse(readFileSync(path, "utf8")); + return typeof parsed === "object" && parsed !== null ? (parsed as Registry) : {}; + } catch { + return {}; // missing or corrupt: it is an index, so rebuild rather than fail + } +} + +export function saveRegistry(registry: Registry, env?: NodeJS.ProcessEnv): void { + const path = registryPath(env); + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, `${JSON.stringify(registry, null, 2)}\n`); +} + +/** + * Session name for a root. + * + * Sanitised to something safe to type and to pass as a session name, and + * disambiguated with a short hash when another root already claims the name — + * two checkouts both called `api` must not fight over one session. + */ +export function sessionNameFor(root: string, registry: Registry = {}): string { + const cleaned = basename(resolve(root)).replace(/[^A-Za-z0-9_-]/g, "-").replace(/^-+|-+$/g, ""); + const base = cleaned.length > 0 ? cleaned : "root"; + const claimed = registry[base]; + if (claimed === undefined || resolve(claimed) === resolve(root)) return base; + return `${base}-${createHash("sha256").update(resolve(root)).digest("hex").slice(0, 6)}`; +} + +export interface ResolvedRoot { + root: string; + session: string; + /** Set when the CWD is itself a project, so `sl0ppi` can focus its tab. */ + project?: string; +} + +/** + * Work out which root the user means. + * + * --root DIR -> that, explicitly + * inside a project-> its parent is the root, and we remember which project + * inside a session-> the root the session is registered against + * otherwise -> the cwd is the root + */ +export function resolveRoot(options: { + rootFlag?: string; + cwd: string; + sessionEnv?: string | null; + registry?: Registry; +}): ResolvedRoot { + const registry = options.registry ?? {}; + const cwd = resolve(options.cwd); + + if (options.rootFlag) { + const root = resolve(options.rootFlag); + return { root, session: sessionNameFor(root, registry) }; + } + + if (isProjectDir(cwd)) { + const root = dirname(cwd); + return { root, session: sessionNameFor(root, registry), project: basename(cwd) }; + } + + if (options.sessionEnv && registry[options.sessionEnv]) { + const root = resolve(registry[options.sessionEnv] as string); + return { root, session: options.sessionEnv }; + } + + return { root: cwd, session: sessionNameFor(cwd, registry) }; +} + +/** Record that `session` belongs to `root`, so later runs can find it. */ +export function rememberRoot(session: string, root: string, env?: NodeJS.ProcessEnv): void { + const registry = loadRegistry(env); + const resolved = resolve(root); + if (registry[session] === resolved) return; + registry[session] = resolved; + saveRegistry(registry, env); +} + +export function rootExists(root: string): boolean { + return existsSync(root); +} diff --git a/cli/src/core/sl0ppij.ts b/cli/src/core/sl0ppij.ts new file mode 100644 index 0000000..b8442b2 --- /dev/null +++ b/cli/src/core/sl0ppij.ts @@ -0,0 +1,205 @@ +/** + * Thin wrapper around the sl0ppij binary. + * + * sl0ppi orchestrates, it does not reimplement: every piece of state comes back + * out of `list-tabs`/`list-panes`, so there is nothing here to desync. + * + * Index conventions, both verified against a live session rather than inferred, + * because getting either wrong closes or focuses the wrong tab: + * + * list-tabs `position` 0-based + * close-tab --tab-id 0-based (same numbering as `position`) + * go-to-tab <INDEX> 1-BASED (matches the `GoToTab 1` keybinds) + * + * Closing also RENUMBERS the tabs after it, so a batch of closes must run in + * descending position order. + */ + +import { spawnSync } from "node:child_process"; + +export const DEFAULT_BIN = "sl0ppij"; + +export interface TabInfo { + position: number; + name: string; + purpose?: string; + active?: boolean; +} + +export interface PaneInfo { + id: number; + tab_id: number; + is_plugin: boolean; + title: string; + purpose?: string; + exited?: boolean; + is_held?: boolean; + terminal_command?: string | null; +} + +export interface RunResult { + code: number; + stdout: string; + stderr: string; +} + +export class Sl0ppijError extends Error { + constructor( + message: string, + readonly result: RunResult, + ) { + super(message); + this.name = "Sl0ppijError"; + } +} + +/** + * The variables that tell a sl0ppij process "you are inside a session". + * + * Both spellings, because the fork exports `SL0PPIJ*` and keeps `ZELLIJ*` for + * ecosystem compatibility. + */ +export const SESSION_ENV_KEYS = [ + "SL0PPIJ", + "SL0PPIJ_SESSION_NAME", + "SL0PPIJ_PANE_ID", + "ZELLIJ", + "ZELLIJ_SESSION_NAME", + "ZELLIJ_PANE_ID", +] as const; + +/** A copy of `env` with the "inside a session" markers removed. */ +export function withoutSessionEnv(env: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv { + const copy = { ...env }; + for (const key of SESSION_ENV_KEYS) delete copy[key]; + return copy; +} + +export interface ClientOptions { + bin?: string; + session?: string; +} + +export class Sl0ppij { + readonly bin: string; + readonly session?: string; + + constructor(options: ClientOptions = {}) { + this.bin = options.bin ?? process.env.SL0PPI_BIN ?? DEFAULT_BIN; + this.session = options.session; + } + + /** Same client, pinned to a session. */ + forSession(session: string): Sl0ppij { + return new Sl0ppij({ bin: this.bin, session }); + } + + run( + args: string[], + { session = true, detached = false }: { session?: boolean; detached?: boolean } = {}, + ): RunResult { + const argv = session && this.session ? ["-s", this.session, ...args] : args; + if (process.env.SL0PPI_DEBUG) { + process.stderr.write(`sl0ppi: exec ${this.bin} ${argv.map((a) => JSON.stringify(a)).join(" ")}\n`); + } + const proc = spawnSync(this.bin, argv, { + encoding: "utf8", + env: detached ? withoutSessionEnv() : process.env, + }); + if (proc.error) { + throw new Sl0ppijError(`could not run ${this.bin}: ${proc.error.message}`, { + code: -1, + stdout: "", + stderr: String(proc.error.message), + }); + } + return { + code: proc.status ?? -1, + stdout: proc.stdout ?? "", + stderr: proc.stderr ?? "", + }; + } + + private runOk( + args: string[], + what: string, + opts?: { session?: boolean; detached?: boolean }, + ): RunResult { + const result = this.run(args, opts); + if (result.code !== 0) { + throw new Sl0ppijError(`${what} failed: ${result.stderr.trim() || result.stdout.trim()}`, result); + } + return result; + } + + listTabs(): TabInfo[] { + const { stdout } = this.runOk(["action", "list-tabs", "--json"], "list-tabs"); + return JSON.parse(stdout) as TabInfo[]; + } + + listPanes(): PaneInfo[] { + const { stdout } = this.runOk(["action", "list-panes", "--json"], "list-panes"); + return JSON.parse(stdout) as PaneInfo[]; + } + + /** Adds a tab from a KDL layout string. Returns its new position. */ + newTab(layoutKdl: string): number { + const { stdout } = this.runOk( + ["action", "new-tab", "--layout-string", layoutKdl], + "new-tab", + ); + return Number.parseInt(stdout.trim(), 10); + } + + /** `position` is the 0-based `position` from list-tabs. */ + closeTab(position: number): void { + this.runOk(["action", "close-tab", "--tab-id", String(position)], "close-tab"); + } + + /** Takes a 0-based position and converts to go-to-tab's 1-based index. */ + focusTab(position: number): void { + this.runOk(["action", "go-to-tab", String(position + 1)], "go-to-tab"); + } + + /** + * Live sessions, excluding dead-but-resurrectable ones. + * + * `--short` lists EXITED sessions too with no way to tell them apart, so we + * parse the long form and drop them. (The same trap is documented in the + * pane-finder installer.) + */ + liveSessions(): string[] { + const result = this.run(["list-sessions", "--no-formatting"], { session: false }); + if (result.code !== 0) return []; // "no sessions" is an error exit, not a failure + return result.stdout + .split("\n") + .filter((line) => line.trim() !== "" && !line.includes("EXITED")) + .map((line) => line.trim().split(/\s+/)[0] as string) + .filter((name) => name.length > 0); + } + + sessionExists(name: string): boolean { + return this.liveSessions().includes(name); + } + + /** + * Creates a detached session from a layout file, without attaching. + * + * Runs with the session markers stripped: `attach --create-background` fails + * with "There is no active session!" when the caller is itself inside a + * session, and sl0ppi is nearly always invoked from inside one. We are + * creating a new detached session, not nesting, so dropping the markers is + * exactly right. + */ + createBackground(name: string, layoutPath: string): void { + this.runOk(["--layout", layoutPath, "attach", "--create-background", name], "create session", { + session: false, + detached: true, + }); + } +} + +/** True when we are running inside a sl0ppij/zellij pane already. */ +export function insideSession(env: NodeJS.ProcessEnv = process.env): string | null { + return env.SL0PPIJ_SESSION_NAME ?? env.ZELLIJ_SESSION_NAME ?? null; +} |
