@reefclaw/openclaw-plugin 0.1.47 → 0.1.48

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.
@@ -11,6 +11,7 @@
11
11
  import { makeReadinessCheck, deriveOverallReadiness, GEO_BLOCK_FIX_HINT, HOST_STALL_FIX_HINT, } from '@reefclaw/shared';
12
12
  import { logger, formatError } from '../logger.js';
13
13
  import { startEventLoopMonitor, sampleEventLoopDelayMs, sampleRunqueueWaitMs, } from './event-loop-monitor.js';
14
+ import { noteWebappResponse, webappEdgeGate, webappHeaders, } from '../http/webapp-edge.js';
14
15
  const TAG = 'readiness';
15
16
  const DEFAULT_INTERVAL_MS = 300_000; // 5 min — geo/clock state changes rarely.
16
17
  const MIN_INTERVAL_MS = 60_000;
@@ -85,6 +86,36 @@ export function stopProtectionCheck(snap, checkedAt) {
85
86
  checkedAt,
86
87
  });
87
88
  }
89
+ /** Fix hint for the `reefclaw_api_reachable` row. Assertive on purpose: the
90
+ * edge answered with its own header, so — like a 451 from Binance — this is
91
+ * reporting what the server said, not an inference. */
92
+ export const WEBAPP_EDGE_FIX_HINT = "ReefClaw's edge protection is denying this host's IP (an automatic Vercel DDoS mitigation — not your account, token or anything on this machine). " +
93
+ 'The agent keeps trading with its safety floor intact, but the position journal, central config and instruction updates pause until it lifts. ' +
94
+ 'It usually clears within 30 minutes on its own; if it keeps coming back, email support@reefclaw.com with the time and your hosting provider so ReefClaw can add an allow rule.';
95
+ /** Map the shared edge-gate snapshot to a readiness row. Pure. Blocked → fail;
96
+ * anything else → null (absent evidence stays absent — the row is omitted,
97
+ * never fabricated as a pass, and never a stale "warn" riding a POST that
98
+ * just succeeded). Built by hand rather than makeReadinessCheck because the
99
+ * id is newer than the shared copy map vendored on older boxes. */
100
+ export function webappApiCheck(snap, checkedAt) {
101
+ if (!snap.blocked)
102
+ return null;
103
+ const since = snap.firstDeniedAt ? new Date(snap.firstDeniedAt).toISOString().slice(11, 16) + ' UTC' : '?';
104
+ const rid = snap.lastRequestId ? `, request ${snap.lastRequestId}` : '';
105
+ const base = {
106
+ id: 'reefclaw_api_reachable',
107
+ label: 'ReefClaw API reachable',
108
+ phase: 'connect',
109
+ checkedAt,
110
+ };
111
+ const left = snap.blockedUntil ? Math.max(1, Math.ceil((snap.blockedUntil - checkedAt) / 60_000)) : null;
112
+ return {
113
+ ...base,
114
+ status: 'fail',
115
+ detail: `edge firewall 403 (${snap.lastAction ?? 'deny'}) since ${since}, ${snap.deniedCount} denied${rid}${left ? `; retrying in ${left} min` : ''}`,
116
+ fixHint: WEBAPP_EDGE_FIX_HINT,
117
+ };
118
+ }
88
119
  export function createReadinessCycleState() {
89
120
  return { consecutiveReachFailures: 0 };
90
121
  }
@@ -126,6 +157,19 @@ export async function collectReadiness(opts, bootWarmup = false, deps = {}) {
126
157
  detail: `${opts.toolCount} tools`,
127
158
  checkedAt: now,
128
159
  }));
160
+ // reefclaw_api_reachable — the shared edge gate's verdict on the webapp
161
+ // itself. Omitted while nothing has ever been denied. NOTE: when this row
162
+ // is 'fail' the report usually cannot be POSTed (the POST is what is being
163
+ // denied) — the connector carries the same episode over the relay
164
+ // (agent_state health.webappApi), which is how the dashboard learns of it.
165
+ try {
166
+ const edgeRow = webappApiCheck((deps.webappEdgeSnapshot ?? (() => webappEdgeGate().snapshot()))(), now);
167
+ if (edgeRow)
168
+ checks.push(edgeRow);
169
+ }
170
+ catch (err) {
171
+ logger.warn(TAG, `edge-gate snapshot failed (row omitted): ${formatError(err)}`);
172
+ }
129
173
  // live_stop_protection — a local config/adapter read, no network. Resolved
