Files
hapi/docs/guide/installation.md
T
7f5d6b17f3 feat(peer): spawn-peer remit + rename-proof Parent UUID stamps (#1922)
* feat(cli): spawn-peer with required remit and MCP spawn_peer

Machine spawn creates an empty composer; stuffing message into that
JSON is stripped. Add hapi spawn-peer and MCP spawn_peer that spawn,
rename, deliver via the ping-peer path, and fail closed unless the
remit is on the new session. Reject message/prompt/text on machine
spawn with 400. Do not auto-approve spawn_peer in default/read-only.

Fixes #1509

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): reject overlong spawn-peer names before spawn

Hub rename max is 255; continuing past PATCH 400 left a live session under a different title. MCP/steer copy now says the hub 400s a spawn-body remit instead of stripping it.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): wait for fresh spawn-peer child instead of resuming it

Machine spawn can return while the hub row is still inactive. ping-peer then POSTed /resume, which can launch a second agent because the original spawn has no existingSessionId for runner dedupe.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): reject flavor-illegal permissionMode before spawn-peer

Codex + bypassPermissions (and Pi + any mode) used to reach the runner and fail after a child existed, or silently drop the mode. Check isPermissionModeAllowedForFlavor when both agent and mode are explicit.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): treat omitted spawn-peer agent as Claude for permissionMode

Hub and runner default agent to claude when spawn omits it. Validate permissionMode against that effective flavor so yolo/read-only fail closed before a child starts.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): resolve spawn-peer dir locally and archive failed children

Relative --dir values were forwarded unchanged, so the runner resolved them against daemon cwd. Remit delivery failures also left the new session running, so a retry spawned a duplicate. Resolve in the caller and best-effort archive the child before rethrowing.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): verify remit before archiving a failed spawn-peer child

A timed-out ping-peer POST can still land the remit. Check the transcript before archive, and only say the child was archived when the hub returns ok.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): swallow spawn-peer transcript GET errors and skip unapplied names

A thrown messages GET after spawn skipped archive and leaked a live child. Treat transport errors as a miss so the verify loop can retry, then clean up. Also do not return a requested name the hub never applied.

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(spawn-peer): hub peerSpawnDefaults + model/effort spawn surface

Add hub settings peerSpawnDefaults (agent, permissionMode, per-flavor models)
with stock claude/yolo/sonnet fallbacks. spawnPeer resolves explicit args →
hub settings → stock, maps yolo to flavor equivalents, and forwards model/effort
into machine spawn. Settings UI under General → Agents; MCP/CLI optional overrides.

Co-authored-by: Cursor <cursoragent@cursor.com>

* test(hub): use cursor-valid permission mode in peer spawn defaults test

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): teach spawn_peer that omit permissionMode means yolo

MCP copy said "pass permissionMode only when the operator asked", so agents
omitted it and got hub/stock whatever was stored — often approval-gated
default. Clarify omit = yolo via peerSpawnDefaults/stock; pass only to tighten.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(hub,web): apply peerSpawnDefaults to machine spawn and New Session

POST /api/machines/:id/spawn now resolves omitted agent/permissionMode/model
from hub Settings, and New Session seeds from the same peerSpawnDefaults so
UI create and peer spawn share one authoritative default (stock yolo).

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): NewSession hub seed respects sticky prefs + QueryClient in tests

Sticky localStorage last-used agent wins over hub seed; machine spawn still
applies peerSpawnDefaults server-side. Tests provide QueryClientProvider.

Co-authored-by: Cursor <cursoragent@cursor.com>

* test(web): mock CREATABLE_AGENT_FLAVORS for settings general peerSpawn UI

Co-authored-by: Cursor <cursoragent@cursor.com>

* test(web): stabilize NewSession tests after hub peerSpawnDefaults seed

Wrap remaining mounts in QueryClientProvider, pre-seed hub settings so a
late useQuery resolve cannot wipe in-test model picks, and use neutral
stock permission defaults in the fixture.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(spawn-peer): address tip Codex Majors for peerSpawnDefaults

Preserve explicit yolo booleans on machine spawn, fail closed when hub
defaults cannot load, validate permission modes against the resolved
agent, remap auto-approval across flavors, and stop late hub settings
from wiping New Session edits. Reject retired agents in spawn defaults
and restore the CLI executable build docs.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(spawn-peer): address follow-up tip Codex Majors

