@reefclaw/openclaw-plugin 0.1.34 → 0.1.35

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.
package/README.md ADDED
@@ -0,0 +1,65 @@
1
+ # @reefclaw/openclaw-plugin
2
+
3
+ The ReefClaw trading plugin for OpenClaw. It gives an OpenClaw agent a supervised trading toolkit and connects it to the operator's ReefClaw dashboard. Everything runs on the operator's own machine; ReefClaw's servers host the dashboard, a relay and a market-data API, and never execute trades.
4
+
5
+ This file is the plain-language ledger of what the package does on the machine it is installed on: what runs, what it writes, what it sends, what it never does, and how to switch each part off. Every line is checkable against the shipped source.
6
+
7
+ ## What runs
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`.
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
+ - 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 operator provenance from the dashboard.
12
+
13
+ ## What it writes on this machine
14
+
15
+ | Path | What | Why |
16
+ | --- | --- | --- |
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 |
18
+ | `~/.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
+ | 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** |
21
+ | 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
+ | 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
+ | 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 |
24
+
25
+ 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
+
27
+ ## What leaves this machine
28
+
29
+ Everything below goes to the operator's own ReefClaw account and nowhere else.
30
+
31
+ | Flow | What is sent | Switch |
32
+ | --- | --- | --- |
33
+ | Dashboard relay | Order, position, balance and agent-state events; dashboard chat both ways | none, it is the product |
34
+ | Journal / trade feed | Fills, position entries, heartbeat reviews and closes with the agent's stated reasoning | none, it is the product |
35
+ | Heartbeat flight recorder | For every heartbeat: the tool calls it made (arguments and results truncated, credential-shaped tools redacted), its final report, the model that answered and raw token counts | `RC_HEARTBEAT_RECORDER=off` |
36
+ | Shock wakes | Nothing is sent; the connector polls the account's `shockWake` setting and, when the operator turned it on, delivers up to 8 extra agent turns a day on a sharp market move | `RC_SHOCK_WAKE=off` |
37
+ | Intelligence | Market-context reads; the plugin sends symbols and parameters, never keys | none, tools degrade without it |
38
+ | Version report | The installed plugin and connector versions, so the dashboard can offer an update | none |
39
+
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.
41
+
42
+ ## What it never does
43
+
44
+ - **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
+ - **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.
47
+ - **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
+
49
+ ## Switches and removal
50
+
51
+ | Setting | Effect |
52
+ | --- | --- |
53
+ | `REEFCLAW_ALLOW_CONNECTOR_UPDATE=0` (or `connectorUpdate: "off"` in `plugin-config.json`) | The dashboard's one-click update is refused on this box |
54
+ | `RC_HEARTBEAT_RECORDER=off` | Heartbeat transcripts are not read or reported |
55
+ | `RC_SHOCK_WAKE=off` | Shock wakes are never constructed, whatever the account setting says |
56
+ | `SKILL_OTA_REQUIRE_SIGNATURE=off` | Break-glass: accept an *unsigned* instruction update on this box (a forged signature is still always refused) |
57
+
58
+ 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.
59
+
60
+ ## Install
61
+
62
+ - From ClawHub on OpenClaw 2026.8.1 or newer: Control UI → Plugins → Discover → search "reefclaw" → Install, then accept the listed capabilities; or in chat `/plugins install clawhub:@reefclaw/openclaw-plugin`, then the same command with `--accept-capabilities` after reading the capability list (the chat command needs `commands.plugins: true` in `openclaw.json`).
63
+ - Or with the ReefClaw connect installer from npm (`@reefclaw/connect`), run once in a terminal on the OpenClaw host and pinned to the exact release named in the bundled skill and on the onboarding page.
64
+
65
+ Support: support@reefclaw.com · https://reefclaw.com
@@ -28,17 +28,16 @@ export declare function writeOpenClawConfig(token: string, userId?: string, rela
28
28
  * never gets to run — this is the equivalent proven-need signal for it. */
29
29
  export declare function isDeviceIdentityRejection(code: number | undefined, reason: string | undefined): boolean;
30
30
  export declare function handshakeLacksWriteScope(scopes: readonly string[] | undefined): boolean;
31
+ /** The two legacy gateway flags older OpenClaw builds needed before they would
32
+ * keep `operator.write` on a connection without device identity. Named here
33
+ * ONLY so the remedy text can spell them out — this module never writes them. */
34
+ export declare const LEGACY_GATEWAY_AUTH_FLAGS: readonly ["gateway.controlUi.dangerouslyDisableDeviceAuth", "gateway.controlUi.allowInsecureAuth"];
31
35
  /**
32
- * LAST RESORT: relax the local gateway's device-identity auth because a
33
- * completed handshake proved the gateway is withholding `operator.write`
34
- * (without it the bridge cannot place or cancel orders). Idempotent, and a
35
- * no-op once the flags are set — so it warns exactly once per box, at the
36
- * moment the need is demonstrated.
37
- *
38
- * Returns true if it changed the config (⇒ the gateway must be restarted for
39
- * the flags to take effect; they are read at gateway boot).
36
+ * Operator-facing remedy for a gateway that withholds `operator.write` (or
37
+ * rejects the handshake for missing device identity). Pure: it builds text
38
+ * and changes nothing on disk.
40
39
  */
41
- export declare function relaxGatewayDeviceAuth(reason: string): boolean;
40
+ export declare function describeGatewayWriteScopeRemedy(reason: string): string;
42
41
  export interface CliArgs {
43
42
  provider: 'mock' | 'gateway';
44
43
  token?: string;
package/bridge/config.js CHANGED
@@ -17,13 +17,13 @@ const DEFAULT_RELAY_URL = 'wss://reefclaw.radunlupsa.partykit.dev';
17
17
  // during onboarding, so the connector can pick the connection up and persist
18
18
  // it across restarts). Every other key in the file is preserved verbatim.
19
19
  //
20
- // It deliberately does NOT weaken the local gateway's auth. Until 2026-07-29
21
- // it also set gateway.controlUi.{dangerouslyDisableDeviceAuth,
22
- // allowInsecureAuth} = true on EVERY write — a security-relevant downgrade of
23
- // the user's own gateway, applied pre-emptively whether or not their OpenClaw
24
- // needed it. That relaxation now happens only on PROVEN need, via
25
- // relaxGatewayDeviceAuth() below, which the bridge calls if and only if a
26
- // completed handshake shows the gateway actually withheld `operator.write`.
20
+ // It deliberately does NOT touch the local gateway's auth settings. Until
21
+ // 2026-07-29 the connector set gateway.controlUi.{dangerouslyDisableDeviceAuth,
22
+ // allowInsecureAuth} = true on every write, and until 2026-09-19 it still
23
+ // wrote them as a "last resort" when a handshake came back without
24
+ // `operator.write`. Both are gone: this software never changes the user's
25
+ // gateway security posture. When the gateway withholds the scope, the bridge
26
+ // logs the exact manual remedy (describeGatewayWriteScopeRemedy) and stops.
27
27
  /** Read the OpenClaw config file and extract ReefClaw skill settings.
28
28
  * Prefers the schema-valid nested shape (entry.config.*), falls back to the
29
29
  * legacy flat shape per-field. */
@@ -80,8 +80,9 @@ export function writeOpenClawConfig(token, userId, relayUrl) {
80
80
  delete entry.token;
81
81
  delete entry.userId;
82
82
  delete entry.relayUrl;
83
- // NOTE: no gateway.controlUi relaxation here. Saving a connection must not
84
- // change the user's gateway security posture — see relaxGatewayDeviceAuth().
83
+ // NOTE: nothing under gateway.controlUi is touched here or anywhere else in
84
+ // the connector. Saving a connection must not change the user's gateway
85
+ // security posture — see describeGatewayWriteScopeRemedy().
85
86
  // Write — file holds the connection token, so restrict to owner.
86
87
  mkdirSync(OPENCLAW_DIR, { recursive: true, mode: 0o700 });
87
88
  writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2) + '\n', { encoding: 'utf-8', mode: 0o600 });
@@ -104,43 +105,15 @@ function restrictConfigPermissions() {
104
105
  logger.debug(TAG, `Could not chmod ${CONFIG_PATH} to 0600: ${err instanceof Error ? err.message : String(err)}`);
105
106
  }
106
107
  }
107
- // ---- Gateway device-auth relaxation (LAST RESORT, proven need only) ----
108
+ // ---- Gateway scope: report, never relax ----
108
109
  //
