@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.
Files changed (38) hide show
  1. package/README.md +6 -2
  2. package/bridge/config.js +10 -3
  3. package/bridge/gateway/heartbeat-cron.d.ts +96 -2
  4. package/bridge/gateway/heartbeat-cron.js +274 -16
  5. package/bridge/gateway/tool-discovery.d.ts +1 -1
  6. package/bridge/gateway/tool-discovery.js +4 -0
  7. package/bridge/heartbeat-runs.d.ts +24 -0
  8. package/bridge/heartbeat-runs.js +106 -5
  9. package/bridge/heartbeat-transcript.d.ts +18 -1
  10. package/bridge/heartbeat-transcript.js +103 -19
  11. package/bridge/index.js +2 -2
  12. package/bridge/providers/emergency-commands.d.ts +26 -1
  13. package/bridge/providers/emergency-commands.js +74 -4
  14. package/bridge/providers/gateway.d.ts +27 -0
  15. package/bridge/providers/gateway.js +155 -14
  16. package/bridge/setup.js +6 -3
  17. package/bridge/types.d.ts +12 -0
  18. package/bridge/utils/relay-host.d.ts +16 -0
  19. package/bridge/utils/relay-host.js +30 -1
  20. package/config/late-wiring.d.ts +37 -0
  21. package/config/late-wiring.js +111 -0
  22. package/config/operator-halt.d.ts +60 -0
  23. package/config/operator-halt.js +160 -0
  24. package/config/plugin-config-io.d.ts +7 -0
  25. package/config/tool-gate.js +3 -0
  26. package/index.js +255 -45
  27. package/openclaw.plugin.json +8 -2
  28. package/package.json +1 -1
  29. package/release-integrity.json +15 -0
  30. package/release-notes.json +4 -1
  31. package/skills/reefclaw/SKILL.md +1 -1
  32. package/strategy/builtin-strategies.js +2 -2
  33. package/tools/get-market-intel.js +2 -1
  34. package/tools/get-risk-summary.d.ts +5 -0
  35. package/tools/get-risk-summary.js +5 -0
  36. package/tools/intel-api.d.ts +10 -0
  37. package/tools/intel-api.js +13 -1
  38. package/tools/score-setup.js +4 -2
package/index.js CHANGED
@@ -18,6 +18,7 @@ import { ExchangeSimulator } from './simulator/exchange-simulator.js';
18
18
  import { ShadowTracker } from './shadow/shadow-tracker.js';
19
19
  import { StateManager } from './persistence/state-manager.js';
20
20
  import { logger, setLogLevel, formatError } from './logger.js';
21
+ import { LateWiring } from './config/late-wiring.js';
21
22
  import { DEFAULT_CONFIG } from './types.js';
22
23
  import { PaperAdapter } from './paper-adapter.js';
23
24
  import { LiveAdapter, } from './live/live-adapter.js';
@@ -62,6 +63,7 @@ import { ToolGate } from './config/tool-gate.js';
62
63
  import { wrapToolWithHyperliquidQuoteHint } from './tools/venue-quote-hint.js';
63
64
  import { gateStore } from './config/gate-store.js';
64
65
  import { entitlementGate } from './config/entitlement-gate.js';
66
+ import { OperatorHaltGate, setOperatorHaltTool } from './config/operator-halt.js';
65
67
  import { startAgentConfigPoller } from './config/agent-config-poller.js';
66
68
  import { PositionWatcher } from './live/stop-watcher.js';
67
69
  import { PaperMarketFeed } from './simulator/paper-market-feed.js';
@@ -891,6 +893,14 @@ const TOOL_PARAMS = {
891
893
  },
892
894
  required: ['flag', 'value'],
893
895
  },
896
+ set_operator_halt: {
897
+ type: 'object',
898
+ properties: {
899
+ operator_token: { type: 'string', description: 'Operator provenance — a per-boot secret that exists only inside the ReefClaw connector process and is attached by the dashboard path. It is not available to the agent; agent-initiated calls are refused.' },
900
+ mode: { type: 'string', enum: ['ACTIVE', 'PAUSED', 'STOPPED'], description: 'PAUSED / STOPPED block new entries (create_order); ACTIVE clears the halt. Omit to read the current state.' },
901
+ },
902
+ required: [],
903
+ },
894
904
  };
895
905
  // ---- Helpers ----
896
906
  /** Wrap tool result in OpenClaw AgentToolResult format */
@@ -1217,8 +1227,48 @@ const paperTradingPlugin = {
1217
1227
  logger.info(TAG, `Connection token loaded (prefix: ${connectionToken.slice(0, 7)}...)`);
1218
1228
  }
1219
1229
  else {
1220
- logger.warn(TAG, 'No connection token found — get_market_intel will return errors');
1230
+ logger.warn(TAG, 'No connection token found — token-gated tools return errors until the connection is saved');
1221
1231
  }
1232
+ // Late wiring (config/late-wiring.ts): everything below that needs the
1233
+ // connection and could not get it at boot registers a step here, so a
1234
+ // connection saved AFTER this plugin started (the normal chat-onboarding
1235
+ // order when the plugin is already installed) heals without a restart.
1236
+ const lateWiring = new LateWiring();
1237
+ if (!connectionToken) {
1238
+ lateWiring.add({
1239
+ name: 'connection token',
1240
+ tryWire: () => {
1241
+ let fromFile = '';
1242
+ try {
1243
+ fromFile = readPluginConfig().connectionToken?.trim() ?? '';
1244
+ }
1245
+ catch { /* unreadable → fall through */ }
1246
+ const found = fromFile || (readOpenClawConnection().token?.trim() ?? '');
1247
+ if (!found)
1248
+ return false;
1249
+ connectionToken = found;
1250
+ logger.info(TAG, `Connection token loaded after boot (prefix: ${found.slice(0, 7)}...)`);
1251
+ return true;
1252
+ },
1253
+ });
1254
+ }
1255
+ const safeReadPluginConfig = () => {
1256
+ try {
1257
+ return readPluginConfig();
1258
+ }
1259
+ catch {
1260
+ return undefined;
1261
+ }
1262
+ };
1263
+ /** The connection token as of NOW. Tool deps read it through this (as a
1264
+ * getter) so the boot-time empty string is never latched. */
1265
+ const currentConnectionToken = () => {
1266
+ // Also while any OTHER step is still pending (e.g. the journal waiting
1267
+ // for a flat book): agent activity retries it, not just the 30 s watcher.
1268
+ if (!connectionToken || lateWiring.hasPending)
1269
+ lateWiring.check();
1270
+ return connectionToken;
1271
+ };
1222
1272
  // Venue support gate (multi-venue Phase 0). Checked BEFORE the credentials