Stop absent Yolo localStorage from beating hub defaults, track New Session
edits before late hub seed, reject incompatible machine-spawn permissions,
resolve MCP spawn_peer paths against the session working directory, and
hide unsupported Codex safe-yolo from Settings spawn defaults.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(spawn-peer): clear tip-2 CI and follow-up Codex Majors

Omit permissionMode for Pi/DSH, preserve explicit Yolo-off across delayed
hub seed, fix settings test mocks for launch permission helpers, and
restore unrelated CLI README lifecycle/ACP docs.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(spawn-peer): tip-3 Majors for seed edits and launchable modes

Skip hub agent seed after permission edits, resolve inherited modes via
the launch catalog (AGY request-review fallback), preserve hub Cursor
models through preference restore, and restore Codex auth README nuance.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): tip Minors for Cursor/Grok hub permission seeding

Give Cursor the native permission select so Plan/Ask survive machine
spawn, and re-apply Grok hub permissions after agent-init resets.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(spawn-peer): tip Minors for Cursor select and hub seed remap

Map hub permission through resolvePermissionModeForFlavor, keep native
Default when agent is explicit without a model, and assert Cursor Plan/Ask Mode labels.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): tip Minors for delayed hub seed and Default model

Apply hub permission/model to unset fields even with a sticky agent,
preserve explicitly saved auto models, and seed OpenCode/AGY selectors
from hub defaults.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(spawn-peer): tip Minors for model edit sticky and clear override

Mark OpenCode/AGY model picks as edited so delayed hub seed cannot
overwrite them, and treat empty hub model values as clear sentinels.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(spawn-peer): tip Majors for models patch typing and remit page scan

Type the models patch as NonNullable and paginate transcript verification
oldest-ward so a busy child is not archived when the remit leaves page 1.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): tip Minor — keep agent after explicit model pick

Do not apply a late hub default agent when the operator already chose a
model; otherwise preference restore drops that selection.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(spawn-peer): tip Cursor YOLO migrate and Codex effort map

Bridge Cursor's saved YOLO toggle (incl. false) into native Default over
hub yolo, and send Codex/OpenCode --effort as modelReasoningEffort.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): tip Majors — scoped YOLO bridge and catalog fallback

Keep unsupported saved permission modes at Default instead of hub yolo,
and apply delayed YOLO migration only when the sticky bridge agent matches.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): drop rebase conflict markers in startHappyServer

Both sessionDisplayRename and spawnPeer imports are required after
rebasing onto upstream rename work; markers had slipped into tip.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): wrap Kimi NewSession tests in QueryClientProvider

Hub settings useQuery requires a provider; upstream Kimi catalog tests
rendered bare and broke after the spawn-peer rebase onto main.

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(peer): rename-proof Parent UUID stamp on spawn remits

Orchestrated spawn_peer / spawn-peer remits now auto-stamp a durable
[title](/sessions/<uuid>) Parent chip (fail-closed in-session). MCP copy
forbids inventing titles; UUID stays identity after parent rename.

Refs heavygee/hapi#175

Co-authored-by: Cursor <cursoragent@cursor.com>

* style(peer): plain hyphen in Parent-stamp warning and test comment

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(peer): reject blank remit before Parent stamp

Codex review on #1922: stamping first turned empty remits non-empty and
bypassed the idle-session guard. Also only treat ## Parent blocks as
already-present so bare /sessions citations still get the chip.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(peer): gate New Session Create on hub defaults; require Parent chip

Codex tip review on #1922: block Create while getHubSettings is pending so
stock mount defaults cannot bypass restrictive hub peerSpawnDefaults; skip
Parent stamp only when ## Parent already has a markdown session chip; clarify
codex resume takes a native thread id.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(peer): resolve MCP spawn cwd; Agents settings section

Codex Major on #1922: spawn_peer relative directories now prefer the
launcher cwd (Codex --cd), then skillLookup, then session metadata.path.
Move peerSpawnDefaults UI into the unused Agents settings section.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(peer): pass session cwd to MCP spawn_peer; Agents settings section

Codex tip review on #1922: resolve relative spawn_peer directories from the
launcher working directory (Codex --cd), skillLookup, then metadata.path;
move peerSpawnDefaults UI into the Agents settings section.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(peer): skip archive on unread transcript; validate startingMode after hub agent

Codex tip review: do not archive a child when remit verification cannot read
the transcript; run AGY/DSH remote-only startingMode checks against the
resolved hub agent; update MCP bridge test expectations for workingDirectory.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(peer): treat exhausted remit pagination as unverifiable

Hitting the messages page cap with hasMore still true must not count as an
observed-empty transcript — that would archive a child whose remit may still
exist on older pages.

