@reefclaw/openclaw-plugin 0.1.48 → 0.1.50
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 +10 -6
- package/bridge/bridge.js +22 -16
- package/bridge/gateway/gateway-ws-client.d.ts +79 -1
- package/bridge/gateway/gateway-ws-client.js +99 -5
- package/bridge/gateway/heartbeat-cron.d.ts +64 -0
- package/bridge/gateway/heartbeat-cron.js +150 -1
- package/bridge/provider.d.ts +12 -0
- package/bridge/providers/connector-update-direct.d.ts +3 -0
- package/bridge/providers/connector-update-direct.js +11 -1
- package/bridge/providers/connector-update-openclaw.d.ts +268 -0
- package/bridge/providers/connector-update-openclaw.js +772 -0
- package/bridge/providers/connector-update.d.ts +115 -1
- package/bridge/providers/connector-update.js +228 -13
- package/bridge/providers/gateway.d.ts +52 -10
- package/bridge/providers/gateway.js +243 -34
- package/bridge/utils/skill-version.d.ts +6 -0
- package/bridge/utils/skill-version.js +10 -0
- package/config/first-start-venue.d.ts +147 -0
- package/config/first-start-venue.js +400 -0
- package/config/plugin-config-io.d.ts +9 -2
- package/config/plugin-config-io.js +29 -5
- package/connector-supervisor.d.ts +20 -0
- package/connector-supervisor.js +27 -1
- package/index.js +36 -1
- package/openclaw.plugin.json +333 -1
- package/package.json +1 -1
- package/release-integrity.json +10 -0
- package/release-notes.json +3 -1
- package/signals/stop-rules.d.ts +13 -0
- package/signals/stop-rules.js +35 -6
- package/signals/strategy-adapter.js +25 -6
- package/skills/reefclaw/SKILL.md +21 -8
- package/tools/assessment-validation.d.ts +10 -2
- package/tools/assessment-validation.js +19 -5
- package/tools/create-order.d.ts +4 -0
- package/tools/create-order.js +15 -0
- package/tools/intel-cache.d.ts +14 -0
- package/tools/intel-cache.js +59 -0
- package/tools/venue-quote-hint.d.ts +49 -0
- package/tools/venue-quote-hint.js +200 -0
|
@@ -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 {
|
|
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,14 +16,16 @@ 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 {
|
|
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';
|
|
23
24
|
import { executeKill as _executeKill, executeFlatten as _executeFlatten, executePause as _executePause, executeResume as _executeResume, cancelPendingProposals, withProposalDetail, } from './emergency-commands.js';
|
|
24
25
|
import { executeSetTradingMode, executeGetBracketConfig, executeSetBracketRequirement, executeSetExchangeCredentials, executeTestExchangeCredentials, executeClearExchangeCredentials, executeProvisionHlAgentWallet, executeHlAgentWalletStatus, executeSubmitHlAgentApproval, } from './onboarding-commands.js';
|
|
25
|
-
import { startConnectorUpdate, runConnectorUpdate,
|
|
26
|
+
import { startConnectorUpdate, runConnectorUpdate, fetchPinnedRelease, openAdminGatewaySession, checkPositionGuard, describeUnconfirmedConnectVersion, describeUpdateAlreadyRunning, describeUpdateDisabled, tryBeginConnectorUpdate, requestGatewayRestart, RESTART_REASON_OPERATOR, } from './connector-update.js';
|
|
26
27
|
import { isInsideContainer, readContainerProbe, runDirectConnectorUpdate } from './connector-update-direct.js';
|
|
28
|
+
import { getRunningPluginRelease, inspectInstalledPlugin, planConnectorUpdate, runOpenClawPluginUpdate, } from './connector-update-openclaw.js';
|
|
27
29
|
import { DEFAULT_AGENT_ID, isForeignAgentEvent, resolveAgentEventOwner } from '../gateway/agent-scope.js';
|
|
28
30
|
import { noteWebappResponse, webappEdgeTracker, webappHeaders } from '../utils/webapp-edge.js';
|
|
29
31
|
const TAG = 'gateway';
|
|
@@ -186,6 +188,13 @@ export class GatewayProvider {
|
|
|
186
188
|
agentNameReadAtMs = 0;
|
|
187
189
|
/** One-shot latch for the boot-time heartbeat-cron ensure (re-armed on failure). */
|
|
188
190
|
heartbeatCronEnsureStarted = false;
|
|
191
|
+
/** Whether this install's FIRST market check may still run early:
|
|
192
|
+
* 'maybe' while the ensure is in flight, 'pending' from 'created' until
|
|
193
|
+
* runFirstHeartbeat settles, 'none' otherwise (deferToFirstMarketCheck). */
|
|
194
|
+
firstBeatState = 'none';
|
|
195
|
+
/** The bridge's "instructions updated" notice, held while a first check is
|
|
196
|
+
* possible; sent only if that check does not start. Latest wins. */
|
|
197
|
+
deferredSkillNotice = null;
|
|
189
198
|
/** Live heartbeat cadence (seconds), read from the OpenClaw cron store; cached 60s. */
|
|
190
199
|
heartbeatSeconds;
|
|
191
200
|
heartbeatReadAtMs = 0;
|
|
@@ -702,6 +711,47 @@ export class GatewayProvider {
|
|
|
702
711
|
return { received: false, error: reason };
|
|
703
712
|
}
|
|
704
713
|
}
|
|
714
|
+
/** See OpenClawProvider.deferToFirstMarketCheck. Held while this install's
|
|
715
|
+
* first market check may still run early, or while an earlier held notice
|
|
716
|
+
* waits for the socket to come back; the latest notice wins. */
|
|
717
|
+
deferToFirstMarketCheck(send) {
|
|
718
|
+
if (this.firstBeatState === 'none' && !this.deferredSkillNotice)
|
|
719
|
+
return false;
|
|
720
|
+
this.deferredSkillNotice = send;
|
|
721
|
+
return true;
|
|
722
|
+
}
|
|
723
|
+
/** The first market check is settled: send a held notice ('send') or drop
|
|
724
|
+
* it ('drop': the check started, or may have, and reads the new
|
|
725
|
+
* instructions itself). A stopped provider sends nothing. If the socket is
|
|
726
|
+
* down right now (the settle may be BECAUSE it dropped), the notice stays
|
|
727
|
+
* held and goes out on the next connect (flushHeldSkillNotice) instead of
|
|
728
|
+
* being lost. */
|
|
729
|
+
settleFirstBeat(action) {
|
|
730
|
+
this.firstBeatState = 'none';
|
|
731
|
+
if (!this.deferredSkillNotice)
|
|
732
|
+
return;
|
|
733
|
+
if (action === 'drop' || !this.started) {
|
|
734
|
+
this.deferredSkillNotice = null;
|
|
735
|
+
return;
|
|
736
|
+
}
|
|
737
|
+
if (this.wsClient?.getState() !== 'connected') {
|
|
738
|
+
logger.info(TAG, 'Held "instructions updated" chat notice kept for the next gateway connect (the socket is down)');
|
|
739
|
+
return;
|
|
740
|
+
}
|
|
741
|
+
this.flushHeldSkillNotice();
|
|
742
|
+
}
|
|
743
|
+
/** Send a held notice once nothing is pending any more (settle, or the next
|
|
744
|
+
* connect after a settle that found the socket down). */
|
|
745
|
+
flushHeldSkillNotice() {
|
|
746
|
+
if (this.firstBeatState !== 'none' || !this.started)
|
|
747
|
+
return;
|
|
748
|
+
const send = this.deferredSkillNotice;
|
|
749
|
+
this.deferredSkillNotice = null;
|
|
750
|
+
if (!send)
|
|
751
|
+
return;
|
|
752
|
+
logger.info(TAG, 'Sending the held "instructions updated" chat notice (the first market check did not start early)');
|
|
753
|
+
send();
|
|
754
|
+
}
|
|
705
755
|
async closePosition(symbol) {
|
|
706
756
|
const tool = this.toolMap.close_position;
|
|
707
757
|
if (!tool || !this.http) {
|
|
@@ -768,15 +818,21 @@ export class GatewayProvider {
|
|
|
768
818
|
* Operator-only. Update the ReefClaw connector on this box to the latest
|
|
769
819
|
* published version.
|
|
770
820
|
*
|
|
771
|
-
*
|
|
772
|
-
*
|
|
773
|
-
*
|
|
774
|
-
*
|
|
775
|
-
*
|
|
821
|
+
* Two update paths, chosen by how the plugin was installed (plugins.inspect
|
|
822
|
+
* over the admin session, after every guard):
|
|
823
|
+
* - a copy OpenClaw installed from ClawHub → OpenClaw's own plugins.install
|
|
824
|
+
* (update mode), pinned to the exact PLUGIN release ReefClaw's public
|
|
825
|
+
* release endpoint reports, then a gateway self-restart
|
|
826
|
+
* (providers/connector-update-openclaw.ts);
|
|
827
|
+
* - everything else → the connect installer over the gateway's PTY, or run
|
|
828
|
+
* directly (files-only) where there is no usable terminal, pinned to the
|
|
829
|
+
* exact CONNECTOR release (providers/connector-update.ts).
|
|
830
|
+
* The RPC carries no command/version/args parameter and never should — the
|
|
831
|
+
* versions are looked up by this process, never taken from the caller.
|
|
776
832
|
*
|
|
777
|
-
* The
|
|
778
|
-
*
|
|
779
|
-
* `restarting` and the dashboard waits for the reconnect.
|
|
833
|
+
* The update restarts the gateway when it finishes, which kills both the
|
|
834
|
+
* session and this process's own transport. That is the SUCCESS path: we
|
|
835
|
+
* report `restarting` and the dashboard waits for the reconnect.
|
|
780
836
|
*/
|
|
781
837
|
async updateConnector(args) {
|
|
782
838
|
// Per-host opt-out FIRST: a box whose operator switched this off must
|
|
@@ -803,16 +859,51 @@ export class GatewayProvider {
|
|
|
803
859
|
const blocked = checkPositionGuard(guardArgs);
|
|
804
860
|
if (blocked)
|
|
805
861
|
return blocked;
|
|
806
|
-
//
|
|
862
|
+
// ONE update at a time, process-wide (connector-update.ts
|
|
863
|
+
// tryBeginConnectorUpdate): the dashboard's busy flag is per browser, so a
|
|
864
|
+
// second tab or device can ask again mid-install — and a second run's
|
|
865
|
+
// gateway restart would kill the first run's install mid-stage. Taken
|
|
866
|
+
// synchronously, before the first await, so two requests cannot interleave;
|
|
867
|
+
// released when the run ends, whichever way (a background run releases it
|
|
868
|
+
// itself — `handedOff`).
|
|
869
|
+
const endUpdate = tryBeginConnectorUpdate();
|
|
870
|
+
if (!endUpdate) {
|
|
871
|
+
logger.info(TAG, 'connector.update refused: an update is already running on this box');
|
|
872
|
+
return describeUpdateAlreadyRunning();
|
|
873
|
+
}
|
|
874
|
+
let handedOff = false;
|
|
875
|
+
try {
|
|
876
|
+
return await this.updateConnectorLocked(guardArgs, () => {
|
|
877
|
+
handedOff = true;
|
|
878
|
+
return endUpdate;
|
|
879
|
+
});
|
|
880
|
+
}
|
|
881
|
+
finally {
|
|
882
|
+
if (!handedOff)
|
|
883
|
+
endUpdate();
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
/** updateConnector past its guards and holding the one-update lock.
|
|
887
|
+
* `handOff()` is called by a path that returns while its run continues in
|
|
888
|
+
* the background; that run releases the lock (the returned function) when
|
|
889
|
+
* it ends. */
|
|
890
|
+
async updateConnectorLocked(guardArgs, handOff) {
|
|
891
|
+
if (!this.wsClient) {
|
|
892
|
+
return { ok: false, status: 'failed', message: 'Not connected to the OpenClaw gateway.' };
|
|
893
|
+
}
|
|
894
|
+
// Which version? Only the ones ReefClaw vouches for, fetched by THIS
|
|
807
895
|
// process from the public release endpoint — never `@latest`, never a
|
|
808
|
-
// caller-supplied string.
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
//
|
|
815
|
-
//
|
|
896
|
+
// caller-supplied string. One request, both releases (connector + plugin);
|
|
897
|
+
// each path below refuses when ITS release is missing. Neither confirmed ⇒
|
|
898
|
+
// no update, before any gateway call.
|
|
899
|
+
const release = await fetchPinnedRelease({});
|
|
900
|
+
if (!release.ok)
|
|
901
|
+
return release.outcome;
|
|
902
|
+
// terminal.* and plugins.install are operator.admin-only (OpenClaw
|
|
903
|
+
// method-scopes). The long-lived session runs on operator.read/write by
|
|
904
|
+
// design, so open a SEPARATE short-lived admin session for this update.
|
|
905
|
+
// Reconnects are effectively disabled: the gateway restart is supposed to
|
|
906
|
+
// kill it.
|
|
816
907
|
const admin = new GatewayWsClient({
|
|
817
908
|
gatewayUrl: this.config.gatewayUrl,
|
|
818
909
|
gatewayToken: this.config.gatewayToken,
|
|
@@ -825,6 +916,38 @@ export class GatewayProvider {
|
|
|
825
916
|
if (!session.ok)
|
|
826
917
|
return session.outcome;
|
|
827
918
|
const rpc = (method, params) => admin.sendRpc(method, params);
|
|
919
|
+
// ★ Who installed this copy? Decided BEFORE picking PTY / direct: a copy
|
|
920
|
+
// OpenClaw installed from ClawHub (the no-terminal onboarding route) is
|
|
921
|
+
// not the connect installer's to update — the installer refuses it
|
|
922
|
+
// (ALREADY_INSTALLED_MARKER) — so it goes through OpenClaw's own
|
|
923
|
+
// plugins.install instead. No usable answer (older OpenClaw, an error) or
|
|
924
|
+
// a path install keeps today's installer path, unchanged.
|
|
925
|
+
const inspected = await inspectInstalledPlugin(rpc);
|
|
926
|
+
const plan = planConnectorUpdate(inspected, { pluginVersion: release.pluginVersion });
|
|
927
|
+
logger.info(TAG, `connector.update: route=${plan.path} (${plan.reason})`);
|
|
928
|
+
if (plan.path === 'blocked') {
|
|
929
|
+
admin.destroy();
|
|
930
|
+
return plan.outcome;
|
|
931
|
+
}
|
|
932
|
+
if (plan.path === 'openclaw') {
|
|
933
|
+
// opts only when given, so every other call is the byte-identical
|
|
934
|
+
// two-argument sendRpc it always was.
|
|
935
|
+
const gatewayRpc = (method, params, opts) => opts ? admin.sendRpc(method, params, opts) : admin.sendRpc(method, params);
|
|
936
|
+
const running = getRunningPluginRelease();
|
|
937
|
+
return this.runOpenClawUpdate(gatewayRpc, admin, {
|
|
938
|
+
inspect: inspected,
|
|
939
|
+
pinnedPluginVersion: release.pluginVersion,
|
|
940
|
+
hello: admin.getHelloInfo(),
|
|
941
|
+
runningRelease: running.version,
|
|
942
|
+
runningReleaseLoadedByGateway: running.loadedByGateway,
|
|
943
|
+
}, handOff());
|
|
944
|
+
}
|
|
945
|
+
// The installer path needs the exact CONNECTOR release.
|
|
946
|
+
if (release.connectVersion === null) {
|
|
947
|
+
admin.destroy();
|
|
948
|
+
return describeUnconfirmedConnectVersion();
|
|
949
|
+
}
|
|
950
|
+
const connectVersion = release.connectVersion;
|
|
828
951
|
// Inside a container the PTY path is the wrong tool even where the
|
|
829
952
|
// terminal RPC exists: the full installer runs the `openclaw` CLI inside
|
|
830
953
|
// the live gateway (a second plugin stack) and cannot restart the
|
|
@@ -832,14 +955,14 @@ export class GatewayProvider {
|
|
|
832
955
|
// the gateway restart itself (connector-update-direct.ts).
|
|
833
956
|
if (isInsideContainer(readContainerProbe())) {
|
|
834
957
|
logger.info(TAG, 'connector.update: container detected — running the installer directly (files-only)');
|
|
835
|
-
return this.runDirectUpdate(rpc,
|
|
958
|
+
return this.runDirectUpdate(rpc, connectVersion, admin, release.pluginVersion, handOff());
|
|
836
959
|
}
|
|
837
|
-
const started = await startConnectorUpdate(rpc, guardArgs,
|
|
960
|
+
const started = await startConnectorUpdate(rpc, guardArgs, connectVersion);
|
|
838
961
|
if (started.status === 'blocked' && started.directFallback) {
|
|
839
962
|
// The gateway has no usable terminal (OpenClaw < 2026.7, terminal
|
|
840
963
|
// disabled, sandboxed agent). The connector does not need one.
|
|
841
964
|
logger.info(TAG, `connector.update: no gateway terminal (${started.message}) — running the installer directly`);
|
|
842
|
-
return this.runDirectUpdate(rpc,
|
|
965
|
+
return this.runDirectUpdate(rpc, connectVersion, admin, release.pluginVersion, handOff());
|
|
843
966
|
}
|
|
844
967
|
if (started.status !== 'started' || !started.sessionId) {
|
|
845
968
|
admin.destroy();
|
|
@@ -847,17 +970,23 @@ export class GatewayProvider {
|
|
|
847
970
|
}
|
|
848
971
|
// Stream progress in the background; the RPC returns as soon as the command
|
|
849
972
|
// is running so the browser is never left waiting on a minutes-long call.
|
|
850
|
-
// The admin session is torn down
|
|
851
|
-
|
|
973
|
+
// The admin session is torn down, and the one-update lock released, when
|
|
974
|
+
// the loop ends, whichever way.
|
|
975
|
+
const endUpdate = handOff();
|
|
976
|
+
void runConnectorUpdate(rpc, started.sessionId, (outcome) => this.emitConnectorUpdate(outcome), {
|
|
977
|
+
pluginVersion: release.pluginVersion,
|
|
978
|
+
}).finally(() => {
|
|
852
979
|
admin.destroy();
|
|
980
|
+
endUpdate();
|
|
853
981
|
});
|
|
854
982
|
return started;
|
|
855
983
|
}
|
|
856
984
|
/** The direct (no-PTY) update. Resolves the RPC with the `started` frame as
|
|
857
985
|
* soon as the installer is running (or the refusal), streams the rest as
|
|
858
|
-
* connector_update events, and tears the admin session down
|
|
859
|
-
* the same contract as the PTY
|
|
860
|
-
|
|
986
|
+
* connector_update events, and tears the admin session down (and releases
|
|
987
|
+
* the one-update lock, `onEnd`) at the end — the same contract as the PTY
|
|
988
|
+
* path. */
|
|
989
|
+
runDirectUpdate(rpc, version, admin, pluginVersion, onEnd) {
|
|
861
990
|
return new Promise((resolve) => {
|
|
862
991
|
let answered = false;
|
|
863
992
|
const answer = (outcome) => {
|
|
@@ -872,9 +1001,41 @@ export class GatewayProvider {
|
|
|
872
1001
|
this.emitConnectorUpdate(outcome);
|
|
873
1002
|
if (outcome.status === 'started')
|
|
874
1003
|
answer(outcome);
|
|
1004
|
+
}, { pluginVersion })
|
|
1005
|
+
.then((final) => answer(final))
|
|
1006
|
+
.finally(() => {
|
|
1007
|
+
admin.destroy();
|
|
1008
|
+
onEnd();
|
|
1009
|
+
});
|
|
1010
|
+
});
|
|
1011
|
+
}
|
|
1012
|
+
/** The OpenClaw (plugins.install) update. Same contract as the direct path:
|
|
1013
|
+
* the RPC resolves with the first `started` frame (a restart-only run sends
|
|
1014
|
+
* one too, before it asks the gateway to restart) else with the final
|
|
1015
|
+
* outcome (a refusal decided before anything ran, or "already up to
|
|
1016
|
+
* date"); every emitted frame also goes out as a connector_update event.
|
|
1017
|
+
* The admin session stays open for the whole install (OpenClaw 2026.9.7
|
|
1018
|
+
* re-checks the caller's admin authority before persisting) and is torn
|
|
1019
|
+
* down — and the one-update lock released (`onEnd`) — at the end. */
|
|
1020
|
+
runOpenClawUpdate(rpc, admin, ctx, onEnd) {
|
|
1021
|
+
return new Promise((resolve) => {
|
|
1022
|
+
let answered = false;
|
|
1023
|
+
const answer = (outcome) => {
|
|
1024
|
+
if (answered)
|
|
1025
|
+
return;
|
|
1026
|
+
answered = true;
|
|
1027
|
+
resolve(outcome);
|
|
1028
|
+
};
|
|
1029
|
+
void runOpenClawPluginUpdate(rpc, ctx, (outcome) => {
|
|
1030
|
+
this.emitConnectorUpdate(outcome);
|
|
1031
|
+
if (outcome.status === 'started')
|
|
1032
|
+
answer(outcome);
|
|
875
1033
|
})
|
|
876
1034
|
.then((final) => answer(final))
|
|
877
|
-
.finally(() =>
|
|
1035
|
+
.finally(() => {
|
|
1036
|
+
admin.destroy();
|
|
1037
|
+
onEnd();
|
|
1038
|
+
});
|
|
878
1039
|
});
|
|
879
1040
|
}
|
|
880
1041
|
/**
|
|
@@ -1112,12 +1273,16 @@ export class GatewayProvider {
|
|
|
1112
1273
|
// Step 3: Create WS client and connect FIRST to obtain device token.
|
|
1113
1274
|
// OpenClaw's REST API requires a device token from the WS handshake,
|
|
1114
1275
|
// not the raw gateway auth token. Tool discovery must wait for this.
|
|
1115
|
-
// Least privilege: operator.admin (cron
|
|
1116
|
-
//
|
|
1117
|
-
//
|
|
1276
|
+
// Least privilege: operator.admin (cron.add / cron.run) is requested only
|
|
1277
|
+
// when this process starts with the once-per-install heartbeat ensure
|
|
1278
|
+
// still owed: no marker yet, or an old-rule marker that adopted a job that
|
|
1279
|
+
// is not ReefClaw's (heartbeatEnsureOwed — the same check the ensure
|
|
1280
|
+
// itself runs on, so the re-check always has the scope it needs). This
|
|
1281
|
+
// client keeps the scope across reconnects until the bridge restarts;
|
|
1282
|
+
// every later process runs on operator.read/write alone.
|
|
1118
1283
|
this.wsClient = new GatewayWsClient({
|
|
1119
1284
|
...this.config,
|
|
1120
|
-
requestAdminScope:
|
|
1285
|
+
requestAdminScope: heartbeatEnsureOwed(join(this.workspaceDir(), 'heartbeat-cron-ensured.json')),
|
|
1121
1286
|
});
|
|
1122
1287
|
this.wireWsEvents();
|
|
1123
1288
|
// Wait for WS handshake to complete (or fail)
|
|
@@ -1459,9 +1624,14 @@ export class GatewayProvider {
|
|
|
1459
1624
|
// A box with no chat channel gets delivery `none`: announce can only
|
|
1460
1625
|
// fail there and would record every beat as an error (2026-09-27).
|
|
1461
1626
|
const channelsConfigured = hasConfiguredChannels(readOpenClawConfigFile());
|
|
1627
|
+
const markerPath = join(this.workspaceDir(), 'heartbeat-cron-ensured.json');
|
|
1628
|
+
// A first market check is possible only while the ensure is owed; hold
|
|
1629
|
+
// the bridge's update notice from now until it is known either way.
|
|
1630
|
+
if (heartbeatEnsureOwed(markerPath))
|
|
1631
|
+
this.firstBeatState = 'maybe';
|
|
1462
1632
|
void ensureHeartbeatCron({
|
|
1463
1633
|
rpc: ws,
|
|
1464
|
-
markerPath
|
|
1634
|
+
markerPath,
|
|
1465
1635
|
log: (msg) => logger.info(TAG, msg),
|
|
1466
1636
|
// Scoped to the agent we serve: on a shared gateway the business
|
|
1467
1637
|
// agent's own heartbeat must not suppress the trading agent's, and
|
|
@@ -1473,8 +1643,45 @@ export class GatewayProvider {
|
|
|
1473
1643
|
// A transient failure retries on the next (re)connect, not just next boot.
|
|
1474
1644
|
if (outcome === 'failed') {
|
|
1475
1645
|
this.heartbeatCronEnsureStarted = false;
|
|
1646
|
+
this.settleFirstBeat('send');
|
|
1476
1647
|
return;
|
|
1477
1648
|
}
|
|
1649
|
+
// The job did not exist until now (a fresh install, or a box whose
|
|
1650
|
+
// old marker adopted a job that was not ReefClaw's, so it never had
|
|
1651
|
+
// a ReefClaw beat): run the first market check as soon as the full
|
|
1652
|
+
// instructions are in place instead of one interval later. Same
|
|
1653
|
+
// client — cron.run needs the admin scope this session was opened
|
|
1654
|
+
// with. Never on an existing job ('found_existing' /
|
|
1655
|
+
// 'already_ensured'): that would add beats to a running agent.
|
|
1656
|
+
if (outcome === 'created') {
|
|
1657
|
+
this.firstBeatState = 'pending';
|
|
1658
|
+
void runFirstHeartbeat({
|
|
1659
|
+
rpc: ws,
|
|
1660
|
+
log: (msg) => logger.info(TAG, msg),
|
|
1661
|
+
agentId: this.agentId(),
|
|
1662
|
+
agentIsDefault: this.config.agentIsDefault ?? true,
|
|
1663
|
+
// The tracker copy AND every copy the agent can load: a bootstrap
|
|
1664
|
+
// copy left in an extension or workspace skills dir would make
|
|
1665
|
+
// the first beat a wasted run.
|
|
1666
|
+
instructionsReady: () => {
|
|
1667
|
+
const dir = this.workspaceDir();
|
|
1668
|
+
if (isBootstrapSkillVersion(readLocalSkillVersion(dir)))
|
|
1669
|
+
return false;
|
|
1670
|
+
return readAgentVisibleSkillVersions(dir).every((v) => !isBootstrapSkillVersion(v));
|
|
1671
|
+
},
|
|
1672
|
+
isActive: () => this.started && this.wsClient === ws,
|
|
1673
|
+
})
|
|
1674
|
+
.catch(() => 'failed')
|
|
1675
|
+
// Started, or may have started ('unknown': cron.run was sent
|
|
1676
|
+
// but its answer was lost): the check reads the new
|
|
1677
|
+
// instructions, so a held notice is dropped. Gone ('inactive'):
|
|
1678
|
+
// nothing to tell. Otherwise the held notice goes out, as it
|
|
1679
|
+
// always did.
|
|
1680
|
+
.then((first) => this.settleFirstBeat(first === 'started' || first === 'unknown' || first === 'inactive' ? 'drop' : 'send'));
|
|
1681
|
+
}
|
|
1682
|
+
else {
|
|
1683
|
+
this.settleFirstBeat('send');
|
|
1684
|
+
}
|
|
1478
1685
|
// Existing jobs predate the rule above — repair them in place.
|
|
1479
1686
|
void reconcileHeartbeatDelivery({
|
|
1480
1687
|
rpc: ws,
|
|
@@ -1486,6 +1693,8 @@ export class GatewayProvider {
|
|
|
1486
1693
|
});
|
|
1487
1694
|
}
|
|
1488
1695
|
}
|
|
1696
|
+
// A notice whose first-check settle found the socket down goes out now.
|
|
1697
|
+
this.flushHeldSkillNotice();
|
|
1489
1698
|
// Start periodic agent state emission (every 5s)
|
|
1490
1699
|
if (!this.agentStateInterval) {
|
|
1491
1700
|
this.agentStateInterval = setInterval(() => {
|
|
@@ -29,3 +29,9 @@ export declare function validateSkillContent(content: string): {
|
|
|
29
29
|
version: string | null;
|
|
30
30
|
error?: string;
|
|
31
31
|
};
|
|
32
|
+
/** True while the agent is still on the thin bootstrap SKILL.md and has NOT yet
|
|
33
|
+
* received the full trading instructions. The bootstrap ships 0.0.x; the full
|
|
34
|
+
* trading SKILL.md is 2.x — treat anything below 1.0.0 (or an unknown version)
|
|
35
|
+
* as bootstrap. Shared by the bridge (pull/heal) and the gateway provider
|
|
36
|
+
* (first heartbeat after a fresh install). */
|
|
37
|
+
export declare function isBootstrapSkillVersion(version: string | null | undefined): boolean;
|
|
@@ -128,3 +128,13 @@ export function validateSkillContent(content) {
|
|
|
128
128
|
}
|
|
129
129
|
return { valid: true, version };
|
|
130
130
|
}
|
|
131
|
+
/** True while the agent is still on the thin bootstrap SKILL.md and has NOT yet
|
|
132
|
+
* received the full trading instructions. The bootstrap ships 0.0.x; the full
|
|
133
|
+
* trading SKILL.md is 2.x — treat anything below 1.0.0 (or an unknown version)
|
|
134
|
+
* as bootstrap. Shared by the bridge (pull/heal) and the gateway provider
|
|
135
|
+
* (first heartbeat after a fresh install). */
|
|
136
|
+
export function isBootstrapSkillVersion(version) {
|
|
137
|
+
if (!version)
|
|
138
|
+
return true;
|
|
139
|
+
return compareSemver('1.0.0', version) > 0; // '1.0.0' > version ⟺ version < 1.0.0
|
|
140
|
+
}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { type VenueId } from '../venues/symbols.js';
|
|
2
|
+
import { updatePluginConfig } from './plugin-config-io.js';
|
|
3
|
+
/** = index.ts PLUGIN_ID, the StateManager directory name (pinned by test). */
|
|
4
|
+
export declare const FIRST_START_PLUGIN_ID = "reefclaw-paper-trading";
|
|
5
|
+
/** The marker left in <OpenClaw state dir>/plugins/<pluginId>/ when that dir
|
|
6
|
+
* is not the plugin's own $HOME state dir. */
|
|
7
|
+
export declare const FIRST_START_MARKER_FILE = "first-start.json";
|
|
8
|
+
/** Keys the connect installer writes into plugin-config.json before the
|
|
9
|
+
* plugin's first start. Same table as installer/src/venue-config.ts
|
|
10
|
+
* isInstallerOwned — change both together. `connectorSupervisor` counts only
|
|
11
|
+
* as the installer's 'on'; an 'off' is a deliberate human setting. */
|
|
12
|
+
export declare function isInstallerOwnedKey(key: string, value: unknown): boolean;
|
|
13
|
+
export type SavedVenue = {
|
|
14
|
+
kind: 'none';
|
|
15
|
+
} | {
|
|
16
|
+
kind: 'venue';
|
|
17
|
+
venue: VenueId;
|
|
18
|
+
} | {
|
|
19
|
+
kind: 'unrecognized';
|
|
20
|
+
shown: string;
|
|
21
|
+
};
|
|
22
|
+
/** Tolerant parse (an agent wrote it): strings only, trimmed + lowercased,
|
|
23
|
+
* and only the exact ids 'hyperliquid' / 'binance' after that. */
|
|
24
|
+
export declare function parseSavedVenue(raw: unknown): SavedVenue;
|
|
25
|
+
export type PluginConfigView = {
|
|
26
|
+
kind: 'absent';
|
|
27
|
+
} | {
|
|
28
|
+
kind: 'unreadable';
|
|
29
|
+
} | {
|
|
30
|
+
kind: 'object';
|
|
31
|
+
value: Record<string, unknown>;
|
|
32
|
+
};
|
|
33
|
+
export type FirstStartVenueSkipReason = 'disabled' | 'not-requested' | 'ran-before' | 'unrecognized' | 'binance-default' | 'unreadable' | 'already-set' | 'configured-before';
|
|
34
|
+
export type FirstStartVenueDecision = {
|
|
35
|
+
action: 'write';
|
|
36
|
+
venue: 'hyperliquid';
|
|
37
|
+
} | {
|
|
38
|
+
action: 'skip';
|
|
39
|
+
reason: Exclude<FirstStartVenueSkipReason, 'disabled'>;
|
|
40
|
+
};
|
|
41
|
+
/** Pure. Order matters: `ran-before` is checked before garbage, so a box that
|
|
42
|
+
* ran before never warns about its saved value on every restart. */
|
|
43
|
+
export declare function decideFirstStartVenue(input: {
|
|
44
|
+
saved: SavedVenue;
|
|
45
|
+
ranBefore: boolean;
|
|
46
|
+
pluginConfig: PluginConfigView;
|
|
47
|
+
}): FirstStartVenueDecision;
|
|
48
|
+
/** The state dir and the transport key are written only by this plugin's
|
|
49
|
+
* first full register() (StateManager, ensureCredentialTransportKey); the
|
|
50
|
+
* OpenClaw-side dir only by markFirstStart below. Any one present = ran
|
|
51
|
+
* before. */
|
|
52
|
+
export declare function pluginRanBefore(paths: {
|
|
53
|
+
stateDir: string;
|
|
54
|
+
transportKeyFile: string;
|
|
55
|
+
openclawPluginDir?: string;
|
|
56
|
+
}): boolean;
|
|
57
|
+
export type FirstStartMarkOutcome = 'not-needed' | 'present' | 'written' | 'failed';
|
|
58
|
+
/** Record that ReefClaw has started on this OpenClaw state, in OpenClaw's
|
|
59
|
+
* state dir, when that is not where StateManager already records it (the
|
|
60
|
+
* $HOME state dir). Exclusive create: never overwrites. Never throws. */
|
|
61
|
+
export declare function markFirstStart(paths: {
|
|
62
|
+
stateDir: string;
|
|
63
|
+
openclawPluginDir: string;
|
|
64
|
+
}, now?: Date): FirstStartMarkOutcome;
|
|
65
|
+
/** plugin-config.json as this rule sees it. Never throws. A symlink or a
|
|
66
|
+
* directory is `unreadable` (never written through), as is bad JSON, a BOM,
|
|
67
|
+
* or a non-object root. */
|
|
68
|
+
export declare function viewPluginConfig(path: string): PluginConfigView;
|
|
69
|
+
/** The saved onboarding venue, raw. OpenClaw's own resolved config handed to
|
|
70
|
+
* register() (api.config) first: it is the running gateway's config, and a
|
|
71
|
+
* config file at a default location may belong to another layout. The file
|
|
72
|
+
* only when api.config holds no venue (the agent wrote the file a moment
|
|
73
|
+
* before the hot-load). Nested `.config.venue` only. */
|
|
74
|
+
export declare function readSavedVenue(openclawConfig?: unknown, openclawConfigPath?: string): unknown;
|
|
75
|
+
/** Mirror of OpenClaw's resolveStateDir (src/config/state-dir.ts, v2026.9.7)
|
|
76
|
+
* without its legacy-dir fallback: OPENCLAW_STATE_DIR (a `~` expands against
|
|
77
|
+
* the effective home), else <effective home>/.openclaw, where the effective
|
|
78
|
+
* home is OPENCLAW_HOME, else the OS home. */
|
|
79
|
+
export declare function openClawStateDirFromEnv(env: NodeJS.ProcessEnv, home: string): string;
|
|
80
|
+
/** OpenClaw's state dir: the host's own answer when it hands one over
|
|
81
|
+
* (api.runtime.state.resolveStateDir on 2026.9.x, through `hostStateDir`),
|
|
82
|
+
* else the env mirror. Never throws. */
|
|
83
|
+
export declare function resolveOpenClawStateDir(input: {
|
|
84
|
+
hostStateDir?: () => unknown;
|
|
85
|
+
env: NodeJS.ProcessEnv;
|
|
86
|
+
home: string;
|
|
87
|
+
}): string;
|
|
88
|
+
export interface FirstStartPaths {
|
|
89
|
+
/** = plugin-config-io defaultConfigPath(). */
|
|
90
|
+
pluginConfigPath: string;
|
|
91
|
+
/** = dirname(new StateManager(pluginId).getStatePath()). */
|
|
92
|
+
stateDir: string;
|
|
93
|
+
/** = the file ensureCredentialTransportKey() writes with no dir. */
|
|
94
|
+
transportKeyFile: string;
|
|
95
|
+
/** <OpenClaw state dir>/plugins/<pluginId>: the marker's home. */
|
|
96
|
+
openclawPluginDir: string;
|
|
97
|
+
/** OPENCLAW_CONFIG_PATH, else <OpenClaw state dir>/openclaw.json. */
|
|
98
|
+
openclawConfigPath: string;
|
|
99
|
+
}
|
|
100
|
+
/** The default paths. Exported so tests pin them against the code that
|
|
101
|
+
* creates each one (StateManager, ensureCredentialTransportKey,
|
|
102
|
+
* defaultConfigPath) rather than against a literal. */
|
|
103
|
+
export declare function defaultFirstStartPaths(input: {
|
|
104
|
+
home: string;
|
|
105
|
+
pluginId: string;
|
|
106
|
+
openclawStateDir: string;
|
|
107
|
+
env: NodeJS.ProcessEnv;
|
|
108
|
+
}): FirstStartPaths;
|
|
109
|
+
export interface ApplyFirstStartVenueOptions {
|
|
110
|
+
/** register()'s api.config (OpenClaw's resolved config) — read first. */
|
|
111
|
+
openclawConfig?: unknown;
|
|
112
|
+
/** Lazily yields OpenClaw's own state dir (api.runtime.state.resolveStateDir);
|
|
113
|
+
* called inside the never-throw boundary. */
|
|
114
|
+
hostStateDir?: () => unknown;
|
|
115
|
+
/** Defaults to FIRST_START_PLUGIN_ID; decides the default state dirs. */
|
|
116
|
+
pluginId?: string;
|
|
117
|
+
/** Test seams. Defaults: defaultFirstStartPaths(). */
|
|
118
|
+
pluginConfigPath?: string;
|
|
119
|
+
stateDir?: string;
|
|
120
|
+
transportKeyFile?: string;
|
|
121
|
+
openclawPluginDir?: string;
|
|
122
|
+
openclawConfigPath?: string;
|
|
123
|
+
/** Test seam: OpenClaw's state dir (default resolveOpenClawStateDir()). */
|
|
124
|
+
openclawStateDir?: string;
|
|
125
|
+
env?: NodeJS.ProcessEnv;
|
|
126
|
+
/** Test seam for the atomic writer (default updatePluginConfig). */
|
|
127
|
+
writePluginConfig?: typeof updatePluginConfig;
|
|
128
|
+
}
|
|
129
|
+
export type FirstStartVenueResult = {
|
|
130
|
+
outcome: 'applied';
|
|
131
|
+
venue: 'hyperliquid';
|
|
132
|
+
} | {
|
|
133
|
+
outcome: 'skipped';
|
|
134
|
+
reason: FirstStartVenueSkipReason;
|
|
135
|
+
} | {
|
|
136
|
+
outcome: 'failed';
|
|
137
|
+
error: string;
|
|
138
|
+
};
|
|
139
|
+
/** See the file header. Synchronous (register() must be), never throws. */
|
|
140
|
+
export declare function applyFirstStartVenue(options?: ApplyFirstStartVenueOptions): FirstStartVenueResult;
|
|
141
|
+
/** The venue this box will actually start on, for log lines: what
|
|
142
|
+
* plugin-config.json selects, read the way index.ts reads it (following a
|
|
143
|
+
* symlink; unreadable = the Binance default). Never throws. */
|
|
144
|
+
export declare function describeSelectedVenue(path: string): {
|
|
145
|
+
venue: VenueId;
|
|
146
|
+
text: string;
|
|
147
|
+
};
|