* refactor(agy): isolate the stream-json transport in its own module
Move everything only the stream-json driver uses into
cli/src/agy/legacyStreamJson/: the driver and stream process, the NDJSON
parser, the conversation-DB model and title readers, the transcript entry
types, and the agy transcript producer that lived on ApiSessionClient as
sendAgySessionMessage. The driver now registers its own queued-message
cancel handler for batches held in its retry backoff instead of reaching
through AgySession.
The loop runs the remote session through agyRemoteLauncher, the one place
that picks a transport; it is the only importer of the new module. No
behavior change.
* feat(acp): report soft-steer usage and prompt timing to the caller
Antigravity ends a steered session/prompt request early and reports each
request's share of the turn in its own response. Let soft-steer callers
receive that usage so they can total it for the turn.
prompt() waits for earlier output before it sends and for late output
after the answer. Callers can now learn when the request was sent and
answered, and a soft steer exposes when it was answered, so they can time
the agent itself and run their own timers on its answers.
* fix(acp): keep the JSON-RPC error code on failed requests
A rejected request lost the agent's error code, and the soft-steer failure
log printed the Error as {}. The rejection now carries code and data, and
the log keeps the message and code.
* feat(agy): run Antigravity on agy acp when agy supports it
agy 1.5.0 added an ACP server. When `agy --version` reports 1.5.0 or
newer, agyRemoteLauncher runs the session on a new ACP launcher over the
shared AcpSdkBackend; older agy, or a version that cannot be read
(pre-release of 1.5.0, missing binary, no answer), keeps the stream-json
driver and says why in the session. The check and the stream-json
launcher live in legacyStreamJson/, behind one call.
On ACP, one agy acp process serves the session. The agy conversation id is
the ACP session id, so stored agySessionId values resume through
session/resume without replay, whichever transport started them. The
launcher marks the session with agyProtocol 'acp' in metadata; the
stream-json launcher removes a stale marker.
- Model and effort apply per turn through session/set_model with agy's
<model>-<effort> ids; clearing the model returns to agy's default. The
mode is sent every turn, since agy can change it on its own.
- A queued message counts as delivered once agy takes it (its echo,
output, or answer), or when it goes back to the composer.
- Permission modes map to ACP session modes. agy approval requests reach
HAPI through the shared ACP permission handler. agy titles a
run_command request with the command line, so the handler's name hints
for HAPI's own MCP tools (change_title, think, ...) are turned off for
agy; otherwise a command such as `grep think notes.md` would skip the
approval prompt. Automatic approvals pick a one-time option, because the
agy process outlives mode switches, and agy question requests always
wait for the user.
- Titles come from session_info_update, and each turn reports one usage
total built from the prompt responses.
- If the agy process dies, the next turn restarts it and resumes the
conversation (the transport now reports whether its process is alive).
A restart that fails part way leaves no half-started process in use;
the next turn tries again. A prompt agy never started is restored to
the composer.
* feat(agy): add accept-edits and plan permission modes
agy has default, accept-edits, and plan execution modes. Expose
accept-edits and plan as acceptEdits and plan next to request-review
(agy's default mode) and always-proceed. On agy acp they switch per turn
through session/set_mode without restarting agy; the stream-json driver
passes them as --mode, so a change restarts its process like other
launch settings. The iOS and Android catalogs mirror the new list.
* feat(agy): steer queued messages into the running turn
agy acp folds a second session/prompt into the running turn. Register the
SteerQueuedMessage handler in the agy ACP launcher and open the steering
gate for agy sessions whose metadata says agyProtocol 'acp'; stream-json
sessions stay queue-only. The launcher publishes the marker and registers
the handler before it starts agy, so the hub knows the protocol before any
turn can take a steer; until then the hub tells a steer on an agy session
that Steer is not available yet, rather than listing other flavors.
agy answers the request a steer interrupts at once (end_turn) while the
turn continues under the steer, and it lets a running tool call finish.
So the launcher keeps the turn, its steeringActive state, and thinking
until every open prompt request settles, and totals usage across them;
usage from a steer answered after its turn ended is not reported again.
agy echoes a steer as a user_message_chunk when it folds it in. The ACP
backend now reports those echoes after flushing the output before them,
and the launcher commits the steer when the echo text that follows the
prompt's own echo matches it (whitespace-insensitive; the longest steer
text wins when one contains another), so the message lands in the transcript where
it entered the turn rather than after the final answer. Each steer
resolves once (echoed or answered, held, or put back). agy rejects a
prompt while an approval is open, so a steer is refused then and the
message stays queued.
Stop applies to the whole turn lifetime. It withdraws Steer at once and
refuses steers that arrive after it. The turn is registered before agy
restarts or switches settings, so a Stop before the prompt is sent puts
it back in the composer, and a prompt still waiting to send is cancelled
as soon as it reaches agy. agy answers a cancelled prompt with a normal
`cancelled` result; when it produced no output, the prompt also goes back
to the composer. agy answers open requests with `cancelled` and
ends open tool calls; the turn's handler stays active so those final tool
updates still render. A steer cancelled before its echo is held for an
explicit Retry or Cancel, as for Cursor. A steer agy never answers is
dropped after a grace period: its row is held the same way and the agy
process is stopped (late permission requests are cancelled, not
approved), and the next turn restarts it. If agy ignores the cancel, its
process is stopped after a timeout in the same way.
* feat(agy): report and fall back when agy acp fails to start
An agy older than 1.5.0 never reaches this path: the version check in the
selection seam already runs it on stream-json. On 1.5.0 or newer, agy acp
can still fail to start or to open the conversation, for example when agy
is not signed in, the ACP install is broken, or the process exits during
start-up. The session used to end as crashed, without the reason.
The launcher now sends the reason to the chat, and the selection seam runs
the session on the stream-json driver instead, saying in the session that
Steer is not available. Only start failures fall back: errors after agy
acp is up end the session as before, and a kill during start-up is
neither reported as a failure nor falls back. The fallback stays in the
selection seam and legacyStreamJson/.
* feat(agy): show per-turn usage in the response footer
On agy acp each turn ends with a round summary: input, output, thinking,
cache-read and total tokens (summed across the requests of a steered
turn), the model, and agy's own time from sending the prompt to its last answer
(HAPI's waits before sending and for late output are left out), and
tok/s. agy reports no per-step timing, so generation time is that round
time minus the spans spent running tools or waiting for the user
(overlaps counted once), and generated tokens are output plus thinking,
as for OpenCode. The web footer renders it like the
other round summaries.
agy's usage adds up every model call of a request and agy sends no
usage_update, so it is not a context size. The turn's usage therefore no
longer goes out as a token_count for the context indicator, which stays
empty as it is for agy on stream-json.
* fix(agy): keep the session when Stop arrives while no turn is running
Stop aborts the queue wait and replaces the abort controller. The main
loop then checked the new controller's signal, found it not aborted, and
left the loop, so a late or repeated Stop after a turn had ended closed
the session and disconnected agy. The loop now checks the signal its
wait used and keeps waiting for the next message.
* fix(agy): confirm a steer only at its echo
A later steer makes agy answer an earlier steer's request at once
(end_turn) while the tool call and the turn go on, before agy has folded
the earlier steer in. Taking that answer as delivery marked the message
consumed, so a Stop before its echo left it without Retry or Cancel.
A steer is now confirmed when agy echoes it. An answer without an echo
counts only when the turn ends: confirmed if the turn ended without a
Stop, held for Retry or Cancel after one.
* fix(agy): hold unechoed steers when agy is lost mid-turn
An early-answered steer was confirmed when its turn ended without a Stop.
If agy exited before echoing it (for example when a later steer answered
its request and then the process died), the turn still ended without a
Stop, so the steer was marked consumed although agy may never have folded
it in, and Retry or Cancel was gone.
A steer request that fails with a lost transport now marks agy as lost
for the turn, and an early-answered steer without an echo is confirmed
only when the turn ends cleanly: no Stop and no lost agy process.
Otherwise it is held for Retry or Cancel.
* test(agy): pin how each steer outcome is decided
Cover the steer paths that had no test: a control command or a message
that left the queue is refused; a steer whose delivery state cannot be
recorded, or whose request agy loses while starting or writing it, is
held for Retry or Cancel; a steer sent while agy restarts stays queued
and runs next; an early-answered steer echoed before a Stop stays
confirmed; a steer agy rejects after a Stop goes back to the queue; the
main prompt stays delivered when Stop leaves a steer agy may have taken;
and an open steer is held when agy ignores the cancel or the session is
killed.
* fix(agy): confirm every steer that one echo chunk carries
When agy echoed two pending steers in one user_message_chunk, the first
match cleared every steer's echo text, so the other steer was not
confirmed at its echo. It was confirmed only when the turn ended, and a
Stop before then held it for Retry although agy had taken it. A match now
uses up only its own text, and the remaining steers keep matching.
* fix(agy): keep matching the prompt's echo after a stray echo
An echo chunk that did not continue the prompt (for example a late echo
from the previous turn) ended the wait for the prompt's own echo. The
prompt's echo that followed was then matched against the steers, so a
steer whose text the prompt contains could be confirmed before agy took
it. Such a chunk is now checked against the steers only, and the prompt's
echo is still recognized when it comes.
* fix(agy): settle the running turn before a kill returns
The runner ends the session and closes the client as soon as kill()
returns. kill() only cancelled the turn and disconnected agy, so a prompt
that was still waiting to send, or whose cancelled answer was still
draining, put itself back in the composer (or was confirmed) only after
that, and those events were lost; the session end could then record the
prompt as delivered without restoring it.
kill() now waits for the running turn to settle after disconnecting agy,
bounded to a few seconds so an agy that never settles cannot hold the
session end. Archive and runner stop both end the session through kill();
leaving remote mode does not apply to agy, and a normal exit waits for
the turn in the main loop.
* fix(web): choose the Antigravity permission mode when creating a session
The create form still showed Antigravity's old YOLO toggle, so a new
session could only start in request-review or always-proceed, although
the session mode picker offers request-review, acceptEdits, plan and
always-proceed. Antigravity now uses the same native permission select
as the other agents, filled from the shared mode catalog, and the chosen
mode is sent with the spawn.
The default stays as before: a stored YOLO toggle carries over
(on → always-proceed, off → request-review), otherwise the hub's default
applies, mapped onto agy's modes. Fallbacks that used the literal
'default' mode, which agy does not have, now ask the shared catalog for
the flavor's default instead.
hapi-hub
Telegram bot + HTTP API + realtime updates for hapi hub.
What it does
- Telegram bot for notifications and the Mini App entrypoint.
- HTTP API for sessions, messages, permissions, machines, and files.
- Server-Sent Events stream for live updates in web and native clients.
- Socket.IO channel for CLI connections.
- Serves the web app from
web/distor embedded assets in the single binary; network-relay mode uses the separately hosted official web app. - Persists state in SQLite via
bun:sqlite.
Configuration
See src/configuration.ts for all options.
Required
CLI_API_TOKEN- Base shared secret used by CLI, web login and native pairing. Clients append:<namespace>for isolation. Auto-generated on first run if not set.
Optional (Telegram)
TELEGRAM_BOT_TOKEN- Token from @BotFather.HAPI_PUBLIC_URL- Public HTTPS URL for Telegram Mini App access. Also used to derive default CORS origins for the web app.
Optional (Voice)
Dictation and voice-assistant provider keys can also be added from Settings → Voice (stored in settings.json under providerCredentials; env vars still win when set at process start).
ELEVENLABS_API_KEY- ElevenLabs API key for voice assistant + dictation.ELEVENLABS_AGENT_ID- Custom ElevenLabs agent ID (auto-created if not set).GEMINI_API_KEY/GOOGLE_API_KEY- Gemini Live voice assistant.DASHSCOPE_API_KEY/QWEN_API_KEY- Qwen Realtime voice assistant.VOICE_BACKEND- Default assistant backend (elevenlabs,gemini-live, orqwen-realtime).OPENAI_API_KEY- OpenAI dictation (gpt-transcribe/gpt-live-transcribe).DEEPGRAM_API_KEY- Deepgram dictation (nova-3, standard and realtime).GROQ_API_KEY- Groq dictation (whisper-large-v3).TRANSCRIPTION_BASE_URLandTRANSCRIPTION_MODEL- OpenAI-compatible/local transcription endpoint and model.TRANSCRIPTION_API_KEY- Optional bearer token for the OpenAI-compatible endpoint.
Optional (automatic session titles)
When the configured OpenAI-compatible title provider is available, the Hub performs one best-effort automatic title suggestion after the first completed turn when the session has no manual name or existing summary. Automatic failures are silent and never block the agent conversation. The manual Generate action remains available.
Configure HAPI_TITLE_PROVIDER_BASE_URL, HAPI_TITLE_PROVIDER_API_KEY, and
HAPI_TITLE_PROVIDER_MODEL on the Hub. The attempt is persisted across restarts;
manual or Agent titles arriving during generation are preserved. No automatic
request is made without a configured provider.
Optional
HAPI_LISTEN_HOST- HTTP bind address (default: 127.0.0.1).HAPI_LISTEN_PORT- HTTP port (default: 3006).CORS_ORIGINS- Comma-separated origins, or*.HAPI_HOME- Data directory (default: ~/.hapi).DB_PATH- SQLite database path (default: HAPI_HOME/hapi.db).TELEGRAM_NOTIFICATION- Enable/disable Telegram notifications (default: true).HAPI_RELAY_API- Relay API domain (default: relay.hapi.run).HAPI_RELAY_AUTH- Explicit relay auth key. By default the hub obtains and persists an individually revocable key from the relay. A persisted key rejected with HTTP 403 is discarded and reissued once; an explicitly configured environment key must be updated manually.HAPI_RELAY_FORCE_TCP- Force TCP relay mode (true/1).VAPID_SUBJECT- Contact email/URL for Web Push.HAPI_ANDROID_PUSH-auto(default: direct FCM when credentials are configured, otherwise relay),relay,fcm, oroff.FCM_SERVICE_ACCOUNT_PATH- Service-account JSON for private Firebase builds; the app must use the same project. Invalid configured credentials disable Android push instead of switching projects.HAPI_IOS_PUSH-relay(default),apns, oroff.HAPI_PUSH_RELAY_URL- Shared Android/iOS push relay (default:https://push.hapi.run; persisted asiosPushRelayUrl). Independent of the--relaynetwork tunnel.HAPI_SESSION_IDLE_TIMEOUT_MS- Keep-alive-idle window in ms (default: 43200000 / 12 h;0disables). See "Session liveness" below.
Official native apps register their encryption keys automatically; no push provider setup is needed on a fresh hub. See the native companion push contract.
Running
Binary (single executable):
export TELEGRAM_BOT_TOKEN="..."
export CLI_API_TOKEN="shared-secret"
export HAPI_PUBLIC_URL="https://your-domain.example"
hapi hub
hapi server remains supported as an alias.
For web/native clients + CLI, you can omit TELEGRAM_BOT_TOKEN.
To enable Telegram, set TELEGRAM_BOT_TOKEN and HAPI_PUBLIC_URL, start the hub, open /app
in the bot chat, and bind the Mini App with CLI_API_TOKEN:<namespace> when prompted.
From source:
bun install
bun run dev:hub
HTTP API
The following is an overview. See the client contract
for request/response shapes and error semantics, and src/web/routes/ for all endpoints.
Authentication (src/web/routes/auth.ts, src/web/routes/bind.ts)
POST /api/auth- Get JWT token (Telegram initData orCLI_API_TOKEN[:namespace]).POST /api/bind- Bind a Telegram account using initData +CLI_API_TOKEN:<namespace>.
Sessions (src/web/routes/sessions.ts)
GET /api/sessions- List all sessions. The default order is global-pinned, project-pinned, thenlastUserMessageAt ?? createdAtdescending (creation time and ID break ties);?order=updatedAtrequests pure recency. Each summary includeshasConversationContent, derived from stored conversation messages (not titles or lifecycle events); full session SSE updates carry changes to this flag. See the client contract for the wire-level ordering rules.GET /api/sessions/:id- Get session details.POST /api/sessions/:id/abort- Abort session.POST /api/sessions/:id/switch- Hand off session control to the web.POST /api/sessions/:id/resume- Resume inactive session.POST /api/sessions/:id/reopen- Reopen a session; follow the returned session ID.POST /api/sessions/:id/clear- Start a fresh conversation when supported.POST /api/sessions/:id/upload- Upload file (base64, max 50MB).POST /api/sessions/:id/upload/delete- Delete uploaded file.POST /api/sessions/:id/archive- Archive active session. Runner-owned sessions wait for verified cleanup, including retries after an early inactive/archived update. Concurrent requests join the same operation. Cleanup confirmation has a 90-second budget; failure returns a structuredarchive-cleanup-unconfirmed(409),archive-cleanup-unavailable(503), orarchive-cleanup-timeout(504) error. A timeout does not cancel Runner cleanup or prove the process is still alive; retry to verify the final result.PATCH /api/sessions/:id- Rename session.DELETE /api/sessions/:id- Delete inactive session.GET /api/sessions/:id/slash-commands- List slash commands.GET /api/sessions/:id/skills- List skills.POST /api/sessions/:id/permission-mode- Set permission mode.POST /api/sessions/:id/model- Set model preference.POST /api/sessions/:id/effort- Set effort for Claude, Grok, or Pi; other config controls are flavor/capability-gated (see the client contract).GET/POST /api/sessions/:id/scratchlist- Read/create Hub-persisted scratchlist entries; update/delete and attachment routes share this prefix.
Messages (src/web/routes/messages.ts)
GET /api/sessions/:id/messages- Get messages (paginated).POST /api/sessions/:id/messages- Send message.POST /api/sessions/:id/messages/queued-state- Reconcile queued, indeterminate, and invoked local IDs.DELETE /api/sessions/:id/messages/:messageId- Cancel a queued message.POST /api/sessions/:id/messages/:messageId/steer- Steer a queued message when the session supports it.POST /api/sessions/:id/messages/:messageId/retry- Explicitly retry indeterminate delivery when safe; never auto-replay.
Permissions (src/web/routes/permissions.ts)
POST /api/sessions/:id/permissions/:requestId/approve- Approve permission.POST /api/sessions/:id/permissions/:requestId/deny- Deny permission.
Machines (src/web/routes/machines.ts)
GET /api/machines- List online machines.PATCH /api/machines/:id- Set/clear the machine display name.GET /api/machines/:id/agent-availability- List installed/configured Agents.POST /api/machines/:id/spawn- Spawn new session on machine.POST /api/machines/:id/list-directory- Browse runner-scoped directories.POST /api/machines/:id/paths/exists- Check if path exists.POST /api/machines/:id/restart-runner- Request runner restart (requires an available restart path).
Usage (src/web/routes/usage.ts)
GET /api/usage/summary- Get cache-aware token usage for the owner namespace (range=7d|30d|all).
Activity (src/web/routes/activity.ts)
GET /api/activity- When agents in the caller's namespace were working (since/untilepoch ms, default last 24 h, max 31 days): each session's turns from thesession_turnstable, plus the permission prompts and questions it waited on. Used byhapi usage.
Storage (src/web/routes/storage.ts)
GET /api/storage/sqlite- SQLite database/WAL/SHM sizes for the owner namespace.
Git/Files (src/web/routes/git.ts)
GET /api/sessions/:id/git-status- Git status.GET /api/sessions/:id/git-diff-numstat- Diff summary.GET /api/sessions/:id/git-diff-file- File-specific diff.GET /api/sessions/:id/file- Read file content.GET /api/sessions/:id/files- File search with ripgrep.
For inactive sessions, including archived sessions, these read-only file and Git operations fall back to
the matching online Runner when it advertises workspace-file-access. The
Runner reads the current workspace under its configured roots; HAPI does not
copy or snapshot files during archive.
Events (src/web/routes/events.ts)
GET /api/events- SSE stream for live updates.POST /api/visibility- Report client visibility state.
Voice (src/web/routes/voice.ts)
POST /api/voice/token- Get ElevenLabs conversation token.GET /api/voice/backend- Discover configured assistant backends.GET /api/voice/voices- List voices for the selected backend.GET/PUT /api/voice/transcription/credentials- Read masked provider settings or update credentials (owner-only).GET /api/voice/transcription/providers- List configured providers and supported modes.POST /api/voice/transcription- Transcribe a bounded recording.POST /api/voice/transcription/realtime-token- Mint a short-lived OpenAI, ElevenLabs, or Deepgram credential.
Push Notifications (src/web/routes/push.ts)
GET /api/push/vapid-public-key- Get VAPID public key.POST /api/push/subscribe- Subscribe to push notifications.DELETE /api/push/subscribe- Unsubscribe.
Native Android/iOS registration uses POST/DELETE /api/devices/register
(src/web/routes/devices.ts); see the native push contract.
CLI (src/web/routes/cli.ts)
POST /cli/sessions- Create/load session.GET /cli/sessions/:id- Get session by ID.POST /cli/machines- Create/load machine.GET /cli/machines/:id- Get machine by ID.
Socket.IO
See src/socket/handlers/cli/index.ts and src/socket/handlers/terminal.ts for event handlers.
Namespaces: /cli (raw CLI access token) and /terminal (client JWT).
Ordinary web/native session updates use SSE, not the CLI Socket.IO namespace.
Client events (CLI to hub)
message- Send message to session.update-metadata- Update session metadata.update-state- Update agent state.session-alive- Keep session active.session-ready- Cursor ACPsession/load(ornewSession) succeeded; hub defers merge/dedup until this arrives on reopen.session-end- Mark session ended.machine-alive- Keep machine online.rpc-register- Register RPC handler.rpc-unregister- Unregister RPC handler.
Terminal events (web to hub, /terminal)
terminal:create- Open terminal for session.terminal:write- Send input.terminal:resize- Resize dimensions.terminal:close- Close terminal.agent-terminal:subscribe/agent-terminal:unsubscribe- Attach/detach the wrapped agent's terminal stream.agent-terminal:input/agent-terminal:resize- Interact with that terminal when supported.
Hub events (hub to CLI clients, /cli)
update- Broadcast session/message updates.rpc-request- Incoming RPC call.
See src/socket/rpcRegistry.ts for RPC routing.
Telegram Bot
See src/telegram/bot.ts for bot implementation.
Commands
/start- Welcome message with Mini App link./app- Open Mini App.
Features
- Permission request notifications with approve/deny buttons.
- Session ready notifications.
- Deep links to Mini App sessions.
See src/telegram/callbacks.ts for button handlers.
Core Logic
See src/sync/syncEngine.ts for the main session/message manager:
- In-memory session cache with versioning.
- Message pagination and retrieval.
- Permission approval/denial.
- RPC method routing via Socket.IO.
- Event publishing to SSE and Telegram.
- Git operations and file search.
- Activity tracking and timeouts.
Session liveness
Two separate signals, deliberately (tiann/hapi#1820):
active/activeAt- transport. The CLI socket is connected;session-aliverefreshes it every ~2 s.sessionCache.expireInactivedropsactiveafter 30 s of silence.metadata.lifecycleState- agent health.running->idle->running, plusarchived.
Keep-alives prove a socket, not an agent. A session can therefore heartbeat for days with no messages, no thinking and no background tasks - active: true forever, which expireInactive can never catch. sessionCache.reconcileKeepaliveIdle (same 5 s tick) closes that gap: after HAPI_SESSION_IDLE_TIMEOUT_MS with no agent progress it moves lifecycleState running -> idle.
activeis left alone on purpose. The CLI really is reachable, and flipping it would letresumeSessionspawn a second agent against a live process, and unlock dedup-merge / delete on it.- Progress means a message in either direction, a queued prompt, or a background task - never a keep-alive. Sessions that are thinking, running background tasks or holding a pending permission request are never marked.
idlereverts torunningon the next progress, within one tick.metadata.idleReconcileExempt: trueopts a session out entirely.
Storage
See src/store/index.ts for SQLite persistence:
- Sessions with metadata and agent state.
- Messages with pagination support.
- Machines with runner state.
- Todo extraction from messages.
- Users table for Telegram bindings (includes namespace).
- Scratchlist entries/attachments, usage, work graph, and push registrations.
Message content is stored via src/store/contentCodec.ts: oversized strings
inside agent messages (giant tool output) are head+tail truncated at ingest,
and payloads ≥256 chars are zstd-compressed (TEXT = plaintext JSON, BLOB =
zstd). User prompts are never truncated — queued rows are delivered to the CLI
verbatim.
Maintenance scripts (run with the hub stopped before swapping files):
scripts/compact-db.ts— retroactively truncate + compress + VACUUM an existing DB into a new file (the source is only opened read-only).scripts/cleanup-sessions.ts— bulk-delete sessions by message count, path glob, or first-message pattern.
Source structure
src/web/- HTTP service and routes.src/socket/- Socket.IO setup and handlers.src/socket/handlers/cli/- Modular CLI handlers.src/telegram/- Telegram bot.src/sync/- Core session/message logic.src/store/- SQLite persistence.src/sse/- Server-Sent Events.src/config/- Configuration loading and generation.src/notifications/- Push and Telegram notifications.src/visibility/- Client visibility tracking.
Security model
Access is controlled by:
- Telegram initData verification plus bound Telegram users (bound via
CLI_API_TOKEN:<namespace>). CLI_API_TOKENbase secret for CLI and browser access (namespace is appended by clients).
Transport security depends on HTTPS in front of the hub.
Build for deployment
From the repo root:
bun run build:hub
bun run build:web
The hub build output is hub/dist/index.js, and the web assets are in web/dist.
Networking notes
- Telegram Mini Apps require HTTPS and a public URL. If the hub has no public IP, use Cloudflare Tunnel or Tailscale and set
HAPI_PUBLIC_URLto the HTTPS endpoint. - If the web app is hosted on a different origin, set
CORS_ORIGINS(orHAPI_PUBLIC_URL) to include that static host origin.
Standalone web hosting
The web UI can be hosted separately from the hub (for example on GitHub Pages or Cloudflare Pages):
- Build and deploy
web/distfrom the repo root. - Set
CORS_ORIGINS(orHAPI_PUBLIC_URL) to the static host origin. - Open the static site, click the Hub button on the login screen, and enter the hapi hub origin.
Leaving the hub override empty preserves the default same-origin behavior when the hub serves the web assets directly.