Co-authored-by: Cursor <cursoragent@cursor.com>

* docs(cli): list HAPI_API_URL as optional with localhost default

Codex tip review: the README had moved HAPI_API_URL under Required even
though configuration defaults it to http://localhost:3006 (and settings can
supply a URL). Also drop trailing whitespace flagged by git diff --check.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(peer): re-verify empty transcript before archiving failed spawn

An earlier observed-absent page plus later unread GETs must not archive a
child whose remit may have landed after the first empty read.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(peer): never auto-archive on spawnPeer failure path

Timed-out remit POSTs and empty-read/archive TOCTOU races can still land
work on the child. Leave the session running with its id for inspection
instead of terminating an in-flight peer.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(peer): classify empty_session from final remit verify

An earlier empty transcript read must not stick as empty_session once
later message GETs become unavailable — report verify_failed instead.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(peer): recognize escaped brackets in Parent chip labels

Titles with ] were escaped in the chip label but the idempotency regex
stopped at the first raw bracket and re-stamped a second Parent block.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(peer): avoid Parent chip regex backtracking on backslashes

Exclude \\ from the single-char label alternative so escaped pairs have
one parse path — long nonmatching backslash runs no longer explode.

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(cli): MCP/CLI spawn_peer --machine for cross-host remits

Wire optional machine (UUID or hostname via GET /api/machines) through
MCP spawn_peer and hapi spawn-peer into existing spawnPeer({ machineId }).
Skip local directory existence checks for cross-host targets to match the
estate wrapper; keep fail-closed remit verify.

Fixes tiann/hapi#1931

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(peer): reject ambiguous spawn --machine label matches

Tip bot Major on #1922: hostname/displayName selectors that match more
than one online runner now fail closed with ambiguous + UUID guidance.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(peer): preserve cross-OS absolute dirs for spawn --machine

path.resolve on the caller OS was rewriting foreign absolute roots
(C:\… on Linux, /srv/… on Windows) before the hub spawn POST. Detect
POSIX or Windows absolute paths and only resolve relative directories.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(peer): resolve spawn dirs after local vs remote is known

Defer directory resolution until the target machine is selected. Remote
spawns still preserve foreign absolute roots; local spawns use native
path.resolve so Windows drive-less paths like \repo bind to the caller
drive.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): apply delayed DSH model defaults without replacing edits

* fix(web): preserve hub permission defaults across form remounts

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: weishu <twsxtd@gmail.com>
2026-11-02 13:17:22 +08:00

17 KiB
Raw Blame History

Installation

Install the HAPI CLI and set up the hub. To install the paid phone apps and pair them, see Native apps (iOS / Android); for the free browser client, see PWA.

Prerequisites

  • At least one supported agent CLI installed (Claude Code, Codex, Cursor Agent, Grok Build, OpenCode, DeepSeek Harness ACP server, and more — see Supported Agents)

Verify your CLI is installed:

# For Claude Code
claude --version

# For OpenAI Codex CLI
codex --version

# For Cursor Agent CLI
agent --version

# For Grok Build CLI
grok --version

# For OpenCode CLI
opencode --version

Architecture

HAPI uses these runtime roles:

Component Role Required
CLI Wraps AI coding agents, runs sessions Yes
Hub Central coordinator: persistence, real-time sync, remote access Yes
Runner Background service for remote session spawning Optional
Client Native iOS/Android, Web/PWA or Telegram Mini App One client for remote control

How they work together

The CLI and Runner connect to the hub over Socket.IO; clients send actions through REST and receive live updates through SSE. The Runner spawns CLI sessions when requested through the hub. See the architecture overview.

  • CLI: Choose an agent with hapi, or start one directly with hapi <agent>. The CLI wraps your AI agent and syncs with the hub. Scripts must specify the agent explicitly.
  • Hub: Run hapi hub. Stores sessions, handles permissions, enables remote access.
  • Runner: Run hapi runner start. Lets you spawn sessions from native or web clients without keeping a terminal open.
  • Client: Pair a native app with the HTTPS hub origin and access token, or log in through the web app.

Typical workflows

Local only: hapi hub → hapi → work in terminal

Remote access: hapi hub --relay → hapi runner start → pair a native app or open the web app

Install the CLI

npm install -g @twsxtd/hapi --registry=https://registry.npmjs.org

Recommendation: use the official npm registry for global install. Some mirrors may not sync platform packages in time.

Or with Homebrew:

brew install tiann/tap/hapi

