@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.
@@ -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,11 @@
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';
15
16
  import { resolveWebappBaseUrl } from './utils/base-url.js';
16
17
  import { Connector } from './connector.js';
17
18
  import { readLocalSkillVersion, readAgentVisibleSkillVersions, validateSkillContent, compareSemver } from './utils/skill-version.js';
@@ -62,6 +63,9 @@ const CRITICAL_EVENTS = new Set([
62
63
  * (0.x) version. Long enough to be negligible load, short enough to un-strand
63
64
  * a new user whose one-shot startup pull failed. */
64
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;
65
69
  /** True while the agent is still on the thin bootstrap SKILL.md and has NOT yet
66
70
  * received the full trading instructions. The bootstrap ships 0.0.x; the full
67
71
  * trading SKILL.md is 2.x — treat anything below 1.0.0 (or an unknown version)
@@ -132,6 +136,9 @@ export class Bridge {
132
136
  * timer) double-applying / double-notifying during the one-time bootstrap→
133
137
  * full transition. The chain that starts (attempt 1) owns the flag. */
134
138
  skillPullInFlight = false;
139
+ /** Drains webapp edge-deny transitions into one-shot agent_state events. */
140
+ webappEdgeTimer = null;
141
+ edgeProbeInFlight = false;
135
142
  constructor(provider, connectorConfig,
136
143
  /** Where the served agent's SKILL.md and session index live. The legacy
137
144
  * single-agent paths by default; index.ts passes the resolved agent's
@@ -166,12 +173,14 @@ export class Bridge {
166
173
  // without reconnecting can't be stranded on the bootstrap. No-op once
167
174
  // upgraded (guarded on version).
168
175
  this.startBootstrapHeal();
176
+ this.startWebappEdgeEmitter();
169
177
  }
170
178
  /** Stop the bridge: disconnect + stop provider */
171
179
  stop() {
172
180
  logger.info(TAG, 'Stopping bridge');
173
181
  this.stopThrottleTimer();
174
182
  this.stopBootstrapHeal();
183
+ this.stopWebappEdgeEmitter();
175
184
  this.unwireProviderEvents();
176
185
  this.connector.destroy();
177
186
  this.provider.stop();
@@ -1075,6 +1084,86 @@ export class Bridge {
1075
1084
  // ---- OTA SKILL.md update ----
1076
1085
  /** Apply a SKILL.md update: verify signature (C1), write to workspace +
1077
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
+ }
1078
1167
  async applySkillUpdate(env) {
1079
1168
  const { version, content } = env;
1080
1169
  const workspacePath = this.paths.workspaceDir;
@@ -1303,23 +1392,48 @@ export class Bridge {
1303
1392
  // Scheme-checked (https, or http only to a private host) — see utils/base-url.ts.
1304
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);
@@ -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;
@@ -26,6 +26,7 @@
26
26
  // the main session, whose transcript is one long file). Heartbeats only.
27
27
  import { logger } from './logger.js';
28
28
  import { resolveWebappBaseUrl } from './utils/base-url.js';
29
+ import { noteWebappResponse, webappEdgeTracker, webappUserAgent } from './utils/webapp-edge.js';
29
30
  import { buildHeartbeatRunRecord, describeTranscriptStore, isCronSessionKey, listAllSessionCandidates, readCandidateCronMarker, readSession, resolveAgentDbPath, resolveSessionsDir, shrinkRecord, } from './heartbeat-transcript.js';
30
31
  import { defaultStateFile, loadState, markRecorded, saveState } from './heartbeat-runs-state.js';
31
32
  const TAG = 'heartbeat-runs';
@@ -48,6 +49,10 @@ export const BOOTSTRAP_LOOKBACK_MS = 6 * 60 * 60_000;
48
49
  export const MAX_PER_SCAN = 5;
49
50
  /** Give up on a run after this many failed POST cycles. */
50
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;
51
56
  /** Cool down `cron.runs` for this long after it errors (older gateway). */
52
57
  export const CRON_RUNS_COOLDOWN_MS = 60 * 60_000;
53
58
  /** With nothing to read, ask `cron.runs` this often whether beats ran anyway
@@ -64,6 +69,8 @@ export class HeartbeatRunRecorder {
64
69
  scanning = false;
65
70
  stopped = false;
66
71
  attempts = new Map();
72
+ /** First time a record was DEFERRED behind the edge gate (EDGE_DEFER_MAX_MS). */
73
+ firstAttemptAt = new Map();
67
74
  cronRunsUnavailableUntil = 0;
68
75
  probeLogged = false;
69
76
  store = null;
@@ -175,6 +182,21 @@ export class HeartbeatRunRecorder {
175
182
  deferred++;
176
183
  continue;
177
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
+ }
178
200
  const parsed = readSession(c);
179
201
  if (!parsed) {
180
202
  deferred++;
@@ -212,6 +234,7 @@ export class HeartbeatRunRecorder {
212
234
  this.stats.recorded++;
213
235
  markRecorded(state, c.sessionId);
214
236
  this.attempts.delete(c.sessionId);
237
+ this.firstAttemptAt.delete(c.sessionId);
215
238
  dirty = true;
216
239
  logger.info(TAG, `Heartbeat run recorded: ${c.sessionId.slice(0, 8)} status=${record.status} tools=${record.toolCallCount}` +
217
240
  ` (${record.toolErrorCount} err) tokens=${record.tokens.total ?? 'n/a'}/${record.tokens.source}` +
@@ -224,6 +247,7 @@ export class HeartbeatRunRecorder {
224
247
  if (outcome.terminal || n >= MAX_POST_ATTEMPTS) {
225
248
  markRecorded(state, c.sessionId);
226
249
  this.attempts.delete(c.sessionId);
250
+ this.firstAttemptAt.delete(c.sessionId);
227
251
  dirty = true;
228
252
  logger.warn(TAG, `Heartbeat run ${c.sessionId.slice(0, 8)} NOT persisted (${outcome.terminal ? 'rejected' : 'gave up'}: ` +
229
253
  `${outcome.status ?? 'network'} ${outcome.error ?? ''}) — shown on the dashboard, not in the journal`);
@@ -322,17 +346,21 @@ export class HeartbeatRunRecorder {
322
346
  const base = resolveWebappBaseUrl(this.opts.webappUrl);
323
347
  const fetchImpl = this.opts.fetchImpl ?? fetch;
324
348
  try {
349
+ const startedAt = Date.now();
325
350
  const res = await fetchImpl(`${base}/api/internal/heartbeat-runs`, {
326
351
  method: 'POST',
327
352
  headers: {
328
353
  'content-type': 'application/json',
329
354
  authorization: `Bearer ${this.opts.token}`,
355
+ 'user-agent': webappUserAgent(),
330
356
  },
331
357
  body: JSON.stringify(record),
332
358
  signal: AbortSignal.timeout(15_000),
333
359
  });
334
- if (res.ok)
360
+ if (res.ok) {
361
+ noteWebappResponse(res, '/api/internal/heartbeat-runs', undefined, startedAt);
335
362
  return { ok: true, terminal: false, status: res.status };
363
+ }
336
364
  let text = '';
337
365
  try {
338
366
  text = (await res.text()).slice(0, 200);
@@ -340,6 +368,20 @@ export class HeartbeatRunRecorder {
340
368
  catch {
341
369
  /* ignore */
342
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
+ }
343
385
  return { ok: false, terminal: res.status >= 400 && res.status < 500, status: res.status, error: text };
344
386
  }
345
387
  catch (err) {
package/bridge/index.js CHANGED
@@ -20,6 +20,7 @@ import { resolveGatewayConfig, validateGatewayConfig } from './gateway/gateway-c
20
20
  import { ShockWakePoller } from './shock-wake.js';
21
21
  import { HeartbeatRunRecorder } from './heartbeat-runs.js';
22
22
  import { runSetup } from './setup.js';
23
+ import { resolveBridgeVersion, setWebappClientVersion } from './utils/webapp-edge.js';
23
24
  import { resolveRelayInstanceId } from './utils/instance-id.js';
24
25
  import { readOperatorSecretFromStdin } from './utils/operator-secret.js';
25
26
  const TAG = 'main';
@@ -276,6 +277,8 @@ async function main() {
276
277
  // same-box restart (instant takeover) vs a second box (rejected 4011).
277
278
  instanceId: resolveRelayInstanceId(),
278
279
  };
280
+ // Name our traffic at the webapp's edge (User-Agent reefclaw-connect/<version>).
281
+ setWebappClientVersion(resolveBridgeVersion());
279
282
  const bridge = new Bridge(provider, connectorConfig, bridgePaths);
280
283
  // Shock-wake poller (WS3, docs/MARKET_ADAPTIVITY_PLAN.md) — watches intel's
281
284
  // /api/shocks (the WS2 change-of-character flags) and delivers an
@@ -57,6 +57,7 @@
57
57
  // as any reinstall would. Self-hosters carrying patches: switch it off.
58
58
  import { logger } from '../logger.js';
59
59
  import { resolveWebappBaseUrl } from '../utils/base-url.js';
60
+ import { noteWebappResponse } from '../utils/webapp-edge.js';
60
61
  const TAG = 'connector-update';
61
62
  /** The npm package the update runs. Fixed. */
62
63
  export const CONNECT_PACKAGE = '@reefclaw/connect';
@@ -116,9 +117,26 @@ export async function fetchPinnedConnectVersion(opts) {
116
117
  const base = resolveWebappBaseUrl(opts.webappUrl);
117
118
  try {
118
119
  const doFetch = opts.fetchImpl ?? fetch;
120
+ // No headers at all on purpose: this is the PUBLIC endpoint and a test
121
+ // pins that no credential (or anything else) rides along.
122
+ const startedAt = Date.now();
119
123
  const res = await doFetch(`${base}/api/release`, { signal: AbortSignal.timeout(15_000) });
120
- if (!res.ok)
121
- return refuse(`ReefClaw answered HTTP ${res.status}`);
124
+ if (!res.ok) {
125
+ let text = '';
126
+ if (res.status === 403) {
127
+ try {
128
+ text = (await res.text()).slice(0, 200);
129
+ }
130
+ catch {
131
+ /* classify on headers alone */
132
+ }
133
+ }
134
+ const edge = noteWebappResponse(res, '/api/release', text);
135
+ return refuse(edge
136
+ ? `ReefClaw's edge firewall denied this host (HTTP 403 ${edge.action ?? 'deny'}${edge.requestId ? `, request ${edge.requestId}` : ''}) — an IP-level block, not a version problem; retry once it lifts`
137
+ : `ReefClaw answered HTTP ${res.status}`);
138
+ }
139
+ noteWebappResponse(res, '/api/release', undefined, startedAt);
122
140
  const body = (await res.json());
123
141
  const version = body?.connectVersion;
124
142
  if (!isExactConnectVersion(version))
@@ -25,6 +25,7 @@ import { executeSetTradingMode, executeGetBracketConfig, executeSetBracketRequir
25
25
  import { startConnectorUpdate, runConnectorUpdate, fetchPinnedConnectVersion, openAdminGatewaySession, checkPositionGuard, describeUpdateDisabled, requestGatewayRestart, RESTART_REASON_OPERATOR, } from './connector-update.js';
26
26
  import { isInsideContainer, readContainerProbe, runDirectConnectorUpdate } from './connector-update-direct.js';
27
27
  import { DEFAULT_AGENT_ID, isForeignAgentEvent, resolveAgentEventOwner } from '../gateway/agent-scope.js';
28
+ import { noteWebappResponse, webappEdgeTracker, webappHeaders } from '../utils/webapp-edge.js';
28
29
  const TAG = 'gateway';
29
30
  // ---- Day-start NAV persistence ----
30
31
  // Persists sessionStartNav (the UTC-day P&L anchor) per date so Day P&L
@@ -2644,6 +2645,13 @@ export class GatewayProvider {
2644
2645
  // Lazily re-read IDENTITY.md (60s) so a name filled in after connect shows up.
2645
2646
  this.maybeRefreshAgentName();
2646
2647
  const hb = this.heartbeatHealth;
2648
+ let webappApi;
2649
+ try {
2650
+ webappApi = webappEdgeTracker().health();
2651
+ }
2652
+ catch {
2653
+ webappApi = undefined;
2654
+ }
2647
2655
  return {
2648
2656
  mode: this.agentMode,
2649
2657
  strategy: this.lastKnownStrategy,
@@ -2674,6 +2682,9 @@ export class GatewayProvider {
2674
2682
  // stays byte-identical to the pre-feature shape until then.
2675
2683
  ...(this.lastHeartbeat ? { lastHeartbeat: this.lastHeartbeat } : {}),
2676
2684
  ...(this.modelHealth ? { modelHealth: this.modelHealth } : {}),
2685
+ // Edge-deny verdict (bridge ∪ plugin file). Absent while never denied
2686
+ // → byte-identical payload; the relay carries it while HTTP can't.
2687
+ ...(webappApi ? { webappApi } : {}),
2677
2688
  },
2678
2689
  };
2679
2690
  }
@@ -3016,12 +3027,16 @@ export class GatewayProvider {
3016
3027
  const base = resolveWebappBaseUrl();
3017
3028
  const mode = this.tradingMode === 'PAPER' ? 'paper' : 'live';
3018
3029
  try {
3030
+ const startedAt = Date.now();
3019
3031
  const res = await fetch(`${base}/api/internal/trades?limit=1&mode=${mode}`, {
3020
- headers: { Authorization: `Bearer ${token}` },
3032
+ headers: webappHeaders(token),
3021
3033
  signal: AbortSignal.timeout(5_000),
3022
3034
  });
3023
- if (!res.ok)
3035
+ if (!res.ok) {
3036
+ noteWebappResponse(res, '/api/internal/trades', res.status === 403 ? await res.text().catch(() => '') : null);
3024
3037
  return;
3038
+ }
3039
+ noteWebappResponse(res, '/api/internal/trades', undefined, startedAt);
3025
3040
  const body = (await res.json());
3026
3041
  const ts = body.trades?.[0]?.fillTimestamp;
3027
3042
  if (ts) {
@@ -43,6 +43,7 @@
43
43
  import { logger, formatError } from './logger.js';
44
44
  import { labelOr, finiteOr } from './utils/untrusted-text.js';
45
45
  import { resolveWebappBaseUrl } from './utils/base-url.js';
46
+ import { noteWebappResponse, webappEdgeTracker, webappHeaders } from './utils/webapp-edge.js';
46
47
  const TAG = 'shock-wake';
47
48
  /** Coerce one intel row into a ShockEntry, or null when it is not one.
48
49
  * The wake message interpolates `symbol` and `regime` into a
@@ -252,13 +253,22 @@ export class ShockWakePoller {
252
253
  }
253
254
  async refreshGate() {
254
255
  const base = resolveWebappBaseUrl(this.opts.webappUrl);
256
+ // Edge-denied host: keep the last-known mode instead of feeding the ban.
257
+ if (webappEdgeTracker().isBlocked())
258
+ return;
255
259
  try {
256
260
  const doFetch = this.opts.fetchImpl ?? fetch;
261
+ const startedAt = Date.now();
257
262
  const res = await doFetch(`${base}/api/internal/config`, {
258
- headers: { Authorization: `Bearer ${this.opts.token}` },
263
+ headers: webappHeaders(this.opts.token),
259
264
  });
260
- if (!res.ok)
265
+ if (!res.ok) {
266
+ // Edge deny (Vercel mitigation) is recorded on the shared tracker so
267
+ // the dashboard/fleet alarm learn of it; the gate itself stays inert.
268
+ noteWebappResponse(res, '/api/internal/config', res.status === 403 ? await res.text().catch(() => '') : null);
261
269
  return; // keep last-known mode on outage (fail toward inert)
270
+ }
271
+ noteWebappResponse(res, '/api/internal/config', undefined, startedAt);
262
272
  const next = parseShockWakeGate(await res.json());
263
273
  if (next !== this.mode) {
264
274
  logger.info(TAG, `gate: shockWake ${this.mode} → ${next}`);
package/bridge/types.d.ts CHANGED
@@ -141,10 +141,27 @@ export interface AgentStateData {
141
141
  * cron job's FailoverReason + the last recorded beat
142
142
  * (skill/src/model-health.ts). Absent until first derived. */
143
143
  modelHealth?: ModelHealthSummary;
144
+ /** Can this host reach ReefClaw's webapp, or is its IP being denied at
145
+ * the edge (Vercel DDoS mitigation)? Bridge ∪ plugin observation
146
+ * (skill/src/utils/webapp-edge.ts). Absent while never denied — the
147
+ * relay is the one channel that still works during the deny, so this
148
+ * is how the dashboard learns of it. */
149
+ webappApi?: WebappApiHealth;
144
150
  };
145
151
  };
146
152
  timestamp: string;
147
153
  }
154
+ /** See skill/src/utils/webapp-edge.ts (mirrored in webapp/src/types/agent.ts). */
155
+ export interface WebappApiHealth {
156
+ status: 'ok' | 'edge_denied';
157
+ since?: string;
158
+ lastDeniedAt?: string;
159
+ deniedCount: number;
160
+ source: 'bridge' | 'plugin' | 'both';
161
+ requestId?: string | null;
162
+ lastPath?: string | null;
163
+ recoveredAt?: string;
164
+ }
148
165
  /** Dashboard-facing summary of one heartbeat run (the full record lives in
149
166
  * the webapp's heartbeat_runs table). Token counts are RAW COUNTS — never
150
167
  * translated to a currency here or downstream. */