@reefclaw/openclaw-plugin 0.1.45 → 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.
Files changed (74) hide show
  1. package/README.md +1 -1
  2. package/bridge/bridge.d.ts +39 -0
  3. package/bridge/bridge.js +210 -7
  4. package/bridge/config.js +5 -2
  5. package/bridge/gateway/gateway-config.d.ts +5 -0
  6. package/bridge/gateway/gateway-config.js +5 -2
  7. package/bridge/gateway/heartbeat-cron.js +3 -2
  8. package/bridge/heartbeat-runs.d.ts +6 -0
  9. package/bridge/heartbeat-runs.js +45 -4
  10. package/bridge/heartbeat-transcript.d.ts +2 -0
  11. package/bridge/heartbeat-transcript.js +45 -13
  12. package/bridge/index.js +31 -0
  13. package/bridge/providers/connector-update.js +22 -5
  14. package/bridge/providers/emergency-commands.js +2 -3
  15. package/bridge/providers/gateway.d.ts +6 -0
  16. package/bridge/providers/gateway.js +57 -27
  17. package/bridge/providers/onboarding-commands.d.ts +8 -7
  18. package/bridge/setup.js +12 -0
  19. package/bridge/shock-wake.d.ts +7 -0
  20. package/bridge/shock-wake.js +72 -9
  21. package/bridge/types.d.ts +17 -0
  22. package/bridge/utils/base-url.d.ts +26 -0
  23. package/bridge/utils/base-url.js +108 -0
  24. package/bridge/utils/operator-secret.d.ts +7 -0
  25. package/bridge/utils/operator-secret.js +59 -0
  26. package/bridge/utils/relay-host.d.ts +23 -0
  27. package/bridge/utils/relay-host.js +66 -0
  28. package/bridge/utils/untrusted-text.d.ts +9 -0
  29. package/bridge/utils/untrusted-text.js +51 -0
  30. package/bridge/utils/webapp-edge.d.ts +145 -0
  31. package/bridge/utils/webapp-edge.js +366 -0
  32. package/config/agent-config-client.js +18 -2
  33. package/config/agent-config-poller.d.ts +4 -0
  34. package/config/agent-config-poller.js +46 -6
  35. package/config/base-url.d.ts +16 -0
  36. package/config/base-url.js +87 -0
  37. package/config/operator-provenance.d.ts +19 -0
  38. package/config/operator-provenance.js +102 -25
  39. package/config/user-data-stream-config.d.ts +5 -1
  40. package/config/user-data-stream-config.js +7 -5
  41. package/connector-supervisor.d.ts +15 -0
  42. package/connector-supervisor.js +22 -1
  43. package/http/webapp-edge.d.ts +116 -0
  44. package/http/webapp-edge.js +313 -0
  45. package/index.js +36 -24
  46. package/ingest/position-decisions-client.js +51 -11
  47. package/ingest/readiness-reporter.d.ts +13 -0
  48. package/ingest/readiness-reporter.js +78 -8
  49. package/ingest/retry-after.d.ts +5 -0
  50. package/ingest/retry-after.js +21 -0
  51. package/ingest/trade-store-client.js +43 -7
  52. package/lifecycle/process-role.d.ts +4 -0
  53. package/lifecycle/process-role.js +1 -1
  54. package/openclaw.plugin.json +1 -1
  55. package/package.json +2 -2
  56. package/release-integrity.json +10 -0
  57. package/release-notes.json +3 -1
  58. package/risk/pre-trade-check.js +1 -1
  59. package/risk/stop-widening-guard.d.ts +35 -0
  60. package/risk/stop-widening-guard.js +98 -0
  61. package/skills/reefclaw/SKILL.md +2 -2
  62. package/tools/create-order.js +17 -12
  63. package/tools/get-bracket-config.d.ts +3 -1
  64. package/tools/get-bracket-config.js +3 -1
  65. package/tools/get-market-intel.d.ts +4 -0
  66. package/tools/get-market-intel.js +38 -4
  67. package/tools/modify-stop.d.ts +6 -0
  68. package/tools/modify-stop.js +110 -0
  69. package/tools/set-bracket-requirement.d.ts +7 -0
  70. package/tools/set-bracket-requirement.js +12 -0
  71. package/trading-params-bounds.d.ts +32 -0
  72. package/trading-params-bounds.js +113 -0
  73. package/trading-params-cache.d.ts +9 -1
  74. package/trading-params-cache.js +33 -2
package/README.md CHANGED
@@ -8,7 +8,7 @@ This file is the plain-language ledger of what the package does on the machine i
8
8
 
9
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
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.
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 an operator-provenance secret — a per-boot value the plugin mints in memory and hands only to the connector it supervises (never a file, argv or environment variable, so it cannot be read back from the config or supplied in conversation). While trading is live a new entry without a protective stop is refused whatever the settings say.
12
12
 
13
13
  ## What it writes on this machine
14
14
 
@@ -55,6 +55,9 @@ export declare class Bridge {
55
55
  * timer) double-applying / double-notifying during the one-time bootstrap→
56
56
  * full transition. The chain that starts (attempt 1) owns the flag. */
57
57
  private skillPullInFlight;