Upgrades that still run an older version

The @twsxtd/hapi package is a launcher. Its platform binary (for example, @twsxtd/hapi-darwin-arm64) is an optional dependency pinned to the same version. If a mirror has the new launcher but not the matching platform package, the package manager can finish upgrading the launcher while skipping the binary. A previous binary may remain installed. Older launchers can silently run it; launchers with version validation instead report a version mismatch.

Retry against the official registry using your existing package manager. For Bun:

bun remove -g @twsxtd/hapi && bun add -g @twsxtd/hapi@latest --registry=https://registry.npmjs.org
hapi --version

Removing the launcher first clears its dependency resolution; --force alone can leave a previously skipped platform package out of Bun's lockfile. This does not remove your HAPI settings or sessions. To stay on a specific release, replace latest with that version. For npm, use npm install -g @twsxtd/hapi@latest --registry=https://registry.npmjs.org. If the command still reports an old version, check for another HAPI installation earlier on PATH. Restart an already-running hub or runner after upgrading; installing a new binary does not replace running processes.

Other install options

npx (no install)
npx @twsxtd/hapi
Prebuilt binary

Download the latest release from GitHub Releases.

xattr -d com.apple.quarantine ./hapi
chmod +x ./hapi
sudo mv ./hapi /usr/local/bin/
Build from source

Requires Bun 1.4.4.

git clone https://github.com/tiann/hapi.git
cd hapi
bun install
bun build:single-exe

./cli/dist-exe/<target>/hapi

<target> is the Bun build target (e.g., bun-linux-x64, bun-darwin-arm64); it defaults to the host platform and architecture.

Hub setup

The hub can be deployed on:

  • Local desktop (default) - Run on your development machine
  • Remote host - Deploy the hub on a VPS, cloud host, or any machine with network access
hapi hub --relay

The terminal displays a URL and QR code. Scan to access from anywhere.

hapi server remains supported as an alias.

  • End-to-end encrypted with WireGuard + TLS
  • No configuration needed
  • Works behind NAT, firewalls, and any network

For relay key management, TCP fallback, and self-hosted tunnel alternatives, see Deployment.

Local Only

hapi hub
# or
hapi hub --no-relay

The hub listens on http://localhost:3006 by default.

On first run, HAPI:

  1. Creates ~/.hapi/
  2. Generates a secure access token
  3. Prints the token and saves it to ~/.hapi/settings.json