109
- // Some OpenClaw builds (observed on v2026.4.2) clear `operator.write` from a WS
110
- // connection that carries no device identity — the bridge then cannot place or
111
- // cancel orders. The historical workaround was to set
112
- // gateway.controlUi.{dangerouslyDisableDeviceAuth, allowInsecureAuth} = true
113
- // on every install and every config save, whether or not the user's OpenClaw
114
- // actually behaved that way. That is a real downgrade of the user's gateway
115
- // applied on speculation, and the flag name says so.
116
- //
117
- // Since 2026-07-29 the relaxation is applied ONLY when a completed handshake
118
- // proves it is needed: the bridge inspects the granted scopes from hello-ok and
119
- // calls relaxGatewayDeviceAuth() if `operator.write` is missing. On the
120
- // supported range (the plugin's compat floor is pluginApi >=2026.6.0) the
121
- // handshake keeps its scopes and these flags are never written at all. Boxes
122
- // that already have them keep them — nothing here removes an existing flag,
123
- // because clearing it mid-session would strip the running bridge's scopes.
124
- /** Set the two relaxation flags on an in-memory config. Returns true if either
125
- * changed, so callers only write + disclose when something actually flipped. */
126
- function applyGatewayAuthRelaxation(config) {
127
- if (!config.gateway)
128
- config.gateway = {};
129
- const gw = config.gateway;
130
- if (!gw.controlUi)
131
- gw.controlUi = {};
132
- const cui = gw.controlUi;
133
- let changed = false;
134
- if (cui.dangerouslyDisableDeviceAuth !== true) {
135
- cui.dangerouslyDisableDeviceAuth = true;
136
- changed = true;
137
- }
138
- if (cui.allowInsecureAuth !== true) {
139
- cui.allowInsecureAuth = true;
140
- changed = true;
141
- }
142
- return changed;
143
- }
110
+ // Some OpenClaw builds withhold `operator.write` from a connection that
111
+ // carries no device identity, and OpenClaw >= 2026.9 rejects such a handshake
112
+ // outright. From 2026-07-29 to 2026-09-19 the connector answered that by
113
+ // writing gateway.controlUi.{dangerouslyDisableDeviceAuth, allowInsecureAuth}
114
+ // = true into the user's openclaw.json itself. It no longer does: a downgrade
115
+ // of the user's gateway auth is the user's decision, made by hand. The helpers
116
+ // below only DETECT the condition and DESCRIBE the remedy.
144
117
  /** True when the bridge lacks the write scope it needs to trade — i.e. the
145
118
  * gateway granted a scope set without `operator.write`. Read from the
146
119
  * handshake, so it reflects what the gateway ACTUALLY did, not a version
@@ -165,37 +138,29 @@ export function handshakeLacksWriteScope(scopes) {
165
138
  return false;
166
139
  return !scopes.includes('operator.write');
167
140
  }
141
+ /** The two legacy gateway flags older OpenClaw builds needed before they would
142
+ * keep `operator.write` on a connection without device identity. Named here
143
+ * ONLY so the remedy text can spell them out — this module never writes them. */
144
+ export const LEGACY_GATEWAY_AUTH_FLAGS = [
145
+ 'gateway.controlUi.dangerouslyDisableDeviceAuth',
146
+ 'gateway.controlUi.allowInsecureAuth',
147
+ ];
168
148
  /**
169
- * LAST RESORT: relax the local gateway's device-identity auth because a
170
- * completed handshake proved the gateway is withholding `operator.write`
171
- * (without it the bridge cannot place or cancel orders). Idempotent, and a
172
- * no-op once the flags are set — so it warns exactly once per box, at the
173
- * moment the need is demonstrated.
174
- *
175
- * Returns true if it changed the config (⇒ the gateway must be restarted for
176
- * the flags to take effect; they are read at gateway boot).
149
+ * Operator-facing remedy for a gateway that withholds `operator.write` (or
150
+ * rejects the handshake for missing device identity). Pure: it builds text
151
+ * and changes nothing on disk.
177
152
  */
178
- export function relaxGatewayDeviceAuth(reason) {
179
- try {
180
- const raw = readFileSync(CONFIG_PATH, 'utf-8');
181
- const config = JSON5.parse(raw);
182
- if (!applyGatewayAuthRelaxation(config))
183
- return false; // already relaxed
184
- writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2) + '\n', { encoding: 'utf-8', mode: 0o600 });
185
- restrictConfigPermissions(); // mode above is ignored on an existing file
186
- logger.warn(TAG, `Enabled gateway.controlUi.{dangerouslyDisableDeviceAuth,allowInsecureAuth} in ` +
187
- `${CONFIG_PATH} because ${reason}. This RELAXES your local gateway's ` +
188
- `device-identity auth — it is the only way this OpenClaw build will keep ` +
189
- `operator.write on the bridge connection, which trading requires. Keep the ` +
190
- `gateway bound to localhost. RESTART the gateway for it to take effect. If ` +
191
- `you would rather not run with it, upgrade OpenClaw (builds meeting the ` +
192
- `plugin's compat floor keep the scope without this) and remove both flags.`);
193
- return true;
194
- }
195
- catch {
196
- // Config missing/unparseable — setup hasn't run yet; nothing to relax.
197
- return false;
198
- }
153
+ export function describeGatewayWriteScopeRemedy(reason) {
154
+ return (`The OpenClaw gateway did not grant the connector operator.write (${reason}), so order ` +
155
+ `placement and cancellation would fail on this connection. ReefClaw does not change your ` +
156
+ `gateway's auth settings; the fix is yours to apply. Options: (1) upgrade OpenClaw to a build ` +
157
+ `that meets this plugin's compat floor — those keep the scope for the connector's ` +
158
+ `local-backend identity with no flags at all; (2) on OpenClaw 2026.9+, pair the connector as a ` +
159
+ `device or run the gateway with device pairing configured (see the gateway auth section of ` +
160
+ `${CONFIG_PATH}); (3) on older builds the historical workaround was setting ` +
161
+ `${LEGACY_GATEWAY_AUTH_FLAGS.join(' and ')} to true in ${CONFIG_PATH} and restarting the gateway — ` +
162
+ `that relaxes device-identity auth for every client, so only do it on a gateway bound to ` +
163
+ `localhost. Trading tools stay blocked until the gateway grants the scope.`);
199
164
  }
200
165
  /**
201
166
  * Resolve config with priority:
@@ -120,7 +120,7 @@ export async function ensureHeartbeatCron(opts) {
120
120
  // right for boxes with a chat channel (the heartbeat's summary reaches the
121
121
  // operator). On a FRESH box with no channels configured, cron.add REJECTS
122
122
  // announce/'last' (no resolvable recipient — observed live on a first
123
- // real npx onboarding, 2026-07-22; the old setup-time CLI path failed the
123
+ // real connect-installer onboarding, 2026-07-22; the old setup-time CLI path failed the
124
124
  // same way, silently). Fall back to delivery mode 'none': a heartbeat that
125
125
  // runs without announcing beats no heartbeat at all, and the operator sees
126
126
  // the results on the dashboard anyway.
@@ -1,17 +1,46 @@
1
+ /** The npm package the update runs. Fixed. */
2
+ export declare const CONNECT_PACKAGE = "@reefclaw/connect";
3
+ export declare function isExactConnectVersion(v: unknown): v is string;
1
4
  /**
2
- * The ONE command this feature can ever run.
3
- *
4
- * `-y` so npx never blocks on its install prompt; `@latest` because this is an
5
- * update. No user input, no interpolation, no exceptions.
5
+ * The ONE command shape this feature can ever run. The only variable part is
6
+ * an exact version, validated against EXACT_VERSION_RE; anything else throws.
7
+ * `-y` keeps the package runner from stopping at its install prompt.
6
8
  */
7
- export declare const CONNECTOR_UPDATE_COMMAND = "npx -y @reefclaw/connect@latest";
9
+ export declare function connectorUpdateCommand(version: string): string;
8
10
  /** Marker printed after the command so we can detect completion + exit code. */
9
11
  export declare const DONE_SENTINEL = "__RC_CONNECTOR_UPDATE_DONE__";
