@reefclaw/openclaw-plugin 0.1.47 → 0.1.49

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 (43) hide show
  1. package/bridge/bridge.d.ts +39 -0
  2. package/bridge/bridge.js +229 -20
  3. package/bridge/gateway/heartbeat-cron.d.ts +64 -0
  4. package/bridge/gateway/heartbeat-cron.js +153 -3
  5. package/bridge/heartbeat-runs.d.ts +6 -0
  6. package/bridge/heartbeat-runs.js +43 -1
  7. package/bridge/index.js +3 -0
  8. package/bridge/provider.d.ts +12 -0
  9. package/bridge/providers/connector-update.js +20 -2
  10. package/bridge/providers/gateway.d.ts +21 -0
  11. package/bridge/providers/gateway.js +121 -9
  12. package/bridge/shock-wake.js +12 -2
  13. package/bridge/types.d.ts +17 -0
  14. package/bridge/utils/skill-version.d.ts +6 -0
  15. package/bridge/utils/skill-version.js +10 -0
  16. package/bridge/utils/webapp-edge.d.ts +145 -0
  17. package/bridge/utils/webapp-edge.js +366 -0
  18. package/config/agent-config-client.js +18 -2
  19. package/config/agent-config-poller.d.ts +4 -0
  20. package/config/agent-config-poller.js +46 -6
  21. package/http/webapp-edge.d.ts +116 -0
  22. package/http/webapp-edge.js +313 -0
  23. package/index.js +7 -0
  24. package/ingest/position-decisions-client.js +28 -7
  25. package/ingest/readiness-reporter.d.ts +13 -0
  26. package/ingest/readiness-reporter.js +78 -8
  27. package/ingest/trade-store-client.js +25 -4
  28. package/openclaw.plugin.json +1 -1
  29. package/package.json +1 -1
  30. package/release-integrity.json +10 -0
  31. package/release-notes.json +3 -1
  32. package/signals/stop-rules.d.ts +13 -0
  33. package/signals/stop-rules.js +35 -6
  34. package/signals/strategy-adapter.js +25 -6
  35. package/skills/reefclaw/SKILL.md +1 -1
  36. package/tools/assessment-validation.d.ts +10 -2
  37. package/tools/assessment-validation.js +19 -5
  38. package/tools/create-order.d.ts +4 -0
  39. package/tools/create-order.js +15 -0
  40. package/tools/get-market-intel.d.ts +3 -0
  41. package/tools/get-market-intel.js +24 -1
  42. package/tools/intel-cache.d.ts +14 -0
  43. package/tools/intel-cache.js +59 -0
@@ -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. */
@@ -29,3 +29,9 @@ export declare function validateSkillContent(content: string): {
29
29
  version: string | null;
30
30
  error?: string;
31
31
  };
32
+ /** True while the agent is still on the thin bootstrap SKILL.md and has NOT yet
33
+ * received the full trading instructions. The bootstrap ships 0.0.x; the full
34
+ * trading SKILL.md is 2.x — treat anything below 1.0.0 (or an unknown version)
35
+ * as bootstrap. Shared by the bridge (pull/heal) and the gateway provider
36
+ * (first heartbeat after a fresh install). */
37
+ export declare function isBootstrapSkillVersion(version: string | null | undefined): boolean;
@@ -128,3 +128,13 @@ export function validateSkillContent(content) {
128
128
  }
129
129
  return { valid: true, version };
130
130
  }
