@reefclaw/openclaw-plugin 0.1.51 → 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/gateway/heartbeat-cron.d.ts +57 -0
- package/bridge/gateway/heartbeat-cron.js +212 -8
- 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 +15 -0
- package/bridge/heartbeat-transcript.js +77 -14
- 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 +150 -13
- package/bridge/types.d.ts +12 -0
- 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 +10 -0
- package/release-notes.json +3 -1
- package/skills/reefclaw/SKILL.md +1 -1
- 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
|
@@ -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) {
|
|
@@ -1685,7 +1776,9 @@ export class GatewayProvider {
|
|
|
1685
1776
|
else {
|
|
1686
1777
|
this.settleFirstBeat('send');
|
|
1687
1778
|
}
|
|
1688
|
-
// 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.
|
|
1689
1782
|
void reconcileHeartbeatDelivery({
|
|
1690
1783
|
rpc: ws,
|
|
1691
1784
|
log: (msg) => logger.info(TAG, msg),
|
|
@@ -1693,7 +1786,7 @@ export class GatewayProvider {
|
|
|
1693
1786
|
adminScope: ensureOwed,
|
|
1694
1787
|
agentId: this.agentId(),
|
|
1695
1788
|
agentIsDefault: this.config.agentIsDefault ?? true,
|
|
1696
|
-
});
|
|
1789
|
+
}).then(() => this.refreshHeartbeatInstructions(ws, ensureOwed));
|
|
1697
1790
|
});
|
|
1698
1791
|
}
|
|
1699
1792
|
}
|
|
@@ -2522,23 +2615,46 @@ export class GatewayProvider {
|
|
|
2522
2615
|
if (!state || typeof state !== 'object')
|
|
2523
2616
|
return;
|
|
2524
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;
|
|
2525
2624
|
const next = {
|
|
2526
2625
|
consecutiveErrors: typeof s.consecutiveErrors === 'number' && s.consecutiveErrors >= 0 ? s.consecutiveErrors : 0,
|
|
2527
2626
|
lastRunAtMs: typeof s.lastRunAtMs === 'number' ? s.lastRunAtMs : undefined,
|
|
2528
2627
|
lastRunStatus: typeof s.lastRunStatus === 'string' ? s.lastRunStatus : undefined,
|
|
2529
2628
|
lastErrorReason: typeof s.lastErrorReason === 'string' ? s.lastErrorReason : undefined,
|
|
2530
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,
|
|
2531
2638
|
};
|
|
2532
2639
|
const prev = this.heartbeatHealth;
|
|
2533
2640
|
const changed = !prev ||
|
|
2534
2641
|
prev.consecutiveErrors !== next.consecutiveErrors ||
|
|
2535
2642
|
prev.lastRunAtMs !== next.lastRunAtMs ||
|
|
2536
2643
|
prev.lastRunStatus !== next.lastRunStatus ||
|
|
2537
|
-
prev.lastErrorReason !== next.lastErrorReason
|
|
2644
|
+
prev.lastErrorReason !== next.lastErrorReason ||
|
|
2645
|
+
prev.enabled !== next.enabled ||
|
|
2646
|
+
prev.autoDisabled?.atMs !== next.autoDisabled?.atMs;
|
|
2538
2647
|
this.heartbeatHealth = next;
|
|
2539
2648
|
this.heartbeatHealthReadAtMs = Date.now();
|
|
2540
2649
|
if (changed) {
|
|
2541
|
-
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) {
|
|
2542
2658
|
logger.warn(TAG, `Heartbeat health: ${next.consecutiveErrors} consecutive error(s), lastStatus=${next.lastRunStatus ?? 'unknown'}` +
|
|
2543
2659
|
(next.lastErrorReason ? ` reason=${next.lastErrorReason}` : ''));
|
|
2544
2660
|
}
|
|
@@ -2564,6 +2680,23 @@ export class GatewayProvider {
|
|
|
2564
2680
|
void this.refreshHeartbeatHealth();
|
|
2565
2681
|
}
|
|
2566
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
|
+
}
|
|
2567
2700
|
/** The gateway's cron run log for the heartbeat job (`cron.runs`, newest
|
|
2568
2701
|
* first), normalised to the recorder's shape. Returns null when the RPC or
|
|
2569
2702
|
* the job id is unavailable (older gateway / scope) — the recorder then
|
|
@@ -2888,6 +3021,10 @@ export class GatewayProvider {
|
|
|
2888
3021
|
consecutiveErrors: hb.consecutiveErrors,
|
|
2889
3022
|
...(hb.lastRunAtMs !== undefined ? { lastRunAtMs: hb.lastRunAtMs } : {}),
|
|
2890
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 } : {}),
|
|
2891
3028
|
},
|
|
2892
3029
|
}
|
|
2893
3030
|
: {}),
|
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
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// Late wiring: heal a plugin that booted BEFORE its connection was saved.
|
|
2
|
+
//
|
|
3
|
+
// register() reads the connection (rc_ token + userId) exactly once. In the
|
|
4
|
+
// chat-onboarding flow the plugin is usually already installed and running
|
|
5
|
+
// when the agent saves the connection into OpenClaw's config — so the plugin
|
|
6
|
+
// used to stay token-less until a FULL process restart: every intel tool
|
|
7
|
+
// errored, the journal ingest / central-config poller / readiness reporter
|
|
8
|
+
// never started, and the agent could not find a single setup (first seen live
|
|
9
|
+
// 2026-11-23: 16 h of heartbeats, zero trades). An in-process gateway restart
|
|
10
|
+
// does not help either — the repeat register() early-returns on the process
|
|
11
|
+
// record.
|
|
12
|
+
//
|
|
13
|
+
// Each boot-time dependency that could not be wired registers a STEP here.
|
|
14
|
+
// A step re-tries its own wiring and returns true once done; pending steps are
|
|
15
|
+
// re-run (throttled) on demand — the intel tools call check() when they find
|
|
16
|
+
// no token — and by an unref'd watcher, so the whole plugin heals within
|
|
17
|
+
// seconds of the connection being saved, with no restart.
|
|
18
|
+
//
|
|
19
|
+
// Scope: this only ever ADDS wiring that a boot with the connection present
|
|
20
|
+
// would have built. It never tears anything down and never touches the order
|
|
21
|
+
// path, stops, brackets or emergency controls. Kill-switch: RC_LATE_WIRING=off.
|
|
22
|
+
import { logger } from '../logger.js';
|
|
23
|
+
const TAG = 'late-wiring';
|
|
24
|
+
export class LateWiring {
|
|
25
|
+
steps = [];
|
|
26
|
+
failed = new Set();
|
|
27
|
+
minIntervalMs;
|
|
28
|
+
watchIntervalMs;
|
|
29
|
+
now;
|
|
30
|
+
enabled;
|
|
31
|
+
lastCheckAt = Number.NEGATIVE_INFINITY;
|
|
32
|
+
running = false;
|
|
33
|
+
timer;
|
|
34
|
+
constructor(opts = {}) {
|
|
35
|
+
this.minIntervalMs = opts.minIntervalMs ?? 5_000;
|
|
36
|
+
this.watchIntervalMs = opts.watchIntervalMs ?? 30_000;
|
|
37
|
+
this.now = opts.now ?? Date.now;
|
|
38
|
+
this.enabled =
|
|
39
|
+
opts.enabled ?? (process.env.RC_LATE_WIRING ?? 'on').trim().toLowerCase() !== 'off';
|
|
40
|
+
}
|
|
41
|
+
/** Register a dependency that could not be wired at boot. */
|
|
42
|
+
add(step) {
|
|
43
|
+
this.steps.push(step);
|
|
44
|
+
}
|
|
45
|
+
get hasPending() {
|
|
46
|
+
return this.steps.length > 0;
|
|
47
|
+
}
|
|
48
|
+
get pending() {
|
|
49
|
+
return this.steps.map((s) => s.name);
|
|
50
|
+
}
|
|
51
|
+
/** Re-try every pending step, in registration order. Throttled, synchronous,
|
|
52
|
+
* never throws. Cheap when nothing is pending. */
|
|
53
|
+
check() {
|
|
54
|
+
if (!this.enabled || this.steps.length === 0 || this.running)
|
|
55
|
+
return;
|
|
56
|
+
const t = this.now();
|
|
57
|
+
// `t >= lastCheckAt` guard: a backward wall-clock step must not suppress
|
|
58
|
+
// every check until the clock catches up.
|
|
59
|
+
if (t >= this.lastCheckAt && t - this.lastCheckAt < this.minIntervalMs)
|
|
60
|
+
return;
|
|
61
|
+
this.lastCheckAt = t;
|
|
62
|
+
this.running = true;
|
|
63
|
+
try {
|
|
64
|
+
for (const step of [...this.steps]) {
|
|
65
|
+
let wired = false;
|
|
66
|
+
try {
|
|
67
|
+
wired = step.tryWire() === true;
|
|
68
|
+
}
|
|
69
|
+
catch (err) {
|
|
70
|
+
// Log once per step, then keep retrying quietly.
|
|
71
|
+
if (!this.failed.has(step.name)) {
|
|
72
|
+
this.failed.add(step.name);
|
|
73
|
+
logger.warn(TAG, `step '${step.name}' threw (will keep retrying): ${err instanceof Error ? err.message : String(err)}`);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
if (wired) {
|
|
77
|
+
const i = this.steps.indexOf(step);
|
|
78
|
+
if (i >= 0)
|
|
79
|
+
this.steps.splice(i, 1);
|
|
80
|
+
logger.info(TAG, `wired '${step.name}' after boot — no restart needed`);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
if (this.steps.length === 0)
|
|
84
|
+
this.stop();
|
|
85
|
+
}
|
|
86
|
+
finally {
|
|
87
|
+
this.running = false;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/** Start the background watcher (no-op when nothing is pending). */
|
|
91
|
+
startWatch() {
|
|
92
|
+
if (!this.enabled) {
|
|
93
|
+
if (this.steps.length > 0) {
|
|
94
|
+
logger.warn(TAG, `RC_LATE_WIRING=off — ${this.steps.length} dependency(ies) stay unwired until a restart: ${this.pending.join(', ')}`);
|
|
95
|
+
}
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
if (this.timer || this.steps.length === 0)
|
|
99
|
+
return;
|
|
100
|
+
logger.info(TAG, `${this.steps.length} dependency(ies) not wired at boot (${this.pending.join(', ')}) — watching for the connection to be saved`);
|
|
101
|
+
this.timer = setInterval(() => this.check(), this.watchIntervalMs);
|
|
102
|
+
// Never keep the process alive just for the watcher.
|
|
103
|
+
this.timer.unref?.();
|
|
104
|
+
}
|
|
105
|
+
stop() {
|
|
106
|
+
if (this.timer) {
|
|
107
|
+
clearInterval(this.timer);
|
|
108
|
+
this.timer = undefined;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
export type OperatorHaltMode = 'ACTIVE' | 'PAUSED' | 'STOPPED';
|
|
2
|
+
/** The ONLY tools an operator halt blocks. A denylist on purpose: a tool added
|
|
3
|
+
* tomorrow is never blocked by default (the conservative failure mode). */
|
|
4
|
+
export declare const OPERATOR_HALT_GATED_TOOLS: ReadonlySet<string>;
|
|
5
|
+
export interface OperatorHaltState {
|
|
6
|
+
mode: OperatorHaltMode;
|
|
7
|
+
/** ISO time the current halt began; null when ACTIVE. */
|
|
8
|
+
since: string | null;
|
|
9
|
+
/** Set when the state could not be read and the gate failed closed. */
|
|
10
|
+
unreadable?: string;
|
|
11
|
+
}
|
|
12
|
+
export type OperatorHaltGateMode = 'enforce' | 'shadow' | 'off';
|
|
13
|
+
export declare function resolveOperatorHaltGateMode(): OperatorHaltGateMode;
|
|
14
|
+
/** The operator's current halt. Never throws. */
|
|
15
|
+
export declare function readOperatorHalt(configPath?: string): OperatorHaltState;
|
|
16
|
+
export interface SetOperatorHaltResult {
|
|
17
|
+
ok: boolean;
|
|
18
|
+
mode: OperatorHaltMode;
|
|
19
|
+
previousMode: OperatorHaltMode;
|
|
20
|
+
since: string | null;
|
|
21
|
+
error?: string;
|
|
22
|
+
}
|
|
23
|
+
/** set_operator_halt: `mode` omitted = read the current state (no write).
|
|
24
|
+
* ACTIVE clears the halt; PAUSED / STOPPED set it. Provenance is checked by
|
|
25
|
+
* the registration (operator-only), not here. */
|
|
26
|
+
export declare function setOperatorHaltTool(args: {
|
|
27
|
+
mode?: unknown;
|
|
28
|
+
} | undefined, deps?: {
|
|
29
|
+
configPath?: string;
|
|
30
|
+
now?: () => Date;
|
|
31
|
+
}): SetOperatorHaltResult;
|
|
32
|
+
/** Structured, agent-visible result for a blocked call. Worded so the agent
|
|
33
|
+
* stops cleanly (no retry loop) and keeps managing the existing book. */
|
|
34
|
+
export declare function operatorHaltBlockedResult(name: string, state: OperatorHaltState): {
|
|
35
|
+
ok: false;
|
|
36
|
+
error: 'operator_halt';
|
|
37
|
+
tool: string;
|
|
38
|
+
mode: OperatorHaltMode;
|
|
39
|
+
since: string | null;
|
|
40
|
+
message: string;
|
|
41
|
+
};
|
|
42
|
+
/** Minimal structural view of a registered plugin tool (same shape the other gates use). */
|
|
43
|
+
export interface OperatorHaltGateableTool {
|
|
44
|
+
name: string;
|
|
45
|
+
execute: (...args: never[]) => unknown;
|
|
46
|
+
}
|
|
47
|
+
export declare class OperatorHaltGate {
|
|
48
|
+
private readonly mode;
|
|
49
|
+
private readonly configPath;
|
|
50
|
+
/** One log line per state change, not per blocked call. */
|
|
51
|
+
private lastLoggedKey;
|
|
52
|
+
constructor(opts?: {
|
|
53
|
+
mode?: OperatorHaltGateMode;
|
|
54
|
+
configPath?: string;
|
|
55
|
+
});
|
|
56
|
+
/** The halt that blocks this call, or null. Non-gated names short-circuit
|
|
57
|
+
* FIRST, so no state, mode or file can ever touch the safety set. */
|
|
58
|
+
blocking(name: string): OperatorHaltState | null;
|
|
59
|
+
wrapTool<T extends OperatorHaltGateableTool>(tool: T, jsonResult: (data: unknown) => unknown): T;
|
|
60
|
+
}
|