@reefclaw/openclaw-plugin 0.1.45 → 0.1.47

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 (61) hide show
  1. package/README.md +1 -1
  2. package/bridge/bridge.js +3 -3
  3. package/bridge/config.js +5 -2
  4. package/bridge/gateway/gateway-config.d.ts +5 -0
  5. package/bridge/gateway/gateway-config.js +5 -2
  6. package/bridge/heartbeat-runs.js +2 -3
  7. package/bridge/heartbeat-transcript.d.ts +2 -0
  8. package/bridge/heartbeat-transcript.js +45 -13
  9. package/bridge/index.js +28 -0
  10. package/bridge/providers/connector-update.js +2 -3
  11. package/bridge/providers/emergency-commands.js +2 -3
  12. package/bridge/providers/gateway.d.ts +6 -0
  13. package/bridge/providers/gateway.js +40 -25
  14. package/bridge/providers/onboarding-commands.d.ts +8 -7
  15. package/bridge/setup.js +12 -0
  16. package/bridge/shock-wake.d.ts +7 -0
  17. package/bridge/shock-wake.js +60 -7
  18. package/bridge/utils/base-url.d.ts +26 -0
  19. package/bridge/utils/base-url.js +108 -0
  20. package/bridge/utils/operator-secret.d.ts +7 -0
  21. package/bridge/utils/operator-secret.js +59 -0
  22. package/bridge/utils/relay-host.d.ts +23 -0
  23. package/bridge/utils/relay-host.js +66 -0
  24. package/bridge/utils/untrusted-text.d.ts +9 -0
  25. package/bridge/utils/untrusted-text.js +51 -0
  26. package/config/base-url.d.ts +16 -0
  27. package/config/base-url.js +87 -0
  28. package/config/operator-provenance.d.ts +19 -0
  29. package/config/operator-provenance.js +102 -25
  30. package/config/user-data-stream-config.d.ts +5 -1
  31. package/config/user-data-stream-config.js +7 -5
  32. package/connector-supervisor.d.ts +15 -0
  33. package/connector-supervisor.js +22 -1
  34. package/index.js +33 -24
  35. package/ingest/position-decisions-client.js +23 -4
  36. package/ingest/retry-after.d.ts +5 -0
  37. package/ingest/retry-after.js +21 -0
  38. package/ingest/trade-store-client.js +18 -3
  39. package/lifecycle/process-role.d.ts +4 -0
  40. package/lifecycle/process-role.js +1 -1
  41. package/openclaw.plugin.json +1 -1
  42. package/package.json +2 -2
  43. package/release-integrity.json +5 -0
  44. package/release-notes.json +2 -1
  45. package/risk/pre-trade-check.js +1 -1
  46. package/risk/stop-widening-guard.d.ts +35 -0
  47. package/risk/stop-widening-guard.js +98 -0
  48. package/skills/reefclaw/SKILL.md +2 -2
  49. package/tools/create-order.js +17 -12
  50. package/tools/get-bracket-config.d.ts +3 -1
  51. package/tools/get-bracket-config.js +3 -1
  52. package/tools/get-market-intel.d.ts +1 -0
  53. package/tools/get-market-intel.js +14 -3
  54. package/tools/modify-stop.d.ts +6 -0
  55. package/tools/modify-stop.js +110 -0
  56. package/tools/set-bracket-requirement.d.ts +7 -0
  57. package/tools/set-bracket-requirement.js +12 -0
  58. package/trading-params-bounds.d.ts +32 -0
  59. package/trading-params-bounds.js +113 -0
  60. package/trading-params-cache.d.ts +9 -1
  61. package/trading-params-cache.js +33 -2
@@ -1,50 +1,127 @@
1
1
  // Operator-provenance gate for the state-mutating operator tools
2
- // (audit 2026-07-26 F12).
2
+ // (audit 2026-07-26 F12; redesigned audit 2026-09-27 H1).
3
3
  //
4
4
  // "Operator-only. Never called by the agent." was PROSE in four tool
5
5
  // descriptions — nothing enforced it, and `acknowledged:true` is
6
6
  // caller-supplied, so a tool-capable agent could walk the PAPER→LIVE ladder,
7
7
  // clear the exchange credentials, or disable the stop-loss requirement with
8
- // one impulsive call. The dashboard path (browser → relay → skill bridge →
9
- // gateway) now proves provenance: the bridge injects the rc_* connection
10
- // token it already authenticates with, and the plugin compares it against
11
- // its own copy. The chat redaction guards keep rc_* tokens OUT of the
12
- // agent's context, so the agent cannot produce one conversationally.
8
+ // one impulsive call. The dashboard path (browser → relay → bridge → gateway
9
+ // `/tools/invoke`) proves provenance by attaching a secret the agent does not
10
+ // have.
13
11
  //
14
- // THREAT-MODEL HONESTY: the agent runs on the operator's own box and could
15
- // read plugin-config with exec tools — this gate defends against one-call
16
- // LLM impulsivity (the realistic failure mode), not a deliberately
17
- // adversarial agent, which owns the box and could edit the config directly.
12
+ // ★ WHAT THE SECRET IS (2026-09-27): a random per-boot value the plugin MINTS
13
+ // in memory and hands to the bridge it supervises over the child's STDIN at
14
+ // spawn — never argv (visible in `ps`), never the environment (readable from
15
+ // /proc/<pid>/environ by any same-user process, i.e. the agent's `exec`),
16
+ // never a file. The previous scheme used the rc_ connection token, which the
17
+ // onboarding flow tells the agent to write into its own config and which the
18
+ // tool schema advertised by name; an injected agent could `read` the file
19
+ // and forge provenance in two calls.
18
20
  //
