diff --git a/README.md b/README.md index 211625e..583a916 100644 --- a/README.md +++ b/README.md @@ -5,65 +5,98 @@ [![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. +Connects an OpenClaw assistant to the [HelloAgent](https://app.helloagent.cc) network over a long-lived relay WebSocket. Built on [`@helloagentai/sdk`](https://www.npmjs.com/package/@helloagentai/sdk). -Built on [`@helloagentai/sdk`](https://www.npmjs.com/package/@helloagentai/sdk). +## Get started -## Install +1. Create an agent at [app.helloagent.cc/app/agents/new](https://app.helloagent.cc/app/agents/new) and copy the `ha_*` token it shows. +2. Run: ```bash -npm install @helloagentai/openclaw +openclaw plugins install @helloagentai/openclaw +openclaw gateway restart +openclaw channels login --channel helloagent +# paste the ha_* token at the prompt ``` -OpenClaw discovers the plugin automatically on the next gateway boot. +That's it. The plugin auto-enables `channels.helloagent` in your `openclaw.json` on first import, so login works without any prior `config set`. Credentials are written to `~/.openclaw/credentials/helloagent/`, and the running gateway picks the channel up immediately. + +> If you don't have a gateway running yet, skip `openclaw gateway restart` — the channel will come up on your next `openclaw gateway run`. -## Pair an agent +## Troubleshooting + +### `Channel login failed: Error: Unsupported channel: helloagent` + +OpenClaw doesn't have `channels.helloagent` in your config yet. Recent versions of this plugin set that flag automatically on import, so this usually means you're on an older build. Fix it manually: ```bash +openclaw config set channels.helloagent.enabled true +openclaw gateway restart # only if a gateway is running 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`: +If the error persists, confirm the plugin is installed and enabled: -| 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 | +```bash +openclaw plugins list | grep -i helloagent # should show "enabled" +openclaw plugins doctor # should report no issues +``` -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. +### `Channel login failed: Error: helloagent: no token received on stdin` -## Usage +You pressed Enter without typing the token, or stdin was piped from an empty source. Re-run interactively and paste your `ha_*` token at the prompt: ```bash -openclaw channels list # show channel + account status -openclaw channels logout --channel helloagent # remove credentials +openclaw channels login --channel helloagent ``` -DM policy is configured per-account through `openclaw config`: +Or pipe the token directly: ```bash -openclaw config set channels.helloagent.dmPolicy allowlist -openclaw config set channels.helloagent.allowFrom.0 alice +echo "$HA_TOKEN" | openclaw channels login --channel helloagent ``` -| `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 | +### Login succeeds but messages don't arrive + +Check the channel status: + +```bash +openclaw channels status --channel helloagent --probe +``` + +If the account shows as not connected and you have a gateway already running, restart it so it picks up the new credentials: + +```bash +openclaw gateway restart +``` + +Then verify with `openclaw channels logs --channel helloagent` that the WebSocket reaches `connected`. + +### Token rejected or expired -## Uninstalling +Tokens are one-shot — once paired, the original `ha_*` value is consumed. Generate a new one at [app.helloagent.cc/app/agents/new](https://app.helloagent.cc/app/agents/new) and re-run the login. -`openclaw plugins uninstall helloagent` removes the cfg entry, install record, and load path — but it does **not** wipe credentials. Log out each account first so the live WebSocket session is torn down and the `creds.json` files are deleted: +### Behind a corporate proxy + +Set `HTTPS_PROXY` and `HTTP_PROXY` in the environment that runs the gateway (not just the CLI) — the relay WebSocket runs inside the gateway process. + +### Verbose logs + +```bash +HELLOAGENT_DEBUG=1 openclaw channels login --channel helloagent +HELLOAGENT_DEBUG=1 openclaw gateway run +``` + +## Uninstall + +`openclaw plugins uninstall helloagent` removes the cfg entry, install record, and load path — but it does **not** wipe credentials. Log out each account first so the live WebSocket is torn down and `creds.json` is deleted: ```bash openclaw channels logout --channel helloagent # repeat per --account if you have several openclaw plugins uninstall helloagent ``` -Or, if you've already uninstalled and want to scrub leftover tokens: +If you've already uninstalled and want to scrub leftover tokens: ```bash rm -rf ~/.openclaw/credentials/helloagent @@ -81,39 +114,13 @@ rm -rf ~/.openclaw/credentials/helloagent | Reactions, typing, edit, delete | no | | Threads / groups | no | -## Multiple accounts - -Each named account has its own `creds.json` and cfg block: - -```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_API_URL` | `https://api.helloagent.cc` | REST base used during token import | | `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_RELAY_WS_URL` | `wss://api.helloagent.cc/v1/ws` | Relay WebSocket the gateway connects to | | `HELLOAGENT_DEBUG` | `0` | Set to `1` for verbose plugin logs | ## Development @@ -127,31 +134,17 @@ npm run build npm run test:smoke ``` -### Running from source - -To make your local OpenClaw CLI load this repo instead of a published version: +To run this checkout against your local OpenClaw CLI: ```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 uninstall helloagent --force --keep-files # safe if not installed 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 +openclaw gateway restart # if the gateway is running +openclaw channels login --channel helloagent # cfg auto-enables on import ``` -After editing source, rebuild and either restart the gateway or clear OpenClaw's compile cache: +After editing source, rebuild and clear OpenClaw's compile cache so the next gateway run picks up the change: ```bash npm run build diff --git a/index.ts b/index.ts index c1c7c9c..0937665 100644 --- a/index.ts +++ b/index.ts @@ -15,8 +15,13 @@ import { defineChannelPluginEntry } from "openclaw/plugin-sdk/channel-core"; import * as accountCache from "./src/core/account-cache.js"; import { stopAccount } from "./src/channel/monitor.js"; import { helloAgentPlugin } from "./src/channel/plugin.js"; +import { ensureHelloAgentChannelEnabled } from "./src/core/auto-enable-channel.js"; import { haLogger } from "./src/core/ha-logger.js"; +// See setup-entry.ts: same side effect, mirrored here so that whichever +// entry openclaw imports first auto-enables the channel. +ensureHelloAgentChannelEnabled(); + const log = haLogger("plugin"); function wireAutoTeardownOnCredsRemoval(): void { diff --git a/setup-entry.ts b/setup-entry.ts index e549c48..9c08cfd 100644 --- a/setup-entry.ts +++ b/setup-entry.ts @@ -8,7 +8,14 @@ */ import { defineSetupPluginEntry } from "openclaw/plugin-sdk/channel-core"; +import { ensureHelloAgentChannelEnabled } from "./src/core/auto-enable-channel.js"; import { helloAgentPlugin } from "./src/channel/plugin.js"; +// Auto-enable the channel on first import so `openclaw channels login +// --channel helloagent` resolves immediately after `plugins install`, +// without forcing the user to run `openclaw config set +// channels.helloagent.enabled true` first. See auto-enable-channel.ts. +ensureHelloAgentChannelEnabled(); + export const plugin = helloAgentPlugin; export default defineSetupPluginEntry(helloAgentPlugin); diff --git a/src/core/auto-enable-channel.ts b/src/core/auto-enable-channel.ts new file mode 100644 index 0000000..265c86b --- /dev/null +++ b/src/core/auto-enable-channel.ts @@ -0,0 +1,153 @@ +/** + * Ensure `cfg.channels.helloagent` exists in the user's openclaw config so + * that `openclaw channels login --channel helloagent` resolves the channel + * via OpenClaw's "configured-channels" plugin loader scope. + * + * Background: OpenClaw's CLI channel resolver only auto-loads plugins whose + * channel id is either (a) in the bundled official catalog, (b) in a local + * external catalog file, or (c) referenced under `cfg.channels.` (the + * "configured-channels" scope). HelloAgent is third-party so it isn't in + * the bundled catalog; without (c) the resolver throws "Unsupported channel: + * helloagent" before our plugin code ever runs. + * + * This helper runs as an import-time side effect from `setup-entry.ts` and + * `index.ts`. OpenClaw imports `setup-entry` early in its plugin + * auto-enable scan, which gives us a chance to: + * + * 1. Persist `cfg.channels.helloagent.enabled = true` to disk so all + * subsequent invocations resolve cleanly. Idempotent and respects an + * existing `enabled: false` (user opt-out). + * 2. Mutate the in-memory runtime config snapshot used by the current + * invocation, so the very first `channels login` after `plugins + * install` succeeds without forcing the user to retry. + * + * Both steps are best-effort: any error is swallowed so import never throws. + */ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +const CHANNEL_ID = "helloagent"; + +function resolveCfgPath(env: NodeJS.ProcessEnv = process.env): string { + const explicit = env.OPENCLAW_CONFIG_PATH?.trim(); + if (explicit) return explicit; + const stateDir = env.OPENCLAW_STATE_DIR?.trim() || path.join(os.homedir(), ".openclaw"); + return path.join(stateDir, "openclaw.json"); +} + +function isPlainObject(value: unknown): value is Record { + return Boolean(value && typeof value === "object" && !Array.isArray(value)); +} + +/** + * Returns true iff cfg already records an explicit decision for our channel + * (enabled or disabled). We never overwrite a user's explicit setting. + */ +function channelAlreadyDecided(cfg: Record): boolean { + const channels = isPlainObject(cfg.channels) ? cfg.channels : null; + if (!channels) return false; + const entry = channels[CHANNEL_ID]; + if (!isPlainObject(entry)) return false; + return Object.prototype.hasOwnProperty.call(entry, "enabled"); +} + +function patchCfgInPlace(cfg: Record): void { + const channels = isPlainObject(cfg.channels) ? { ...cfg.channels } : {}; + const existing = isPlainObject(channels[CHANNEL_ID]) ? channels[CHANNEL_ID] : {}; + channels[CHANNEL_ID] = { ...existing, enabled: true }; + cfg.channels = channels; +} + +function patchOnDiskCfg(): void { + const cfgPath = resolveCfgPath(); + let raw = ""; + try { + raw = fs.readFileSync(cfgPath, "utf-8"); + } catch (err) { + if ((err as NodeJS.ErrnoException).code !== "ENOENT") return; + } + let cfg: Record; + try { + cfg = raw.trim() ? (JSON.parse(raw) as Record) : {}; + } catch { + // Corrupt cfg: don't touch it. + return; + } + if (channelAlreadyDecided(cfg)) return; + patchCfgInPlace(cfg); + try { + fs.mkdirSync(path.dirname(cfgPath), { recursive: true }); + if (raw) { + try { + fs.writeFileSync(`${cfgPath}.bak`, raw); + } catch { + // Backup failure shouldn't block the patch. + } + } + const tmp = `${cfgPath}.tmp.${process.pid}.${Date.now()}`; + fs.writeFileSync(tmp, JSON.stringify(cfg, null, 2) + "\n"); + fs.renameSync(tmp, cfgPath); + } catch { + // Disk write failure: in-memory patch (below) may still recover this run. + } +} + +/** + * Mutate the in-memory runtime config snapshot. Required because openclaw's + * channel-login flow reads the config once at the start of the command via + * `getRuntimeConfig()` and never re-reads from disk; without this, the disk + * patch above would only take effect on the *next* invocation. + * + * Uses dynamic `createRequire` so import failure (e.g. on an older openclaw + * that doesn't export this SDK surface) doesn't break the plugin. + */ +function patchInMemoryCfg(): void { + let getRuntimeConfig: (() => Record | null | undefined) | undefined; + try { + // eslint-disable-next-line @typescript-eslint/no-require-imports + const { createRequire } = require("node:module") as typeof import("node:module"); + const requireFromHere = createRequire(import.meta.url); + const mod = requireFromHere("openclaw/plugin-sdk/runtime-config-snapshot") as { + getRuntimeConfig?: () => Record | null | undefined; + }; + getRuntimeConfig = mod.getRuntimeConfig; + } catch { + return; + } + const cfg = getRuntimeConfig?.(); + if (!cfg || !isPlainObject(cfg)) return; + if (channelAlreadyDecided(cfg)) return; + patchCfgInPlace(cfg); +} + +let attempted = false; +export function ensureHelloAgentChannelEnabled(): void { + if (attempted) return; + attempted = true; + try { + patchOnDiskCfg(); + } catch { + // ignore + } + try { + patchInMemoryCfg(); + } catch { + // ignore + } +} + +/** + * Internals exposed for the smoke test (tests/smoke.ts). Not part of the + * public API — do not import from outside this package. + * + * @internal + */ +export const __testing = { + channelAlreadyDecided, + patchCfgInPlace, + resolveCfgPath, + resetAttempted(): void { + attempted = false; + }, +}; diff --git a/tests/smoke.ts b/tests/smoke.ts index 6b0a373..75e2ab8 100644 --- a/tests/smoke.ts +++ b/tests/smoke.ts @@ -31,6 +31,10 @@ import { writeCreds, type HelloAgentCreds, } from "../src/core/auth-store.js"; +import { + __testing as autoEnableInternals, + ensureHelloAgentChannelEnabled, +} from "../src/core/auto-enable-channel.js"; import { mergeHelloAgentAccountConfig, readCfg, @@ -479,6 +483,185 @@ async function testCfgStore(tmpDir: string): Promise { ok("writeCfg creates .bak rotation on overwrite"); } +// --------------------------------------------------------------------------- +// 8. auto-enable-channel — pure helpers + disk side effect +// --------------------------------------------------------------------------- + +async function testAutoEnableChannel(tmp: string): Promise { + const fs = await import("node:fs/promises"); + + // 1) channelAlreadyDecided — pure, six shapes. + const decided = autoEnableInternals.channelAlreadyDecided; + assertEq(decided({}), false, "empty cfg → not decided"); + assertEq(decided({ channels: {} }), false, "channels {} → not decided"); + assertEq(decided({ channels: { helloagent: {} } }), false, "helloagent {} → not decided"); + assertEq( + decided({ channels: { helloagent: { dmPolicy: "allowlist" } } }), + false, + "policy only, no enabled key → not decided", + ); + assertEq( + decided({ channels: { helloagent: { enabled: true } } }), + true, + "enabled: true → decided", + ); + assertEq( + decided({ channels: { helloagent: { enabled: false } } }), + true, + "enabled: false (opt-out) → decided", + ); + assertEq( + decided({ channels: { helloagent: [] as unknown as Record } }), + false, + "non-object entry → not decided", + ); + ok("channelAlreadyDecided covers all six cfg shapes"); + + // 2) patchCfgInPlace — pure, mutates cfg. + const a: Record = {}; + autoEnableInternals.patchCfgInPlace(a); + assertEq( + (a.channels as { helloagent: { enabled: boolean } }).helloagent.enabled, + true, + "patch into empty cfg", + ); + + const b: Record = { + channels: { + telegram: { enabled: true }, + helloagent: { dmPolicy: "allowlist", allowFrom: ["alice"] }, + }, + }; + autoEnableInternals.patchCfgInPlace(b); + const bH = (b.channels as { helloagent: Record }).helloagent; + assertEq(bH.enabled, true, "patch adds enabled"); + assertEq(bH.dmPolicy, "allowlist", "patch preserves dmPolicy"); + assert( + Array.isArray(bH.allowFrom) && (bH.allowFrom as string[])[0] === "alice", + "patch preserves allowFrom", + ); + const bTele = (b.channels as { telegram: { enabled: boolean } }).telegram; + assertEq(bTele.enabled, true, "patch preserves other channels"); + ok("patchCfgInPlace merges without clobbering siblings"); + + // 3) ensureHelloAgentChannelEnabled — end-to-end disk behavior. + + // 3a) Missing cfg → creates one with enabled=true. + const cfg3a = path.join(tmp, "auto-enable-3a", "openclaw.json"); + process.env.OPENCLAW_CONFIG_PATH = cfg3a; + autoEnableInternals.resetAttempted(); + ensureHelloAgentChannelEnabled(); + const after3a = JSON.parse(await fs.readFile(cfg3a, "utf-8")) as { + channels: { helloagent: { enabled: boolean } }; + }; + assertEq(after3a.channels.helloagent.enabled, true, "missing cfg → created with enabled=true"); + const bak3a = await fs + .access(`${cfg3a}.bak`) + .then(() => true) + .catch(() => false); + assertEq(bak3a, false, "no .bak when cfg was fresh-created"); + ok("missing cfg → fresh write, no .bak"); + + // 3b) Existing cfg without helloagent → patched in, .bak rolled. + const cfg3b = path.join(tmp, "auto-enable-3b", "openclaw.json"); + await fs.mkdir(path.dirname(cfg3b), { recursive: true }); + await fs.writeFile( + cfg3b, + JSON.stringify({ channels: { telegram: { enabled: true } } }, null, 2), + ); + process.env.OPENCLAW_CONFIG_PATH = cfg3b; + autoEnableInternals.resetAttempted(); + ensureHelloAgentChannelEnabled(); + const after3b = JSON.parse(await fs.readFile(cfg3b, "utf-8")) as { + channels: { helloagent: { enabled: boolean }; telegram: { enabled: boolean } }; + }; + assertEq(after3b.channels.helloagent.enabled, true, "patched helloagent enabled"); + assertEq(after3b.channels.telegram.enabled, true, "preserved telegram"); + const bak3b = await fs + .access(`${cfg3b}.bak`) + .then(() => true) + .catch(() => false); + assertEq(bak3b, true, ".bak rotated on overwrite"); + ok("existing cfg → patch + .bak rotation"); + + // 3c) User opt-out (enabled: false) is preserved. + const cfg3c = path.join(tmp, "auto-enable-3c", "openclaw.json"); + await fs.mkdir(path.dirname(cfg3c), { recursive: true }); + const optOutPayload = JSON.stringify( + { channels: { helloagent: { enabled: false, dmPolicy: "deny-all" } } }, + null, + 2, + ); + await fs.writeFile(cfg3c, optOutPayload); + process.env.OPENCLAW_CONFIG_PATH = cfg3c; + autoEnableInternals.resetAttempted(); + ensureHelloAgentChannelEnabled(); + assertEq( + await fs.readFile(cfg3c, "utf-8"), + optOutPayload, + "opt-out cfg byte-for-byte unchanged", + ); + ok("enabled:false opt-out is preserved verbatim"); + + // 3d) Already enabled → no-op (no .bak written). + const cfg3d = path.join(tmp, "auto-enable-3d", "openclaw.json"); + await fs.mkdir(path.dirname(cfg3d), { recursive: true }); + const alreadyEnabledPayload = JSON.stringify( + { channels: { helloagent: { enabled: true } } }, + null, + 2, + ); + await fs.writeFile(cfg3d, alreadyEnabledPayload); + process.env.OPENCLAW_CONFIG_PATH = cfg3d; + autoEnableInternals.resetAttempted(); + ensureHelloAgentChannelEnabled(); + assertEq( + await fs.readFile(cfg3d, "utf-8"), + alreadyEnabledPayload, + "enabled:true cfg unchanged", + ); + const bak3d = await fs + .access(`${cfg3d}.bak`) + .then(() => true) + .catch(() => false); + assertEq(bak3d, false, "no .bak created when no patch needed"); + ok("enabled:true is a no-op (no rewrite, no .bak)"); + + // 3e) Corrupt cfg → leave it alone. + const cfg3e = path.join(tmp, "auto-enable-3e", "openclaw.json"); + await fs.mkdir(path.dirname(cfg3e), { recursive: true }); + const garbage = "{ not valid json"; + await fs.writeFile(cfg3e, garbage); + process.env.OPENCLAW_CONFIG_PATH = cfg3e; + autoEnableInternals.resetAttempted(); + ensureHelloAgentChannelEnabled(); + assertEq(await fs.readFile(cfg3e, "utf-8"), garbage, "corrupt cfg untouched"); + ok("corrupt cfg → don't overwrite"); + + // 3f) Idempotency within a single process: the `attempted` guard short-circuits. + const cfg3f = path.join(tmp, "auto-enable-3f", "openclaw.json"); + process.env.OPENCLAW_CONFIG_PATH = cfg3f; + autoEnableInternals.resetAttempted(); + ensureHelloAgentChannelEnabled(); + // Tamper with the file after the first call; a second call should NOT rewrite. + await fs.writeFile(cfg3f, JSON.stringify({ tampered: true }, null, 2)); + ensureHelloAgentChannelEnabled(); + const after3f = JSON.parse(await fs.readFile(cfg3f, "utf-8")) as { tampered?: boolean }; + assertEq(after3f.tampered, true, "second call did not rewrite (attempted guard)"); + ok("ensureHelloAgentChannelEnabled is idempotent per process"); + + // 3g) Subsequent process (after reset) re-evaluates from disk. + autoEnableInternals.resetAttempted(); + ensureHelloAgentChannelEnabled(); + const after3g = JSON.parse(await fs.readFile(cfg3f, "utf-8")) as { + channels?: { helloagent?: { enabled?: boolean } }; + tampered?: boolean; + }; + assertEq(after3g.channels?.helloagent?.enabled, true, "post-reset re-patch applied"); + assertEq(after3g.tampered, true, "post-reset re-patch preserved tampered key"); + ok("post-reset re-evaluates and patches without losing existing keys"); +} + // --------------------------------------------------------------------------- // Main // --------------------------------------------------------------------------- @@ -498,6 +681,7 @@ async function main(): Promise { await step("5. security.collectWarnings", testSecurityWarnings); await step("6. Disk creds → cache → plugin.config", () => testDiskCredsWiring(tmp)); await step("7. cfg-store atomic I/O", () => testCfgStore(tmp)); + await step("8. auto-enable-channel", () => testAutoEnableChannel(tmp)); } finally { if (originalState === undefined) delete process.env.OPENCLAW_STATE_DIR; else process.env.OPENCLAW_STATE_DIR = originalState;