From 1952c92d4cf2817f30b2286201b860e1ed9215de Mon Sep 17 00:00:00 2001 From: himanshu Date: Sat, 9 May 2026 18:55:02 +0530 Subject: [PATCH 1/3] =?UTF-8?q?Rename=20relay=20=E2=86=92=20server,=20trim?= =?UTF-8?q?=20public=20API,=20ship=20type=20declarations?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Terminology - "relay" is internal HelloAgent jargon; the user-facing name is "HelloAgent server". Renamed user-facing strings, log messages, comments, README, package.json description, and the CLI flag (--relay-ws → --server-ws). - Renamed our internal field names: Account.relayWs / Creds.relayWs / ImportTokenOptions.relayWs → serverWs. Note: this is a breaking change for any existing creds.json — re-pair to migrate. SDK contract names (Agent's `relayUrl` param, linkChannel's `relay_ws` response field) are left untouched since they belong to the SDK package. - Stripped other internal-jargon leaks: sister-repo provenance comments (`openclaw-HelloAgent/...` in 7 files), server-internal Go path reference (`relay/internal/api/channels.go`), and a stale pre-split integration path in wschat/server.ts. - The CLI help's manual-import example was using the dev relay URL (`ws://localhost:8080/v1/ws`); switched to `wss://api.helloagent.cc/v1/ws`. Public API trimmed - Published surface (src/index.ts) now exposes only what an embedder needs: createBridge / Bridge / BridgeOptions, ResolvedAccount, pairWithBrowser, pairWithDeviceCode, importToken (+ option types), hasAnyAuth, Creds and the read/write/delete/list helpers, DEFAULT_ACCOUNT_ID. - Removed from exports (still used internally): HaClient and friends, createWschatServer + WschatServer types, all wschat frame types (internal wire protocol), path helpers (resolveStateDir/etc), CREDS_VERSION. Dead code removed - `export { randomUUID as newMsgId }` in bridge.ts and wschat/server.ts — nothing imported them. - cli.ts had a trailing `export { hasAnyAuth }` plus its only-for-the- re-export `import` — unreachable since cli.ts is not in package.json#exports. - Made ClientStatusListener / IncomingHandler file-internal in ha-client.ts. Type declarations now ship - tsconfig: declaration: false → true. - package.json: exports gains types/import conditions; added top-level `types` field. Embedders importing `@helloagentai/hermes` now get full TypeScript types instead of `any`. Quality fixes - bridge.ts: the "bridge ready" log fired immediately after wschat started, before the HelloAgent connection completed. Split into "wschat listening on H:P" then "bridge ready: linked to HelloAgent as @x" after the SDK handshake finishes. - bridge.ts: named the magic idleMs*5 initial-reply timeout multiplier (INITIAL_REPLY_IDLE_MULTIPLIER) with a comment explaining why first chunks get more time than subsequent ones. - store.ts: creds-version mismatch error now names the offending file path and tells the user exactly which command (pair or logout) fixes it. Co-Authored-By: Claude Opus 4.7 --- README.md | 38 +++++++++++++++++++------------------- package.json | 12 ++++++++---- src/auth/import-token.ts | 19 ++++++++----------- src/auth/login-device.ts | 5 ++--- src/auth/login-oauth.ts | 13 ++++++------- src/auth/login.ts | 5 +---- src/auth/store.ts | 10 +++++----- src/bridge.ts | 35 +++++++++++++++++++++-------------- src/cli.ts | 24 ++++++++++-------------- src/core/ha-client.ts | 13 ++++--------- src/core/logger.ts | 1 - src/core/types.ts | 4 ++-- src/index.ts | 36 +++++++++--------------------------- src/wschat/dedup.ts | 7 +++---- src/wschat/server.ts | 6 ++---- tsconfig.json | 2 +- 16 files changed, 101 insertions(+), 129 deletions(-) diff --git a/README.md b/README.md index 1cd7434..8254f7f 100644 --- a/README.md +++ b/README.md @@ -8,9 +8,9 @@ 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 + ▼ WebSocket, ha_* token (server-side: this bridge looks like ┌────────────────────┐ an agent named e.g. @alice/hermes) │ helloagent-hermes │ │ (this package) │ @@ -25,15 +25,15 @@ 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 +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 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. -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 from the user flow HelloAgent server → bridge → wschat → +Hermes. Hermes' streamed reply chunks flow back the other way and are +forwarded to the user as a streaming response. ## Auth @@ -45,13 +45,13 @@ The pairing flow mirrors [`@helloagentai/openclaw`](https://www.npmjs.com/packag 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. +3. **Manual token import** (`--token --server-ws`) — paste an existing + `ha_*` token; we validate it with one WS handshake against the + HelloAgent server, 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 +> The HelloAgent server only registers the channel-provider name `"openclaw"` +> today, so internally we link as that provider for now. Functionally +> identical for the bridge — when the server 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). @@ -73,7 +73,7 @@ helloagent-hermes pair --device --agent-name jarvis # Or to import an existing token: helloagent-hermes pair --token ha_xxx \ - --relay-ws wss://api.helloagent.cc/v1/ws + --server-ws wss://api.helloagent.cc/v1/ws # 2) Start the bridge helloagent-hermes run --port 8770 @@ -89,7 +89,7 @@ Now any HelloAgent user can DM `@/jarvis` and chat with Hermes. ## CLI ``` -helloagent-hermes pair [--device | --token --relay-ws ] +helloagent-hermes pair [--device | --token --server-ws ] [--agent-name ] [--api-url ] [--web-url ] [--account ] helloagent-hermes run [--port ] [--host ] [--wschat-token ] @@ -104,8 +104,8 @@ Environment variables: |---|---|---| | `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_API_URL` | `https://api.helloagent.cc` | Default `--api-url` (override for a local HelloAgent server) | +| `HA_HERMES_BRIDGE_WEB_URL` | `https://app.helloagent.cc` | Default `--web-url` (override for a local HelloAgent web app) | | `HA_HERMES_BRIDGE_CLIENT_ID` | `helloagent-hermes` | OAuth client id | | `HA_HERMES_BRIDGE_DEBUG` | unset | Verbose logs | @@ -117,7 +117,7 @@ Environment variables: - Edits — we advertise `supports: ["typing"]` so Hermes' streamer auto-downgrades to fresh-send chunks. Each Hermes `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 @@ -137,7 +137,7 @@ src/ ├── wschat/ │ ├── server.ts local WS server (single Hermes client) │ ├── types.ts wire frames -│ └── dedup.ts inbound dedup (relay reconnects) +│ └── dedup.ts inbound dedup (server reconnects) ├── bridge.ts wires HaClient ↔ wschat server, streaming bridge ├── cli.ts pair / run / status / logout └── index.ts library re-exports diff --git a/package.json b/package.json index fa2dcf4..1224029 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", 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 index c62e20c..cf9670b 100644 --- a/src/auth/login-device.ts +++ b/src/auth/login-device.ts @@ -3,8 +3,7 @@ * 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). + * Provider held at "openclaw" for now (see ./login-oauth.ts). */ import { HelloAgentApiError, @@ -86,7 +85,7 @@ export async function pairWithDeviceCode(opts: DevicePairOptions): Promise/credentials//creds.json @@ -27,7 +25,7 @@ export type Creds = { ownerHandle: string; token: string; apiUrl: string; - relayWs: string; + serverWs: string; linkedAt: string; source?: "oauth" | "device" | "manual"; }; @@ -63,7 +61,9 @@ export async function readCreds( 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}`); + throw new Error( + `creds at ${credsPath(accountId)} are version ${parsed.version}, expected ${CREDS_VERSION}. Run 'helloagent-hermes pair' to re-link, or 'helloagent-hermes logout --account ${accountId}' to delete.`, + ); } return parsed; } catch (e) { diff --git a/src/bridge.ts b/src/bridge.ts index 576e657..569fba8 100644 --- a/src/bridge.ts +++ b/src/bridge.ts @@ -1,12 +1,12 @@ /** - * Bridge wiring: HelloAgent relay ↔ wschat server ↔ Hermes plugin. + * Bridge wiring: HelloAgent server ↔ wschat server ↔ Hermes plugin. * * Direction 1 (inbound to Hermes): - * relay → HaClient.onMessage(IncomingMessage) + * HelloAgent server → 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) + * by chatId, AsyncIterable back to the HelloAgent server) * * Direction 2 (outbound from Hermes): * Hermes → wschat `send`/`edit` frame @@ -24,7 +24,6 @@ * 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"; @@ -83,7 +82,7 @@ export function createBridge(opts: BridgeOptions): Bridge { let haClient: HaClient | null = null; - // Outbound: Hermes wschat frames → relay sends. + // Outbound: Hermes wschat frames → HelloAgent server sends. server.onClientFrame((frame: ClientToServer) => { if (frame.type === "send") { handleHermesSend(frame); @@ -102,7 +101,7 @@ export function createBridge(opts: BridgeOptions): Bridge { return; } if (frame.type === "typing") { - // No relay-side typing indicator yet; logged for visibility. + // No server-side typing indicator yet; logged for visibility. log.debug(`hermes typing on ${frame.chatId}`); return; } @@ -118,7 +117,7 @@ export function createBridge(opts: BridgeOptions): Bridge { return; } // No pending stream — Hermes is sending unsolicited (or the response - // already closed). Send via the relay as a fresh message. + // 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 +133,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 → wschat `message` frame, then yield + // chunks back from the wschat side as Hermes streams its reply. function onIncoming(msg: IncomingMessage): AsyncIterable | string { if (!dedup.tryRecord(msg.messageId)) { log.debug(`duplicate message ${msg.messageId}, skipping`); @@ -174,18 +173,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(`wschat 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 +202,12 @@ export function createBridge(opts: BridgeOptions): Bridge { return { start, stop, isReady }; } +// Hermes' 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. @@ -264,7 +269,10 @@ function collectStreamingResponse(opts: StreamCollectOpts): AsyncIterable channel.end(), opts.idleMs * 5); + idleTimer = setTimeout( + () => channel.end(), + opts.idleMs * INITIAL_REPLY_IDLE_MULTIPLIER, + ); } return { @@ -290,4 +298,3 @@ function collectStreamingResponse(opts: StreamCollectOpts): AsyncIterable --relay-ws Manual ha_* token import (no browser). + * --token --server-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 * --account Account id for multi-account setups (default: default). * - * run Start the bridge (relay client + wschat server). + * run Start the bridge (HelloAgent server 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. @@ -30,7 +30,6 @@ import { pairWithBrowser } from "./auth/login.js"; import { pairWithDeviceCode } from "./auth/login-device.js"; import { importToken } from "./auth/import-token.js"; -import { hasAnyAuth } from "./auth/presence.js"; import { DEFAULT_ACCOUNT_ID, deleteCreds, @@ -86,12 +85,12 @@ async function cmdPair(flags: Argv["flags"]): Promise { // 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 serverWs = String(flags["server-ws"] ?? ""); + if (!serverWs) throw new Error("--server-ws is required with --token"); const creds = await importToken({ token: String(flags.token), apiUrl, - relayWs, + serverWs, accountId, onProgress: (l) => console.log(l), }); @@ -148,7 +147,7 @@ async function cmdRun(flags: Argv["flags"]): Promise { ownerHandle: creds.ownerHandle, token: creds.token, apiUrl: creds.apiUrl, - relayWs: creds.relayWs, + serverWs: creds.serverWs, }, host, port, @@ -184,7 +183,7 @@ async function cmdStatus(): Promise { 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)"}`); } @@ -200,7 +199,7 @@ async function cmdLogout(flags: Argv["flags"]): Promise { await deleteCreds(accountId); console.log(`✓ removed creds for @${creds.handle} (${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 or DELETE /v1/channels/.", ); } @@ -208,7 +207,7 @@ function printHelp(): void { console.log(`helloagent-hermes — bridge HelloAgent users to a Hermes agent Usage: - helloagent-hermes pair [--device | --token --relay-ws ] [--agent-name ] + helloagent-hermes pair [--device | --token --server-ws ] [--agent-name ] helloagent-hermes run [--port ] [--host ] [--wschat-token ] helloagent-hermes status helloagent-hermes logout [--account ] @@ -218,7 +217,7 @@ Examples: helloagent-hermes pair --agent-name jarvis # 2. Pair (manual token import for advanced users) - helloagent-hermes pair --token ha_xxx --relay-ws ws://localhost:8080/v1/ws + helloagent-hermes pair --token ha_xxx --server-ws wss://api.helloagent.cc/v1/ws # 3. Run the bridge helloagent-hermes run --port 8770 @@ -268,6 +267,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..8fa7804 100644 --- a/src/core/logger.ts +++ b/src/core/logger.ts @@ -1,6 +1,5 @@ /** * Tiny namespaced logger. Honors HA_HERMES_BRIDGE_DEBUG=1 for verbose output. - * Adapted from openclaw-HelloAgent/src/core/ha-logger.ts. */ const DEBUG = process.env.HA_HERMES_BRIDGE_DEBUG === "1"; 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..ea40cb5 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,45 +1,27 @@ /** * 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 +// Auth flows export { pairWithBrowser, type PairOptions } from "./auth/login.js"; export { pairWithDeviceCode, type DevicePairOptions } from "./auth/login-device.js"; 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/src/wschat/dedup.ts b/src/wschat/dedup.ts index a0ceb7d..054392f 100644 --- a/src/wschat/dedup.ts +++ b/src/wschat/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/wschat/server.ts index 9a08e1b..c2abc50 100644 --- a/src/wschat/server.ts +++ b/src/wschat/server.ts @@ -5,9 +5,9 @@ * `message` frames; receive Hermes outbound `send`/`edit` frames → notify * subscribers. * - * Wire protocol matches integrations/hermes-ws-channel/adapter.py. + * Wire protocol matches the Hermes wschat plugin; frame shapes live in + * ./types.ts. */ -import { randomUUID } from "node:crypto"; import { WebSocketServer, type WebSocket } from "ws"; import { logger } from "../core/logger.js"; @@ -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/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, From 1b609ac084344c781c52d365396542ae34e788eb Mon Sep 17 00:00:00 2001 From: himanshu Date: Sat, 9 May 2026 23:00:45 +0530 Subject: [PATCH 2/3] One-step pair-and-bridge UX: paste token, daemonize, drop wschat naming MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three cohesive changes against the previous polish pass: 1. Replace OAuth/device-code/manual-flag combo with a single interactive token paste flow. Deleted src/auth/login.ts, src/auth/login-oauth.ts, src/auth/login-device.ts (~360 LOC of OAuth + linkChannel + PKCE loopback machinery). The HelloAgent web UI now handles agent creation and ha_* token issuance; this CLI just consumes the resulting token. `pair` prompts: Link this bridge to a HelloAgent account: 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 Token: _ --token still works for non-interactive scripting. Public API shrinks: pairWithBrowser / pairWithDeviceCode / their option types removed from index.ts; importToken stays. 2. Daemonize `pair`. After pairing succeeds (or creds already exist), the foreground spawns a detached child running `_serve` (hidden subcommand) that holds the bridge open. Foreground waits for the agent socket to actually bind (TCP probe, 8s timeout) before printing success and exiting — terminal returns to prompt. State files under ~/.helloagent-hermes/: bridge.pid (PID of the daemon, chmod 0600), bridge.log (verbose log; daemon always runs with HA_HERMES_BRIDGE_DEBUG=1). Added `stop` command (SIGTERM the daemon, clean up PID file). `status` now reports "bridge: running (pid X, log …)" or "bridge: stopped". `logout` stops the daemon before deleting creds. Output collapses from the previous block of internal log lines plus "Press Ctrl+C to stop the bridge" footer to two lines: ✓ Connected to HelloAgent as @alice/jarvis. You can now chat with your agent through the HelloAgent app or browser. logger.ts: info-level emission is now gated on HA_HERMES_BRIDGE_DEBUG=1. Warnings and errors still print. The daemon always runs with DEBUG=1 in its env so its log file captures the full picture. 3. Rebrand "wschat" out of our package. The protocol stays compatible with Hermes' wschat plugin on the wire, but our code, types, and docs no longer call it that: - src/wschat/ → src/agent-socket/ (folder rename via git mv) - createWschatServer → createAgentSocket - WschatServerOptions → AgentSocketOptions - WschatServer → AgentSocket - BridgeOptions.wschatToken → BridgeOptions.socketToken - Log namespaces and code comments scrubbed - README's architecture diagram says "agent-socket protocol" instead of "wschat protocol"; one cross-reference note retained pointing at the Hermes plugin currently named wschat - CLI help drops `--port` / `--host` / `--wschat-token` flags from the visible surface; same overrides remain via env vars (HA_HERMES_BRIDGE_PORT / _HOST / _TOKEN) Build hygiene: package.json gains a `postbuild` step that re-applies chmod +x to dist/cli.js (tsc strips the executable bit). Without this the global symlink (`npm link` / `npm install -g`) breaks after every rebuild. Tested end-to-end: paired with a real ha_* token, daemon spawned, agent socket bound, Hermes plugin (after a parallel rename to "helloagent" in its own install) connected, DM round-tripped from HelloAgent → bridge → Hermes → reply back through the same chain. Co-Authored-By: Claude Opus 4.7 --- README.md | 168 ++++++------ package.json | 1 + src/{wschat => agent-socket}/dedup.ts | 0 src/{wschat => agent-socket}/server.ts | 40 +-- src/{wschat => agent-socket}/types.ts | 7 +- src/auth/login-device.ts | 95 ------- src/auth/login-oauth.ts | 74 ------ src/auth/login.ts | 204 --------------- src/bridge.ts | 68 +++-- src/cli.ts | 345 +++++++++++++++++-------- src/core/logger.ts | 11 +- src/index.ts | 4 +- 12 files changed, 397 insertions(+), 620 deletions(-) rename src/{wschat => agent-socket}/dedup.ts (100%) rename src/{wschat => agent-socket}/server.ts (83%) rename src/{wschat => agent-socket}/types.ts (85%) delete mode 100644 src/auth/login-device.ts delete mode 100644 src/auth/login-oauth.ts delete mode 100644 src/auth/login.ts diff --git a/README.md b/README.md index 8254f7f..992d115 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 @@ -10,14 +11,14 @@ A bridge that lets HelloAgent users chat with their personal Hermes agent. ▼ WebSocket, ha_* token HelloAgent server │ - ▼ WebSocket, ha_* token (server-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,115 @@ A bridge that lets HelloAgent users chat with their personal Hermes agent. The bridge holds two things at once: -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 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 HelloAgent server → bridge → wschat → -Hermes. Hermes' streamed reply chunks flow back the other way and are -forwarded to the user as a streaming response. +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 --server-ws`) — paste an existing - `ha_*` token; we validate it with one WS handshake against the - HelloAgent server, then persist. - -> The HelloAgent server only registers the channel-provider name `"openclaw"` -> today, so internally we link as that provider for now. Functionally -> identical for the bridge — when the server 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 \ - --server-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 +✓ paired as @alice/jarvis +✓ bridge running as @alice/jarvis + agent socket: ws://127.0.0.1:8770 ``` -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 --server-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 logout [--account ] ``` -Environment variables: +`pair` is the only running command — it pairs (if needed) and serves the +agent socket until you Ctrl+C. + +## Configuration + +Defaults are baked in for the common case: + +| Setting | Default | +|---|---| +| API URL | `https://api.helloagent.cc` | +| Web URL | `https://app.helloagent.cc` | +| 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 a local HelloAgent server) | -| `HA_HERMES_BRIDGE_WEB_URL` | `https://app.helloagent.cc` | Default `--web-url` (override for a local HelloAgent web app) | -| `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 HelloAgent server side. +- Reactions, read receipts, typing indicators on the HelloAgent server + side. ## Layout @@ -126,20 +143,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 (server reconnects) -├── bridge.ts wires HaClient ↔ wschat server, streaming bridge -├── cli.ts pair / run / status / logout +├── 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 1224029..9dc0d5a 100644 --- a/package.json +++ b/package.json @@ -41,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 100% rename from src/wschat/dedup.ts rename to src/agent-socket/dedup.ts 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 c2abc50..6f2b665 100644 --- a/src/wschat/server.ts +++ b/src/agent-socket/server.ts @@ -1,12 +1,12 @@ /** - * 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 the Hermes wschat plugin; frame shapes live in - * ./types.ts. + * Frame shapes live in ./types.ts. On Hermes' side this protocol is + * exposed via a plugin currently called `wschat`. */ import { WebSocketServer, type WebSocket } from "ws"; @@ -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) { 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/login-device.ts b/src/auth/login-device.ts deleted file mode 100644 index cf9670b..0000000 --- a/src/auth/login-device.ts +++ /dev/null @@ -1,95 +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. - * - * 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, - serverWs: 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 2c9ed39..0000000 --- a/src/auth/login-oauth.ts +++ /dev/null @@ -1,74 +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 HelloAgent server - * only registers that channel-provider name today. Functionally identical - * for our purposes — the server just labels the link that way. Switch to - * "hermes" once the server 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 HelloAgent server registers it - -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, - serverWs: 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 1668ac8..0000000 --- a/src/auth/login.ts +++ /dev/null @@ -1,204 +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. - */ -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 dev clients 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/bridge.ts b/src/bridge.ts index 569fba8..d4fad0e 100644 --- a/src/bridge.ts +++ b/src/bridge.ts @@ -1,15 +1,16 @@ /** - * Bridge wiring: HelloAgent server ↔ wschat server ↔ Hermes plugin. + * Bridge wiring: HelloAgent server ↔ agent socket ↔ agent (e.g. Hermes). * - * Direction 1 (inbound to Hermes): + * Direction 1 (inbound to the agent): * HelloAgent server → 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 HelloAgent server) + * → 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,7 +21,7 @@ * 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. */ @@ -29,27 +30,24 @@ 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; }; @@ -72,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 → HelloAgent server 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, @@ -101,13 +99,13 @@ export function createBridge(opts: BridgeOptions): Bridge { return; } if (frame.type === "typing") { - // No server-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()) { @@ -116,7 +114,7 @@ export function createBridge(opts: BridgeOptions): Bridge { channel.emit(frame.text); return; } - // No pending stream — Hermes is sending unsolicited (or the response + // 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( @@ -133,8 +131,8 @@ export function createBridge(opts: BridgeOptions): Bridge { } } - // Inbound: HelloAgent server 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`); @@ -142,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 ""; } @@ -173,7 +171,7 @@ export function createBridge(opts: BridgeOptions): Bridge { async function start(): Promise { await server.start(); - log.info(`wschat listening on ${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, @@ -202,7 +200,7 @@ export function createBridge(opts: BridgeOptions): Bridge { return { start, stop, isReady }; } -// Hermes' first chunk gets a more generous wait than subsequent ones: +// 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. @@ -264,11 +262,11 @@ function collectStreamingResponse(opts: StreamCollectOpts): AsyncIterable channel.end(), opts.idleMs * INITIAL_REPLY_IDLE_MULTIPLIER, diff --git a/src/cli.ts b/src/cli.ts index edffa3b..5353a3c 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -1,45 +1,63 @@ #!/usr/bin/env node /** - * helloagent-hermes — bridge CLI. + * helloagent-hermes — CLI. * * Commands: - * pair Pair with HelloAgent. Default: PKCE OAuth (browser). - * --device Headless device-code flow. - * --token --server-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 (HelloAgent server 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 } from "node:child_process"; +import * as fs from "node:fs/promises"; +import * as net from "node:net"; +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 { + type Creds, DEFAULT_ACCOUNT_ID, deleteCreds, listLinkedAccountIds, 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; @@ -64,80 +82,163 @@ 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 serverWs = String(flags["server-ws"] ?? ""); - if (!serverWs) throw new Error("--server-ws is required with --token"); - const creds = await importToken({ - token: String(flags.token), - apiUrl, - serverWs, - 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), +async function waitForListener(host: string, port: number, timeoutMs: number): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + const ok = await new Promise((resolve) => { + const sock = net.createConnection({ host, port }); + sock.once("connect", () => { + sock.destroy(); + resolve(true); + }); + sock.once("error", () => resolve(false)); }); - console.log(`✓ paired as @${creds.handle}`); - return; + if (ok) return true; + await new Promise((r) => setTimeout(r, 100)); } + return false; +} + +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; +} + +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], + env: { ...process.env, HA_HERMES_BRIDGE_DEBUG: "1" }, + }, + ); + if (!child.pid) throw new Error("failed to spawn bridge daemon"); + await fs.writeFile(pidPath(), String(child.pid), { mode: 0o600 }); + child.unref(); + return { pid: child.pid }; + } 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); - const creds = await readCreds(accountId); - if (!creds) { + + // 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); + + const ok = await waitForListener(DEFAULTS.host(), DEFAULTS.port(), 8000); + if (!ok) { throw new Error( - `no paired account "${accountId}". Run 'helloagent-hermes pair' first.`, + `bridge daemon did not start listening within 8s. Check ${logPath()} for details.`, ); } - 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; + + 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}"`); + } const bridge = createBridge({ account: { @@ -149,25 +250,43 @@ async function cmdRun(flags: Argv["flags"]): Promise { apiUrl: creds.apiUrl, 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.`); + // 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 { @@ -187,6 +306,10 @@ async function cmdStatus(): Promise { 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 { @@ -196,41 +319,44 @@ async function cmdLogout(flags: Argv["flags"]): Promise { console.log(`No paired account "${accountId}".`); return; } + await stopDaemon(); await deleteCreds(accountId); console.log(`✓ removed creds for @${creds.handle} (${accountId})`); console.log( - "Note: the server-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 --server-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 --server-ws wss://api.helloagent.cc/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 `); } @@ -244,15 +370,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(); diff --git a/src/core/logger.ts b/src/core/logger.ts index 8fa7804..2f04abc 100644 --- a/src/core/logger.ts +++ b/src/core/logger.ts @@ -1,5 +1,10 @@ /** - * Tiny namespaced logger. Honors HA_HERMES_BRIDGE_DEBUG=1 for verbose output. + * 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"; @@ -25,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/index.ts b/src/index.ts index ea40cb5..60ed3ee 100644 --- a/src/index.ts +++ b/src/index.ts @@ -10,9 +10,7 @@ export { createBridge, type Bridge, type BridgeOptions } from "./bridge.js"; export type { ResolvedAccount } from "./core/types.js"; -// Auth flows -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"; From ce7f74c677213fb0ab6844d243d4a673d4161288 Mon Sep 17 00:00:00 2001 From: himanshu Date: Sun, 10 May 2026 07:11:16 +0530 Subject: [PATCH 3/3] Fix PR review issues --- README.md | 14 +++-- src/auth/store.ts | 81 +++++++++++++++++++++++--- src/cli.ts | 145 ++++++++++++++++++++++++++++++++++------------ 3 files changed, 191 insertions(+), 49 deletions(-) diff --git a/README.md b/README.md index 992d115..bdbf98d 100644 --- a/README.md +++ b/README.md @@ -58,9 +58,9 @@ Link this bridge to a HelloAgent account: Token: ha_xxxxxxxxxxxxx -✓ paired as @alice/jarvis -✓ bridge running as @alice/jarvis - agent socket: ws://127.0.0.1:8770 +imported token for @alice/jarvis +✓ Connected to HelloAgent as @alice/jarvis. + You can now chat with your agent through the HelloAgent app or browser. ``` Then in Hermes (with the `wschat` plugin installed at @@ -96,11 +96,13 @@ the state dir with `HA_HERMES_BRIDGE_DIR`. ``` helloagent-hermes pair [--token ] [--account ] [--re-pair] helloagent-hermes status +helloagent-hermes stop helloagent-hermes logout [--account ] ``` -`pair` is the only running command — it pairs (if needed) and serves the -agent socket until you Ctrl+C. +`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 @@ -109,7 +111,7 @@ Defaults are baked in for the common case: | Setting | Default | |---|---| | API URL | `https://api.helloagent.cc` | -| Web URL | `https://app.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): diff --git a/src/auth/store.ts b/src/auth/store.ts index 25c1a51..b677e1c 100644 --- a/src/auth/store.ts +++ b/src/auth/store.ts @@ -15,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; @@ -54,20 +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( - `creds at ${credsPath(accountId)} are version ${parsed.version}, expected ${CREDS_VERSION}. Run 'helloagent-hermes pair' to re-link, or 'helloagent-hermes logout --account ${accountId}' to delete.`, - ); + 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/cli.ts b/src/cli.ts index 5353a3c..820bbd1 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -39,9 +39,8 @@ * HA_HERMES_BRIDGE_DEBUG=1 verbose CLI logs (the daemon is always verbose * in its log file) */ -import { spawn } from "node:child_process"; +import { spawn, type ChildProcess } from "node:child_process"; import * as fs from "node:fs/promises"; -import * as net from "node:net"; import * as path from "node:path"; import * as readline from "node:readline/promises"; import { stdin, stdout } from "node:process"; @@ -49,9 +48,11 @@ import { stdin, stdout } from "node:process"; import { importToken } from "./auth/import-token.js"; import { type Creds, + CredsFormatError, DEFAULT_ACCOUNT_ID, deleteCreds, listLinkedAccountIds, + readCredsLenient, readCreds, resolveStateDir, } from "./auth/store.js"; @@ -118,23 +119,6 @@ async function readRunningPid(): Promise { } } -async function waitForListener(host: string, port: number, timeoutMs: number): Promise { - const deadline = Date.now() + timeoutMs; - while (Date.now() < deadline) { - const ok = await new Promise((resolve) => { - const sock = net.createConnection({ host, port }); - sock.once("connect", () => { - sock.destroy(); - resolve(true); - }); - sock.once("error", () => resolve(false)); - }); - if (ok) return true; - await new Promise((r) => setTimeout(r, 100)); - } - return false; -} - async function promptForToken(): Promise { console.log(""); console.log("Link this bridge to a HelloAgent account:"); @@ -179,6 +163,62 @@ async function ensurePaired(flags: Argv["flags"]): Promise { 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 }); @@ -190,14 +230,28 @@ async function spawnDaemon(accountId: string): Promise<{ pid: number }> { [process.argv[1], "_serve", "--account", accountId], { detached: true, - stdio: ["ignore", out.fd, out.fd], + stdio: ["ignore", out.fd, out.fd, "ipc"], env: { ...process.env, HA_HERMES_BRIDGE_DEBUG: "1" }, }, ); - if (!child.pid) throw new Error("failed to spawn bridge daemon"); - await fs.writeFile(pidPath(), String(child.pid), { mode: 0o600 }); - child.unref(); - return { pid: child.pid }; + 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(); } @@ -220,13 +274,6 @@ async function cmdPair(flags: Argv["flags"]): Promise { await spawnDaemon(accountId); - const ok = await waitForListener(DEFAULTS.host(), DEFAULTS.port(), 8000); - if (!ok) { - throw new Error( - `bridge daemon did not start listening within 8s. Check ${logPath()} for details.`, - ); - } - console.log(`✓ Connected to HelloAgent as @${creds.handle}.`); console.log(" You can now chat with your agent through the HelloAgent app or browser."); } @@ -264,6 +311,9 @@ async function cmdServe(flags: Argv["flags"]): Promise { process.once("SIGTERM", () => void onShutdown()); await bridge.start(); + 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); @@ -297,7 +347,15 @@ 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}`); @@ -314,14 +372,29 @@ async function cmdStatus(): Promise { 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 server-side agent token is not revoked — delete via the HelloAgent web UI.", );