131
+ /** True while the agent is still on the thin bootstrap SKILL.md and has NOT yet
132
+ * received the full trading instructions. The bootstrap ships 0.0.x; the full
133
+ * trading SKILL.md is 2.x — treat anything below 1.0.0 (or an unknown version)
134
+ * as bootstrap. Shared by the bridge (pull/heal) and the gateway provider
135
+ * (first heartbeat after a fresh install). */
136
+ export function isBootstrapSkillVersion(version) {
137
+ if (!version)
138
+ return true;
139
+ return compareSemver('1.0.0', version) > 0; // '1.0.0' > version ⟺ version < 1.0.0
140
+ }
@@ -0,0 +1,145 @@
1
+ export interface HeadersLike {
2
+ get(name: string): string | null;
3
+ }
4
+ export interface EdgeDenyMatch {
5
+ kind: 'vercel_mitigated' | 'plain_forbidden';
6
+ action: string | null;
7
+ requestId: string | null;
8
+ }
9
+ /** Is this 403 the edge (Vercel) rather than the webapp? Pure. The app's own
10
+ * denials are JSON; the edge answers text/plain "Forbidden" + `x-vercel-mitigated`. */
11
+ export declare function classifyEdgeDeny(status: number, headers: HeadersLike | null | undefined, bodyText?: string | null): EdgeDenyMatch | null;
12
+ /** Kill-switch (repo convention: every new mechanism ships with one).
13
+ * `RC_WEBAPP_EDGE_GATE=off` disables the BRAKE only — no call is ever skipped
14
+ * or deferred — while detection, logging, the state file and the relay-borne
15
+ * health signal stay on. Read at call time; logged once. */
16
+ export declare function webappEdgeGateDisabled(): boolean;
17
+ /** The health field carried on agent_state (webapp/src/types/agent.ts
18
+ * AgentHealth.webappApi). Absent from the payload while nothing was ever
19
+ * denied, so older dashboards see a byte-identical shape. */
20
+ export interface WebappApiHealth {
21
+ status: 'ok' | 'edge_denied';
22
+ /** ISO — first deny of the current episode. */
23
+ since?: string;
24
+ lastDeniedAt?: string;
25
+ deniedCount: number;
26
+ /** Who observed it: the connector's own calls, the plugin's gate file, or both. */
27
+ source: 'bridge' | 'plugin' | 'both';
28
+ requestId?: string | null;
29
+ lastPath?: string | null;
30
+ /** ISO — when the last episode ended (status 'ok' only). */
31
+ recoveredAt?: string;
32
+ }
33
+ export type WebappEdgeEvent = {
34
+ event: 'webapp_edge_denied';
35
+ since: string;
36
+ deniedCount: number;
37
+ source: WebappApiHealth['source'];
38
+ requestId: string | null;
39
+ lastPath: string | null;
40
+ timestamp: string;
41
+ } | {
42
+ event: 'webapp_edge_recovered';
43
+ since: string;
44
+ recoveredAt: string;
45
+ deniedCount: number;
46
+ timestamp: string;
47
+ };
48
+ /** Shape of the plugin's state file (plugin/src/http/webapp-edge.ts). Only the
49
+ * fields read here are typed; unknown fields are ignored. */
50
+ interface PluginEdgeStateFile {
51
+ schemaVersion?: number;
52
+ updatedAt?: number;
53
+ blocked?: boolean;
54
+ blockedUntil?: number | null;
55
+ firstDeniedAt?: number | null;
56
+ lastDeniedAt?: number | null;
57
+ deniedCount?: number;
58
+ lastPath?: string | null;
59
+ lastRequestId?: string | null;
60
+ }
61
+ export declare function defaultPluginEdgeStatePath(): string;
62
+ /** Read + validate the plugin's gate file. Missing/corrupt/stale → null. */
63
+ export declare function readPluginEdgeState(path?: string, now?: number): PluginEdgeStateFile | null;
64
+ /** Is the plugin file describing an episode that is still live? */
65
+ export declare function pluginEpisodeActive(f: PluginEdgeStateFile | null, now: number): boolean;
66
+ /** 5 → 10 → 20 → 30 min — the plugin gate's ladder (30 = Vercel's window). */
67
+ export declare const DEFAULT_EDGE_BACKOFF_LADDER_MS: readonly number[];
68
+ export interface WebappEdgeTrackerOptions {
69
+ now?: () => number;
70
+ /** Where the plugin writes its gate file; null disables the merge. */
71
+ pluginStatePath?: string | null;
72
+ backoffLadderMs?: readonly number[];
73
+ }
74
+ /**
75
+ * Merges the bridge's own observations with the plugin's file into one
76
+ * health verdict, runs the bridge-side backoff gate, and queues one event per
77
+ * transition for the bridge to emit.
78
+ */
79
+ export declare class WebappEdgeTracker {
80
+ private readonly now;
81
+ private readonly pluginStatePath;
82
+ private readonly ladder;
83
+ private firstDeniedAt;
84
+ private lastDeniedAt;
85
+ private deniedCount;
86
+ private lastPath;
87
+ private lastRequestId;
88
+ private blockedUntil;
89
+ private step;
90
+ private emittedDenied;
91
+ private emittedSince;
92
+ private recoveredAt;
93
+ private lastSource;
94
+ private pending;
95
+ private pluginCache;
96
+ constructor(opts?: WebappEdgeTrackerOptions);
97
+ /** The bridge itself observed a deny that no success has cleared yet. */
98
+ hasOwnEpisode(): boolean;
99
+ /** True while the bridge's own periodic webapp calls should be skipped.
100
+ * Always false under the kill-switch (the episode itself is still tracked). */
101
+ isBlocked(): boolean;
102
+ /** ms until the bridge gate reopens (0 when open). */
103
+ msUntilOpen(): number;
104
+ /** The connector's own webapp call was denied by the edge. Only an
105
+ * UNBLOCKED deny climbs the ladder (several 403s at the start of a ban are
106
+ * one event, not four). */
107
+ noteDeny(rawPath: string, match: EdgeDenyMatch): void;
108
+ /** The connector's own webapp call succeeded. A response that was already
109
+ * in flight when the ban started proves nothing: pass `startedAt` and a
110
+ * success older than the last deny is ignored. */
111
+ noteSuccess(startedAt?: number): void;
112
+ /** Current verdict (bridge ∪ plugin file). Undefined while nothing was ever
113
+ * denied — the caller omits the field. Re-reads the plugin file (cached
114
+ * 10 s), so a plugin-only episode is picked up on every state build. */
115
+ health(): WebappApiHealth | undefined;
116
+ /** Drain the queued transition events (called by the bridge's emitter). Also
117
+ * refreshes against the plugin file so a plugin-only transition is noticed
118
+ * even when the bridge made no webapp call of its own. */
119
+ takeEvents(): WebappEdgeEvent[];
120
+ private pluginState;
121
+ /** Compare the current verdict with the last emitted one; queue on change. */
122
+ private refresh;
123
+ }
124
+ export declare function webappEdgeTracker(): WebappEdgeTracker;
125
+ /** Test-only: fresh tracker with injected clock / plugin file path. */
126
+ export declare function __resetWebappEdgeTrackerForTests(opts?: WebappEdgeTrackerOptions): WebappEdgeTracker;
127
+ /** Inspect a webapp response on the shared tracker. Never throws. Returns the
128
+ * edge match (if any) so the caller can word its own log line. Pass
129
+ * `startedAt` (epoch ms before the request) so an in-flight success cannot
130
+ * end an episode that began after it was sent. */
131
+ export declare function noteWebappResponse(res: {
132
+ ok: boolean;
133
+ status: number;
134
+ headers: HeadersLike;
135
+ }, path: string, bodyText?: string | null, startedAt?: number): EdgeDenyMatch | null;
136
+ /** Set once at boot from the installed bridge's package.json (index.ts). */
137
+ export declare function setWebappClientVersion(version: string | null | undefined): void;
138
+ export declare function webappUserAgent(): string;
139
+ /** Bearer + User-Agent for a webapp call. `extra` wins on key collision.
140
+ * Capitalised `Authorization` on purpose: the skill-pull test pins that key. */
141
+ export declare function webappHeaders(token: string, extra?: Record<string, string>): Record<string, string>;
142
+ /** Best-effort: the version stamped in the package.json beside the running
143
+ * entry (the installed bridge dir). Unknown → null; never throws. */
144
+ export declare function resolveBridgeVersion(entryPath?: string | undefined): string | null;
145
+ export {};
@@ -0,0 +1,366 @@
1
+ // Edge-deny detection for the connector's webapp (reefclaw.com) calls, a
2
+ // bridge-side backoff gate, and the relay-borne health signal that survives
3
+ // the deny.
4
+ //
5
+ // Why (2026-09-28): Vercel's automatic DDoS mitigation denied a host's IP for
6
+ // rolling 30-minute windows. Every HTTP path to the webapp answered a
7
+ // plain-text `403 Forbidden` with `x-vercel-mitigated: deny` — the SKILL.md
8
+ // pull ("not authorized — connect the account first"), the heartbeat recorder
9
+ // ("rejected"), the plugin's config/readiness/journal calls — while the relay
10
+ // kept working, so the dashboard stayed green. The relay is therefore the one
11
+ // channel that can carry the episode to the operator: this tracker feeds
12
+ // `agent_state.health.webappApi` and a one-shot `webapp_edge_denied` /
13
+ // `webapp_edge_recovered` event (the relay audits both as `skill.<event>`,
14
+ // which is what the fleet alarm keys on).
15
+ //
16
+ // The bridge also backs off (5 → 10 → 20 → 30 min, like the plugin's gate) so
17
+ // the recorder, the shock-wake gate poll and the bootstrap heal stop feeding
18
+ // a ban from this IP; the gate reopens on its own and the next call re-probes.
19
+ //
20
+ // The plugin sees the deny far more often than the bridge (its config poll is
21
+ // every 60 s; the bridge only posts after each beat), so it records its own
22
+ // gate in ~/.reefclaw/webapp-edge-state.json (plugin/src/http/webapp-edge.ts)
23
+ // and the bridge merges that file here. The classifier is deliberately a
24
+ // small duplicate of the plugin's: npx boxes vendor @reefclaw/shared twice
25
+ // and a new shared export would crash an older bridge on a missing symbol.
26
+ //
27
+ // Fails open everywhere: a missing file, a bad header, a classifier miss —
28
+ // the tracker stays silent and the payload stays byte-identical to today's.
29
+ // The gate only ever pauses the bridge's OWN optional webapp traffic; it
30
+ // never touches the relay, the gateway, emergency commands or trading.
31
+ import { existsSync, readFileSync } from 'node:fs';
32
+ import { dirname, join } from 'node:path';
33
+ import { homedir } from 'node:os';
34
+ import { logger } from '../logger.js';
35
+ const TAG = 'webapp-edge';
36
+ /** Is this 403 the edge (Vercel) rather than the webapp? Pure. The app's own
37
+ * denials are JSON; the edge answers text/plain "Forbidden" + `x-vercel-mitigated`. */
38
+ export function classifyEdgeDeny(status, headers, bodyText) {
39
+ if (status !== 403)
40
+ return null;
41
+ const get = (name) => {
42
+ try {
43
+ return headers?.get(name) ?? null;
44
+ }
45
+ catch {
46
+ return null;
47
+ }
48
+ };
49
+ const mitigated = get('x-vercel-mitigated');
50
+ const requestId = get('x-vercel-id');
51
+ if (mitigated) {
52
+ return { kind: 'vercel_mitigated', action: mitigated.trim().toLowerCase() || null, requestId };
53
+ }
54
+ const contentType = (get('content-type') ?? '').toLowerCase();
55
+ const body = (bodyText ?? '').trimStart();
56
+ if (contentType.startsWith('text/plain') && /^forbidden\b/i.test(body)) {
57
+ return { kind: 'plain_forbidden', action: null, requestId };
58
+ }
59
+ return null;
60
+ }
61
+ /** Kill-switch (repo convention: every new mechanism ships with one).
62
+ * `RC_WEBAPP_EDGE_GATE=off` disables the BRAKE only — no call is ever skipped
63
+ * or deferred — while detection, logging, the state file and the relay-borne
64
+ * health signal stay on. Read at call time; logged once. */
65
+ export function webappEdgeGateDisabled() {
66
+ return (process.env.RC_WEBAPP_EDGE_GATE ?? 'on').trim().toLowerCase() === 'off';
67
+ }
68
+ let loggedDisabled = false;
69
+ function noteGateDisabled() {
70
+ if (loggedDisabled)
71
+ return;
72
+ loggedDisabled = true;
73
+ logger.info(TAG, 'backoff gate disabled by RC_WEBAPP_EDGE_GATE=off — edge denies are still detected and reported, but no call is skipped');
74
+ }
75
+ function stripQuery(path) {
76
+ const i = path.indexOf('?');
77
+ return i >= 0 ? path.slice(0, i) : path;
78
+ }
79
+ export function defaultPluginEdgeStatePath() {
80
+ return join(homedir(), '.reefclaw', 'webapp-edge-state.json');
81
+ }
82
+ /** A plugin file older than this is ignored outright (corrupt clock, dead
83
+ * gateway that never wrote again). */
84
+ const PLUGIN_STATE_MAX_AGE_MS = 2 * 60 * 60_000;
85
+ /** A plugin EPISODE counts as live only while its last deny is this recent
86
+ * (or its block is still open): a gateway that died mid-episode must not
87
+ * haunt the dashboard until the 2 h file rule drops it. 45 min covers the
88
+ * plugin gate's longest backoff (30 min) plus its re-probe. */
89
+ const PLUGIN_EPISODE_MAX_AGE_MS = 45 * 60_000;
90
+ /** The file is re-read at most this often from health() (called on every
91
+ * agent-state build). */
92
+ const PLUGIN_STATE_READ_TTL_MS = 10_000;
93
+ /** Read + validate the plugin's gate file. Missing/corrupt/stale → null. */
94
+ export function readPluginEdgeState(path = defaultPluginEdgeStatePath(), now = Date.now()) {
95
+ try {
96
+ if (!existsSync(path))
97
+ return null;
98
+ const raw = JSON.parse(readFileSync(path, 'utf-8'));
99
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
100
+ return null;
101
+ const f = raw;
102
+ if (typeof f.updatedAt !== 'number' || now - f.updatedAt > PLUGIN_STATE_MAX_AGE_MS)
103
+ return null;
104
+ return f;
105
+ }
106
+ catch {
107
+ return null;
108
+ }
109
+ }
110
+ /** Is the plugin file describing an episode that is still live? */
111
+ export function pluginEpisodeActive(f, now) {
112
+ if (!f)
113
+ return false;
114
+ if (typeof f.firstDeniedAt !== 'number' || !((f.deniedCount ?? 0) > 0))
115
+ return false;
116
+ const recentDeny = typeof f.lastDeniedAt === 'number' && now - f.lastDeniedAt <= PLUGIN_EPISODE_MAX_AGE_MS;
117
+ const openBlock = typeof f.blockedUntil === 'number' && f.blockedUntil > now - 5 * 60_000;
118
+ return recentDeny || openBlock;
119
+ }
120
+ /** 5 → 10 → 20 → 30 min — the plugin gate's ladder (30 = Vercel's window). */
121
+ export const DEFAULT_EDGE_BACKOFF_LADDER_MS = [
122
+ 5 * 60_000,
123
+ 10 * 60_000,
124
+ 20 * 60_000,
125
+ 30 * 60_000,
126
+ ];
127
+ /**
128
+ * Merges the bridge's own observations with the plugin's file into one
129
+ * health verdict, runs the bridge-side backoff gate, and queues one event per
130
+ * transition for the bridge to emit.
131
+ */
132
+ export class WebappEdgeTracker {
133
+ now;
134
+ pluginStatePath;
135
+ ladder;
136
+ // Bridge-observed episode + gate.
137
+ firstDeniedAt = null;
138
+ lastDeniedAt = null;
139
+ deniedCount = 0;
140
+ lastPath = null;
141
+ lastRequestId = null;
142
+ blockedUntil = null;
143
+ step = 0;
144
+ // Last emitted verdict (for transition detection) + queued events.
145
+ emittedDenied = false;
146
+ emittedSince = null;
147
+ recoveredAt = null;
148
+ lastSource = 'bridge';
149
+ pending = [];
150
+ // Plugin file cache.
151
+ pluginCache = null;
152
+ constructor(opts = {}) {
153
+ this.now = opts.now ?? (() => Date.now());
154
+ this.pluginStatePath = opts.pluginStatePath === undefined ? defaultPluginEdgeStatePath() : opts.pluginStatePath;
155
+ this.ladder = opts.backoffLadderMs && opts.backoffLadderMs.length > 0 ? opts.backoffLadderMs : DEFAULT_EDGE_BACKOFF_LADDER_MS;
156
+ }
157
+ /** The bridge itself observed a deny that no success has cleared yet. */
158
+ hasOwnEpisode() {
159
+ return this.firstDeniedAt !== null;
160
+ }
161
+ /** True while the bridge's own periodic webapp calls should be skipped.
162
+ * Always false under the kill-switch (the episode itself is still tracked). */
163
+ isBlocked() {
164
+ const blocked = this.blockedUntil !== null && this.now() < this.blockedUntil;
165
+ if (blocked && webappEdgeGateDisabled()) {
166
+ noteGateDisabled();
167
+ return false;
168
+ }
169
+ return blocked;
170
+ }
171
+ /** ms until the bridge gate reopens (0 when open). */
172
+ msUntilOpen() {
173
+ if (this.blockedUntil === null)
174
+ return 0;
175
+ return Math.max(0, this.blockedUntil - this.now());
176
+ }
177
+ /** The connector's own webapp call was denied by the edge. Only an
178
+ * UNBLOCKED deny climbs the ladder (several 403s at the start of a ban are
179
+ * one event, not four). */
180
+ noteDeny(rawPath, match) {
181
+ const now = this.now();
182
+ const path = stripQuery(rawPath);
183
+ const wasBlocked = this.isBlocked();
184
+ if (!wasBlocked) {
185
+ const backoff = this.ladder[Math.min(this.step, this.ladder.length - 1)];
186
+ this.step += 1;
187
+ this.blockedUntil = now + backoff;
188
+ }
189
+ if (this.firstDeniedAt === null) {
190
+ this.firstDeniedAt = now;
191
+ const who = match.kind === 'vercel_mitigated' ? "ReefClaw's edge firewall" : 'a firewall in front of ReefClaw';
192
+ const how = match.kind === 'vercel_mitigated' ? `Vercel mitigation '${match.action ?? 'deny'}'` : 'plain-text Forbidden, no Vercel header';
193
+ logger.warn(TAG, `${path} denied by ${who} (${how}${match.requestId ? `, request ${match.requestId}` : ''}) — an IP-level block on this host, NOT the account or token. ` +
194
+ `Instruction pulls and heartbeat records wait for it to lift (pausing webapp calls for ${Math.round(this.msUntilOpen() / 60_000)} min); trading and the safety floor are unaffected.`);
195
+ }
196
+ this.lastDeniedAt = now;
197
+ this.deniedCount += 1;
198
+ this.lastPath = path;
199
+ this.lastRequestId = match.requestId;
200
+ this.refresh();
201
+ }
202
+ /** The connector's own webapp call succeeded. A response that was already
203
+ * in flight when the ban started proves nothing: pass `startedAt` and a
204
+ * success older than the last deny is ignored. */
205
+ noteSuccess(startedAt) {
206
+ if (startedAt !== undefined && this.lastDeniedAt !== null && startedAt < this.lastDeniedAt) {
207
+ logger.debug(TAG, 'ignoring a success that started before the last edge deny');
208
+ return;
209
+ }
210
+ if (this.firstDeniedAt !== null) {
211
+ logger.info(TAG, `webapp reachable again after ${this.deniedCount} edge denials`);
212
+ }
213
+ this.firstDeniedAt = null;
214
+ this.lastDeniedAt = null;
215
+ this.deniedCount = 0;
216
+ this.lastPath = null;
217
+ this.lastRequestId = null;
218
+ this.blockedUntil = null;
219
+ this.step = 0;
220
+ this.refresh();
221
+ }
222
+ /** Current verdict (bridge ∪ plugin file). Undefined while nothing was ever
223
+ * denied — the caller omits the field. Re-reads the plugin file (cached
224
+ * 10 s), so a plugin-only episode is picked up on every state build. */
225
+ health() {
226
+ const now = this.now();
227
+ const plugin = this.pluginState(now);
228
+ const bridgeActive = this.firstDeniedAt !== null;
229
+ const pluginActive = pluginEpisodeActive(plugin, now);
230
+ if (bridgeActive || pluginActive) {
231
+ const since = Math.min(bridgeActive ? this.firstDeniedAt : Number.POSITIVE_INFINITY, pluginActive ? plugin?.firstDeniedAt : Number.POSITIVE_INFINITY);
232
+ const last = Math.max(this.lastDeniedAt ?? 0, pluginActive && typeof plugin?.lastDeniedAt === 'number' ? plugin.lastDeniedAt : 0);
233
+ const source = bridgeActive && pluginActive ? 'both' : bridgeActive ? 'bridge' : 'plugin';
234
+ this.lastSource = source;
235
+ const requestId = this.lastRequestId ?? (pluginActive ? (plugin?.lastRequestId ?? null) : null);
236
+ const lastPath = this.lastPath ?? (pluginActive ? stripQuery(plugin?.lastPath ?? '') || null : null);
237
+ return {
238
+ status: 'edge_denied',
239
+ since: new Date(Number.isFinite(since) ? since : now).toISOString(),
240
+ ...(last > 0 ? { lastDeniedAt: new Date(last).toISOString() } : {}),
241
+ deniedCount: this.deniedCount + (pluginActive ? (plugin?.deniedCount ?? 0) : 0),
242
+ source,
243
+ requestId,
244
+ lastPath,
245
+ };
246
+ }
247
+ if (this.recoveredAt !== null) {
248
+ return { status: 'ok', deniedCount: 0, source: this.lastSource, recoveredAt: new Date(this.recoveredAt).toISOString() };
249
+ }
250
+ return undefined;
251
+ }
252
+ /** Drain the queued transition events (called by the bridge's emitter). Also
253
+ * refreshes against the plugin file so a plugin-only transition is noticed
254
+ * even when the bridge made no webapp call of its own. */
255
+ takeEvents() {
256
+ this.refresh();
257
+ const out = this.pending;
258
+ this.pending = [];
259
+ return out;
260
+ }
261
+ pluginState(now) {
262
+ if (!this.pluginStatePath)
263
+ return null;
264
+ if (this.pluginCache && now - this.pluginCache.at < PLUGIN_STATE_READ_TTL_MS && now >= this.pluginCache.at) {
265
+ return this.pluginCache.value;
266
+ }
267
+ const value = readPluginEdgeState(this.pluginStatePath, now);
268
+ this.pluginCache = { at: now, value };
269
+ return value;
270
+ }
271
+ /** Compare the current verdict with the last emitted one; queue on change. */
272
+ refresh() {
273
+ // Force a fresh file read on a transition check so a plugin-side change
274
+ // is never masked by the 10 s cache.
275
+ this.pluginCache = null;
276
+ const h = this.health();
277
+ const denied = h?.status === 'edge_denied';
278
+ const now = this.now();
279
+ if (denied && !this.emittedDenied) {
280
+ this.emittedDenied = true;
281
+ this.emittedSince = h?.since ? Date.parse(h.since) : now;
282
+ this.recoveredAt = null;
283
+ this.pending.push({
284
+ event: 'webapp_edge_denied',
285
+ since: h?.since ?? new Date(now).toISOString(),
286
+ deniedCount: h?.deniedCount ?? 0,
287
+ source: h?.source ?? 'bridge',
288
+ requestId: h?.requestId ?? null,
289
+ lastPath: h?.lastPath ?? null,
290
+ timestamp: new Date(now).toISOString(),
291
+ });
292
+ }
293
+ else if (!denied && this.emittedDenied) {
294
+ this.emittedDenied = false;
295
+ this.recoveredAt = now;
296
+ this.pending.push({
297
+ event: 'webapp_edge_recovered',
298
+ since: new Date(this.emittedSince ?? now).toISOString(),
299
+ recoveredAt: new Date(now).toISOString(),
300
+ deniedCount: 0,
301
+ timestamp: new Date(now).toISOString(),
302
+ });
303
+ this.emittedSince = null;
304
+ }
305
+ }
306
+ }
307
+ // ---- process-wide singleton (the connector is single-tenant) ---------------------
308
+ let tracker = new WebappEdgeTracker();
309
+ export function webappEdgeTracker() {
310
+ return tracker;
311
+ }
312
+ /** Test-only: fresh tracker with injected clock / plugin file path. */
313
+ export function __resetWebappEdgeTrackerForTests(opts = {}) {
314
+ tracker = new WebappEdgeTracker(opts);
315
+ return tracker;
316
+ }
317
+ /** Inspect a webapp response on the shared tracker. Never throws. Returns the
318
+ * edge match (if any) so the caller can word its own log line. Pass
319
+ * `startedAt` (epoch ms before the request) so an in-flight success cannot
320
+ * end an episode that began after it was sent. */
321
+ export function noteWebappResponse(res, path, bodyText, startedAt) {
322
+ try {
323
+ if (res.ok) {
324
+ tracker.noteSuccess(startedAt);
325
+ return null;
326
+ }
327
+ const match = classifyEdgeDeny(res.status, res.headers, bodyText);
328
+ if (match)
329
+ tracker.noteDeny(path, match);
330
+ return match;
331
+ }
332
+ catch {
333
+ return null;
334
+ }
335
+ }
336
+ // ---- user agent ---------------------------------------------------------------------
337
+ let clientVersion = null;
338
+ /** Set once at boot from the installed bridge's package.json (index.ts). */
339
+ export function setWebappClientVersion(version) {
340
+ clientVersion = version && /^[0-9A-Za-z.+-]{1,40}$/.test(version) ? version : null;
341
+ }
342
+ export function webappUserAgent() {
343
+ return `reefclaw-connect/${clientVersion ?? 'unknown'} (openclaw-bridge)`;
344
+ }
345
+ /** Bearer + User-Agent for a webapp call. `extra` wins on key collision.
346
+ * Capitalised `Authorization` on purpose: the skill-pull test pins that key. */
347
+ export function webappHeaders(token, extra = {}) {
348
+ return {
349
+ Authorization: `Bearer ${token}`,
350
+ 'user-agent': webappUserAgent(),
351
+ ...extra,
352
+ };
353
+ }
354
+ /** Best-effort: the version stamped in the package.json beside the running
355
+ * entry (the installed bridge dir). Unknown → null; never throws. */
356
+ export function resolveBridgeVersion(entryPath = process.argv[1]) {
357
+ if (!entryPath)
358
+ return null;
359
+ try {
360
+ const raw = JSON.parse(readFileSync(join(dirname(entryPath), 'package.json'), 'utf-8'));
361
+ return typeof raw.version === 'string' && raw.version !== '0.1.0' ? raw.version : null;
362
+ }
363
+ catch {
364
+ return null;
365
+ }
366
+ }
@@ -18,6 +18,7 @@ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from '
18
18
  import { dirname, join } from 'node:path';
