@reefclaw/openclaw-plugin 0.1.50 → 0.1.53
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 +6 -2
- package/bridge/config.js +10 -3
- package/bridge/gateway/heartbeat-cron.d.ts +96 -2
- package/bridge/gateway/heartbeat-cron.js +274 -16
- package/bridge/gateway/tool-discovery.d.ts +1 -1
- package/bridge/gateway/tool-discovery.js +4 -0
- package/bridge/heartbeat-runs.d.ts +24 -0
- package/bridge/heartbeat-runs.js +106 -5
- package/bridge/heartbeat-transcript.d.ts +18 -1
- package/bridge/heartbeat-transcript.js +103 -19
- package/bridge/index.js +2 -2
- package/bridge/providers/emergency-commands.d.ts +26 -1
- package/bridge/providers/emergency-commands.js +74 -4
- package/bridge/providers/gateway.d.ts +27 -0
- package/bridge/providers/gateway.js +155 -14
- package/bridge/setup.js +6 -3
- package/bridge/types.d.ts +12 -0
- package/bridge/utils/relay-host.d.ts +16 -0
- package/bridge/utils/relay-host.js +30 -1
- package/config/late-wiring.d.ts +37 -0
- package/config/late-wiring.js +111 -0
- package/config/operator-halt.d.ts +60 -0
- package/config/operator-halt.js +160 -0
- package/config/plugin-config-io.d.ts +7 -0
- package/config/tool-gate.js +3 -0
- package/index.js +255 -45
- package/openclaw.plugin.json +8 -2
- package/package.json +1 -1
- package/release-integrity.json +15 -0
- package/release-notes.json +4 -1
- package/skills/reefclaw/SKILL.md +1 -1
- package/strategy/builtin-strategies.js +2 -2
- package/tools/get-market-intel.js +2 -1
- package/tools/get-risk-summary.d.ts +5 -0
- package/tools/get-risk-summary.js +5 -0
- package/tools/intel-api.d.ts +10 -0
- package/tools/intel-api.js +13 -1
- package/tools/score-setup.js +4 -2
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// Functions return results — callers apply state changes (agentMode, emitAgentState).
|
|
3
3
|
import { logger } from '../logger.js';
|
|
4
4
|
import { resolveWebappBaseUrl } from '../utils/base-url.js';
|
|
5
|
+
import { GatewayHttpError } from '../gateway/gateway-http-client.js';
|
|
5
6
|
const TAG = 'emergency';
|
|
6
7
|
/** Distinct human-readable reasons from the rejected entries of an
|
|
7
8
|
* allSettled batch — surfaced in EmergencyResult.details so the dashboard
|
|
@@ -195,18 +196,37 @@ export async function executeFlatten(ctx, cachedPositions) {
|
|
|
195
196
|
return Promise.reject(new Error('No close_position or create_order tool available'));
|
|
196
197
|
}
|
|
197
198
|
}));
|
|
198
|
-
|
|
199
|
-
|
|
199
|
+
// A call can SUCCEED at the transport and still close nothing: close_position
|
|
200
|
+
// answers { error } on a refusal, and the create_order fallback can be refused
|
|
201
|
+
// (risk gate, operator halt) inside a 200 envelope. Counting those as closed
|
|
202
|
+
// reported "Closed N/N" while N positions stayed open (2026-10-24 review).
|
|
203
|
+
const reasons = results.map((r) => {
|
|
204
|
+
if (r.status === 'rejected')
|
|
205
|
+
return r.reason instanceof Error ? r.reason.message : String(r.reason);
|
|
206
|
+
const data = r.value?.data;
|
|
207
|
+
if (data && typeof data === 'object' && (data.ok === false || (typeof data.error === 'string' && data.error))) {
|
|
208
|
+
return typeof data.error === 'string' && data.error ? data.error : 'the close was refused';
|
|
209
|
+
}
|
|
210
|
+
return null;
|
|
211
|
+
});
|
|
212
|
+
const failedReasons = reasons.filter((x) => x !== null);
|
|
213
|
+
const succeeded = reasons.length - failedReasons.length;
|
|
214
|
+
const failed = failedReasons.length;
|
|
215
|
+
const reasonsText = () => {
|
|
216
|
+
const distinct = [...new Set(failedReasons)];
|
|
217
|
+
const shown = distinct.slice(0, 3).join('; ');
|
|
218
|
+
return distinct.length > 3 ? `${shown}; …` : shown;
|
|
219
|
+
};
|
|
200
220
|
// Any un-closed position = NOT executed. "Closed 1/5" rendering as a green
|
|
201
221
|
// "Flattened" would leave the operator believing they're flat while 4 real
|
|
202
222
|
// positions stay live — the dashboard must show Failed + which/why.
|
|
203
223
|
if (succeeded === 0 && openPositions.length > 0) {
|
|
204
|
-
const details = `Failed to close any of ${openPositions.length} position(s): ${
|
|
224
|
+
const details = `Failed to close any of ${openPositions.length} position(s): ${reasonsText()}`;
|
|
205
225
|
logger.error(TAG, details);
|
|
206
226
|
return { action: 'flatten', executed: false, timestamp: new Date().toISOString(), details };
|
|
207
227
|
}
|
|
208
228
|
if (failed > 0) {
|
|
209
|
-
const details = `Closed ${succeeded}/${openPositions.length} positions (${failed} failed: ${
|
|
229
|
+
const details = `Closed ${succeeded}/${openPositions.length} positions (${failed} failed: ${reasonsText()})`;
|
|
210
230
|
logger.error(TAG, details);
|
|
211
231
|
return { action: 'flatten', executed: false, timestamp: new Date().toISOString(), details };
|
|
212
232
|
}
|
|
@@ -309,6 +329,56 @@ export function withProposalDetail(result, summary) {
|
|
|
309
329
|
details: result.details ? `${result.details}. ${summary.detail}` : summary.detail,
|
|
310
330
|
};
|
|
311
331
|
}
|
|
332
|
+
/**
|
|
333
|
+
* Set (PAUSED / STOPPED / ACTIVE) or, with `mode` omitted, read the plugin's
|
|
334
|
+
* operator halt — the state create_order refuses new entries under
|
|
335
|
+
* (plugin/src/config/operator-halt.ts). Until 2026-10-24 Pause / Kill /
|
|
336
|
+
* Flatten only changed this connector's agentMode, so an agent could open a
|
|
337
|
+
* position minutes after the operator pressed them. Operator provenance is
|
|
338
|
+
* attached like every other operator tool. Never throws.
|
|
339
|
+
*/
|
|
340
|
+
export async function setOperatorHalt(ctx, mode) {
|
|
341
|
+
if (!ctx.http)
|
|
342
|
+
return { ok: false, error: 'not connected to the OpenClaw gateway' };
|
|
343
|
+
// By its fixed name when discovery missed it (a probe timeout must not leave
|
|
344
|
+
// Pause / Kill / Resume without the halt for the life of the process).
|
|
345
|
+
const tool = ctx.toolMap.set_operator_halt ?? 'set_operator_halt';
|
|
346
|
+
try {
|
|
347
|
+
const res = await ctx.http.invoke(tool, {
|
|
348
|
+
...(mode ? { mode } : {}),
|
|
349
|
+
operator_token: ctx.operatorToken,
|
|
350
|
+
});
|
|
351
|
+
const d = res.data;
|
|
352
|
+
if (d?.ok === true && (d.mode === 'ACTIVE' || d.mode === 'PAUSED' || d.mode === 'STOPPED'))
|
|
353
|
+
return { ok: true, mode: d.mode };
|
|
354
|
+
return { ok: false, error: typeof d?.error === 'string' && d.error ? d.error : 'set_operator_halt refused the call' };
|
|
355
|
+
}
|
|
356
|
+
catch (err) {
|
|
357
|
+
// A plugin older than this connector has no such tool: the gateway answers 404.
|
|
358
|
+
if (err instanceof GatewayHttpError && err.status === 404) {
|
|
359
|
+
return { ok: false, unsupported: true, error: 'this ReefClaw plugin cannot block new entries yet — update ReefClaw' };
|
|
360
|
+
}
|
|
361
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
362
|
+
logger.error(TAG, `set_operator_halt${mode ? ` ${mode}` : ' (read)'} failed: ${reason}`);
|
|
363
|
+
return { ok: false, error: reason };
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
/** Fold the halt outcome into a command result: an emergency command that
|
|
367
|
+
* could not block new entries did not fully execute, and the dashboard must
|
|
368
|
+
* say so (it renders `executed:false` as Failed, with these details). */
|
|
369
|
+
export function withHaltDetail(result, halt, mode) {
|
|
370
|
+
if (halt.ok)
|
|
371
|
+
return result;
|
|
372
|
+
const what = mode === 'ACTIVE' ? 'could NOT lift the block on new entries' : 'could NOT block new entries';
|
|
373
|
+
const detail = `${what}: ${halt.error ?? 'unknown error'}`;
|
|
374
|
+
const details = result.details ? `${result.details}. ${detail}` : detail;
|
|
375
|
+
// An older plugin cannot hold a halt at all: Kill / Flatten still did their
|
|
376
|
+
// exchange work, so that verdict stands with the warning. Pause has no other
|
|
377
|
+
// effect, so it did not execute.
|
|
378
|
+
if (halt.unsupported && mode === 'STOPPED')
|
|
379
|
+
return { ...result, details };
|
|
380
|
+
return { ...result, executed: false, details };
|
|
381
|
+
}
|
|
312
382
|
// ---- Sync commands (pure state transitions) ----
|
|
313
383
|
/**
|
|
314
384
|
* Pause: prevent new entries, keep existing positions.
|
|
@@ -35,6 +35,10 @@ export declare class GatewayProvider implements OpenClawProvider {
|
|
|
35
35
|
private eventParser;
|
|
36
36
|
private toolMap;
|
|
37
37
|
private agentMode;
|
|
38
|
+
/** The plugin's operator halt as last confirmed (null = not read yet / no
|
|
39
|
+
* such tool). Unlike agentMode it survives restarts — it is what
|
|
40
|
+
* create_order actually enforces (plugin/src/config/operator-halt.ts). */
|
|
41
|
+
private operatorHalt;
|
|
38
42
|
private lastKnownStrategy;
|
|
39
43
|
/** Agent display name + live model id, resolved from the gateway (best-effort).
|
|
40
44
|
* Surfaced in agent_state so the dashboard header can show the real agent +
|
|
@@ -233,6 +237,12 @@ export declare class GatewayProvider implements OpenClawProvider {
|
|
|
233
237
|
private executeFlatten;
|
|
234
238
|
private executePause;
|
|
235
239
|
private executeResume;
|
|
240
|
+
/** Set the plugin's operator halt and remember what it confirmed. */
|
|
241
|
+
private applyOperatorHalt;
|
|
242
|
+
/** The plugin's halt survives restarts; this connector's agentMode does
|
|
243
|
+
* not. Read it back so the dashboard shows the stop the order path still
|
|
244
|
+
* enforces (and Resume is offered). Never throws. */
|
|
245
|
+
private syncOperatorHalt;
|
|
236
246
|
handleChat(content: string): Promise<{
|
|
237
247
|
received: boolean;
|
|
238
248
|
error?: string;
|
|
@@ -342,6 +352,15 @@ export declare class GatewayProvider implements OpenClawProvider {
|
|
|
342
352
|
acknowledgeOpenPositions?: boolean;
|
|
343
353
|
}): Promise<ConnectorUpdateOutcome>;
|
|
344
354
|
private emitConnectorUpdate;
|
|
355
|
+
/**
|
|
356
|
+
* Replace a superseded default heartbeat message with the current one
|
|
357
|
+
* (refreshHeartbeatMessage: byte-identical defaults only). cron.update is
|
|
358
|
+
* operator.admin: a session opened with the ensure owed already holds it;
|
|
359
|
+
* otherwise a short-lived admin session is opened for the write, the same
|
|
360
|
+
* way the one-click update and the restart do — and only when a job
|
|
361
|
+
* actually needs it. Kill-switch: RC_HEARTBEAT_MESSAGE_REFRESH=off.
|
|
362
|
+
*/
|
|
363
|
+
private refreshHeartbeatInstructions;
|
|
345
364
|
/** Operator-only. Approval/balance status of the provisioned HL wallet. */
|
|
346
365
|
getHlAgentWalletStatus(): Promise<HlAgentWalletStatusOutcome>;
|
|
347
366
|
/** Operator-only. Read the current bracket-orders config from the plugin. */
|
|
@@ -485,6 +504,14 @@ export declare class GatewayProvider implements OpenClawProvider {
|
|
|
485
504
|
* refresh is in flight. Fire-and-forget: the RPC completion re-emits
|
|
486
505
|
* agent_state, so callers stay synchronous. */
|
|
487
506
|
private maybeRefreshHeartbeatHealth;
|
|
507
|
+
/** The gateway's cron jobs (`cron.list`, disabled ones included), so the
|
|
508
|
+
* recorder can keep to ReefClaw's (isReefclawCronJob). Null when the RPC is
|
|
509
|
+
* unavailable — the recorder then judges each run by its marker / prompt. */
|
|
510
|
+
fetchCronJobs(): Promise<Array<{
|
|
511
|
+
id?: unknown;
|
|
512
|
+
name?: unknown;
|
|
513
|
+
payload?: unknown;
|
|
514
|
+
}> | null>;
|
|
488
515
|
/** The gateway's cron run log for the heartbeat job (`cron.runs`, newest
|
|
489
516
|
* first), normalised to the recorder's shape. Returns null when the RPC or
|
|
490
517
|
* the job id is unavailable (older gateway / scope) — the recorder then
|
|
@@ -17,11 +17,11 @@ 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
19
|
import { readLocalSkillVersion, readAgentVisibleSkillVersions, isBootstrapSkillVersion } from '../utils/skill-version.js';
|
|
20
|
-
import { ensureHeartbeatCron, hasConfiguredChannels, heartbeatEnsureOwed, pickHeartbeatJob, reconcileHeartbeatDelivery, runFirstHeartbeat, } from '../gateway/heartbeat-cron.js';
|
|
20
|
+
import { ensureHeartbeatCron, hasConfiguredChannels, heartbeatEnsureOwed, isReefclawHeartbeatJob, pickHeartbeatJob, reconcileHeartbeatDelivery, refreshHeartbeatMessage, runFirstHeartbeat, } from '../gateway/heartbeat-cron.js';
|
|
21
21
|
import { readOpenClawConfigFile } from '../gateway/gateway-config.js';
|
|
22
22
|
import { parseIdentityName } from '../utils/identity-name.js';
|
|
23
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';
|
|
24
|
-
import { executeKill as _executeKill, executeFlatten as _executeFlatten, executePause as _executePause, executeResume as _executeResume, cancelPendingProposals, withProposalDetail, } from './emergency-commands.js';
|
|
24
|
+
import { executeKill as _executeKill, executeFlatten as _executeFlatten, executePause as _executePause, executeResume as _executeResume, cancelPendingProposals, withProposalDetail, setOperatorHalt, withHaltDetail, } from './emergency-commands.js';
|
|
25
25
|
import { executeSetTradingMode, executeGetBracketConfig, executeSetBracketRequirement, executeSetExchangeCredentials, executeTestExchangeCredentials, executeClearExchangeCredentials, executeProvisionHlAgentWallet, executeHlAgentWalletStatus, executeSubmitHlAgentApproval, } from './onboarding-commands.js';
|
|
26
26
|
import { startConnectorUpdate, runConnectorUpdate, fetchPinnedRelease, openAdminGatewaySession, checkPositionGuard, describeUnconfirmedConnectVersion, describeUpdateAlreadyRunning, describeUpdateDisabled, tryBeginConnectorUpdate, requestGatewayRestart, RESTART_REASON_OPERATOR, } from './connector-update.js';
|
|
27
27
|
import { isInsideContainer, readContainerProbe, runDirectConnectorUpdate } from './connector-update-direct.js';
|
|
@@ -159,6 +159,10 @@ export class GatewayProvider {
|
|
|
159
159
|
toolMap = {};
|
|
160
160
|
// ---- Internal state ----
|
|
161
161
|
agentMode = 'ACTIVE';
|
|
162
|
+
/** The plugin's operator halt as last confirmed (null = not read yet / no
|
|
163
|
+
* such tool). Unlike agentMode it survives restarts — it is what
|
|
164
|
+
* create_order actually enforces (plugin/src/config/operator-halt.ts). */
|
|
165
|
+
operatorHalt = null;
|
|
162
166
|
// 'agent_discretionary' is the honest default for trades the agent opens
|
|
163
167
|
// via create_order without a named strategy-engine signal firing. The
|
|
164
168
|
// legacy 'Unknown' value polluted every trade_results row on intel — see
|
|
@@ -640,6 +644,9 @@ export class GatewayProvider {
|
|
|
640
644
|
// without adding a single millisecond to the kill path. Fail-soft — it
|
|
641
645
|
// reports into `details`, it can never throw or block.
|
|
642
646
|
const proposalCancel = cancelPendingProposals(this.config.connectionToken, 'kill_switch');
|
|
647
|
+
// The block on new entries goes up FIRST, concurrently with the exchange
|
|
648
|
+
// work: an agent mid-beat must not open a position while Kill cancels.
|
|
649
|
+
const halt = this.applyOperatorHalt('STOPPED');
|
|
643
650
|
// Pass a FRESH, all-symbols order snapshot so Kill cancels every working
|
|
644
651
|
// order portfolio-wide and correctly identifies (and preserves) protective
|
|
645
652
|
// reduceOnly brackets. On a failed fresh read Kill still runs against the
|
|
@@ -649,16 +656,21 @@ export class GatewayProvider {
|
|
|
649
656
|
const result = await _executeKill(ctx, freshOrders, this.openOrders);
|
|
650
657
|
this.agentMode = 'STOPPED';
|
|
651
658
|
this.emitAgentState();
|
|
652
|
-
return withProposalDetail(result, await proposalCancel);
|
|
659
|
+
return withHaltDetail(withProposalDetail(result, await proposalCancel), await halt, 'STOPPED');
|
|
653
660
|
}
|
|
654
661
|
async executeFlatten() {
|
|
655
662
|
const ctx = { http: this.http, toolMap: this.toolMap, symbol: this.config.symbol };
|
|
656
663
|
// Started before the closes, awaited after — see executeKill.
|
|
657
664
|
const proposalCancel = cancelPendingProposals(this.config.connectionToken, 'flatten');
|
|
665
|
+
// Without close_position the closes go through create_order — which the
|
|
666
|
+
// halt refuses — so on that path the halt goes up only AFTER the closes.
|
|
667
|
+
const closesViaCreateOrder = !this.toolMap.close_position;
|
|
668
|
+
const earlyHalt = closesViaCreateOrder ? null : this.applyOperatorHalt('STOPPED');
|
|
658
669
|
const result = await _executeFlatten(ctx, this.positions);
|
|
670
|
+
const halt = earlyHalt ? await earlyHalt : await this.applyOperatorHalt('STOPPED');
|
|
659
671
|
this.agentMode = 'STOPPED';
|
|
660
672
|
this.emitAgentState();
|
|
661
|
-
return withProposalDetail(result, await proposalCancel);
|
|
673
|
+
return withHaltDetail(withProposalDetail(result, await proposalCancel), halt, 'STOPPED');
|
|
662
674
|
}
|
|
663
675
|
async executePause() {
|
|
664
676
|
const { result, newMode } = _executePause(this.agentMode);
|
|
@@ -667,20 +679,54 @@ export class GatewayProvider {
|
|
|
667
679
|
this.emitAgentState();
|
|
668
680
|
}
|
|
669
681
|
// A pending proposal IS a new entry, which is exactly what Pause forbids.
|
|
670
|
-
// No exchange work here, so awaiting directly costs nothing.
|
|
682
|
+
// No exchange work here, so awaiting directly costs nothing. The halt is
|
|
683
|
+
// what makes Pause real: create_order refuses new entries under it.
|
|
671
684
|
if (result.executed) {
|
|
672
|
-
|
|
685
|
+
const halt = await this.applyOperatorHalt('PAUSED');
|
|
686
|
+
return withHaltDetail(withProposalDetail(result, await cancelPendingProposals(this.config.connectionToken, 'pause')), halt, 'PAUSED');
|
|
673
687
|
}
|
|
674
688
|
return result;
|
|
675
689
|
}
|
|
676
|
-
executeResume() {
|
|
690
|
+
async executeResume() {
|
|
677
691
|
const { result, newMode } = _executeResume(this.agentMode);
|
|
692
|
+
if (!result.executed)
|
|
693
|
+
return result;
|
|
694
|
+
// Lift the plugin's block BEFORE showing ACTIVE — also when this
|
|
695
|
+
// connector already thinks it is active, so a halt that outlived its
|
|
696
|
+
// state is cleared. A plugin without the tool has nothing to lift.
|
|
697
|
+
const halt = await this.applyOperatorHalt('ACTIVE');
|
|
698
|
+
if (!halt.ok && !halt.unsupported)
|
|
699
|
+
return withHaltDetail(result, halt, 'ACTIVE');
|
|
678
700
|
if (newMode !== this.agentMode) {
|
|
679
701
|
this.agentMode = newMode;
|
|
680
702
|
this.emitAgentState();
|
|
681
703
|
}
|
|
682
704
|
return result;
|
|
683
705
|
}
|
|
706
|
+
/** Set the plugin's operator halt and remember what it confirmed. */
|
|
707
|
+
applyOperatorHalt(mode) {
|
|
708
|
+
return setOperatorHalt({ http: this.http, toolMap: this.toolMap, operatorToken: this.operatorProvenance() }, mode).then((o) => {
|
|
709
|
+
if (o.ok && o.mode)
|
|
710
|
+
this.operatorHalt = o.mode;
|
|
711
|
+
return o;
|
|
712
|
+
});
|
|
713
|
+
}
|
|
714
|
+
/** The plugin's halt survives restarts; this connector's agentMode does
|
|
715
|
+
* not. Read it back so the dashboard shows the stop the order path still
|
|
716
|
+
* enforces (and Resume is offered). Never throws. */
|
|
717
|
+
async syncOperatorHalt() {
|
|
718
|
+
if (!this.http)
|
|
719
|
+
return;
|
|
720
|
+
const r = await setOperatorHalt({ http: this.http, toolMap: this.toolMap, operatorToken: this.operatorProvenance() });
|
|
721
|
+
if (!r.ok || !r.mode)
|
|
722
|
+
return;
|
|
723
|
+
this.operatorHalt = r.mode;
|
|
724
|
+
if (r.mode !== 'ACTIVE' && this.agentMode !== r.mode && this.agentMode !== 'ERROR') {
|
|
725
|
+
logger.info(TAG, `operator halt ${r.mode} read back from the plugin — new entries stay blocked until Resume`);
|
|
726
|
+
this.agentMode = r.mode;
|
|
727
|
+
this.emitAgentState();
|
|
728
|
+
}
|
|
729
|
+
}
|
|
684
730
|
async handleChat(content) {
|
|
685
731
|
// Capture reference before await — defensive against stop() mid-execution
|
|
686
732
|
const ws = this.wsClient;
|
|
@@ -1085,6 +1131,44 @@ export class GatewayProvider {
|
|
|
1085
1131
|
emitConnectorUpdate(payload) {
|
|
1086
1132
|
this.fire('connectorUpdate', payload);
|
|
1087
1133
|
}
|
|
1134
|
+
/**
|
|
1135
|
+
* Replace a superseded default heartbeat message with the current one
|
|
1136
|
+
* (refreshHeartbeatMessage: byte-identical defaults only). cron.update is
|
|
1137
|
+
* operator.admin: a session opened with the ensure owed already holds it;
|
|
1138
|
+
* otherwise a short-lived admin session is opened for the write, the same
|
|
1139
|
+
* way the one-click update and the restart do — and only when a job
|
|
1140
|
+
* actually needs it. Kill-switch: RC_HEARTBEAT_MESSAGE_REFRESH=off.
|
|
1141
|
+
*/
|
|
1142
|
+
async refreshHeartbeatInstructions(ws, sessionHasAdmin) {
|
|
1143
|
+
if (process.env.RC_HEARTBEAT_MESSAGE_REFRESH === 'off')
|
|
1144
|
+
return;
|
|
1145
|
+
// A box that opted out of the dashboard's one-click update opted out of
|
|
1146
|
+
// ReefClaw changing things on it from here — this rewrite included.
|
|
1147
|
+
if (this.config.allowConnectorUpdate === false)
|
|
1148
|
+
return;
|
|
1149
|
+
await refreshHeartbeatMessage({
|
|
1150
|
+
rpc: ws,
|
|
1151
|
+
log: (msg) => logger.info(TAG, msg),
|
|
1152
|
+
agentId: this.agentId(),
|
|
1153
|
+
agentIsDefault: this.config.agentIsDefault ?? true,
|
|
1154
|
+
openAdmin: async () => {
|
|
1155
|
+
if (sessionHasAdmin)
|
|
1156
|
+
return { rpc: ws, close: () => { } };
|
|
1157
|
+
const admin = new GatewayWsClient({
|
|
1158
|
+
gatewayUrl: this.config.gatewayUrl,
|
|
1159
|
+
gatewayToken: this.config.gatewayToken,
|
|
1160
|
+
requestAdminScope: true,
|
|
1161
|
+
identities: [ws.getClientId()],
|
|
1162
|
+
requireScope: 'operator.admin',
|
|
1163
|
+
}, { baseDelayMs: 60_000, maxDelayMs: 60_000, maxFastAttempts: 0, jitterFactor: 0, slowRetryMs: 3_600_000 });
|
|
1164
|
+
// A failed or scope-less session is destroyed by openAdminGatewaySession.
|
|
1165
|
+
const session = await openAdminGatewaySession(admin);
|
|
1166
|
+
if (!session.ok)
|
|
1167
|
+
return null;
|
|
1168
|
+
return { rpc: admin, close: () => admin.destroy() };
|
|
1169
|
+
},
|
|
1170
|
+
}).catch(() => undefined);
|
|
1171
|
+
}
|
|
1088
1172
|
/** Operator-only. Approval/balance status of the provisioned HL wallet. */
|
|
1089
1173
|
async getHlAgentWalletStatus() {
|
|
1090
1174
|
return executeHlAgentWalletStatus({
|
|
@@ -1362,6 +1446,9 @@ export class GatewayProvider {
|
|
|
1362
1446
|
// Step 11: Seed lastTradeTs from Intelligence API (one-shot, best-effort)
|
|
1363
1447
|
// Without this, "Last Trade" shows "Never" after every restart until a new trade fires.
|
|
1364
1448
|
void this.seedLastTradeTs();
|
|
1449
|
+
// Step 12: an operator halt set before this restart still blocks new
|
|
1450
|
+
// entries in the plugin — show it (best-effort; re-emits state if halted).
|
|
1451
|
+
void this.syncOperatorHalt();
|
|
1365
1452
|
// Emit initial agent state
|
|
1366
1453
|
this.emitAgentState();
|
|
1367
1454
|
}
|
|
@@ -1465,11 +1552,15 @@ export class GatewayProvider {
|
|
|
1465
1552
|
}
|
|
1466
1553
|
const newCount = Object.keys(this.toolMap).length;
|
|
1467
1554
|
logger.info(TAG, `Tools discovered on retry: ${discovery.found.join(', ')} (total: ${newCount})`);
|
|
1468
|
-
// Transition from PAUSED to ACTIVE once we have required tools
|
|
1469
|
-
|
|
1555
|
+
// Transition from PAUSED to ACTIVE once we have required tools —
|
|
1556
|
+
// never out of an OPERATOR pause (that PAUSED is the plugin's halt).
|
|
1557
|
+
if (this.agentMode === 'PAUSED' && this.operatorHalt !== 'PAUSED' && this.toolMap.fetch_ticker && this.toolMap.fetch_balance) {
|
|
1470
1558
|
this.agentMode = 'ACTIVE';
|
|
1471
1559
|
this.emitAgentState();
|
|
1472
1560
|
}
|
|
1561
|
+
// The halt tool may only now be visible: read the halt back.
|
|
1562
|
+
if (this.operatorHalt === null)
|
|
1563
|
+
void this.syncOperatorHalt();
|
|
1473
1564
|
// If new tools were added, restart the poller with the updated toolMap
|
|
1474
1565
|
if (newCount > prevCount && this.started && this.http) {
|
|
1475
1566
|
if (this.poller) {
|
|
@@ -1627,7 +1718,10 @@ export class GatewayProvider {
|
|
|
1627
1718
|
const markerPath = join(this.workspaceDir(), 'heartbeat-cron-ensured.json');
|
|
1628
1719
|
// A first market check is possible only while the ensure is owed; hold
|
|
1629
1720
|
// the bridge's update notice from now until it is known either way.
|
|
1630
|
-
|
|
1721
|
+
// Read BEFORE the ensure writes its marker: owed = this session was
|
|
1722
|
+
// opened with operator.admin (the reconcile below needs it).
|
|
1723
|
+
const ensureOwed = heartbeatEnsureOwed(markerPath);
|
|
1724
|
+
if (ensureOwed)
|
|
1631
1725
|
this.firstBeatState = 'maybe';
|
|
1632
1726
|
void ensureHeartbeatCron({
|
|
1633
1727
|
rpc: ws,
|
|
@@ -1682,14 +1776,17 @@ export class GatewayProvider {
|
|
|
1682
1776
|
else {
|
|
1683
1777
|
this.settleFirstBeat('send');
|
|
1684
1778
|
}
|
|
1685
|
-
// Existing jobs predate the rule above — repair them in place.
|
|
1779
|
+
// Existing jobs predate the rule above — repair them in place. The
|
|
1780
|
+
// instructions refresh runs after it, so the two never update the
|
|
1781
|
+
// same job at once.
|
|
1686
1782
|
void reconcileHeartbeatDelivery({
|
|
1687
1783
|
rpc: ws,
|
|
1688
1784
|
log: (msg) => logger.info(TAG, msg),
|
|
1689
1785
|
channelsConfigured,
|
|
1786
|
+
adminScope: ensureOwed,
|
|
1690
1787
|
agentId: this.agentId(),
|
|
1691
1788
|
agentIsDefault: this.config.agentIsDefault ?? true,
|
|
1692
|
-
});
|
|
1789
|
+
}).then(() => this.refreshHeartbeatInstructions(ws, ensureOwed));
|
|
1693
1790
|
});
|
|
1694
1791
|
}
|
|
1695
1792
|
}
|
|
@@ -2518,23 +2615,46 @@ export class GatewayProvider {
|
|
|
2518
2615
|
if (!state || typeof state !== 'object')
|
|
2519
2616
|
return;
|
|
2520
2617
|
const s = state;
|
|
2618
|
+
// "Switched off" is reported only for a job that IS ReefClaw's: the
|
|
2619
|
+
// display fallback can pick any heartbeat-named job (OpenClaw 2026.9
|
|
2620
|
+
// ships its own "Heartbeat (<agent>)" monitor), and a disabled job of
|
|
2621
|
+
// someone else's must never raise HEARTBEAT OFF.
|
|
2622
|
+
const oursJob = isReefclawHeartbeatJob(hb);
|
|
2623
|
+
const ad = oursJob && s.autoDisabled && typeof s.autoDisabled === 'object' ? s.autoDisabled : null;
|
|
2521
2624
|
const next = {
|
|
2522
2625
|
consecutiveErrors: typeof s.consecutiveErrors === 'number' && s.consecutiveErrors >= 0 ? s.consecutiveErrors : 0,
|
|
2523
2626
|
lastRunAtMs: typeof s.lastRunAtMs === 'number' ? s.lastRunAtMs : undefined,
|
|
2524
2627
|
lastRunStatus: typeof s.lastRunStatus === 'string' ? s.lastRunStatus : undefined,
|
|
2525
2628
|
lastErrorReason: typeof s.lastErrorReason === 'string' ? s.lastErrorReason : undefined,
|
|
2526
2629
|
lastError: typeof s.lastError === 'string' ? s.lastError.slice(0, 300) : undefined,
|
|
2630
|
+
enabled: !oursJob || row?.enabled !== false,
|
|
2631
|
+
autoDisabled: ad
|
|
2632
|
+
? {
|
|
2633
|
+
reason: typeof ad.reason === 'string' ? ad.reason : 'unknown',
|
|
2634
|
+
...(typeof ad.atMs === 'number' ? { atMs: ad.atMs } : {}),
|
|
2635
|
+
...(typeof ad.consecutiveErrors === 'number' ? { consecutiveErrors: ad.consecutiveErrors } : {}),
|
|
2636
|
+
}
|
|
2637
|
+
: undefined,
|
|
2527
2638
|
};
|
|
2528
2639
|
const prev = this.heartbeatHealth;
|
|
2529
2640
|
const changed = !prev ||
|
|
2530
2641
|
prev.consecutiveErrors !== next.consecutiveErrors ||
|
|
2531
2642
|
prev.lastRunAtMs !== next.lastRunAtMs ||
|
|
2532
2643
|
prev.lastRunStatus !== next.lastRunStatus ||
|
|
2533
|
-
prev.lastErrorReason !== next.lastErrorReason
|
|
2644
|
+
prev.lastErrorReason !== next.lastErrorReason ||
|
|
2645
|
+
prev.enabled !== next.enabled ||
|
|
2646
|
+
prev.autoDisabled?.atMs !== next.autoDisabled?.atMs;
|
|
2534
2647
|
this.heartbeatHealth = next;
|
|
2535
2648
|
this.heartbeatHealthReadAtMs = Date.now();
|
|
2536
2649
|
if (changed) {
|
|
2537
|
-
if (next.
|
|
2650
|
+
if (!next.enabled) {
|
|
2651
|
+
logger.warn(TAG, `Heartbeat job is SWITCHED OFF in OpenClaw` +
|
|
2652
|
+
(next.autoDisabled
|
|
2653
|
+
? ` (auto-disabled after ${next.autoDisabled.consecutiveErrors ?? '?'} ${next.autoDisabled.reason})`
|
|
2654
|
+
: '') +
|
|
2655
|
+
` — the agent will not run its beat until it is re-enabled (openclaw cron enable ${this.heartbeatJobId ?? '<id>'})`);
|
|
2656
|
+
}
|
|
2657
|
+
else if (next.consecutiveErrors > 0) {
|
|
2538
2658
|
logger.warn(TAG, `Heartbeat health: ${next.consecutiveErrors} consecutive error(s), lastStatus=${next.lastRunStatus ?? 'unknown'}` +
|
|
2539
2659
|
(next.lastErrorReason ? ` reason=${next.lastErrorReason}` : ''));
|
|
2540
2660
|
}
|
|
@@ -2560,6 +2680,23 @@ export class GatewayProvider {
|
|
|
2560
2680
|
void this.refreshHeartbeatHealth();
|
|
2561
2681
|
}
|
|
2562
2682
|
// ---- Heartbeat flight recorder hooks (skill/src/heartbeat-runs.ts) ----
|
|
2683
|
+
/** The gateway's cron jobs (`cron.list`, disabled ones included), so the
|
|
2684
|
+
* recorder can keep to ReefClaw's (isReefclawCronJob). Null when the RPC is
|
|
2685
|
+
* unavailable — the recorder then judges each run by its marker / prompt. */
|
|
2686
|
+
async fetchCronJobs() {
|
|
2687
|
+
const ws = this.wsClient;
|
|
2688
|
+
if (!ws)
|
|
2689
|
+
return null;
|
|
2690
|
+
try {
|
|
2691
|
+
const resp = await ws.sendRpc('cron.list', { includeDisabled: true });
|
|
2692
|
+
const jobs = resp?.jobs;
|
|
2693
|
+
return Array.isArray(jobs) ? jobs : null;
|
|
2694
|
+
}
|
|
2695
|
+
catch (err) {
|
|
2696
|
+
logger.debug(TAG, `cron.list RPC failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
2697
|
+
return null;
|
|
2698
|
+
}
|
|
2699
|
+
}
|
|
2563
2700
|
/** The gateway's cron run log for the heartbeat job (`cron.runs`, newest
|
|
2564
2701
|
* first), normalised to the recorder's shape. Returns null when the RPC or
|
|
2565
2702
|
* the job id is unavailable (older gateway / scope) — the recorder then
|
|
@@ -2884,6 +3021,10 @@ export class GatewayProvider {
|
|
|
2884
3021
|
consecutiveErrors: hb.consecutiveErrors,
|
|
2885
3022
|
...(hb.lastRunAtMs !== undefined ? { lastRunAtMs: hb.lastRunAtMs } : {}),
|
|
2886
3023
|
...(hb.lastRunStatus !== undefined ? { lastRunStatus: hb.lastRunStatus } : {}),
|
|
3024
|
+
// Only while switched off: an enabled job keeps the old shape.
|
|
3025
|
+
...(hb.enabled ? {} : { enabled: false }),
|
|
3026
|
+
...(hb.autoDisabled ? { autoDisabled: hb.autoDisabled } : {}),
|
|
3027
|
+
...(!hb.enabled && this.heartbeatJobId ? { jobId: this.heartbeatJobId } : {}),
|
|
2887
3028
|
},
|
|
2888
3029
|
}
|
|
2889
3030
|
: {}),
|
package/bridge/setup.js
CHANGED
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
// Validates token format, tests relay connection, saves to OpenClaw config.
|
|
3
3
|
import WebSocket from 'ws';
|
|
4
4
|
import { writeOpenClawConfig } from './config.js';
|
|
5
|
-
import { checkRelayHost, describeRelayRefusal } from './utils/relay-host.js';
|
|
5
|
+
import { checkRelayHost, describeRelayRefusal, migrateRetiredRelayUrl } from './utils/relay-host.js';
|
|
6
6
|
import { logger } from './logger.js';
|
|
7
7
|
const TAG = 'setup';
|
|
8
|
-
const DEFAULT_RELAY_URL = 'wss://reefclaw.
|
|
8
|
+
const DEFAULT_RELAY_URL = 'wss://relay.reefclaw.com';
|
|
9
9
|
const TOKEN_PREFIX = 'rc_';
|
|
10
10
|
const TOKEN_MIN_LENGTH = 10; // rc_ + at least 7 chars
|
|
11
11
|
const CONNECTION_TEST_TIMEOUT_MS = 10_000;
|
|
@@ -119,7 +119,10 @@ export async function runSetup(tokenOrBundle, userId, relayUrl) {
|
|
|
119
119
|
const parsed = parseConnectBundle(tokenOrBundle);
|
|
120
120
|
const token = parsed.token ?? tokenOrBundle.trim();
|
|
121
121
|
const resolvedUserId = userId ?? parsed.userId;
|
|
122
|
-
const
|
|
122
|
+
const givenRelayUrl = relayUrl ?? parsed.relayUrl;
|
|
123
|
+
// An old connect message still names the retired PartyKit host — save its
|
|
124
|
+
// replacement so the config is right on disk, not just rewritten at startup.
|
|
125
|
+
const resolvedRelayUrl = givenRelayUrl ? migrateRetiredRelayUrl(givenRelayUrl).url : givenRelayUrl;
|
|
123
126
|
// Validate token format
|
|
124
127
|
const validation = validateToken(token);
|
|
125
128
|
if (!validation.valid) {
|
package/bridge/types.d.ts
CHANGED
|
@@ -132,6 +132,18 @@ export interface AgentStateData {
|
|
|
132
132
|
lastRunAtMs?: number;
|
|
133
133
|
/** Last run outcome, e.g. "ok" | "error". */
|
|
134
134
|
lastRunStatus?: string;
|
|
135
|
+
/** Sent (as false) only while the job is switched off in OpenClaw —
|
|
136
|
+
* by the user, or by OpenClaw after repeated failures. */
|
|
137
|
+
enabled?: boolean;
|
|
138
|
+
/** OpenClaw's record when IT switched the job off (2026.9.6: 10
|
|
139
|
+
* consecutive failed runs, or repeated schedule errors). */
|
|
140
|
+
autoDisabled?: {
|
|
141
|
+
reason: string;
|
|
142
|
+
atMs?: number;
|
|
143
|
+
consecutiveErrors?: number;
|
|
144
|
+
};
|
|
145
|
+
/** The heartbeat job's id while switched off, for the re-enable hint. */
|
|
146
|
+
jobId?: string;
|
|
135
147
|
};
|
|
136
148
|
/** Compact summary of the last recorded heartbeat run (flight recorder,
|
|
137
149
|
* skill/src/heartbeat-runs.ts). Absent until the first beat is
|
|
@@ -1,6 +1,22 @@
|
|
|
1
1
|
/** Hosts (exact, lowercase) or suffixes (leading dot) of ReefClaw relays. */
|
|
2
2
|
export declare const ALLOWED_RELAY_HOSTS: readonly string[];
|
|
3
3
|
export declare const ALLOW_CUSTOM_RELAY_ENV = "REEFCLAW_ALLOW_CUSTOM_RELAY";
|
|
4
|
+
/** Where a connect message from reefclaw.com points today. */
|
|
5
|
+
export declare const PRIMARY_RELAY_HOST = "relay.reefclaw.com";
|
|
6
|
+
/**
|
|
7
|
+
* Relay hosts that no longer serve traffic, mapped to their replacement.
|
|
8
|
+
* PartyKit's hosted platform deleted `reefclaw.radunlupsa.partykit.dev` on
|
|
9
|
+
* 2026-10-23 and the relay moved to our own Cloudflare account. Most boxes
|
|
10
|
+
* saved the old URL in openclaw.json at onboarding, and many are on hosts we
|
|
11
|
+
* cannot log into, so the bridge rewrites the host in memory at startup
|
|
12
|
+
* instead of asking every user to edit their config.
|
|
13
|
+
*/
|
|
14
|
+
export declare const RETIRED_RELAY_HOSTS: Readonly<Record<string, string>>;
|
|
15
|
+
/** Rewrite a relay URL whose host is retired; any other URL comes back unchanged. */
|
|
16
|
+
export declare function migrateRetiredRelayUrl(relayUrl: string): {
|
|
17
|
+
url: string;
|
|
18
|
+
retiredHost?: string;
|
|
19
|
+
};
|
|
4
20
|
export type RelayHostVerdict = {
|
|
5
21
|
ok: true;
|
|
6
22
|
host: string;
|
|
@@ -20,6 +20,35 @@ export const ALLOWED_RELAY_HOSTS = [
|
|
|
20
20
|
'.reefclaw.partykit.dev',
|
|
21
21
|
];
|
|
22
22
|
export const ALLOW_CUSTOM_RELAY_ENV = 'REEFCLAW_ALLOW_CUSTOM_RELAY';
|
|
23
|
+
/** Where a connect message from reefclaw.com points today. */
|
|
24
|
+
export const PRIMARY_RELAY_HOST = 'relay.reefclaw.com';
|
|
25
|
+
/**
|
|
26
|
+
* Relay hosts that no longer serve traffic, mapped to their replacement.
|
|
27
|
+
* PartyKit's hosted platform deleted `reefclaw.radunlupsa.partykit.dev` on
|
|
28
|
+
* 2026-10-23 and the relay moved to our own Cloudflare account. Most boxes
|
|
29
|
+
* saved the old URL in openclaw.json at onboarding, and many are on hosts we
|
|
30
|
+
* cannot log into, so the bridge rewrites the host in memory at startup
|
|
31
|
+
* instead of asking every user to edit their config.
|
|
32
|
+
*/
|
|
33
|
+
export const RETIRED_RELAY_HOSTS = {
|
|
34
|
+
'reefclaw.radunlupsa.partykit.dev': PRIMARY_RELAY_HOST,
|
|
35
|
+
};
|
|
36
|
+
/** Rewrite a relay URL whose host is retired; any other URL comes back unchanged. */
|
|
37
|
+
export function migrateRetiredRelayUrl(relayUrl) {
|
|
38
|
+
let u;
|
|
39
|
+
try {
|
|
40
|
+
u = new URL(relayUrl);
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
return { url: relayUrl };
|
|
44
|
+
}
|
|
45
|
+
const replacement = RETIRED_RELAY_HOSTS[u.hostname.toLowerCase()];
|
|
46
|
+
if (!replacement)
|
|
47
|
+
return { url: relayUrl };
|
|
48
|
+
const retiredHost = u.hostname;
|
|
49
|
+
u.hostname = replacement;
|
|
50
|
+
return { url: u.toString().replace(/\/+$/, ''), retiredHost };
|
|
51
|
+
}
|
|
23
52
|
function isPrivateHost(h) {
|
|
24
53
|
if (h === 'localhost' || h.endsWith('.localhost') || h === '::1' || h === '[::1]')
|
|
25
54
|
return true;
|
|
@@ -61,6 +90,6 @@ export function describeRelayRefusal(v) {
|
|
|
61
90
|
return v.reason === 'unparseable'
|
|
62
91
|
? 'The relay URL in the connect message could not be parsed.'
|
|
63
92
|
: `The relay host "${v.host}" is not a ReefClaw relay. A connect message from reefclaw.com always points at ` +
|
|
64
|
-
`${
|
|
93
|
+
`${PRIMARY_RELAY_HOST} — a different host means the message was altered, and connecting would hand it your token. ` +
|
|
65
94
|
`Self-hosting your own relay? Set ${ALLOW_CUSTOM_RELAY_ENV}=1 in the connector's environment to allow it.`;
|
|
66
95
|
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
export interface LateWiringStep {
|
|
2
|
+
name: string;
|
|
3
|
+
/** Try to wire this dependency. Return true once wired (the step is then
|
|
4
|
+
* dropped); false to be retried on a later check. A throw counts as false. */
|
|
5
|
+
tryWire: () => boolean;
|
|
6
|
+
}
|
|
7
|
+
export interface LateWiringOptions {
|
|
8
|
+
/** Minimum gap between two check() passes (default 5 s). */
|
|
9
|
+
minIntervalMs?: number;
|
|
10
|
+
/** Watcher cadence (default 30 s). */
|
|
11
|
+
watchIntervalMs?: number;
|
|
12
|
+
now?: () => number;
|
|
13
|
+
/** Defaults to RC_LATE_WIRING !== 'off'. */
|
|
14
|
+
enabled?: boolean;
|
|
15
|
+
}
|
|
16
|
+
export declare class LateWiring {
|
|
17
|
+
private readonly steps;
|
|
18
|
+
private readonly failed;
|
|
19
|
+
private readonly minIntervalMs;
|
|
20
|
+
private readonly watchIntervalMs;
|
|
21
|
+
private readonly now;
|
|
22
|
+
private readonly enabled;
|
|
23
|
+
private lastCheckAt;
|
|
24
|
+
private running;
|
|
25
|
+
private timer;
|
|
26
|
+
constructor(opts?: LateWiringOptions);
|
|
27
|
+
/** Register a dependency that could not be wired at boot. */
|
|
28
|
+
add(step: LateWiringStep): void;
|
|
29
|
+
get hasPending(): boolean;
|
|
30
|
+
get pending(): string[];
|
|
31
|
+
/** Re-try every pending step, in registration order. Throttled, synchronous,
|
|
32
|
+
* never throws. Cheap when nothing is pending. */
|
|
33
|
+
check(): void;
|
|
34
|
+
/** Start the background watcher (no-op when nothing is pending). */
|
|
35
|
+
startWatch(): void;
|
|
36
|
+
stop(): void;
|
|
37
|
+
}
|