@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
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
// OperatorHalt — the plugin-side enforcement of the dashboard's Pause, Kill
|
|
2
|
+
// and Flatten: while the operator has paused or stopped trading, NEW ENTRIES
|
|
3
|
+
// are refused. Everything else keeps working.
|
|
4
|
+
//
|
|
5
|
+
// Why (2026-10-24 review): Pause / Kill / Flatten only set the connector's own
|
|
6
|
+
// `agentMode` (skill/src/providers/gateway.ts) and cancel pending proposals.
|
|
7
|
+
// Nothing reached the order path, so an agent — a heartbeat beat in its own
|
|
8
|
+
// isolated session, or a chat turn — could open a position minutes after the
|
|
9
|
+
// operator pressed Pause or Kill. "Pause = no new entries" was a display.
|
|
10
|
+
//
|
|
11
|
+
// ★ SAFETY ANALYSIS (why this can never add risk to an existing book): the
|
|
12
|
+
// gate blocks ONLY the names in OPERATOR_HALT_GATED_TOOLS — exactly
|
|
13
|
+
// `create_order`, the one tool that ADDS risk (same set and same reasoning as
|
|
14
|
+
// entitlement-gate.ts). close_position, modify_stop, attach_brackets,
|
|
15
|
+
// audit_bracket_protection, record_position_reviews and the operator tools are
|
|
16
|
+
// untouched by construction; a pin test asserts the set can never grow into
|
|
17
|
+
// them. A partial exit through create_order waits for Resume. Flatten's
|
|
18
|
+
// create_order fallback (only when close_position is missing) runs BEFORE the
|
|
19
|
+
// connector sets the halt (skill/src/providers/gateway.ts executeFlatten).
|
|
20
|
+
//
|
|
21
|
+
// State: `operatorHalt` in plugin-config.json, written ONLY by the
|
|
22
|
+
// set_operator_halt operator tool (dashboard provenance required) and read per
|
|
23
|
+
// call — so a halt applies on the very next order and survives a gateway or
|
|
24
|
+
// connector restart. Fail direction: CLOSED. A config file that exists but
|
|
25
|
+
// cannot be read, or an `operatorHalt` value of the wrong shape, is treated
|
|
26
|
+
// as PAUSED: a halt we cannot read is kept, never dropped. The operator clears
|
|
27
|
+
// it from the dashboard (Resume), which rewrites the field.
|
|
28
|
+
//
|
|
29
|
+
// THREAT-MODEL HONESTY: like every local gate, this stops an agent that
|
|
30
|
+
// follows its tools (the realistic failure) — not a deliberately adversarial
|
|
31
|
+
// agent with shell access to its own box, which could edit the file.
|
|
32
|
+
//
|
|
33
|
+
// Kill-switch (break-glass only): RC_OPERATOR_HALT_GATE=off (never blocks)
|
|
34
|
+
// | shadow (log-only) | default enforce.
|
|
35
|
+
import { readPluginConfig, updatePluginConfig } from './plugin-config-io.js';
|
|
36
|
+
import { logger, formatError } from '../logger.js';
|
|
37
|
+
const TAG = 'operator-halt';
|
|
38
|
+
/** The ONLY tools an operator halt blocks. A denylist on purpose: a tool added
|
|
39
|
+
* tomorrow is never blocked by default (the conservative failure mode). */
|
|
40
|
+
export const OPERATOR_HALT_GATED_TOOLS = new Set(['create_order']);
|
|
41
|
+
export function resolveOperatorHaltGateMode() {
|
|
42
|
+
const raw = (process.env.RC_OPERATOR_HALT_GATE ?? '').toLowerCase();
|
|
43
|
+
if (raw === 'off')
|
|
44
|
+
return 'off';
|
|
45
|
+
if (raw === 'shadow')
|
|
46
|
+
return 'shadow';
|
|
47
|
+
return 'enforce';
|
|
48
|
+
}
|
|
49
|
+
function isHaltMode(v) {
|
|
50
|
+
return v === 'PAUSED' || v === 'STOPPED';
|
|
51
|
+
}
|
|
52
|
+
/** The operator's current halt. Never throws. */
|
|
53
|
+
export function readOperatorHalt(configPath) {
|
|
54
|
+
let cfg;
|
|
55
|
+
try {
|
|
56
|
+
cfg = readPluginConfig(configPath);
|
|
57
|
+
}
|
|
58
|
+
catch (err) {
|
|
59
|
+
return { mode: 'PAUSED', since: null, unreadable: `plugin-config.json unreadable: ${formatError(err)}` };
|
|
60
|
+
}
|
|
61
|
+
const halt = cfg.operatorHalt;
|
|
62
|
+
if (halt === undefined || halt === null)
|
|
63
|
+
return { mode: 'ACTIVE', since: null };
|
|
64
|
+
const h = halt;
|
|
65
|
+
if (typeof halt !== 'object' || !isHaltMode(h.mode)) {
|
|
66
|
+
return { mode: 'PAUSED', since: null, unreadable: 'operatorHalt has an unexpected shape' };
|
|
67
|
+
}
|
|
68
|
+
return { mode: h.mode, since: typeof h.since === 'string' ? h.since : null };
|
|
69
|
+
}
|
|
70
|
+
/** set_operator_halt: `mode` omitted = read the current state (no write).
|
|
71
|
+
* ACTIVE clears the halt; PAUSED / STOPPED set it. Provenance is checked by
|
|
72
|
+
* the registration (operator-only), not here. */
|
|
73
|
+
export function setOperatorHaltTool(args, deps = {}) {
|
|
74
|
+
const current = readOperatorHalt(deps.configPath);
|
|
75
|
+
const mode = args?.mode;
|
|
76
|
+
if (mode === undefined || mode === null || mode === '') {
|
|
77
|
+
return { ok: true, mode: current.mode, previousMode: current.mode, since: current.since };
|
|
78
|
+
}
|
|
79
|
+
if (mode !== 'ACTIVE' && !isHaltMode(mode)) {
|
|
80
|
+
return {
|
|
81
|
+
ok: false,
|
|
82
|
+
mode: current.mode,
|
|
83
|
+
previousMode: current.mode,
|
|
84
|
+
since: current.since,
|
|
85
|
+
error: "Invalid mode. Must be 'ACTIVE', 'PAUSED' or 'STOPPED' (or omitted to read the current state).",
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
// Keep the original start time when the halt only changes kind (PAUSED → STOPPED).
|
|
89
|
+
const since = mode === 'ACTIVE' ? null : current.mode !== 'ACTIVE' && current.since ? current.since : (deps.now?.() ?? new Date()).toISOString();
|
|
90
|
+
try {
|
|
91
|
+
updatePluginConfig({ operatorHalt: mode === 'ACTIVE' ? undefined : { mode, since } }, deps.configPath);
|
|
92
|
+
}
|
|
93
|
+
catch (err) {
|
|
94
|
+
return { ok: false, mode: current.mode, previousMode: current.mode, since: current.since, error: `Cannot write config: ${formatError(err)}` };
|
|
95
|
+
}
|
|
96
|
+
if (mode !== current.mode)
|
|
97
|
+
logger.info(TAG, `operator halt ${current.mode} → ${mode}`);
|
|
98
|
+
return { ok: true, mode, previousMode: current.mode, since };
|
|
99
|
+
}
|
|
100
|
+
/** Structured, agent-visible result for a blocked call. Worded so the agent
|
|
101
|
+
* stops cleanly (no retry loop) and keeps managing the existing book. */
|
|
102
|
+
export function operatorHaltBlockedResult(name, state) {
|
|
103
|
+
const what = state.mode === 'STOPPED' ? 'stopped' : 'paused';
|
|
104
|
+
return {
|
|
105
|
+
ok: false,
|
|
106
|
+
error: 'operator_halt',
|
|
107
|
+
tool: name,
|
|
108
|
+
mode: state.mode,
|
|
109
|
+
since: state.since,
|
|
110
|
+
message: `New entries are blocked: the operator ${what} trading from the dashboard` +
|
|
111
|
+
`${state.since ? ` (since ${state.since})` : ''}. Do not retry this call and do not look for ` +
|
|
112
|
+
`another way to open a position. Existing positions stay manageable: close_position closes them ` +
|
|
113
|
+
`and modify_stop / attach_brackets keep protecting them; a partial exit through create_order ` +
|
|
114
|
+
`waits until the operator resumes, from the dashboard.`,
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
export class OperatorHaltGate {
|
|
118
|
+
mode;
|
|
119
|
+
configPath;
|
|
120
|
+
/** One log line per state change, not per blocked call. */
|
|
121
|
+
lastLoggedKey = '';
|
|
122
|
+
constructor(opts = {}) {
|
|
123
|
+
this.mode = opts.mode ?? resolveOperatorHaltGateMode();
|
|
124
|
+
this.configPath = opts.configPath;
|
|
125
|
+
if (this.mode !== 'enforce')
|
|
126
|
+
logger.info(TAG, `mode=${this.mode}`);
|
|
127
|
+
}
|
|
128
|
+
/** The halt that blocks this call, or null. Non-gated names short-circuit
|
|
129
|
+
* FIRST, so no state, mode or file can ever touch the safety set. */
|
|
130
|
+
blocking(name) {
|
|
131
|
+
if (!OPERATOR_HALT_GATED_TOOLS.has(name))
|
|
132
|
+
return null;
|
|
133
|
+
if (this.mode === 'off')
|
|
134
|
+
return null;
|
|
135
|
+
const state = readOperatorHalt(this.configPath);
|
|
136
|
+
if (state.mode === 'ACTIVE')
|
|
137
|
+
return null;
|
|
138
|
+
const key = `${state.mode}:${state.since}:${state.unreadable ?? ''}`;
|
|
139
|
+
if (key !== this.lastLoggedKey) {
|
|
140
|
+
this.lastLoggedKey = key;
|
|
141
|
+
logger.warn(TAG, `${name} ${this.mode === 'shadow' ? 'WOULD BE blocked (shadow)' : 'blocked'}: operator ${state.mode}` +
|
|
142
|
+
(state.unreadable ? ` — ${state.unreadable} (failing closed)` : ''));
|
|
143
|
+
}
|
|
144
|
+
return this.mode === 'shadow' ? null : state;
|
|
145
|
+
}
|
|
146
|
+
wrapTool(tool, jsonResult) {
|
|
147
|
+
if (!OPERATOR_HALT_GATED_TOOLS.has(tool.name))
|
|
148
|
+
return tool;
|
|
149
|
+
const execute = tool.execute;
|
|
150
|
+
return {
|
|
151
|
+
...tool,
|
|
152
|
+
execute: (...a) => {
|
|
153
|
+
const state = this.blocking(tool.name);
|
|
154
|
+
if (state)
|
|
155
|
+
return jsonResult(operatorHaltBlockedResult(tool.name, state));
|
|
156
|
+
return execute(...a);
|
|
157
|
+
},
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
}
|
|
@@ -223,6 +223,13 @@ export interface PluginConfigFile {
|
|
|
223
223
|
mode?: 'off' | 'shadow' | 'observe' | 'enforce';
|
|
224
224
|
minutes?: number;
|
|
225
225
|
};
|
|
226
|
+
/** The dashboard's Pause / Kill / Flatten as the order path sees it. Written
|
|
227
|
+
* ONLY by the set_operator_halt operator tool; absent = ACTIVE. Read per
|
|
228
|
+
* create_order by OperatorHaltGate (config/operator-halt.ts). */
|
|
229
|
+
operatorHalt?: {
|
|
230
|
+
mode: 'PAUSED' | 'STOPPED';
|
|
231
|
+
since: string | null;
|
|
232
|
+
};
|
|
226
233
|
[extra: string]: unknown;
|
|
227
234
|
}
|
|
228
235
|
export declare function defaultConfigPath(): string;
|
package/config/tool-gate.js
CHANGED
|
@@ -31,6 +31,9 @@ export const UNGOVERNABLE_TOOLS = new Set([
|
|
|
31
31
|
'set_trading_mode',
|
|
32
32
|
'get_bracket_config',
|
|
33
33
|
'set_bracket_requirement',
|
|
34
|
+
// The dashboard's Pause / Kill / Flatten as create_order enforces them —
|
|
35
|
+
// disabling it would leave the operator's stop a display (operator-halt.ts).
|
|
36
|
+
'set_operator_halt',
|
|
34
37
|
// Hyperliquid guided onboarding (box-generated agent wallet) — same
|
|
35
38
|
// operator-only channel; disabling them would strand the HL setup flow.
|
|
36
39
|
'hl_provision_agent_wallet',
|
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 —
|
|
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
|
-
|
|
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
|
-
|
|
1418
|
-
|
|
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
|
-
|
|
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
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
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
|
-
|
|
1808
|
-
|
|
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
|
-
|
|
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 = {
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
3038
|
-
|
|
3039
|
-
gateStore,
|
|
3040
|
-
|
|
3041
|
-
|
|
3042
|
-
|
|
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
|
-
|
|
3122
|
-
|
|
3123
|
-
|
|
3124
|
-
|
|
3125
|
-
|
|
3126
|
-
|
|
3127
|
-
|
|
3128
|
-
|
|
3129
|
-
|
|
3130
|
-
|
|
3131
|
-
|
|
3132
|
-
|
|
3133
|
-
|
|
3134
|
-
|
|
3135
|
-
|
|
3136
|
-
|
|
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
|
};
|