@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
@@ -15,9 +15,17 @@
15
15
  // multiple times per process and we must never spawn a second timer.
16
16
  import { defaultAgentConfig, fetchAgentConfig, isAcceptableVersion, readCachedConfig, writeCachedConfig, } from './agent-config-client.js';
17
17
  import { logger } from '../logger.js';
18
+ import { webappEdgeGate } from '../http/webapp-edge.js';
18
19
  const TAG = 'agent-config';
19
20
  const DEFAULT_POLL_MS = 60_000;
20
21
  const MIN_POLL_MS = 5_000;
22
+ /** Each tick fires up to this fraction EARLY (never late): several boxes behind
23
+ * one IP restarted together must not knock on the webapp in lockstep every
24
+ * 60 s — that synchronized pattern is what Vercel's DDoS heuristics read as
25
+ * an attack (2026-09-28). Early-only keeps the configured interval the
26
+ * maximum gap, so tests and operators can still reason about "at least one
27
+ * poll per interval". */
28
+ const DEFAULT_JITTER = 0.2;
21
29
  export function resolvePollIntervalMs() {
22
30
  const raw = Number(process.env.RC_AGENT_CONFIG_POLL_MS);
23
31
  if (!Number.isFinite(raw) || raw <= 0)
@@ -44,8 +52,11 @@ export function startAgentConfigPoller(opts) {
44
52
  }
45
53
  pollerStarted = true;
46
54
  const intervalMs = opts.intervalMs ?? resolvePollIntervalMs();
55
+ const jitter = Math.min(0.5, Math.max(0, opts.jitter ?? DEFAULT_JITTER));
56
+ const random = opts.random ?? Math.random;
47
57
  let current = defaultAgentConfig();
48
58
  let loggedFetchFailure = false;
59
+ let loggedEdgeSkip = false;
49
60
  const applyIfAcceptable = (fetched, source) => {
50
61
  if (!isAcceptableVersion(fetched, current)) {
51
62
  logger.warn(TAG, `rejected ${source} config v${fetched.version} < applied v${current.version} (rollback guard)`);
@@ -58,6 +69,17 @@ export function startAgentConfigPoller(opts) {
58
69
  return true;
59
70
  };
60
71
  const poll = async (isBoot) => {
72
+ // The edge firewall is denying this host: every poll would be another
73
+ // 403 feeding the block. Keep last-known-good and wait the gate out; the
74
+ // boot poll still runs (it is the one that seeds the cache fallback).
75
+ if (!isBoot && webappEdgeGate().isBlocked()) {
76
+ if (!loggedEdgeSkip) {
77
+ loggedEdgeSkip = true;
78
+ logger.info(TAG, `config polls paused — webapp edge-denied (${Math.ceil(webappEdgeGate().msUntilOpen() / 60_000)} min); keeping v${current.version}`);
79
+ }
80
+ return;
81
+ }
82
+ loggedEdgeSkip = false;
61
83
  const fetched = await fetchAgentConfig({
62
84
  apiBaseUrl: opts.apiBaseUrl,
63
85
  token: opts.token,
@@ -93,13 +115,31 @@ export function startAgentConfigPoller(opts) {
93
115
  }
94
116
  };
95
117
  void poll(true);
96
- const timer = setInterval(() => {
97
- void poll(false);
98
- }, intervalMs);
99
- timer.unref();
100
- logger.info(TAG, `poller started (interval ${Math.round(intervalMs / 1000)}s)`);
118
+ // Self-scheduling timeout (not setInterval) so each gap can be jittered
119
+ // early; the delay never exceeds intervalMs.
120
+ let timer = null;
121
+ let stopped = false;
122
+ const schedule = (elapsedMs = 0) => {
123
+ if (stopped)
124
+ return;
125
+ const early = intervalMs * jitter * Math.min(1, Math.max(0, random()));
126
+ // Measured from the START of the previous tick, so a slow fetch cannot
127
+ // push the next poll past the configured interval.
128
+ const delay = Math.max(1_000, Math.round(intervalMs - early - elapsedMs));
129
+ timer = setTimeout(() => {
130
+ const tickStart = Date.now();
131
+ void poll(false).finally(() => schedule(Date.now() - tickStart));
132
+ }, delay);
133
+ timer.unref();
134
+ };
135
+ schedule();
136
+ logger.info(TAG, `poller started (interval ${Math.round(intervalMs / 1000)}s, jitter ${Math.round(jitter * 100)}% early)`);
101
137
  return {
102
- stop: () => clearInterval(timer),
138
+ stop: () => {
139
+ stopped = true;
140
+ if (timer)
141
+ clearTimeout(timer);
142
+ },
103
143
  getCurrent: () => current,
104
144
  };
105
145
  }
@@ -0,0 +1,116 @@
1
+ export interface HeadersLike {
2
+ get(name: string): string | null;
3
+ }
4
+ export interface EdgeDenyMatch {
5
+ /** `vercel_mitigated` = the `x-vercel-mitigated` header was present (the
6
+ * definitive signal); `plain_forbidden` = a text/plain "Forbidden" body
7
+ * without the header (older/other edge shapes — still not our app). */
8
+ kind: 'vercel_mitigated' | 'plain_forbidden';
9
+ /** The mitigation action the edge reported (`deny`, `challenge`, …). */
10
+ action: string | null;
11
+ /** `x-vercel-id` — the request id Vercel support can look up. */
12
+ requestId: string | null;
13
+ }
14
+ /**
15
+ * Decide whether a 403 came from the edge rather than the webapp. Pure.
16
+ *
17
+ * The webapp's own 403s (entitlement walls, verifyProAccess) are JSON with an
18
+ * `error` field; authInternalRequest answers 401 JSON. The Vercel edge answers
19
+ * `403` with `content-type: text/plain`, a body that starts with "Forbidden"
20
+ * and the `x-vercel-mitigated` header. Anything else → null (not an edge deny).
21
+ */
22
+ export declare function classifyEdgeDeny(status: number, headers: HeadersLike | null | undefined, bodyText?: string | null): EdgeDenyMatch | null;
23
+ /** Kill-switch (repo convention: every new mechanism ships with one).
24
+ * `RC_WEBAPP_EDGE_GATE=off` disables the BRAKE only — no call is ever skipped
25
+ * or deferred — while detection, logging, the state file and the relay-borne
26
+ * health signal stay on. Read at call time; logged once. */
27
+ export declare function webappEdgeGateDisabled(): boolean;
28
+ export interface EdgeGateSnapshot {
29
+ blocked: boolean;
30
+ /** Epoch ms the gate reopens; null when open. */
31
+ blockedUntil: number | null;
32
+ /** First deny of the CURRENT episode (null once a success resets it). */
33
+ firstDeniedAt: number | null;
34
+ lastDeniedAt: number | null;
35
+ /** Denies in the current episode. */
36
+ deniedCount: number;
37
+ lastPath: string | null;
38
+ lastRequestId: string | null;
39
+ lastAction: string | null;
40
+ lastSuccessAt: number | null;
41
+ }
42
+ /** 5 → 10 → 20 → 30 min. The cap equals Vercel's persistent-action window: a
43
+ * host that stops knocking for a full window gives the block a chance to
44
+ * expire instead of feeding the pattern that armed it. */
45
+ export declare const DEFAULT_EDGE_BACKOFF_LADDER_MS: readonly number[];
46
+ export interface WebappEdgeGateOptions {
47
+ now?: () => number;
48
+ backoffLadderMs?: readonly number[];
49
+ /** Called on every state change (deny, success-after-deny). Used to persist
50
+ * the state file; errors inside are swallowed. */
51
+ onChange?: (snapshot: EdgeGateSnapshot) => void;
52
+ }
53
+ export declare class WebappEdgeGate {
54
+ private readonly now;
55
+ private readonly ladder;
56
+ private readonly onChange?;
57
+ private blockedUntil;
58
+ private firstDeniedAt;
59
+ private lastDeniedAt;
60
+ private deniedCount;
61
+ private step;
62
+ private lastPath;
63
+ private lastRequestId;
64
+ private lastAction;
65
+ private lastSuccessAt;
66
+ constructor(opts?: WebappEdgeGateOptions);
67
+ /** True while periodic webapp calls should be skipped. Always false under
68
+ * the kill-switch (the episode itself is still tracked). */
69
+ isBlocked(): boolean;
70
+ /** ms until the gate reopens (0 when open). */
71
+ msUntilOpen(): number;
72
+ /** Record an edge deny for `path`. Extends the block along the ladder and
73
+ * logs ONCE per episode at warn (every further deny is debug). */
74
+ noteDeny(rawPath: string, match: EdgeDenyMatch): void;
75
+ /** Record a successful webapp call. Ends the episode (logged once). */
76
+ noteSuccess(startedAt?: number): void;
77
+ snapshot(): EdgeGateSnapshot;
78
+ private emitChange;
79
+ }
80
+ /** The one sentence every client logs when the edge denies it — names the
81
+ * actual cause so nobody goes hunting for a token or subscription problem. */
82
+ export declare function edgeDenyMessage(match: EdgeDenyMatch, path: string, backoffMs: number): string;
83
+ export declare const WEBAPP_EDGE_STATE_FILENAME = "webapp-edge-state.json";
84
+ export declare function defaultWebappEdgeStatePath(): string;
85
+ export interface WebappEdgeStateFile extends EdgeGateSnapshot {
86
+ schemaVersion: 1;
87
+ updatedAt: number;
88
+ source: 'plugin';
89
+ }
90
+ /** Atomic write (tmp + rename, 0o600 — the plugin-config-io convention). Never
91
+ * throws: persistence is an observability aid, not a correctness requirement. */
92
+ export declare function writeWebappEdgeState(snapshot: EdgeGateSnapshot, path?: string): void;
93
+ /** The process-wide gate every webapp client consults. */
94
+ export declare function webappEdgeGate(): WebappEdgeGate;
95
+ /** Test-only: fresh gate, optional custom state path / clock. */
96
+ export declare function __resetWebappEdgeGateForTests(opts?: WebappEdgeGateOptions & {
97
+ statePath?: string;
98
+ }): WebappEdgeGate;
99
+ /**
100
+ * Inspect a webapp response on the shared gate. Success → episode over;
101
+ * 403 → classified (using `bodyText` when the caller already read it). Returns
102
+ * the match so the caller can word its own log line. Never throws.
103
+ */
104
+ export declare function noteWebappResponse(res: {
105
+ ok: boolean;
106
+ status: number;
107
+ headers: HeadersLike;
108
+ }, path: string, bodyText?: string | null,
109
+ /** Epoch ms taken BEFORE the request was sent — lets the gate ignore a
110
+ * success that was already in flight when the ban started. */
111
+ startedAt?: number): EdgeDenyMatch | null;
112
+ /** Set once at boot from the shipped manifest (plugin-version.ts). */
113
+ export declare function setWebappClientVersion(version: string | null | undefined): void;
114
+ export declare function webappUserAgent(): string;
115
+ /** Bearer + User-Agent for a webapp call. `extra` wins on key collision. */
116
+ export declare function webappHeaders(token: string, extra?: Record<string, string>): Record<string, string>;
@@ -0,0 +1,313 @@
1
+ // Edge-deny detection + backoff for the plugin's webapp (reefclaw.com) calls.
2
+ //
3
+ // Why (2026-09-28): Vercel's automatic DDoS mitigation ("System Mitigations",
4
+ // nothing the operator configured) put a rolling 30-minute Deny on the IP of a
5
+ // host running four OpenClaw boxes. Every plugin→webapp call answered
6
+ // `403 Forbidden` (plain text, `x-vercel-mitigated: deny`) while the relay kept
7
+ // working — so the dashboard showed Connected and all-green while the SKILL.md
8
+ // pull, central config, readiness, the position journal and the heartbeat
9
+ // recorder were all dead, and every client kept polling at full cadence
10
+ // through the ban. Worse, the clients read the 403 as "Pro subscription
11
+ // required" / "connect the account first": a firewall verdict reported as an
12
+ // account problem.
13
+ //
14
+ // This module gives every webapp client one shared verdict and one shared
15
+ // brake:
16
+ // • classifyEdgeDeny() — is this 403 the edge (Vercel) or the app? The app's
17
+ // own denials are JSON (`{error: …}`); the edge answers plain text with an
18
+ // `x-vercel-mitigated` header. Only the edge shape counts.
19
+ // • WebappEdgeGate — process-wide backoff (5 → 10 → 20 → 30 min, the
20
+ // 30-min cap matching Vercel's persistent-action window). Periodic callers
21
+ // skip their call while blocked; the gate reopens on its own and the next
22
+ // successful call resets it. Same shape as the Binance ban gate.
23
+ // • a state file (~/.reefclaw/webapp-edge-state.json) so the connector — the
24
+ // process that still reaches the dashboard over the relay — can surface
25
+ // the episode (agent_state health.webappApi) even though every HTTP path
26
+ // to the webapp is the thing being denied.
27
+ // • webappHeaders() — one place for the Bearer header + a real
28
+ // User-Agent (`reefclaw-plugin/<release>`), so our traffic is nameable in
29
+ // the edge's traffic view instead of showing up as "node".
30
+ //
31
+ // Everything here fails open: a missing state dir, an unreadable header, a
32
+ // classifier miss — nothing throws into a caller, and the gate never blocks
33
+ // anything but the plugin's OWN optional webapp traffic (never trading, never
34
+ // the safety floor, never the exchange).
35
+ import { existsSync, mkdirSync, renameSync, writeFileSync } from 'node:fs';
36
+ import { dirname, join } from 'node:path';
37
+ import { homedir } from 'node:os';
38
+ import { logger, formatError } from '../logger.js';
39
+ const TAG = 'webapp-edge';
40
+ /**
41
+ * Decide whether a 403 came from the edge rather than the webapp. Pure.
42
+ *
43
+ * The webapp's own 403s (entitlement walls, verifyProAccess) are JSON with an
44
+ * `error` field; authInternalRequest answers 401 JSON. The Vercel edge answers
45
+ * `403` with `content-type: text/plain`, a body that starts with "Forbidden"
46
+ * and the `x-vercel-mitigated` header. Anything else → null (not an edge deny).
47
+ */
48
+ export function classifyEdgeDeny(status, headers, bodyText) {
49
+ if (status !== 403)
50
+ return null;
51
+ const get = (name) => {
52
+ try {
53
+ return headers?.get(name) ?? null;
54
+ }
55
+ catch {
56
+ return null;
57
+ }
58
+ };
59
+ const mitigated = get('x-vercel-mitigated');
60
+ const requestId = get('x-vercel-id');
61
+ if (mitigated) {
62
+ return { kind: 'vercel_mitigated', action: mitigated.trim().toLowerCase() || null, requestId };
63
+ }
64
+ const contentType = (get('content-type') ?? '').toLowerCase();
65
+ const body = (bodyText ?? '').trimStart();
66
+ if (contentType.startsWith('text/plain') && /^forbidden\b/i.test(body)) {
67
+ return { kind: 'plain_forbidden', action: null, requestId };
68
+ }
69
+ return null;
70
+ }
71
+ /** Kill-switch (repo convention: every new mechanism ships with one).
72
+ * `RC_WEBAPP_EDGE_GATE=off` disables the BRAKE only — no call is ever skipped
73
+ * or deferred — while detection, logging, the state file and the relay-borne
74
+ * health signal stay on. Read at call time; logged once. */
75
+ export function webappEdgeGateDisabled() {
76
+ return (process.env.RC_WEBAPP_EDGE_GATE ?? 'on').trim().toLowerCase() === 'off';
77
+ }
78
+ let loggedDisabled = false;
79
+ function noteGateDisabled() {
80
+ if (loggedDisabled)
81
+ return;
82
+ loggedDisabled = true;
83
+ logger.info(TAG, 'backoff gate disabled by RC_WEBAPP_EDGE_GATE=off — edge denies are still detected and reported, but no call is skipped');
84
+ }
85
+ function stripQuery(path) {
86
+ const i = path.indexOf('?');
87
+ return i >= 0 ? path.slice(0, i) : path;
88
+ }
89
+ /** 5 → 10 → 20 → 30 min. The cap equals Vercel's persistent-action window: a
90
+ * host that stops knocking for a full window gives the block a chance to
91
+ * expire instead of feeding the pattern that armed it. */
92
+ export const DEFAULT_EDGE_BACKOFF_LADDER_MS = [
93
+ 5 * 60_000,
94
+ 10 * 60_000,
95
+ 20 * 60_000,
96
+ 30 * 60_000,
97
+ ];
98
+ export class WebappEdgeGate {
99
+ now;
100
+ ladder;
101
+ onChange;
102
+ blockedUntil = null;
103
+ firstDeniedAt = null;
104
+ lastDeniedAt = null;
105
+ deniedCount = 0;
106
+ step = 0;
107
+ lastPath = null;
108
+ lastRequestId = null;
109
+ lastAction = null;
110
+ lastSuccessAt = null;
111
+ constructor(opts = {}) {
112
+ this.now = opts.now ?? (() => Date.now());
113
+ this.ladder = opts.backoffLadderMs && opts.backoffLadderMs.length > 0
114
+ ? opts.backoffLadderMs
115
+ : DEFAULT_EDGE_BACKOFF_LADDER_MS;
116
+ this.onChange = opts.onChange;
117
+ }
118
+ /** True while periodic webapp calls should be skipped. Always false under
119
+ * the kill-switch (the episode itself is still tracked). */
120
+ isBlocked() {
121
+ const blocked = this.blockedUntil !== null && this.now() < this.blockedUntil;
122
+ if (blocked && webappEdgeGateDisabled()) {
123
+ noteGateDisabled();
124
+ return false;
125
+ }
126
+ return blocked;
127
+ }
128
+ /** ms until the gate reopens (0 when open). */
129
+ msUntilOpen() {
130
+ if (this.blockedUntil === null)
131
+ return 0;
132
+ return Math.max(0, this.blockedUntil - this.now());
133
+ }
134
+ /** Record an edge deny for `path`. Extends the block along the ladder and
135
+ * logs ONCE per episode at warn (every further deny is debug). */
136
+ noteDeny(rawPath, match) {
137
+ const now = this.now();
138
+ const path = stripQuery(rawPath);
139
+ const wasBlocked = this.isBlocked();
140
+ const backoff = this.ladder[Math.min(this.step, this.ladder.length - 1)];
141
+ // Only an UNBLOCKED deny climbs the ladder: four 403s arriving together
142
+ // at the start of a ban (config, readiness, journal, intel) are one event,
143
+ // not four — otherwise the first episode would jump straight to 30 min.
144
+ if (!wasBlocked) {
145
+ this.step += 1;
146
+ this.blockedUntil = now + backoff;
147
+ }
148
+ this.lastDeniedAt = now;
149
+ this.deniedCount += 1;
150
+ this.lastPath = path;
151
+ this.lastRequestId = match.requestId;
152
+ this.lastAction = match.action;
153
+ if (this.firstDeniedAt === null) {
154
+ this.firstDeniedAt = now;
155
+ logger.warn(TAG, edgeDenyMessage(match, path, backoff));
156
+ }
157
+ else if (!wasBlocked) {
158
+ logger.warn(TAG, `still denied by the webapp's edge firewall on ${path} (${this.deniedCount} denials since ` +
159
+ `${new Date(this.firstDeniedAt).toISOString()}) — pausing webapp calls for ${Math.round(backoff / 60_000)} min`);
160
+ }
161
+ else {
162
+ logger.debug(TAG, `edge deny on ${path} (${this.deniedCount} in episode)`);
163
+ }
164
+ this.emitChange();
165
+ }
166
+ /** Record a successful webapp call. Ends the episode (logged once). */
167
+ noteSuccess(startedAt) {
168
+ const now = this.now();
169
+ // A response that was already in flight when the ban started proves
170
+ // nothing about the ban: a success older than the last deny is ignored.
171
+ if (startedAt !== undefined && this.lastDeniedAt !== null && startedAt < this.lastDeniedAt) {
172
+ logger.debug(TAG, 'ignoring a success that started before the last edge deny');
173
+ return;
174
+ }
175
+ const hadEpisode = this.firstDeniedAt !== null;
176
+ const firstSuccess = this.lastSuccessAt === null;
177
+ this.lastSuccessAt = now;
178
+ if (!hadEpisode && this.blockedUntil === null) {
179
+ // First success of this process: rewrite the state file, so an episode
180
+ // left on disk by a previous gateway process cannot outlive it.
181
+ if (firstSuccess)
182
+ this.emitChange();
183
+ return;
184
+ }
185
+ if (hadEpisode) {
186
+ logger.info(TAG, `webapp reachable again after ${this.deniedCount} edge denials ` +
187
+ `(episode ${new Date(this.firstDeniedAt).toISOString()} → now) — resuming normal cadence`);
188
+ }
189
+ this.blockedUntil = null;
190
+ this.firstDeniedAt = null;
191
+ this.lastDeniedAt = null;
192
+ this.deniedCount = 0;
193
+ this.step = 0;
194
+ this.lastPath = null;
195
+ this.lastRequestId = null;
196
+ this.lastAction = null;
197
+ this.emitChange();
198
+ }
199
+ snapshot() {
200
+ return {
201
+ blocked: this.isBlocked(),
202
+ blockedUntil: this.blockedUntil,
203
+ firstDeniedAt: this.firstDeniedAt,
204
+ lastDeniedAt: this.lastDeniedAt,
205
+ deniedCount: this.deniedCount,
206
+ lastPath: this.lastPath,
207
+ lastRequestId: this.lastRequestId,
208
+ lastAction: this.lastAction,
209
+ lastSuccessAt: this.lastSuccessAt,
210
+ };
211
+ }
212
+ emitChange() {
213
+ if (!this.onChange)
214
+ return;
215
+ try {
216
+ this.onChange(this.snapshot());
217
+ }
218
+ catch (err) {
219
+ logger.debug(TAG, `onChange threw: ${formatError(err)}`);
220
+ }
221
+ }
222
+ }
223
+ /** The one sentence every client logs when the edge denies it — names the
224
+ * actual cause so nobody goes hunting for a token or subscription problem. */
225
+ export function edgeDenyMessage(match, path, backoffMs) {
226
+ const who = match.kind === 'vercel_mitigated' ? "ReefClaw's edge firewall" : 'a firewall in front of ReefClaw';
227
+ const via = match.kind === 'vercel_mitigated'
228
+ ? `Vercel edge mitigation '${match.action ?? 'deny'}'`
229
+ : 'plain-text Forbidden with no Vercel header — possibly a proxy on your side';
230
+ const rid = match.requestId ? `, request ${match.requestId}` : '';
231
+ return (`${path} denied by ${who} (${via}${rid}) — an IP-level block on this host, ` +
232
+ `NOT your account or token. Journal, central config and instruction updates pause until it lifts ` +
233
+ `(pausing webapp calls for ${Math.round(backoffMs / 60_000)} min); trading and the safety floor are unaffected. ` +
234
+ `If it persists, tell support@reefclaw.com the time and your hosting provider.`);
235
+ }
236
+ // ---- state file (read by the connector for the relay-borne health field) ----
237
+ export const WEBAPP_EDGE_STATE_FILENAME = 'webapp-edge-state.json';
238
+ export function defaultWebappEdgeStatePath() {
239
+ return join(homedir(), '.reefclaw', WEBAPP_EDGE_STATE_FILENAME);
240
+ }
241
+ /** Atomic write (tmp + rename, 0o600 — the plugin-config-io convention). Never
242
+ * throws: persistence is an observability aid, not a correctness requirement. */
243
+ export function writeWebappEdgeState(snapshot, path = defaultWebappEdgeStatePath()) {
244
+ try {
245
+ const dir = dirname(path);
246
+ if (!existsSync(dir))
247
+ mkdirSync(dir, { recursive: true });
248
+ const file = { schemaVersion: 1, updatedAt: Date.now(), source: 'plugin', ...snapshot };
249
+ const tmp = `${path}.${process.pid}.tmp`; // per-process: several runtimes may share the file
250
+ writeFileSync(tmp, JSON.stringify(file) + '\n', { encoding: 'utf-8', mode: 0o600 });
251
+ renameSync(tmp, path);
252
+ }
253
+ catch (err) {
254
+ logger.debug(TAG, `state file write failed: ${formatError(err)}`);
255
+ }
256
+ }
257
+ // ---- process-wide singleton ---------------------------------------------------
258
+ let statePath = defaultWebappEdgeStatePath();
259
+ let gate = new WebappEdgeGate({ onChange: (s) => writeWebappEdgeState(s, statePath) });
260
+ /** The process-wide gate every webapp client consults. */
261
+ export function webappEdgeGate() {
262
+ return gate;
263
+ }
264
+ /** Test-only: fresh gate, optional custom state path / clock. */
265
+ export function __resetWebappEdgeGateForTests(opts = {}) {
266
+ statePath = opts.statePath ?? defaultWebappEdgeStatePath();
267
+ gate = new WebappEdgeGate({
268
+ ...opts,
269
+ onChange: opts.onChange ?? ((s) => writeWebappEdgeState(s, statePath)),
270
+ });
271
+ return gate;
272
+ }
273
+ /**
274
+ * Inspect a webapp response on the shared gate. Success → episode over;
275
+ * 403 → classified (using `bodyText` when the caller already read it). Returns
276
+ * the match so the caller can word its own log line. Never throws.
277
+ */
278
+ export function noteWebappResponse(res, path, bodyText,
279
+ /** Epoch ms taken BEFORE the request was sent — lets the gate ignore a
280
+ * success that was already in flight when the ban started. */
281
+ startedAt) {
282
+ try {
283
+ if (res.ok) {
284
+ gate.noteSuccess(startedAt);
285
+ return null;
286
+ }
287
+ const match = classifyEdgeDeny(res.status, res.headers, bodyText);
288
+ if (match)
289
+ gate.noteDeny(path, match);
290
+ return match;
291
+ }
292
+ catch (err) {
293
+ logger.debug(TAG, `noteWebappResponse failed: ${formatError(err)}`);
294
+ return null;
295
+ }
296
+ }
297
+ // ---- headers / user agent ------------------------------------------------------
298
+ let clientVersion = null;
299
+ /** Set once at boot from the shipped manifest (plugin-version.ts). */
300
+ export function setWebappClientVersion(version) {
301
+ clientVersion = version && /^[0-9A-Za-z.+-]{1,40}$/.test(version) ? version : null;
302
+ }
303
+ export function webappUserAgent() {
304
+ return `reefclaw-plugin/${clientVersion ?? 'unknown'} (openclaw-plugin)`;
305
+ }
306
+ /** Bearer + User-Agent for a webapp call. `extra` wins on key collision. */
307
+ export function webappHeaders(token, extra = {}) {
308
+ return {
309
+ authorization: `Bearer ${token}`,
310
+ 'user-agent': webappUserAgent(),
311
+ ...extra,
312
+ };
313
+ }
package/index.js CHANGED
@@ -40,6 +40,7 @@ import { onStopWatcherClose } from './ingest/position-auto-capture.js';
40
40
  import { ReentryTracker } from './portfolio/reentry-tracker.js';
41
41
  import { startReadinessReporter } from './ingest/readiness-reporter.js';
42
42
  import { resolvePluginInstallFacts } from './plugin-version.js';
43
+ import { setWebappClientVersion } from './http/webapp-edge.js';
43
44
  import { processRuntime, resolveProcessRole } from './lifecycle/process-role.js';
44
45
  import { computePluginIntegrity, describePluginIntegrity } from './plugin-integrity.js';
45
46
  import { IntelMicrostructureAssembler } from './live/microstructure-assembler.js';
@@ -115,6 +116,7 @@ import { toggleStrategyTool } from './tools/toggle-strategy.js';
115
116
  import { getPatternScanTool } from './tools/get-pattern-scan.js';
116
117
  import { scanPairsTool } from './tools/scan-pairs.js';
117
118
  import { getSetupDetailTool } from './tools/get-setup-detail.js';
119
+ import { readAtr14FromFacts } from './tools/intel-cache.js';
118
120
  import { queryTradesTool } from './tools/query-trades.js';
119
121
  import { getAgentProfileTool } from './tools/get-agent-profile.js';
120
122
  import { getCvdTool } from './tools/get-cvd.js';
@@ -2367,6 +2369,9 @@ const paperTradingPlugin = {
2367
2369
  approvalMode: resolveApprovalMode(),
2368
2370
  wave9AdmissionGuard,
2369
2371
  wave9ActivationCheck: () => wave9ActivationClient.getActivation(),
2372
+ // 0.3×ATR term of the stop-distance floor, from the cached intel
2373
+ // fact (fail-open → 30 bps only). See assessment-validation.ts.
2374
+ readAtr14: (symbol) => readAtr14FromFacts(symbol, intelApiDeps),
2370
2375
  refreshPaperState: reloadState,
2371
2376
  wave9TradingModeCheck: () => runtime.mode,
2372
2377
  wave9VenueCheck: () => venue,
@@ -3065,6 +3070,8 @@ const paperTradingPlugin = {
3065
3070
  });
3066
3071
  logger.info(TAG, `Plugin release ${installFacts.version ?? 'unknown (no stamped manifest)'} via ${installFacts.channel}`);
3067
3072
  processRecord.release = installFacts.version ?? null;
3073
+ // Name our traffic at the webapp's edge (User-Agent reefclaw-plugin/<release>).
3074
+ setWebappClientVersion(installFacts.version ?? null);
3068
3075
  // What THIS process actually loaded — install-location CLASS (never the
3069
3076
  // path), process start, SHA-256 of the plugin's own order-path files —
3070
3077
  // captured once here at boot and carried on every readiness post. The
@@ -15,6 +15,7 @@
15
15
  //
16
16
  // All four routes accept the same auth: Bearer + X-User-Id headers.
17
17
  import { keepAliveFetch } from '../http/keepalive-fetch.js';
18
+ import { noteWebappResponse, webappEdgeGate, webappHeaders } from '../http/webapp-edge.js';
18
19
  import { retryAfterMs, sleepMs } from './retry-after.js';
19
20
  import { logger, formatError } from '../logger.js';
20
21
  const TAG = 'position-decisions-client';
@@ -201,19 +202,24 @@ export class PositionDecisionsClient {
201
202
  async runReturning(userId, path, body) {
202
203
  const url = `${this.opts.baseUrl}${path}`;
203
204
  const json = JSON.stringify(body);
205
+ // Journal WRITES are never gated: they are rare one-off calls that carry
206
+ // data with no other path to the dashboard (a skipped create-position
207
+ // would orphan every later review/close). If the edge is denying us the
208
+ // 403 below drops the row exactly as before — no extra traffic is saved
209
+ // by pre-empting it, and the ban may have lifted since the gate closed.
204
210
  for (let attempt = 1; attempt <= this.opts.maxAttempts; attempt++) {
205
211
  try {
206
212
  const ac = new AbortController();
207
213
  const tid = setTimeout(() => ac.abort(), this.opts.requestTimeoutMs);
208
214
  let res;
215
+ const startedAt = Date.now();
209
216
  try {
210
217
  res = await this.opts.fetchImpl(url, {
211
218
  method: 'POST',
212
- headers: {
219
+ headers: webappHeaders(this.opts.ingestToken, {
213
220
  'content-type': 'application/json',
214
- authorization: `Bearer ${this.opts.ingestToken}`,
215
221
  'x-user-id': userId,
216
- },
222
+ }),
217
223
  body: json,
218
224
  signal: ac.signal,
219
225
  });
@@ -223,6 +229,7 @@ export class PositionDecisionsClient {
223
229
  }
224
230
  if (res.status >= 200 && res.status < 300) {
225
231
  this.totalSucceeded++;
232
+ noteWebappResponse(res, path, undefined, startedAt);
226
233
  try {
227
234
  return (await res.json());
228
235
  }
@@ -245,6 +252,12 @@ export class PositionDecisionsClient {
245
252
  catch {
246
253
  // ignore
247
254
  }
255
+ const edge = noteWebappResponse(res, path, errBody);
256
+ if (edge) {
257
+ // The gate logs the episode once at warn; repeats stay at debug.
258
+ logger[webappEdgeGate().snapshot().deniedCount > 1 ? 'debug' : 'warn'](TAG, `POST ${url} → 403 from the edge firewall (${edge.action ?? 'deny'}${edge.requestId ? `, request ${edge.requestId}` : ''}) — dropped; not an account/token problem. userId=${userId}`);
259
+ return null;
260
+ }
248
261
  logger.warn(TAG, `POST ${url} → ${res.status} (terminal, dropped). userId=${userId} body=${errBody.slice(0, 200)}`);
249
262
  return null;
250
263
  }
@@ -274,6 +287,10 @@ export class PositionDecisionsClient {
274
287
  const maxAttempts = budget?.maxAttempts ??
275
288
  Math.min(this.opts.maxAttempts, PositionDecisionsClient.READ_MAX_ATTEMPTS);
276
289
  const deadlineAt = Date.now() + (budget?.deadlineMs ?? PositionDecisionsClient.READ_DEADLINE_MS);
290
+ if (webappEdgeGate().isBlocked()) {
291
+ logger.debug(TAG, `GET ${url} skipped — webapp edge-denied (${Math.ceil(webappEdgeGate().msUntilOpen() / 60_000)} min left)`);
292
+ return null;
293
+ }
277
294
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
278
295
  const remainingMs = deadlineAt - Date.now();
279
296
  if (remainingMs <= 0)
@@ -282,13 +299,11 @@ export class PositionDecisionsClient {
282
299
  const ac = new AbortController();
283
300
  const tid = setTimeout(() => ac.abort(), Math.min(this.opts.requestTimeoutMs, remainingMs));
284
301
  let res;
302
+ const startedAt = Date.now();
285
303
  try {
286
304
  res = await this.opts.fetchImpl(url, {
287
305
  method: 'GET',
288
- headers: {
289
- authorization: `Bearer ${this.opts.ingestToken}`,
290
- 'x-user-id': userId,
291
- },
306
+ headers: webappHeaders(this.opts.ingestToken, { 'x-user-id': userId }),
292
307
  signal: ac.signal,
293
308
  });
294
309
  }
@@ -296,6 +311,7 @@ export class PositionDecisionsClient {
296
311
  clearTimeout(tid);
297
312
  }
298
313
  if (res.status >= 200 && res.status < 300) {
314
+ noteWebappResponse(res, path, undefined, startedAt);
299
315
  try {
300
316
  return (await res.json());
301
317
  }
@@ -317,6 +333,11 @@ export class PositionDecisionsClient {
317
333
  catch {
318
334
  // ignore
319
335
  }
336
+ const edge = noteWebappResponse(res, path, errBody);
337
+ if (edge) {
338
+ logger[webappEdgeGate().snapshot().deniedCount > 1 ? 'debug' : 'warn'](TAG, `GET ${url} → 403 from the edge firewall (${edge.action ?? 'deny'}${edge.requestId ? `, request ${edge.requestId}` : ''}) — dropped; not an account/token problem. userId=${userId}`);
339
+ return null;
340
+ }
320
341
  logger.warn(TAG, `GET ${url} → ${res.status} (terminal, dropped). userId=${userId} body=${errBody.slice(0, 200)}`);
321
342
  return null;
322
343
  }