19
- // Fail direction: OPEN when no connection token is configured (a pure-local
20
- // dev box has no dashboard to inject provenance — same
21
- // infrastructure-absent ⇒ allow direction as the entitlement gate);
22
- // CLOSED on a missing or mismatched token when one IS configured.
21
+ // Fallback: a bridge NOT spawned by this plugin (an unsupervised systemd unit)
22
+ // has no stdin channel, so no secret is issued and the plugin accepts the rc_
23
+ // connection token exactly as before — with a one-time warning that the box
24
+ // is on the weaker scheme. Supervised is the default on every npx / ClawHub
25
+ // install (the bridge ships inside the plugin package).
26
+ //
27
+ // Fail direction: OPEN only when the box has no connection token configured
28
+ // AT ALL (a pure-local dev box has no dashboard to inject provenance);
29
+ // CLOSED on a missing/mismatched value, and CLOSED when the config cannot be
30
+ // read (a corrupt or garbled plugin-config.json used to fail OPEN — the one
31
+ // file the agent could scribble on to disarm the gate).
23
32
  // Read per call (no restart needed after a token rotation — F10 philosophy).
24
- import { timingSafeEqual } from 'node:crypto';
33
+ //
34
+ // THREAT-MODEL HONESTY: the agent runs on the operator's own box as the same
35
+ // user as this plugin. The gate defends against one-call LLM impulsivity and
36
+ // against an agent READING a static proof (the realistic failure modes) — not
37
+ // against a deliberately adversarial agent, which owns the box: it could
38
+ // overwrite the bridge entrypoint the supervisor spawns and collect the secret
39
+ // on the next restart, or edit plugin-config.json directly. User-facing prose
40
+ // must therefore say the agent cannot supply provenance conversationally or
41
+ // read it back — never that the setting "cannot be changed by anyone".
42
+ import { randomBytes, timingSafeEqual } from 'node:crypto';
25
43
  import { readPluginConfig } from './plugin-config-io.js';
26
44
  import { resolveIngestToken } from './user-data-stream-config.js';
45
+ import { processRuntime } from '../lifecycle/process-role.js';
46
+ import { logger } from '../logger.js';
47
+ const TAG = 'operator-provenance';
27
48
  const REFUSAL = 'operator_only: this tool changes safety-critical operator settings and accepts requests ' +
