@reefclaw/openclaw-plugin 0.1.49 → 0.1.51

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 (35) hide show
  1. package/README.md +10 -6
  2. package/bridge/config.js +10 -3
  3. package/bridge/gateway/gateway-ws-client.d.ts +79 -1
  4. package/bridge/gateway/gateway-ws-client.js +99 -5
  5. package/bridge/gateway/heartbeat-cron.d.ts +39 -2
  6. package/bridge/gateway/heartbeat-cron.js +62 -8
  7. package/bridge/heartbeat-transcript.d.ts +3 -1
  8. package/bridge/heartbeat-transcript.js +26 -5
  9. package/bridge/index.js +2 -2
  10. package/bridge/providers/connector-update-direct.d.ts +3 -0
  11. package/bridge/providers/connector-update-direct.js +11 -1
  12. package/bridge/providers/connector-update-openclaw.d.ts +268 -0
  13. package/bridge/providers/connector-update-openclaw.js +772 -0
  14. package/bridge/providers/connector-update.d.ts +115 -1
  15. package/bridge/providers/connector-update.js +228 -13
  16. package/bridge/providers/gateway.d.ts +31 -10
  17. package/bridge/providers/gateway.js +144 -28
  18. package/bridge/setup.js +6 -3
  19. package/bridge/utils/relay-host.d.ts +16 -0
  20. package/bridge/utils/relay-host.js +30 -1
  21. package/config/first-start-venue.d.ts +147 -0
  22. package/config/first-start-venue.js +400 -0
  23. package/config/plugin-config-io.d.ts +9 -2
  24. package/config/plugin-config-io.js +29 -5
  25. package/connector-supervisor.d.ts +20 -0
  26. package/connector-supervisor.js +27 -1
  27. package/index.js +32 -1
  28. package/openclaw.plugin.json +333 -1
  29. package/package.json +1 -1
  30. package/release-integrity.json +10 -0
  31. package/release-notes.json +3 -1
  32. package/skills/reefclaw/SKILL.md +21 -8
  33. package/strategy/builtin-strategies.js +2 -2
  34. package/tools/venue-quote-hint.d.ts +49 -0
  35. package/tools/venue-quote-hint.js +200 -0