10
12
  /**
11
- * The exact line written to the PTY. Built once, from constants only.
12
- * `$?` is expanded by the remote shell, not by us.
13
+ * The exact line written to the PTY. `$?` is expanded by the remote shell,
14
+ * not by us.
15
+ */
16
+ export declare function buildUpdateCommandLine(version: string): string;
17
+ /** Manual-fallback copy for the refusals below: the operator runs the same
18
+ * pinned command from a shell on the box. `version` is unknown when the
19
+ * refusal happened before the release lookup. */
20
+ export declare function manualUpdateHint(version?: string): string;
21
+ export interface PinnedVersionLookup {
22
+ /** Webapp base URL; defaults to REEFCLAW_API_URL, then production. */
23
+ webappUrl?: string;
24
+ fetchImpl?: typeof fetch;
25
+ }
26
+ export type PinnedVersionResult = {
27
+ ok: true;
28
+ version: string;
29
+ } | {
30
+ ok: false;
31
+ outcome: ConnectorUpdateOutcome;
32
+ };
33
+ /**
34
+ * Ask ReefClaw which connector release an update installs: `connectVersion` on
35
+ * the PUBLIC `/api/release` endpoint, baked by the webapp at build from the
36
+ * released installer (the same constants ride the authenticated config
37
+ * channel as `release.connectVersion`). No credential is needed or sent —
38
+ * release versions are public data, and an update must keep working on a box
39
+ * whose connection token is stale. Any failure, or anything that is not an
40
+ * exact version, refuses the update — this feature never falls back to an
41
+ * unpinned install.
13
42
  */
14
- export declare function buildUpdateCommandLine(): string;
43
+ export declare function fetchPinnedConnectVersion(opts: PinnedVersionLookup): Promise<PinnedVersionResult>;
15
44
  /** Minimal RPC surface this module needs (injected — keeps it unit-testable). */
16
45
  export type TerminalRpc = (method: string, params: Record<string, unknown>) => Promise<unknown>;
17
46
  export type ConnectorUpdateStatus =
@@ -90,7 +119,9 @@ export declare function checkPositionGuard(opts: StartOptions): ConnectorUpdateO
90
119
  * Open a PTY and write the update command to it. Returns as soon as the command
91
120
  * is running — the caller polls `readTerminalText` for output.
92
121
  */
93
- export declare function startConnectorUpdate(rpc: TerminalRpc, opts: StartOptions): Promise<ConnectorUpdateOutcome>;
122
+ export declare function startConnectorUpdate(rpc: TerminalRpc, opts: StartOptions,
123
+ /** Exact connector release to install — from fetchPinnedConnectVersion, nowhere else. */
124
+ version: string): Promise<ConnectorUpdateOutcome>;
94
125
  /** Read the current screen contents. Returns null when the session is gone. */
95
126
  export declare function readTerminalText(rpc: TerminalRpc, sessionId: string): Promise<string | null>;
96
127
  /** Best-effort PTY cleanup. Never throws — cleanup failure must not mask an outcome. */
@@ -15,11 +15,16 @@
15
15
  // This module can run a command on the trader's machine, initiated from our
16
16
  // dashboard. That is only acceptable because the command is a FIXED CONSTANT:
17
17
  //
18
- // - `CONNECTOR_UPDATE_COMMAND` is a module constant. Nothing from the
19
- // browser, the relay, the agent, or any config is interpolated into it.
20
- // There is deliberately NO version/args/flags parameter — not even a
21
- // validated one — because the moment a caller can influence the string this
22
- // stops being an update button and becomes a remote shell.
18
+ // - The command shape is fixed (`connectorUpdateCommand`). Its ONLY variable
19
+ // is an exact release version, and that version has exactly one source:
20
+ // ReefClaw's release endpoint (`fetchPinnedConnectVersion`, a public HTTPS
21
+ // GET of build-time constants; release versions are public data), validated
22
+ // as MAJOR.MINOR.PATCH before use. Nothing from the browser, the
23
+ // relay, the agent, or any config file reaches the string, and there is no
24
+ // args/flags parameter. A missing or malformed version refuses the update;
25
+ // it never falls back to an unpinned install. The moment a caller could
26
+ // influence the string this would stop being an update button and become
27
+ // a remote shell, which is why the RPC carries none.
23
28
  // - The RPC that reaches this module carries NO command field. Adding one is
24
29
  // not a feature request to accept; it is the vulnerability.
25
30
  // - No secret is ever placed on the command line. `@reefclaw/connect` takes
@@ -43,31 +48,89 @@
43
48
  // `gateway.terminal.enabled=false` is honoured too (`describeOpenFailure`).
44
49
  // - terminal.* needs operator.admin: the update opens a separate short-lived
45
50
  // admin session and checks the granted scopes before `terminal.open`.
46
- // - Residual trust: `@latest` resolves on the npm registry, so the trust root
47
- // is the registry plus the publisher account (2FA), exactly as for a manual
48
- // `npx`. Pinning an exact, offline-signed version is the planned follow-up
49
- // (the SKILL.md OTA already carries the Ed25519 key for it).
51
+ // - Residual trust: the exact version still resolves on the npm registry, so
52
+ // the trust root is the registry plus the publisher account (2FA), exactly
53
+ // as for a manual install of that version. An offline signature over the
54
+ // release (the SKILL.md OTA already carries the Ed25519 key for it) is the
55
+ // planned next step.
50
56
  // - The updater overwrites local modifications to the placed bridge/plugin,
51
57
  // as any reinstall would. Self-hosters carrying patches: switch it off.
52
58
  import { logger } from '../logger.js';
53
59
  const TAG = 'connector-update';
60
+ /** The npm package the update runs. Fixed. */
61
+ export const CONNECT_PACKAGE = '@reefclaw/connect';
62
+ /** Exact release versions only — no tags, ranges or pre-release suffixes. */
63
+ const EXACT_VERSION_RE = /^\d{1,4}\.\d{1,4}\.\d{1,4}$/;
64
+ export function isExactConnectVersion(v) {
65
+ return typeof v === 'string' && EXACT_VERSION_RE.test(v);
66
+ }
54
67
  /**
55
- * The ONE command this feature can ever run.
56
- *
57
- * `-y` so npx never blocks on its install prompt; `@latest` because this is an
58
- * update. No user input, no interpolation, no exceptions.
68
+ * The ONE command shape this feature can ever run. The only variable part is
69
+ * an exact version, validated against EXACT_VERSION_RE; anything else throws.
70
+ * `-y` keeps the package runner from stopping at its install prompt.
59
71
  */
60
- export const CONNECTOR_UPDATE_COMMAND = 'npx -y @reefclaw/connect@latest';
72
+ export function connectorUpdateCommand(version) {
73
+ if (!isExactConnectVersion(version)) {
74
+ throw new Error(`refusing to build an update command for a non-exact version: ${JSON.stringify(version)}`);
75
+ }
76
+ return `npx -y ${CONNECT_PACKAGE}@${version}`;
77
+ }
61
78
  /** Marker printed after the command so we can detect completion + exit code. */
62
79
  export const DONE_SENTINEL = '__RC_CONNECTOR_UPDATE_DONE__';
63
80
  /**
64
- * The exact line written to the PTY. Built once, from constants only.
65
- * `$?` is expanded by the remote shell, not by us.
81
+ * The exact line written to the PTY. `$?` is expanded by the remote shell,
82
+ * not by us.
83
+ */
84
+ export function buildUpdateCommandLine(version) {
85
+ return `${connectorUpdateCommand(version)}; printf '\\n${DONE_SENTINEL}%s\\n' "$?"`;
86
+ }
87
+ /** Manual-fallback copy for the refusals below: the operator runs the same
88
+ * pinned command from a shell on the box. `version` is unknown when the
89
+ * refusal happened before the release lookup. */
90
+ export function manualUpdateHint(version) {
91
+ return version
92
+ ? `run this from a shell on the box: npx -y ${CONNECT_PACKAGE}@${version}`
93
+ : `run the ReefClaw connect installer from a shell on the box, pinned to the version the dashboard's update notice shows (${CONNECT_PACKAGE}@<version>)`;
94
+ }
95
+ /**
96
+ * Ask ReefClaw which connector release an update installs: `connectVersion` on
97
+ * the PUBLIC `/api/release` endpoint, baked by the webapp at build from the
98
+ * released installer (the same constants ride the authenticated config
99
+ * channel as `release.connectVersion`). No credential is needed or sent —
100
+ * release versions are public data, and an update must keep working on a box
101
+ * whose connection token is stale. Any failure, or anything that is not an
102
+ * exact version, refuses the update — this feature never falls back to an
103
+ * unpinned install.
66
104
  */