28
- 'ONLY from the ReefClaw dashboard (operator provenance token missing or invalid). Do not ' +
29
- 'retry and do not attempt to obtain the token — if this change is wanted, the OPERATOR ' +
30
- 'makes it from the dashboard Settings panel.';
49
+ 'ONLY from the ReefClaw dashboard (operator provenance missing or invalid). Do not ' +
50
+ 'retry and do not attempt to obtain the provenance secret — it exists only inside the ' +
51
+ 'ReefClaw connector process. If this change is wanted, the OPERATOR makes it from the ' +
52
+ 'dashboard Settings panel.';
53
+ /** The presented value is an rc_ connection token while a per-boot secret is
54
+ * issued: that is a CONNECTOR on the older scheme (pre-dates this plugin
55
+ * version, or was not started by it), not an agent — say so, and say what
56
+ * fixes it (review 2026-09-27 N3). */
57
+ const REFUSAL_STALE_CONNECTOR = 'operator_only: this request presented the rc_ connection token as provenance, but this plugin ' +
58
+ 'issues a per-boot secret to the connector it supervises and accepts only that. The connector that ' +
59
+ 'sent this is on the older scheme — it predates this plugin version or was not started by it. ' +
60
+ 'OPERATOR: update the connector (dashboard → Update, or re-run the installer) and restart the ' +
61
+ 'gateway so plugin and connector match. Agent: do not retry.';
62
+ const REFUSAL_CONFIG_UNREADABLE = 'operator_only: the plugin config could not be read, so operator provenance cannot be ' +
63
+ 'verified — refusing (fail closed). The operator should check ~/.reefclaw/plugin-config.json.';
64
+ /** Mint (once per process) the per-boot secret the supervised bridge will
65
+ * present as `operator_token`. Idempotent: repeat calls return the same
66
+ * value so every module instance of this plugin agrees. */
67
+ export function issueOperatorSecret() {
68
+ const rec = processRuntime();
69
+ if (!rec.operatorSecret)
70
+ rec.operatorSecret = randomBytes(32).toString('hex');
71
+ return rec.operatorSecret;
72
+ }
73
+ /** The issued secret, or null when this process never spawned a bridge. */
74
+ export function currentOperatorSecret() {
75
+ return processRuntime().operatorSecret ?? null;
76
+ }
77
+ let warnedLegacyScheme = false;
78
+ function constantTimeEqual(given, expected) {
79
+ const a = Buffer.from(given, 'utf8');
80
+ const b = Buffer.from(expected, 'utf8');
81
+ return a.length === b.length && timingSafeEqual(a, b);
82
+ }
31
83
  export function verifyOperatorProvenance(provided, configPath) {
84
+ const given = typeof provided === 'string' ? provided.trim() : '';
85
+ // Strong scheme: the process minted a secret for the bridge it supervises.
86
+ // Nothing else — not even the rc_ connection token — is accepted then.
87
+ const secret = currentOperatorSecret();
88
+ if (secret) {
89
+ if (given.length > 0 && constantTimeEqual(given, secret))
90
+ return { ok: true };
91
+ return { ok: false, error: /^rc_/.test(given) ? REFUSAL_STALE_CONNECTOR : REFUSAL };
92
+ }
93
+ // Legacy scheme (unsupervised bridge): the rc_ connection token.
32
94
  let expected;
33
95
  try {
34
96
  expected = resolveIngestToken(readPluginConfig(configPath))?.trim() || undefined;
35
97
  }
36
98
  catch {
37
- expected = undefined;
99
+ return { ok: false, error: REFUSAL_CONFIG_UNREADABLE };
38
100
  }
39
101
  if (!expected)
40
102
  return { ok: true }; // unconfigured box — nothing to prove against
41
- const given = typeof provided === 'string' ? provided.trim() : '';
42
- if (given.length === 0)
43
- return { ok: false, error: REFUSAL };
44
- const a = Buffer.from(given, 'utf8');
45
- const b = Buffer.from(expected, 'utf8');
46
- if (a.length !== b.length || !timingSafeEqual(a, b)) {
103
+ if (!warnedLegacyScheme) {
104
+ warnedLegacyScheme = true;
105
+ logger.warn(TAG, 'operator provenance is using the rc_ connection token (no supervised connector in this process). ' +
106
+ 'A connector spawned by the plugin gets a per-boot secret instead — prefer that deployment shape.');
107
+ }
108
+ if (given.length === 0 || !constantTimeEqual(given, expected)) {
47
109
  return { ok: false, error: REFUSAL };
48
110
  }
49
111
  return { ok: true };
50
112
  }
113
+ /** Tool-result envelope for a refusal. Carries BOTH `error` (what every
114
+ * plugin tool returns and the agent reads) and `ok:false` + `message` (what
115
+ * the bridge's execute* wrappers pass through and the dashboard's
116
+ * TradingModeControl / ExchangeConnection render). Review 2026-09-27 B2: a
117
+ * bare `{error}` reached the dashboard as an EMPTY red box, so the stale-
118
+ * connector window this scheme creates was silent to the operator. */
119
+ export function provenanceRefusal(v) {
120
+ const text = v.error ?? REFUSAL;
121
+ return { ok: false, error: text, message: text };
122
+ }
123
+ /** Test-only: forget the issued secret and the one-time warning. */
124
+ export function resetOperatorProvenanceForTest() {
125
+ processRuntime().operatorSecret = null;
126
+ warnedLegacyScheme = false;
127
+ }
@@ -52,7 +52,11 @@ export type UserDataStreamDbWrite = 'off' | 'on';
52
52
  * Both must be enabled together for WS rows to land in `trades`. */
53
53
  export declare function getUserDataStreamDbWrite(config?: PluginConfigFile): UserDataStreamDbWrite;
54
54
  export declare function loadUserDataStreamDbWrite(): UserDataStreamDbWrite;
55
- /** Webapp ingest base URL (POST target). Defaults to production reefclaw.com. */
55
+ /** Webapp ingest base URL (POST target). Defaults to production reefclaw.com.
56
+ * `https:` required for a public host; plain `http:` only to a private /
57
+ * loopback host (local dev, on-prem) — anything else falls back to the
58
+ * default with a warning, so the rc_ token never goes out in cleartext
59
+ * (audit 2026-09-27 H4). */
56
60
  export declare function getUserDataStreamIngestBaseUrl(config?: PluginConfigFile): string;
57
61
  /** Resolve the webapp-ingest credential (the per-user `rc_*` token).
58
62
  *
@@ -21,6 +21,7 @@
21
21
  // Reverse transitions to any earlier stage (including 'shadow' and 'off') are
22
22
  // always permitted as a safety-net rollback.
23
23
  import { readPluginConfig, readOpenClawConnection } from './plugin-config-io.js';
24
+ import { sanitizeBaseUrl } from './base-url.js';
24
25
  const VALID = new Set(['off', 'shadow', 'observe', 'enforce']);
25
26
  /** Allowed forward transitions. Reverse transitions are always permitted so
26
27
  * the operator can fall back to REST if WS misbehaves.
@@ -118,12 +119,13 @@ export function loadUserDataStreamDbWrite() {
118
119
  return 'off';
119
120
  }
120
121
  }
121
- /** Webapp ingest base URL (POST target). Defaults to production reefclaw.com. */
122
+ /** Webapp ingest base URL (POST target). Defaults to production reefclaw.com.
123
+ * `https:` required for a public host; plain `http:` only to a private /
124
+ * loopback host (local dev, on-prem) — anything else falls back to the
125
+ * default with a warning, so the rc_ token never goes out in cleartext
126
+ * (audit 2026-09-27 H4). */
122
127
  export function getUserDataStreamIngestBaseUrl(config) {
123
- const raw = config?.userDataStream?.ingestBaseUrl;
124
- if (typeof raw === 'string' && /^https?:\/\//.test(raw))
125
- return raw;
126
- return 'https://www.reefclaw.com';
128
+ return sanitizeBaseUrl(config?.userDataStream?.ingestBaseUrl, 'https://www.reefclaw.com', 'userDataStream.ingestBaseUrl');
127
129
  }
128
130
  /** Resolve the webapp-ingest credential (the per-user `rc_*` token).
129
131
  *
@@ -20,7 +20,22 @@ export interface ConnectorSupervisorOptions {
20
20
  bridgeDir?: string;
21
21
  /** Injectable spawn for tests. */
22
22
  spawnFn?: typeof spawn;
23
+ /** Per-boot operator-provenance secret (config/operator-provenance.ts).
24
+ * Delivered to the child over STDIN as one line, then stdin is closed —
25
+ * never argv, never the environment (both readable by the agent's `exec`
26
+ * as the same user). The env only carries a non-secret MARKER telling the
27
+ * bridge to read the line. Absent → nothing is written and the bridge
28
+ * falls back to the rc_ token scheme. */
29
+ operatorSecret?: string;
30
+ /** Lazy form of `operatorSecret`: called only once a bridge is actually
31
+ * found and about to be launched, so a box with no connector on disk never
32
+ * mints a secret that would (correctly) lock out the rc_ token fallback of
33
+ * a bridge run some other way. Takes precedence over `operatorSecret`. */
34
+ issueOperatorSecret?: () => string;
23
35
  }
36
+ /** Env marker (value is not secret): the spawned bridge reads one line of
37
+ * stdin for the provenance secret when this is '1'. */
38
+ export declare const OPERATOR_SECRET_STDIN_MARKER = "REEFCLAW_OPERATOR_SECRET_STDIN";
24
39
  export interface ConnectorSupervisorHandle {
25
40
  stop(): void;
26
41
  /** Test/debug introspection. */
@@ -51,6 +51,9 @@ const MIN_BACKOFF_MS = 5_000;
51
51
  const MAX_BACKOFF_MS = 60_000;
52
52
  /** A child that survives this long resets the backoff (it was healthy). */
53
53
  const STABLE_RESET_MS = 5 * 60_000;
54
+ /** Env marker (value is not secret): the spawned bridge reads one line of
55
+ * stdin for the provenance secret when this is '1'. */
56
+ export const OPERATOR_SECRET_STDIN_MARKER = 'REEFCLAW_OPERATOR_SECRET_STDIN';
54
57
  // Process-wide, not module-scoped: OpenClaw 2026.9.5+ can load the plugin as
55
58
  // two module instances in one gateway, and a per-module singleton let each
56
59
  // start its own connector — two bridges sharing one relay-instance-id, which
@@ -81,6 +84,8 @@ export function startConnectorSupervisor(opts = {}) {
81
84
  return null;
82
85
  }
83
86
  const spawnFn = opts.spawnFn ?? spawn;
87
+ // A bridge WILL be launched from here on — only now mint the secret.
88
+ const operatorSecret = opts.issueOperatorSecret ? opts.issueOperatorSecret() : opts.operatorSecret;
84
89
  let child = null;
85
90
  let stopped = false;
86
91
  let backoffMs = MIN_BACKOFF_MS;
@@ -91,11 +96,27 @@ export function startConnectorSupervisor(opts = {}) {
91
96
  const startedAt = Date.now();
92
97
  // NOT detached: the connector must die with the gateway (a gateway
93
98
  // restart resurrects both, and an orphan bridge can never linger).
99
+ const withSecret = typeof operatorSecret === 'string' && operatorSecret.length > 0;
94
100
  child = spawnFn(process.execPath, [indexJs, '--provider', 'gateway', '--log-level', 'info'], {
95
101
  cwd: bridgeDir,
96
- stdio: ['ignore', 'pipe', 'pipe'],
102
+ stdio: [withSecret ? 'pipe' : 'ignore', 'pipe', 'pipe'],
103
+ env: withSecret ? { ...process.env, [OPERATOR_SECRET_STDIN_MARKER]: '1' } : process.env,
97
104
  });
98
105
  logger.info(TAG, `connector started (pid ${child.pid})`);
106
+ if (withSecret) {
107
+ // One line, then EOF: the bridge's reader stops at the newline and the
108
+ // pipe never carries anything else. Errors here (EPIPE if the child
109
+ // died at once) are logged, not thrown — the restart loop handles it.
110
+ try {
111
+ child.stdin?.on('error', (err) => logger.warn(TAG, `connector stdin: ${err.message}`));
112
+ // One call: write + EOF together, so a throwing write can never leave
113
+ // the pipe open with the bridge blocked in readSync (review N6).
114
+ child.stdin?.end(`${operatorSecret}\n`);
115
+ }
116
+ catch (err) {
117
+ logger.warn(TAG, `could not hand the provenance secret to the connector: ${err instanceof Error ? err.message : String(err)}`);
118
+ }
119
+ }
99
120
  const forward = (stream, level) => {
100
121
  stream?.on('data', (chunk) => {
101
122
  for (const line of chunk.toString().split('\n')) {
package/index.js CHANGED
@@ -4,7 +4,7 @@
4
4
  // Paper mode: simulated execution, no API keys needed.
5
5
  //
6
6
  // CRITICAL: register() MUST be synchronous — OpenClaw silently ignores async registration.
7
- // CRITICAL: Agent needs "group:plugins" in tools.sandbox.tools.allow in openclaw.json.
7
+ // CRITICAL: Agent needs "group:plugins" in tools.sandbox.tools.alsoAllow in openclaw.json (never an explicit allow list — audit M6).
8
8
  // See memory/connection.md for full deployment guide.
9
9
  import { readFileSync, existsSync } from 'node:fs';
10
10
  import { homedir } from 'node:os';
@@ -25,6 +25,7 @@ import { createLiveAdapter, fillExchangeId, isLiveVenueSupported, parseVenue, ve
25
25
  import { resolvePluginSymbol } from './venues/symbols.js';
26
26
  import { HyperliquidPublicApi } from './venues/hyperliquid/hl-public.js';
27
27
  import { bracketsEnabled, loadBracketMode } from './config/brackets-config.js';
28
+ import { sanitizeBaseUrl } from './config/base-url.js';
28
29
  import { loadUserDataStreamMode, loadUserDataStreamTunables, loadUserDataStreamDbWrite, getUserDataStreamIngestBaseUrl, resolveIngestToken, resolveReefclawUserId, } from './config/user-data-stream-config.js';
29
30
  import { TradeStoreClient } from './ingest/trade-store-client.js';
30
31
  import { ProposalManager } from './live/proposal-manager.js';
@@ -53,7 +54,7 @@ import { loadPositionReviewMode } from './config/position-review-config.js';
53
54
  import { installSignalHandlers } from './lifecycle/install-signal-handlers.js';
54
55
  import { SerialTradingOperationLock } from './lifecycle/trading-operation-lock.js';
55
56
  import { readPluginConfig, readOpenClawConnection, loadMicroLiveConfig, loadStopWatcherIntervalMs } from './config/plugin-config-io.js';
56
- import { verifyOperatorProvenance } from './config/operator-provenance.js';
57
+ import { verifyOperatorProvenance, issueOperatorSecret, provenanceRefusal } from './config/operator-provenance.js';
57
58
  import { startConnectorSupervisor, hasBundledBridge } from './connector-supervisor.js';
58
59
  import { ToolGate } from './config/tool-gate.js';
59
60
  import { gateStore } from './config/gate-store.js';
@@ -242,7 +243,7 @@ const TOOL_PARAMS = {
242
243
  type: 'object',
243
244
  properties: {
244
245
  symbol: { type: 'string', description: 'Symbol of the open live position' },
245
- new_stop_price: { type: 'number', description: 'New stop-loss price (must be on the protective side of entry)' },
246
+ new_stop_price: { type: 'number', description: 'New stop-loss price (must be on the protective side of entry). Widening is refused while the position is under water; a widening in profit must keep the loss-at-stop from entry within the per-trade loss cap. Tightening is always allowed.' },
246
247
  },
247
248
  required: ['symbol', 'new_stop_price'],
248
249
  },
@@ -805,7 +806,7 @@ const TOOL_PARAMS = {
805
806
  set_exchange_credentials: {
806
807
  type: 'object',
807
808
  properties: {
808
- operator_token: { type: 'string', description: 'Operator provenance — injected automatically by the ReefClaw dashboard path. Agent-initiated calls are refused without it.' },
809
+ 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.' },
809
810
  venue: { type: 'string', enum: ['binance', 'hyperliquid'], description: "Trading venue the credentials are for (default 'binance')" },
810
811
  apiKey: { type: 'string', description: 'Binance API key (venue=binance)' },
811
812
  secret: { type: 'string', description: 'Binance API secret (venue=binance)' },
@@ -819,7 +820,7 @@ const TOOL_PARAMS = {
819
820
  set_trading_mode: {
820
821
  type: 'object',
821
822
  properties: {
822
- operator_token: { type: 'string', description: 'Operator provenance — injected automatically by the ReefClaw dashboard path. Agent-initiated calls are refused without it.' },
823
+ 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.' },
823
824
  mode: { type: 'string', enum: ['PAPER', 'MICRO_LIVE', 'LIVE'], description: 'Target trading mode' },
824
825
  acknowledged: { type: 'boolean', description: 'Required when moving to LIVE — explicit operator acknowledgment' },
825
826
  },
@@ -828,7 +829,7 @@ const TOOL_PARAMS = {
828
829
  test_exchange_credentials: {
829
830
  type: 'object',
830
831
  properties: {
831
- operator_token: { type: 'string', description: 'Operator provenance — injected automatically by the ReefClaw dashboard path. Agent-initiated calls are refused without it.' },
832
+ 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.' },
832
833
  venue: { type: 'string', enum: ['binance', 'hyperliquid'], description: "Trading venue to verify against (default 'binance')" },
833
834
  apiKey: { type: 'string', description: 'Binance API key to verify (venue=binance; not persisted)' },
834
835
  secret: { type: 'string', description: 'Binance API secret to verify (venue=binance; not persisted)' },
@@ -841,7 +842,7 @@ const TOOL_PARAMS = {
841
842
  hl_provision_agent_wallet: {
842
843
  type: 'object',
843
844
  properties: {
844
- operator_token: { type: 'string', description: 'Operator provenance — injected automatically by the ReefClaw dashboard path. Agent-initiated calls are refused without it.' },
845
+ 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.' },
845
846
  walletAddress: { type: 'string', description: 'Hyperliquid MASTER account address 0x… the agent wallet will trade for (public; never a private key)' },
846
847
  testnet: { type: 'boolean', description: 'Provision for the Hyperliquid testnet (default: false)' },
847
848
  regenerate: { type: 'boolean', description: 'Replace an existing agent wallet with a fresh key (PAPER mode only; the old approval is orphaned)' },
@@ -851,14 +852,14 @@ const TOOL_PARAMS = {
851
852
  hl_agent_wallet_status: {
852
853
  type: 'object',
853
854
  properties: {
854
- operator_token: { type: 'string', description: 'Operator provenance — injected automatically by the ReefClaw dashboard path. Agent-initiated calls are refused without it.' },
855
+ 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.' },
855
856
  probe: { type: 'boolean', description: 'Tool-discovery probe — returns immediately without config or network access' },
856
857
  },
857
858
  },
858
859
  hl_submit_agent_approval: {
859
860
  type: 'object',
860
861
  properties: {
861
- operator_token: { type: 'string', description: 'Operator provenance — injected automatically by the ReefClaw dashboard path. Agent-initiated calls are refused without it.' },
862
+ 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.' },
862
863
  action: { type: 'object', description: "The wallet-signed approveAgent action, verbatim. Only type='approveAgent' is accepted." },
863
864
  nonce: { type: 'number', description: 'Outer nonce — must equal action.nonce (user-signed actions carry one nonce)' },
864
865
  signature: { type: 'object', description: 'Wallet signature { r, s, v } over the approveAgent typed data' },
@@ -868,7 +869,7 @@ const TOOL_PARAMS = {
868
869
  clear_exchange_credentials: {
869
870
  type: 'object',
870
871
  properties: {
871
- operator_token: { type: 'string', description: 'Operator provenance — injected automatically by the ReefClaw dashboard path. Agent-initiated calls are refused without it.' },
872
+ 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.' },
872
873
  confirm: { type: 'boolean', description: 'Must be true — safety gate against accidental probe wipes' },
873
874
  },
874
875
  required: ['confirm'],
@@ -880,7 +881,7 @@ const TOOL_PARAMS = {
880
881
  set_bracket_requirement: {
881
882
  type: 'object',
882
883
  properties: {
883
- operator_token: { type: 'string', description: 'Operator provenance — injected automatically by the ReefClaw dashboard path. Agent-initiated calls are refused without it.' },
884
+ 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.' },
884
885
  flag: { type: 'string', enum: ['requireStopLoss', 'requireTakeProfit'], description: 'Which requirement to flip' },
885
886
  value: { type: 'boolean', description: 'New value. False disables the requirement and returns a warning banner copy.' },
886
887
  },
@@ -1130,8 +1131,11 @@ const paperTradingPlugin = {
1130
1131
  const rcRaw = readFileSync(rcConfigPath, 'utf-8');
1131
1132
  const rcConfig = JSON.parse(rcRaw);
1132
1133
  connectionToken = rcConfig?.connectionToken ?? '';
1133
- apiBaseUrl = rcConfig?.apiBaseUrl ?? apiBaseUrl;
1134
- intelligenceUrl = rcConfig?.intelligenceUrl ?? intelligenceUrl;
1134
+ // Both carry the rc_ token as a Bearer header: https required for a
1135
+ // public host, plain http only to a private/loopback host (dev,
1136
+ // on-prem); anything else → production default + warning (H4).
1137
+ apiBaseUrl = sanitizeBaseUrl(rcConfig?.apiBaseUrl, apiBaseUrl, 'apiBaseUrl');
1138
+ intelligenceUrl = sanitizeBaseUrl(rcConfig?.intelligenceUrl, intelligenceUrl, 'intelligenceUrl');
1135
1139
  const ev = rcConfig?.signals?.evaluator;
1136
1140
  if (ev === 'shadow' || ev === 'enforce')
1137
1141
  signalsEvaluator = ev;
@@ -2418,7 +2422,7 @@ const paperTradingPlugin = {
2418
2422
  {
2419
2423
  name: 'modify_stop',
2420
2424
  label: 'Modify Stop',
2421
- description: 'Move the exchange-side stop-loss on an open live position. Atomic cancel-then-resubmit with automatic rollback. Live mode only; requires brackets.mode enabled.',
2425
+ description: 'Move the exchange-side stop-loss on an open live position. Atomic cancel-then-resubmit with automatic rollback. Live mode only; requires brackets.mode enabled. Safety floor: a wider stop is refused while the position is under water, and a widening in profit is capped at the per-trade loss limit.',
2422
2426
  parameters: TOOL_PARAMS.modify_stop,
2423
2427
  execute: async (_id, params) => jsonResult(await modifyStopTool(params, {
2424
2428
  ...adapterDeps,
@@ -2848,7 +2852,7 @@ const paperTradingPlugin = {
2848
2852
  execute: async (_id, params) => {
2849
2853
  const prov = verifyOperatorProvenance(params.operator_token);
2850
2854
  if (!prov.ok)
2851
- return jsonResult({ error: prov.error });
2855
+ return jsonResult(provenanceRefusal(prov));
2852
2856
  return jsonResult(await setExchangeCredentialsTool(params, { runtime, adapterDeps, bootVenue: venue }));
2853
2857
  },
2854
2858
  },
@@ -2860,7 +2864,7 @@ const paperTradingPlugin = {
2860
2864
  execute: async (_id, params) => {
2861
2865
  const prov = verifyOperatorProvenance(params.operator_token);
2862
2866
  if (!prov.ok)
2863
- return jsonResult({ error: prov.error });
2867
+ return jsonResult(provenanceRefusal(prov));
2864
2868
  return jsonResult(await setTradingModeTool(params, { runtime, adapterDeps, bootVenue: venue }));
2865
2869
  },
2866
2870
  },
@@ -2875,7 +2879,7 @@ const paperTradingPlugin = {
2875
2879
  execute: async (_id, params) => {
2876
2880
  const prov = verifyOperatorProvenance(params.operator_token);
2877
2881
  if (!prov.ok)
2878
- return jsonResult({ error: prov.error });
2882
+ return jsonResult(provenanceRefusal(prov));
2879
2883
  return jsonResult(await testExchangeCredentialsTool(params));
2880
2884
  },
2881
2885
  },
@@ -2887,7 +2891,7 @@ const paperTradingPlugin = {
2887
2891
  execute: async (_id, params) => {
2888
2892
  const prov = verifyOperatorProvenance(params.operator_token);
2889
2893
  if (!prov.ok)
2890
- return jsonResult({ error: prov.error });
2894
+ return jsonResult(provenanceRefusal(prov));
2891
2895
  return jsonResult(await clearExchangeCredentialsTool(params, { runtime, adapterDeps }));
2892
2896
  },
2893
2897
  },
@@ -2899,7 +2903,7 @@ const paperTradingPlugin = {
2899
2903
  execute: async (_id, params) => {
2900
2904
  const prov = verifyOperatorProvenance(params.operator_token);
2901
2905
  if (!prov.ok)
2902
- return jsonResult({ error: prov.error });
2906
+ return jsonResult(provenanceRefusal(prov));
2903
2907
  return jsonResult(await hlProvisionAgentWalletTool(params, { runtime, bootVenue: venue }));
2904
2908
  },
2905
2909
  },
@@ -2913,7 +2917,7 @@ const paperTradingPlugin = {
2913
2917
  return jsonResult(await hlSubmitAgentApprovalTool(params));
2914
2918
  const prov = verifyOperatorProvenance(params.operator_token);
2915
2919
  if (!prov.ok)
2916
- return jsonResult({ error: prov.error });
2920
+ return jsonResult(provenanceRefusal(prov));
2917
2921
  return jsonResult(await hlSubmitAgentApprovalTool(params));
2918
2922
  },
2919
2923
  },
@@ -2930,7 +2934,7 @@ const paperTradingPlugin = {
2930
2934
  return jsonResult(await hlAgentWalletStatusTool(params, {}));
2931
2935
  const prov = verifyOperatorProvenance(params.operator_token);
2932
2936
  if (!prov.ok)
2933
- return jsonResult({ error: prov.error });
2937
+ return jsonResult(provenanceRefusal(prov));
2934
2938
  return jsonResult(await hlAgentWalletStatusTool(params, { bootVenue: venue }));
2935
2939
  },
2936
2940
  },
@@ -2951,8 +2955,10 @@ const paperTradingPlugin = {
2951
2955
  execute: async (_id, params) => {
2952
2956
  const prov = verifyOperatorProvenance(params.operator_token);
2953
2957
  if (!prov.ok)
2954
- return jsonResult({ error: prov.error });
2955
- return jsonResult(setBracketRequirementTool(params));
2958
+ return jsonResult(provenanceRefusal(prov));
2959
+ // Adapter read at execute time: the protective-stop floor is not
2960
+ // waivable while trading is live (audit 2026-09-27 H1/H4).
2961
+ return jsonResult(setBracketRequirementTool(params, { isLive: runtime.adapter.isLive }));
2956
2962
  },
2957
2963
  },
2958
2964
  ];
@@ -3120,7 +3126,10 @@ function maybeStartConnectorSupervisor() {
3120
3126
  // is self-contained by design). Prod's linked plugin dir has no bundled
3121
3127
  // bridge and no flag → stays off; systemd keeps owning prod's bridge.
3122
3128
  if (supervisorMode === 'on' || hasBundledBridge()) {
3123
- startConnectorSupervisor();
3129
+ // The supervised connector receives a per-boot provenance secret over
3130
+ // stdin; from then on the operator-only tools accept ONLY that secret
3131
+ // (config/operator-provenance.ts, audit 2026-09-27 H1).
3132
+ startConnectorSupervisor({ issueOperatorSecret });
3124
3133
  }
3125
3134
  }
3126
3135
  catch (err) {
@@ -3,6 +3,8 @@
3
3
  //
4
4
  // Mirrors trade-store-client.ts retry semantics:
5
5
  // - 2xx : success.
6
+ // - 429 : rate-limited by the ingest guard — retryable (bounded Retry-After
7
+ // on top of the backoff; review 2026-09-27).
6
8
  // - 4xx : terminal — drop + log loudly (caller bug or duplicate).
7
9
  // - 5xx / network : retry with exponential backoff up to maxAttempts.
8
10
  //
@@ -13,6 +15,7 @@
13
15
  //
14
16
  // All four routes accept the same auth: Bearer + X-User-Id headers.
15
17
  import { keepAliveFetch } from '../http/keepalive-fetch.js';
18
+ import { retryAfterMs, sleepMs } from './retry-after.js';
16
19
  import { logger, formatError } from '../logger.js';
17
20
  const TAG = 'position-decisions-client';
18
21
  export class PositionDecisionsClient {
@@ -227,7 +230,13 @@ export class PositionDecisionsClient {
227
230
  return null;
228
231
  }
229
232
  }
230
- if (res.status >= 400 && res.status < 500) {
233
+ if (res.status === 429) {
234
+ const wait = retryAfterMs(res.headers.get('retry-after'));
235
+ logger.warn(TAG, `POST ${url} → 429 rate-limited (attempt ${attempt}/${this.opts.maxAttempts})${wait ? `, Retry-After ${wait}ms` : ''}.`);
236
+ if (wait)
237
+ await sleepMs(wait);
238
+ }
239
+ else if (res.status >= 400 && res.status < 500) {
231
240
  this.totalDroppedTerminal++;
232
241
  let errBody = '';
233
242
  try {
@@ -239,7 +248,9 @@ export class PositionDecisionsClient {
239
248
  logger.warn(TAG, `POST ${url} → ${res.status} (terminal, dropped). userId=${userId} body=${errBody.slice(0, 200)}`);
240
249
  return null;
241
250
  }
242
- logger.warn(TAG, `POST ${url} → ${res.status} (attempt ${attempt}/${this.opts.maxAttempts}).`);
251
+ else {
252
+ logger.warn(TAG, `POST ${url} → ${res.status} (attempt ${attempt}/${this.opts.maxAttempts}).`);
253
+ }
243
254
  }
244
255
  catch (err) {
245
256
  logger.warn(TAG, `POST ${url} threw (attempt ${attempt}/${this.opts.maxAttempts}): ${formatError(err)}`);
@@ -292,7 +303,13 @@ export class PositionDecisionsClient {
292
303
  return null;
293
304
  }
294
305
  }
295
- if (res.status >= 400 && res.status < 500) {
306
+ if (res.status === 429) {
307
+ const wait = retryAfterMs(res.headers.get('retry-after'));
308
+ logger.warn(TAG, `GET ${url} → 429 rate-limited (attempt ${attempt}/${maxAttempts})${wait ? `, Retry-After ${wait}ms` : ''}.`);
309
+ if (wait)
310
+ await sleepMs(wait);
311
+ }
312
+ else if (res.status >= 400 && res.status < 500) {
296
313
  let errBody = '';
297
314
  try {
298
315
  errBody = await res.text();
@@ -303,7 +320,9 @@ export class PositionDecisionsClient {
303
320
  logger.warn(TAG, `GET ${url} → ${res.status} (terminal, dropped). userId=${userId} body=${errBody.slice(0, 200)}`);
304
321
  return null;
305
322
  }
306
- logger.warn(TAG, `GET ${url} → ${res.status} (attempt ${attempt}/${maxAttempts}).`);
323
+ else {
324
+ logger.warn(TAG, `GET ${url} → ${res.status} (attempt ${attempt}/${maxAttempts}).`);
325
+ }
307
326
  }
308
327
  catch (err) {
309
328
  logger.warn(TAG, `GET ${url} threw (attempt ${attempt}/${maxAttempts}): ${formatError(err)}`);
@@ -0,0 +1,5 @@
1
+ /** Retry-After in ms from a header value: delta-seconds only (an HTTP-date
2
+ * form is ignored → null). Bounded to [0, RETRY_AFTER_CAP_MS]. */
3
+ export declare const RETRY_AFTER_CAP_MS = 30000;
4
+ export declare function retryAfterMs(header: string | null | undefined): number | null;
5
+ export declare function sleepMs(ms: number): Promise<void>;
@@ -0,0 +1,21 @@
1
+ // Retry-After parsing for the webapp ingest clients.
2
+ //
3
+ // The webapp's /api/internal/* routes answer 429 with a per-tenant sliding
4
+ // window (webapp/src/lib/api/internal-guard.ts). A 429 is NOT a terminal 4xx:
5
+ // the request was well-formed and will succeed once the window moves, so the
6
+ // clients retry it — honouring Retry-After when present, bounded so a hostile
7
+ // or buggy header can never park a client for minutes (review 2026-09-27).
8
+ /** Retry-After in ms from a header value: delta-seconds only (an HTTP-date
9
+ * form is ignored → null). Bounded to [0, RETRY_AFTER_CAP_MS]. */
10
+ export const RETRY_AFTER_CAP_MS = 30_000;
11
+ export function retryAfterMs(header) {
12
+ if (typeof header !== 'string')
13
+ return null;
14
+ const t = header.trim();
15
+ if (!/^\d{1,6}$/.test(t))
16
+ return null;
17
+ return Math.min(Number(t) * 1000, RETRY_AFTER_CAP_MS);
18
+ }
19
+ export function sleepMs(ms) {
20
+ return new Promise((resolve) => setTimeout(resolve, ms));
21
+ }
@@ -5,6 +5,10 @@
5
5
  //
6
6
  // - 2xx : success (including the implicit "no-op on conflict"
7
7
  // that the upsert returns as 200 + ok:true).
8
+ // - 429 : rate-limited by the ingest guard — RETRYABLE (honours a
9
+ // bounded Retry-After on top of the backoff). A reconnect
10
+ // resync can burst a whole fetchMyTrades page; a terminal
11
+ // drop here was permanent audit-trail loss (review 2026-09-27).
8
12
  // - 4xx (e.g. 400, 409) : terminal failure. Logged + dropped. Retrying
9
13
  // won't help: either the payload is malformed or
10
14
  // we're racing on a duplicate that's already
@@ -21,6 +25,7 @@
21
25
  // background. In-flight requests are tracked so `drain()` can be awaited at
22
26
  // shutdown to avoid losing the last fills before stop.
23
27
  import { logger, formatError } from '../logger.js';
28
+ import { retryAfterMs, sleepMs } from './retry-after.js';
24
29
  const TAG = 'trade-store-client';
25
30
  export class TradeStoreClient {
26
31
  opts;
@@ -94,15 +99,25 @@ export class TradeStoreClient {
94
99
  this.totalSucceeded++;
95
100
  return;
96
101
  }
97
- if (res.status >= 400 && res.status < 500) {
102
+ if (res.status === 429) {
103
+ // Rate-limited (per-tenant window) — retryable, never terminal.
104
+ const wait = retryAfterMs(res.headers.get('retry-after'));
105
+ logger.warn(TAG, `POST ${url} → 429 rate-limited (attempt ${attempt}/${this.opts.maxAttempts})` +
106
+ `${wait ? `, Retry-After ${wait}ms` : ''}. tradeId=${fill.exchangeTradeId}`);
107
+ if (wait)
108
+ await sleepMs(wait);
109
+ }
110
+ else if (res.status >= 400 && res.status < 500) {
98
111
  // Terminal — re-tries won't change the outcome. 409 is a duplicate
99
112
  // (idempotency win); 400/401/404 are bugs we want logged loudly.
100
113
  this.totalDroppedTerminal++;
101
114
  logger.warn(TAG, `POST ${url} → ${res.status} (terminal, dropped). userId=${userId} tradeId=${fill.exchangeTradeId}`);
102
115
  return;
103
116
  }
104
- // 5xx — fall through to retry.
105
- logger.warn(TAG, `POST ${url} → ${res.status} (attempt ${attempt}/${this.opts.maxAttempts}).`);
117
+ else {
118
+ // 5xx — fall through to retry.
119
+ logger.warn(TAG, `POST ${url} → ${res.status} (attempt ${attempt}/${this.opts.maxAttempts}).`);
120
+ }
106
121
  }
107
122
  catch (err) {
108
123
  // Network error / abort. Retry.