Config files
~/.hapi/
├── settings.json      # Main configuration
├── hapi.db           # SQLite database (hub)
├── runner.state.json  # Runner process state
└── logs/             # Log files
Environment variables
Variable Default settings.json Description
CLI_API_TOKEN Auto-generated cliApiToken Shared secret for authentication
HAPI_API_URL http://localhost:3006 apiUrl Hub URL for CLI connections
HAPI_EXTRA_HEADERS_JSON - extraHeaders JSON object of extra outbound headers for CLI → hub HTTP/WebSocket requests
HAPI_LISTEN_HOST 127.0.0.1 listenHost Hub HTTP bind address
HAPI_LISTEN_PORT 3006 listenPort Hub HTTP port
HAPI_PUBLIC_URL - publicUrl Public URL for external access
CORS_ORIGINS - corsOrigins Allowed CORS origins (comma-separated)
TELEGRAM_BOT_TOKEN - telegramBotToken Telegram Bot API token
TELEGRAM_NOTIFICATION true telegramNotification Enable Telegram notifications
SERVERCHAN_SENDKEY - serverChanSendKey Server酱 (ServerChan) SendKey for push notifications
SERVERCHAN_NOTIFICATION true serverChanNotification Enable ServerChan notifications
SERVERCHAN_BACKGROUND_ONLY false serverChanBackgroundOnly Only send ServerChan notifications when no visible HAPI connection exists in the namespace
HAPI_RELAY_API relay.hapi.run - Relay API domain for the public relay
HAPI_RELAY_AUTH Per-hub key issued by the relay relayAuthKey Relay auth key override (set only when an operator provides a key)
HAPI_RELAY_FORCE_TCP false - Force TCP mode for relay
HAPI_OFFICIAL_WEB_URL https://app.hapi.run - Official web app origin, added to CORS when the relay is enabled
VAPID_SUBJECT mailto:admin@hapi.run - Web Push contact info
HAPI_ANDROID_PUSH auto androidPushMode Android push: official relay by default, direct FCM when private credentials are configured; also accepts relay, fcm, off
HAPI_IOS_PUSH relay iosPushMode iOS push: relay, direct apns, or off
HAPI_PUSH_RELAY_URL https://push.hapi.run iosPushRelayUrl Shared Android/iOS push relay, independent of the network tunnel
FCM_SERVICE_ACCOUNT_PATH - fcmServiceAccountPath Direct FCM credentials for private builds using the same Firebase project
HAPI_HOME ~/.hapi - Config directory path
DB_PATH ~/.hapi/hapi.db - Database file path
HAPI_EXPERIMENTAL - - CLI: enable experimental features (true/1/yes)
ELEVENLABS_API_KEY - Settings / env ElevenLabs API key for voice + dictation
ELEVENLABS_AGENT_ID Auto-created - Custom ElevenLabs agent ID
ELEVENLABS_MAX_DURATION_SECONDS 1800 - Max length of one ElevenLabs voice conversation (60-7200)
GEMINI_API_KEY / GOOGLE_API_KEY - Settings / env Gemini Live voice assistant
DASHSCOPE_API_KEY / QWEN_API_KEY - Settings / env Qwen Realtime voice assistant
VOICE_BACKEND Auto-detected - Default assistant backend: elevenlabs, gemini-live, or qwen-realtime
OPENAI_API_KEY - Settings / env OpenAI API key for dictation (gpt-transcribe / gpt-live-transcribe)
DEEPGRAM_API_KEY - Settings / env Deepgram API key for dictation (nova-3)
GROQ_API_KEY - Settings / env Groq API key for dictation (whisper-large-v3)
TRANSCRIPTION_BASE_URL - Settings / env OpenAI-compatible/local transcription base URL
TRANSCRIPTION_MODEL - Settings / env Model for the OpenAI-compatible transcription endpoint
TRANSCRIPTION_API_KEY - Settings / env Optional bearer token for that endpoint
HAPI_TITLE_PROVIDER_BASE_URL - - Server-only OpenAI-compatible Chat Completions base URL for generated session titles
HAPI_TITLE_PROVIDER_API_KEY - - Server-only API key for generated session titles; never sent to the browser
HAPI_TITLE_PROVIDER_MODEL - - Server-only lightweight model used for generated session titles
HAPI_TITLE_SUGGESTION_RATE_LIMIT 5 - Maximum title suggestions per session in the rate-limit window
HAPI_TITLE_SUGGESTION_RATE_WINDOW_MS 600000 - Title suggestion rate-limit window in milliseconds
HAPI_TITLE_PROVIDER_MAX_TOKENS 64 - Maximum completion-token budget per generated title; raise for reasoning-model providers
HAPI_TITLE_PROVIDER_TIMEOUT_MS 10000 - Title provider request timeout in milliseconds

The session rename dialog's Generate action is unavailable until all three HAPI_TITLE_PROVIDER_* variables are configured on the Hub. The provider is used by the automatic fallback below and the manual Generate action. The existing manual rename flow does not require these variables. Each request sends recent visible user/assistant conversation text (up to 200 stored messages and a bounded prompt) to that configured provider.

When a provider is configured, the Hub also makes one best-effort automatic request after the first completed turn if the session has no manual name or existing summary. Automatic failures are ignored and do not affect the primary conversation. The manual Generate action remains available for retrying after an automatic failure. An attempt is remembered across Hub restarts, so later turns do not silently retry it. A manual or Agent title arriving during generation takes precedence. Without a configured provider, existing title behavior is unchanged.

settings.json example

Configuration priority: ENV > settings.json > default

When ENV values are set and not present in settings.json, they are automatically saved. HAPI_EXTRA_HEADERS_JSON is not automatically saved, so access credentials are not persisted unexpectedly.

{
  "$schema": "https://hapi.run/docs/schemas/settings.schema.json",
  "listenHost": "0.0.0.0",
  "listenPort": 3006,
  "publicUrl": "https://your-domain.com",
  "extraHeaders": {
    "Cookie": "CF_Authorization=..."
  }
}

JSON Schema: settings.schema.json

CLI setup

If the hub is not on localhost, set these before running hapi:

export HAPI_API_URL="http://your-hub:3006"
export CLI_API_TOKEN="your-token-here"
export HAPI_EXTRA_HEADERS_JSON='{"Cookie":"CF_Authorization=..."}'

Or use interactive login:

hapi auth login

Authentication commands:

hapi auth status
hapi auth login
hapi auth logout

Each machine gets a unique ID stored in ~/.hapi/settings.json. This allows:

  • Multiple machines to connect to one hub
  • Remote session spawning on specific machines
  • Machine health monitoring