130
174
  // per cycle so a paper→live flip surfaces on the next report without a
131
175
  // restart. Resolver failure → omit the row (absent evidence stays absent).
@@ -306,17 +350,30 @@ async function postReadiness(apiBaseUrl, token, report, fetchImpl, timeoutMs) {
306
350
  const ac = new AbortController();
307
351
  const tid = setTimeout(() => ac.abort(), timeoutMs);
308
352
  try {
353
+ const startedAt = Date.now();
309
354
  const res = await fetchImpl(url, {
310
355
  method: 'POST',
311
- headers: {
312
- 'content-type': 'application/json',
313
- authorization: `Bearer ${token}`,
314
- },
356
+ headers: webappHeaders(token, { 'content-type': 'application/json' }),
315
357
  body: JSON.stringify(report),
316
358
  signal: ac.signal,
317
359
  });
318
360
  if (res.status < 200 || res.status >= 300) {
319
- logger.warn(TAG, `POST ${url} → ${res.status}`);
361
+ let bodyText = null;
362
+ if (res.status === 403) {
363
+ try {
364
+ bodyText = (await res.text()).slice(0, 200);
365
+ }
366
+ catch {
367
+ /* classify on headers alone */
368
+ }
369
+ }
370
+ const edge = noteWebappResponse(res, '/api/internal/agent-readiness', bodyText);
371
+ // The gate logs the episode once at warn; repeats stay at debug.
372
+ const level = edge && webappEdgeGate().snapshot().deniedCount > 1 ? 'debug' : 'warn';
373
+ logger[level](TAG, `POST ${url} → ${res.status}${edge ? ` (edge firewall ${edge.action ?? 'deny'}${edge.requestId ? `, request ${edge.requestId}` : ''} — not an account problem)` : ''}`);
374
+ }
375
+ else {
376
+ noteWebappResponse(res, '/api/internal/agent-readiness', undefined, startedAt);
320
377
  }
321
378
  }
322
379
  catch (err) {
@@ -364,10 +421,23 @@ export function startReadinessReporter(opts) {
364
421
  installChannel: opts.installChannel,
365
422
  runtime: opts.runtime,
366
423
  }, bootWarmup, { state });
367
- await postReadiness(opts.apiBaseUrl, opts.token, report, fetchImpl, timeoutMs);
424
+ if (webappEdgeGate().isBlocked()) {
425
+ // Every POST during the block is another denied request feeding it.
426
+ // The gate reopens on its own (≤30 min); the next cycle re-probes.
427
+ logger.debug(TAG, `readiness POST skipped — webapp edge-denied (${Math.ceil(webappEdgeGate().msUntilOpen() / 60_000)} min left)`);
428
+ }
429
+ else {
430
+ await postReadiness(opts.apiBaseUrl, opts.token, report, fetchImpl, timeoutMs);
431
+ }
368
432
  if (report.overall === 'fail') {
369
- const failing = report.checks.filter((c) => c.status === 'fail').map((c) => c.id).join(', ');
370
- logger.warn(TAG, `readiness FAIL: ${failing}`);
433
+ // The edge row is already logged (once) by the gate — repeating it
434
+ // every 5 min as "readiness FAIL" would alarm a customer for nothing.
435
+ const failing = report.checks
436
+ .filter((c) => c.status === 'fail' && c.id !== 'reefclaw_api_reachable')
437
+ .map((c) => c.id)
438
+ .join(', ');
439
+ if (failing)
440
+ logger.warn(TAG, `readiness FAIL: ${failing}`);
371
441
  }
372
442
  }
