@reefclaw/openclaw-plugin 0.1.48 → 0.1.50

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 (40) hide show
  1. package/README.md +10 -6
  2. package/bridge/bridge.js +22 -16
  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 +64 -0
  6. package/bridge/gateway/heartbeat-cron.js +150 -1
  7. package/bridge/provider.d.ts +12 -0
  8. package/bridge/providers/connector-update-direct.d.ts +3 -0
  9. package/bridge/providers/connector-update-direct.js +11 -1
  10. package/bridge/providers/connector-update-openclaw.d.ts +268 -0
  11. package/bridge/providers/connector-update-openclaw.js +772 -0
  12. package/bridge/providers/connector-update.d.ts +115 -1
  13. package/bridge/providers/connector-update.js +228 -13
  14. package/bridge/providers/gateway.d.ts +52 -10
  15. package/bridge/providers/gateway.js +243 -34
  16. package/bridge/utils/skill-version.d.ts +6 -0
  17. package/bridge/utils/skill-version.js +10 -0
  18. package/config/first-start-venue.d.ts +147 -0
  19. package/config/first-start-venue.js +400 -0
  20. package/config/plugin-config-io.d.ts +9 -2
  21. package/config/plugin-config-io.js +29 -5
  22. package/connector-supervisor.d.ts +20 -0
  23. package/connector-supervisor.js +27 -1
  24. package/index.js +36 -1
  25. package/openclaw.plugin.json +333 -1
  26. package/package.json +1 -1
  27. package/release-integrity.json +10 -0
  28. package/release-notes.json +3 -1
  29. package/signals/stop-rules.d.ts +13 -0
  30. package/signals/stop-rules.js +35 -6
  31. package/signals/strategy-adapter.js +25 -6
  32. package/skills/reefclaw/SKILL.md +21 -8
  33. package/tools/assessment-validation.d.ts +10 -2
  34. package/tools/assessment-validation.js +19 -5
  35. package/tools/create-order.d.ts +4 -0
  36. package/tools/create-order.js +15 -0
  37. package/tools/intel-cache.d.ts +14 -0
  38. package/tools/intel-cache.js +59 -0
  39. package/tools/venue-quote-hint.d.ts +49 -0
  40. 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/bridge.js CHANGED
@@ -15,7 +15,7 @@ import { logger, formatError } from './logger.js';
15
15
  import { noteWebappResponse, webappEdgeTracker, webappHeaders } from './utils/webapp-edge.js';
16
16
  import { resolveWebappBaseUrl } from './utils/base-url.js';
17
17
  import { Connector } from './connector.js';
18
- import { readLocalSkillVersion, readAgentVisibleSkillVersions, validateSkillContent, compareSemver } from './utils/skill-version.js';
18
+ import { readLocalSkillVersion, readAgentVisibleSkillVersions, validateSkillContent, compareSemver, isBootstrapSkillVersion } from './utils/skill-version.js';
19
19
  import { invalidateSkillsSnapshot } from './utils/skills-snapshot-invalidation.js';
20
20
  import { verifySkillSignature, signatureRequired, readLastAppliedSignedAtMs, recordAppliedSignedAt, } from './utils/skill-signing.js';
21
21
  import { isTradingMode, validateModeTransition, redactTokens } from '@reefclaw/shared';
@@ -66,15 +66,6 @@ const BOOTSTRAP_SKILL_HEAL_INTERVAL_MS = 10 * 60_000; // 10 min
66
66
  /** How often the bridge drains edge-deny transitions into agent_state events
67
67
  * (skill.webapp_edge_denied / _recovered audit rows via the relay). */
68
68
  const WEBAPP_EDGE_EMIT_INTERVAL_MS = 60_000;
