@reefclaw/openclaw-plugin 0.1.35 → 0.1.37

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/bridge/bridge.js CHANGED
@@ -638,6 +638,26 @@ export class Bridge {
638
638
  this.connector.sendResponse(id, true, outcome);
639
639
  return;
640
640
  }
641
+ if (method === 'connector.restart') {
642
+ const provider = this.provider;
643
+ if (!provider.restartGateway) {
644
+ this.connector.sendResponse(id, true, {
645
+ ok: false,
646
+ status: 'failed',
647
+ message: 'Provider does not support connector.restart (likely mock provider)',
648
+ });
649
+ return;
650
+ }
651
+ // Same single-field contract as connector.update: no target, no
652
+ // reason, no args cross this boundary — the RPC the provider issues is
653
+ // a constant (providers/connector-update.ts requestGatewayRestart).
654
+ const acknowledgeOpenPositions = params?.acknowledgeOpenPositions === true;
655
+ audit('connector_restart.start', { id, acknowledgeOpenPositions });
656
+ const outcome = await provider.restartGateway({ acknowledgeOpenPositions });
657
+ audit('connector_restart.dispatched', { id, ok: outcome.ok, status: outcome.status });
658
+ this.connector.sendResponse(id, true, outcome);
659
+ return;
660
+ }
641
661
  if (method === 'get_bracket_config') {
642
662
  if (!this.provider.getBracketConfig) {
643
663
  this.connector.sendResponse(id, false, undefined, {
@@ -1287,7 +1307,7 @@ export class Bridge {
1287
1307
  // 2026-07-11 — agent stranded on 0.0.5 with the tracker at 2.20.4). If
1288
1308
  // ANY agent-visible copy is behind the webapp version, re-apply anyway;
1289
1309
  // applySkillUpdate is idempotent across all copies.
1290
- const staleAgentCopies = readAgentVisibleSkillVersions().filter((v) => compareSemver(body.version, v) > 0);
1310
+ const staleAgentCopies = readAgentVisibleSkillVersions(this.paths.workspaceDir).filter((v) => compareSemver(body.version, v) > 0);
1291
1311
  if (compareSemver(body.version, this.currentSkillVersion) <= 0 && staleAgentCopies.length === 0) {
1292
1312
  logger.info(TAG, `SKILL.md webapp pull: local v${this.currentSkillVersion ?? 'unknown'} already >= webapp v${body.version} — nothing to do`);
1293
1313
  this.skillPullInFlight = false;
@@ -19,6 +19,29 @@ export interface CcxtPosition {
19
19
  notional?: number;
20
20
  [key: string]: unknown;
21
21
  }
22
+ /** Plugin-computed day figures that ride on every `fetch_balance` response.
23
+ *
24
+ * ★ WHY THE ANCHOR RIDES HERE (2026-09-20 rig incident): the plugin rolls its
25
+ * UTC-midnight Day-P&L anchor (`sessionStartNav`) at 00:00:01, but the bridge
26
+ * used to adopt it ONLY inside the reconnect snapshot (`fetchFreshBalance`).
27
+ * On a live box with no dashboard reconnect after midnight the bridge kept
28
+ * YESTERDAY's anchor for 7 h 15 m and the KPI strip showed two days of P&L as
29
+ * "today" (−12.31 vs the true −4.74) — and the RED-zone daily-drawdown math
30
+ * read the same stale anchor. This 10 s poll is the only balance read that
31
+ * runs unconditionally, so the anchor must be adopted from it. */
32
+ export interface BalanceExtras {
33
+ /** Σ realized today, net of fees + funding (plugin's income / day-anchor value). */
34
+ realizedPnlToday?: number;
35
+ /** wallet_at_UTC_midnight (+ capital flows since) — the Day-P&L anchor. */
36
+ sessionStartNav?: number;
37
+ /** Plugin's NAV (= wallet + Σ uPnl on live; simulator equity on paper). */
38
+ equity?: number;
39
+ }
40
+ /** Pull the finite numeric extras off a raw `fetch_balance` payload. Returns
41
+ * undefined when none is present (an old plugin, or a rate-limited empty
42
+ * response) so the consumer never mistakes "absent" for "zero". Pure — tested
43
+ * directly. */
44
+ export declare function extractBalanceExtras(data: unknown): BalanceExtras | undefined;
22
45
  /** Callbacks fired by the Poller when fresh data arrives from polls. */
23
46
  export interface PollerCallbacks {
24
47
  /** Ticker data from fetch_ticker — fires every 1s */
@@ -28,15 +51,14 @@ export interface PollerCallbacks {
28
51
  /** Raw CCXT positions from fetch_positions — fires every 3s */
29
52
  onPositions: (positions: CcxtPosition[]) => void;
30
53
  /** Parsed balance from fetch_balance — fires every 10s. `extras` carries the
31
- * plugin-computed day figures that ride on the same response when present. */
54
+ * plugin-computed day figures that ride on the same response when present
55
+ * (see `BalanceExtras`). */
32
56
  onBalance: (balance: {
33
57
  currency: string;
34
58
  total: number;
35
59
  available: number;
36
60
  locked: number;
37
- }, extras?: {
38
- realizedPnlToday?: number;
39
- }) => void;
61
+ }, extras?: BalanceExtras) => void;
40
62
  /** Parsed open orders from fetch_open_orders — fires every 3s */
41
63
  onOpenOrders: (orders: OrderData[]) => void;
42
64
  /** Multi-TF analysis from get_market_structure — fires every 30s */
@@ -43,6 +43,24 @@ export const OPEN_ORDERS_INTERVAL_MS = 60_000;
43
43
  export const MARKET_STRUCTURE_INTERVAL_MS = 60_000;
44
44
  const CRYPTO_METRICS_INTERVAL_MS = 60_000;
45
45
  const VOLUME_ANALYSIS_INTERVAL_MS = 15_000;
46
+ const BALANCE_EXTRA_KEYS = ['realizedPnlToday', 'sessionStartNav', 'equity'];
47
+ /** Pull the finite numeric extras off a raw `fetch_balance` payload. Returns
48
+ * undefined when none is present (an old plugin, or a rate-limited empty
49
+ * response) so the consumer never mistakes "absent" for "zero". Pure — tested
50
+ * directly. */
51
+ export function extractBalanceExtras(data) {
52
+ if (!data || typeof data !== 'object')
53
+ return undefined;
54
+ const rec = data;
55
+ let out;
56
+ for (const key of BALANCE_EXTRA_KEYS) {
57
+ const v = rec[key];
58
+ if (typeof v === 'number' && Number.isFinite(v)) {
59
+ (out ??= {})[key] = v;
60
+ }
61
+ }
62
+ return out;
63
+ }
46
64
  // ---- Poller class ----
47
65
  /** 429 exponential-backoff schedule (ms). After each consecutive 429 we
48
66
  * advance one step; a clean poll resets to step 0. Capped so we never go
@@ -378,8 +396,7 @@ export class Poller {
378
396
  const tool = this.toolMap.fetch_balance;
379
397
  const result = await this.http.invoke(tool, {});
380
398
  const balance = mapCcxtBalance(result.data, this.quoteCurrency);
381
- const realized = result.data?.realizedPnlToday;
382
- this.callbacks.onBalance(balance, typeof realized === 'number' && Number.isFinite(realized) ? { realizedPnlToday: realized } : undefined);
399
+ this.callbacks.onBalance(balance, extractBalanceExtras(result.data));
383
400
  }
384
401
  /** Poll positions NOW (same ban-gate + in-flight guard as the timer). The
385
402
  * RED-zone guard calls this when the wallet/positions snapshot is torn by a
@@ -415,6 +415,9 @@ export function parseSessionTranscript(text) {
415
415
  let lastAssistantText = null;
416
416
  let lastAnyText = null;
417
417
  let firstUserSeen = false;
418
+ // The model the session is currently running on (from model_change events
419
+ // and assistant messages) — a model_change only counts as a switch against it.
420
+ let currentModel = null;
418
421
  for (const raw of text.split('\n')) {
419
422
  const line = raw.trim();
420
423
  if (!line)
@@ -445,7 +448,26 @@ export function parseSessionTranscript(text) {
445
448
  }
446
449
  case 'model_change': {
447
450
  const pm = providerModel(rec.provider, rec.modelId);
448
- pushEvent(out, { kind: 'model_change', at, detail: pm ?? 'model changed' });
451
+ // A model_change is a SWITCH only when the session already ran on a
452
+ // different model. OpenClaw ≥ 2026.9 opens every isolated cron session
453
+ // with `{type:"model_change", parentId:null}` at seq 1 — the initial
454
+ // model assignment, one per beat, same model start to finish. Counting
455
+ // it made model health read "degraded: 1 model change" on every beat
456
+ // of every 2026.9 box (Ardi report #7: 52 sessions, 52 records, all at
457
+ // seq 1), so the dot could never be green. The first model seen sets
458
+ // the baseline (and still names the beat's model when no assistant
459
+ // message ever arrives); a repeat of the current model is a no-op.
460
+ if (pm && currentModel !== null && pm !== currentModel) {
461
+ pushEvent(out, { kind: 'model_change', at, detail: pm });
462
+ }
463
+ if (pm) {
464
+ // `models` stays "models that answered" (assistant messages); the
465
+ // baseline is the one exception so a beat that dies before any
466
+ // assistant message still reports the model it was assigned.
467
+ if (currentModel === null && out.models.length === 0)
468
+ out.models.push(pm);
469
+ currentModel = pm;
470
+ }
449
471
  break;
450
472
  }
451
473
  case 'thinking_level_change': {
@@ -474,6 +496,8 @@ export function parseSessionTranscript(text) {
474
496
  const pm = providerModel(m.provider, m.responseModel ?? m.model);
475
497
  if (pm && !out.models.includes(pm))
476
498
  out.models.push(pm);
499
+ if (pm)
500
+ currentModel = pm;
477
501
  if (typeof m.api === 'string' && !out.api)
478
502
  out.api = m.api;
479
503
  const u = m.usage;
@@ -236,6 +236,14 @@ export interface OpenClawProvider {
236
236
  updateConnector?(args: {
237
237
  acknowledgeOpenPositions?: boolean;
238
238
  }): Promise<ConnectorUpdateOutcome>;
239
+ /** Operator-only: ask the OpenClaw gateway to restart ITSELF through its own
240
+ * `gateway.restart.request` RPC (operator.admin). This is how a box whose
241
+ * installer could not restart the gateway (Docker, any unmanaged gateway)
242
+ * loads already-installed connector files — no terminal, no host access.
243
+ * Same single input as updateConnector: the open-positions acknowledgement. */
244
+ restartGateway?(args: {
245
+ acknowledgeOpenPositions?: boolean;
246
+ }): Promise<ConnectorUpdateOutcome>;
239
247
  /** Operator-only: remove stored credentials from the plugin config and
240
248
  * de-escalate to PAPER mode if currently running in a live mode. */
241
249
  clearExchangeCredentials?(): Promise<{
@@ -64,6 +64,10 @@ export interface ConnectorUpdateOutcome {
64
64
  output?: string;
65
65
  /** True when the caller must re-submit with acknowledgeOpenPositions. */
66
66
  requiresPositionAck?: boolean;
67
+ /** Completed with the files in place, but the installer could not restart
68
+ * the gateway (its output carries INSTALLER_NOT_RESTARTED_MARKER) — the
69
+ * previous version is still running until the operator restarts it. */
70
+ restartRequired?: boolean;
67
71
  }
68
72
  /**
69
73
  * Map a gateway error from `terminal.open` onto an operator-readable outcome.
@@ -84,6 +88,13 @@ export declare function describeUpdateDisabled(): ConnectorUpdateOutcome;
84
88
  * broken, so the distinction is explicit and tested.
85
89
  */
86
90
  export declare function classifyTransportLoss(started: boolean): ConnectorUpdateStatus;
91
+ /** What the installer prints when it placed the new version but could not
92
+ * restart the gateway (installer/src/gateway-restart.ts NOT_RESTARTED_MARKER
93
+ * — inside a Docker container that is the normal outcome, only the host can
94
+ * restart the container). The installer still exits 0 (the files ARE
95
+ * installed), so completion is inspected for it. Pinned across packages. */
96
+ export declare const INSTALLER_NOT_RESTARTED_MARKER = "GATEWAY NOT RESTARTED";
97
+ export declare function installerReportedNoRestart(screen: string | null | undefined): boolean;
87
98
  /** Extract the exit code that follows the DONE sentinel, if it has appeared. */
88
99
  export declare function parseDoneSentinel(screen: string): {
89
100
  done: boolean;
@@ -122,8 +133,46 @@ export declare function checkPositionGuard(opts: StartOptions): ConnectorUpdateO
122
133
  export declare function startConnectorUpdate(rpc: TerminalRpc, opts: StartOptions,
123
134
  /** Exact connector release to install — from fetchPinnedConnectVersion, nowhere else. */
124
135
  version: string): Promise<ConnectorUpdateOutcome>;
125
- /** Read the current screen contents. Returns null when the session is gone. */
136
+ /** Read the current screen contents via `terminal.text`. Returns null when the
137
+ * session is gone. Prefer `createTerminalReader` — `terminal.text` no longer
138
+ * exists on OpenClaw ≥ 2026.8 (see there). */
126
139
  export declare function readTerminalText(rpc: TerminalRpc, sessionId: string): Promise<string | null>;
140
+ /** The gateway's reply to a method it does not have. A capability fact about
141
+ * the box, not a sign the box went away. */
142
+ export declare function isUnknownMethodError(err: unknown): boolean;
143
+ /** Reduce raw PTY output to the plain text a human (or the marker scan) would
144
+ * read — what the removed `terminal.text` used to do server-side. Handles the
145
+ * families a shell + npm + the installer emit: CSI (incl. private parameter
146
+ * bytes `<=>?:` and 8-bit `\x9b`), OSC (BEL- or ST-terminated), charset
147
+ * designations (`ESC ( B`), DEC save/restore/keypad (`ESC 7`, `ESC 8`,
148
+ * `ESC =`, `ESC >`), then carriage-return overwrites (progress bars redraw a
149
+ * line with `\r`; keep the last rendering) and stray C0 controls. */
150
+ export declare function stripAnsi(s: string): string;
151
+ export interface TerminalReader {
152
+ /** Current output of the session; null when the session/gateway is gone. */
153
+ read(sessionId: string): Promise<string | null>;
154
+ /** Which method served the last successful read (for the log line). */
155
+ readonly method: 'terminal.attach' | 'terminal.text' | null;
156
+ /** True once BOTH reads answered `unknown method`: the gateway is alive but
157
+ * offers no way to watch the PTY (no known OpenClaw does this; guarded so a
158
+ * null read from it is never mistaken for the restart). */
159
+ readonly unreadable: boolean;
160
+ }
161
+ /**
162
+ * Reads a PTY's output on any OpenClaw that has `terminal.open` at all.
163
+ *
164
+ * OpenClaw's 2026.7 terminal family offered two reads — `terminal.text` (the
165
+ * rendered screen) and `terminal.attach` (the raw replay `buffer`) — and
166
+ * REMOVED `terminal.text` in 2026.8 (gateway-protocol CHANGELOG, #121387). A
167
+ * bridge that only knew `terminal.text` got `unknown method` on every poll
168
+ * from 2026.8.1 on, counted the two rejections as the gateway dying, and
169
+ * reported "restarting" ~3 s into every one-click update with no output —
170
+ * while the installer kept running unwatched in a PTY that the dropped admin
171
+ * session left to be reaped. So: `terminal.attach` first (it exists wherever
172
+ * `terminal.open` does), `terminal.text` for a gateway that answers
173
+ * `unknown method` to attach, and an unknown-method reply is NEVER a dead read.
174
+ */
175
+ export declare function createTerminalReader(rpc: TerminalRpc): TerminalReader;
127
176
  /** Best-effort PTY cleanup. Never throws — cleanup failure must not mask an outcome. */
128
177
  export declare function closeTerminal(rpc: TerminalRpc, sessionId: string): Promise<void>;
129
178
  /** The subset of GatewayWsClient the admin session needs — injected so the
@@ -153,11 +202,42 @@ export type AdminSessionResult = {
153
202
  /** Connect a fresh admin-scoped client and wait for hello-ok. Resolves with the
154
203
  * granted scopes, or a blocked/failed outcome (client already destroyed). */
155
204
  export declare function openAdminGatewaySession(client: AdminSessionClient, timeoutMs?: number): Promise<AdminSessionResult>;
205
+ /** The gateway's answer to `gateway.restart.request`, as far as we read it. */
206
+ export interface GatewayRestartReply {
207
+ status?: string;
208
+ ok?: boolean;
209
+ preflight?: {
210
+ safe?: boolean;
211
+ blockers?: Array<{
212
+ kind?: string;
213
+ count?: number;
214
+ message?: string;
215
+ }>;
216
+ summary?: string;
217
+ };
218
+ }
219
+ /** Pure: map the RPC reply / error onto an operator outcome.
220
+ * `scheduled` + `coalesced` = the restart is happening now; `deferred` = the
221
+ * gateway restarts as soon as its active agent run drains (still a promise
222
+ * the gateway itself made, so it is `restarting`, with the reason shown). */
223
+ export declare function classifyGatewayRestartReply(reply: unknown): ConnectorUpdateOutcome;
224
+ /** Map an RPC error from `gateway.restart.request` onto an outcome. */
225
+ export declare function describeRestartRpcFailure(err: unknown): ConnectorUpdateOutcome;
226
+ /** Ask the gateway to restart itself. Never throws. */
227
+ export declare function requestGatewayRestart(rpc: TerminalRpc, opts: {
228
+ reason: string;
229
+ skipDeferral?: boolean;
230
+ }): Promise<ConnectorUpdateOutcome>;
231
+ /** The reason string the gateway logs for a restart we asked for. */
232
+ export declare const RESTART_REASON_AFTER_UPDATE = "reefclaw.connector.update";
233
+ export declare const RESTART_REASON_OPERATOR = "reefclaw.connector.restart";
156
234
  export interface RunOptions {
157
235
  pollMs?: number;
158
236
  maxPolls?: number;
159
237
  /** Injected for tests. */
160
238
  sleep?: (ms: number) => Promise<void>;
239
+ /** Injected for tests; defaults to createTerminalReader(rpc). */
240
+ reader?: TerminalReader;
161
241
  }
162
242
  /**
163
243
  * Poll the PTY and emit progress until the command finishes or the gateway
@@ -178,6 +178,19 @@ export function describeOpenFailure(err) {
178
178
  + `command to your agent, or ${manualUpdateHint()}. After that, updates are one click.`,
179
179
  };
180
180
  }
181
+ // No terminal RPC at all: OpenClaw < 2026.7 has no `terminal.*` methods, so
182
+ // the gateway answers `unknown method: terminal.open`. That is a fact about
183
+ // the box's OpenClaw version, not a fault, and no retry / "Update anyway"
184
+ // changes it (the rig on 2026.6.9 looped on exactly this, 2026-09-20).
185
+ if (/unknown method/.test(lower)) {
186
+ return {
187
+ ok: false,
188
+ status: 'blocked',
189
+ message: 'This box runs an OpenClaw older than 2026.7, which has no terminal API, so ReefClaw cannot run the '
190
+ + 'update for you. Upgrade OpenClaw to enable one-click updates; until then, paste the manual command '
191
+ + `to your agent, or ${manualUpdateHint()}.`,
192
+ };
193
+ }
181
194
  return {
182
195
  ok: false,
183
196
  status: 'failed',
@@ -203,6 +216,15 @@ export function describeUpdateDisabled() {
203
216
  export function classifyTransportLoss(started) {
204
217
  return started ? 'restarting' : 'failed';
205
218
  }
219
+ /** What the installer prints when it placed the new version but could not
220
+ * restart the gateway (installer/src/gateway-restart.ts NOT_RESTARTED_MARKER
221
+ * — inside a Docker container that is the normal outcome, only the host can
222
+ * restart the container). The installer still exits 0 (the files ARE
223
+ * installed), so completion is inspected for it. Pinned across packages. */
224
+ export const INSTALLER_NOT_RESTARTED_MARKER = 'GATEWAY NOT RESTARTED';
225
+ export function installerReportedNoRestart(screen) {
226
+ return typeof screen === 'string' && screen.includes(INSTALLER_NOT_RESTARTED_MARKER);
227
+ }
206
228
  /** Extract the exit code that follows the DONE sentinel, if it has appeared. */
207
229
  export function parseDoneSentinel(screen) {
208
230
  const idx = screen.lastIndexOf(DONE_SENTINEL);
@@ -296,7 +318,9 @@ version) {
296
318
  message: 'Update started. The agent restarts when it finishes, so the dashboard will reconnect on its own.',
297
319
  };
298
320
  }
299
- /** Read the current screen contents. Returns null when the session is gone. */
321
+ /** Read the current screen contents via `terminal.text`. Returns null when the
322
+ * session is gone. Prefer `createTerminalReader` — `terminal.text` no longer
323
+ * exists on OpenClaw ≥ 2026.8 (see there). */
300
324
  export async function readTerminalText(rpc, sessionId) {
301
325
  try {
302
326
  const res = await rpc('terminal.text', { sessionId });
@@ -315,6 +339,122 @@ export async function readTerminalText(rpc, sessionId) {
315
339
  return null;
316
340
  }
317
341
  }
342
+ /** The gateway's reply to a method it does not have. A capability fact about
343
+ * the box, not a sign the box went away. */
344
+ export function isUnknownMethodError(err) {
345
+ return /unknown method/i.test(err instanceof Error ? err.message : String(err));
346
+ }
347
+ /** Reduce raw PTY output to the plain text a human (or the marker scan) would
348
+ * read — what the removed `terminal.text` used to do server-side. Handles the
349
+ * families a shell + npm + the installer emit: CSI (incl. private parameter
350
+ * bytes `<=>?:` and 8-bit `\x9b`), OSC (BEL- or ST-terminated), charset
351
+ * designations (`ESC ( B`), DEC save/restore/keypad (`ESC 7`, `ESC 8`,
352
+ * `ESC =`, `ESC >`), then carriage-return overwrites (progress bars redraw a
353
+ * line with `\r`; keep the last rendering) and stray C0 controls. */
354
+ export function stripAnsi(s) {
355
+ return (s
356
+ // npm's spinner redraws its line with "cursor to column 1" (CSI 1G) +
357
+ // "clear line" instead of \r; make it an overwrite point too, so the
358
+ // pane shows the last frame rather than a wall of braille glyphs.
359
+ // eslint-disable-next-line no-control-regex
360
+ .replace(/(?:\u001b\[|\u009b)0?1?G/g, '\r')
361
+ // eslint-disable-next-line no-control-regex
362
+ .replace(/(?:\u001b\[|\u009b)[0-?]*[ -/]*[@-~]/g, '') // CSI
363
+ // eslint-disable-next-line no-control-regex
364
+ .replace(/\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)/g, '') // OSC
365
+ // eslint-disable-next-line no-control-regex
366
+ .replace(/\u001b[()*+][0-~]/g, '') // charset designation, e.g. ESC ( B
367
+ // eslint-disable-next-line no-control-regex
368
+ .replace(/\u001b[@-Z\\-_=>78]/g, '') // lone ESC + final (Fe / Fp)
369
+ .replace(/\r+\n/g, '\n') // CRLF → LF
370
+ .replace(/(^|\n)[^\n]*\r(?=[^\n])/g, '$1') // `\r` overwrite: keep what came after
371
+ .replace(/\r/g, '')
372
+ // eslint-disable-next-line no-control-regex
373
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, '') // other C0 / DEL
374
+ );
375
+ }
376
+ /**
377
+ * Reads a PTY's output on any OpenClaw that has `terminal.open` at all.
378
+ *
379
+ * OpenClaw's 2026.7 terminal family offered two reads — `terminal.text` (the
380
+ * rendered screen) and `terminal.attach` (the raw replay `buffer`) — and
381
+ * REMOVED `terminal.text` in 2026.8 (gateway-protocol CHANGELOG, #121387). A
382
+ * bridge that only knew `terminal.text` got `unknown method` on every poll
383
+ * from 2026.8.1 on, counted the two rejections as the gateway dying, and
384
+ * reported "restarting" ~3 s into every one-click update with no output —
385
+ * while the installer kept running unwatched in a PTY that the dropped admin
386
+ * session left to be reaped. So: `terminal.attach` first (it exists wherever
387
+ * `terminal.open` does), `terminal.text` for a gateway that answers
388
+ * `unknown method` to attach, and an unknown-method reply is NEVER a dead read.
389
+ */
390
+ export function createTerminalReader(rpc) {
391
+ let attachSupported = null; // null = not yet probed
392
+ let textSupported = null;
393
+ let method = null;
394
+ const viaAttach = async (sessionId) => {
395
+ try {
396
+ const res = (await rpc('terminal.attach', { sessionId }));
397
+ const buffer = res && typeof res === 'object' && typeof res.buffer === 'string' ? res.buffer : '';
398
+ return stripAnsi(buffer);
399
+ }
400
+ catch (err) {
401
+ return isUnknownMethodError(err) ? 'unsupported' : null;
402
+ }
403
+ };
404
+ const viaText = async (sessionId) => {
405
+ try {
406
+ const res = await rpc('terminal.text', { sessionId });
407
+ if (typeof res === 'string')
408
+ return res;
409
+ if (res && typeof res === 'object') {
410
+ const t = res;
411
+ if (typeof t.text === 'string')
412
+ return t.text;
413
+ if (typeof t.data === 'string')
414
+ return t.data;
415
+ }
416
+ return '';
417
+ }
418
+ catch (err) {
419
+ return isUnknownMethodError(err) ? 'unsupported' : null;
420
+ }
421
+ };
422
+ return {
423
+ get method() {
424
+ return method;
425
+ },
426
+ get unreadable() {
427
+ return attachSupported === false && textSupported === false;
428
+ },
429
+ async read(sessionId) {
430
+ if (attachSupported !== false) {
431
+ const r = await viaAttach(sessionId);
432
+ if (r !== 'unsupported') {
433
+ attachSupported = true;
434
+ if (r !== null)
435
+ method = 'terminal.attach';
436
+ return r;
437
+ }
438
+ attachSupported = false;
439
+ logger.info(TAG, 'terminal.attach is not available on this gateway — reading via terminal.text');
440
+ }
441
+ if (textSupported !== false) {
442
+ const r = await viaText(sessionId);
443
+ if (r !== 'unsupported') {
444
+ textSupported = true;
445
+ if (r !== null)
446
+ method = 'terminal.text';
447
+ return r;
448
+ }
449
+ textSupported = false;
450
+ }
451
+ // Neither read exists: the gateway is alive but we cannot watch the PTY
452
+ // (`unreadable` tells the loop this null is not the restart).
453
+ logger.warn(TAG, 'neither terminal.attach nor terminal.text is available on this gateway — cannot watch the update');
454
+ return null;
455
+ },
456
+ };
457
+ }
318
458
  /** Best-effort PTY cleanup. Never throws — cleanup failure must not mask an outcome. */
319
459
  export async function closeTerminal(rpc, sessionId) {
320
460
  await rpc('terminal.close', { sessionId }).catch(() => undefined);
@@ -362,6 +502,80 @@ export async function openAdminGatewaySession(client, timeoutMs = 20_000) {
362
502
  logger.info(TAG, `admin session open (scopes: ${result.join(', ')})`);
363
503
  return { ok: true, scopes: result };
364
504
  }
505
+ /** Pure: map the RPC reply / error onto an operator outcome.
506
+ * `scheduled` + `coalesced` = the restart is happening now; `deferred` = the
507
+ * gateway restarts as soon as its active agent run drains (still a promise
508
+ * the gateway itself made, so it is `restarting`, with the reason shown). */
509
+ export function classifyGatewayRestartReply(reply) {
510
+ const r = (reply && typeof reply === 'object' ? reply : {});
511
+ const status = typeof r.status === 'string' ? r.status : '';
512
+ if (status === 'scheduled' || status === 'coalesced') {
513
+ return {
514
+ ok: true,
515
+ status: 'restarting',
516
+ message: 'The gateway is restarting itself to load the new version. The dashboard reconnects on its own.',
517
+ };
518
+ }
519
+ if (status === 'deferred') {
520
+ const blockers = (r.preflight?.blockers ?? [])
521
+ .map((b) => (typeof b?.message === 'string' ? b.message : ''))
522
+ .filter(Boolean);
523
+ const why = blockers.length > 0 ? ` (waiting on: ${blockers.join('; ')})` : '';
524
+ return {
525
+ ok: true,
526
+ status: 'restarting',
527
+ message: `The gateway accepted the restart and will apply it as soon as its current agent run finishes${why}. `
528
+ + 'The dashboard reconnects on its own.',
529
+ };
530
+ }
531
+ return {
532
+ ok: false,
533
+ status: 'failed',
534
+ message: `The gateway did not accept the restart request (reply: ${status || 'unrecognised'}).`,
535
+ };
536
+ }
537
+ /** Map an RPC error from `gateway.restart.request` onto an outcome. */
538
+ export function describeRestartRpcFailure(err) {
539
+ const raw = err instanceof Error ? err.message : String(err);
540
+ const lower = raw.toLowerCase();
541
+ if (/unknown method/.test(lower)) {
542
+ return {
543
+ ok: false,
544
+ status: 'blocked',
545
+ message: 'This OpenClaw has no gateway.restart.request RPC (older than 2026.5.12), so the connector cannot restart it. '
546
+ + 'Restart OpenClaw yourself — in Docker, from the host machine (docker restart <container>).',
547
+ };
548
+ }
549
+ if (/operator\.admin|scope|forbidden|unauthori[sz]ed|not allowed|\b403\b/.test(lower)) {
550
+ return {
551
+ ok: false,
552
+ status: 'blocked',
553
+ message: 'The gateway refused the restart request (it needs the operator.admin scope). '
554
+ + 'Restart OpenClaw yourself — in Docker, from the host machine (docker restart <container>).',
555
+ };
556
+ }
557
+ return { ok: false, status: 'failed', message: `Could not ask the gateway to restart: ${raw}` };
558
+ }
559
+ /** Ask the gateway to restart itself. Never throws. */
560
+ export async function requestGatewayRestart(rpc, opts) {
561
+ try {
562
+ const reply = await rpc('gateway.restart.request', {
563
+ reason: opts.reason,
564
+ ...(opts.skipDeferral === true ? { skipDeferral: true } : {}),
565
+ });
566
+ const outcome = classifyGatewayRestartReply(reply);
567
+ logger.info(TAG, `gateway.restart.request → ${outcome.status}: ${outcome.message}`);
568
+ return outcome;
569
+ }
570
+ catch (err) {
571
+ const outcome = describeRestartRpcFailure(err);
572
+ logger.warn(TAG, `gateway.restart.request failed: ${outcome.message}`);
573
+ return outcome;
574
+ }
575
+ }
576
+ /** The reason string the gateway logs for a restart we asked for. */
577
+ export const RESTART_REASON_AFTER_UPDATE = 'reefclaw.connector.update';
578
+ export const RESTART_REASON_OPERATOR = 'reefclaw.connector.restart';
365
579
  /**
366
580
  * Poll the PTY and emit progress until the command finishes or the gateway
367
581
  * restart takes the session down. Returns the final outcome. A single failed
@@ -373,11 +587,26 @@ export async function runConnectorUpdate(rpc, sessionId, emit, opts = {}) {
373
587
  // Generous: an npm install on a small VPS is slow (240 × 1.5 s = 6 min).
374
588
  const maxPolls = opts.maxPolls ?? 240;
375
589
  const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
590
+ const reader = opts.reader ?? createTerminalReader(rpc);
376
591
  let lastEmitted = '';
377
592
  let consecutiveDeadReads = 0;
378
593
  for (let i = 0; i < maxPolls; i++) {
379
594
  await sleep(pollMs);
380
- const screen = await readTerminalText(rpc, sessionId);
595
+ const screen = await reader.read(sessionId);
596
+ if (screen === null && reader.unreadable) {
597
+ // Alive but unwatchable — not a restart, not a completion. Leave the PTY
598
+ // running (the installer is in it) and say exactly that.
599
+ const outcome = {
600
+ ok: false,
601
+ status: 'failed',
602
+ sessionId,
603
+ output: lastEmitted,
604
+ message: 'The update was started, but this gateway offers no way to watch the terminal (neither terminal.attach nor '
605
+ + 'terminal.text), so its outcome cannot be reported here. Check the plugin version notice on the dashboard in a few minutes.',
606
+ };
607
+ emit(outcome);
608
+ return outcome;
609
+ }
381
610
  if (screen !== null)
382
611
  consecutiveDeadReads = 0;
383
612
  else if (++consecutiveDeadReads < 2)
@@ -402,15 +631,53 @@ export async function runConnectorUpdate(rpc, sessionId, emit, opts = {}) {
402
631
  if (isCredibleCompletion(screen)) {
403
632
  const { exitCode } = parseDoneSentinel(screen);
404
633
  const ok = exitCode === 0;
634
+ // Exit 0 + the installer's own "not restarted" verdict: the files are in
635
+ // place but the OLD gateway is still running (a Docker box, or any
636
+ // unmanaged gateway the CLI cannot signal). Say so — "the agent restarts
637
+ // to load it" would be false, and no restart is coming from this side.
638
+ const restartRequired = ok && installerReportedNoRestart(screen);
639
+ if (restartRequired) {
640
+ // ★ Finish the job from here: the admin session that ran the PTY holds
641
+ // the operator.admin scope `gateway.restart.request` needs, so ask the
642
+ // gateway to restart ITSELF (in-process / respawn — works in Docker).
643
+ // Only when it refuses does the operator get the host-side advice.
644
+ await closeTerminal(rpc, sessionId);
645
+ const kicked = await requestGatewayRestart(rpc, { reason: RESTART_REASON_AFTER_UPDATE });
646
+ if (kicked.status === 'restarting') {
647
+ const outcome = {
648
+ ok: true,
649
+ status: 'restarting',
650
+ sessionId,
651
+ exitCode,
652
+ output: screen,
653
+ message: `Connector files updated. ${kicked.message}`,
654
+ };
655
+ emit(outcome);
656
+ return outcome;
657
+ }
658
+ const outcome = {
659
+ ok: true,
660
+ status: 'completed',
661
+ sessionId,
662
+ exitCode,
663
+ output: screen,
664
+ restartRequired: true,
665
+ message: 'Connector files updated, but the gateway was NOT restarted, so the previous version is still running. '
666
+ + 'If OpenClaw runs in Docker, restart the container from the host machine (docker restart <container>); '
667
+ + `otherwise restart OpenClaw. The new version loads then. (Self-restart refused: ${kicked.message})`,
668
+ };
669
+ emit(outcome);
670
+ return outcome;
671
+ }
405
672
  const outcome = {
406
673
  ok,
407
674
  status: 'completed',
408
675
  sessionId,
409
676
  exitCode,
410
677
  output: screen,
411
- message: ok
412
- ? 'Connector updated. The agent restarts to load it.'
413
- : `The updater exited with code ${exitCode}. The connector was left as it was.`,
678
+ message: !ok
679
+ ? `The updater exited with code ${exitCode}. The connector was left as it was.`
680
+ : 'Connector updated. The agent restarts to load it.',
414
681
  };
415
682
  emit(outcome);
416
683
  await closeTerminal(rpc, sessionId);
@@ -274,6 +274,20 @@ export declare class GatewayProvider implements OpenClawProvider {
274
274
  updateConnector(args: {
275
275
  acknowledgeOpenPositions?: boolean;
276
276
  }): Promise<ConnectorUpdateOutcome>;
277
+ /**
278
+ * Operator-triggered gateway self-restart through OpenClaw's own
279
+ * `gateway.restart.request` RPC. The one door on a Docker / unmanaged box:
280
+ * the installer cannot restart such a gateway, a raw signal is ignored as
281
+ * unauthorized, and running the CLI inside the container boots a second
282
+ * plugin stack (2026-09-19/20). Same gates as updateConnector — per-host
283
+ * opt-out, connected gateway, open-positions acknowledgement — then a
284
+ * short-lived operator.admin session for the single RPC. A `restarting`
285
+ * outcome is also emitted as a connector_update frame so the dashboard
286
+ * latches "restart expected" before the connection drops.
287
+ */
288
+ restartGateway(args: {
289
+ acknowledgeOpenPositions?: boolean;
290
+ }): Promise<ConnectorUpdateOutcome>;
277
291
  private emitConnectorUpdate;
278
292
  /** Operator-only. Approval/balance status of the provisioned HL wallet. */
279
293
  getHlAgentWalletStatus(): Promise<HlAgentWalletStatusOutcome>;
@@ -352,6 +366,14 @@ export declare class GatewayProvider implements OpenClawProvider {
352
366
  */
353
367
  private emitSyntheticFill;
354
368
  private onPollerBalance;
369
+ /**
370
+ * Adopt the plugin-provided Day-P&L anchor whenever it differs from ours.
371
+ * Shared by the 10 s balance poll and the reconnect snapshot so the two can
372
+ * never disagree about which anchor is current. No-op for a missing / zero /
373
+ * garbage value (old plugin, torn response) — the self-seed fallback in
374
+ * trySetSessionStartNav covers plugins that emit nothing.
375
+ */
376
+ private syncPluginSessionNav;
355
377
  /**
356
378
  * Set session start NAV once both balance AND positions have been received.
357
379
  * Checks persisted file first — if today's NAV was already captured in a
@@ -19,7 +19,7 @@ import { parseIdentityName } from '../utils/identity-name.js';
19
19
  import { assessDrawdownPlausibility, computeEquity as _computeEquity, computePositionNotional as _computePositionNotional, computeRiskMetrics as _computeRiskMetrics, DEFAULT_RISK_LIMITS, DRAWDOWN_ZONE_THRESHOLDS, TENANT_LIMIT_BOUNDS, boundedNum, validateDrawdownLadder, } from './risk-calculator.js';
20
20
  import { executeKill as _executeKill, executeFlatten as _executeFlatten, executePause as _executePause, executeResume as _executeResume, cancelPendingProposals, withProposalDetail, } from './emergency-commands.js';
21
21
  import { executeSetTradingMode, executeGetBracketConfig, executeSetBracketRequirement, executeSetExchangeCredentials, executeTestExchangeCredentials, executeClearExchangeCredentials, executeProvisionHlAgentWallet, executeHlAgentWalletStatus, executeSubmitHlAgentApproval, } from './onboarding-commands.js';
22
- import { startConnectorUpdate, runConnectorUpdate, fetchPinnedConnectVersion, openAdminGatewaySession, checkPositionGuard, describeUpdateDisabled, } from './connector-update.js';
22
+ import { startConnectorUpdate, runConnectorUpdate, fetchPinnedConnectVersion, openAdminGatewaySession, checkPositionGuard, describeUpdateDisabled, requestGatewayRestart, RESTART_REASON_OPERATOR, } from './connector-update.js';
23
23
  import { DEFAULT_AGENT_ID, isForeignAgentEvent, resolveAgentEventOwner } from '../gateway/agent-scope.js';
24
24
  const TAG = 'gateway';
25
25
  // ---- Day-start NAV persistence ----
@@ -828,6 +828,50 @@ export class GatewayProvider {
828
828
  });
829
829
  return started;
830
830
  }
831
+ /**
832
+ * Operator-triggered gateway self-restart through OpenClaw's own
833
+ * `gateway.restart.request` RPC. The one door on a Docker / unmanaged box:
834
+ * the installer cannot restart such a gateway, a raw signal is ignored as
835
+ * unauthorized, and running the CLI inside the container boots a second
836
+ * plugin stack (2026-09-19/20). Same gates as updateConnector — per-host
837
+ * opt-out, connected gateway, open-positions acknowledgement — then a
838
+ * short-lived operator.admin session for the single RPC. A `restarting`
839
+ * outcome is also emitted as a connector_update frame so the dashboard
840
+ * latches "restart expected" before the connection drops.
841
+ */
842
+ async restartGateway(args) {
843
+ if (this.config.allowConnectorUpdate === false) {
844
+ logger.info(TAG, 'connector.restart refused: one-click updates are switched off on this box');
845
+ return describeUpdateDisabled();
846
+ }
847
+ if (!this.wsClient) {
848
+ return { ok: false, status: 'failed', message: 'Not connected to the OpenClaw gateway.' };
849
+ }
850
+ const openPositionCount = this.positions.filter((p) => Math.abs(Number(p.contracts) || 0) > 0).length;
851
+ const blocked = checkPositionGuard({ acknowledgeOpenPositions: args.acknowledgeOpenPositions, openPositionCount });
852
+ if (blocked)
853
+ return blocked;
854
+ const admin = new GatewayWsClient({
855
+ gatewayUrl: this.config.gatewayUrl,
856
+ gatewayToken: this.config.gatewayToken,
857
+ requestAdminScope: true,
858
+ identities: [this.wsClient.getClientId()],
859
+ requireScope: 'operator.admin',
860
+ }, { baseDelayMs: 60_000, maxDelayMs: 60_000, maxFastAttempts: 0, jitterFactor: 0, slowRetryMs: 3_600_000 });
861
+ const session = await openAdminGatewaySession(admin);
862
+ if (!session.ok)
863
+ return session.outcome;
864
+ try {
865
+ const rpc = (method, params) => admin.sendRpc(method, params);
866
+ const outcome = await requestGatewayRestart(rpc, { reason: RESTART_REASON_OPERATOR });
867
+ if (outcome.status === 'restarting')
868
+ this.emitConnectorUpdate(outcome);
869
+ return outcome;
870
+ }
871
+ finally {
872
+ admin.destroy();
873
+ }
874
+ }
831
875
  emitConnectorUpdate(payload) {
832
876
  this.fire('connectorUpdate', payload);
833
877
  }
@@ -1781,9 +1825,41 @@ export class GatewayProvider {
1781
1825
  }
1782
1826
  this.balance = balance;
1783
1827
  this.hasReceivedBalance = true;
1828
+ // ★ Adopt the plugin's Day-P&L anchor from THIS poll, not only from the
1829
+ // reconnect snapshot. The plugin rolls `sessionStartNav` at UTC midnight;
1830
+ // before this the bridge only picked the new value up in
1831
+ // fetchFreshBalance() (a dashboard reconnect), so a live box with no
1832
+ // reconnect after midnight showed yesterday's anchor for hours — the
1833
+ // 2026-09-20 rig incident: Day P&L −12.31 (two UTC days) while the true
1834
+ // figure was −4.74, until a reconnect at 07:15 UTC synced it. The same
1835
+ // stale anchor feeds the RED-zone daily-drawdown math, so this is a
1836
+ // safety-floor input, not just a KPI. Must run BEFORE trySetSessionStartNav
1837
+ // (so the self-seed fallback never fires when the plugin has an anchor)
1838
+ // and BEFORE emitRiskUpdate (so the emitted numbers use the fresh anchor).
1839
+ if (typeof extras?.equity === 'number')
1840
+ this.equity = extras.equity;
1841
+ this.syncPluginSessionNav(extras?.sessionStartNav);
1784
1842
  this.trySetSessionStartNav();
1785
1843
  this.emitRiskUpdate();
1786
1844
  }
1845
+ /**
1846
+ * Adopt the plugin-provided Day-P&L anchor whenever it differs from ours.
1847
+ * Shared by the 10 s balance poll and the reconnect snapshot so the two can
1848
+ * never disagree about which anchor is current. No-op for a missing / zero /
1849
+ * garbage value (old plugin, torn response) — the self-seed fallback in
1850
+ * trySetSessionStartNav covers plugins that emit nothing.
1851
+ */
1852
+ syncPluginSessionNav(pluginNav) {
1853
+ if (!shouldSyncPluginSessionNav(pluginNav, this.sessionStartNav))
1854
+ return;
1855
+ const prev = this.sessionStartNav;
1856
+ this.sessionStartNav = pluginNav;
1857
+ // Stamp the day so the PAPER self-seed path (shouldAnchorSessionNav
1858
+ // re-anchors on a stale sessionDate) doesn't flap against the sync.
1859
+ this.sessionDate = todayDateStr();
1860
+ saveSessionStartNav(this.workspaceDir(), pluginNav);
1861
+ logger.info(TAG, `Session start NAV synced from plugin: ${prev.toFixed(4)} -> ${pluginNav} (${this.tradingMode} mode)`);
1862
+ }
1787
1863
  /**
1788
1864
  * Set session start NAV once both balance AND positions have been received.
1789
1865
  * Checks persisted file first — if today's NAV was already captured in a
@@ -2012,19 +2088,9 @@ export class GatewayProvider {
2012
2088
  // Crossing UTC midnight is handled automatically — the plugin's anchor
2013
2089
  // refreshes, the skill syncs next poll. The skill's self-seed
2014
2090
  // (trySetSessionStartNav) remains only as a fallback for plugins too old
2015
- // to emit sessionStartNav.
2016
- {
2017
- const pluginNav = result.data.sessionStartNav;
2018
- if (shouldSyncPluginSessionNav(pluginNav, this.sessionStartNav)) {
2019
- const prev = this.sessionStartNav;
2020
- this.sessionStartNav = pluginNav;
2021
- // Stamp the day so the PAPER self-seed path (shouldAnchorSessionNav
2022
- // re-anchors on a stale sessionDate) doesn't flap against the sync.
2023
- this.sessionDate = todayDateStr();
2024
- saveSessionStartNav(this.workspaceDir(), pluginNav);
2025
- logger.info(TAG, `Session start NAV synced from plugin: ${prev.toFixed(4)} -> ${pluginNav} (${this.tradingMode} mode)`);
2026
- }
2027
- }
2091
+ // to emit sessionStartNav. The 10 s balance poll (onPollerBalance) runs
2092
+ // the SAME sync, so a midnight rollover never waits for a reconnect.
2093
+ this.syncPluginSessionNav(result.data.sessionStartNav);
2028
2094
  return mapCcxtBalance(result.data, this.quoteCurrency);
2029
2095
  }
2030
2096
  catch (err) {
package/bridge/types.d.ts CHANGED
@@ -3,7 +3,7 @@ export type { Channel, RequestFrame, ResponseFrame, EventFrame, Frame, Emergency
3
3
  export { VALID_CHANNELS, VALID_EMERGENCY_ACTIONS } from '@reefclaw/shared';
4
4
  type EventFrame = _EventFrame;
5
5
  /** Methods the skill accepts from the relay (browser → skill) */
6
- export declare const ALLOWED_METHODS: readonly ["emergency.kill", "emergency.flatten", "emergency.pause", "emergency.resume", "reconcile", "chat.send", "skill.update", "close_position", "set_trading_mode", "set_exchange_credentials", "test_exchange_credentials", "clear_exchange_credentials", "hl_provision_agent_wallet", "hl_agent_wallet_status", "hl_submit_agent_approval", "get_bracket_config", "set_bracket_requirement", "connector.update"];
6
+ export declare const ALLOWED_METHODS: readonly ["emergency.kill", "emergency.flatten", "emergency.pause", "emergency.resume", "reconcile", "chat.send", "skill.update", "close_position", "set_trading_mode", "set_exchange_credentials", "test_exchange_credentials", "clear_exchange_credentials", "hl_provision_agent_wallet", "hl_agent_wallet_status", "hl_submit_agent_approval", "get_bracket_config", "set_bracket_requirement", "connector.update", "connector.restart"];
7
7
  /** Subset of ALLOWED_METHODS that require operator.write scope. The bridge
8
8
  * enforces this before dispatching — a session without the scope gets a
9
9
  * 403 error. PR2 ships the scope as session-wide (inherited from the Clerk
package/bridge/types.js CHANGED
@@ -29,6 +29,11 @@ export const ALLOWED_METHODS = [
29
29
  // the gateway PTY — carries no command/version/args field by design (see the
30
30
  // security note in providers/connector-update.ts). operator.write-gated.
31
31
  'connector.update',
32
+ // Operator-triggered gateway restart via OpenClaw's OWN `gateway.restart.request`
33
+ // RPC (the gateway restarts itself in-process — works in Docker, needs no
34
+ // terminal and no host access). Carries only the open-positions
35
+ // acknowledgement. operator.write-gated.
36
+ 'connector.restart',
32
37
  ];
33
38
  /** Subset of ALLOWED_METHODS that require operator.write scope. The bridge
34
39
  * enforces this before dispatching — a session without the scope gets a
@@ -47,6 +52,7 @@ export const OPERATOR_WRITE_METHODS = new Set([
47
52
  'get_bracket_config',
48
53
  'set_bracket_requirement',
49
54
  'connector.update',
55
+ 'connector.restart',
50
56
  'emergency.kill',
51
57
  'emergency.flatten',
52
58
  'emergency.pause',
@@ -2,15 +2,20 @@
2
2
  export declare function parseSkillVersion(content: string): string | null;
3
3
  /** Read current SKILL.md version from disk */
4
4
  export declare function readLocalSkillVersion(workspaceDir?: string): string | null;
5
- /** Versions of the AGENT-VISIBLE reefclaw SKILL.md copies under the
6
- * plugin-extension layout (`~/.openclaw/extensions/<plugin>/skills/<skill>/`)
7
- * — what OpenClaw's skill loader actually reads on chat-channel installs.
8
- * A plugin (re)install resets these to the bundled bootstrap while the
9
- * workspace copy (the version tracker above) survives, so the tracker alone
10
- * cannot be trusted for "already up to date" (observed live 2026-07-11: agent
11
- * stranded on bootstrap 0.0.5 while the tracker read 2.20.4). Fail-soft:
12
- * unreadable dirs/files are skipped; no extensions dir → empty list. */
13
- export declare function readAgentVisibleSkillVersions(): string[];
5
+ /** Versions of the AGENT-VISIBLE reefclaw SKILL.md copies — the files
6
+ * OpenClaw's skill loader actually reads, as opposed to the workspace tracker
7
+ * above. Two layouts:
8
+ * - `~/.openclaw/extensions/<plugin>/skills/<skill>/SKILL.md` (chat-channel
9
+ * installs). A plugin (re)install resets it to the bundled bootstrap while
10
+ * the tracker survives (observed live 2026-07-11: agent stranded on 0.0.5
11
+ * with the tracker at 2.20.4).
12
+ * - `<workspace>/skills/<skill>/SKILL.md` (every npx-installer box). The
13
+ * same reset happens there whenever anything re-runs
14
+ * `openclaw skills install --force` on the placed bootstrap
15
+ * (found 2026-09-19 while reviewing the installer's re-run path).
16
+ * The tracker alone cannot be trusted for "already up to date" in either
17
+ * layout. Fail-soft: unreadable dirs/files are skipped. */
18
+ export declare function readAgentVisibleSkillVersions(workspaceDir?: string): string[];
14
19
  /**
15
20
  * Compare two semver strings.
16
21
  * Returns 1 if a > b, -1 if a < b, 0 if equal.
@@ -19,46 +19,57 @@ export function readLocalSkillVersion(workspaceDir = DEFAULT_WORKSPACE_DIR) {
19
19
  return null;
20
20
  }
21
21
  }
22
- /** Versions of the AGENT-VISIBLE reefclaw SKILL.md copies under the
23
- * plugin-extension layout (`~/.openclaw/extensions/<plugin>/skills/<skill>/`)
24
- * — what OpenClaw's skill loader actually reads on chat-channel installs.
25
- * A plugin (re)install resets these to the bundled bootstrap while the
26
- * workspace copy (the version tracker above) survives, so the tracker alone
27
- * cannot be trusted for "already up to date" (observed live 2026-07-11: agent
28
- * stranded on bootstrap 0.0.5 while the tracker read 2.20.4). Fail-soft:
29
- * unreadable dirs/files are skipped; no extensions dir → empty list. */
30
- export function readAgentVisibleSkillVersions() {
22
+ /** Versions of the AGENT-VISIBLE reefclaw SKILL.md copies — the files
23
+ * OpenClaw's skill loader actually reads, as opposed to the workspace tracker
24
+ * above. Two layouts:
25
+ * - `~/.openclaw/extensions/<plugin>/skills/<skill>/SKILL.md` (chat-channel
26
+ * installs). A plugin (re)install resets it to the bundled bootstrap while
27
+ * the tracker survives (observed live 2026-07-11: agent stranded on 0.0.5
28
+ * with the tracker at 2.20.4).
29
+ * - `<workspace>/skills/<skill>/SKILL.md` (every npx-installer box). The
30
+ * same reset happens there whenever anything re-runs
31
+ * `openclaw skills install --force` on the placed bootstrap
32
+ * (found 2026-09-19 while reviewing the installer's re-run path).
33
+ * The tracker alone cannot be trusted for "already up to date" in either
34
+ * layout. Fail-soft: unreadable dirs/files are skipped. */
35
+ export function readAgentVisibleSkillVersions(workspaceDir = DEFAULT_WORKSPACE_DIR) {
31
36
  const versions = [];
32
37
  const extensionsDir = join(homedir(), '.openclaw', 'extensions');
33
- let extEntries;
38
+ let extEntries = [];
34
39
  try {
35
40
  extEntries = readdirSync(extensionsDir, { withFileTypes: true });
36
41
  }
37
42
  catch {
38
- return versions;
43
+ // no extensions dir — the workspace layout below may still apply
39
44
  }
40
45
  for (const ext of extEntries) {
41
46
  if (!ext.isDirectory() || !ext.name.includes('reefclaw'))
42
47
  continue;
43
- const skillsDir = join(extensionsDir, ext.name, 'skills');
44
- let skillEntries;
48
+ versions.push(...readSkillDirVersions(join(extensionsDir, ext.name, 'skills')));
49
+ }
50
+ versions.push(...readSkillDirVersions(join(workspaceDir, 'skills')));
51
+ return versions;
52
+ }
53
+ /** Versions of every `<skillsDir>/<*reefclaw*>/SKILL.md`; [] when unreadable. */
54
+ function readSkillDirVersions(skillsDir) {
55
+ const versions = [];
56
+ let skillEntries;
57
+ try {
58
+ skillEntries = readdirSync(skillsDir, { withFileTypes: true });
59
+ }
60
+ catch {
61
+ return versions;
62
+ }
63
+ for (const s of skillEntries) {
64
+ if (!s.isDirectory() || !s.name.includes('reefclaw'))
65
+ continue;
45
66
  try {
46
- skillEntries = readdirSync(skillsDir, { withFileTypes: true });
67
+ const v = parseSkillVersion(readFileSync(join(skillsDir, s.name, 'SKILL.md'), 'utf-8'));
68
+ if (v)
69
+ versions.push(v);
47
70
  }
48
71
  catch {
49
- continue;
50
- }
51
- for (const s of skillEntries) {
52
- if (!s.isDirectory() || !s.name.includes('reefclaw'))
53
- continue;
54
- try {
55
- const v = parseSkillVersion(readFileSync(join(skillsDir, s.name, 'SKILL.md'), 'utf-8'));
56
- if (v)
57
- versions.push(v);
58
- }
59
- catch {
60
- // unreadable/absent copy — nothing to report for this entry
61
- }
72
+ // unreadable/absent copy — nothing to report for this entry
62
73
  }
63
74
  }
64
75
  return versions;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "id": "reefclaw-paper-trading",
3
3
  "name": "ReefClaw Trading",
4
- "version": "0.1.35",
4
+ "version": "0.1.37",
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.35",
3
+ "version": "0.1.37",
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",
@@ -6,5 +6,7 @@
6
6
  "0.1.30": "Restores the connector's version reporting, so the dashboard's update notice works again for boxes that already updated (0.1.28 and 0.1.29 reported no version and could not be nudged).",
7
7
  "0.1.33": "Adds the connect installer's --agent <id> option for gateways that host several agents: the trading skill, heartbeat and dashboard attach to that agent and the trading tools are denied to the others.",
8
8
  "0.1.34": "The heartbeat flight recorder now reads OpenClaw 2026.9's SQLite transcript store (it recorded nothing on those gateways) and warns when it cannot see beats; a RED-zone drawdown is re-checked on a fresh position snapshot before it is judged, and a loss larger than the open book plus today's realized losses is refused as a calculation error instead of trusting a -50% constant; RC_SHOCK_WAKE=off switches shock wakes off per box; the README lists what the connector sends and how to read the risk log.",
9
- "0.1.35": "The connector never changes your gateway's auth settings any more (it reports the manual remedy instead); the install line in the bundled skill and the one-click update are pinned to an exact connector release instead of 'latest'; the bundled skill spells out what the remotely delivered trading instructions can and cannot do; the package README lists every file the plugin writes and everything it sends."
9
+ "0.1.35": "The connector never changes your gateway's auth settings any more (it reports the manual remedy instead); the install line in the bundled skill and the one-click update are pinned to an exact connector release instead of 'latest'; the bundled skill spells out what the remotely delivered trading instructions can and cannot do; the package README lists every file the plugin writes and everything it sends.",
10
+ "0.1.36": "Day P&L no longer shows two days as 'today' after midnight UTC: the connector now takes the exchange-anchored figure on every balance read, not only when the dashboard reconnects. The one-click update tells the truth on Docker and other unmanaged gateways (a restart the installer could not perform is reported, never assumed), shows live progress again on OpenClaw 2026.8+, and never resets the live skill with a forced reinstall; a box whose OpenClaw has no terminal API gets a clear 'update from a shell' notice instead of a retry loop.",
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."
10
12
  }
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: reefclaw
3
- version: 0.0.11
3
+ version: 0.0.12
4
4
  description: ReefClaw trading control room — bootstrap (connects your agent; the full trading instructions arrive after first connect as a signed, signature-verified update)
5
5
  author: ReefClaw
6
6
  homepage: https://reefclaw.com
@@ -101,14 +101,14 @@ 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.48
104
+ npx --yes @reefclaw/connect@0.1.50
105
105
  ```
106
106
 
107
- That is the whole install. It places the plugin, sets up the connector, restarts the gateway, and prints what it changed. 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.
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.
108
108
 
109
109
  **Do not attempt to perform this install yourself, and do not work around it if it is unavailable to you.** Specifically: do not edit OpenClaw's configuration to enable chat install commands, do not add anyone to an owner or elevated-exec allowlist, do not enable elevated mode, and do not restart the gateway to widen your own permissions. If you cannot run the command, the correct outcome is to hand the user the one line above and let them run it deliberately. A trading integration is exactly the kind of software whose installation a human should perform knowingly.
110
110
 
111
- **If the user installs via ClawHub instead** — no terminal needed on OpenClaw 2026.8.1 or newer: either OpenClaw's Control UI (Plugins → Discover → search "reefclaw" → Install → accept the listed capabilities), or the chat command `/plugins install clawhub:@reefclaw/openclaw-plugin` followed, after reading the capability list it replies with, by the same command plus `--accept-capabilities` (the chat command needs `commands.plugins: true` in openclaw.json, which only the user sets). ClawHub labels the plugin "Security scan: suspicious". That is expected and honest — ReefClaw discloses live-trading capability, exchange-credential storage, and remote instruction updates, which ClawHub flags for review (its linked security page has the details; VirusTotal reports the artifact clean). OpenClaw 2026.8.1+ shows that audit and continues once the capabilities are accepted; OpenClaw 2026.7.x still blocks the chat command on that label — there the user runs the `npx` line above, or `openclaw plugins install clawhub:@reefclaw/openclaw-plugin --acknowledge-clawhub-risk` in a terminal.
111
+ **If the user installs via ClawHub instead** — no terminal needed on OpenClaw 2026.8.1 or newer: either OpenClaw's Control UI (Plugins → Discover → search "reefclaw" → Install → accept the listed capabilities), or the chat command `/plugins install clawhub:@reefclaw/openclaw-plugin` followed, after reading the capability list it replies with, by the same command plus `--accept-capabilities` (the chat command needs `commands.plugins: true` in openclaw.json, which only the user sets). ClawHub scans every release with an automated security reviewer; the current release passes it (no warning at install). If a newer release ever shows a "Review" label, OpenClaw 2026.8.1+ shows the audit and continues once the capabilities are accepted, while OpenClaw 2026.7.x may block the chat command on it — there the user runs the `npx` line above.
112
112
 
113
113
  Whatever the install path, **save the connection settings anyway** — the connector picks them up automatically the moment the plugin is running.
114
114
 
@@ -964,6 +964,26 @@ export async function createOrderTool(args, deps) {
964
964
  }
965
965
  return { error: `${wave9Claimed ? 'Wave 9 runtime divergence; daily event latched. ' : ''}${message}` };
966
966
  };
967
+ // A refusal that touched nothing at the venue and is NOT a market divergence
968
+ // (an operator config gate, a size/exposure limit, the drawdown zone) hands
969
+ // the capability back instead of burning the day: the account is exactly as
970
+ // the batch projected it, so a fresh authorization for the same candidate is
971
+ // safe once the cause is fixed — the same contract as every other
972
+ // pre-mutation refusal below (mode / venue / activation / readiness /
973
+ // brackets). Ardi report #7 item 0: one pre-trade gate refusal latched the
974
+ // whole daily event and the next window was 24h away.
975
+ const releaseWave9BeforeMutation = (message, code) => {
976
+ if (wave9Lease) {
977
+ deps.wave9AdmissionGuard.abort(wave9Lease, code, { retryable: true, latchEvent: false });
978
+ wave9Lease = undefined;
979
+ }
980
+ return {
981
+ error: `${wave9Claimed
982
+ ? 'Wave 9 order refused before any venue mutation; authorization released, daily event NOT latched — ' +
983
+ 'fix the cause, then call get_wave9_status for a fresh authorization inside the entry window. '
984
+ : ''}${message}`,
985
+ };
986
+ };
967
987
  // From beginEntry onward, every unexpected failure must release the
968
988
  // in-flight capability. Explicit geometry/risk divergences still use the
969
989
  // latching helper above; infrastructure/pure-computation throws are
@@ -1067,7 +1087,9 @@ export async function createOrderTool(args, deps) {
1067
1087
  });
1068
1088
  if (!riskCheck.allowed) {
1069
1089
  const reasons = riskCheck.violations.map(v => v.message).join('; ');
1070
- return rejectWave9Divergence(`Order REJECTED by risk gate [${riskCheck.drawdownZone} zone]: ${reasons}`, `generic_pretrade_divergence:${riskCheck.violations.map((v) => v.rule).join(',')}`);
1090
+ // Nothing reached the venue and the account is unchanged: release the
1091
+ // wave9 capability rather than latching the daily event (see helper).
1092
+ return releaseWave9BeforeMutation(`Order REJECTED by risk gate [${riskCheck.drawdownZone} zone]: ${reasons}`, `generic_pretrade_refusal:${riskCheck.violations.map((v) => v.rule).join(',')}`);
1071
1093
  }
1072
1094
  // ---- Re-entry cooldown gate (mode-laddered; ships 'off') ----
1073
1095
  // Generic NEW entries only: wave9 has its own frozen admission policy,
@@ -90,8 +90,16 @@ export class BinanceUsdmWave9EvidenceProvider {
90
90
  const fourHourBars = ohlcvRows(fourHourRaw, `${symbol} 4h`)
91
91
  .filter((bar) => bar.time.getTime() >= fromMs && bar.time.getTime() <= eventMs)
92
92
  .sort((left, right) => left.time.getTime() - right.time.getTime());
93
+ // Both window edges carry the same jitter tolerance. Binance stamps the
94
+ // PREVIOUS day's boundary settlement a few ms late as routinely as any
95
+ // other (a real 2026-09-18T00:00:00.003Z row blocked three nights of
96
+ // entries — Ardi report #7): with a bare `> fromMs` lower bound that row
97
+ // survives the filter, the list runs one settlement long, and the whole
98
+ // universe is refused as "partial or stale" although every expected
99
+ // settlement is present. A row jittered past the tolerance still fails
100
+ // closed below, exactly like an interior settlement would.
93
101
  const fundingRowsInWindow = fundingRows(fundingRaw, symbol)
94
- .filter((row) => row.time.getTime() > fromMs
102
+ .filter((row) => row.time.getTime() > fromMs + FUNDING_TIME_TOLERANCE_MS
95
103
  && row.time.getTime() <= eventMs + FUNDING_TIME_TOLERANCE_MS)
96
104
  .sort((left, right) => left.time.getTime() - right.time.getTime());
97
105
  requireExactTimes(dailyBars, expectedDaily, `${symbol} completed 1d evidence`);