@reefclaw/openclaw-plugin 0.1.40 → 0.1.41

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/.gitignore CHANGED
@@ -7,3 +7,4 @@
7
7
  !README.md
8
8
  !.gitignore
9
9
  !release-notes.json
10
+ !release-integrity.json
@@ -186,6 +186,8 @@ export interface OpenClawProvider {
186
186
  requiresVenueSwitchConfirm?: boolean;
187
187
  currentVenue?: string;
188
188
  currentMode?: string;
189
+ /** False = keyless (paper-only) venue activation. */
190
+ credentialsStored?: boolean;
189
191
  }>;
190
192
  /** Operator-only: verify exchange credentials with transient read-only
191
193
  * calls, per venue. Nothing is persisted. */
@@ -26,6 +26,9 @@ export interface SetExchangeCredentialsOutcome {
26
26
  requiresVenueSwitchConfirm?: boolean;
27
27
  currentVenue?: string;
28
28
  currentMode?: string;
29
+ /** False = keyless (paper-only) venue activation — the venue was selected
30
+ * with no credentials on disk (plugin ≥ 0.1.41). */
31
+ credentialsStored?: boolean;
29
32
  }
30
33
  export interface TestExchangeCredentialsOutcome {
31
34
  ok: boolean;
@@ -19,6 +19,7 @@ import { homedir } from 'node:os';
19
19
  import { join, dirname } from 'node:path';
20
20
  import { fileURLToPath } from 'node:url';
21
21
  import { logger } from './logger.js';
22
+ import { processRuntime } from './lifecycle/process-role.js';
22
23
  const TAG = 'connector-supervisor';
23
24
  /** Bridge bundled INSIDE the plugin package (the npm-channel distribution
24
25
  * `@reefclaw/openclaw-plugin` ships the connector at <pluginRoot>/bridge).
@@ -50,15 +51,25 @@ const MIN_BACKOFF_MS = 5_000;
50
51
  const MAX_BACKOFF_MS = 60_000;
51
52
  /** A child that survives this long resets the backoff (it was healthy). */
52
53
  const STABLE_RESET_MS = 5 * 60_000;
53
- let singleton = null;
54
+ // Process-wide, not module-scoped: OpenClaw 2026.9.5+ can load the plugin as
55
+ // two module instances in one gateway, and a per-module singleton let each
56
+ // start its own connector — two bridges sharing one relay-instance-id, which
57
+ // the relay's same-instance rule turns into a 4010 eviction loop.
58
+ function getSingleton() {
59
+ return processRuntime().connectorSupervisor ?? null;
60
+ }
61
+ function setSingleton(h) {
62
+ processRuntime().connectorSupervisor = h;
63
+ }
54
64
  /**
55
65
  * Start supervising the connector. Idempotent per process — repeat calls
56
66
  * (OpenClaw can invoke register() more than once) return the existing handle.
57
67
  * Returns null when the bridge isn't placed on disk (installer not run).
58
68
  */
59
69
  export function startConnectorSupervisor(opts = {}) {
60
- if (singleton)
61
- return singleton;
70
+ const existing = getSingleton();
71
+ if (existing)
72
+ return existing;
62
73
  const bridgeDir = opts.bridgeDir ?? resolveBridgeDir();
63
74
  if (!bridgeDir) {
64
75
  logger.warn(TAG, 'connector not found (no bundled bridge/ and no ~/.reefclaw/bridge) — supervisor idle');
@@ -134,16 +145,16 @@ export function startConnectorSupervisor(opts = {}) {
134
145
  /* already gone */
135
146
  }
136
147
  }
137
- singleton = null;
148
+ setSingleton(null);
138
149
  },
139
150
  isRunning() {
140
151
  return child !== null;
141
152
  },
142
153
  };
143
- singleton = handle;
154
+ setSingleton(handle);
144
155
  return handle;
145
156
  }
146
157
  /** Test-only: reset the module singleton. */
147
158
  export function resetConnectorSupervisorForTest() {
148
- singleton = null;
159
+ setSingleton(null);
149
160
  }
package/index.js CHANGED
@@ -39,6 +39,7 @@ import { onStopWatcherClose } from './ingest/position-auto-capture.js';
39
39
  import { ReentryTracker } from './portfolio/reentry-tracker.js';
40
40
  import { startReadinessReporter } from './ingest/readiness-reporter.js';
41
41
  import { resolvePluginInstallFacts } from './plugin-version.js';
42
+ import { processRuntime, resolveProcessRole } from './lifecycle/process-role.js';
42
43
  import { computePluginIntegrity, describePluginIntegrity } from './plugin-integrity.js';
43
44
  import { IntelMicrostructureAssembler } from './live/microstructure-assembler.js';
44
45
  import { recordPositionReviewsTool } from './tools/record-position-reviews.js';
