diff --git a/README.md b/README.md index 1cd7434..bdbf98d 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,7 @@ # @helloagentai/hermes -A bridge that lets HelloAgent users chat with their personal Hermes agent. +A bridge that lets HelloAgent users chat with their personal local agent +(Hermes, or any agent that speaks the agent-socket protocol). ## What this is @@ -8,16 +9,16 @@ A bridge that lets HelloAgent users chat with their personal Hermes agent. HelloAgent client (web / iOS) │ ▼ WebSocket, ha_* token - HelloAgent relay (Go) + HelloAgent server │ - ▼ WebSocket, ha_* token (relay-side: this bridge looks like - ┌────────────────────┐ an agent named e.g. @alice/hermes) + ▼ WebSocket, ha_* token (this bridge looks like an agent + ┌────────────────────┐ named e.g. @alice/hermes) │ helloagent-hermes │ │ (this package) │ └────────────────────┘ │ - ▼ wschat protocol (JSON over WS, ws://127.0.0.1:8770) - Hermes gateway with wschat plugin + ▼ agent-socket protocol (JSON over WS, ws://127.0.0.1:8770) + Local agent process (e.g. Hermes) │ ▼ Agent loop (LLM, tools, memory) @@ -25,99 +26,117 @@ A bridge that lets HelloAgent users chat with their personal Hermes agent. The bridge holds two things at once: -1. **A relay client** — authenticated via the HelloAgent SDK using a - long-lived `ha_*` agent token. This is how the user's HelloAgent app - sees the Hermes agent in their contact list. -2. **A wschat WebSocket server** — listens on `ws://127.0.0.1:8770` for the - Hermes `wschat` plugin to connect. +1. **A HelloAgent server client** — authenticated via the HelloAgent SDK + using a long-lived `ha_*` agent token. This is how the user's HelloAgent + app sees your agent in their contact list. +2. **An agent socket** — listens on `ws://127.0.0.1:8770` for one local + agent process to connect. -Inbound messages from the user flow relay → bridge → wschat → Hermes. -Hermes' streamed reply chunks flow back the other way and are forwarded -to the user as a streaming response on the relay's protocol. +Inbound messages flow HelloAgent server → bridge → agent. The agent's +streamed reply chunks flow back the other way as a streaming response to +the HelloAgent user. -## Auth - -The pairing flow mirrors [`@helloagentai/openclaw`](https://www.npmjs.com/package/@helloagentai/openclaw). Three paths, identical UX: - -1. **Browser PKCE OAuth** (default for `pair`) — opens a browser to - `/oauth/connect`, captures the redirect on a loopback server, - exchanges the code for an access token, calls `linkChannel()` to mint - a scoped `ha_*` agent token, persists creds. -2. **Device code** (`--device`) — for headless/CI machines. Print a - user code, the user approves it from any other browser. -3. **Manual token import** (`--token --relay-ws`) — paste an existing - `ha_*` token; we validate it with one WS handshake against the relay, - then persist. - -> The relay's `channelProviders` map currently knows only `"openclaw"`, so -> internally we link as the `openclaw` provider for now. Functionally -> identical for the bridge — when the relay registers `"hermes"` as a -> provider this becomes a two-line change in -> [`auth/login-oauth.ts`](src/auth/login-oauth.ts) and -> [`auth/login-device.ts`](src/auth/login-device.ts). - -Credentials are persisted at `~/.helloagent-hermes/credentials//creds.json` -with `chmod 0600`, atomic temp-file + rename, and a `.bak` of the prior -file. Override the state dir with `HA_HERMES_BRIDGE_DIR`. +> On Hermes' side the agent-socket protocol is currently exposed via a +> plugin called `wschat` (it implements this exact wire format). Future +> Hermes versions may rename it to match this rebrand. ## Quickstart ```bash npm install -g @helloagentai/hermes +helloagent-hermes pair +``` -# 1) Pair with HelloAgent -helloagent-hermes pair --agent-name jarvis +The CLI prompts you to paste an agent token: -# Or for a headless box: -helloagent-hermes pair --device --agent-name jarvis +``` +Link this bridge to a HelloAgent account: -# Or to import an existing token: -helloagent-hermes pair --token ha_xxx \ - --relay-ws wss://api.helloagent.cc/v1/ws + 1. Open https://app.helloagent.cc/app/agents/new + 2. Create an agent and copy its token (starts with "ha_") + 3. Paste the token below -# 2) Start the bridge -helloagent-hermes run --port 8770 +Token: ha_xxxxxxxxxxxxx -# 3) Tell Hermes to use it -# (assumes the Hermes wschat plugin is installed under ~/.hermes/plugins/wschat -# and platforms.wschat.enabled: true is set in ~/.hermes/config.yaml) -WSCHAT_URL=ws://127.0.0.1:8770 hermes gateway run +imported token for @alice/jarvis +✓ Connected to HelloAgent as @alice/jarvis. + You can now chat with your agent through the HelloAgent app or browser. ``` -Now any HelloAgent user can DM `@/jarvis` and chat with Hermes. +Then in Hermes (with the `wschat` plugin installed at +`~/.hermes/plugins/wschat`), set `platforms.wschat.enabled: true` and the +plugin's URL to `ws://127.0.0.1:8770/agent` in `~/.hermes/config.yaml`, +and restart `hermes gateway`. Now any HelloAgent user can DM +`@/` and chat with your Hermes. + +For non-interactive use (CI, scripting): + +```bash +helloagent-hermes pair --token ha_xxxxxxxxxxxxx +``` + +## Auth + +Pairing is one step: paste an `ha_*` agent token. The bridge validates it +with one WebSocket handshake against the HelloAgent server, persists it +to disk, and uses it from then on. + +You create the agent (and get the token) on the web at +[`https://app.helloagent.cc/app/agents/new`](https://app.helloagent.cc/app/agents/new). +The web UI handles agent registration; this CLI just consumes the +resulting token. + +Credentials persist at +`~/.helloagent-hermes/credentials//creds.json` with `chmod +0600`, atomic temp-file + rename, and a `.bak` of the prior file. Override +the state dir with `HA_HERMES_BRIDGE_DIR`. ## CLI ``` -helloagent-hermes pair [--device | --token --relay-ws ] - [--agent-name ] [--api-url ] [--web-url ] - [--account ] -helloagent-hermes run [--port ] [--host ] [--wschat-token ] - [--account ] +helloagent-hermes pair [--token ] [--account ] [--re-pair] helloagent-hermes status +helloagent-hermes stop helloagent-hermes logout [--account ] ``` -Environment variables: +`pair` pairs if needed, starts the bridge as a background daemon, waits +until it is connected to HelloAgent, and then returns. Use `status` to see +whether the daemon is running and `stop` to shut it down. + +## Configuration + +Defaults are baked in for the common case: + +| Setting | Default | +|---|---| +| API URL | `https://api.helloagent.cc` | +| Server WS | `wss://api.helloagent.cc/v1/ws` | +| Bind | `ws://127.0.0.1:8770` | + +Env-var overrides if you really need them (local dev mostly): -| Var | Default | Use | -|---|---|---| -| `HA_HERMES_BRIDGE_DIR` | `~/.helloagent-hermes` | State dir | -| `HA_HERMES_BRIDGE_AUTH_DIR` | `/credentials` | Cred dir override | -| `HA_HERMES_BRIDGE_API_URL` | `https://api.helloagent.cc` | Default `--api-url` (override for local relay dev) | -| `HA_HERMES_BRIDGE_WEB_URL` | `https://app.helloagent.cc` | Default `--web-url` (override for local web dev) | -| `HA_HERMES_BRIDGE_CLIENT_ID` | `helloagent-hermes` | OAuth client id | -| `HA_HERMES_BRIDGE_DEBUG` | unset | Verbose logs | +| Var | Use | +|---|---| +| `HA_HERMES_BRIDGE_DIR` | State dir (default `~/.helloagent-hermes`) | +| `HA_HERMES_BRIDGE_AUTH_DIR` | Credential dir override | +| `HA_HERMES_BRIDGE_API_URL` | Override REST API URL (e.g. local HelloAgent server) | +| `HA_HERMES_BRIDGE_SERVER_WS` | Override server WS URL (e.g. local HelloAgent server) | +| `HA_HERMES_BRIDGE_HOST` | Bind host (default `127.0.0.1`) | +| `HA_HERMES_BRIDGE_PORT` | Bind port (default `8770`) | +| `HA_HERMES_BRIDGE_TOKEN` | Shared secret the agent must echo in its hello frame | +| `HA_HERMES_BRIDGE_DEBUG` | `1` for verbose logs | ## What's not in scope (yet) -- Multiple concurrent Hermes connections (server is single-tenant). +- Multiple concurrent agent connections (the socket is single-tenant). - Group conversations (DMs only — `chatType=dm`). - Media / files / cards (text only). -- Edits — we advertise `supports: ["typing"]` so Hermes' streamer - auto-downgrades to fresh-send chunks. Each Hermes `send` becomes one +- Edits — we advertise `supports: ["typing"]` so the agent's streamer + auto-downgrades to fresh-send chunks. Each agent `send` becomes one `StreamChunk` back to the user. -- Reactions, read receipts, typing indicators on the relay side. +- Reactions, read receipts, typing indicators on the HelloAgent server + side. ## Layout @@ -126,20 +145,17 @@ src/ ├── auth/ │ ├── store.ts creds.json I/O (chmod 0600, atomic write) │ ├── presence.ts hasAnyAuth probe -│ ├── login.ts PKCE OAuth (browser loopback) -│ ├── login-device.ts device-code flow -│ ├── login-oauth.ts code exchange + linkChannel + persist -│ └── import-token.ts manual ha_* token import +│ └── import-token.ts ha_* token validation + persist ├── core/ │ ├── ha-client.ts per-account managed Agent (lifecycle + status) │ ├── logger.ts namespaced logger │ └── types.ts ResolvedAccount -├── wschat/ -│ ├── server.ts local WS server (single Hermes client) +├── agent-socket/ +│ ├── server.ts local WS server (single agent client) │ ├── types.ts wire frames -│ └── dedup.ts inbound dedup (relay reconnects) -├── bridge.ts wires HaClient ↔ wschat server, streaming bridge -├── cli.ts pair / run / status / logout +│ └── dedup.ts inbound dedup (server reconnects) +├── bridge.ts wires HaClient ↔ agent socket, streaming bridge +├── cli.ts pair / status / logout └── index.ts library re-exports ``` diff --git a/package.json b/package.json index fa2dcf4..9dc0d5a 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@helloagentai/hermes", "version": "0.1.0", - "description": "Bridge between HelloAgent's relay and a Hermes Agent gateway. HelloAgent users chat with their personal Hermes through the same UX as any HelloAgent contact.", + "description": "Bridge between the HelloAgent server and a Hermes Agent gateway. HelloAgent users chat with their personal Hermes through the same UX as any HelloAgent contact.", "license": "MIT", "author": "HelloAgent", "homepage": "https://github.com/helloagentai/helloagent-hermes#readme", @@ -16,17 +16,21 @@ "helloagent", "hermes", "bridge", - "agent", - "relay" + "agent" ], "type": "module", "bin": { "helloagent-hermes": "./dist/cli.js" }, "exports": { - ".": "./dist/index.js" + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js", + "default": "./dist/index.js" + } }, "main": "./dist/index.js", + "types": "./dist/index.d.ts", "files": [ "dist", "README.md", @@ -37,6 +41,7 @@ }, "scripts": { "build": "tsc", + "postbuild": "chmod +x dist/cli.js", "typecheck": "tsc --noEmit", "start": "node ./dist/cli.js", "dev": "tsx src/cli.ts", diff --git a/src/wschat/dedup.ts b/src/agent-socket/dedup.ts similarity index 82% rename from src/wschat/dedup.ts rename to src/agent-socket/dedup.ts index a0ceb7d..054392f 100644 --- a/src/wschat/dedup.ts +++ b/src/agent-socket/dedup.ts @@ -1,8 +1,7 @@ /** - * TTL + LRU dedup for inbound messages from the relay. Prevents - * double-dispatch after relay reconnects (the Agent SDK can replay messages - * within its delivery window). Mirrors the shape used by openclaw-HelloAgent - * but trimmed to the inputs we actually need. + * TTL + LRU dedup for inbound messages from the HelloAgent server. Prevents + * double-dispatch after server reconnects (the Agent SDK can replay messages + * within its delivery window). */ const DEFAULT_TTL_MS = 5 * 60 * 1000; diff --git a/src/wschat/server.ts b/src/agent-socket/server.ts similarity index 83% rename from src/wschat/server.ts rename to src/agent-socket/server.ts index 9a08e1b..6f2b665 100644 --- a/src/wschat/server.ts +++ b/src/agent-socket/server.ts @@ -1,13 +1,13 @@ /** - * Local wschat WebSocket server. Hermes' wschat plugin connects here as a - * client (one connection per Hermes process). We expose a small typed - * surface for the bridge: forward inbound HelloAgent messages → wschat - * `message` frames; receive Hermes outbound `send`/`edit` frames → notify + * Local WebSocket server: the agent process (e.g. Hermes) connects here as + * a client (one connection per agent process). We expose a small typed + * surface for the bridge: forward inbound HelloAgent messages → wire + * `message` frames; receive agent-outbound `send`/`edit` frames → notify * subscribers. * - * Wire protocol matches integrations/hermes-ws-channel/adapter.py. + * Frame shapes live in ./types.ts. On Hermes' side this protocol is + * exposed via a plugin currently called `wschat`. */ -import { randomUUID } from "node:crypto"; import { WebSocketServer, type WebSocket } from "ws"; import { logger } from "../core/logger.js"; @@ -18,9 +18,9 @@ import type { WelcomeFrame, } from "./types.js"; -const log = logger("wschat/server"); +const log = logger("agent-socket"); -export type WschatServerOptions = { +export type AgentSocketOptions = { /** Bind host. Default 127.0.0.1. */ host?: string; /** Bind port. Default 8770. */ @@ -29,7 +29,7 @@ export type WschatServerOptions = { agentId: string; /** Capabilities advertised in `welcome.supports`. */ supports?: ("edit" | "typing")[]; - /** Optional shared secret; if set, Hermes' hello.token must match. */ + /** Optional shared secret; if set, the agent's hello.token must match. */ authToken?: string; }; @@ -37,22 +37,22 @@ export type WschatServerOptions = { * Frames the bridge wants to know about. We do NOT surface ping/pong here — * server handles those itself. */ -export type ClientFrameHandler = (frame: ClientToServer) => void; +type ClientFrameHandler = (frame: ClientToServer) => void; -export type WschatServer = { +export type AgentSocket = { start(): Promise; stop(): Promise; - /** Push an inbound HelloAgent message to the connected Hermes. */ + /** Push an inbound HelloAgent message to the connected agent. */ pushIncoming(msg: IncomingMessageFrame): boolean; - /** Emit an ack for a Hermes-sent msgId. */ + /** Emit an ack for an agent-sent msgId. */ ack(refMsgId: string): boolean; - /** Subscribe to Hermes-sent frames (send/edit/typing/pong). */ + /** Subscribe to agent-sent frames (send/edit/typing/pong). */ onClientFrame(handler: ClientFrameHandler): void; - /** True iff a Hermes plugin has completed the hello/welcome handshake. */ + /** True iff an agent has completed the hello/welcome handshake. */ isReady(): boolean; }; -export function createWschatServer(opts: WschatServerOptions): WschatServer { +export function createAgentSocket(opts: AgentSocketOptions): AgentSocket { const host = opts.host ?? "127.0.0.1"; const port = opts.port ?? 8770; const supports = opts.supports ?? ["typing"]; @@ -82,12 +82,12 @@ export function createWschatServer(opts: WschatServerOptions): WschatServer { safeJson(socket, { type: "error", code: "already_connected", - message: "wschat bridge accepts a single Hermes connection", + message: "agent socket accepts a single agent connection", }); socket.close(); return; } - log.info(`client connected from ${remote ?? "?"}`); + log.info(`agent connected from ${remote ?? "?"}`); active = socket; activeReady = false; @@ -115,7 +115,7 @@ export function createWschatServer(opts: WschatServerOptions): WschatServer { }); socket.on("close", () => { - log.info("client disconnected"); + log.info("agent disconnected"); if (active === socket) { active = null; activeReady = false; @@ -150,7 +150,7 @@ export function createWschatServer(opts: WschatServerOptions): WschatServer { safeJson(socket, welcome); activeReady = true; log.info(`handshake complete (agent=${frame.agent}, version=${frame.version})`); - // Start app-level keepalive ping every 25 s (the plugin replies pong). + // Start app-level keepalive ping every 25 s (the agent replies pong). if (!pingTimer) { pingTimer = setInterval(() => { if (active && active.readyState === active.OPEN) { @@ -236,5 +236,3 @@ function isClientFrame(v: unknown): v is ClientToServer { t === "hello" || t === "send" || t === "edit" || t === "typing" || t === "pong" ); } - -export { randomUUID as newMsgId }; diff --git a/src/wschat/types.ts b/src/agent-socket/types.ts similarity index 85% rename from src/wschat/types.ts rename to src/agent-socket/types.ts index 54c0ce3..5f22236 100644 --- a/src/wschat/types.ts +++ b/src/agent-socket/types.ts @@ -1,9 +1,12 @@ /** - * Wire types for the wschat protocol (matches the Hermes wschat plugin). + * Wire types for the agent-socket protocol. * - * Hermes adapter (client) ↔ this bridge (server): + * Agent adapter (client) ↔ this bridge (server): * client → server: hello, send, edit, typing, pong * server → client: welcome, message, ack, ping, error + * + * On Hermes' side this protocol is currently exposed via a plugin named + * `wschat` — it implements this exact wire format. */ export type HelloFrame = { diff --git a/src/auth/import-token.ts b/src/auth/import-token.ts index 67383b4..b470360 100644 --- a/src/auth/import-token.ts +++ b/src/auth/import-token.ts @@ -1,10 +1,7 @@ /** * Manual fallback: paste an existing HelloAgent ha_* agent token, validate - * by completing one WebSocket auth handshake against the relay, then - * persist it under the bridge's credential dir. - * - * Lifted from openclaw-HelloAgent/src/auth/import-token.ts with imports - * pointed at the bridge-local store. + * by completing one WebSocket auth handshake against the HelloAgent server, + * then persist it under the bridge's credential dir. */ import { Agent, AuthFailedError } from "@helloagentai/sdk"; @@ -18,7 +15,7 @@ import { export type ImportTokenOptions = { token: string; apiUrl: string; - relayWs: string; + serverWs: string; accountId?: string; timeoutMs?: number; onProgress?: (line: string) => void; @@ -29,7 +26,7 @@ export async function importToken(opts: ImportTokenOptions): Promise { const log = opts.onProgress ?? ((s: string) => console.log(s)); const handle = await resolveHandleFromToken( opts.token, - opts.relayWs, + opts.serverWs, opts.timeoutMs, ); const { ownerHandle, agentName } = splitHandle(handle); @@ -41,7 +38,7 @@ export async function importToken(opts: ImportTokenOptions): Promise { ownerHandle, token: opts.token, apiUrl: opts.apiUrl, - relayWs: opts.relayWs, + serverWs: opts.serverWs, linkedAt: new Date().toISOString(), source: "manual", }; @@ -52,7 +49,7 @@ export async function importToken(opts: ImportTokenOptions): Promise { async function resolveHandleFromToken( token: string, - relayWs: string, + serverWs: string, timeoutMs = 30_000, ): Promise { if (!token.startsWith("ha_")) { @@ -62,7 +59,7 @@ async function resolveHandleFromToken( let authFailure: AuthFailedError | undefined; const agent = new Agent({ token, - relayUrl: relayWs, + relayUrl: serverWs, reconnect: { initialMs: 100, maxMs: 100 }, logger: { warn: () => undefined, error: () => undefined }, onAuthFailed: (err) => { @@ -75,7 +72,7 @@ async function resolveHandleFromToken( while (Date.now() < deadline) { if (agent.handle) return agent.handle; if (authFailure) { - throw new Error(`token rejected by relay: ${authFailure.detail}`); + throw new Error(`token rejected by HelloAgent server: ${authFailure.detail}`); } await new Promise((r) => setTimeout(r, 50)); } diff --git a/src/auth/login-device.ts b/src/auth/login-device.ts deleted file mode 100644 index c62e20c..0000000 --- a/src/auth/login-device.ts +++ /dev/null @@ -1,96 +0,0 @@ -/** - * Headless device-code pairing. For machines that can't open a browser: - * print a short user code, the user signs in elsewhere and approves the - * code, the bridge polls until it receives a scoped channel-link token. - * - * Lifted from openclaw-HelloAgent/src/auth/login-device.ts; provider held - * at "openclaw" for now (see ./login-oauth.ts). - */ -import { - HelloAgentApiError, - linkChannel, - oauthPollDeviceToken, - oauthStartDeviceAuthorization, -} from "@helloagentai/sdk"; - -import { - CREDS_VERSION, - DEFAULT_ACCOUNT_ID, - type Creds, - writeCreds, -} from "./store.js"; - -const CHANNEL_PROVIDER = "openclaw"; - -export type DevicePairOptions = { - agentName: string; - clientId: string; - apiUrl: string; - accountId?: string; - timeoutMs?: number; - onProgress?: (line: string) => void; -}; - -const DEFAULT_TIMEOUT_MS = 15 * 60 * 1000; - -export async function pairWithDeviceCode(opts: DevicePairOptions): Promise { - const accountId = opts.accountId ?? DEFAULT_ACCOUNT_ID; - const log = opts.onProgress ?? ((s: string) => console.log(s)); - - const device = await oauthStartDeviceAuthorization({ - clientId: opts.clientId, - apiUrl: opts.apiUrl, - }); - - log(`open ${device.verification_uri}`); - log(`enter code: ${device.user_code}`); - - const deadline = - Date.now() + Math.min(opts.timeoutMs ?? DEFAULT_TIMEOUT_MS, device.expires_in * 1000); - const intervalMs = Math.max(device.interval, 1) * 1000; - let accessToken = ""; - - while (Date.now() < deadline) { - await new Promise((r) => setTimeout(r, intervalMs)); - try { - const tokenResp = await oauthPollDeviceToken({ - clientId: opts.clientId, - deviceCode: device.device_code, - apiUrl: opts.apiUrl, - }); - accessToken = tokenResp.access_token; - break; - } catch (e) { - if (e instanceof HelloAgentApiError && e.code === "authorization_pending") { - continue; - } - throw e; - } - } - - if (!accessToken) { - throw new Error("device authorization timed out"); - } - - const linkResp = await linkChannel({ - provider: CHANNEL_PROVIDER, - token: accessToken, - agentName: opts.agentName, - apiUrl: opts.apiUrl, - }); - - const creds: Creds = { - version: CREDS_VERSION, - handle: linkResp.handle, - agentName: linkResp.agent_name, - ownerHandle: linkResp.user_handle, - token: linkResp.token, - apiUrl: opts.apiUrl, - relayWs: linkResp.relay_ws, - linkedAt: new Date().toISOString(), - source: "device", - }; - await writeCreds(creds, accountId); - log(`linked as @${creds.handle}`); - return creds; -} diff --git a/src/auth/login-oauth.ts b/src/auth/login-oauth.ts deleted file mode 100644 index 089321f..0000000 --- a/src/auth/login-oauth.ts +++ /dev/null @@ -1,75 +0,0 @@ -/** - * OAuth code exchange + channel link + persistence. Takes the authorization - * code captured by the loopback server (./login.ts), trades it for a scoped - * access token, calls `/v1/channels/openclaw/link`, persists the returned - * ha_* token to disk. - * - * NOTE: provider is hardcoded to "openclaw" because the relay's - * `channelProviders` map (relay/internal/api/channels.go) only knows - * "openclaw" today. Functionally identical for our purposes — the relay - * just labels the link that way. Switch to "hermes" once the relay - * registers it. - */ -import { - HelloAgentApiError, - linkChannel, - oauthExchangeToken, -} from "@helloagentai/sdk"; - -import { - CREDS_VERSION, - DEFAULT_ACCOUNT_ID, - type Creds, - writeCreds, -} from "./store.js"; - -const CHANNEL_PROVIDER = "openclaw"; // TODO: switch to "hermes" once relay supports - -export type ExchangeAndPersistOptions = { - code: string; - agentName: string; - clientId: string; - clientSecret?: string; - codeVerifier?: string; - redirectUri: string; - apiUrl: string; - accountId?: string; -}; - -export async function exchangeAndPersist( - opts: ExchangeAndPersistOptions, -): Promise { - const accountId = opts.accountId ?? DEFAULT_ACCOUNT_ID; - - const tokenResp = await oauthExchangeToken({ - code: opts.code, - clientId: opts.clientId, - clientSecret: opts.clientSecret, - codeVerifier: opts.codeVerifier, - redirectUri: opts.redirectUri, - apiUrl: opts.apiUrl, - }); - - const linkResp = await linkChannel({ - provider: CHANNEL_PROVIDER, - token: tokenResp.access_token, - agentName: opts.agentName, - apiUrl: opts.apiUrl, - }); - - const creds: Creds = { - version: CREDS_VERSION, - handle: linkResp.handle, - agentName: linkResp.agent_name, - ownerHandle: linkResp.user_handle, - token: linkResp.token, - apiUrl: opts.apiUrl, - relayWs: linkResp.relay_ws, - linkedAt: new Date().toISOString(), - source: "oauth", - }; - await writeCreds(creds, accountId); - return creds; -} - -export { HelloAgentApiError }; diff --git a/src/auth/login.ts b/src/auth/login.ts deleted file mode 100644 index 74b12b9..0000000 --- a/src/auth/login.ts +++ /dev/null @@ -1,207 +0,0 @@ -/** - * Top-level pairing orchestrator. Drives the OAuth-loopback dance: - * - * 1. Bind a single-use HTTP server on 127.0.0.1:. - * 2. Open the user's browser to /oauth/connect?... with our - * loopback URI as redirect_uri. - * 3. Wait for the browser to hit /oauth/callback?code=...&state=..., - * verify state matches our CSRF token, capture the code. - * 4. Hand off to ./login-oauth#exchangeAndPersist (token + link + persist). - * 5. Close the loopback server, return the persisted creds. - * - * Lifted from openclaw-HelloAgent/src/auth/login.ts with the import of the - * persist-side updated to the bridge's local store. - */ -import { spawn } from "node:child_process"; -import crypto from "node:crypto"; -import http from "node:http"; -import { AddressInfo } from "node:net"; - -import type { Creds } from "./store.js"; -import { exchangeAndPersist } from "./login-oauth.js"; - -export type PairOptions = { - agentName: string; - clientId: string; - /** Optional confidential-client secret. Local relays use PKCE instead. */ - clientSecret?: string; - apiUrl: string; - webUrl: string; - /** Loopback port for the redirect handler. Default 9999. */ - loopbackPort?: number; - /** Loopback path. Default `/cb`. */ - loopbackPath?: string; - accountId?: string; - /** Wait this long for the browser callback before giving up. Default 5min. */ - timeoutMs?: number; - openBrowser?: (url: string) => void; - onProgress?: (line: string) => void; -}; - -const DEFAULT_PORT = 9999; -const DEFAULT_PATH = "/cb"; -const DEFAULT_TIMEOUT_MS = 5 * 60 * 1000; - -export async function pairWithBrowser(opts: PairOptions): Promise { - const port = opts.loopbackPort ?? DEFAULT_PORT; - const cbPath = opts.loopbackPath ?? DEFAULT_PATH; - const redirectUri = `http://127.0.0.1:${port}${cbPath}`; - const state = crypto.randomBytes(16).toString("hex"); - const codeVerifier = newPkceVerifier(); - const codeChallenge = pkceChallenge(codeVerifier); - const log = opts.onProgress ?? ((s: string) => console.log(s)); - - const { code, boundPort } = await captureAuthCode({ - cbPath, - desiredPort: port, - expectedState: state, - timeoutMs: opts.timeoutMs ?? DEFAULT_TIMEOUT_MS, - onListening: (boundPort) => { - const url = buildConsentUrl({ - webUrl: opts.webUrl, - clientId: opts.clientId, - redirectUri: `http://127.0.0.1:${boundPort}${cbPath}`, - scope: "channel:link", - state, - codeChallenge, - }); - log(`open in your browser to authorize:\n ${url}`); - const opener = opts.openBrowser ?? defaultBrowserOpen; - opener(url); - }, - }); - - const effectiveRedirect = - boundPort === port ? redirectUri : `http://127.0.0.1:${boundPort}${cbPath}`; - - log(`code received; exchanging for token…`); - const creds = await exchangeAndPersist({ - code, - agentName: opts.agentName, - clientId: opts.clientId, - clientSecret: opts.clientSecret, - codeVerifier, - redirectUri: effectiveRedirect, - apiUrl: opts.apiUrl, - accountId: opts.accountId, - }); - log(`linked as @${creds.handle}`); - return creds; -} - -type CaptureOptions = { - cbPath: string; - desiredPort: number; - expectedState: string; - timeoutMs: number; - onListening: (boundPort: number) => void; -}; - -function captureAuthCode(opts: CaptureOptions): Promise<{ code: string; boundPort: number }> { - return new Promise((resolve, reject) => { - const server = http.createServer((req, res) => { - const url = new URL(req.url ?? "/", `http://127.0.0.1`); - if (url.pathname !== opts.cbPath) { - res.writeHead(404).end("not found"); - return; - } - const error = url.searchParams.get("error"); - if (error) { - sendHtml(res, "Pairing cancelled", `The bridge did not receive authorization. (${error})`); - cleanup(new Error(`oauth flow returned error: ${error}`)); - return; - } - const code = url.searchParams.get("code"); - const state = url.searchParams.get("state"); - if (!code) { - sendHtml(res, "Missing code", "The redirect carried no authorization code. Try again."); - cleanup(new Error("missing code in callback")); - return; - } - if (state !== opts.expectedState) { - sendHtml(res, "State mismatch", "CSRF guard rejected this redirect. Restart pairing."); - cleanup(new Error("oauth state mismatch (possible CSRF)")); - return; - } - sendHtml( - res, - "You can close this tab", - "The bridge has captured the authorization. Return to your terminal.", - ); - const boundPort = (server.address() as AddressInfo).port; - cleanup(null, { code, boundPort }); - }); - - let timer: NodeJS.Timeout | null = null; - let settled = false; - - function cleanup(err: Error | null, value?: { code: string; boundPort: number }) { - if (settled) return; - settled = true; - if (timer) clearTimeout(timer); - server.close(); - if (err) reject(err); - else if (value) resolve(value); - } - - server.on("error", (err) => cleanup(err)); - server.listen(opts.desiredPort, "127.0.0.1", () => { - const boundPort = (server.address() as AddressInfo).port; - timer = setTimeout( - () => cleanup(new Error(`pairing timed out after ${opts.timeoutMs}ms`)), - opts.timeoutMs, - ); - opts.onListening(boundPort); - }); - }); -} - -function sendHtml(res: http.ServerResponse, title: string, body: string) { - res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }); - res.end(`${title} - -

