From 6a533f3d2cd95166fd59e8d55b6961cf3e234384 Mon Sep 17 00:00:00 2001 From: himanshu Date: Sat, 9 May 2026 19:44:07 +0530 Subject: [PATCH] Clean up plugin source for public release - Strip internal terminology (MVP, Lark, Feishu, session-manager refs) from comments and docs. Rewrite README as a user-facing reference with pair flow, env-var reference, and "Running from source" steps. - Remove dead exports (defaultAccountId, getResolvedAccountOrThrow, loadAccount/loadAccountOrThrow, listClientIds, HelloAgentApiError re-export) and delete one-off debug/e2e test scripts. - Drop child_process auto-browser-open in the OAuth flow so the plugin installs without --dangerously-force-unsafe-install. Embedders can still inject their own openBrowser callback. - Polish the pair prompt: drop diagnostic mode/api/relay lines and replace the token-paste instructions with numbered steps and a clean Token: input. Co-Authored-By: Claude Opus 4.7 --- README.md | 195 ++++++++++++++++++----------- index.cjs | 6 +- src/auth/login-oauth.ts | 8 +- src/auth/login.ts | 28 +---- src/channel/config-adapter.ts | 10 +- src/channel/event-handlers.ts | 10 +- src/channel/monitor.ts | 10 +- src/channel/plugin.ts | 11 +- src/channel/probe.ts | 5 +- src/commands/auth-login.ts | 15 +-- src/core/accounts.ts | 45 ------- src/core/cfg-store.ts | 34 ++--- src/core/ha-client.ts | 12 +- src/core/ha-logger.ts | 11 +- src/core/types.ts | 2 +- src/messaging/inbound/dedup.ts | 3 +- src/messaging/inbound/dispatch.ts | 14 +-- src/messaging/outbound/outbound.ts | 12 +- tests/cache-debug.ts | 39 ------ tests/e2e-cfg-write.ts | 73 ----------- tests/smoke.ts | 13 +- 21 files changed, 198 insertions(+), 358 deletions(-) delete mode 100644 tests/cache-debug.ts delete mode 100644 tests/e2e-cfg-write.ts diff --git a/README.md b/README.md index df5ce1a..514e552 100644 --- a/README.md +++ b/README.md @@ -1,93 +1,148 @@ # @helloagentai/openclaw -OpenClaw channel plugin for HelloAgent — relay-backed messaging through OpenClaw's plugin API. Built on top of [`@helloagentai/sdk`](https://www.npmjs.com/package/@helloagentai/sdk). +> OpenClaw channel plugin for HelloAgent — relay-backed messaging for OpenClaw assistants. + +[![npm](https://img.shields.io/npm/v/@helloagentai/openclaw.svg)](https://www.npmjs.com/package/@helloagentai/openclaw) +[![License](https://img.shields.io/npm/l/@helloagentai/openclaw.svg)](LICENSE) + +Connects an OpenClaw assistant to the [HelloAgent](https://app.helloagent.cc) network. Peers DM your assistant over a long-lived relay WebSocket; inbound messages are dispatched as streams and replies are sent back chunk-by-chunk on the same connection. + +Built on [`@helloagentai/sdk`](https://www.npmjs.com/package/@helloagentai/sdk). + +## Install ```bash npm install @helloagentai/openclaw ``` -## Features - -- **`security.dm`** policy adapter (allowlist / allow-all / deny-all) -- **`pairing`** adapter for pairing-code DM approval -- **`status`** snapshot + relay probe -- **Streaming inbound** — `deliver` callback writes chunks live instead of - collecting and returning a single string at the end -- **Inbound dedup** with TTL + LRU -- **`auth.login` writes cfg directly** — after a successful pair, the plugin - writes `channels.helloagent.enabled=true` to `openclaw.json` itself, so - the channel shows up in `channels list` and auto-starts on next gateway - boot regardless of whether the host's reconciler can reach the running - gateway. (See [src/core/cfg-store.ts](src/core/cfg-store.ts) for why this - matters when running with `--profile`, custom gateway port, or no daemon.) -- Plain `register(api)` entry shape (no `defineChannelPluginEntry` wrapper) -- Cleaned manifest (`openclaw.plugin.json` follows the Lark minimal shape) - -## Layout +OpenClaw discovers the plugin automatically on the next gateway boot. + +## Pair an agent + +```bash +openclaw channels login --channel helloagent +``` + +The default flow prompts for an `ha_*` token — create one at [app.helloagent.cc/app/agents/new](https://app.helloagent.cc/app/agents/new) and paste it. To switch flows, set `HELLOAGENT_PAIR_MODE`: + +| Mode | Use when… | +|---|---| +| `import` (default) | You can paste an `ha_*` token | +| `oauth` | A browser is available — opens a loopback OAuth + PKCE flow | +| `device` | Headless machine — prints a code to enter on another device | + +A successful pair writes `channels.helloagent.enabled = true` to your `openclaw.json`, so the channel appears in `openclaw channels list` and starts automatically on the next gateway boot. +## Usage + +```bash +openclaw channels list # show channel + account status +openclaw channels logout --channel helloagent # remove credentials ``` -. -├── openclaw.plugin.json minimal manifest -├── package.json npm packaging + openclaw.channel block -├── index.ts plain register(api) plugin entry -└── src/ - ├── channel/ - │ ├── plugin.ts ChannelPlugin literal - │ ├── monitor.ts per-account WS lifecycle (replaces session-manager) - │ ├── event-handlers.ts IncomingMessage → dispatch - │ ├── config-adapter.ts set/apply/delete account config helpers - │ ├── probe.ts relay reachability probe - │ └── types.ts MonitorContext, MonitorOpts - ├── core/ - │ ├── accounts.ts cfg-aware account list/resolve + credsToAccount - │ ├── account-cache.ts sync façade over disk creds (copied) - │ ├── auth-store.ts creds.json I/O (copied) - │ ├── cfg-store.ts atomic openclaw.json read/write - │ ├── ha-client.ts per-account managed Agent - │ ├── ha-logger.ts namespaced logger factory - │ └── types.ts HelloAgentAccount, ResolvedHelloAgentAccount - ├── messaging/ - │ ├── inbound/ - │ │ ├── dedup.ts TTL + LRU dedup - │ │ └── dispatch.ts streaming dispatchInboundDirectDmWithRuntime - │ └── outbound/ - │ ├── outbound.ts ChannelOutboundAdapter - │ └── send.ts low-level send via ha-client - ├── auth/ - │ ├── login.ts OAuth + PKCE pairing (copied) - │ ├── login-oauth.ts code exchange + link (copied) - │ ├── login-device.ts device-code flow (copied) - │ ├── import-token.ts manual ha_* import (copied) - │ └── presence.ts hasAnyHelloAgentAuth probe (copied) - └── commands/ - ├── auth-login.ts auth.login adapter (channels login) - └── auth-logout.ts gateway.logoutAccount adapter + +DM policy is configured per-account through `openclaw config`: + +```bash +openclaw config set channels.helloagent.dmPolicy allowlist +openclaw config set channels.helloagent.allowFrom.0 alice ``` -## What this MVP does NOT include (deferred) +| `dmPolicy` | Behavior | +|---|---| +| `allowlist` (default) | Only handles in `allowFrom` can DM the agent | +| `pairing` | New peers must approve a pairing code first | +| `allow-all` | Any HelloAgent peer can DM (a warning is logged) | +| `deny-all` | Inbound DMs are dropped | + +## Capabilities -- `actions: ChannelMessageActionAdapter` — only `outbound.sendText` for now. -- Media / payloads / cards. `outbound.sendMedia` and `sendPayload` are stubs - that throw "not implemented". -- `directory` adapter (peer/group enumeration). -- `setup` wizard adapter (no `openclaw setup` integration; pairing is via - `openclaw channels login --channel helloagent`). -- HelloAgent-specific tools (`helloagent_send`, search-handle, etc.). -- Skills directory. -- CLI diagnostics (`helloagent doctor`, `helloagent diagnose`). -- Reactions, typing indicator, edit/delete. +| | | +|---|---| +| Direct messages | yes | +| Streaming replies | yes — chunked back to the peer | +| Inbound dedup | yes — TTL + LRU | +| Multi-account | yes — under `channels.helloagent.accounts.` | +| Media / rich payloads | no — relay carries text only | +| Reactions, typing, edit, delete | no | +| Threads / groups | no | -These are the next wave once the MVP compiles and pairs cleanly. +## Multiple accounts -## Local development +Each named account has its own `creds.json` and cfg block: -```sh +```json +{ + "channels": { + "helloagent": { + "accounts": { + "work": { "enabled": true, "dmPolicy": "allowlist", "allowFrom": ["alice"] }, + "personal": { "enabled": true, "dmPolicy": "allow-all" } + } + } + } +} +``` + +Pair them with `--account`: + +```bash +openclaw channels login --channel helloagent --account work +``` + +## Environment variables + +| Variable | Default | Purpose | +|---|---|---| +| `HELLOAGENT_API_URL` | `https://api.helloagent.cc` | REST base for OAuth + channel link | +| `HELLOAGENT_WEB_URL` | `https://app.helloagent.cc` | Web app URL (token-issue page) | +| `HELLOAGENT_RELAY_WS_URL` | `wss://api.helloagent.cc/v1/ws` | Relay WebSocket | +| `HELLOAGENT_AGENT_NAME` | `jarvis` | Agent suffix used during pair | +| `HELLOAGENT_PAIR_MODE` | `import` | `import` / `oauth` / `device` | +| `HELLOAGENT_OAUTH_CLIENT_ID` | `openclaw` | OAuth client id (PKCE flow) | +| `HELLOAGENT_DEBUG` | `0` | Set to `1` for verbose plugin logs | + +## Development + +```bash +git clone https://github.com/helloagentai/helloagent-openclaw +cd helloagent-openclaw npm install npm run typecheck npm run build npm run test:smoke ``` +### Running from source + +To make your local OpenClaw CLI load this repo instead of a published version: + +```bash +# 1. Build +npm run build + +# 2. Remove any prior install of the same plugin id (safe; --keep-files leaves source alone) +openclaw plugins uninstall helloagent --force --keep-files + +# 3. Link this directory as the plugin source +openclaw plugins install . --link + +# 4. Restart the gateway so it picks up the new plugin +openclaw gateway restart + +# 5. Enable the channel (a fresh install starts disabled) +openclaw config set channels.helloagent.enabled true + +# 6. Pair +openclaw channels login --channel helloagent +``` + +After editing source, rebuild and either restart the gateway or clear OpenClaw's compile cache: + +```bash +npm run build +rm -rf ~/.openclaw/tmp/jiti +``` + ## License -MIT +[MIT](LICENSE) diff --git a/index.cjs b/index.cjs index 355022c..5afec5e 100644 --- a/index.cjs +++ b/index.cjs @@ -4,9 +4,9 @@ * `require()` synchronously. This file exposes the ESM plugin (./dist/index.js) * as a CJS module by leveraging Node's >=22.12 require-of-ESM support. * - * Mirrors the published `@larksuite/openclaw-lark` shape: a CJS file at the - * package root pointed at by `package.json.openclaw.extensions`. The actual - * implementation stays in dist/ as ESM. + * The package root holds this CJS shim (pointed at by + * `package.json.openclaw.extensions`) while the implementation lives in + * dist/ as ESM. */ const esm = require("./dist/index.js"); diff --git a/src/auth/login-oauth.ts b/src/auth/login-oauth.ts index 2fc797d..af34e08 100644 --- a/src/auth/login-oauth.ts +++ b/src/auth/login-oauth.ts @@ -4,11 +4,7 @@ * access token, calls /v1/channels/openclaw/link, and persists the returned * ha_* token to disk. */ -import { - HelloAgentApiError, - linkChannel, - oauthExchangeToken, -} from "@helloagentai/sdk"; +import { linkChannel, oauthExchangeToken } from "@helloagentai/sdk"; import { CREDS_VERSION, @@ -63,5 +59,3 @@ export async function exchangeAndPersist( await writeCreds(creds, accountId); return creds; } - -export { HelloAgentApiError }; diff --git a/src/auth/login.ts b/src/auth/login.ts index 4d5cadb..ba7f1f8 100644 --- a/src/auth/login.ts +++ b/src/auth/login.ts @@ -2,14 +2,15 @@ * 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. + * 2. Print the consent URL for the user to open in their browser. * 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. + * + * The user opens the URL themselves; we don't spawn a browser process. An + * embedder can inject auto-open behavior via `openBrowser` if needed. */ -import { spawn } from "node:child_process"; import crypto from "node:crypto"; import http from "node:http"; import { AddressInfo } from "node:net"; @@ -31,6 +32,7 @@ export type PairOptions = { accountId?: string; /** Wait this long for the browser callback before giving up. Default 5min. */ timeoutMs?: number; + /** Optional hook embedders can use to auto-open the consent URL. */ openBrowser?: (url: string) => void; onProgress?: (line: string) => void; }; @@ -63,8 +65,7 @@ export async function pairHelloAgent(opts: PairOptions): Promise undefined); - child.unref(); - } catch { - /* swallow */ - } -} diff --git a/src/channel/config-adapter.ts b/src/channel/config-adapter.ts index aa673eb..c976880 100644 --- a/src/channel/config-adapter.ts +++ b/src/channel/config-adapter.ts @@ -1,10 +1,10 @@ /** * Configuration merge helpers for HelloAgent account management. * - * Mirrors Lark's config-adapter.ts: centralises the pattern of merging a - * partial configuration patch into the HelloAgent section of the top-level - * OpenClaw config, handling both the default account (top-level fields) and - * named accounts (nested under `accounts`). + * Centralises the pattern of merging a partial configuration patch into the + * HelloAgent section of the top-level OpenClaw config, handling both the + * default account (top-level fields) and named accounts (nested under + * `accounts`). * * Plus: `collectHelloAgentSecurityWarnings` produces user-facing warnings * for the channel plugin's `security.collectWarnings` adapter. @@ -127,7 +127,7 @@ export function deleteAccount>( * Produce user-facing security warnings for a HelloAgent account. * Surfaced through the channel plugin's `security.collectWarnings`. * - * MVP rules: + * Rules: * - dmPolicy="allow-all" with no allowFrom → warn (anyone can DM the agent). * - allowFrom configured with dmPolicy="allow-all" → warn (allowFrom is ignored). */ diff --git a/src/channel/event-handlers.ts b/src/channel/event-handlers.ts index d8ca938..d307523 100644 --- a/src/channel/event-handlers.ts +++ b/src/channel/event-handlers.ts @@ -1,13 +1,11 @@ /** * Event handlers for the per-account HelloAgent client. * - * Mirrors Lark's channel/event-handlers.ts: per-event functions that receive - * a `MonitorContext` and pre-filter (dedup, expiry) before handing off to - * the inbound dispatcher. + * Per-event functions receive a `MonitorContext` and pre-filter (dedup, expiry) + * before handing off to the inbound dispatcher. * - * MVP scope: only `handleIncomingMessage`. Reactions, comment events, - * card actions, and bot membership changes are not part of HelloAgent's - * relay protocol yet. + * The relay protocol currently carries `IncomingMessage` only — there are no + * reaction events, card actions, or membership changes to handle. */ import type { IncomingMessage } from "@helloagentai/sdk"; diff --git a/src/channel/monitor.ts b/src/channel/monitor.ts index a719bab..8a80546 100644 --- a/src/channel/monitor.ts +++ b/src/channel/monitor.ts @@ -1,6 +1,5 @@ /** - * Per-account WebSocket monitor — replaces the role of the old - * `session-manager.ts` and aligns with Lark's `channel/monitor.ts` shape. + * Per-account WebSocket monitor. * * `startAccount(ctx)` is what the gateway adapter (`gateway.startAccount` in * src/channel/plugin.ts) hands off to. It: @@ -13,8 +12,8 @@ * 5. Awaits `gatewayCtx.abortSignal` — does NOT return early. The host's * channel-runtime treats `startAccount` resolution as "channel exited" * and schedules an auto-restart, which crashes if its internal logger - * is undefined (server.impl-hNr66nDN.js:2073). Lark's monitor follows - * the same long-running-promise contract. + * is undefined (server.impl-hNr66nDN.js:2073). The contract is to stay + * pending until the host signals abort, then clean up. * * `stopAccount(accountId)` tears down the live client. */ @@ -117,8 +116,7 @@ export async function startAccount( // channel-runtime interprets that as "channel exited" and enters its // auto-restart machinery — which has a bug // (server.impl-hNr66nDN.js:2073: log.info?.() on undefined log) that - // crashes the entire gateway. Mirror Lark's `await lark.startWS({...})` - // pattern: stay pending until abort, then clean up. + // crashes the entire gateway. Stay pending until abort, then clean up. await new Promise((resolve) => { if (gatewayCtx.abortSignal.aborted) { resolve(); diff --git a/src/channel/plugin.ts b/src/channel/plugin.ts index d0ce8ee..27734f9 100644 --- a/src/channel/plugin.ts +++ b/src/channel/plugin.ts @@ -5,13 +5,12 @@ * * This is intentionally a plain literal (no `createChatChannelPlugin` wrapper) * so we can populate the richer surfaces — `security`, `pairing`, `status`, - * `reload`, `agentPrompt`, `messaging` — that the wrapper hides. Mirrors - * Lark's `feishuPlugin` shape from `larksuite/openclaw-lark`. + * `reload`, `agentPrompt`, `messaging` — that the wrapper hides. * * Adapters wired here: * * meta label / blurb / docs - * capabilities chatTypes (DM only for MVP), media/reactions/threads = false + * capabilities chatTypes (direct only); media/reactions/threads = false * reload configPrefixes for hot reload * agentPrompt message-tool hints for HelloAgent handle conventions * pairing pairing-code DM flow (notify via outbound send) @@ -314,8 +313,7 @@ export const helloAgentPlugin: ChannelPlugin = { // ------------------------------------------------------------------------- // Threading — reply to the message that triggered the turn so the peer's - // UI threads the response under the inbound. "first" matches the prior - // plugin's `topLevelReplyToMode: "reply"` semantics under the current SDK. + // UI threads the response under the inbound. // ------------------------------------------------------------------------- threading: { @@ -323,7 +321,8 @@ export const helloAgentPlugin: ChannelPlugin = { }, // ------------------------------------------------------------------------- - // Outbound — sendText only for MVP. + // Outbound — sendText. sendMedia/sendPayload throw (relay does not carry + // media or rich payloads). // ------------------------------------------------------------------------- outbound: helloAgentOutbound, diff --git a/src/channel/probe.ts b/src/channel/probe.ts index 1963c21..1815493 100644 --- a/src/channel/probe.ts +++ b/src/channel/probe.ts @@ -2,10 +2,9 @@ * Health probe for the HelloAgent channel. * * The host's `status.probeAccount` calls this to decide whether the channel - * is reachable for a given account. Mirrors Lark's `probeFeishu` which calls - * the bot/v3/info API. + * is reachable for a given account. * - * MVP strategy: + * Strategy: * - If a HaClient is registered and ready → ok=true (we know the WS is up). * - If a HaClient is registered but `needs_repairing` → ok=false with the * stored auth-failed detail. diff --git a/src/commands/auth-login.ts b/src/commands/auth-login.ts index 335a46f..c8b3c0a 100644 --- a/src/commands/auth-login.ts +++ b/src/commands/auth-login.ts @@ -83,10 +83,14 @@ async function readTokenFromStdin( } const rl = createInterface({ input, output }); try { - runtime.log("[helloagent] To link this assistant, create an agent and copy its ha_* token:"); - runtime.log(`[helloagent] → ${hint.issueUrl}`); - runtime.log("[helloagent] Paste the token below, then press Enter:"); - const token = (await rl.question("")).trim(); + runtime.log(""); + runtime.log("Link this assistant to a HelloAgent account:"); + runtime.log(""); + runtime.log(` 1. Open ${hint.issueUrl}`); + runtime.log(" 2. Create an agent and copy its token (starts with \"ha_\")"); + runtime.log(" 3. Paste the token below"); + runtime.log(""); + const token = (await rl.question("Token: ")).trim(); if (!token) throw new Error("helloagent: empty token"); return token; } finally { @@ -111,9 +115,6 @@ export async function loginHelloAgent(params: LoginParams): Promise { const agentName = envOr("HELLOAGENT_AGENT_NAME", DEFAULT_AGENT_NAME); const mode = resolvePairMode(); - log(`[helloagent] pairing mode=${mode} account=${accountId} agent=${agentName}`); - log(`[helloagent] api=${apiUrl} relay=${relayWs}`); - if (mode === "oauth") { const creds = await pairHelloAgent({ agentName, diff --git a/src/core/accounts.ts b/src/core/accounts.ts index f0dfe94..a3e9e1f 100644 --- a/src/core/accounts.ts +++ b/src/core/accounts.ts @@ -97,11 +97,6 @@ export function listAccountIds(cfg: unknown): string[] { return [...combined]; } -export function defaultAccountId(): string { - const ids = accountCache.listAccountIds(); - return ids[0] ?? DEFAULT_ACCOUNT_ID; -} - /** * Resolve a single account by merging disk creds with cfg overrides. The * resolved view is what host status/security/lifecycle code consumes. @@ -137,43 +132,3 @@ export function getAccount(cfg: unknown, accountId?: string | null): HelloAgentA }; } -/** - * Strict variant — used by code paths that have already verified pairing - * (e.g. lifecycle.startAccount once the host has filtered by isEnabled). - */ -export function getResolvedAccountOrThrow( - cfg: unknown, - accountId?: string | null, -): ResolvedHelloAgentAccount { - const account = getAccount(cfg, accountId); - if (!account.resolved) { - throw new Error( - `helloagent: account ${account.accountId} is not paired. ` + - `Run \`openclaw channels login --channel helloagent\` first.`, - ); - } - return account.resolved; -} - -/** - * Async variant for code paths outside the gateway hot path (CLI, auth, etc.). - * Reads creds from disk directly rather than going through the cache. - */ -export async function loadAccount( - accountId: string = DEFAULT_ACCOUNT_ID, -): Promise { - const { readCreds } = await import("./auth-store.js"); - const creds = await readCreds(accountId); - if (!creds) return null; - return credsToAccount(accountId, creds); -} - -export async function loadAccountOrThrow( - accountId: string = DEFAULT_ACCOUNT_ID, -): Promise { - const account = await loadAccount(accountId); - if (!account) { - throw new Error(`helloagent: account ${accountId} is not paired`); - } - return account; -} diff --git a/src/core/cfg-store.ts b/src/core/cfg-store.ts index c062bad..49c18b0 100644 --- a/src/core/cfg-store.ts +++ b/src/core/cfg-store.ts @@ -1,37 +1,19 @@ /** * Atomic read/write for the OpenClaw config file (`openclaw.json`). * - * Why this exists: when the user runs `openclaw channels login --channel - * helloagent`, the host's post-login reconciler tries to call - * `channels.start` over the gateway WebSocket so the new account becomes - * live without a daemon restart. That call requires the gateway to be - * reachable AND the CLI to have valid credentials for it. In two common - * cases — the gateway is down, or the user is targeting a non-default - * gateway URL/port without auth — the reconciler bails with: - * - * Local login saved auth for helloagent/default, but the running - * gateway did not restart it: gateway url override requires explicit - * credentials - * - * Critically, the reconciler also does NOT update the cfg file. So even - * though creds.json is on disk, `channels.helloagent` is missing from - * `cfg.channels`, and the channel becomes invisible to: - * - * - `openclaw channels list` (it filters by `cfg.channels.` presence) - * - the gateway's auto-start loop on next boot - * - * This module fixes that by giving our `auth.login` adapter a way to write - * `cfg.channels.helloagent` directly, so pairing is "single-step - * pair-and-go" regardless of gateway reachability. - * - * Path resolution mirrors openclaw's own (paths-B2cMK-wd.js): + * Used by `auth.login` to write `channels.helloagent.enabled=true` directly + * after pairing, so the channel becomes visible to `channels list` and + * auto-starts on next gateway boot — regardless of whether the host's + * post-login reconciler can reach the running gateway (it skips the cfg + * update when the gateway is down or running with a URL override that + * requires explicit credentials). * + * Path resolution: * 1. `OPENCLAW_CONFIG_PATH` env var if set (fully qualified path). * 2. `${OPENCLAW_STATE_DIR}/openclaw.json` if state dir is set. * 3. `~/.openclaw/openclaw.json`. * - * Atomic write: temp file + rename + .bak rotation. Same crash-safety - * guarantees as `auth-store.ts` for creds. + * Atomic write: temp file + rename + `.bak` rotation. */ import { promises as fs } from "node:fs"; import os from "node:os"; diff --git a/src/core/ha-client.ts b/src/core/ha-client.ts index 891aba1..2ec1a40 100644 --- a/src/core/ha-client.ts +++ b/src/core/ha-client.ts @@ -3,12 +3,8 @@ * * One `HaClient` wraps one `Agent` from `@helloagentai/sdk` plus the lifecycle * state needed to expose it through the channel plugin's status surface - * (starting / ready / needs_repairing / stopped). - * - * Replaces the role of the old `session-manager.ts` by reorganising along - * Lark's structure: a `HaClient` is to HelloAgent what `LarkClient` is to - * Feishu — the per-account handle that lifecycle, outbound, and probe code - * all share. + * (starting / ready / needs_repairing / stopped). It is the single per-account + * handle that lifecycle, outbound, and probe code all share. */ import { Agent, AuthFailedError, type IncomingMessage } from "@helloagentai/sdk"; @@ -173,7 +169,3 @@ export function stopAllClients(): void { } clients.clear(); } - -export function listClientIds(): string[] { - return [...clients.keys()]; -} diff --git a/src/core/ha-logger.ts b/src/core/ha-logger.ts index 659c94d..7550167 100644 --- a/src/core/ha-logger.ts +++ b/src/core/ha-logger.ts @@ -1,11 +1,10 @@ /** - * Namespaced logger factory. Mirrors Lark's `larkLogger('category')` pattern - * so log lines carry a stable prefix like `[helloagent/channel/monitor]`, - * making it easy to grep daemon output for plugin activity. + * Namespaced logger factory. Each call produces a logger that prefixes lines + * with `[helloagent/]`, making it easy to grep daemon output for + * plugin activity. * - * No external dependencies — falls back to console.* with a small wrapper - * so the runtime doesn't need pino/winston/etc. The host's log pipeline - * captures stdout/stderr regardless. + * No external dependencies — wraps `console.*` so the runtime doesn't need + * pino/winston/etc. The host's log pipeline captures stdout/stderr regardless. */ type LogLevel = "info" | "warn" | "error" | "debug"; diff --git a/src/core/types.ts b/src/core/types.ts index b4d41f2..c9757d6 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -19,7 +19,7 @@ export type ResolvedHelloAgentAccount = { }; /** - * Lark-style "account view" returned by config.resolveAccount. Combines the + * Combined "account view" returned by config.resolveAccount. Pairs the * disk-resident creds with the host-managed enabled/configured flags so the * status panel can describe an account that is paired but disabled, or * referenced in cfg but not yet paired. diff --git a/src/messaging/inbound/dedup.ts b/src/messaging/inbound/dedup.ts index de5e9e4..425e435 100644 --- a/src/messaging/inbound/dedup.ts +++ b/src/messaging/inbound/dedup.ts @@ -3,8 +3,7 @@ * * The relay re-delivers undelivered messages on WebSocket reconnect, so a * brief disconnect can produce duplicates. Without dedup, the agent would - * dispatch the same inbound twice, sending the user two replies. This - * mirrors Lark's `MessageDedup` (src/messaging/inbound/dedup.ts). + * dispatch the same inbound twice, sending the user two replies. * * - `tryRecord(messageId, accountId)` returns false if the (id, account) * pair was seen recently. Returns true (and records) on first sight. diff --git a/src/messaging/inbound/dispatch.ts b/src/messaging/inbound/dispatch.ts index 6460f6b..9471115 100644 --- a/src/messaging/inbound/dispatch.ts +++ b/src/messaging/inbound/dispatch.ts @@ -1,10 +1,8 @@ /** * Streaming inbound dispatch. * - * Replaces the prior "collect-then-return-one-string" approach in - * inbound-bridge.ts with a true streaming bridge. The SDK's - * `Agent.onMessage` handler can return an `AsyncIterable`; each - * yielded value becomes a separate `StreamChunk` back to the peer (final + * The SDK's `Agent.onMessage` handler can return an `AsyncIterable`; + * each yielded value becomes a separate `StreamChunk` back to the peer (final * chunk with `is_final=true`). The OpenClaw reply dispatcher emits a * `deliver(payload)` call per text block; we forward each one as a yield. * @@ -73,10 +71,10 @@ async function* streamDispatch( return; } - // Type-erasure cast — see the original inbound-bridge.ts for the full - // explanation. The plugin-sdk types `channelRuntime` as the minimal - // ChannelRuntimeSurface for forward-compat, but the actual object is the - // full createPluginRuntime().channel surface. + // The plugin-sdk types `channelRuntime` as the minimal ChannelRuntimeSurface + // for forward-compat, but the actual object is the full + // createPluginRuntime().channel surface — cast to expose the wider shape + // dispatchInboundDirectDmWithRuntime expects. const runtime = { channel: channelRuntime as unknown as Parameters< typeof dispatchInboundDirectDmWithRuntime diff --git a/src/messaging/outbound/outbound.ts b/src/messaging/outbound/outbound.ts index a49e4f6..504b314 100644 --- a/src/messaging/outbound/outbound.ts +++ b/src/messaging/outbound/outbound.ts @@ -9,10 +9,10 @@ * via `messaging/inbound/dispatch.ts` (an AsyncIterable that the * SDK turns into StreamChunks), NOT through this adapter. * - * MVP scope: - * - `sendText` ✅ - * - `sendMedia` ❌ (throws; deferred — relay does not yet ship media) - * - `sendPayload` ❌ (throws; deferred — no rich-payload support yet) + * Supported operations: + * - `sendText` — routes through the relay session. + * - `sendMedia` — throws; the relay does not carry media. + * - `sendPayload` — throws; the relay does not carry rich payloads. * * Conventions: * - `deliveryMode: "direct"` — we own the WebSocket; no gateway hop. @@ -57,13 +57,13 @@ export const helloAgentOutbound: ChannelOutboundAdapter = { async sendMedia() { throw new Error( - "helloagent: sendMedia is not implemented yet — the relay does not ship media in MVP", + "helloagent: sendMedia is not supported — the relay does not carry media", ); }, async sendPayload() { throw new Error( - "helloagent: sendPayload is not implemented yet — no rich-payload (channelData) support in MVP", + "helloagent: sendPayload is not supported — the relay does not carry rich payloads (channelData)", ); }, }; diff --git a/tests/cache-debug.ts b/tests/cache-debug.ts deleted file mode 100644 index 4305327..0000000 --- a/tests/cache-debug.ts +++ /dev/null @@ -1,39 +0,0 @@ -/** - * One-off debug: with OPENCLAW_STATE_DIR set the way --profile sets it, - * what does our account-cache see, AND what does helloAgentPlugin.config.listAccountIds - * (which `channels list` calls) return? - */ -import * as accountCache from "../src/core/account-cache.js"; -import { resolveHelloAgentAuthDir } from "../src/core/auth-store.js"; -import { helloAgentPlugin } from "../src/channel/plugin.js"; - -console.log("env OPENCLAW_STATE_DIR =", process.env.OPENCLAW_STATE_DIR ?? "(unset)"); -console.log("env OPENCLAW_PROFILE =", process.env.OPENCLAW_PROFILE ?? "(unset)"); -console.log("env HELLOAGENT_AUTH_DIR=", process.env.HELLOAGENT_AUTH_DIR ?? "(unset)"); -console.log("resolveHelloAgentAuthDir →", resolveHelloAgentAuthDir()); - -console.log("\n--- accountCache direct ---"); -accountCache.init(); -const cacheIds = accountCache.listAccountIds(); -console.log("accountCache.listAccountIds →", cacheIds); - -console.log("\n--- helloAgentPlugin.config.listAccountIds (what `channels list` calls) ---"); -const cfgEmpty = {}; -const ids = helloAgentPlugin.config!.listAccountIds!(cfgEmpty as never); -console.log(`with cfg={}: → ${JSON.stringify(ids)}`); - -const cfgWithChannel = { channels: { helloagent: { enabled: true } } }; -const idsWithChannel = helloAgentPlugin.config!.listAccountIds!(cfgWithChannel as never); -console.log(`with cfg.channels.helloagent={enabled:true}: → ${JSON.stringify(idsWithChannel)}`); - -console.log("\n--- inspectAccount ---"); -const insp = helloAgentPlugin.config!.inspectAccount!(cfgEmpty as never, "default"); -console.log("inspectAccount(cfg={}, 'default') →", insp); - -console.log("\n--- resolveAccount ---"); -try { - const acc = helloAgentPlugin.config!.resolveAccount(cfgEmpty as never, "default"); - console.log("resolveAccount → handle:", acc.handle); -} catch (err) { - console.log("resolveAccount threw:", (err as Error).message); -} diff --git a/tests/e2e-cfg-write.ts b/tests/e2e-cfg-write.ts deleted file mode 100644 index 1f58d9b..0000000 --- a/tests/e2e-cfg-write.ts +++ /dev/null @@ -1,73 +0,0 @@ -/** - * End-to-end verification that the auth-login fix works without requiring - * a real device-code human-approval round-trip. - * - * Simulates exactly what `loginHelloAgent` does post-pair: - * 1. Confirm cfg.channels.helloagent is absent (matches "fresh pair" state). - * 2. Call `persistChannelEnabled` (extracted from auth-login.ts). - * 3. Confirm cfg.channels.helloagent.enabled = true is now on disk. - * 4. Confirm reading the cfg back yields the same shape openclaw expects. - * - * Intentionally targets ~/.openclaw-ha-test (set via OPENCLAW_STATE_DIR) - * so we can manually inspect with `openclaw --profile ha-test channels list` - * after this script runs. - */ -import { mergeHelloAgentAccountConfig, readCfg, resolveCfgPath } from "../src/core/cfg-store.js"; - -async function main(): Promise { - const stateDir = process.env.OPENCLAW_STATE_DIR ?? "(unset)"; - console.log(`[e2e] OPENCLAW_STATE_DIR=${stateDir}`); - console.log(`[e2e] cfg path: ${resolveCfgPath()}`); - - const before = await readCfg(); - const beforeChannels = (before.channels as Record | undefined) ?? {}; - console.log( - `[e2e] BEFORE: channels.helloagent =`, - JSON.stringify(beforeChannels.helloagent ?? null), - ); - - if (beforeChannels.helloagent != null) { - console.log( - "[e2e] WARNING: channels.helloagent already present; the fix would still work but the test is less interesting.", - ); - } - - console.log("[e2e] simulating post-pair cfg write (mergeHelloAgentAccountConfig)..."); - const result = await mergeHelloAgentAccountConfig("default", { enabled: true }); - - const afterChannels = (result.after.channels as Record | undefined) ?? {}; - console.log( - `[e2e] AFTER: channels.helloagent =`, - JSON.stringify(afterChannels.helloagent ?? null), - ); - - // Re-read from disk and verify it matches. - const onDisk = await readCfg(); - const onDiskChannels = (onDisk.channels as Record | undefined) ?? {}; - const onDiskHelloAgent = onDiskChannels.helloagent as { enabled?: boolean } | undefined; - if (onDiskHelloAgent?.enabled === true) { - console.log(`[e2e] ✅ cfg on disk now has channels.helloagent.enabled = true`); - } else { - console.error(`[e2e] ❌ cfg on disk does NOT have the expected entry`); - console.error(`[e2e] raw channels =`, JSON.stringify(onDiskChannels)); - process.exit(1); - } - - // Verify other fields are preserved. - const expectedKeys = Object.keys(before).filter((k) => k !== "channels"); - for (const k of expectedKeys) { - if (JSON.stringify(onDisk[k]) !== JSON.stringify(before[k])) { - console.error(`[e2e] ❌ unrelated field "${k}" was modified`); - process.exit(1); - } - } - console.log(`[e2e] ✅ unrelated cfg fields preserved (${expectedKeys.length})`); - - console.log(""); - console.log("[e2e] PASS — run `openclaw --profile ha-test channels list` to see the channel."); -} - -main().catch((err) => { - console.error("[e2e] FATAL:", err); - process.exit(1); -}); diff --git a/tests/smoke.ts b/tests/smoke.ts index 8e2c329..6b0a373 100644 --- a/tests/smoke.ts +++ b/tests/smoke.ts @@ -1,12 +1,12 @@ /** - * No-relay smoke test for the new HelloAgent channel plugin. + * No-relay smoke test for the HelloAgent channel plugin. * - * Validates structurally what we just built — without opening a WebSocket, - * without spawning openclaw, without touching the user's home directory: + * Validates structurally without opening a WebSocket, spawning openclaw, or + * touching the user's home directory: * - * 1. Plugin shape: every adapter we wired exists at the right path with - * the right type (ChannelPlugin literal: id, meta, capabilities, - * reload, agentPrompt, pairing, security, configSchema, config, setup, + * 1. Plugin shape: every adapter exists at the right path with the right + * type (ChannelPlugin literal: id, meta, capabilities, reload, + * agentPrompt, pairing, security, configSchema, config, setup, * messaging, threading, outbound, status, gateway, auth). * 2. Account list/resolve via cfg+disk merge. * 3. Disk creds → account-cache → plugin.config.listAccountIds / .resolveAccount. @@ -18,7 +18,6 @@ * 8. messaging.normalizeTarget / targetResolver behavior. * * Run: - * cd integrations/openclaw-HelloAgent * npm run test:smoke */ import { mkdtemp, rm } from "node:fs/promises";