373
443
  catch (err) {
@@ -25,6 +25,7 @@
25
25
  // background. In-flight requests are tracked so `drain()` can be awaited at
26
26
  // shutdown to avoid losing the last fills before stop.
27
27
  import { logger, formatError } from '../logger.js';
28
+ import { noteWebappResponse, webappEdgeGate, webappHeaders } from '../http/webapp-edge.js';
28
29
  import { retryAfterMs, sleepMs } from './retry-after.js';
29
30
  const TAG = 'trade-store-client';
30
31
  export class TradeStoreClient {
@@ -75,19 +76,23 @@ export class TradeStoreClient {
75
76
  async run(userId, fill) {
76
77
  const url = `${this.opts.baseUrl}/api/internal/trades`;
77
78
  const body = JSON.stringify(fill);
79
+ // Fill WRITES are never gated: the trades ledger has no other ingress
80
+ // (the gap filler only runs on a WS resync), a fill is a rare one-off
81
+ // call, and the ban may have lifted since the gate closed. If the edge
82
+ // still denies us, the 403 below drops the row exactly as before.
78
83
  for (let attempt = 1; attempt <= this.opts.maxAttempts; attempt++) {
79
84
  try {
80
85
  const ac = new AbortController();
81
86
  const tid = setTimeout(() => ac.abort(), this.opts.requestTimeoutMs);
82
87
  let res;
88
+ const startedAt = Date.now();
83
89
  try {
84
90
  res = await this.opts.fetchImpl(url, {
85
91
  method: 'POST',
86
- headers: {
92
+ headers: webappHeaders(this.opts.ingestToken, {
87
93
  'content-type': 'application/json',
88
- authorization: `Bearer ${this.opts.ingestToken}`,
89
94
  'x-user-id': userId,
90
- },
95
+ }),
91
96
  body,
92
97
  signal: ac.signal,
93
98
  });
@@ -97,6 +102,7 @@ export class TradeStoreClient {
97
102
  }
98
103
  if (res.status >= 200 && res.status < 300) {
99
104
  this.totalSucceeded++;
105
+ noteWebappResponse(res, '/api/internal/trades', undefined, startedAt);
100
106
  return;
101
107
  }
102
108
  if (res.status === 429) {
@@ -110,8 +116,23 @@ export class TradeStoreClient {
110
116
  else if (res.status >= 400 && res.status < 500) {
111
117
  // Terminal — re-tries won't change the outcome. 409 is a duplicate
112
118
  // (idempotency win); 400/401/404 are bugs we want logged loudly.
119
+ // A 403 from the EDGE (not the app) is named as such: it is the
120
+ // host being blocked, not a caller bug.
113
121
  this.totalDroppedTerminal++;
114
- logger.warn(TAG, `POST ${url} → ${res.status} (terminal, dropped). userId=${userId} tradeId=${fill.exchangeTradeId}`);
122
+ let errBody = '';
123
+ if (res.status === 403) {
124
+ try {
125
+ errBody = (await res.text()).slice(0, 200);
126
+ }
127
+ catch {
128
+ // ignore
129
+ }
130
+ }
131
+ const edge = noteWebappResponse(res, '/api/internal/trades', errBody);
132
+ // The gate logs the episode once at warn; repeats stay at debug.
133
+ logger[edge && webappEdgeGate().snapshot().deniedCount > 1 ? 'debug' : 'warn'](TAG, edge
134
+ ? `POST ${url} → 403 from the edge firewall (${edge.action ?? 'deny'}${edge.requestId ? `, request ${edge.requestId}` : ''}) — dropped; not an account/token problem. userId=${userId} tradeId=${fill.exchangeTradeId}`
135
+ : `POST ${url} → ${res.status} (terminal, dropped). userId=${userId} tradeId=${fill.exchangeTradeId}`);
115
136
  return;
116
137
  }
117
138
  else {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "id": "reefclaw-paper-trading",
3
3
  "name": "ReefClaw Trading",
4
- "version": "0.1.47",
4
+ "version": "0.1.48",
5
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": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reefclaw/openclaw-plugin",
3
- "version": "0.1.47",
3
+ "version": "0.1.48",
4
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",
@@ -33,5 +33,10 @@
33
33
  "index.js": "833343d35aeecb17f77ebb23ab816abae8df9c0d1d2dbf6c0f0622e96d7cd5a1",
34
34
  "tools/create-order.js": "b0244ff69cb5b4a44e18c7ceaf91669ee19649d0e6b18bb857aa47ca80f63b2a",
35
35
  "risk/pre-trade-check.js": "15ba2c91e7a1f5ea03a2452eda40d489eda406a434e3bc3e9b7e024190f6a22f"
36
+ },
37
+ "0.1.47": {
38
+ "index.js": "47477ea63083abeb07c3088481acd723c0366a9170f6069a67a055362f61a878",
39
+ "tools/create-order.js": "3bf10b657b97fb67fa6a893822929d61ee164d169f6bedf5ec978263b3fb6847",
40
+ "risk/pre-trade-check.js": "5074ac12687d554f9c0a0aee611202aba9ecb4536e4632f8a5c76a5614ae0aad"
36
41
  }
37
42
  }
@@ -17,5 +17,6 @@
17
17
  "0.1.43": "Connector fixes. The ReefClaw heartbeat is now created even when your OpenClaw already has its own job named like a heartbeat (before, the connector could mistake that job for ours, so the agent's trading heartbeat never ran); a box affected by this repairs itself after updating. The trading instructions (SKILL.md) are re-applied correctly when an older copy is found, instead of failing on every reconnect.",
18
18
  "0.1.44": "Heartbeats on a box without a chat channel (no Telegram etc.) are no longer recorded as errors: the heartbeat job is created without a chat delivery, existing jobs are repaired automatically, and a failed announcement no longer counts as a failed heartbeat. get_regime, get_crypto_metrics and get_market_intel now work when called without arguments (they default to your trading symbol / the overview category), which removes the rejected calls seen on OpenClaw 2026.9.",
19
19
  "0.1.45": "Every market-data and analysis tool now works when called without a symbol (it uses your configured trading symbol), so agents on OpenClaw 2026.9 no longer waste calls on rejected arguments. Trading actions still require an explicit symbol. The heartbeat prompt no longer sends the agent looking for a checklist file that is not installed.",
20
- "0.1.47": "Security release (independent audit, 2026-09-27). The heartbeat recorder no longer uploads the output of file and shell tools and scrubs anything key-shaped from what it does record. Dashboard-only settings (trading mode, exchange credentials, the stop requirement) now require a secret the plugin hands to its own connector at start - nothing the agent can read or repeat; plugin and connector must be updated together, which this update does. While trading is live a new entry without a protective stop is refused whatever the settings say, and a stop can no longer be moved wider on a losing position. Risk limits fetched from the server are clamped to hardcoded bounds. The installer pins its runtime dependencies to exact, integrity-checked versions and no longer widens the OpenClaw sandbox allow-list. Market-intel text is fenced against prompt injection in more places, the connector refuses relay hosts outside ReefClaw's, and uploads that hit a rate limit are retried instead of dropped."
20
+ "0.1.47": "Security release (independent audit, 2026-09-27). The heartbeat recorder no longer uploads the output of file and shell tools and scrubs anything key-shaped from what it does record. Dashboard-only settings (trading mode, exchange credentials, the stop requirement) now require a secret the plugin hands to its own connector at start - nothing the agent can read or repeat; plugin and connector must be updated together, which this update does. While trading is live a new entry without a protective stop is refused whatever the settings say, and a stop can no longer be moved wider on a losing position. Risk limits fetched from the server are clamped to hardcoded bounds. The installer pins its runtime dependencies to exact, integrity-checked versions and no longer widens the OpenClaw sandbox allow-list. Market-intel text is fenced against prompt injection in more places, the connector refuses relay hosts outside ReefClaw's, and uploads that hit a rate limit are retried instead of dropped.",
21
+ "0.1.48": "Two changes. The heartbeat checklist (HEARTBEAT.md) now arrives with your trading instructions, signed, and is placed beside SKILL.md, so the agent reads it instead of failing every beat looking for a file that was never installed. And if ReefClaw's own edge protection ever blocks your host's address (an automatic DDoS mitigation, seen once on 2026-09-28), the plugin and connector now recognise it, back off instead of retrying into it, keep trading with the safety floor intact, and report it to the dashboard over the relay so you see a banner and support is paged; the log names the real cause instead of 'connect the account first' or 'Pro subscription required'. Periodic checks are spread out so several agents behind one address no longer call in lockstep. RC_WEBAPP_EDGE_GATE=off disables the back-off only."
21
22
  }
@@ -101,7 +101,7 @@ 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@0.1.60
104
+ npx --yes @reefclaw/connect@0.1.61
105
105
  ```
106
106
 
107
107
  That is the whole install. It places the plugin, sets up the connector, restarts the gateway where it can, and prints what it changed. If its closing lines say **GATEWAY NOT RESTARTED**, the plugin is on disk but not running yet: restarting is the user's step (in Docker, `docker restart <container>` from the host; otherwise restarting OpenClaw). Tell the user exactly that and stop — do not restart, signal or kill any process, do not run docker or service commands, and do not edit the gateway config, even if you could. The plugin reports its own version to ReefClaw after the restart; never post readiness, version or health reports yourself. 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.
@@ -1,3 +1,6 @@
1
+ /** What the agent is told when the EDGE (not the app) denies the host. Names
2
+ * the real cause; the old branch called every 403 a subscription problem. */
3
+ export declare const MARKET_INTEL_EDGE_DENIED_MESSAGE: string;
1
4
  export type MarketIntelCategory = 'sentiment' | 'news' | 'calendar' | 'overview' | 'derivatives' | 'onchain' | 'social';
2
5
  export interface MarketIntelDeps {
3
6
  connectionToken: string;
@@ -13,6 +13,11 @@
13
13
  // order (the create_order gate still applies) — and makes injected directives
14
14
  // far less likely to be followed.
15
15
  import { keepAliveFetch } from '../http/keepalive-fetch.js';
16
+ import { noteWebappResponse, webappEdgeGate, webappUserAgent } from '../http/webapp-edge.js';
17
+ /** What the agent is told when the EDGE (not the app) denies the host. Names
18
+ * the real cause; the old branch called every 403 a subscription problem. */
19
+ export const MARKET_INTEL_EDGE_DENIED_MESSAGE = "ReefClaw's edge firewall is currently denying this host's IP (automatic DDoS mitigation — not a subscription or token problem). " +
20
+ 'Market intelligence is unavailable until it lifts (usually within 30 minutes); trading continues normally with exchange data.';
16
21
  /** Categories whose payloads contain attacker-influenceable free text.
17
22
  * `overview` carries CoinGecko coin names / trending titles and `sentiment`
18
23
  * carries provider labels — third-party strings like the other three
@@ -99,16 +104,34 @@ export async function getMarketIntelTool(args, deps) {
99
104
  if (symbols?.length) {
100
105
  url.searchParams.set('symbols', symbols.join(','));
101
106
  }
107
+ // Edge-denied host: answer without a request (each one feeds the block).
108
+ if (webappEdgeGate().isBlocked()) {
109
+ return { error: MARKET_INTEL_EDGE_DENIED_MESSAGE };
110
+ }
102
111
  try {
112
+ const startedAt = Date.now();
103
113
  const res = await keepAliveFetch(url.toString(), {
104
- headers: { Authorization: `Bearer ${connectionToken}` },
114
+ // Capitalised key on purpose: the tool test pins `headers.Authorization`.
115
+ headers: { Authorization: `Bearer ${connectionToken}`, 'user-agent': webappUserAgent() },
105
116
  signal: AbortSignal.timeout(10_000),
106
117
  });
107
118
  if (res.status === 403) {
119
+ let bodyText = null;
120
+ try {
121
+ bodyText = (await res.text()).slice(0, 200);
122
+ }
123
+ catch {
124
+ /* classify on headers alone */
125
+ }
126
+ if (noteWebappResponse(res, url.pathname, bodyText)) {
127
+ return { error: MARKET_INTEL_EDGE_DENIED_MESSAGE };
128
+ }
108
129
  return {
109
130
  error: 'Market intelligence requires a Pro subscription at reefclaw.com. Trading continues normally with Binance data.',
110
131
  };
111
132
  }
133
+ if (res.ok)
134
+ noteWebappResponse(res, url.pathname, undefined, startedAt);
112
135
  if (res.status === 401) {
113
136
  return { error: 'Invalid or expired ReefClaw connection token.' };
114
137
  }