@@ -906,9 +907,31 @@ function jsonResult(data) {
906
907
  // Tools are re-registered on the second+ calls so OpenClaw's tool map stays
907
908
  // consistent (the api.registerTool factory closes over the singleton state
908
909
  // created on the first call).
909
- let pluginInitialised = false;
910
- let pluginToolsFactory = null;
911
- let pluginToolNames = [];
910
+ //
911
+ // 2026-09-26: the guard lives on globalThis (lifecycle/process-role.ts), not
912
+ // in module scope — OpenClaw 2026.9.5+ can load this file as two module
913
+ // instances in one gateway, and a module-scoped flag let the second one start
914
+ // a full second runtime. And the runtime starts only in a runtime process:
915
+ // the `openclaw` CLI loads plugins too, and a CLI-started runtime ran a second
916
+ // simulator + stop watcher + connector (whose bridge evicted the gateway's
917
+ // from the relay). CLI processes get the tool NAMES only, with a handler
918
+ // that says where the tools run.
919
+ /** Tools registered in a non-runtime process (CLI / discovery): same names and
920
+ * schemas, so OpenClaw's manifest contract and tool listings stay intact, but
921
+ * nothing is started and every call answers that trading runs in the gateway. */
922
+ function buildInspectionTools() {
923
+ return Object.keys(TOOL_PARAMS).map((name) => ({
924
+ name,
925
+ label: name,
926
+ description: 'ReefClaw trading tool. It runs inside the OpenClaw gateway process; this process is not the gateway.',
927
+ parameters: TOOL_PARAMS[name],
928
+ execute: async () => jsonResult({
929
+ error: 'not_available_in_this_process',
930
+ message: 'ReefClaw trading tools run only inside the OpenClaw gateway. This process is an OpenClaw CLI command, '
931
+ + 'so nothing was executed. Use the tool from a normal agent turn (heartbeat or chat).',
932
+ }),
933
+ }));
934
+ }
912
935
  const paperTradingPlugin = {
913
936
  id: PLUGIN_ID,
914
937
  name: 'ReefClaw Trading',
@@ -930,14 +953,30 @@ const paperTradingPlugin = {
930
953
  },
931
954
  register(api) {
932
955
  setLogLevel('info');
933
- // Idempotency guard (see note above module singleton). If already
934
- // initialised, re-register the same tools so OpenClaw's tool map stays
935
- // populated across its multiple register() calls, but do NOT spin up a
936
- // second adapter / stream / poller stack.
937
- if (pluginInitialised) {
956
+ // Not the gateway (a CLI command or an OpenClaw inspection pass): register
957
+ // the tool names only. Nothing below — adapters, watchers, feeds,
958
+ // reporters, the connector — may start in such a process.
959
+ const role = resolveProcessRole({ registrationMode: api.registrationMode });
960
+ if (role.role === 'inspect') {
961
+ logger.debug(TAG, `register() in a non-runtime process (${role.reason}) — tool names only, runtime not started`);
962
+ const inspectionTools = buildInspectionTools();
963
+ api.registerTool(() => inspectionTools, { names: inspectionTools.map(t => t.name) });
964
+ return;
965
+ }
966
+ // Idempotency guard (see note above). Process-wide: every module instance
967
+ // of this file shares the record. If already initialised, re-register the
968
+ // same tools so OpenClaw's tool map stays populated across its multiple
969
+ // register() calls, but do NOT spin up a second adapter / stream / poller
970
+ // stack.
971
+ const processRecord = processRuntime();
972
+ if (processRecord.initialised) {
938
973
  logger.warn(TAG, 'register() called again — reusing existing adapter (singleton)');
939
- if (pluginToolsFactory) {
940
- api.registerTool(pluginToolsFactory, { names: pluginToolNames });
974
+ if (processRecord.toolsFactory) {
975
+ api.registerTool(processRecord.toolsFactory, { names: processRecord.toolNames });
976
+ }
977
+ const diskRelease = resolvePluginInstallFacts({ pluginRoot: dirname(fileURLToPath(import.meta.url)) }).version ?? null;
978
+ if (diskRelease && processRecord.release && diskRelease !== processRecord.release) {
979
+ logger.warn(TAG, `plugin ${diskRelease} is on disk but this gateway process is still running ${processRecord.release} — restart the gateway to load it`);
941
980
  }
942
981
  // The supervisor must be (re)evaluated on EVERY register call, not just
943
982
  // the first: the first full register can run BEFORE the installer has
@@ -2747,7 +2786,7 @@ const paperTradingPlugin = {
2747
2786
  {
2748
2787
  name: 'set_exchange_credentials',
2749
2788
  label: 'Set Exchange Credentials',
2750
- description: 'Operator-only. Store exchange credentials in ~/.reefclaw/plugin-config.json — Binance API key + secret, or Hyperliquid master address + agent wallet key (venue-selected). Same-venue live modes reconnect the adapter; a venue CHANGE is stored but requires an agent restart. Refused without dashboard operator provenance.',
2789
+ description: 'Operator-only. Store exchange credentials in ~/.reefclaw/plugin-config.json — Binance API key + secret, or Hyperliquid master address + agent wallet key (venue-selected). A venue-only call (no credential fields) activates that venue: with stored credentials it switches back to them; with none it selects the venue for PAPER trading (refused in live modes). Same-venue live modes reconnect the adapter; a venue CHANGE is stored but requires an agent restart. Refused without dashboard operator provenance.',
2751
2790
  parameters: TOOL_PARAMS.set_exchange_credentials,
2752
2791
  execute: async (_id, params) => {
2753
2792
  const prov = verifyOperatorProvenance(params.operator_token);
@@ -2918,9 +2957,9 @@ const paperTradingPlugin = {
2918
2957
  // Cache factory + names on the module singleton so repeat register()
2919
2958
  // calls can re-register without spinning up duplicate adapters (the
2920
2959
  // factory closes over the already-wrapped tools — idempotent).
2921
- pluginToolsFactory = toolsFactory;
2922
- pluginToolNames = toolNames;
2923
- pluginInitialised = true;
2960
+ processRecord.toolsFactory = toolsFactory;
2961
+ processRecord.toolNames = toolNames;
2962
+ processRecord.initialised = true;
2924
2963
  logger.info(TAG, `Registered ${gatedTools.length} tools (gate mode=${toolGate.getMode()}): ${toolNames.join(', ')}. Plugin v3.8.0 (${runtime.mode} mode)`);
2925
2964
  // Agent-readiness reporter (docs/AGENT_READINESS_GATE_PLAN.md Phase 1):
2926
2965
  // probe host→venue reachability (Binance HTTP 451 geo-block / Hyperliquid
@@ -2950,6 +2989,7 @@ const paperTradingPlugin = {
2950
2989
  connectorSupervisor: readPluginConfig().connectorSupervisor,
2951
2990
  });
2952
2991
  logger.info(TAG, `Plugin release ${installFacts.version ?? 'unknown (no stamped manifest)'} via ${installFacts.channel}`);
2992
+ processRecord.release = installFacts.version ?? null;
2953
2993
  // What THIS process actually loaded — install-location CLASS (never the
2954
2994
  // path), process start, SHA-256 of the plugin's own order-path files —
2955
2995
  // captured once here at boot and carried on every readiness post. The
@@ -2963,7 +3003,7 @@ const paperTradingPlugin = {
2963
3003
  logger.info(TAG, runtimeIntegrity
2964
3004
  ? `Plugin runtime ${describePluginIntegrity(runtimeIntegrity, pluginRoot)}`
2965
3005
  : `Plugin runtime integrity report OFF (RC_READINESS_INTEGRITY=off); root=${pluginRoot}`);
2966
- // Runs here once (guarded by the pluginInitialised early-return → once per
3006
+ // Runs here once (guarded by the process-record early-return → once per
2967
3007
  // process) + on an unref'd interval inside the reporter.
2968
3008
  startReadinessReporter({
2969
3009
  apiBaseUrl,
@@ -0,0 +1,27 @@
1
+ export type ProcessRole = 'runtime' | 'inspect';
2
+ export interface ProcessRoleInput {
3
+ registrationMode?: unknown;
4
+ title?: string;
5
+ argv?: readonly string[];
6
+ /** RC_PLUGIN_PROCESS_ROLE: 'runtime' | 'inspect' forces the role; anything
7
+ * else means auto. Escape hatch if a future OpenClaw renames its gateway. */
8
+ override?: string;
9
+ }
10
+ export interface ProcessRoleDecision {
11
+ role: ProcessRole;
12
+ reason: string;
13
+ }
14
+ export declare function resolveProcessRole(input?: ProcessRoleInput): ProcessRoleDecision;
15
+ /** The one runtime this process runs, shared by every module instance. */
16
+ export interface ProcessRuntimeRecord {
17
+ initialised: boolean;
18
+ toolsFactory: ((context?: unknown) => unknown[]) | null;
19
+ toolNames: string[];
20
+ /** Plugin release that started the runtime (disk read at boot). */
21
+ release: string | null;
22
+ /** Connector supervisor handle — started at most once per process. */
23
+ connectorSupervisor: unknown;
24
+ }
25
+ export declare function processRuntime(): ProcessRuntimeRecord;
26
+ /** Test-only. */
27
+ export declare function resetProcessRuntimeForTest(): void;
@@ -0,0 +1,99 @@
1
+ // Which OpenClaw process loaded this plugin, and the process-wide record of
2
+ // the one runtime this process may run.
3
+ //
4
+ // Two defects share this file (2026-09-26):
5
+ //
6
+ // 1. The `openclaw` CLI loads plugins IN ITS OWN PROCESS. Every `openclaw
7
+ // --help`, `openclaw hooks …`, `openclaw agent …` ran a full register():
8
+ // a second simulator over the same state.json, a second stop watcher, a
9
+ // second readiness reporter, and a second connector supervisor. The second
10
+ // bridge reads the same ~/.reefclaw/relay-instance-id as the gateway's, so
11
+ // the relay's same-instance rule evicted the real bridge (4010) on every
12
+ // connect for as long as the CLI lived. Seen on a paying customer's box:
13
+ // one `openclaw --help` by the agent → 55 evictions in 2 minutes. A CLI's
14
+ // un-unref'd watcher timers also kept it alive until a reaper killed it.
15
+ //
16
+ // 2. OpenClaw 2026.9.5+ can load index.js as TWO module instances inside the
17
+ // gateway (Ardi report #8). A module-scoped "already initialised" flag is
18
+ // invisible to the second instance, so everything above ran twice in the
19
+ // gateway itself — on a live box, two exchange adapters.
20
+ //
21
+ // Fix: the runtime (adapters, watchers, feeds, reporters, the connector
22
+ // supervisor) starts ONLY in a runtime process, at most once per process,
23
+ // recorded on globalThis so every module instance sees it.
24
+ //
25
+ // Fail direction: only a POSITIVE non-gateway signal makes this a CLI. An
26
+ // unknown process runs the runtime exactly as before, because a gateway
27
+ // misread as a CLI would leave the agent with no working trading tools.
28
+ /** Registration modes in which OpenClaw only inspects the plugin (it never
29
+ * runs tools from these registries). Unknown or absent → runtime. */
30
+ const INSPECTION_MODES = new Set([
31
+ 'cli-metadata',
32
+ 'discovery',
33
+ 'tool-discovery',
34
+ 'setup-only',
35
+ ]);
36
+ export function resolveProcessRole(input = {}) {
37
+ const override = input.override ?? process.env.RC_PLUGIN_PROCESS_ROLE;
38
+ if (override === 'runtime' || override === 'inspect') {
39
+ return { role: override, reason: `RC_PLUGIN_PROCESS_ROLE=${override}` };
40
+ }
41
+ const mode = input.registrationMode;
42
+ if (typeof mode === 'string' && INSPECTION_MODES.has(mode)) {
43
+ return { role: 'inspect', reason: `registrationMode=${mode}` };
44
+ }
45
+ // OpenClaw titles its CLI processes `openclaw-<top-level command>` and its
46
+ // gateway `openclaw-gateway`; a bare `openclaw` is the root command (e.g.
47
+ // `openclaw --help`), or a gateway that has not renamed itself yet.
48
+ const title = input.title ?? process.title;
49
+ const argv = input.argv ?? process.argv;
50
+ const sub = gatewaySubcommand(argv);
51
+ if (title === 'openclaw-gateway') {
52
+ // `openclaw gateway status|stop|call …` are CLIs titled the same way.
53
+ return sub
54
+ ? { role: 'inspect', reason: `title=openclaw-gateway subcommand=${sub}` }
55
+ : { role: 'runtime', reason: 'title=openclaw-gateway' };
56
+ }
57
+ if (/^openclaw-[a-z0-9][a-z0-9-]*$/.test(title))
58
+ return { role: 'inspect', reason: `title=${title}` };
59
+ if (title === 'openclaw') {
60
+ return argv.slice(2).includes('gateway') && !sub
61
+ ? { role: 'runtime', reason: 'title=openclaw argv=gateway' }
62
+ : { role: 'inspect', reason: 'title=openclaw (CLI command)' };
63
+ }
64
+ return { role: 'runtime', reason: `unrecognised process (title=${title}) — runtime by default` };
65
+ }
66
+ /** `openclaw gateway <sub>` commands that talk to or manage a gateway and
67
+ * exit — they never ARE the gateway. From OpenClaw's gateway CLI (checked
68
+ * against 2026.7.1 and 2026.9.6) plus the service-manager verbs.
69
+ * Deliberately a known list, not "any positional": `gateway --bind lan`
70
+ * must stay the runtime. Left OUT on purpose (unlisted = runtime, the safe
71
+ * side): `start` and `daemon` (can start the gateway in the foreground) and
72
+ * the 9.6 restart-handoff commands (`restart-handoff`, `consume`). */
73
+ const GATEWAY_CLI_SUBCOMMANDS = new Set([
74
+ 'call', 'probe', 'health', 'discover', 'diagnostics', 'export', 'stability', 'usage-cost',
75
+ 'status', 'stop', 'restart', 'install', 'uninstall',
76
+ // 2026.9.6
77
+ 'suspend', 'resume', 'capabilities', 'auth-token',
78
+ ]);
79
+ function gatewaySubcommand(argv) {
80
+ const args = argv.slice(2);
81
+ const i = args.indexOf('gateway');
82
+ if (i < 0)
83
+ return null;
84
+ return args.slice(i + 1).find((a) => GATEWAY_CLI_SUBCOMMANDS.has(a)) ?? null;
85
+ }
86
+ const RUNTIME_KEY = Symbol.for('reefclaw.paper-trading.process-runtime');
87
+ export function processRuntime() {
88
+ const g = globalThis;
89
+ let rec = g[RUNTIME_KEY];
90
+ if (!rec) {
91
+ rec = { initialised: false, toolsFactory: null, toolNames: [], release: null, connectorSupervisor: null };
92
+ g[RUNTIME_KEY] = rec;
93
+ }
94
+ return rec;
95
+ }
96
+ /** Test-only. */
97
+ export function resetProcessRuntimeForTest() {
98
+ delete globalThis[RUNTIME_KEY];
99
+ }
@@ -3,6 +3,14 @@ import type { IExchangeAdapter } from '../exchange-adapter.js';
3
3
  import type { CcxtOrder, CcxtPosition } from '../types.js';
4
4
  import type { TradingOperationLock } from '../lifecycle/trading-operation-lock.js';
5
5
  export declare const DEFAULT_INTERVAL_MS = 10000;
6
+ /** After start(), a missing mark is reported as warm-up (INFO) rather than
7
+ * STOP UNENFORCEABLE (ERROR) for this long. The quote feed needs a cycle or
8
+ * two after a gateway restart before it has a mark for every symbol (Ardi
9
+ * report #8: the first tick ~13s after boot alarmed on every position, the
10
+ * second was clean). Enforcement is unchanged: a position WITH a mark is
11
+ * evaluated from the first tick, and one still without a mark after this
12
+ * window raises the full ERROR. */
13
+ export declare const STOP_WATCHER_WARMUP_MS = 30000;
6
14
  export interface StopTriggeredEvent {
7
15
  symbol: string;
8
16
  side: 'long' | 'short';
@@ -68,6 +76,10 @@ export declare class PositionWatcher extends EventEmitter {
68
76
  /** Symbols already alarmed for an unusable mark, so the ERROR fires once per
69
77
  * episode rather than every tick. Cleared as soon as a usable mark returns. */
70
78
  private notifiedUnusableMark;
79
+ /** Symbols already reported as waiting for a first mark during warm-up. */
80
+ private notifiedWarmup;
81
+ /** When start() ran; null when ticks are driven directly (tests). */
82
+ private startedAt;
71
83
  constructor(adapter: IExchangeAdapter, intervalMs?: number, operationLock?: TradingOperationLock);
72
84
  /** Configure this after the durable execution ledger is ready. Runtime
73
85
  * lifecycle hooks reapply it to every watcher after reconnect. */
@@ -28,6 +28,14 @@ const TAG = 'stop-watcher';
28
28
  // revert with zero deploy via plugin-config.json `stopWatcher.intervalMs`.
29
29
  // See docs/EFFICIENCY_QUICK_WINS_PLAN.md + the Binance ban-gate context.
30
30
  export const DEFAULT_INTERVAL_MS = 10_000;
31
+ /** After start(), a missing mark is reported as warm-up (INFO) rather than
32
+ * STOP UNENFORCEABLE (ERROR) for this long. The quote feed needs a cycle or
33
+ * two after a gateway restart before it has a mark for every symbol (Ardi
34
+ * report #8: the first tick ~13s after boot alarmed on every position, the
35
+ * second was clean). Enforcement is unchanged: a position WITH a mark is
36
+ * evaluated from the first tick, and one still without a mark after this
37
+ * window raises the full ERROR. */
38
+ export const STOP_WATCHER_WARMUP_MS = 30_000;
31
39
  /** True when this position carries a protective stop we are supposed to be
32
40
  * enforcing. Used to decide whether an unusable mark is an ALARM (a stop we
33
41
  * cannot evaluate) or simply uninteresting (no stop set). */
@@ -74,6 +82,10 @@ export class PositionWatcher extends EventEmitter {
74
82
  /** Symbols already alarmed for an unusable mark, so the ERROR fires once per
75
83
  * episode rather than every tick. Cleared as soon as a usable mark returns. */
76
84
  notifiedUnusableMark = new Set();
85
+ /** Symbols already reported as waiting for a first mark during warm-up. */
86
+ notifiedWarmup = new Set();
87
+ /** When start() ran; null when ticks are driven directly (tests). */
88
+ startedAt = null;
77
89
  constructor(adapter, intervalMs = DEFAULT_INTERVAL_MS, operationLock) {
78
90
  super();
79
91
  this.adapter = adapter;
@@ -91,6 +103,7 @@ export class PositionWatcher extends EventEmitter {
91
103
  return;
92
104
  }
93
105
  logger.info(TAG, `Starting stop watcher (interval: ${this.intervalMs}ms)`);
106
+ this.startedAt = Date.now();
94
107
  this.interval = setInterval(() => {
95
108
  void this.tick();
96
109
  }, this.intervalMs);
@@ -103,6 +116,8 @@ export class PositionWatcher extends EventEmitter {
103
116
  this.closePending.clear();
104
117
  this.notifiedBreach.clear();
105
118
  this.notifiedUnusableMark.clear();
119
+ this.notifiedWarmup.clear();
120
+ this.startedAt = null;
106
121
  logger.info(TAG, 'Stopped');
107
122
  }
108
123
  /** Run one check cycle. Exposed for tests (skip setInterval). */
@@ -146,6 +161,15 @@ export class PositionWatcher extends EventEmitter {
146
161
  // fabricated entryPrice fallback, isStopBreached read false, and the
147
162
  // watcher skipped it every tick without ever saying so. Alarm instead.
148
163
  if (hasEnforceableStop(position) && isMarkUnusable(position)) {
164
+ const warmingUp = this.startedAt !== null && Date.now() - this.startedAt < STOP_WATCHER_WARMUP_MS;
165
+ if (warmingUp) {
166
+ if (!this.notifiedWarmup.has(position.symbol)) {
167
+ logger.info(TAG, `warming up: no mark yet for ${position.symbol} (stop=${position.stopPrice}) — the quote feed has not ` +
168
+ `delivered its first price since start; this stop is evaluated as soon as it does`);
169
+ this.notifiedWarmup.add(position.symbol);
170
+ }
171
+ continue;
172
+ }
149
173
  if (!this.notifiedUnusableMark.has(position.symbol)) {
150
174
  logger.error(TAG, `STOP UNENFORCEABLE: ${position.symbol} ${position.side} has stop=${position.stopPrice} ` +
151
175
  `but no usable mark (markPrice=${position.markPrice}` +
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "id": "reefclaw-paper-trading",
3
3
  "name": "ReefClaw Trading",
4
- "version": "0.1.40",
4
+ "version": "0.1.41",
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": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reefclaw/openclaw-plugin",
3
- "version": "0.1.40",
3
+ "version": "0.1.41",
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",
@@ -4,9 +4,12 @@
4
4
  export declare const INTEGRITY_FILES: readonly ["index.js", "tools/create-order.js", "risk/pre-trade-check.js"];
5
5
  /** Where the running index.js lives, as a class — never the path.
6
6
  * reefclaw_home = under ~/.reefclaw (the connect installer's layout);
7
- * openclaw_home = under ~/.openclaw (ClawHub extension layout);
7
+ * openclaw_capture = under ~/.openclaw/tmp/plugin-captures (OpenClaw
8
+ * 2026.9.6+ runs plugins from a copy it makes there — the hashes are of
9
+ * that copy, i.e. of what actually runs; Ardi report #8);
10
+ * openclaw_home = elsewhere under ~/.openclaw (ClawHub extension layout);
8
11
  * other = anywhere else (a hand-placed copy, a source checkout, a fork). */
9
- export type PluginRootLocation = 'reefclaw_home' | 'openclaw_home' | 'other';
12
+ export type PluginRootLocation = 'reefclaw_home' | 'openclaw_capture' | 'openclaw_home' | 'other';
10
13
  export interface PluginRuntimeIntegrity {
11
14
  rootLocation: PluginRootLocation;
12
15
  /** ISO timestamp the gateway process started (now − process.uptime()). */
@@ -38,7 +38,10 @@ export function classifyPluginRoot(pluginRoot, homes = {}) {
38
38
  const root = resolve(pluginRoot);
39
39
  if (isUnder(root, homes.reefclawHome ?? join(homedir(), '.reefclaw')))
40
40
  return 'reefclaw_home';
41
- if (isUnder(root, homes.openclawHome ?? join(homedir(), '.openclaw')))
41
+ const openclawHome = homes.openclawHome ?? join(homedir(), '.openclaw');
42
+ if (isUnder(root, join(openclawHome, 'tmp', 'plugin-captures')))
43
+ return 'openclaw_capture';
44
+ if (isUnder(root, openclawHome))
42
45
  return 'openclaw_home';
43
46
  return 'other';
44
47
  }
@@ -0,0 +1,12 @@
1
+ {
2
+ "0.1.39": {
3
+ "index.js": "03b9e7ea593dfd8b8cc372603967f2be3bf87b05835dc32b1147cc3579e28cd7",
4
+ "tools/create-order.js": "b0244ff69cb5b4a44e18c7ceaf91669ee19649d0e6b18bb857aa47ca80f63b2a",
5
+ "risk/pre-trade-check.js": "15ba2c91e7a1f5ea03a2452eda40d489eda406a434e3bc3e9b7e024190f6a22f"
6
+ },
7
+ "0.1.40": {
8
+ "index.js": "03b9e7ea593dfd8b8cc372603967f2be3bf87b05835dc32b1147cc3579e28cd7",
9
+ "tools/create-order.js": "b0244ff69cb5b4a44e18c7ceaf91669ee19649d0e6b18bb857aa47ca80f63b2a",
10
+ "risk/pre-trade-check.js": "15ba2c91e7a1f5ea03a2452eda40d489eda406a434e3bc3e9b7e024190f6a22f"
11
+ }
12
+ }
@@ -11,5 +11,6 @@
11
11
  "0.1.37": "Updates now finish on Docker and other unmanaged gateways: the connector asks the gateway to restart itself through OpenClaw's own restart request, so a one-click update no longer ends with 'files installed, restart it from the host', and the dashboard offers 'Restart now' if that ever does happen. The installer no longer re-registers an already-registered plugin on an update, which is what used to start a second plugin process inside a container.",
12
12
  "0.1.38": "Fixes the restart that 0.1.37 introduced for Docker and other unmanaged gateways: the connector now asks for OpenClaw's update restart, the one kind that replaces the running process so the new files actually load (the previous kind restarted in place and kept the old code while reporting success). The installer no longer claims a self-restart it cannot verify; the connector or the dashboard's Restart now button performs it, waiting for an in-progress agent run to finish first.",
13
13
  "0.1.39": "wave9: a refusal by the plugin's own risk gate no longer burns the whole trading day (the authorization is released and a fresh one can be requested inside the window; a wrong-side stop still latches). wave9 evidence: the previous day's funding settlement stamped a few milliseconds late no longer makes the whole night's evidence read as incomplete. Model health: the model note OpenClaw 2026.9 writes at the start of every session no longer counts as a model switch, so the model dot can be green. Readiness: the plugin now reports whether its own files match the release (an install-location class, the process start time and fingerprints of three of its own files; never a path, never file contents; switch RC_READINESS_INTEGRITY=off), so a stale or modified install can be told apart from the release without touching the box.",
14
- "0.1.40": "One-click updates now work on boxes without a gateway terminal (OpenClaw older than 2026.7, terminal disabled) and inside Docker: the connector runs the installer itself in a files-only mode that never touches the OpenClaw CLI or config, then asks the gateway to restart itself. The installer gains --files-only for the same purpose."
14
+ "0.1.40": "One-click updates now work on boxes without a gateway terminal (OpenClaw older than 2026.7, terminal disabled) and inside Docker: the connector runs the installer itself in a files-only mode that never touches the OpenClaw CLI or config, then asks the gateway to restart itself. The installer gains --files-only for the same purpose.",
15
+ "0.1.41": "Fixes the dashboard link dropping and reconnecting (seen as a connect/disconnect loop): when the agent or anyone ran an openclaw command, that command started a second copy of the trading plugin and its connector, which knocked the real one off the relay. The trading runtime now starts only inside the OpenClaw gateway, once per process (also covers OpenClaw 2026.9.5+ loading the plugin twice); openclaw commands see the tool names but nothing runs there. Paper venue switch: Binance <-> Hyperliquid can now be switched from the dashboard in paper mode without exchange keys (refused while live). Stop watcher: right after a restart, a position waiting for its first price is reported as warming up instead of as an unenforceable stop; an alarm still fires if the price never arrives. Readiness: OpenClaw 2026.9.6's plugin run copy is reported as its own install location."
15
16
  }
@@ -101,7 +101,7 @@ When a user gives you this message (or just a bare `Here's my ReefClaw token: rc
101
101
  If the ReefClaw trading tools are not present yet, the **user** installs them by running this once, in a terminal on the machine running OpenClaw (inside the container, if OpenClaw runs in Docker):
102
102
 
103
103
  ```
104
- npx --yes @reefclaw/connect@0.1.53
104
+ npx --yes @reefclaw/connect@0.1.54
105
105
  ```
106
106
 
107
107
  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 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.
@@ -47,6 +47,10 @@ export interface SetExchangeCredentialsResult {
47
47
  currentVenue?: VenueId;
48
48
  /** Trading mode currently persisted (only with the confirm request). */
49
49
  currentMode?: TradingMode;
50
+ /** Whether the activated venue has a usable credential set on disk after
51
+ * this call. False = keyless (paper-only) activation — the dashboard says
52
+ * "add credentials to go live" instead of implying a live-capable box. */
53
+ credentialsStored?: boolean;
50
54
  }
51
55
  export interface SetExchangeCredentialsDeps {
52
56
  runtime: PluginRuntime;
@@ -20,6 +20,15 @@
20
20
  // agent (`/restart` in chat). Same-venue behavior is unchanged: PAPER stores
21
21
  // without activating; live modes hot-reconnect the adapter.
22
22
  //
23
+ // Keyless (paper) activation — 2026-09-25: a `{ venue }` call with NO credential
24
+ // fields and NOTHING stored for that venue is allowed when the box is in PAPER.
25
+ // Paper trading needs no keys on either venue (public market data), and this is
26
+ // the one-click answer for a host Binance geo-blocks (HTTP 451): switch the agent
27
+ // to Hyperliquid and keep trading paper from the same box. Refused when the
28
+ // persisted or running mode is non-PAPER — a venue with no credentials cannot
29
+ // carry a live book, and boot would silently fall back to PAPER; the operator
30
+ // steps down to PAPER (or stores credentials) first. Never a silent mode change.
31
+ //
23
32
  // Security:
24
33
  // - Secrets (Binance secret / HL agent key) are NEVER logged. Only a redacted
25
34
  // fingerprint (Binance apiKey prefix, or the PUBLIC master address for HL)
@@ -145,13 +154,26 @@ export async function setExchangeCredentialsTool(rawArgs, deps) {
145
154
  catch {
146
155
  // Unreadable/absent config — treat as a fresh box.
147
156
  }
148
- // Activation-only: no credentials supplied, but this venue already has some
149
- // stored → the operator is switching back to a venue they configured before.
157
+ // Activation-only: no credentials supplied. Either the operator is switching
158
+ // back to a venue they configured before (credentials on disk), or — keyless
159
+ // — they want to paper-trade a venue they never gave keys for. Keyless is
160
+ // fine in PAPER (no keys needed for public market data) and REFUSED in any
161
+ // live mode: the switch would leave the box with nothing to trade live and
162
+ // boot would silently fall back to PAPER — the operator must step down (or
163
+ // store credentials) first, so a mode change is never a side effect here.
150
164
  const activationOnly = isActivationOnly(args, venue);
151
- if (activationOnly && !hasCredentialsForVenue(existing, venue)) {
152
- return fail(venue === 'hyperliquid'
153
- ? 'No Hyperliquid credentials are stored yet — provide walletAddress + agentPrivateKey (or use the guided setup).'
154
- : 'No Binance credentials are stored yet — provide apiKey + secret.', '(not-set)', deps, venue);
165
+ const keyless = activationOnly && !hasCredentialsForVenue(existing, venue);
166
+ if (keyless) {
167
+ const persistedMode = existingMode ?? 'PAPER';
168
+ if (persistedMode !== 'PAPER' || deps.runtime.mode !== 'PAPER') {
169
+ const liveMode = persistedMode !== 'PAPER' ? persistedMode : deps.runtime.mode;
170
+ return fail(`This agent is in ${liveMode} mode and has no ${venue} credentials stored, so switching it to ` +
171
+ `${venue} now would leave it with nothing to trade live. Switch to PAPER first, or store ` +
172
+ (venue === 'hyperliquid'
173
+ ? 'Hyperliquid credentials (walletAddress + agentPrivateKey, or the guided setup) '
174
+ : 'Binance credentials (apiKey + secret) ') +
175
+ 'and try again.', '(not-set)', deps, venue);
176
+ }
155
177
  }
156
178
  const validationError = activationOnly
157
179
  ? null
@@ -185,7 +207,9 @@ export async function setExchangeCredentialsTool(rawArgs, deps) {
185
207
  let fingerprint;
186
208
  if (activationOnly) {
187
209
  exchange = buildVenueExchangeConfig(existing, venue, {}, args.testnet);
188
- fingerprint = redactCredential(venue === 'hyperliquid' ? (exchange.walletAddress ?? '') : (exchange.apiKey ?? ''));
210
+ fingerprint = keyless
211
+ ? '(no credentials — paper)'
212
+ : redactCredential(venue === 'hyperliquid' ? (exchange.walletAddress ?? '') : (exchange.apiKey ?? ''));
189
213
  }
190
214
  else if (venue === 'hyperliquid') {
191
215
  const walletAddress = args.walletAddress.trim();
@@ -229,7 +253,10 @@ export async function setExchangeCredentialsTool(rawArgs, deps) {
229
253
  logger.error(TAG, `Failed to write credentials: ${msg}`);
230
254
  return fail(`Failed to persist credentials: ${msg}`, fingerprint, deps, venue);
231
255
  }
232
- logger.info(TAG, `Stored ${venue} credentials (fingerprint: ${fingerprint}, testnet: ${exchange.testnet === true})`);
256
+ const credentialsStored = hasCredentialsForVenue(exchange, venue);
257
+ logger.info(TAG, keyless
258
+ ? `Venue set to ${venue} for paper trading (no ${venue} credentials stored, testnet: ${exchange.testnet === true})`
259
+ : `Stored ${venue} credentials (fingerprint: ${fingerprint}, testnet: ${exchange.testnet === true})`);
233
260
  // Venue change: the paper feed / symbols / quote currency / readiness prober
234
261
  // are wired to the BOOT venue — hot-reconnecting a live adapter into a
235
262
  // different venue would run it on top of the old venue's paper stack. Write,
@@ -237,14 +264,33 @@ export async function setExchangeCredentialsTool(rawArgs, deps) {
237
264
  if (venue !== bootVenue) {
238
265
  return {
239
266
  ok: true,
240
- message: `Credentials stored and venue set to ${venue} — restart your agent to apply ` +
241
- `(send /restart to your agent in chat, or restart the OpenClaw service)`,
267
+ message: keyless
268
+ ? `Venue set to ${venue} for paper trading (no ${venue} credentials stored — add them whenever you ` +
269
+ `want to go live). Restart your agent to apply.`
270
+ : `Credentials stored and venue set to ${venue} — restart your agent to apply ` +
271
+ `(send /restart to your agent in chat, or restart the OpenClaw service)`,
242
272
  fingerprint,
243
273
  reconnected: false,
244
274
  mode: deps.runtime.mode,
245
275
  readiness: deps.runtime.adapter.readiness,
246
276
  venue,
247
277
  restartRequired: true,
278
+ credentialsStored,
279
+ };
280
+ }
281
+ // Keyless on the venue we already booted with: nothing changes at runtime
282
+ // (the gate above guarantees PAPER) — the write only made `venue` explicit.
283
+ if (keyless) {
284
+ return {
285
+ ok: true,
286
+ message: `Already trading ${venue} in PAPER mode — nothing to change.`,
287
+ fingerprint,
288
+ reconnected: false,
289
+ mode: deps.runtime.mode,
290
+ readiness: deps.runtime.adapter.readiness,
291
+ venue,
292
+ restartRequired: false,
293
+ credentialsStored,
248
294
  };
249
295
  }
250
296
  // Same venue: only reconnect if we're already in a live mode — if the
@@ -276,5 +322,6 @@ export async function setExchangeCredentialsTool(rawArgs, deps) {
276
322
  readiness: deps.runtime.adapter.readiness,
277
323
  venue,
278
324
  restartRequired: false,
325
+ credentialsStored,
279
326
  };
280
327
  }