@reefclaw/openclaw-plugin 0.1.49 → 0.1.51

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/README.md +10 -6
  2. package/bridge/config.js +10 -3
  3. package/bridge/gateway/gateway-ws-client.d.ts +79 -1
  4. package/bridge/gateway/gateway-ws-client.js +99 -5
  5. package/bridge/gateway/heartbeat-cron.d.ts +39 -2
  6. package/bridge/gateway/heartbeat-cron.js +62 -8
  7. package/bridge/heartbeat-transcript.d.ts +3 -1
  8. package/bridge/heartbeat-transcript.js +26 -5
  9. package/bridge/index.js +2 -2
  10. package/bridge/providers/connector-update-direct.d.ts +3 -0
  11. package/bridge/providers/connector-update-direct.js +11 -1
  12. package/bridge/providers/connector-update-openclaw.d.ts +268 -0
  13. package/bridge/providers/connector-update-openclaw.js +772 -0
  14. package/bridge/providers/connector-update.d.ts +115 -1
  15. package/bridge/providers/connector-update.js +228 -13
  16. package/bridge/providers/gateway.d.ts +31 -10
  17. package/bridge/providers/gateway.js +144 -28
  18. package/bridge/setup.js +6 -3
  19. package/bridge/utils/relay-host.d.ts +16 -0
  20. package/bridge/utils/relay-host.js +30 -1
  21. package/config/first-start-venue.d.ts +147 -0
  22. package/config/first-start-venue.js +400 -0
  23. package/config/plugin-config-io.d.ts +9 -2
  24. package/config/plugin-config-io.js +29 -5
  25. package/connector-supervisor.d.ts +20 -0
  26. package/connector-supervisor.js +27 -1
  27. package/index.js +32 -1
  28. package/openclaw.plugin.json +333 -1
  29. package/package.json +1 -1
  30. package/release-integrity.json +10 -0
  31. package/release-notes.json +3 -1
  32. package/skills/reefclaw/SKILL.md +21 -8
  33. package/strategy/builtin-strategies.js +2 -2
  34. package/tools/venue-quote-hint.d.ts +49 -0
  35. package/tools/venue-quote-hint.js +200 -0
package/README.md CHANGED
@@ -6,21 +6,24 @@ This file is the plain-language ledger of what the package does on the machine i
6
6
 
7
7
  ## What runs
8
8
 
9
- - **The plugin** loads into the OpenClaw gateway at startup (`activation.onStartup` in the manifest) and registers the trading tools listed under `contracts.tools`.
9
+ - **The plugin** loads into the OpenClaw gateway at startup (`activation.onStartup` in the manifest) and registers the trading tools listed under `contracts.tools`. The manifest also declares each of those tools a member of OpenClaw's "coding" tool profile (`toolMetadata`, one entry per tool and nothing else), so agents whose OpenClaw uses that profile can see them. That is a declaration in this package's own manifest: no OpenClaw config file is edited for it.
10
10
  - **One connector process** (the `bridge/` folder) is started and supervised by the plugin. It holds the outbound connection to the ReefClaw relay, runs the agent's scheduled heartbeat, and delivers signed instruction updates. If it exits, the plugin restarts it.
11
+ - **One-click update, for a copy OpenClaw installed from ClawHub.** When the operator presses Update in the ReefClaw dashboard, the connector asks the LOCAL gateway, over the `operator.admin` session it already uses for gateway restarts, to install from ClawHub exactly the version of this package (`@reefclaw/openclaw-plugin`) that ReefClaw's release endpoint names (`plugins.install` with `mode: "update"`), then restarts the gateway so that version loads. It never installs any other package or version, and never runs without that click. A copy placed by the connect installer is updated by that installer instead, pinned to the exact release the same endpoint names.
12
+ - **First start on a fresh box.** When the connection saved in OpenClaw's config (`~/.openclaw/openclaw.json` by default) carries the exchange picked during onboarding (`skills.entries.reefclaw.config.venue`) and ReefClaw has never run on this box (no plugin state, credential transport key or first-start marker, and `plugin-config.json` absent or holding only what the connect installer wrote), the plugin applies it once. For Hyperliquid it writes the keyless Hyperliquid `exchange` block into `~/.reefclaw/plugin-config.json`, the same block the dashboard's exchange switch writes, and nothing else there; Binance is the default and writes nothing. It never overwrites an existing setting, never adds keys and never enables live trading. Separately, whenever OpenClaw keeps its state somewhere other than `~/.openclaw`, the plugin leaves a small marker (`first-start.json`) in that state dir on the first start that finds none, whether or not an exchange was saved (a box upgrading to this release gets one too), so a later start is never mistaken for a first one; it is never rewritten. `RC_FIRST_START_VENUE=off` switches all of this off, the marker included.
11
13
  - The agent starts in **PAPER mode**: real market data, simulated fills, no exchange account and no API keys. Moving to real money is a separate step the **operator** takes from the dashboard (PAPER → MICRO_LIVE → LIVE), and the tools that change mode or store credentials refuse calls that do not carry an operator-provenance secret — a per-boot value the plugin mints in memory and hands only to the connector it supervises (never a file, argv or environment variable, so it cannot be read back from the config or supplied in conversation). While trading is live a new entry without a protective stop is refused whatever the settings say.
12
14
 
13
15
  ## What it writes on this machine
14
16
 
15
17
  | Path | What | Why |
16
18
  | --- | --- | --- |
