@reefclaw/openclaw-plugin 0.1.45 → 0.1.48
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/bridge/bridge.d.ts +39 -0
- package/bridge/bridge.js +210 -7
- package/bridge/config.js +5 -2
- package/bridge/gateway/gateway-config.d.ts +5 -0
- package/bridge/gateway/gateway-config.js +5 -2
- package/bridge/gateway/heartbeat-cron.js +3 -2
- package/bridge/heartbeat-runs.d.ts +6 -0
- package/bridge/heartbeat-runs.js +45 -4
- package/bridge/heartbeat-transcript.d.ts +2 -0
- package/bridge/heartbeat-transcript.js +45 -13
- package/bridge/index.js +31 -0
- package/bridge/providers/connector-update.js +22 -5
- package/bridge/providers/emergency-commands.js +2 -3
- package/bridge/providers/gateway.d.ts +6 -0
- package/bridge/providers/gateway.js +57 -27
- package/bridge/providers/onboarding-commands.d.ts +8 -7
- package/bridge/setup.js +12 -0
- package/bridge/shock-wake.d.ts +7 -0
- package/bridge/shock-wake.js +72 -9
- package/bridge/types.d.ts +17 -0
- package/bridge/utils/base-url.d.ts +26 -0
- package/bridge/utils/base-url.js +108 -0
- package/bridge/utils/operator-secret.d.ts +7 -0
- package/bridge/utils/operator-secret.js +59 -0
- package/bridge/utils/relay-host.d.ts +23 -0
- package/bridge/utils/relay-host.js +66 -0
- package/bridge/utils/untrusted-text.d.ts +9 -0
- package/bridge/utils/untrusted-text.js +51 -0
- package/bridge/utils/webapp-edge.d.ts +145 -0
- package/bridge/utils/webapp-edge.js +366 -0
- package/config/agent-config-client.js +18 -2
- package/config/agent-config-poller.d.ts +4 -0
- package/config/agent-config-poller.js +46 -6
- package/config/base-url.d.ts +16 -0
- package/config/base-url.js +87 -0
- package/config/operator-provenance.d.ts +19 -0
- package/config/operator-provenance.js +102 -25
- package/config/user-data-stream-config.d.ts +5 -1
- package/config/user-data-stream-config.js +7 -5
- package/connector-supervisor.d.ts +15 -0
- package/connector-supervisor.js +22 -1
- package/http/webapp-edge.d.ts +116 -0
- package/http/webapp-edge.js +313 -0
- package/index.js +36 -24
- package/ingest/position-decisions-client.js +51 -11
- package/ingest/readiness-reporter.d.ts +13 -0
- package/ingest/readiness-reporter.js +78 -8
- package/ingest/retry-after.d.ts +5 -0
- package/ingest/retry-after.js +21 -0
- package/ingest/trade-store-client.js +43 -7
- package/lifecycle/process-role.d.ts +4 -0
- package/lifecycle/process-role.js +1 -1
- package/openclaw.plugin.json +1 -1
- package/package.json +2 -2
- package/release-integrity.json +10 -0
- package/release-notes.json +3 -1
- package/risk/pre-trade-check.js +1 -1
- package/risk/stop-widening-guard.d.ts +35 -0
- package/risk/stop-widening-guard.js +98 -0
- package/skills/reefclaw/SKILL.md +2 -2
- package/tools/create-order.js +17 -12
- package/tools/get-bracket-config.d.ts +3 -1
- package/tools/get-bracket-config.js +3 -1
- package/tools/get-market-intel.d.ts +4 -0
- package/tools/get-market-intel.js +38 -4
- package/tools/modify-stop.d.ts +6 -0
- package/tools/modify-stop.js +110 -0
- package/tools/set-bracket-requirement.d.ts +7 -0
- package/tools/set-bracket-requirement.js +12 -0
- package/trading-params-bounds.d.ts +32 -0
- package/trading-params-bounds.js +113 -0
- package/trading-params-cache.d.ts +9 -1
- package/trading-params-cache.js +33 -2
|
@@ -3,6 +3,8 @@
|
|
|
3
3
|
//
|
|
4
4
|
// Mirrors trade-store-client.ts retry semantics:
|
|
5
5
|
// - 2xx : success.
|
|
6
|
+
// - 429 : rate-limited by the ingest guard — retryable (bounded Retry-After
|
|
7
|
+
// on top of the backoff; review 2026-09-27).
|
|
6
8
|
// - 4xx : terminal — drop + log loudly (caller bug or duplicate).
|
|
7
9
|
// - 5xx / network : retry with exponential backoff up to maxAttempts.
|
|
8
10
|
//
|
|
@@ -13,6 +15,8 @@
|
|
|
13
15
|
//
|
|
14
16
|
// All four routes accept the same auth: Bearer + X-User-Id headers.
|
|
15
17
|
import { keepAliveFetch } from '../http/keepalive-fetch.js';
|
|
18
|
+
import { noteWebappResponse, webappEdgeGate, webappHeaders } from '../http/webapp-edge.js';
|
|
19
|
+
import { retryAfterMs, sleepMs } from './retry-after.js';
|
|
16
20
|
import { logger, formatError } from '../logger.js';
|
|
17
21
|
const TAG = 'position-decisions-client';
|
|
18
22
|
export class PositionDecisionsClient {
|
|
@@ -198,19 +202,24 @@ export class PositionDecisionsClient {
|
|
|
198
202
|
async runReturning(userId, path, body) {
|
|
199
203
|
const url = `${this.opts.baseUrl}${path}`;
|
|
200
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.
|
|
201
210
|
for (let attempt = 1; attempt <= this.opts.maxAttempts; attempt++) {
|
|
202
211
|
try {
|
|
203
212
|
const ac = new AbortController();
|
|
204
213
|
const tid = setTimeout(() => ac.abort(), this.opts.requestTimeoutMs);
|
|
205
214
|
let res;
|
|
215
|
+
const startedAt = Date.now();
|
|
206
216
|
try {
|
|
207
217
|
res = await this.opts.fetchImpl(url, {
|
|
208
218
|
method: 'POST',
|
|
209
|
-
headers: {
|
|
219
|
+
headers: webappHeaders(this.opts.ingestToken, {
|
|
210
220
|
'content-type': 'application/json',
|
|
211
|
-
authorization: `Bearer ${this.opts.ingestToken}`,
|
|
212
221
|
'x-user-id': userId,
|
|
213
|
-
},
|
|
222
|
+
}),
|
|
214
223
|
body: json,
|
|
215
224
|
signal: ac.signal,
|
|
216
225
|
});
|
|
@@ -220,6 +229,7 @@ export class PositionDecisionsClient {
|
|
|
220
229
|
}
|
|
221
230
|
if (res.status >= 200 && res.status < 300) {
|
|
222
231
|
this.totalSucceeded++;
|
|
232
|
+
noteWebappResponse(res, path, undefined, startedAt);
|
|
223
233
|
try {
|
|
224
234
|
return (await res.json());
|
|
225
235
|
}
|
|
@@ -227,7 +237,13 @@ export class PositionDecisionsClient {
|
|
|
227
237
|
return null;
|
|
228
238
|
}
|
|
229
239
|
}
|
|
230
|
-
if (res.status
|
|
240
|
+
if (res.status === 429) {
|
|
241
|
+
const wait = retryAfterMs(res.headers.get('retry-after'));
|
|
242
|
+
logger.warn(TAG, `POST ${url} → 429 rate-limited (attempt ${attempt}/${this.opts.maxAttempts})${wait ? `, Retry-After ${wait}ms` : ''}.`);
|
|
243
|
+
if (wait)
|
|
244
|
+
await sleepMs(wait);
|
|
245
|
+
}
|
|
246
|
+
else if (res.status >= 400 && res.status < 500) {
|
|
231
247
|
this.totalDroppedTerminal++;
|
|
232
248
|
let errBody = '';
|
|
233
249
|
try {
|
|
@@ -236,10 +252,18 @@ export class PositionDecisionsClient {
|
|
|
236
252
|
catch {
|
|
237
253
|
// ignore
|
|
238
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
|
+
}
|
|
239
261
|
logger.warn(TAG, `POST ${url} → ${res.status} (terminal, dropped). userId=${userId} body=${errBody.slice(0, 200)}`);
|
|
240
262
|
return null;
|
|
241
263
|
}
|
|
242
|
-
|
|
264
|
+
else {
|
|
265
|
+
logger.warn(TAG, `POST ${url} → ${res.status} (attempt ${attempt}/${this.opts.maxAttempts}).`);
|
|
266
|
+
}
|
|
243
267
|
}
|
|
244
268
|
catch (err) {
|
|
245
269
|
logger.warn(TAG, `POST ${url} threw (attempt ${attempt}/${this.opts.maxAttempts}): ${formatError(err)}`);
|
|
@@ -263,6 +287,10 @@ export class PositionDecisionsClient {
|
|
|
263
287
|
const maxAttempts = budget?.maxAttempts ??
|
|
264
288
|
Math.min(this.opts.maxAttempts, PositionDecisionsClient.READ_MAX_ATTEMPTS);
|
|
265
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
|
+
}
|
|
266
294
|
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
267
295
|
const remainingMs = deadlineAt - Date.now();
|
|
268
296
|
if (remainingMs <= 0)
|
|
@@ -271,13 +299,11 @@ export class PositionDecisionsClient {
|
|
|
271
299
|
const ac = new AbortController();
|
|
272
300
|
const tid = setTimeout(() => ac.abort(), Math.min(this.opts.requestTimeoutMs, remainingMs));
|
|
273
301
|
let res;
|
|
302
|
+
const startedAt = Date.now();
|
|
274
303
|
try {
|
|
275
304
|
res = await this.opts.fetchImpl(url, {
|
|
276
305
|
method: 'GET',
|
|
277
|
-
headers: {
|
|
278
|
-
authorization: `Bearer ${this.opts.ingestToken}`,
|
|
279
|
-
'x-user-id': userId,
|
|
280
|
-
},
|
|
306
|
+
headers: webappHeaders(this.opts.ingestToken, { 'x-user-id': userId }),
|
|
281
307
|
signal: ac.signal,
|
|
282
308
|
});
|
|
283
309
|
}
|
|
@@ -285,6 +311,7 @@ export class PositionDecisionsClient {
|
|
|
285
311
|
clearTimeout(tid);
|
|
286
312
|
}
|
|
287
313
|
if (res.status >= 200 && res.status < 300) {
|
|
314
|
+
noteWebappResponse(res, path, undefined, startedAt);
|
|
288
315
|
try {
|
|
289
316
|
return (await res.json());
|
|
290
317
|
}
|
|
@@ -292,7 +319,13 @@ export class PositionDecisionsClient {
|
|
|
292
319
|
return null;
|
|
293
320
|
}
|
|
294
321
|
}
|
|
295
|
-
if (res.status
|
|
322
|
+
if (res.status === 429) {
|
|
323
|
+
const wait = retryAfterMs(res.headers.get('retry-after'));
|
|
324
|
+
logger.warn(TAG, `GET ${url} → 429 rate-limited (attempt ${attempt}/${maxAttempts})${wait ? `, Retry-After ${wait}ms` : ''}.`);
|
|
325
|
+
if (wait)
|
|
326
|
+
await sleepMs(wait);
|
|
327
|
+
}
|
|
328
|
+
else if (res.status >= 400 && res.status < 500) {
|
|
296
329
|
let errBody = '';
|
|
297
330
|
try {
|
|
298
331
|
errBody = await res.text();
|
|
@@ -300,10 +333,17 @@ export class PositionDecisionsClient {
|
|
|
300
333
|
catch {
|
|
301
334
|
// ignore
|
|
302
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
|
+
}
|
|
303
341
|
logger.warn(TAG, `GET ${url} → ${res.status} (terminal, dropped). userId=${userId} body=${errBody.slice(0, 200)}`);
|
|
304
342
|
return null;
|
|
305
343
|
}
|
|
306
|
-
|
|
344
|
+
else {
|
|
345
|
+
logger.warn(TAG, `GET ${url} → ${res.status} (attempt ${attempt}/${maxAttempts}).`);
|
|
346
|
+
}
|
|
307
347
|
}
|
|
308
348
|
catch (err) {
|
|
309
349
|
logger.warn(TAG, `GET ${url} threw (attempt ${attempt}/${maxAttempts}): ${formatError(err)}`);
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { type ReadinessCheck, type ReadinessReport, type VenueId, type VenueReachabilityResult } from '@reefclaw/shared';
|
|
2
2
|
import type { InstallChannel } from '../plugin-version.js';
|
|
3
3
|
import type { PluginRuntimeIntegrity } from '../plugin-integrity.js';
|
|
4
|
+
import { type EdgeGateSnapshot } from '../http/webapp-edge.js';
|
|
4
5
|
/** Who froze the loop. 'unknown' when the kernel counter is unreadable (not
|
|
5
6
|
* Linux / no CONFIG_SCHEDSTATS / first cycle) — attribution is evidence, and
|
|
6
7
|
* absent evidence stays absent rather than defaulting to a blame. */
|
|
@@ -30,6 +31,16 @@ export interface StopProtectionSnapshot {
|
|
|
30
31
|
* branch by branch. Null snapshot → null (older wiring: omit the row rather
|
|
31
32
|
* than fabricate a verdict). */
|
|
32
33
|
export declare function stopProtectionCheck(snap: StopProtectionSnapshot | null, checkedAt: number): ReadinessCheck | null;
|
|
34
|
+
/** Fix hint for the `reefclaw_api_reachable` row. Assertive on purpose: the
|
|
35
|
+
* edge answered with its own header, so — like a 451 from Binance — this is
|
|
36
|
+
* reporting what the server said, not an inference. */
|
|
37
|
+
export declare const WEBAPP_EDGE_FIX_HINT: string;
|
|
38
|
+
/** Map the shared edge-gate snapshot to a readiness row. Pure. Blocked → fail;
|
|
39
|
+
* anything else → null (absent evidence stays absent — the row is omitted,
|
|
40
|
+
* never fabricated as a pass, and never a stale "warn" riding a POST that
|
|
41
|
+
* just succeeded). Built by hand rather than makeReadinessCheck because the
|
|
42
|
+
* id is newer than the shared copy map vendored on older boxes. */
|
|
43
|
+
export declare function webappApiCheck(snap: EdgeGateSnapshot, checkedAt: number): ReadinessCheck | null;
|
|
33
44
|
/** Cross-cycle memory for the debounced rungs. Held by the interval loop and
|
|
34
45
|
* passed in explicitly so `collectReadiness` stays a pure function of its
|
|
35
46
|
* inputs — a module-global counter would leak between unit tests. */
|
|
@@ -89,6 +100,8 @@ export declare function collectReadiness(opts: Pick<ReadinessReporterOptions, 'v
|
|
|
89
100
|
sampleHostStallMs?: () => number | null;
|
|
90
101
|
/** Injected for tests; production reads /proc/self/schedstat. */
|
|
91
102
|
sampleRunqueueWaitMs?: () => number | null;
|
|
103
|
+
/** Injected for tests; production reads the process-wide edge gate. */
|
|
104
|
+
webappEdgeSnapshot?: () => EdgeGateSnapshot;
|
|
92
105
|
}): Promise<ReadinessReport>;
|
|
93
106
|
/** Test-only — reset the singleton guard between unit tests. */
|
|
94
107
|
export declare function __resetReadinessReporterForTests(): void;
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
import { makeReadinessCheck, deriveOverallReadiness, GEO_BLOCK_FIX_HINT, HOST_STALL_FIX_HINT, } from '@reefclaw/shared';
|
|
12
12
|
import { logger, formatError } from '../logger.js';
|
|
13
13
|
import { startEventLoopMonitor, sampleEventLoopDelayMs, sampleRunqueueWaitMs, } from './event-loop-monitor.js';
|
|
14
|
+
import { noteWebappResponse, webappEdgeGate, webappHeaders, } from '../http/webapp-edge.js';
|
|
14
15
|
const TAG = 'readiness';
|
|
15
16
|
const DEFAULT_INTERVAL_MS = 300_000; // 5 min — geo/clock state changes rarely.
|
|
16
17
|
const MIN_INTERVAL_MS = 60_000;
|
|
@@ -85,6 +86,36 @@ export function stopProtectionCheck(snap, checkedAt) {
|
|
|
85
86
|
checkedAt,
|
|
86
87
|
});
|
|
87
88
|
}
|
|
89
|
+
/** Fix hint for the `reefclaw_api_reachable` row. Assertive on purpose: the
|
|
90
|
+
* edge answered with its own header, so — like a 451 from Binance — this is
|
|
91
|
+
* reporting what the server said, not an inference. */
|
|
92
|
+
export const WEBAPP_EDGE_FIX_HINT = "ReefClaw's edge protection is denying this host's IP (an automatic Vercel DDoS mitigation — not your account, token or anything on this machine). " +
|
|
93
|
+
'The agent keeps trading with its safety floor intact, but the position journal, central config and instruction updates pause until it lifts. ' +
|
|
94
|
+
'It usually clears within 30 minutes on its own; if it keeps coming back, email support@reefclaw.com with the time and your hosting provider so ReefClaw can add an allow rule.';
|
|
95
|
+
/** Map the shared edge-gate snapshot to a readiness row. Pure. Blocked → fail;
|
|
96
|
+
* anything else → null (absent evidence stays absent — the row is omitted,
|
|
97
|
+
* never fabricated as a pass, and never a stale "warn" riding a POST that
|
|
98
|
+
* just succeeded). Built by hand rather than makeReadinessCheck because the
|
|
99
|
+
* id is newer than the shared copy map vendored on older boxes. */
|
|
100
|
+
export function webappApiCheck(snap, checkedAt) {
|
|
101
|
+
if (!snap.blocked)
|
|
102
|
+
return null;
|
|
103
|
+
const since = snap.firstDeniedAt ? new Date(snap.firstDeniedAt).toISOString().slice(11, 16) + ' UTC' : '?';
|
|
104
|
+
const rid = snap.lastRequestId ? `, request ${snap.lastRequestId}` : '';
|
|
105
|
+
const base = {
|
|
106
|
+
id: 'reefclaw_api_reachable',
|
|
107
|
+
label: 'ReefClaw API reachable',
|
|
108
|
+
phase: 'connect',
|
|
109
|
+
checkedAt,
|
|
110
|
+
};
|
|
111
|
+
const left = snap.blockedUntil ? Math.max(1, Math.ceil((snap.blockedUntil - checkedAt) / 60_000)) : null;
|
|
112
|
+
return {
|
|
113
|
+
...base,
|
|
114
|
+
status: 'fail',
|
|
115
|
+
detail: `edge firewall 403 (${snap.lastAction ?? 'deny'}) since ${since}, ${snap.deniedCount} denied${rid}${left ? `; retrying in ${left} min` : ''}`,
|
|
116
|
+
fixHint: WEBAPP_EDGE_FIX_HINT,
|
|
117
|
+
};
|
|
118
|
+
}
|
|
88
119
|
export function createReadinessCycleState() {
|
|
89
120
|
return { consecutiveReachFailures: 0 };
|
|
90
121
|
}
|
|
@@ -126,6 +157,19 @@ export async function collectReadiness(opts, bootWarmup = false, deps = {}) {
|
|
|
126
157
|
detail: `${opts.toolCount} tools`,
|
|
127
158
|
checkedAt: now,
|
|
128
159
|
}));
|
|
160
|
+
// reefclaw_api_reachable — the shared edge gate's verdict on the webapp
|
|
161
|
+
// itself. Omitted while nothing has ever been denied. NOTE: when this row
|
|
162
|
+
// is 'fail' the report usually cannot be POSTed (the POST is what is being
|
|
163
|
+
// denied) — the connector carries the same episode over the relay
|
|
164
|
+
// (agent_state health.webappApi), which is how the dashboard learns of it.
|
|
165
|
+
try {
|
|
166
|
+
const edgeRow = webappApiCheck((deps.webappEdgeSnapshot ?? (() => webappEdgeGate().snapshot()))(), now);
|
|
167
|
+
if (edgeRow)
|
|
168
|
+
checks.push(edgeRow);
|
|
169
|
+
}
|
|
170
|
+
catch (err) {
|
|
171
|
+
logger.warn(TAG, `edge-gate snapshot failed (row omitted): ${formatError(err)}`);
|
|
172
|
+
}
|
|
129
173
|
// live_stop_protection — a local config/adapter read, no network. Resolved
|
|
130
174
|
// per cycle so a paper→live flip surfaces on the next report without a
|
|
131
175
|
// restart. Resolver failure → omit the row (absent evidence stays absent).
|
|
@@ -306,17 +350,30 @@ async function postReadiness(apiBaseUrl, token, report, fetchImpl, timeoutMs) {
|
|
|
306
350
|
const ac = new AbortController();
|
|
307
351
|
const tid = setTimeout(() => ac.abort(), timeoutMs);
|
|
308
352
|
try {
|
|
353
|
+
const startedAt = Date.now();
|
|
309
354
|
const res = await fetchImpl(url, {
|
|
310
355
|
method: 'POST',
|
|
311
|
-
headers: {
|
|
312
|
-
'content-type': 'application/json',
|
|
313
|
-
authorization: `Bearer ${token}`,
|
|
314
|
-
},
|
|
356
|
+
headers: webappHeaders(token, { 'content-type': 'application/json' }),
|
|
315
357
|
body: JSON.stringify(report),
|
|
316
358
|
signal: ac.signal,
|
|
317
359
|
});
|
|
318
360
|
if (res.status < 200 || res.status >= 300) {
|
|
319
|
-
|
|
361
|
+
let bodyText = null;
|
|
362
|
+
if (res.status === 403) {
|
|
363
|
+
try {
|
|
364
|
+
bodyText = (await res.text()).slice(0, 200);
|
|
365
|
+
}
|
|
366
|
+
catch {
|
|
367
|
+
/* classify on headers alone */
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
const edge = noteWebappResponse(res, '/api/internal/agent-readiness', bodyText);
|
|
371
|
+
// The gate logs the episode once at warn; repeats stay at debug.
|
|
372
|
+
const level = edge && webappEdgeGate().snapshot().deniedCount > 1 ? 'debug' : 'warn';
|
|
373
|
+
logger[level](TAG, `POST ${url} → ${res.status}${edge ? ` (edge firewall ${edge.action ?? 'deny'}${edge.requestId ? `, request ${edge.requestId}` : ''} — not an account problem)` : ''}`);
|
|
374
|
+
}
|
|
375
|
+
else {
|
|
376
|
+
noteWebappResponse(res, '/api/internal/agent-readiness', undefined, startedAt);
|
|
320
377
|
}
|
|
321
378
|
}
|
|
322
379
|
catch (err) {
|
|
@@ -364,10 +421,23 @@ export function startReadinessReporter(opts) {
|
|
|
364
421
|
installChannel: opts.installChannel,
|
|
365
422
|
runtime: opts.runtime,
|
|
366
423
|
}, bootWarmup, { state });
|
|
367
|
-
|
|
424
|
+
if (webappEdgeGate().isBlocked()) {
|
|
425
|
+
// Every POST during the block is another denied request feeding it.
|
|
426
|
+
// The gate reopens on its own (≤30 min); the next cycle re-probes.
|
|
427
|
+
logger.debug(TAG, `readiness POST skipped — webapp edge-denied (${Math.ceil(webappEdgeGate().msUntilOpen() / 60_000)} min left)`);
|
|
428
|
+
}
|
|
429
|
+
else {
|
|
430
|
+
await postReadiness(opts.apiBaseUrl, opts.token, report, fetchImpl, timeoutMs);
|
|
431
|
+
}
|
|
368
432
|
if (report.overall === 'fail') {
|
|
369
|
-
|
|
370
|
-
|
|
433
|
+
// The edge row is already logged (once) by the gate — repeating it
|
|
434
|
+
// every 5 min as "readiness FAIL" would alarm a customer for nothing.
|
|
435
|
+
const failing = report.checks
|
|
436
|
+
.filter((c) => c.status === 'fail' && c.id !== 'reefclaw_api_reachable')
|
|
437
|
+
.map((c) => c.id)
|
|
438
|
+
.join(', ');
|
|
439
|
+
if (failing)
|
|
440
|
+
logger.warn(TAG, `readiness FAIL: ${failing}`);
|
|
371
441
|
}
|
|
372
442
|
}
|
|
373
443
|
catch (err) {
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/** Retry-After in ms from a header value: delta-seconds only (an HTTP-date
|
|
2
|
+
* form is ignored → null). Bounded to [0, RETRY_AFTER_CAP_MS]. */
|
|
3
|
+
export declare const RETRY_AFTER_CAP_MS = 30000;
|
|
4
|
+
export declare function retryAfterMs(header: string | null | undefined): number | null;
|
|
5
|
+
export declare function sleepMs(ms: number): Promise<void>;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// Retry-After parsing for the webapp ingest clients.
|
|
2
|
+
//
|
|
3
|
+
// The webapp's /api/internal/* routes answer 429 with a per-tenant sliding
|
|
4
|
+
// window (webapp/src/lib/api/internal-guard.ts). A 429 is NOT a terminal 4xx:
|
|
5
|
+
// the request was well-formed and will succeed once the window moves, so the
|
|
6
|
+
// clients retry it — honouring Retry-After when present, bounded so a hostile
|
|
7
|
+
// or buggy header can never park a client for minutes (review 2026-09-27).
|
|
8
|
+
/** Retry-After in ms from a header value: delta-seconds only (an HTTP-date
|
|
9
|
+
* form is ignored → null). Bounded to [0, RETRY_AFTER_CAP_MS]. */
|
|
10
|
+
export const RETRY_AFTER_CAP_MS = 30_000;
|
|
11
|
+
export function retryAfterMs(header) {
|
|
12
|
+
if (typeof header !== 'string')
|
|
13
|
+
return null;
|
|
14
|
+
const t = header.trim();
|
|
15
|
+
if (!/^\d{1,6}$/.test(t))
|
|
16
|
+
return null;
|
|
17
|
+
return Math.min(Number(t) * 1000, RETRY_AFTER_CAP_MS);
|
|
18
|
+
}
|
|
19
|
+
export function sleepMs(ms) {
|
|
20
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
21
|
+
}
|
|
@@ -5,6 +5,10 @@
|
|
|
5
5
|
//
|
|
6
6
|
// - 2xx : success (including the implicit "no-op on conflict"
|
|
7
7
|
// that the upsert returns as 200 + ok:true).
|
|
8
|
+
// - 429 : rate-limited by the ingest guard — RETRYABLE (honours a
|
|
9
|
+
// bounded Retry-After on top of the backoff). A reconnect
|
|
10
|
+
// resync can burst a whole fetchMyTrades page; a terminal
|
|
11
|
+
// drop here was permanent audit-trail loss (review 2026-09-27).
|
|
8
12
|
// - 4xx (e.g. 400, 409) : terminal failure. Logged + dropped. Retrying
|
|
9
13
|
// won't help: either the payload is malformed or
|
|
10
14
|
// we're racing on a duplicate that's already
|
|
@@ -21,6 +25,8 @@
|
|
|
21
25
|
// background. In-flight requests are tracked so `drain()` can be awaited at
|
|
22
26
|
// shutdown to avoid losing the last fills before stop.
|
|
23
27
|
import { logger, formatError } from '../logger.js';
|
|
28
|
+
import { noteWebappResponse, webappEdgeGate, webappHeaders } from '../http/webapp-edge.js';
|
|
29
|
+
import { retryAfterMs, sleepMs } from './retry-after.js';
|
|
24
30
|
const TAG = 'trade-store-client';
|
|
25
31
|
export class TradeStoreClient {
|
|
26
32
|
opts;
|
|
@@ -70,19 +76,23 @@ export class TradeStoreClient {
|
|
|
70
76
|
async run(userId, fill) {
|
|
71
77
|
const url = `${this.opts.baseUrl}/api/internal/trades`;
|
|
72
78
|
const body = JSON.stringify(fill);
|
|
79
|
+
// Fill WRITES are never gated: the trades ledger has no other ingress
|
|
80
|
+
// (the gap filler only runs on a WS resync), a fill is a rare one-off
|
|
81
|
+
// call, and the ban may have lifted since the gate closed. If the edge
|
|
82
|
+
// still denies us, the 403 below drops the row exactly as before.
|
|
73
83
|
for (let attempt = 1; attempt <= this.opts.maxAttempts; attempt++) {
|
|
74
84
|
try {
|
|
75
85
|
const ac = new AbortController();
|
|
76
86
|
const tid = setTimeout(() => ac.abort(), this.opts.requestTimeoutMs);
|
|
77
87
|
let res;
|
|
88
|
+
const startedAt = Date.now();
|
|
78
89
|
try {
|
|
79
90
|
res = await this.opts.fetchImpl(url, {
|
|
80
91
|
method: 'POST',
|
|
81
|
-
headers: {
|
|
92
|
+
headers: webappHeaders(this.opts.ingestToken, {
|
|
82
93
|
'content-type': 'application/json',
|
|
83
|
-
authorization: `Bearer ${this.opts.ingestToken}`,
|
|
84
94
|
'x-user-id': userId,
|
|
85
|
-
},
|
|
95
|
+
}),
|
|
86
96
|
body,
|
|
87
97
|
signal: ac.signal,
|
|
88
98
|
});
|
|
@@ -92,17 +102,43 @@ export class TradeStoreClient {
|
|
|
92
102
|
}
|
|
93
103
|
if (res.status >= 200 && res.status < 300) {
|
|
94
104
|
this.totalSucceeded++;
|
|
105
|
+
noteWebappResponse(res, '/api/internal/trades', undefined, startedAt);
|
|
95
106
|
return;
|
|
96
107
|
}
|
|
97
|
-
if (res.status
|
|
108
|
+
if (res.status === 429) {
|
|
109
|
+
// Rate-limited (per-tenant window) — retryable, never terminal.
|
|
110
|
+
const wait = retryAfterMs(res.headers.get('retry-after'));
|
|
111
|
+
logger.warn(TAG, `POST ${url} → 429 rate-limited (attempt ${attempt}/${this.opts.maxAttempts})` +
|
|
112
|
+
`${wait ? `, Retry-After ${wait}ms` : ''}. tradeId=${fill.exchangeTradeId}`);
|
|
113
|
+
if (wait)
|
|
114
|
+
await sleepMs(wait);
|
|
115
|
+
}
|
|
116
|
+
else if (res.status >= 400 && res.status < 500) {
|
|
98
117
|
// Terminal — re-tries won't change the outcome. 409 is a duplicate
|
|
99
118
|
// (idempotency win); 400/401/404 are bugs we want logged loudly.
|
|
119
|
+
// A 403 from the EDGE (not the app) is named as such: it is the
|
|
120
|
+
// host being blocked, not a caller bug.
|
|
100
121
|
this.totalDroppedTerminal++;
|
|
101
|
-
|
|
122
|
+
let errBody = '';
|
|
123
|
+
if (res.status === 403) {
|
|
124
|
+
try {
|
|
125
|
+
errBody = (await res.text()).slice(0, 200);
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
// ignore
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
const edge = noteWebappResponse(res, '/api/internal/trades', errBody);
|
|
132
|
+
// The gate logs the episode once at warn; repeats stay at debug.
|
|
133
|
+
logger[edge && webappEdgeGate().snapshot().deniedCount > 1 ? 'debug' : 'warn'](TAG, edge
|
|
134
|
+
? `POST ${url} → 403 from the edge firewall (${edge.action ?? 'deny'}${edge.requestId ? `, request ${edge.requestId}` : ''}) — dropped; not an account/token problem. userId=${userId} tradeId=${fill.exchangeTradeId}`
|
|
135
|
+
: `POST ${url} → ${res.status} (terminal, dropped). userId=${userId} tradeId=${fill.exchangeTradeId}`);
|
|
102
136
|
return;
|
|
103
137
|
}
|
|
104
|
-
|
|
105
|
-
|
|
138
|
+
else {
|
|
139
|
+
// 5xx — fall through to retry.
|
|
140
|
+
logger.warn(TAG, `POST ${url} → ${res.status} (attempt ${attempt}/${this.opts.maxAttempts}).`);
|
|
141
|
+
}
|
|
106
142
|
}
|
|
107
143
|
catch (err) {
|
|
108
144
|
// Network error / abort. Retry.
|
|
@@ -21,6 +21,10 @@ export interface ProcessRuntimeRecord {
|
|
|
21
21
|
release: string | null;
|
|
22
22
|
/** Connector supervisor handle — started at most once per process. */
|
|
23
23
|
connectorSupervisor: unknown;
|
|
24
|
+
/** Per-boot operator-provenance secret minted for the supervised connector
|
|
25
|
+
* (config/operator-provenance.ts). In-memory only; null until a connector
|
|
26
|
+
* is spawned by this process. */
|
|
27
|
+
operatorSecret: string | null;
|
|
24
28
|
}
|
|
25
29
|
export declare function processRuntime(): ProcessRuntimeRecord;
|
|
26
30
|
/** Test-only. */
|
|
@@ -88,7 +88,7 @@ export function processRuntime() {
|
|
|
88
88
|
const g = globalThis;
|
|
89
89
|
let rec = g[RUNTIME_KEY];
|
|
90
90
|
if (!rec) {
|
|
91
|
-
rec = { initialised: false, toolsFactory: null, toolNames: [], release: null, connectorSupervisor: null };
|
|
91
|
+
rec = { initialised: false, toolsFactory: null, toolNames: [], release: null, connectorSupervisor: null, operatorSecret: null };
|
|
92
92
|
g[RUNTIME_KEY] = rec;
|
|
93
93
|
}
|
|
94
94
|
return rec;
|
package/openclaw.plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"id": "reefclaw-paper-trading",
|
|
3
3
|
"name": "ReefClaw Trading",
|
|
4
|
-
"version": "0.1.
|
|
4
|
+
"version": "0.1.48",
|
|
5
5
|
"description": "Supervised trading plugin for the ReefClaw dashboard. It runs on YOUR machine and starts in PAPER mode with no API keys. It cannot trade real funds until you supply exchange credentials and step PAPER→MICRO_LIVE→LIVE yourself from the dashboard — the agent cannot make that change (the tool is refused without operator provenance). Exchange keys stay local, are used only to sign requests to the exchange, and are never transmitted to ReefClaw (asserted by a test in this package). Trading telemetry — positions, fills, decision journal — is sent to ReefClaw to render the dashboard. Every live position carries exchange-native protective stops. Remote updates to the agent's trading instructions are applied only after an Ed25519 signature is verified against a public key pinned in this build. It runs on gateway startup and supervises a local connector process; the package README lists every path it writes and everything it sends. It never changes the gateway's auth settings.",
|
|
6
6
|
"author": "ReefClaw",
|
|
7
7
|
"activation": {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@reefclaw/openclaw-plugin",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.48",
|
|
4
4
|
"description": "ReefClaw supervised trading plugin for OpenClaw. Runs entirely on YOUR machine and starts in PAPER mode — it cannot trade real funds until you supply exchange credentials and walk the PAPER→MICRO_LIVE→LIVE ladder yourself from the ReefClaw dashboard (the agent cannot make that change; it is refused without operator provenance). Your exchange API keys stay on your machine to sign requests to the exchange and are NEVER sent to ReefClaw — a test in the package asserts this. What does reach ReefClaw is trading telemetry for the dashboard (positions, fills, decision journal). Live trading always carries exchange-native protective stops. Trading instructions can be updated remotely, and every update must carry a valid Ed25519 signature verified against a key pinned in this build before it is applied. Install from ClawHub on OpenClaw 2026.8.1+ (Control UI Plugins > Discover, or /plugins install clawhub:@reefclaw/openclaw-plugin then the same with --accept-capabilities after reviewing the listed capabilities), or with the ReefClaw connect installer (@reefclaw/connect on npm, pinned to the exact release named in the bundled skill). It runs on gateway startup, supervises a local connector process, and writes only under ~/.reefclaw and OpenClaw's own skill, config and cron locations; the README lists every path it writes and everything it sends. It never changes the gateway's auth settings.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "index.js",
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
"node": ">=20"
|
|
24
24
|
},
|
|
25
25
|
"dependencies": {
|
|
26
|
-
"@reefclaw/shared": "0.1.
|
|
26
|
+
"@reefclaw/shared": "0.1.5",
|
|
27
27
|
"ccxt": "4.5.37",
|
|
28
28
|
"json5": "2.2.3",
|
|
29
29
|
"ws": "8.21.1"
|
package/release-integrity.json
CHANGED
|
@@ -28,5 +28,15 @@
|
|
|
28
28
|
"index.js": "8fa4ed8df6122484ddb32159ba08e676fbdcd2febf203467b6aa9b6761ac27f9",
|
|
29
29
|
"tools/create-order.js": "b0244ff69cb5b4a44e18c7ceaf91669ee19649d0e6b18bb857aa47ca80f63b2a",
|
|
30
30
|
"risk/pre-trade-check.js": "15ba2c91e7a1f5ea03a2452eda40d489eda406a434e3bc3e9b7e024190f6a22f"
|
|
31
|
+
},
|
|
32
|
+
"0.1.45": {
|
|
33
|
+
"index.js": "833343d35aeecb17f77ebb23ab816abae8df9c0d1d2dbf6c0f0622e96d7cd5a1",
|
|
34
|
+
"tools/create-order.js": "b0244ff69cb5b4a44e18c7ceaf91669ee19649d0e6b18bb857aa47ca80f63b2a",
|
|
35
|
+
"risk/pre-trade-check.js": "15ba2c91e7a1f5ea03a2452eda40d489eda406a434e3bc3e9b7e024190f6a22f"
|
|
36
|
+
},
|
|
37
|
+
"0.1.47": {
|
|
38
|
+
"index.js": "47477ea63083abeb07c3088481acd723c0366a9170f6069a67a055362f61a878",
|
|
39
|
+
"tools/create-order.js": "3bf10b657b97fb67fa6a893822929d61ee164d169f6bedf5ec978263b3fb6847",
|
|
40
|
+
"risk/pre-trade-check.js": "5074ac12687d554f9c0a0aee611202aba9ecb4536e4632f8a5c76a5614ae0aad"
|
|
31
41
|
}
|
|
32
42
|
}
|
package/release-notes.json
CHANGED
|
@@ -16,5 +16,7 @@
|
|
|
16
16
|
"0.1.42": "Fixes a problem in 0.1.41 on OpenClaw 2026.9.6: the agent's own tool calls (heartbeats and chat) were answered with \"not available in this process\" instead of running, so the agent could not trade or move stops. The agent now always gets the live tools. On older OpenClaw the same thing could affect the first heartbeat after a restart; that is fixed too.",
|
|
17
17
|
"0.1.43": "Connector fixes. The ReefClaw heartbeat is now created even when your OpenClaw already has its own job named like a heartbeat (before, the connector could mistake that job for ours, so the agent's trading heartbeat never ran); a box affected by this repairs itself after updating. The trading instructions (SKILL.md) are re-applied correctly when an older copy is found, instead of failing on every reconnect.",
|
|
18
18
|
"0.1.44": "Heartbeats on a box without a chat channel (no Telegram etc.) are no longer recorded as errors: the heartbeat job is created without a chat delivery, existing jobs are repaired automatically, and a failed announcement no longer counts as a failed heartbeat. get_regime, get_crypto_metrics and get_market_intel now work when called without arguments (they default to your trading symbol / the overview category), which removes the rejected calls seen on OpenClaw 2026.9.",
|
|
19
|
-
"0.1.45": "Every market-data and analysis tool now works when called without a symbol (it uses your configured trading symbol), so agents on OpenClaw 2026.9 no longer waste calls on rejected arguments. Trading actions still require an explicit symbol. The heartbeat prompt no longer sends the agent looking for a checklist file that is not installed."
|
|
19
|
+
"0.1.45": "Every market-data and analysis tool now works when called without a symbol (it uses your configured trading symbol), so agents on OpenClaw 2026.9 no longer waste calls on rejected arguments. Trading actions still require an explicit symbol. The heartbeat prompt no longer sends the agent looking for a checklist file that is not installed.",
|
|
20
|
+
"0.1.47": "Security release (independent audit, 2026-09-27). The heartbeat recorder no longer uploads the output of file and shell tools and scrubs anything key-shaped from what it does record. Dashboard-only settings (trading mode, exchange credentials, the stop requirement) now require a secret the plugin hands to its own connector at start - nothing the agent can read or repeat; plugin and connector must be updated together, which this update does. While trading is live a new entry without a protective stop is refused whatever the settings say, and a stop can no longer be moved wider on a losing position. Risk limits fetched from the server are clamped to hardcoded bounds. The installer pins its runtime dependencies to exact, integrity-checked versions and no longer widens the OpenClaw sandbox allow-list. Market-intel text is fenced against prompt injection in more places, the connector refuses relay hosts outside ReefClaw's, and uploads that hit a rate limit are retried instead of dropped.",
|
|
21
|
+
"0.1.48": "Two changes. The heartbeat checklist (HEARTBEAT.md) now arrives with your trading instructions, signed, and is placed beside SKILL.md, so the agent reads it instead of failing every beat looking for a file that was never installed. And if ReefClaw's own edge protection ever blocks your host's address (an automatic DDoS mitigation, seen once on 2026-09-28), the plugin and connector now recognise it, back off instead of retrying into it, keep trading with the safety floor intact, and report it to the dashboard over the relay so you see a banner and support is paged; the log names the real cause instead of 'connect the account first' or 'Pro subscription required'. Periodic checks are spread out so several agents behind one address no longer call in lockstep. RC_WEBAPP_EDGE_GATE=off disables the back-off only."
|
|
20
22
|
}
|
package/risk/pre-trade-check.js
CHANGED
|
@@ -134,7 +134,7 @@ export function preTradeRiskCheck(order, portfolio, limits = DEFAULT_PRE_TRADE_L
|
|
|
134
134
|
if (requireStopLoss && (order.stopPrice === undefined || !(order.stopPrice > 0))) {
|
|
135
135
|
violations.push({
|
|
136
136
|
rule: 'requireStopLoss',
|
|
137
|
-
message: 'Live trades require a stopPrice
|
|
137
|
+
message: 'Live trades require a stopPrice — the protective-stop floor cannot be switched off while trading is live.',
|
|
138
138
|
current: 0,
|
|
139
139
|
limit: 1,
|
|
140
140
|
});
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
export interface StopWideningInput {
|
|
2
|
+
/** Entry side of the position: 'buy' = long, 'sell' = short. */
|
|
3
|
+
entrySide: 'buy' | 'sell';
|
|
4
|
+
entryPrice: number;
|
|
5
|
+
/** Current mark; undefined/null when unknown. */
|
|
6
|
+
markPrice: number | null | undefined;
|
|
7
|
+
/** Current protective stop; undefined/null when the position has none. */
|
|
8
|
+
oldStopPrice: number | null | undefined;
|
|
9
|
+
newStopPrice: number;
|
|
10
|
+
/** Position size in base units (contracts). */
|
|
11
|
+
quantity: number;
|
|
12
|
+
/** Mark-to-market account equity in quote units; null when unknown. */
|
|
13
|
+
equity: number | null;
|
|
14
|
+
/** Operator's absolute per-trade loss limit (trading param). */
|
|
15
|
+
maxPerTradeLoss: number;
|
|
16
|
+
/** Fraction of equity the floor caps a single trade's loss at. */
|
|
17
|
+
maxPerTradeLossPct: number;
|
|
18
|
+
}
|
|
19
|
+
export type StopWideningVerdict = {
|
|
20
|
+
ok: true;
|
|
21
|
+
widening: false;
|
|
22
|
+
} | {
|
|
23
|
+
ok: true;
|
|
24
|
+
widening: true;
|
|
25
|
+
lossAtStop: number;
|
|
26
|
+
cap: number;
|
|
27
|
+
} | {
|
|
28
|
+
ok: false;
|
|
29
|
+
code: 'risk_increase_on_loser' | 'loss_cap_exceeded' | 'inputs_unavailable';
|
|
30
|
+
error: string;
|
|
31
|
+
};
|
|
32
|
+
/** Loss (positive = money lost) if the stop at `stop` fires on a position
|
|
33
|
+
* entered at `entry`. Negative when the stop is beyond entry (locked profit). */
|
|
34
|
+
export declare function lossAtStop(entrySide: 'buy' | 'sell', entryPrice: number, stop: number, quantity: number): number;
|
|
35
|
+
export declare function evaluateStopWidening(input: StopWideningInput): StopWideningVerdict;
|