Diagnostics

Run hapi doctor for a full diagnostics report: configuration, runner status, logs, and relevant environment info.

hapi doctor          # Diagnostics report
hapi doctor clean    # Kill runaway hapi processes

Runner setup

Run a background service for remote session spawning:

hapi runner start
hapi runner status
hapi runner logs
hapi runner stop

With the runner running:

  • Your machine appears in the "Machines" list
  • You can spawn sessions remotely from the web app
  • Sessions persist even when the terminal is closed

Split hub + remote runner (peer discovery)

When the hub runs on one host and the runner on another, agents inside runner-spawned sessions should discover peers via MCP list_peers (same hub credentials as the session CLI). Prefer that over shelling hapi ping-peer --list.

[Hub host]  hapi hub          ← sessions DB + /api/sessions
     ▲
     │ HAPI_API_URL + CLI_API_TOKEN
     │
[Runner host]  hapi runner start  → spawns session CLIs
                     │
                     ▼
              agent session  → MCP list_peers / inspect_peer / ping_peer / spawn_peer

On the runner host, configure the same hub URL and token the hub uses:

export HAPI_API_URL="http://your-hub:3006"   # or Tailscale / public URL
export CLI_API_TOKEN="your-token-here"
# or: hapi auth login   # saves the token; still set HAPI_API_URL for a remote hub
hapi runner start

Session CLI may export an explicit non-default HAPI_API_URL (from env or settings) into child env so shell helpers hit the same remote hub. It does not mirror CLI_API_TOKEN into wrapped agents (settings/prompt-backed secrets stay out of agent env; a fresh hapi re-reads ~/.hapi/settings.json, and systemd/env tokens already inherit). Prefer MCP list_peers inside a session. Web terminal PTYs still strip hub secrets. If --list fails with an auth/URL error, the message points at hapi auth login and the configured hub URL.

Disabling peer tools on a runner

Set HAPI_DISABLE_PEER_TOOLS=1 (also true/yes) in the runner environment to stop wrapped agents from browsing, messaging, or spawning other HAPI sessions — for example when one agent digging through the session list and pinging peers pollutes other sessions' contexts. The switch is not advertised-then-refused: the list_peers / inspect_peer / ping_peer / spawn_peer MCP tools are not registered on the session MCP server and not passed to --allowedTools / --tools, the peer steer block is dropped from agent system prompts (a pasted /sessions/<id> citation only reminds the agent it is a hub path, not a local file), and the peer core refuses with an explicit disabled error as defense in depth — so hapi ping-peer / hapi inspect-peer / hapi spawn-peer from inside a wrapped agent shell fails loudly too. Scope the env to the runner (systemd unit, launchd plist, or runner guard script); operators who leave it unset in their interactive terminal keep full hapi ping-peer CLI access.

Additional runner commands:

hapi runner list                      # List active sessions
hapi runner stop-session <sessionId>  # Stop a single session managed by the runner

Use --workspace-root <path> to restrict which directories the runner can browse and spawn sessions in. Repeat the flag to allow multiple directories; supports ~ expansion:

hapi runner start --workspace-root ~/projects --workspace-root ~/work

Without --workspace-root, directory browsing and spawning both accept paths anywhere the runner's OS account can access. The iOS directory picker starts at the home directory and can navigate above it. Configuring roots restricts both browsing and spawning to those roots, including symlink targets.

For running the hub and runner as persistent background services (pm2, launchd, systemd), see Deployment. Supervised installs should set HAPI_RUNNER_SUPERVISED=1 on the runner process (systemd Environment= / pm2 --env) so the web Restart control can safely stop-runner knowing the supervisor will cold-start it.

Multi-machine hubs

You can run one hub and runners on many machines (each machine installs its own CLI). When you upgrade the hub, upgrade the HAPI CLI on every machine that parents sessions. After the CLI binary on disk changes, that machine’s runner normally self-restarts via version handoff (unless HAPI_DISABLE_VERSION_HANDOFF=1). Until a runner reports the capabilities the hub requires, the web UI shows a Runner out of date banner (minimizable / snoozeable) with the host name and upgrade steps. The banner’s per-host Restart is only an escape hatch when handoff is stuck or disabled — the hub never downloads or installs packages on remotes.

Security notes

  • Keep tokens secret and rotate if needed
  • Use HTTPS for public access
  • Restrict CORS origins in production
Firewall example (ufw)
ufw allow from 192.168.1.0/24 to any port 3006