67
- export function buildUpdateCommandLine() {
68
- return `${CONNECTOR_UPDATE_COMMAND}; printf '\\n${DONE_SENTINEL}%s\\n' "$?"`;
105
+ export async function fetchPinnedConnectVersion(opts) {
106
+ const refuse = (why) => ({
107
+ ok: false,
108
+ outcome: {
109
+ ok: false,
110
+ status: 'blocked',
111
+ message: `Could not confirm the connector version to install (${why}), so the update was not started — ` +
112
+ `it only ever installs an exact, ReefClaw-confirmed release. Try again shortly, or ${manualUpdateHint()}.`,
113
+ },
114
+ });
115
+ // www matches every other webapp call the bridge makes (reefclaw.com
116
+ // 307-redirects to it).
117
+ const base = (opts.webappUrl ?? process.env.REEFCLAW_API_URL ?? 'https://www.reefclaw.com').replace(/\/$/, '');
118
+ try {
119
+ const doFetch = opts.fetchImpl ?? fetch;
120
+ const res = await doFetch(`${base}/api/release`, { signal: AbortSignal.timeout(15_000) });
121
+ if (!res.ok)
122
+ return refuse(`ReefClaw answered HTTP ${res.status}`);
123
+ const body = (await res.json());
124
+ const version = body?.connectVersion;
125
+ if (!isExactConnectVersion(version))
126
+ return refuse('ReefClaw did not report an exact release version');
127
+ return { ok: true, version };
128
+ }
129
+ catch (err) {
130
+ return refuse(err instanceof Error ? err.message : String(err));
131
+ }
69
132
  }
70
- /** Terminal grid we request. Wide enough that npm/npx output does not wrap into
133
+ /** Terminal grid we request. Wide enough that package-manager output does not wrap into
71
134
  * unreadable soup in the dashboard's output pane. */
72
135
  const COLS = 120;
73
136
  const ROWS = 40;
@@ -90,7 +153,7 @@ export function describeOpenFailure(err) {
90
153
  ok: false,
91
154
  status: 'blocked',
92
155
  message: 'This box has the OpenClaw terminal disabled, so ReefClaw cannot run the update for you. '
93
- + 'Update it from a shell on the box instead: npx -y @reefclaw/connect@latest',
156
+ + `Instead, ${manualUpdateHint()}.`,
94
157
  };
95
158
  }
96
159
  if (lower.includes('sandbox')) {
@@ -98,7 +161,7 @@ export function describeOpenFailure(err) {
98
161
  ok: false,
99
162
  status: 'blocked',
100
163
  message: 'This agent runs in a sandbox, and OpenClaw does not support terminals inside one yet. '
101
- + 'Update from a shell on the box instead: npx -y @reefclaw/connect@latest',
164
+ + `Instead, ${manualUpdateHint()}.`,
102
165
  };
103
166
  }
104
167
  // Scope refusal: terminal.* requires operator.admin on OpenClaw >= 2026.7
@@ -112,7 +175,7 @@ export function describeOpenFailure(err) {
112
175
  status: 'blocked',
113
176
  message: 'The gateway refused to open a terminal for the connector (it needs the operator.admin scope). '
114
177
  + 'One-click updates need a connector released 2026-09-14 or later — update once by pasting the manual '
115
- + 'command to your agent or from a shell: npx -y @reefclaw/connect@latest. After that, updates are one click.',
178
+ + `command to your agent, or ${manualUpdateHint()}. After that, updates are one click.`,
116
179
  };
117
180
  }
118
181
  return {
@@ -128,7 +191,7 @@ export function describeUpdateDisabled() {
128
191
  ok: false,
129
192
  status: 'blocked',
130
193
  message: 'One-click updates are switched off on this box (REEFCLAW_ALLOW_CONNECTOR_UPDATE=0). '
131
- + `Update from a shell on the box instead: ${CONNECTOR_UPDATE_COMMAND}`,
194
+ + `Instead, ${manualUpdateHint()}.`,
132
195
  };
133
196
  }
134
197
  /**
@@ -184,7 +247,9 @@ export function checkPositionGuard(opts) {
184
247
  * Open a PTY and write the update command to it. Returns as soon as the command
185
248
  * is running — the caller polls `readTerminalText` for output.
186
249
  */