17
- | `~/.reefclaw/plugin-config.json` (owner-only permissions) | Trading mode, per-box switches, and exchange credentials once the operator adds them | The only place exchange keys ever live; used only to sign requests to the exchange |
19
+ | `~/.reefclaw/plugin-config.json` (owner-only permissions) | Trading mode, per-box switches, the exchange in use (on a fresh box's first start, the keyless Hyperliquid block when that was picked during onboarding), and exchange credentials once the operator adds them | The only place exchange keys ever live; used only to sign requests to the exchange |
18
20
  | `~/.reefclaw/credential-transport-key.json` | A key pair used to receive exchange credentials from the dashboard in encrypted form | So credentials cross the relay encrypted to this box; the private half never leaves it |
19
21
  | Other files under `~/.reefclaw/` | Paper-trading state, the protective-order ledger, position state, a cached copy of the account's central config, market-data caches | Local bookkeeping so a restart resumes where it left off |
20
- | `~/.openclaw/openclaw.json` → `skills.entries.reefclaw.config` only | The connection token, user id and relay URL the operator pasted | So the connector can reach the operator's own dashboard room. Nothing else in that file is touched, and **nothing under `gateway` is ever written** |
22
+ | `~/.openclaw/openclaw.json` → `skills.entries.reefclaw.config` only | The connection token, user id and relay URL the operator pasted, and the exchange picked during onboarding (`venue`) | So the connector can reach the operator's own dashboard room. Nothing else in that file is touched, and **nothing under `gateway` is ever written** |
21
23
  | OpenClaw's cron store | One heartbeat job (`reefclaw-heartbeat`), created through the gateway's own cron API | The scheduled position review; remove it with the OpenClaw cron commands |
22
24
  | The `reefclaw` skill's `SKILL.md` in the agent workspace, in `~/.openclaw/skills/`, and in this package's `skills/` folder | The agent's trading instructions, kept identical in the places OpenClaw reads them | The bundled copy is a bootstrap; the full instructions arrive after connect and are applied only after their Ed25519 signature verifies against a key pinned in this build |
23
25
  | The agent's `sessions.json` (older OpenClaw builds only) | One cached skills-snapshot key is cleared after an instruction update | So the running session re-reads the updated skill; nothing else in that file changes |
26
+ | `first-start.json` in `<OpenClaw state dir>/plugins/reefclaw-paper-trading/`, only when OpenClaw keeps its state outside `~/.openclaw` | A first-start timestamp and a one-line note, written on the first start that finds none (whether or not an exchange was saved) and never overwritten | So the exchange picked during onboarding is applied on the first start only, even where the home directory is reset between restarts |
24
27
 
25
28
  It **reads** the agent's heartbeat transcripts (OpenClaw's SQLite store on 2026.9+, JSONL before) to build the heartbeat flight recorder described below.
26
29
 
@@ -37,22 +40,23 @@ Everything below goes to the operator's own ReefClaw account and nowhere else.
37
40
  | Intelligence | Market-context reads; the plugin sends symbols and parameters, never keys | none, tools degrade without it |
38
41
  | Version report | The installed plugin and connector versions, so the dashboard can offer an update; plus, from plugin 0.1.39, an integrity check of the running plugin: whether it runs from the standard install location (a yes/no class, never the path), the process start time, and SHA-256 fingerprints of three of the plugin's own files (`index.js`, `tools/create-order.js`, `risk/pre-trade-check.js`), so a box running stale or modified plugin files can be told apart from the release. Never file contents, never a path, never anything outside the plugin's own files | `RC_READINESS_INTEGRITY=off` (the integrity part only) |
39
42
 
40
- Network access is outbound only: the relay (WebSocket), `www.reefclaw.com`, the intelligence API, the exchange when credentials are present, and the npm registry only during an operator-triggered update. The package opens no listening port.
43
+ Network access is outbound only: the relay (WebSocket), `www.reefclaw.com`, the intelligence API, the exchange when credentials are present, and the npm registry only during an operator-triggered update (for a copy OpenClaw installed from ClawHub, the gateway itself downloads the release from ClawHub, as described above). The package opens no listening port.
41
44
 
42
45
  ## What it never does
43
46
 
44
47
  - **It never changes the gateway's auth settings.** If the gateway withholds the scope the connector needs, the connector logs the exact manual remedy and stops; the decision stays with the operator.
45
48
  - **It never sends exchange API keys to ReefClaw.** A test in this package drives the real outbound clients and asserts no credential reaches the wire. On Hyperliquid the key is an agent key, which cannot withdraw or transfer funds; on Binance the operator is asked to create keys without withdrawal permission.
46
- - **It never runs an unpinned install.** The install line in the bundled skill names the exact connector release this plugin was published with, and the dashboard's one-click update installs exactly the release ReefClaw's public release endpoint reports. If that lookup fails, the update does not run.
49
+ - **It never runs an unpinned install.** The install line in the bundled skill names the exact connector release this plugin was published with, and the dashboard's one-click update installs exactly the release ReefClaw's public release endpoint reports, whether it runs the connect installer or asks OpenClaw to install from ClawHub. If that lookup fails, the update does not run.
47
50
  - **It never trades real money on its own initiative.** Live trading requires credentials and a mode change that only the operator can make from the dashboard; every live position carries exchange-native protective stops; and the operator's pause, flatten and kill controls are never gated behind subscription state.
48
51
 
49
52
  ## Switches and removal
50
53
 
51
54
  | Setting | Effect |
52
55
  | --- | --- |
53
- | `REEFCLAW_ALLOW_CONNECTOR_UPDATE=0` (or `connectorUpdate: "off"` in `plugin-config.json`) | The dashboard's one-click update is refused on this box |
56
+ | `REEFCLAW_ALLOW_CONNECTOR_UPDATE=0` (or `connectorUpdate: "off"` in `plugin-config.json`) | The dashboard's one-click update is refused on this box, by either route (connect installer or ClawHub) |
54
57
  | `RC_HEARTBEAT_RECORDER=off` | Heartbeat transcripts are not read or reported |
