mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-09-30 20:49:41 +02:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c790166564 | ||
|
|
d19895651d |
@@ -1,18 +0,0 @@
|
||||
---
|
||||
"aicodeman": minor
|
||||
---
|
||||
|
||||
Add Pi (pi.dev) as a sixth CLI run mode (#206).
|
||||
|
||||
`SessionMode` gains `'pi'`, a first-class backend alongside Claude Code, OpenCode, Codex, Gemini and Antigravity: its own PTY, tmux session, rose tab identity, welcome button, run-mode entry, cron `agentType`, Docker and remote-SSH command defaults, and clone-repo Brain option.
|
||||
|
||||
- **New resolver** `src/utils/pi-cli-resolver.ts`. Unlike the sibling resolvers it sanity-probes `pi --version` and requires semver-shaped output, because `pi` is a short generic name that a stray binary on `$PATH` can shadow; the rejected path is logged. `GET /api/pi/status` returns `{ available, path, version }` so a misresolution is diagnosable.
|
||||
- **`PiConfig`** maps to `--model` (accepts `provider/id` and a `:thinking` suffix), `--provider`, `--thinking`, `--session`/`-c`, and the tri-state `--approve` / `--no-approve`. Every value is regex-allowlisted and dropped on failure. `--api-key` is deliberately never wired: it would put a provider secret on the spawn command line.
|
||||
- **No bypass flag.** Pi has no permission prompts and no sandbox, so there is no `--dangerously-skip-permissions` analog. Its privilege-shaped knob is `approveProjectTrust`, which makes pi load and execute repo-local `.pi/extensions` TypeScript and install missing project packages. `clampExternalCliBypassForOwner()` therefore puts pi in the **materialize** branch: a non-granted multi-user owner gets `--no-approve` even when no config was sent, because pi's own default is an interactive prompt the session user could answer themselves. The same materialization applies to cron-fired jobs (`clampCronExternalCliConfigs`), which carry no per-CLI config and would otherwise launch on pi's own default. Both helpers had no test coverage at all; they now do, for every CLI.
|
||||
- **Env allowlist gains only the `PI_*` prefix.** Pi's ~34 provider key vars share no prefix and `ALLOWED_ENV_PREFIXES` is one global list with no mode context, so admitting them would widen the allowlist for every mode at once. Users authenticate via pi's `/login` or the server process's own environment.
|
||||
- **Pi stays out of `isAltScreenStripMode()`.** Its default TUI renders into the main screen with terminal-owned scrollback and is mouse-aware, so it consumes `\x1b[3J` and the mouse DECSETs that the full strip removes, unlike an Ink TUI repainting in place. Note what exclusion does NOT do: pi is tmux-backed, so it still falls through to the narrow `isMuxAltScreenOnlyStripMode()` strip and its alt-screen toggles are dropped either way. Pi's runtime-switchable fullscreen TUI therefore paints into the main buffer, exactly like vim inside a tmux `shell` session.
|
||||
- **Docker**: pi installs in its own `--ignore-scripts` step so that flag cannot affect the other four CLIs, and its credentials are seeded per-file (`auth.json`, `settings.json`, `trust.json`, `models.json`, `models-store.json`) rather than whole-dir, since `~/.pi/agent` also holds sessions, extensions and installed package trees.
|
||||
- **Local echo**: pi lands on the buffer overlay. Verified that codex's per-keystroke starvation does not reproduce — pi's slash picker re-filters on the whole composer content, so a one-shot flush behaves identically to per-keystroke typing.
|
||||
- **Mode-list parity**: pi is excluded from the Ralph tracker auto-enable on `POST /api/sessions/:id/interactive` (like every other external CLI, whose output the tracker never parses), carries a `REMOTE_CLI_BIN` entry so a remote-SSH pi session reports its CLI version, and gets its own badge in the desktop home rail instead of rendering like Claude. The packaged agent skill's mode enumerations list pi too, and it now documents the per-CLI availability probes (`GET /api/<mode>/status`) that agents should check before spawning a worker on a backend the server may not have installed. Both are pinned by a new guard that derives the mode set from the Zod schema instead of restating it.
|
||||
- **`codeman doctor` and the run mode agree about pi.** The registry entry resolved a bare `which pi` while `pi-cli-resolver` demanded semver output, so the Dependencies panel could report an installed Pi CLI that sessions refuse to launch. Both now share one exported regex, and the registry's new `requireVersionMatch` reports a non-semver `pi` as missing rather than installed. Only pi sets it; every other tool keeps its existing behaviour.
|
||||
- Installer detection, docs (`docs/pi-integration.md`), READMEs, and the architecture invariants are updated. Tests: `test/pi-mode.test.ts` and `test/routes/external-cli-bypass-clamp.test.ts`, plus extensions to the run-mode, mobile-overview, render-index-html, system-routes and local-echo suites.
|
||||
@@ -80,7 +80,7 @@ CI runs `npm run check:lockfile` on every push/PR, so lockfile drift fails the b
|
||||
|
||||
Codeman is a Claude Code session manager with web interface and autonomous Ralph Loop. Spawns Claude CLI via PTY, streams via SSE, supports respawn cycling for 24+ hour autonomous runs.
|
||||
|
||||
**Tech Stack**: TypeScript (ES2022/NodeNext, strict mode), Node.js, Fastify, node-pty, xterm.js. Supports Claude Code, OpenCode, Codex (OpenAI), Gemini (Google, enterprise-only since Google's June 2026 consumer cutover), Antigravity (`agy`, Google) and Pi (pi.dev) CLIs via pluggable CLI resolvers (`SessionMode = 'claude' | 'shell' | 'opencode' | 'codex' | 'gemini' | 'antigravity' | 'pi'`).
|
||||
**Tech Stack**: TypeScript (ES2022/NodeNext, strict mode), Node.js, Fastify, node-pty, xterm.js. Supports Claude Code, OpenCode, Codex (OpenAI), Gemini (Google, enterprise-only since Google's June 2026 consumer cutover), and Antigravity (`agy`, Google) CLIs via pluggable CLI resolvers (`SessionMode = 'claude' | 'shell' | 'opencode' | 'codex' | 'gemini' | 'antigravity'`).
|
||||
|
||||
**TypeScript Strictness** (see `tsconfig.json`): `noUnusedLocals`, `noUnusedParameters`, `noImplicitReturns`, `noImplicitOverride`, `noFallthroughCasesInSwitch`, `allowUnreachableCode: false`, `allowUnusedLabels: false`.
|
||||
|
||||
@@ -124,10 +124,10 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
|
||||
- **ESM only** — Never `require()`, use `await import()`. `tsx` masks CJS/ESM issues in dev but production breaks
|
||||
- **Package ≠ product name** — npm: `aicodeman`, product: **Codeman**. Release renames tags accordingly. Both `aicodeman` and `codeman` bin aliases are installed (`package.json` `bin`)
|
||||
- **Global regex `lastIndex`** — Shared `g`-flag patterns in loops must reset `lastIndex = 0` first, or use the `execPattern()` helper in `utils/regex-patterns.ts` (resets automatically)
|
||||
- **`envOverrides` flow `CLAUDE_CODE_*` / `OPENCODE_*` / `CODEX_*` / `GEMINI_*` / `GOOGLE_*` / `ANTIGRAVITY_*` / `PI_*` env vars, plus exact-key `CLAUDE_CONFIG_DIR`** — Set via `POST /api/sessions { envOverrides }`, stored on `Session._envOverrides`, exported by `tmux-manager.buildEnvExports()` at spawn time, persisted in `SessionState.envOverrides`. **Do NOT** write these to `<case>/.claude/settings.local.json` — that's the old path and creates UI/disk drift. (`GOOGLE_*` is the deliberately-broad Vertex-AI namespace for Gemini — see Multi-CLI prefix discipline.) `CLAUDE_CONFIG_DIR` (#255, exact match via `ALLOWED_ENV_KEYS` in `schemas.ts`) points a session at a separate Claude account/config dir for per-client subscriptions; it persists to state.json (a path, not a secret; losing it on restart would silently switch accounts). ⚠️ A relocated config dir writes transcripts outside `~/.claude/projects`, so the response viewer, subagent windows, ultracode panel and Read My Mind capture go blind for that session unless the user symlinks `projects` back into the shared tree (`ln -s ~/.claude/projects <configDir>/projects`). → [architecture-invariants#per-session-env-overrides-exact-key-allowlist-and-claude_config_dir](docs/architecture-invariants.md#per-session-env-overrides-exact-key-allowlist-and-claude_config_dir)
|
||||
- **`envOverrides` flow `CLAUDE_CODE_*` / `OPENCODE_*` / `CODEX_*` / `GEMINI_*` / `GOOGLE_*` / `ANTIGRAVITY_*` env vars, plus exact-key `CLAUDE_CONFIG_DIR`** — Set via `POST /api/sessions { envOverrides }`, stored on `Session._envOverrides`, exported by `tmux-manager.buildEnvExports()` at spawn time, persisted in `SessionState.envOverrides`. **Do NOT** write these to `<case>/.claude/settings.local.json` — that's the old path and creates UI/disk drift. (`GOOGLE_*` is the deliberately-broad Vertex-AI namespace for Gemini — see Multi-CLI prefix discipline.) `CLAUDE_CONFIG_DIR` (#255, exact match via `ALLOWED_ENV_KEYS` in `schemas.ts`) points a session at a separate Claude account/config dir for per-client subscriptions; it persists to state.json (a path, not a secret; losing it on restart would silently switch accounts). ⚠️ A relocated config dir writes transcripts outside `~/.claude/projects`, so the response viewer, subagent windows, ultracode panel and Read My Mind capture go blind for that session unless the user symlinks `projects` back into the shared tree (`ln -s ~/.claude/projects <configDir>/projects`). → [architecture-invariants#per-session-env-overrides-exact-key-allowlist-and-claude_config_dir](docs/architecture-invariants.md#per-session-env-overrides-exact-key-allowlist-and-claude_config_dir)
|
||||
- **Effort is NOT an env var** — never carry effort as `CLAUDE_CODE_EFFORT_LEVEL`: the env var hard-locks effort and blocks in-session `/effort` switching (incl. ultracode). It flows as the dedicated `effort` payload field → `Session._effort` → `claude --effort <level>` for regular levels incl. `max` (the settings `effortLevel` key is `enum(["low","medium","high","xhigh"]).catch(undefined)` — `max` gets SILENTLY dropped there), or `claude --settings '{"ultracode":true}'` for ultracode (rejected by `--effort`). Both are soft defaults the user can override anytime. Legacy env-var entries are auto-migrated by the Session constructor and unset from tmux sessions in `applyEnvOverrides()`. See `buildEffortCliArgs()` in `session-cli-builder.ts`, tests in `test/effort-injection.test.ts`
|
||||
- **Model choice flows via `settings.local.json`, NOT `--model` or env** — the App Settings **Claude Model** picker (`claudeModel` in `settings.json`) is read by `session-ui.js` at session create (wins over the legacy 1M-Opus toggles `opusContext1m`/`opusContext1mEnabled`), sent as the `modelOverride` payload field, and `updateCaseModel()` (`hooks-config.ts`) writes/deletes the `model` key in `<case>/.claude/settings.local.json`. This is the intended exception to the envOverrides rule above: model legitimately lives in `settings.local.json` (a soft default — in-session `/model` still works); env vars do not
|
||||
- **Multi-CLI prefix discipline** — env-var prefix is CLI-specific (`CLAUDE_CODE_*` vs `OPENCODE_*` vs `CODEX_*` vs `GEMINI_*` vs `ANTIGRAVITY_*` vs `PI_*`) and the `ALLOWED_ENV_PREFIXES` allowlist in `schemas.ts` enforces this; non-prefix exceptions are exact keys in `ALLOWED_ENV_KEYS` (currently only `CLAUDE_CONFIG_DIR`), never a widened prefix. Gemini additionally allowlists the **broad `GOOGLE_*`** namespace (intentional: Vertex AI auth needs `GOOGLE_CLOUD_PROJECT`/`GOOGLE_APPLICATION_CREDENTIALS`/`GOOGLE_GENAI_USE_VERTEXAI`; it is the loosest allowlist entry, affecting only the user's own spawned CLI). When adding a setting, decide which CLI(s) it applies to and gate the env export accordingly. Never blanket-forward all prefixes. ⚠️ Pi is the case that proves the rule: its ~34 provider keys (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `HF_TOKEN`, …) share NO prefix, and the allowlist is one GLOBAL list applied by a refine with no mode context, so admitting them for pi would widen it for every mode at once — they stay out, and pi users authenticate via `/login` or the server process's own env. Resolver design pattern: `docs/opencode-integration.md`, `docs/pi-integration.md`
|
||||
- **Multi-CLI prefix discipline** — env-var prefix is CLI-specific (`CLAUDE_CODE_*` vs `OPENCODE_*` vs `CODEX_*` vs `GEMINI_*` vs `ANTIGRAVITY_*`) and the `ALLOWED_ENV_PREFIXES` allowlist in `schemas.ts` enforces this; non-prefix exceptions are exact keys in `ALLOWED_ENV_KEYS` (currently only `CLAUDE_CONFIG_DIR`), never a widened prefix. Gemini additionally allowlists the **broad `GOOGLE_*`** namespace (intentional: Vertex AI auth needs `GOOGLE_CLOUD_PROJECT`/`GOOGLE_APPLICATION_CREDENTIALS`/`GOOGLE_GENAI_USE_VERTEXAI`; it is the loosest allowlist entry, affecting only the user's own spawned CLI). When adding a setting, decide which CLI(s) it applies to and gate the env export accordingly. Never blanket-forward all prefixes. Resolver design pattern: `docs/opencode-integration.md`
|
||||
- **Zod `.optional()` rejects `null`** — accepts `undefined` only. When the frontend builds a request body with `JSON.stringify`, an explicit `null` field is preserved on the wire and fails validation with `INVALID_INPUT`. Convert `null` → `undefined` before stringifying (e.g. `field: value ?? undefined`), or declare the schema `.nullish()`. This has caused real shipped bugs twice
|
||||
- **`xterm-zerolag-input` is single-source** — BOTH echo addons live ONLY in `packages/xterm-zerolag-input/src/`, bundled into TWO **gitignored** vendor files: `vendor/xterm-zerolag-input.js` (buffer overlay, entry `zerolag-input-addon.ts`) and `vendor/xterm-predictive-echo.js` (codex write-through, entry `predictive-echo-addon.ts`) — dev by `scripts/postinstall.js`, prod by `scripts/build.mjs`. `app.js`/terminal-ui.js only **consume** them via `new LocalEchoOverlay(terminal)` / `new PredictiveEchoOverlay(terminal)`; there is no inline copy. So: change the package source, then rerun the bundle step (`npm install` for dev, `npm run build` for prod). **Never hand-edit `app.js` for overlay behavior, and never commit the gitignored vendor bundles.** Always test on mobile after touching it. → [architecture-invariants#xterm-zerolag-input-is-single-source](docs/architecture-invariants.md#xterm-zerolag-input-is-single-source), `docs/local-echo-overlay-plan.md`
|
||||
- **Default bind is loopback-only; non-loopback without a password starts but warns** — the server defaults to `--host 127.0.0.1`. Binding non-loopback (`--host`/`-H`/`CODEMAN_HOST`) without `CODEMAN_PASSWORD` starts anyway but prints a loud warning; `--allow-unauthenticated-network` / `CODEMAN_ALLOW_UNAUTHENTICATED_NETWORK=1` acknowledges it. ⚠️ The production systemd unit passes no `--host`, so prod binds **localhost only**: reach it via `tailscale serve`/tunnel to `127.0.0.1`. A loopback bind is reachable through a same-host tunnel but NOT by a browser hitting the box's LAN IP. `install.sh` is separate and prompts for the binding (defaulting to LAN + a password), and preserves the existing binding on re-runs. → [architecture-invariants#default-bind-and-the-non-loopback-warning-path](docs/architecture-invariants.md#default-bind-and-the-non-loopback-warning-path), `docs/security-architecture.md`
|
||||
@@ -169,7 +169,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
|
||||
|
||||
**Config**: `src/config/` — 20 files, no barrel (`index.ts`) exists; import from the specific file.
|
||||
|
||||
**Utilities**: `src/utils/` — re-exported via index. Key: `CleanupManager`, `LRUMap` (⚠ NOT in the barrel — import from `./utils/lru-map.js` directly), `StaleExpirationMap`, `BufferAccumulator`, `stripAnsi`, `Debouncer`, `KeyedDebouncer`. Also: `claude-cli-resolver`/`opencode-cli-resolver`/`codex-cli-resolver`/`gemini-cli-resolver`/`antigravity-cli-resolver`/`pi-cli-resolver` (CLI path resolution; ⚠ `pi-cli-resolver` additionally version-probes the binary, since `pi` is a generic name), `string-similarity` (fuzzy matching), `regex-patterns` (ANSI/token/spinner patterns), `assertNever` (exhaustive checks), `token-validation` (auth tokens), `nice-wrapper` (process priority).
|
||||
**Utilities**: `src/utils/` — re-exported via index. Key: `CleanupManager`, `LRUMap` (⚠ NOT in the barrel — import from `./utils/lru-map.js` directly), `StaleExpirationMap`, `BufferAccumulator`, `stripAnsi`, `Debouncer`, `KeyedDebouncer`. Also: `claude-cli-resolver`/`opencode-cli-resolver`/`codex-cli-resolver`/`gemini-cli-resolver` (CLI path resolution), `string-similarity` (fuzzy matching), `regex-patterns` (ANSI/token/spinner patterns), `assertNever` (exhaustive checks), `token-validation` (auth tokens), `nice-wrapper` (process priority).
|
||||
|
||||
### Data Flow
|
||||
|
||||
@@ -200,7 +200,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
|
||||
|
||||
**Docker cases**: a case can point at a **container**, with any of the five CLI backends running inside it. Like remote-SSH this is a **LOCATION OVERLAY on cases, never a sixth `SessionMode`**. Exactly one long-lived container **per case**, shared by all its sessions, so killing a session kills only that session's in-container tmux and **never** `docker stop` while siblings remain. The workspace is a real host dir bind-mounted at the **same absolute path**, which is what keeps file-routes/watchers on real host bytes and makes the in-container transcript projHash match the host. Credentials are **seeded** (RO mount, copied into the container once) rather than shared RW, so in-container CLIs never write refreshed tokens back to the host, and bind mounts are excluded from `docker commit` so exports stay secret-free. **NEVER a create-time `-e` for secrets, NEVER `--privileged`, NEVER the docker socket.** Config drift is detected via a label hash and a drifted launch is REFUSED rather than silently launched with stale config. ⚠️ On the loopback-only prod bind a container cannot reach 127.0.0.1, so in-container hooks need `CODEMAN_DOCKER_BRIDGE_HOOKS=1`; otherwise idle detection falls back to output-based. → [architecture-invariants#docker-cases](docs/architecture-invariants.md#docker-cases), `docs/docker-cases.md` (user guide), `docs/docker-cases-plan.md` (design)
|
||||
|
||||
**External CLI modes (OpenCode, Codex, Gemini, Antigravity, Pi)**: `isExternalCliMode()` in `session.ts` gates Claude-specific behavior off (Ralph tracker, BashToolParser, token/CLI-info parsing, ❯-prompt readiness); these CLIs render their own TUIs, so readiness is output stabilization instead. All five **require tmux with no direct PTY fallback**, because secrets are injected via socket-scoped `tmux setenv` and never on the spawn command line. ⚠️ `run*()` in `session-ui.js` MUST unwrap the `{success,data}` envelope; reading the raw shape silently breaks the run. ⚠️ **Codex sessions use PREDICTIVE WRITE-THROUGH echo, never the buffer overlay** (`_localEchoPolicy` in `_updateLocalEchoState`, terminal-ui.js): codex's composer reacts per keystroke ("/" pops a live-filtering picker, arrows edit server-side state, the composer grows as it wraps), so buffer-until-Enter starved it into issues #218/#219/#220/#222 and stays disabled (`_localEchoEnabled` remains false for codex). Instead, `PredictiveEchoAddon` (separate `vendor/xterm-predictive-echo.js` bundle) paints each keystroke at the predicted cell while the wire path stays BYTE-IDENTICAL: the onData hook (`_predictHookOnData`) is a plain statement with no `return`, so control always falls through into the untouched send path — pinned by vm and E2E byte-identity tests. Predictions reconcile against the parsed buffer and only while the cursor sits on the measured composer row (`isCodexComposerRow`, `/^› /`). Codex also **drops keystrokes that share a PTY read with a bracketed paste**, so flushed text and the paste sequence must go out as separate delayed writes (mirroring the Enter branch's delayed `\r`). Tests: `test/local-echo-codex-gating.test.ts`, `test/codex-predictive-echo.test.ts` (E2E vs real codex), `packages/xterm-zerolag-input/test/codex-replay.test.ts`. ⚠️ **Pi is the opposite kind of CLI and needs the opposite instincts**: it has NO permission prompts and no sandbox, so there is no bypass flag to send and Codeman must not invent one; its privileged knob is the tri-state `approveProjectTrust` (`--approve`/`--no-approve`), which makes pi EXECUTE repo-local `.pi/extensions` TypeScript, so the multi-user clamp puts pi in the **materialize** branch (an absent config still yields `--no-approve` for a non-granted owner) and `--api-key` is never wired. Pi stays OUT of `isAltScreenStripMode()` (main-screen TUI, and its 0.84.0 fullscreen mode is runtime-switchable via `/settings`, where the alt screen is load-bearing), and lands on the `'buffer'` echo policy via the `_updateLocalEchoState` fallthrough. Pi's own tests: `test/pi-mode.test.ts`, `test/routes/external-cli-bypass-clamp.test.ts`; user guide `docs/pi-integration.md`. → [architecture-invariants#external-cli-modes-opencode-codex-gemini-antigravity-pi](docs/architecture-invariants.md#external-cli-modes-opencode-codex-gemini-antigravity-pi)
|
||||
**External CLI modes (OpenCode, Codex, Gemini, Antigravity)**: `isExternalCliMode()` in `session.ts` gates Claude-specific behavior off (Ralph tracker, BashToolParser, token/CLI-info parsing, ❯-prompt readiness); these CLIs render their own TUIs, so readiness is output stabilization instead. All four **require tmux with no direct PTY fallback**, because secrets are injected via socket-scoped `tmux setenv` and never on the spawn command line. ⚠️ `run*()` in `session-ui.js` MUST unwrap the `{success,data}` envelope; reading the raw shape silently breaks the run. ⚠️ **Codex sessions use PREDICTIVE WRITE-THROUGH echo, never the buffer overlay** (`_localEchoPolicy` in `_updateLocalEchoState`, terminal-ui.js): codex's composer reacts per keystroke ("/" pops a live-filtering picker, arrows edit server-side state, the composer grows as it wraps), so buffer-until-Enter starved it into issues #218/#219/#220/#222 and stays disabled (`_localEchoEnabled` remains false for codex). Instead, `PredictiveEchoAddon` (separate `vendor/xterm-predictive-echo.js` bundle) paints each keystroke at the predicted cell while the wire path stays BYTE-IDENTICAL: the onData hook (`_predictHookOnData`) is a plain statement with no `return`, so control always falls through into the untouched send path — pinned by vm and E2E byte-identity tests. Predictions reconcile against the parsed buffer and only while the cursor sits on the measured composer row (`isCodexComposerRow`, `/^› /`). Codex also **drops keystrokes that share a PTY read with a bracketed paste**, so flushed text and the paste sequence must go out as separate delayed writes (mirroring the Enter branch's delayed `\r`). Tests: `test/local-echo-codex-gating.test.ts`, `test/codex-predictive-echo.test.ts` (E2E vs real codex), `packages/xterm-zerolag-input/test/codex-replay.test.ts`. → [architecture-invariants#external-cli-modes-opencode-codex-gemini](docs/architecture-invariants.md#external-cli-modes-opencode-codex-gemini-antigravity)
|
||||
|
||||
**Run launch synchronization**: the Run entrypoint holds an in-flight lock and disables `#runBtn` for the whole launch (≥500ms), so a double click cannot create duplicate sessions with the same `w<n>-<case>` name. `_ensureCreatedSessionVisible()` runs before `selectSession()`, and `_onSessionCreated()` stays an idempotent upsert, so POST-first and SSE-first ordering both produce exactly one rendered tab. → [architecture-invariants#run-launch-synchronization](docs/architecture-invariants.md#run-launch-synchronization)
|
||||
|
||||
@@ -292,6 +292,8 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L
|
||||
|
||||
**Connection-loss UI** (`computeConnectionLossUi()` in constants.js, writer `_updateConnectionLossUi()` in app.js): the service worker serves the cached app shell, so an unreachable server (phone off the tailnet, VPN down, server stopped) used to render a normal-looking empty dashboard whose only tell was the 8px header dot, which reads as "no sessions", not "no connection". Two surfaces now: a full-screen **overlay** while no server state has loaded this page load (nothing behind it is worth preserving), and a non-blocking **banner** once it has (the terminal scrollback stays readable). ⚠️ A **2.5s grace** is load-bearing: a COM deploy restarts the server and SSE is back in ~200ms, and a banner on every deploy trains the user to ignore it. `navigator.onLine === false` skips the grace, since that is never a blip. Retry re-arms SSE **and** the terminal WS (`planWsReconnect` can 'give-up', and the SSE backoff caps at 30s).
|
||||
|
||||
**SSE staleness watchdog** (`computeSseStale()` in constants.js, `_checkSseStale()` + a 5s interval in app.js): an `EventSource` that stops delivering does not always error, so `onerror` never fires, the header dot stays green, and every SSE-driven surface (tab status dots, sessions created on another device, renames) freezes until the user reloads. ⚠️ The 15s server keepalive was an SSE **comment** (`:keepalive`), and comments are **invisible to `EventSource` by spec**, so there was nothing a client could observe: it is now the named `sse:heartbeat` event (`cleanupDeadClients()`, sse-stream-manager.ts), which is exactly why the frame had to change type. ⚠️ Staleness is judged **only while the status is `connected`** and the device is online; that guard is the loop breaker, since a forced `connectSSE()` leaves `connected` immediately and cannot re-fire while a reconnect is in flight. ⚠️ The liveness stamp is applied inside `addListener` itself, so every registered handler (the `_SSE_HANDLER_MAP` wrappers AND the directly-registered ones) feeds it from one place; the heartbeat's own listener is a no-op that exists **only** to be registered, since `EventSource` drops named events nobody listens for. ⚠️ The watchdog interval is cleared at the top of `connectSSE()` and nowhere else (its only teardown path); clearing it elsewhere stacks intervals. Recovery needs no new sync path: the reconnect re-runs `handleInit` → `_resetAllAppState()`. The forced reconnect logs one diagnostic line, because a middlebox that strips heartbeats presents as "silently reconnects every 45s".
|
||||
|
||||
**Z-index layers**: subagent windows (1000), plan agents (1100), mobile/tablet fixed header (1200, `mobile.css`), modals on ≤768px (1300 — must beat the fixed header or the modal close button is buried), log viewers (2000), connection-loss overlay (2500, above the fixed header and modals), image popups (3000), local echo overlay (7).
|
||||
|
||||
**Respawn presets**: `solo-work` (3s/60min), `subagent-workflow` (45s/240min), `team-lead` (90s/480min), `ralph-todo` (8s/480min), `overnight-autonomous` (10s/480min).
|
||||
@@ -320,7 +322,7 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L
|
||||
|
||||
### SSE Event Registry
|
||||
|
||||
154 event constants in `src/web/sse-events.ts` (backend) and `SSE_EVENTS` in `constants.js` (frontend). **Both must be kept in sync**, and `test/sse-registry-parity.test.ts` is the guard that pins it (currently exactly in sync, 154 = 154, no drift either direction). The backend file's `@fileoverview` carries the per-category breakdown.
|
||||
155 event constants in `src/web/sse-events.ts` (backend) and `SSE_EVENTS` in `constants.js` (frontend). **Both must be kept in sync**, and `test/sse-registry-parity.test.ts` is the guard that pins it (currently exactly in sync, 155 = 155, no drift either direction). The backend file's `@fileoverview` carries the per-category breakdown.
|
||||
|
||||
### API Routes
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<h2 align="center">Mission control for AI coding agents</h2>
|
||||
|
||||
<p align="center">
|
||||
<em>Claude Code • OpenCode • Codex • Antigravity • Gemini • Pi • Terminal - One Dashboard • Any Device</em>
|
||||
<em>Claude Code • OpenCode • Codex • Antigravity • Gemini • Terminal - One Dashboard • Any Device</em>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -27,7 +27,7 @@
|
||||
<img src="docs/images/subagent-demo-20260724.gif" alt="Codeman — parallel subagent visualization" width="900">
|
||||
</p>
|
||||
|
||||
**Codeman** is a self-hosted mission control for AI coding agents. It spawns Claude Code, OpenCode, Codex, Antigravity, Gemini, or Pi inside persistent tmux sessions, streams the real terminal to any browser, and keeps agents productive after you walk away: it re-prompts on idle, resumes when a usage limit resets, runs scheduled jobs, and shows every background agent working in real time.
|
||||
**Codeman** is a self-hosted mission control for AI coding agents. It spawns Claude Code, OpenCode, Codex, Antigravity, or Gemini CLI inside persistent tmux sessions, streams the real terminal to any browser, and keeps agents productive after you walk away: it re-prompts on idle, resumes when a usage limit resets, runs scheduled jobs, and shows every background agent working in real time.
|
||||
|
||||
Get started in one line (macOS & Linux, Windows via WSL):
|
||||
|
||||
@@ -42,7 +42,7 @@ codeman web
|
||||
|
||||
The installer asks before every system change, and re-running the same line updates in place. Full details: [Quick Start - Installation](#quick-start---installation).
|
||||
|
||||
- **One dashboard, six CLIs** - run [Claude Code, OpenCode, Codex, Antigravity, Gemini, or Pi](#more-features) per session (plus plain shell), locally, [in Docker](#isolated-docker-sessions), or [over SSH](#remote-ssh-sessions)
|
||||
- **One dashboard, five CLIs** - run [Claude Code, OpenCode, Codex, Antigravity, or Gemini](#more-features) per session (plus plain shell), locally, [in Docker](#isolated-docker-sessions), or [over SSH](#remote-ssh-sessions)
|
||||
- **Truly phone-friendly** - a [touch-optimized terminal](#mobile-optimized-web-ui) with instant local echo, QR login, swipe navigation, and push notifications
|
||||
- **Runs while you sleep** - [idle detection + respawn cycling](#respawn-controller) and auto-resume when a subscription limit resets, for 24+ hour unattended runs
|
||||
- **See your agents think** - [live floating windows](#live-agent-visualization) for every subagent and teammate, with real-time transcripts
|
||||
@@ -68,7 +68,7 @@ This installs Node.js and tmux if missing, clones Codeman to `~/.codeman/app`, a
|
||||
- **Re-run to update.** The same one-liner updates a finished install in place: local changes in `~/.codeman/app` are stashed (never discarded), and a running service is restarted and verified. If a first install was interrupted, re-running resumes the full setup instead. `install.sh update` and `install.sh uninstall` also exist.
|
||||
- **CI / headless:** without a terminal attached, steps that would change your system abort with instructions instead of running silently. Set `CODEMAN_NONINTERACTIVE=1` to approve them for automation.
|
||||
|
||||
You'll need at least one AI coding CLI installed — [Claude Code](https://docs.anthropic.com/en/docs/claude-code), [OpenCode](https://opencode.ai), [Codex](https://developers.openai.com/codex/cli), [Antigravity](https://antigravity.google), [Gemini CLI](https://github.com/google-gemini/gemini-cli), or [Pi](https://pi.dev) (any combination works; Gemini CLI is enterprise-only since Google's consumer cutover, and Antigravity is its successor). The installer detects whichever of the six is present; if none is found, it offers to install Claude Code or OpenCode, or you can skip and install one yourself later. After install:
|
||||
You'll need at least one AI coding CLI installed — [Claude Code](https://docs.anthropic.com/en/docs/claude-code), [OpenCode](https://opencode.ai), [Codex](https://developers.openai.com/codex/cli), [Antigravity](https://antigravity.google), or [Gemini CLI](https://github.com/google-gemini/gemini-cli) (any combination works; Gemini CLI is enterprise-only since Google's consumer cutover, and Antigravity is its successor). The installer detects whichever of the five is present; if none is found, it offers to install Claude Code or OpenCode, or you can skip and install one yourself later. After install:
|
||||
|
||||
```bash
|
||||
codeman web
|
||||
@@ -171,7 +171,7 @@ launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.codeman.web.plist
|
||||
wsl bash -c "curl -fsSL https://getcodeman.com/install | bash"
|
||||
```
|
||||
|
||||
Codeman requires tmux, so Windows users need [WSL](https://learn.microsoft.com/en-us/windows/wsl/install). If you don't have WSL yet: run `wsl --install` in an admin PowerShell, reboot, open Ubuntu, then install your preferred AI coding CLI inside WSL ([Claude Code](https://docs.anthropic.com/en/docs/claude-code), [OpenCode](https://opencode.ai), [Codex](https://developers.openai.com/codex/cli), [Antigravity](https://antigravity.google), [Gemini CLI](https://github.com/google-gemini/gemini-cli), or [Pi](https://pi.dev)). After installing, `http://localhost:3000` is accessible from your Windows browser.
|
||||
Codeman requires tmux, so Windows users need [WSL](https://learn.microsoft.com/en-us/windows/wsl/install). If you don't have WSL yet: run `wsl --install` in an admin PowerShell, reboot, open Ubuntu, then install your preferred AI coding CLI inside WSL ([Claude Code](https://docs.anthropic.com/en/docs/claude-code), [OpenCode](https://opencode.ai), [Codex](https://developers.openai.com/codex/cli), [Antigravity](https://antigravity.google), or [Gemini CLI](https://github.com/google-gemini/gemini-cli)). After installing, `http://localhost:3000` is accessible from your Windows browser.
|
||||
|
||||
</details>
|
||||
|
||||
@@ -253,7 +253,7 @@ Click **+ New Session** (or **Quick Start**). A session is one AI CLI running in
|
||||
| Field | What it does |
|
||||
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------- |
|
||||
| **Working directory / case** | The folder the agent operates in. A "case" is just a named working dir Codeman remembers. **Add Case** creates one from scratch, links an existing folder, or clones a GitHub repo straight into one (**Clone Repo**). |
|
||||
| **CLI / run mode** | `Claude` (default), `OpenCode`, `Codex`, `Antigravity`, `Gemini`, `Pi`, or `Terminal` (plain shell). |
|
||||
| **CLI / run mode** | `Claude` (default), `OpenCode`, `Codex`, `Antigravity`, `Gemini`, or `Terminal` (plain shell). |
|
||||
| **Model** | Per-session model (App Settings → Models → New Claude sessions). A soft default — `/model` still works in-session. |
|
||||
| **Effort / Ultracode** | Reasoning effort (`low`–`max`) or `ultracode` for dynamic multi-agent workflows. Switchable anytime with `/effort`. |
|
||||
|
||||
@@ -429,7 +429,7 @@ PTY Output → 16ms Server Batch → DEC 2026 Wrap → SSE → Client rAF → xt
|
||||
- **Background daemon & service install** — `codeman web -d` runs the server detached with a pidfile, `~/.codeman/web.log`, and verified startup (it polls the server until it answers, so a port clash never reads as success); `codeman service install` writes a systemd user unit (Linux) or LaunchAgent (macOS) with your shell's PATH baked in, so an nvm or Homebrew `node`, `tmux` and `claude` are actually found. Secrets are never written into unit files
|
||||
- **Self-update** — git-clone installs under systemd/launchd update in place from **App Settings → System → Updates**: it detects the latest release, auto-stashes a dirty tree, and streams build progress across the service restart (npm installs report as non-updatable)
|
||||
- **Clone a GitHub repo as a case** — paste a repository URL into **Add Case → Clone Repo** and Codeman clones it into `~/codeman-cases/<name>` and registers it as a normal case, ready to run an agent in. It preflights the URL while you type (tells you whether it can be cloned anonymously and offers the repo's real branches and tags for the optional branch/tag field), fills the case name in from the URL, and lets you pick which CLI the Run button should use. Public repositories over `https://`; Codeman never collects or stores credentials
|
||||
- **Multi-CLI** — run **Claude Code**, **OpenCode**, **Codex**, **Antigravity**, **Gemini**, or **Pi** per session; env-var prefixes auto-gate (`CLAUDE_CODE_*` vs `OPENCODE_*` vs `CODEX_*` vs `ANTIGRAVITY_*` vs `GEMINI_*`/`GOOGLE_*` vs `PI_*`). See [`docs/opencode-integration.md`](docs/opencode-integration.md) and [`docs/pi-integration.md`](docs/pi-integration.md)
|
||||
- **Multi-CLI** — run **Claude Code**, **OpenCode**, **Codex**, **Antigravity**, or **Gemini** per session; env-var prefixes auto-gate (`CLAUDE_CODE_*` vs `OPENCODE_*` vs `CODEX_*` vs `ANTIGRAVITY_*` vs `GEMINI_*`/`GOOGLE_*`). See [`docs/opencode-integration.md`](docs/opencode-integration.md)
|
||||
- **Docker sessions** — run a case inside an isolated, hardened container. One checkbox on **Create New** spins up a container with sensible defaults and starts the agent inside it; multiple sessions share one per-case container; export a container + its workspace to a portable `.tar.gz` to move it to another machine. See [`docs/docker-cases.md`](docs/docker-cases.md)
|
||||
- **Remote SSH sessions** — point a case at another machine and run the agent there inside a durable remote tmux: survives SSH drops, auto-reconnects, and can discover + attach sessions already running on the host. See [`docs/remote-sessions.md`](docs/remote-sessions.md)
|
||||
- **Effort & Ultracode** — set a per-session default effort (`low`–`max`) or enable **ultracode** (dynamic multi-agent workflows). Soft defaults only — switchable anytime with `/effort` in-session. Extended-thinking budget is configurable too
|
||||
@@ -451,7 +451,7 @@ Run a case inside its own hardened Docker container instead of directly on your
|
||||
- **Resource templates** — expand the checkbox for a **Small / Medium / Large / GPU** preset (memory, CPUs, GPU), or set your own. **Disk is elastic** — storage grows as data flows in, no fixed cap.
|
||||
- **Shared per-case container** — many sessions can `docker exec` into the same container; killing one session never tears the container out from under the others.
|
||||
- **Hardened by default** — non-root, `--cap-drop ALL`, `no-new-privileges`, PID/memory caps, never `--privileged` or the docker socket; a **sealed** profile (no host credentials, network off) is one toggle away.
|
||||
- **Seamless auth, isolated credentials** — your host Claude / Codex / Antigravity / Gemini / OpenCode / Pi logins work inside the container out of the box: credentials are seeded (copied) in at launch and onboarding/trust prompts are pre-answered, so no login wizard appears. The container keeps its own copies and never writes back to your host credential stores; only conversation transcripts are shared, and exports never capture secrets.
|
||||
- **Seamless auth, isolated credentials** — your host Claude / Codex / Antigravity / Gemini / OpenCode logins work inside the container out of the box: credentials are seeded (copied) in at launch and onboarding/trust prompts are pre-answered, so no login wizard appears. The container keeps its own copies and never writes back to your host credential stores; only conversation transcripts are shared, and exports never capture secrets.
|
||||
- **Move it to another machine** — export a container's whole environment (toolchain + workspace) to a portable `.tar.gz`, `docker load` it on the other side, and import it into a fresh case.
|
||||
- **Durable** — reconnect after a restart lands back in the same live agent; a container stop/reboot resumes the conversation from the bind-mounted transcript.
|
||||
|
||||
@@ -996,7 +996,7 @@ flowchart TB
|
||||
end
|
||||
|
||||
subgraph External["External"]
|
||||
CLI["AI CLI<br/><small>Claude Code / OpenCode / Codex / Antigravity / Gemini / Pi</small>"]
|
||||
CLI["AI CLI<br/><small>Claude Code / OpenCode / Codex / Antigravity / Gemini</small>"]
|
||||
BG["Background Agents<br/><small>(Task tool)</small>"]
|
||||
end
|
||||
end
|
||||
|
||||
+7
-7
@@ -5,7 +5,7 @@
|
||||
<h2 align="center">AI 编程智能体的任务控制中心</h2>
|
||||
|
||||
<p align="center">
|
||||
<em>Claude Code • OpenCode • Codex • Antigravity • Gemini • Pi • 终端 —— 统一仪表盘 • 任意设备</em>
|
||||
<em>Claude Code • OpenCode • Codex • Antigravity • Gemini • 终端 —— 统一仪表盘 • 任意设备</em>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -58,7 +58,7 @@ curl -fsSL https://getcodeman.com/install | bash
|
||||
- **重跑即更新。** 再次运行同一条命令即可原地更新已完成的安装:`~/.codeman/app` 中的本地改动会被 stash(绝不丢弃),运行中的服务会自动重启并校验。若首次安装中途失败,重跑会继续完成完整的安装流程。也可以使用 `install.sh update` 与 `install.sh uninstall`。
|
||||
- **CI / 无终端环境:** 没有终端时,涉及系统改动的步骤会带着说明中止,而不是静默执行;在自动化场景设置 `CODEMAN_NONINTERACTIVE=1` 即可批准这些步骤。
|
||||
|
||||
你至少需要安装一个 AI 编程 CLI —— [Claude Code](https://docs.anthropic.com/en/docs/claude-code)、[OpenCode](https://opencode.ai)、[Codex](https://developers.openai.com/codex/cli)、[Antigravity](https://antigravity.google)、[Gemini CLI](https://github.com/google-gemini/gemini-cli) 或 [Pi](https://pi.dev)(任意组合均可;自 Google 面向消费者停售后,Gemini CLI 仅限企业版,Antigravity 是其继任者)。安装器会自动检测这六个中已安装的任意一个;若一个都没有,会提供安装 Claude Code 或 OpenCode 的选项,也可以选择跳过、稍后自行安装。安装完成后:
|
||||
你至少需要安装一个 AI 编程 CLI —— [Claude Code](https://docs.anthropic.com/en/docs/claude-code)、[OpenCode](https://opencode.ai)、[Codex](https://developers.openai.com/codex/cli)、[Antigravity](https://antigravity.google) 或 [Gemini CLI](https://github.com/google-gemini/gemini-cli)(任意组合均可;自 Google 面向消费者停售后,Gemini CLI 仅限企业版,Antigravity 是其继任者)。安装器会自动检测这五个中已安装的任意一个;若一个都没有,会提供安装 Claude Code 或 OpenCode 的选项,也可以选择跳过、稍后自行安装。安装完成后:
|
||||
|
||||
```bash
|
||||
codeman web
|
||||
@@ -141,7 +141,7 @@ launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.codeman.web.plist
|
||||
wsl bash -c "curl -fsSL https://getcodeman.com/install | bash"
|
||||
```
|
||||
|
||||
Codeman 依赖 tmux,因此 Windows 用户需要 [WSL](https://learn.microsoft.com/en-us/windows/wsl/install)。如果还没装 WSL:在管理员 PowerShell 中运行 `wsl --install`,重启,打开 Ubuntu,然后在 WSL 内安装你偏好的 AI 编程 CLI([Claude Code](https://docs.anthropic.com/en/docs/claude-code)、[OpenCode](https://opencode.ai)、[Codex](https://developers.openai.com/codex/cli)、[Antigravity](https://antigravity.google)、[Gemini CLI](https://github.com/google-gemini/gemini-cli) 或 [Pi](https://pi.dev))。安装完成后,即可从 Windows 浏览器访问 `http://localhost:3000`。
|
||||
Codeman 依赖 tmux,因此 Windows 用户需要 [WSL](https://learn.microsoft.com/en-us/windows/wsl/install)。如果还没装 WSL:在管理员 PowerShell 中运行 `wsl --install`,重启,打开 Ubuntu,然后在 WSL 内安装你偏好的 AI 编程 CLI([Claude Code](https://docs.anthropic.com/en/docs/claude-code)、[OpenCode](https://opencode.ai)、[Codex](https://developers.openai.com/codex/cli)、[Antigravity](https://antigravity.google) 或 [Gemini CLI](https://github.com/google-gemini/gemini-cli))。安装完成后,即可从 Windows 浏览器访问 `http://localhost:3000`。
|
||||
|
||||
</details>
|
||||
|
||||
@@ -221,7 +221,7 @@ codeman web -H 0.0.0.0 # 绑定局域网 —— 必须设置 CODEMAN_
|
||||
| 字段 | 作用 |
|
||||
| ---------------------- | ------------------------------------------------------------------------------------------- |
|
||||
| **工作目录 / case** | 智能体操作的文件夹。「case」就是一个 Codeman 记住的命名工作目录。 |
|
||||
| **CLI / 运行模式** | `Claude`(默认)、`OpenCode`、`Codex`、`Antigravity`、`Gemini`、`Pi` 或 `Terminal`(普通 shell)。 |
|
||||
| **CLI / 运行模式** | `Claude`(默认)、`OpenCode`、`Codex`、`Antigravity`、`Gemini` 或 `Terminal`(普通 shell)。 |
|
||||
| **模型** | 每会话模型(App Settings → Claude Model)。软默认值 —— 会话内 `/model` 依然有效。 |
|
||||
| **Effort / Ultracode** | 推理力度(`low`–`max`),或用 `ultracode` 开启动态多智能体工作流。随时可用 `/effort` 切换。 |
|
||||
|
||||
@@ -394,7 +394,7 @@ PTY 输出 → 16ms 服务端批处理 → DEC 2026 包裹 → SSE → 客户端
|
||||
## 更多特性
|
||||
|
||||
- **自更新** —— systemd/launchd 管理下的 git-clone 安装可在 **App Settings → Updates** 中原地更新:它会检测最新发行版,自动暂存(stash)脏工作树,并在服务重启期间流式展示构建进度(npm 安装会被报告为不可更新)
|
||||
- **多 CLI** —— 每个会话可选 **Claude Code**、**OpenCode**、**Codex**、**Antigravity**、**Gemini** 或 **Pi**;环境变量前缀自动隔离(`CLAUDE_CODE_*`、`OPENCODE_*`、`CODEX_*`、`ANTIGRAVITY_*`、`PI_*` 与 `GEMINI_*`/`GOOGLE_*`)。详见 [`docs/opencode-integration.md`](docs/opencode-integration.md) 与 [`docs/pi-integration.md`](docs/pi-integration.md)
|
||||
- **多 CLI** —— 每个会话可选 **Claude Code**、**OpenCode**、**Codex**、**Antigravity** 或 **Gemini**;环境变量前缀自动隔离(`CLAUDE_CODE_*`、`OPENCODE_*`、`CODEX_*`、`ANTIGRAVITY_*` 与 `GEMINI_*`/`GOOGLE_*`)。详见 [`docs/opencode-integration.md`](docs/opencode-integration.md)
|
||||
- **Docker 会话** —— 在隔离且加固的容器中运行案例。**Create New** 上勾选一个复选框即可用合理的默认值启动容器并在其中启动智能体;同一案例的多个会话共享一个容器;可将容器连同工作区导出为可移植的 `.tar.gz`,迁移到另一台机器。详见 [`docs/docker-cases.md`](docs/docker-cases.md)
|
||||
- **远程 SSH 会话**:把案例指向另一台机器,让智能体在那里一个持久的远程 tmux 中运行:SSH 断连不中断任务、自动重连,还能发现并附着主机上已在运行的会话。详见 [`docs/remote-sessions.md`](docs/remote-sessions.md)
|
||||
- **Effort 与 Ultracode** —— 设置每会话的默认 effort(`low`–`max`),或启用 **ultracode**(动态多智能体工作流)。这些都只是软默认值 —— 会话中可随时用 `/effort` 切换。扩展思考预算也可配置
|
||||
@@ -416,7 +416,7 @@ PTY 输出 → 16ms 服务端批处理 → DEC 2026 包裹 → SSE → 客户端
|
||||
- **资源模板** —— 展开复选框可选 **Small / Medium / Large / GPU** 预设(内存、CPU、GPU),也可以完全自定义。**磁盘是弹性的** —— 存储随数据增长,没有固定上限。
|
||||
- **按案例共享容器** —— 多个会话可以 `docker exec` 进同一个容器;结束某个会话绝不会影响其他会话所在的容器。
|
||||
- **默认加固** —— 非 root、`--cap-drop ALL`、`no-new-privileges`、PID/内存上限,绝不使用 `--privileged` 或 docker socket;**密封(sealed)** 配置(不注入主机凭据、关闭网络)只需一个开关。
|
||||
- **无感认证、凭据隔离** —— 主机上的 Claude / Codex / Antigravity / Gemini / OpenCode / Pi 登录在容器内开箱即用:凭据在启动时以只读种子方式复制注入,onboarding/信任提示已预先答复,不会弹出登录向导。容器保留自己的副本,绝不回写主机的凭据存储;跨边界共享的只有对话转录,导出文件也绝不包含机密。
|
||||
- **无感认证、凭据隔离** —— 主机上的 Claude / Codex / Antigravity / Gemini / OpenCode 登录在容器内开箱即用:凭据在启动时以只读种子方式复制注入,onboarding/信任提示已预先答复,不会弹出登录向导。容器保留自己的副本,绝不回写主机的凭据存储;跨边界共享的只有对话转录,导出文件也绝不包含机密。
|
||||
- **迁移到另一台机器** —— 把容器的完整环境(工具链 + 工作区)导出为可移植的 `.tar.gz`,在另一台机器上导入到新案例即可继续。
|
||||
- **持久耐用** —— Codeman 重启后重连会回到同一个存活的智能体;容器停止/重启后则从绑定挂载的转录恢复对话。
|
||||
|
||||
@@ -906,7 +906,7 @@ flowchart TB
|
||||
end
|
||||
|
||||
subgraph External["外部"]
|
||||
CLI["AI CLI<br/><small>Claude Code / OpenCode / Codex / Antigravity / Gemini / Pi</small>"]
|
||||
CLI["AI CLI<br/><small>Claude Code / OpenCode / Codex / Antigravity / Gemini</small>"]
|
||||
BG["后台智能体<br/><small>(Task 工具)</small>"]
|
||||
end
|
||||
end
|
||||
|
||||
+1
-10
@@ -44,13 +44,6 @@ RUN curl -fsSL https://antigravity.google/cli/install.sh | bash -s -- --dir /usr
|
||||
&& chmod 755 /usr/local/bin/agy \
|
||||
&& agy --version
|
||||
|
||||
# Pi (pi.dev). Upstream documents --ignore-scripts (pi needs no lifecycle scripts);
|
||||
# kept out of the shared npm block above so the flag cannot silently change how the
|
||||
# other four CLIs install.
|
||||
RUN npm install -g --ignore-scripts @earendil-works/pi-coding-agent \
|
||||
&& npm cache clean --force \
|
||||
&& pi --version
|
||||
|
||||
# `agent` user (gid 0) with an arbitrary-uid-writable HOME. The uid is
|
||||
# auto-assigned (node:22-slim already occupies uid 1000 with its `node` user); at
|
||||
# runtime Codeman overrides with `--user <hostUid>:0` on Linux, so the baked uid
|
||||
@@ -68,11 +61,9 @@ ENV HOME=/home/agent
|
||||
# transcript/rollout dirs (`.claude/projects`, `.codex/sessions`) are bind-mounted from
|
||||
# the host. (gemini/gcloud/opencode are whole seed-copies and need no pre-created dir;
|
||||
# Antigravity nests its state inside `.gemini/antigravity-cli`, so it rides that seed.)
|
||||
# `.pi/agent` IS pre-created: pi is seeded per-FILE (auth/settings/trust/models), and a
|
||||
# per-file seed copy, unlike a whole-dir one, does not create its parent directory.
|
||||
RUN useradd -g 0 -m -d /home/agent -s /bin/bash agent \
|
||||
&& mkdir -p /home/agent/.npm /home/agent/.cache /home/agent/.config /home/agent/.codeman \
|
||||
/home/agent/.claude/projects /home/agent/.codex/sessions /home/agent/.pi/agent \
|
||||
/home/agent/.claude/projects /home/agent/.codex/sessions \
|
||||
&& chgrp -R 0 /home/agent \
|
||||
&& chmod -R g=u /home/agent
|
||||
|
||||
|
||||
@@ -534,6 +534,29 @@ the stable contract — event names are not renamed without a major bump. An
|
||||
optional `?sessions=<id,...>` filter suppresses only the high-volume terminal
|
||||
stream; lifecycle/metadata events are delivered to all clients regardless.
|
||||
|
||||
### `sse:heartbeat` (liveness)
|
||||
|
||||
Every 15s the server writes a `sse:heartbeat` frame to every connected client:
|
||||
|
||||
```
|
||||
event: sse:heartbeat
|
||||
data: {"t":1755100000000}
|
||||
```
|
||||
|
||||
`t` is the server's epoch-ms timestamp at write time. The frame carries no
|
||||
application state and can be ignored for correctness. It exists so a client can
|
||||
tell a live stream from a dead one: an `EventSource` whose connection has been
|
||||
idle-closed by a proxy (or that resumed from sleep on a stale socket) keeps
|
||||
delivering nothing without ever firing `onerror`. Clients that care should treat
|
||||
silence longer than about three intervals as a dead stream and reconnect, which
|
||||
is what the bundled frontend does.
|
||||
|
||||
This replaced a `:keepalive` SSE **comment**, which served the same
|
||||
proxy-flushing purpose but is invisible to `EventSource` by spec and so could
|
||||
never be observed by a client. Consumers written against the old behavior are
|
||||
unaffected: `EventSource` dispatches only events that have a registered
|
||||
listener, so an unknown event name is dropped.
|
||||
|
||||
## Consuming from JavaScript
|
||||
|
||||
The bundled frontend reads responses through `_apiJson()`
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -44,9 +44,9 @@ records), kept distinct from the existing `ScheduledRun`.
|
||||
|
||||
## 2. Where agent/session types are defined
|
||||
|
||||
- `type SessionMode = 'claude' | 'shell' | 'opencode' | 'codex' | 'gemini' | 'antigravity' | 'pi'`
|
||||
- `type SessionMode = 'claude' | 'shell' | 'opencode' | 'codex' | 'gemini' | 'antigravity'`
|
||||
(`src/types/session.ts:43-44`). `shell` covers the brief's "Terminal/custom".
|
||||
- CLI availability resolvers in `src/utils/{claude,codex,gemini,antigravity,opencode,pi}-cli-resolver.ts`.
|
||||
- CLI availability resolvers in `src/utils/{claude,codex,gemini,antigravity,opencode}-cli-resolver.ts`.
|
||||
- **Integration point:** the job's `agentType` reuses `SessionMode` verbatim.
|
||||
|
||||
## 3. Where input is sent into a session
|
||||
|
||||
+1
-1
@@ -91,7 +91,7 @@ These map 1:1 to `CronJobSchema` (`src/web/schemas.ts`) and the `CronJob` type
|
||||
| Field | Required | Values / limits | Notes |
|
||||
| -------------------------- | ----------- | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `name` | ✅ | 1–200 chars | Display name; also used as the created session's name. |
|
||||
| `agentType` | ✅ | `claude` \| `shell` \| `opencode` \| `codex` \| `gemini` \| `antigravity` \| `pi` | Reuses Codeman's `SessionMode`. `shell` = a plain terminal. ⚠️ A `pi` job's readiness poll looks for `❯`/a token count, neither of which pi prints, so it burns the poll budget and then sends the prompt anyway (slower start, still works). |
|
||||
| `agentType` | ✅ | `claude` \| `shell` \| `opencode` \| `codex` \| `gemini` \| `antigravity` | Reuses Codeman's `SessionMode`. `shell` = a plain terminal. |
|
||||
| `workingDir` | ✅ | valid path (allowlist-validated) | Validated at **create/update** (must exist, be a directory, and not resolve into a blocked tree — `/etc`, `/root`, `/proc`, `/sys`, `/dev`, or `/` itself) and again **at fire time**. |
|
||||
| `launchCommand` | — | ≤ 2000 chars, single line | `shell` mode only: sent as the **first input line** once the shell is up, before the prompt. Ignored for other agent types. |
|
||||
| `promptMode` | ✅ | `inline_text` \| `prompt_file_path` | See §5. |
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
Run a case inside an **isolated Docker container** instead of directly on the host. Any number of Codeman sessions can share one container (it is scoped to the case, not the session), so a whole project lives in a sandbox with its own network, resource caps, and filesystem, and you can **export the container to move it to another machine**.
|
||||
|
||||
Docker mode is a **location overlay on cases**, the direct analog of [remote SSH cases](./remote-hosts.md): where a remote case runs a local tmux pane doing `ssh host` into a durable remote tmux server, a docker case runs a local tmux pane doing `docker exec -it` into a durable **in-container** tmux server. It is not a separate `SessionMode`, so `claude` / `shell` / `opencode` / `codex` / `gemini` / `antigravity` / `pi` all work inside the container.
|
||||
Docker mode is a **location overlay on cases**, the direct analog of [remote SSH cases](./remote-hosts.md): where a remote case runs a local tmux pane doing `ssh host` into a durable remote tmux server, a docker case runs a local tmux pane doing `docker exec -it` into a durable **in-container** tmux server. It is not a separate `SessionMode`, so `claude` / `shell` / `opencode` / `codex` / `gemini` / `antigravity` all work inside the container.
|
||||
|
||||
## One-time setup: build the base image
|
||||
|
||||
@@ -25,12 +25,10 @@ A zero exit code only proves the layers ran, not that the toolchain works. Verif
|
||||
|
||||
```bash
|
||||
docker run --rm codeman/agent:base bash -lc \
|
||||
'for c in claude codex gemini opencode agy pi; do printf "%-9s " $c; $c --version 2>&1 | head -1; done'
|
||||
'for c in claude codex gemini opencode agy; do printf "%-9s " $c; $c --version 2>&1 | head -1; done'
|
||||
```
|
||||
|
||||
Antigravity (`agy`) is the one CLI not installed from npm (Google ships a standalone binary), so it has its own Dockerfile step and adds roughly 190MB; a full image lands near 1.6GB. Pi also gets its own step, because upstream documents installing it with `--ignore-scripts` and that flag must not silently change how the other four npm CLIs install.
|
||||
|
||||
Pi's credentials are seeded per-FILE rather than as a whole directory (`auth.json`, `settings.json`, `trust.json`, `models.json`, `models-store.json` out of `~/.pi/agent`), because that directory also holds `sessions/`, `extensions/`, `skills/` and the installed package trees — gigabytes on an active host. Consequence: in-container pi sessions are invisible host-side, so `pi -c` inside a Docker case only sees that container's own history. See [`pi-integration.md`](./pi-integration.md).
|
||||
Antigravity (`agy`) is the one CLI not installed from npm (Google ships a standalone binary), so it has its own Dockerfile step and adds roughly 190MB; a full image lands near 1.6GB.
|
||||
|
||||
## Quickest path: one-click "Run in Docker"
|
||||
|
||||
|
||||
@@ -1,681 +0,0 @@
|
||||
# Pi (pi.dev) Run Mode: Implementation Plan
|
||||
|
||||
Tracking issue: [#206 "Plans to support pi.dev?"](https://github.com/Ark0N/Codeman/issues/206)
|
||||
|
||||
Status: **IMPLEMENTED 2026-08-13** (see `docs/pi-integration.md` for the user-facing
|
||||
guide). Everything below is the design record; the open questions were resolved
|
||||
empirically against pi 0.84.1 and the answers are recorded inline as **RESULT**
|
||||
notes. Originally reworked 2026-08-06; **rechecked 2026-08-13 against master @
|
||||
`f39beb3` (v1.17.0)**, and every line anchor below was re-verified at that commit (the 1.11.2-era
|
||||
anchors drifted heavily: six releases landed in between, including the settings-surface overhaul and
|
||||
the codex predictive-echo work, both of which added new pi touchpoints, §2.10 and the Brain picker in
|
||||
Phase 3). Upstream facts verified against `@earendil-works/pi-coding-agent` **v0.84.1** (npm latest,
|
||||
published 2026-08-07) and the [`earendil-works/pi`](https://github.com/earendil-works/pi) repo (cite
|
||||
that name: upstream docs still contain stale `pi-mono` links from a repo rename). Line numbers are
|
||||
anchors for orientation, not contracts; they drift.
|
||||
|
||||
---
|
||||
|
||||
## 1. What Pi is
|
||||
|
||||
[Pi](https://pi.dev) (MIT) is a minimal, extensible coding-agent harness. Facts below are verified
|
||||
against the upstream docs in `packages/coding-agent/docs/`.
|
||||
|
||||
| Property | Value |
|
||||
| ---------------- | -------------------------------------------------------------------------------------------------- |
|
||||
| Binary | `pi` (`bin: { pi: 'dist/cli.js' }`) |
|
||||
| npm package | `@earendil-works/pi-coding-agent`, latest **0.84.1** (2026-08-07; 0.84.0 was 2026-08-06); `legacy-node20` dist-tag at 0.74.2 |
|
||||
| Install | `npm install -g --ignore-scripts @earendil-works/pi-coding-agent`, or `curl -fsSL https://pi.dev/install.sh \| sh` (the curl installer also goes through global npm, so both uninstall via npm) |
|
||||
| Config dir | `~/.pi/agent` (override: `PI_CODING_AGENT_DIR`). Holds `auth.json`, `trust.json`, `settings.json`, `models.json` (user-defined providers), `models-store.json` (cached catalogs), `keybindings.json`, `extensions/`, `skills/`, `prompts/`, `themes/`, `AGENTS.md`, `SYSTEM.md`, and the package trees `npm/` + `git/` |
|
||||
| Sessions | `~/.pi/agent/sessions/--<cwd with / replaced by ->--/<timestamp>_<uuid>.jsonl`, tree-structured (`id`/`parentId`), format v3. Overrides: `PI_CODING_AGENT_SESSION_DIR`, `--session-dir` |
|
||||
| Credentials | `~/.pi/agent/auth.json` (OAuth subscriptions + API keys, auto-refresh), plus ~34 provider env vars with **no common prefix**. 0.84.1 adds `pi auth check` (auth preflight with optional credential output) |
|
||||
| TUI | Default: **main screen with terminal-owned scrollback**. Since **0.84.0** an experimental fullscreen mode exists, selectable via `--tui-mode fullscreen` **or at runtime through `/settings`**; the default remains the main-screen mode |
|
||||
| Providers | 15+ (Anthropic, OpenAI, Google, Azure, Bedrock, Mistral, Groq, xAI, OpenRouter, Copilot, Baseten since 0.84.0, ...). OAuth subscription login via `/login` for six: ChatGPT Plus/Pro, Claude Pro/Max, GitHub Copilot, xAI, OpenRouter, Radius |
|
||||
| Permission model | **No permission prompts at all.** No built-in sandbox, no MCP (none planned), no sub-agents, no plan mode, no to-dos, no background bash. Tools run with the user's own permissions |
|
||||
| Trust model | "Project trust" gates **loading** of project-local `.pi/` config/extensions/skills and **installing missing project packages**, not tool execution. Triggered only when the cwd (or an ancestor) contains `.pi/settings.json`, `.pi/extensions\|skills\|prompts\|themes`, `.pi/SYSTEM.md`/`.pi/APPEND_SYSTEM.md`, or `.agents/skills`; a bare `.pi/` directory does NOT prompt. Global `defaultProjectTrust`: `ask` (default) / `always` / `never` |
|
||||
|
||||
Three consequences shape the whole integration:
|
||||
|
||||
1. **There is no `--dangerously-skip-permissions` analog and none is needed.** Pi never prompts for
|
||||
tool approval. The Claude/Codex/Gemini/Antigravity pattern of "send the bypass flag so the session
|
||||
is not stuck on a modal" does not apply. Codeman must not invent a flag here.
|
||||
2. **The one privileged knob is `--approve` / `-a`** (trust project-local files for this run), which
|
||||
makes pi load and execute project `.pi/extensions` TypeScript **and run an npm install of missing
|
||||
project packages**. That is the field the multi-user clamp has to cover. Its explicit inverse
|
||||
`-na` / `--no-approve` exists, which lets the clamp force-deny rather than merely omit (§3, §5.2).
|
||||
3. **Provider keys cannot ride the env allowlist.** Pi's provider key vars (`ANTHROPIC_API_KEY`,
|
||||
`OPENAI_API_KEY`, `DEEPSEEK_API_KEY`, `HF_TOKEN`, `BASETEN_API_KEY`, ...) share no prefix, so
|
||||
there is no way to admit them through `ALLOWED_ENV_PREFIXES` without widening the list for every
|
||||
mode (§2.4).
|
||||
|
||||
---
|
||||
|
||||
## 2. Design decisions
|
||||
|
||||
### 2.1 Mode identity
|
||||
|
||||
`SessionMode` gains `'pi'`. Not a location overlay (unlike Docker/remote-SSH cases), not a web tab:
|
||||
a real sixth CLI backend with its own PTY, tmux session and respawn behaviour, exactly like
|
||||
`antigravity`. Append `pi` after `antigravity` in every enum/list to keep ordering consistent.
|
||||
|
||||
| Surface | Value |
|
||||
| ---------------- | --------------------------------------------------------------------- |
|
||||
| `SessionMode` | `'pi'` |
|
||||
| Display label | `Pi` |
|
||||
| Tab badge | `pi` (two-letter lowercase, like `sh`/`oc`/`cx`/`gm`/`ag`) |
|
||||
| Run button label | `Run PI` (short-label ternary in `_applyRunMode`, pattern `Run AG`) |
|
||||
| Kill-menu label | `Kill Tmux & Pi` |
|
||||
| Identity color | **`#f472b6` (rose-400)**. Verified free: live computed values on the default skin are claude `#38b6f0`, opencode `#44b993`, codex `#2b8fd9`, gemini `#8ab4f8`, antigravity `#22d3ee`, shell `#98a2b1`, web `#38bdf8`; purple is codex's base hex and amber reads as the shell tab badge, so pink/rose (or orange `#fb923c`) are the only genuinely free hues. No `pi` CSS identifier collides anywhere (`mode-pi`, `.tab-mode.pi`, `.run-mode-dot.pi` all grep clean, re-checked at f39beb3) |
|
||||
| Env prefix | `PI_` |
|
||||
| Dependency id | `pi` |
|
||||
| Status endpoint | `GET /api/pi/status` |
|
||||
|
||||
### 2.2 `isExternalCliMode()` yes, `isAltScreenStripMode()` no
|
||||
|
||||
Pi joins `isExternalCliMode()` (`session.ts:164-167`): its own TUI, its own output format, so the
|
||||
Ralph tracker, `BashToolParser`, token/CLI-info scraping and the `❯` readiness probe all stay off
|
||||
(gates at `session.ts:1100`, `:1701`, `:2000`, `:2103`), and readiness falls back to the output
|
||||
stabilization used by the other external CLIs.
|
||||
|
||||
Pi stays **out** of `isAltScreenStripMode()` (`session.ts:197-199`, currently codex/claude/gemini;
|
||||
antigravity and opencode are deliberately excluded). Pi's default TUI renders into the main screen
|
||||
with terminal-owned scrollback, so there is nothing to strip. The fullscreen mode **shipped in
|
||||
0.84.0 and is runtime-switchable via `/settings`**, so Codeman cannot assume a pi session stays
|
||||
main-screen for its lifetime; staying out of the strip list is exactly what makes that safe (the alt
|
||||
screen is load-bearing when the user flips to fullscreen, as it is for `opencode`). Putting pi IN
|
||||
the strip list would corrupt fullscreen sessions. Three mirrors must stay consistent (all unchanged
|
||||
for pi, i.e. pi appears in none of them): the replay-side strip in `session-routes.ts:2275`, the
|
||||
live-stream twin in `session.ts`, and the frontend `_sessionUsesServerMouseStrip()` in
|
||||
`terminal-ui.js` (usages `:3432`, `:3697`).
|
||||
|
||||
### 2.3 tmux required, no direct-PTY fallback, no per-mode configurator
|
||||
|
||||
Same rule as the other external CLIs: `pi` mode throws if tmux is unavailable. Add a fourth block to
|
||||
the guard chain at `session.ts:1751-1768` (antigravity's is `:1765-1768`).
|
||||
|
||||
**No `_configurePi()` is needed.** Opencode/codex/gemini each have a tmux-`setenv` configurator
|
||||
(`tmux-manager.ts:1709-1727`), but antigravity has none: it relies entirely on the generic
|
||||
`applyEnvOverrides()` (`tmux-manager.ts:1643`, `VALID_KEY = /^[A-Z_][A-Z0-9_]*$/`), which runs for
|
||||
every mode in both create (`:1880`) and respawn (`:2107`) and injects via socket-scoped
|
||||
`tmux setenv`, never the spawn command line. Pi follows the antigravity precedent: `PI_*` overrides
|
||||
flow through `applyEnvOverrides()` and nothing else.
|
||||
|
||||
Pi joins the truecolor branches: `buildEnvExports()` (`tmux-manager.ts:1604-1609`,
|
||||
`export COLORTERM=truecolor` + `unset NO_COLOR` for codex/gemini/antigravity) and the attach-env
|
||||
condition at `session.ts:1400-1402` (`buildMuxAttachEnv(...)`, whose comment says it must mirror
|
||||
`buildEnvExports`). Add `|| mode === 'pi'` to both, or the tmux session and the attach client
|
||||
disagree about color depth.
|
||||
|
||||
### 2.4 Env prefix: `PI_` only
|
||||
|
||||
Add `'PI_'` to `ALLOWED_ENV_PREFIXES` (`schemas.ts:125`) and to the prose error message at `:163`
|
||||
(two edits: the message hardcodes the list, and since 1.12+ it also names the exact-key allowlist,
|
||||
currently `...ANTIGRAVITY_* keys and CLAUDE_CONFIG_DIR are allowed.`; there is now a separate
|
||||
`ALLOWED_ENV_KEYS` exact-key set alongside the prefix list, which pi does not need to touch). That
|
||||
covers every documented variable pi reads: `PI_CODING_AGENT_DIR`, `PI_CODING_AGENT_SESSION_DIR`,
|
||||
`PI_PACKAGE_DIR`, `PI_OFFLINE`, `PI_SKIP_VERSION_CHECK`, `PI_TELEMETRY`, `PI_CACHE_RETENTION`,
|
||||
`PI_SHARE_VIEWER_URL`, `PI_HARDWARE_CURSOR`, `PI_EXPERIMENTAL` (whose meaning 0.84.0 extended to
|
||||
strict JSON-schema tool sampling). (Pi also *sets* `PI_CODING_AGENT=true` and `AI_AGENT=pi` in child
|
||||
processes; those are output markers, not inputs, and need nothing from us.)
|
||||
|
||||
**Deliberately not added:** `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `GEMINI_API_KEY`, `XAI_API_KEY`,
|
||||
`GROQ_API_KEY`, `MISTRAL_API_KEY` and the other ~28 provider keys. `ALLOWED_ENV_PREFIXES` is a
|
||||
single global list applied by one Zod refine with no mode context (`safeEnvOverridesSchema`,
|
||||
`schemas.ts:153-165`), so allowlisting bare provider keys for pi would widen the allowlist for
|
||||
**every** mode at once, violating the multi-CLI prefix discipline in CLAUDE.md. Users authenticate
|
||||
pi through `/login` (stored in `~/.pi/agent/auth.json`, auto-refreshed) or by exporting the key in
|
||||
the Codeman server process's own environment.
|
||||
|
||||
Making the allowlist mode-aware is the clean fix, listed as a follow-up in §9. Do not smuggle it
|
||||
into this change.
|
||||
|
||||
### 2.5 Docker credential policy: seed files, not the whole dir
|
||||
|
||||
`CRED_STORES` (`docker-hosts.ts:597-605`; file unchanged since the 2026-08-06 verification) gets a
|
||||
`.pi/agent` entry. Nested `rel` paths already work (`.config/gcloud` maps to seed name
|
||||
`.config-gcloud` via the `replace(/\//g, '-')` at `:620`). Unlike antigravity, which needed **no**
|
||||
entry (`agy` nests all state under `~/.gemini/antigravity-cli/`, already covered by the `.gemini`
|
||||
policy, per the comment at `:599-602`), pi has its own top-level dir and needs its own entry. Use
|
||||
`seedFiles`, **not** `seedWhole`:
|
||||
|
||||
```ts
|
||||
{ rel: '.pi/agent', seedFiles: ['auth.json', 'settings.json', 'trust.json', 'models.json', 'models-store.json'] },
|
||||
```
|
||||
|
||||
Rationale: `~/.pi/agent` also contains `sessions/`, `extensions/`, `skills/` and the installed
|
||||
package trees (`npm/`, `git/`), which on an active host is easily gigabytes; `seedWhole` would
|
||||
`cp -a` all of it into every container start. The five seeded files are what pi needs to
|
||||
authenticate and behave consistently: `models.json` is in the list because it holds user-defined
|
||||
custom providers, and omitting it would silently strip those inside containers. Seeding (RO mount
|
||||
then copy) also means the in-container pi never writes refreshed OAuth tokens back to the host,
|
||||
which is the whole point of the seeding policy, and bind mounts stay excluded from `docker commit`
|
||||
so exports remain secret-free.
|
||||
|
||||
Trade-off to accept and document: in-container pi sessions are not visible host-side, so `pi -c`
|
||||
inside a Docker case only sees that container's own history. Codex shares `sessions/` RW precisely
|
||||
because Codeman reads it host-side for the response viewer; there is no such reader for pi yet
|
||||
(the response-viewer follow-up in §9 would justify flipping this).
|
||||
|
||||
### 2.6 The `pi` binary name is generic
|
||||
|
||||
Unlike `agy`/`codex`/`gemini`, `pi` is a short, common name (Raspberry Pi tooling, personal scripts,
|
||||
`$PATH` accidents). The resolver must not blindly trust a hit. None of the existing external-CLI
|
||||
resolvers execute their binary (only `claude-cli-resolver.ts` does, via the cached
|
||||
`getClaudeCliVersion()`, skipped under vitest), so the sanity check is new ground: model it on
|
||||
`getClaudeCliVersion()`. Run `pi --version` once via `execFileSync`, cache the result module-level,
|
||||
skip under `VITEST`, and require output matching `/^\d+\.\d+\.\d+/`; on mismatch treat the binary as
|
||||
unavailable and log the rejected path. Surface `{ available, path, version }` from
|
||||
`GET /api/pi/status` so a misresolution is diagnosable from the UI (additive relative to the sibling
|
||||
endpoints' `{ available, path }`). The `dependency-registry` entry carries `versionArg: '--version'`
|
||||
for `codeman doctor`.
|
||||
|
||||
### 2.7 tmux extended keys (a real pi-specific footgun)
|
||||
|
||||
Pi documents (`docs/tmux.md`, verified verbatim) that without
|
||||
|
||||
```tmux
|
||||
set -g extended-keys on
|
||||
set -g extended-keys-format csi-u
|
||||
```
|
||||
|
||||
tmux collapses `Shift+Enter` and `Ctrl+Enter` into a plain `\r` (and `Alt+Enter` into `\x1b\r`), and
|
||||
pi's editor uses those for newline vs submit. `extended-keys-format` requires tmux 3.5+; tmux
|
||||
3.2-3.4 works with `extended-keys on` alone (pi then falls back to xterm `modifyOtherKeys`).
|
||||
Codeman's own browser input path sends `\r` for submit, so basic use works unconfigured, but
|
||||
newline-in-editor is degraded both for a user typing in an attached terminal (`sc`) and potentially
|
||||
for the browser Shift+Enter path.
|
||||
|
||||
Upstream recommends `~/.tmux.conf` and notes the setting may need a full `tmux kill-server` restart
|
||||
to take effect. **Codeman must NEVER run `kill-server` on its socket** (it would kill every live
|
||||
session, including `w1`/`w2`/`w3`). Action: attempt to set both options **server-scoped on
|
||||
Codeman's own socket only** (`tmux -L codeman set -s ...`, never `-g` on the user's default socket)
|
||||
at the point the tmux server is first started, verify with `tmux -L codeman show-options -s` and an
|
||||
empirical Shift+Enter test which scope actually takes for the installed tmux version, and fall back
|
||||
to a documented manual step in `docs/pi-integration.md` (a `~/.tmux.conf` snippet plus the
|
||||
kill-server caveat) if it cannot be applied safely to an already-running server. Upstream does not
|
||||
discuss socket- or server-scoped configuration at all, so this verification is original work, not a
|
||||
doc lookup.
|
||||
|
||||
**RESULT (measured, tmux 3.4 + pi 0.84.1):** `tmux -L <socket> set -s extended-keys on` takes effect
|
||||
on an **already-running** server with **no `kill-server`** — pi's own startup warning
|
||||
(`Warning: tmux extended-keys is off…`, a convenient in-band probe) disappears for the next session
|
||||
started afterwards. `extended-keys-format` does **not exist on tmux 3.4** and errors with
|
||||
`invalid option: extended-keys-format`, so the two options must be issued independently rather than
|
||||
chained. Decision: Codeman does **not** set this itself — it is a server-wide tmux option affecting
|
||||
every session of every backend, so silently changing key encoding is not Codeman's call. It is
|
||||
documented as a user step in `docs/pi-integration.md` instead, carrying the measured facts.
|
||||
|
||||
### 2.8 The completeness trap: which mode tables fail loud vs silent
|
||||
|
||||
Adding `'pi'` to the `SessionMode` union makes some omissions compile errors and leaves others
|
||||
silent. The plan calls this out so review can focus on the silent ones.
|
||||
|
||||
**Loud (typecheck fails until edited):** `getModeLabel()` (`session.ts:168-183`, exhaustive switch
|
||||
with no default), `defaultDockerCommandForMode` and `defaultRemoteCommandForMode` (both typed
|
||||
`Record<...CommandMode, string>`), **but only after** `RemoteCommandMode` (`types/session.ts:48-51`)
|
||||
and `DockerCommandMode` (`:157-161`) are widened: both are `Extract<SessionMode, '...'>` with every
|
||||
member spelled out, so forgetting the `Extract` lists keeps `tsc` green while docker/remote pi cases
|
||||
silently fall back to `exec bash -l` via the `|| commands.shell` on the lookup. Edit union + both
|
||||
`Extract` lists + both `Record` literals together.
|
||||
|
||||
**Silent (compiles clean, mode just doesn't work):**
|
||||
|
||||
- `appendResumeFlag()` (`tmux-manager.ts:1030-1042`) has a `default:` arm; a missing `case 'pi'`
|
||||
silently drops docker resume.
|
||||
- `buildSpawnCommand()` (`:770-825`) and `buildPathExport()` (`:1680-1707`) are if-chains with
|
||||
fallthrough returns; a missing branch spawns pi as a login shell / with no PATH augmentation.
|
||||
- `isExternalCliMode()` / `isAltScreenStripMode()` are boolean chains.
|
||||
- The `runMode` accessor's **setter whitelist** (`session-ui.js:2949-2960`) coerces any unknown mode
|
||||
to `'claude'`. Omitting `pi` there makes the mode **unselectable while every other edit appears to
|
||||
work**: this is the single most deceptive omission in the frontend.
|
||||
- `window.__codemanCliAvailable` (injected by `renderIndexHtml`, `server.ts:1375-1407`): the client
|
||||
treats a **missing key as available** (`isCliAvailable` in settings-ui.js), so forgetting the
|
||||
injection un-gates pi on boxes without the CLI instead of hiding it.
|
||||
|
||||
### 2.9 The Daylight skin cascade eats per-mode run-button colors
|
||||
|
||||
A finding that changes the CSS work (verified empirically with computed styles on the live
|
||||
instance, re-confirmed at f39beb3): `styles.css:13681` opens a nested skin block,
|
||||
`html:not([data-skin="og"]) { ... }`, and the **default skin is `daylight-blue`, not `og`**, so the
|
||||
block is live for every default-skin user. Inside it, `.btn-toolbar.btn-run` is re-declared
|
||||
generically and per-mode only for claude/opencode/codex (codex at `:13787`). CSS nesting adds the
|
||||
wrapper's specificity (the nested rules resolve to (0,3,1) vs (0,3,0) for
|
||||
`.btn-toolbar.btn-run.mode-X`), so **gemini's and antigravity's toolbar gradients are dead on the
|
||||
default skin**: both render the generic claude gradient today, still unfixed as of f39beb3. The
|
||||
base-sheet rules (gemini/antigravity at `:4406`/`:4420`) only ever render on the `og` skin. Since
|
||||
1.12+ styles.css itself documents this trap in comments (`:9214`, `:11091`), which confirms the
|
||||
mechanism.
|
||||
|
||||
Consequences for pi:
|
||||
|
||||
- The toolbar gradient needs **two** rules: one in the base sheet (`:4420` area, for `og`), and one
|
||||
**inside** the `13681` block next to codex's (`:13787` area), using the block's own idiom
|
||||
(or the color is invisible to the average user).
|
||||
- `mobile.css` phone-toolbar colors need `!important` on `background`/`border-color`/`color`,
|
||||
exactly as the CLAUDE.md gotcha prescribes. Antigravity's phone block (`mobile.css:895-910`,
|
||||
inside the `@media (max-width: 430px)` opened at `:338`) has no `!important` and is dead on the
|
||||
default skin; do not copy that mistake.
|
||||
- Three surfaces work from base rules alone (verified): run-mode **dots** (list at `:4506-4516`;
|
||||
the skin block overrides only claude/opencode/codex/shell dots, so a base-sheet
|
||||
`.run-mode-dot.pi` renders as authored), **tab badges**, and the **welcome button** (the skin
|
||||
block overrides only claude/opencode/tunnel welcome buttons).
|
||||
- Optional, separate cleanup (not this change): gemini/antigravity could get the same in-block
|
||||
treatment to resurrect their colors.
|
||||
|
||||
### 2.10 Local-echo policy: pi lands on the buffer overlay by default
|
||||
|
||||
New since the first draft of this plan: the codex predictive-echo work (1.13+) introduced a
|
||||
per-session echo policy in `_updateLocalEchoState()` (terminal-ui.js, `_localEchoPolicy` set at
|
||||
`:2837`): `codex → 'predict'` (write-through predictive echo), `shell → 'off'`, **everything else
|
||||
→ 'buffer'** (the `LocalEchoOverlay` that buffers typed text until Enter). Pi therefore gets the
|
||||
buffer overlay on touch devices with zero edits, via the fallthrough.
|
||||
|
||||
That default is a real open question, not a freebie: the codex history (issues #218/#219/#220/#222)
|
||||
shows that a composer which re-renders per keystroke (live-filtering slash picker, server-side
|
||||
cursor movement, wrap-as-you-type) is starved by buffer-until-Enter, and pi's editor is exactly
|
||||
such a composer. Decision for v1: ship with the default `'buffer'` policy but make phone-profile
|
||||
typing an explicit E2E gate (§7 step 4); if pi's editor mis-renders under the overlay, the cheap
|
||||
fallback is forcing `'off'` for pi (one branch in `_updateLocalEchoState`), and teaching the
|
||||
predict path pi's composer row is a follow-up, not a v1 requirement.
|
||||
`test/local-echo-codex-gating.test.ts` pins the per-mode policy via
|
||||
`it.each(['claude', 'gemini', 'opencode'])` lists (`:193`, `:376`); add `'pi'` to those lists once
|
||||
the buffer decision is confirmed (or pin the `'off'` branch if that is the outcome).
|
||||
|
||||
**RESULT (measured, pi 0.84.1, iPhone 14 Pro profile + a PTY-level A/B):** the buffer policy
|
||||
**holds**; codex's failure mode does **not** reproduce. Pi's slash picker re-filters on the **whole
|
||||
composer content**, not on per-keystroke deltas: a one-shot literal write of `/set` (what the overlay
|
||||
flush does) filters the picker to `settings` **identically** to sending `/ s e t` as five separate
|
||||
keystrokes, and the delayed `\r` then selects it and opens the settings menu. Prose prompts buffer
|
||||
correctly (`pendingText` right, nothing on the PTY before Enter), flush on Enter, and are accepted as
|
||||
a single prompt. `'pi'` was added to both `it.each` lists. The `'off'` fallback stays documented but
|
||||
unused.
|
||||
|
||||
---
|
||||
|
||||
## 3. Config surface: `PiConfig` to CLI flags
|
||||
|
||||
```ts
|
||||
/** Pi CLI session configuration */
|
||||
export interface PiConfig {
|
||||
/** Model pattern or ID. Supports `provider/id` and a `:<thinking>` suffix (e.g. `sonnet:high`). Passed via --model. */
|
||||
model?: string;
|
||||
/** Provider name (anthropic, openai, google, ...). Passed via --provider. */
|
||||
provider?: string;
|
||||
/** Reasoning level. Passed via --thinking. */
|
||||
thinking?: 'off' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max';
|
||||
/** Continue the most recent session (-c). Per-cwd scoping is strongly implied upstream but not documented; treat as probable. */
|
||||
continueSession?: boolean;
|
||||
/** Resume a specific session by ID or partial UUID (--session). Codeman deliberately accepts ids only, never paths. */
|
||||
resumeSessionId?: string;
|
||||
/**
|
||||
* Tri-state project trust (repo-local `.pi/` settings/extensions/skills, plus installing
|
||||
* missing project packages):
|
||||
* true -> --approve (trust for this run; loads and EXECUTES repository TypeScript)
|
||||
* false -> --no-approve (force-deny; the trust prompt never appears)
|
||||
* absent -> pi's own defaultProjectTrust (ask).
|
||||
* Multi-user: MATERIALIZED to false for non-granted owners (§5.2).
|
||||
*/
|
||||
approveProjectTrust?: boolean;
|
||||
}
|
||||
```
|
||||
|
||||
Flag mapping in `buildPiCommand()` (new, `tmux-manager.ts`, directly after `buildAntigravityCommand`
|
||||
at `:718-736`; every builder there regex-allowlists each user value and silently drops failures
|
||||
because the result lands in a `bash -c "..."` string):
|
||||
|
||||
| Field | Flag | Validation |
|
||||
| --------------------- | ------------------------------- | --------------------------------------------------------------------------------- |
|
||||
| `approveProjectTrust` | `--approve` / `--no-approve` / nothing | tri-state boolean, clamped (§5.2) |
|
||||
| `model` | `--model <v>` | `/^[a-zA-Z0-9._\-/:]+$/` (`:` for `sonnet:high`, `/` for `openai/gpt-4o`) |
|
||||
| `provider` | `--provider <v>` | `/^[a-z0-9-]+$/` |
|
||||
| `thinking` | `--thinking <v>` | runtime allowlist of the 7 enum values (defense in depth beyond Zod) |
|
||||
| `resumeSessionId` | `--session <v>` | `/^[a-zA-Z0-9._-]+$/` (same shape as `RESUME_ID_SAFE`, `:1021`; excludes paths on purpose) |
|
||||
| `continueSession` | `-c` | boolean; **skipped when a valid `resumeSessionId` is present** (the two conflict) |
|
||||
|
||||
**Not** wired in v1, with reasons:
|
||||
|
||||
- `--api-key <key>`: ⚠️ **never wire this.** It puts a provider secret on the spawn command line,
|
||||
which is exactly what the socket-scoped `tmux setenv` discipline exists to prevent (visible in
|
||||
`ps`, tmux server state, and logs). Listed here so nobody "helpfully" adds it later.
|
||||
- `--tui-mode` (released in 0.84.0): never passed by Codeman. The main-screen default is the
|
||||
friendly case for the browser terminal, and fullscreen remains the user's own runtime choice via
|
||||
`/settings` (§2.2 is designed for that). `--use-theme` (still unreleased) likewise.
|
||||
- `--name <name>` (`-n`): nice for `/resume` readability, but names contain spaces and would be the
|
||||
first user-controlled value needing real shell quoting in `buildSpawnCommand`. Defer.
|
||||
- `--no-session`: ephemeral mode fights respawn/resume. Defer.
|
||||
- `-p`/`--print`, `--mode json`, `--mode rpc`: non-interactive transports, a different product shape
|
||||
(§9). Note upstream already shipped a breaking change to JSON-mode `message_update` framing, so
|
||||
any future consumer must assemble deltas.
|
||||
- `--tools` / `--exclude-tools` / `--no-tools` / `--no-builtin-tools` (`-t`/`-xt`/`-nt`/`-nbt`): a
|
||||
genuinely useful "read-only session" affordance (0.84.0 also added a `defaultTools` setting), but
|
||||
it needs UI design. Follow-up.
|
||||
- `-r`/`--resume` (interactive picker), `--fork`, `-e`/`--extension`, `--skill`, `--system-prompt`,
|
||||
`--append-system-prompt`, `--export`, `--models`, `--list-models`: not session-manager concerns in
|
||||
v1. (`-e` matters later: §9's extension follow-up notes CLI extensions load before trust
|
||||
resolution.)
|
||||
|
||||
---
|
||||
|
||||
## 4. Implementation phases
|
||||
|
||||
### Phase 1: Backend core
|
||||
|
||||
| File | Change |
|
||||
| ----------------------------------- | ------------------------------------------------------------------------------------------------------------ |
|
||||
| `src/utils/pi-cli-resolver.ts` | **New**, mirror `antigravity-cli-resolver.ts` (65 lines: search-dir list, module-level cache with `''` negative sentinel, `which pi` first). Search dirs: `~/.local/bin`, `/usr/local/bin`, `~/.bun/bin`, `~/.npm-global/bin`, `~/bin`. Add the `pi --version` sanity probe from §2.6 (execFileSync, cached, vitest-skipped). Export `resolvePiDir()`, `isPiAvailable()`, `getPiCliVersion()` |
|
||||
| `src/utils/index.ts` | Re-export the three (resolver block `:30-36`) |
|
||||
| `src/types/session.ts` | `SessionMode` union `:46`; **both `Extract` lists**: `RemoteCommandMode` `:48-51`, `DockerCommandMode` `:157-161` (§2.8); new `PiConfig` after `AntigravityConfig` (`:325-333`); `SessionState.piConfig` after `:486`; `@fileoverview` mode list `:11` + config list `:17` |
|
||||
| `src/mux-interface.ts` | `piConfig?: PiConfig` on `CreateSessionOptions` (config block ends `:78`) and `RespawnPaneOptions` (ends `:109`) |
|
||||
| `src/session.ts` | `isExternalCliMode()` `:164-167` (+pi); `getModeLabel()` `:168-183` (+`'Pi'`); `_piConfig` field decl `:466-470`; ctor option `:556-563` + apply `:652-654`; `toState()` `:1227-1230`; `_buildRespawnPaneOptions()` `:1466-1469` (single source of truth shared by `startInteractive` and `reattachRemote`); `startInteractive()` createSessionOptions `:1680-1683`; COLORTERM attach-env condition `:1400-1402` (+pi); requires-tmux guard chain `:1751-1768` (new block: "Pi sessions require tmux for env override injection via setenv") |
|
||||
| `src/tmux-manager.ts` | `buildPiCommand()` after `:736` per §3; `buildSpawnCommand()` signature `:770-779` + dispatch branch after `:822-825`; `appendResumeFlag()` `:1030-1042` (`case 'pi': return \`${modeCommand} --session ${resumeId}\`;`); `buildEnvExports()` truecolor branches `:1604-1609` (+pi); `buildPathExport()` `:1680-1707` (+pi branch calling `resolvePiDir()`); missing-CLI error chain in `createSession` `:1788-1806` (+pi, install hint `npm install -g --ignore-scripts @earendil-works/pi-coding-agent`; note `respawnPane` deliberately has no such check); `piConfig` threading at the four sites `:1748`, `:1817`, `:2041`, `:2080`. **No `_configurePi`** (§2.3) |
|
||||
| `src/config/dependency-registry.ts` | New entry after antigravity's (`:101-108`; file unchanged since 2026-08-06): `{ id: 'pi', label: 'Pi CLI', category: 'core', required: false, usedBy: ['Pi sessions'], resolvers: [{ match: ALL, resolver: { kind: 'path', bins: ['pi'], versionArg: '--version' } }] }` |
|
||||
| `src/docker-hosts.ts` | `defaultDockerCommandForMode` `:138-149`: `pi: 'exec pi'`. `CRED_STORES` `:597-605`: the `.pi/agent` seedFiles entry per §2.5 (nested `rel` already handled at `:613-645`). File unchanged since 2026-08-06 |
|
||||
| `src/remote-hosts.ts` | `defaultRemoteCommandForMode` `:92-118`: `pi: remoteLoginShellCommand('pi')` (`remoteLoginShellCommand` at `:88-90`). Login-shell routing is mandatory (the #209/e803186 lesson: ssh remote-command exec sees only sshd's minimal PATH, and npm's global bin is usually only on PATH via rc files) |
|
||||
|
||||
### Phase 2: Web layer
|
||||
|
||||
| File | Change |
|
||||
| ---------------------------------- | ----------------------------------------------------------------------------------------------- |
|
||||
| `src/web/schemas.ts` | `'PI_'` in `ALLOWED_ENV_PREFIXES` `:125` **and** the prose error message `:163` (which now also names `CLAUDE_CONFIG_DIR`; the `ALLOWED_ENV_KEYS` exact-key set needs no change); new `PiConfigSchema` after `AntigravityConfigSchema` (`:256-271`), mirroring §3's regexes, `.optional()`, not `.strict()`; `piConfig` on `CreateSessionSchema` (`:299` area) and `QuickStartSchema` (`:712` area); `'pi'` in all three mode enums (`:285`, `:708`, cron `agentType` `:1214`; they are byte-identical and there is no fourth); `pi` key in `RemoteCommandOverridesSchema` `:426-436` (it is `.strict()`, so an unknown key is a hard error today; one edit covers both remote `:501` and docker `:577` reuse) |
|
||||
| `src/web/routes/session-routes.ts` | Thread `piConfig` through create (`POST /api/sessions`): disk-strip exclusion chain `:705-712`, availability gate `:782-790` (+`isPiAvailable` with install-hint error), model resolution `:825-838` (`mode === 'pi' ? body.piConfig?.model : ...`), clamp call `:845`, Session ctor `:860` (`piConfig: mode === 'pi' ? gatedPiConfig : undefined`). Quick-start (`POST /api/quick-start`, handler `:2559`): remote-case config rejection `:2614-2621` and docker-case `:2645-2652` (+`piConfig`: per-CLI config does not cross ssh or the bind mount), hooks-scaffold exclusions `:2801`/`:2809`, availability gate `:2744-2752` (local-case branch only), env-strip chains `:2833`/`:2863`, model resolution `:2885`, clamp `:2897`, ctor `:2913`. **Extend `clampExternalCliBypassForOwner()`** (`:305-336`, doc comment above): fifth param + return field; pi joins the **materialize** branch per §5.2. Alt-screen replay-strip at `:2275` unchanged (pi not in it, §2.2) |
|
||||
| `src/web/routes/system-routes.ts` | `GET /api/pi/status` after the antigravity handler (`:418-426`; file unchanged since 2026-08-06), same shape plus `version` (§2.6); update the "CLI Integrations" prose comment `:377` |
|
||||
| `src/web/server.ts` | Restore path: `piConfig: muxSession.mode === 'pi' ? savedState?.piConfig : undefined` after `:2636`. **`renderIndexHtml` CLI-availability injection `:1375-1407`**: add `isPiAvailable` to the dynamic-import tuple (`:1382`) and a `pi` key to the injected object (`:1399`). Per §2.8 a missing key reads as *available*, so this is a correctness edit, not polish |
|
||||
|
||||
### Phase 3: Frontend
|
||||
|
||||
The antigravity touchpoints are the template. Since the first draft, the settings-surface overhaul
|
||||
moved most anchors and added one **new touchpoint** (the clone-repo Brain picker below).
|
||||
`constants.js`, `api-client.js`, `ralph-wizard.js`, `cron-ui.js`, `webview-tabs.js` and `sw.js`
|
||||
still need **no** changes (re-verified zero mode coupling at f39beb3; cron-ui reads the `<select>`
|
||||
generically and special-cases only `shell`).
|
||||
|
||||
| File | Change |
|
||||
| ------------------- | ------------------------------------------------------------------------------------------------------ |
|
||||
| `index.html` | Welcome button `welcomePiBtn` after Gemini's (antigravity's is `:347`; there is deliberately no codex welcome button), `display:none` default, `onclick="app.setRunMode('pi'); app.runPi()"`, text `Run Pi`; run-mode-option row with `.run-mode-dot.pi` after antigravity's (`:526-528`), before the `.run-mode-sep` `:529`; cron `<option value="pi">Pi</option>` after `:803`; **NEW: the clone-repo "Brain" picker** (`cloneCaseBrain`, `:2476-2486`): add `<option value="pi" data-cli="pi">Pi</option>` after the antigravity option `:2483` (gating is automatic: session-ui.js `:2107-2115` hides options whose `data-cli` fails `isCliAvailable`, and `:2250` reads the value at clone time); docker image hint `:2624` (`claude/codex/gemini/opencode/agy` + pi). No per-CLI remote-command override field needed (only codex has one, `:2559`) |
|
||||
| `session-ui.js` | `@fileoverview` mode list `:2`; `run()` dispatch branch after `:400-402`; `_refreshRunModeAvailability` list `:468` (+`'pi'` as a quoted literal, the static test in §6 demands it); short-label ternary `:565` (+`'Run PI'`); **the `runMode` setter whitelist `:2949-2960`** (§2.8, the deceptive one); new `runPi()` modeled on `runAntigravity()` `:1170-1219`: same remote/docker skip, same `_beginSessionLaunchStatus` frame, probes `/api/pi/status` reading `(await res.json()).data.available` (envelope!), **sends no `piConfig` at all** (no bypass exists and trust defaults are pi's own; envOverrides still sent for local cases), install-hint error text matching Phase 1's; `isAltMode` `:1233` and `isExternalCli` `:1263` four-way comparisons (+pi) |
|
||||
| `settings-ui.js` | `applyWelcomeCliVisibility()` `:1176-1191`: add `['welcomePiBtn', 'pi']` |
|
||||
| `app.js` | Response-viewer agent label `:1998-2009` (+pi -> `'Pi'`); tab badge ternary `:3884` (`<span class="tab-mode pi" aria-hidden="true">pi</span>`; claude stays badge-less); kill-title ternary `:5046-5057` (`Kill Tmux & Pi`) |
|
||||
| `panels-ui.js` | Command-palette `labels` map `:430` (+`pi: 'Pi'`; the `\|\| mode` fallback means this is cosmetic, not load-bearing) |
|
||||
| `mobile-overview.js`| `MOBILE_OVERVIEW_RUN_MODES` `:55-62`: `{ mode: 'pi', label: 'Pi', short: 'Pi' }` after antigravity `:60`, before the shell entry. Nothing else: the Run-button badge (`:499`) and menu builder (`:554-556`) consume the list generically, and the buttons carry `btn-toolbar btn-run mode-pi`, which is exactly why they inherit the §2.9 cascade problem and its fix |
|
||||
| `terminal-ui.js` | Badge-row comment `:1750` only (the badge itself is a raw `s.mode` passthrough, no list to extend). `_sessionUsesServerMouseStrip` unchanged (§2.2). `_updateLocalEchoState` unchanged for v1 (§2.10: pi lands on `'buffer'` via the fallthrough; only touch it if E2E forces the `'off'` fallback) |
|
||||
| `i18n.js` | `'Run Pi': '运行 Pi'` in the zh-CN table (`:102-107`, matches the welcome-button text; short labels like `Run PI` are deliberately untranslated, as are the other modes') |
|
||||
| `styles.css` | Tab badge `.session-tab .tab-mode.pi` after `:2157` (`background: rgba(244,114,182,0.2); color: #f472b6;`); add `.session-tab .tab-mode.pi` to the light-skin ink list `:325-336` (gemini + antigravity are its precedent, `:332`); welcome `.welcome-btn-pi` + `:hover` after antigravity's `:3366` block, rose family (e.g. base `linear-gradient(135deg, #33121f 0%, #9d174d 55%, #be185d 100%)`, border `rgba(244,114,182,0.4)`, text `#fce7f3`); toolbar gradient pair `.btn-toolbar.btn-run.mode-pi, .btn-toolbar.btn-run-gear.mode-pi` + `:hover` after `:4420`'s antigravity block; `.run-mode-dot.pi { background: #f472b6; }` in the dot list `:4506-4516`; **and the §2.9 rule inside the Daylight block** next to codex's `:13787` (e.g. `background: linear-gradient(135deg, #be185d, #f472b6); border-color: #be185d; color: #fff1f7;`). The dot needs no skin-block entry (the block overrides only claude/opencode/codex/shell dots; gemini/antigravity dots already fall through correctly) |
|
||||
| `mobile.css` | Phone toolbar block after `:910` inside the `@media (max-width: 430px)` opened at `:338`: `mode-pi` base + `:active`, **with `!important` on background/border-color/color** (§2.9; antigravity's block `:895-910` omits it and is dead); light-skin override entry after `:2985` with the same four-skin `html:is(...)` prefix as its siblings |
|
||||
|
||||
### Phase 4: Docker image and installer
|
||||
|
||||
Both files are unchanged since the 2026-08-06 verification; all anchors stand.
|
||||
|
||||
- `docker/agent.Dockerfile`: a **separate** `RUN` step after the antigravity block (`:38-45`), not a
|
||||
fifth line in the shared npm block (`:31-36`), because pi documents `--ignore-scripts` and that
|
||||
flag must not silently change how the other four install:
|
||||
|
||||
```dockerfile
|
||||
# Pi (pi.dev). Upstream documents --ignore-scripts (pi needs no lifecycle scripts);
|
||||
# kept out of the shared npm block above so the flag cannot affect the other CLIs.
|
||||
RUN npm install -g --ignore-scripts @earendil-works/pi-coding-agent \
|
||||
&& npm cache clean --force \
|
||||
&& pi --version
|
||||
```
|
||||
|
||||
Implementation checklist item: the gid-0 pre-created dirs at `:64-68` include `.claude/projects`
|
||||
and `.codex/sessions`; verify whether the cred-seed copy into `~/.pi/agent` creates its target
|
||||
dir in a fresh container or whether `.pi/agent` must join that `mkdir` line. Rebuild with
|
||||
`node scripts/build-agent-image.mjs --no-cache` (the script itself needs no change; nothing in it
|
||||
is CLI-specific). The cached npm layer has silently frozen a CLI at a broken version before; see
|
||||
`docs/docker-cases.md`.
|
||||
- `install.sh` (six edit sites, all verified): `PI_SEARCH_PATHS` block after `:125` (mirror the
|
||||
resolver's dirs); `check_pi` / `get_pi_path` pair inserted at `:531` (antigravity's pair spans
|
||||
`:504-530`); the satisfying-AI-CLI chain `:2032-2063` (`has_pi` local at `:2037` area, detect
|
||||
block after `:2059`, widen the five-way test at `:2061` and the warn text at `:2063`); the menu
|
||||
option-4 text `:2070`; the skip-path hints `:2115-2116` (add
|
||||
`npm install -g --ignore-scripts @earendil-works/pi-coding-agent (Pi)`); the final no-CLI
|
||||
reminder `:2416-2423` (add `check_pi` to the condition and a pi line to the echo block).
|
||||
Detection plus a hint only; do **not** add an auto-install path in this change.
|
||||
|
||||
### Phase 5: Docs
|
||||
|
||||
- `docs/pi-integration.md` (**new**, user-facing): install (both installers uninstall via npm), auth
|
||||
(`/login` OAuth for six providers vs API keys; `pi auth check` for preflight; Claude Pro/Max
|
||||
third-party harness usage bills as Anthropic "extra usage" per token, not plan limits; OpenRouter
|
||||
login supports pasting the redirect URL, which matters over remote SSH), what Codeman wires up
|
||||
and deliberately does not (§3, incl. never passing `--tui-mode`), the tmux extended-keys note
|
||||
from §2.7 with the manual `~/.tmux.conf` fallback, Docker/remote behaviour (in-container sessions
|
||||
invisible host-side), the trust model in §1 words, known gaps.
|
||||
- `CLAUDE.md`: tech-stack line (six CLIs + `SessionMode` union), the env-prefix gotcha bullet, the
|
||||
multi-CLI prefix-discipline bullet, the "External CLI modes" key-pattern paragraph (note it now
|
||||
also carries the codex predictive-echo block; pi's echo-policy decision from §2.10 belongs in the
|
||||
same paragraph), the `src/utils/` resolver list.
|
||||
- `docs/architecture-invariants.md`: the external-CLI-modes section. ⚠️ Its anchor was already
|
||||
renamed once to `#external-cli-modes-opencode-codex-gemini-antigravity` while CLAUDE.md's link
|
||||
text still shows the old name; when renaming again for pi, update every inbound link (CLAUDE.md
|
||||
and this file).
|
||||
- `docs/docker-cases.md` (cred-seeding table + supported modes + image contents),
|
||||
`docs/remote-sessions.md` (`RemoteCommandMode`), `docs/cron-guide.md` + `docs/cron-discovery.md`
|
||||
(`agentType` enum; note the readiness caveat from §6's cron paragraph),
|
||||
`docs/security-architecture.md` (env prefix allowlist row).
|
||||
- `README.md` + `README.zh-CN.md`: six CLIs.
|
||||
- `package.json` keywords: `pi`.
|
||||
- Update the issue #206 thread when it ships.
|
||||
|
||||
---
|
||||
|
||||
## 5. Security checklist
|
||||
|
||||
1. **Command injection.** Every `PiConfig` value is regex-validated in `buildPiCommand()` before
|
||||
entering the `bash -c "..."` string; anything failing validation is dropped, not escaped
|
||||
(matching the four existing builders). No user string reaches the spawn line unvalidated. Pinned
|
||||
by a "rejects unsafe values" test per field.
|
||||
2. **Multi-user clamp, materialize branch.** `approveProjectTrust` is the privilege-shaped field: it
|
||||
makes pi execute repository-supplied TypeScript and install project packages.
|
||||
`clampExternalCliBypassForOwner()` (`session-routes.ts:305-336`) has two branches, and pi belongs
|
||||
in the **gemini-style materialize branch**, not the codex/antigravity only-if-sent branch:
|
||||
pi's absent-config default is an *interactive trust prompt the session user can answer
|
||||
themselves in the terminal*, so merely omitting `--approve` is not a clamp. For a non-granted
|
||||
owner, materialize `{ ...(piConfig ?? {}), approveProjectTrust: false }` so `buildPiCommand`
|
||||
always emits `--no-approve` and the prompt never appears. Both call sites (`:845`, `:2897`)
|
||||
widen. This helper still has **zero test coverage** (re-confirmed at f39beb3); §6 adds the first
|
||||
tests.
|
||||
3. **Secrets stay off the command line.** `PI_*` overrides flow through `applyEnvOverrides()` /
|
||||
socket-scoped `tmux setenv`, never inlined into the spawn string. No `-e` at container create
|
||||
time. And `--api-key` is never wired (§3): it would put a provider secret into `ps`/tmux state.
|
||||
4. **Env allowlist not widened.** Only the `PI_` prefix is added; the provider keys stay out (§2.4)
|
||||
and `ALLOWED_ENV_KEYS` is untouched. Pinned by a test that `PI_OFFLINE` passes and
|
||||
`ANTHROPIC_API_KEY` still fails validation.
|
||||
5. **Docker seeding, not sharing.** Per §2.5: RO mount then copy, so refreshed OAuth tokens never
|
||||
write back to the host; bind mounts stay excluded from `docker commit` so exports remain
|
||||
secret-free.
|
||||
6. **Remote SSH.** `pi` mode goes through `defaultRemoteCommandForMode` and therefore
|
||||
`buildSshConnectionArgs()`. No hand-built ssh line anywhere.
|
||||
7. **No sandbox claims.** Pi documents that it has no sandbox and no permission prompts, and that
|
||||
extensions run with the user's full permissions. Codeman docs must say plainly that a pi session
|
||||
can read, write and execute anything the Codeman user can, and point at Docker cases as the
|
||||
isolation story. Do not imply the trust prompt is a safety boundary (upstream itself says it is
|
||||
not). Worth one doc sentence: `pi auth print-api-key` / `print-bearer-token` (0.83.0) and
|
||||
`pi auth check` (0.84.1) mean a pi session can print its own provider credentials by design;
|
||||
isolation, again, is Docker.
|
||||
8. **Loud-vs-silent audit.** Before review, walk §2.8's silent list and confirm each site has its
|
||||
pi branch; the loud ones the compiler already caught.
|
||||
|
||||
---
|
||||
|
||||
## 6. Test plan
|
||||
|
||||
- `test/pi-mode.test.ts` (**new**, modeled on `test/antigravity-mode.test.ts`, 125 lines, no port;
|
||||
file unchanged since 2026-08-06 so its structure remains the template):
|
||||
`CreateSessionSchema`/`QuickStartSchema` accept a pi config; unsafe `model`/`provider`/
|
||||
`resumeSessionId` values are rejected (`'pi; rm -rf /'` shapes); `buildSpawnCommand({ mode: 'pi', ... })`
|
||||
emits expected flags, drops invalid ones, emits `--no-approve` for `approveProjectTrust: false`
|
||||
and `--approve` for `true`, and skips `-c` when a `resumeSessionId` is present;
|
||||
`defaultDockerCommandForMode('pi') === 'exec pi'` and
|
||||
`defaultRemoteCommandForMode('pi') === 'exec "${SHELL:-/bin/sh}" -i -l -c \'pi\''`;
|
||||
`isExternalCliMode('pi') === true`, `isAltScreenStripMode('pi') === false`; the env pair
|
||||
(`PI_OFFLINE` accepted, `ANTHROPIC_API_KEY` rejected), mirroring antigravity-mode `:49-63`.
|
||||
- **First-ever coverage for `clampExternalCliBypassForOwner`** (still nothing in `test/` touches
|
||||
it): cover pi's materialize branch (absent config still yields `approveProjectTrust: false` for a
|
||||
non-granted owner; a sent `true` is forced to `false`; granted owner passes through) and, while
|
||||
there, pin the three existing modes' behavior. Prefer exporting the helper for direct unit tests
|
||||
over a heavier multi-user route fixture; either way it lives under `test/routes/`.
|
||||
- `test/run-mode-ui.test.ts`: extend `loadUi()`'s stub lists (welcome-button ids, mode buttons,
|
||||
`ALL_OFF`) and add pi welcome/dropdown gating cases; note the static parser test
|
||||
`'gates every mode the run-mode menu actually offers'` (`:433-456`) picks up the new
|
||||
`data-mode="pi"` from index.html automatically and **fails until** `_refreshRunModeAvailability`
|
||||
contains a quoted `'pi'`, which is exactly the regression it exists for. Add a
|
||||
`describe('Pi quick start')` modeled on the antigravity one (`:840`) driving `runPi()` against a
|
||||
stubbed `/api/pi/status` + `/api/quick-start`, asserting the posted body has `mode: 'pi'` and
|
||||
**no `piConfig`**, and that the envelope is unwrapped. (The short-label assertion pattern is at
|
||||
`:82`, `'Run AG'`.)
|
||||
- `test/render-index-html.test.ts` `:141`: the injected `window.__codemanCliAvailable` is asserted
|
||||
with an exact `toEqual` and now carries **seven** keys (claude, opencode, codex, gemini,
|
||||
antigravity, cloudflared, and since 1.12+ `git`), so it **must** gain the `pi` key (and the
|
||||
resolver mock an `isPiAvailable`); its comment explains why: a dropped key silently un-gates
|
||||
(§2.8).
|
||||
- `test/routes/system-routes.test.ts`: `GET /api/pi/status` shape, modeled on the antigravity
|
||||
describe (`:816-838`) + resolver mock (`:84-87`); file unchanged since 2026-08-06.
|
||||
- `test/mobile-overview.test.ts`: `:375` is an exact-array `toEqual` over the run-menu modes and
|
||||
**will fail until updated** to include `'pi'` (the second exact-array at `:366`,
|
||||
`['claude', 'shell']`, is a gating case and stays as-is); the sibling static parser then covers
|
||||
the new entry automatically. The no-hex-literals guard only scans `.mobile-overview*` rules, so
|
||||
pi's `mode-pi` colors in mobile.css do not trip it.
|
||||
- `test/local-echo-codex-gating.test.ts` (§2.10): once the buffer-policy decision is confirmed in
|
||||
E2E, add `'pi'` to the `it.each(['claude', 'gemini', 'opencode'])` lists (`:193`, `:376`) so the
|
||||
chosen policy is pinned.
|
||||
- `test/skin-themes.test.ts`: will NOT trip (it enumerates skins, not modes); run it anyway since
|
||||
styles.css is touched. `test/mobile-header-buttons-policy.test.ts`: trips only if a header
|
||||
button is added; pi adds none (welcome button and run-menu rows are outside `header-right`).
|
||||
- Cron: schema-level acceptance of `agentType: 'pi'` (the service consumes `SessionMode`
|
||||
generically; `src/cron/` is unchanged since the first draft). Known, documented degradation: the
|
||||
readiness poll (`cron-service.ts:515`) looks for `❯`/`tokens`, which pi never prints, so cron pi
|
||||
jobs burn the ready-poll attempts and then send anyway. Acceptable for v1; note it in
|
||||
`docs/cron-guide.md`.
|
||||
- Sweep with `npm run test:ci`. Never bare `npm test`. No new ports needed (all new/extended suites
|
||||
are portless).
|
||||
|
||||
---
|
||||
|
||||
## 7. End-to-end verification (required before COM)
|
||||
|
||||
Unit tests passing is not evidence the mode works (pi is not currently installed on the dev box, so
|
||||
step 1 is a real step). Before shipping:
|
||||
|
||||
1. Install pi (`npm install -g --ignore-scripts @earendil-works/pi-coding-agent`), authenticate once
|
||||
with `/login`.
|
||||
2. `curl -sk https://localhost:3000/api/pi/status | jq` reports `available: true`, the right path,
|
||||
and a sane `version`.
|
||||
3. Create a **throwaway** case, launch a pi session from the Run dropdown, send a prompt from the
|
||||
browser, confirm the reply renders and scrollback survives a tab switch. Do not touch
|
||||
`w1`/`w2`/`w3`.
|
||||
4. **Local-echo policy gate (§2.10):** on a phone profile, type into the pi editor through the
|
||||
buffer overlay (drive with `page.keyboard.type()`, never `app.sendInput()`, and force
|
||||
`app._localEchoEnabled = true`; headless Chromium reports touch as false) and confirm pi's
|
||||
composer renders the flushed text correctly on Enter. If it mis-renders, flip pi to the `'off'`
|
||||
branch in `_updateLocalEchoState` and pin that instead.
|
||||
5. Visual pass on the **default skin** (the §2.9 finding makes this the load-bearing check, not a
|
||||
formality): run-button gradient actually renders rose (not generic claude blue), dot, tab badge,
|
||||
welcome button, kill-menu label; then a phone profile (toolbar `!important` colors and light-skin
|
||||
overrides are the usual regressions).
|
||||
6. Kill and respawn the session; confirm `piConfig` round-trips through `state.json` and the pane
|
||||
comes back with the same flags. Then `/clear`-style respawn via the Respawn tab.
|
||||
7. Extended keys (§2.7): in an attached terminal, verify whether Shift+Enter inserts a newline in
|
||||
pi's editor with and without the socket-scoped options; record the outcome in
|
||||
`docs/pi-integration.md` either way. While attached, also flip `/settings` to the fullscreen TUI
|
||||
and back to confirm the no-strip decision holds (§2.2).
|
||||
8. Trust model: point a throwaway case at a repo containing `.pi/extensions`, confirm the trust
|
||||
prompt appears interactively and that a multi-user non-granted session instead launches with
|
||||
`--no-approve` (prompt never shown, extensions not loaded).
|
||||
9. **NOT RUN in this pass — an honest gap.** Docker case with `mode: 'pi'`: rebuild the agent image with `--no-cache`, confirm `pi --version`
|
||||
inside the container **as the `agent` user**, confirm seeded auth works and a session starts
|
||||
(this is exactly where the antigravity Docker path broke in 1.11.2: the CLI was never installed
|
||||
in the image).
|
||||
10. **NOT RUN in this pass — the other gap.** Remote SSH case with `mode: 'pi'`: confirm the
|
||||
login-shell wrapper resolves the npm global bin.
|
||||
11. Only then: changeset, `COM minor` (new capability, additive to the API surface).
|
||||
|
||||
**Verification actually performed** (2026-08-13, pi 0.84.1, isolated `CODEMAN_INSTANCE=pi-beta`
|
||||
server on :5055 with its own tmux socket and data dir): steps 1-8 pass. Highlights:
|
||||
`/api/pi/status` resolved through the **search-dir fallback** (pi installed to `~/.npm-global/bin`,
|
||||
deliberately not on PATH) and reported
|
||||
`{available:true, path:'/home/arkon/.npm-global/bin', version:'0.84.1'}`; the real spawn line came
|
||||
out as `… COLORTERM=truecolor … && pi --approve --provider anthropic --thinking high`; `piConfig`
|
||||
round-tripped through `state.json` across a **full server restart**; the trust prompt appeared for a
|
||||
case containing `.pi/extensions` + `.pi/settings.json`, and `--no-approve` suppressed it
|
||||
(`This project is not trusted. Project .pi resources and packages are ignored.`); on the **default
|
||||
`daylight-blue` skin** the toolbar Run button computed to
|
||||
`linear-gradient(135deg, rgb(190,24,93), rgb(244,114,182))` — genuinely rose and **distinct from
|
||||
claude's blue**, so the §2.9 cascade trap is avoided; and flipping `/settings` to the fullscreen TUI
|
||||
put the pane into the alt screen (`alternate_on=1`), **empirically confirming §2.2**: had pi been in
|
||||
the strip list, Codeman would have stripped that switch and corrupted the session. Steps 9-10 need a
|
||||
Docker daemon and a remote host respectively.
|
||||
|
||||
---
|
||||
|
||||
## 8. Effort estimate
|
||||
|
||||
Calibrated against the real antigravity history, which is the honest baseline: the feature commit
|
||||
`26cbbe0` was 24 files, +638/-63, and it then took **four follow-up commits** (`e803186` login-shell
|
||||
routing, `292ba2c` ownership helpers, `5d28999` CLI gating incl. tests, `0d0b772` docs/installer/UI
|
||||
propagation) totaling roughly +600/-170 across ~43 file-touches to make the mode actually
|
||||
first-class. Budgeting only the feature-commit shape under-scopes by ~40%. This plan folds all four
|
||||
follow-up surfaces in from the start (login-shell routing in Phase 1, availability gating in Phases
|
||||
2-3, installer/docs propagation in Phases 4-5), so expect the full footprint in one pass:
|
||||
|
||||
| Phase | Size |
|
||||
| --------------------- | -------------------------------------------------------------------------- |
|
||||
| 1. Backend core | ~260 lines across 9 files, one new file (resolver incl. version probe) |
|
||||
| 2. Web layer | ~110 lines across 4 files (incl. the clamp widening + availability inject) |
|
||||
| 3. Frontend | ~175 lines across 10 files (enumerations + CSS in two sheets + skin block + the Brain picker option) |
|
||||
| 4. Docker + installer | ~45 lines, plus one `--no-cache` image rebuild |
|
||||
| 5. Docs | one new doc, ~10 files touched |
|
||||
| 6. Tests | one new test file, 6 extended (2 of which fail loudly until updated), plus the first clamp coverage |
|
||||
|
||||
---
|
||||
|
||||
## 9. Out of scope, tracked as follow-ups
|
||||
|
||||
- **A Codeman pi extension for real idle/completion events (highest value, now fully de-risked).**
|
||||
Pi extensions are TypeScript modules with Node built-ins and npm deps available, so an HTTP POST
|
||||
to `/api/hook-event` is trivial. The **`agent_settled`** event **shipped in 0.84.0** and is
|
||||
documented for exactly this use case (fires only when pi will not continue on its own: after
|
||||
auto-retries, auto-compaction and queued follow-ups; `ctx.isIdle()` is true inside the handler).
|
||||
That is a genuine idle signal replacing output-silence heuristics, i.e. the same class of upgrade
|
||||
hooks give Claude sessions. The bash tool exposes five env vars (`PI_SESSION_ID`,
|
||||
`PI_SESSION_FILE`, `PI_PROVIDER`, `PI_MODEL`, `PI_REASONING_LEVEL`), injected per command. Bonus:
|
||||
an extension can own the **`project_trust`** event (first yes/no wins, and CLI `-e` extensions
|
||||
load *before* trust resolution), so Codeman could answer the trust prompt programmatically, a
|
||||
cleaner mechanism than the `--approve` flag for both the single-user convenience case and the
|
||||
multi-user deny case.
|
||||
- **Response viewer for pi.** Sessions are JSONL v3 under
|
||||
`~/.pi/agent/sessions/--<cwd-dashed>--/<timestamp>_<uuid>.jsonl` with an `id`/`parentId` tree and
|
||||
typed content blocks (text, image, thinking, toolCall); the cwd-derived dir name is trivially
|
||||
computable host-side. Feasible, and it would justify flipping the Docker cred policy to share
|
||||
`sessions/` RW like Codex.
|
||||
- **Mode-aware env allowlist.** Would let pi sessions accept provider keys without widening the
|
||||
global list. Needs `ALLOWED_ENV_PREFIXES` to become a per-mode map plus mode context inside the
|
||||
Zod refine.
|
||||
- **`--tools` / `--exclude-tools` / `--no-tools` / `--no-builtin-tools` read-only sessions** (plus
|
||||
the 0.84.0 `defaultTools` setting). Real product value, needs UI.
|
||||
- **Predictive echo for pi's composer** if the §2.10 buffer decision does not hold up in practice:
|
||||
teach `PredictiveEchoAddon` pi's composer row the way `isCodexComposerRow` handles codex's.
|
||||
- **`--mode json` / `--mode rpc`, and upstream's experimental remote-session client APIs**
|
||||
(transport-neutral `PiClient`, CBOR protocol, Unix-socket transport, `RemoteSession` controller,
|
||||
still unreleased as of 0.84.1). A potential non-PTY integration path, a different architecture
|
||||
from the tmux+PTY model. Note the already-shipped breaking change to `message_update` framing
|
||||
(delta-only): any consumer must assemble deltas between `message_start`/`message_end`.
|
||||
- **`--name` for session labels.** Blocked on shell-quoting a user string in `buildSpawnCommand`.
|
||||
|
||||
---
|
||||
|
||||
## 10. Risks
|
||||
|
||||
| Risk | Mitigation |
|
||||
| ------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
|
||||
| `pi` resolves to an unrelated binary | `pi --version` + semver-shape check in the resolver (§2.6); path and version shown in `/api/pi/status` |
|
||||
| Pi's TUI repaints in a way the browser terminal handles badly | Test scrollback and repaint early (step 3 of §7); pi's default is main-screen with terminal-owned scrollback, which is the friendly case |
|
||||
| Fullscreen TUI mode (shipped 0.84.0, runtime-switchable) | Already designed for: pi stays OUT of the strip list, so a user flipping `/settings` to fullscreen gets opencode-like alt-screen behavior, not corruption. §7 step 7 tests the flip explicitly |
|
||||
| The buffer local-echo overlay fights pi's live composer | §2.10: explicit E2E gate (§7 step 4) with the one-line `'off'` fallback; predictive echo for pi is a tracked follow-up, not a v1 blocker |
|
||||
| Pi moves fast (pre-1.0; 9 releases in the 7 weeks before 0.84.1) | Keep the flag surface small; every flag validated and droppable; nothing pinned in the Dockerfile beyond the `--no-cache` rebuild cadence. Live example of the hazard: `--tui-mode` went from main-only docs to released between the two drafts of this plan |
|
||||
| Docker image grows | Pi is an npm package; the layer is modest next to the ~190MB `agy` binary |
|
||||
| Trust prompt blocks a session | Narrower than feared: only fires when `.pi/settings.json`, `.pi/extensions\|skills\|prompts\|themes`, `.pi/SYSTEM.md`/`APPEND_SYSTEM.md` or `.agents/skills` exists (bare `.pi/` does not). Documented; `approveProjectTrust` is the opt-in escape hatch; multi-user forces `--no-approve` (§5.2); the `project_trust` extension follow-up removes the prompt entirely |
|
||||
| Interactive `/login` OAuth can't complete headlessly | Document: authenticate once interactively (or seed `auth.json`); `pi auth check` verifies credentials preflight; OpenRouter's paste-the-redirect-URL flow covers remote SSH |
|
||||
| Provider auth is awkward without key prefixes in the allowlist | `/login` writes `~/.pi/agent/auth.json` once and Docker seeds it; the mode-aware allowlist follow-up removes the friction |
|
||||
| Cron pi jobs mis-detect readiness | Known degradation, documented in §6; readiness falls through after the poll budget and the prompt still sends |
|
||||
@@ -1,235 +0,0 @@
|
||||
# Pi (pi.dev) sessions
|
||||
|
||||
Codeman can drive [Pi](https://pi.dev) (`@earendil-works/pi-coding-agent`, MIT) as a
|
||||
session backend, alongside Claude Code, OpenCode, Codex, Gemini and Antigravity.
|
||||
`pi` is a sixth **run mode**: its own PTY, its own tmux session, its own tab colour
|
||||
(rose). It is not a location overlay like Docker or remote-SSH cases, and it is not
|
||||
a web tab.
|
||||
|
||||
Tracking issue: [#206](https://github.com/Ark0N/Codeman/issues/206). The design
|
||||
rationale behind each decision below lives in `docs/pi-integration-plan.md`.
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
npm install -g --ignore-scripts @earendil-works/pi-coding-agent
|
||||
# or
|
||||
curl -fsSL https://pi.dev/install.sh | sh
|
||||
```
|
||||
|
||||
Both installers end up going through global npm, so either one uninstalls with
|
||||
`npm uninstall -g @earendil-works/pi-coding-agent`.
|
||||
|
||||
Codeman finds the binary via `which pi` and then the usual global-bin locations
|
||||
(`~/.local/bin`, `/usr/local/bin`, `~/.bun/bin`, `~/.npm-global/bin`, `~/bin`).
|
||||
|
||||
**`pi` is a short, generic name**, so unlike the other CLI resolvers Codeman does
|
||||
not trust a `which` hit on its own: it runs `pi --version` once and requires
|
||||
semver-shaped output. Anything else is rejected as "not installed" and the
|
||||
rejected path is logged. Check what it resolved:
|
||||
|
||||
```bash
|
||||
curl -s localhost:3000/api/pi/status | jq
|
||||
# { "available": true, "path": "/home/you/.local/bin", "version": "0.84.1" }
|
||||
```
|
||||
|
||||
That endpoint carries `version` on top of the shape the sibling `/api/*/status`
|
||||
endpoints return, precisely so a misresolution is visible rather than presenting
|
||||
as "the mode just doesn't work".
|
||||
|
||||
## Authenticate
|
||||
|
||||
Pi supports 15+ providers. Two ways in:
|
||||
|
||||
- **OAuth subscription login** — run `/login` inside a pi session. Six providers
|
||||
support it: ChatGPT Plus/Pro, Claude Pro/Max, GitHub Copilot, xAI, OpenRouter
|
||||
and Radius. Credentials land in `~/.pi/agent/auth.json` and pi refreshes them
|
||||
itself. OpenRouter's flow accepts a pasted redirect URL, which is what makes it
|
||||
workable over remote SSH.
|
||||
- **API keys** — exported in the environment of the **Codeman server process**.
|
||||
|
||||
⚠️ **Provider API keys cannot be sent as per-session `envOverrides`.** Pi reads
|
||||
about 34 provider variables (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`,
|
||||
`DEEPSEEK_API_KEY`, `HF_TOKEN`, `BASETEN_API_KEY`, …) that share no common prefix.
|
||||
Codeman's env allowlist is a single global list applied to every mode at once, so
|
||||
admitting bare provider keys for pi would widen the allowlist for Claude, Codex,
|
||||
Gemini and everything else too. Only the **`PI_*`** prefix was added, which covers
|
||||
every documented pi input: `PI_CODING_AGENT_DIR`, `PI_CODING_AGENT_SESSION_DIR`,
|
||||
`PI_PACKAGE_DIR`, `PI_OFFLINE`, `PI_SKIP_VERSION_CHECK`, `PI_TELEMETRY`,
|
||||
`PI_CACHE_RETENTION`, `PI_SHARE_VIEWER_URL`, `PI_HARDWARE_CURSOR`,
|
||||
`PI_EXPERIMENTAL`.
|
||||
|
||||
`pi auth check` verifies credentials before you start a long run.
|
||||
|
||||
Note if you authenticate with a Claude Pro/Max subscription: third-party harness
|
||||
usage bills as Anthropic "extra usage" per token rather than against plan limits.
|
||||
|
||||
## What Codeman wires up
|
||||
|
||||
`PiConfig` (per session, persisted in `state.json`, round-trips through respawn):
|
||||
|
||||
| Field | Flag | Notes |
|
||||
| --------------------- | -------------------------------------- | ---------------------------------------------------------------- |
|
||||
| `model` | `--model <v>` | Accepts `provider/id` and a `:<thinking>` suffix (`sonnet:high`) |
|
||||
| `provider` | `--provider <v>` | `anthropic`, `openai`, `google`, … |
|
||||
| `thinking` | `--thinking <v>` | `off`/`minimal`/`low`/`medium`/`high`/`xhigh`/`max` |
|
||||
| `continueSession` | `-c` | Skipped when `resumeSessionId` is set (the two conflict) |
|
||||
| `resumeSessionId` | `--session <v>` | Ids only, never paths |
|
||||
| `approveProjectTrust` | `--approve` / `--no-approve` / nothing | Tri-state, see below |
|
||||
|
||||
Every value is regex-validated and **dropped** (not escaped) if it fails, because
|
||||
the result is interpolated into the pane's `bash -c "…"` command.
|
||||
|
||||
The Run button sends **no `PiConfig` at all**: pi has no permission prompts to
|
||||
bypass, and project trust is a decision the person at the terminal makes.
|
||||
|
||||
## What Codeman deliberately does NOT wire up
|
||||
|
||||
- **`--api-key`.** Never. It would put a provider secret on the spawn command
|
||||
line, visible in `ps`, tmux server state and logs. `PI_*` overrides go through
|
||||
socket-scoped `tmux setenv` for exactly this reason.
|
||||
- **`--tui-mode`.** Pi's default main-screen TUI is the friendly case for a
|
||||
browser terminal. The fullscreen mode (0.84.0) stays your own runtime choice via
|
||||
`/settings`.
|
||||
- **`--name`, `--no-session`, `-p`/`--print`, `--mode json`, `--mode rpc`,
|
||||
`--tools`/`--exclude-tools`, `-e`/`--extension`, `--skill`,
|
||||
`--system-prompt`.** Tracked as follow-ups in the plan doc.
|
||||
|
||||
## Permission and trust model — read this
|
||||
|
||||
**Pi has no permission prompts and no sandbox.** There is no
|
||||
`--dangerously-skip-permissions` analog and none is needed: tools run with the
|
||||
user's own permissions, always. A pi session can read, write and execute anything
|
||||
the Codeman user can. If you need isolation, use a **Docker case** — that is the
|
||||
isolation story, here as everywhere else in Codeman.
|
||||
|
||||
Pi's "project trust" prompt is **not** a safety boundary (upstream says so too).
|
||||
It gates *loading* repo-local `.pi/` config, extensions and skills, and
|
||||
*installing* missing project packages. It only appears when the cwd or an ancestor
|
||||
contains `.pi/settings.json`, `.pi/extensions|skills|prompts|themes`,
|
||||
`.pi/SYSTEM.md`/`.pi/APPEND_SYSTEM.md`, or `.agents/skills`. A bare `.pi/`
|
||||
directory does not trigger it.
|
||||
|
||||
`approveProjectTrust: true` answers it with `--approve`, which means pi **loads
|
||||
and executes repository-supplied TypeScript** and runs an npm install for missing
|
||||
project packages. Treat it exactly as seriously as that sounds.
|
||||
|
||||
**Multi-user mode:** for an owner without the privileged-command grant, Codeman
|
||||
materializes `approveProjectTrust: false` so the pane launches with
|
||||
`--no-approve` and the prompt never appears. Merely *omitting* `--approve` would
|
||||
not be a clamp, since pi's own default is to ask and the session user could just
|
||||
answer yes.
|
||||
|
||||
Also worth knowing: `pi auth print-api-key` / `print-bearer-token` and
|
||||
`pi auth check` mean a pi session can print its own provider credentials by
|
||||
design. Isolation is Docker.
|
||||
|
||||
## tmux extended keys (Shift+Enter)
|
||||
|
||||
Pi's editor uses `Shift+Enter` / `Ctrl+Enter` for newline-vs-submit. Without
|
||||
extended keys, tmux collapses both into a plain `\r`. Upstream recommends:
|
||||
|
||||
```tmux
|
||||
set -g extended-keys on
|
||||
set -g extended-keys-format csi-u
|
||||
```
|
||||
|
||||
`extended-keys-format` needs tmux 3.5+; on 3.2–3.4 `extended-keys on` alone works
|
||||
(pi falls back to xterm `modifyOtherKeys`).
|
||||
|
||||
Codeman's browser input path sends `\r` for submit, so basic use works
|
||||
unconfigured — what degrades is newline-in-editor, mostly when you attach to the
|
||||
pane directly (`sc`).
|
||||
|
||||
⚠️ Upstream notes the setting may need a full `tmux kill-server` to take effect.
|
||||
**Never run `tmux kill-server` on Codeman's socket** — it would kill every live
|
||||
session, `w1`/`w2`/`w3` included.
|
||||
|
||||
**Measured (tmux 3.4, pi 0.84.1): no `kill-server` is needed.** Setting the option
|
||||
server-scoped on Codeman's own socket takes effect on the ALREADY-RUNNING server;
|
||||
the next pi session starts without the warning. Existing sessions keep the old
|
||||
setting until they respawn.
|
||||
|
||||
```bash
|
||||
tmux -L codeman set -s extended-keys on
|
||||
tmux -L codeman set -s extended-keys-format csi-u # tmux 3.5+ only, see below
|
||||
tmux -L codeman show-options -s | grep extended # verify
|
||||
```
|
||||
|
||||
On **tmux 3.4 and older, `extended-keys-format` does not exist** and the second
|
||||
line fails with `invalid option: extended-keys-format`. That is harmless — pi
|
||||
falls back to xterm `modifyOtherKeys` and `extended-keys on` alone silences the
|
||||
warning. Run the two lines independently rather than chained.
|
||||
|
||||
Pi tells you which state it is in: an unconfigured session prints
|
||||
`Warning: tmux extended-keys is off. Modified Enter keys may not work.` in its
|
||||
startup banner, so you can verify the change by starting a new pi session.
|
||||
|
||||
⚠️ Use `-L <socket>` and `-s`, never `-g` on your default socket, and never
|
||||
`kill-server`. Codeman does not set this for you: it is a server-wide tmux option
|
||||
and silently changing key encoding for every session of every backend is not
|
||||
Codeman's call to make.
|
||||
|
||||
## Typing from the browser (local echo)
|
||||
|
||||
On touch devices Codeman buffers typed characters in the `LocalEchoOverlay` and
|
||||
flushes them to the PTY on Enter. Pi gets that `'buffer'` policy, the same as
|
||||
Claude, Gemini and OpenCode.
|
||||
|
||||
This was an explicit open question, because that policy is exactly what broke
|
||||
Codex (issues #218/#219/#220/#222): Codex's composer reacts per keystroke, so
|
||||
buffer-until-Enter starved it. **Measured against pi 0.84.1: it does not
|
||||
reproduce.** Pi's slash-command picker re-filters on the whole composer content
|
||||
rather than on per-keystroke deltas, so a one-shot flush of `/set` filters the
|
||||
picker down to `settings` identically to typing it character by character, and
|
||||
the delayed `\r` then selects it. Prose prompts flush and submit correctly too.
|
||||
|
||||
If a future pi release changes that, the cheap fallback is one `'off'` branch in
|
||||
`_updateLocalEchoState` (terminal-ui.js); teaching `PredictiveEchoAddon` pi's
|
||||
composer row is the larger follow-up.
|
||||
|
||||
## Docker cases
|
||||
|
||||
The agent image (`docker/agent.Dockerfile`) installs pi in its own `RUN` step with
|
||||
`--ignore-scripts`, kept out of the shared npm block so the flag cannot change how
|
||||
the other four CLIs install. Rebuild with:
|
||||
|
||||
```bash
|
||||
node scripts/build-agent-image.mjs --no-cache # --no-cache is mandatory
|
||||
```
|
||||
|
||||
Credentials are **seeded**, not shared: `~/.pi/agent/auth.json`, `settings.json`,
|
||||
`trust.json`, `models.json` and `models-store.json` are mounted read-only and
|
||||
copied into the container's own `~/.pi/agent`. So an in-container pi never writes
|
||||
refreshed OAuth tokens back to the host, and `docker commit` exports stay
|
||||
secret-free. `models.json` is in the list because it holds user-defined custom
|
||||
providers, which would otherwise silently vanish inside containers.
|
||||
|
||||
Only those five files are seeded because `~/.pi/agent` also holds `sessions/`,
|
||||
`extensions/`, `skills/` and the installed package trees (`npm/`, `git/`), which
|
||||
on an active host is easily gigabytes.
|
||||
|
||||
**Trade-off:** in-container pi sessions are invisible host-side, so `pi -c` inside
|
||||
a Docker case only sees that container's own history.
|
||||
|
||||
## Remote SSH cases
|
||||
|
||||
`pi` mode is routed through an interactive login shell
|
||||
(`exec "$SHELL" -i -l -c 'pi'`), because sshd's remote-command PATH does not
|
||||
include npm's global bin on most hosts. Per-session config and `envOverrides` do
|
||||
not cross ssh and are rejected rather than silently ignored; use the per-host
|
||||
command override instead.
|
||||
|
||||
## Known gaps
|
||||
|
||||
- **No idle/completion hook.** Pi has no hook system Codeman can install into, so
|
||||
idle detection falls back to output-stabilization like the other external CLIs.
|
||||
Pi 0.84.0 shipped an `agent_settled` extension event that is a genuine idle
|
||||
signal; a Codeman pi extension using it is the highest-value follow-up.
|
||||
- **No response viewer.** Pi writes JSONL v3 session files under
|
||||
`~/.pi/agent/sessions/`; nothing reads them yet.
|
||||
- **Cron jobs mis-detect readiness.** The cron readiness poll looks for `❯` or a
|
||||
token count, neither of which pi prints, so a pi cron job burns its poll budget
|
||||
and then sends the prompt anyway. It works; it is just slower to start.
|
||||
- **Ralph, respawn heuristics, token/CLI-info parsing and the `❯` readiness probe
|
||||
are off** for pi, as for every external CLI.
|
||||
@@ -1,7 +1,7 @@
|
||||
# Remote Sessions (SSH)
|
||||
|
||||
Codeman can run a session's agent on a **remote host over SSH** instead of the
|
||||
local machine. The agent (Claude, OpenCode, Codex, Antigravity, Gemini, Pi, or a plain shell)
|
||||
local machine. The agent (Claude, OpenCode, Codex, Antigravity, Gemini, or a plain shell)
|
||||
runs inside a `tmux` server **on the remote host**, so it survives the SSH
|
||||
connection dropping; Codeman attaches to it the same way it attaches to a local
|
||||
managed session.
|
||||
@@ -30,7 +30,7 @@ Types live in `src/types/session.ts`; persistence in `src/remote-hosts.ts`.
|
||||
| `RemoteHost` (extends `RemoteSshOptions`) | A saved host: `id`, `label`, `host`, `username`, `port?`, `commands?` (per-mode launch command override). |
|
||||
| `RemoteCase` | A working directory on a host: `name`, `type: 'remote'`, `hostId`, `remotePath`. |
|
||||
| `SessionRemote` (extends `RemoteSshOptions`) | The resolved bundle stamped onto a live session: host coordinates + `remotePath` + `commands`, plus **`owned?`** and **`remoteSessionName?`** (COD-105 — see [Ownership](#ownership-launched-vs-discovered-and-attached-cod-105)). Built by `toSessionRemote(host, case)` (sets `owned: true`) for the launch path, or `toAttachedSessionRemote(host, name, path)` (sets `owned: false`) for the attach path. Both copy the advanced SSH options through so every connection is identical. |
|
||||
| `RemoteCommandMode` | `Extract<SessionMode, 'shell' \| 'claude' \| 'opencode' \| 'codex' \| 'gemini' \| 'antigravity' \| 'pi'>` — the modes that can run remotely. |
|
||||
| `RemoteCommandMode` | `Extract<SessionMode, 'shell' \| 'claude' \| 'opencode' \| 'codex' \| 'gemini' \| 'antigravity'>` — the modes that can run remotely. |
|
||||
| `RemoteSessionInfo` (COD-105) | One discovered remote tmux session: `name` (always `codeman-*`), `attached` (a client is connected), `created` (epoch s), `windows`. Returned by `listRemoteCodemanSessions()`. |
|
||||
|
||||
Persistence is two flat JSON arrays in the instance data dir:
|
||||
|
||||
@@ -489,7 +489,7 @@ production layout (`~/.codeman`, `-L codeman`, port 3000).
|
||||
Docker cases (1.4.0) run a session inside a per‑case container instead of on the host. The security posture:
|
||||
|
||||
- **Hardened create flags, always** — `--cap-drop ALL`, `--security-opt no-new-privileges`, `--pids-limit` (fork‑bomb guard), `--memory` == `--memory-swap` (a real OOM cap), `--init`, and non‑root: `--user <hostUid>:0` on Linux (host uid → workspace files stay host‑owned; GID 0 keeps `$HOME` writable), `--userns=keep-id` on rootless Podman. **Never** `--privileged`, and **never** the docker socket — the pure builder in `docker-hosts.ts` cannot emit them and the schema cannot represent them.
|
||||
- **Credentials never enter an image** — the convenient default bind‑mounts host cred dirs (`~/.claude`, `~/.codex`, `~/.gemini` — which also carries Antigravity's `antigravity-cli/` state — `~/.config/{gcloud,opencode}`, and five seeded files from `~/.pi/agent`) read‑write. Bind mounts are physically excluded from `docker commit`, so exported images are secret‑free. API‑key CLIs get their key as an exec‑time NAME‑ONLY `--env OPENAI_API_KEY` (no `=value`, no `ps` leak, never committed); a create‑time `-e` for a secret is never used. The **sealed** profile (`mountCredentials:false` + `network:none`) drops the host mounts; full‑image export is then refused (an in‑container login would ride the committed layer) unless a pre‑commit scrub is opted into.
|
||||
- **Credentials never enter an image** — the convenient default bind‑mounts host cred dirs (`~/.claude`, `~/.codex`, `~/.gemini` — which also carries Antigravity's `antigravity-cli/` state — and `~/.config/{gcloud,opencode}`) read‑write. Bind mounts are physically excluded from `docker commit`, so exported images are secret‑free. API‑key CLIs get their key as an exec‑time NAME‑ONLY `--env OPENAI_API_KEY` (no `=value`, no `ps` leak, never committed); a create‑time `-e` for a secret is never used. The **sealed** profile (`mountCredentials:false` + `network:none`) drops the host mounts; full‑image export is then refused (an in‑container login would ride the committed layer) unless a pre‑commit scrub is opted into.
|
||||
- **Blast radius — accept it explicitly** — the convenient profile mounts an arbitrary host workspace RW plus the host credential dirs RW into a network‑enabled container, so container‑run agent code can read/modify those host trees and reach the network at once. Still a net improvement over today's on‑host `--dangerously-skip-permissions` execution; use the sealed profile for genuinely untrusted work.
|
||||
- **Import is untrusted‑bundle‑safe** — `/api/docker-cases/import` validates the manifest + per‑member SHA‑256 before extraction, rejects absolute / `..` tar members (traversal guard), and re‑tags the loaded image into a quarantined namespace so it can never overwrite `codeman/agent:base` or a pre‑existing tag.
|
||||
- **Host guard & the bridge‑hooks listener** — in‑container hook callbacks carry `Host: host.docker.internal` / `host.containers.internal`; both are on the always‑on host‑header allowlist (`DOCKER_HOST_GATEWAY_ALIASES`) and resolve to the host only from inside a container netns, so they are not a browser DNS‑rebinding surface. On a loopback‑only server, in‑container hooks are opt‑in via `CODEMAN_DOCKER_BRIDGE_HOOKS=1`, which binds a SECOND listener on the docker bridge gateway serving **only** the hook endpoints (every other path → `403`) into the same hook‑secret‑gated pipeline. The bridge is host‑internal (containers + host), not the LAN, so it does not widen network exposure; the hook secret is bind‑mounted read‑only and referenced by path.
|
||||
|
||||
+5
-52
@@ -116,15 +116,6 @@ GEMINI_SEARCH_PATHS=(
|
||||
"$HOME/bin/gemini"
|
||||
)
|
||||
|
||||
# Pi CLI search paths (from src/utils/pi-cli-resolver.ts)
|
||||
PI_SEARCH_PATHS=(
|
||||
"$HOME/.local/bin/pi"
|
||||
"/usr/local/bin/pi"
|
||||
"$HOME/.bun/bin/pi"
|
||||
"$HOME/.npm-global/bin/pi"
|
||||
"$HOME/bin/pi"
|
||||
)
|
||||
|
||||
# Antigravity CLI search paths (from src/utils/antigravity-cli-resolver.ts)
|
||||
ANTIGRAVITY_SEARCH_PATHS=(
|
||||
"$HOME/.local/bin/agy"
|
||||
@@ -538,37 +529,6 @@ get_antigravity_path() {
|
||||
done
|
||||
}
|
||||
|
||||
# `pi` is a short, generic name (Raspberry Pi tooling, personal scripts), so the
|
||||
# server-side resolver additionally probes `pi --version`. Detection here only feeds
|
||||
# the "you have no AI CLI" hint, so a plain executable test is enough.
|
||||
check_pi() {
|
||||
if command -v pi &>/dev/null; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
for path in "${PI_SEARCH_PATHS[@]}"; do
|
||||
if [[ -x "$path" ]]; then
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
get_pi_path() {
|
||||
if command -v pi &>/dev/null; then
|
||||
command -v pi
|
||||
return
|
||||
fi
|
||||
|
||||
for path in "${PI_SEARCH_PATHS[@]}"; do
|
||||
if [[ -x "$path" ]]; then
|
||||
echo "$path"
|
||||
return
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
check_cloudflared() {
|
||||
# Check ~/.local/bin first (matches tunnel-manager.ts resolution order)
|
||||
if [[ -x "$HOME/.local/bin/cloudflared" ]]; then
|
||||
@@ -2069,13 +2029,12 @@ main() {
|
||||
fi
|
||||
fi
|
||||
|
||||
# AI CLI (Codeman drives one of: Claude Code, OpenCode, Codex, Gemini, Antigravity, Pi)
|
||||
# AI CLI (Codeman drives one of: Claude Code, OpenCode, Codex, Gemini, Antigravity)
|
||||
local has_claude=false
|
||||
local has_opencode=false
|
||||
local has_codex=false
|
||||
local has_gemini=false
|
||||
local has_antigravity=false
|
||||
local has_pi=false
|
||||
|
||||
info "Checking AI CLI tools..."
|
||||
if check_claude; then
|
||||
@@ -2098,21 +2057,17 @@ main() {
|
||||
has_antigravity=true
|
||||
success "Antigravity CLI found at $(get_antigravity_path)"
|
||||
fi
|
||||
if check_pi; then
|
||||
has_pi=true
|
||||
success "Pi CLI found at $(get_pi_path)"
|
||||
fi
|
||||
|
||||
if [[ "$has_claude" == "false" && "$has_opencode" == "false" && "$has_codex" == "false" && "$has_gemini" == "false" && "$has_antigravity" == "false" && "$has_pi" == "false" ]]; then
|
||||
if [[ "$has_claude" == "false" && "$has_opencode" == "false" && "$has_codex" == "false" && "$has_gemini" == "false" && "$has_antigravity" == "false" ]]; then
|
||||
echo ""
|
||||
warn "No AI CLI found. Codeman needs at least one: Claude Code, OpenCode, Codex, Antigravity, Gemini, or Pi."
|
||||
warn "No AI CLI found. Codeman needs at least one: Claude Code, OpenCode, Codex, Antigravity, or Gemini."
|
||||
headless_guard "install an AI CLI (curl | bash from its vendor)"
|
||||
echo ""
|
||||
echo -e " ${BOLD}Which AI CLI would you like to install?${NC}"
|
||||
echo -e " ${CYAN}1)${NC} Claude Code (Anthropic)"
|
||||
echo -e " ${CYAN}2)${NC} OpenCode (open-source)"
|
||||
echo -e " ${CYAN}3)${NC} Both"
|
||||
echo -e " ${CYAN}4)${NC} Skip (I'll install one myself, e.g. Codex, Antigravity or Pi)"
|
||||
echo -e " ${CYAN}4)${NC} Skip (I'll install one myself, e.g. Codex or Antigravity)"
|
||||
echo ""
|
||||
|
||||
local cli_choice=""
|
||||
@@ -2159,7 +2114,6 @@ main() {
|
||||
warn "Skipping AI CLI install. Codeman will run, but sessions need a CLI to drive."
|
||||
info "Install one later, e.g.: npm install -g @openai/codex (Codex)"
|
||||
info " or: curl -fsSL https://antigravity.google/cli/install.sh | bash (Antigravity)"
|
||||
info " or: npm install -g --ignore-scripts @earendil-works/pi-coding-agent (Pi)"
|
||||
elif [[ "$has_claude" == "false" ]] && [[ "$has_opencode" == "false" ]]; then
|
||||
die "The selected AI CLI failed to install. Install one manually and re-run the installer."
|
||||
fi
|
||||
@@ -2459,13 +2413,12 @@ main() {
|
||||
echo -e " https://github.com/Ark0N/Codeman"
|
||||
echo ""
|
||||
|
||||
if ! check_claude && ! check_opencode && ! check_codex && ! check_gemini && ! check_antigravity && ! check_pi; then
|
||||
if ! check_claude && ! check_opencode && ! check_codex && ! check_gemini && ! check_antigravity; then
|
||||
echo -e " ${YELLOW}${BOLD}Reminder:${NC} Install at least one AI CLI to start using Codeman:"
|
||||
echo -e " ${CYAN}curl -fsSL https://claude.ai/install.sh | bash${NC} # Claude Code"
|
||||
echo -e " ${CYAN}curl -fsSL https://opencode.ai/install | bash${NC} # OpenCode"
|
||||
echo -e " ${CYAN}npm install -g @openai/codex${NC} # Codex"
|
||||
echo -e " ${CYAN}curl -fsSL https://antigravity.google/cli/install.sh | bash${NC} # Antigravity"
|
||||
echo -e " ${CYAN}npm install -g --ignore-scripts @earendil-works/pi-coding-agent${NC} # Pi"
|
||||
echo ""
|
||||
fi
|
||||
|
||||
|
||||
@@ -58,7 +58,6 @@
|
||||
"opencode",
|
||||
"codex",
|
||||
"antigravity",
|
||||
"pi",
|
||||
"gemini-cli",
|
||||
"ai-agents",
|
||||
"agent",
|
||||
|
||||
@@ -568,7 +568,7 @@ recovered by submitting it with `{"input":"\r"}`.
|
||||
|
||||
⚠️ `stop` and `blocked` fire for `claude` sessions only (they are Claude Code hooks,
|
||||
and only when the workspace actually has them, see [§5.1](#51-where-to-spawn)). On
|
||||
`shell`/`opencode`/`codex`/`gemini`/`antigravity`/`pi`, requesting them explicitly is a
|
||||
`shell`/`opencode`/`codex`/`gemini`/`antigravity`, requesting them explicitly is a
|
||||
400, and lifecycle transitions there are coarse (a short shell command may emit **no**
|
||||
`idle` transition at all, verified live), so synchronize those with markers.
|
||||
|
||||
@@ -594,8 +594,7 @@ from the transcript file, which is flushed slightly *after* the `stop` hook fire
|
||||
single read taken the instant send-and-wait returns comes back `""` even though the
|
||||
turn finished (verified live: empty on the first call, full text seconds later). `text`
|
||||
is also `""` before the worker's first completed turn, and always `""` for modes with
|
||||
no transcript (`shell`, `opencode`, `gemini`, `antigravity`, `pi`; the first four
|
||||
verified live, pi from the same source path), which is
|
||||
no transcript (`shell`, `opencode`, `gemini`, `antigravity`, verified live), which is
|
||||
why the loop above is bounded rather than open-ended. Fall back to the terminal buffer
|
||||
there, tail in **bytes** (`textOutput` in `GET .../output` stays empty for interactive
|
||||
sessions; don't use it):
|
||||
@@ -679,7 +678,7 @@ turn), and both better than diffing terminal samples:
|
||||
```
|
||||
|
||||
⚠️ `active-tools` is parsed out of Claude's own output format, so it is **empty for
|
||||
`opencode`/`codex`/`gemini`/`antigravity`/`pi`** (those parsers are skipped wholesale) and
|
||||
`opencode`/`codex`/`gemini`/`antigravity`** (those parsers are skipped wholesale) and
|
||||
in practice empty for `shell`. Source-verified, not measured live.
|
||||
|
||||
Only if neither helps: sample `terminal?tail=` twice a few seconds apart. A changing
|
||||
|
||||
@@ -237,7 +237,7 @@ minutes, never retry the credential.
|
||||
flushed slightly *after* the `stop` hook fires, so a read taken the instant the wait
|
||||
returns is too early (verified live: empty on the first call, full prose seconds later).
|
||||
It is also `""` before the worker's first completed turn, and permanently `""` for
|
||||
`shell`, `opencode`, `gemini`, `antigravity` and `pi`, which write no Claude transcript.
|
||||
`shell`, `opencode`, `gemini` and `antigravity`, which write no transcript.
|
||||
|
||||
**Fix** Poll it, bounded (10 tries, 1 s apart). If it is still empty on a hook-less mode,
|
||||
that is expected, not a failure: read `terminal?tail=` and strip ANSI instead.
|
||||
@@ -334,20 +334,10 @@ ESC=$(printf '\033')
|
||||
|
||||
`POST /api/v1/quick-start` body (all optional):
|
||||
`{"caseName":"worker-1","mode":"claude","sessionName":"w9-worker","effort":"high"}`
|
||||
, `mode` ∈ `claude|shell|opencode|codex|gemini|antigravity|pi`; response is
|
||||
, `mode` ∈ `claude|shell|opencode|codex|gemini|antigravity`; response is
|
||||
`.data.{sessionId, caseName, casePath}`. Creates the case directory (a real directory
|
||||
on the user's disk) if missing, do not retry it in a loop, and remember the name.
|
||||
|
||||
⚠️ A `mode` whose CLI is **not installed on the server** fails the spawn with
|
||||
`OPERATION_FAILED`; it never falls back to claude. Probe first whenever you did not pick
|
||||
the mode yourself: `GET /api/v1/claude/status`, `GET /api/v1/opencode/status`,
|
||||
`GET /api/v1/codex/status`, `GET /api/v1/gemini/status`, `GET /api/v1/antigravity/status`
|
||||
and `GET /api/v1/pi/status` each return `.data.{available, path}` (no session needed).
|
||||
Pi's also carries `.data.version`, because `pi` is a short generic name that an unrelated
|
||||
binary on `$PATH` can shadow: the resolver rejects one whose `--version` is not
|
||||
semver-shaped, so `available:false` there can mean "a different `pi` is in front" rather
|
||||
than "nothing is installed". `shell` has no CLI to probe.
|
||||
|
||||
⚠️ **Branch on `.success` before reading `.data.sessionId`.** On any failure the field
|
||||
is absent, `jq -r` prints the literal string `null`, and every later call then targets
|
||||
`/api/v1/sessions/null`, burning the full readiness budget and reporting jq noise
|
||||
@@ -460,9 +450,9 @@ Quirks that will bite you:
|
||||
session answers with an empty timeline rather than a 404.
|
||||
- ⚠️ **`active-tools` proves presence, never absence.** It is fed by the BashToolParser,
|
||||
which reads Claude's rendered `● Bash(…)` lines, and `_processExpensiveParsers`
|
||||
returns early for every external CLI mode (`session.ts:2136`), so it is permanently
|
||||
`[]` on `opencode`/`codex`/`gemini`/`antigravity`/`pi`. ⚠️ **`shell` is NOT one of those**
|
||||
(`isExternalCliMode`, `session.ts:165-167`, lists only those five), so the parser does
|
||||
returns early for every external CLI mode (`session.ts:2086`), so it is permanently
|
||||
`[]` on `opencode`/`codex`/`gemini`/`antigravity`. ⚠️ **`shell` is NOT one of those**
|
||||
(`isExternalCliMode`, `session.ts:164-166`, lists only those four), so the parser does
|
||||
run on a shell worker, and `TEXT_COMMAND_PATTERN` (`bash-tool-parser.ts:88`) matches
|
||||
bare `tail|cat|head|less|grep|watch|multitail <path>` lines with no `● Bash(` wrapper:
|
||||
a shell worker running `cat build.log` really does populate this. In practice it stays
|
||||
|
||||
@@ -56,7 +56,7 @@ own head: the worker enforcing the cap is the one who has to be told about it.
|
||||
| synchronize on end of turn | HTTP `wait until=stop` (fires for message-initiated turns too, verified live) |
|
||||
| liveness / death check | HTTP `wait?until=exit` |
|
||||
| interrupt a running turn (break-glass) | HTTP input, a bare `\x1b` with no `\r` |
|
||||
| non-claude modes (`shell`/`opencode`/`codex`/`gemini`/`antigravity`/`pi`) | HTTP only (no other CLI has messaging) |
|
||||
| non-claude modes (`shell`/`opencode`/`codex`/`gemini`/`antigravity`) | HTTP only (no other CLI has messaging) |
|
||||
| delete | HTTP, via SKILL.md's `delete_session` guard |
|
||||
|
||||
## Availability: probe, never assume
|
||||
@@ -345,7 +345,7 @@ Without a break-glass, a pair with a bad brief is a token bonfire with no off sw
|
||||
|
||||
### Mixed fleets: the pairing matrix
|
||||
|
||||
Non-claude workers (`shell`, `opencode`, `codex`, `gemini`, `antigravity`, `pi`) cannot be peers
|
||||
Non-claude workers (`shell`, `opencode`, `codex`, `gemini`, `antigravity`) cannot be peers
|
||||
at all; no other CLI has this feature. Their tasks route over HTTP, and you never mention
|
||||
messaging in their briefs. The claude half of the fleet can use messaging among itself,
|
||||
subject to the namespace rule: **messaging works between two sessions that share one
|
||||
|
||||
@@ -177,7 +177,7 @@ for _ in $(seq 1 10); do
|
||||
done
|
||||
printf '%s\n' "$TXT"
|
||||
# (.data is {text,timestamp}; text is also "" before the first completed turn and
|
||||
# always "" for shell/opencode/gemini/antigravity/pi, which have no transcript, use
|
||||
# always "" for shell/opencode/gemini/antigravity, which have no transcript, use
|
||||
# the terminal tail there, and here only to diagnose an unsubmitted prompt.)
|
||||
|
||||
# 6. clean up: exact id, own list only, through the fail-closed preamble helper
|
||||
|
||||
@@ -7,8 +7,6 @@
|
||||
* @module config/dependency-registry
|
||||
*/
|
||||
|
||||
import { PI_VERSION_REGEX } from '../utils/pi-cli-resolver.js';
|
||||
|
||||
export type ProbeEnvironment = 'linux' | 'darwin' | 'win32' | 'wsl';
|
||||
|
||||
/** The valid `--category` filter values; single source of truth for the type, the CLI
|
||||
@@ -22,13 +20,6 @@ export interface PathResolver {
|
||||
bins: string[];
|
||||
versionArg?: string; // default '--version'
|
||||
versionRegex?: RegExp; // default matches first \d+.\d+(.\d+)?
|
||||
/**
|
||||
* Treat a binary whose version output does not match as NOT INSTALLED, instead of
|
||||
* reporting it with an unknown version. Only for tools with a short, generic binary
|
||||
* name (`pi`), where a `which` hit is not by itself evidence the right program is
|
||||
* there and a false "installed" contradicts the run mode's own resolver.
|
||||
*/
|
||||
requireVersionMatch?: boolean;
|
||||
}
|
||||
|
||||
/** Resolve a Windows-installed app reachable from win32 or WSL. */
|
||||
@@ -115,30 +106,6 @@ export const DEPENDENCY_REGISTRY: ToolDependency[] = [
|
||||
usedBy: ['Antigravity sessions'],
|
||||
resolvers: [{ match: ALL, resolver: { kind: 'path', bins: ['agy'], versionArg: '--version' } }],
|
||||
},
|
||||
{
|
||||
id: 'pi',
|
||||
label: 'Pi CLI',
|
||||
category: 'core',
|
||||
required: false,
|
||||
usedBy: ['Pi sessions'],
|
||||
// The only entry that requires a version match, for the same reason
|
||||
// pi-cli-resolver.ts probes: `pi` is a short generic name (Raspberry Pi tooling,
|
||||
// personal scripts), so a `which pi` hit alone is not the coding agent. Both sides
|
||||
// share PI_VERSION_REGEX, so the doctor and the run mode cannot drift into telling
|
||||
// the user opposite things about the same binary.
|
||||
resolvers: [
|
||||
{
|
||||
match: ALL,
|
||||
resolver: {
|
||||
kind: 'path',
|
||||
bins: ['pi'],
|
||||
versionArg: '--version',
|
||||
versionRegex: PI_VERSION_REGEX,
|
||||
requireVersionMatch: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'libreoffice',
|
||||
label: 'LibreOffice',
|
||||
|
||||
@@ -27,7 +27,7 @@ import { validateSessionFilePath } from '../web/route-helpers.js';
|
||||
import { computeNextRunAt, dueKeyFor } from './cron-time.js';
|
||||
import type { SessionPort, EventPort, ConfigPort, InfraPort } from '../web/ports/index.js';
|
||||
import type { CronJob, CronJobRun, CronJobRunStatus, TriggerType } from '../types/cron.js';
|
||||
import type { GeminiConfig, PiConfig, SessionMode } from '../types/session.js';
|
||||
import type { GeminiConfig } from '../types/session.js';
|
||||
import type { CronJobInput } from './cron-input.js';
|
||||
|
||||
/** The subset of the route context the cron depends on. */
|
||||
@@ -35,32 +35,6 @@ export type CronDeps = SessionPort & EventPort & ConfigPort & InfraPort;
|
||||
|
||||
const delay = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
/**
|
||||
* Section 6.3 clamp for a cron-launched external CLI, mirroring
|
||||
* `clampExternalCliBypassForOwner()` in session-routes.ts.
|
||||
*
|
||||
* A cron job carries NO per-CLI config, so what a non-granted owner actually gets is
|
||||
* each CLI's SPAWN DEFAULT, and for two of them that default is itself unsafe:
|
||||
* - gemini: `buildGeminiCommand(undefined)` emits `--approval-mode yolo` (classifier-free),
|
||||
* so `auto_edit` is materialized.
|
||||
* - pi: pi's own `defaultProjectTrust` is an interactive prompt the session user can simply
|
||||
* answer "yes" to, which then loads and EXECUTES repo-local `.pi/extensions` TypeScript,
|
||||
* so `approveProjectTrust: false` (`--no-approve`) is materialized. Omitting `--approve`
|
||||
* is NOT a clamp.
|
||||
* Codex and antigravity need nothing here: their absent config already spawns safe.
|
||||
* Granted/admin/single-user get undefined for both, i.e. upstream defaults untouched.
|
||||
*/
|
||||
export function clampCronExternalCliConfigs(
|
||||
mode: SessionMode,
|
||||
ownerGranted: boolean
|
||||
): { geminiConfig: GeminiConfig | undefined; piConfig: PiConfig | undefined } {
|
||||
if (ownerGranted) return { geminiConfig: undefined, piConfig: undefined };
|
||||
return {
|
||||
geminiConfig: mode === 'gemini' ? { approvalMode: 'auto_edit' } : undefined,
|
||||
piConfig: mode === 'pi' ? { approveProjectTrust: false } : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/** Hard ceiling on a prompt-file read (defends against unbounded-read DoS). */
|
||||
const MAX_PROMPT_FILE_BYTES = 1024 * 1024;
|
||||
|
||||
@@ -397,10 +371,13 @@ export class CronService {
|
||||
const claudeModeConfig = await this.deps.getClaudeModeConfig();
|
||||
const effectiveClaudeMode = await resolveClaudeModeForUsername(claudeModeConfig.claudeMode, job.owner);
|
||||
const model = mode !== 'shell' ? modelConfig?.defaultModel || undefined : undefined;
|
||||
// Section 6.3: materialize the safe default for a non-granted owner (see
|
||||
// clampCronExternalCliConfigs — cron sends no per-CLI config, so the CLI's own
|
||||
// spawn default is what would otherwise apply).
|
||||
const { geminiConfig, piConfig } = clampCronExternalCliConfigs(mode, ownerGranted);
|
||||
// Section 6.3: cron carries no per-CLI config, so buildGeminiCommand(undefined)
|
||||
// would default a non-granted owner to `--approval-mode yolo` (classifier-free) —
|
||||
// materialize auto_edit for a non-granted gemini owner, mirroring the route clamp
|
||||
// (#15). Granted/admin/single-user leave it undefined → yolo parity. Codex's absent
|
||||
// config already defaults to the safe sandbox, so no clamp is needed there.
|
||||
const geminiConfig: GeminiConfig | undefined =
|
||||
mode === 'gemini' && !ownerGranted ? { approvalMode: 'auto_edit' } : undefined;
|
||||
session = new Session({
|
||||
workingDir: job.workingDir,
|
||||
mode,
|
||||
@@ -412,7 +389,6 @@ export class CronService {
|
||||
claudeMode: effectiveClaudeMode,
|
||||
allowedTools: claudeModeConfig.allowedTools,
|
||||
geminiConfig,
|
||||
piConfig,
|
||||
owner: job.owner,
|
||||
});
|
||||
this.deps.addSession(session);
|
||||
|
||||
@@ -144,7 +144,6 @@ export function defaultDockerCommandForMode(mode: SessionMode): string {
|
||||
codex: 'exec codex',
|
||||
gemini: 'exec gemini',
|
||||
antigravity: 'exec agy',
|
||||
pi: 'exec pi',
|
||||
};
|
||||
return commands[mode as DockerCommandMode] || commands.shell;
|
||||
}
|
||||
@@ -601,19 +600,6 @@ const CRED_STORES: CredStorePolicy[] = [
|
||||
// `conversations/`, `knowledge/`) under `~/.gemini/antigravity-cli/`, so it needs no
|
||||
// entry of its own. There is no `~/.antigravity` credential dir to add.
|
||||
{ rel: '.gemini', seedWhole: true },
|
||||
// Pi (pi.dev) keeps auth + config in `~/.pi/agent`, but that dir ALSO holds
|
||||
// `sessions/`, `extensions/`, `skills/` and the installed package trees
|
||||
// (`npm/`, `git/`) — easily gigabytes on an active host, so seedWhole would
|
||||
// `cp -a` all of it into every container start. Seed only what pi needs to
|
||||
// authenticate and behave consistently; `models.json` is in the list because it
|
||||
// holds user-defined custom providers. Consequence to document: in-container pi
|
||||
// sessions are invisible host-side, so `pi -c` inside a Docker case only sees
|
||||
// that container's own history (unlike codex, whose `sessions/` is shared RW
|
||||
// precisely because Codeman reads it host-side).
|
||||
{
|
||||
rel: '.pi/agent',
|
||||
seedFiles: ['auth.json', 'settings.json', 'trust.json', 'models.json', 'models-store.json'],
|
||||
},
|
||||
{ rel: '.config/gcloud', seedWhole: true },
|
||||
{ rel: '.config/opencode', seedWhole: true },
|
||||
];
|
||||
|
||||
@@ -18,7 +18,6 @@ import type {
|
||||
EffortLevel,
|
||||
GeminiConfig,
|
||||
AntigravityConfig,
|
||||
PiConfig,
|
||||
SessionRemote,
|
||||
SessionDocker,
|
||||
} from './types.js';
|
||||
@@ -77,7 +76,6 @@ export interface CreateSessionOptions {
|
||||
codexConfig?: CodexConfig;
|
||||
geminiConfig?: GeminiConfig;
|
||||
antigravityConfig?: AntigravityConfig;
|
||||
piConfig?: PiConfig;
|
||||
/** When restoring after reboot, resume a previous Claude conversation by its session ID */
|
||||
resumeSessionId?: string;
|
||||
/** Extra env vars exported before launching the CLI (e.g., CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS). Ephemeral — not written to disk. */
|
||||
@@ -109,7 +107,6 @@ export interface RespawnPaneOptions {
|
||||
codexConfig?: CodexConfig;
|
||||
geminiConfig?: GeminiConfig;
|
||||
antigravityConfig?: AntigravityConfig;
|
||||
piConfig?: PiConfig;
|
||||
/** Resume a previous Claude conversation when respawning */
|
||||
resumeSessionId?: string;
|
||||
/** Extra env vars exported before launching the CLI (preserved across respawns). */
|
||||
|
||||
@@ -113,7 +113,6 @@ export function defaultRemoteCommandForMode(mode: SessionMode): string {
|
||||
codex: remoteLoginShellCommand('codex'),
|
||||
gemini: remoteLoginShellCommand('gemini'),
|
||||
antigravity: remoteLoginShellCommand('agy'),
|
||||
pi: remoteLoginShellCommand('pi'),
|
||||
};
|
||||
return commands[mode as RemoteCommandMode] || commands.shell;
|
||||
}
|
||||
@@ -268,7 +267,6 @@ const REMOTE_CLI_BIN: Partial<Record<SessionMode, string>> = {
|
||||
codex: 'codex',
|
||||
gemini: 'gemini',
|
||||
antigravity: 'agy',
|
||||
pi: 'pi',
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
+6
-39
@@ -50,7 +50,6 @@ import {
|
||||
type EffortLevel,
|
||||
type GeminiConfig,
|
||||
type AntigravityConfig,
|
||||
type PiConfig,
|
||||
type SessionRemote,
|
||||
type SessionDocker,
|
||||
} from './types.js';
|
||||
@@ -163,7 +162,7 @@ const NEWLINE_SPLIT_PATTERN = /\r?\n/;
|
||||
|
||||
/** True for external-CLI run modes (non-Claude) that use their own TUI and output format. */
|
||||
export function isExternalCliMode(mode: SessionMode): boolean {
|
||||
return mode === 'opencode' || mode === 'codex' || mode === 'gemini' || mode === 'antigravity' || mode === 'pi';
|
||||
return mode === 'opencode' || mode === 'codex' || mode === 'gemini' || mode === 'antigravity';
|
||||
}
|
||||
|
||||
function getModeLabel(mode: SessionMode): string {
|
||||
@@ -176,8 +175,6 @@ function getModeLabel(mode: SessionMode): string {
|
||||
return 'Gemini';
|
||||
case 'antigravity':
|
||||
return 'Antigravity';
|
||||
case 'pi':
|
||||
return 'Pi';
|
||||
case 'shell':
|
||||
return 'Shell';
|
||||
case 'claude':
|
||||
@@ -193,21 +190,9 @@ function getModeLabel(mode: SessionMode): string {
|
||||
* Codex, Claude Code, and Gemini are known, controlled (Ink/React) TUIs that
|
||||
* repaint via cursor positioning, so dropping the alt-screen switch is safe —
|
||||
* content stays in the normal buffer. Excluded: `shell` (arbitrary programs like
|
||||
* vim/less/htop legitimately need the alt screen), `opencode` (renders its own
|
||||
* TUI that may rely on it) and `pi` (below). Keep parity with the replay-side
|
||||
* strip in session-routes.ts.
|
||||
*
|
||||
* ⚠️ Being excluded here does NOT preserve the alt screen. Every excluded mode
|
||||
* falls through to isMuxAltScreenOnlyStripMode(), which strips the alt-screen
|
||||
* toggles too whenever the session is tmux-backed, and pi/opencode ALWAYS are
|
||||
* (both refuse the direct-PTY fallback). What exclusion actually buys is the rest
|
||||
* of the full strip: `\x1b[3J` and the mouse-tracking DECSETs survive. That is the
|
||||
* real reason pi is out: its default TUI renders into the MAIN screen with
|
||||
* terminal-owned scrollback and is mouse-aware, so it is a `3J`/mouse consumer in
|
||||
* a way an Ink TUI repainting in place is not. Consequence to know before
|
||||
* debugging it: pi's runtime-switchable fullscreen TUI (`/settings`, 0.84.0+)
|
||||
* still gets its `?1049h` stripped and paints into the main buffer, exactly like
|
||||
* vim inside a tmux `shell` session.
|
||||
* vim/less/htop legitimately need the alt screen) and `opencode` (renders its own
|
||||
* TUI that may rely on it). Keep parity with the replay-side strip in
|
||||
* session-routes.ts.
|
||||
*/
|
||||
export function isAltScreenStripMode(mode: SessionMode): boolean {
|
||||
return mode === 'codex' || mode === 'claude' || mode === 'gemini';
|
||||
@@ -483,8 +468,6 @@ export class Session extends EventEmitter {
|
||||
private _geminiConfig: GeminiConfig | undefined;
|
||||
// Antigravity configuration (only for mode === 'antigravity')
|
||||
private _antigravityConfig: AntigravityConfig | undefined;
|
||||
// Pi configuration (only for mode === 'pi')
|
||||
private _piConfig: PiConfig | undefined;
|
||||
private _resumeSessionId: string | undefined;
|
||||
|
||||
// Ephemeral env overrides (e.g., CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS). Exported by tmux
|
||||
@@ -578,8 +561,6 @@ export class Session extends EventEmitter {
|
||||
geminiConfig?: GeminiConfig;
|
||||
/** Antigravity configuration (only for mode === 'antigravity') */
|
||||
antigravityConfig?: AntigravityConfig;
|
||||
/** Pi configuration (only for mode === 'pi') */
|
||||
piConfig?: PiConfig;
|
||||
/** Resume a previous Claude conversation (used after server reboot) */
|
||||
resumeSessionId?: string;
|
||||
/** Extra env vars exported to the CLI at spawn time (no disk persistence) */
|
||||
@@ -673,11 +654,6 @@ export class Session extends EventEmitter {
|
||||
this._antigravityConfig = config.antigravityConfig;
|
||||
}
|
||||
|
||||
// Apply Pi configuration
|
||||
if (config.piConfig) {
|
||||
this._piConfig = config.piConfig;
|
||||
}
|
||||
|
||||
// Apply env overrides (exported at spawn, not persisted to disk).
|
||||
// Legacy migration: pre-0.7.2 carried effort as the CLAUDE_CODE_EFFORT_LEVEL env var,
|
||||
// which hard-locks /effort switching. Extract it into _effort (--settings soft default)
|
||||
@@ -1252,7 +1228,6 @@ export class Session extends EventEmitter {
|
||||
codexConfig: this._codexConfig,
|
||||
geminiConfig: this._geminiConfig,
|
||||
antigravityConfig: this._antigravityConfig,
|
||||
piConfig: this._piConfig,
|
||||
resumeSessionId: this._resumeSessionId,
|
||||
effort: this._effort,
|
||||
// COD-118: runtime-only — surfaced so the frontend can require explicit user
|
||||
@@ -1422,11 +1397,9 @@ export class Session extends EventEmitter {
|
||||
cols: ptyCols,
|
||||
rows: ptyRows,
|
||||
cwd: resolveMuxAttachCwd(this.workingDir, this._remote, this._docker),
|
||||
// COD-75: codex/gemini/antigravity/pi get COLORTERM=truecolor — mirrors buildEnvExports()
|
||||
// COD-75: codex/gemini/antigravity get COLORTERM=truecolor — mirrors buildEnvExports()
|
||||
// in tmux-manager.ts so the attach client and the tmux session agree.
|
||||
env: buildMuxAttachEnv(
|
||||
this.mode === 'codex' || this.mode === 'gemini' || this.mode === 'antigravity' || this.mode === 'pi'
|
||||
),
|
||||
env: buildMuxAttachEnv(this.mode === 'codex' || this.mode === 'gemini' || this.mode === 'antigravity'),
|
||||
})
|
||||
);
|
||||
} catch (spawnErr) {
|
||||
@@ -1494,7 +1467,6 @@ export class Session extends EventEmitter {
|
||||
codexConfig: this._codexConfig,
|
||||
geminiConfig: this._geminiConfig,
|
||||
antigravityConfig: this._antigravityConfig,
|
||||
piConfig: this._piConfig,
|
||||
resumeSessionId: this._resumeSessionId,
|
||||
envOverrides: this._envOverrides,
|
||||
effort: this._effort,
|
||||
@@ -1709,7 +1681,6 @@ export class Session extends EventEmitter {
|
||||
codexConfig: this._codexConfig,
|
||||
geminiConfig: this._geminiConfig,
|
||||
antigravityConfig: this._antigravityConfig,
|
||||
piConfig: this._piConfig,
|
||||
resumeSessionId: this._resumeSessionId,
|
||||
envOverrides: this._envOverrides,
|
||||
effort: this._effort,
|
||||
@@ -1795,10 +1766,6 @@ export class Session extends EventEmitter {
|
||||
if (this.mode === 'antigravity') {
|
||||
throw new Error('Antigravity sessions require tmux. Direct PTY fallback is not supported.');
|
||||
}
|
||||
// Pi sessions require tmux for env override injection via setenv
|
||||
if (this.mode === 'pi') {
|
||||
throw new Error('Pi sessions require tmux. Direct PTY fallback is not supported.');
|
||||
}
|
||||
try {
|
||||
// Pass --session-id to use the SAME ID as the Codeman session
|
||||
// This ensures subagents can be directly matched to the correct tab
|
||||
|
||||
+2
-80
@@ -45,7 +45,6 @@ import {
|
||||
type EffortLevel,
|
||||
type GeminiConfig,
|
||||
type AntigravityConfig,
|
||||
type PiConfig,
|
||||
type SessionRemote,
|
||||
type SessionDocker,
|
||||
type DockerCommandMode,
|
||||
@@ -79,7 +78,6 @@ import {
|
||||
resolveCodexDir,
|
||||
resolveGeminiDir,
|
||||
resolveAntigravityDir,
|
||||
resolvePiDir,
|
||||
resolveLocalShell,
|
||||
loginShellArgs,
|
||||
} from './utils/index.js';
|
||||
@@ -737,63 +735,6 @@ function buildAntigravityCommand(config?: AntigravityConfig): string {
|
||||
return parts.join(' ');
|
||||
}
|
||||
|
||||
/** Pi's `--thinking` levels. Runtime allowlist — defense in depth beyond the Zod enum. */
|
||||
const PI_THINKING_LEVELS = new Set(['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max']);
|
||||
|
||||
/**
|
||||
* Build the Pi CLI (pi.dev) command with appropriate flags.
|
||||
*
|
||||
* Pi has NO permission prompts and no `--dangerously-skip-permissions` analog, so
|
||||
* there is deliberately nothing bypass-shaped here. The privileged knob is the
|
||||
* TRI-STATE `approveProjectTrust`: `true` -> `--approve` (trust repo-local `.pi/`
|
||||
* config, which means loading and EXECUTING repository TypeScript and installing
|
||||
* missing project packages), `false` -> `--no-approve` (force-deny, used by the
|
||||
* multi-user clamp so the trust prompt never appears), absent -> pi's own
|
||||
* `defaultProjectTrust`.
|
||||
*
|
||||
* `--api-key` is deliberately NEVER wired: it would put a provider secret on the
|
||||
* spawn command line (visible in `ps` and tmux state), which is exactly what the
|
||||
* socket-scoped `tmux setenv` discipline exists to prevent.
|
||||
*
|
||||
* Like the sibling builders, every user value is regex-allowlisted and silently
|
||||
* DROPPED on failure — the result is interpolated into a `bash -c "..."` string.
|
||||
*/
|
||||
function buildPiCommand(config?: PiConfig): string {
|
||||
const parts = ['pi'];
|
||||
|
||||
if (config?.approveProjectTrust === true) {
|
||||
parts.push('--approve');
|
||||
} else if (config?.approveProjectTrust === false) {
|
||||
parts.push('--no-approve');
|
||||
}
|
||||
|
||||
if (config?.model) {
|
||||
// `:` for a thinking suffix (`sonnet:high`), `/` for `provider/id` (`openai/gpt-4o`).
|
||||
const safeModel = /^[a-zA-Z0-9._\-/:]+$/.test(config.model) ? config.model : undefined;
|
||||
if (safeModel) parts.push('--model', safeModel);
|
||||
}
|
||||
|
||||
if (config?.provider) {
|
||||
const safeProvider = /^[a-z0-9-]+$/.test(config.provider) ? config.provider : undefined;
|
||||
if (safeProvider) parts.push('--provider', safeProvider);
|
||||
}
|
||||
|
||||
if (config?.thinking && PI_THINKING_LEVELS.has(config.thinking)) {
|
||||
parts.push('--thinking', config.thinking);
|
||||
}
|
||||
|
||||
// --session and -c conflict; a valid explicit session id wins.
|
||||
const safeSessionId =
|
||||
config?.resumeSessionId && /^[a-zA-Z0-9._-]+$/.test(config.resumeSessionId) ? config.resumeSessionId : undefined;
|
||||
if (safeSessionId) {
|
||||
parts.push('--session', safeSessionId);
|
||||
} else if (config?.continueSession) {
|
||||
parts.push('-c');
|
||||
}
|
||||
|
||||
return parts.join(' ');
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the spawn command for any session mode.
|
||||
* Shared by createSession() and respawnPane() to avoid duplication.
|
||||
@@ -836,7 +777,6 @@ export function buildSpawnCommand(options: {
|
||||
codexConfig?: CodexConfig;
|
||||
geminiConfig?: GeminiConfig;
|
||||
antigravityConfig?: AntigravityConfig;
|
||||
piConfig?: PiConfig;
|
||||
resumeSessionId?: string;
|
||||
effort?: EffortLevel;
|
||||
/** Codeman session name, passed to claude as `--name` (version-gated, sanitized; local spawns only). */
|
||||
@@ -883,9 +823,6 @@ export function buildSpawnCommand(options: {
|
||||
if (options.mode === 'antigravity') {
|
||||
return buildAntigravityCommand(options.antigravityConfig);
|
||||
}
|
||||
if (options.mode === 'pi') {
|
||||
return buildPiCommand(options.piConfig);
|
||||
}
|
||||
// #208: NOT the literal '$SHELL'. This string is embedded in the `bash -c "…"`
|
||||
// argument of the respawn-pane line, which execSync runs through `/bin/sh -c`,
|
||||
// so a `$SHELL` here is expanded by the SERVER process's shell against the
|
||||
@@ -1099,8 +1036,6 @@ function appendResumeFlag(modeCommand: string, mode: SessionMode, resumeId: stri
|
||||
return `${modeCommand} resume ${resumeId}`;
|
||||
case 'antigravity':
|
||||
return `${modeCommand} --conversation ${resumeId}`;
|
||||
case 'pi':
|
||||
return `${modeCommand} --session ${resumeId}`;
|
||||
default:
|
||||
return modeCommand; // shell / opencode: no resume
|
||||
}
|
||||
@@ -1669,10 +1604,10 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
const exports = [
|
||||
'export LANG=en_US.UTF-8',
|
||||
'export LC_ALL=en_US.UTF-8',
|
||||
mode === 'codex' || mode === 'gemini' || mode === 'antigravity' || mode === 'pi'
|
||||
mode === 'codex' || mode === 'gemini' || mode === 'antigravity'
|
||||
? 'export COLORTERM=truecolor'
|
||||
: 'unset COLORTERM',
|
||||
...(mode === 'codex' || mode === 'gemini' || mode === 'antigravity' || mode === 'pi' ? ['unset NO_COLOR'] : []),
|
||||
...(mode === 'codex' || mode === 'gemini' || mode === 'antigravity' ? ['unset NO_COLOR'] : []),
|
||||
// Stamp each Codex pane with a unique originator so the response-viewer
|
||||
// can locate THIS pane's rollout exactly — codex writes the value into
|
||||
// session_meta.originator of every rollout it creates. Without it,
|
||||
@@ -1763,10 +1698,6 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
const dir = resolveAntigravityDir();
|
||||
return { pathExport: dir ? `export PATH="${dir}:$PATH" && ` : '', dir };
|
||||
}
|
||||
if (mode === 'pi') {
|
||||
const dir = resolvePiDir();
|
||||
return { pathExport: dir ? `export PATH="${dir}:$PATH" && ` : '', dir };
|
||||
}
|
||||
return { pathExport: '', dir: null };
|
||||
}
|
||||
|
||||
@@ -1815,7 +1746,6 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
codexConfig,
|
||||
geminiConfig,
|
||||
antigravityConfig,
|
||||
piConfig,
|
||||
resumeSessionId,
|
||||
envOverrides,
|
||||
effort,
|
||||
@@ -1872,11 +1802,6 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
'Antigravity CLI not found. Install with: curl -fsSL https://antigravity.google/cli/install.sh | bash'
|
||||
);
|
||||
}
|
||||
if (mode === 'pi' && !cliDir) {
|
||||
throw new Error(
|
||||
'Pi CLI not found. Install with: npm install -g --ignore-scripts @earendil-works/pi-coding-agent'
|
||||
);
|
||||
}
|
||||
|
||||
const envExportsStr = this.buildEnvExports(sessionId, muxName, mode).join(' && ');
|
||||
|
||||
@@ -1890,7 +1815,6 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
codexConfig,
|
||||
geminiConfig,
|
||||
antigravityConfig,
|
||||
piConfig,
|
||||
resumeSessionId,
|
||||
effort,
|
||||
sessionName: name,
|
||||
@@ -2115,7 +2039,6 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
codexConfig,
|
||||
geminiConfig,
|
||||
antigravityConfig,
|
||||
piConfig,
|
||||
resumeSessionId,
|
||||
envOverrides,
|
||||
effort,
|
||||
@@ -2155,7 +2078,6 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
codexConfig,
|
||||
geminiConfig,
|
||||
antigravityConfig,
|
||||
piConfig,
|
||||
resumeSessionId,
|
||||
effort,
|
||||
sessionName: name,
|
||||
|
||||
+4
-38
@@ -8,14 +8,13 @@
|
||||
* - SessionConfig — creation-time config (id, workingDir, createdAt)
|
||||
* - SessionOutput — captured stdout/stderr/exitCode
|
||||
* - SessionStatus — 'idle' | 'busy' | 'stopped' | 'error'
|
||||
* - SessionMode — 'claude' | 'shell' | 'opencode' | 'codex' | 'gemini' | 'antigravity' | 'pi' (which CLI backend)
|
||||
* - SessionMode — 'claude' | 'shell' | 'opencode' | 'codex' | 'gemini' | 'antigravity' (which CLI backend)
|
||||
* - ClaudeMode — CLI permission mode ('dangerously-skip-permissions' | 'auto' | 'normal' | 'allowedTools')
|
||||
* - SessionColor — visual differentiation color
|
||||
* - OpenCodeConfig — OpenCode-specific settings (model, autoAllowTools, continueSession)
|
||||
* - CodexConfig — Codex (OpenAI CLI)-specific settings (model, resumeSessionId)
|
||||
* - GeminiConfig — Gemini CLI-specific settings (model, approvalMode, resumeSession)
|
||||
* - AntigravityConfig — Antigravity CLI (agy) settings (model, dangerouslySkipPermissions, resumeConversationId)
|
||||
* - PiConfig — Pi CLI (pi.dev) settings (model, provider, thinking, resume/continue, project trust)
|
||||
*
|
||||
* Cross-domain relationships:
|
||||
* - SessionState.respawnConfig embeds RespawnConfig (respawn domain)
|
||||
@@ -44,11 +43,11 @@ export type SessionStatus = 'idle' | 'busy' | 'stopped' | 'error';
|
||||
export type ClaudeMode = 'dangerously-skip-permissions' | 'auto' | 'normal' | 'allowedTools';
|
||||
|
||||
/** Session mode: which CLI backend a session runs */
|
||||
export type SessionMode = 'claude' | 'shell' | 'opencode' | 'codex' | 'gemini' | 'antigravity' | 'pi';
|
||||
export type SessionMode = 'claude' | 'shell' | 'opencode' | 'codex' | 'gemini' | 'antigravity';
|
||||
|
||||
export type RemoteCommandMode = Extract<
|
||||
SessionMode,
|
||||
'shell' | 'claude' | 'opencode' | 'codex' | 'gemini' | 'antigravity' | 'pi'
|
||||
'shell' | 'claude' | 'opencode' | 'codex' | 'gemini' | 'antigravity'
|
||||
>;
|
||||
|
||||
/**
|
||||
@@ -157,7 +156,7 @@ export interface RemoteSessionInfo {
|
||||
/** Which CLI backends a Docker case can run (same set as remote). */
|
||||
export type DockerCommandMode = Extract<
|
||||
SessionMode,
|
||||
'shell' | 'claude' | 'opencode' | 'codex' | 'gemini' | 'antigravity' | 'pi'
|
||||
'shell' | 'claude' | 'opencode' | 'codex' | 'gemini' | 'antigravity'
|
||||
>;
|
||||
|
||||
/** Container engine. Docker and Podman differ in the uid/userns + host-gateway alias. */
|
||||
@@ -332,37 +331,6 @@ export interface AntigravityConfig {
|
||||
resumeConversationId?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pi CLI (pi.dev) session configuration.
|
||||
*
|
||||
* Pi has NO permission prompts and no `--dangerously-skip-permissions` analog,
|
||||
* so there is deliberately no bypass field here. The one privilege-shaped knob is
|
||||
* `approveProjectTrust`, which controls whether pi loads and EXECUTES repo-local
|
||||
* `.pi/` extensions (and installs missing project packages).
|
||||
*/
|
||||
export interface PiConfig {
|
||||
/** Model pattern or ID. Supports `provider/id` and a `:<thinking>` suffix (e.g. `sonnet:high`). Passed via --model. */
|
||||
model?: string;
|
||||
/** Provider name (anthropic, openai, google, ...). Passed via --provider. */
|
||||
provider?: string;
|
||||
/** Reasoning level. Passed via --thinking. */
|
||||
thinking?: 'off' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max';
|
||||
/** Continue the most recent session (-c). Skipped when resumeSessionId is set (the two conflict). */
|
||||
continueSession?: boolean;
|
||||
/** Resume a specific session by ID or partial UUID (--session). Ids only, never paths. */
|
||||
resumeSessionId?: string;
|
||||
/**
|
||||
* Tri-state project trust (repo-local `.pi/` settings/extensions/skills, plus
|
||||
* installing missing project packages):
|
||||
* true -> --approve (trust for this run; loads and EXECUTES repository TypeScript)
|
||||
* false -> --no-approve (force-deny; the trust prompt never appears)
|
||||
* absent -> pi's own defaultProjectTrust (ask).
|
||||
* Multi-user: MATERIALIZED to false for non-granted owners, because pi's
|
||||
* absent-config default is a prompt the session user could answer themselves.
|
||||
*/
|
||||
approveProjectTrust?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration for creating a new session
|
||||
*/
|
||||
@@ -516,8 +484,6 @@ export interface SessionState {
|
||||
geminiConfig?: GeminiConfig;
|
||||
/** Antigravity-specific configuration (only for mode === 'antigravity') */
|
||||
antigravityConfig?: AntigravityConfig;
|
||||
/** Pi-specific configuration (only for mode === 'pi') */
|
||||
piConfig?: PiConfig;
|
||||
/** Claude conversation session ID to resume after reboot (set by restore script) */
|
||||
resumeSessionId?: string;
|
||||
/** Claude CLI effort level (soft default via --settings, switchable in-session via /effort) */
|
||||
|
||||
@@ -94,17 +94,12 @@ export function checkTool(tool: ToolDependency, host: ProbeHost): ToolResult {
|
||||
if (!spec) return { ...base, status: 'skipped', reason: `not applicable on ${host.environment}` };
|
||||
|
||||
if (spec.resolver.kind === 'path') {
|
||||
const { bins, versionArg, versionRegex, requireVersionMatch } = spec.resolver;
|
||||
const { bins, versionArg, versionRegex } = spec.resolver;
|
||||
for (const bin of bins) {
|
||||
const resolved = host.which(bin);
|
||||
if (resolved) {
|
||||
const out = host.runVersion(bin, [versionArg ?? '--version']);
|
||||
const version = out ? extractVersion(out, versionRegex) : undefined;
|
||||
// A generic binary name that prints the wrong thing is some OTHER program (see
|
||||
// PathResolver.requireVersionMatch). Keep looking, then report MISSING; the
|
||||
// alternative is claiming a tool is installed that the feature's own resolver
|
||||
// rejects, which reads as "the mode is broken" rather than "install it".
|
||||
if (requireVersionMatch && !version) continue;
|
||||
return finalize(base, tool, resolved, version);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,4 +34,3 @@ export { resolveOpenCodeDir } from './opencode-cli-resolver.js';
|
||||
export { resolveCodexDir, isCodexAvailable } from './codex-cli-resolver.js';
|
||||
export { resolveGeminiDir, isGeminiAvailable } from './gemini-cli-resolver.js';
|
||||
export { resolveAntigravityDir, isAntigravityAvailable } from './antigravity-cli-resolver.js';
|
||||
export { resolvePiDir, isPiAvailable, getPiCliVersion } from './pi-cli-resolver.js';
|
||||
|
||||
@@ -1,146 +0,0 @@
|
||||
/**
|
||||
* @fileoverview Resolve the Pi CLI (`pi`) binary across common install paths.
|
||||
*
|
||||
* Mirrors antigravity-cli-resolver.ts, with one addition the other external-CLI
|
||||
* resolvers do not need: `pi` is a SHORT, GENERIC name (Raspberry Pi tooling,
|
||||
* personal scripts, `$PATH` accidents), so a `which pi` hit is not by itself
|
||||
* evidence that the coding agent is installed. Every candidate is therefore
|
||||
* sanity-probed with `pi --version` and required to print a semver-shaped
|
||||
* string; a binary that fails the probe is treated as absent and the rejected
|
||||
* path is logged so a misresolution is diagnosable.
|
||||
*
|
||||
* Pi ships as the npm package `@earendil-works/pi-coding-agent`, so the search
|
||||
* dirs are the usual global-bin locations (npm/bun/manual installs).
|
||||
*
|
||||
* @module utils/pi-cli-resolver
|
||||
*/
|
||||
|
||||
import { execFileSync, execSync } from 'node:child_process';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import { EXEC_TIMEOUT_MS } from '../config/exec-timeout.js';
|
||||
|
||||
/** Common directories where the Pi CLI binary may be installed */
|
||||
const PI_SEARCH_DIRS = [
|
||||
join(homedir(), '.local', 'bin'),
|
||||
'/usr/local/bin',
|
||||
join(homedir(), '.bun', 'bin'),
|
||||
join(homedir(), '.npm-global', 'bin'),
|
||||
join(homedir(), 'bin'),
|
||||
];
|
||||
|
||||
/**
|
||||
* A real `pi --version` prints a semver-shaped string (e.g. `0.84.1`).
|
||||
*
|
||||
* Exported and SHARED with the `pi` entry in `config/dependency-registry.ts`, so
|
||||
* `codeman doctor` and the run mode cannot disagree about what counts as an installed
|
||||
* pi: two copies of this rule would let the Dependencies panel report "Pi CLI ✓" on a
|
||||
* box where `resolvePiDir()` rejects the same binary and Run Pi stays hidden.
|
||||
*
|
||||
* Shape is dictated by the doctor's `extractVersion()`, which returns the first CAPTURE
|
||||
* GROUP and scans the whole output: hence a capturing group, and a leading boundary
|
||||
* instead of `^` so `pi 0.84.1` matches while `v0.84.1` (some other program) does not.
|
||||
* No `g` flag, so there is no shared `lastIndex` to reset.
|
||||
*/
|
||||
export const PI_VERSION_REGEX = /(?:^|\s)(\d+\.\d+\.\d+)/;
|
||||
|
||||
/** Cached directory containing the pi binary (empty string = searched but not found) */
|
||||
let _piDir: string | null = null;
|
||||
/** Cached version string reported by the resolved binary (empty string = probed, unusable) */
|
||||
let _piVersion: string | null = null;
|
||||
|
||||
/**
|
||||
* Run `pi --version` on a candidate path and return the trimmed version when it
|
||||
* looks like the coding agent. Returns null for anything else — a missing
|
||||
* binary, a non-zero exit, a hang (timeout), or output that is not semver-shaped
|
||||
* (which is how an unrelated `pi` on PATH gets rejected).
|
||||
*
|
||||
* Never runs under vitest: the suites must stay hermetic and must not depend on
|
||||
* whether the dev box happens to have pi installed.
|
||||
*/
|
||||
function probePiVersion(binPath: string): string | null {
|
||||
if (process.env.VITEST) return null;
|
||||
try {
|
||||
const out = execFileSync(binPath, ['--version'], {
|
||||
encoding: 'utf-8',
|
||||
timeout: EXEC_TIMEOUT_MS,
|
||||
stdio: ['ignore', 'pipe', 'ignore'],
|
||||
}).trim();
|
||||
// Upstream prints a bare version today; tolerate a `pi 0.84.1` style prefix too.
|
||||
const candidate = PI_VERSION_REGEX.exec(out)?.[1];
|
||||
if (candidate) return candidate;
|
||||
console.warn(`[PiResolver] Ignoring ${binPath}: "pi --version" printed ${JSON.stringify(out.slice(0, 80))}`);
|
||||
} catch (err) {
|
||||
console.warn(`[PiResolver] Ignoring ${binPath}: "pi --version" failed (${(err as Error).message})`);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the directory containing a verified `pi` binary.
|
||||
* Checks `which pi` first, then falls back to common install locations. Every
|
||||
* candidate must pass the `pi --version` sanity probe (§2.6 of the integration
|
||||
* plan) before it is accepted.
|
||||
*
|
||||
* @returns Directory path, or null if not found
|
||||
*/
|
||||
export function resolvePiDir(): string | null {
|
||||
if (_piDir !== null) return _piDir || null;
|
||||
|
||||
const accept = (binPath: string): string | null => {
|
||||
// Under vitest the probe never runs, so existence alone decides (keeps the
|
||||
// suites hermetic and matches how the sibling resolvers behave there).
|
||||
if (process.env.VITEST) {
|
||||
_piDir = dirname(binPath);
|
||||
_piVersion = '';
|
||||
return _piDir;
|
||||
}
|
||||
const version = probePiVersion(binPath);
|
||||
if (!version) return null;
|
||||
_piDir = dirname(binPath);
|
||||
_piVersion = version;
|
||||
return _piDir;
|
||||
};
|
||||
|
||||
try {
|
||||
const result = execSync('which pi', {
|
||||
encoding: 'utf-8',
|
||||
timeout: EXEC_TIMEOUT_MS,
|
||||
}).trim();
|
||||
if (result && existsSync(result)) {
|
||||
const dir = accept(result);
|
||||
if (dir) return dir;
|
||||
}
|
||||
} catch {
|
||||
// pi not in PATH, will check common locations
|
||||
}
|
||||
|
||||
for (const dir of PI_SEARCH_DIRS) {
|
||||
const binPath = join(dir, 'pi');
|
||||
if (!existsSync(binPath)) continue;
|
||||
const accepted = accept(binPath);
|
||||
if (accepted) return accepted;
|
||||
}
|
||||
|
||||
_piDir = '';
|
||||
_piVersion = '';
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the Pi CLI is available on the system.
|
||||
*/
|
||||
export function isPiAvailable(): boolean {
|
||||
return resolvePiDir() !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Version reported by the resolved `pi` binary, or null when pi is unavailable
|
||||
* (or when the probe was skipped, i.e. under vitest). Surfaced through
|
||||
* `GET /api/pi/status` so a misresolution is diagnosable from the UI.
|
||||
*/
|
||||
export function getPiCliVersion(): string | null {
|
||||
resolvePiDir();
|
||||
return _piVersion || null;
|
||||
}
|
||||
+91
-12
@@ -684,6 +684,17 @@ class CodemanApp {
|
||||
this.maxReconnectAttempts = 10;
|
||||
this.isOnline = navigator.onLine;
|
||||
|
||||
// SSE staleness watchdog. An EventSource that stops delivering does not
|
||||
// always error (a proxy that idle-closed it, a resumed laptop), so
|
||||
// `onerror` never fires and every SSE-driven surface freezes silently.
|
||||
// The server heartbeats every 15s; going quiet for three of them means the
|
||||
// stream is a zombie and has to be rebuilt. The decision is pure
|
||||
// (computeSseStale in constants.js); these are its inputs. The threshold
|
||||
// is an instance field so a browser test can shrink it.
|
||||
this._sseLastMessageAt = 0;
|
||||
this._sseStaleTimeoutMs = window.CodemanSseStale?.TIMEOUT_MS ?? 45000;
|
||||
this._sseStaleWatchdog = null;
|
||||
|
||||
// Connection-loss UI (banner + full-screen overlay). The decision itself is
|
||||
// pure and lives in constants.js (computeConnectionLossUi); these are just
|
||||
// its inputs. `_connDownSince` is the timestamp the transport LEFT the
|
||||
@@ -719,6 +730,11 @@ class CodemanApp {
|
||||
window.addEventListener('pagehide', () => this._persistReliableNow());
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
if (document.visibilityState === 'hidden') this._persistReliableNow();
|
||||
// A background tab's timers are throttled, so the 5s watchdog may not
|
||||
// have run for minutes, and a wake/unlock is exactly when a stream
|
||||
// comes back zombie. Checking here is what makes recovery feel instant
|
||||
// instead of up to a full timeout late.
|
||||
else this._checkSseStale();
|
||||
});
|
||||
|
||||
// Local echo overlay — DOM overlay positioned at the visible ❯ prompt
|
||||
@@ -1421,6 +1437,14 @@ class CodemanApp {
|
||||
// Clear any pending reconnect timeout to prevent duplicate connections
|
||||
this._clearTimer('sseReconnectTimeout');
|
||||
|
||||
// Same discipline for the staleness watchdog: connectSSE() runs on every
|
||||
// reconnect and is the only teardown path this page-lifetime interval has,
|
||||
// so clearing it anywhere else (or not at all) stacks intervals.
|
||||
if (this._sseStaleWatchdog) {
|
||||
clearInterval(this._sseStaleWatchdog);
|
||||
this._sseStaleWatchdog = null;
|
||||
}
|
||||
|
||||
// Clean up existing SSE listeners before creating new connection (prevents listener accumulation)
|
||||
if (this._sseListenerCleanup) {
|
||||
this._sseListenerCleanup();
|
||||
@@ -1448,11 +1472,20 @@ class CodemanApp {
|
||||
if (this.activeSessionId) _sseParams.set('sessions', this.activeSessionId);
|
||||
this.eventSource = new EventSource(`/api/events?${_sseParams.toString()}`);
|
||||
|
||||
// Store all event listeners for cleanup on reconnect
|
||||
// Store all event listeners for cleanup on reconnect.
|
||||
//
|
||||
// Every handler is wrapped so ANY frame that arrives stamps the liveness
|
||||
// clock the staleness watchdog reads. Doing it here (rather than at the
|
||||
// three separate registration sites below) is what keeps a future
|
||||
// addListener() call from silently opting out of it.
|
||||
const listeners = [];
|
||||
const addListener = (event, handler) => {
|
||||
this.eventSource.addEventListener(event, handler);
|
||||
listeners.push({ event, handler });
|
||||
const stamped = (e) => {
|
||||
this._sseLastMessageAt = Date.now();
|
||||
handler(e);
|
||||
};
|
||||
this.eventSource.addEventListener(event, stamped);
|
||||
listeners.push({ event, handler: stamped });
|
||||
};
|
||||
|
||||
// Create cleanup function to remove all listeners
|
||||
@@ -1467,6 +1500,10 @@ class CodemanApp {
|
||||
|
||||
this.eventSource.onopen = () => {
|
||||
this.reconnectAttempts = 0;
|
||||
// Start the liveness clock here, not at the first frame: the watchdog
|
||||
// only ever fires while the status is 'connected', and this is the
|
||||
// moment that becomes true.
|
||||
this._sseLastMessageAt = Date.now();
|
||||
this.setConnectionStatus('connected');
|
||||
};
|
||||
this.eventSource.onerror = () => {
|
||||
@@ -1614,6 +1651,52 @@ class CodemanApp {
|
||||
}
|
||||
this._onSessionListMaybeChanged();
|
||||
});
|
||||
|
||||
// Liveness heartbeat. The handler is deliberately empty: the whole point
|
||||
// is the stamp inherited from addListener's wrapper. It still has to be
|
||||
// REGISTERED: EventSource only dispatches named events that have a
|
||||
// listener, so without this the frame arrives on the wire and is dropped
|
||||
// before it can prove the stream is alive.
|
||||
addListener(SSE_EVENTS.HEARTBEAT, () => {});
|
||||
|
||||
// Watchdog: a stream that goes quiet without erroring is invisible to
|
||||
// onerror, so poll the pure staleness policy and rebuild the connection
|
||||
// ourselves. 5s granularity against a 45s threshold: cheap, and it keeps
|
||||
// the worst-case detection lag well under a heartbeat interval.
|
||||
this._sseStaleWatchdog = setInterval(() => this._checkSseStale(), 5000);
|
||||
}
|
||||
|
||||
/**
|
||||
* Force a reconnect if the SSE stream has gone quiet while still claiming to
|
||||
* be connected. Called by the 5s watchdog and on tab-visible.
|
||||
*
|
||||
* Recovery needs no new sync path: the reconnect re-runs `handleInit`, which
|
||||
* already calls `_resetAllAppState()` and rebuilds everything from the
|
||||
* server. The connection-loss UI needs nothing either: `connectSSE()` sets
|
||||
* status 'connecting' (reconnectAttempts was zeroed by onopen), and the 2.5s
|
||||
* grace in computeConnectionLossUi means a stream that heals in 200ms shows
|
||||
* nothing at all.
|
||||
*/
|
||||
_checkSseStale() {
|
||||
const policy = window.CodemanSseStale;
|
||||
if (!policy) return;
|
||||
const now = Date.now();
|
||||
const stale = policy.compute({
|
||||
lastMessageAt: this._sseLastMessageAt,
|
||||
now,
|
||||
status: this._connectionStatus,
|
||||
isOnline: this.isOnline,
|
||||
timeoutMs: this._sseStaleTimeoutMs,
|
||||
});
|
||||
if (!stale) return;
|
||||
// If a middlebox ever strips or delays heartbeats, the failure mode is
|
||||
// "silently reconnects every 45s", and a field report of that would be
|
||||
// undebuggable without this line.
|
||||
console.log(
|
||||
`[SSE] stream stale: no frame for ${now - this._sseLastMessageAt}ms ` +
|
||||
`(threshold ${this._sseStaleTimeoutMs}ms), forcing reconnect`
|
||||
);
|
||||
this.connectSSE();
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
@@ -2003,11 +2086,9 @@ class CodemanApp {
|
||||
? 'Gemini'
|
||||
: mode === 'antigravity'
|
||||
? 'Antigravity'
|
||||
: mode === 'pi'
|
||||
? 'Pi'
|
||||
: mode === 'opencode'
|
||||
? 'OpenCode'
|
||||
: 'Claude';
|
||||
: mode === 'opencode'
|
||||
? 'OpenCode'
|
||||
: 'Claude';
|
||||
}
|
||||
|
||||
async toggleResponseViewer() {
|
||||
@@ -3883,7 +3964,7 @@ class CodemanApp {
|
||||
<span class="tab-status ${status}" aria-hidden="true"></span>
|
||||
<span class="tab-info">
|
||||
<span class="tab-name-row">
|
||||
${mode === 'shell' ? '<span class="tab-mode shell" aria-hidden="true">sh</span>' : mode === 'opencode' ? '<span class="tab-mode opencode" aria-hidden="true">oc</span>' : mode === 'codex' ? '<span class="tab-mode codex" aria-hidden="true">cx</span>' : mode === 'gemini' ? '<span class="tab-mode gemini" aria-hidden="true">gm</span>' : mode === 'antigravity' ? '<span class="tab-mode antigravity" aria-hidden="true">ag</span>' : mode === 'pi' ? '<span class="tab-mode pi" aria-hidden="true">pi</span>' : ''}
|
||||
${mode === 'shell' ? '<span class="tab-mode shell" aria-hidden="true">sh</span>' : mode === 'opencode' ? '<span class="tab-mode opencode" aria-hidden="true">oc</span>' : mode === 'codex' ? '<span class="tab-mode codex" aria-hidden="true">cx</span>' : mode === 'gemini' ? '<span class="tab-mode gemini" aria-hidden="true">gm</span>' : mode === 'antigravity' ? '<span class="tab-mode antigravity" aria-hidden="true">ag</span>' : ''}
|
||||
<span class="tab-name" data-session-id="${id}">${escapeHtml(tabLabel)}</span>
|
||||
<span class="tab-detached-badge" aria-hidden="true">detached</span>
|
||||
</span>
|
||||
@@ -5055,9 +5136,7 @@ class CodemanApp {
|
||||
? 'Kill Tmux & Gemini'
|
||||
: session.mode === 'antigravity'
|
||||
? 'Kill Tmux & Antigravity'
|
||||
: session.mode === 'pi'
|
||||
? 'Kill Tmux & Pi'
|
||||
: 'Kill Tmux & Claude Code';
|
||||
: 'Kill Tmux & Claude Code';
|
||||
}
|
||||
|
||||
document.getElementById('closeConfirmModal').classList.add('active');
|
||||
|
||||
@@ -379,6 +379,41 @@ function computeConnectionLossUi(input) {
|
||||
};
|
||||
}
|
||||
|
||||
// SSE staleness policy: is this stream a zombie?
|
||||
//
|
||||
// An EventSource that stops delivering does not always error. A proxy that
|
||||
// idle-closed the connection, a laptop resumed from sleep, a tailnet
|
||||
// reconnect: `onerror` never fires, the header dot stays green, and every
|
||||
// SSE-driven surface (tab status dots, sessions created on another device,
|
||||
// renames) freezes until the user reloads. The server writes a
|
||||
// `sse:heartbeat` frame every 15s, so silence longer than three of them means
|
||||
// the stream is dead even though the transport still claims otherwise.
|
||||
//
|
||||
// Stale ONLY when the transport believes it is 'connected': the other states
|
||||
// already have the reconnect/backoff machinery running, and re-firing on top
|
||||
// of them would stack reconnects. That guard is also the loop breaker: a
|
||||
// forced reconnect leaves 'connected' immediately, so the watchdog cannot
|
||||
// fire again while one is in flight. `navigator.onLine === false` is not
|
||||
// staleness either; there is nothing to reconnect to yet.
|
||||
//
|
||||
// Pure: no DOM, no timers, no side effects. `now` is passed in.
|
||||
const SSE_STALE_TIMEOUT_MS = 45000; // three missed 15s heartbeats
|
||||
|
||||
function computeSseStale(input) {
|
||||
const {
|
||||
lastMessageAt = null,
|
||||
now = 0,
|
||||
status = 'connected',
|
||||
isOnline = true,
|
||||
timeoutMs = SSE_STALE_TIMEOUT_MS,
|
||||
} = input || {};
|
||||
if (!isOnline || status !== 'connected') return false;
|
||||
// No frame has ever arrived: `init` lands on connect, so this is a stream
|
||||
// that has not opened yet rather than one that went quiet.
|
||||
if (typeof lastMessageAt !== 'number' || !(lastMessageAt > 0)) return false;
|
||||
return now - lastMessageAt >= timeoutMs;
|
||||
}
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
window.WEBGL_FALLBACK = WEBGL_FALLBACK;
|
||||
window.evaluateWebGLLongTaskTrip = evaluateWebGLLongTaskTrip;
|
||||
@@ -401,6 +436,10 @@ if (typeof window !== 'undefined') {
|
||||
compute: computeConnectionLossUi,
|
||||
GRACE_MS: CONNECTION_LOSS_GRACE_MS,
|
||||
};
|
||||
window.CodemanSseStale = {
|
||||
compute: computeSseStale,
|
||||
TIMEOUT_MS: SSE_STALE_TIMEOUT_MS,
|
||||
};
|
||||
}
|
||||
|
||||
// Scheduler API — prioritize terminal writes over background UI updates.
|
||||
@@ -514,6 +553,9 @@ const SSE_EVENTS = {
|
||||
// Core
|
||||
INIT: 'init',
|
||||
|
||||
// Transport
|
||||
HEARTBEAT: 'sse:heartbeat',
|
||||
|
||||
// Session lifecycle
|
||||
SESSION_CREATED: 'session:created',
|
||||
SESSION_UPDATED: 'session:updated',
|
||||
|
||||
@@ -69,7 +69,6 @@ const HOME_SESSIONS_MODE_BADGE = {
|
||||
codex: 'cx',
|
||||
gemini: 'gm',
|
||||
antigravity: 'ag',
|
||||
pi: 'pi',
|
||||
};
|
||||
|
||||
Object.assign(CodemanApp.prototype, {
|
||||
|
||||
@@ -104,7 +104,6 @@
|
||||
'Run OpenCode': '运行 OpenCode',
|
||||
'Run Gemini': '运行 Gemini',
|
||||
'Run Antigravity': '运行 Antigravity',
|
||||
'Run Pi': '运行 Pi',
|
||||
'Run Shell': '运行 Shell',
|
||||
'Select AI backend': '选择 AI 后端',
|
||||
'Create New Case': '新建案例',
|
||||
|
||||
@@ -352,10 +352,6 @@
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="5 3 19 12 5 21 5 3"/></svg>
|
||||
Run Gemini
|
||||
</button>
|
||||
<button class="welcome-btn welcome-btn-pi" id="welcomePiBtn" style="display: none;" onclick="app.setRunMode('pi'); app.runPi()">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="5 3 19 12 5 21 5 3"/></svg>
|
||||
Run Pi
|
||||
</button>
|
||||
</div>
|
||||
<div class="welcome-qr" id="welcomeQr" onclick="app.toggleWelcomeQrSize()">
|
||||
<div class="welcome-qr-inner" id="welcomeQrInner"></div>
|
||||
@@ -530,9 +526,6 @@
|
||||
<button class="run-mode-option" data-mode="antigravity" onclick="app.setRunMode('antigravity')">
|
||||
<span class="run-mode-dot antigravity"></span>Antigravity
|
||||
</button>
|
||||
<button class="run-mode-option" data-mode="pi" onclick="app.setRunMode('pi')">
|
||||
<span class="run-mode-dot pi"></span>Pi
|
||||
</button>
|
||||
<div class="run-mode-sep"></div>
|
||||
<button class="run-mode-option" data-mode="shell" onclick="app.setRunMode('shell')">
|
||||
<span class="run-mode-dot shell"></span>Terminal / Shell
|
||||
@@ -808,7 +801,6 @@
|
||||
<option value="codex">Codex</option>
|
||||
<option value="gemini">Gemini</option>
|
||||
<option value="antigravity">Antigravity</option>
|
||||
<option value="pi">Pi</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-row"><label>Working Directory</label><input type="text" id="schWorkingDir" placeholder="/absolute/path"></div>
|
||||
@@ -2489,7 +2481,6 @@
|
||||
<option value="gemini" data-cli="gemini">Gemini</option>
|
||||
<option value="opencode" data-cli="opencode">OpenCode</option>
|
||||
<option value="antigravity" data-cli="antigravity">Antigravity</option>
|
||||
<option value="pi" data-cli="pi">Pi</option>
|
||||
<option value="shell">Shell (no agent)</option>
|
||||
</select>
|
||||
<span class="form-hint">Which CLI to point the Run button at once the clone finishes. Changeable any time from the Run dropdown.</span>
|
||||
@@ -2630,7 +2621,7 @@
|
||||
<div class="form-row">
|
||||
<label>Image</label>
|
||||
<input type="text" id="dockerImage" placeholder="codeman/agent:base" autocomplete="off" autocapitalize="off" spellcheck="false">
|
||||
<span class="form-hint">Build it once with <code>node scripts/build-agent-image.mjs</code>. Contains node + claude/codex/gemini/opencode/agy/pi + tmux.</span>
|
||||
<span class="form-hint">Build it once with <code>node scripts/build-agent-image.mjs</code>. Contains node + claude/codex/gemini/opencode/agy + tmux.</span>
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label>Network</label>
|
||||
|
||||
@@ -58,7 +58,6 @@ const MOBILE_OVERVIEW_RUN_MODES = [
|
||||
{ mode: 'codex', label: 'Codex', short: 'Codex' },
|
||||
{ mode: 'gemini', label: 'Gemini', short: 'Gemini' },
|
||||
{ mode: 'antigravity', label: 'Antigravity', short: 'Antigravity' },
|
||||
{ mode: 'pi', label: 'Pi', short: 'Pi' },
|
||||
{ mode: 'shell', label: 'Terminal / Shell', short: 'Shell' },
|
||||
];
|
||||
|
||||
|
||||
@@ -911,25 +911,6 @@ html.mobile-init .file-browser-panel {
|
||||
border-color: rgba(34, 211, 238, 0.5);
|
||||
}
|
||||
|
||||
/* Pi mode colors on mobile.
|
||||
`!important` is load-bearing here, not noise: styles.css nests its skin rules
|
||||
inside `html:not([data-skin="og"])`, so a bare `.btn-toolbar.btn-run` in there
|
||||
resolves to (0,2,1) and outranks this (0,2,0) `.mode-pi` pair regardless of
|
||||
load order. The antigravity block right above omits it and is consequently
|
||||
dead on every non-og skin (i.e. on the default) — do not copy that. */
|
||||
.btn-toolbar.btn-run.mode-pi,
|
||||
.btn-toolbar.btn-run-gear.mode-pi {
|
||||
background: #33121f !important;
|
||||
border-color: rgba(244, 114, 182, 0.3) !important;
|
||||
color: #fce7f3 !important;
|
||||
}
|
||||
|
||||
.btn-toolbar.btn-run.mode-pi:active,
|
||||
.btn-toolbar.btn-run-gear.mode-pi:active {
|
||||
background: #9d174d !important;
|
||||
border-color: rgba(244, 114, 182, 0.5) !important;
|
||||
}
|
||||
|
||||
/* Run mode dropdown menu — positioned above toolbar on mobile */
|
||||
.run-mode-menu {
|
||||
bottom: 100%;
|
||||
@@ -3007,12 +2988,6 @@ html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="cat
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="catppuccin-latte"], [data-skin="rose-pine-dawn"]) :is(.btn-toolbar.btn-run.mode-pi, .btn-toolbar.btn-run-gear.mode-pi) {
|
||||
background: linear-gradient(135deg, #be185d, #db2777);
|
||||
border-color: #9d174d;
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="catppuccin-latte"], [data-skin="rose-pine-dawn"]) .btn-toolbar.btn-run-gear {
|
||||
border-left-color: var(--control-border-hover) !important;
|
||||
}
|
||||
|
||||
@@ -427,7 +427,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
|
||||
_buildCommandPaletteNewSessionItem(query = '') {
|
||||
const mode = this.runMode || this._runMode || 'claude';
|
||||
const labels = { claude: 'Claude', opencode: 'OpenCode', codex: 'Codex', gemini: 'Gemini', antigravity: 'Antigravity', pi: 'Pi' };
|
||||
const labels = { claude: 'Claude', opencode: 'OpenCode', codex: 'Codex', gemini: 'Gemini', antigravity: 'Antigravity' };
|
||||
const caseName = this._findCommandPaletteCaseMatch(query) || document.getElementById('quickStartCase')?.value || 'testcase';
|
||||
return {
|
||||
id: 'new-session',
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* @fileoverview Quick start (case loading, session spawning for Claude/Shell/OpenCode/Codex/Gemini/Antigravity/Pi),
|
||||
* @fileoverview Quick start (case loading, session spawning for Claude/Shell/OpenCode/Codex/Gemini/Antigravity),
|
||||
* session options modal (per-session settings, color picker, rename),
|
||||
* session options tabs (Ralph config tab), case settings (CRUD, links),
|
||||
* create case modal, and mobile case picker.
|
||||
@@ -400,9 +400,6 @@ Object.assign(CodemanApp.prototype, {
|
||||
if (mode === 'antigravity') {
|
||||
return await this.runAntigravity();
|
||||
}
|
||||
if (mode === 'pi') {
|
||||
return await this.runPi();
|
||||
}
|
||||
if (mode === 'shell') {
|
||||
return await this.runShell();
|
||||
}
|
||||
@@ -464,11 +461,11 @@ Object.assign(CodemanApp.prototype, {
|
||||
* `.run-mode-option` is also the class the saved-dashboard rows and the history
|
||||
* rows use, and a bare querySelector would find whichever came first in the DOM.
|
||||
*
|
||||
* Antigravity and Pi are in this list even though #201 predates them — they are
|
||||
* run modes like the rest, and neither `agy` nor `pi` is likely to be installed.
|
||||
* Antigravity is in this list even though #201 predates it — it is a run mode
|
||||
* like the rest, and `agy` is the LEAST likely of the five to be installed.
|
||||
*/
|
||||
_refreshRunModeAvailability(menu) {
|
||||
for (const mode of ['claude', 'opencode', 'codex', 'gemini', 'antigravity', 'pi']) {
|
||||
for (const mode of ['claude', 'opencode', 'codex', 'gemini', 'antigravity']) {
|
||||
const btn = menu.querySelector(`.run-mode-option[data-mode="${mode}"]`);
|
||||
if (btn) btn.style.display = this.isCliAvailable(mode) ? 'flex' : 'none';
|
||||
}
|
||||
@@ -565,7 +562,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
gearBtn.className = `btn-toolbar btn-run-gear mode-${mode}`;
|
||||
}
|
||||
if (label) {
|
||||
label.textContent = mode === 'opencode' ? 'Run OC' : mode === 'codex' ? 'Run CX' : mode === 'gemini' ? 'Run GM' : mode === 'antigravity' ? 'Run AG' : mode === 'pi' ? 'Run PI' : mode === 'shell' ? 'Run SH' : 'Run';
|
||||
label.textContent = mode === 'opencode' ? 'Run OC' : mode === 'codex' ? 'Run CX' : mode === 'gemini' ? 'Run GM' : mode === 'antigravity' ? 'Run AG' : mode === 'shell' ? 'Run SH' : 'Run';
|
||||
}
|
||||
},
|
||||
|
||||
@@ -1221,63 +1218,6 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Launch a Pi (pi.dev) session.
|
||||
*
|
||||
* Deliberately sends NO piConfig: pi has no permission prompts, so there is no
|
||||
* bypass to opt into, and project trust is pi's own `defaultProjectTrust`
|
||||
* decision (an interactive prompt the user answers in the terminal). Sending
|
||||
* `approveProjectTrust: true` here would silently opt every browser-launched pi
|
||||
* session into executing repo-supplied TypeScript.
|
||||
*/
|
||||
async runPi() {
|
||||
const caseName = document.getElementById('quickStartCase').value || 'testcase';
|
||||
// Remote/docker cases run pi on the OTHER side — skip the local status probe and the
|
||||
// local-only config/env below (quick-start rejects them for remote cases).
|
||||
const _runLoc = (this.cases || []).find(c => c.name === caseName)?.location;
|
||||
const isRemote = _runLoc === 'remote' || _runLoc === 'docker';
|
||||
|
||||
const ownsLaunchTerminal = this._beginSessionLaunchStatus(`Starting Pi session in ${caseName}...`);
|
||||
this.terminal.focus();
|
||||
|
||||
try {
|
||||
if (!isRemote) {
|
||||
const statusRes = await fetch('/api/pi/status');
|
||||
const status = (await statusRes.json()).data;
|
||||
if (!status.available) {
|
||||
this._reportSessionLaunchError(
|
||||
ownsLaunchTerminal,
|
||||
'Pi CLI not found. Install with: npm install -g --ignore-scripts @earendil-works/pi-coding-agent'
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const envOverrides = this.buildEnvOverrides(this.getCaseSettings(caseName), this.loadAppSettingsFromStorage());
|
||||
const res = await fetch('/api/quick-start', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
caseName,
|
||||
mode: 'pi',
|
||||
sessionName: `w${this._nextCaseSessionStartNumber(caseName)}-${caseName}`,
|
||||
...(isRemote || Object.keys(envOverrides).length === 0 ? {} : { envOverrides }),
|
||||
})
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!data.success) throw new Error(data.error || 'Failed to start Pi');
|
||||
await this._ensureCreatedSessionVisible(data.data.sessionId, data.data.session);
|
||||
|
||||
if (data.data.sessionId) {
|
||||
await this.selectSession(data.data.sessionId);
|
||||
}
|
||||
|
||||
this.terminal.focus();
|
||||
} catch (err) {
|
||||
this._reportSessionLaunchError(ownsLaunchTerminal, err.message);
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// Session Options Modal
|
||||
@@ -1290,7 +1230,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
this.editingSessionId = sessionId;
|
||||
|
||||
// Reset to an appropriate tab — Summary for external CLIs (Respawn/Ralph are Claude-only)
|
||||
const isAltMode = session.mode === 'opencode' || session.mode === 'codex' || session.mode === 'gemini' || session.mode === 'antigravity' || session.mode === 'pi';
|
||||
const isAltMode = session.mode === 'opencode' || session.mode === 'codex' || session.mode === 'gemini' || session.mode === 'antigravity';
|
||||
this.switchOptionsTab(isAltMode ? 'summary' : 'respawn');
|
||||
|
||||
// Update respawn status display and buttons
|
||||
@@ -1320,7 +1260,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
|
||||
// Hide Claude-specific options for external CLI sessions
|
||||
const isExternalCli = session.mode === 'opencode' || session.mode === 'codex' || session.mode === 'gemini' || session.mode === 'antigravity' || session.mode === 'pi';
|
||||
const isExternalCli = session.mode === 'opencode' || session.mode === 'codex' || session.mode === 'gemini' || session.mode === 'antigravity';
|
||||
const claudeOnlyEls = document.querySelectorAll('[data-claude-only]');
|
||||
claudeOnlyEls.forEach(el => { el.style.display = isExternalCli ? 'none' : ''; });
|
||||
|
||||
@@ -1415,9 +1355,54 @@ Object.assign(CodemanApp.prototype, {
|
||||
this.activeFocusTrap.activate();
|
||||
},
|
||||
|
||||
/**
|
||||
* Write a name the server has just confirmed into the local session map.
|
||||
*
|
||||
* Both rename surfaces re-render the tab strip from `this.sessions` right
|
||||
* after their PUT, so without this they depended on the `session:updated` SSE
|
||||
* frame to carry their own write back. On a page whose SSE stream has gone
|
||||
* quiet without erroring (a proxy that idle-closed it, a laptop resumed from
|
||||
* sleep) that frame never lands: the PUT stores the new name, the re-render
|
||||
* repaints the stale one, and the rename looks like it did nothing until a
|
||||
* full page reload. The response body is authoritative, so apply it directly.
|
||||
* The SSE frame, when it does arrive, replaces the object with the same name.
|
||||
*/
|
||||
_applyLocalSessionName(sessionId, name) {
|
||||
if (typeof name !== 'string') return;
|
||||
const session = this.sessions.get(sessionId);
|
||||
if (!session) return;
|
||||
session.name = name;
|
||||
this.sessions.set(sessionId, session);
|
||||
// Mirrors _onSessionUpdated: subagent windows cache their parent's name.
|
||||
this.updateSubagentParentNames?.(sessionId);
|
||||
},
|
||||
|
||||
/**
|
||||
* PUT a session name and return the name the server stored, or null if the
|
||||
* request failed. `_apiPut` swallows network errors into a null Response and
|
||||
* an API-level failure arrives as a non-ok status or `{success:false}`, so a
|
||||
* rename that silently did nothing has to be detected here, not thrown.
|
||||
*/
|
||||
async _putSessionName(sessionId, name) {
|
||||
const res = await this._apiPut(`/api/sessions/${sessionId}/name`, { name });
|
||||
if (!res || !res.ok) return null;
|
||||
let payload = null;
|
||||
try {
|
||||
payload = await res.json();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (payload && payload.success === false) return null;
|
||||
const confirmed = payload?.data?.name;
|
||||
return typeof confirmed === 'string' ? confirmed : name;
|
||||
},
|
||||
|
||||
async saveSessionName() {
|
||||
if (!this.editingSessionId) return;
|
||||
const session = this.sessions.get(this.editingSessionId);
|
||||
// Captured: the modal can be closed (or switched to another session) while
|
||||
// the PUT is in flight, and the name belongs to the session that was open.
|
||||
const sessionId = this.editingSessionId;
|
||||
const session = this.sessions.get(sessionId);
|
||||
const parsed = session ? parseSessionPrefix(session.name) : null;
|
||||
const inputVal = document.getElementById('modalSessionName').value.trim();
|
||||
let name;
|
||||
@@ -1426,11 +1411,13 @@ Object.assign(CodemanApp.prototype, {
|
||||
} else {
|
||||
name = inputVal;
|
||||
}
|
||||
try {
|
||||
await this._apiPut(`/api/sessions/${this.editingSessionId}/name`, { name });
|
||||
} catch (err) {
|
||||
this.showToast('Failed to save session name: ' + err.message, 'error');
|
||||
const confirmed = await this._putSessionName(sessionId, name);
|
||||
if (confirmed === null) {
|
||||
this.showToast('Failed to save session name', 'error');
|
||||
return;
|
||||
}
|
||||
this._applyLocalSessionName(sessionId, confirmed);
|
||||
this.renderSessionTabs();
|
||||
},
|
||||
|
||||
async autoSaveAutoCompact() {
|
||||
@@ -1740,15 +1727,14 @@ Object.assign(CodemanApp.prototype, {
|
||||
// Skip the API call if the session vanished between focus and blur.
|
||||
const stillExists = this.sessions.has(sessionId);
|
||||
if (stillExists && fullName !== session.name) {
|
||||
try {
|
||||
await fetch(`/api/sessions/${sessionId}/name`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: fullName })
|
||||
});
|
||||
} catch (err) {
|
||||
const confirmed = await this._putSessionName(sessionId, fullName);
|
||||
if (confirmed === null) {
|
||||
tabName.textContent = originalContent;
|
||||
this.showToast('Failed to rename', 'error');
|
||||
} else {
|
||||
// The re-render below repaints from this.sessions, so the new name has
|
||||
// to be in the map before it runs (see _applyLocalSessionName()).
|
||||
this._applyLocalSessionName(sessionId, confirmed);
|
||||
}
|
||||
}
|
||||
// Re-render tabs to restore full tab structure
|
||||
@@ -3012,7 +2998,7 @@ Object.defineProperty(CodemanApp.prototype, 'runMode', {
|
||||
},
|
||||
set(mode) {
|
||||
this._runMode =
|
||||
mode === 'opencode' || mode === 'codex' || mode === 'gemini' || mode === 'antigravity' || mode === 'pi' || mode === 'claude'
|
||||
mode === 'opencode' || mode === 'codex' || mode === 'gemini' || mode === 'antigravity' || mode === 'claude'
|
||||
? mode
|
||||
: 'claude';
|
||||
},
|
||||
|
||||
@@ -1179,7 +1179,6 @@ Object.assign(CodemanApp.prototype, {
|
||||
['welcomeOpencodeBtn', 'opencode'],
|
||||
['welcomeAntigravityBtn', 'antigravity'],
|
||||
['welcomeGeminiBtn', 'gemini'],
|
||||
['welcomePiBtn', 'pi'],
|
||||
// Not a run mode, same reasoning: offering a Cloudflare Tunnel on a box
|
||||
// without cloudflared can only ever produce "cloudflared not found".
|
||||
['welcomeTunnelBtn', 'cloudflared'],
|
||||
|
||||
@@ -329,8 +329,7 @@ html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="cat
|
||||
.search-badge-session,
|
||||
.history-view-all-btn,
|
||||
.session-tab .tab-mode.gemini,
|
||||
.session-tab .tab-mode.antigravity,
|
||||
.session-tab .tab-mode.pi
|
||||
.session-tab .tab-mode.antigravity
|
||||
) {
|
||||
color: var(--accent-d);
|
||||
}
|
||||
@@ -2160,11 +2159,6 @@ body.solo-mode .btn-lifecycle-log {
|
||||
color: #22d3ee;
|
||||
}
|
||||
|
||||
.session-tab .tab-mode.pi {
|
||||
background: rgba(244, 114, 182, 0.2);
|
||||
color: #f472b6;
|
||||
}
|
||||
|
||||
/* Timer Banner - Compact */
|
||||
.timer-banner {
|
||||
display: flex;
|
||||
@@ -3384,23 +3378,6 @@ body.touch-device .terminal-container .xterm .xterm-helper-textarea {
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
/* Pi (pi.dev): rose identity, matching .btn-toolbar.btn-run.mode-pi and
|
||||
.run-mode-dot.pi so the welcome action reads as the same backend. */
|
||||
.welcome-btn-pi {
|
||||
background: linear-gradient(135deg, #33121f 0%, #9d174d 55%, #be185d 100%);
|
||||
border-color: rgba(244, 114, 182, 0.4);
|
||||
color: #fce7f3;
|
||||
box-shadow: 0 2px 8px rgba(244, 114, 182, 0.16), inset 0 1px 0 rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
|
||||
.welcome-btn-pi:hover {
|
||||
background: linear-gradient(135deg, #4a1a2c 0%, #be185d 55%, #db2777 100%);
|
||||
box-shadow: 0 4px 20px rgba(244, 114, 182, 0.3), 0 0 40px rgba(190, 24, 93, 0.12), inset 0 1px 0 rgba(255, 255, 255, 0.08);
|
||||
border-color: rgba(249, 168, 212, 0.5);
|
||||
color: #fff1f7;
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.welcome-btn-gemini {
|
||||
background: linear-gradient(135deg, #10243f 0%, #174ea6 55%, #4f46e5 100%);
|
||||
border-color: rgba(96, 165, 250, 0.4);
|
||||
@@ -4455,26 +4432,6 @@ body.touch-device .terminal-container .xterm .xterm-helper-textarea {
|
||||
color: #ecfeff;
|
||||
}
|
||||
|
||||
/* Pi mode colors. NOTE: this base-sheet pair only renders on the `og` skin — the
|
||||
nested `html:not([data-skin="og"])` block further down re-declares
|
||||
`.btn-toolbar.btn-run` at a HIGHER specificity, which is why gemini's and
|
||||
antigravity's gradients are dead on the default skin. Pi therefore also carries
|
||||
a rule inside that block (search `.btn-toolbar.btn-run.mode-pi`). */
|
||||
.btn-toolbar.btn-run.mode-pi,
|
||||
.btn-toolbar.btn-run-gear.mode-pi {
|
||||
background: linear-gradient(135deg, #33121f 0%, #9d174d 55%, #be185d 100%);
|
||||
border-color: rgba(244, 114, 182, 0.5);
|
||||
color: #fce7f3;
|
||||
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.2), inset 0 1px 0 rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
.btn-toolbar.btn-run.mode-pi:hover,
|
||||
.btn-toolbar.btn-run-gear.mode-pi:hover {
|
||||
background: linear-gradient(135deg, #4a1a2c 0%, #be185d 55%, #db2777 100%);
|
||||
box-shadow: 0 0 12px rgba(244, 114, 182, 0.35), 0 2px 8px rgba(190, 24, 93, 0.2), inset 0 1px 0 rgba(255, 255, 255, 0.08);
|
||||
border-color: rgba(249, 168, 212, 0.6);
|
||||
color: #fff1f7;
|
||||
}
|
||||
|
||||
/* Dropdown menu */
|
||||
.run-mode-menu {
|
||||
display: none;
|
||||
@@ -4557,7 +4514,6 @@ body.touch-device .terminal-container .xterm .xterm-helper-textarea {
|
||||
.run-mode-dot.codex { background: #a855f7; }
|
||||
.run-mode-dot.gemini { background: #8ab4f8; }
|
||||
.run-mode-dot.antigravity { background: #22d3ee; }
|
||||
.run-mode-dot.pi { background: #f472b6; }
|
||||
.run-mode-dot.shell { background: #94a3b8; }
|
||||
|
||||
/* Phone-only Enter button (see index.html). Hidden by default at every width;
|
||||
@@ -13834,17 +13790,6 @@ html:not([data-skin="og"]) {
|
||||
color: #061c20;
|
||||
}
|
||||
.btn-toolbar.btn-run.mode-codex:hover { box-shadow: 0 0 14px -2px rgba(43, 203, 187, 0.45); }
|
||||
/* Pi keeps its rose identity on the non-og skins. This rule has to live INSIDE
|
||||
this nested block: the generic `.btn-toolbar.btn-run` above resolves to (0,3,1)
|
||||
here and would otherwise beat the base sheet's (0,3,0) `.mode-pi` pair, which
|
||||
is exactly why gemini's and antigravity's gradients render as generic claude
|
||||
blue on the default skin. */
|
||||
.btn-toolbar.btn-run.mode-pi {
|
||||
background: linear-gradient(135deg, #be185d, #f472b6);
|
||||
border-color: #be185d;
|
||||
color: #fff1f7;
|
||||
}
|
||||
.btn-toolbar.btn-run.mode-pi:hover { box-shadow: 0 0 14px -2px rgba(244, 114, 182, 0.45); }
|
||||
.btn-toolbar.btn-run-gear {
|
||||
background: var(--accent-d);
|
||||
border-color: var(--accent);
|
||||
|
||||
@@ -1747,7 +1747,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
titleSpan.appendChild(document.createTextNode(this._historyRowLabel(s, shortDir)));
|
||||
|
||||
// Badge row: mode (claude/codex/opencode/gemini/antigravity/pi/shell) + a LIVE pill.
|
||||
// Badge row: mode (claude/codex/opencode/gemini/antigravity/shell) + a LIVE pill.
|
||||
const badgeRow = document.createElement('div');
|
||||
badgeRow.className = 'history-item-badges';
|
||||
if (s.mode) {
|
||||
|
||||
@@ -22,7 +22,6 @@ import {
|
||||
type CodexConfig,
|
||||
type GeminiConfig,
|
||||
type AntigravityConfig,
|
||||
type PiConfig,
|
||||
} from '../../types.js';
|
||||
import { Session, isAltScreenStripMode, isMuxAltScreenOnlyStripMode } from '../../session.js';
|
||||
import { SseEvent } from '../sse-events.js';
|
||||
@@ -313,50 +312,29 @@ export function _resetPasteRateBuckets(): void {
|
||||
* Antigravity is like Codex: an ABSENT config already defaults safe (no bypass flag), so
|
||||
* only a sent config needs the flag forced off. No-op in single-user mode / for a granted
|
||||
* owner (canUsernameRunPrivilegedCommands returns true when !isMultiUserMode()).
|
||||
*
|
||||
* Pi has no permission prompts at all, so there is no bypass switch to clamp; its
|
||||
* privilege-shaped knob is `approveProjectTrust`, which makes pi LOAD AND EXECUTE
|
||||
* repo-local `.pi/extensions` TypeScript and npm-install missing project packages.
|
||||
* Pi joins the gemini-style MATERIALIZE branch, not the codex/antigravity
|
||||
* only-if-sent one: pi's absent-config default is an interactive trust prompt the
|
||||
* session user could simply answer "yes" to in the terminal, so merely omitting
|
||||
* `--approve` is not a clamp. Forcing `approveProjectTrust: false` makes
|
||||
* buildPiCommand emit `--no-approve`, and the prompt never appears.
|
||||
*/
|
||||
async function clampExternalCliBypassForOwner(
|
||||
owner: string | undefined,
|
||||
codexConfig: CodexConfig | undefined,
|
||||
geminiConfig: GeminiConfig | undefined,
|
||||
antigravityConfig: AntigravityConfig | undefined,
|
||||
piConfig: PiConfig | undefined
|
||||
antigravityConfig: AntigravityConfig | undefined
|
||||
): Promise<{
|
||||
codexConfig: CodexConfig | undefined;
|
||||
geminiConfig: GeminiConfig | undefined;
|
||||
antigravityConfig: AntigravityConfig | undefined;
|
||||
piConfig: PiConfig | undefined;
|
||||
}> {
|
||||
const granted = await canUsernameRunPrivilegedCommands(owner);
|
||||
if (granted) return { codexConfig, geminiConfig, antigravityConfig, piConfig };
|
||||
if (granted) return { codexConfig, geminiConfig, antigravityConfig };
|
||||
// Non-granted: force codex/antigravity bypass off (only meaningful when a config was
|
||||
// sent) and materialize gemini to auto_edit (clamps an explicit 'yolo' and the yolo default)
|
||||
// and pi to --no-approve (clamps an explicit true AND pi's own "ask" default).
|
||||
// sent) and materialize gemini to auto_edit (clamps an explicit 'yolo' and the yolo default).
|
||||
const clampedCodex = codexConfig ? { ...codexConfig, dangerouslyBypassApprovals: false } : codexConfig;
|
||||
const clampedGemini: GeminiConfig = { ...(geminiConfig ?? {}), approvalMode: 'auto_edit' };
|
||||
const clampedAntigravity = antigravityConfig
|
||||
? { ...antigravityConfig, dangerouslySkipPermissions: false }
|
||||
: antigravityConfig;
|
||||
const clampedPi: PiConfig = { ...(piConfig ?? {}), approveProjectTrust: false };
|
||||
return {
|
||||
codexConfig: clampedCodex,
|
||||
geminiConfig: clampedGemini,
|
||||
antigravityConfig: clampedAntigravity,
|
||||
piConfig: clampedPi,
|
||||
};
|
||||
return { codexConfig: clampedCodex, geminiConfig: clampedGemini, antigravityConfig: clampedAntigravity };
|
||||
}
|
||||
|
||||
/** Test hook: the clamp is the multi-user safety gate for the external CLIs' privileged flags. */
|
||||
export const _clampExternalCliBypassForOwner = clampExternalCliBypassForOwner;
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// Agent wait helpers (shared by GET /wait, GET /wait-output, POST /input)
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
@@ -728,7 +706,6 @@ export function registerSessionRoutes(
|
||||
body.mode !== 'codex' &&
|
||||
body.mode !== 'gemini' &&
|
||||
body.mode !== 'antigravity' &&
|
||||
body.mode !== 'pi' &&
|
||||
body.envOverrides &&
|
||||
Object.keys(body.envOverrides).length > 0 &&
|
||||
(workingDir.startsWith(CASES_DIR + '/') || workingDir.startsWith(managedCasesBase + '/'));
|
||||
@@ -811,15 +788,6 @@ export function registerSessionRoutes(
|
||||
);
|
||||
}
|
||||
}
|
||||
if (body.mode === 'pi') {
|
||||
const { isPiAvailable } = await import('../../utils/pi-cli-resolver.js');
|
||||
if (!isPiAvailable()) {
|
||||
return createErrorResponse(
|
||||
ApiErrorCode.OPERATION_FAILED,
|
||||
'Pi CLI not found. Install with: npm install -g --ignore-scripts @earendil-works/pi-coding-agent'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Pre-validate resumeSessionId: check that the conversation file actually exists
|
||||
// in Claude's projects directory. If not, skip resume to avoid confusing
|
||||
@@ -863,11 +831,9 @@ export function registerSessionRoutes(
|
||||
? body.geminiConfig?.model
|
||||
: mode === 'antigravity'
|
||||
? body.antigravityConfig?.model
|
||||
: mode === 'pi'
|
||||
? body.piConfig?.model
|
||||
: mode !== 'shell'
|
||||
? modelConfig?.defaultModel || undefined
|
||||
: undefined;
|
||||
: mode !== 'shell'
|
||||
? modelConfig?.defaultModel || undefined
|
||||
: undefined;
|
||||
const claudeModeConfig = await ctx.getClaudeModeConfig();
|
||||
// Section 6.3: force non-granted users to a classifier-guarded mode.
|
||||
const effectiveClaudeMode = await resolveClaudeModeForUsername(claudeModeConfig.claudeMode, owner);
|
||||
@@ -876,14 +842,7 @@ export function registerSessionRoutes(
|
||||
codexConfig: gatedCodexConfig,
|
||||
geminiConfig: gatedGeminiConfig,
|
||||
antigravityConfig: gatedAntigravityConfig,
|
||||
piConfig: gatedPiConfig,
|
||||
} = await clampExternalCliBypassForOwner(
|
||||
owner,
|
||||
body.codexConfig,
|
||||
body.geminiConfig,
|
||||
body.antigravityConfig,
|
||||
body.piConfig
|
||||
);
|
||||
} = await clampExternalCliBypassForOwner(owner, body.codexConfig, body.geminiConfig, body.antigravityConfig);
|
||||
const terminalHistoryConfig = await ctx.getTerminalHistoryConfig();
|
||||
const session = new Session({
|
||||
workingDir,
|
||||
@@ -899,7 +858,6 @@ export function registerSessionRoutes(
|
||||
codexConfig: mode === 'codex' ? gatedCodexConfig : undefined,
|
||||
geminiConfig: mode === 'gemini' ? gatedGeminiConfig : undefined,
|
||||
antigravityConfig: mode === 'antigravity' ? gatedAntigravityConfig : undefined,
|
||||
piConfig: mode === 'pi' ? gatedPiConfig : undefined,
|
||||
resumeSessionId: validatedResumeId,
|
||||
envOverrides: body.envOverrides,
|
||||
effort: body.effort,
|
||||
@@ -1114,16 +1072,12 @@ export function registerSessionRoutes(
|
||||
|
||||
try {
|
||||
// Auto-detect completion phrase from CLAUDE.md BEFORE starting (only if globally enabled and not explicitly disabled by user)
|
||||
// Ralph tracker is not supported for opencode / codex / gemini / antigravity / pi sessions.
|
||||
// Keep this list in step with isExternalCliMode(): _processExpensiveParsers() returns early
|
||||
// for those modes, so a tracker enabled here would never be fed, and the session would
|
||||
// still report ralphEnabled + Ralph UI state that no other external CLI shows.
|
||||
// Ralph tracker is not supported for opencode / codex / gemini / antigravity sessions
|
||||
if (
|
||||
session.mode !== 'opencode' &&
|
||||
session.mode !== 'codex' &&
|
||||
session.mode !== 'gemini' &&
|
||||
session.mode !== 'antigravity' &&
|
||||
session.mode !== 'pi' &&
|
||||
ctx.store.getConfig().ralphEnabled &&
|
||||
!session.ralphTracker.autoEnableDisabled
|
||||
) {
|
||||
@@ -2616,7 +2570,6 @@ export function registerSessionRoutes(
|
||||
codexConfig,
|
||||
geminiConfig,
|
||||
antigravityConfig,
|
||||
piConfig,
|
||||
envOverrides,
|
||||
effort,
|
||||
parentSessionId,
|
||||
@@ -2664,7 +2617,6 @@ export function registerSessionRoutes(
|
||||
codexConfig ||
|
||||
geminiConfig ||
|
||||
antigravityConfig ||
|
||||
piConfig ||
|
||||
openCodeConfig
|
||||
) {
|
||||
return createErrorResponse(
|
||||
@@ -2696,7 +2648,6 @@ export function registerSessionRoutes(
|
||||
codexConfig ||
|
||||
geminiConfig ||
|
||||
antigravityConfig ||
|
||||
piConfig ||
|
||||
openCodeConfig
|
||||
) {
|
||||
return createErrorResponse(
|
||||
@@ -2800,17 +2751,6 @@ export function registerSessionRoutes(
|
||||
}
|
||||
}
|
||||
|
||||
// Check Pi availability if requested
|
||||
if (mode === 'pi') {
|
||||
const { isPiAvailable } = await import('../../utils/pi-cli-resolver.js');
|
||||
if (!isPiAvailable()) {
|
||||
return createErrorResponse(
|
||||
ApiErrorCode.OPERATION_FAILED,
|
||||
'Pi CLI not found. Install with: npm install -g --ignore-scripts @earendil-works/pi-coding-agent'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve case path: check linked-cases registry first, then fall back to CASES_DIR.
|
||||
// This mirrors the behaviour of resolveCasePath() in case-routes so that linked
|
||||
// external project directories are honoured by quick-start just like regular case routes.
|
||||
@@ -2858,7 +2798,7 @@ export function registerSessionRoutes(
|
||||
|
||||
// Write .claude/settings.local.json with hooks for desktop notifications
|
||||
// (Claude-specific — OpenCode, Codex, Gemini, and Antigravity use their own systems)
|
||||
if (mode !== 'opencode' && mode !== 'codex' && mode !== 'gemini' && mode !== 'antigravity' && mode !== 'pi') {
|
||||
if (mode !== 'opencode' && mode !== 'codex' && mode !== 'gemini' && mode !== 'antigravity') {
|
||||
await writeHooksConfig(resolvedCasePath);
|
||||
}
|
||||
|
||||
@@ -2893,8 +2833,7 @@ export function registerSessionRoutes(
|
||||
mode !== 'opencode' &&
|
||||
mode !== 'codex' &&
|
||||
mode !== 'gemini' &&
|
||||
mode !== 'antigravity' &&
|
||||
mode !== 'pi'
|
||||
mode !== 'antigravity'
|
||||
) {
|
||||
try {
|
||||
if (!existsSync(join(resolvedCasePath, 'CLAUDE.md'))) {
|
||||
@@ -2925,7 +2864,6 @@ export function registerSessionRoutes(
|
||||
mode !== 'codex' &&
|
||||
mode !== 'gemini' &&
|
||||
mode !== 'antigravity' &&
|
||||
mode !== 'pi' &&
|
||||
!remote &&
|
||||
envOverrides &&
|
||||
Object.keys(envOverrides).length > 0
|
||||
@@ -2946,11 +2884,9 @@ export function registerSessionRoutes(
|
||||
? geminiConfig?.model
|
||||
: mode === 'antigravity'
|
||||
? antigravityConfig?.model
|
||||
: mode === 'pi'
|
||||
? piConfig?.model
|
||||
: mode !== 'shell'
|
||||
? qsModelConfig?.defaultModel || undefined
|
||||
: undefined;
|
||||
: mode !== 'shell'
|
||||
? qsModelConfig?.defaultModel || undefined
|
||||
: undefined;
|
||||
const qsClaudeModeConfig = await ctx.getClaudeModeConfig();
|
||||
const qsEffectiveClaudeMode = await resolveClaudeModeForUsername(qsClaudeModeConfig.claudeMode, owner);
|
||||
// Section 6.3: clamp Codex/Gemini/Antigravity bypass switches for a non-granted owner (no-op single-user/granted).
|
||||
@@ -2958,8 +2894,7 @@ export function registerSessionRoutes(
|
||||
codexConfig: qsGatedCodexConfig,
|
||||
geminiConfig: qsGatedGeminiConfig,
|
||||
antigravityConfig: qsGatedAntigravityConfig,
|
||||
piConfig: qsGatedPiConfig,
|
||||
} = await clampExternalCliBypassForOwner(owner, codexConfig, geminiConfig, antigravityConfig, piConfig);
|
||||
} = await clampExternalCliBypassForOwner(owner, codexConfig, geminiConfig, antigravityConfig);
|
||||
const qsTerminalHistoryConfig = await ctx.getTerminalHistoryConfig();
|
||||
const session = new Session({
|
||||
workingDir: resolvedCasePath,
|
||||
@@ -2976,7 +2911,6 @@ export function registerSessionRoutes(
|
||||
codexConfig: mode === 'codex' ? qsGatedCodexConfig : undefined,
|
||||
geminiConfig: mode === 'gemini' ? qsGatedGeminiConfig : undefined,
|
||||
antigravityConfig: mode === 'antigravity' ? qsGatedAntigravityConfig : undefined,
|
||||
piConfig: mode === 'pi' ? qsGatedPiConfig : undefined,
|
||||
envOverrides,
|
||||
effort,
|
||||
remote,
|
||||
|
||||
@@ -374,7 +374,7 @@ export function registerSystemRoutes(
|
||||
});
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// CLI Integrations (Claude, OpenCode, Codex, Gemini, Antigravity, Pi)
|
||||
// CLI Integrations (Claude, OpenCode, Codex, Gemini, Antigravity)
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
// ========== Claude ==========
|
||||
@@ -425,21 +425,6 @@ export function registerSystemRoutes(
|
||||
};
|
||||
});
|
||||
|
||||
// ========== Pi ==========
|
||||
|
||||
// Carries `version` on top of the sibling shape: `pi` is a short, generic binary
|
||||
// name, so the resolver sanity-probes `pi --version` and rejects anything that
|
||||
// is not the coding agent. Surfacing path + version makes a misresolution
|
||||
// diagnosable from the UI instead of presenting as "the mode just doesn't work".
|
||||
app.get('/api/pi/status', async () => {
|
||||
const { isPiAvailable, resolvePiDir, getPiCliVersion } = await import('../../utils/pi-cli-resolver.js');
|
||||
return {
|
||||
available: isPiAvailable(),
|
||||
path: resolvePiDir(),
|
||||
version: getPiCliVersion(),
|
||||
};
|
||||
});
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// State & Lifecycle (cleanup, lifecycle log, stats)
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
+5
-39
@@ -122,7 +122,7 @@ export const FileWriteSchema = z
|
||||
// ========== Env Var Allowlist ==========
|
||||
|
||||
/** Allowlisted env var key prefixes */
|
||||
const ALLOWED_ENV_PREFIXES = ['CLAUDE_CODE_', 'OPENCODE_', 'CODEX_', 'GEMINI_', 'GOOGLE_', 'ANTIGRAVITY_', 'PI_'];
|
||||
const ALLOWED_ENV_PREFIXES = ['CLAUDE_CODE_', 'OPENCODE_', 'CODEX_', 'GEMINI_', 'GOOGLE_', 'ANTIGRAVITY_'];
|
||||
|
||||
/**
|
||||
* Allowlisted exact env var keys (checked alongside the prefixes).
|
||||
@@ -161,7 +161,7 @@ const safeEnvOverridesSchema = z
|
||||
},
|
||||
{
|
||||
message:
|
||||
'envOverrides contains blocked or disallowed env var keys. Only CLAUDE_CODE_*, OPENCODE_*, CODEX_*, GEMINI_*, GOOGLE_*, ANTIGRAVITY_*, PI_* keys and CLAUDE_CONFIG_DIR are allowed.',
|
||||
'envOverrides contains blocked or disallowed env var keys. Only CLAUDE_CODE_*, OPENCODE_*, CODEX_*, GEMINI_*, GOOGLE_*, ANTIGRAVITY_* keys and CLAUDE_CONFIG_DIR are allowed.',
|
||||
}
|
||||
);
|
||||
|
||||
@@ -269,37 +269,6 @@ const AntigravityConfigSchema = z
|
||||
})
|
||||
.optional();
|
||||
|
||||
/**
|
||||
* Schema for Pi CLI (pi.dev)-specific configuration.
|
||||
*
|
||||
* No bypass field exists on purpose: pi has no permission prompts. The one
|
||||
* privilege-shaped knob is the TRI-STATE `approveProjectTrust` (see PiConfig),
|
||||
* which the multi-user clamp MATERIALIZES to `false` for non-granted owners.
|
||||
*/
|
||||
const PiConfigSchema = z
|
||||
.object({
|
||||
// `:` for a thinking suffix (`sonnet:high`), `/` for `provider/id`.
|
||||
model: z
|
||||
.string()
|
||||
.max(100)
|
||||
.regex(/^[a-zA-Z0-9._\-/:]+$/)
|
||||
.optional(),
|
||||
provider: z
|
||||
.string()
|
||||
.max(50)
|
||||
.regex(/^[a-z0-9-]+$/)
|
||||
.optional(),
|
||||
thinking: z.enum(['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max']).optional(),
|
||||
continueSession: z.boolean().optional(),
|
||||
resumeSessionId: z
|
||||
.string()
|
||||
.max(100)
|
||||
.regex(/^[a-zA-Z0-9._-]+$/)
|
||||
.optional(),
|
||||
approveProjectTrust: z.boolean().optional(),
|
||||
})
|
||||
.optional();
|
||||
|
||||
/**
|
||||
* The session that spawned the one being created — pure UI decoration, drawn as a
|
||||
* lineage line between the two tabs. Accepted here and, equivalently, as the
|
||||
@@ -313,7 +282,7 @@ const parentSessionIdSchema = z.string().max(100).optional();
|
||||
|
||||
export const CreateSessionSchema = z.object({
|
||||
workingDir: safePathSchema.optional(),
|
||||
mode: z.enum(['claude', 'shell', 'opencode', 'codex', 'gemini', 'antigravity', 'pi']).optional(),
|
||||
mode: z.enum(['claude', 'shell', 'opencode', 'codex', 'gemini', 'antigravity']).optional(),
|
||||
name: z.string().max(100).optional(),
|
||||
/** Session that spawned this one — see parentSessionIdSchema. */
|
||||
parentSessionId: parentSessionIdSchema,
|
||||
@@ -328,7 +297,6 @@ export const CreateSessionSchema = z.object({
|
||||
codexConfig: CodexConfigSchema,
|
||||
geminiConfig: GeminiConfigSchema,
|
||||
antigravityConfig: AntigravityConfigSchema,
|
||||
piConfig: PiConfigSchema,
|
||||
/** Resume a previous Claude conversation by its session ID (used for reboot recovery) */
|
||||
resumeSessionId: z
|
||||
.string()
|
||||
@@ -463,7 +431,6 @@ const RemoteCommandOverridesSchema = z
|
||||
codex: z.string().min(1).max(300).optional(),
|
||||
gemini: z.string().min(1).max(300).optional(),
|
||||
antigravity: z.string().min(1).max(300).optional(),
|
||||
pi: z.string().min(1).max(300).optional(),
|
||||
})
|
||||
.strict()
|
||||
.optional();
|
||||
@@ -738,12 +705,11 @@ export const QuickStartSchema = z.object({
|
||||
* a real host dir, so the settings file crosses the bind mount); rejected for
|
||||
* remote cases (the file would be written on the WRONG machine). */
|
||||
modelOverride: z.string().max(50).optional(),
|
||||
mode: z.enum(['claude', 'shell', 'opencode', 'codex', 'gemini', 'antigravity', 'pi']).optional(),
|
||||
mode: z.enum(['claude', 'shell', 'opencode', 'codex', 'gemini', 'antigravity']).optional(),
|
||||
openCodeConfig: OpenCodeConfigSchema,
|
||||
codexConfig: CodexConfigSchema,
|
||||
geminiConfig: GeminiConfigSchema,
|
||||
antigravityConfig: AntigravityConfigSchema,
|
||||
piConfig: PiConfigSchema,
|
||||
envOverrides: safeEnvOverridesSchema,
|
||||
/** Claude CLI effort level (soft default via --settings, switchable in-session via /effort) */
|
||||
effort: effortLevelSchema,
|
||||
@@ -1245,7 +1211,7 @@ const noNewlines = (v: string) => !/[\r\n]/.test(v);
|
||||
/** Shared field shape for creating/updating a scheduled job. */
|
||||
const CronJobBaseSchema = z.object({
|
||||
name: z.string().min(1).max(200),
|
||||
agentType: z.enum(['claude', 'shell', 'opencode', 'codex', 'gemini', 'antigravity', 'pi']),
|
||||
agentType: z.enum(['claude', 'shell', 'opencode', 'codex', 'gemini', 'antigravity']),
|
||||
workingDir: safePathSchema,
|
||||
launchCommand: z.string().max(2000).refine(noNewlines, 'launchCommand must be a single line').optional(),
|
||||
promptMode: z.enum(['inline_text', 'prompt_file_path']),
|
||||
|
||||
@@ -1380,7 +1380,6 @@ export class WebServer extends EventEmitter {
|
||||
{ isCodexAvailable },
|
||||
{ isGeminiAvailable },
|
||||
{ isAntigravityAvailable },
|
||||
{ isPiAvailable },
|
||||
{ isCloudflaredAvailable },
|
||||
{ isGitAvailable },
|
||||
] = await Promise.all([
|
||||
@@ -1389,7 +1388,6 @@ export class WebServer extends EventEmitter {
|
||||
import('../utils/codex-cli-resolver.js'),
|
||||
import('../utils/gemini-cli-resolver.js'),
|
||||
import('../utils/antigravity-cli-resolver.js'),
|
||||
import('../utils/pi-cli-resolver.js'),
|
||||
import('../utils/cloudflared-resolver.js'),
|
||||
import('../git-clone.js'),
|
||||
]);
|
||||
@@ -1399,7 +1397,6 @@ export class WebServer extends EventEmitter {
|
||||
codex: isCodexAvailable(),
|
||||
gemini: isGeminiAvailable(),
|
||||
antigravity: isAntigravityAvailable(),
|
||||
pi: isPiAvailable(),
|
||||
cloudflared: isCloudflaredAvailable(),
|
||||
// Not a run mode: the Add Case → Clone tab is an offer this box cannot
|
||||
// keep without git (issue #236), same reasoning as cloudflared above.
|
||||
@@ -2637,7 +2634,6 @@ export class WebServer extends EventEmitter {
|
||||
codexConfig: muxSession.mode === 'codex' ? savedState?.codexConfig : undefined,
|
||||
geminiConfig: muxSession.mode === 'gemini' ? savedState?.geminiConfig : undefined,
|
||||
antigravityConfig: muxSession.mode === 'antigravity' ? savedState?.antigravityConfig : undefined,
|
||||
piConfig: muxSession.mode === 'pi' ? savedState?.piConfig : undefined,
|
||||
envOverrides: savedEnvOverrides,
|
||||
effort: savedState?.effort,
|
||||
attachmentHistory: savedAttachmentHistory,
|
||||
|
||||
+21
-1
@@ -5,8 +5,9 @@
|
||||
* and referenced by the frontend (`SSE_EVENTS` in `constants.js`).
|
||||
* Both files MUST be kept in sync.
|
||||
*
|
||||
* 154 event constants organized by category:
|
||||
* 155 event constants organized by category:
|
||||
* - **Core** (1): init
|
||||
* - **Transport** (1): sse:heartbeat
|
||||
* - **Session lifecycle** (23): created, updated, deleted, terminal, idle, working, ...
|
||||
* - **Session: Ralph** (6): ralphLoopUpdate, todoUpdate, completionDetected, ...
|
||||
* - **Session: Bash tools** (3): bashToolStart, bashToolEnd, bashToolsUpdate
|
||||
@@ -52,6 +53,22 @@
|
||||
/** Sent to each SSE client on initial connection with full app state. */
|
||||
export const Init = 'init' as const;
|
||||
|
||||
// ─── Transport ───────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Liveness frame written to every SSE client every `SSE_HEARTBEAT_INTERVAL`.
|
||||
* Payload: `{ t: <epoch ms> }`.
|
||||
*
|
||||
* Carries no application data; its only job is to be *observable*. This was a
|
||||
* `:keepalive` SSE **comment**, and comments are invisible to `EventSource` by
|
||||
* spec, so a stream that stopped delivering without erroring (a proxy that
|
||||
* idle-closed it, a laptop resumed from sleep, a tailnet reconnect) was
|
||||
* undetectable to the client: `onerror` never fires and the UI freezes until a
|
||||
* reload. A named event reaches a listener, which is what lets the client's
|
||||
* staleness watchdog notice the silence and force a reconnect.
|
||||
*/
|
||||
export const Heartbeat = 'sse:heartbeat' as const;
|
||||
|
||||
// ─── Session Lifecycle ───────────────────────────────────────────────────────
|
||||
|
||||
/** New session spawned. */
|
||||
@@ -443,6 +460,9 @@ export const SseEvent = {
|
||||
// Core
|
||||
Init,
|
||||
|
||||
// Transport
|
||||
Heartbeat,
|
||||
|
||||
// Session lifecycle
|
||||
SessionCreated,
|
||||
SessionUpdated,
|
||||
|
||||
@@ -470,12 +470,20 @@ export class SseStreamManager {
|
||||
// ========== Client Health ==========
|
||||
|
||||
/**
|
||||
* Clean up dead SSE clients and send keep-alive comments.
|
||||
* Clean up dead SSE clients and send the liveness heartbeat.
|
||||
* Keep-alive prevents proxy/load-balancer timeouts on idle connections.
|
||||
* Dead client cleanup prevents memory leaks from abruptly terminated connections.
|
||||
*
|
||||
* The heartbeat is a NAMED event, not the `:keepalive` comment it used to be:
|
||||
* comments are invisible to `EventSource` by spec, so a stream that stopped
|
||||
* delivering without erroring was undetectable to the client (see
|
||||
* `SseEvent.Heartbeat`). Written per-client rather than through `broadcast()`
|
||||
* deliberately: the frame carries no session data, so it needs no owner
|
||||
* routing, and this loop is already walking every client to check its socket.
|
||||
*/
|
||||
cleanupDeadClients(): void {
|
||||
const deadClients: FastifyReply[] = [];
|
||||
const heartbeat = `event: ${SseEvent.Heartbeat}\ndata: ${JSON.stringify({ t: Date.now() })}\n\n`;
|
||||
|
||||
for (const [client] of this.sseClients) {
|
||||
try {
|
||||
@@ -484,11 +492,9 @@ export class SseStreamManager {
|
||||
if (!socket || socket.destroyed || !socket.writable) {
|
||||
deadClients.push(client);
|
||||
} else {
|
||||
// Send SSE comment as keep-alive. Only add padding when tunnel is
|
||||
// active — it flushes Cloudflare proxy buffers but wastes bandwidth
|
||||
// for direct/Tailscale connections.
|
||||
const ka = this._isTunnelActive ? ':keepalive\n' + SSE_PADDING : ':keepalive\n\n';
|
||||
client.raw.write(ka);
|
||||
// Only add padding when tunnel is active: it flushes Cloudflare
|
||||
// proxy buffers but wastes bandwidth for direct/Tailscale connections.
|
||||
client.raw.write(this._isTunnelActive ? heartbeat + SSE_PADDING : heartbeat);
|
||||
}
|
||||
} catch {
|
||||
// Error accessing socket means client is dead
|
||||
|
||||
@@ -1,125 +0,0 @@
|
||||
/**
|
||||
* @fileoverview Static guard: the packaged agent skill's run-mode enumerations stay in
|
||||
* step with the modes the server actually accepts.
|
||||
*
|
||||
* `skills/codeman/**` is injected into cases and read by agents driving Codeman over
|
||||
* HTTP, so a mode missing from its lists is not cosmetic: the agent is told a backend
|
||||
* does not exist, or that a whole-class caveat ("these modes write no transcript")
|
||||
* covers four modes when it covers five. Adding pi (#206) left every one of those lists
|
||||
* stale while CI stayed green, because nothing tied the prose to the schema.
|
||||
*
|
||||
* Two rules, both derived from the RUNTIME source of truth (the Zod enum in schemas.ts,
|
||||
* not a copy):
|
||||
*
|
||||
* 1. The `mode ∈ a|b|c` enumeration in endpoints.md is the mode list, exactly, and the
|
||||
* per-CLI availability probe (`GET /api/<mode>/status`) is documented for every
|
||||
* agent mode. That second half is the narrow, family-scoped answer to "should the
|
||||
* endpoint scanner also check registered-to-documented?". In general it should not:
|
||||
* the skill documents 34 of 217 registered endpoints on purpose (it is an agent
|
||||
* guide, not an API reference), so a blanket reverse check needs a 183-entry
|
||||
* allowlist that fails CI on unrelated routes and gets appended to mechanically.
|
||||
* Grouping by path shape does not rescue it either: the families that produces are
|
||||
* things like `DELETE /api/<any>/:id`, which lumps cases, webviews and docker hosts
|
||||
* together. A family the SCHEMA can enumerate is the exception, since it needs no
|
||||
* allowlist at all.
|
||||
* 2. Any prose enumeration of 3+ distinct modes must be COMPLETE with respect to the
|
||||
* external CLIs: those lists exist to describe what `isExternalCliMode()` gates
|
||||
* (no Claude transcript, no hooks, no Claude-format parsers), so naming some but
|
||||
* not all of them is the drift itself. Runs of one or two modes are exempt, since
|
||||
* a legitimate pair ("claude or shell") is not a class claim. ONE exception is
|
||||
* allowed and it is a real one: the "writes no transcript" lists drop `codex`,
|
||||
* which does write a rollout Codeman reads back (the pane carries a unique
|
||||
* originator precisely so `last-response` can find it), so external-minus-codex
|
||||
* is a meaningful class rather than an oversight.
|
||||
*
|
||||
* Port: N/A (pure static analysis).
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { join } from 'node:path';
|
||||
import { CreateSessionSchema, QuickStartSchema } from '../src/web/schemas.js';
|
||||
import { isExternalCliMode } from '../src/session.js';
|
||||
import type { SessionMode } from '../src/types/session.js';
|
||||
|
||||
const HERE = fileURLToPath(new URL('.', import.meta.url));
|
||||
const SKILL_DIR = join(HERE, '../skills/codeman');
|
||||
const SKILL_FILES = ['SKILL.md', 'reference/endpoints.md', 'reference/messaging.md', 'reference/recipes.md'];
|
||||
|
||||
/** Modes the API actually accepts, read off the schema rather than restated here. */
|
||||
function schemaModes(schema: typeof CreateSessionSchema | typeof QuickStartSchema): SessionMode[] {
|
||||
// `mode` is `z.enum([...]).optional()`; unwrap the optional to reach `.options`.
|
||||
return (schema as unknown as { shape: { mode: { unwrap(): { options: SessionMode[] } } } }).shape.mode.unwrap()
|
||||
.options;
|
||||
}
|
||||
|
||||
const MODES = schemaModes(CreateSessionSchema);
|
||||
const EXTERNAL_MODES = MODES.filter(isExternalCliMode);
|
||||
|
||||
/**
|
||||
* Mode tokens appearing back to back, separated only by list punctuation — `a|b|c`,
|
||||
* `a`/`b`/`c`, "`a`, `b` and `c`". Newlines collapse to spaces first so a wrapped list
|
||||
* still reads as one run. The separator budget is deliberately small: it must span
|
||||
* ", " and " and " without swallowing a sentence between two unrelated mentions.
|
||||
*/
|
||||
const MODE_ALTERNATION = MODES.map((m) => `\`?${m}\`?`).join('|');
|
||||
const ENUMERATION_RUN = new RegExp(`(?:(?:${MODE_ALTERNATION})(?:[\\s,/|]|and\\b|or\\b){0,6}){3,}`, 'g');
|
||||
|
||||
function enumerationRuns(text: string): string[] {
|
||||
const flat = text.replace(/\s+/g, ' ');
|
||||
return [...flat.matchAll(ENUMERATION_RUN)].map((m) => m[0]);
|
||||
}
|
||||
|
||||
function modesIn(run: string): SessionMode[] {
|
||||
return MODES.filter((m) => new RegExp(`\\b${m}\\b`).test(run));
|
||||
}
|
||||
|
||||
describe('agent skill run-mode lists', () => {
|
||||
it('derives the mode list from the schema, and both endpoints agree', () => {
|
||||
expect(MODES).toContain('pi');
|
||||
expect(new Set(schemaModes(QuickStartSchema))).toEqual(new Set(MODES));
|
||||
expect(EXTERNAL_MODES.length).toBeGreaterThan(1);
|
||||
});
|
||||
|
||||
it('documents the CLI availability probe for every agent mode', () => {
|
||||
// The gap this closes: /api/pi/status shipped undocumented and only a human reading
|
||||
// the doc noticed, because the sibling scanner (agent-skill-endpoints-doc.test.ts)
|
||||
// only checks documented -> registered. Derived from the schema, so a seventh
|
||||
// backend fails here until its probe is documented; the sibling test still proves
|
||||
// the reverse, that nothing documented here is a 404.
|
||||
const doc = readFileSync(join(SKILL_DIR, 'reference/endpoints.md'), 'utf-8');
|
||||
const documented = new Set([...doc.matchAll(/\bGET\s+\/api(?:\/v1)?\/([a-z-]+)\/status\b/g)].map((m) => m[1]));
|
||||
const probeable = MODES.filter((m) => m !== 'shell'); // shell has no CLI to probe
|
||||
expect([...probeable].filter((m) => !documented.has(m))).toEqual([]);
|
||||
});
|
||||
|
||||
it("documents exactly the accepted modes in endpoints.md's `mode ∈ …` enumeration", () => {
|
||||
const doc = readFileSync(join(SKILL_DIR, 'reference/endpoints.md'), 'utf-8');
|
||||
const match = doc.match(/`mode` ∈ `([a-z|]+)`/);
|
||||
expect(match, 'endpoints.md no longer states the accepted `mode` values').not.toBeNull();
|
||||
expect(new Set(match![1].split('|'))).toEqual(new Set(MODES));
|
||||
});
|
||||
|
||||
it('never enumerates a partial set of external CLI modes', () => {
|
||||
const complete = new Set<string>(EXTERNAL_MODES);
|
||||
/** The documented exception: codex writes a rollout, so it is absent from the
|
||||
* "no transcript" lists on purpose. Every OTHER external mode must still be there. */
|
||||
const withoutCodex = new Set<string>(EXTERNAL_MODES.filter((m) => m !== 'codex'));
|
||||
const sameSet = (a: Set<string>, b: Set<string>) => a.size === b.size && [...a].every((v) => b.has(v));
|
||||
|
||||
const offenders: string[] = [];
|
||||
for (const file of SKILL_FILES) {
|
||||
for (const run of enumerationRuns(readFileSync(join(SKILL_DIR, file), 'utf-8'))) {
|
||||
const listed = modesIn(run);
|
||||
if (listed.length < 3) continue;
|
||||
const externals = new Set<string>(listed.filter(isExternalCliMode));
|
||||
// Empty is fine (a claude/shell-only list); partial is the drift.
|
||||
if (externals.size === 0 || sameSet(externals, complete) || sameSet(externals, withoutCodex)) continue;
|
||||
const missing = EXTERNAL_MODES.filter((m) => !externals.has(m));
|
||||
offenders.push(`${file}: "${run.trim()}" is missing ${missing.join(', ')}`);
|
||||
}
|
||||
}
|
||||
expect(offenders).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -16,7 +16,7 @@ import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { existsSync, mkdtempSync, mkdirSync, writeFileSync, symlinkSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { CronService, clampCronExternalCliConfigs, type CronDeps } from '../src/cron/cron-service.js';
|
||||
import { CronService, type CronDeps } from '../src/cron/cron-service.js';
|
||||
import { CronJobSchema } from '../src/web/schemas.js';
|
||||
import { MAX_CRON_JOBS } from '../src/config/map-limits.js';
|
||||
import type { CronJob, CronJobRun } from '../src/types/cron.js';
|
||||
@@ -632,36 +632,3 @@ describe('CronService', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* The §6.3 clamp cron applies at FIRE time. Cron sends no per-CLI config, so a
|
||||
* missing clamp here is not "the default applies" but "the CLI's own unsafe default
|
||||
* applies", which is the whole reason gemini and pi are materialized rather than
|
||||
* left absent like codex/antigravity.
|
||||
*/
|
||||
describe('clampCronExternalCliConfigs', () => {
|
||||
it('leaves everything undefined for a granted owner (upstream defaults)', () => {
|
||||
expect(clampCronExternalCliConfigs('gemini', true)).toEqual({ geminiConfig: undefined, piConfig: undefined });
|
||||
expect(clampCronExternalCliConfigs('pi', true)).toEqual({ geminiConfig: undefined, piConfig: undefined });
|
||||
});
|
||||
|
||||
it('materializes gemini auto_edit for a non-granted owner (its default is yolo)', () => {
|
||||
expect(clampCronExternalCliConfigs('gemini', false)).toEqual({
|
||||
geminiConfig: { approvalMode: 'auto_edit' },
|
||||
piConfig: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it('materializes pi --no-approve for a non-granted owner (its default is an answerable prompt)', () => {
|
||||
expect(clampCronExternalCliConfigs('pi', false)).toEqual({
|
||||
geminiConfig: undefined,
|
||||
piConfig: { approveProjectTrust: false },
|
||||
});
|
||||
});
|
||||
|
||||
it('clamps nothing for modes whose absent config already spawns safe', () => {
|
||||
for (const mode of ['claude', 'shell', 'opencode', 'codex', 'antigravity'] as const) {
|
||||
expect(clampCronExternalCliConfigs(mode, false)).toEqual({ geminiConfig: undefined, piConfig: undefined });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
} from '../src/utils/dependency-checker.js';
|
||||
import type { ProbeHost } from '../src/utils/dependency-checker.js';
|
||||
import type { ProbeEnvironment, ToolDependency } from '../src/config/dependency-registry.js';
|
||||
import { PI_VERSION_REGEX } from '../src/utils/pi-cli-resolver.js';
|
||||
|
||||
describe('DEPENDENCY_REGISTRY', () => {
|
||||
it('has unique ids', () => {
|
||||
@@ -30,20 +29,6 @@ describe('DEPENDENCY_REGISTRY', () => {
|
||||
expect(office.every((t) => t.required === false)).toBe(true);
|
||||
});
|
||||
|
||||
it('resolves pi through the SAME version rule the run mode uses', () => {
|
||||
// `pi` is a short generic name, so pi-cli-resolver.ts refuses a binary that does not
|
||||
// print semver. If the doctor did not apply the identical rule it would report
|
||||
// "Pi CLI ✓" on a box where Run Pi stays hidden, which reads as a broken mode
|
||||
// rather than a missing install. One regex, shared, is what keeps them agreeing.
|
||||
const pi = DEPENDENCY_REGISTRY.find((t) => t.id === 'pi');
|
||||
expect(pi).toBeDefined();
|
||||
const spec = pi!.resolvers.find((r) => r.resolver.kind === 'path');
|
||||
expect(spec).toBeDefined();
|
||||
const resolver = spec!.resolver as { versionRegex?: RegExp; requireVersionMatch?: boolean };
|
||||
expect(resolver.requireVersionMatch).toBe(true);
|
||||
expect(resolver.versionRegex).toBe(PI_VERSION_REGEX);
|
||||
});
|
||||
|
||||
it('gives msoffice a windows-side resolver scoped to wsl + win32 only', () => {
|
||||
const ms = DEPENDENCY_REGISTRY.find((t) => t.id === 'msoffice');
|
||||
expect(ms).toBeDefined();
|
||||
@@ -179,54 +164,6 @@ describe('checkTool', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('checkTool with requireVersionMatch (generic binary names)', () => {
|
||||
const piTool: ToolDependency = {
|
||||
id: 'pi',
|
||||
label: 'Pi CLI',
|
||||
category: 'core',
|
||||
required: false,
|
||||
resolvers: [
|
||||
{
|
||||
match: ['linux'],
|
||||
resolver: {
|
||||
kind: 'path',
|
||||
bins: ['pi'],
|
||||
versionArg: '--version',
|
||||
versionRegex: PI_VERSION_REGEX,
|
||||
requireVersionMatch: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
it('accepts a binary that prints a semver version', () => {
|
||||
const host = fakeHost('linux', { which: () => '/home/u/.npm-global/bin/pi', runVersion: () => '0.84.1\n' });
|
||||
expect(checkTool(piTool, host)).toMatchObject({
|
||||
id: 'pi',
|
||||
status: 'ok',
|
||||
version: '0.84.1',
|
||||
path: '/home/u/.npm-global/bin/pi',
|
||||
});
|
||||
});
|
||||
|
||||
it('reports MISSING for an unrelated `pi` on PATH instead of an installed tool', () => {
|
||||
// The whole point: a Raspberry Pi helper answers `--version` with prose, and calling
|
||||
// that "installed" contradicts resolvePiDir(), which rejects it.
|
||||
const host = fakeHost('linux', { which: () => '/usr/bin/pi', runVersion: () => 'Raspberry Pi utility\n' });
|
||||
expect(checkTool(piTool, host)).toMatchObject({ id: 'pi', status: 'missing' });
|
||||
});
|
||||
|
||||
it('reports MISSING when the binary answers nothing at all', () => {
|
||||
const host = fakeHost('linux', { which: () => '/usr/bin/pi', runVersion: () => null });
|
||||
expect(checkTool(piTool, host)).toMatchObject({ id: 'pi', status: 'missing' });
|
||||
});
|
||||
|
||||
it('leaves tools without the flag reporting ok on an unparsable version (unchanged)', () => {
|
||||
const host = fakeHost('linux', { which: () => '/usr/bin/tmux', runVersion: () => 'no version here' });
|
||||
expect(checkTool(tmuxTool, host)).toMatchObject({ id: 'tmux', status: 'ok', version: undefined });
|
||||
});
|
||||
});
|
||||
|
||||
describe('checkAll', () => {
|
||||
it('maps every tool to a result', () => {
|
||||
const results = checkAll([tmuxTool, msTool], fakeHost('linux'));
|
||||
|
||||
@@ -143,26 +143,6 @@ describe('home sessions column: model', () => {
|
||||
});
|
||||
expect(plain.buildHomeSessionRows()[0].modeBadge).toBe('');
|
||||
});
|
||||
|
||||
it('badges every non-claude backend, so a new run mode cannot read as claude here', () => {
|
||||
// The badge map is a per-mode lookup with a '' fallback, so a mode missing from it
|
||||
// is indistinguishable from claude in this rail while the tab strip badges it fine.
|
||||
for (const [mode, badge] of [
|
||||
['shell', 'sh'],
|
||||
['opencode', 'oc'],
|
||||
['codex', 'cx'],
|
||||
['gemini', 'gm'],
|
||||
['antigravity', 'ag'],
|
||||
['pi', 'pi'],
|
||||
] as const) {
|
||||
const app = loadHomeSessionsApp({
|
||||
sessions: sessionMap([{ id: 'a', mode }]),
|
||||
sessionOrder: ['a'],
|
||||
cases: CASES,
|
||||
});
|
||||
expect(app.buildHomeSessionRows()[0].modeBadge).toBe(badge);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('home sessions column: gate', () => {
|
||||
|
||||
@@ -358,6 +358,83 @@ describe('Inline rename input', () => {
|
||||
expect(result.editingAfter).toBe(null);
|
||||
});
|
||||
|
||||
it('Commit writes the confirmed name into app.sessions WITHOUT any session:updated frame', async () => {
|
||||
await resetState();
|
||||
expect(await startRename('no-sse', 'w9-case')).toBe(true);
|
||||
|
||||
// finishRename() re-renders the tab strip from app.sessions, so the rename
|
||||
// used to depend on the session:updated SSE frame to carry its own write
|
||||
// back. On a page whose stream has gone quiet without erroring, the PUT
|
||||
// stored the new name, the re-render repainted the stale one, and the tab
|
||||
// only showed it after a full reload. No SSE is dispatched here at all.
|
||||
const result = await page.evaluate(async () => {
|
||||
const app = (
|
||||
window as unknown as {
|
||||
app: { sessions: Map<string, { id: string; name: string }> };
|
||||
}
|
||||
).app;
|
||||
const origFetch = window.fetch;
|
||||
window.fetch = (async () =>
|
||||
new Response('{"success":true,"data":{"name":"w9-case: fresh"}}', {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})) as typeof window.fetch;
|
||||
|
||||
const inputEl = document.querySelector('input.tab-rename-input') as HTMLInputElement;
|
||||
inputEl.value = 'fresh';
|
||||
inputEl.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));
|
||||
await new Promise((r) => setTimeout(r, 60));
|
||||
|
||||
window.fetch = origFetch;
|
||||
return { mapName: app.sessions.get('no-sse')?.name ?? null };
|
||||
});
|
||||
|
||||
expect(result.mapName).toBe('w9-case: fresh');
|
||||
});
|
||||
|
||||
it('A rejected rename restores the old label and leaves app.sessions untouched', async () => {
|
||||
await resetState();
|
||||
expect(await startRename('rename-500', 'w9-case')).toBe(true);
|
||||
|
||||
// _apiPut turns a network error into a null Response and an API-level
|
||||
// failure arrives as a non-ok status, neither of which throws, so a
|
||||
// rejected rename has to be detected from the response, or it reports
|
||||
// success and silently discards the user's edit.
|
||||
const result = await page.evaluate(async () => {
|
||||
const app = (
|
||||
window as unknown as {
|
||||
app: { sessions: Map<string, { id: string; name: string }>; showToast: (m: string, k: string) => void };
|
||||
}
|
||||
).app;
|
||||
const toasts: string[] = [];
|
||||
const origToast = app.showToast;
|
||||
app.showToast = (msg: string) => void toasts.push(msg);
|
||||
const origFetch = window.fetch;
|
||||
window.fetch = (async () =>
|
||||
new Response('{"success":false,"error":"boom","errorCode":"INTERNAL"}', {
|
||||
status: 500,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})) as typeof window.fetch;
|
||||
|
||||
const inputEl = document.querySelector('input.tab-rename-input') as HTMLInputElement;
|
||||
inputEl.value = 'never-stored';
|
||||
inputEl.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));
|
||||
await new Promise((r) => setTimeout(r, 60));
|
||||
|
||||
window.fetch = origFetch;
|
||||
app.showToast = origToast;
|
||||
return {
|
||||
mapName: app.sessions.get('rename-500')?.name ?? null,
|
||||
label: document.querySelector('.tab-name[data-session-id="rename-500"]')?.textContent ?? null,
|
||||
toasts,
|
||||
};
|
||||
});
|
||||
|
||||
expect(result.mapName).toBe('w9-case');
|
||||
expect(result.label).toBe('w9-case');
|
||||
expect(result.toasts).toContain('Failed to rename');
|
||||
});
|
||||
|
||||
it('Re-entry: starting rename while one is active aborts the previous one', async () => {
|
||||
await resetState();
|
||||
expect(await startRename('first-id', 'First')).toBe(true);
|
||||
|
||||
@@ -190,7 +190,7 @@ describe('_updateLocalEchoState mode gating', () => {
|
||||
expect(app._localEchoEnabled).toBe(false);
|
||||
});
|
||||
|
||||
it.each(['claude', 'gemini', 'opencode', 'pi'])('keeps the overlay enabled for %s sessions', (mode) => {
|
||||
it.each(['claude', 'gemini', 'opencode'])('keeps the overlay enabled for %s sessions', (mode) => {
|
||||
const overlay = makeOverlay();
|
||||
const app = makeApp(mode, overlay);
|
||||
app._updateLocalEchoState();
|
||||
@@ -373,19 +373,16 @@ describe('_updateLocalEchoState echo policy', () => {
|
||||
expect(app._predictiveEcho.clearPredictions).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(['claude', 'gemini', 'opencode', 'pi'])(
|
||||
"%s -> policy 'buffer' + overlay enabled (existing behavior)",
|
||||
(mode) => {
|
||||
const overlay = makeOverlay();
|
||||
const app = makeApp(mode, overlay) as PredictiveApp;
|
||||
app._predictiveEcho = makePredictor();
|
||||
app._updateLocalEchoState();
|
||||
expect(app._localEchoPolicy).toBe('buffer');
|
||||
expect(app._localEchoEnabled).toBe(true);
|
||||
expect(overlay.prompts.length).toBeGreaterThan(0); // setPrompt still called
|
||||
expect(app._predictiveEcho.clearPredictions).toHaveBeenCalled(); // not predict -> stray spans cleared
|
||||
}
|
||||
);
|
||||
it.each(['claude', 'gemini', 'opencode'])("%s -> policy 'buffer' + overlay enabled (existing behavior)", (mode) => {
|
||||
const overlay = makeOverlay();
|
||||
const app = makeApp(mode, overlay) as PredictiveApp;
|
||||
app._predictiveEcho = makePredictor();
|
||||
app._updateLocalEchoState();
|
||||
expect(app._localEchoPolicy).toBe('buffer');
|
||||
expect(app._localEchoEnabled).toBe(true);
|
||||
expect(overlay.prompts.length).toBeGreaterThan(0); // setPrompt still called
|
||||
expect(app._predictiveEcho.clearPredictions).toHaveBeenCalled(); // not predict -> stray spans cleared
|
||||
});
|
||||
|
||||
it('no active session -> policy off, no crash without a predictor instance', () => {
|
||||
const app = makeApp('codex') as PredictiveApp;
|
||||
|
||||
@@ -372,7 +372,7 @@ describe('mobile overview run picker (CLI availability gating)', () => {
|
||||
isCliAvailable: () => true,
|
||||
});
|
||||
const menu = app._buildMobileOverviewRunMenu();
|
||||
expect(modeButtons(menu)).toEqual(['claude', 'opencode', 'codex', 'gemini', 'antigravity', 'pi', 'shell']);
|
||||
expect(modeButtons(menu)).toEqual(['claude', 'opencode', 'codex', 'gemini', 'antigravity', 'shell']);
|
||||
});
|
||||
|
||||
it('gates every mode the picker actually offers', () => {
|
||||
|
||||
@@ -1,200 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { CreateSessionSchema, QuickStartSchema } from '../src/web/schemas.js';
|
||||
import { buildSpawnCommand } from '../src/tmux-manager.js';
|
||||
import { defaultDockerCommandForMode } from '../src/docker-hosts.js';
|
||||
import { defaultRemoteCommandForMode, buildRemoteCliVersionProbeCommand } from '../src/remote-hosts.js';
|
||||
import { isExternalCliMode, isAltScreenStripMode } from '../src/session.js';
|
||||
|
||||
describe('Pi mode schemas', () => {
|
||||
it('accepts Pi session creation config', () => {
|
||||
const parsed = CreateSessionSchema.parse({
|
||||
workingDir: '/tmp',
|
||||
mode: 'pi',
|
||||
piConfig: {
|
||||
model: 'sonnet:high',
|
||||
provider: 'anthropic',
|
||||
thinking: 'high',
|
||||
},
|
||||
});
|
||||
|
||||
expect(parsed.mode).toBe('pi');
|
||||
expect(parsed.piConfig).toEqual({
|
||||
model: 'sonnet:high',
|
||||
provider: 'anthropic',
|
||||
thinking: 'high',
|
||||
});
|
||||
});
|
||||
|
||||
it('accepts Pi quick-start config', () => {
|
||||
const parsed = QuickStartSchema.parse({
|
||||
caseName: 'pi-case',
|
||||
mode: 'pi',
|
||||
piConfig: { resumeSessionId: '0f9c2b14-aa10', continueSession: true },
|
||||
});
|
||||
|
||||
expect(parsed.mode).toBe('pi');
|
||||
expect(parsed.piConfig?.resumeSessionId).toBe('0f9c2b14-aa10');
|
||||
});
|
||||
|
||||
it('accepts a provider-qualified model (`openai/gpt-4o`)', () => {
|
||||
const parsed = CreateSessionSchema.parse({
|
||||
workingDir: '/tmp',
|
||||
mode: 'pi',
|
||||
piConfig: { model: 'openai/gpt-4o' },
|
||||
});
|
||||
expect(parsed.piConfig?.model).toBe('openai/gpt-4o');
|
||||
});
|
||||
|
||||
it('rejects unsafe Pi model strings', () => {
|
||||
expect(() =>
|
||||
CreateSessionSchema.parse({
|
||||
workingDir: '/tmp',
|
||||
mode: 'pi',
|
||||
piConfig: { model: 'pi; rm -rf /' },
|
||||
})
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it('rejects unsafe Pi provider strings', () => {
|
||||
expect(() =>
|
||||
CreateSessionSchema.parse({
|
||||
workingDir: '/tmp',
|
||||
mode: 'pi',
|
||||
piConfig: { provider: 'anthropic`whoami`' },
|
||||
})
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it('rejects unsafe Pi resumeSessionId values (ids only, never paths)', () => {
|
||||
expect(() =>
|
||||
CreateSessionSchema.parse({
|
||||
workingDir: '/tmp',
|
||||
mode: 'pi',
|
||||
piConfig: { resumeSessionId: '../../etc/passwd' },
|
||||
})
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it('rejects thinking levels outside pi’s enum', () => {
|
||||
expect(() =>
|
||||
CreateSessionSchema.parse({
|
||||
workingDir: '/tmp',
|
||||
mode: 'pi',
|
||||
piConfig: { thinking: 'ultra' },
|
||||
})
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it('allows PI_* env overrides but NOT bare provider keys', () => {
|
||||
const parsed = CreateSessionSchema.parse({
|
||||
workingDir: '/tmp',
|
||||
mode: 'pi',
|
||||
envOverrides: { PI_OFFLINE: '1' },
|
||||
});
|
||||
expect(parsed.envOverrides).toEqual({ PI_OFFLINE: '1' });
|
||||
|
||||
// Pi's ~34 provider key vars share no prefix, and ALLOWED_ENV_PREFIXES is a single
|
||||
// GLOBAL list with no mode context — allowlisting them for pi would widen the
|
||||
// allowlist for every mode at once. They stay out; auth goes through pi's /login.
|
||||
expect(() =>
|
||||
CreateSessionSchema.parse({
|
||||
workingDir: '/tmp',
|
||||
mode: 'pi',
|
||||
envOverrides: { ANTHROPIC_API_KEY: 'sk-test' },
|
||||
})
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Pi spawn command', () => {
|
||||
it('builds a bare pi command when no config is sent (pi has no permission prompts)', () => {
|
||||
const cmd = buildSpawnCommand({ mode: 'pi', sessionId: 'abc12345' });
|
||||
expect(cmd).toBe('pi');
|
||||
});
|
||||
|
||||
it('maps model/provider/thinking to flags', () => {
|
||||
const cmd = buildSpawnCommand({
|
||||
mode: 'pi',
|
||||
sessionId: 'abc12345',
|
||||
piConfig: { model: 'sonnet:high', provider: 'anthropic', thinking: 'xhigh' },
|
||||
});
|
||||
expect(cmd).toBe('pi --model sonnet:high --provider anthropic --thinking xhigh');
|
||||
});
|
||||
|
||||
it('emits --approve for true and --no-approve for false (tri-state project trust)', () => {
|
||||
expect(buildSpawnCommand({ mode: 'pi', sessionId: 'a', piConfig: { approveProjectTrust: true } })).toBe(
|
||||
'pi --approve'
|
||||
);
|
||||
expect(buildSpawnCommand({ mode: 'pi', sessionId: 'a', piConfig: { approveProjectTrust: false } })).toBe(
|
||||
'pi --no-approve'
|
||||
);
|
||||
// Absent = pi's own defaultProjectTrust; Codeman must not decide it.
|
||||
expect(buildSpawnCommand({ mode: 'pi', sessionId: 'a', piConfig: {} })).toBe('pi');
|
||||
});
|
||||
|
||||
it('passes --session for resume and skips -c when both are present', () => {
|
||||
expect(buildSpawnCommand({ mode: 'pi', sessionId: 'a', piConfig: { resumeSessionId: '0f9c2b14' } })).toBe(
|
||||
'pi --session 0f9c2b14'
|
||||
);
|
||||
|
||||
expect(buildSpawnCommand({ mode: 'pi', sessionId: 'a', piConfig: { continueSession: true } })).toBe('pi -c');
|
||||
|
||||
// The two conflict upstream: a valid explicit session id wins.
|
||||
expect(
|
||||
buildSpawnCommand({
|
||||
mode: 'pi',
|
||||
sessionId: 'a',
|
||||
piConfig: { continueSession: true, resumeSessionId: '0f9c2b14' },
|
||||
})
|
||||
).toBe('pi --session 0f9c2b14');
|
||||
});
|
||||
|
||||
it('drops unsafe values rather than escaping them (the result lands in `bash -c "..."`)', () => {
|
||||
expect(buildSpawnCommand({ mode: 'pi', sessionId: 'a', piConfig: { model: 'a`b' } })).toBe('pi');
|
||||
expect(buildSpawnCommand({ mode: 'pi', sessionId: 'a', piConfig: { provider: 'x;id' } })).toBe('pi');
|
||||
expect(buildSpawnCommand({ mode: 'pi', sessionId: 'a', piConfig: { resumeSessionId: 'x; rm -rf /' } })).toBe('pi');
|
||||
// An out-of-enum thinking level never reaches the command line either.
|
||||
expect(
|
||||
buildSpawnCommand({
|
||||
mode: 'pi',
|
||||
sessionId: 'a',
|
||||
piConfig: { thinking: 'ultra' as unknown as 'high' },
|
||||
})
|
||||
).toBe('pi');
|
||||
});
|
||||
|
||||
it('never emits --api-key (a provider secret must not reach the spawn line)', () => {
|
||||
const cmd = buildSpawnCommand({
|
||||
mode: 'pi',
|
||||
sessionId: 'a',
|
||||
piConfig: { model: 'sonnet', provider: 'anthropic', approveProjectTrust: true },
|
||||
});
|
||||
expect(cmd).not.toContain('--api-key');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Pi mode gates', () => {
|
||||
it('is an external CLI mode (readiness/ralph/respawn gating)', () => {
|
||||
expect(isExternalCliMode('pi')).toBe(true);
|
||||
});
|
||||
|
||||
it('is NOT an alt-screen strip mode (main-screen TUI + runtime-switchable fullscreen)', () => {
|
||||
expect(isAltScreenStripMode('pi')).toBe(false);
|
||||
});
|
||||
|
||||
it('has docker/remote default commands', () => {
|
||||
expect(defaultDockerCommandForMode('pi')).toBe('exec pi');
|
||||
// Routed through an interactive login shell so npm's global bin resolves —
|
||||
// same fix as the other remote agent CLIs (see defaultRemoteCommandForMode).
|
||||
expect(defaultRemoteCommandForMode('pi')).toBe('exec "${SHELL:-/bin/sh}" -i -l -c \'pi\'');
|
||||
});
|
||||
|
||||
it('probes the CLI version on a remote host (REMOTE_CLI_BIN carries pi)', () => {
|
||||
// Without the REMOTE_CLI_BIN entry this returns null and Session.cliVersion stays
|
||||
// blank for every remote pi session, which is invisible until someone asks why the
|
||||
// version column is empty on that host only.
|
||||
const cmd = buildRemoteCliVersionProbeCommand({ username: 'dev', host: 'box.example', port: 22 }, 'pi');
|
||||
expect(cmd).not.toBeNull();
|
||||
expect(cmd).toContain('pi --version');
|
||||
});
|
||||
});
|
||||
@@ -17,7 +17,6 @@ import { isOpenCodeAvailable } from '../src/utils/opencode-cli-resolver.js';
|
||||
import { isCodexAvailable } from '../src/utils/codex-cli-resolver.js';
|
||||
import { isGeminiAvailable } from '../src/utils/gemini-cli-resolver.js';
|
||||
import { isAntigravityAvailable } from '../src/utils/antigravity-cli-resolver.js';
|
||||
import { isPiAvailable } from '../src/utils/pi-cli-resolver.js';
|
||||
import { isCloudflaredAvailable } from '../src/utils/cloudflared-resolver.js';
|
||||
import { isGitAvailable } from '../src/git-clone.js';
|
||||
|
||||
@@ -44,11 +43,6 @@ vi.mock('../src/utils/antigravity-cli-resolver.js', () => ({
|
||||
isAntigravityAvailable: vi.fn(() => false),
|
||||
resolveAntigravityDir: vi.fn(() => null),
|
||||
}));
|
||||
vi.mock('../src/utils/pi-cli-resolver.js', () => ({
|
||||
isPiAvailable: vi.fn(() => false),
|
||||
resolvePiDir: vi.fn(() => null),
|
||||
getPiCliVersion: vi.fn(() => null),
|
||||
}));
|
||||
vi.mock('../src/utils/cloudflared-resolver.js', () => ({
|
||||
isCloudflaredAvailable: vi.fn(() => false),
|
||||
resolveCloudflaredPath: vi.fn(() => null),
|
||||
@@ -137,7 +131,6 @@ describe('WebServer.renderIndexHtml', () => {
|
||||
vi.mocked(isCodexAvailable).mockReturnValue(true);
|
||||
vi.mocked(isGeminiAvailable).mockReturnValue(false);
|
||||
vi.mocked(isAntigravityAvailable).mockReturnValue(false);
|
||||
vi.mocked(isPiAvailable).mockReturnValue(true);
|
||||
vi.mocked(isCloudflaredAvailable).mockReturnValue(true);
|
||||
vi.mocked(isGitAvailable).mockReturnValue(true);
|
||||
const { server } = makeServer({});
|
||||
@@ -151,7 +144,6 @@ describe('WebServer.renderIndexHtml', () => {
|
||||
codex: true,
|
||||
gemini: false,
|
||||
antigravity: false,
|
||||
pi: true,
|
||||
cloudflared: true,
|
||||
git: true,
|
||||
});
|
||||
@@ -166,7 +158,6 @@ describe('WebServer.renderIndexHtml', () => {
|
||||
isCodexAvailable,
|
||||
isGeminiAvailable,
|
||||
isAntigravityAvailable,
|
||||
isPiAvailable,
|
||||
isCloudflaredAvailable,
|
||||
isGitAvailable,
|
||||
]) {
|
||||
|
||||
@@ -1,132 +0,0 @@
|
||||
/**
|
||||
* First coverage for `clampExternalCliBypassForOwner` (session-routes.ts), the
|
||||
* multi-user §6.3 gate that keeps a NON-GRANTED owner from launching an external
|
||||
* CLI with its safety switches off. It backs both `POST /api/sessions` and
|
||||
* `POST /api/quick-start` and, until pi was added, had no tests at all.
|
||||
*
|
||||
* The helper has two shapes and the difference is the whole point:
|
||||
* - only-if-sent (codex, antigravity): an ABSENT config already spawns safe, so
|
||||
* only a sent config needs its flag forced off.
|
||||
* - MATERIALIZE (gemini, pi): the absent-config default is itself unsafe for a
|
||||
* non-granted owner (gemini's builder defaults to `yolo`; pi's default is an
|
||||
* interactive trust prompt the session user could just answer "yes" to), so
|
||||
* the clamp has to CREATE a config.
|
||||
*/
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
import { _clampExternalCliBypassForOwner } from '../../src/web/routes/session-routes.js';
|
||||
import { createUser, invalidateUsersCache } from '../../src/user-store.js';
|
||||
|
||||
const PASSWORD = 'clamp-test-password';
|
||||
|
||||
describe('clampExternalCliBypassForOwner — single-user mode', () => {
|
||||
it('passes every config through untouched (the gate is a no-op)', async () => {
|
||||
const out = await _clampExternalCliBypassForOwner(
|
||||
undefined,
|
||||
{ dangerouslyBypassApprovals: true },
|
||||
{ approvalMode: 'yolo' },
|
||||
{ dangerouslySkipPermissions: true },
|
||||
{ approveProjectTrust: true }
|
||||
);
|
||||
expect(out.codexConfig).toEqual({ dangerouslyBypassApprovals: true });
|
||||
expect(out.geminiConfig).toEqual({ approvalMode: 'yolo' });
|
||||
expect(out.antigravityConfig).toEqual({ dangerouslySkipPermissions: true });
|
||||
expect(out.piConfig).toEqual({ approveProjectTrust: true });
|
||||
});
|
||||
|
||||
it('leaves absent configs absent', async () => {
|
||||
const out = await _clampExternalCliBypassForOwner(undefined, undefined, undefined, undefined, undefined);
|
||||
expect(out.codexConfig).toBeUndefined();
|
||||
expect(out.geminiConfig).toBeUndefined();
|
||||
expect(out.antigravityConfig).toBeUndefined();
|
||||
expect(out.piConfig).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('clampExternalCliBypassForOwner — multi-user mode', () => {
|
||||
// The temp HOME from test/setup.ts is per-FILE, so users.json survives between
|
||||
// tests here — create the three accounts once.
|
||||
beforeAll(async () => {
|
||||
process.env.CODEMAN_MULTIUSER = '1';
|
||||
invalidateUsersCache();
|
||||
await createUser({ username: 'boss', role: 'admin', password: PASSWORD });
|
||||
await createUser({ username: 'peon', role: 'user', password: PASSWORD });
|
||||
await createUser({ username: 'trusted', role: 'user', password: PASSWORD, canBypassPermissions: true });
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
delete process.env.CODEMAN_MULTIUSER;
|
||||
invalidateUsersCache();
|
||||
});
|
||||
|
||||
it('passes through for an admin owner', async () => {
|
||||
const out = await _clampExternalCliBypassForOwner(
|
||||
'boss',
|
||||
{ dangerouslyBypassApprovals: true },
|
||||
undefined,
|
||||
{ dangerouslySkipPermissions: true },
|
||||
{ approveProjectTrust: true }
|
||||
);
|
||||
expect(out.codexConfig).toEqual({ dangerouslyBypassApprovals: true });
|
||||
expect(out.geminiConfig).toBeUndefined();
|
||||
expect(out.antigravityConfig).toEqual({ dangerouslySkipPermissions: true });
|
||||
expect(out.piConfig).toEqual({ approveProjectTrust: true });
|
||||
});
|
||||
|
||||
it('passes through for a user holding the bypass grant', async () => {
|
||||
const out = await _clampExternalCliBypassForOwner('trusted', undefined, undefined, undefined, {
|
||||
approveProjectTrust: true,
|
||||
});
|
||||
expect(out.piConfig).toEqual({ approveProjectTrust: true });
|
||||
});
|
||||
|
||||
it('forces codex/antigravity bypass off for a non-granted owner (only-if-sent branch)', async () => {
|
||||
const out = await _clampExternalCliBypassForOwner(
|
||||
'peon',
|
||||
{ dangerouslyBypassApprovals: true, model: 'gpt-5' },
|
||||
undefined,
|
||||
{ dangerouslySkipPermissions: true, model: 'gemini-3-pro' },
|
||||
undefined
|
||||
);
|
||||
expect(out.codexConfig).toEqual({ dangerouslyBypassApprovals: false, model: 'gpt-5' });
|
||||
expect(out.antigravityConfig).toEqual({ dangerouslySkipPermissions: false, model: 'gemini-3-pro' });
|
||||
});
|
||||
|
||||
it('leaves codex/antigravity absent when nothing was sent (they already spawn safe)', async () => {
|
||||
const out = await _clampExternalCliBypassForOwner('peon', undefined, undefined, undefined, undefined);
|
||||
expect(out.codexConfig).toBeUndefined();
|
||||
expect(out.antigravityConfig).toBeUndefined();
|
||||
});
|
||||
|
||||
it('MATERIALIZES gemini to auto_edit even when no config was sent', async () => {
|
||||
const out = await _clampExternalCliBypassForOwner('peon', undefined, undefined, undefined, undefined);
|
||||
expect(out.geminiConfig).toEqual({ approvalMode: 'auto_edit' });
|
||||
});
|
||||
|
||||
it('MATERIALIZES pi to --no-approve even when no config was sent', async () => {
|
||||
// The load-bearing case: omitting --approve is NOT a clamp for pi, because
|
||||
// pi's own default is to ASK, and the session user can answer that prompt.
|
||||
const out = await _clampExternalCliBypassForOwner('peon', undefined, undefined, undefined, undefined);
|
||||
expect(out.piConfig).toEqual({ approveProjectTrust: false });
|
||||
});
|
||||
|
||||
it('forces a sent pi approveProjectTrust:true down to false, keeping other fields', async () => {
|
||||
const out = await _clampExternalCliBypassForOwner('peon', undefined, undefined, undefined, {
|
||||
approveProjectTrust: true,
|
||||
model: 'sonnet:high',
|
||||
provider: 'anthropic',
|
||||
});
|
||||
expect(out.piConfig).toEqual({
|
||||
approveProjectTrust: false,
|
||||
model: 'sonnet:high',
|
||||
provider: 'anthropic',
|
||||
});
|
||||
});
|
||||
|
||||
it('fails closed for an unknown/deleted owner', async () => {
|
||||
const out = await _clampExternalCliBypassForOwner('ghost', undefined, undefined, undefined, {
|
||||
approveProjectTrust: true,
|
||||
});
|
||||
expect(out.piConfig).toEqual({ approveProjectTrust: false });
|
||||
expect(out.geminiConfig).toEqual({ approvalMode: 'auto_edit' });
|
||||
});
|
||||
});
|
||||
@@ -86,12 +86,6 @@ vi.mock('../../src/utils/antigravity-cli-resolver.js', () => ({
|
||||
resolveAntigravityDir: vi.fn(() => null),
|
||||
}));
|
||||
|
||||
vi.mock('../../src/utils/pi-cli-resolver.js', () => ({
|
||||
isPiAvailable: vi.fn(() => false),
|
||||
resolvePiDir: vi.fn(() => null),
|
||||
getPiCliVersion: vi.fn(() => null),
|
||||
}));
|
||||
|
||||
import fs from 'node:fs/promises';
|
||||
import { existsSync, readdirSync } from 'node:fs';
|
||||
import { subagentWatcher } from '../../src/subagent-watcher.js';
|
||||
@@ -99,7 +93,6 @@ import { getLifecycleLog } from '../../src/session-lifecycle-log.js';
|
||||
import { isOpenCodeAvailable, resolveOpenCodeDir } from '../../src/utils/opencode-cli-resolver.js';
|
||||
import { isGeminiAvailable, resolveGeminiDir } from '../../src/utils/gemini-cli-resolver.js';
|
||||
import { isAntigravityAvailable, resolveAntigravityDir } from '../../src/utils/antigravity-cli-resolver.js';
|
||||
import { isPiAvailable, resolvePiDir, getPiCliVersion } from '../../src/utils/pi-cli-resolver.js';
|
||||
|
||||
const mockedReadFile = vi.mocked(fs.readFile);
|
||||
const mockedWriteFile = vi.mocked(fs.writeFile);
|
||||
@@ -113,9 +106,6 @@ const mockedIsGeminiAvailable = vi.mocked(isGeminiAvailable);
|
||||
const mockedResolveGeminiDir = vi.mocked(resolveGeminiDir);
|
||||
const mockedIsAntigravityAvailable = vi.mocked(isAntigravityAvailable);
|
||||
const mockedResolveAntigravityDir = vi.mocked(resolveAntigravityDir);
|
||||
const mockedIsPiAvailable = vi.mocked(isPiAvailable);
|
||||
const mockedResolvePiDir = vi.mocked(resolvePiDir);
|
||||
const mockedGetPiCliVersion = vi.mocked(getPiCliVersion);
|
||||
|
||||
describe('system-routes', () => {
|
||||
let harness: RouteTestHarness;
|
||||
@@ -849,38 +839,6 @@ describe('system-routes', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ========== GET /api/pi/status ==========
|
||||
|
||||
describe('GET /api/pi/status', () => {
|
||||
it('returns unavailable when pi is not installed', async () => {
|
||||
mockedIsPiAvailable.mockReturnValue(false);
|
||||
mockedResolvePiDir.mockReturnValue(null);
|
||||
mockedGetPiCliVersion.mockReturnValue(null);
|
||||
|
||||
const res = await harness.app.inject({ method: 'GET', url: '/api/pi/status' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.available).toBe(false);
|
||||
expect(body.path).toBeNull();
|
||||
expect(body.version).toBeNull();
|
||||
});
|
||||
|
||||
it('returns available with path AND version when pi is installed', async () => {
|
||||
// `version` is pi-specific: `pi` is a generic binary name, so the resolver
|
||||
// version-probes it and this endpoint is where a misresolution shows up.
|
||||
mockedIsPiAvailable.mockReturnValue(true);
|
||||
mockedResolvePiDir.mockReturnValue('/home/user/.local/bin');
|
||||
mockedGetPiCliVersion.mockReturnValue('0.84.1');
|
||||
|
||||
const res = await harness.app.inject({ method: 'GET', url: '/api/pi/status' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.available).toBe(true);
|
||||
expect(body.path).toBe('/home/user/.local/bin');
|
||||
expect(body.version).toBe('0.84.1');
|
||||
});
|
||||
});
|
||||
|
||||
// ========== GET /api/execution/model-config ==========
|
||||
|
||||
describe('GET /api/execution/model-config', () => {
|
||||
|
||||
+2
-106
@@ -168,15 +168,7 @@ describe('Run launch synchronization', () => {
|
||||
// Fail loudly if the scan matched nothing: a silently empty scan would make
|
||||
// every assertion below vacuously true.
|
||||
expect([...bodies.keys()]).toEqual(
|
||||
expect.arrayContaining([
|
||||
'runClaude',
|
||||
'runShell',
|
||||
'runOpenCode',
|
||||
'runCodex',
|
||||
'runGemini',
|
||||
'runAntigravity',
|
||||
'runPi',
|
||||
])
|
||||
expect.arrayContaining(['runClaude', 'runShell', 'runOpenCode', 'runCodex', 'runGemini', 'runAntigravity'])
|
||||
);
|
||||
|
||||
for (const [name, body] of bodies) {
|
||||
@@ -364,13 +356,12 @@ describe('Codex quick start settings', () => {
|
||||
'welcomeOpencodeBtn',
|
||||
'welcomeAntigravityBtn',
|
||||
'welcomeGeminiBtn',
|
||||
'welcomePiBtn',
|
||||
'welcomeTunnelBtn',
|
||||
]) {
|
||||
welcomeBtns[id] = { style: { display: 'PRISTINE' } };
|
||||
}
|
||||
const modeBtns: Record<string, { style: { display: string } }> = {};
|
||||
for (const mode of ['claude', 'opencode', 'codex', 'gemini', 'antigravity', 'pi', 'shell']) {
|
||||
for (const mode of ['claude', 'opencode', 'codex', 'gemini', 'antigravity', 'shell']) {
|
||||
modeBtns[mode] = { style: { display: 'PRISTINE' } };
|
||||
}
|
||||
const menu = {
|
||||
@@ -401,7 +392,6 @@ describe('Codex quick start settings', () => {
|
||||
codex: false,
|
||||
gemini: false,
|
||||
antigravity: false,
|
||||
pi: false,
|
||||
cloudflared: false,
|
||||
};
|
||||
|
||||
@@ -420,13 +410,6 @@ describe('Codex quick start settings', () => {
|
||||
withTunnel.app.applyWelcomeCliVisibility();
|
||||
expect(withTunnel.welcomeBtns.welcomeTunnelBtn.style.display).toBe('flex');
|
||||
|
||||
// Pi is gated on `pi` like the rest; the resolver additionally version-probes
|
||||
// the binary, so a stray `pi` on PATH reports unavailable rather than broken.
|
||||
const withPi = loadUi({ ...ALL_OFF, pi: true });
|
||||
withPi.app.applyWelcomeCliVisibility();
|
||||
expect(withPi.welcomeBtns.welcomePiBtn.style.display).toBe('flex');
|
||||
expect(withPi.welcomeBtns.welcomeClaudeBtn.style.display).toBe('none');
|
||||
|
||||
// Antigravity is a first-class welcome action, gated on `agy` like the rest.
|
||||
const withAgy = loadUi({ ...ALL_OFF, antigravity: true });
|
||||
withAgy.app.applyWelcomeCliVisibility();
|
||||
@@ -456,7 +439,6 @@ describe('Codex quick start settings', () => {
|
||||
(m) => m[1]
|
||||
);
|
||||
expect(offered).toContain('antigravity');
|
||||
expect(offered).toContain('pi');
|
||||
const src = readFileSync(resolve(import.meta.dirname, '../src/web/public/session-ui.js'), 'utf8');
|
||||
// Anchor on the DEFINITION, not the earlier call site in toggleRunModeMenu.
|
||||
const fn = src.slice(src.indexOf('_refreshRunModeAvailability(menu) {'));
|
||||
@@ -907,89 +889,3 @@ describe('Antigravity quick start', () => {
|
||||
expect(selected).toEqual(['sess-ag']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Pi quick start', () => {
|
||||
// Same envelope-unwrap regression guard as the blocks above, for runPi(), plus the
|
||||
// rule that makes pi different: it must send NO piConfig. Pi has no permission
|
||||
// prompts, and `approveProjectTrust` would opt the session into EXECUTING
|
||||
// repo-supplied TypeScript — never something a Run button decides silently.
|
||||
it('drives runPi() through the {success,data} envelope and sends no piConfig', async () => {
|
||||
const elements: Record<string, any> = {
|
||||
quickStartCase: { value: 'pi-case' },
|
||||
};
|
||||
const requests: Array<{ url: string; body?: any }> = [];
|
||||
const CodemanApp = function CodemanApp(this: any) {};
|
||||
|
||||
const context = vm.createContext({
|
||||
CodemanApp,
|
||||
localStorage: { getItem: () => null, setItem: () => {} },
|
||||
document: { getElementById: (id: string) => elements[id] ?? null },
|
||||
fetch: async (url: string, init?: { body?: string }) => {
|
||||
requests.push({ url, body: init?.body ? JSON.parse(init.body) : undefined });
|
||||
if (url === '/api/pi/status')
|
||||
return {
|
||||
json: async () => ({ success: true, data: { available: true, path: '/usr/local/bin', version: '0.84.1' } }),
|
||||
};
|
||||
if (url === '/api/quick-start')
|
||||
return { json: async () => ({ success: true, data: { sessionId: 'sess-pi' } }) };
|
||||
if (url === '/api/sessions/sess-pi')
|
||||
return { json: async () => ({ success: true, data: { id: 'sess-pi', name: 'w1-pi-case' } }) };
|
||||
throw new Error(`unexpected fetch: ${url}`);
|
||||
},
|
||||
console,
|
||||
});
|
||||
|
||||
const sessionUi = readFileSync(resolve(import.meta.dirname, '../src/web/public/session-ui.js'), 'utf8');
|
||||
vm.runInContext(sessionUi, context, { filename: 'session-ui.js' });
|
||||
|
||||
const app = new (CodemanApp as any)();
|
||||
app.terminal = { clear: () => {}, writeln: () => {}, focus: () => {} };
|
||||
app.loadAppSettingsFromStorage = () => ({});
|
||||
app.getCaseSettings = () => ({});
|
||||
app.buildEnvOverrides = () => ({});
|
||||
app.sessions = new Map();
|
||||
app._onSessionCreated = (session: any) => app.sessions.set(session.id, session);
|
||||
app._renderSessionTabsImmediate = vi.fn();
|
||||
const selected: string[] = [];
|
||||
app.selectSession = async (id: string) => {
|
||||
selected.push(id);
|
||||
};
|
||||
|
||||
await app.runPi();
|
||||
|
||||
const body = requests.find((req) => req.url === '/api/quick-start')?.body;
|
||||
expect(body).toMatchObject({ caseName: 'pi-case', mode: 'pi' });
|
||||
expect(body).not.toHaveProperty('piConfig');
|
||||
expect(selected).toEqual(['sess-pi']);
|
||||
});
|
||||
|
||||
it('reports the install hint when the CLI is missing and starts nothing', async () => {
|
||||
const elements: Record<string, any> = { quickStartCase: { value: 'pi-case' } };
|
||||
const requests: string[] = [];
|
||||
const CodemanApp = function CodemanApp(this: any) {};
|
||||
const context = vm.createContext({
|
||||
CodemanApp,
|
||||
localStorage: { getItem: () => null, setItem: () => {} },
|
||||
document: { getElementById: (id: string) => elements[id] ?? null },
|
||||
fetch: async (url: string) => {
|
||||
requests.push(url);
|
||||
if (url === '/api/pi/status')
|
||||
return { json: async () => ({ success: true, data: { available: false, path: null, version: null } }) };
|
||||
throw new Error(`unexpected fetch: ${url}`);
|
||||
},
|
||||
console,
|
||||
});
|
||||
const sessionUi = readFileSync(resolve(import.meta.dirname, '../src/web/public/session-ui.js'), 'utf8');
|
||||
vm.runInContext(sessionUi, context, { filename: 'session-ui.js' });
|
||||
|
||||
const app = new (CodemanApp as any)();
|
||||
app.terminal = { clear: () => {}, writeln: () => {}, focus: () => {} };
|
||||
const errors: string[] = [];
|
||||
app._reportSessionLaunchError = (_owns: boolean, msg: string) => errors.push(msg);
|
||||
|
||||
await app.runPi();
|
||||
|
||||
expect(requests).toEqual(['/api/pi/status']);
|
||||
expect(errors[0]).toContain('@earendil-works/pi-coding-agent');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
/**
|
||||
* SSE liveness heartbeat.
|
||||
*
|
||||
* `cleanupDeadClients()` runs every SSE_HEARTBEAT_INTERVAL (15s) and does two
|
||||
* jobs: evict clients whose socket died, and write a liveness frame to the
|
||||
* ones that are still up.
|
||||
*
|
||||
* The regression these guard: that frame used to be an SSE `:keepalive`
|
||||
* COMMENT, and comments are invisible to `EventSource` by spec. A stream that
|
||||
* stopped delivering without erroring was therefore undetectable to the
|
||||
* client: `onerror` never fired, the header dot stayed green, and every
|
||||
* SSE-driven surface froze until the user reloaded. A named `sse:heartbeat`
|
||||
* event reaches a listener, which is what lets the client's staleness
|
||||
* watchdog notice the silence (see test/sse-staleness.test.ts).
|
||||
*
|
||||
* No port needed (the manager is driven directly with fake replies).
|
||||
*/
|
||||
import type { FastifyReply } from 'fastify';
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { SSE_PADDING_SIZE } from '../src/config/server-timing.js';
|
||||
import { SseEvent } from '../src/web/sse-events.js';
|
||||
import { SseStreamManager } from '../src/web/sse-stream-manager.js';
|
||||
import { CleanupManager } from '../src/utils/index.js';
|
||||
|
||||
/** A FastifyReply stand-in that records every raw write. */
|
||||
function fakeClient(opts: { destroyed?: boolean; writable?: boolean; throwOnAccess?: boolean } = {}) {
|
||||
const writes: string[] = [];
|
||||
const socket = { destroyed: opts.destroyed ?? false, writable: opts.writable ?? true };
|
||||
const raw = {
|
||||
get socket() {
|
||||
if (opts.throwOnAccess) throw new Error('socket gone');
|
||||
return socket;
|
||||
},
|
||||
write(chunk: string) {
|
||||
writes.push(chunk);
|
||||
return true;
|
||||
},
|
||||
};
|
||||
return { reply: { raw } as unknown as FastifyReply, writes };
|
||||
}
|
||||
|
||||
function makeManager() {
|
||||
const cleanup = new CleanupManager();
|
||||
const manager = new SseStreamManager({ getSessionStateWithRespawn: () => null }, cleanup);
|
||||
return { manager, cleanup };
|
||||
}
|
||||
|
||||
describe('SSE liveness heartbeat', () => {
|
||||
it('writes a NAMED sse:heartbeat event, not an invisible comment', () => {
|
||||
const { manager, cleanup } = makeManager();
|
||||
const client = fakeClient();
|
||||
manager.addClient(client.reply, null, false);
|
||||
|
||||
manager.cleanupDeadClients();
|
||||
|
||||
expect(client.writes).toHaveLength(1);
|
||||
const frame = client.writes[0];
|
||||
// A comment (`:keepalive`) never reaches an EventSource listener, and that is
|
||||
// the entire bug. The frame must be a dispatchable named event.
|
||||
expect(frame.startsWith(':')).toBe(false);
|
||||
expect(frame).toMatch(/^event: sse:heartbeat\n/);
|
||||
expect(frame.endsWith('\n\n')).toBe(true);
|
||||
expect(SseEvent.Heartbeat).toBe('sse:heartbeat');
|
||||
cleanup.dispose();
|
||||
});
|
||||
|
||||
it('carries a parseable epoch-ms payload', () => {
|
||||
const { manager, cleanup } = makeManager();
|
||||
const client = fakeClient();
|
||||
manager.addClient(client.reply, null, false);
|
||||
const before = Date.now();
|
||||
|
||||
manager.cleanupDeadClients();
|
||||
|
||||
const dataLine = client.writes[0].split('\n').find((l) => l.startsWith('data: '));
|
||||
expect(dataLine).toBeDefined();
|
||||
const payload = JSON.parse(dataLine!.slice('data: '.length)) as { t: number };
|
||||
expect(payload.t).toBeGreaterThanOrEqual(before);
|
||||
expect(payload.t).toBeLessThanOrEqual(Date.now());
|
||||
cleanup.dispose();
|
||||
});
|
||||
|
||||
it('still appends Cloudflare tunnel padding when a tunnel is active', () => {
|
||||
const { manager, cleanup } = makeManager();
|
||||
const client = fakeClient();
|
||||
manager.addClient(client.reply, null, false);
|
||||
manager.setTunnelActive(true);
|
||||
|
||||
manager.cleanupDeadClients();
|
||||
|
||||
const frame = client.writes[0];
|
||||
expect(frame).toMatch(/^event: sse:heartbeat\n/);
|
||||
// Padding rides AFTER the terminating blank line, so the event still parses.
|
||||
const [event, padding] = frame.split('\n\n');
|
||||
expect(event).toMatch(/^event: sse:heartbeat\ndata: \{/);
|
||||
expect(padding.startsWith(':')).toBe(true);
|
||||
expect(padding.length).toBeGreaterThanOrEqual(SSE_PADDING_SIZE);
|
||||
cleanup.dispose();
|
||||
});
|
||||
|
||||
it('sends no padding without a tunnel', () => {
|
||||
const { manager, cleanup } = makeManager();
|
||||
const client = fakeClient();
|
||||
manager.addClient(client.reply, null, false);
|
||||
|
||||
manager.cleanupDeadClients();
|
||||
|
||||
expect(client.writes[0].length).toBeLessThan(200);
|
||||
cleanup.dispose();
|
||||
});
|
||||
|
||||
it('still evicts dead clients instead of heartbeating them', () => {
|
||||
const { manager, cleanup } = makeManager();
|
||||
const alive = fakeClient();
|
||||
const destroyed = fakeClient({ destroyed: true });
|
||||
const unwritable = fakeClient({ writable: false });
|
||||
const exploding = fakeClient({ throwOnAccess: true });
|
||||
for (const c of [alive, destroyed, unwritable, exploding]) manager.addClient(c.reply, null, false);
|
||||
expect(manager.clientCount).toBe(4);
|
||||
|
||||
manager.cleanupDeadClients();
|
||||
|
||||
expect(manager.clientCount).toBe(1);
|
||||
expect(alive.writes).toHaveLength(1);
|
||||
for (const c of [destroyed, unwritable, exploding]) expect(c.writes).toHaveLength(0);
|
||||
cleanup.dispose();
|
||||
});
|
||||
|
||||
it('heartbeats every client on each pass', () => {
|
||||
const { manager, cleanup } = makeManager();
|
||||
const a = fakeClient();
|
||||
const b = fakeClient();
|
||||
manager.addClient(a.reply, null, false);
|
||||
manager.addClient(b.reply, null, false);
|
||||
|
||||
manager.cleanupDeadClients();
|
||||
manager.cleanupDeadClients();
|
||||
|
||||
// The frame carries no session data, so it needs no owner routing and is
|
||||
// written per-client rather than through the scoped broadcast() path.
|
||||
expect(a.writes).toHaveLength(2);
|
||||
expect(b.writes).toHaveLength(2);
|
||||
cleanup.dispose();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
* SSE staleness policy.
|
||||
*
|
||||
* `CodemanSseStale.compute(input)` is the pure decision behind app.js's
|
||||
* watchdog: given when the last SSE frame arrived, the transport status and
|
||||
* the browser's online flag, it says whether the stream has gone quiet while
|
||||
* still claiming to be connected: a zombie that has to be rebuilt.
|
||||
*
|
||||
* The regression it guards: the server's liveness keepalive used to be an SSE
|
||||
* `:keepalive` COMMENT, and comments are invisible to `EventSource` by spec.
|
||||
* A stream that stopped delivering without erroring (a proxy that idle-closed
|
||||
* it, a laptop resumed from sleep, a tailnet reconnect) never fired `onerror`,
|
||||
* so the header dot stayed green and tab status dots, sessions created on
|
||||
* another device, and renames all froze until the user reloaded the page.
|
||||
*
|
||||
* Loaded in a plain node VM context (no jsdom), mirroring
|
||||
* test/connection-loss-ui.test.ts.
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
type StaleInput = {
|
||||
lastMessageAt?: number | null;
|
||||
now?: number;
|
||||
status?: 'connected' | 'connecting' | 'reconnecting' | 'disconnected' | 'offline';
|
||||
isOnline?: boolean;
|
||||
timeoutMs?: number;
|
||||
};
|
||||
|
||||
function loadPolicy() {
|
||||
const context = vm.createContext({ window: {}, globalThis: {} });
|
||||
const source = readFileSync(resolve(import.meta.dirname, '../src/web/public/constants.js'), 'utf8');
|
||||
vm.runInContext(source, context, { filename: 'constants.js' });
|
||||
return (
|
||||
context.window as {
|
||||
CodemanSseStale: { compute: (input: StaleInput) => boolean; TIMEOUT_MS: number };
|
||||
}
|
||||
).CodemanSseStale;
|
||||
}
|
||||
|
||||
const T0 = 1_000_000;
|
||||
|
||||
describe('SSE staleness policy', () => {
|
||||
it('defaults to three missed 15s heartbeats', () => {
|
||||
const { TIMEOUT_MS } = loadPolicy();
|
||||
expect(TIMEOUT_MS).toBe(45000);
|
||||
});
|
||||
|
||||
it('is not stale while frames keep arriving', () => {
|
||||
const { compute, TIMEOUT_MS } = loadPolicy();
|
||||
expect(compute({ lastMessageAt: T0, now: T0 + TIMEOUT_MS - 1, status: 'connected' })).toBe(false);
|
||||
});
|
||||
|
||||
it('is stale once the threshold is reached', () => {
|
||||
const { compute, TIMEOUT_MS } = loadPolicy();
|
||||
// Boundary is inclusive: exactly three missed heartbeats already means the
|
||||
// stream has been silent through a window it was contractually filling.
|
||||
expect(compute({ lastMessageAt: T0, now: T0 + TIMEOUT_MS, status: 'connected' })).toBe(true);
|
||||
expect(compute({ lastMessageAt: T0, now: T0 + TIMEOUT_MS * 10, status: 'connected' })).toBe(true);
|
||||
});
|
||||
|
||||
it('honours a custom timeoutMs (what a browser test shrinks)', () => {
|
||||
const { compute } = loadPolicy();
|
||||
expect(compute({ lastMessageAt: T0, now: T0 + 999, status: 'connected', timeoutMs: 1000 })).toBe(false);
|
||||
expect(compute({ lastMessageAt: T0, now: T0 + 1000, status: 'connected', timeoutMs: 1000 })).toBe(true);
|
||||
});
|
||||
|
||||
it('is never stale while the transport is already reconnecting', () => {
|
||||
const { compute, TIMEOUT_MS } = loadPolicy();
|
||||
// These states already have the backoff machinery running; firing on top
|
||||
// of them would stack reconnects. This guard is also the loop breaker:
|
||||
// a forced reconnect leaves 'connected' immediately, so the watchdog
|
||||
// cannot re-fire while one is in flight.
|
||||
for (const status of ['connecting', 'reconnecting', 'disconnected', 'offline'] as const) {
|
||||
expect(compute({ lastMessageAt: T0, now: T0 + TIMEOUT_MS * 10, status })).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it('is never stale while the device is offline', () => {
|
||||
const { compute, TIMEOUT_MS } = loadPolicy();
|
||||
// Nothing to reconnect to yet; the connection-loss UI already owns this.
|
||||
expect(compute({ lastMessageAt: T0, now: T0 + TIMEOUT_MS * 10, status: 'connected', isOnline: false })).toBe(false);
|
||||
});
|
||||
|
||||
it('is not stale before any frame has ever arrived', () => {
|
||||
const { compute, TIMEOUT_MS } = loadPolicy();
|
||||
// The clock starts at onopen, and `init` lands immediately after. A zero
|
||||
// stamp means the stream has not opened yet, not that it went quiet. The
|
||||
// constructor optimistically seeds status 'connected' before the first
|
||||
// connect, so without this guard the watchdog would fire on page load.
|
||||
for (const lastMessageAt of [0, null, undefined]) {
|
||||
expect(compute({ lastMessageAt, now: T0 + TIMEOUT_MS * 10, status: 'connected' })).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it('tolerates a missing input object', () => {
|
||||
const { compute } = loadPolicy();
|
||||
expect(compute(undefined as unknown as StaleInput)).toBe(false);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user