* feat: session-attached long-running jobs (#1404) Hub-persisted jobs that outlive the agent process: register/update/clear via REST + `hapi job`, surface primary running progress on the session list even when active=false. Opt-in registration only — not thinking progress. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(jobs): agent guidance + wall-clock elapsed on list chrome Document the session-job contract for agents and always show startedAt elapsed next to remaining/fraction/running so indeterminate drains still read as wall time without inventing an ETA. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): address Opus cold-review Majors for #1404 Add hapi job run supervisor (auto-heartbeat + exit status), follow post-merge job-owner redirects so $HAPI_SESSION_ID heartbeats keep working, cover the CLI parser/resolve/run paths with tests, and steer agents toward the supervisor instead of an idle-agent heartbeat myth. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): honor explicit startedAt on PUT; document late-attach clock Beets dogfood: PATCH rejects startedAt; sticky PUT clock made elapsed lie after late attach. Explicit upsert startedAt now corrects; CLI --started-at; clear+set recipe kept for older hubs. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): keep merge redirect keys in MetadataSchema (#1404) SessionCache.refreshSession stripped jobsAcceptedFromSessionIds / jobsTransferredToSessionId as unknown keys, so resolveAttachedJobSessionId could not follow post-merge heartbeats. Declare the fields, add a real SessionCache integration test, and pass full UUIDs through the CLI when the merge source is missing from GET /sessions. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(jobs): MCP session_job tool for catalog-level discoverability Expose session-attached jobs in the same HAPI MCP catalog as ping_peer / inspect_peer so Cursor/ACP and steered flavors see outliving-work meters as first-class tooling, not docs-only. Auto-approve own-session calls; steer prefers MCP set/update or CLI job run for supervised children. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(web): tri-state pin — default long-running jobs with #1404 Replace boolean pin-in-progress with off / jobs / all. Unset preference defaults to jobs so outliving attached-job sessions float to In progress by default; legacy true→all, false→off. Settings Display gets a 3-way control. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): cold-review pass 3 Blocker + Majors (#1404) CI: bump migration tip expects to SCHEMA 22; stub list attachedJobs mocks; align Codex/OpenCode/ACP fixtures with job steer + session_job tool list. Merge: write jobsAccepted/Transferred redirects after metadata merge so a name/summary copy cannot clobber the post-merge job owner map. MCP: session_job is own-session only (drop sessionId from schema) so auto-approve cannot silently write peer meters. Prefer hapi job run in steer. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): close pass-3 minors — stable primary, own-client heartbeats Resolve JWT/session once for job run heartbeats; order primary job by started_at ASC; cover job redirect 404 + invalid key/body; idle jobs get a Jobs bucket (not Running); treat attachedJob.startedAt as render-relevant. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): refresh JWT for long job-run heartbeats (#1404) Cache sessionId once but re-exchange JWT before hub's 4h expiry and on 401 retry so days-long supervised jobs keep heartbeating and can still mark completed/failed. Log the first heartbeat failure to stderr. Co-authored-by: Cursor <cursoragent@cursor.com> * test(jobs): cover proactive JWT refresh; map 401 to auth_failed Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): stamp fresh startedAt on job run; prefer supervisor Re-running the same job key was sticky-reusing a prior row's startedAt, so elapsed lied. Drain in-flight heartbeats before terminal status. Align AGENTS/guide: CLI supervisor first, MCP as manual path. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): typecheck-safe assertion for run startedAt Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): type put mock args so startedAt assertion typechecks Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): address Codex Majors — redirect ancestry, heartbeat status, ACP allowlist Inherit jobsAcceptedFromSessionIds across A→B→C merges; heartbeat PATCH omits status so late ticks cannot resurrect running; drop session_job from global name-only auto-approve (bridge/--allowedTools remain the trust path). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): type from-session metadata when inheriting job redirects Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): version attachedJob SSE; keep live job on merge collision Gate list cache on versioned attachedJob patches so dual EventSources cannot resurrect a cleared meter. On transfer key collision, prefer a running source over a terminal target (heartbeats no longer rewrite status). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): monotonic attachedJob emit watermark (not primary.updatedAt) Primary switches can go backwards in updatedAt and strand the list cache. Emit versions are Math.max(Date.now(), prev+1); REST list stamps a fresh wall-clock watermark so null jobs do not reset the client gate to 0. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): one attachedJob watermark allocator for REST and SSE GET /sessions and emitAttachedJobChanged share allocateAttachedJobVersion so equal-ms terminal patches are not rejected after a list refetch. Also preserve real Unix signal exit codes in hapi job run. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): stub allocateAttachedJobVersion in sessions route mocks Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): always record merge redirects even with zero jobs transferred Agents may attach the first outliving job after merge while still holding the pre-merge HAPI_SESSION_ID; redirects must exist before that first set. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): install source redirect before merge awaits; allow empty update Point jobsTransferredToSession immediately after transfer so mid-merge heartbeats follow the new owner during scratchlist I/O. Empty CLI/MCP update bodies are heartbeat-only (hub stamps heartbeatAt). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): expect empty MCP update as heartbeat Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): treat merge redirect metadata as hub-owned CLI update-metadata must not forge or erase jobsAcceptedFromSessionIds / jobsTransferredToSessionId — same strip/restore as supersede/clear links. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): reconcile REST list against attachedJob watermark Slow /api/sessions can finish after SSE clear/progress and resurrect a stale attachedJob. Also prefer newer terminal results on merge key collisions. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): retry terminal status write; reject startedAt on update Supervisor exit is the only running→terminal transition — retry transient hub failures. --started-at / startedAt only apply to set, not update/run. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): keep both live jobs on same-key merge Dual-running collisions remap the source key and record jobKeyRedirects so pre-merge supervisors cannot terminal-mark the winner. Also raise the flaky claudeRemote first-result test timeout under CI load. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): hard-refuse MCP set; louder stale heartbeat chrome Process-shaped work must use Shell hapi job run. MCP set is refused with the run recipe (wardrobe freeze). Stale rows show "no heartbeat · age". Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): preserve jobKeyRedirects across metadata merge + A→B→C Recompute merge metadata from latest target so early key remaps are not clobbered; compose inherited redirects through the current remaps. Localize stale/progress chip strings (en + zh-CN). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): keep running-job stubs in sidebar; align bar precedence Empty idle stubs with a live attachedJob must survive prepareSidebarSessions before title metadata lands. Match fraction to remaining-first label order. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): block delete while job running; keep jobful dedup losers CASCADE would erase outliving meters on inactive delete. Sidebar dedup must not hide a running attachedJob behind a jobless duplicate winner. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): guard store delete for running jobs; transfer on Codex merge Route-only 409 still left Codex duplicate consolidation and other callers cascading live meters. Refuse in DELETE SQL, clear watermarks, and transfer+redirect before Codex hard-deletes duplicates. Co-authored-by: Cursor <cursoragent@cursor.com> * test(jobs): stub transferAttachedJobs in Codex duplicate-merge mock Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): fence supervisor PATCH with expectedStartedAt Stale hapi job run processes must not heartbeat or terminal-write a newer run that reused the same job key. Treat startedAt as the run generation: supervisors send expectedStartedAt; hub rejects mismatches with 409 (CAS in SQL too). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): CAS supervisor writes with UUID runId (schema V24) Date.now()/startedAt is not unique across concurrent job-run processes. Persist run_id, mint UUID on PUT (client or hub), and reject PATCH when expectedRunId does not match. Replaces the interim expectedStartedAt fence. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): heartbeat PATCH must not re-send launch --detail Supervisor timer only needs expectedRunId so MCP/CLI progress detail updates are not clobbered by the next heartbeat. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): stamp heartbeatAt on the hub only Drop heartbeatAt from upsert/patch schemas and always persist Date.now() on the hub so a skewed/future client clock cannot keep a dead job green. Co-authored-by: Cursor <cursoragent@cursor.com> * docs(jobs): note schema tip V25 after A2A V23 collision Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): clear stale jobsTransferred redirect on reclaim When A→B then B→A makes A canonical again, drop A's outgoing jobsTransferredToSessionId so resolve(A) no longer hops to deleted B. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): transfer attached jobs on OpenCode /clear finishOpenCodeClear already wrote supersededBySessionId (which job APIs follow) without moving session_jobs. Transfer first so heartbeats on the retained source id reach the replacement row. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): follow job redirects with cycle detection Replace the five-hop cap so supervisors that retain the original HAPI_SESSION_ID across many OpenCode /clear replacements still resolve to the canonical owner. Visited-set stops redirect cycles. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): defer no-engine Codex merge; pending outranks Jobs Refuse duplicate merge when SyncEngine is unavailable and the source still has attached jobs (redirects cannot be persisted). Sidebar: put operator-pending ahead of the Jobs bucket when both apply. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): allocate list watermark before reading jobs GET /api/sessions was labeling snapshots with a version allocated after the job read, so a concurrent SSE emit could lose to a stale REST value. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): stamp supervised startedAt on the hub clock hapi job run omits startedAt; hub uses now when runId starts a new generation so runner/hub skew cannot zero or inflate elapsed time. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): preserve -- for hapi job run under normalizeCliArgs Runtime-wrapper handoff was dropping everything before `--` (or stripping `--` itself), so `job run … -- <cmd>` fell through to Claude. Keep `--` when a HAPI command already precedes it; only treat bare `bun entry -- <cli>` as a wrapper handoff. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): allow PATCH null clears from CLI and MCP Hub already accepts null to drop stale remaining/done/total so done+total can take over. Expose that via MCP nullable fields and hapi job update --clear-remaining (and siblings). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): scope -- keep to job run; expose runId fence on CLI Only preserve the child `--` separator for `job run`. Re-inserting it for `hapi -- auth` / `codex --` broke resolveCommand. Manual wrappers can now stamp `--run-id` / `--expected-run-id` to match hub CAS. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): fence DELETE/clear with expectedRunId Stale manual wrappers must not clear a newer run after key reuse; hub DELETE and CLI/MCP clear now honor the same run fence as PATCH. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): include runId on listSessionJobs for fence recovery Safe PATCH/DELETE need expectedRunId; list/MCP/CLI must return the generation so reconnecting wrappers can fence without guessing. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): stamp attachedJob on new SessionSummary test helpers Upstream share-picker / row-summary fixtures landed without #1404 fields; restore typecheck after rebase onto main. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): fail job run when terminal status never persists Child exit 0 with a frozen running meter lied to wrappers; surface hub write failure as exit 1 (run-mismatch still non-fatal). Clarify Active-sessions-only copy for attached jobs. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cursor,web): stop attached-job sessions bouncing Running/Jobs (#1553) Rebase onto upstream/main (#1503). Ignore ambient ACP thinking bumps while the message queue is idle and prompt() is not in flight. Prefer the Jobs in-progress bucket and suppress the thinking spinner when a running attached job is the honest outliving signal. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): do not mask foreground thinking when attached job runs (#1553) Keep the CLI queue-idle ACP guard; web now trusts hub thinking during real prompts instead of treating every attached job as ambient chatter. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: rebase onto upstream/main — resolve test mock conflicts Merge upstream title/summary stubs with attached-job mocks; drop duplicate showSessionSummaryInChat key introduced during rebase. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): preserve child exit 0 when meter cleared during job run Treat terminal PATCH not_found as detached (operator cleared via session_job) instead of a supervision failure. Retry transient 404s; accept absence on the last attempt. Regression test covers successful child after external clear. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cursor): filter only debounced running chatter while queue-idle (#1553) Tag agent-activity listener callbacks with source in AcpSdkBackend so the Cursor launcher can ignore queue-idle state_update:running without hiding harness resume (requires_action, permission). Regression test updated. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1424): trust ACP foreground signals; preflight merge job check Drop queue-idle running suppression in Cursor launcher — it hid autonomous harness work. Attached-job Running/Jobs flicker stays in web/sessionInProgress. Refuse no-engine Codex merge before copying history when sources have jobs. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): steer agents away from sleep-stub jobs and remaining=0 traps MCP update-before-create and hapi job run -- sleep while real work runs elsewhere can leave a misleading running meter. Return job-run recipe on not_found, warn when remaining hits zero without completion, and tighten session_job agent instructions. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): steer MCP session_job not_found even when instanceof breaks MCP HTTP server bundles can load duplicate SessionJobError identities so update-before-create fell through to bare "job not found". Detect not_found by code and message, not instanceof alone. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): idempotent MCP clear-not-found; reject --heartbeat-sec off run Clear on an already-absent job returns success without steering to hapi job run. Parser rejects --heartbeat-sec on set/update/clear/list. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): reject mutation flags on job list/clear and status on run Parser now fails fast when list/clear receive label/status/progress fields, or when run receives --status, instead of silently discarding them. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): reject stray MCP fields and non-run command suffix MCP list/clear reject incompatible fields; CLI rejects -- <cmd> unless action is run so clear/set cannot silently drop a trailing command. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(hub): preserve runId on corrective job PUT without runId Started-at corrections via job set must not mint a new generation and break an in-flight supervisor's expectedRunId fence. Docs heartbeat recipe now shows run-id + expected-run-id. Co-authored-by: Cursor <cursoragent@cursor.com> * docs: mark ALL_DONE late-attach example as completed status job set defaults to running; remaining=0 alone does not finish the meter. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web,cli): finish #1424 rebase onto upstream pin buckets Keep Jobs in the In progress section after upstream split Active/Running. Preserve Cursor ACP retry fields and Codex prompt test names from main. Quiet connected sessions stay in directories (#1404 stand). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): rename All activity — quiet connected is not in-progress Connected-but-idle sessions stay in project folders in every pin mode. UI mode label is now Working & pending; drop the unreachable Active pin bucket and the copy that claimed quiet actives floated under All. Co-authored-by: Cursor <cursoragent@cursor.com> * docs(guide): session-id contract and remaining vs bar fill Document hub-row vs worker HAPI_SESSION_ID bug and that --remaining alone does not move the progress bar without total. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): bind isNewerVersionedPatch after sessionPatch extract `export … from` does not put the helper in module scope, so attachedJob list patches failed typecheck after the rebase onto upstream's extract. Guide copy now matches Working & pending; quiet connected stays in folders. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(hub): commit job-row move and owner redirects together A failed metadata write after sessionJobs.transfer left the old session id pointing at an emptied source, so heartbeats 404ed. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): fail-closed session id for remote Cursor job run AGENTS and recipe copy no longer treat \$HAPI_SESSION_ID as always safe; remote Cursor may export a worker row. Cursor resume bootstrap test asserts the requested existingSessionId is exported into the child env. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(hub): refresh job redirects before scratchlist merge await persistAttachedJobRedirects wrote SQLite while resolveAttachedJobSessionId still read stale cache; heartbeats via the old id could 404 during attachment I/O. Refresh both sessions immediately after persist. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cursor): ignore ambient ACP running without a prompt in flight state_update_running chatter while the queue is idle was setting hub thinking and floating quiet sessions (with jobs) into Working. Permission and requires_action still bump; prompt-owned running still bumps. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cursor): drop leftover rebase conflict markers in ACP launcher Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): sanitize job text before terminal stdout Strip VT/ANSI and remaining C0 controls from job key/label/unit/detail/runId in formatJobLine so list/set/update cannot emit OSC escapes from persisted fields. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): sanitize MCP session_job output via shared formatter Move terminalText/formatJobLine into modules so CLI stdout and MCP tool results both strip VT/ANSI/C0 before agents render job fields. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): scrub C1 controls in shared job-output sanitizer Co-authored-by: Cursor <cursoragent@cursor.com> * test(cli): fix C1 sanitizer assertion (content may remain) Co-authored-by: Cursor <cursoragent@cursor.com> * fix(hub): remap late job PUT when merge left no key redirect When a merged-away session registers a new runId for a key the target already owns as a different running generation, allocate a remapped key and persist jobKeyRedirects so the target's live meter is not overwritten. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(hub): also remap redirected job set without runId on collision Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): tree-kill supervised job children on SIGINT/SIGTERM Bare process.kill only hit the immediate child; a shell grandchild could keep running after the wrapper marked the job terminal. Use killProcessByChildProcess. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): preserve SIGINT on job tree-kill and await teardown Forward the received signal through killProcessByChildProcess so Ctrl-C stays exit 130, and wait for verified tree termination before writing the terminal job meter. Co-authored-by: Cursor <cursoragent@cursor.com> * test(cli): type the tree-kill teardown patch mock for typecheck Co-authored-by: Cursor <cursoragent@cursor.com> * test(web): supply attachedJob fields in upstream session fixtures After rebasing onto main, mark-all-read and app-badge helpers need attachedJob / attachedJobUpdatedAt for SessionSummary typecheck. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(hub): record identity jobKeyRedirects on no-collision transfer A→B transfers that keep the original key must still map A/key→key so a later B→C remap can compose A through to the remapped key instead of resolving onto C's unrelated live same-key job. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(hub): resolve job owner after PUT/PATCH body parse A merge/clear during the JSON await must not leave mutations targeting the pre-merge session id. Validate the body first, then resolve owner and key synchronously before upsert/patch. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(hub): honor identity jobKeyRedirects on corrective PUT Explicit A/key→key maps from no-collision transfers must short-circuit late-registration remapping so job set without runId updates the same row instead of allocating a second key and orphaning the supervisor. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(hub): persist identity redirects on late free-key job PUT Empty A→B then late register left no A/batch map, so B→C remaps could not compose and A targeted C's live meter. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(hub): skip redirect inheritance on late job-key PUT Recording a free-key identity via retained B was reimporting B's stale A/batch map onto C and undoing composed A→B→C remaps. Co-authored-by: Cursor <cursoragent@cursor.com> * test(web): supply attachedJob on new upstream search fixtures Rebase onto main brought search-rank helpers that omit SessionSummary.attachedJob fields required by #1424. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): pass XDG_CACHE_HOME through vitest hub globalSetup Estate bun installs pin the cache via XDG_CACHE_HOME; the test hub whitelist omitted it and `bun run hub` hung before ready. Co-authored-by: Cursor <cursoragent@cursor.com> * test(web): retarget bucketRunningSessions for jobs pin modes Upstream #1820 idle/active boolean buckets no longer exist after the quiet-connected never-floats contract; cover jobs/working/pending instead. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): add Russian strings for session jobs pin modes Upstream shipped ru locale after the jobs pin UI; fill attachedJob and tri-state pin copy so Display settings are not missing keys. Co-authored-by: Cursor <cursoragent@cursor.com> * docs(cli): steer agents to list session jobs before done/archive MCP session_job description and always-on SESSION_JOB_INSTRUCTION now require list on resume and before done; clear zombie running meters without asking the operator. No hub auto-clear. Co-authored-by: Cursor <cursoragent@cursor.com> * test(cli): keep ACP MCP tool list without video/media after rebase Co-authored-by: Cursor <cursoragent@cursor.com> * docs(jobs): forbid frozen 0/N job run for display meters Split alive-only vs fraction bars in the guide and always-on steer: heartbeats do not advance launch --done/--total; name hapi-job-run-metered and the continuous-update portable path; note exit≠semantic failure. Co-authored-by: Cursor <cursoragent@cursor.com> * test(cli): expect Codex autoReview in set-mode allowed lists Upstream #2090 added autoReview after #2095 set-mode tests; update the allowed-mode strings so CI matches the catalog. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): use SessionSpinner for foreground thinking after merge Keep isAgentForegroundThinking gate; match upstream SessionSpinner markup so background/thinking spinner equality tests pass. Co-authored-by: Cursor <cursoragent@cursor.com> * test(hub): expect schema tip v29 in migration-v26 after jobs remap Co-authored-by: Cursor <cursoragent@cursor.com> * test(web): expect fixed-order + jobs pin after merge with upstream display Upstream asserted Fixed session order was gone; #1424 keeps it with the tri-state pin choice group. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): honor Fixed session order with creation-time sort Tip Minor: the setting only paused pin float while directories still sorted by lastUserMessageAt. Use createdAt comparators for rows, groups, and global pins when fixed mode is on. Co-authored-by: Cursor <cursoragent@cursor.com> * test(web): cover Fixed session order vs activity list promotion Upstream order test forced obsolete fixed-order=true and expected activity promotion; with #1424 keeping the setting, split default vs fixed cases. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(hub): preserve composed jobKeyRedirects on cleanup re-merge A second B→C merge with empty remaps was reimporting retained B's stale A/batch→batch and clobbering C's composed A/batch→batch.<B> mapping. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): survive hub-down after job run child exit Terminal completed/failed PATCH now retries connection/502–504 failures for up to ~10m so a brief hub restart cannot leave a zombie running meter. Refuse wrapping hapi-restart-hub / stack-switch argv in job run; document the hard rule in the guide and CLI help. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): classify HTTP 502–504 via SessionJobError.httpStatus Structured hub outage bodies (e.g. 503 "Not connected") no longer drop the status code, so terminal PATCH keeps the hub-down retry window instead of exiting after three short attempts. Co-authored-by: Cursor <cursoragent@cursor.com> * chore: nudge GitHub PR head sync for #1424 Fork tip already includes the upstream/main merge; empty commit to re-fire the cross-repo PR head webhook (API still showed prior SHA). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): honor jobs exception and fixed order under list view Active status filter keeps idle running attachedJob rows (and keeps them out of archived). Fixed session order forces created sort with activeFirst off, not only pin-off. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): ignore obsolete fixed-order key under SessionListView Upstream #2263 made hapi-fixed-session-order obsolete; reading it overrode last-message promotion. Keep jobs-aware status filtering; list sort stays on SessionListView. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(hub): include attachedJob on content-search summaries Content-search replaces live list rows; omitting jobs dropped meters and the active-filter exception for matching idle sessions (#1424). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): remove obsolete fixed session order setting SessionListView owns list order (#2263); the switch only wrote a dead localStorage key and kept recycling tip Findings on #1424. Co-authored-by: Cursor <cursoragent@cursor.com> * chore: nudge GitHub PR head sync for #1424 Co-authored-by: Cursor <cursoragent@cursor.com> * test(web): drop Fixed session order assertion from display settings Matches removal of the obsolete switch under SessionListView (#2263). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): drop fake 1/3 fill for indeterminate attached jobs Remaining-only jobs have no fraction; the old pulse bar painted a constant w-1/3 that looked like progress. Keep honest text; show a bar only when done/remaining+total yields a real fraction. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(jobs): wake owning session on terminal status (#1489) Fold opt-in wakeOnTerminal into the #1424 tip for dogfood-lane ship. Schema v33→v34 additive wake columns + runId one-shot claim. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): release terminal wake claim on delivery failure Provisional wake_emitted claims must clear when resume/send fails so a reconnect retry can reclaim; schedule capped backoff and use a run-scoped localId for send dedupe (#1489 tip Finding). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): requeue wakes after retry budget and follow ownership Keep undelivered terminal wakes eligible after rapid-retry exhaustion and rescan on hub start / machine offline→online. Resolve job-owner and key redirects before claim, release, and deferred retry so merges cannot strand a provisional wake_emitted claim. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): provisional pending wake claims + run fence Persist wake delivery as pending:<runId> until send succeeds so hub restart can clearAbandoned and reclaim. Before send, fence the live row to the claimed run/terminal/opt-in so key reuse mid-resume cannot mis-prompt. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): classic indeterminate marquee for unknown attached jobs Session list claimed an "indeterminate bar" but only rendered the pulse dot when fraction was null. Show a track with a sliding segment (no %) in the same slot as determinate fill, with unit coverage and docs/help aligned to shapes A/B. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): quiet striped indeterminate job bar Replace the loud sliding-chunk marquee with CSS-Tricks-style diagonal stripes that drift slowly at low contrast — still reads as moving, not carnival mode. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): seamless loop for indeterminate job stripes Animate background-position by exactly one 8px tile on both axes so the diagonal stripe phase matches at the loop boundary (was -12px → jump). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): requeue wakes on machine-update-state online Connect marks active via runner-state update before the first heartbeat, so heartbeat offline→online never fired. Requeue pending terminal wakes when machine-updated refreshes an offline machine to active. Co-authored-by: Cursor <cursoragent@cursor.com> * test(hub): cast private machineCache in wake reconnect coverage CI typecheck failed on private SyncEngine.machineCache access from the machine-updated requeue test. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(hub): monotonic machine active_at on runner-state online refreshMachine only adopts store activity when storedActiveAt is strictly newer than the cache. Same-ms create→updateMachineRunnerState left the cache stuck inactive and skipped #1489 wake requeue. Bump active_at past the activity floor; align the reconnect test with memory-only expiry. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(cli): require --progress mode on job run/set Forces an explicit affordance (unknown|fraction|until) so known-duration countdowns cannot silently fall into indeterminate stripes. until stamps remaining/total and job-run heartbeats re-stamp remaining from the deadline. Co-authored-by: Cursor <cursoragent@cursor.com> * docs(session-jobs): require --progress in create examples Bot Minor: wake/set/heartbeat/CLI recipes and AGENTS.md omitted the now-mandatory progress mode, so copy-paste creates would fail parse. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): refuse numeric sleep without until; honor --started-at on countdown Closes the dogfood footgun: sleep N under unknown/fraction is rejected. Until-mode job run accepts --started-at so mid-window re-attach keeps the original window total; heartbeats stamp against that start. Docs demote estate-only hapi-job-run-metered as non-upstream. Co-authored-by: Cursor <cursoragent@cursor.com> * test(cli): type heartbeat mock args in until startedAt coverage Fixes CI TS2493 on patch.mock.calls[0][1] from an untyped vi.fn. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(hub): exempt job-wake prompts from session-end sweep Session-end was synthetically consuming unacked hapi-job-wake: rows, so a completion wake queued behind an active turn could be lost when the CLI disconnected before messages-consumed. Mirror the ping-peer- exemption so wakes stay replayable until a real runtime ACK. Co-authored-by: Cursor <cursoragent@cursor.com> --------- Co-authored-by: Cursor <cursoragent@cursor.com>
26 KiB
hapi CLI
Choose a supported coding agent from your terminal and control its sessions remotely through the hapi hub. See the supported agents.
What it does
- Starts Claude Code sessions and registers them with hapi-hub.
- Starts Codex mode for OpenAI-based sessions.
- Starts Cursor Agent mode for Cursor CLI sessions.
- Starts Grok Build locally or via ACP for remote sessions.
- Starts OpenCode mode via ACP and its plugin hook system.
- Starts DeepSeek Harness through an external ACP stdio server.
- Provides an MCP stdio bridge for external tools.
- Manages a background runner for long-running sessions.
- Includes diagnostics and auth helpers.
Typical flow
- Start the hub and set env vars (see ../hub/README.md).
- Set the same CLI_API_TOKEN on this machine or run
hapi auth login. - Run
hapito choose an agent, orhapi <agent>to start one directly. - Use the web app or Telegram Mini App to monitor and control.
Commands
Session commands
hapi- Choose an agent interactively. Unavailable agents are shown with a reason and cannot be selected.hapi claude- Start a Claude Code session (passes through Claude CLI flags).hapi codex- Start Codex mode. Seesrc/codex/runCodex.ts.hapi codex resume <native-thread-id>- Resume a Codex conversation by its native thread ID. For a HAPI session ID, usehapi resume <id>.hapi cursor- Start Cursor Agent mode. Seesrc/cursor/runCursor.ts. Supportshapi cursor resume <chatId>,hapi cursor --continue,--mode plan|ask,--yolo,--model. Local and remote modes supported; new remote sessions useagent acp. Pre-ACP sessions retain the legacyagent -pstream-json resume path.hapi grok- Start Grok Build mode. Seesrc/grok/runGrok.ts.hapi copilot- Start GitHub Copilot mode.hapi kimi- Start Kimi mode.hapi agy- Start Antigravity mode (remote-only).hapi pi- Start Pi mode (remote-only).hapi opencode- Start OpenCode mode via ACP. Seesrc/opencode/runOpencode.ts. Note: OpenCode supports local and remote modes; local mode streams via OpenCode plugins.hapi dsh- Start DeepSeek Harness through ACP. Seesrc/dsh/runDsh.ts. DSH is remote-only and its ACP server must be configured separately.hapi resume [sessionId]- List resumable sessions for this machine or resume one locally.hapi ping-peer <session-id-prefix> <message>- Message another session. Inactive targets are refused (exit 5) unless--wakeresumes them first. Prefer this or MCPping_peer/list_peersover reinventing JWT+curl. Also--message-file/--list [--all](active sessions with machine and cwd;--allincludes inactive).hapi spawn-peer --dir PATH --name TITLE --message-file -- Spawn a session and deliver a required first message. Optional--machine ID|hostnametargets another runner (resolved via GET /api/machines);--dirmust exist on the target. Machine spawn HTTP 200 is not a working peer; this command fails if the remit does not land. Prefer MCPspawn_peer.hapi usage [--since 24h|7d|<ISO>|<ms>] [--until …] [--json]- When agents were working across every machine on the hub, fromGET /api/activity.--jsonprints onehapi.activity.v1report for other tools (time trackers); errors go to stderr with exit codes 2 (arguments), 3 (no token or refused), 4 (hub too old), 1 (other).hapi inspect-peer <session-id-or-prefix>- Read-only peer metadata + recent message text (no resume). Prefer this or MCPinspect_peerwhen a user cites[title](/sessions/<id>)or Copy-referenceSee session "…" (/sessions/<id>) for context./sessions/<id>is a hub path, not a local file. Optional--limit.hapi set-mode <session-id-or-prefix> <mode>- Change the permission mode of an existing session, like the web permission picker. Active sessions switch immediately; inactive ones use it on next resume. An invalid mode prints the modes allowed for that agent.hapi job set|update|clear|list|run- Attach long-running outliving work to a session so the list UI shows progress while the agent is idle (tiann/hapi#1404). Prefer"$HAPI_SESSION_ID". Heartbeat viaupdate(orrun); honest--remainingor--done/--total(omit counts if unknown — never invent a percent). Late-attach clock fix:set --started-at <epoch-ms>or clear+set. Seedocs/guide/session-jobs.mdandhapi job --help.
Peer messages default to auto: use the target's live capabilities and turn
state to steer an active, eligible turn; otherwise queue. Inactive peers require explicit wake: true; awakened peers enter the ordinary queue. This applies to every steering-supported
flavor: remote Claude, Pi, Codex, OpenCode, Antigravity on agy acp, and Cursor ACP.
Unsupported agents and legacy Cursor sessions queue instead. Prefer auto for routine collaboration
when queueing is an acceptable fallback.
Use explicit queue for non-urgent updates that can wait. Use steer for
important, time-sensitive findings the peer needs to know now, not after its
current turn: a correction that invalidates its assumptions, a blocker, or a
result that changes its next action. State why it matters now and what the peer
should adjust.
Explicit steer rejects unsupported agents, idle targets, and inactive targets
before sending. It does not abort the current turn or guarantee an immediate
response. MCP ping_peer accepts the same optional
deliveryMode: "auto" | "queue" | "steer" field. Auto is a peer-sender policy;
ordinary web/native chat delivery is unchanged.
Peer messages never wake an inactive session by default: ping_peer refuses
with inactive and sends nothing. Pass MCP wake: true (CLI --wake) only
when the user asked or the handed-off work requires that peer to act. Agents
should message only peers tied to their task (a cited session, their Parent,
peers they spawned or were handed off to), inspect_peer an unfamiliar peer's
machine, cwd, and recent work before messaging it, and never broadcast.
list_peers returns active sessions only unless includeInactive: true.
hapi ping-peer <session-id> 'The dependency is ready' --delivery-mode auto
hapi ping-peer <session-id> 'Run the next check' --delivery-mode queue
hapi ping-peer <session-id> 'Use the corrected input path' --delivery-mode steer
Every submission retains one ping-peer- localId. Auto first stores an ordinary
queued message, then tries the existing queued-message Steer action when the
live target is eligible. A steer rejection or unconfirmed steer response retains
that same accepted message without resending or retrying the action. The
receipt and progress output say whether steering was not attempted, rejected by
the Hub, or not confirmed with delivery unresolved. An
accepted receipt proves Hub acceptance, not whether the message remains queued
or has already been consumed. Actual runtime acknowledgements determine delivery.
Steer success reports steered, or invoked when consumption won the race.
Explicit steer still reports an error if steering cannot be confirmed after
acceptance, including the original localId. Initial send failures or ACK loss
are never converted into successful auto fallback. Inspect the target before
retrying an unconfirmed send; do not automatically resend the prompt.
The picker lists agents alphabetically by command name. Use Up/Down and Enter to choose; Esc or Ctrl-C cancels. It appears on every bare invocation, even when only one agent is available. No default agent or selection is saved.
Scripts and non-interactive shells must specify an agent. Old implicit-Claude
commands such as hapi --yolo, hapi --resume, and hapi "prompt" now report
an error; use hapi claude --yolo, hapi claude --resume, or
hapi claude "prompt" instead.
hapi --help, hapi -h, and hapi help show only HAPI's help, without starting
a session or requiring an installed agent. hapi --version / hapi -v show
HAPI's version. Flags after an agent name are handled by that agent's existing
integration; supported flags vary by agent. HAPI does not translate or append
agent help text.
Resume a remote session locally
hapi resume
hapi resume <session-id>
hapi resume lists resumable sessions for the current machine. hapi resume <session-id> hands off an active remote session and opens the same HAPI session in the local terminal.
For Codex, the terminal and Web stay usable at the same time. Closing the original terminal stops a terminal-started run, but its history remains resumable. Sessions started from the Web run under the Runner; closing a terminal attached later does not stop them. End session archives the selected conversation. See Codex usage and limits for details.
Answer local Claude prompts from HAPI
In a local Claude session started by hapi claude, main-session AskUserQuestion
questions and tool permission prompts can also be answered from the web app.
The terminal dialog stays usable; answering does not restart Claude or switch
the session to remote mode. Claude arbitrates terminal/web races, and HAPI
records the native result rather than assuming the web response won.
The bridge uses Claude's PermissionRequest hook, not a blocking
PreToolUse approval gate. An unanswered remote request expires after one
hour; expiration, disconnection, or bridge failure leaves the native prompt
available. Local answers/cancellation, session changes, and mode switches
withdraw stale web controls. Cancellation detection may wait for the next
transcript scan.
Verified with Claude Code 2.1.221. Background subagents, ExitPlanMode,
and requests that cannot be unambiguously matched to a native tool call remain
terminal-only. Earlier Claude versions have not been verified.
Authentication
hapi auth status- Show authentication configuration and token source.hapi auth login- Interactively enter and save CLI_API_TOKEN.hapi auth logout- Clear saved credentials.
See src/commands/auth.ts.
Runner management
hapi runner start- Replace any existing runner and start a detached process with the supplied flags/environment.hapi runner stop- Stop runner gracefully; agent sessions stay alive.hapi runner start-sync- Run in the foreground (for a process supervisor).hapi runner status- Show runner diagnostics.hapi runner list- List active sessions managed by runner.hapi runner stop-session <sessionId>- Terminate specific session.hapi runner logs- Print path to latest runner log file.
Both start and start-sync accept repeatable --workspace-root <path> (or --workspace-root=<path>). When set:
- The web
/browsepage surfaces scoped file trees rooted at those paths. - The runner refuses
list-directoryandspawn-sessionrequests for paths outside the configured roots. - The runner can serve read-only file, Git, and ripgrep requests for inactive
sessions through its machine-scoped
workspace-file-accesscapability. ~and~/fooare expanded.
Omitting the flag keeps manual session spawning unrestricted and leaves the
web /browse feature disabled. Machine directory lookups used by session
autocomplete and native pickers are still available, but are limited to the
runner's home directory.
See src/runner/run.ts.
Diagnostics
hapi doctor- Show full diagnostics (version, runner status, logs, processes).hapi doctor clean- Kill runaway HAPI processes.
See src/ui/doctor.ts.
Other
hapi mcp- Start MCP stdio bridge. Seesrc/codex/happyMcpStdioBridge.ts.hapi hub- Start the bundled hub (single binary workflow).hapi server- Alias forhapi hub.
Codex round timing
Completed live Codex turns persist their duration in the message stream, so Web and PWA response details keep the same Round duration after refresh or a cached tail reload. Local transcript timing uses the original start and completion timestamps; imported history and turns without an observed live start do not receive a new duration.
Codex model catalog
To use an existing static Codex model catalog, set
HAPI_CODEX_MODEL_CATALOG_JSON on the CLI/runner machine to an absolute path
or ~/.... HAPI passes it as -c model_catalog_json=... to standalone and
shared app-servers, including resumed sessions. This explicit HAPI setting
has precedence over Codex configuration files; an explicit launch
-c 'model_catalog_json="/path/to/catalog.json"' takes precedence over HAPI.
When unset, HAPI adds no catalog override and Codex uses its normal configuration
and discovery. You can also configure model_catalog_json directly in Codex's
config.toml. HAPI does not inspect, generate, refresh or copy catalogs or
credentials, and does not start extra processes to prepare them. Codex validates
catalog contents during its normal startup and reports invalid files itself.
Use a complete catalog appropriate for the current provider/account and update
it when availability changes; a static catalog bypasses native discovery.
Paths support macOS, Linux and Windows, including spaces. Restart the runner after changing its environment; existing servers use the new setting after they are safely stopped and resumed. Inference traffic is unaffected.
Codex MCP servers
Codex sessions keep the MCP servers configured in the user's Codex
config.toml. HAPI adds its own hapi bridge without replacing other user
servers. When a runner spawn supplies a Codex auth token, it copies only
config.toml into a temporary CODEX_HOME and writes the supplied auth.json,
preserving MCP settings without copying unrelated authentication state.
Without a supplied token, Codex uses the runner's normal Codex home/auth.
The hapi server name is reserved by HAPI.
On Windows, known package-manager shims (uvx, npx, npm, pnpm, yarn,
bunx, and .cmd/.bat commands) use a short-lived HAPI stdio compatibility
proxy before reaching the configured MCP server. The proxy keeps the original
command and arguments in a session-temporary file and forwards MCP JSON-RPC
bytes without putting environment-variable values into arguments or that file.
Secret and network variables still need to be listed in the MCP entry's
env_vars (or supplied through env); HAPI does not forward the whole host
environment automatically.
Configuration
See src/configuration.ts for all options.
DeepSeek Harness ACP uses the official dsh CLI with --profile acp by default
(the ACP profile ships with @deepseek-ai/dsh since 0.2.0). Override the
executable or its arguments without shell parsing:
export HAPI_DSH_ACP_COMMAND=dsh-acp-demo
export HAPI_DSH_ACP_CONFIG=/path/to/deepseek-harness/examples/acp-agent/cordis.yml
hapi dsh
HAPI_DSH_ACP_CONFIG maps to --config for the configured server. Without
HAPI_DSH_ACP_COMMAND it instead applies to the official CLI, which has no
--config flag — the path is passed as a --patch overlay on top of
--profile acp.
For a source checkout, use JSON arguments:
export HAPI_DSH_ACP_COMMAND=pnpm
export HAPI_DSH_ACP_ARGS_JSON='["--dir", "/path/to/deepseek-harness", "run", "demo:acp"]'
The DSH ACP profile can restore native context through session/resume when
advertised; Hub history remains the transcript source. A legacy server may
fall back to a fresh session with a visible notice. Model catalogs are exposed
through ListDshModels and selected per turn via session/set_config_option.
DSH owns MCP injection, live tool/reasoning telemetry and permission policy.
Required
CLI_API_TOKEN- Shared secret; must match the hub. Can be set via env or~/.hapi/settings.json(env wins).
Optional
HAPI_API_URL- Hub base URL (default: http://localhost:3006; also configurable asapiUrlin settings).HAPI_HOME- Config/data directory (default: ~/.hapi).HAPI_EXPERIMENTAL- Enable experimental features (true/1/yes).HAPI_EXTRA_HEADERS_JSON- JSON object of extra headers to send on CLI → hub requests, e.g.{"Cookie":"CF_Authorization=..."}. Can also be set as theextraHeadersobject in~/.hapi/settings.json(environment variable wins).HAPI_CLAUDE_PATH- Path to a specificclaudeexecutable.HAPI_DSH_ACP_COMMAND- ACP server executable forhapi dsh(default:dshwith--profile acp).HAPI_DSH_ACP_CONFIG- Optional config path for the configured DSH ACP server (--configwithHAPI_DSH_ACP_COMMAND,--patchoverlay on the default official CLI).HAPI_DSH_ACP_ARGS_JSON- Optional JSON array of ACP server arguments.HAPI_HTTP_MCP_URL- Default MCP target forhapi mcp.
Runner
HAPI_RUNNER_HEARTBEAT_INTERVAL- Heartbeat interval in ms (default: 60000).HAPI_RUNNER_HTTP_TIMEOUT- HTTP timeout for runner control in ms (default: 10000).HAPI_RUNNER_WEBHOOK_TIMEOUT_MS- Session-start webhook timeout in ms (default: 15000); raise for slow agent startup/resume.HAPI_DISABLE_VERSION_HANDOFF- Set to1to disable automatic runner replacement on CLI binary changes.HAPI_RUNNER_SUPERVISED- Set to1only when a supervisor restarts the runner after exit; enables the web Restart control's supervised path.
Worktree (set by runner)
HAPI_WORKTREE_BASE_PATH- Base repository path.HAPI_WORKTREE_BRANCH- Current branch name.HAPI_WORKTREE_NAME- Worktree name.HAPI_WORKTREE_PATH- Full worktree path.HAPI_WORKTREE_CREATED_AT- Creation timestamp (ms).
Set for the wrapped agent
HAPI_SESSION_ID- The current HAPI session ID, available inside agent shells. Use it in scripts that target the current conversation without listing sessions.- An explicitly configured
HAPI_API_URLis also made available to agent shells. HAPI does not copy settings-backedCLI_API_TOKENsecrets into the agent environment; credentials already present in the parent environment may still be inherited. Web Terminal PTYs (session Terminal button) strip hub secrets and agent-context markers (HAPI_AGENT_CONTEXT,CURSOR_AGENT, …) and setHAPI_USER_TERMINAL=1so operator tools treat that shell as human-facing.
For peer discovery and messaging, use the session's MCP list_peers,
inspect_peer, and ping_peer tools, or the corresponding CLI commands.
To create a new peer with work attached, use MCP spawn_peer or hapi spawn-peer.
The first message is required and verified in the transcript before success;
machine-spawn HTTP 200 alone does not prove the task was delivered. In-session
spawns add a Parent [title](/sessions/<uuid>) citation so parent renames do not
change its identity.
With waitForReply on ping_peer or spawn_peer, the peer's reply is posted
back into the calling session when the peer's turn ends (Pi peers are not
supported). The caller's CLI process does the polling, so if that process exits
first, the reply is not posted back; it stays in the peer session.
On a remote runner host, configure the matching hub URL and token so shell
commands reach the same hub (hapi auth login saves the token).
For example, this source-checkout helper displays an image in the current session when MCP is unavailable:
bun scripts/tooling/hapi-display-image.mjs /absolute/path/to/image.png "optional title"
Session lifecycle invariants
- Runner waits up to 30 seconds for Codex startup (15 seconds for other agents),
overridable with
HAPI_RUNNER_WEBHOOK_TIMEOUT_MS. A Codex startup deadline returns an unconfirmed result and keeps its process tracked; a late webhook completes the same session. Wait for that row or explicitly stop it rather than creating duplicates. Process exit and explicit stop still clean up the child. The Hub gives Codex spawn RPCs 60 seconds for preflight plus startup. - On macOS, when the spawner's responsible process goes away with it (a runner
started by launchd, directly or through the npm launcher
bin/hapi.cjs, which passesHAPI_LAUNCHER_PID), every detachedspawnHappyCLIchild (sessions, runner handoff, runner start) is started withHAPI_DISCLAIM_RESPONSIBILITY=<spawner pid>. In a direct child of that pid, the entry hook clears the variable and re-executes the same executable in place so the child becomes its own responsible process; the pid, stdio and cwd are unchanged. Without this, a session kept alive across a runner restart loses LAN access for every new process in its tree (macOS Local Network check,EHOSTUNREACH) once the old runner is gone. Spawners started from Terminal or SSH keep the inherited responsibility (and its implicit LAN allowance). Binaries without the hook ignore the variable; any failure in the hook falls back to a plain exec or to continuing in-process, and is logged. Implementation:src/runtime/disclaimExec.ts,src/runtime/responsibility.ts.
When changing agent bootstrap, handoff, or shared-session plumbing:
- Handoff-capable integrations use
local(terminal) andremote(web-controlled) ownership modes. Codex instead supports concurrent clients without ownership switching; see Codex shared sessions. - Ordinary wrappers export
HAPI_SESSION_IDafter bootstrap. Shared Codex uses a per-root MCP bridge andshell_environment_policy.set.HAPI_SESSION_ID; never put one root's ID into the shared app-server environment. Implementation:src/codex/shared/root.ts,src/codex/shared/runtime.ts. - Gemini remains a historical wire flavor, not a launchable integration. Use the supported-agent guide for the launchable set.
Storage
Data is stored in ~/.hapi/ (or $HAPI_HOME):
settings.json- User settings (machineId, token, onboarding flag). Seesrc/persistence.ts.runner.state.json- Runner state (pid, port, version, heartbeat).logs/- Log files.
Requirements
- Install and authenticate the agent you want to use. Claude CLI (
claudeon PATH) is required only forhapi claude. - Cursor Agent CLI installed (
agenton PATH) forhapi cursor. Install:curl https://cursor.com/install -fsS | bash(macOS/Linux),irm 'https://cursor.com/install?win32=true' | iex(Windows). - Grok Build CLI installed (
grokon PATH) forhapi grok. Authenticate withgrok login --device-authon headless runner machines, or setXAI_API_KEY. - OpenCode CLI installed (
opencodeon PATH). - Bun 1.4.4 for building from source.
Build from source
From the repo root:
bun install
bun run build:cli # Type-check the CLI; no executable output
bun run --cwd cli build:exe # Host-platform executable in cli/dist-exe/<target>/
For an all-in-one binary that also embeds the web app:
bun run build:single-exe
Large Codex thread recovery
Cold resumes and established internal subscriptions exclude inline turns; HAPI reads history separately. The initial root subscription retains the existing response behavior so empty native threads can initialize their history source. This does not truncate the native rollout or reduce the context restored by Codex.
For exceptionally large threads, set HAPI_CODEX_LAZY_HISTORY_IDS to a
comma-separated list of native Codex thread IDs in the Runner environment before
starting the Runner. Only these roots replay their newest turn when reading
paginated history and skip child history replay. Other threads retain full replay;
legacy native threads without paginated history still use the full-history path.
Descendant discovery and subscriptions to loaded children are retained, including
after reconnect, so pending questions and live child events can still reach HAPI.
This option favors recovery latency over Hub history completeness. It does not implement UI-driven pagination or asynchronous backfill. Older turns and child traces missing from the Hub may remain missing after reconnect; messages with an uncertain delivery state may need manual inspection if their acceptance evidence is in an older turn. Native rollout files remain intact. Historical fork checks still read complete history when the message-to-turn mapping is already known; older messages without that mapping cannot be forked through the Hub. A single turn can still be large, so this is a turn limit rather than a byte limit.
Source structure
src/api/- Hub communication (Socket.IO + REST).src/claude/- Claude Code integration.src/codex/- Codex mode integration.src/cursor/- Cursor Agent integration.src/grok/- Grok Build native TUI + ACP integration.src/agent/- Shared support for ACP-compatible agents.src/opencode/- OpenCode ACP + hook integration.src/runner/- Background service.src/commands/- CLI command handlers.src/ui/- User interface and diagnostics.src/modules/- Tool implementations (ripgrep, difftastic, git).
Releasing
From the repository root, bun run release-all <version> updates the CLI package,
shared app version, iOS MARKETING_VERSION (app and notification extension, all
configurations), and Android's default versionName, then commits, tags v<version>,
and pushes. It requires a clean working tree on main. Use --dry-run to preview
without changing files. Native build numbers (CURRENT_PROJECT_VERSION / versionCode)
remain managed separately; Android's -PhapiVersionName override is preserved.
The pushed tag triggers .github/workflows/release.yml, which builds all binaries,
runs bun run --cwd cli publish-npm, and creates the GitHub Release. npm publishing
uses Trusted Publishing (OIDC), so no npm
token is involved; each @twsxtd/hapi* package must list tiann/hapi /
release.yml as its trusted publisher on npmjs.com. Packages already on npm are
skipped, so a failed release can be retried by re-running the workflow.
setup-bun reads the build version from the root package.json's packageManager.
Keep local release builds on that version too. Bun 1.4.0 produces invalid
darwin-arm64 signatures that macOS 27 rejects with SIGKILL; Bun 1.4.4 includes
the upstream signing fix.
Related docs
../hub/README.md../web/README.md