@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
@@ -45,8 +45,9 @@ export const HEARTBEAT_TIMEOUT_SECONDS = 780;
45
45
  // get_wave9_status, and the liquidity batch entirely (observed on prod
46
46
  // 2026-08-04 12:25/12:40 UTC): the checklist being in context is not enough,
47
47
  // the beat prompt itself must name what cannot be skipped.
48
- export const HEARTBEAT_MESSAGE = 'Heartbeat. If a HEARTBEAT.md checklist is in your context, execute EVERY checkbox in it; if not, the items below ARE ' +
49
- 'the checklist — do not go looking for the file, and do NOT re-read SKILL.md from disk unless preparing a NEW entry. ' +
48
+ export const HEARTBEAT_MESSAGE = 'Heartbeat. FIRST read the checklist file skills/reefclaw/HEARTBEAT.md (it sits beside your ReefClaw SKILL.md; one read call) ' +
49
+ 'and execute EVERY checkbox in it. If that read fails, the items below ARE the checklist — do not look anywhere else for it, ' +
50
+ 'and do NOT re-read SKILL.md from disk unless preparing a NEW entry. ' +
50
51
  'NON-SKIPPABLE every beat: (1) query_trades({hours:1}) stop-watcher reconcile; ' +
51
52
  '(2) get_wave9_status() once, unconditionally; ' +
52
53
  '(3) if ANY position is open and the Position Decision Journal is enabled (record_position_reviews reports off-mode when it is not): ' +