55
58
  | `RC_SHOCK_WAKE=off` | Shock wakes are never constructed, whatever the account setting says |
59
+ | `RC_FIRST_START_VENUE=off` | First start neither reads nor applies the exchange saved with the connection, and writes no first-start marker |
56
60
  | `SKILL_OTA_REQUIRE_SIGNATURE=off` | Break-glass: accept an *unsigned* instruction update on this box (a forged signature is still always refused) |
57
61
 
58
62
  To remove the plugin: uninstall it with OpenClaw's plugin commands, delete `~/.reefclaw/`, remove the `reefclaw` skill folder(s), the `skills.entries.reefclaw` entry in `openclaw.json`, and the `reefclaw-heartbeat` cron job.
package/bridge/config.js CHANGED
@@ -7,10 +7,11 @@ import { homedir } from 'os';
7
7
  import JSON5 from 'json5';
8
8
  import { logger } from './logger.js';
9
9
  import { sanitizeRelayUrl } from './utils/base-url.js';
10
+ import { migrateRetiredRelayUrl } from './utils/relay-host.js';
10
11
  const TAG = 'config';
11
12
  const OPENCLAW_DIR = join(homedir(), '.openclaw');
12
13
  const CONFIG_PATH = join(OPENCLAW_DIR, 'openclaw.json');
13
- const DEFAULT_RELAY_URL = 'wss://reefclaw.radunlupsa.partykit.dev';
14
+ const DEFAULT_RELAY_URL = 'wss://relay.reefclaw.com';
14
15
  // ---- Read/write OpenClaw config ----
15
16
  //
16
17
  // Scope contract — writeOpenClawConfig touches ONLY