@@ -0,0 +1,400 @@
1
+ // Apply the exchange the user picked during onboarding on this plugin's FIRST
2
+ // start on a box, so a no-terminal install comes up on that venue instead of
3
+ // the Binance default.
4
+ //
5
+ // Why (2026-09-30): the no-terminal install is the agent's own `plugins` tool
6
+ // (ClawHub → hot-load, no npx installer), so installer/src/venue-config.ts —
7
+ // which writes the venue before registering the plugin — never runs there.
8
+ // The agent saves the choice WITH the connection, as
9
+ // skills.entries.reefclaw.config.venue in OpenClaw's config, BEFORE it
10
+ // installs the plugin; this module turns it into the exact block the
11
+ // dashboard's keyless paper switch writes (buildVenueExchangeConfig(undefined,
12
+ // 'hyperliquid', {}, undefined)).
13
+ //
14
+ // ★ ORDER (index.ts register()): called once, right after "Initializing paper
15
+ // trading plugin...", i.e. after the inspect-role and process-wide
16
+ // "initialised" early returns and BEFORE
17
+ // - the venue peek (paper quote currency + default symbol follow it),
18
+ // - new StateManager (it creates the state dir, our "ran before" signal),
19
+ // - the connector supervisor (the connector reads exchange.venue at start).
20
+ //
21
+ // Where the saved venue is read: OpenClaw's own resolved config handed to
22
+ // register() (api.config) FIRST — it is the running gateway's config, whatever
23
+ // profile / OPENCLAW_STATE_DIR / JSON5 layout it came from — then the config
24
+ // file (OPENCLAW_CONFIG_PATH, else <OpenClaw state dir>/openclaw.json) for the
25
+ // case where the agent wrote it a moment before the hot-load and api.config
26
+ // has not caught up. Nested `.config.venue` only.
27
+ //
28
+ // Safety rules. A venue change on a running agent is consequential, so this
29
+ // never changes an agent that has been set up before (mirrors the installer):
30
+ // • FIRST START ONLY. "Ran before" is any of:
31
+ // - the plugin's state dir (~/.openclaw/plugins/reefclaw-paper-trading,
32
+ // created by StateManager),
33
+ // - the credential transport key (~/.reefclaw/credential-transport-key.json,
34
+ // created by ensureCredentialTransportKey),
35
+ // - <OpenClaw state dir>/plugins/reefclaw-paper-trading, where this
36
+ // module leaves a first-start.json marker whenever OpenClaw keeps its
37
+ // state somewhere other than ~/.openclaw (OPENCLAW_STATE_DIR,
38
+ // OPENCLAW_HOME, a profile).
39
+ // The first two live under $HOME. OpenClaw's own Fly / Railway / Northflank
40
+ // guides keep OpenClaw's state on a volume (OPENCLAW_STATE_DIR=/data...)
41
+ // while $HOME is ephemeral, so without the marker every redeploy of such a
42
+ // host would look like a first start and re-apply the onboarding venue.
43
+ // The marker lives with OpenClaw's config, so the rule holds as long as
44
+ // OpenClaw's own state persists. Wiping every one of these (and keeping
45
+ // the saved connection) is a reset to the onboarding choice; it can only
46
+ // ever select keyless paper.
47
+ // • plugin-config.json is absent or holds only installer-owned keys
48
+ // (agentId; connectorSupervisor only when 'on'). Never over an `exchange`
49
+ // key of any value (null included) or any tradingMode.
50
+ // • Hyperliquid only, keyless PAPER only. 'binance' is the default and
51
+ // writes nothing; a missing or unrecognised value writes nothing.
52
+ // • An unreadable, non-object, directory-shaped or symlinked plugin-config
53
+ // is never touched.
54
+ // • Never throws: a failed write is a warning with the dashboard fallback.
55
+ // Kill-switch: RC_FIRST_START_VENUE=off (fully inert: no read, no write, no
56
+ // marker).
57
+ import { lstatSync, mkdirSync, writeFileSync } from 'node:fs';
58
+ import { homedir } from 'node:os';
59
+ import { isAbsolute, join, resolve } from 'node:path';
60
+ import { logger } from '../logger.js';
61
+ import { isVenueId, parseVenue } from '../venues/symbols.js';
62
+ import { buildVenueExchangeConfig, readOpenClawConnection, readPluginConfig, updatePluginConfig, } from './plugin-config-io.js';
63
+ const TAG = 'first-start-venue';
64
+ /** = index.ts PLUGIN_ID, the StateManager directory name (pinned by test). */
65
+ export const FIRST_START_PLUGIN_ID = 'reefclaw-paper-trading';
66
+ /** The marker left in <OpenClaw state dir>/plugins/<pluginId>/ when that dir
67
+ * is not the plugin's own $HOME state dir. */
68
+ export const FIRST_START_MARKER_FILE = 'first-start.json';
69
+ const DASHBOARD_HINT = 'Change it on the dashboard (Settings, Exchange connection).';
70
+ /** Keys the connect installer writes into plugin-config.json before the
71
+ * plugin's first start. Same table as installer/src/venue-config.ts
72
+ * isInstallerOwned — change both together. `connectorSupervisor` counts only
73
+ * as the installer's 'on'; an 'off' is a deliberate human setting. */
74
+ export function isInstallerOwnedKey(key, value) {
75
+ if (key === 'agentId')
76
+ return true;
77
+ if (key === 'connectorSupervisor')
78
+ return value === 'on';
79
+ return false;
80
+ }
81
+ /** Tolerant parse (an agent wrote it): strings only, trimmed + lowercased,
82
+ * and only the exact ids 'hyperliquid' / 'binance' after that. */
83
+ export function parseSavedVenue(raw) {
84
+ if (raw === undefined || raw === null)
85
+ return { kind: 'none' };
86
+ if (typeof raw === 'string') {
87
+ const v = raw.trim().toLowerCase();
88
+ if (v === '')
89
+ return { kind: 'none' };
90
+ if (isVenueId(v))
91
+ return { kind: 'venue', venue: v };
92
+ }
93
+ return { kind: 'unrecognized', shown: describeForLog(raw) };
94
+ }
95
+ /** Echo a short plain word verbatim (so a typo like "hl" is visible in the
96
+ * log); describe anything else by type and length only, so a pasted token or
97
+ * key that landed in the wrong field never reaches a log line. */
98
+ function describeForLog(raw) {
99
+ if (typeof raw === 'string') {
100
+ const t = raw.trim();
101
+ return /^[A-Za-z0-9 _.-]{1,24}$/.test(t) ? JSON.stringify(t) : `a ${raw.length}-character string`;
102
+ }
103
+ if (Array.isArray(raw))
104
+ return 'an array';
105
+ return `a ${typeof raw}`;
106
+ }
107
+ /** Pure. Order matters: `ran-before` is checked before garbage, so a box that
108
+ * ran before never warns about its saved value on every restart. */
109
+ export function decideFirstStartVenue(input) {
110
+ const { saved, ranBefore, pluginConfig } = input;
111
+ if (saved.kind === 'none')
112
+ return { action: 'skip', reason: 'not-requested' };
113
+ if (ranBefore)
114
+ return { action: 'skip', reason: 'ran-before' };
115
+ if (saved.kind === 'unrecognized')
116
+ return { action: 'skip', reason: 'unrecognized' };
117
+ if (saved.venue === 'binance')
118
+ return { action: 'skip', reason: 'binance-default' };
119
+ if (pluginConfig.kind === 'unreadable')
120
+ return { action: 'skip', reason: 'unreadable' };
121
+ if (pluginConfig.kind === 'object') {
122
+ const value = pluginConfig.value;
123
+ if (Object.prototype.hasOwnProperty.call(value, 'exchange')) {
124
+ const ex = value.exchange;
125
+ const isHl = !!ex && typeof ex === 'object' && ex.venue === 'hyperliquid';
126
+ // Hyperliquid already there (the npx installer, or an earlier call) → nothing to say.
127
+ return { action: 'skip', reason: isHl ? 'already-set' : 'configured-before' };
128
+ }
129
+ if (Object.entries(value).some(([k, v]) => !isInstallerOwnedKey(k, v))) {
130
+ return { action: 'skip', reason: 'configured-before' }; // tradingMode of any value lands here too
131
+ }
132
+ }
133
+ return { action: 'write', venue: 'hyperliquid' };
134
+ }
135
+ /** ENOENT = absent; any other error (EACCES, ENOTDIR, …) counts as present,
136
+ * which fails safe (nothing is written). lstat: a symlink is present. */
137
+ function pathPresent(p) {
138
+ try {
139
+ lstatSync(p);
140
+ return true;
141
+ }
142
+ catch (err) {
143
+ return err?.code !== 'ENOENT';
144
+ }
145
+ }
146
+ function samePath(a, b) {
147
+ const ra = resolve(a);
148
+ const rb = resolve(b);
149
+ return process.platform === 'win32' ? ra.toLowerCase() === rb.toLowerCase() : ra === rb;
150
+ }
151
+ /** The state dir and the transport key are written only by this plugin's
152
+ * first full register() (StateManager, ensureCredentialTransportKey); the
153
+ * OpenClaw-side dir only by markFirstStart below. Any one present = ran
154
+ * before. */
155
+ export function pluginRanBefore(paths) {
156
+ return (pathPresent(paths.stateDir) ||
157
+ pathPresent(paths.transportKeyFile) ||
158
+ (paths.openclawPluginDir !== undefined && pathPresent(paths.openclawPluginDir)));
159
+ }
160
+ /** Record that ReefClaw has started on this OpenClaw state, in OpenClaw's
161
+ * state dir, when that is not where StateManager already records it (the
162
+ * $HOME state dir). Exclusive create: never overwrites. Never throws. */
163
+ export function markFirstStart(paths, now = new Date()) {
164
+ try {
165
+ if (samePath(paths.openclawPluginDir, paths.stateDir))
166
+ return 'not-needed';
167
+ const file = join(paths.openclawPluginDir, FIRST_START_MARKER_FILE);
168
+ if (pathPresent(file))
169
+ return 'present';
170
+ mkdirSync(paths.openclawPluginDir, { recursive: true, mode: 0o700 });
171
+ const body = JSON.stringify({
172
+ firstStartAt: now.toISOString(),
173
+ note: 'ReefClaw has started with this OpenClaw state. The exchange saved with the connection is applied ' +
174
+ 'only on the first start (config/first-start-venue.ts); deleting this file does not change the venue.',
175
+ }, null, 2) + '\n';
176
+ try {
177
+ writeFileSync(file, body, { encoding: 'utf-8', mode: 0o600, flag: 'wx' });
178
+ }
179
+ catch (err) {
180
+ // Another start (a second process) got there first.
181
+ if (err?.code === 'EEXIST')
182
+ return 'present';
183
+ throw err;
184
+ }
185
+ return 'written';
186
+ }
187
+ catch (err) {
188
+ try {
189
+ logger.debug(TAG, `could not write the first-start marker under ${paths.openclawPluginDir}: ${err instanceof Error ? err.message : String(err)}`);
190
+ }
191
+ catch {
192
+ /* never break register() */
193
+ }
194
+ return 'failed';
195
+ }
196
+ }
197
+ /** plugin-config.json as this rule sees it. Never throws. A symlink or a
198
+ * directory is `unreadable` (never written through), as is bad JSON, a BOM,
199
+ * or a non-object root. */
200
+ export function viewPluginConfig(path) {
201
+ let isFile;
202
+ try {
203
+ isFile = lstatSync(path).isFile();
204
+ }
205
+ catch (err) {
206
+ return err?.code === 'ENOENT' ? { kind: 'absent' } : { kind: 'unreadable' };
207
+ }
208
+ if (!isFile)
209
+ return { kind: 'unreadable' };
210
+ try {
211
+ return { kind: 'object', value: readPluginConfig(path) };
212
+ }
213
+ catch {
214
+ return { kind: 'unreadable' };
215
+ }
216
+ }
217
+ function venueFromResolvedConfig(openclawConfig) {
218
+ try {
219
+ const cfg = openclawConfig;
220
+ return cfg?.skills?.entries?.reefclaw?.config?.venue;
221
+ }
222
+ catch {
223
+ return undefined; // a hostile getter / proxy: treat as nothing saved
224
+ }
225
+ }
226
+ /** The saved onboarding venue, raw. OpenClaw's own resolved config handed to
227
+ * register() (api.config) first: it is the running gateway's config, and a
228
+ * config file at a default location may belong to another layout. The file
229
+ * only when api.config holds no venue (the agent wrote the file a moment
230
+ * before the hot-load). Nested `.config.venue` only. */
231
+ export function readSavedVenue(openclawConfig, openclawConfigPath) {
232
+ const fromApi = venueFromResolvedConfig(openclawConfig);
233
+ if (parseSavedVenue(fromApi).kind !== 'none')
234
+ return fromApi;
235
+ return readOpenClawConnection(openclawConfigPath).venue;
236
+ }
237
+ /** `~` / `~/x` against `home`, then absolute (OpenClaw's resolveUserPath). */
238
+ function expandUserPath(p, home) {
239
+ const t = p.trim();
240
+ if (t === '~')
241
+ return resolve(home);
242
+ if (t.startsWith('~/') || t.startsWith('~\\'))
243
+ return resolve(join(home, t.slice(2)));
244
+ return resolve(t);
245
+ }
246
+ /** Mirror of OpenClaw's resolveStateDir (src/config/state-dir.ts, v2026.9.7)
247
+ * without its legacy-dir fallback: OPENCLAW_STATE_DIR (a `~` expands against
248
+ * the effective home), else <effective home>/.openclaw, where the effective
249
+ * home is OPENCLAW_HOME, else the OS home. */
250
+ export function openClawStateDirFromEnv(env, home) {
251
+ const openclawHome = env.OPENCLAW_HOME?.trim();
252
+ const effectiveHome = openclawHome ? expandUserPath(openclawHome, home) : home;
253
+ const override = env.OPENCLAW_STATE_DIR?.trim();
254
+ if (override)
255
+ return expandUserPath(override, effectiveHome);
256
+ return join(effectiveHome, '.openclaw');
257
+ }
258
+ /** OpenClaw's state dir: the host's own answer when it hands one over
259
+ * (api.runtime.state.resolveStateDir on 2026.9.x, through `hostStateDir`),
260
+ * else the env mirror. Never throws. */
261
+ export function resolveOpenClawStateDir(input) {
262
+ try {
263
+ const dir = input.hostStateDir?.();
264
+ if (typeof dir === 'string' && dir.trim() !== '' && isAbsolute(dir.trim()))
265
+ return dir.trim();
266
+ }
267
+ catch {
268
+ /* an older host / a proxy that refuses: use the env mirror */
269
+ }
270
+ return openClawStateDirFromEnv(input.env, input.home);
271
+ }
272
+ /** The default paths. Exported so tests pin them against the code that
273
+ * creates each one (StateManager, ensureCredentialTransportKey,
274
+ * defaultConfigPath) rather than against a literal. */
275
+ export function defaultFirstStartPaths(input) {
276
+ const { home, pluginId, openclawStateDir, env } = input;
277
+ const configOverride = env.OPENCLAW_CONFIG_PATH?.trim();
278
+ return {
279
+ pluginConfigPath: join(home, '.reefclaw', 'plugin-config.json'),
280
+ stateDir: join(home, '.openclaw', 'plugins', pluginId),
281
+ transportKeyFile: join(home, '.reefclaw', 'credential-transport-key.json'),
282
+ openclawPluginDir: join(openclawStateDir, 'plugins', pluginId),
283
+ openclawConfigPath: configOverride
284
+ ? expandUserPath(configOverride, env.OPENCLAW_HOME?.trim() ? expandUserPath(env.OPENCLAW_HOME, home) : home)
285
+ : join(openclawStateDir, 'openclaw.json'),
286
+ };
287
+ }
288
+ /** See the file header. Synchronous (register() must be), never throws. */
289
+ export function applyFirstStartVenue(options = {}) {
290
+ let pluginConfigPath = options.pluginConfigPath;
291
+ let paths;
292
+ try {
293
+ const env = options.env ?? process.env;
294
+ if ((env.RC_FIRST_START_VENUE ?? '').trim().toLowerCase() === 'off') {
295
+ logger.debug(TAG, 'RC_FIRST_START_VENUE=off: the saved onboarding venue is not applied');
296
+ return { outcome: 'skipped', reason: 'disabled' };
297
+ }
298
+ const home = homedir();
299
+ const pluginId = options.pluginId ?? FIRST_START_PLUGIN_ID;
300
+ const openclawStateDir = options.openclawStateDir ?? resolveOpenClawStateDir({ hostStateDir: options.hostStateDir, env, home });
301
+ const defaults = defaultFirstStartPaths({ home, pluginId, openclawStateDir, env });
302
+ paths = {
303
+ pluginConfigPath: options.pluginConfigPath ?? defaults.pluginConfigPath,
304
+ stateDir: options.stateDir ?? defaults.stateDir,
305
+ transportKeyFile: options.transportKeyFile ?? defaults.transportKeyFile,
306
+ openclawPluginDir: options.openclawPluginDir ?? defaults.openclawPluginDir,
307
+ openclawConfigPath: options.openclawConfigPath ?? defaults.openclawConfigPath,
308
+ };
309
+ pluginConfigPath = paths.pluginConfigPath;
310
+ const saved = parseSavedVenue(readSavedVenue(options.openclawConfig, paths.openclawConfigPath));
311
+ // Nothing saved: the common case on every box that onboarded before this
312
+ // feature — silent. (The marker below is still left, in `finally`.)
313
+ if (saved.kind === 'none')
314
+ return { outcome: 'skipped', reason: 'not-requested' };
315
+ // Probed BEFORE this start leaves its own marker (in `finally`).
316
+ const ranBefore = pluginRanBefore(paths);
317
+ const decision = decideFirstStartVenue({
318
+ saved,
319
+ ranBefore,
320
+ // A box that ran before is decided without reading its config.
321
+ pluginConfig: ranBefore ? { kind: 'absent' } : viewPluginConfig(pluginConfigPath),
322
+ });
323
+ if (decision.action === 'skip') {
324
+ logSkip(decision.reason, saved, pluginConfigPath);
325
+ return { outcome: 'skipped', reason: decision.reason };
326
+ }
327
+ const write = options.writePluginConfig ?? updatePluginConfig;
328
+ write({ exchange: buildVenueExchangeConfig(undefined, 'hyperliquid', {}, undefined) }, pluginConfigPath);
329
+ logger.info(TAG, 'first start: applied the exchange saved with the connection (hyperliquid, paper)');
330
+ return { outcome: 'applied', venue: 'hyperliquid' };
331
+ }
332
+ catch (err) {
333
+ const message = err instanceof Error ? err.message : String(err);
334
+ try {
335
+ logger.warn(TAG, `first start: could not apply the exchange saved with the connection to ${pluginConfigPath ?? 'plugin-config.json'} (${message}). ` +
336
+ `The agent starts on Binance paper. ${DASHBOARD_HINT}`);
337
+ }
338
+ catch {
339
+ /* a logger failure must never break register() */
340
+ }
341
+ return { outcome: 'failed', error: message };
342
+ }
343
+ finally {
344
+ // Every start past the kill-switch counts as "ran here", whatever it
345
+ // decided — the same as StateManager's dir on a $HOME layout.
346
+ if (paths)
347
+ markFirstStart(paths);
348
+ }
349
+ }
350
+ /** The venue this box will actually start on, for log lines: what
351
+ * plugin-config.json selects, read the way index.ts reads it (following a
352
+ * symlink; unreadable = the Binance default). Never throws. */
353
+ export function describeSelectedVenue(path) {
354
+ try {
355
+ const exchange = readPluginConfig(path).exchange;
356
+ const raw = exchange && typeof exchange === 'object' ? exchange.venue : undefined;
357
+ const venue = parseVenue(raw).venue;
358
+ return raw === undefined || raw === null || raw === ''
359
+ ? { venue, text: `${venue}, the default` }
360
+ : { venue, text: `${venue}, set in plugin-config.json` };
361
+ }
362
+ catch {
363
+ return { venue: 'binance', text: 'binance, the default: plugin-config.json is unreadable' };
364
+ }
365
+ }
366
+ function logSkip(reason, saved, path) {
367
+ switch (reason) {
368
+ case 'ran-before': {
369
+ // Only a saved Hyperliquid can ever be applied, so only it can be
370
+ // "ignored"; and only when the box is not on it already. One line per
371
+ // gateway start at most.
372
+ if (saved.kind !== 'venue' || saved.venue !== 'hyperliquid')
373
+ return;
374
+ const current = describeSelectedVenue(path);
375
+ if (current.venue === 'hyperliquid')
376
+ return;
377
+ logger.info(TAG, `the exchange saved with the connection (hyperliquid) was not applied: ReefClaw has run here before, ` +
378
+ `so its venue is left unchanged (${current.text}). ${DASHBOARD_HINT}`);
379
+ return;
380
+ }
381
+ case 'unrecognized':
382
+ if (saved.kind === 'unrecognized') {
383
+ const current = describeSelectedVenue(path);
384
+ logger.warn(TAG, `the exchange saved with the connection is ${saved.shown}, which is not a venue; ignored. The agent starts on ` +
385
+ `${current.text}. Valid values: "hyperliquid", "binance". ${DASHBOARD_HINT}`);
386
+ }
387
+ return;
388
+ case 'unreadable':
389
+ logger.warn(TAG, `${path} is not a plain readable JSON file, so the exchange saved with the connection (hyperliquid) was not applied. ${DASHBOARD_HINT}`);
390
+ return;
391
+ case 'configured-before':
392
+ logger.info(TAG, `the exchange saved with the connection (hyperliquid) was not applied: plugin-config.json already has its own ` +
393
+ `settings, so its venue is left unchanged. ${DASHBOARD_HINT}`);
394
+ return;
395
+ case 'not-requested':
396
+ case 'binance-default':
397
+ case 'already-set':
398
+ return;
399
+ }
400
+ }
@@ -7,11 +7,18 @@ type VenueId = 'binance' | 'hyperliquid';
7
7
  * every fresh install has working dashboards but token-starved intel tools,