1223
1273
  // gate so a hyperliquid config gets the accurate diagnosis ("venue not
1224
1274
  // supported yet"), not a misleading "missing API keys". Fallback-to-PAPER,
@@ -1293,7 +1343,11 @@ const paperTradingPlugin = {
1293
1343
  }
1294
1344
  let positionDecisionsClient;
1295
1345
  let positionDecisionsUserId;
1296
- {
1346
+ // Called at boot and, when the credentials were missing then, again by
1347
+ // late wiring. Returns true once the journal client exists.
1348
+ const wireJournalIngest = (atBoot) => {
1349
+ if (positionDecisionsClient)
1350
+ return true;
1297
1351
  let cfgForIngest;
1298
1352
  try {
1299
1353
  cfgForIngest = readPluginConfig();
@@ -1313,11 +1367,14 @@ const paperTradingPlugin = {
1313
1367
  });
1314
1368
  positionDecisionsUserId = reefclawUserId;
1315
1369
  logger.info(TAG, `Position-decisions ingest wired to ${ingestBaseUrl} (userId=${reefclawUserId.slice(0, 8)}…)`);
1370
+ return true;
1316
1371
  }
1317
- else {
1372
+ if (atBoot) {
1318
1373
  logger.info(TAG, `Position-decisions ingest disabled (ingest token [plugin-config connectionToken / WEBAPP_INGEST_TOKEN] or REEFCLAW_USER_ID missing)`);
1319
1374
  }
1320
- }
1375
+ return false;
1376
+ };
1377
+ const journalWiredAtBoot = wireJournalIngest(true);
1321
1378
  // Reduce-only-fill close capture: when a bracket SL/TP (or other reduce-only
1322
1379
  // fill) takes a journaled position flat, auto-journal an exact close so the
1323
1380
  // position doesn't leak as status='open' forever (close-bypass class). On by