@@ -188,13 +189,19 @@ export function resolveConfig(args) {
188
189
  || null;
189
190
  // wss required for a public relay; ws only to a private host (`partykit
190
191
  // dev`) — the socket's auth query carries the rc_ token (audit H4).
191
- const relayUrl = sanitizeRelayUrl(args.relayUrl
192
+ const configuredRelayUrl = sanitizeRelayUrl(args.relayUrl
192
193
  || process.env.REEFCLAW_RELAY_URL
193
194
  || savedConfig?.relayUrl
194
195
  || process.env.RELAY_URL
195
196
  || DEFAULT_RELAY_URL, DEFAULT_RELAY_URL, 'relayUrl');
197
+ // A box onboarded before the relay left PartyKit still names the old host;
198
+ // follow it to its replacement rather than dialling a deleted endpoint.
199
+ const migrated = migrateRetiredRelayUrl(configuredRelayUrl);
200
+ if (migrated.retiredHost) {
201
+ logger.info(TAG, `relay host ${migrated.retiredHost} is retired — connecting to ${migrated.url} instead`);
202
+ }
196
203
  if (savedConfig?.token && !args.token && !process.env.REEFCLAW_TOKEN) {
197
204
  logger.info(TAG, 'Using token from OpenClaw config');
198
205
  }
199
- return { token, userId, relayUrl };
206
+ return { token, userId, relayUrl: migrated.url };
200
207
  }
@@ -10,6 +10,56 @@ interface ReconnectConfig extends BaseReconnectConfig {
10
10
  /** Slow retry interval once the fast attempts are exhausted (ms) */
11
11
  slowRetryMs: number;
12
12
  }
13
+ /** Per-call options for `sendRpc`. Both optional; omitted = the historical call. */
14
+ export interface SendRpcOptions {
15
+ /** Reply deadline for THIS call (default 30 s). OpenClaw's own CLI allows
16
+ * plugins.install 600 s — a ClawHub download + package install on a small
17
+ * box does not fit the default. */
18
+ timeoutMs?: number;
19
+ /** Receives every gateway event frame this client does not interpret itself
20
+ * (e.g. `plugins.install.progress`) for as long as this call is pending.
21
+ * Detached when the call settles, whichever way. Not filtered by request id. */
22
+ onEvent?: (event: string, payload: unknown) => void;
23
+ }
24
+ /**
25
+ * A gateway `res` frame with ok:false, carried whole. `.message` is exactly the
26
+ * string this client has always rejected with (the gateway's message, else
27
+ * `RPC failed (code …)`), so every caller that reads only the message is
28
+ * unaffected. The structured fields are what OpenClaw's plugin-management
29
+ * errors are decided on — code / details / retryable / retryAfterMs, the same
30
+ * fields scripts/canary-plugins-install.mjs reads — and a message-only reject
31
+ * threw them away.
32
+ *
33
+ * Transport failures (timeout, connection closed, not connected) stay plain
34
+ * `Error`s: "the gateway answered no" and "we never heard back" are different
35
+ * facts, and a caller deciding whether a mutation happened must tell them apart.
36
+ */
37
+ export declare class GatewayRpcError extends Error {
38
+ /** The gateway's error code (OpenClaw sends strings such as `UNAVAILABLE`,
39
+ * `INVALID_REQUEST`; a numeric code is stringified); null when absent. */
40
+ readonly code: string | null;
41
+ /** The gateway's structured `details`, verbatim; null when absent. */
42
+ readonly details: unknown;
43
+ /** True only when the gateway said so (`retryable: true`). */
44
+ readonly retryable: boolean;
45
+ /** The gateway's suggested wait, when it gave a finite non-negative one. */
46
+ readonly retryAfterMs: number | null;
47
+ constructor(message: string, fields?: {
48
+ code?: unknown;
49
+ details?: unknown;
50
+ retryable?: unknown;
51
+ retryAfterMs?: unknown;
52
+ });
53
+ }
54
+ /** What the gateway said about itself in hello-ok (read-only copy). */
55
+ export interface GatewayHelloInfo {
56
+ /** hello-ok `server.version`: the OpenClaw release, a calendar version such
57
+ * as "2026.9.6" (possibly with a suffix); null when the gateway omits it. */
58
+ readonly serverVersion: string | null;
59
+ /** hello-ok `features.methods`: the RPC methods this gateway serves (466 on
60
+ * 2026.9.6); null when the gateway does not list them. */
61
+ readonly methods: readonly string[] | null;
62
+ }
13
63
  /** hello-ok response payload from gateway */
14
64
  export interface HelloOkPayload {
15
65
  type: 'hello-ok';
@@ -29,6 +79,18 @@ export interface HelloOkPayload {
29
79
  role: string;
30
80
  scopes: string[];
31
81
  };
82
+ /** OpenClaw identifies itself here (`version`, e.g. "2026.9.6"). Optional:
83
+ * read defensively (see getHelloInfo). */
84
+ server?: {
85
+ version?: unknown;
86
+ [key: string]: unknown;
87
+ };
88
+ /** Capability lists (`methods`, `events`). Optional, read defensively. */
89
+ features?: {
90
+ methods?: unknown;
91
+ events?: unknown;
92
+ [key: string]: unknown;
93
+ };
32
94
  }
33
95
  export type GatewayWsEvent = 'connected' | 'disconnected' | 'reconnecting' | 'failed' | 'agent' | 'presence' | 'tick' | 'shutdown';
34
96
  export type GatewayWsEventPayload = {
@@ -80,8 +142,13 @@ export declare class GatewayWsClient {
80
142
  private deviceToken;
81
143
  /** Last hello-ok payload — contains initial snapshot */
82
144
  private lastHelloOk;
145
+ /** server.version + features.methods from the last accepted hello-ok. */
146
+ private helloInfo;
83
147
  /** Event listeners */
84
148
  private listeners;
149
+ /** Per-call listeners for event frames the client does not interpret
150
+ * (SendRpcOptions.onEvent). */
151
+ private passthroughListeners;
85
152
  private readonly gatewayUrl;
86
153
  private readonly gatewayToken;
87
154
  private readonly requestAdminScope;
@@ -108,8 +175,12 @@ export declare class GatewayWsClient {
108
175
  /**
109
176
  * Send an RPC request and wait for the response.
110
177
  * Used for: agent (chat), health, status
178
+ *
179
+ * A gateway refusal rejects with a GatewayRpcError (same message as ever,
180
+ * plus code/details/retryable/retryAfterMs); a transport failure rejects
181
+ * with a plain Error. `opts` is optional and changes nothing when omitted.
111
182
  */
112
- sendRpc(method: string, params?: Record<string, unknown>): Promise<unknown>;
183
+ sendRpc(method: string, params?: Record<string, unknown>, opts?: SendRpcOptions): Promise<unknown>;
113
184
  /** Register an event listener */
114
185
  on<E extends GatewayWsEvent>(event: E, listener: EventListener<E>): void;
115
186
  /** Remove an event listener */
@@ -118,6 +189,9 @@ export declare class GatewayWsClient {
118
189
  getState(): GatewayWsState;
119
190
  /** Get the hello-ok snapshot from the last successful connection */
120
191
  getHelloOk(): HelloOkPayload | null;
192
+ /** What the gateway said about itself in the last accepted hello-ok —
193
+ * OpenClaw release + served RPC methods. Null before the first hello-ok. */
194
+ getHelloInfo(): GatewayHelloInfo | null;
121
195
  /** The client identity currently in use (the one the gateway admitted, once connected). */
122
196
  getClientId(): GatewayClientId;
123
197
  private hasNextIdentity;
@@ -148,4 +222,8 @@ export declare class GatewayWsClient {
148
222
  private emit;
149
223
  private rejectAllPending;
150
224
  }
225
+ /** Defensive read of the self-description in hello-ok (L5: 2026.9.6 sends
226
+ * `server.version` and a `features.methods` list). Anything malformed is
227
+ * reported as absent, never guessed. */
228
+ export declare function readHelloInfo(payload: HelloOkPayload | null | undefined): GatewayHelloInfo;
151
229
  export {};
@@ -56,6 +56,42 @@ const DEFAULT_RECONNECT = {
56
56
  /** Auth errors — do not reconnect */
57
57
  const FATAL_CLOSE_CODES = [4001];
58
58
  const RPC_TIMEOUT_MS = 30_000;
59
+ /**
60
+ * A gateway `res` frame with ok:false, carried whole. `.message` is exactly the
61
+ * string this client has always rejected with (the gateway's message, else
62
+ * `RPC failed (code …)`), so every caller that reads only the message is
63
+ * unaffected. The structured fields are what OpenClaw's plugin-management
64
+ * errors are decided on — code / details / retryable / retryAfterMs, the same
65
+ * fields scripts/canary-plugins-install.mjs reads — and a message-only reject
66
+ * threw them away.
67
+ *
68
+ * Transport failures (timeout, connection closed, not connected) stay plain
69
+ * `Error`s: "the gateway answered no" and "we never heard back" are different
70
+ * facts, and a caller deciding whether a mutation happened must tell them apart.
71
+ */
72
+ export class GatewayRpcError extends Error {
73
+ /** The gateway's error code (OpenClaw sends strings such as `UNAVAILABLE`,
74
+ * `INVALID_REQUEST`; a numeric code is stringified); null when absent. */
75
+ code;
76
+ /** The gateway's structured `details`, verbatim; null when absent. */
77
+ details;
78
+ /** True only when the gateway said so (`retryable: true`). */
79
+ retryable;
80
+ /** The gateway's suggested wait, when it gave a finite non-negative one. */
81
+ retryAfterMs;
82
+ constructor(message, fields = {}) {
83
+ super(message);
84
+ this.name = 'GatewayRpcError';
85
+ this.code =
86
+ typeof fields.code === 'string' ? fields.code : typeof fields.code === 'number' ? String(fields.code) : null;
87
+ this.details = fields.details ?? null;
88
+ this.retryable = fields.retryable === true;
89
+ this.retryAfterMs =
90
+ typeof fields.retryAfterMs === 'number' && Number.isFinite(fields.retryAfterMs) && fields.retryAfterMs >= 0
91
+ ? fields.retryAfterMs
92
+ : null;
93
+ }
94
+ }
59
95
  // ---- Client ----
60
96
  export class GatewayWsClient {
61
97
  ws = null;
@@ -75,8 +111,13 @@ export class GatewayWsClient {
75
111
  deviceToken = null;
76
112
  /** Last hello-ok payload — contains initial snapshot */
77
113
  lastHelloOk = null;
114
+ /** server.version + features.methods from the last accepted hello-ok. */
115
+ helloInfo = null;
78
116
  /** Event listeners */
79
117
  listeners = new Map();
118
+ /** Per-call listeners for event frames the client does not interpret
119
+ * (SendRpcOptions.onEvent). */
120
+ passthroughListeners = new Set();
80
121
  gatewayUrl;
81
122
  gatewayToken;
82
123
  requestAdminScope;
@@ -190,11 +231,18 @@ export class GatewayWsClient {
190
231
  /**
191
232
  * Send an RPC request and wait for the response.
192
233
  * Used for: agent (chat), health, status
234
+ *
235
+ * A gateway refusal rejects with a GatewayRpcError (same message as ever,
236
+ * plus code/details/retryable/retryAfterMs); a transport failure rejects
237
+ * with a plain Error. `opts` is optional and changes nothing when omitted.
193
238
  */
194
- async sendRpc(method, params) {
239
+ async sendRpc(method, params, opts = {}) {
195
240
  if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
196
241
  throw new Error(`Cannot send RPC: not connected (state=${this.state})`);
197
242
  }
243
+ const timeoutMs = typeof opts.timeoutMs === 'number' && Number.isFinite(opts.timeoutMs) && opts.timeoutMs > 0
244
+ ? opts.timeoutMs
245
+ : RPC_TIMEOUT_MS;
198
246
  const id = `rpc-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
199
247
  const frame = {
200
248
  type: 'req',
@@ -203,11 +251,20 @@ export class GatewayWsClient {
203
251
  ...(params && { params }),
204
252
  };
205
253
  return new Promise((resolve, reject) => {
254
+ let cleanup;
255
+ if (opts.onEvent) {
256
+ const listener = opts.onEvent;
257
+ this.passthroughListeners.add(listener);
258
+ cleanup = () => {
259
+ this.passthroughListeners.delete(listener);
260
+ };
261
+ }
206
262
  const timer = setTimeout(() => {
207
263
  this.pendingRpcs.delete(id);
208
- reject(new Error(`RPC ${method} timed out after ${RPC_TIMEOUT_MS}ms`));
209
- }, RPC_TIMEOUT_MS);
210
- this.pendingRpcs.set(id, { resolve, reject, timer });
264
+ cleanup?.();
265
+ reject(new Error(`RPC ${method} timed out after ${timeoutMs}ms`));
266
+ }, timeoutMs);
267
+ this.pendingRpcs.set(id, { resolve, reject, timer, cleanup });
211
268
  this.ws.send(JSON.stringify(frame));
212
269
  logger.debug(TAG, `Sent RPC: ${method} (id=${id})`);
213
270
  });
@@ -231,6 +288,11 @@ export class GatewayWsClient {
231
288
  getHelloOk() {
232
289
  return this.lastHelloOk;
233
290
  }
291
+ /** What the gateway said about itself in the last accepted hello-ok —
292
+ * OpenClaw release + served RPC methods. Null before the first hello-ok. */
293
+ getHelloInfo() {
294
+ return this.helloInfo;
295
+ }
234
296
  /** The client identity currently in use (the one the gateway admitted, once connected). */
235
297
  getClientId() {
236
298
  return this.identities[this.identityIndex];
@@ -303,6 +365,7 @@ export class GatewayWsClient {
303
365
  if (pending) {
304
366
  clearTimeout(pending.timer);
305
367
  this.pendingRpcs.delete(id);
368
+ pending.cleanup?.();
306
369
  if (frame.ok) {
307
370
  // Check if this is the hello-ok response to our connect request
308
371
  if (frame.payload && typeof frame.payload === 'object') {
@@ -314,7 +377,13 @@ export class GatewayWsClient {
314
377
  pending.resolve(frame.payload);
315
378
  }
316
379
  else {
317
- pending.reject(new Error(frame.error?.message ?? `RPC failed (code ${frame.error?.code ?? 'unknown'})`));
380
+ const error = frame.error ?? {};
381
+ pending.reject(new GatewayRpcError(error.message ?? `RPC failed (code ${error.code ?? 'unknown'})`, {
382
+ code: error.code,
383
+ details: error.details,
384
+ retryable: error.retryable,
385
+ retryAfterMs: error.retryAfterMs,
386
+ }));
318
387
  }
319
388
  return;
320
389
  }
@@ -365,6 +434,16 @@ export class GatewayWsClient {
365
434
  break;
366
435
  default:
367
436
  logger.debug(TAG, `Unknown gateway event: ${event}`);
437
+ if (typeof event === 'string' && this.passthroughListeners.size > 0) {
438
+ for (const listener of [...this.passthroughListeners]) {
439
+ try {
440
+ listener(event, frame.payload);
441
+ }
442
+ catch (err) {
443
+ logger.error(TAG, `RPC event listener error (${event}): ${err instanceof Error ? err.message : String(err)}`);
444
+ }
445
+ }
446
+ }
368
447
  }
369
448
  }
370
449
  // ---- Handshake ----
@@ -454,6 +533,7 @@ export class GatewayWsClient {
454
533
  }
455
534
  logger.info(TAG, `Connected to gateway (protocol=${payload.protocol}, client=${this.getClientId()})`);
456
535
  this.lastHelloOk = payload;
536
+ this.helloInfo = readHelloInfo(payload);
457
537
  this.attempt = 0; // Reset reconnect counter
458
538
  this.slowRetryActive = false; // Back on the fast budget for the next drop
459
539
  // Parse policy
@@ -560,8 +640,22 @@ export class GatewayWsClient {
560
640
  rejectAllPending(reason) {
561
641
  for (const [, pending] of this.pendingRpcs) {
562
642
  clearTimeout(pending.timer);
643
+ pending.cleanup?.();
563
644
  pending.reject(new Error(reason));
564
645
  }
565
646
  this.pendingRpcs.clear();
566
647
  }
567
648
  }
649
+ /** Defensive read of the self-description in hello-ok (L5: 2026.9.6 sends
650
+ * `server.version` and a `features.methods` list). Anything malformed is
651
+ * reported as absent, never guessed. */
652
+ export function readHelloInfo(payload) {
653
+ const version = payload?.server?.version;
654
+ const methods = payload?.features?.methods;
655
+ return {
656
+ serverVersion: typeof version === 'string' && version.trim().length > 0 ? version.trim() : null,
657
+ methods: Array.isArray(methods)
658
+ ? Object.freeze(methods.filter((m) => typeof m === 'string'))
659
+ : null,
660
+ };
661
+ }
@@ -20,8 +20,16 @@ export interface CronRpcClient {
20
20
  */
21
21
  export declare function hasConfiguredChannels(cfg: unknown): boolean | undefined;
22
22
  /**
23
- * Repair an existing heartbeat job on a box WITHOUT a chat channel: its
24
- * delivery `announce` can only fail at run time, so switch it to `none`.
23
+ * Repair an existing heartbeat job's announce delivery. On a box WITHOUT a
24
+ * chat channel announce can only fail at run time, so switch it to `none`;
25
+ * anywhere else make it best-effort (HEARTBEAT_ANNOUNCE_DELIVERY), so a
26
+ * channel with no recipient yet stops failing the beat. The best-effort
27
+ * patch is attempted only on a session holding operator.admin (`adminScope`)
28
+ * and only when the job has no bestEffort setting at all — an explicit
29
+ * `false` is an operator's choice. Without admin it is skipped silently, so
30
+ * boxes created before this fix are NOT repaired by it (the recorder's
31
+ * delivery-phase rule covers what they record; the operator can run
32
+ * `openclaw cron edit <id> --best-effort-deliver`).
25
33
  * Runs on every bridge start (cheap: one cron.list), independent of the
26
34
  * once-per-install marker, because the job predates this fix on every box.
27
35
  *
@@ -40,6 +48,9 @@ export declare function reconcileHeartbeatDelivery(opts: {
40
48
  rpc: CronRpcClient;
41
49
  log: (msg: string) => void;
42
50
  channelsConfigured: boolean | undefined;
51
+ /** The session was opened with operator.admin (heartbeatEnsureOwed at
52
+ * connect). Absent = true (legacy callers). */
53
+ adminScope?: boolean;
43
54
  agentId?: string;
44
55
  agentIsDefault?: boolean;
45
56
  }): Promise<'patched' | 'unchanged' | 'skipped' | 'failed'>;
@@ -103,6 +114,32 @@ export declare function cronJobBelongsToAgent(job: {
103
114
  * error naming the field. Creating the job WITHOUT it would put the trading
104
115
  * heartbeat on the wrong (default) agent, so that case fails loudly instead. */
105
116
  export declare function isAgentIdRejection(err: unknown): boolean;
117
+ /**
118
+ * The heartbeat's announce delivery. `bestEffort` (OpenClaw cron
119
+ * `delivery.bestEffort`, CLI `--best-effort-deliver`: "Do not fail the job if
120
+ * delivery fails") makes a target that cannot be resolved a logged warning
121
+ * and the run `ok`, while a box whose chat works still gets the summary.
122
+ *
123
+ * ★ 2026-10-14 (a new user's first evening): Telegram configured but never
124
+ * chatted with, so channel `last` resolved to Telegram with no chat id and
125
+ * every beat failed AFTER its work completed — "Delivering to Telegram
126
+ * requires target <chatId>". The no-channel guard (hasConfiguredChannels)
127
+ * cannot see this case: a channel exists, it just has no recipient yet.
128
+ *
129
+ * Trade-off (accepted): OpenClaw also skips its own opt-in cron failure
130
+ * alerts / failureDestination for a bestEffort job — for every error, not
131
+ * only delivery ones. The run status itself stays `error` for a failed turn
132
+ * (OpenClaw re-applies the outcome), so our recorder, model health and fleet
133
+ * alarms are unaffected; they are what watches ReefClaw beats.
134
+ */
135
+ export declare const HEARTBEAT_ANNOUNCE_DELIVERY: {
136
+ readonly mode: "announce";
137
+ readonly channel: "last";
138
+ readonly bestEffort: true;
139
+ };
140
+ /** A gateway that predates `delivery.bestEffort` answers with a schema error
141
+ * naming the field; the job is then created with plain announce, as before. */
142
+ export declare function isBestEffortRejection(err: unknown): boolean;
106
143
  export declare function ensureHeartbeatCron(opts: {
107
144
  rpc: CronRpcClient;
108
145
  markerPath: string;
@@ -89,8 +89,16 @@ export function hasConfiguredChannels(cfg) {
89
89
  return false;
90
90
  }
91
91
  /**
92
- * Repair an existing heartbeat job on a box WITHOUT a chat channel: its
93
- * delivery `announce` can only fail at run time, so switch it to `none`.
92
+ * Repair an existing heartbeat job's announce delivery. On a box WITHOUT a
93
+ * chat channel announce can only fail at run time, so switch it to `none`;
94
+ * anywhere else make it best-effort (HEARTBEAT_ANNOUNCE_DELIVERY), so a
95
+ * channel with no recipient yet stops failing the beat. The best-effort
96
+ * patch is attempted only on a session holding operator.admin (`adminScope`)
97
+ * and only when the job has no bestEffort setting at all — an explicit
98
+ * `false` is an operator's choice. Without admin it is skipped silently, so
99
+ * boxes created before this fix are NOT repaired by it (the recorder's
100
+ * delivery-phase rule covers what they record; the operator can run
101
+ * `openclaw cron edit <id> --best-effort-deliver`).
94
102
  * Runs on every bridge start (cheap: one cron.list), independent of the
95
103
  * once-per-install marker, because the job predates this fix on every box.
96
104
  *
@@ -106,7 +114,9 @@ export function hasConfiguredChannels(cfg) {
106
114
  * this guess.
107
115
  */
108
116
  export async function reconcileHeartbeatDelivery(opts) {
109
- if (opts.channelsConfigured !== false)
117
+ // Best-effort repair needs a cron.update this session may not be allowed;
118
+ // without admin it would only log a refusal on every bridge start.
119
+ if (opts.channelsConfigured !== false && opts.adminScope === false)
110
120
  return 'skipped';
111
121
  const agentId = opts.agentId?.trim().toLowerCase() || undefined;
112
122
  const agentIsDefault = opts.agentIsDefault ?? true;
@@ -116,11 +126,22 @@ export async function reconcileHeartbeatDelivery(opts) {
116
126
  const job = jobs.find((j) => isReefclawHeartbeatJob(j) && cronJobBelongsToAgent(j, agentId, agentIsDefault));
117
127
  if (!job || typeof job.id !== 'string')
118
128
  return 'unchanged';
119
- const mode = job.delivery?.mode;
120
- if (mode !== 'announce')
129
+ const delivery = job.delivery;
130
+ if (delivery?.mode !== 'announce')
121
131
  return 'unchanged';
122
- await opts.rpc.sendRpc('cron.update', { id: job.id, patch: { delivery: { mode: 'none' } } });
123
- opts.log(`Heartbeat cron: no chat channel is configured — delivery switched from announce to none (${String(job.name)})`);
132
+ if (opts.channelsConfigured === false) {
133
+ await opts.rpc.sendRpc('cron.update', { id: job.id, patch: { delivery: { mode: 'none' } } });
134
+ opts.log(`Heartbeat cron: no chat channel is configured — delivery switched from announce to none (${String(job.name)})`);
135
+ return 'patched';
136
+ }
137
+ // A channel exists (or the config is unreadable): keep announcing, but a
138
+ // missing recipient must not fail the beat. Unlike the switch to `none`
139
+ // this can never silence a summary that is delivered today, so it needs
140
+ // no channel guess — every announce job gets it.
141
+ if (delivery.bestEffort !== undefined)
142
+ return 'unchanged';
143
+ await opts.rpc.sendRpc('cron.update', { id: job.id, patch: { delivery: { bestEffort: true } } });
144
+ opts.log(`Heartbeat cron: announce delivery set to best-effort — a missing chat recipient no longer fails the beat (${String(job.name)})`);
124
145
  return 'patched';
125
146
  }
126
147
  catch (err) {
@@ -227,6 +248,31 @@ export function isAgentIdRejection(err) {
227
248
  const msg = err instanceof Error ? err.message : String(err);
228
249
  return /agentId/i.test(msg) && /additional|unknown|unexpected|invalid|not allowed|schema|must not/i.test(msg);
229
250
  }
251
+ /**
252
+ * The heartbeat's announce delivery. `bestEffort` (OpenClaw cron
253
+ * `delivery.bestEffort`, CLI `--best-effort-deliver`: "Do not fail the job if
254
+ * delivery fails") makes a target that cannot be resolved a logged warning
255
+ * and the run `ok`, while a box whose chat works still gets the summary.
256
+ *
257
+ * ★ 2026-10-14 (a new user's first evening): Telegram configured but never
258
+ * chatted with, so channel `last` resolved to Telegram with no chat id and
259
+ * every beat failed AFTER its work completed — "Delivering to Telegram
260
+ * requires target <chatId>". The no-channel guard (hasConfiguredChannels)
261
+ * cannot see this case: a channel exists, it just has no recipient yet.
262
+ *
263
+ * Trade-off (accepted): OpenClaw also skips its own opt-in cron failure
264
+ * alerts / failureDestination for a bestEffort job — for every error, not
265
+ * only delivery ones. The run status itself stays `error` for a failed turn
266
+ * (OpenClaw re-applies the outcome), so our recorder, model health and fleet
267
+ * alarms are unaffected; they are what watches ReefClaw beats.
268
+ */
269
+ export const HEARTBEAT_ANNOUNCE_DELIVERY = { mode: 'announce', channel: 'last', bestEffort: true };
270
+ /** A gateway that predates `delivery.bestEffort` answers with a schema error
271
+ * naming the field; the job is then created with plain announce, as before. */
272
+ export function isBestEffortRejection(err) {
273
+ const msg = err instanceof Error ? err.message : String(err);
274
+ return /bestEffort/i.test(msg) && /additional|unknown|unexpected|invalid|not allowed|schema|must not/i.test(msg);
275
+ }
230
276
  export async function ensureHeartbeatCron(opts) {
231
277
  const { rpc, markerPath, log } = opts;
232
278
  const agentId = opts.agentId?.trim().toLowerCase() || undefined;
@@ -290,7 +336,15 @@ export async function ensureHeartbeatCron(opts) {
290
336
  return 'created';
291
337
  }
292
338
  try {
293
- await rpc.sendRpc('cron.add', { ...baseJob, delivery: { mode: 'announce', channel: 'last' } });
339
+ try {
340
+ await rpc.sendRpc('cron.add', { ...baseJob, delivery: HEARTBEAT_ANNOUNCE_DELIVERY });
341
+ }
342
+ catch (bestEffortErr) {
343
+ if (!isBestEffortRejection(bestEffortErr))
344
+ throw bestEffortErr;
345
+ log('Heartbeat cron: this OpenClaw does not accept delivery.bestEffort — creating with plain announce');
346
+ await rpc.sendRpc('cron.add', { ...baseJob, delivery: { mode: 'announce', channel: 'last' } });
347
+ }
294
348
  }
295
349
  catch (addErr) {
296
350
  if (agentId && !agentIsDefault && isAgentIdRejection(addErr)) {
@@ -260,7 +260,9 @@ export interface BuildRecordInput {
260
260
  }
261
261
  /** OpenClaw run-log errors raised AFTER the agent turn, by the delivery of
262
262
  * its final reply (announce to a chat channel). On a box with no channel
263
- * every beat ends this way; the trading work itself completed. */
263
+ * every beat ends this way; the trading work itself completed. "requires
264
+ * target" is a channel that exists with no recipient yet (Telegram set up,
265
+ * never chatted with — 2026-10-14), from OpenClaw's missingTargetMessage. */
264
266
  export declare function isDeliveryPhaseError(text: string | null | undefined): boolean;
265
267
  export declare function buildHeartbeatRunRecord(i: BuildRecordInput): HeartbeatRunRecord;
266
268
  /** Shrink a record until its JSON fits `maxBytes`: first shorter tool
@@ -760,11 +760,13 @@ function clean(s) {
760
760
  }
761
761
  /** OpenClaw run-log errors raised AFTER the agent turn, by the delivery of
762
762
  * its final reply (announce to a chat channel). On a box with no channel
763
- * every beat ends this way; the trading work itself completed. */
763
+ * every beat ends this way; the trading work itself completed. "requires
764
+ * target" is a channel that exists with no recipient yet (Telegram set up,
765
+ * never chatted with — 2026-10-14), from OpenClaw's missingTargetMessage. */
764
766
  export function isDeliveryPhaseError(text) {
765
767
  if (!text)
766
768
  return false;
767
- return /channel is required|no configured channels|no resolvable (recipient|owner|channel)|announce delivery/i.test(text);
769
+ return /channel is required|no configured channels|no resolvable (recipient|owner|channel)|announce delivery|delivering to .+ requires target/i.test(text);
768
770
  }
769
771
  export function buildHeartbeatRunRecord(i) {
770
772
  const t = i.transcript;
@@ -780,8 +782,21 @@ export function buildHeartbeatRunRecord(i) {
780
782
  // A delivery-only failure (announce with no channel) after a completed
781
783
  // turn is NOT a failed beat — 2026-09-27, every channel-less box.
782
784
  const runLogError = clean(rl?.error);
783
- const deliveryOnly = rl?.status === 'error' &&
784
- isDeliveryPhaseError(runLogError) &&
785
+ // ★ The turn itself must not have failed. On a job without
786
+ // delivery.bestEffort, OpenClaw reports the DELIVERY error even when the
787
+ // agent turn died first (a retired model), replacing the model's error in
788
+ // the run log — so a delivery-phase run error proves nothing on its own.
789
+ // An errored assistant message still counts in assistantCount, so the
790
+ // completed-turn check below cannot catch it either (2026-10-15 review).
791
+ const endedStatus = tj?.ended?.status ?? null;
792
+ const turnFailed = t.lastStopReason === 'error' ||
793
+ t.lastErrorMessage != null ||
794
+ tj?.ended?.timedOut === true ||
795
+ tj?.ended?.promptError != null ||
796
+ (endedStatus != null && endedStatus !== 'success' && endedStatus !== 'ok');
797
+ const deliveryPhase = rl?.status === 'error' && isDeliveryPhaseError(runLogError);
798
+ const deliveryOnly = deliveryPhase &&
799
+ !turnFailed &&
785
800
  (t.complete || t.finalText != null || t.assistantCount > 0);
786
801
  let status;
787
802
  if (rl?.status === 'ok' || deliveryOnly)
@@ -825,7 +840,13 @@ export function buildHeartbeatRunRecord(i) {
825
840
  .map((e) => ({ ...e, detail: scrubSecrets(e.detail) }))
826
841
  .sort((a, b) => (a.at ?? 0) - (b.at ?? 0))
827
842
  .slice(0, MODEL_EVENTS_MAX);
828
- const errorText = (deliveryOnly ? null : runLogError) ?? clean(tj?.ended?.promptError) ?? clean(t.lastErrorMessage);
843
+ // A delivery-phase run-log error on a failed turn hides the turn's own
844
+ // error: show the turn's error first, the delivery text only as a fallback.
845
+ const errorText = deliveryOnly
846
+ ? clean(tj?.ended?.promptError) ?? clean(t.lastErrorMessage)
847
+ : deliveryPhase
848
+ ? clean(tj?.ended?.promptError) ?? clean(t.lastErrorMessage) ?? runLogError
849
+ : runLogError ?? clean(tj?.ended?.promptError) ?? clean(t.lastErrorMessage);
829
850
  const summaryClip = t.finalText ? clip(scrubSecrets(t.finalText), SUMMARY_MAX) : null;
830
851
  const toolCalls = t.toolCalls.map((c) => ({
831
852
  ...c,