8
8
  * journaling ingest, and config polling (hit live on the first real user,
9
9
  * 2026-07-06). Nested `.config.*` is the schema-valid shape; legacy flat
10
- * fields are read as a fallback. Fail-soft: {} on any problem. */
11
- export declare function readOpenClawConnection(): {
10
+ * fields are read as a fallback. Fail-soft: {} on any problem.
11
+ *
12
+ * `venue` is the exchange picked during onboarding, raw and unvalidated (an
13
+ * agent wrote it). Nested `.config.venue` only: there is no legacy flat
14
+ * venue, and a flat entry key fails OpenClaw's strict schema. Consumed once,
15
+ * on the plugin's first start (config/first-start-venue.ts). `path` defaults
16
+ * to OPENCLAW_CONFIG_PATH, then ~/.openclaw/openclaw.json. */
17
+ export declare function readOpenClawConnection(path?: string): {
12
18
  token?: string;
13
19
  userId?: string;
14
20
  relayUrl?: string;
21
+ venue?: unknown;
15
22
  };
16
23
  /** Full on-disk schema. Unknown keys are preserved on round-trip. */
17
24
  export interface PluginConfigFile {
@@ -10,6 +10,23 @@
10
10
  // operator-only tool gated on dashboard provenance (verifyOperatorProvenance,
11
11
  // audit F12) — the agent cannot reach these writes conversationally. The file
12
12
  // is the plugin's OWN config store; nothing here touches OpenClaw's config.
13
+ //
14
+ // ONE bounded exception (2026-09-30, config/first-start-venue.ts): on this
15
+ // plugin's FIRST start on a box, register() applies the exchange the user
16
+ // picked during onboarding (saved by the agent with the connection, as
17
+ // skills.entries.reefclaw.config.venue in OpenClaw's config). It writes only
18
+ // the keyless PAPER Hyperliquid block the dashboard's keyless switch writes,
19
+ // only when the plugin never ran here and plugin-config.json is absent or
20
+ // holds nothing but installer-owned keys — never over any exchange key (even
21
+ // null), any tradingMode, credentials, or a file it cannot read. "Never ran
22
+ // here" = no plugin state dir and no credential transport key under $HOME,
23
+ // AND no first-start marker in OpenClaw's own state dir (left there whenever
24
+ // OpenClaw keeps its state outside ~/.openclaw, e.g. OPENCLAW_STATE_DIR on a
25
+ // volume with an ephemeral $HOME). So the rule keeps an existing agent's venue
26
+ // as long as either the plugin's $HOME state or OpenClaw's own state
27
+ // persists; a host that loses both is reset to the onboarding choice, which
28
+ // can only ever be keyless paper. It can never add credentials or enable live
29
+ // trading. Kill-switch: RC_FIRST_START_VENUE=off.
13
30
  import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync, } from 'node:fs';
14
31
  import { homedir } from 'node:os';
15
32
  import { dirname, join } from 'node:path';
@@ -21,13 +38,19 @@ import { logger } from '../logger.js';
21
38
  * every fresh install has working dashboards but token-starved intel tools,
22
39
  * journaling ingest, and config polling (hit live on the first real user,
23
40
  * 2026-07-06). Nested `.config.*` is the schema-valid shape; legacy flat
24
- * fields are read as a fallback. Fail-soft: {} on any problem. */
25
- export function readOpenClawConnection() {
41
+ * fields are read as a fallback. Fail-soft: {} on any problem.
42
+ *
43
+ * `venue` is the exchange picked during onboarding, raw and unvalidated (an
44
+ * agent wrote it). Nested `.config.venue` only: there is no legacy flat
45
+ * venue, and a flat entry key fails OpenClaw's strict schema. Consumed once,
46
+ * on the plugin's first start (config/first-start-venue.ts). `path` defaults
47
+ * to OPENCLAW_CONFIG_PATH, then ~/.openclaw/openclaw.json. */
48
+ export function readOpenClawConnection(path) {
26
49
  try {
27
- const path = process.env.OPENCLAW_CONFIG_PATH ?? join(homedir(), '.openclaw', 'openclaw.json');
28
- if (!existsSync(path))
50
+ const file = path ?? process.env.OPENCLAW_CONFIG_PATH ?? join(homedir(), '.openclaw', 'openclaw.json');
51
+ if (!existsSync(file))
29
52
  return {};
30
- const parsed = JSON.parse(readFileSync(path, 'utf-8'));
53
+ const parsed = JSON.parse(readFileSync(file, 'utf-8'));
31
54
  const entry = parsed?.skills?.entries?.reefclaw;
32
55
  if (!entry)
33
56
  return {};
@@ -35,6 +58,7 @@ export function readOpenClawConnection() {
35
58
  token: entry.config?.token ?? entry.token,
36
59
  userId: entry.config?.userId ?? entry.userId,
37
60
  relayUrl: entry.config?.relayUrl ?? entry.relayUrl,
61
+ venue: entry.config?.venue,
38
62
  };
39
63
  }
40
64
  catch {
@@ -36,6 +36,26 @@ export interface ConnectorSupervisorOptions {
36
36
  /** Env marker (value is not secret): the spawned bridge reads one line of
37
37
  * stdin for the provenance secret when this is '1'. */
38
38
  export declare const OPERATOR_SECRET_STDIN_MARKER = "REEFCLAW_OPERATOR_SECRET_STDIN";
39
+ /** Env var (value is not secret: a public release number) through which the
40
+ * connector learns which plugin release THIS GATEWAY PROCESS loaded —
41
+ * processRuntime().release, stamped at the first full register(), before the
42
+ * supervisor starts. The connector's one-click update for a copy OpenClaw
43
+ * installed from ClawHub (skill/src/providers/connector-update-openclaw.ts
44
+ * RUNNING_RELEASE_ENV, the same name — pinned by connector-supervisor.test.ts)
45
+ * may report "already up to date" only on this first-hand answer: OpenClaw's
46
+ * plugins.inspect reports the version ON DISK, which an install that was never
47
+ * followed by a restart has already moved on. Without it, an up-to-date box
48
+ * got a needless gateway restart instead of "nothing to update". Set on every
49
+ * launch; never inherited from the gateway's own environment (a stale value
50
+ * there would claim a release this process did not load). */
51
+ export declare const RUNNING_RELEASE_ENV = "REEFCLAW_PLUGIN_RUNNING_RELEASE";
52
+ /** The child's environment: the gateway's, minus any inherited
53
+ * RUNNING_RELEASE_ENV, plus the loaded release (when stamped) and the
54
+ * provenance-secret marker (when a secret is handed over). */
55
+ export declare function connectorChildEnv(base: NodeJS.ProcessEnv, opts: {
56
+ release: string | null;
57
+ secretOnStdin: boolean;
58
+ }): NodeJS.ProcessEnv;
39
59
  export interface ConnectorSupervisorHandle {
40
60
  stop(): void;
41
61
  /** Test/debug introspection. */
@@ -54,6 +54,32 @@ const STABLE_RESET_MS = 5 * 60_000;
54
54
  /** Env marker (value is not secret): the spawned bridge reads one line of
55
55
  * stdin for the provenance secret when this is '1'. */
56
56
  export const OPERATOR_SECRET_STDIN_MARKER = 'REEFCLAW_OPERATOR_SECRET_STDIN';
57
+ /** Env var (value is not secret: a public release number) through which the
58
+ * connector learns which plugin release THIS GATEWAY PROCESS loaded —
59
+ * processRuntime().release, stamped at the first full register(), before the
60
+ * supervisor starts. The connector's one-click update for a copy OpenClaw
61
+ * installed from ClawHub (skill/src/providers/connector-update-openclaw.ts
62
+ * RUNNING_RELEASE_ENV, the same name — pinned by connector-supervisor.test.ts)
63
+ * may report "already up to date" only on this first-hand answer: OpenClaw's
64
+ * plugins.inspect reports the version ON DISK, which an install that was never
65
+ * followed by a restart has already moved on. Without it, an up-to-date box
66
+ * got a needless gateway restart instead of "nothing to update". Set on every
67
+ * launch; never inherited from the gateway's own environment (a stale value
68
+ * there would claim a release this process did not load). */
69
+ export const RUNNING_RELEASE_ENV = 'REEFCLAW_PLUGIN_RUNNING_RELEASE';
70
+ /** The child's environment: the gateway's, minus any inherited
71
+ * RUNNING_RELEASE_ENV, plus the loaded release (when stamped) and the
72
+ * provenance-secret marker (when a secret is handed over). */
73
+ export function connectorChildEnv(base, opts) {
74
+ const env = { ...base };
75
+ delete env[RUNNING_RELEASE_ENV];
76
+ if (typeof opts.release === 'string' && /^\d+\.\d+\.\d+$/.test(opts.release)) {
77
+ env[RUNNING_RELEASE_ENV] = opts.release;
78
+ }
79
+ if (opts.secretOnStdin)
80
+ env[OPERATOR_SECRET_STDIN_MARKER] = '1';
81
+ return env;
82
+ }
57
83
  // Process-wide, not module-scoped: OpenClaw 2026.9.5+ can load the plugin as
58
84
  // two module instances in one gateway, and a per-module singleton let each
59
85
  // start its own connector — two bridges sharing one relay-instance-id, which
@@ -100,7 +126,7 @@ export function startConnectorSupervisor(opts = {}) {
100
126
  child = spawnFn(process.execPath, [indexJs, '--provider', 'gateway', '--log-level', 'info'], {
101
127
  cwd: bridgeDir,
102
128
  stdio: [withSecret ? 'pipe' : 'ignore', 'pipe', 'pipe'],
103
- env: withSecret ? { ...process.env, [OPERATOR_SECRET_STDIN_MARKER]: '1' } : process.env,
129
+ env: connectorChildEnv(process.env, { release: processRuntime().release, secretOnStdin: withSecret }),
104
130
  });
105
131
  logger.info(TAG, `connector started (pid ${child.pid})`);
106
132
  if (withSecret) {
package/index.js CHANGED
@@ -55,9 +55,11 @@ import { loadPositionReviewMode } from './config/position-review-config.js';
55
55
  import { installSignalHandlers } from './lifecycle/install-signal-handlers.js';
56
56
  import { SerialTradingOperationLock } from './lifecycle/trading-operation-lock.js';
57
57
  import { readPluginConfig, readOpenClawConnection, loadMicroLiveConfig, loadStopWatcherIntervalMs } from './config/plugin-config-io.js';
58
+ import { applyFirstStartVenue } from './config/first-start-venue.js';
58
59
  import { verifyOperatorProvenance, issueOperatorSecret, provenanceRefusal } from './config/operator-provenance.js';
59
60
  import { startConnectorSupervisor, hasBundledBridge } from './connector-supervisor.js';
60
61
  import { ToolGate } from './config/tool-gate.js';
62
+ import { wrapToolWithHyperliquidQuoteHint } from './tools/venue-quote-hint.js';
61
63
  import { gateStore } from './config/gate-store.js';
62
64
  import { entitlementGate } from './config/entitlement-gate.js';
63
65
  import { startAgentConfigPoller } from './config/agent-config-poller.js';
@@ -1048,6 +1050,22 @@ const paperTradingPlugin = {
1048
1050
  return;
1049
1051
  }
1050
1052
  logger.info(TAG, 'Initializing paper trading plugin...');
1053
+ // First start on this box only: apply the exchange the user picked during
1054
+ // onboarding, saved by the agent WITH the connection
1055
+ // (skills.entries.reefclaw.config.venue). MUST stay here: after the
1056
+ // inspect / process-wide early returns above (runs at most once per
1057
+ // process), BEFORE the venue peek below (paper quote currency + default
1058
+ // symbol follow it), BEFORE StateManager creates the state dir (the "ran
1059
+ // before" signal) and BEFORE the connector is spawned (it reads
1060
+ // exchange.venue at start). Keyless paper Hyperliquid only; never over an
1061
+ // existing setting; never throws. See config/first-start-venue.ts.
1062
+ applyFirstStartVenue({
1063
+ openclawConfig: api.config,
1064
+ // OpenClaw's own state dir (2026.9.x runtime helper), resolved lazily
1065
+ // inside the function's never-throw boundary.
1066
+ hostStateDir: () => api.runtime?.state?.resolveStateDir?.(),
1067
+ pluginId: PLUGIN_ID,
1068
+ });
1051
1069
  // Resolve config from plugin settings. The paper wallet's quote currency
1052
1070
  // follows the VENUE (USDC on hyperliquid, USDT on binance — issue #174:
1053
1071
  // a hardcoded USDT wallet reads as $0 equity on the USDC venue). The
@@ -2994,7 +3012,20 @@ const paperTradingPlugin = {
2994
3012
  },
2995
3013
  }
2996
3014
  : tool);
2997
- const gatedTools = withDefaultSymbol.map((t) => entitlementGate.wrapTool(toolGate.wrapTool(t, jsonResult), jsonResult));
3015
+ // Hyperliquid quote hint (tools/venue-quote-hint.ts): a FAILED call whose
3016
+ // `symbol` / `symbols` look USDT-quoted gets an additive `hint` naming the
3017
+ // USDC pair on a hyperliquid box. Never translates, retries or rewrites
3018
+ // the call, never touches a success, never throws. Wrapped INSIDE both
3019
+ // gates (a gate's own refusal is not a symbol problem and never gets the
3020
+ // hint) and OUTSIDE the bare-call symbol default (it judges the symbol the
3021
+ // AGENT sent, not the venue-correct default). The venue is read per call:
3022
+ // `venue` is the venue this process booted on, i.e. the exchange that
3023
+ // actually serves the call. A venue switch stored from the dashboard
3024
+ // (set_exchange_credentials) applies only when the gateway restarts (the
3025
+ // one-click switch restarts it for exactly that reason), so a stored but
3026
+ // not yet applied venue must not change what the hint says.
3027
+ const hintedTools = withDefaultSymbol.map((t) => wrapToolWithHyperliquidQuoteHint(t, () => venue));
3028
+ const gatedTools = hintedTools.map((t) => entitlementGate.wrapTool(toolGate.wrapTool(t, jsonResult), jsonResult));
2998
3029
  // Poll the central config (boot + every ~60s), keyed by the same rc_
2999
3030
  // token the ingest paths use (plugin-config connectionToken →
3000
3031
  // WEBAPP_INGEST_TOKEN env fallback). No token → poller no-ops → gate