187
- export async function startConnectorUpdate(rpc, opts) {
250
+ export async function startConnectorUpdate(rpc, opts,
251
+ /** Exact connector release to install — from fetchPinnedConnectVersion, nowhere else. */
252
+ version) {
188
253
  const blocked = checkPositionGuard(opts);
189
254
  if (blocked) {
190
255
  logger.info(TAG, `update refused: ${opts.openPositionCount} open position(s), no acknowledgement`);
@@ -214,7 +279,7 @@ export async function startConnectorUpdate(rpc, opts) {
214
279
  logger.info(TAG, `terminal opened (shell=${opened.shell} cwd=${opened.cwd} confined=${opened.confined})`);
215
280
  try {
216
281
  // `\r` submits the line — terminal.input is raw keystrokes, not a command API.
217
- await rpc('terminal.input', { sessionId, data: `${buildUpdateCommandLine()}\r` });
282
+ await rpc('terminal.input', { sessionId, data: `${buildUpdateCommandLine(version)}\r` });
218
283
  }
219
284
  catch (err) {
220
285
  const reason = err instanceof Error ? err.message : String(err);
@@ -263,7 +328,7 @@ export function describeMissingAdminScope(granted) {
263
328
  ok: false,
264
329
  status: 'blocked',
265
330
  message: `This gateway did not grant the connector the operator.admin scope it needs to open a terminal (granted: ${list}). `
266
- + 'One-click updates are unavailable on this box — update from a shell instead: npx -y @reefclaw/connect@latest',
331
+ + `One-click updates are unavailable on this box — ${manualUpdateHint()}.`,
267
332
  };
268
333
  }
269
334
  /** Connect a fresh admin-scoped client and wait for hello-ok. Resolves with the
@@ -261,10 +261,11 @@ export declare class GatewayProvider implements OpenClawProvider {
261
261
  * Operator-only. Update the ReefClaw connector on this box to the latest
262
262
  * published version.
263
263
  *
264
- * Runs `npx -y @reefclaw/connect@latest` over the gateway's PTY. There is no
265
- * command/version/args parameter and there never should be — the whole
266
- * security argument for this feature is that the string is a constant (see
267
- * providers/connector-update.ts).
264
+ * Runs the connect installer over the gateway's PTY, pinned to the exact
265
+ * connector release ReefClaw's public release endpoint reports. The
266
+ * RPC carries no command/version/args parameter and never should — the
267
+ * version is looked up server-side by this process, never taken from the
268
+ * caller (see providers/connector-update.ts).
268
269
  *
269
270
  * The installer restarts the gateway when it finishes, which kills both the
270
271
  * PTY and this process's own transport. That is the SUCCESS path: we report
@@ -300,18 +301,15 @@ export declare class GatewayProvider implements OpenClawProvider {
300
301
  private startToolRetry;
301
302
  private createPoller;
302
303
  private wireWsEvents;
303
- /** Whether we've already acted on a missing write scope this process. */
304
- private writeScopeRelaxationApplied;
305
- /** Least-privilege escalation, gated on evidence. Some OpenClaw builds strip
306
- * `operator.write` from a WS connection with no device identity; without it
307
- * the bridge cannot place or cancel orders. Rather than pre-emptively
308
- * relaxing every user's gateway auth at install time (what we did until
309
- * 2026-07-29), we read the scopes the gateway ACTUALLY granted and relax
310
- * only when it demonstrably withheld the one we need. On the supported
311
- * range the scope survives and nothing is written. */
312
- private deviceIdentityRelaxationApplied;
304
+ /** The gateway withheld `operator.write` from this connection (or rejected
305
+ * the handshake for missing device identity). The connector used to react
306
+ * by writing OpenClaw's legacy auth-relaxation flags itself (2026-07-29 →
307
+ * 2026-09-19). It no longer touches the gateway's auth settings at all: it
308
+ * reports the exact manual remedy once per process and leaves the decision
309
+ * to the operator. */
310
+ private writeScopeRemedyReported;
313
311
  /** Handshake rejected outright for missing device identity (see
314
- * isDeviceIdentityRejection). Same escalation as the withheld-write-scope
312
+ * isDeviceIdentityRejection). Same report as the withheld-write-scope
315
313
  * case, keyed on the rejection instead of on hello-ok scopes. */
316
314
  private onHandshakeRejectedForDeviceIdentity;
317
315
  private checkGrantedScopes;
@@ -7,7 +7,7 @@ import { homedir } from 'os';
7
7
  import { logger, formatError } from '../logger.js';
8
8
  import { isTradingMode } from '../types.js';
9
9
  import { deriveModelHealth } from '../model-health.js';
10
- import { handshakeLacksWriteScope, isDeviceIdentityRejection, relaxGatewayDeviceAuth } from '../config.js';
10
+ import { describeGatewayWriteScopeRemedy, handshakeLacksWriteScope, isDeviceIdentityRejection } from '../config.js';
11
11
  import { toIntelSymbol } from '@reefclaw/shared';
12
12
  import { GatewayHttpClient } from '../gateway/gateway-http-client.js';
13
13
  import { GatewayWsClient } from '../gateway/gateway-ws-client.js';
@@ -19,7 +19,7 @@ import { parseIdentityName } from '../utils/identity-name.js';
19
19
  import { assessDrawdownPlausibility, computeEquity as _computeEquity, computePositionNotional as _computePositionNotional, computeRiskMetrics as _computeRiskMetrics, DEFAULT_RISK_LIMITS, DRAWDOWN_ZONE_THRESHOLDS, TENANT_LIMIT_BOUNDS, boundedNum, validateDrawdownLadder, } from './risk-calculator.js';
20
20
  import { executeKill as _executeKill, executeFlatten as _executeFlatten, executePause as _executePause, executeResume as _executeResume, cancelPendingProposals, withProposalDetail, } from './emergency-commands.js';
21
21
  import { executeSetTradingMode, executeGetBracketConfig, executeSetBracketRequirement, executeSetExchangeCredentials, executeTestExchangeCredentials, executeClearExchangeCredentials, executeProvisionHlAgentWallet, executeHlAgentWalletStatus, executeSubmitHlAgentApproval, } from './onboarding-commands.js';
22
- import { startConnectorUpdate, runConnectorUpdate, openAdminGatewaySession, checkPositionGuard, describeUpdateDisabled, } from './connector-update.js';
22
+ import { startConnectorUpdate, runConnectorUpdate, fetchPinnedConnectVersion, openAdminGatewaySession, checkPositionGuard, describeUpdateDisabled, } from './connector-update.js';
23
23
  import { DEFAULT_AGENT_ID, isForeignAgentEvent, resolveAgentEventOwner } from '../gateway/agent-scope.js';
24
24
  const TAG = 'gateway';
25
25
  // ---- Day-start NAV persistence ----
@@ -758,10 +758,11 @@ export class GatewayProvider {
758
758
  * Operator-only. Update the ReefClaw connector on this box to the latest
759
759
  * published version.
760
760
  *
761
- * Runs `npx -y @reefclaw/connect@latest` over the gateway's PTY. There is no
762
- * command/version/args parameter and there never should be — the whole
763
- * security argument for this feature is that the string is a constant (see
764
- * providers/connector-update.ts).
761
+ * Runs the connect installer over the gateway's PTY, pinned to the exact
762
+ * connector release ReefClaw's public release endpoint reports. The
763
+ * RPC carries no command/version/args parameter and never should — the
764
+ * version is looked up server-side by this process, never taken from the
765
+ * caller (see providers/connector-update.ts).
765
766
  *
766
767
  * The installer restarts the gateway when it finishes, which kills both the
767
768
  * PTY and this process's own transport. That is the SUCCESS path: we report
@@ -792,6 +793,12 @@ export class GatewayProvider {
792
793
  const blocked = checkPositionGuard(guardArgs);
793
794
  if (blocked)
794
795
  return blocked;
796
+ // Which version? Only the one ReefClaw vouches for, fetched by THIS
797
+ // process from the public release endpoint — never `@latest`, never a
798
+ // caller-supplied string. No confirmed version ⇒ no update.
799
+ const pinned = await fetchPinnedConnectVersion({});
800
+ if (!pinned.ok)
801
+ return pinned.outcome;
795
802
  // terminal.* is operator.admin-only (OpenClaw method-scopes, since 2026.7).
796
803
  // The long-lived session runs on operator.read/write by design, so open a
797
804
  // SEPARATE short-lived admin session for this update. Reconnects are
@@ -808,7 +815,7 @@ export class GatewayProvider {
808
815
  if (!session.ok)
809
816
  return session.outcome;
810
817
  const rpc = (method, params) => admin.sendRpc(method, params);
811
- const started = await startConnectorUpdate(rpc, guardArgs);
818
+ const started = await startConnectorUpdate(rpc, guardArgs, pinned.version);
812
819
  if (started.status !== 'started' || !started.sessionId) {
813
820
  admin.destroy();
814
821
  return started;
@@ -1290,37 +1297,26 @@ export class GatewayProvider {
1290
1297
  });
1291
1298
  this.wsClient.on('agent', (payload) => this.onAgentEvent(payload));
1292
1299
  }
1293
- /** Whether we've already acted on a missing write scope this process. */
1294
- writeScopeRelaxationApplied = false;
1295
- /** Least-privilege escalation, gated on evidence. Some OpenClaw builds strip
1296
- * `operator.write` from a WS connection with no device identity; without it
1297
- * the bridge cannot place or cancel orders. Rather than pre-emptively
1298
- * relaxing every user's gateway auth at install time (what we did until
1299
- * 2026-07-29), we read the scopes the gateway ACTUALLY granted and relax
1300
- * only when it demonstrably withheld the one we need. On the supported
1301
- * range the scope survives and nothing is written. */
1302
- deviceIdentityRelaxationApplied = false;
1300
+ /** The gateway withheld `operator.write` from this connection (or rejected
1301
+ * the handshake for missing device identity). The connector used to react
1302
+ * by writing OpenClaw's legacy auth-relaxation flags itself (2026-07-29 →
1303
+ * 2026-09-19). It no longer touches the gateway's auth settings at all: it
1304
+ * reports the exact manual remedy once per process and leaves the decision
1305
+ * to the operator. */
1306
+ writeScopeRemedyReported = false;
1303
1307
  /** Handshake rejected outright for missing device identity (see
1304
- * isDeviceIdentityRejection). Same escalation as the withheld-write-scope
1308
+ * isDeviceIdentityRejection). Same report as the withheld-write-scope
1305
1309
  * case, keyed on the rejection instead of on hello-ok scopes. */
1306
1310
  onHandshakeRejectedForDeviceIdentity(reason) {
1307
- if (this.deviceIdentityRelaxationApplied)
1311
+ if (this.writeScopeRemedyReported)
1308
1312
  return;
1309
- this.deviceIdentityRelaxationApplied = true;
1313
+ this.writeScopeRemedyReported = true;
1310
1314
  const tried = this.wsClient?.getClientId() ?? 'unknown';
1311
1315
  logger.error(TAG, `Gateway REJECTED the connector handshake under every client identity (last: ${tried}): ${reason}. ` +
1312
- `OpenClaw >= 2026.9 admits only a local-backend client (gateway-client) or a device-paired one — ` +
1313
- `the retired gateway.controlUi relaxation no longer applies — and this gateway did neither. The ` +
1314
- `dashboard cannot reach this agent (no tools, no state, no updates) until the handshake completes.`);
1315
- // Last resort for OLDER builds only: on 2026.9+ the flags are retired and
1316
- // ignored (a config migration deletes them), so this is best-effort and
1317
- // says so.
1318
- const changed = relaxGatewayDeviceAuth(`the gateway rejected the connector handshake (${reason})`);
1319
- if (changed) {
1320
- logger.warn(TAG, 'Wrote the legacy gateway.controlUi relaxation flags in case this is an older OpenClaw build — ' +
1321
- 'RESTART the gateway to find out. On OpenClaw >= 2026.9 they are ignored: check the gateway ' +
1322
- 'auth config / device pairing instead.');
1323
- }
1316
+ `OpenClaw >= 2026.9 admits only a local-backend client (gateway-client) or a device-paired one, ` +
1317
+ `and this gateway did neither. The dashboard cannot reach this agent (no tools, no state, no ` +
1318
+ `updates) until the handshake completes. ` +
1319
+ describeGatewayWriteScopeRemedy(`the handshake was rejected: ${reason}`));
1324
1320
  this.agentMode = 'ERROR';
1325
1321
  this.emitAgentState();
1326
1322
  }
@@ -1328,21 +1324,11 @@ export class GatewayProvider {
1328
1324
  const scopes = helloOk.auth?.scopes;
1329
1325
  if (!handshakeLacksWriteScope(scopes))
1330
1326
  return;
1331
- if (this.writeScopeRelaxationApplied)
1327
+ if (this.writeScopeRemedyReported)
1332
1328
  return;
1333
- this.writeScopeRelaxationApplied = true;
1334
- logger.warn(TAG, `Gateway granted [${(scopes ?? []).join(', ')}] — operator.write is MISSING, ` +
1335
- `so order placement and cancellation would fail on this connection.`);
1336
- const changed = relaxGatewayDeviceAuth('the gateway completed a handshake without granting operator.write');
1337
- if (changed) {
1338
- logger.warn(TAG, 'Gateway config updated — RESTART the OpenClaw gateway to regain operator.write. ' +
1339
- 'Trading tools will keep failing until you do.');
1340
- }
1341
- else {
1342
- logger.error(TAG, 'operator.write is missing and the relaxation flags are ALREADY set — this is ' +
1343
- 'not the known device-identity case. Check gateway auth config; trading is ' +
1344
- 'blocked until the gateway grants operator.write.');
1345
- }
1329
+ this.writeScopeRemedyReported = true;
1330
+ logger.error(TAG, `Gateway granted [${(scopes ?? []).join(', ')}] — operator.write is MISSING. ` +
1331
+ describeGatewayWriteScopeRemedy('the handshake completed without operator.write'));
1346
1332
  }
1347
1333
  onWsConnected(helloOk) {
1348
1334
  if (!this.started)
@@ -233,7 +233,7 @@ export async function executeProvisionHlAgentWallet(ctx, args) {
233
233
  if (!tool || !ctx.http) {
234
234
  return {
235
235
  ok: false,
236
- message: 'hl_provision_agent_wallet tool not available on gateway — update the ReefClaw plugin (npx @reefclaw/connect@latest)',
236
+ message: 'hl_provision_agent_wallet tool not available on gateway — update the ReefClaw plugin (re-run the ReefClaw connect installer)',
237
237
  venue: 'hyperliquid',
238
238
  mode: 'PAPER',
239
239
  };
@@ -261,7 +261,7 @@ export async function executeSubmitHlAgentApproval(ctx, args) {
261
261
  if (!tool || !ctx.http) {
262
262
  return {
263
263
  ok: false,
264
- message: 'hl_submit_agent_approval tool not available on gateway — update the ReefClaw plugin (npx @reefclaw/connect@latest)',
264
+ message: 'hl_submit_agent_approval tool not available on gateway — update the ReefClaw plugin (re-run the ReefClaw connect installer)',
265
265
  };
266
266
  }
267
267
  try {
@@ -285,7 +285,7 @@ export async function executeHlAgentWalletStatus(ctx) {
285
285
  if (!tool || !ctx.http) {
286
286
  return {
287
287
  ok: false,
288
- message: 'hl_agent_wallet_status tool not available on gateway — update the ReefClaw plugin (npx @reefclaw/connect@latest)',
288
+ message: 'hl_agent_wallet_status tool not available on gateway — update the ReefClaw plugin (re-run the ReefClaw connect installer)',
289
289
  configured: false,
290
290
  };
291
291
  }
@@ -8,7 +8,7 @@
8
8
  // 3. Default: CONTEXT-AWARE since 2026-08-25 (E2E audit #3, the last
9
9
  // real-money item on the fresh-box list): a box whose persisted
10
10
  // tradingMode is MICRO_LIVE/LIVE on the BINANCE venue defaults to
11
- // 'enforce' — the historical 'off' default meant a fresh npx install
11
+ // 'enforce' — the historical 'off' default meant a fresh connect-installer install
12
12
  // flipped to live traded with NO exchange-side stops AND no mandatory-
13
13
  // stop pre-trade gate (the gate is wired behind bracketsEnabled), i.e.
14
14
  // genuinely naked, with no in-product way to notice. Everything else
@@ -18,7 +18,7 @@ export interface PluginConfigFile {
18
18
  connectionToken?: string;
19
19
  /** 'on' → the plugin spawns + restarts the relay connector as a child of
20
20
  * the gateway process (no systemd — OpenClaw is the process manager).
21
- * Written by the npx installer on fresh installs. MUST stay defaulted off:
21
+ * Written by the connect installer on fresh installs. MUST stay defaulted off:
22
22
  * prod runs the bridge under systemd and a supervisor there would
23
23
  * double-connect the relay room. Kill-switch: RC_CONNECTOR_SUPERVISOR=off. */
24
24
  connectorSupervisor?: 'on' | 'off';
@@ -141,7 +141,7 @@ export function resolveIngestToken(config) {
141
141
  const fromEnv = process.env.WEBAPP_INGEST_TOKEN ?? '';
142
142
  if (fromEnv.trim())
143
143
  return fromEnv.trim();
144
- // Chat/npx onboarding stores the token only where the AGENT saves it —
144
+ // Chat/connect-installer onboarding stores the token only where the AGENT saves it —
145
145
  // OpenClaw's own config. Without this fallback every fresh install has a
146
146
  // token-starved plugin (intel tools, ingest, config poller all dead).
147
147
  return readOpenClawConnection().token?.trim() ?? '';
@@ -5,13 +5,13 @@ import { spawn } from 'node:child_process';
5
5
  * bundled bridge is a sibling directory. */
6
6
  export declare function bundledBridgeDir(): string;
7
7
  /** Where the connector lives, in preference order: bundled-in-package first
8
- * (npm-channel install — self-contained), then the npx installer's
8
+ * (npm-channel install — self-contained), then the connect installer's
9
9
  * placement. Returns null when neither exists. */
10
10
  export declare function resolveBridgeDir(): string | null;
11
11
  /** True when the plugin should supervise the connector even WITHOUT an
12
12
  * explicit connectorSupervisor='on' in plugin-config: the connector is
13
13
  * bundled inside this plugin package, which only the npm-channel
14
- * distribution does. Prod's linked plugin dir and the npx installer's
14
+ * distribution does. Prod's linked plugin dir and the connect installer's
15
15
  * ~/.reefclaw/plugin have no bridge/ subdir, so they stay opt-in — prod
16
16
  * keeps running the bridge under systemd and must never double-connect. */
17
17
  export declare function hasBundledBridge(): boolean;
@@ -10,7 +10,7 @@
10
10
  //
11
11
  // SAFETY: default OFF. Prod runs the bridge as `reefclaw-skill.service`
12
12
  // (systemd) — a supervisor turned on there would double-connect the relay
13
- // room. Only the fresh-install path (the npx installer) writes
13
+ // room. Only the fresh-install path (the connect installer) writes
14
14
  // `connectorSupervisor: 'on'` into ~/.reefclaw/plugin-config.json.
15
15
  // Kill-switch: RC_CONNECTOR_SUPERVISOR=off beats config.
16
16
  import { spawn } from 'node:child_process';
@@ -28,7 +28,7 @@ export function bundledBridgeDir() {
28
28
  return join(dirname(fileURLToPath(import.meta.url)), 'bridge');
29
29
  }
30
30
  /** Where the connector lives, in preference order: bundled-in-package first
31
- * (npm-channel install — self-contained), then the npx installer's
31
+ * (npm-channel install — self-contained), then the connect installer's
32
32
  * placement. Returns null when neither exists. */
33
33
  export function resolveBridgeDir() {
34
34
  for (const dir of [bundledBridgeDir(), join(homedir(), '.reefclaw', 'bridge')]) {
@@ -40,7 +40,7 @@ export function resolveBridgeDir() {
40
40
  /** True when the plugin should supervise the connector even WITHOUT an
41
41
  * explicit connectorSupervisor='on' in plugin-config: the connector is
42
42
  * bundled inside this plugin package, which only the npm-channel
43
- * distribution does. Prod's linked plugin dir and the npx installer's
43
+ * distribution does. Prod's linked plugin dir and the connect installer's
44
44
  * ~/.reefclaw/plugin have no bridge/ subdir, so they stay opt-in — prod
45
45
  * keeps running the bridge under systemd and must never double-connect. */
46
46
  export function hasBundledBridge() {
package/index.js CHANGED
@@ -1082,7 +1082,7 @@ const paperTradingPlugin = {
1082
1082
  logger.warn(TAG, `Could not read ReefClaw config: ${formatError(err)}`);
1083
1083
  }
1084
1084
  if (!connectionToken) {
1085
- // Chat/npx onboarding saves the connection ONLY in OpenClaw's config
1085
+ // Chat/connect-installer onboarding saves the connection ONLY in OpenClaw's config
1086
1086
  // (skills.entries.reefclaw.config) — the agent writes it there and the
1087
1087
  // connector reads it there. Fall back so a fresh install's intel tools,
1088
1088
  // ingest, and config poller aren't token-starved (first-user bug).
@@ -1261,7 +1261,7 @@ const paperTradingPlugin = {
1261
1261
  // Built whenever credentials allow — NOT only on live boots. Every real
1262
1262
  // trader onboards in PAPER and goes live later from the dashboard; wiring
1263
1263
  // that only a live BOOT could construct silently never existed on their
1264
- // box (no audit-trail ingest, no approval listener), and "restart the
1264
+ // box (audit-trail ingest and the approval listener absent), and "restart the
1265
1265
  // container" is not an instruction we can hand a trader. These clients
1266
1266
  // are passive until a live adapter carries them — F9's runtime wiring
1267
1267
  // threads them into every adapter build, boot and reconnect alike.
@@ -1395,7 +1395,7 @@ const paperTradingPlugin = {
1395
1395
  const microLiveConfig = loadMicroLiveConfig();
1396
1396
  // Bracket-orders feature flag read from plugin-config at construction
1397
1397
  // time. Since 2026-08-25 (E2E audit #3) the default on a live-Binance
1398
- // box is 'enforce' — the old 'off' default meant a fresh npx install
1398
+ // box is 'enforce' — the old 'off' default meant a fresh connect-installer install
1399
1399
  // flipped to live traded genuinely naked (no exchange stops AND the
1400
1400
  // mandatory-stop gate skipped, since it is wired behind
1401
1401
  // bracketsEnabled). An 'off' here can only be an explicit override.
@@ -2971,7 +2971,7 @@ const paperTradingPlugin = {
2971
2971
  },
2972
2972
  };
2973
2973
  /** Plugin-supervised connector (frictionless onboarding): when plugin-config
2974
- * says connectorSupervisor='on' (written by the npx installer on fresh
2974
+ * says connectorSupervisor='on' (written by the connect installer on fresh
2975
2975
  * installs — NEVER defaulted on, prod runs the bridge under systemd and
2976
2976
  * would double-connect the relay room), the plugin spawns + restarts the
2977
2977
  * relay connector as a child of the gateway process. OpenClaw is the process
@@ -2989,7 +2989,7 @@ function maybeStartConnectorSupervisor() {
2989
2989
  }
2990
2990
  if (supervisorMode === 'off')
2991
2991
  return;
2992
- // 'on' → explicit opt-in (the npx installer writes this).
2992
+ // 'on' → explicit opt-in (the connect installer writes this).
2993
2993
  // undefined → auto-start ONLY when the connector is bundled inside this
2994
2994
  // plugin package (the npm-channel @reefclaw/openclaw-plugin distribution
2995
2995
  // is self-contained by design). Prod's linked plugin dir has no bundled
@@ -20,7 +20,7 @@ export interface ProposalDecisionListenerOptions {
20
20
  pollIntervalMs?: number;
21
21
  /** Idle poll interval — used after a tick returns zero pending proposals.
22
22
  * Default 15 s. Cuts the constant-warm pressure on the webapp DB by ~5x
23
- * during idle stretches (no approvals queued). Reset to active on the
23
+ * during idle stretches (an empty approval queue). Reset to active on the
24
24
  * next non-empty tick. 15 s is well within the shortest hard-expiry
25
25
  * bucket (90 s momentum) even allowing for operator decision time. */
26
26
  pollIntervalIdleMs?: number;
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "id": "reefclaw-paper-trading",
3
3
  "name": "ReefClaw Trading",
4
- "version": "0.1.34",
5
- "description": "Supervised trading plugin for the ReefClaw dashboard. It runs on YOUR machine and starts in PAPER mode with no API keys. It cannot trade real funds until you supply exchange credentials and step PAPER→MICRO_LIVE→LIVE yourself from the dashboard — the agent cannot make that change (the tool is refused without operator provenance). Exchange keys stay local, are used only to sign requests to the exchange, and are never transmitted to ReefClaw (asserted by a test in this package). Trading telemetry — positions, fills, decision journal — is sent to ReefClaw to render the dashboard. Every live position carries exchange-native protective stops. Remote updates to the agent's trading instructions are applied only after an Ed25519 signature is verified against a public key pinned in this build.",
4
+ "version": "0.1.35",
5
+ "description": "Supervised trading plugin for the ReefClaw dashboard. It runs on YOUR machine and starts in PAPER mode with no API keys. It cannot trade real funds until you supply exchange credentials and step PAPER→MICRO_LIVE→LIVE yourself from the dashboard — the agent cannot make that change (the tool is refused without operator provenance). Exchange keys stay local, are used only to sign requests to the exchange, and are never transmitted to ReefClaw (asserted by a test in this package). Trading telemetry — positions, fills, decision journal — is sent to ReefClaw to render the dashboard. Every live position carries exchange-native protective stops. Remote updates to the agent's trading instructions are applied only after an Ed25519 signature is verified against a public key pinned in this build. It runs on gateway startup and supervises a local connector process; the package README lists every path it writes and everything it sends. It never changes the gateway's auth settings.",
6
6
  "author": "ReefClaw",
7
7
  "activation": {
8
8
  "onStartup": true
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@reefclaw/openclaw-plugin",
3
- "version": "0.1.34",
4
- "description": "ReefClaw supervised trading plugin for OpenClaw. Runs entirely on YOUR machine and starts in PAPER mode — it cannot trade real funds until you supply exchange credentials and walk the PAPER→MICRO_LIVE→LIVE ladder yourself from the ReefClaw dashboard (the agent cannot make that change; it is refused without operator provenance). Your exchange API keys stay on your machine to sign requests to the exchange and are NEVER sent to ReefClaw — a test in the package asserts this. What does reach ReefClaw is trading telemetry for the dashboard (positions, fills, decision journal). Live trading always carries exchange-native protective stops. Trading instructions can be updated remotely, and every update must carry a valid Ed25519 signature verified against a key pinned in this build before it is applied. Install: npx --yes @reefclaw/connect, or from ClawHub on OpenClaw 2026.8.1+ (Control UI Plugins > Discover, or /plugins install clawhub:@reefclaw/openclaw-plugin then the same with --accept-capabilities after reviewing the listed capabilities)",
3
+ "version": "0.1.35",
4
+ "description": "ReefClaw supervised trading plugin for OpenClaw. Runs entirely on YOUR machine and starts in PAPER mode — it cannot trade real funds until you supply exchange credentials and walk the PAPER→MICRO_LIVE→LIVE ladder yourself from the ReefClaw dashboard (the agent cannot make that change; it is refused without operator provenance). Your exchange API keys stay on your machine to sign requests to the exchange and are NEVER sent to ReefClaw — a test in the package asserts this. What does reach ReefClaw is trading telemetry for the dashboard (positions, fills, decision journal). Live trading always carries exchange-native protective stops. Trading instructions can be updated remotely, and every update must carry a valid Ed25519 signature verified against a key pinned in this build before it is applied. Install from ClawHub on OpenClaw 2026.8.1+ (Control UI Plugins > Discover, or /plugins install clawhub:@reefclaw/openclaw-plugin then the same with --accept-capabilities after reviewing the listed capabilities), or with the ReefClaw connect installer (@reefclaw/connect on npm, pinned to the exact release named in the bundled skill). It runs on gateway startup, supervises a local connector process, and writes only under ~/.reefclaw and OpenClaw's own skill, config and cron locations; the README lists every path it writes and everything it sends. It never changes the gateway's auth settings.",
5
5
  "type": "module",
6
6
  "main": "index.js",
7
7
  "openclaw": {
@@ -12,7 +12,7 @@ export declare const UNSTAMPED_VERSION = "0.1.0";
12
12
  export interface ResolveInstallFactsInput {
13
13
  /** Directory holding the plugin's index.js (+ openclaw.plugin.json). */
14
14
  pluginRoot: string;
15
- /** plugin-config.json `connectorSupervisor` — the npx installer writes 'on'
15
+ /** plugin-config.json `connectorSupervisor` — the connect installer writes 'on'
16
16
  * on every install; nothing else does. */
17
17
  connectorSupervisor?: 'on' | 'off';
18
18
  /** ~/.reefclaw (injectable for tests). */
package/plugin-version.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // Which ReefClaw plugin RELEASE is running, and how it was installed — the two
2
2
  // facts the dashboard needs to (a) tell the trader an update exists and (b)
3
- // offer the right update path (one click for npx installs, ClawHub steps for
3
+ // offer the right update path (one click for connect-installer installs, ClawHub steps for
4
4
  // ClawHub installs, silence for the operator's own source/dist deploys).
5
5
  //
6
6
  // Version source: the `openclaw.plugin.json` that ships NEXT TO index.js in
@@ -43,8 +43,8 @@ function detectChannel(input, version) {
43
43
  if (version === undefined || version === UNSTAMPED_VERSION)
44
44
  return 'source';
45
45
  // ClawHub packages carry the bootstrap skill at the package root
46
- // (plugin-package/scripts/assemble.mjs); the npx layout deliberately does
47
- // not. Checked FIRST: a box that once ran the npx installer and later
46
+ // (plugin-package/scripts/assemble.mjs); the connect-installer layout deliberately does
47
+ // not. Checked FIRST: a box that once ran the connect installer and later
48
48
  // installed from ClawHub loads the ClawHub copy.
49
49
  if (existsSync(join(input.pluginRoot, 'skills')))
50
50
  return 'clawhub';
@@ -4,6 +4,7 @@
4
4
  "0.1.28": "Fixes the connector's gateway handshake on OpenClaw 2026.9+ (it now connects as OpenClaw's local-backend client) and adds in-app update notices with one-click updates.",
5
5
  "0.1.29": "Paper stop and target fills now use the price the decision was made on when the cached order book is stale (paper P&L gets more honest); on a gateway with several agents the connector shows only its own agent's runs; one-click updates can be switched off per box.",
6
6
  "0.1.30": "Restores the connector's version reporting, so the dashboard's update notice works again for boxes that already updated (0.1.28 and 0.1.29 reported no version and could not be nudged).",
7
- "0.1.33": "Adds npx @reefclaw/connect --agent <id> for gateways that host several agents: the trading skill, heartbeat and dashboard attach to that agent and the trading tools are denied to the others.",
8
- "0.1.34": "The heartbeat flight recorder now reads OpenClaw 2026.9's SQLite transcript store (it recorded nothing on those gateways) and warns when it cannot see beats; a RED-zone drawdown is re-checked on a fresh position snapshot before it is judged, and a loss larger than the open book plus today's realized losses is refused as a calculation error instead of trusting a -50% constant; RC_SHOCK_WAKE=off switches shock wakes off per box; the README lists what the connector sends and how to read the risk log."
7
+ "0.1.33": "Adds the connect installer's --agent <id> option for gateways that host several agents: the trading skill, heartbeat and dashboard attach to that agent and the trading tools are denied to the others.",
8
+ "0.1.34": "The heartbeat flight recorder now reads OpenClaw 2026.9's SQLite transcript store (it recorded nothing on those gateways) and warns when it cannot see beats; a RED-zone drawdown is re-checked on a fresh position snapshot before it is judged, and a loss larger than the open book plus today's realized losses is refused as a calculation error instead of trusting a -50% constant; RC_SHOCK_WAKE=off switches shock wakes off per box; the README lists what the connector sends and how to read the risk log.",
9
+ "0.1.35": "The connector never changes your gateway's auth settings any more (it reports the manual remedy instead); the install line in the bundled skill and the one-click update are pinned to an exact connector release instead of 'latest'; the bundled skill spells out what the remotely delivered trading instructions can and cannot do; the package README lists every file the plugin writes and everything it sends."
9
10
  }
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: reefclaw
3
- version: 0.0.10
3
+ version: 0.0.11
4
4
  description: ReefClaw trading control room — bootstrap (connects your agent; the full trading instructions arrive after first connect as a signed, signature-verified update)
5
5
  author: ReefClaw
6
6
  homepage: https://reefclaw.com
@@ -93,7 +93,7 @@ When a user gives you this message (or just a bare `Here's my ReefClaw token: rc
93
93
  **Do NOT put the fields directly on the `reefclaw` entry** — OpenClaw's config schema only allows `{enabled, apiKey, env, config}` there; a flat entry fails config validation and **prevents the whole gateway from starting**.
94
94
  - **`userId` is mandatory to connect** — the relay room URL is keyed by it. A token-only config **cannot reach the relay** and the connector will exit with "No user ID found". If the user pasted only a token, ask them for the full connect message from [reefclaw.com/onboarding](https://reefclaw.com/onboarding) (it includes the userId).
95
95
  - `userId` is a UUID and is **not** a secret; `relayUrl` is optional (defaults to the production relay). Only `token` is secret.
96
- - After saving, the connector picks the config up within seconds (it restarts until a token appears). The user does not need to run any command.
96
+ - After saving, the connector picks the config up within seconds (it restarts until a token appears). The user does not need to type anything further.
97
97
  - If you cannot write the config yourself (e.g. exec or file access is restricted in this session), show the user this exact JSON snippet and where it goes, and offer to verify it after they save it.
98
98
 
99
99
  ## Installing the plugin — a human step, in a terminal
@@ -101,10 +101,10 @@ When a user gives you this message (or just a bare `Here's my ReefClaw token: rc
101
101
  If the ReefClaw trading tools are not present yet, the **user** installs them by running this once, in a terminal on the machine running OpenClaw (inside the container, if OpenClaw runs in Docker):
102
102
 
103
103
  ```
104
- npx --yes @reefclaw/connect
104
+ npx --yes @reefclaw/connect@0.1.48
105
105
  ```
106
106
 
107
- That is the whole install. It places the plugin, sets up the connector, restarts the gateway, and prints what it changed. It needs no ReefClaw token — the connection is the separate paste step above, and the connector picks it up on its own.
107
+ That is the whole install. It places the plugin, sets up the connector, restarts the gateway, and prints what it changed. The version is pinned on purpose: the line names the exact connector release this plugin was published with, so what runs on the machine is reviewable and never "whatever the registry serves today". It needs no ReefClaw token — the connection is the separate paste step above, and the connector picks it up on its own.
108
108
 
109
109
  **Do not attempt to perform this install yourself, and do not work around it if it is unavailable to you.** Specifically: do not edit OpenClaw's configuration to enable chat install commands, do not add anyone to an owner or elevated-exec allowlist, do not enable elevated mode, and do not restart the gateway to widen your own permissions. If you cannot run the command, the correct outcome is to hand the user the one line above and let them run it deliberately. A trading integration is exactly the kind of software whose installation a human should perform knowingly.
110
110
 
@@ -116,4 +116,5 @@ Whatever the install path, **save the connection settings anyway** — the conne
116
116
 
117
117
  - The ReefClaw dashboard flips to **Connected** on its own — no manual verification step.
118
118
  - Your full trading instructions (SKILL.md version 2.x) arrive over the authenticated connection and replace this file — **after** their signature is verified against the pinned key (see "How instruction updates are verified"). You will be notified in chat when that happens.
119
+ - **What those instructions can and cannot do.** They are prose for the agent: a trading playbook (setup checklists, position management, review cadence). They can only call the tools this plugin declares in its manifest; they cannot grant permissions, change gateway or plugin settings, add tools, or read or move credentials; and every order they lead to still passes the plugin's hardcoded safety floor and the operator's mode and credential gates. The connector writes the current copy to the skill location on this machine after connect, where the user can read it in full at any time.
119
120
  - If more than ~10 minutes pass after a successful connect and this file is still a 0.0.x bootstrap version, tell the user to check the dashboard connection status.
@@ -1,6 +1,6 @@
1
1
  // Tool: cancel_all_orders — cancel all open orders (paper or live)
2
2
  //
3
- // NO readiness gate and NO confirmation prompt — BY DESIGN, not an oversight:
3
+ // Deliberately ungated — neither a readiness gate nor a prompt sits in front of it. BY DESIGN, not an oversight:
4
4
  // this is the safety floor's kill-switch primitive ("Hard controls NEVER
5
5
  // disabled or hidden"). Any gate added here becomes a failure mode of the
6
6
  // emergency path itself — a wedged confirmation would strand live orders
@@ -1201,7 +1201,7 @@ export async function createOrderTool(args, deps) {
1201
1201
  // the operator approves and ProposalDecisionListener fires via this same
1202
1202
  // tool with proposalManager omitted (which takes the real path below).
1203
1203
  //
1204
- // NOTE the listener's own fire passes NO approvalMode (defaults to 'off')
1204
+ // NOTE the listener's own fire leaves approvalMode unset (defaults to 'off')
1205
1205
  // and no proposalManager, so it never re-enters this branch.
1206
1206
  if (approvalMode === 'per_trade' && proposalPathWired) {
1207
1207
  if (!argsMetadataComplete) {