69
- /** True while the agent is still on the thin bootstrap SKILL.md and has NOT yet
70
- * received the full trading instructions. The bootstrap ships 0.0.x; the full
71
- * trading SKILL.md is 2.x — treat anything below 1.0.0 (or an unknown version)
72
- * as bootstrap so we keep pulling until the real skill lands. */
73
- function isBootstrapSkillVersion(version) {
74
- if (!version)
75
- return true;
76
- return compareSemver('1.0.0', version) > 0; // '1.0.0' > version ⟺ version < 1.0.0
77
- }
78
69
  /** The single-agent layout every box used before multi-agent attach. */
79
70
  export function defaultBridgePaths() {
80
71
  return {
@@ -1298,13 +1289,28 @@ export class Bridge {
1298
1289
  else if (invalidation.outcome !== 'no-sessions-file') {
1299
1290
  logger.info(TAG, invalidation.message);
1300
1291
  }
1301
- // 4. Send chat message to agent to trigger immediate re-read
1302
- try {
1303
- await this.provider.handleChat(`Your trading instructions (SKILL.md) have been updated to v${version}. ` +
1304
- `Check for any open positions with fetch_positions() and fetch_open_orders(), then re-read SKILL.md to confirm you've processed the changes.`);
1292
+ // 4. Send chat message to agent to trigger immediate re-read — except
1293
+ // while this install's FIRST market check is pending (the heartbeat
1294
+ // job was just created and runFirstHeartbeat is waiting for these
1295
+ // instructions): that check reads them itself, and the notice would
1296
+ // be a second agent turn at the same moment on a new box. The
1297
+ // provider holds the notice and sends it only if the first check
1298
+ // ends without starting, so every other path (existing job, a slow
1299
+ // or blocked pull past the wait, a restart) still gets it.
1300
+ const sendNotice = async () => {
1301
+ try {
1302
+ await this.provider.handleChat(`Your trading instructions (SKILL.md) have been updated to v${version}. ` +
1303
+ `Check for any open positions with fetch_positions() and fetch_open_orders(), then re-read SKILL.md to confirm you've processed the changes.`);
1304
+ }
1305
+ catch (chatErr) {
1306
+ logger.warn(TAG, `Chat notification failed (non-fatal): ${chatErr instanceof Error ? chatErr.message : String(chatErr)}`);
1307
+ }
1308
+ };
1309
+ if (this.provider.deferToFirstMarketCheck?.(() => { void sendNotice(); }) === true) {
1310
+ logger.info(TAG, `SKILL.md v${version} applied while the first market check is pending — chat notice held (sent only if that check does not start)`);
1305
1311
  }
1306
- catch (chatErr) {
1307
- logger.warn(TAG, `Chat notification failed (non-fatal): ${chatErr instanceof Error ? chatErr.message : String(chatErr)}`);
1312
+ else {
1313
+ await sendNotice();
1308
1314
  }
1309
1315
  // 5. Update local version tracker + advance the replay clock. The clock
1310
1316
  // advances ONLY on a VERIFIED signature: recording an unverified
@@ -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
+ }
@@ -24,6 +24,17 @@ export declare function hasConfiguredChannels(cfg: unknown): boolean | undefined
24
24
  * delivery `announce` can only fail at run time, so switch it to `none`.
25
25
  * Runs on every bridge start (cheap: one cron.list), independent of the
26
26
  * once-per-install marker, because the job predates this fix on every box.
27
+ *
28
+ * ★ `cron.update` needs operator.admin, which the long-lived session holds
29
+ * only when the process started with the heartbeat ensure owed, so on a box
30
+ * with a marker this patch is refused and nothing changes. That is
31
+ * DELIBERATE (2026-09-29 review): the "no channel" signal
32
+ * (hasConfiguredChannels) reads only the top-level openclaw.json and
33
+ * misreads an env-only Telegram token, `$include`d channels and a moved
34
+ * config dir as "none". Widening the repair (an admin side-session was
35
+ * tried) would silently switch off heartbeat summaries that work today. A
36
+ * wider repair must key off the job's own recorded delivery failure, never
37
+ * this guess.
27
38
  */
28
39
  export declare function reconcileHeartbeatDelivery(opts: {
29
40
  rpc: CronRpcClient;
@@ -65,6 +76,16 @@ export declare function pickHeartbeatJob<T extends {
65
76
  name?: unknown;
66
77
  payload?: unknown;
67
78
  }>(jobs: readonly T[]): T | undefined;
79
+ /**
80
+ * Is the once-per-install ensure still owed on this box? True with no marker,
81
+ * and with a marker from the old rule that adopted a job that is not
82
+ * ReefClaw's (re-checked once). ensureHeartbeatCron runs exactly when this is
83
+ * true, and the bridge requests operator.admin exactly when this is true:
84
+ * both read this one function so they cannot drift. (They did: the re-check
85
+ * ran on a read/write-only session, so its cron.add failed on the scope and
86
+ * the adopted box kept getting no ReefClaw beat.)
87
+ */
88
+ export declare function heartbeatEnsureOwed(markerPath: string): boolean;
68
89
  export type EnsureHeartbeatOutcome = 'already_ensured' | 'found_existing' | 'created' | 'failed';
69
90
  /**
70
91
  * Ensure a heartbeat cron exists. Non-fatal by contract: every failure path
@@ -96,3 +117,46 @@ export declare function ensureHeartbeatCron(opts: {
96
117
  * `none` (announce can only fail); true/undefined → announce as before. */
97
118
  channelsConfigured?: boolean;
98
119
  }): Promise<EnsureHeartbeatOutcome>;
120
+ /** How long a fresh install waits for the full trading instructions before
121
+ * starting its first market check. Past this, the first check is left to the
122
+ * regular schedule (one interval later), exactly as before. */
123
+ export declare const FIRST_BEAT_MAX_WAIT_MS = 120000;
124
+ export type FirstBeatOutcome = 'started' | 'not_ready' | 'not_found' | 'not_run' | 'inactive' | 'unknown' | 'failed';
125
+ /**
126
+ * Start the FIRST market check right away on a fresh install instead of one
127
+ * full interval (15 min) after connecting.
128
+ *
129
+ * Why (2026-09-29): a new user connected, saw "You're connected", and then
130
+ * nothing happened for 15 minutes — the job's first run is scheduled one
131
+ * interval after creation. Call this ONLY when ensureHeartbeatCron returned
132
+ * 'created' (a brand-new job, once per install): it must never add beats to
133
+ * an existing agent.
134
+ *
135
+ * Rules:
136
+ * • Waits (≤ FIRST_BEAT_MAX_WAIT_MS) until the full trading SKILL.md is what
137
+ * the agent reads. A beat on the bootstrap instructions would be a wasted
138
+ * run; if they never arrive, the first check stays on the schedule (old
139
+ * behaviour).
140
+ * • `cron.run` needs operator.admin, which the bridge's session holds only
141
+ * when the process started with the ensure owed; call this with the client
142
+ * that created the job.
143
+ * • ONE cron.run call, never retried: a timeout or a dropped socket may
144
+ * still have started the run, and a second call would start a second beat.
145
+ * • Never throws; every failure leaves the regular schedule untouched.
146
+ */
147
+ export declare function runFirstHeartbeat(opts: {
148
+ rpc: CronRpcClient;
149
+ log: (msg: string) => void;
150
+ agentId?: string;
151
+ agentIsDefault?: boolean;
152
+ /** True once the full trading SKILL.md (not the bootstrap) is what the agent reads. */
153
+ instructionsReady: () => boolean;
154
+ /** False once the connection this was started on is gone (provider stopped
155
+ * or client replaced). Checked while waiting and before each call.
156
+ * Absent = always active. */
157
+ isActive?: () => boolean;
158
+ maxWaitMs?: number;
159
+ pollMs?: number;
160
+ /** Injectable for tests. */
161
+ sleep?: (ms: number) => Promise<void>;
162
+ }): Promise<FirstBeatOutcome>;