58
+ /** Drains webapp edge-deny transitions into one-shot agent_state events. */
59
+ private webappEdgeTimer;
60
+ private edgeProbeInFlight;
58
61
  constructor(provider: OpenClawProvider, connectorConfig: ConnectorConfig,
59
62
  /** Where the served agent's SKILL.md and session index live. The legacy
60
63
  * single-agent paths by default; index.ts passes the resolved agent's
@@ -142,6 +145,26 @@ export declare class Bridge {
142
145
  private handleClearExchangeCredentials;
143
146
  /** Apply a SKILL.md update: verify signature (C1), write to workspace +
144
147
  * installed skill dir, clear session cache, notify agent. */
148
+ /**
149
+ * HEARTBEAT.md — the heartbeat checklist the agent reads at the start of
150
+ * every beat. Until 2026-09-27 the file never reached npx boxes, so every
151
+ * beat opened with a failed `read` and ran on the abbreviated inline list.
152
+ * It now rides the SKILL.md pull, signed offline like SKILL.md (same C1
153
+ * gate: enforced → a valid signature is required; a PRESENT signature is
154
+ * always verified), and is written beside every agent-visible reefclaw
155
+ * SKILL.md copy — NEVER at the workspace root, where OpenClaw's own
156
+ * heartbeat monitor (`openclaw doctor`) would adopt it and double-run beats.
157
+ */
158
+ private applyHeartbeatChecklist;
159
+ /** Every `<skills dir>/<*reefclaw*>/` that currently holds a SKILL.md, across
160
+ * the layouts applySkillUpdate maintains (~/.openclaw/skills, the workspace
161
+ * skills dir, plugin-extension bundled skills). Fail-soft. */
162
+ private reefclawSkillDirs;
163
+ /** Write `HEARTBEAT.md` into each dir whose copy differs; returns the count
164
+ * written. Pure with respect to the bridge (exported for tests via the
165
+ * instance); never creates a directory, so it can never plant a file where
166
+ * no reefclaw skill lives. */
167
+ private writeHeartbeatChecklistFiles;
145
168
  private applySkillUpdate;
146
169
  /**
147
170
  * Fetch the stored SKILL.md envelope from the relay's Durable-Object store
@@ -165,6 +188,22 @@ export declare class Bridge {
165
188
  * gate when enforced) as the relay pull path.
166
189
  */
167
190
  private pullSkillContentFromWebapp;
191
+ /** Every minute: surface an edge-deny episode (the bridge's own webapp calls
192
+ * ∪ the plugin's gate file) as one-shot agent_state events. The relay audits
193
+ * them as skill.webapp_edge_denied / skill.webapp_edge_recovered — what the
194
+ * fleet alarm keys on — while buildAgentState carries the live verdict
195
+ * (health.webappApi) to the dashboard banner. Relay-borne on purpose: every
196
+ * HTTP path to the webapp is the thing being denied. */
197
+ private startWebappEdgeEmitter;
198
+ /** Re-send agent_state from a fresh snapshot (carries health.webappApi). */
199
+ private reemitAgentState;
200
+ /** While the bridge's own episode is open and its gate has reopened, send
201
+ * ONE authenticated probe (GET /api/internal/config — the same class of
202
+ * call the plugin polls) and feed the verdict to the tracker: a success
203
+ * ends the episode, a deny re-closes the gate at the next rung. Exported
204
+ * on the instance for tests. */
205
+ private maybeProbeEdge;
206
+ private stopWebappEdgeEmitter;
168
207
  /** Start a bounded periodic re-pull of the full SKILL.md while the box is
169
208
  * still on the bootstrap (0.x). pullSkillContentFromWebapp() (fired once at
170
209
  * startup) is a one-shot with a finite retry burst; if every attempt fails —
package/bridge/bridge.js CHANGED
@@ -8,10 +8,12 @@
8
8
  // out of this file: it owns the relay connection, and a local read sitting
9
9
  // beside a network send is what a scanner classifies as exfiltration, and what
10
10
  // a human reviewer then has to disprove.
11
- import { writeFileSync, renameSync, existsSync, mkdirSync, unlinkSync, readdirSync } from 'fs';
11
+ import { writeFileSync, renameSync, existsSync, mkdirSync, unlinkSync, readdirSync, readFileSync } from 'fs';
12
12
  import { join } from 'path';
13
13
  import { homedir } from 'os';
14
14
  import { logger, formatError } from './logger.js';
15
+ import { noteWebappResponse, webappEdgeTracker, webappHeaders } from './utils/webapp-edge.js';
16
+ import { resolveWebappBaseUrl } from './utils/base-url.js';
15
17
  import { Connector } from './connector.js';
16
18
  import { readLocalSkillVersion, readAgentVisibleSkillVersions, validateSkillContent, compareSemver } from './utils/skill-version.js';
17
19
  import { invalidateSkillsSnapshot } from './utils/skills-snapshot-invalidation.js';
@@ -61,6 +63,9 @@ const CRITICAL_EVENTS = new Set([
61
63
  * (0.x) version. Long enough to be negligible load, short enough to un-strand
62
64
  * a new user whose one-shot startup pull failed. */
63
65
  const BOOTSTRAP_SKILL_HEAL_INTERVAL_MS = 10 * 60_000; // 10 min
66
+ /** How often the bridge drains edge-deny transitions into agent_state events
67
+ * (skill.webapp_edge_denied / _recovered audit rows via the relay). */
68
+ const WEBAPP_EDGE_EMIT_INTERVAL_MS = 60_000;
64
69
  /** True while the agent is still on the thin bootstrap SKILL.md and has NOT yet
65
70
  * received the full trading instructions. The bootstrap ships 0.0.x; the full
66
71
  * trading SKILL.md is 2.x — treat anything below 1.0.0 (or an unknown version)
@@ -131,6 +136,9 @@ export class Bridge {
131
136
  * timer) double-applying / double-notifying during the one-time bootstrap→
132
137
  * full transition. The chain that starts (attempt 1) owns the flag. */
133
138
  skillPullInFlight = false;
139
+ /** Drains webapp edge-deny transitions into one-shot agent_state events. */
140
+ webappEdgeTimer = null;
141
+ edgeProbeInFlight = false;
134
142
  constructor(provider, connectorConfig,
135
143
  /** Where the served agent's SKILL.md and session index live. The legacy
136
144
  * single-agent paths by default; index.ts passes the resolved agent's
@@ -165,12 +173,14 @@ export class Bridge {
165
173
  // without reconnecting can't be stranded on the bootstrap. No-op once
166
174
  // upgraded (guarded on version).
167
175
  this.startBootstrapHeal();
176
+ this.startWebappEdgeEmitter();
168
177
  }
169
178
  /** Stop the bridge: disconnect + stop provider */
170
179
  stop() {
171
180
  logger.info(TAG, 'Stopping bridge');
172
181
  this.stopThrottleTimer();
173
182
  this.stopBootstrapHeal();
183
+ this.stopWebappEdgeEmitter();
174
184
  this.unwireProviderEvents();
175
185
  this.connector.destroy();
176
186
  this.provider.stop();
@@ -1074,6 +1084,86 @@ export class Bridge {
1074
1084
  // ---- OTA SKILL.md update ----
1075
1085
  /** Apply a SKILL.md update: verify signature (C1), write to workspace +
1076
1086
  * installed skill dir, clear session cache, notify agent. */
1087
+ /**
1088
+ * HEARTBEAT.md — the heartbeat checklist the agent reads at the start of
1089
+ * every beat. Until 2026-09-27 the file never reached npx boxes, so every
1090
+ * beat opened with a failed `read` and ran on the abbreviated inline list.
1091
+ * It now rides the SKILL.md pull, signed offline like SKILL.md (same C1
1092
+ * gate: enforced → a valid signature is required; a PRESENT signature is
1093
+ * always verified), and is written beside every agent-visible reefclaw
1094
+ * SKILL.md copy — NEVER at the workspace root, where OpenClaw's own
1095
+ * heartbeat monitor (`openclaw doctor`) would adopt it and double-run beats.
1096
+ */
1097
+ applyHeartbeatChecklist(env) {
1098
+ if (!env || typeof env.content !== 'string' || !env.content || typeof env.version !== 'string')
1099
+ return;
1100
+ if (signatureRequired() || env.signature) {
1101
+ const verdict = verifySkillSignature(env);
1102
+ if (!verdict.ok) {
1103
+ logger.warn(TAG, `HEARTBEAT.md: rejected — ${verdict.reason}`);
1104
+ return;
1105
+ }
1106
+ }
1107
+ const dirs = this.reefclawSkillDirs();
1108
+ const written = this.writeHeartbeatChecklistFiles(env.content, dirs);
1109
+ if (written > 0)
1110
+ logger.info(TAG, `HEARTBEAT.md v${env.version} written beside ${written} reefclaw SKILL.md cop${written === 1 ? 'y' : 'ies'}`);
1111
+ }
1112
+ /** Every `<skills dir>/<*reefclaw*>/` that currently holds a SKILL.md, across
1113
+ * the layouts applySkillUpdate maintains (~/.openclaw/skills, the workspace
1114
+ * skills dir, plugin-extension bundled skills). Fail-soft. */
1115
+ reefclawSkillDirs() {
1116
+ const out = [];
1117
+ const scan = (skillsDir) => {
1118
+ let entries;
1119
+ try {
1120
+ entries = readdirSync(skillsDir, { withFileTypes: true });
1121
+ }
1122
+ catch {
1123
+ return;
1124
+ }
1125
+ for (const e of entries) {
1126
+ if (!e.isDirectory() || !e.name.includes('reefclaw'))
1127
+ continue;
1128
+ const dir = join(skillsDir, e.name);
1129
+ if (existsSync(join(dir, 'SKILL.md')))
1130
+ out.push(dir);
1131
+ }
1132
+ };
1133
+ scan(join(homedir(), '.openclaw', 'skills'));
1134
+ scan(join(this.paths.workspaceDir, 'skills'));
1135
+ const extensionsDir = join(homedir(), '.openclaw', 'extensions');
1136
+ try {
1137
+ for (const ext of readdirSync(extensionsDir, { withFileTypes: true })) {
1138
+ if (ext.isDirectory() && ext.name.includes('reefclaw'))
1139
+ scan(join(extensionsDir, ext.name, 'skills'));
1140
+ }
1141
+ }
1142
+ catch {
1143
+ // no extensions dir
1144
+ }
1145
+ return out;
1146
+ }
1147
+ /** Write `HEARTBEAT.md` into each dir whose copy differs; returns the count
1148
+ * written. Pure with respect to the bridge (exported for tests via the
1149
+ * instance); never creates a directory, so it can never plant a file where
1150
+ * no reefclaw skill lives. */
1151
+ writeHeartbeatChecklistFiles(content, dirs) {
1152
+ let written = 0;
1153
+ for (const dir of dirs) {
1154
+ const target = join(dir, 'HEARTBEAT.md');
1155
+ try {
1156
+ if (existsSync(target) && readFileSync(target, 'utf-8') === content)
1157
+ continue;
1158
+ writeFileSync(target, content, 'utf-8');
1159
+ written++;
1160
+ }
1161
+ catch (err) {
1162
+ logger.warn(TAG, `HEARTBEAT.md: could not write ${target}: ${err instanceof Error ? err.message : String(err)}`);
1163
+ }
1164
+ }
1165
+ return written;
1166
+ }
1077
1167
  async applySkillUpdate(env) {
1078
1168
  const { version, content } = env;
1079
1169
  const workspacePath = this.paths.workspaceDir;
@@ -1299,27 +1389,51 @@ export class Bridge {
1299
1389
  this.skillPullInFlight = true;
1300
1390
  }
1301
1391
  const MAX_ATTEMPTS = 5;
1302
- // www is load-bearing: reefclaw.com 307-redirects and Node fetch strips the
1303
- // Authorization header on cross-origin redirect (verified 2026-03-18).
1304
- const base = (process.env.REEFCLAW_API_URL || 'https://www.reefclaw.com').replace(/\/$/, '');
1392
+ // Scheme-checked (https, or http only to a private host) — see utils/base-url.ts.
1393
+ const base = resolveWebappBaseUrl();
1305
1394
  try {
1395
+ const pullStartedAt = Date.now();
1306
1396
  const res = await fetch(`${base}/api/internal/skill-content`, {
1307
- headers: { Authorization: `Bearer ${this.connectionToken}` },
1397
+ headers: webappHeaders(this.connectionToken),
1308
1398
  signal: AbortSignal.timeout(15_000),
1309
1399
  });
1310
1400
  if (res.status === 401 || res.status === 403) {
1311
- logger.warn(TAG, `SKILL.md webapp pull: not authorized (${res.status}) — connect the account first`);
1401
+ // A 403 can be the EDGE (Vercel mitigation denying this host's IP —
1402
+ // plain-text Forbidden + x-vercel-mitigated) rather than our auth.
1403
+ // Naming it matters: for a day this read as "connect the account
1404
+ // first" on a box whose account was fine (2026-09-28).
1405
+ let bodyText = null;
1406
+ if (res.status === 403) {
1407
+ try {
1408
+ bodyText = (await res.text()).slice(0, 200);
1409
+ }
1410
+ catch {
1411
+ /* classify on headers alone */
1412
+ }
1413
+ }
1414
+ const edge = noteWebappResponse(res, '/api/internal/skill-content', bodyText);
1415
+ if (edge) {
1416
+ logger.warn(TAG, `SKILL.md webapp pull: denied by ReefClaw's edge firewall (${edge.action ?? 'deny'}${edge.requestId ? `, request ${edge.requestId}` : ''}) — ` +
1417
+ `an IP-level block on this host, not the account; the heal timer retries every ${BOOTSTRAP_SKILL_HEAL_INTERVAL_MS / 60_000} min`);
1418
+ }
1419
+ else {
1420
+ logger.warn(TAG, `SKILL.md webapp pull: not authorized (${res.status}) — connect the account first`);
1421
+ }
1312
1422
  this.skillPullInFlight = false;
1313
- return; // A bad token won't get better by retrying within this chain.
1423
+ return; // Neither a bad token nor an edge block gets better within this chain.
1314
1424
  }
1315
1425
  if (!res.ok)
1316
1426
  throw new Error(`HTTP ${res.status}`);
1427
+ noteWebappResponse(res, '/api/internal/skill-content', undefined, pullStartedAt);
1317
1428
  const body = (await res.json());
1318
1429
  if (!body?.version || !body?.content) {
1319
1430
  logger.warn(TAG, 'SKILL.md webapp pull: response missing version/content');
1320
1431
  this.skillPullInFlight = false;
1321
1432
  return;
1322
1433
  }
1434
+ // The heartbeat checklist is independent of the SKILL.md version gate
1435
+ // below: an up-to-date box still gets (or refreshes) HEARTBEAT.md.
1436
+ this.applyHeartbeatChecklist(body.heartbeat);
1323
1437
  this.currentSkillVersion = readLocalSkillVersion(this.paths.workspaceDir);
1324
1438
  // The workspace tracker alone is NOT proof the agent has the full skill:
1325
1439
  // a plugin (re)install resets the agent-visible extension copy to the
@@ -1376,6 +1490,91 @@ export class Bridge {
1376
1490
  setTimeout(() => void this.pullSkillContentFromWebapp(attempt + 1), delayMs).unref?.();
1377
1491
  }
1378
1492
  }
1493
+ /** Every minute: surface an edge-deny episode (the bridge's own webapp calls
1494
+ * ∪ the plugin's gate file) as one-shot agent_state events. The relay audits
1495
+ * them as skill.webapp_edge_denied / skill.webapp_edge_recovered — what the
1496
+ * fleet alarm keys on — while buildAgentState carries the live verdict
1497
+ * (health.webappApi) to the dashboard banner. Relay-borne on purpose: every
1498
+ * HTTP path to the webapp is the thing being denied. */
1499
+ startWebappEdgeEmitter() {
1500
+ if (this.webappEdgeTimer)
1501
+ return;
1502
+ const tick = () => {
1503
+ try {
1504
+ const events = webappEdgeTracker().takeEvents();
1505
+ for (const ev of events) {
1506
+ this.emit('agent_state', ev.event, ev);
1507
+ }
1508
+ // The live verdict rides health.webappApi on agent_state — re-emit the
1509
+ // state right away so the banner does not wait for the next natural
1510
+ // emission (review M2).
1511
+ if (events.length > 0)
1512
+ void this.reemitAgentState();
1513
+ }
1514
+ catch (err) {
1515
+ logger.debug(TAG, `webapp-edge emitter: ${formatError(err)}`);
1516
+ }
1517
+ // A deny observed on a one-shot call (the startup pull on an upgraded
1518
+ // box, the release check) has nothing periodic to clear it: re-probe
1519
+ // once per gate window so the bridge's own episode can never stick.
1520
+ void this.maybeProbeEdge();
1521
+ };
1522
+ this.webappEdgeTimer = setInterval(tick, WEBAPP_EDGE_EMIT_INTERVAL_MS);
1523
+ this.webappEdgeTimer.unref?.();
1524
+ }
1525
+ /** Re-send agent_state from a fresh snapshot (carries health.webappApi). */
1526
+ async reemitAgentState() {
1527
+ try {
1528
+ const snap = await this.provider.getSnapshot();
1529
+ if (snap?.agentState) {
1530
+ // Same payload shape the provider's own emission uses (AgentStateData).
1531
+ this.emit('agent_state', 'state_update', { state: snap.agentState, timestamp: new Date().toISOString() });
1532
+ }
1533
+ }
1534
+ catch (err) {
1535
+ logger.debug(TAG, `webapp-edge: state re-emit skipped: ${formatError(err)}`);
1536
+ }
1537
+ }
1538
+ /** While the bridge's own episode is open and its gate has reopened, send
1539
+ * ONE authenticated probe (GET /api/internal/config — the same class of
1540
+ * call the plugin polls) and feed the verdict to the tracker: a success
1541
+ * ends the episode, a deny re-closes the gate at the next rung. Exported
1542
+ * on the instance for tests. */
1543
+ async maybeProbeEdge() {
1544
+ const tr = webappEdgeTracker();
1545
+ if (!tr.hasOwnEpisode() || tr.isBlocked() || this.edgeProbeInFlight)
1546
+ return;
1547
+ this.edgeProbeInFlight = true;
1548
+ try {
1549
+ const startedAt = Date.now();
1550
+ const res = await fetch(`${resolveWebappBaseUrl()}/api/internal/config`, {
1551
+ headers: webappHeaders(this.connectionToken),
1552
+ signal: AbortSignal.timeout(10_000),
1553
+ });
1554
+ let body = null;
1555
+ if (res.status === 403) {
1556
+ try {
1557
+ body = (await res.text()).slice(0, 200);
1558
+ }
1559
+ catch {
1560
+ /* classify on headers alone */
1561
+ }
1562
+ }
1563
+ noteWebappResponse(res, '/api/internal/config', body, startedAt);
1564
+ }
1565
+ catch (err) {
1566
+ logger.debug(TAG, `webapp-edge re-probe failed: ${formatError(err)}`);
1567
+ }
1568
+ finally {
1569
+ this.edgeProbeInFlight = false;
1570
+ }
1571
+ }
1572
+ stopWebappEdgeEmitter() {
1573
+ if (this.webappEdgeTimer) {
1574
+ clearInterval(this.webappEdgeTimer);
1575
+ this.webappEdgeTimer = null;
1576
+ }
1577
+ }
1379
1578
  /** Start a bounded periodic re-pull of the full SKILL.md while the box is
1380
1579
  * still on the bootstrap (0.x). pullSkillContentFromWebapp() (fired once at
1381
1580
  * startup) is a one-shot with a finite retry burst; if every attempt fails —
@@ -1398,6 +1597,10 @@ export class Bridge {
1398
1597
  this.stopBootstrapHeal();
1399
1598
  return;
1400
1599
  }
1600
+ if (webappEdgeTracker().isBlocked()) {
1601
+ logger.debug(TAG, `bootstrap heal: webapp edge-denied (${Math.ceil(webappEdgeTracker().msUntilOpen() / 60_000)} min left) — skipping this re-pull`);
1602
+ return;
1603
+ }
1401
1604
  logger.info(TAG, `Still on bootstrap SKILL.md (v${this.currentSkillVersion ?? 'unknown'}) — re-attempting webapp pull`);
1402
1605
  void this.pullSkillContentFromWebapp();
1403
1606
  }, BOOTSTRAP_SKILL_HEAL_INTERVAL_MS);
package/bridge/config.js CHANGED
@@ -6,6 +6,7 @@ import { join } from 'path';
6
6
  import { homedir } from 'os';
7
7
  import JSON5 from 'json5';
8
8
  import { logger } from './logger.js';
9
+ import { sanitizeRelayUrl } from './utils/base-url.js';
9
10
  const TAG = 'config';
10
11
  const OPENCLAW_DIR = join(homedir(), '.openclaw');
11
12
  const CONFIG_PATH = join(OPENCLAW_DIR, 'openclaw.json');
@@ -185,11 +186,13 @@ export function resolveConfig(args) {
185
186
  || savedConfig?.userId
186
187
  || process.env.USER_ID
187
188
  || null;
188
- const relayUrl = args.relayUrl
189
+ // wss required for a public relay; ws only to a private host (`partykit
190
+ // dev`) — the socket's auth query carries the rc_ token (audit H4).
191
+ const relayUrl = sanitizeRelayUrl(args.relayUrl
189
192
  || process.env.REEFCLAW_RELAY_URL
190
193
  || savedConfig?.relayUrl
191
194
  || process.env.RELAY_URL
192
- || DEFAULT_RELAY_URL;
195
+ || DEFAULT_RELAY_URL, DEFAULT_RELAY_URL, 'relayUrl');
193
196
  if (savedConfig?.token && !args.token && !process.env.REEFCLAW_TOKEN) {
194
197
  logger.info(TAG, 'Using token from OpenClaw config');
195
198
  }
@@ -10,6 +10,11 @@ export interface GatewayConfig {
10
10
  intelligenceUrl?: string;
11
11
  /** Connection token for intelligence service auth */
12
12
  connectionToken?: string;
13
+ /** Per-boot operator-provenance secret handed over stdin by the plugin
14
+ * that supervises this bridge (utils/operator-secret.ts). When present it
15
+ * is what the operator-only tools receive as `operator_token`; absent →
16
+ * the connection token (the plugin's fallback for unsupervised bridges). */
17
+ operatorSecret?: string;
13
18
  /** Trading venue this box is configured for. Decides how a canonical symbol
14
19
  * is spelled in the intel DB ('BTC/USDT' → 'BTCUSDT' vs 'BTC/USDC' →
15
20
  * 'HL_BTC'), so every skill↔intel symbol crossing depends on it.
@@ -7,6 +7,7 @@ import { homedir } from 'os';
7
7
  import JSON5 from 'json5';
8
8
  import { parseVenue, VENUE_DEFAULT_SYMBOL } from '@reefclaw/shared';
9
9
  import { logger } from '../logger.js';
10
+ import { sanitizeBaseUrl } from '../utils/base-url.js';
10
11
  import { normalizeAgentId, resolveDefaultAgentIdFromConfig, resolveAgentWorkspaceDir, resolveAgentSessionsDir, expandUserPath, listAgentEntries, } from './agent-scope.js';
11
12
  const TAG = 'gateway-config';
12
13
  /** What the bridge serves when the config resolves no default agent. */
@@ -147,10 +148,12 @@ export function resolveGatewayConfig(args) {
147
148
  // --- Intelligence URL ---
148
149
  // CLI > env > plugin-config.json > default. A default is mandatory: this URL
149
150
  // gates the ONLY writer of intel's trade_results (see the constant).
150
- const intelligenceUrl = args.intelligenceUrl
151
+ // Scheme-checked: the bridge sends the rc_ token here as a Bearer header
152
+ // (https, or http only to a private host — utils/base-url.ts, audit H4).
153
+ const intelligenceUrl = sanitizeBaseUrl(args.intelligenceUrl
151
154
  || process.env.REEFCLAW_INTELLIGENCE_URL
152
155
  || pluginConfig?.intelligenceUrl
153
- || DEFAULT_INTELLIGENCE_URL;
156
+ || DEFAULT_INTELLIGENCE_URL, DEFAULT_INTELLIGENCE_URL, 'intelligenceUrl');
154
157
  // --- Agent id ---
155
158
  // CLI > env > plugin-config.json agentId > the gateway's DEFAULT agent from
156
159
  // openclaw.json (OpenClaw's own rule, see resolveDefaultAgentIdFromConfig)
@@ -45,8 +45,9 @@ export const HEARTBEAT_TIMEOUT_SECONDS = 780;
45
45
  // get_wave9_status, and the liquidity batch entirely (observed on prod
46
46
  // 2026-08-04 12:25/12:40 UTC): the checklist being in context is not enough,
47
47
  // the beat prompt itself must name what cannot be skipped.
48
- export const HEARTBEAT_MESSAGE = 'Heartbeat. If a HEARTBEAT.md checklist is in your context, execute EVERY checkbox in it; if not, the items below ARE ' +
49
- 'the checklist — do not go looking for the file, and do NOT re-read SKILL.md from disk unless preparing a NEW entry. ' +
48
+ export const HEARTBEAT_MESSAGE = 'Heartbeat. FIRST read the checklist file skills/reefclaw/HEARTBEAT.md (it sits beside your ReefClaw SKILL.md; one read call) ' +
49
+ 'and execute EVERY checkbox in it. If that read fails, the items below ARE the checklist — do not look anywhere else for it, ' +
50
+ 'and do NOT re-read SKILL.md from disk unless preparing a NEW entry. ' +
50
51
  'NON-SKIPPABLE every beat: (1) query_trades({hours:1}) stop-watcher reconcile; ' +
51
52
  '(2) get_wave9_status() once, unconditionally; ' +
52
53
  '(3) if ANY position is open and the Position Decision Journal is enabled (record_position_reviews reports off-mode when it is not): ' +
@@ -20,6 +20,10 @@ export declare const BOOTSTRAP_LOOKBACK_MS: number;
20
20
  export declare const MAX_PER_SCAN = 5;
21
21
  /** Give up on a run after this many failed POST cycles. */
22
22
  export declare const MAX_POST_ATTEMPTS = 5;
23
+ /** While the bridge's edge gate is closed a record is DEFERRED (no attempt
24
+ * burned) rather than posted into the ban; this wall-clock cap bounds how
25
+ * long one record can wait before the normal attempt budget resumes. */
26
+ export declare const EDGE_DEFER_MAX_MS: number;
23
27
  /** Cool down `cron.runs` for this long after it errors (older gateway). */
24
28
  export declare const CRON_RUNS_COOLDOWN_MS: number;
25
29
  /** With nothing to read, ask `cron.runs` this often whether beats ran anyway
@@ -72,6 +76,8 @@ export declare class HeartbeatRunRecorder {
72
76
  private scanning;
73
77
  private stopped;
74
78
  private readonly attempts;
79
+ /** First time a record was DEFERRED behind the edge gate (EDGE_DEFER_MAX_MS). */
80
+ private readonly firstAttemptAt;
75
81
  private cronRunsUnavailableUntil;
76
82
  private probeLogged;
77
83
  private store;
@@ -25,6 +25,8 @@
25
25
  // Deliberately NOT recorded: shock wakes and operator chat turns (they run in
26
26
  // the main session, whose transcript is one long file). Heartbeats only.
27
27
  import { logger } from './logger.js';
28
+ import { resolveWebappBaseUrl } from './utils/base-url.js';
29
+ import { noteWebappResponse, webappEdgeTracker, webappUserAgent } from './utils/webapp-edge.js';
28
30
  import { buildHeartbeatRunRecord, describeTranscriptStore, isCronSessionKey, listAllSessionCandidates, readCandidateCronMarker, readSession, resolveAgentDbPath, resolveSessionsDir, shrinkRecord, } from './heartbeat-transcript.js';
29
31
  import { defaultStateFile, loadState, markRecorded, saveState } from './heartbeat-runs-state.js';
30
32
  const TAG = 'heartbeat-runs';
@@ -47,6 +49,10 @@ export const BOOTSTRAP_LOOKBACK_MS = 6 * 60 * 60_000;
47
49
  export const MAX_PER_SCAN = 5;
48
50
  /** Give up on a run after this many failed POST cycles. */
49
51
  export const MAX_POST_ATTEMPTS = 5;
52
+ /** While the bridge's edge gate is closed a record is DEFERRED (no attempt
53
+ * burned) rather than posted into the ban; this wall-clock cap bounds how
54
+ * long one record can wait before the normal attempt budget resumes. */
55
+ export const EDGE_DEFER_MAX_MS = 6 * 60 * 60_000;
50
56
  /** Cool down `cron.runs` for this long after it errors (older gateway). */
51
57
  export const CRON_RUNS_COOLDOWN_MS = 60 * 60_000;
52
58
  /** With nothing to read, ask `cron.runs` this often whether beats ran anyway
@@ -63,6 +69,8 @@ export class HeartbeatRunRecorder {
63
69
  scanning = false;
64
70
  stopped = false;
65
71
  attempts = new Map();
72
+ /** First time a record was DEFERRED behind the edge gate (EDGE_DEFER_MAX_MS). */
73
+ firstAttemptAt = new Map();
66
74
  cronRunsUnavailableUntil = 0;
67
75
  probeLogged = false;
68
76
  store = null;
@@ -174,6 +182,21 @@ export class HeartbeatRunRecorder {
174
182
  deferred++;
175
183
  continue;
176
184
  }
185
+ // Edge-denied host (the bridge's own backoff, skill/src/utils/
186
+ // webapp-edge.ts): posting would be one more 403 feeding the block
187
+ // and would burn an attempt. Defer without counting — and BEFORE the
188
+ // transcript is parsed, so a 6 h block does not re-parse the backlog
189
+ // every minute — bounded by EDGE_DEFER_MAX_MS so a record can never
190
+ // wait forever.
191
+ if (webappEdgeTracker().isBlocked()) {
192
+ const first = this.firstAttemptAt.get(c.sessionId) ?? now;
193
+ this.firstAttemptAt.set(c.sessionId, first);
194
+ if (now - first < EDGE_DEFER_MAX_MS) {
195
+ deferred++;
196
+ logger.debug(TAG, `POST deferred for ${c.sessionId.slice(0, 8)} — webapp edge-denied (${Math.ceil(webappEdgeTracker().msUntilOpen() / 60_000)} min left)`);
197
+ continue;
198
+ }
199
+ }
177
200
  const parsed = readSession(c);
178
201
  if (!parsed) {
179
202
  deferred++;
@@ -211,6 +234,7 @@ export class HeartbeatRunRecorder {
211
234
  this.stats.recorded++;
212
235
  markRecorded(state, c.sessionId);
213
236
  this.attempts.delete(c.sessionId);
237
+ this.firstAttemptAt.delete(c.sessionId);
214
238
  dirty = true;
215
239
  logger.info(TAG, `Heartbeat run recorded: ${c.sessionId.slice(0, 8)} status=${record.status} tools=${record.toolCallCount}` +
216
240
  ` (${record.toolErrorCount} err) tokens=${record.tokens.total ?? 'n/a'}/${record.tokens.source}` +
@@ -223,6 +247,7 @@ export class HeartbeatRunRecorder {
223
247
  if (outcome.terminal || n >= MAX_POST_ATTEMPTS) {
224
248
  markRecorded(state, c.sessionId);
225
249
  this.attempts.delete(c.sessionId);
250
+ this.firstAttemptAt.delete(c.sessionId);
226
251
  dirty = true;
227
252
  logger.warn(TAG, `Heartbeat run ${c.sessionId.slice(0, 8)} NOT persisted (${outcome.terminal ? 'rejected' : 'gave up'}: ` +
228
253
  `${outcome.status ?? 'network'} ${outcome.error ?? ''}) — shown on the dashboard, not in the journal`);
@@ -318,22 +343,24 @@ export class HeartbeatRunRecorder {
318
343
  }
319
344
  /** POST one record to the webapp. Never throws. */
320
345
  async post(record) {
321
- // www is load-bearing: reefclaw.com 307-redirects and Node fetch strips the
322
- // Authorization header on cross-origin redirect (verified 2026-03-18).
323
- const base = (this.opts.webappUrl ?? process.env.REEFCLAW_API_URL ?? 'https://www.reefclaw.com').replace(/\/$/, '');
346
+ const base = resolveWebappBaseUrl(this.opts.webappUrl);
324
347
  const fetchImpl = this.opts.fetchImpl ?? fetch;
325
348
  try {
349
+ const startedAt = Date.now();
326
350
  const res = await fetchImpl(`${base}/api/internal/heartbeat-runs`, {
327
351
  method: 'POST',
328
352
  headers: {
329
353
  'content-type': 'application/json',
330
354
  authorization: `Bearer ${this.opts.token}`,
355
+ 'user-agent': webappUserAgent(),
331
356
  },
332
357
  body: JSON.stringify(record),
333
358
  signal: AbortSignal.timeout(15_000),
334
359
  });
335
- if (res.ok)
360
+ if (res.ok) {
361
+ noteWebappResponse(res, '/api/internal/heartbeat-runs', undefined, startedAt);
336
362
  return { ok: true, terminal: false, status: res.status };
363
+ }
337
364
  let text = '';
338
365
  try {
339
366
  text = (await res.text()).slice(0, 200);
@@ -341,6 +368,20 @@ export class HeartbeatRunRecorder {
341
368
  catch {
342
369
  /* ignore */
343
370
  }
371
+ // A 403 from the EDGE (Vercel mitigation on this host's IP) is not a
372
+ // rejection of the record: it stays queued. Later scans DEFER it while
373
+ // the bridge's edge gate is closed (no attempt burned, bounded by
374
+ // EDGE_DEFER_MAX_MS wall-clock) and retry once the gate reopens; the
375
+ // usual MAX_POST_ATTEMPTS budget then applies. A real 4xx stays terminal.
376
+ const edge = noteWebappResponse(res, '/api/internal/heartbeat-runs', text);
377
+ if (edge) {
378
+ return {
379
+ ok: false,
380
+ terminal: false,
381
+ status: res.status,
382
+ error: `edge firewall ${edge.action ?? 'deny'}${edge.requestId ? ` (request ${edge.requestId})` : ''} — retried once the block lifts`,
383
+ };
384
+ }
344
385
  return { ok: false, terminal: res.status >= 400 && res.status < 500, status: res.status, error: text };
345
386
  }
346
387
  catch (err) {
@@ -10,6 +10,8 @@ export declare const SUMMARY_MAX = 4000;
10
10
  export declare const MODEL_EVENTS_MAX = 50;
11
11
  /** Target upper bound for a serialized record (bytes). */
12
12
  export declare const RECORD_MAX_BYTES = 200000;
13
+ /** Placeholder stored instead of an uncaptured result. */
14
+ export declare const RESULT_NOT_CAPTURED = "[not captured: file/shell output may contain secrets]";
13
15
  export interface HeartbeatToolCall {
14
16
  /** The gateway's toolCallId (pairs the call with its result). */
15
17
  id: string;