@@ -1348,6 +1405,57 @@ const paperTradingPlugin = {
1348
1405
  if (positionDecisionsClient) {
1349
1406
  logger.info(TAG, `Journal close-on-reduce-only-fill ${closeOnReduceOnlyFill ? 'ENABLED' : 'disabled'}`);
1350
1407
  }
1408
+ if (!journalWiredAtBoot) {
1409
+ // `autoCapture` is ONE shared object held by reference (adapters, WS
1410
+ // ingest, tools) and read per capture, so filling it in here reaches
1411
+ // every holder. The other journal consumers below read the two `let`s
1412
+ // per call (or through getters), so they follow too.
1413
+ //
1414
+ // ★ Only while the book is FLAT. A position opened while the journal
1415
+ // was unwired has no state-store entry (onCreateOrderFilled returned
1416
+ // before upsert); wiring the journal under it would journal a later
1417
+ // scale-in as a NEW position sized as the add alone, and stitch the
1418
+ // eventual full-size close onto that undersized row — the
1419
+ // mis-stitch class of the 2026-07-20 corruption. So the step waits for
1420
+ // a TRUSTED flat snapshot (null = unknown ≠ flat) and wires in the same
1421
+ // tick the snapshot resolves.
1422
+ let journalFlatCheckInFlight = false;
1423
+ let journalDeferLogged = false;
1424
+ lateWiring.add({
1425
+ name: 'position journal ingest',
1426
+ tryWire: () => {
1427
+ if (autoCapture.decisionsClient && autoCapture.userId)
1428
+ return true;
1429
+ if (!resolveIngestToken(safeReadPluginConfig()) || !resolveReefclawUserId())
1430
+ return false;
1431
+ if (journalFlatCheckInFlight)
1432
+ return false;
1433
+ journalFlatCheckInFlight = true;
1434
+ void runtime.adapter
1435
+ .getPositionsOrNull()
1436
+ .then((positions) => {
1437
+ if (positions === null)
1438
+ return; // untrusted — retry on a later check
1439
+ if (positions.length > 0) {
1440
+ if (!journalDeferLogged) {
1441
+ journalDeferLogged = true;
1442
+ logger.warn(TAG, `Connection saved, but ${positions.length} position(s) were opened while the journal was unwired — journal wiring deferred until the book is flat (those positions are not journaled)`);
1443
+ }
1444
+ return;
1445
+ }
1446
+ if (!wireJournalIngest(false))
1447
+ return;
1448
+ autoCapture.decisionsClient = positionDecisionsClient;
1449
+ autoCapture.userId = positionDecisionsUserId;
1450
+ })
1451
+ .catch((err) => {
1452
+ logger.warn(TAG, `Late journal wiring: position read failed (will retry): ${formatError(err)}`);
1453
+ })
1454
+ .finally(() => { journalFlatCheckInFlight = false; });
1455
+ return false; // reported as wired by the next check, once the snapshot resolved
1456
+ },
1457
+ });
1458
+ }
1351
1459
  // Reconciler-driven close-bypass cleanup, installed on EVERY live adapter —
1352
1460
  // the boot one below AND every reconnect-built one (via
1353
1461
  // runtime.onAdapterCreated; audit 2026-07-26 F9 — previously boot-only, so
@@ -1387,7 +1495,12 @@ const paperTradingPlugin = {
1387
1495
  // are passive until a live adapter carries them — F9's runtime wiring
1388
1496
  // threads them into every adapter build, boot and reconnect alike.
1389
1497
  let tradeIngest;
1390
- {
1498
+ // Called at boot and, when the credentials were missing then, again by
1499
+ // late wiring. Returns true when there is nothing (more) to wire: the
1500
+ // client exists, or this box does not want audit-trail ingest at all.
1501
+ const wireTradeIngest = (atBoot) => {
1502
+ if (tradeIngest)
1503
+ return true;
1391
1504
  const dbWriteMode = loadUserDataStreamDbWrite();
1392
1505
  let cfgForIngest;
1393
1506
  try {
@@ -1413,10 +1526,23 @@ const paperTradingPlugin = {
1413
1526
  exchange: fillExchangeId(venue),
1414
1527
  };
1415
1528
  logger.info(TAG, `User-data stream dbWrite=on — WS audit-trail ingest wired to ${ingestBaseUrl} (userId=${reefclawUserId.slice(0, 8)}…)`);
1529
+ return true;
1416
1530
  }
1417
- else if (wsReadPathActive && dbWriteMode === 'on') {
1418
- logger.warn(TAG, `User-data stream dbWrite=on but ingest token (plugin-config connectionToken / WEBAPP_INGEST_TOKEN) or REEFCLAW_USER_ID missing — audit-trail ingest disabled`);
1531
+ if (wsReadPathActive && dbWriteMode === 'on') {
1532
+ if (atBoot) {
1533
+ logger.warn(TAG, `User-data stream dbWrite=on but ingest token (plugin-config connectionToken / WEBAPP_INGEST_TOKEN) or REEFCLAW_USER_ID missing — audit-trail ingest disabled`);
1534
+ }
1535
+ return false; // wanted, credentials missing → late wiring retries
1419
1536
  }
1537
+ return true; // not wanted on this box (dbWrite off / read path off)
1538
+ };
1539
+ if (!wireTradeIngest(true)) {
1540
+ // Reconnect-built live adapters read `liveWiring.tradeIngestBase` per
1541
+ // build and the SIGTERM drain reads `tradeStore` at signal time — both
1542
+ // are getters below, so a client built here reaches them. An adapter
1543
+ // that is ALREADY live keeps the wiring it was built with (it could not
1544
+ // have been built with the client: the credentials were missing).
1545
+ lateWiring.add({ name: 'audit-trail ingest', tryWire: () => wireTradeIngest(false) });
1420
1546
  }
1421
1547
  // Approval mode is resolved PER READ (config + env), not snapshotted at
1422
1548
  // boot: a config change applies on the next create_order call and the
@@ -1458,7 +1584,11 @@ const paperTradingPlugin = {
1458
1584
  // trading-mode change finds them ready instead of needing a restart.
1459
1585
  let proposalManagerCtx;
1460
1586
  let proposalListenerCredentials;
1461
- {
1587
+ // Called at boot and, when the credentials were missing then, again by
1588
+ // late wiring. Returns true once the proposal wiring exists.
1589
+ const wireProposalIngest = (atBoot) => {
1590
+ if (proposalManagerCtx && proposalListenerCredentials)
1591
+ return true;
1462
1592
  let cfgForUrl;
1463
1593
  try {
1464
1594
  cfgForUrl = readPluginConfig();
@@ -1479,8 +1609,11 @@ const paperTradingPlugin = {
1479
1609
  if (bootApprovalMode !== 'off') {
1480
1610
  logger.info(TAG, `Approval wiring active (mode=${bootApprovalMode}) → ${ingestBaseUrl} (userId=${reefclawUserId.slice(0, 8)}…)`);
1481
1611
  }
1612
+ return true;
1482
1613
  }
1483
- else if (bootApprovalMode === 'per_trade') {
1614
+ if (!atBoot)
1615
+ return false;
1616
+ if (bootApprovalMode === 'per_trade') {
1484
1617
  // FAIL-CLOSED state: create_order will REFUSE every new entry until the
1485
1618
  // credentials are restored or approval.mode is set back to off. Loud at
1486
1619
  // boot AND at each refusal (create-order.ts) — a boot-only signal is how
@@ -1493,7 +1626,9 @@ const paperTradingPlugin = {
1493
1626
  else if (bootApprovalMode !== 'off') {
1494
1627
  logger.warn(TAG, `approval mode=${bootApprovalMode} but ingest token / REEFCLAW_USER_ID missing — shadow telemetry disabled (orders fire directly, as in off mode)`);
1495
1628
  }
1496
- }
1629
+ return false;
1630
+ };
1631
+ const proposalsWiredAtBoot = wireProposalIngest(true);
1497
1632
  // ---- Create exchange adapter based on trading mode ----
1498
1633
  let adapter;
1499
1634
  if (tradingMode === 'MICRO_LIVE' || tradingMode === 'LIVE') {
@@ -1792,9 +1927,13 @@ const paperTradingPlugin = {
1792
1927
  // of silently reverting to bare adapters until the next restart.
1793
1928
  onAdapterCreated: installDriftCleanup,
1794
1929
  liveWiring: {
1795
- tradeIngestBase: tradeIngest
1796
- ? { client: tradeIngest.client, userId: tradeIngest.userId }
1797
- : undefined,
1930
+ // Getter: read per adapter build, so an ingest client wired after
1931
+ // boot (config/late-wiring.ts) reaches the next reconnect-built adapter.
1932
+ get tradeIngestBase() {
1933
+ return tradeIngest
1934
+ ? { client: tradeIngest.client, userId: tradeIngest.userId }
1935
+ : undefined;
1936
+ },
1798
1937
  autoCapture,
1799
1938
  },
1800
1939
  });
@@ -1804,8 +1943,11 @@ const paperTradingPlugin = {
1804
1943
  // snapshot discipline preserved (null → skip). First pass shortly after
1805
1944
  // boot so restart-deploys heal existing phantoms immediately.
1806
1945
  const dbReconcileSweep = startPeriodicDbReconcile({
1807
- decisionsClient: positionDecisionsClient,
1808
- userId: positionDecisionsUserId,
1946
+ // Getters, not values: this object lives for the whole process and the
1947
+ // sweep reads it every tick — a journal client wired after boot
1948
+ // (config/late-wiring.ts) must be seen, not the boot-time undefined.
1949
+ get decisionsClient() { return positionDecisionsClient; },
1950
+ get userId() { return positionDecisionsUserId; },
1809
1951
  resolveAdapter: () => runtime.adapter,
1810
1952
  // Scope each tick's DB read to the ACTIVE book (deferred closure —
1811
1953
  // follows a set_trading_mode reconnect). Without this, the sweep
@@ -1835,11 +1977,22 @@ const paperTradingPlugin = {
1835
1977
  const bootSweep = setTimeout(() => { void dbReconcileSweep.runOnce(); }, 15_000);
1836
1978
  bootSweep.unref?.();
1837
1979
  }
1838
- const intelDeps = { connectionToken, apiBaseUrl };
1980
+ // connectionToken is a GETTER on both deps objects: they are built once
1981
+ // here and handed to every intel tool for the life of the process, so a
1982
+ // plain value would latch a token-less boot forever. Consumers read
1983
+ // `deps.connectionToken` per call — never spread/copy these objects.
1984
+ const intelDeps = {
1985
+ get connectionToken() { return currentConnectionToken(); },
1986
+ apiBaseUrl,
1987
+ };
1839
1988
  // venue rides the deps so every intel tool maps agent-facing symbols to
1840
1989
  // the venue's intel namespace (plan §5.3) — absent/'binance' is
1841
1990
  // byte-identical passthrough.
1842
- const intelApiDeps = { connectionToken, intelligenceUrl, venue };
1991
+ const intelApiDeps = {
1992
+ get connectionToken() { return currentConnectionToken(); },
1993
+ intelligenceUrl,
1994
+ venue,
1995
+ };
1843
1996
  const wave9AdmissionGuard = new Wave9PaperAdmissionGuard();
1844
1997
  let wave9LiveLedger;
1845
1998
  try {
@@ -2076,6 +2229,20 @@ const paperTradingPlugin = {
2076
2229
  runtime.setOnAdapterSwapped((a) => { void approvalLifecycle.onAdapterSwapped(a); });
2077
2230
  // Boot application — the same path every later swap takes.
2078
2231
  void approvalLifecycle.onAdapterSwapped(runtime.adapter);
2232
+ if (!proposalsWiredAtBoot) {
2233
+ // Credentials arrived after boot: build the proposal wiring, then
2234
+ // re-apply the lifecycle exactly as boot does so a per_trade tenant gets
2235
+ // its decision listener (hasWiring() is read per application).
2236
+ lateWiring.add({
2237
+ name: 'approval proposal ingest',
2238
+ tryWire: () => {
2239
+ if (!wireProposalIngest(false))
2240
+ return false;
2241
+ void approvalLifecycle.onAdapterSwapped(runtime.adapter);
2242
+ return true;
2243
+ },
2244
+ });
2245
+ }
2079
2246
  const wave9ActivationClient = new IntelWave9ActivationClient(intelApiDeps);
2080
2247
  const getWave9AccountSnapshot = async () => {
2081
2248
  if (!runtime.adapter.isLive) {
@@ -2260,7 +2427,12 @@ const paperTradingPlugin = {
2260
2427
  logger.info(TAG, `Facts-out local evaluator=${signalsEvaluator} for ${signalsSymbols.length} symbols`);
2261
2428
  }
2262
2429
  const getSignalsDeps = {
2263
- ...intelApiDeps,
2430
+ // NOT `...intelApiDeps`: a spread evaluates the token getter once, here,
2431
+ // and copies the boot-time value — get_signals would then stay
2432
+ // token-less forever while every other intel tool healed.
2433
+ get connectionToken() { return currentConnectionToken(); },
2434
+ intelligenceUrl,
2435
+ venue,
2264
2436
  evaluatorMode: signalsEvaluator,
2265
2437
  localSignalService,
2266
2438
  logger,
@@ -2283,7 +2455,8 @@ const paperTradingPlugin = {
2283
2455
  // env+network co-location as possible credential harvesting.
2284
2456
  installSignalHandlers({
2285
2457
  runtime,
2286
- tradeStore: tradeIngest?.client,
2458
+ // Getter: resolved at signal time (a late-wired client must be drained too).
2459
+ get tradeStore() { return tradeIngest?.client; },
2287
2460
  proposalListener: approvalLifecycle,
2288
2461
  stateManager,
2289
2462
  });
@@ -2984,6 +3157,18 @@ const paperTradingPlugin = {
2984
3157
  return jsonResult(setBracketRequirementTool(params, { isLive: runtime.adapter.isLive }));
2985
3158
  },
2986
3159
  },
3160
+ {
3161
+ name: 'set_operator_halt',
3162
+ label: 'Set Operator Halt',
3163
+ description: 'Operator-only. The dashboard\'s Pause / Kill / Flatten (PAUSED / STOPPED) and Resume (ACTIVE) as the order path enforces them: while halted, create_order refuses new entries; closes, stops and brackets keep working. Omit mode to read the current state. Refused without dashboard operator provenance.',
3164
+ parameters: TOOL_PARAMS.set_operator_halt,
3165
+ execute: async (_id, params) => {
3166
+ const prov = verifyOperatorProvenance(params?.operator_token);
3167
+ if (!prov.ok)
3168
+ return jsonResult(provenanceRefusal(prov));
3169
+ return jsonResult(setOperatorHaltTool(params));
3170
+ },
3171
+ },
2987
3172
  ];
2988
3173
  // ---- Tool gate (central per-user config, slice 1) ----
2989
3174
  // Wrap EVERY tool's execute with the ToolGate check — the one dispatch
@@ -3025,7 +3210,11 @@ const paperTradingPlugin = {
3025
3210
  // one-click switch restarts it for exactly that reason), so a stored but
3026
3211
  // not yet applied venue must not change what the hint says.
3027
3212
  const hintedTools = withDefaultSymbol.map((t) => wrapToolWithHyperliquidQuoteHint(t, () => venue));
3028
- const gatedTools = hintedTools.map((t) => entitlementGate.wrapTool(toolGate.wrapTool(t, jsonResult), jsonResult));
3213
+ // Operator halt (the dashboard's Pause / Kill / Flatten): OUTERMOST, so
3214
+ // the operator's explicit stop wins over every other refusal. Like the
3215
+ // entitlement gate it touches exactly create_order. See config/operator-halt.ts.
3216
+ const operatorHaltGate = new OperatorHaltGate();
3217
+ const gatedTools = hintedTools.map((t) => operatorHaltGate.wrapTool(entitlementGate.wrapTool(toolGate.wrapTool(t, jsonResult), jsonResult), jsonResult));
3029
3218
  // Poll the central config (boot + every ~60s), keyed by the same rc_
3030
3219
  // token the ingest paths use (plugin-config connectionToken →
3031
3220
  // WEBAPP_INGEST_TOKEN env fallback). No token → poller no-ops → gate
@@ -3034,13 +3223,20 @@ const paperTradingPlugin = {
3034
3223
  // exitGate) — loadExitGateMode() consults it before the local file;
3035
3224
  // kill-switch RC_CENTRAL_GATES=off. See config/gate-store.ts.
3036
3225
  // entitlementGate receives the server-resolved billing verdict.
3037
- startAgentConfigPoller({
3038
- gate: toolGate,
3039
- gateStore,
3040
- entitlementGate,
3041
- apiBaseUrl,
3042
- token: resolveIngestToken({ connectionToken }),
3043
- });
3226
+ const startConfigPoller = () => {
3227
+ const token = resolveIngestToken({ connectionToken });
3228
+ startAgentConfigPoller({ gate: toolGate, gateStore, entitlementGate, apiBaseUrl, token });
3229
+ return token.length > 0;
3230
+ };
3231
+ if (!startConfigPoller()) {
3232
+ // No token at boot → the poller did not start (and did not latch): start
3233
+ // it once the connection is saved so Tools-tab toggles, central gates
3234
+ // and the entitlement verdict apply without a restart.
3235
+ lateWiring.add({
3236
+ name: 'central config poller',
3237
+ tryWire: () => resolveIngestToken({ connectionToken }).length > 0 && startConfigPoller(),
3238
+ });
3239
+ }
3044
3240
  // Register all tools with OpenClaw
3045
3241
  const toolNames = gatedTools.map(t => t.name);
3046
3242
  // OpenClaw 2026.6+ SILENTLY DROPS any registered tool not declared in
@@ -3118,24 +3314,38 @@ const paperTradingPlugin = {
3118
3314
  : `Plugin runtime integrity report OFF (RC_READINESS_INTEGRITY=off); root=${pluginRoot}`);
3119
3315
  // Runs here once (guarded by the process-record early-return → once per
3120
3316
  // process) + on an unref'd interval inside the reporter.
3121
- startReadinessReporter({
3122
- apiBaseUrl,
3123
- token: resolveIngestToken({ connectionToken }),
3124
- venue,
3125
- publicApi: hlPublicApi ?? binanceApi,
3126
- toolCount: toolNames.length,
3127
- pluginVersion: installFacts.version,
3128
- installChannel: installFacts.channel,
3129
- runtime: runtimeIntegrity,
3130
- // live_stop_protection (E2E audit #3): what would stop a losing live
3131
- // position. Deferred closure over the runtime so paper↔live flips and
3132
- // adapter swaps surface on the next 5-min report without a restart.
3133
- resolveStopProtection: () => ({
3134
- tradingMode: runtime.mode,
3135
- venueEnforced: runtime.adapter.bracketsAlwaysEnforced === true,
3136
- bracketMode: loadBracketMode(),
3137
- }),
3138
- });
3317
+ const startReadiness = () => {
3318
+ const token = resolveIngestToken({ connectionToken });
3319
+ startReadinessReporter({
3320
+ apiBaseUrl,
3321
+ token,
3322
+ venue,
3323
+ publicApi: hlPublicApi ?? binanceApi,
3324
+ toolCount: toolNames.length,
3325
+ pluginVersion: installFacts.version,
3326
+ installChannel: installFacts.channel,
3327
+ runtime: runtimeIntegrity,
3328
+ // live_stop_protection (E2E audit #3): what would stop a losing live
3329
+ // position. Deferred closure over the runtime so paper↔live flips and
3330
+ // adapter swaps surface on the next 5-min report without a restart.
3331
+ resolveStopProtection: () => ({
3332
+ tradingMode: runtime.mode,
3333
+ venueEnforced: runtime.adapter.bracketsAlwaysEnforced === true,
3334
+ bracketMode: loadBracketMode(),
3335
+ }),
3336
+ });
3337
+ return token.length > 0;
3338
+ };
3339
+ if (!startReadiness()) {
3340
+ // Same as the config poller: no token → not started, not latched.
3341
+ lateWiring.add({
3342
+ name: 'readiness reporter',
3343
+ tryWire: () => resolveIngestToken({ connectionToken }).length > 0 && startReadiness(),
3344
+ });
3345
+ }
3346
+ // Everything that could not be wired at boot is now registered — watch
3347
+ // for the connection (no-op when nothing is pending).
3348
+ lateWiring.startWatch();
3139
3349
  maybeStartConnectorSupervisor();
3140
3350
  },
3141
3351
  };
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "id": "reefclaw-paper-trading",
3
3
  "name": "ReefClaw Trading",
4
- "version": "0.1.50",
4
+ "version": "0.1.53",
5
5
  "description": "Supervised trading plugin for the ReefClaw dashboard. It runs on YOUR machine and starts in PAPER mode with no API keys. It cannot trade real funds until you supply exchange credentials and step PAPER→MICRO_LIVE→LIVE yourself from the dashboard — the agent cannot make that change (the tool is refused without operator provenance). Exchange keys stay local, are used only to sign requests to the exchange, and are never transmitted to ReefClaw (asserted by a test in this package). Trading telemetry — positions, fills, decision journal — is sent to ReefClaw to render the dashboard. Every live position carries exchange-native protective stops. Remote updates to the agent's trading instructions are applied only after an Ed25519 signature is verified against a public key pinned in this build. It runs on gateway startup and supervises a local connector process; the package README lists every path it writes and everything it sends. It never changes the gateway's auth settings.",
6
6
  "author": "ReefClaw",
7
7
  "activation": {
@@ -74,7 +74,8 @@
74
74
  "hl_agent_wallet_status",
75
75
  "hl_submit_agent_approval",
76
76
  "get_bracket_config",
77
- "set_bracket_requirement"
77
+ "set_bracket_requirement",
78
+ "set_operator_halt"
78
79
  ]
79
80
  },
80
81
  "toolMetadata": {
@@ -407,6 +408,11 @@
407
408
  "profiles": [
408
409
  "coding"
409
410
  ]
411
+ },
412
+ "set_operator_halt": {
413
+ "profiles": [
414
+ "coding"
415
+ ]
410
416
  }
411
417
  },
412
418
  "configSchema": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reefclaw/openclaw-plugin",
3
- "version": "0.1.50",
3
+ "version": "0.1.53",
4
4
  "description": "ReefClaw supervised trading plugin for OpenClaw. Runs entirely on YOUR machine and starts in PAPER mode — it cannot trade real funds until you supply exchange credentials and walk the PAPER→MICRO_LIVE→LIVE ladder yourself from the ReefClaw dashboard (the agent cannot make that change; it is refused without operator provenance). Your exchange API keys stay on your machine to sign requests to the exchange and are NEVER sent to ReefClaw — a test in the package asserts this. What does reach ReefClaw is trading telemetry for the dashboard (positions, fills, decision journal). Live trading always carries exchange-native protective stops. Trading instructions can be updated remotely, and every update must carry a valid Ed25519 signature verified against a key pinned in this build before it is applied. Install from ClawHub on OpenClaw 2026.8.1+ (Control UI Plugins > Discover, or /plugins install clawhub:@reefclaw/openclaw-plugin then the same with --accept-capabilities after reviewing the listed capabilities), or with the ReefClaw connect installer (@reefclaw/connect on npm, pinned to the exact release named in the bundled skill). It runs on gateway startup, supervises a local connector process, and writes only under ~/.reefclaw and OpenClaw's own skill, config and cron locations; the README lists every path it writes and everything it sends. It never changes the gateway's auth settings.",
5
5
  "type": "module",
6
6
  "main": "index.js",
@@ -48,5 +48,20 @@
48
48
  "index.js": "97dcdf356bdafa6703de2d17084be94d00bbd2a2a15d1efe57eb21757bf0b215",
49
49
  "tools/create-order.js": "72aa6a78f246bdc1e0fe8321948c5ca06b101c6055b7336a5c61bbcee1fc4f2e",
50
50
  "risk/pre-trade-check.js": "5074ac12687d554f9c0a0aee611202aba9ecb4536e4632f8a5c76a5614ae0aad"
51
+ },
52
+ "0.1.50": {
53
+ "index.js": "04cfdd9de44d347b16689b7fc6ff05ef50823dd4cfa7b1106e6cda6fbce93710",
54
+ "tools/create-order.js": "72aa6a78f246bdc1e0fe8321948c5ca06b101c6055b7336a5c61bbcee1fc4f2e",
55
+ "risk/pre-trade-check.js": "5074ac12687d554f9c0a0aee611202aba9ecb4536e4632f8a5c76a5614ae0aad"
56
+ },
57
+ "0.1.51": {
58
+ "index.js": "04cfdd9de44d347b16689b7fc6ff05ef50823dd4cfa7b1106e6cda6fbce93710",
59
+ "tools/create-order.js": "72aa6a78f246bdc1e0fe8321948c5ca06b101c6055b7336a5c61bbcee1fc4f2e",
60
+ "risk/pre-trade-check.js": "5074ac12687d554f9c0a0aee611202aba9ecb4536e4632f8a5c76a5614ae0aad"
61
+ },
62
+ "0.1.52": {
63
+ "index.js": "b1b54e5c43742b92961d53b4027ec068e9226abb53ade188a945d365c448b287",
64
+ "tools/create-order.js": "72aa6a78f246bdc1e0fe8321948c5ca06b101c6055b7336a5c61bbcee1fc4f2e",
65
+ "risk/pre-trade-check.js": "5074ac12687d554f9c0a0aee611202aba9ecb4536e4632f8a5c76a5614ae0aad"
51
66
  }
52
67
  }
@@ -20,5 +20,8 @@
20
20
  "0.1.47": "Security release (independent audit, 2026-09-27). The heartbeat recorder no longer uploads the output of file and shell tools and scrubs anything key-shaped from what it does record. Dashboard-only settings (trading mode, exchange credentials, the stop requirement) now require a secret the plugin hands to its own connector at start - nothing the agent can read or repeat; plugin and connector must be updated together, which this update does. While trading is live a new entry without a protective stop is refused whatever the settings say, and a stop can no longer be moved wider on a losing position. Risk limits fetched from the server are clamped to hardcoded bounds. The installer pins its runtime dependencies to exact, integrity-checked versions and no longer widens the OpenClaw sandbox allow-list. Market-intel text is fenced against prompt injection in more places, the connector refuses relay hosts outside ReefClaw's, and uploads that hit a rate limit are retried instead of dropped.",
21
21
  "0.1.48": "Two changes. The heartbeat checklist (HEARTBEAT.md) now arrives with your trading instructions, signed, and is placed beside SKILL.md, so the agent reads it instead of failing every beat looking for a file that was never installed. And if ReefClaw's own edge protection ever blocks your host's address (an automatic DDoS mitigation, seen once on 2026-09-28), the plugin and connector now recognise it, back off instead of retrying into it, keep trading with the safety floor intact, and report it to the dashboard over the relay so you see a banner and support is paged; the log names the real cause instead of 'connect the account first' or 'Pro subscription required'. Periodic checks are spread out so several agents behind one address no longer call in lockstep. RC_WEBAPP_EDGE_GATE=off disables the back-off only.",
22
22
  "0.1.49": "Fixes for new and stuck agents. On a fresh install the first market check now starts as soon as the full trading instructions arrive, instead of 15 minutes after connecting. An agent whose ReefClaw heartbeat was never created, because an older version mistook one of your own scheduled jobs for it, now gets the heartbeat with this update and runs its first check straight away. The heartbeat job can no longer be created twice when the gateway answers slowly. New installs from the dashboard's paste message start on the exchange you picked there. New entries now need a stop at least 0.3 x ATR away, the rule the order checks always described (only the 30 bps minimum was enforced before); when ATR is unavailable the 30 bps minimum applies as before. The local signal evaluator (off by default) applies the same minimum stop distance as the server.",
23
- "0.1.50": "Install and update without a terminal. On OpenClaw 2026.9.5 or newer your agent can now install ReefClaw from chat with OpenClaw's own plugins tool, and the dashboard's Update button now also updates a ReefClaw that OpenClaw installed from ClawHub (it installs the new version through OpenClaw, then restarts the gateway). ReefClaw's tools are now visible to agents on OpenClaw's older 'coding' tool profile, where they used to be hidden. A new install starts on the exchange you picked on the onboarding page. On Hyperliquid, a call that fails with a USDT pair now tells the agent which USDC pair to use. The connect installer no longer puts a second copy next to one OpenClaw installed, keeps your own tool allow list valid, and writes its settings file safely."
23
+ "0.1.50": "Install and update without a terminal. On OpenClaw 2026.9.5 or newer your agent can now install ReefClaw from chat with OpenClaw's own plugins tool, and the dashboard's Update button now also updates a ReefClaw that OpenClaw installed from ClawHub (it installs the new version through OpenClaw, then restarts the gateway). ReefClaw's tools are now visible to agents on OpenClaw's older 'coding' tool profile, where they used to be hidden. A new install starts on the exchange you picked on the onboarding page. On Hyperliquid, a call that fails with a USDT pair now tells the agent which USDC pair to use. The connect installer no longer puts a second copy next to one OpenClaw installed, keeps your own tool allow list valid, and writes its settings file safely.",
24
+ "0.1.51": "Keeps your agent connected to the dashboard. The service that carried the live connection between your agent and the ReefClaw dashboard shuts down on 23 October, so this update moves your agent to ReefClaw's new connection server (relay.reefclaw.com) by itself; there is nothing to change. Without this update the dashboard, its chat and the Kill, Flatten and Pause buttons stop reaching your agent once the old service is gone. Also: a heartbeat whose chat channel has no recipient set no longer fails on every run, and a model that has stopped answering is still reported as down.",
25
+ "0.1.52": "Your agent now looks for trades on every heartbeat. Until now the heartbeat’s required steps stopped at checking the market, so agents on smaller models never searched for an entry. Each check now runs the trade search and opens a setup only when your scorecard settings say GO, sized within your risk limits and with a stop and a target; otherwise it says in one line why not. Pause, Kill and Flatten on the dashboard now also block new orders on your machine, while closing positions and stops keep working. The Heartbeats history now shows the whole check on newer OpenClaw versions.",
26
+ "0.1.53": "Fixes a new install that stayed disconnected. If ReefClaw started before your agent saved its connection, the market tools kept answering 'No ReefClaw connection token configured' and the agent never traded until the gateway was fully restarted. ReefClaw now picks up the saved connection by itself within about 30 seconds, with no restart, and starts the journal, the dashboard settings and the readiness checks at the same time. That message now tells the agent where to save the connection. Also includes 0.1.52: every heartbeat looks for trades, and Pause, Kill and Flatten block new orders on your machine."
24
27
  }
@@ -114,7 +114,7 @@ If the ReefClaw trading tools are not present yet, there are two ways to install
114
114
  **2. A terminal, run by the user.** The user runs this once, in a terminal on the machine running OpenClaw (inside the container, if OpenClaw runs in Docker):
115
115
 
116
116
  ```
117
- npx --yes @reefclaw/connect@0.1.63
117
+ npx --yes @reefclaw/connect@0.1.66
118
118
  ```
119
119
 
120
120
  That is the whole install. It places the plugin, sets up the connector, restarts the gateway where it can, and prints what it changed. If OpenClaw already installed ReefClaw itself (ClawHub) and this installer's own copy is not registered, it says so and installs nothing. If its closing lines say **GATEWAY NOT RESTARTED**, the plugin is on disk but not running yet: restarting is the user's step (in Docker, `docker restart <container>` from the host; otherwise restarting OpenClaw). Tell the user exactly that and stop — do not restart, signal or kill any process, do not run docker or service commands, and do not edit the gateway config, even if you could. The plugin reports its own version to ReefClaw after the restart; never post readiness, version or health reports yourself. The version is pinned on purpose: the line names the exact connector release this plugin was published with, so what runs on the machine is reviewable and never "whatever the registry serves today". It needs no ReefClaw token — the connection is the separate paste step above, and the connector picks it up on its own.
@@ -1,8 +1,8 @@
1
1
  // LEGACY strategy configs — used ONLY as fixtures by the local-evaluator
2
2
  // tests (strategy/__tests__/evaluator.test.ts). NOT seeded anywhere and NOT
3
3
  // part of the product catalog: the shipped catalog lives in
4
- // intelligence/src/signals/strategy-store.ts (exactly two template
5
- // strategies since the 2026-07-06 trim — see CLAUDE.md), and the plugin's
4
+ // intelligence/src/signals/strategy-store.ts (exactly one template
5
+ // strategy since the 2026-10-01 catalog decision — see CLAUDE.md), and the plugin's
6
6
  // local evaluator (signals.evaluator, default 'central') receives its
7
7
  // strategy set from the intel service, not from this file.
8
8
  export const BUILTIN_STRATEGIES = [
@@ -13,6 +13,7 @@
13
13
  // order (the create_order gate still applies) — and makes injected directives
14
14
  // far less likely to be followed.
15
15
  import { keepAliveFetch } from '../http/keepalive-fetch.js';
16
+ import { NO_CONNECTION_TOKEN_ERROR } from './intel-api.js';
16
17
  import { noteWebappResponse, webappEdgeGate, webappUserAgent } from '../http/webapp-edge.js';
17
18
  /** What the agent is told when the EDGE (not the app) denies the host. Names
18
19
  * the real cause; the old branch called every 403 a subscription problem. */
@@ -93,7 +94,7 @@ export async function getMarketIntelTool(args, deps) {
93
94
  const { category, symbols } = args;
94
95
  const { connectionToken, apiBaseUrl } = deps;
95
96
  if (!connectionToken) {
96
- return { error: 'No ReefClaw connection token configured. Market intelligence requires a reefclaw.com account.' };
97
+ return { error: NO_CONNECTION_TOKEN_ERROR };
97
98
  }
98
99
  // The category is a path segment AND selects the fence: an unknown value
99
100
  // must never reach the URL (../ into another route) or skip the fence.
@@ -4,6 +4,11 @@ import type { IExchangeAdapter } from '../exchange-adapter.js';
4
4
  import type { TradingMode } from '../types.js';
5
5
  export interface RiskSummaryResult {
6
6
  tradingMode: TradingMode;
7
+ /** Present only while the operator has paused or stopped trading (operator-halt.ts). */
8
+ operator_halt?: {
9
+ mode: 'PAUSED' | 'STOPPED';
10
+ since: string | null;
11
+ };
7
12
  totalEquity: number;
8
13
  availableBalance: number;
9
14
  lockedBalance: number;
@@ -1,6 +1,7 @@
1
1
  // Tool: get_risk_summary — current portfolio risk metrics
2
2
  // Returns exposure, drawdown, heat score, position count — everything
3
3
  // the agent needs for risk-aware decision making.
4
+ import { readOperatorHalt } from '../config/operator-halt.js';
4
5
  import { getQuoteBalance, getQuoteWalletBalance } from '../balance-utils.js';
5
6
  /** Finite number or undefined — never NaN, never a silent 0. */
6
7
  function fin(v) {
@@ -23,6 +24,7 @@ function round(v, dp) {
23
24
  return n === undefined ? 0 : +n.toFixed(dp);
24
25
  }
25
26
  export async function getRiskSummaryTool(_args, deps) {
27
+ const halt = readOperatorHalt();
26
28
  // In live modes, use real exchange data instead of simulator
27
29
  let balance;
28
30
  let positions;
@@ -152,6 +154,9 @@ export async function getRiskSummaryTool(_args, deps) {
152
154
  executionStats,
153
155
  shadowMetrics,
154
156
  ...(dataWarnings.length > 0 ? { dataWarnings } : {}),
157
+ // The operator's Pause / Kill as create_order enforces it: shown so an
158
+ // agent skips its entry work instead of being refused at the order.
159
+ ...(halt.mode !== 'ACTIVE' ? { operator_halt: { mode: halt.mode, since: halt.since } } : {}),
155
160
  timestamp: new Date().toISOString(),
156
161
  };
157
162
  }
@@ -1,5 +1,15 @@
1
1
  import { type VenueId } from '../venues/symbols.js';
2
+ /** Returned by every token-gated tool while this plugin has no connection.
3
+ * Written for the AGENT: it says what to do, and that no restart is needed
4
+ * (config/late-wiring.ts picks the connection up live). The first sentence is
5
+ * a stable prefix — fleet monitoring matches on it; do not reword it. The
6
+ * old text ("requires a reefclaw.com account") was false for an onboarded
7
+ * user whose plugin simply started before the connection was saved, and gave
8
+ * the agent nothing to act on. */
9
+ export declare const NO_CONNECTION_TOKEN_ERROR: string;
2
10
  export interface IntelApiDeps {
11
+ /** May be a GETTER (index.ts) — read it per call, never copy the deps
12
+ * object, so a connection saved after boot is seen (config/late-wiring.ts). */
3
13
  connectionToken: string;
4
14
  intelligenceUrl: string;
5
15
  /** Trading venue of this box (HYPERLIQUID_INTEGRATION_PLAN §5.3). Absent =