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,309 @@
|
||||
# ADR 0002 — Installation and run model: CLI first, service-owned daemon, plugin attaches
|
||||
|
||||
- Status: accepted (implementing)
|
||||
- Date: 2026-10-28
|
||||
- Supersedes: the implicit "the plugin installs and spawns the daemon" default in
|
||||
`README.md` §Install and the resolution table (explicit path → `PATH` → plugin
|
||||
data dir → repo checkout → `npx @latest`)
|
||||
|
||||
## Context
|
||||
|
||||
`pi2d` is two things at once, and that is why its install story drifted:
|
||||
|
||||
1. a **CLI** (`pi2` + `pi2 daemon`) that serves the web console and supervises one
|
||||
headless nvim per workspace, and
|
||||
2. a **dependency of a Neovim plugin** (`:PiWeb` is the only way most users will
|
||||
ever meet it).
|
||||
|
||||
Today the documented path is the second one: the plugin finds no daemon, `npm
|
||||
install`s `@yuez/pi2d` into `<stdpath("data")>/pi2d`, spawns it detached, and mints
|
||||
a loopback token. It works, but it makes the plugin an installer and a supervisor,
|
||||
which is the exact shape the rest of the ecosystem avoids. Nine reference
|
||||
implementations were surveyed (see §1).
|
||||
|
||||
## 1. How the reference implementations do it
|
||||
|
||||
| Agent | Install channels | Long-lived process | Self-update | How editors attach |
|
||||
|---|---|---|---|---|
|
||||
| **pi** (`@earendil-works/pi-coding-agent`) | `curl -fsSL https://pi.dev/install.sh \| sh` → *managed install*: its own Node under `~/.local/share/pi-node`, launcher in `~/.local/bin`, `managed-install.json` marker; `npm i -g --ignore-scripts` (Node ≥22.19); `nix profile add`; bun-compiled single binary in releases | foreground CLI; `pi --mode rpc` is the long-lived JSONL process a client drives | `pi update [self]` (`pi update` cannot update Nix installs) | the plugin **spawns** `pi --mode rpc` and speaks JSONL; the SDK embeds it in-process |
|
||||
| **dsh** (DeepSeek Harness) | npm package under a version manager (mise `npm-deepseek-ai-dsh`), `dsh` launcher; profile plugins via `dsh plugin … pnpm` | `dsh web` = foreground HTTP+WS server (3080, `--host/--port/--no-open/--public-url/--tls-*`); also `dsh tui`, `dsh headless` | package manager | `dsh.nvim` spawns a **node bridge** (`bridge/bridge.mjs`) that dials `dsh web`; `auto_start` spawns the *server*, never installs it |
|
||||
| **Claude Code** | native installer `curl -fsSL https://claude.ai/install.sh \| bash` (auto-updates); brew cask; winget; apt/dnf/apk; npm (legacy) | foreground CLI; IDE extensions spawn it and connect over a WS MCP socket | background auto-update (native); manual for brew/winget | `claudecode.nvim` runs the WS MCP **server inside nvim**; the `claude` binary on `PATH` is a hard requirement |
|
||||
| **Codex CLI** | `curl -fsSL https://chatgpt.com/codex/install.sh \| sh` → standalone binaries (releases.openai.com, GitHub fallback); `npm i -g @openai/codex`; `brew install --cask codex`; raw tarballs | foreground CLI; `codex app-server` for IDE clients | package manager | IDE extension |
|
||||
| **opencode** | `curl -fsSL https://opencode.ai/install \| bash`; npm/bun/pnpm/yarn; brew tap; pacman/AUR; choco/scoop; `mise use -g github:…`; Docker; raw releases | **TUI *and* a server**: `opencode serve` (default `127.0.0.1:4096`, OpenAPI 3.1 at `/doc`, `--mdns`, `--cors`, basic auth via `OPENCODE_SERVER_PASSWORD`) | package manager | IDE plugins drive a **running server** (`/tui` endpoint); the TUI itself is just a client |
|
||||
| **gemini-cli** | `npx @google/gemini-cli`; `npm i -g` (`latest`/`preview`/`nightly`); brew; macports; conda | foreground CLI | npm dist-tag | (retired in favour of Antigravity) |
|
||||
| **aider** | `curl -LsSf https://aider.chat/install.sh \| sh` (uv-backed, brings Python 3.12); `aider-install`; `uv tool install`; pipx; Docker | foreground CLI | `--upgrade` / package manager | — |
|
||||
| **crush** | brew tap; `npm i -g @charmland/crush`; pacman; nix/NUR; apt repo; winget/scoop; FreeBSD pkg | foreground TUI (single Go binary) | package manager | — |
|
||||
| **mason.nvim** (editor-side counter-example) | the *editor* installs into `stdpath("data")`, one `bin/` added to `$PATH`, registry-driven | n/a | `:MasonUpdate` | n/a |
|
||||
|
||||
Common denominators, all nine agreeing:
|
||||
|
||||
1. **The agent is a first-class CLI installed by a package manager or a `curl | sh`
|
||||
installer — never by the editor plugin.** Plugins that *do* install (`mason.nvim`)
|
||||
are infrastructure whose entire purpose is installing, with a registry behind them.
|
||||
2. **Installers that bypass the OS package manager manage their own runtime** (pi
|
||||
pins Node, aider pins Python via uv, claude/codex ship native binaries). "Your
|
||||
distro's Node is too old" is never allowed to block the install.
|
||||
3. **Self-update is an explicit command or an explicit policy** (`pi update`,
|
||||
`claude`'s background updater, gemini dist-tags, brew upgrades), because agents
|
||||
move faster than distros.
|
||||
4. **The long-lived process is an explicit, separately-documented mode** (`pi --mode
|
||||
rpc`, `dsh web`, `opencode serve`, `codex app-server`) with a stable wire contract,
|
||||
and **the editor is a client of it**.
|
||||
5. **Server modes bind loopback by default and take auth seriously** (opencode
|
||||
password env, dsh accepts only a concrete interface, our loopback CLI token).
|
||||
6. **Nobody silently auto-updates the server behind the editor's back.** Version skew
|
||||
is handled by a version field in the handshake or a startup compatibility check.
|
||||
|
||||
`pi2d`'s one genuine asymmetry: the daemon is **not** the agent. It routes to nvim,
|
||||
which owns sessions. So a daemon alone does nothing (`/workspaces` would be empty of
|
||||
live instances), and a plugin without a daemon has no browser console. Neither side
|
||||
can be "the" entry point — but the *install* and the *process* can each have exactly
|
||||
one owner, and today the plugin wrongly claims both.
|
||||
|
||||
## 2. Decision
|
||||
|
||||
### 2.1 Install: Tier-1 distribution channels and Node floor
|
||||
|
||||
The primary distribution shifts from plugin-orchestrated npm installs to first-class
|
||||
CLI distribution channels.
|
||||
|
||||
#### Node engine floor: lowered to >= 20
|
||||
|
||||
The `package.json` `engines` requirement and `pi2 doctor` checks are lowered to
|
||||
`node >= 20` (from `>= 22`). Nothing in `src/` requires Node 22-only features (no
|
||||
`node:sqlite`, no `styleText`, no `import.meta.dirname`, no `--experimental-*`).
|
||||
Lowering to Node 20 broadens compatibility for npm users (including enterprise LTS
|
||||
and Debian/Ubuntu environments). When running as a compiled binary, no Node runtime
|
||||
is needed at all.
|
||||
|
||||
#### Tier-1 distribution channels (shipped as compiled binaries)
|
||||
|
||||
Instead of the installer downloading and managing a separate Node runtime, all three
|
||||
primary channels ship identical precompiled standalone binaries (`bun build --compile`):
|
||||
|
||||
| Channel | Method | Target audience | Runtime dependency |
|
||||
|---|---|---|---|
|
||||
| **curl installer** | `curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh \| sh` | Generic Linux & macOS | None (zero external dependencies) |
|
||||
| **Homebrew tap** | `brew install zgs225/tap/pi2d` | macOS & Linux | None (standalone binary formula) |
|
||||
| **Arch AUR (`-bin`)** | `paru -S pi2d-bin` / `yay -S pi2d-bin` | Arch Linux, EndeavourOS, Manjaro | None (standalone binary package) |
|
||||
| **npm global** | `npm i -g @yuez/pi2d` (or `pnpm add -g`, `bun add -g`) | Node developers | Node >= 20 |
|
||||
| **repo checkout** | `git clone … && pnpm install && pnpm build` | Contributors, offline development | Node >= 20, pnpm |
|
||||
|
||||
The curl installer, Homebrew tap, and Arch AUR package are launched simultaneously (T1).
|
||||
Because they distribute compiled binaries, the installer no longer needs to pin or install
|
||||
Node under `~/.local/share/pi2-node`.
|
||||
|
||||
#### Rejection of `npx` as an install or execution path
|
||||
|
||||
Using `npx @yuez/pi2d@latest` or `npx` auto-execution is explicitly rejected:
|
||||
1. **Network overhead on startup**: `npx` queries npm registries on first use or tag resolution,
|
||||
introducing multi-second latency to editor startup.
|
||||
2. **Phantom dependencies**: creates ephemeral cache directories or uncontrolled
|
||||
`node_modules` under `stdpath("data")`.
|
||||
3. **Supply chain exposure**: `@latest` resolution opens unpinned supply chain attack vectors.
|
||||
4. **Version drift**: different editor sessions or background runs can resolve different
|
||||
daemon versions simultaneously, corrupting singleton socket expectations.
|
||||
|
||||
The plugin's `:PiWebInstall` becomes an explicit convenience command that prompts for
|
||||
confirmation before installing a pinned version matching the plugin into
|
||||
`<stdpath("data")>/pi2d`. It never runs `npx`.
|
||||
|
||||
### 2.2 Run: the daemon owns its own lifecycle
|
||||
|
||||
| Mode | Who starts it | When to use |
|
||||
|---|---|---|
|
||||
| **user service (default)** | `pi2 install-service --write` → `systemctl --user` / `launchd`; `:PiWeb` only *uses* it | daily use, especially phone/another-browser access — the console has to be up when nvim is not |
|
||||
| **plugin spawn** | `:PiWeb` spawns a detached `pi2 daemon` if nothing runs (`web.autostart = "spawn"`) | a machine where the user does not want a service; logs to `PI2_STATE_DIR/daemon.log` |
|
||||
| **foreground** | the user, in a terminal | debugging, `pi2 daemon --foreground` |
|
||||
|
||||
#### `web.autostart = "auto"` semantics
|
||||
|
||||
The plugin setting `web.autostart = "auto"` follows strict three-step semantics:
|
||||
1. **Attach if running**: Check if a daemon is already active (via `daemon.json` / `d.sock`).
|
||||
If running, connect immediately — **never** spawn a second daemon.
|
||||
2. **Start user service**: If an installed user service unit is found (`systemctl --user` or
|
||||
`launchctl`), trigger unit start (`systemctl --user start pi2.service` or `launchctl kickstart`).
|
||||
3. **Spawn detached**: If no service is installed, spawn a detached `pi2 daemon` process and
|
||||
notify the user once in the editor.
|
||||
|
||||
#### `:PiWebStop` behavior in service mode
|
||||
|
||||
When the daemon is managed by a service manager (`systemd` or `launchd`), `:PiWebStop`
|
||||
**must refuse** to stop the process. If a client terminates a service-managed daemon directly
|
||||
via SIGTERM, `Restart=on-failure` (systemd) or `KeepAlive` (launchd) will immediately
|
||||
attempt to restart it or enter an inconsistent state. The plugin must advise the user to
|
||||
use `systemctl --user stop pi2` or `:PiWebService disable`.
|
||||
|
||||
### 2.3 The plugin is a client
|
||||
|
||||
`pi2.nvim` resolution order becomes, in order, with `:PiWebStatus` reporting the
|
||||
winner:
|
||||
|
||||
1. `web.binary` / `$PI2_DAEMON_BIN` (explicit path or command name)
|
||||
2. `pi2` on `$PATH` (the normal case — the CLI install of §2.1)
|
||||
3. `<stdpath("data")>/pi2d/node_modules/.bin/pi2` (only if `:PiWebInstall` created it)
|
||||
4. repo checkout `dist/cli/pi2.js` / `node_modules/.bin/pi2` (developing pi2d)
|
||||
5. **nothing** → one-line error with the install command, no `npx` fallback
|
||||
|
||||
Commands: `:PiWeb` (ensure + open), `:PiWebStatus`, `:PiWebStart`, `:PiWebStop`,
|
||||
`:PiWebPair`, `:PiWebInstall`, `:PiWebService`, `:PiWebLog`. `:checkhealth pi` grows a
|
||||
`web` section: binary source, version, daemon reachability, protocol match, service
|
||||
state, autostart mode.
|
||||
|
||||
### 2.4 Configuration stays environment-only
|
||||
|
||||
The daemon keeps `PI2_*` env as the single config surface (`src/config.ts`, no file
|
||||
parser, no precedence rules). Two additions: `pi2 config` prints the resolved
|
||||
configuration plus the paths that produced it, and the systemd unit carries
|
||||
`EnvironmentFile=-%h/.config/pi2/env` (the leading `-` instructs systemd to ignore missing
|
||||
files). A `pi2.toml` is rejected: ~20 knobs, all deployment-time, all naturally expressed
|
||||
as environment variables.
|
||||
|
||||
### 2.5 Packaging: standalone binary contract
|
||||
|
||||
#### Artifact contract
|
||||
|
||||
Stand-alone binary releases are compiled with Bun (`bun build --compile`) and packaged
|
||||
by `scripts/build-binary.sh` for six cross-compilation targets:
|
||||
- `linux-x64`
|
||||
- `linux-arm64`
|
||||
- `linux-x64-musl`
|
||||
- `linux-arm64-musl`
|
||||
- `darwin-x64`
|
||||
- `darwin-arm64`
|
||||
|
||||
Each release produces a tarball named `pi2d-<version>-<target>.tar.gz` and a top-level
|
||||
`SHA256SUMS` manifest.
|
||||
|
||||
#### Archive layout contract
|
||||
|
||||
Every tarball unpacks with the exact layout:
|
||||
```
|
||||
bin/
|
||||
pi2
|
||||
share/
|
||||
pi2d/
|
||||
web/
|
||||
dist/
|
||||
index.html
|
||||
...
|
||||
LICENSE
|
||||
```
|
||||
|
||||
#### Filesystem prefix rule: `<prefix>/bin` + `<prefix>/share/pi2d/web/dist`
|
||||
|
||||
This directory structure conforms to standard Unix filesystem hierarchies (FHS). It is
|
||||
the exact path probed at runtime by `src/core/install.ts`:
|
||||
```typescript
|
||||
resolve(dirname(executablePath()), "..", "share", "pi2d", "web", "dist")
|
||||
```
|
||||
Every distribution channel preserves this relationship under its installation prefix:
|
||||
- **curl installer**: prefix `~/.local/lib/pi2d` (with symlink `~/.local/bin/pi2`)
|
||||
- **Homebrew**: prefix `#{prefix}` (`/opt/homebrew` or `/usr/local`)
|
||||
- **Arch AUR**: prefix `/usr`
|
||||
|
||||
#### npm package remains JS-only for Node >= 20
|
||||
|
||||
The npm package (`@yuez/pi2d`) deliberately remains pure JavaScript/TypeScript output
|
||||
in `dist/` and `web/dist/`, running under Node >= 20. Packaging native platform binaries
|
||||
into npm optional dependencies (e.g. `@yuez/pi2d-linux-x64`) is intentionally avoided
|
||||
for now (Decision 3 '先不修改') to prevent publishing complexity across npm and GitHub
|
||||
releases before justified by demand.
|
||||
|
||||
### 2.6 Upgrade and restart semantics
|
||||
|
||||
1. **npm upgrade**: running `npm i -g @yuez/pi2d@latest` (or `pnpm`/`bun`) updates the
|
||||
script in place. The running daemon process continues until restarted via
|
||||
`systemctl --user restart pi2` or `pi2 stop && pi2 daemon`.
|
||||
2. **Binary upgrade (installer / brew / AUR)**: package managers or `install.sh`
|
||||
replace the binary on disk. Under Unix filesystem semantics, an open file descriptor
|
||||
to the running executable remains valid; existing daemon operations continue uninterrupted
|
||||
until the service is restarted.
|
||||
3. **Systemd `Restart=on-failure`**: does not fight intentional shutdowns. A clean `SIGTERM`
|
||||
(e.g. via `pi2 stop`) causes `pi2 daemon` to exit with code `0`. Systemd considers exit 0
|
||||
a clean stop and does not trigger restart.
|
||||
4. **Node path staleness**: units created for an npm install hardcode the absolute node
|
||||
path (`process.execPath`). Upgrading Node via a version manager (`mise`, `nvm`, `fnm`)
|
||||
invalidates that path. `pi2 doctor` detects when node cannot run, and re-running
|
||||
`pi2 install-service --write` re-renders the unit with the updated path.
|
||||
5. **Daemon restart & client reconnection**:
|
||||
- **Managed Neovim instances**: spawned nvim processes do not terminate when the daemon
|
||||
stops. They dial `d.sock` with exponential backoff (200 ms to 5 s) and reconnect
|
||||
automatically when the daemon restarts.
|
||||
- **Web browsers**: WebSocket disconnects trigger client-side reconnection. During the
|
||||
initial handshake (`hello`), the daemon presents its newly minted `daemonId`. If the
|
||||
`daemonId` has changed, the browser recognizes a restarted daemon and resynchronizes state.
|
||||
|
||||
### 2.7 Compatibility and protocol handshake
|
||||
|
||||
1. **Protocol v1 handshake**: Every connection over WebSocket or unix socket begins with
|
||||
a `hello` exchange containing:
|
||||
- `daemonVersion`: semantic version of the running daemon (e.g. `0.1.5`)
|
||||
- `protocolVersion`: integer protocol version (currently `1`, defined in `src/protocol/types.ts`)
|
||||
- `daemonId`: unique UUID minted per daemon process run
|
||||
2. **Version skew handling**:
|
||||
- The plugin compares `protocolVersion` against its supported range.
|
||||
- If the protocol version does not match, the plugin refuses to proceed, prints an
|
||||
actionable error message, and displays the exact upgrade command for the user's platform.
|
||||
- `pi2 doctor` probes the live daemon (`/api/v1/info`) and verifies CLI/daemon protocol parity.
|
||||
|
||||
### 2.8 Security hardening
|
||||
|
||||
1. **Service environment file**: `EnvironmentFile=-%h/.config/pi2/env` uses the leading `-`
|
||||
to ensure systemd boots cleanly even if the file is missing. Recommended permissions are
|
||||
`0600` (`chmod 0600 ~/.config/pi2/env`) to protect tokens and configuration from other users.
|
||||
2. **No tokens in logs**:
|
||||
- Local admin token (`cli.token`) is randomly generated per boot, mode `0600`.
|
||||
- Device tokens are stored only as SHA-256 hashes in `devices.json`.
|
||||
- Browser console login (`POST /api/v1/console/session`) passes the session token strictly
|
||||
within the URL fragment (`#t=<token>`), preventing tokens from leaking into server logs,
|
||||
HTTP headers, or `Referer` fields.
|
||||
3. **Pairing rate limits**:
|
||||
- `POST /api/v1/pair/redeem` enforces strict rate limits: 5 attempts/minute/IP and 50 attempts/hour globally. Exceeding limits returns `429 Too Many Requests`.
|
||||
- Pairing codes expire in 10 minutes and are single-use.
|
||||
4. **Service bind warnings**: `pi2 install-service` checks if the daemon is configured to
|
||||
bind to all interfaces (`0.0.0.0`) without TLS and prints an explicit security warning.
|
||||
5. **Doctor posture checks**: `pi2 doctor` verifies file permissions (`0700` for runtime dir,
|
||||
`0600` for `cli.token`), warns when linger is disabled on Linux, and requires explicit
|
||||
acknowledgement when running non-loopback without an `https:` `PI2_PUBLIC_URL`.
|
||||
|
||||
### 2.9 Deferred features and acceptance criteria
|
||||
|
||||
The following items are deferred to future revisions:
|
||||
|
||||
1. **`pi2 update` in-place self-updater**:
|
||||
- *Rationale*: Package managers (Homebrew, AUR, npm) already provide robust upgrade mechanisms.
|
||||
- *Acceptance criteria*: Detects if installed via standalone installer (`~/.local/lib/pi2d`);
|
||||
queries GitHub Releases API for newer version; verifies release `SHA256SUMS`; performs
|
||||
atomic replacement of `bin/` and `share/`; signals running systemd/launchd service to
|
||||
restart; refuses self-update when managed by Homebrew, AUR, or npm with instructions to use
|
||||
the native package manager.
|
||||
2. **npm platform-binary packages (`@yuez/pi2d-<os>-<arch>`)**:
|
||||
- *Rationale*: The npm package works well as pure JS for Node >= 20. Adding platform-specific
|
||||
npm packages in `optionalDependencies` complicates CI/CD and release publishing.
|
||||
- *Acceptance criteria*: CI builds and publishes target-specific packages containing only the
|
||||
compiled binary; root `@yuez/pi2d` package delegates to platform binary if present,
|
||||
falling back to Node JS entrypoint.
|
||||
3. **Upstream distribution repositories (`homebrew-core`, Alpine `aports`, `winget`)**:
|
||||
- *Rationale*: A custom tap (`zgs225/tap`) and AUR package provide fast release iteration
|
||||
without third-party review bottlenecks.
|
||||
- *Acceptance criteria*: Stable v1.0 release, official submission to `homebrew-core` (requires
|
||||
source-based build), official Alpine community package, and signed Windows MSIX/winget package.
|
||||
|
||||
## Consequences
|
||||
|
||||
- **Documentation order changes**: install the CLI → (optionally) enable the service →
|
||||
install the plugin → `:PiWeb`. `:PiWeb` stops being the whole install path.
|
||||
- **Migration for existing users**: users who relied on the legacy auto-install into
|
||||
`<stdpath("data")>/pi2d` must install the `pi2` CLI via one of the Tier-1 channels
|
||||
(curl, brew, AUR, or npm). `:PiWeb` stops silently installing or executing via `npx`.
|
||||
- **Documentation rewrite**: `README.md`, `docs/deployment.md`, and `docs/install.md` are
|
||||
rewritten to emphasize the CLI-first model and the compiled binary options.
|
||||
- **Explicit `:PiWebInstall`**: `:PiWebInstall` remains available as an explicit fallback,
|
||||
installing a pinned version strictly matching the plugin release after user confirmation.
|
||||
- **Node floor lowered to >= 20**: broader compatibility for npm users without compromising
|
||||
runtime stability.
|
||||
- **Standalone binaries eliminate Node dependencies**: users of curl, Homebrew, and AUR
|
||||
require no Node installation, eliminating "distro Node is too old" issues entirely.
|
||||
- **Service is optional**: `pi2 daemon` runs standalone in the foreground, and `pi2 doctor`
|
||||
treats missing service managers or linger as warnings, never fatal errors.
|
||||
+104
-18
@@ -35,15 +35,19 @@ Contents
|
||||
|
||||
| Component | Requirement | Needed for |
|
||||
|---|---|---|
|
||||
| Node | **>= 22** (`engines` field) | daemon + CLI |
|
||||
| Node | **>= 20** (`engines` field for npm install); **none** for compiled binary | daemon + CLI (npm/Node install) |
|
||||
| Neovim | **>= 0.9** | managed instances; `nvim --remote-ui` for `pi2 attach` |
|
||||
| pi CLI | any recent version | agent sessions inside nvim |
|
||||
| pi2.nvim | `lua/pi/web/bridge.lua` present | the plugin that dials the daemon |
|
||||
|
||||
`pi2 doctor` checks all of the above (see [§8.3](#83-pi2-doctor)).
|
||||
The compiled standalone binary (`bun build --compile`) needs no Node at all and reports
|
||||
its runtime as `bundled` (e.g. `bundled bun 1.3.14`). `pi2 doctor` checks all of the above
|
||||
(see [§8.3](#83-pi2-doctor)).
|
||||
|
||||
## 2. Build
|
||||
|
||||
### Node / npm package build
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
pnpm build # tsc -> dist/ (dist/cli/pi2.js)
|
||||
@@ -54,8 +58,35 @@ The daemon serves the browser console from `<repo>/web/dist` (or `PI2_STATIC_DIR
|
||||
Without it `/` returns 404/SPA fallback behaviour and `/api/v1/health` reports
|
||||
`static=FAIL`; the API and `pi2` keep working.
|
||||
|
||||
There is exactly one built binary, `dist/cli/pi2.js` (client commands **and** the
|
||||
`daemon` subcommand). It is ESM and starts with a `#!` line.
|
||||
For an npm install, there is exactly one entrypoint script, `dist/cli/pi2.js` (client
|
||||
commands **and** the `daemon` subcommand). It is ESM and starts with a `#!` line.
|
||||
|
||||
### Compiled binary build
|
||||
|
||||
```bash
|
||||
pnpm build:binary # or: bash scripts/build-binary.sh
|
||||
```
|
||||
|
||||
Produces the standalone artifact tree under `dist-bin/`:
|
||||
- `dist-bin/bin/pi2` — compiled executable (`bun build --compile`) with injected `PI2_BUILD_VERSION`
|
||||
- `dist-bin/share/pi2d/web/dist/` — web console assets
|
||||
- `dist-bin/LICENSE` — license file
|
||||
- `dist-bin/pi2d-<version>-<os>-<arch>.tar.gz` — distribution tarball containing `bin`, `share`, and `LICENSE`
|
||||
|
||||
Cross-compilation targets (`bun-linux-x64`, `bun-linux-arm64`, `bun-linux-x64-musl`,
|
||||
`bun-linux-arm64-musl`, `bun-darwin-x64`, `bun-darwin-arm64`):
|
||||
```bash
|
||||
bash scripts/build-binary.sh --target bun-linux-x64
|
||||
```
|
||||
|
||||
To run the whole test gate against the compiled artifact:
|
||||
```bash
|
||||
bash scripts/smoke-binary.sh # or: pnpm smoke:binary
|
||||
```
|
||||
It asserts daemon startup on ephemeral port 0, `GET /api/v1/info`, `GET /` (HTML from
|
||||
`share/pi2d/web/dist`), `GET /api/v1/health` (`static` ok), `pi2 doctor` (bundled runtime
|
||||
reports ok, no node failure), `pi2 install-service --dry-run` (`ExecStart` contains no
|
||||
`node` or `pi2.js`), and clean `SIGTERM` cleanup.
|
||||
|
||||
## 3. Running the daemon
|
||||
|
||||
@@ -75,10 +106,10 @@ is no detaching mode; that is what the systemd/launchd units below rely on.
|
||||
`pi2 daemon --version` prints `pi2 <version>`, and an unknown daemon positional
|
||||
exits `2` without starting anything.
|
||||
|
||||
Exactly one line goes to **stdout**:
|
||||
Exactly one line goes to **stdout** (the host in that line is the configured bind, so a wildcard bind prints `0.0.0.0`):
|
||||
|
||||
```
|
||||
pi2 daemon listening on http://127.0.0.1:7676
|
||||
pi2 daemon listening on http://0.0.0.0:7676
|
||||
```
|
||||
|
||||
Every log record is JSONL on **stderr** (that is what systemd/launchd capture).
|
||||
@@ -89,7 +120,7 @@ Flags (`pi2 daemon [start] …`):
|
||||
| Flag | Meaning |
|
||||
|---|---|
|
||||
| `--port <n>`, `-p <n>` | TCP port; `0` = ephemeral (the real port lands in `daemon.json`) |
|
||||
| `--host <addr>` | bind address (default `127.0.0.1`) |
|
||||
| `--host <addr>` | bind address (default `0.0.0.0` (all interfaces)) |
|
||||
| `--static-dir <p>` | built web UI directory |
|
||||
| `--force`, `-f` | take the lock even if another `pi2 daemon` holds it |
|
||||
| `--foreground` | stay attached to the terminal (default; used by unit files) |
|
||||
@@ -104,6 +135,25 @@ unix socket → listen (with port retry) → write `daemon.json` → print the l
|
||||
The token is rotated only by the process that owns the lock, so a rejected
|
||||
second daemon cannot invalidate the running one.
|
||||
|
||||
### Install shape and asset resolution
|
||||
|
||||
`pi2` runs in two shapes (see [ADR 0002](adr/0002-install-and-run.md)):
|
||||
1. **npm / Node package**: executed via Node (`node …/dist/cli/pi2.js`), where assets sit
|
||||
next to the source tree.
|
||||
2. **Compiled single binary**: compiled via Bun (`bun build --compile`) and installed as
|
||||
`<prefix>/bin/pi2` with assets at `<prefix>/share/pi2d/web/dist`.
|
||||
|
||||
How `pi2` discovers its own version and web UI (`src/core/install.ts`):
|
||||
- **Version**: build-time define (`PI2_BUILD_VERSION`, injected by `scripts/build-binary.sh`)
|
||||
→ on-disk `package.json` (`../../package.json` next to `dist/cli/` for npm/dev checkout)
|
||||
→ `0.0.0` (`UNKNOWN_VERSION`).
|
||||
- **Static UI directory** (`defaultStaticDir()`): probed in order, first with `index.html` wins:
|
||||
1. `<exe>/../share/pi2d/web/dist` — release layout: `<prefix>/bin/pi2` plus
|
||||
`<prefix>/share/pi2d/web/dist` (what the curl installer, Homebrew tap, and AUR `-bin` package install)
|
||||
2. `<exe>/web/dist` — portable unpacked directory (`pi2` next to its UI)
|
||||
3. `<repo>/web/dist` — npm install or dev checkout relative to module location
|
||||
- **Environment override**: `PI2_STATIC_DIR` still wins over all candidate paths when set.
|
||||
|
||||
## 4. Configuration
|
||||
|
||||
Everything is environment-driven (`src/config.ts` + `src/core/paths.ts`):
|
||||
@@ -114,7 +164,7 @@ Everything is environment-driven (`src/config.ts` + `src/core/paths.ts`):
|
||||
| `PI2_HOST` | `0.0.0.0` | bind address (all interfaces); set `127.0.0.1` for a loopback-only daemon |
|
||||
| `PI2_PUBLIC_URL` | – | external base URL, e.g. `https://myhost.tail1234.ts.net` (no trailing slash) |
|
||||
| `PI2_ORIGINS` | – | **extra** CORS/Origin allowlist entries (comma separated), added to the derived origins |
|
||||
| `PI2_STATIC_DIR` | `<repo>/web/dist` | built web UI |
|
||||
| `PI2_STATIC_DIR` | install layout (`<prefix>/share/pi2d/web/dist` for a compiled binary, `web/dist` for an npm/dev checkout), resolved by `src/core/install.ts` | built web UI (`PI2_STATIC_DIR` overrides it) |
|
||||
| `PI2_RUNTIME_DIR` | Linux `$XDG_RUNTIME_DIR/pi2`, macOS `~/Library/Caches/pi2/run` | sockets, lock, tokens |
|
||||
| `PI2_DATA_DIR` | Linux `$XDG_DATA_HOME/pi2`, macOS `~/Library/Application Support/pi2` | `devices.json`, `workspaces.json` |
|
||||
| `PI2_STATE_DIR` | Linux `$XDG_STATE_HOME/pi2`, macOS `~/Library/Logs/pi2` | instance logs |
|
||||
@@ -127,10 +177,30 @@ Everything is environment-driven (`src/config.ts` + `src/core/paths.ts`):
|
||||
| `PI2_PLUGIN_DIR` | `~/.local/share/nvim/lazy/pi2.nvim` | plugin location for `pi2 doctor` |
|
||||
| `PI2_NVIM_BIN` | `nvim` | binary used for managed instances |
|
||||
| `PI2_NVIM_INIT` | – | extra `-u <init>` for managed instances |
|
||||
| `PI2_CODING_AGENT_DIR` | `~/.pi/agent` | pi session storage (discovery) |
|
||||
| `PI2_CODING_AGENT_DIR`, falling back to `PI_CODING_AGENT_DIR` | `~/.pi/agent` | pi session storage (discovery) |
|
||||
|
||||
There is no config file: the environment *is* the configuration.
|
||||
|
||||
### Service environment file (`~/.config/pi2/env`)
|
||||
|
||||
For background services, the systemd unit automatically includes:
|
||||
```ini
|
||||
EnvironmentFile=-%h/.config/pi2/env
|
||||
```
|
||||
The leading `-` instructs systemd to ignore the file if it does not exist (missing is fine).
|
||||
|
||||
Example `~/.config/pi2/env`:
|
||||
```sh
|
||||
PI2_HOST=127.0.0.1
|
||||
PI2_PORT=7676
|
||||
PI2_PUBLIC_URL=https://myhost.tail1234.ts.net
|
||||
PI2_WORKSPACE_ROOTS=/home/user/Workspace,/home/user/Projects
|
||||
```
|
||||
Set permissions to `0600` (`chmod 0600 ~/.config/pi2/env`) to protect tokens or sensitive paths.
|
||||
Note that macOS `launchd` has no direct `EnvironmentFile` equivalent (`ServicePaths.envFile` is
|
||||
ignored on Darwin); configure environment variables in `launchd` via the plist's
|
||||
`EnvironmentVariables` dictionary or shell environment.
|
||||
|
||||
### Workspace list (noise policy)
|
||||
|
||||
`GET /api/v1/workspaces` always returns **every** known workspace, so
|
||||
@@ -224,8 +294,9 @@ overwritten on the next start.
|
||||
|
||||
Two token kinds:
|
||||
|
||||
1. **Device tokens** (paired phones/laptops): created by `POST /api/v1/pair`
|
||||
(redeem) or `pair.create`; only SHA-256 hashes are stored in
|
||||
1. **Device tokens** (paired phones/laptops): created by `POST /api/v1/pair/redeem`
|
||||
(mint is authenticated `POST /api/v1/pair`, redemption is public
|
||||
`POST /api/v1/pair/redeem`) or `pair.create`; only SHA-256 hashes are stored in
|
||||
`PI2_DATA_DIR/devices.json`.
|
||||
2. **Local CLI token**: `PI2_RUNTIME_DIR/cli.token`, minted by `pi2 daemon` on
|
||||
each start. Any request carrying it authenticates as the synthetic device
|
||||
@@ -321,7 +392,7 @@ object `{daemon, instances, resources, health}`.
|
||||
|
||||
| Check | Fails when | Warns when |
|
||||
|---|---|---|
|
||||
| `node` | < 22 | – |
|
||||
| `node` | < 20 (npm/Node install) | – (compiled binary reports `bundled bun <ver> — bundled runtime, no separate node needed`) |
|
||||
| `nvim` | missing, or < 0.9 | version unparsable |
|
||||
| `pi` | – | not on `PATH` |
|
||||
| `curl` | – | missing → `not found on PATH (:PiWeb cannot sign the browser in automatically; pair instead)`; present but unparsable → `could not parse version of <path>` |
|
||||
@@ -412,7 +483,7 @@ systemctl --user daemon-reload
|
||||
systemctl --user enable --now pi2.service
|
||||
```
|
||||
|
||||
The unit is rendered with absolute paths:
|
||||
The unit is rendered with absolute paths and supports both install shapes:
|
||||
|
||||
```ini
|
||||
[Unit]
|
||||
@@ -421,7 +492,11 @@ After=network.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
ExecStart=/usr/bin/node /repo/dist/cli/pi2.js daemon --foreground
|
||||
# For a compiled binary install:
|
||||
ExecStart=/home/user/.local/lib/pi2d/bin/pi2 daemon --foreground
|
||||
# Or for an npm / Node install:
|
||||
# ExecStart=/usr/bin/node /repo/dist/cli/pi2.js daemon --foreground
|
||||
EnvironmentFile=-%h/.config/pi2/env
|
||||
Environment=PATH=/usr/local/bin:/usr/bin:/bin
|
||||
Restart=on-failure
|
||||
RestartSec=2
|
||||
@@ -432,17 +507,26 @@ TimeoutStopSec=15
|
||||
WantedBy=default.target
|
||||
```
|
||||
|
||||
The `ExecStart` line adapts automatically to how `pi2` was invoked:
|
||||
- **Compiled binary install**: `<prefix>/bin/pi2 daemon --foreground` (invokes the compiled executable directly).
|
||||
- **npm / Node install**: `<nodePath> <scriptPath> daemon --foreground` (e.g. `/usr/bin/node /repo/dist/cli/pi2.js daemon --foreground`).
|
||||
|
||||
The unit includes `EnvironmentFile=-%h/.config/pi2/env`, where the leading `-` tells systemd that a missing file is completely fine.
|
||||
|
||||
`XDG_CONFIG_HOME` is honoured for the target directory. On macOS the same
|
||||
command writes `~/Library/LaunchAgents/com.pi2.daemon.plist` (`RunAtLoad`,
|
||||
`KeepAlive`, absolute node + script paths, `ProgramArguments`
|
||||
`node /repo/dist/cli/pi2.js daemon --foreground`, `StandardOutPath`/
|
||||
`StandardErrorPath` under `PI2_STATE_DIR`) and prints:
|
||||
`KeepAlive`, absolute binary or node + script paths in `ProgramArguments`,
|
||||
`StandardOutPath`/`StandardErrorPath` under `PI2_STATE_DIR`) and prints:
|
||||
|
||||
```bash
|
||||
launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.pi2.daemon.plist
|
||||
launchctl enable gui/$(id -u)/com.pi2.daemon
|
||||
```
|
||||
|
||||
Note: `launchd` on macOS has no direct equivalent for systemd's `EnvironmentFile=`.
|
||||
Environment variables on macOS must be set in the plist `EnvironmentVariables` dictionary
|
||||
or via shell environment.
|
||||
|
||||
`uninstall-service --write` removes the file and prints the disable commands.
|
||||
For a login-less service to keep running on Linux enable linger
|
||||
(`loginctl enable-linger $USER`, `pi2 doctor` warns when it is off).
|
||||
@@ -503,13 +587,15 @@ debugging.
|
||||
| `pi2: another pi2 daemon is running (pid …)` | a live daemon owns this runtime dir. Stop it, or `--force` |
|
||||
| `pi2: no running pi2 daemon (…/daemon.json missing)` | daemon not started, or started with a different `PI2_RUNTIME_DIR` |
|
||||
| `pi2: missing CLI token (…/cli.token)` | token deleted or daemon restarted; restart `pi2 daemon` |
|
||||
| `pi2 --version prints 0.0.0` | compiled binary built without injected version define; rebuild with `scripts/build-binary.sh` (or `pnpm build:binary`) |
|
||||
| `401 E_UNAUTHORIZED` from `curl` | send `Authorization: Bearer $(cat $PI2_RUNTIME_DIR/cli.token)` |
|
||||
| `EADDRINUSE` on an explicit port | pick another `--port` (only the default port retries) |
|
||||
| `403` with the browser console | origin not in `PI2_ORIGINS` (derived from the port) |
|
||||
| `pi2 open` → `403 console login is loopback-only` | the request came from a non-loopback address; pair the device instead |
|
||||
| `pi2 doctor` → `bind warn` | the daemon listens on a non-loopback address without TLS; that is the default posture — pair each device, or set `PI2_HOST=127.0.0.1` / `PI2_PUBLIC_URL=https://…` |
|
||||
| `health: static=FAIL` | `web/dist` missing — build the web UI or set `PI2_STATIC_DIR` |
|
||||
| `health: static=FAIL` / UI 404 | web assets not found next to binary (expected at `<exe>/../share/pi2d/web/dist`) or `<repo>/web/dist` missing — reinstall release tarball, build web UI, or set `PI2_STATIC_DIR` |
|
||||
| Browser console loads but no workspaces | no nvim with the plugin has connected yet; run `pi2 attach` in a project |
|
||||
| `pi2 doctor` → `plugin FAIL` | install pi2.nvim, or point `PI2_PLUGIN_DIR` at the checkout |
|
||||
| `pi2 doctor` → `linger warn` | services stop at logout; `loginctl enable-linger $USER` |
|
||||
| unit points at a node path that no longer exists | mise/nvm/fnm or system Node upgrade changed the binary path; re-run `pi2 install-service --write && systemctl --user daemon-reload` |
|
||||
| Instances gone after a wifi/laptop sleep | daemon restarted: nvim reconnects automatically; check `pi2 status` |
|
||||
+404
@@ -0,0 +1,404 @@
|
||||
# Installation & Run Guide
|
||||
|
||||
`pi2d` follows a **CLI-first architecture** ([ADR 0002](adr/0002-install-and-run.md)): install the `pi2` CLI on your machine, optionally run it as a persistent user service, and let editor plugins (like [pi2.nvim](https://github.com/zgs225/pi2.nvim)) connect as clients.
|
||||
|
||||
This document is the canonical reference for installing, running, configuring, upgrading, and troubleshooting `pi2d`.
|
||||
|
||||
---
|
||||
|
||||
## Decision table
|
||||
|
||||
Find your situation in the table below to choose the right installation command and run model:
|
||||
|
||||
| Situation | Recommended Command | What it gives you |
|
||||
|---|---|---|
|
||||
| **I have Node 20+** | `npm i -g @yuez/pi2d`<br>*(or `pnpm add -g`, `bun add -g`, `mise use -g npm:@yuez/pi2d`)* | The `pi2` CLI running directly on your existing Node.js environment, updated via standard package manager commands. |
|
||||
| **no Node / old Node** | `curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh \| sh` | Standalone compiled binary in `~/.local/lib/pi2d` symlinked to `~/.local/bin/pi2`. Requires zero Node/npm dependencies and no root access. |
|
||||
| **macOS** | `brew install zgs225/tap/pi2d`<br>*(or the curl installer)* | Native Homebrew formula. Places `pi2` in `$(brew --prefix)/bin` and web assets in `$(brew --prefix)/share/pi2d/web/dist`. |
|
||||
| **Arch / EndeavourOS** | `paru -S pi2d-bin`<br>*(or `yay -S pi2d-bin`)* | Native Arch package managed by pacman. Binary in `/usr/bin/pi2`, web assets in `/usr/share/pi2d/web/dist`. |
|
||||
| **NixOS** | `curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh \| sh`<br>*(or dev checkout)* | Standalone binary in user home (`~/.local/bin/pi2`). Bun's `-musl` binaries are dynamically linked against the musl loader, so running a prebuilt binary on NixOS needs `nix-ld` (or an FHS env / `steam-run`-style wrapper). |
|
||||
| **I want it to survive reboot and logout** | `pi2 install-service --write`<br>`systemctl --user enable --now pi2.service`<br>`loginctl enable-linger $USER` | Background systemd user service (or launchd on macOS) that starts at boot and stays alive when SSH sessions disconnect. |
|
||||
| **I only want to try it** | Install via curl or npm, then run:<br>`pi2 daemon` | Foreground daemon in your current terminal. Logs stream to stdout/stderr. Stop anytime with `Ctrl-C` or `pi2 stop`. |
|
||||
| **I develop pi2d itself** | `git clone https://github.com/zgs225/pi2d.git`<br>`pnpm install && pnpm --dir web install` | Source checkout with hot-reloading backend (`pnpm dev`) and Vite dev server (`pnpm --dir web dev`). |
|
||||
|
||||
---
|
||||
|
||||
## Install channels
|
||||
|
||||
`pi2d` distributes through three primary channels:
|
||||
|
||||
### Channel A: Global package manager (Node >= 20)
|
||||
|
||||
Best when your workstation or server already has Node.js (version 20 or later) installed.
|
||||
|
||||
```bash
|
||||
# npm
|
||||
npm i -g @yuez/pi2d
|
||||
|
||||
# pnpm
|
||||
pnpm add -g @yuez/pi2d
|
||||
|
||||
# bun
|
||||
bun add -g @yuez/pi2d
|
||||
|
||||
# mise
|
||||
mise use -g npm:@yuez/pi2d
|
||||
```
|
||||
|
||||
**Where files land**:
|
||||
- Executable binary: `$(npm config get prefix)/bin/pi2`
|
||||
- Node package & web assets: `$(npm config get prefix)/lib/node_modules/@yuez/pi2d/` (with web assets in `web/dist/`)
|
||||
|
||||
---
|
||||
|
||||
### Channel B: Standalone curl installer (no Node required)
|
||||
|
||||
Best for systems with no Node runtime, machines with older distributions (such as Debian 12 shipping Node 18), or environments where you do not want to manage global npm packages.
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh | sh
|
||||
```
|
||||
|
||||
The script automatically detects OS (`linux`, `darwin`), architecture (`x64`, `arm64`), and C library (`glibc`, `musl`). It downloads the corresponding precompiled standalone archive from GitHub Releases, verifies its SHA256 checksum, and extracts it with zero root privileges needed.
|
||||
|
||||
**Where files land**:
|
||||
- Base directory: `~/.local/lib/pi2d/`
|
||||
- `~/.local/lib/pi2d/bin/pi2` (the compiled binary)
|
||||
- `~/.local/lib/pi2d/share/pi2d/web/dist/` (the web console UI assets)
|
||||
- `~/.local/lib/pi2d/LICENSE`
|
||||
- Symlink: `~/.local/bin/pi2` points to `~/.local/lib/pi2d/bin/pi2`
|
||||
|
||||
Ensure `~/.local/bin` is in your `$PATH` (e.g. in your `~/.bashrc` or `~/.zshrc`):
|
||||
```bash
|
||||
export PATH="$HOME/.local/bin:$PATH"
|
||||
```
|
||||
|
||||
#### Installer environment knobs
|
||||
|
||||
You can customize the installer behavior using environment variables:
|
||||
|
||||
| Variable | Default | Purpose |
|
||||
|---|---|---|
|
||||
| `PI2_VERSION` | latest GitHub release | Release version tag to install (e.g. `0.1.6`) |
|
||||
| `PI2_INSTALL_DIR` | `$HOME/.local/lib/pi2d` | Directory where the binary and web bundle are extracted |
|
||||
| `PI2_BIN_DIR` | `$HOME/.local/bin` | Directory where the `pi2` executable symlink is created |
|
||||
| `PI2_ARCHIVE` | unset | Path to a local `.tar.gz` archive (skips network download) |
|
||||
| `PI2_SKIP_CHECKSUM` | `0` | Set to `1` to bypass SHA256 checksum verification |
|
||||
| `PI2_BASE_URL` | GitHub releases URL | Override download mirror or release asset base URL |
|
||||
| `PI2_CHECKSUM_FILE` | unset | Explicit path to a local `SHA256SUMS` file |
|
||||
|
||||
Example installing a specific version to a custom prefix:
|
||||
```bash
|
||||
PI2_VERSION=0.1.6 PI2_BIN_DIR=/usr/local/bin PI2_INSTALL_DIR=/usr/local/lib/pi2d curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh | sh
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Channel C: System packages (Homebrew & AUR)
|
||||
|
||||
*(Note: These channels are available once the release publishing compiled binaries has shipped).*
|
||||
|
||||
#### macOS / Linux (Homebrew Tap)
|
||||
```bash
|
||||
brew install zgs225/tap/pi2d
|
||||
```
|
||||
- Executable: `$(brew --prefix)/bin/pi2`
|
||||
- UI Assets: `$(brew --prefix)/share/pi2d/web/dist`
|
||||
|
||||
#### Arch Linux / Manjaro / EndeavourOS (AUR)
|
||||
```bash
|
||||
paru -S pi2d-bin
|
||||
# or:
|
||||
yay -S pi2d-bin
|
||||
```
|
||||
- Executable: `/usr/bin/pi2`
|
||||
- UI Assets: `/usr/share/pi2d/web/dist`
|
||||
|
||||
---
|
||||
|
||||
## Run modes
|
||||
|
||||
`pi2` is the CLI; `pi2 daemon` is the long-lived HTTP/WS gateway. Three run modes are supported:
|
||||
|
||||
### 1. User service (recommended)
|
||||
|
||||
Running `pi2` as a background user service is the recommended default. Because `pi2d` provides a web console with pairing links, QR codes, and remote device tokens, having the URL always reachable across editor sessions and reboots gives the best experience.
|
||||
|
||||
#### Rendering and writing the service
|
||||
|
||||
Run `pi2 install-service` to render the platform-appropriate service file:
|
||||
|
||||
```bash
|
||||
# Preview what will be installed
|
||||
pi2 install-service --dry-run
|
||||
|
||||
# Write the service file
|
||||
pi2 install-service --write
|
||||
```
|
||||
|
||||
The CLI inspects how it was installed:
|
||||
- If running as a standalone compiled binary, `ExecStart` directly executes the binary (e.g. `/home/user/.local/lib/pi2d/bin/pi2 daemon --foreground`).
|
||||
- If running via Node, `ExecStart` points to `<node> <scriptPath> daemon --foreground`.
|
||||
|
||||
#### Linux (`systemd --user`)
|
||||
|
||||
`pi2 install-service --write` creates `~/.config/systemd/user/pi2.service`.
|
||||
|
||||
1. **Enable and start the service**:
|
||||
```bash
|
||||
systemctl --user daemon-reload
|
||||
systemctl --user enable --now pi2.service
|
||||
```
|
||||
|
||||
2. **Enable lingering across logout**:
|
||||
On systemd-based distributions, user managers and their services terminate when the user's last session (desktop login or SSH session) closes. To keep `pi2.service` running 24/7 on servers or remote workstations:
|
||||
```bash
|
||||
loginctl enable-linger $USER
|
||||
```
|
||||
*(Check linger status anytime with `loginctl show-user $USER --property=Linger` or `pi2 doctor`.)*
|
||||
|
||||
3. **View logs**:
|
||||
```bash
|
||||
journalctl --user -u pi2.service -f
|
||||
```
|
||||
|
||||
4. **Service control**:
|
||||
```bash
|
||||
systemctl --user status pi2.service # check status
|
||||
systemctl --user restart pi2.service # restart daemon
|
||||
systemctl --user stop pi2.service # stop daemon
|
||||
```
|
||||
|
||||
> **Important**: When running under systemd with `Restart=on-failure`, do **not** use `:PiWebStop` inside Neovim or process kill signals to shut down the daemon. Always use `systemctl --user stop pi2.service` so systemd does not interpret the shutdown as a failure and immediately restart it.
|
||||
|
||||
#### macOS (`launchd`)
|
||||
|
||||
`pi2 install-service --write` creates `~/Library/LaunchAgents/com.pi2.daemon.plist`.
|
||||
|
||||
1. **Bootstrap and start the agent**:
|
||||
```bash
|
||||
launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.pi2.daemon.plist
|
||||
launchctl enable gui/$(id -u)/com.pi2.daemon
|
||||
launchctl kickstart -k gui/$(id -u)/com.pi2.daemon
|
||||
```
|
||||
|
||||
2. **View logs**:
|
||||
Logs are configured directly in the plist:
|
||||
- Standard output: `~/Library/Logs/pi2/pi2-daemon.log`
|
||||
- Standard error: `~/Library/Logs/pi2/pi2-daemon.err.log`
|
||||
```bash
|
||||
tail -f ~/Library/Logs/pi2/pi2-daemon.log
|
||||
```
|
||||
|
||||
3. **Stop or unload the agent**:
|
||||
```bash
|
||||
launchctl bootout gui/$(id -u)/com.pi2.daemon
|
||||
```
|
||||
|
||||
#### Removing the service
|
||||
|
||||
To remove the installed service unit from either platform:
|
||||
```bash
|
||||
pi2 uninstall-service --write
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. Foreground process
|
||||
|
||||
For quick evaluation, local experiments, or debugging, run the daemon directly in a terminal:
|
||||
|
||||
```bash
|
||||
pi2 daemon
|
||||
```
|
||||
|
||||
- Output logs stream in real-time to stdout/stderr.
|
||||
- In another terminal, open the console signed in:
|
||||
```bash
|
||||
pi2 open
|
||||
```
|
||||
- Stop the foreground daemon with `Ctrl-C` in its terminal, or from any shell via:
|
||||
```bash
|
||||
pi2 stop
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3. Neovim plugin autostart (lazy spawn)
|
||||
|
||||
If you prefer not to keep a continuous daemon running, the Neovim plugin can start it on demand.
|
||||
|
||||
Configure pi2.nvim:
|
||||
```lua
|
||||
require("pi").setup({
|
||||
web = {
|
||||
autostart = "spawn", -- or "auto" (default: checks service first, then spawns)
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
When you run `:PiWeb`, the plugin discovers `pi2` on `$PATH`, spawns a detached `pi2 daemon` process, and monitors its health.
|
||||
- Logs are written to `$PI2_STATE_DIR/daemon.log` (`~/.local/state/pi2/daemon.log` on Linux, `~/Library/Logs/pi2/daemon.log` on macOS).
|
||||
- Stop the spawned daemon with `:PiWebStop` in Neovim or `pi2 stop` from your terminal.
|
||||
|
||||
---
|
||||
|
||||
## Configuration
|
||||
|
||||
Daemon configuration is **strictly environment-only** ([ADR 0002](adr/0002-install-and-run.md)). There is no configuration file parser, complex precedence hierarchy, or file drift.
|
||||
|
||||
When running as a systemd user service, the generated unit includes:
|
||||
```ini
|
||||
EnvironmentFile=-%h/.config/pi2/env
|
||||
```
|
||||
The leading `-` prefix instructs systemd to ignore the file if it does not exist. Creating this file allows you to configure your daemon persistently without editing the service unit.
|
||||
|
||||
### Example `~/.config/pi2/env`
|
||||
|
||||
Create `~/.config/pi2/env`:
|
||||
|
||||
```bash
|
||||
# ~/.config/pi2/env — Environment configuration for pi2 daemon
|
||||
|
||||
# Port to bind (default: 7676)
|
||||
PI2_PORT=7676
|
||||
|
||||
# Network interface bind address:
|
||||
# 0.0.0.0 = bind all interfaces (default; allows LAN / phone pairing)
|
||||
# 127.0.0.1 = loopback only (local machine only)
|
||||
PI2_HOST=0.0.0.0
|
||||
|
||||
# Public URL when accessed through a reverse proxy or Tailscale Serve:
|
||||
# PI2_PUBLIC_URL=https://laptop.tail1234.ts.net
|
||||
|
||||
# Allowed workspace root directories (comma-separated):
|
||||
# PI2_WORKSPACE_ROOTS=/home/user/workspace,/home/user/projects
|
||||
|
||||
# Logging verbosity: trace | debug | info | warn | error (default: info)
|
||||
PI2_LOG_LEVEL=info
|
||||
|
||||
# Custom directory overrides (optional, default to standard XDG paths):
|
||||
# PI2_RUNTIME_DIR=/run/user/1000/pi2
|
||||
# PI2_STATE_DIR=/home/user/.local/state/pi2
|
||||
# PI2_DATA_DIR=/home/user/.local/share/pi2
|
||||
```
|
||||
|
||||
After editing `~/.config/pi2/env`, restart the systemd service:
|
||||
```bash
|
||||
systemctl --user restart pi2.service
|
||||
```
|
||||
|
||||
*(On macOS, since launchd lacks an `EnvironmentFile` directive, set system environment variables or pass custom values when rendering via `pi2 install-service`).*
|
||||
|
||||
---
|
||||
|
||||
## Upgrading and uninstalling
|
||||
|
||||
### Upgrade per channel
|
||||
|
||||
- **Channel A (npm / pnpm / bun / mise)**:
|
||||
```bash
|
||||
npm i -g @yuez/pi2d@latest
|
||||
# or:
|
||||
pnpm add -g @yuez/pi2d@latest
|
||||
bun add -g @yuez/pi2d@latest
|
||||
mise use -g npm:@yuez/pi2d@latest
|
||||
```
|
||||
|
||||
- **Channel B (Standalone curl installer)**:
|
||||
Re-run the installer. It replaces the binary and assets cleanly in `~/.local/lib/pi2d`:
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh | sh
|
||||
```
|
||||
|
||||
- **Channel C (Homebrew)**:
|
||||
```bash
|
||||
brew update && brew upgrade pi2d
|
||||
```
|
||||
|
||||
- **Channel C (Arch AUR)**:
|
||||
```bash
|
||||
paru -Syu pi2d-bin
|
||||
# or:
|
||||
yay -Syu pi2d-bin
|
||||
```
|
||||
|
||||
### Uninstall per channel
|
||||
|
||||
- **Channel A (npm / pnpm / bun)**:
|
||||
```bash
|
||||
npm rm -g @yuez/pi2d
|
||||
# or: pnpm rm -g @yuez/pi2d / bun rm -g @yuez/pi2d
|
||||
```
|
||||
|
||||
- **Channel B (curl installer)**:
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh | sh -s -- --uninstall
|
||||
```
|
||||
*(Or manually delete `rm -rf ~/.local/lib/pi2d ~/.local/bin/pi2`)*.
|
||||
|
||||
- **Channel C (Homebrew)**:
|
||||
```bash
|
||||
brew uninstall pi2d
|
||||
```
|
||||
|
||||
- **Channel C (Arch AUR)**:
|
||||
```bash
|
||||
sudo pacman -R pi2d-bin
|
||||
```
|
||||
|
||||
If you configured a user service, remember to remove it before uninstalling the binary:
|
||||
```bash
|
||||
pi2 uninstall-service --write
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Verifying your installation
|
||||
|
||||
Use these three CLI commands to verify everything is working properly:
|
||||
|
||||
### 1. Version check
|
||||
```bash
|
||||
pi2 --version
|
||||
```
|
||||
Prints the CLI version (e.g. `0.1.5`).
|
||||
|
||||
### 2. Runtime status
|
||||
```bash
|
||||
pi2 status
|
||||
```
|
||||
Shows:
|
||||
- Whether the daemon is currently running and what port/host it is bound to.
|
||||
- Connected instances (nvim instances supervised per workspace).
|
||||
- Active resource consumption (RSS, heap memory).
|
||||
- Health probes.
|
||||
|
||||
### 3. Comprehensive diagnostic (`pi2 doctor`)
|
||||
```bash
|
||||
pi2 doctor
|
||||
```
|
||||
Runs an end-to-end check of the environment and outputs a diagnostic table:
|
||||
- **node/runtime**: checks Node version (>= 20) or confirms bundled runtime (`bundled bun <version>`).
|
||||
- **nvim**: verifies Neovim >= 0.9 on `$PATH`.
|
||||
- **pi**: verifies the `pi` coding-agent CLI on `$PATH`.
|
||||
- **curl**: verifies HTTP client availability.
|
||||
- **plugin**: checks for `pi2.nvim` bridge installation in Neovim runtime paths.
|
||||
- **runtime**: checks permissions (`0700`) on `$PI2_RUNTIME_DIR`.
|
||||
- **cli-token**: checks permissions (`0600`) on admin token.
|
||||
- **socket / daemon**: checks local daemon connectivity and protocol compatibility.
|
||||
- **service-manager / linger**: reports systemd/launchd availability and whether user linger is enabled.
|
||||
- **web-dist**: verifies static web console bundle assets exist and are readable.
|
||||
|
||||
---
|
||||
|
||||
## Why `npx` is not an install path
|
||||
|
||||
In earlier versions, invoking `npx -y @yuez/pi2d@latest` was considered as an automated fallback. [ADR 0002](adr/0002-install-and-run.md) explicitly rejected this model for several critical reasons:
|
||||
|
||||
1. **Path instability**: `npx` installs packages into temporary, cache-managed paths (`~/.npm/_npx/...`). These directories are routinely evicted by npm cache sweeps or version updates, breaking long-lived processes.
|
||||
2. **Requires Node anyway**: If a machine has Node installed, `npm i -g @yuez/pi2d` takes seconds, produces a stable binary on `$PATH`, works completely offline, and does not re-query the registry. If a machine does not have Node, `npx` cannot run at all.
|
||||
3. **Unstable unit `ExecStart`**: Service managers (systemd, launchd) require an immutable, absolute executable path in `ExecStart`. Pointing a background service unit to `npx` causes network lookups at boot time, unpredictable delays, and catastrophic failure in offline environments.
|
||||
4. **Supply chain and version skew**: Running `@latest` dynamically when opening Neovim introduces network roundtrips, startup lag, and unexpected breaking updates midway through an editing session.
|
||||
|
||||
Instead, installing `pi2` once via your package manager or the standalone curl installer gives you a predictable, deterministic, and offline-capable executable.
|
||||
@@ -85,6 +85,7 @@ Plugin obligations:
|
||||
| `GET /api/v1/health` | `{ok, items:[{name, ok, detail}]}` |
|
||||
| `GET /api/v1/workspaces` | `WorkspaceInfo[]` (registry + disk index + instance state) |
|
||||
| `GET /api/v1/workspaces/:id/sessions` | relayed `workspace.query{kind:"sessions"}` (row fields below) |
|
||||
| `GET /api/v1/sessions/recent?limit=` | disk-projected recent sessions across every workspace (below); never spawns an instance |
|
||||
| `GET /api/v1/sessions/:sid/entries?before=&limit=&workspaceId=&sessionFile=` | relayed `workspace.query{kind:"entries"}`; plugin paginates |
|
||||
| `GET /api/v1/attention?workspaceId=` | pending attention for one workspace |
|
||||
| `GET /api/v1/devices` | paired devices (daemon-owned; `{id, name, kind, createdAt, lastSeenAt, revokedAt}`) |
|
||||
@@ -156,6 +157,23 @@ A client that lets the user *choose* a workspace should list only `default` rows
|
||||
default; `secondary` rows belong behind a “show hidden” toggle. Lookups by
|
||||
`workspaceId` must ignore `visibility` entirely.
|
||||
|
||||
Recent session row (`GET /api/v1/sessions/recent?limit=`): a **disk projection**, not
|
||||
session state. The daemon scans each known workspace's session directory, reads only
|
||||
session headers (id, timestamp, cwd), and sorts by file mtime. It never parses
|
||||
entries, never spawns an instance and never claims ownership of a live session. The
|
||||
console layers live names/statuses over these rows from
|
||||
`GET /api/v1/workspaces/:id/sessions` when that workspace has a connected instance.
|
||||
|
||||
| Field | Notes |
|
||||
|---|---|
|
||||
| `sessionId`, `sessionFile`, `cwd` | identity + path |
|
||||
| `workspaceId`, `workspaceName` | owning workspace, resolved from the daemon's registry/discovery |
|
||||
| `timestamp` | session start from the JSONL header (file-name fallback), epoch ms |
|
||||
| `modified` | file mtime, epoch ms — the recency sort key |
|
||||
|
||||
The `limit` defaults to 20 and is clamped to 1–200. Rows are deduped by `sessionId`
|
||||
(two encoded directories can resolve to the same cwd) and returned newest first.
|
||||
|
||||
Session row (`GET /api/v1/workspaces/:id/sessions`) — a subset of `SessionState` plus list metadata (`usage`, `flags`, `entries` and `attention` arrive via snapshot/events, not on this row):
|
||||
|
||||
| Field | Notes |
|
||||
|
||||
@@ -169,6 +169,7 @@ Everything the console calls is answered from `scripts/ui-fixtures.mjs`:
|
||||
| `POST /api/v1/pair` | `pairCode` | redeem (`{code}` → token+device) and mint (`{accepted,code,url,…}`) |
|
||||
| `GET /api/v1/workspaces` | `workspaces` | 6 rows covering staged/hidden/ghost/tmp/degraded/untrusted |
|
||||
| `GET /api/v1/workspaces/:id/sessions` | `sessions` | `{v,sessions,cursor}`; 6 sessions incl. child, attention, legacy, idle |
|
||||
| `GET /api/v1/sessions/recent` | `sessions` (disk projection) | `{v,sessions}` newest-first, used by the workspaces activity column |
|
||||
| `GET /api/v1/sessions/:sid/entries` | `entriesBySession` | raw pi entries, `before`/`limit` paging with a cursor |
|
||||
| `GET /api/v1/attention` | `attentionByWorkspace` | flattened per workspace |
|
||||
| `GET /api/v1/models` | `modelProviders` | `{providers:[…]}`, 3 providers |
|
||||
|
||||
Reference in new issue
Block a user