${title}

${body}

`); -} - -function buildConsentUrl(opts: { - webUrl: string; - clientId: string; - redirectUri: string; - scope: string; - state: string; - codeChallenge: string; -}): string { - const url = new URL("/oauth/connect", opts.webUrl); - url.searchParams.set("client_id", opts.clientId); - url.searchParams.set("redirect_uri", opts.redirectUri); - url.searchParams.set("scope", opts.scope); - url.searchParams.set("state", opts.state); - url.searchParams.set("code_challenge", opts.codeChallenge); - url.searchParams.set("code_challenge_method", "S256"); - return url.toString(); -} - -function newPkceVerifier(): string { - return crypto.randomBytes(32).toString("base64url"); -} - -function pkceChallenge(verifier: string): string { - return crypto.createHash("sha256").update(verifier).digest("base64url"); -} - -function defaultBrowserOpen(url: string): void { - const cmd = - process.platform === "darwin" - ? "open" - : process.platform === "win32" - ? "cmd" - : "xdg-open"; - const args = process.platform === "win32" ? ["/c", "start", "", url] : [url]; - try { - const child = spawn(cmd, args, { stdio: "ignore", detached: true }); - child.on("error", () => undefined); - child.unref(); - } catch { - /* swallow */ - } -} diff --git a/src/auth/store.ts b/src/auth/store.ts index 506623d..b677e1c 100644 --- a/src/auth/store.ts +++ b/src/auth/store.ts @@ -1,7 +1,5 @@ /** - * Persists per-account HelloAgent credentials to disk. Mirrors - * openclaw-HelloAgent/src/core/auth-store.ts but rooted under the bridge's - * own state dir so it doesn't share a directory with OpenClaw. + * Persists per-account HelloAgent credentials to disk. * * Layout: * /credentials//creds.json @@ -17,9 +15,19 @@ import { promises as fs } from "node:fs"; import os from "node:os"; import path from "node:path"; -export const CREDS_VERSION = 1; +export const CREDS_VERSION = 2; export const DEFAULT_ACCOUNT_ID = "default"; +export class CredsFormatError extends Error { + constructor( + message: string, + readonly path: string, + ) { + super(message); + this.name = "CredsFormatError"; + } +} + export type Creds = { version: number; handle: string; @@ -27,7 +35,7 @@ export type Creds = { ownerHandle: string; token: string; apiUrl: string; - relayWs: string; + serverWs: string; linkedAt: string; source?: "oauth" | "device" | "manual"; }; @@ -56,18 +64,77 @@ function backupPath(accountId: string = DEFAULT_ACCOUNT_ID): string { return path.join(accountAuthDir(accountId), "creds.json.bak"); } +function recoveryHint(accountId: string): string { + return `Run 'helloagent-hermes pair --re-pair --account ${accountId}' to re-link, or 'helloagent-hermes logout --account ${accountId}' to delete.`; +} + +function formatError(accountId: string, reason: string): CredsFormatError { + const file = credsPath(accountId); + return new CredsFormatError( + `creds at ${file} ${reason}. ${recoveryHint(accountId)}`, + file, + ); +} + +function validateCreds(parsed: unknown, accountId: string): Creds { + if (typeof parsed !== "object" || parsed === null) { + throw formatError(accountId, "are not a JSON object"); + } + + const candidate = parsed as Partial; + if (candidate.version !== CREDS_VERSION) { + throw formatError( + accountId, + `are version ${String(candidate.version)}, expected ${CREDS_VERSION}`, + ); + } + + const requiredStrings = [ + "handle", + "agentName", + "ownerHandle", + "token", + "apiUrl", + "serverWs", + "linkedAt", + ] as const; + for (const field of requiredStrings) { + if (typeof candidate[field] !== "string" || candidate[field].length === 0) { + const hint = field === "serverWs" + ? "; this looks like an older credentials file" + : ""; + throw formatError(accountId, `are missing ${field}${hint}`); + } + } + + return candidate as Creds; +} + export async function readCreds( accountId: string = DEFAULT_ACCOUNT_ID, ): Promise { try { const raw = await fs.readFile(credsPath(accountId), "utf-8"); - const parsed = JSON.parse(raw) as Creds; - if (parsed.version !== CREDS_VERSION) { - throw new Error(`unsupported creds version: ${parsed.version}`); + return validateCreds(JSON.parse(raw), accountId); + } catch (e) { + if (e instanceof SyntaxError) { + throw formatError(accountId, "contain invalid JSON"); } - return parsed; + if ((e as NodeJS.ErrnoException).code === "ENOENT") return null; + throw e; + } +} + +export async function readCredsLenient( + accountId: string = DEFAULT_ACCOUNT_ID, +): Promise | null> { + try { + const raw = await fs.readFile(credsPath(accountId), "utf-8"); + const parsed = JSON.parse(raw) as Partial; + return typeof parsed === "object" && parsed !== null ? parsed : {}; } catch (e) { if ((e as NodeJS.ErrnoException).code === "ENOENT") return null; + if (e instanceof SyntaxError) return {}; throw e; } } diff --git a/src/bridge.ts b/src/bridge.ts index 576e657..d4fad0e 100644 --- a/src/bridge.ts +++ b/src/bridge.ts @@ -1,15 +1,16 @@ /** - * Bridge wiring: HelloAgent relay ↔ wschat server ↔ Hermes plugin. + * Bridge wiring: HelloAgent server ↔ agent socket ↔ agent (e.g. Hermes). * - * Direction 1 (inbound to Hermes): - * relay → HaClient.onMessage(IncomingMessage) - * → translate to wschat `message` frame - * → push to Hermes via wschat server - * → wait for Hermes' streamed reply (one or more `send` frames keyed - * by chatId, AsyncIterable back to the relay) + * Direction 1 (inbound to the agent): + * HelloAgent server → HaClient.onMessage(IncomingMessage) + * → translate to wire `message` frame + * → push to the agent via the agent socket + * → wait for the agent's streamed reply (one or more `send` frames + * keyed by chatId, AsyncIterable back to the HelloAgent + * server) * - * Direction 2 (outbound from Hermes): - * Hermes → wschat `send`/`edit` frame + * Direction 2 (outbound from the agent): + * agent → `send`/`edit` frame on the agent socket * → bridge maps frame.chatId → recipient handle * → HaClient.send(handle, text) * @@ -20,37 +21,33 @@ * matches push a chunk into that channel; when the chat goes idle for * `responseIdleMs` ms or the channel is explicitly ended, we close it. * - * Edits: we advertise `supports: ["typing"]` only — the Hermes streamer + * Edits: we advertise `supports: ["typing"]` only — the agent's streamer * auto-downgrades to send-fresh chunks. If we ever advertise "edit" we'd * need to coalesce mid-stream edits into a single chunk per turn. */ -import { randomUUID } from "node:crypto"; import type { IncomingMessage } from "@helloagentai/sdk"; import { HaClient } from "./core/ha-client.js"; import { logger } from "./core/logger.js"; import type { ResolvedAccount } from "./core/types.js"; -import { MessageDedup } from "./wschat/dedup.js"; -import { - createWschatServer, - type WschatServer, -} from "./wschat/server.js"; +import { MessageDedup } from "./agent-socket/dedup.js"; +import { createAgentSocket } from "./agent-socket/server.js"; import type { ClientToServer, IncomingMessageFrame, SendFrame, -} from "./wschat/types.js"; +} from "./agent-socket/types.js"; const log = logger("bridge"); export type BridgeOptions = { account: ResolvedAccount; - /** wschat server bind. Default 127.0.0.1:8770. */ + /** Agent socket bind. Default 127.0.0.1:8770. */ host?: string; port?: number; - /** Optional shared secret the Hermes plugin must echo in hello.token. */ - wschatToken?: string; - /** ms of silence after which we consider Hermes' reply complete. Default 1500. */ + /** Optional shared secret the agent must echo in its hello frame. */ + socketToken?: string; + /** ms of silence after which we consider the agent's reply complete. Default 1500. */ responseIdleMs?: number; }; @@ -73,27 +70,27 @@ export function createBridge(opts: BridgeOptions): Bridge { const dedup = new MessageDedup(); const pending = new Map(); // chatId → channel - const server = createWschatServer({ + const server = createAgentSocket({ host: opts.host, port: opts.port, agentId: opts.account.handle, supports: ["typing"], // see module doc — we don't claim edit support - authToken: opts.wschatToken, + authToken: opts.socketToken, }); let haClient: HaClient | null = null; - // Outbound: Hermes wschat frames → relay sends. + // Outbound: agent frames → HelloAgent server sends. server.onClientFrame((frame: ClientToServer) => { if (frame.type === "send") { - handleHermesSend(frame); + handleAgentSend(frame); return; } if (frame.type === "edit") { // We didn't advertise edit; treat any stray edit as a chunk anyway // so we don't lose data, but log a warning. log.warn("received edit frame though edit was not advertised; treating as chunk"); - handleHermesSend({ + handleAgentSend({ type: "send", msgId: frame.msgId, chatId: frame.chatId, @@ -102,13 +99,13 @@ export function createBridge(opts: BridgeOptions): Bridge { return; } if (frame.type === "typing") { - // No relay-side typing indicator yet; logged for visibility. - log.debug(`hermes typing on ${frame.chatId}`); + // No HelloAgent-server-side typing indicator yet; logged for visibility. + log.debug(`agent typing on ${frame.chatId}`); return; } }); - function handleHermesSend(frame: SendFrame): void { + function handleAgentSend(frame: SendFrame): void { server.ack(frame.msgId); const channel = pending.get(frame.chatId); if (channel && !channel.ended()) { @@ -117,8 +114,8 @@ export function createBridge(opts: BridgeOptions): Bridge { channel.emit(frame.text); return; } - // No pending stream — Hermes is sending unsolicited (or the response - // already closed). Send via the relay as a fresh message. + // No pending stream — the agent is sending unsolicited (or the response + // already closed). Send via the HelloAgent server as a fresh message. if (!haClient || haClient.status !== "ready") { log.warn( `dropping outbound send to ${frame.chatId}: ha-client not ready`, @@ -134,8 +131,8 @@ export function createBridge(opts: BridgeOptions): Bridge { } } - // Inbound: relay messages → wschat `message` frame, then yield chunks - // back from the wschat side as Hermes streams its reply. + // Inbound: HelloAgent server messages → wire `message` frame, then yield + // chunks back as the agent streams its reply. function onIncoming(msg: IncomingMessage): AsyncIterable | string { if (!dedup.tryRecord(msg.messageId)) { log.debug(`duplicate message ${msg.messageId}, skipping`); @@ -143,7 +140,7 @@ export function createBridge(opts: BridgeOptions): Bridge { } if (!server.isReady()) { log.warn( - `inbound from @${msg.fromHandle} dropped — Hermes not connected to wschat yet`, + `inbound from @${msg.fromHandle} dropped — no agent connected to socket yet`, ); return ""; } @@ -174,18 +171,18 @@ export function createBridge(opts: BridgeOptions): Bridge { async function start(): Promise { await server.start(); - log.info(`bridge ready: relay=${opts.account.relayWs}, wschat=${opts.host ?? "127.0.0.1"}:${opts.port ?? 8770}`); + log.info(`agent socket listening on ${opts.host ?? "127.0.0.1"}:${opts.port ?? 8770}`); haClient = new HaClient({ account: opts.account, onIncoming, onStatus: (status, detail) => { if (status === "needs_repairing") { - log.error(`relay rejected token (${detail ?? "?"}). Re-pair.`); + log.error(`HelloAgent server rejected token (${detail ?? "?"}). Re-pair.`); } }, }); await haClient.ready; - log.info(`linked to relay as @${opts.account.handle}`); + log.info(`bridge ready: linked to HelloAgent as @${opts.account.handle}`); } async function stop(): Promise { @@ -203,6 +200,12 @@ export function createBridge(opts: BridgeOptions): Bridge { return { start, stop, isReady }; } +// The agent's first chunk gets a more generous wait than subsequent ones: +// LLMs typically take a moment to start streaming, but once chunks are +// flowing they arrive fast. This multiplier applies to the initial timer +// only; later chunks reset the timer to a single idleMs window. +const INITIAL_REPLY_IDLE_MULTIPLIER = 5; + // --------------------------------------------------------------------------- // Streaming helper: collects chunks from a producer until idle + returns // them as an AsyncIterable for the SDK's onMessage handler. @@ -259,12 +262,15 @@ function collectStreamingResponse(opts: StreamCollectOpts): AsyncIterable channel.end(), opts.idleMs * 5); + // Arm the idle timer for the case where the agent never replies. + idleTimer = setTimeout( + () => channel.end(), + opts.idleMs * INITIAL_REPLY_IDLE_MULTIPLIER, + ); } return { @@ -290,4 +296,3 @@ function collectStreamingResponse(opts: StreamCollectOpts): AsyncIterable --relay-ws Manual ha_* token import (no browser). - * --agent-name Suffix used after your handle (default: hermes). - * --api-url HelloAgent REST base. Env: HA_HERMES_BRIDGE_API_URL - * --web-url HelloAgent web base. Env: HA_HERMES_BRIDGE_WEB_URL + * pair Pair (if not paired) and start the bridge as a + * background daemon. Prompts for an `ha_*` agent + * token interactively. + * + * --token Skip the prompt; use this token directly (e.g. CI). * --account Account id for multi-account setups (default: default). + * --re-pair Stop any running bridge, discard creds, prompt again. * - * run Start the bridge (relay client + wschat server). - * --port wschat bind port (default 8770). - * --host wschat bind host (default 127.0.0.1). - * --wschat-token Optional shared secret Hermes must echo in hello. - * --account Account id to load creds from. + * status Show paired account info and whether the bridge + * daemon is running. * - * status Show paired accounts and creds metadata. + * stop Stop the running bridge daemon. * - * logout Delete creds for the given account. + * logout Stop the bridge and delete creds. * --account Account id (default: default). * - * Defaults: - * API URL https://api.helloagent.cc - * Web URL https://app.helloagent.cc - * Client helloagent-hermes + * State files (under ~/.helloagent-hermes/): + * credentials//creds.json pair output (chmod 0600) + * bridge.pid PID of the running daemon + * bridge.log verbose daemon log + * + * Defaults baked in: + * API URL https://api.helloagent.cc + * Server WS wss://api.helloagent.cc/v1/ws + * Bind ws://127.0.0.1:8770 + * + * Env-var escape hatches (local dev / advanced): + * HA_HERMES_BRIDGE_API_URL override REST API url + * HA_HERMES_BRIDGE_SERVER_WS override server WS url + * HA_HERMES_BRIDGE_HOST override bind host (default 127.0.0.1) + * HA_HERMES_BRIDGE_PORT override bind port (default 8770) + * HA_HERMES_BRIDGE_TOKEN shared secret the agent must echo in hello + * HA_HERMES_BRIDGE_DIR state dir (default ~/.helloagent-hermes) + * HA_HERMES_BRIDGE_DEBUG=1 verbose CLI logs (the daemon is always verbose + * in its log file) */ -import { pairWithBrowser } from "./auth/login.js"; -import { pairWithDeviceCode } from "./auth/login-device.js"; +import { spawn, type ChildProcess } from "node:child_process"; +import * as fs from "node:fs/promises"; +import * as path from "node:path"; +import * as readline from "node:readline/promises"; +import { stdin, stdout } from "node:process"; + import { importToken } from "./auth/import-token.js"; -import { hasAnyAuth } from "./auth/presence.js"; import { + type Creds, + CredsFormatError, DEFAULT_ACCOUNT_ID, deleteCreds, listLinkedAccountIds, + readCredsLenient, readCreds, + resolveStateDir, } from "./auth/store.js"; import { createBridge } from "./bridge.js"; -import { logger } from "./core/logger.js"; -const log = logger("cli"); +const PAIRING_URL = "https://app.helloagent.cc/app/agents/new"; type Argv = { command: string; @@ -65,80 +83,209 @@ function parseArgs(argv: string[]): Argv { return { command: command ?? "help", flags }; } -function envOrDefault(envName: string, fallback: string): string { - return process.env[envName]?.trim() || fallback; +function envOr(envName: string, fallback: T): T { + const v = process.env[envName]?.trim(); + if (!v) return fallback; + return (typeof fallback === "number" ? Number(v) : v) as T; } const DEFAULTS = { - apiUrl: () => envOrDefault("HA_HERMES_BRIDGE_API_URL", "https://api.helloagent.cc"), - webUrl: () => envOrDefault("HA_HERMES_BRIDGE_WEB_URL", "https://app.helloagent.cc"), - clientId: () => envOrDefault("HA_HERMES_BRIDGE_CLIENT_ID", "helloagent-hermes"), - agentName: "hermes", - port: 8770, - host: "127.0.0.1", + apiUrl: () => envOr("HA_HERMES_BRIDGE_API_URL", "https://api.helloagent.cc"), + serverWs: () => envOr("HA_HERMES_BRIDGE_SERVER_WS", "wss://api.helloagent.cc/v1/ws"), + host: () => envOr("HA_HERMES_BRIDGE_HOST", "127.0.0.1"), + port: () => envOr("HA_HERMES_BRIDGE_PORT", 8770), + socketToken: () => process.env.HA_HERMES_BRIDGE_TOKEN?.trim() || undefined, }; -async function cmdPair(flags: Argv["flags"]): Promise { - const accountId = String(flags.account ?? DEFAULT_ACCOUNT_ID); - const apiUrl = String(flags["api-url"] ?? DEFAULTS.apiUrl()); - const agentName = String(flags["agent-name"] ?? DEFAULTS.agentName); - const clientId = String(flags["client-id"] ?? DEFAULTS.clientId()); - - // Manual import path - if (typeof flags.token === "string" && flags.token) { - const relayWs = String(flags["relay-ws"] ?? ""); - if (!relayWs) throw new Error("--relay-ws is required with --token"); - const creds = await importToken({ - token: String(flags.token), - apiUrl, - relayWs, - accountId, - onProgress: (l) => console.log(l), - }); - console.log(`✓ paired as @${creds.handle}`); - return; +const pidPath = () => path.join(resolveStateDir(), "bridge.pid"); +const logPath = () => path.join(resolveStateDir(), "bridge.log"); + +async function readRunningPid(): Promise { + let raw: string; + try { + raw = await fs.readFile(pidPath(), "utf-8"); + } catch { + return null; } + const pid = parseInt(raw.trim(), 10); + if (!Number.isFinite(pid) || pid <= 0) return null; + try { + process.kill(pid, 0); // probe + return pid; + } catch { + // Stale PID; clean up. + await fs.unlink(pidPath()).catch(() => undefined); + return null; + } +} - // Device-code path - if (flags.device) { - const creds = await pairWithDeviceCode({ - agentName, - clientId, - apiUrl, - accountId, - onProgress: (l) => console.log(l), - }); - console.log(`✓ paired as @${creds.handle}`); - return; +async function promptForToken(): Promise { + console.log(""); + console.log("Link this bridge to a HelloAgent account:"); + console.log(""); + console.log(` 1. Open ${PAIRING_URL}`); + console.log(` 2. Create an agent and copy its token (starts with "ha_")`); + console.log(" 3. Paste the token below"); + console.log(""); + const rl = readline.createInterface({ input: stdin, output: stdout }); + try { + const answer = await rl.question("Token: "); + return answer.trim(); + } finally { + rl.close(); } +} + +async function ensurePaired(flags: Argv["flags"]): Promise { + const accountId = String(flags.account ?? DEFAULT_ACCOUNT_ID); + const force = Boolean(flags["re-pair"]); + + const existing = force ? null : await readCreds(accountId); + if (existing) return existing; - // Browser PKCE path (default) - const webUrl = String(flags["web-url"] ?? DEFAULTS.webUrl()); - const creds = await pairWithBrowser({ - agentName, - clientId, - apiUrl, - webUrl, + const token = + typeof flags.token === "string" && flags.token + ? flags.token.trim() + : await promptForToken(); + + if (!token) throw new Error("token is required"); + if (!token.startsWith("ha_")) { + throw new Error('expected an "ha_..." agent token'); + } + + const creds = await importToken({ + token, + apiUrl: DEFAULTS.apiUrl(), + serverWs: DEFAULTS.serverWs(), accountId, onProgress: (l) => console.log(l), }); - console.log(`✓ paired as @${creds.handle}`); + return creds; +} + +function waitForDaemonReady(child: ChildProcess, timeoutMs: number): Promise { + return new Promise((resolve, reject) => { + let settled = false; + + const cleanup = () => { + clearTimeout(timer); + child.off("message", onMessage); + child.off("exit", onExit); + child.off("error", onError); + }; + + const finish = (err?: Error) => { + if (settled) return; + settled = true; + cleanup(); + if (err) reject(err); + else resolve(); + }; + + const onMessage = (message: unknown) => { + if ( + typeof message === "object" && + message !== null && + (message as { type?: unknown }).type === "ready" + ) { + finish(); + } + }; + + const onExit = (code: number | null, signal: NodeJS.Signals | null) => { + const detail = signal ? `signal ${signal}` : `code ${code ?? "unknown"}`; + finish( + new Error( + `bridge daemon exited before ready (${detail}). Check ${logPath()} for details.`, + ), + ); + }; + + const onError = (err: Error) => { + finish(err); + }; + + const timer = setTimeout(() => { + finish( + new Error( + `bridge daemon did not become ready within ${timeoutMs}ms. Check ${logPath()} for details.`, + ), + ); + }, timeoutMs); + + child.once("message", onMessage); + child.once("exit", onExit); + child.once("error", onError); + }); +} + +async function spawnDaemon(accountId: string): Promise<{ pid: number }> { + const stateDir = resolveStateDir(); + await fs.mkdir(stateDir, { recursive: true }); + + const out = await fs.open(logPath(), "a"); + try { + const child = spawn( + process.execPath, + [process.argv[1], "_serve", "--account", accountId], + { + detached: true, + stdio: ["ignore", out.fd, out.fd, "ipc"], + env: { ...process.env, HA_HERMES_BRIDGE_DEBUG: "1" }, + }, + ); + try { + if (!child.pid) throw new Error("failed to spawn bridge daemon"); + await fs.writeFile(pidPath(), String(child.pid), { mode: 0o600 }); + await waitForDaemonReady(child, 12_000); + if (child.connected) child.disconnect(); + child.unref(); + return { pid: child.pid }; + } catch (err) { + if (child.pid) { + try { + process.kill(child.pid, "SIGTERM"); + } catch { + /* best-effort */ + } + } + await fs.unlink(pidPath()).catch(() => undefined); + throw err; + } + } finally { + await out.close(); + } } -async function cmdRun(flags: Argv["flags"]): Promise { +async function cmdPair(flags: Argv["flags"]): Promise { + const accountId = String(flags.account ?? DEFAULT_ACCOUNT_ID); + + // If --re-pair, stop any running daemon first. + if (flags["re-pair"]) await stopDaemon(); + + const running = await readRunningPid(); + const creds = await ensurePaired(flags); + + if (running) { + console.log(`✓ Connected to HelloAgent as @${creds.handle}.`); + console.log(" Bridge already running — chat through the HelloAgent app or browser."); + return; + } + + await spawnDaemon(accountId); + + console.log(`✓ Connected to HelloAgent as @${creds.handle}.`); + console.log(" You can now chat with your agent through the HelloAgent app or browser."); +} + +async function cmdServe(flags: Argv["flags"]): Promise { + // Hidden subcommand — runs the bridge in the foreground until SIGTERM. + // Invoked by `pair` via spawn, with stdout/stderr redirected to bridge.log. const accountId = String(flags.account ?? DEFAULT_ACCOUNT_ID); const creds = await readCreds(accountId); if (!creds) { - throw new Error( - `no paired account "${accountId}". Run 'helloagent-hermes pair' first.`, - ); + throw new Error(`no paired account "${accountId}"`); } - const port = Number(flags.port ?? DEFAULTS.port); - const host = String(flags.host ?? DEFAULTS.host); - const wschatToken = - typeof flags["wschat-token"] === "string" - ? String(flags["wschat-token"]) - : undefined; const bridge = createBridge({ account: { @@ -148,27 +295,48 @@ async function cmdRun(flags: Argv["flags"]): Promise { ownerHandle: creds.ownerHandle, token: creds.token, apiUrl: creds.apiUrl, - relayWs: creds.relayWs, + serverWs: creds.serverWs, }, - host, - port, - wschatToken, + host: DEFAULTS.host(), + port: DEFAULTS.port(), + socketToken: DEFAULTS.socketToken(), }); const onShutdown = async () => { - log.info("shutdown signal received"); await bridge.stop(); + await fs.unlink(pidPath()).catch(() => undefined); process.exit(0); }; process.once("SIGINT", () => void onShutdown()); process.once("SIGTERM", () => void onShutdown()); await bridge.start(); - console.log(`bridge running:`); - console.log(` HelloAgent handle: @${creds.handle}`); - console.log(` wschat endpoint: ws://${host}:${port}`); - console.log(` point Hermes at: WSCHAT_URL=ws://${host}:${port}`); - console.log(`Press Ctrl+C to stop.`); + if (typeof process.send === "function") { + process.send({ type: "ready" }); + } + // Idle until signaled. setInterval keeps the event loop alive without + // doing real work; the bridge has its own listeners holding it open. + setInterval(() => undefined, 1 << 30); +} + +async function stopDaemon(): Promise { + const pid = await readRunningPid(); + if (!pid) return false; + process.kill(pid, "SIGTERM"); + // Wait briefly for it to exit and remove its PID file. + for (let i = 0; i < 30; i++) { + if (!(await readRunningPid())) return true; + await new Promise((r) => setTimeout(r, 100)); + } + // Best-effort cleanup if it didn't go away. + await fs.unlink(pidPath()).catch(() => undefined); + return true; +} + +async function cmdStop(): Promise { + const stopped = await stopDaemon(); + if (stopped) console.log("✓ bridge stopped"); + else console.log("No bridge running."); } async function cmdStatus(): Promise { @@ -179,59 +347,89 @@ async function cmdStatus(): Promise { return; } for (const id of ids) { - const creds = await readCreds(id); + let creds: Creds | null; + try { + creds = await readCreds(id); + } catch (err) { + if (!(err instanceof CredsFormatError)) throw err; + console.log(`account: ${id}`); + console.log(` creds: incompatible (${err.message})`); + continue; + } if (!creds) continue; console.log(`account: ${id}`); console.log(` handle: @${creds.handle}`); console.log(` api: ${creds.apiUrl}`); - console.log(` relay: ${creds.relayWs}`); + console.log(` server: ${creds.serverWs}`); console.log(` linked: ${creds.linkedAt}`); console.log(` source: ${creds.source ?? "(unknown)"}`); } + const pid = await readRunningPid(); + console.log(""); + if (pid) console.log(`bridge: running (pid ${pid}, log ${logPath()})`); + else console.log("bridge: stopped"); } async function cmdLogout(flags: Argv["flags"]): Promise { const accountId = String(flags.account ?? DEFAULT_ACCOUNT_ID); - const creds = await readCreds(accountId); + let creds: Creds | null = null; + let invalidCreds = false; + let invalidHandle: string | undefined; + try { + creds = await readCreds(accountId); + } catch (err) { + if (!(err instanceof CredsFormatError)) throw err; + invalidCreds = true; + const raw = await readCredsLenient(accountId); + invalidHandle = typeof raw?.handle === "string" ? raw.handle : undefined; + console.warn(`Deleting incompatible credentials: ${err.message}`); + } if (!creds) { - console.log(`No paired account "${accountId}".`); - return; + if (!invalidCreds) { + console.log(`No paired account "${accountId}".`); + return; + } } + await stopDaemon(); await deleteCreds(accountId); - console.log(`✓ removed creds for @${creds.handle} (${accountId})`); + const handle = creds?.handle ?? invalidHandle; + if (handle) console.log(`✓ removed creds for @${handle} (${accountId})`); + else console.log(`✓ removed creds for account "${accountId}"`); console.log( - "Note: the relay-side agent token is not revoked — delete via the HelloAgent web UI or DELETE /v1/channels/.", + "Note: the server-side agent token is not revoked — delete via the HelloAgent web UI.", ); } function printHelp(): void { - console.log(`helloagent-hermes — bridge HelloAgent users to a Hermes agent + console.log(`helloagent-hermes — bridge HelloAgent users to a local agent Usage: - helloagent-hermes pair [--device | --token --relay-ws ] [--agent-name ] - helloagent-hermes run [--port ] [--host ] [--wschat-token ] + helloagent-hermes pair [--token ] [--account ] [--re-pair] helloagent-hermes status - helloagent-hermes logout [--account ] + helloagent-hermes stop + helloagent-hermes logout [--account ] + +The 'pair' command links the bridge to a HelloAgent agent token (prompts +interactively if not given), then starts the bridge as a background +daemon and returns. Your terminal is free; the bridge keeps running. + +To get a token, visit ${PAIRING_URL}, create an agent, and copy its token. Examples: - # 1. Pair (browser PKCE) - helloagent-hermes pair --agent-name jarvis + # First-time setup (interactive paste): + helloagent-hermes pair - # 2. Pair (manual token import for advanced users) - helloagent-hermes pair --token ha_xxx --relay-ws ws://localhost:8080/v1/ws + # Subsequent runs (creds already exist — skips the prompt): + helloagent-hermes pair - # 3. Run the bridge - helloagent-hermes run --port 8770 + # Non-interactive (CI / scripting): + helloagent-hermes pair --token ha_xxx - # 4. Then in Hermes (with the wschat plugin installed): - WSCHAT_URL=ws://127.0.0.1:8770 hermes gateway + # Force re-pair against a fresh token: + helloagent-hermes pair --re-pair -Env overrides: - HA_HERMES_BRIDGE_DIR state dir (default ~/.helloagent-hermes) - HA_HERMES_BRIDGE_API_URL default --api-url - HA_HERMES_BRIDGE_WEB_URL default --web-url - HA_HERMES_BRIDGE_CLIENT_ID default --client-id - HA_HERMES_BRIDGE_DEBUG=1 verbose logs + # Stop the running bridge: + helloagent-hermes stop `); } @@ -245,15 +443,18 @@ async function main(): Promise { case "pair": await cmdPair(flags); return; - case "run": - await cmdRun(flags); - return; case "status": await cmdStatus(); return; + case "stop": + await cmdStop(); + return; case "logout": await cmdLogout(flags); return; + case "_serve": + await cmdServe(flags); + return; default: console.error(`unknown command: ${command}\n`); printHelp(); @@ -268,6 +469,3 @@ main().catch((err) => { } process.exit(1); }); - -// Re-export hasAnyAuth so external embedders / tests can probe quickly. -export { hasAnyAuth }; diff --git a/src/core/ha-client.ts b/src/core/ha-client.ts index fcb54b9..c42ae94 100644 --- a/src/core/ha-client.ts +++ b/src/core/ha-client.ts @@ -3,9 +3,7 @@ * * Wraps `Agent` from `@helloagentai/sdk` and tracks lifecycle status * (starting → ready → needs_repairing → stopped) plus a typed inbound - * handler. Adapted from openclaw-HelloAgent/src/core/ha-client.ts but - * trimmed: we don't need OpenClaw's plugin status surface, just a small - * onStatus callback for the bridge runner. + * handler. */ import { Agent, AuthFailedError, type IncomingMessage } from "@helloagentai/sdk"; @@ -16,12 +14,9 @@ const log = logger("core/ha-client"); export type ClientStatus = "starting" | "ready" | "needs_repairing" | "stopped"; -export type ClientStatusListener = ( - status: ClientStatus, - detail?: string, -) => void; +type ClientStatusListener = (status: ClientStatus, detail?: string) => void; -export type IncomingHandler = ( +type IncomingHandler = ( msg: IncomingMessage, ) => string | Promise | AsyncIterable; @@ -47,7 +42,7 @@ export class HaClient { this.agent = new Agent({ token: opts.account.token, - relayUrl: opts.account.relayWs, + relayUrl: opts.account.serverWs, onAuthFailed: (err: AuthFailedError) => this.handleAuthFailed(err), logger: { warn: (msg: string, ...args: unknown[]) => diff --git a/src/core/logger.ts b/src/core/logger.ts index d4377e3..2f04abc 100644 --- a/src/core/logger.ts +++ b/src/core/logger.ts @@ -1,6 +1,10 @@ /** - * Tiny namespaced logger. Honors HA_HERMES_BRIDGE_DEBUG=1 for verbose output. - * Adapted from openclaw-HelloAgent/src/core/ha-logger.ts. + * Tiny namespaced logger. + * + * By default only warnings and errors are emitted — info and debug are + * suppressed to keep CLI output clean. Set `HA_HERMES_BRIDGE_DEBUG=1` to + * print every level. The detached bridge daemon always runs with that + * env var set so its log file captures the full picture. */ const DEBUG = process.env.HA_HERMES_BRIDGE_DEBUG === "1"; @@ -26,7 +30,9 @@ function emit(level: string, ns: string, msg: string, fields?: Record emit("info", ns, msg, fields), + info: (msg, fields) => { + if (DEBUG) emit("info", ns, msg, fields); + }, warn: (msg, fields) => emit("warn", ns, msg, fields), error: (msg, fields) => emit("error", ns, msg, fields), debug: (msg, fields) => { diff --git a/src/core/types.ts b/src/core/types.ts index 91b0ddf..6365f74 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -13,6 +13,6 @@ export type ResolvedAccount = { token: string; /** REST API base. */ apiUrl: string; - /** Relay WebSocket URL. */ - relayWs: string; + /** HelloAgent server WebSocket URL. */ + serverWs: string; }; diff --git a/src/index.ts b/src/index.ts index 9c8b963..60ed3ee 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,45 +1,25 @@ /** * Library entry — programmatic embedders. * - * Most users go through the CLI (./cli.ts). The exports here let you - * compose the bridge in your own Node program (e.g., embedding it in a - * larger orchestrator). + * Most users go through the CLI. The exports here are the minimum surface + * needed to compose the bridge in a Node program: pair an account, then + * start a bridge with the persisted creds. */ + +// Bridge orchestration export { createBridge, type Bridge, type BridgeOptions } from "./bridge.js"; -export { HaClient, type HaClientOptions, type ClientStatus } from "./core/ha-client.js"; -export { - createWschatServer, - type WschatServer, - type WschatServerOptions, -} from "./wschat/server.js"; +export type { ResolvedAccount } from "./core/types.js"; -// Auth surface -export { pairWithBrowser, type PairOptions } from "./auth/login.js"; -export { pairWithDeviceCode, type DevicePairOptions } from "./auth/login-device.js"; +// Auth export { importToken, type ImportTokenOptions } from "./auth/import-token.js"; export { hasAnyAuth } from "./auth/presence.js"; + +// Credential storage export { - CREDS_VERSION, DEFAULT_ACCOUNT_ID, type Creds, readCreds, writeCreds, deleteCreds, listLinkedAccountIds, - resolveStateDir, - resolveAuthDir, - accountAuthDir, } from "./auth/store.js"; - -// Types -export type { ResolvedAccount } from "./core/types.js"; -export type { - ClientToServer, - ServerToClient, - IncomingMessageFrame, - SendFrame, - EditFrame, - TypingFrame, - WelcomeFrame, - HelloFrame, -} from "./wschat/types.js"; diff --git a/tsconfig.json b/tsconfig.json index 4d9c1bb..cb8e4d3 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -6,7 +6,7 @@ "lib": ["ES2022"], "strict": true, "esModuleInterop": true, - "declaration": false, + "declaration": true, "outDir": "dist", "rootDir": "src", "skipLibCheck": true,