@@ -92,6 +93,17 @@ export function hasConfiguredChannels(cfg) {
92
93
  * delivery `announce` can only fail at run time, so switch it to `none`.
93
94
  * Runs on every bridge start (cheap: one cron.list), independent of the
94
95
  * once-per-install marker, because the job predates this fix on every box.
96
+ *
97
+ * ★ `cron.update` needs operator.admin, which the long-lived session holds
98
+ * only when the process started with the heartbeat ensure owed, so on a box
99
+ * with a marker this patch is refused and nothing changes. That is
100
+ * DELIBERATE (2026-09-29 review): the "no channel" signal
101
+ * (hasConfiguredChannels) reads only the top-level openclaw.json and
102
+ * misreads an env-only Telegram token, `$include`d channels and a moved
103
+ * config dir as "none". Widening the repair (an admin side-session was
104
+ * tried) would silently switch off heartbeat summaries that work today. A
105
+ * wider repair must key off the job's own recorded delivery failure, never
106
+ * this guess.
95
107
  */
96
108
  export async function reconcileHeartbeatDelivery(opts) {
97
109
  if (opts.channelsConfigured !== false)
@@ -179,6 +191,18 @@ function markerAdoptedForeignJob(markerPath) {
179
191
  return false;
180
192
  }
181
193
  }
194
+ /**
195
+ * Is the once-per-install ensure still owed on this box? True with no marker,
196
+ * and with a marker from the old rule that adopted a job that is not
197
+ * ReefClaw's (re-checked once). ensureHeartbeatCron runs exactly when this is
198
+ * true, and the bridge requests operator.admin exactly when this is true:
199
+ * both read this one function so they cannot drift. (They did: the re-check
200
+ * ran on a read/write-only session, so its cron.add failed on the scope and
201
+ * the adopted box kept getting no ReefClaw beat.)
202
+ */
203
+ export function heartbeatEnsureOwed(markerPath) {
204
+ return !existsSync(markerPath) || markerAdoptedForeignJob(markerPath);
205
+ }
182
206
  /**
183
207
  * Ensure a heartbeat cron exists. Non-fatal by contract: every failure path
184
208
  * returns 'failed' rather than throwing, and only success writes the marker so
@@ -208,7 +232,7 @@ export async function ensureHeartbeatCron(opts) {
208
232
  const agentId = opts.agentId?.trim().toLowerCase() || undefined;
209
233
  const agentIsDefault = opts.agentIsDefault ?? true;
210
234
  try {
211
- if (existsSync(markerPath) && !markerAdoptedForeignJob(markerPath))
235
+ if (!heartbeatEnsureOwed(markerPath))
212
236
  return 'already_ensured';
213
237
  // includeDisabled: a job the user disabled still means "exists" — re-adding
214
238
  // a duplicate next to a deliberately-disabled one is worse than doing nothing.
@@ -274,6 +298,21 @@ export async function ensureHeartbeatCron(opts) {
274
298
  `A heartbeat without it would run on the default agent, not '${agentId}'. Upgrade OpenClaw, or create the job yourself with the agent set.`);
275
299
  return 'failed';
276
300
  }
301
+ // The failed call may still have created the job (a timeout, a dropped
302
+ // socket). Look again before the retry so it can never add a second job
303
+ // beside it. No usable list = no retry: the next connect lists again and
304
+ // either finds the job or creates it.
305
+ const relist = (await rpc.sendRpc('cron.list', { includeDisabled: true }));
306
+ if (!Array.isArray(relist?.jobs)) {
307
+ log('Heartbeat cron: skipped (the add failed and cron.list returned no job list to check it against)');
308
+ return 'failed';
309
+ }
310
+ const landed = relist.jobs.find((j) => isReefclawHeartbeatJob(j) && cronJobBelongsToAgent(j, agentId, agentIsDefault));
311
+ if (landed) {
312
+ writeMarker(markerPath, { ensuredAt: new Date().toISOString(), created: HEARTBEAT_CRON_NAME, delivery: 'announce' });
313
+ log(`Heartbeat cron: created (${String(landed.name)}; the add reported an error but the job exists)`);
314
+ return 'created';
315
+ }
277
316
  log(`Heartbeat cron: announce delivery rejected (${addErr instanceof Error ? addErr.message.split('\n')[0] : String(addErr)}) — retrying without delivery`);
278
317
  try {
279
318
  await rpc.sendRpc('cron.add', { ...baseJob, delivery: { mode: 'none' } });
@@ -300,3 +339,114 @@ function writeMarker(markerPath, data) {
300
339
  mkdirSync(dirname(markerPath), { recursive: true });
301
340
  writeFileSync(markerPath, JSON.stringify(data, null, 2) + '\n', 'utf-8');
302
341
  }
342
+ /** How long a fresh install waits for the full trading instructions before
343
+ * starting its first market check. Past this, the first check is left to the
344
+ * regular schedule (one interval later), exactly as before. */
345
+ export const FIRST_BEAT_MAX_WAIT_MS = 120_000;
346
+ const FIRST_BEAT_POLL_MS = 5_000;
347
+ /**
348
+ * Start the FIRST market check right away on a fresh install instead of one
349
+ * full interval (15 min) after connecting.
350
+ *
351
+ * Why (2026-09-29): a new user connected, saw "You're connected", and then
352
+ * nothing happened for 15 minutes — the job's first run is scheduled one
353
+ * interval after creation. Call this ONLY when ensureHeartbeatCron returned
354
+ * 'created' (a brand-new job, once per install): it must never add beats to
355
+ * an existing agent.
356
+ *
357
+ * Rules:
358
+ * • Waits (≤ FIRST_BEAT_MAX_WAIT_MS) until the full trading SKILL.md is what
359
+ * the agent reads. A beat on the bootstrap instructions would be a wasted
360
+ * run; if they never arrive, the first check stays on the schedule (old
361
+ * behaviour).
362
+ * • `cron.run` needs operator.admin, which the bridge's session holds only
363
+ * when the process started with the ensure owed; call this with the client
364
+ * that created the job.
365
+ * • ONE cron.run call, never retried: a timeout or a dropped socket may
366
+ * still have started the run, and a second call would start a second beat.
367
+ * • Never throws; every failure leaves the regular schedule untouched.
368
+ */
369
+ export async function runFirstHeartbeat(opts) {
370
+ const maxWaitMs = opts.maxWaitMs ?? FIRST_BEAT_MAX_WAIT_MS;
371
+ const pollMs = Math.max(1, opts.pollMs ?? FIRST_BEAT_POLL_MS);
372
+ const sleep = opts.sleep ??
373
+ ((ms) => new Promise((resolve) => {
374
+ const t = setTimeout(resolve, ms);
375
+ t.unref?.();
376
+ }));
377
+ const ready = () => {
378
+ try {
379
+ return opts.instructionsReady();
380
+ }
381
+ catch {
382
+ return false;
383
+ }
384
+ };
385
+ const active = () => {
386
+ if (!opts.isActive)
387
+ return true;
388
+ try {
389
+ return opts.isActive();
390
+ }
391
+ catch {
392
+ return false;
393
+ }
394
+ };
395
+ const inactive = () => {
396
+ opts.log('Heartbeat cron: first market check not started (the gateway connection it was started on is gone) — it runs on the regular schedule');
397
+ return 'inactive';
398
+ };
399
+ const agentId = opts.agentId?.trim().toLowerCase() || undefined;
400
+ const agentIsDefault = opts.agentIsDefault ?? true;
401
+ try {
402
+ let waited = 0;
403
+ while (!ready() && waited < maxWaitMs) {
404
+ if (!active())
405
+ return inactive();
406
+ await sleep(pollMs);
407
+ waited += pollMs;
408
+ }
409
+ if (!ready()) {
410
+ opts.log('Heartbeat cron: first market check left to the regular schedule (the full trading instructions have not arrived yet)');
411
+ return 'not_ready';
412
+ }
413
+ if (!active())
414
+ return inactive();
415
+ const listResp = (await opts.rpc.sendRpc('cron.list', { includeDisabled: true }));
416
+ const jobs = Array.isArray(listResp?.jobs) ? listResp.jobs : [];
417
+ const job = jobs.find((j) => j?.name === HEARTBEAT_CRON_NAME && cronJobBelongsToAgent(j, agentId, agentIsDefault));
418
+ if (!job || typeof job.id !== 'string' || job.enabled === false) {
419
+ opts.log('Heartbeat cron: first market check not started (the new job is missing or disabled)');
420
+ return 'not_found';
421
+ }
422
+ if (!active())
423
+ return inactive();
424
+ let runResp;
425
+ try {
426
+ runResp = (await opts.rpc.sendRpc('cron.run', { id: job.id }));
427
+ }
428
+ catch (err) {
429
+ // Sent, but no answer we can trust: a timeout or a dropped socket may
430
+ // still have started the run. Report it as unknown (never retried).
431
+ opts.log(`Heartbeat cron: could not confirm the first market check started (${err instanceof Error ? err.message.split('\n')[0] : String(err)}) — if it did not, it runs on the regular schedule`);
432
+ return 'unknown';
433
+ }
434
+ // OpenClaw answers a run it did not start with ran:false + a reason
435
+ // instead of an error ('already-running' = a run is under way anyway).
436
+ if (runResp && typeof runResp === 'object' && (runResp.ran === false || runResp.ok === false)) {
437
+ const reason = typeof runResp.reason === 'string' && runResp.reason ? runResp.reason : 'no reason given';
438
+ if (reason === 'already-running') {
439
+ opts.log('Heartbeat cron: first market check already running');
440
+ return 'started';
441
+ }
442
+ opts.log(`Heartbeat cron: first market check not started now (${reason}) — it runs on the regular schedule`);
443
+ return 'not_run';
444
+ }
445
+ opts.log('Heartbeat cron: first market check started now (the next ones follow on the regular schedule)');
446
+ return 'started';
447
+ }
448
+ catch (err) {
449
+ opts.log(`Heartbeat cron: could not start the first market check now (${err instanceof Error ? err.message.split('\n')[0] : String(err)}) — it runs on the regular schedule`);
450
+ return 'failed';
451
+ }
452
+ }
@@ -20,6 +20,10 @@ export declare const BOOTSTRAP_LOOKBACK_MS: number;
20
20
  export declare const MAX_PER_SCAN = 5;
21
21
  /** Give up on a run after this many failed POST cycles. */
22
22
  export declare const MAX_POST_ATTEMPTS = 5;
23
+ /** While the bridge's edge gate is closed a record is DEFERRED (no attempt
24
+ * burned) rather than posted into the ban; this wall-clock cap bounds how
25
+ * long one record can wait before the normal attempt budget resumes. */
26
+ export declare const EDGE_DEFER_MAX_MS: number;
23
27
  /** Cool down `cron.runs` for this long after it errors (older gateway). */
24
28
  export declare const CRON_RUNS_COOLDOWN_MS: number;
25
29
  /** With nothing to read, ask `cron.runs` this often whether beats ran anyway
@@ -72,6 +76,8 @@ export declare class HeartbeatRunRecorder {
72
76
  private scanning;
73
77
  private stopped;
74
78
  private readonly attempts;
79
+ /** First time a record was DEFERRED behind the edge gate (EDGE_DEFER_MAX_MS). */
80
+ private readonly firstAttemptAt;
75
81
  private cronRunsUnavailableUntil;
76
82
  private probeLogged;
77
83
  private store;
@@ -26,6 +26,7 @@
26
26
  // the main session, whose transcript is one long file). Heartbeats only.
27
27
  import { logger } from './logger.js';
28
28
  import { resolveWebappBaseUrl } from './utils/base-url.js';
29
+ import { noteWebappResponse, webappEdgeTracker, webappUserAgent } from './utils/webapp-edge.js';
29
30
  import { buildHeartbeatRunRecord, describeTranscriptStore, isCronSessionKey, listAllSessionCandidates, readCandidateCronMarker, readSession, resolveAgentDbPath, resolveSessionsDir, shrinkRecord, } from './heartbeat-transcript.js';
30
31
  import { defaultStateFile, loadState, markRecorded, saveState } from './heartbeat-runs-state.js';
31
32
  const TAG = 'heartbeat-runs';
@@ -48,6 +49,10 @@ export const BOOTSTRAP_LOOKBACK_MS = 6 * 60 * 60_000;
48
49
  export const MAX_PER_SCAN = 5;
49
50
  /** Give up on a run after this many failed POST cycles. */
50
51
  export const MAX_POST_ATTEMPTS = 5;
52
+ /** While the bridge's edge gate is closed a record is DEFERRED (no attempt
53
+ * burned) rather than posted into the ban; this wall-clock cap bounds how
54
+ * long one record can wait before the normal attempt budget resumes. */
55
+ export const EDGE_DEFER_MAX_MS = 6 * 60 * 60_000;
51
56
  /** Cool down `cron.runs` for this long after it errors (older gateway). */
52
57
  export const CRON_RUNS_COOLDOWN_MS = 60 * 60_000;
53
58
  /** With nothing to read, ask `cron.runs` this often whether beats ran anyway
@@ -64,6 +69,8 @@ export class HeartbeatRunRecorder {
64
69
  scanning = false;
65
70
  stopped = false;
66
71
  attempts = new Map();
72
+ /** First time a record was DEFERRED behind the edge gate (EDGE_DEFER_MAX_MS). */
73
+ firstAttemptAt = new Map();
67
74
  cronRunsUnavailableUntil = 0;
68
75
  probeLogged = false;
69
76
  store = null;
@@ -175,6 +182,21 @@ export class HeartbeatRunRecorder {
175
182
  deferred++;
176
183
  continue;
177
184
  }
185
+ // Edge-denied host (the bridge's own backoff, skill/src/utils/
186
+ // webapp-edge.ts): posting would be one more 403 feeding the block
187
+ // and would burn an attempt. Defer without counting — and BEFORE the
188
+ // transcript is parsed, so a 6 h block does not re-parse the backlog
189
+ // every minute — bounded by EDGE_DEFER_MAX_MS so a record can never
190
+ // wait forever.
191
+ if (webappEdgeTracker().isBlocked()) {
192
+ const first = this.firstAttemptAt.get(c.sessionId) ?? now;
193
+ this.firstAttemptAt.set(c.sessionId, first);
194
+ if (now - first < EDGE_DEFER_MAX_MS) {
195
+ deferred++;
196
+ logger.debug(TAG, `POST deferred for ${c.sessionId.slice(0, 8)} — webapp edge-denied (${Math.ceil(webappEdgeTracker().msUntilOpen() / 60_000)} min left)`);
197
+ continue;
198
+ }
199
+ }
178
200
  const parsed = readSession(c);
179
201
  if (!parsed) {
180
202
  deferred++;
@@ -212,6 +234,7 @@ export class HeartbeatRunRecorder {
212
234
  this.stats.recorded++;
213
235
  markRecorded(state, c.sessionId);
214
236
  this.attempts.delete(c.sessionId);
237
+ this.firstAttemptAt.delete(c.sessionId);
215
238
  dirty = true;
216
239
  logger.info(TAG, `Heartbeat run recorded: ${c.sessionId.slice(0, 8)} status=${record.status} tools=${record.toolCallCount}` +
217
240
  ` (${record.toolErrorCount} err) tokens=${record.tokens.total ?? 'n/a'}/${record.tokens.source}` +
@@ -224,6 +247,7 @@ export class HeartbeatRunRecorder {
224
247
  if (outcome.terminal || n >= MAX_POST_ATTEMPTS) {
225
248
  markRecorded(state, c.sessionId);
226
249
  this.attempts.delete(c.sessionId);
250
+ this.firstAttemptAt.delete(c.sessionId);
227
251
  dirty = true;
228
252
  logger.warn(TAG, `Heartbeat run ${c.sessionId.slice(0, 8)} NOT persisted (${outcome.terminal ? 'rejected' : 'gave up'}: ` +
229
253
  `${outcome.status ?? 'network'} ${outcome.error ?? ''}) — shown on the dashboard, not in the journal`);
@@ -322,17 +346,21 @@ export class HeartbeatRunRecorder {
322
346
  const base = resolveWebappBaseUrl(this.opts.webappUrl);
323
347
  const fetchImpl = this.opts.fetchImpl ?? fetch;
324
348
  try {
349
+ const startedAt = Date.now();
325
350
  const res = await fetchImpl(`${base}/api/internal/heartbeat-runs`, {
326
351
  method: 'POST',
327
352
  headers: {
328
353
  'content-type': 'application/json',
329
354
  authorization: `Bearer ${this.opts.token}`,
355
+ 'user-agent': webappUserAgent(),
330
356
  },
331
357
  body: JSON.stringify(record),
332
358
  signal: AbortSignal.timeout(15_000),
333
359
  });
334
- if (res.ok)
360
+ if (res.ok) {
361
+ noteWebappResponse(res, '/api/internal/heartbeat-runs', undefined, startedAt);
335
362
  return { ok: true, terminal: false, status: res.status };
363
+ }
336
364
  let text = '';
337
365
  try {
338
366
  text = (await res.text()).slice(0, 200);
@@ -340,6 +368,20 @@ export class HeartbeatRunRecorder {
340
368
  catch {
341
369
  /* ignore */
342
370
  }
371
+ // A 403 from the EDGE (Vercel mitigation on this host's IP) is not a
372
+ // rejection of the record: it stays queued. Later scans DEFER it while
373
+ // the bridge's edge gate is closed (no attempt burned, bounded by
374
+ // EDGE_DEFER_MAX_MS wall-clock) and retry once the gate reopens; the
375
+ // usual MAX_POST_ATTEMPTS budget then applies. A real 4xx stays terminal.
376
+ const edge = noteWebappResponse(res, '/api/internal/heartbeat-runs', text);
377
+ if (edge) {
378
+ return {
379
+ ok: false,
380
+ terminal: false,
381
+ status: res.status,
382
+ error: `edge firewall ${edge.action ?? 'deny'}${edge.requestId ? ` (request ${edge.requestId})` : ''} — retried once the block lifts`,
383
+ };
384
+ }
343
385
  return { ok: false, terminal: res.status >= 400 && res.status < 500, status: res.status, error: text };
344
386
  }
345
387
  catch (err) {
package/bridge/index.js CHANGED
@@ -20,6 +20,7 @@ import { resolveGatewayConfig, validateGatewayConfig } from './gateway/gateway-c
20
20
  import { ShockWakePoller } from './shock-wake.js';
21
21
  import { HeartbeatRunRecorder } from './heartbeat-runs.js';
22
22
  import { runSetup } from './setup.js';
23
+ import { resolveBridgeVersion, setWebappClientVersion } from './utils/webapp-edge.js';
23
24
  import { resolveRelayInstanceId } from './utils/instance-id.js';
24
25
  import { readOperatorSecretFromStdin } from './utils/operator-secret.js';
25
26
  const TAG = 'main';
@@ -276,6 +277,8 @@ async function main() {
276
277
  // same-box restart (instant takeover) vs a second box (rejected 4011).
277
278
  instanceId: resolveRelayInstanceId(),
278
279
  };
280
+ // Name our traffic at the webapp's edge (User-Agent reefclaw-connect/<version>).
281
+ setWebappClientVersion(resolveBridgeVersion());
279
282
  const bridge = new Bridge(provider, connectorConfig, bridgePaths);
280
283
  // Shock-wake poller (WS3, docs/MARKET_ADAPTIVITY_PLAN.md) — watches intel's
281
284
  // /api/shocks (the WS2 change-of-character flags) and delivers an
@@ -152,6 +152,18 @@ export interface OpenClawProvider {
152
152
  received: boolean;
153
153
  error?: string;
154
154
  }>;
155
+ /**
156
+ * Hold the bridge's "instructions updated" chat notice while this install's
157
+ * FIRST market check is pending (the heartbeat job was just created and the
158
+ * early run has not started or given up yet): that check reads the new
159
+ * instructions itself, and the notice would be a second agent turn at the
160
+ * same moment. Returns true when the notice was taken (the provider calls
161
+ * `send` if the first check ends without starting, on the next connect if
162
+ * the socket is down at that moment; the latest call wins), false when
163
+ * nothing is pending and the caller should send it now. Absent = never
164
+ * pending.
165
+ */
166
+ deferToFirstMarketCheck?(send: () => void): boolean;
155
167
  /** Close a specific position by symbol (non-emergency, single-symbol close) */
156
168
  closePosition(symbol: string): Promise<{
157
169
  closed: boolean;
@@ -57,6 +57,7 @@
57
57
  // as any reinstall would. Self-hosters carrying patches: switch it off.
58
58
  import { logger } from '../logger.js';
59
59
  import { resolveWebappBaseUrl } from '../utils/base-url.js';
60
+ import { noteWebappResponse } from '../utils/webapp-edge.js';
60
61
  const TAG = 'connector-update';
61
62
  /** The npm package the update runs. Fixed. */
62
63
  export const CONNECT_PACKAGE = '@reefclaw/connect';
@@ -116,9 +117,26 @@ export async function fetchPinnedConnectVersion(opts) {
116
117
  const base = resolveWebappBaseUrl(opts.webappUrl);
117
118
  try {
118
119
  const doFetch = opts.fetchImpl ?? fetch;
120
+ // No headers at all on purpose: this is the PUBLIC endpoint and a test
121
+ // pins that no credential (or anything else) rides along.
122
+ const startedAt = Date.now();
119
123
  const res = await doFetch(`${base}/api/release`, { signal: AbortSignal.timeout(15_000) });
120
- if (!res.ok)
121
- return refuse(`ReefClaw answered HTTP ${res.status}`);
124
+ if (!res.ok) {
125
+ let text = '';
126
+ if (res.status === 403) {
127
+ try {
128
+ text = (await res.text()).slice(0, 200);
129
+ }
130
+ catch {
131
+ /* classify on headers alone */
132
+ }
133
+ }
134
+ const edge = noteWebappResponse(res, '/api/release', text);
135
+ return refuse(edge
136
+ ? `ReefClaw's edge firewall denied this host (HTTP 403 ${edge.action ?? 'deny'}${edge.requestId ? `, request ${edge.requestId}` : ''}) — an IP-level block, not a version problem; retry once it lifts`
137
+ : `ReefClaw answered HTTP ${res.status}`);
138
+ }
139
+ noteWebappResponse(res, '/api/release', undefined, startedAt);
122
140
  const body = (await res.json());
123
141
  const version = body?.connectVersion;
124
142
  if (!isExactConnectVersion(version))
@@ -54,6 +54,13 @@ export declare class GatewayProvider implements OpenClawProvider {
54
54
  private agentNameReadAtMs;
55
55
  /** One-shot latch for the boot-time heartbeat-cron ensure (re-armed on failure). */
56
56
  private heartbeatCronEnsureStarted;
57
+ /** Whether this install's FIRST market check may still run early:
58
+ * 'maybe' while the ensure is in flight, 'pending' from 'created' until
59
+ * runFirstHeartbeat settles, 'none' otherwise (deferToFirstMarketCheck). */
60
+ private firstBeatState;
61
+ /** The bridge's "instructions updated" notice, held while a first check is
62
+ * possible; sent only if that check does not start. Latest wins. */
63
+ private deferredSkillNotice;
57
64
  /** Live heartbeat cadence (seconds), read from the OpenClaw cron store; cached 60s. */
58
65
  private heartbeatSeconds?;
59
66
  private heartbeatReadAtMs;
@@ -230,6 +237,20 @@ export declare class GatewayProvider implements OpenClawProvider {
230
237
  received: boolean;
231
238
  error?: string;
232
239
  }>;
240
+ /** See OpenClawProvider.deferToFirstMarketCheck. Held while this install's
241
+ * first market check may still run early, or while an earlier held notice
242
+ * waits for the socket to come back; the latest notice wins. */
243
+ deferToFirstMarketCheck(send: () => void): boolean;
244
+ /** The first market check is settled: send a held notice ('send') or drop
245
+ * it ('drop': the check started, or may have, and reads the new
246
+ * instructions itself). A stopped provider sends nothing. If the socket is
247
+ * down right now (the settle may be BECAUSE it dropped), the notice stays
248
+ * held and goes out on the next connect (flushHeldSkillNotice) instead of
249
+ * being lost. */
250
+ private settleFirstBeat;
251
+ /** Send a held notice once nothing is pending any more (settle, or the next
252
+ * connect after a settle that found the socket down). */
253
+ private flushHeldSkillNotice;
233
254
  closePosition(symbol: string): Promise<{
234
255
  closed: boolean;
235
256
  symbol: string;
@@ -1,7 +1,7 @@
1
1
  // GatewayProvider — real OpenClaw gateway integration.
2
2
  // Connects to the OpenClaw gateway via HTTP and WebSocket,
3
3
  // streams live trading data, and emits ProviderEvents.
4
- import { existsSync, readFileSync, writeFileSync, mkdirSync, unlinkSync } from 'fs';
4
+ import { readFileSync, writeFileSync, mkdirSync, unlinkSync } from 'fs';
5
5
  import { join } from 'path';
6
6
  import { homedir } from 'os';
7
7
  import { logger, formatError } from '../logger.js';
@@ -16,7 +16,8 @@ import { GatewayWsClient } from '../gateway/gateway-ws-client.js';
16
16
  import { discoverTools } from '../gateway/tool-discovery.js';
17
17
  import { EventParser, mapCcxtBalance, mapCcxtOrder, extractLiquidationFields, extractBracketField, extractPlannedLevels, } from '../gateway/event-parser.js';
18
18
  import { Poller } from '../gateway/poller.js';
19
- import { ensureHeartbeatCron, hasConfiguredChannels, pickHeartbeatJob, reconcileHeartbeatDelivery } from '../gateway/heartbeat-cron.js';
19
+ import { readLocalSkillVersion, readAgentVisibleSkillVersions, isBootstrapSkillVersion } from '../utils/skill-version.js';
20
+ import { ensureHeartbeatCron, hasConfiguredChannels, heartbeatEnsureOwed, pickHeartbeatJob, reconcileHeartbeatDelivery, runFirstHeartbeat, } from '../gateway/heartbeat-cron.js';
20
21
  import { readOpenClawConfigFile } from '../gateway/gateway-config.js';
21
22
  import { parseIdentityName } from '../utils/identity-name.js';
22
23
  import { assessDrawdownPlausibility, computeEquity as _computeEquity, computePositionNotional as _computePositionNotional, computeRiskMetrics as _computeRiskMetrics, DEFAULT_RISK_LIMITS, DRAWDOWN_ZONE_THRESHOLDS, TENANT_LIMIT_BOUNDS, boundedNum, validateDrawdownLadder, } from './risk-calculator.js';
@@ -25,6 +26,7 @@ import { executeSetTradingMode, executeGetBracketConfig, executeSetBracketRequir
25
26
  import { startConnectorUpdate, runConnectorUpdate, fetchPinnedConnectVersion, openAdminGatewaySession, checkPositionGuard, describeUpdateDisabled, requestGatewayRestart, RESTART_REASON_OPERATOR, } from './connector-update.js';
26
27
  import { isInsideContainer, readContainerProbe, runDirectConnectorUpdate } from './connector-update-direct.js';
27
28
  import { DEFAULT_AGENT_ID, isForeignAgentEvent, resolveAgentEventOwner } from '../gateway/agent-scope.js';
29
+ import { noteWebappResponse, webappEdgeTracker, webappHeaders } from '../utils/webapp-edge.js';
28
30
  const TAG = 'gateway';
29
31
  // ---- Day-start NAV persistence ----
30
32
  // Persists sessionStartNav (the UTC-day P&L anchor) per date so Day P&L
@@ -185,6 +187,13 @@ export class GatewayProvider {
185
187
  agentNameReadAtMs = 0;
186
188
  /** One-shot latch for the boot-time heartbeat-cron ensure (re-armed on failure). */
187
189
  heartbeatCronEnsureStarted = false;
190
+ /** Whether this install's FIRST market check may still run early:
191
+ * 'maybe' while the ensure is in flight, 'pending' from 'created' until
192
+ * runFirstHeartbeat settles, 'none' otherwise (deferToFirstMarketCheck). */
193
+ firstBeatState = 'none';
194
+ /** The bridge's "instructions updated" notice, held while a first check is
195
+ * possible; sent only if that check does not start. Latest wins. */
196
+ deferredSkillNotice = null;
188
197
  /** Live heartbeat cadence (seconds), read from the OpenClaw cron store; cached 60s. */
189
198
  heartbeatSeconds;
190
199
  heartbeatReadAtMs = 0;
@@ -701,6 +710,47 @@ export class GatewayProvider {
701
710
  return { received: false, error: reason };
702
711
  }
703
712
  }
713
+ /** See OpenClawProvider.deferToFirstMarketCheck. Held while this install's
714
+ * first market check may still run early, or while an earlier held notice
715
+ * waits for the socket to come back; the latest notice wins. */
716
+ deferToFirstMarketCheck(send) {
717
+ if (this.firstBeatState === 'none' && !this.deferredSkillNotice)
718
+ return false;
719
+ this.deferredSkillNotice = send;
720
+ return true;
721
+ }
722
+ /** The first market check is settled: send a held notice ('send') or drop
723
+ * it ('drop': the check started, or may have, and reads the new
724
+ * instructions itself). A stopped provider sends nothing. If the socket is
725
+ * down right now (the settle may be BECAUSE it dropped), the notice stays
726
+ * held and goes out on the next connect (flushHeldSkillNotice) instead of
727
+ * being lost. */
728
+ settleFirstBeat(action) {
729
+ this.firstBeatState = 'none';
730
+ if (!this.deferredSkillNotice)
731
+ return;
732
+ if (action === 'drop' || !this.started) {
733
+ this.deferredSkillNotice = null;
734
+ return;
735
+ }
736
+ if (this.wsClient?.getState() !== 'connected') {
737
+ logger.info(TAG, 'Held "instructions updated" chat notice kept for the next gateway connect (the socket is down)');
738
+ return;
739
+ }
740
+ this.flushHeldSkillNotice();
741
+ }
742
+ /** Send a held notice once nothing is pending any more (settle, or the next
743
+ * connect after a settle that found the socket down). */
744
+ flushHeldSkillNotice() {
745
+ if (this.firstBeatState !== 'none' || !this.started)
746
+ return;
747
+ const send = this.deferredSkillNotice;
748
+ this.deferredSkillNotice = null;
749
+ if (!send)
750
+ return;
751
+ logger.info(TAG, 'Sending the held "instructions updated" chat notice (the first market check did not start early)');
752
+ send();
753
+ }
704
754
  async closePosition(symbol) {
705
755
  const tool = this.toolMap.close_position;
706
756
  if (!tool || !this.http) {
@@ -1111,12 +1161,16 @@ export class GatewayProvider {
1111
1161
  // Step 3: Create WS client and connect FIRST to obtain device token.
1112
1162
  // OpenClaw's REST API requires a device token from the WS handshake,
1113
1163
  // not the raw gateway auth token. Tool discovery must wait for this.
1114
- // Least privilege: operator.admin (cron management) is requested only
1115
- // while the once-per-install heartbeat-cron ensure is still owed — after
1116
- // the marker exists, every session runs on operator.read/write alone.
1164
+ // Least privilege: operator.admin (cron.add / cron.run) is requested only
1165
+ // when this process starts with the once-per-install heartbeat ensure
1166
+ // still owed: no marker yet, or an old-rule marker that adopted a job that
1167
+ // is not ReefClaw's (heartbeatEnsureOwed — the same check the ensure
1168
+ // itself runs on, so the re-check always has the scope it needs). This
1169
+ // client keeps the scope across reconnects until the bridge restarts;
1170
+ // every later process runs on operator.read/write alone.
1117
1171
  this.wsClient = new GatewayWsClient({
1118
1172
  ...this.config,
1119
- requestAdminScope: !existsSync(join(this.workspaceDir(), 'heartbeat-cron-ensured.json')),
1173
+ requestAdminScope: heartbeatEnsureOwed(join(this.workspaceDir(), 'heartbeat-cron-ensured.json')),
1120
1174
  });
1121
1175
  this.wireWsEvents();
1122
1176
  // Wait for WS handshake to complete (or fail)
@@ -1458,9 +1512,14 @@ export class GatewayProvider {
1458
1512
  // A box with no chat channel gets delivery `none`: announce can only
1459
1513
  // fail there and would record every beat as an error (2026-09-27).
1460
1514
  const channelsConfigured = hasConfiguredChannels(readOpenClawConfigFile());
1515
+ const markerPath = join(this.workspaceDir(), 'heartbeat-cron-ensured.json');
1516
+ // A first market check is possible only while the ensure is owed; hold
1517
+ // the bridge's update notice from now until it is known either way.
1518
+ if (heartbeatEnsureOwed(markerPath))
1519
+ this.firstBeatState = 'maybe';
1461
1520
  void ensureHeartbeatCron({
1462
1521
  rpc: ws,
1463
- markerPath: join(this.workspaceDir(), 'heartbeat-cron-ensured.json'),
1522
+ markerPath,
1464
1523
  log: (msg) => logger.info(TAG, msg),
1465
1524
  // Scoped to the agent we serve: on a shared gateway the business
1466
1525
  // agent's own heartbeat must not suppress the trading agent's, and
@@ -1472,8 +1531,45 @@ export class GatewayProvider {
1472
1531
  // A transient failure retries on the next (re)connect, not just next boot.
1473
1532
  if (outcome === 'failed') {
1474
1533
  this.heartbeatCronEnsureStarted = false;
1534
+ this.settleFirstBeat('send');
1475
1535
  return;
1476
1536
  }
1537
+ // The job did not exist until now (a fresh install, or a box whose
1538
+ // old marker adopted a job that was not ReefClaw's, so it never had
1539
+ // a ReefClaw beat): run the first market check as soon as the full
1540
+ // instructions are in place instead of one interval later. Same
1541
+ // client — cron.run needs the admin scope this session was opened
1542
+ // with. Never on an existing job ('found_existing' /
1543
+ // 'already_ensured'): that would add beats to a running agent.
1544
+ if (outcome === 'created') {
1545
+ this.firstBeatState = 'pending';
1546
+ void runFirstHeartbeat({
1547
+ rpc: ws,
1548
+ log: (msg) => logger.info(TAG, msg),
1549
+ agentId: this.agentId(),
1550
+ agentIsDefault: this.config.agentIsDefault ?? true,
1551
+ // The tracker copy AND every copy the agent can load: a bootstrap
1552
+ // copy left in an extension or workspace skills dir would make
1553
+ // the first beat a wasted run.
1554
+ instructionsReady: () => {
1555
+ const dir = this.workspaceDir();
1556
+ if (isBootstrapSkillVersion(readLocalSkillVersion(dir)))
1557
+ return false;
1558
+ return readAgentVisibleSkillVersions(dir).every((v) => !isBootstrapSkillVersion(v));
1559
+ },
1560
+ isActive: () => this.started && this.wsClient === ws,
1561
+ })
1562
+ .catch(() => 'failed')
1563
+ // Started, or may have started ('unknown': cron.run was sent
1564
+ // but its answer was lost): the check reads the new
1565
+ // instructions, so a held notice is dropped. Gone ('inactive'):
1566
+ // nothing to tell. Otherwise the held notice goes out, as it
1567
+ // always did.
1568
+ .then((first) => this.settleFirstBeat(first === 'started' || first === 'unknown' || first === 'inactive' ? 'drop' : 'send'));
1569
+ }
1570
+ else {
1571
+ this.settleFirstBeat('send');
1572
+ }
1477
1573
  // Existing jobs predate the rule above — repair them in place.
1478
1574
  void reconcileHeartbeatDelivery({
1479
1575
  rpc: ws,
@@ -1485,6 +1581,8 @@ export class GatewayProvider {
1485
1581
  });
1486
1582
  }
1487
1583
  }
1584
+ // A notice whose first-check settle found the socket down goes out now.
1585
+ this.flushHeldSkillNotice();
1488
1586
  // Start periodic agent state emission (every 5s)
1489
1587
  if (!this.agentStateInterval) {
1490
1588
  this.agentStateInterval = setInterval(() => {
@@ -2644,6 +2742,13 @@ export class GatewayProvider {
2644
2742
  // Lazily re-read IDENTITY.md (60s) so a name filled in after connect shows up.
2645
2743
  this.maybeRefreshAgentName();
2646
2744
  const hb = this.heartbeatHealth;
2745
+ let webappApi;
2746
+ try {
2747
+ webappApi = webappEdgeTracker().health();
2748
+ }
2749
+ catch {
2750
+ webappApi = undefined;
2751
+ }
2647
2752
  return {
2648
2753
  mode: this.agentMode,
2649
2754
  strategy: this.lastKnownStrategy,
@@ -2674,6 +2779,9 @@ export class GatewayProvider {
2674
2779
  // stays byte-identical to the pre-feature shape until then.
2675
2780
  ...(this.lastHeartbeat ? { lastHeartbeat: this.lastHeartbeat } : {}),
2676
2781
  ...(this.modelHealth ? { modelHealth: this.modelHealth } : {}),
2782
+ // Edge-deny verdict (bridge ∪ plugin file). Absent while never denied
2783
+ // → byte-identical payload; the relay carries it while HTTP can't.
2784
+ ...(webappApi ? { webappApi } : {}),
2677
2785
  },
2678
2786
  };
2679
2787
  }
@@ -3016,12 +3124,16 @@ export class GatewayProvider {
3016
3124
  const base = resolveWebappBaseUrl();
3017
3125
  const mode = this.tradingMode === 'PAPER' ? 'paper' : 'live';
3018
3126
  try {
3127
+ const startedAt = Date.now();
3019
3128
  const res = await fetch(`${base}/api/internal/trades?limit=1&mode=${mode}`, {
3020
- headers: { Authorization: `Bearer ${token}` },
3129
+ headers: webappHeaders(token),
3021
3130
  signal: AbortSignal.timeout(5_000),
3022
3131
  });
3023
- if (!res.ok)
3132
+ if (!res.ok) {
3133
+ noteWebappResponse(res, '/api/internal/trades', res.status === 403 ? await res.text().catch(() => '') : null);
3024
3134
  return;
3135
+ }
3136
+ noteWebappResponse(res, '/api/internal/trades', undefined, startedAt);
3025
3137
  const body = (await res.json());
3026
3138
  const ts = body.trades?.[0]?.fillTimestamp;
3027
3139
  if (ts) {