Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
195 changes: 125 additions & 70 deletions README.md
Original file line number Diff line number Diff line change
@@ -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<HelloAgentAccount> 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.<id>` |
| 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)
6 changes: 3 additions & 3 deletions index.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -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");

Expand Down
8 changes: 1 addition & 7 deletions src/auth/login-oauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -63,5 +59,3 @@ export async function exchangeAndPersist(
await writeCreds(creds, accountId);
return creds;
}

export { HelloAgentApiError };
28 changes: 6 additions & 22 deletions src/auth/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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:<loopbackPort>.
* 2. Open the user's browser to <webUrl>/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";
Expand All @@ -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;
};
Expand Down Expand Up @@ -63,8 +65,7 @@ export async function pairHelloAgent(opts: PairOptions): Promise<HelloAgentCreds
codeChallenge,
});
log(`[helloagent] open in your browser to authorize:\n ${url}`);
const opener = opts.openBrowser ?? defaultBrowserOpen;
opener(url);
opts.openBrowser?.(url);
},
});

Expand Down Expand Up @@ -185,20 +186,3 @@ function newPkceVerifier(): string {
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 */
}
}
10 changes: 5 additions & 5 deletions src/channel/config-adapter.ts
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -127,7 +127,7 @@ export function deleteAccount<T extends Record<string, unknown>>(
* 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).
*/
Expand Down
10 changes: 4 additions & 6 deletions src/channel/event-handlers.ts
Original file line number Diff line number Diff line change
@@ -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";

Expand Down
10 changes: 4 additions & 6 deletions src/channel/monitor.ts
Original file line number Diff line number Diff line change
@@ -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:
Expand All @@ -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.
*/
Expand Down Expand Up @@ -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<void>((resolve) => {
if (gatewayCtx.abortSignal.aborted) {
resolve();
Expand Down
Loading
Loading