19
19
  import { homedir } from 'node:os';
20
20
  import { logger, formatError } from '../logger.js';
21
+ import { noteWebappResponse, webappHeaders } from '../http/webapp-edge.js';
21
22
  const TAG = 'agent-config';
22
23
  /** Shared four-stage ladder for the gates migrated so far. Kept as one set
23
24
  * because exitGate + positionReviewMode use identical values; a future gate
@@ -147,14 +148,29 @@ export async function fetchAgentConfig(opts) {
147
148
  const { apiBaseUrl, token, fetchImpl = fetch, timeoutMs = 10_000 } = opts;
148
149
  const url = `${apiBaseUrl.replace(/\/+$/, '')}/api/internal/config`;
149
150
  try {
151
+ const startedAt = Date.now();
150
152
  const res = await fetchImpl(url, {
151
- headers: { authorization: `Bearer ${token}` },
153
+ headers: webappHeaders(token),
152
154
  signal: AbortSignal.timeout(timeoutMs),
153
155
  });
154
156
  if (!res.ok) {
155
- logger.debug(TAG, `config fetch non-200: ${res.status}`);
157
+ // A 403 is classified on the shared edge gate: the edge firewall's
158
+ // plain-text Forbidden (IP-level block) vs the app's JSON denial. The
159
+ // gate logs the episode once; here we only tag the debug line.
160
+ let bodyText = null;
161
+ if (res.status === 403) {
162
+ try {
163
+ bodyText = (await res.text()).slice(0, 200);
164
+ }
165
+ catch {
166
+ /* body unreadable — classify on headers alone */
167
+ }
168
+ }
169
+ const edge = noteWebappResponse(res, '/api/internal/config', bodyText);
170
+ logger.debug(TAG, `config fetch non-200: ${res.status}${edge ? ' (edge firewall deny)' : ''}`);
156
171
  return null;
157
172
  }
173
+ noteWebappResponse(res, '/api/internal/config', undefined, startedAt);
158
174
  const body = (await res.json());
159
175
  const validated = validateAgentConfig(body);
160
176
  if (!validated)
@@ -21,6 +21,10 @@ export interface AgentConfigPollerOptions {
21
21
  fetchImpl?: typeof fetch;
22
22
  intervalMs?: number;
23
23
  cachePath?: string;
24
+ /** Fraction of the interval each tick may fire early (0 → exact cadence). */
25
+ jitter?: number;
26
+ /** Injectable RNG for deterministic tests. */
27
+ random?: () => number;
24
28
  }
25
29
  export interface AgentConfigPollerHandle {
26
30
  stop(): void;