@reefclaw/openclaw-plugin 0.1.34 → 0.1.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,65 @@
1
+ # @reefclaw/openclaw-plugin
2
+
3
+ The ReefClaw trading plugin for OpenClaw. It gives an OpenClaw agent a supervised trading toolkit and connects it to the operator's ReefClaw dashboard. Everything runs on the operator's own machine; ReefClaw's servers host the dashboard, a relay and a market-data API, and never execute trades.
4
+
5
+ This file is the plain-language ledger of what the package does on the machine it is installed on: what runs, what it writes, what it sends, what it never does, and how to switch each part off. Every line is checkable against the shipped source.
6
+
7
+ ## What runs
8
+
9
+ - **The plugin** loads into the OpenClaw gateway at startup (`activation.onStartup` in the manifest) and registers the trading tools listed under `contracts.tools`.
10
+ - **One connector process** (the `bridge/` folder) is started and supervised by the plugin. It holds the outbound connection to the ReefClaw relay, runs the agent's scheduled heartbeat, and delivers signed instruction updates. If it exits, the plugin restarts it.
11
+ - The agent starts in **PAPER mode**: real market data, simulated fills, no exchange account and no API keys. Moving to real money is a separate step the **operator** takes from the dashboard (PAPER → MICRO_LIVE → LIVE), and the tools that change mode or store credentials refuse calls that do not carry operator provenance from the dashboard.
12
+
13
+ ## What it writes on this machine
14
+
15
+ | Path | What | Why |
16
+ | --- | --- | --- |
17
+ | `~/.reefclaw/plugin-config.json` (owner-only permissions) | Trading mode, per-box switches, and exchange credentials once the operator adds them | The only place exchange keys ever live; used only to sign requests to the exchange |
18
+ | `~/.reefclaw/credential-transport-key.json` | A key pair used to receive exchange credentials from the dashboard in encrypted form | So credentials cross the relay encrypted to this box; the private half never leaves it |
19
+ | Other files under `~/.reefclaw/` | Paper-trading state, the protective-order ledger, position state, a cached copy of the account's central config, market-data caches | Local bookkeeping so a restart resumes where it left off |
20
+ | `~/.openclaw/openclaw.json` → `skills.entries.reefclaw.config` only | The connection token, user id and relay URL the operator pasted | So the connector can reach the operator's own dashboard room. Nothing else in that file is touched, and **nothing under `gateway` is ever written** |
21
+ | OpenClaw's cron store | One heartbeat job (`reefclaw-heartbeat`), created through the gateway's own cron API | The scheduled position review; remove it with the OpenClaw cron commands |
22
+ | The `reefclaw` skill's `SKILL.md` in the agent workspace, in `~/.openclaw/skills/`, and in this package's `skills/` folder | The agent's trading instructions, kept identical in the places OpenClaw reads them | The bundled copy is a bootstrap; the full instructions arrive after connect and are applied only after their Ed25519 signature verifies against a key pinned in this build |
23
+ | The agent's `sessions.json` (older OpenClaw builds only) | One cached skills-snapshot key is cleared after an instruction update | So the running session re-reads the updated skill; nothing else in that file changes |
24
+
25
+ It **reads** the agent's heartbeat transcripts (OpenClaw's SQLite store on 2026.9+, JSONL before) to build the heartbeat flight recorder described below.
26
+
27
+ ## What leaves this machine
28
+
29
+ Everything below goes to the operator's own ReefClaw account and nowhere else.
30
+
31
+ | Flow | What is sent | Switch |
32
+ | --- | --- | --- |
33
+ | Dashboard relay | Order, position, balance and agent-state events; dashboard chat both ways | none, it is the product |
34
+ | Journal / trade feed | Fills, position entries, heartbeat reviews and closes with the agent's stated reasoning | none, it is the product |
35
+ | Heartbeat flight recorder | For every heartbeat: the tool calls it made (arguments and results truncated, credential-shaped tools redacted), its final report, the model that answered and raw token counts | `RC_HEARTBEAT_RECORDER=off` |
36
+ | Shock wakes | Nothing is sent; the connector polls the account's `shockWake` setting and, when the operator turned it on, delivers up to 8 extra agent turns a day on a sharp market move | `RC_SHOCK_WAKE=off` |
37
+ | Intelligence | Market-context reads; the plugin sends symbols and parameters, never keys | none, tools degrade without it |
38
+ | Version report | The installed plugin and connector versions, so the dashboard can offer an update | none |
39
+
40
+ Network access is outbound only: the relay (WebSocket), `www.reefclaw.com`, the intelligence API, the exchange when credentials are present, and the npm registry only during an operator-triggered update. The package opens no listening port.
41
+
42
+ ## What it never does
43
+
44
+ - **It never changes the gateway's auth settings.** If the gateway withholds the scope the connector needs, the connector logs the exact manual remedy and stops; the decision stays with the operator.
45
+ - **It never sends exchange API keys to ReefClaw.** A test in this package drives the real outbound clients and asserts no credential reaches the wire. On Hyperliquid the key is an agent key, which cannot withdraw or transfer funds; on Binance the operator is asked to create keys without withdrawal permission.
46
+ - **It never runs an unpinned install.** The install line in the bundled skill names the exact connector release this plugin was published with, and the dashboard's one-click update installs exactly the release ReefClaw's public release endpoint reports. If that lookup fails, the update does not run.
47
+ - **It never trades real money on its own initiative.** Live trading requires credentials and a mode change that only the operator can make from the dashboard; every live position carries exchange-native protective stops; and the operator's pause, flatten and kill controls are never gated behind subscription state.
48
+
49
+ ## Switches and removal
50
+
51
+ | Setting | Effect |
52
+ | --- | --- |
53
+ | `REEFCLAW_ALLOW_CONNECTOR_UPDATE=0` (or `connectorUpdate: "off"` in `plugin-config.json`) | The dashboard's one-click update is refused on this box |
54
+ | `RC_HEARTBEAT_RECORDER=off` | Heartbeat transcripts are not read or reported |
55
+ | `RC_SHOCK_WAKE=off` | Shock wakes are never constructed, whatever the account setting says |
56
+ | `SKILL_OTA_REQUIRE_SIGNATURE=off` | Break-glass: accept an *unsigned* instruction update on this box (a forged signature is still always refused) |
57
+
58
+ To remove the plugin: uninstall it with OpenClaw's plugin commands, delete `~/.reefclaw/`, remove the `reefclaw` skill folder(s), the `skills.entries.reefclaw` entry in `openclaw.json`, and the `reefclaw-heartbeat` cron job.
59
+
60
+ ## Install
61
+
62
+ - From ClawHub on OpenClaw 2026.8.1 or newer: Control UI → Plugins → Discover → search "reefclaw" → Install, then accept the listed capabilities; or in chat `/plugins install clawhub:@reefclaw/openclaw-plugin`, then the same command with `--accept-capabilities` after reading the capability list (the chat command needs `commands.plugins: true` in `openclaw.json`).
63
+ - Or with the ReefClaw connect installer from npm (`@reefclaw/connect`), run once in a terminal on the OpenClaw host and pinned to the exact release named in the bundled skill and on the onboarding page.
64
+
65
+ Support: support@reefclaw.com · https://reefclaw.com
package/bridge/bridge.js CHANGED
@@ -1287,7 +1287,7 @@ export class Bridge {
1287
1287
  // 2026-07-11 — agent stranded on 0.0.5 with the tracker at 2.20.4). If
1288
1288
  // ANY agent-visible copy is behind the webapp version, re-apply anyway;
1289
1289
  // applySkillUpdate is idempotent across all copies.
1290
- const staleAgentCopies = readAgentVisibleSkillVersions().filter((v) => compareSemver(body.version, v) > 0);
1290
+ const staleAgentCopies = readAgentVisibleSkillVersions(this.paths.workspaceDir).filter((v) => compareSemver(body.version, v) > 0);
1291
1291
  if (compareSemver(body.version, this.currentSkillVersion) <= 0 && staleAgentCopies.length === 0) {
1292
1292
  logger.info(TAG, `SKILL.md webapp pull: local v${this.currentSkillVersion ?? 'unknown'} already >= webapp v${body.version} — nothing to do`);
1293
1293
  this.skillPullInFlight = false;
@@ -28,17 +28,16 @@ export declare function writeOpenClawConfig(token: string, userId?: string, rela
28
28
  * never gets to run — this is the equivalent proven-need signal for it. */
29
29
  export declare function isDeviceIdentityRejection(code: number | undefined, reason: string | undefined): boolean;
30
30
  export declare function handshakeLacksWriteScope(scopes: readonly string[] | undefined): boolean;
31
+ /** The two legacy gateway flags older OpenClaw builds needed before they would
32
+ * keep `operator.write` on a connection without device identity. Named here
33
+ * ONLY so the remedy text can spell them out — this module never writes them. */
34
+ export declare const LEGACY_GATEWAY_AUTH_FLAGS: readonly ["gateway.controlUi.dangerouslyDisableDeviceAuth", "gateway.controlUi.allowInsecureAuth"];
31
35
  /**
32
- * LAST RESORT: relax the local gateway's device-identity auth because a
33
- * completed handshake proved the gateway is withholding `operator.write`
34
- * (without it the bridge cannot place or cancel orders). Idempotent, and a
35
- * no-op once the flags are set — so it warns exactly once per box, at the
36
- * moment the need is demonstrated.
37
- *
38
- * Returns true if it changed the config (⇒ the gateway must be restarted for
39
- * the flags to take effect; they are read at gateway boot).
36
+ * Operator-facing remedy for a gateway that withholds `operator.write` (or
37
+ * rejects the handshake for missing device identity). Pure: it builds text
38
+ * and changes nothing on disk.
40
39
  */
41
- export declare function relaxGatewayDeviceAuth(reason: string): boolean;
40
+ export declare function describeGatewayWriteScopeRemedy(reason: string): string;
42
41
  export interface CliArgs {
43
42
  provider: 'mock' | 'gateway';
44
43
  token?: string;
package/bridge/config.js CHANGED
@@ -17,13 +17,13 @@ const DEFAULT_RELAY_URL = 'wss://reefclaw.radunlupsa.partykit.dev';
17
17
  // during onboarding, so the connector can pick the connection up and persist
18
18
  // it across restarts). Every other key in the file is preserved verbatim.
19
19
  //
20
- // It deliberately does NOT weaken the local gateway's auth. Until 2026-07-29
21
- // it also set gateway.controlUi.{dangerouslyDisableDeviceAuth,
22
- // allowInsecureAuth} = true on EVERY write — a security-relevant downgrade of
23
- // the user's own gateway, applied pre-emptively whether or not their OpenClaw
24
- // needed it. That relaxation now happens only on PROVEN need, via
25
- // relaxGatewayDeviceAuth() below, which the bridge calls if and only if a
26
- // completed handshake shows the gateway actually withheld `operator.write`.
20
+ // It deliberately does NOT touch the local gateway's auth settings. Until
21
+ // 2026-07-29 the connector set gateway.controlUi.{dangerouslyDisableDeviceAuth,
22
+ // allowInsecureAuth} = true on every write, and until 2026-09-19 it still
23
+ // wrote them as a "last resort" when a handshake came back without
24
+ // `operator.write`. Both are gone: this software never changes the user's
25
+ // gateway security posture. When the gateway withholds the scope, the bridge
26
+ // logs the exact manual remedy (describeGatewayWriteScopeRemedy) and stops.
27
27
  /** Read the OpenClaw config file and extract ReefClaw skill settings.
28
28
  * Prefers the schema-valid nested shape (entry.config.*), falls back to the
29
29
  * legacy flat shape per-field. */
@@ -80,8 +80,9 @@ export function writeOpenClawConfig(token, userId, relayUrl) {
80
80
  delete entry.token;
81
81
  delete entry.userId;
82
82
  delete entry.relayUrl;
83
- // NOTE: no gateway.controlUi relaxation here. Saving a connection must not
84
- // change the user's gateway security posture — see relaxGatewayDeviceAuth().
83
+ // NOTE: nothing under gateway.controlUi is touched here or anywhere else in
84
+ // the connector. Saving a connection must not change the user's gateway
85
+ // security posture — see describeGatewayWriteScopeRemedy().
85
86
  // Write — file holds the connection token, so restrict to owner.
86
87
  mkdirSync(OPENCLAW_DIR, { recursive: true, mode: 0o700 });
87
88
  writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2) + '\n', { encoding: 'utf-8', mode: 0o600 });
@@ -104,43 +105,15 @@ function restrictConfigPermissions() {
104
105
  logger.debug(TAG, `Could not chmod ${CONFIG_PATH} to 0600: ${err instanceof Error ? err.message : String(err)}`);
105
106
  }
106
107
  }
107
- // ---- Gateway device-auth relaxation (LAST RESORT, proven need only) ----
108
+ // ---- Gateway scope: report, never relax ----
108
109
  //
109
- // Some OpenClaw builds (observed on v2026.4.2) clear `operator.write` from a WS
110
- // connection that carries no device identity — the bridge then cannot place or
111
- // cancel orders. The historical workaround was to set
112
- // gateway.controlUi.{dangerouslyDisableDeviceAuth, allowInsecureAuth} = true
113
- // on every install and every config save, whether or not the user's OpenClaw
114
- // actually behaved that way. That is a real downgrade of the user's gateway
115
- // applied on speculation, and the flag name says so.
116
- //
117
- // Since 2026-07-29 the relaxation is applied ONLY when a completed handshake
118
- // proves it is needed: the bridge inspects the granted scopes from hello-ok and
119
- // calls relaxGatewayDeviceAuth() if `operator.write` is missing. On the
120
- // supported range (the plugin's compat floor is pluginApi >=2026.6.0) the
121
- // handshake keeps its scopes and these flags are never written at all. Boxes
122
- // that already have them keep them — nothing here removes an existing flag,
123
- // because clearing it mid-session would strip the running bridge's scopes.
124
- /** Set the two relaxation flags on an in-memory config. Returns true if either
125
- * changed, so callers only write + disclose when something actually flipped. */
126
- function applyGatewayAuthRelaxation(config) {
127
- if (!config.gateway)
128
- config.gateway = {};
129
- const gw = config.gateway;
130
- if (!gw.controlUi)
131
- gw.controlUi = {};
132
- const cui = gw.controlUi;
133
- let changed = false;
134
- if (cui.dangerouslyDisableDeviceAuth !== true) {
135
- cui.dangerouslyDisableDeviceAuth = true;
136
- changed = true;
137
- }
138
- if (cui.allowInsecureAuth !== true) {
139
- cui.allowInsecureAuth = true;
140
- changed = true;
141
- }
142
- return changed;
143
- }
110
+ // Some OpenClaw builds withhold `operator.write` from a connection that
111
+ // carries no device identity, and OpenClaw >= 2026.9 rejects such a handshake
112
+ // outright. From 2026-07-29 to 2026-09-19 the connector answered that by
113
+ // writing gateway.controlUi.{dangerouslyDisableDeviceAuth, allowInsecureAuth}
114
+ // = true into the user's openclaw.json itself. It no longer does: a downgrade
115
+ // of the user's gateway auth is the user's decision, made by hand. The helpers
116
+ // below only DETECT the condition and DESCRIBE the remedy.
144
117
  /** True when the bridge lacks the write scope it needs to trade — i.e. the
145
118
  * gateway granted a scope set without `operator.write`. Read from the
146
119
  * handshake, so it reflects what the gateway ACTUALLY did, not a version
@@ -165,37 +138,29 @@ export function handshakeLacksWriteScope(scopes) {
165
138
  return false;
166
139
  return !scopes.includes('operator.write');
167
140
  }
141
+ /** The two legacy gateway flags older OpenClaw builds needed before they would
142
+ * keep `operator.write` on a connection without device identity. Named here
143
+ * ONLY so the remedy text can spell them out — this module never writes them. */
144
+ export const LEGACY_GATEWAY_AUTH_FLAGS = [
145
+ 'gateway.controlUi.dangerouslyDisableDeviceAuth',
146
+ 'gateway.controlUi.allowInsecureAuth',
147
+ ];
168
148
  /**
169
- * LAST RESORT: relax the local gateway's device-identity auth because a
170
- * completed handshake proved the gateway is withholding `operator.write`
171
- * (without it the bridge cannot place or cancel orders). Idempotent, and a
172
- * no-op once the flags are set — so it warns exactly once per box, at the
173
- * moment the need is demonstrated.
174
- *
175
- * Returns true if it changed the config (⇒ the gateway must be restarted for
176
- * the flags to take effect; they are read at gateway boot).
149
+ * Operator-facing remedy for a gateway that withholds `operator.write` (or
150
+ * rejects the handshake for missing device identity). Pure: it builds text
151
+ * and changes nothing on disk.
177
152
  */
178
- export function relaxGatewayDeviceAuth(reason) {
179
- try {
180
- const raw = readFileSync(CONFIG_PATH, 'utf-8');
181
- const config = JSON5.parse(raw);
182
- if (!applyGatewayAuthRelaxation(config))
183
- return false; // already relaxed
184
- writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2) + '\n', { encoding: 'utf-8', mode: 0o600 });
185
- restrictConfigPermissions(); // mode above is ignored on an existing file
186
- logger.warn(TAG, `Enabled gateway.controlUi.{dangerouslyDisableDeviceAuth,allowInsecureAuth} in ` +
187
- `${CONFIG_PATH} because ${reason}. This RELAXES your local gateway's ` +
188
- `device-identity auth — it is the only way this OpenClaw build will keep ` +
189
- `operator.write on the bridge connection, which trading requires. Keep the ` +
190
- `gateway bound to localhost. RESTART the gateway for it to take effect. If ` +
191
- `you would rather not run with it, upgrade OpenClaw (builds meeting the ` +
192
- `plugin's compat floor keep the scope without this) and remove both flags.`);
193
- return true;
194
- }
195
- catch {
196
- // Config missing/unparseable — setup hasn't run yet; nothing to relax.
197
- return false;
198
- }
153
+ export function describeGatewayWriteScopeRemedy(reason) {
154
+ return (`The OpenClaw gateway did not grant the connector operator.write (${reason}), so order ` +
155
+ `placement and cancellation would fail on this connection. ReefClaw does not change your ` +
156
+ `gateway's auth settings; the fix is yours to apply. Options: (1) upgrade OpenClaw to a build ` +
157
+ `that meets this plugin's compat floor — those keep the scope for the connector's ` +
158
+ `local-backend identity with no flags at all; (2) on OpenClaw 2026.9+, pair the connector as a ` +
159
+ `device or run the gateway with device pairing configured (see the gateway auth section of ` +
160
+ `${CONFIG_PATH}); (3) on older builds the historical workaround was setting ` +
161
+ `${LEGACY_GATEWAY_AUTH_FLAGS.join(' and ')} to true in ${CONFIG_PATH} and restarting the gateway — ` +
162
+ `that relaxes device-identity auth for every client, so only do it on a gateway bound to ` +
163
+ `localhost. Trading tools stay blocked until the gateway grants the scope.`);
199
164
  }
200
165
  /**
201
166
  * Resolve config with priority:
@@ -120,7 +120,7 @@ export async function ensureHeartbeatCron(opts) {
120
120
  // right for boxes with a chat channel (the heartbeat's summary reaches the
121
121
  // operator). On a FRESH box with no channels configured, cron.add REJECTS
122
122
  // announce/'last' (no resolvable recipient — observed live on a first
123
- // real npx onboarding, 2026-07-22; the old setup-time CLI path failed the
123
+ // real connect-installer onboarding, 2026-07-22; the old setup-time CLI path failed the
124
124
  // same way, silently). Fall back to delivery mode 'none': a heartbeat that
125
125
  // runs without announcing beats no heartbeat at all, and the operator sees
126
126
  // the results on the dashboard anyway.
@@ -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;
@@ -1,17 +1,46 @@
1
+ /** The npm package the update runs. Fixed. */
2
+ export declare const CONNECT_PACKAGE = "@reefclaw/connect";
3
+ export declare function isExactConnectVersion(v: unknown): v is string;
1
4
  /**
2
- * The ONE command this feature can ever run.
3
- *
4
- * `-y` so npx never blocks on its install prompt; `@latest` because this is an
5
- * update. No user input, no interpolation, no exceptions.
5
+ * The ONE command shape this feature can ever run. The only variable part is
6
+ * an exact version, validated against EXACT_VERSION_RE; anything else throws.
7
+ * `-y` keeps the package runner from stopping at its install prompt.
6
8
  */
7
- export declare const CONNECTOR_UPDATE_COMMAND = "npx -y @reefclaw/connect@latest";
9
+ export declare function connectorUpdateCommand(version: string): string;
8
10
  /** Marker printed after the command so we can detect completion + exit code. */
9
11
  export declare const DONE_SENTINEL = "__RC_CONNECTOR_UPDATE_DONE__";
10
12
  /**
11
- * The exact line written to the PTY. Built once, from constants only.
12
- * `$?` is expanded by the remote shell, not by us.
13
+ * The exact line written to the PTY. `$?` is expanded by the remote shell,
14
+ * not by us.
13
15
  */
14
- export declare function buildUpdateCommandLine(): string;
16
+ export declare function buildUpdateCommandLine(version: string): string;
17
+ /** Manual-fallback copy for the refusals below: the operator runs the same
18
+ * pinned command from a shell on the box. `version` is unknown when the
19
+ * refusal happened before the release lookup. */
20
+ export declare function manualUpdateHint(version?: string): string;
21
+ export interface PinnedVersionLookup {
22
+ /** Webapp base URL; defaults to REEFCLAW_API_URL, then production. */
23
+ webappUrl?: string;
24
+ fetchImpl?: typeof fetch;
25
+ }
26
+ export type PinnedVersionResult = {
27
+ ok: true;
28
+ version: string;
29
+ } | {
30
+ ok: false;
31
+ outcome: ConnectorUpdateOutcome;
32
+ };
33
+ /**
34
+ * Ask ReefClaw which connector release an update installs: `connectVersion` on
35
+ * the PUBLIC `/api/release` endpoint, baked by the webapp at build from the
36
+ * released installer (the same constants ride the authenticated config
37
+ * channel as `release.connectVersion`). No credential is needed or sent —
38
+ * release versions are public data, and an update must keep working on a box
39
+ * whose connection token is stale. Any failure, or anything that is not an
40
+ * exact version, refuses the update — this feature never falls back to an
41
+ * unpinned install.
42
+ */
43
+ export declare function fetchPinnedConnectVersion(opts: PinnedVersionLookup): Promise<PinnedVersionResult>;
15
44
  /** Minimal RPC surface this module needs (injected — keeps it unit-testable). */
16
45
  export type TerminalRpc = (method: string, params: Record<string, unknown>) => Promise<unknown>;
17
46
  export type ConnectorUpdateStatus =
@@ -35,6 +64,10 @@ export interface ConnectorUpdateOutcome {
35
64
  output?: string;
36
65
  /** True when the caller must re-submit with acknowledgeOpenPositions. */
37
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;
38
71
  }
39
72
  /**
40
73
  * Map a gateway error from `terminal.open` onto an operator-readable outcome.
@@ -55,6 +88,13 @@ export declare function describeUpdateDisabled(): ConnectorUpdateOutcome;
55
88
  * broken, so the distinction is explicit and tested.
56
89
  */
57
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;
58
98
  /** Extract the exit code that follows the DONE sentinel, if it has appeared. */
59
99
  export declare function parseDoneSentinel(screen: string): {
60
100
  done: boolean;
@@ -90,9 +130,49 @@ export declare function checkPositionGuard(opts: StartOptions): ConnectorUpdateO
90
130
  * Open a PTY and write the update command to it. Returns as soon as the command
91
131
  * is running — the caller polls `readTerminalText` for output.
92
132
  */
93
- export declare function startConnectorUpdate(rpc: TerminalRpc, opts: StartOptions): Promise<ConnectorUpdateOutcome>;
94
- /** Read the current screen contents. Returns null when the session is gone. */
133
+ export declare function startConnectorUpdate(rpc: TerminalRpc, opts: StartOptions,
134
+ /** Exact connector release to install — from fetchPinnedConnectVersion, nowhere else. */
135
+ version: string): Promise<ConnectorUpdateOutcome>;
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). */
95
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;
96
176
  /** Best-effort PTY cleanup. Never throws — cleanup failure must not mask an outcome. */
97
177
  export declare function closeTerminal(rpc: TerminalRpc, sessionId: string): Promise<void>;
98
178
  /** The subset of GatewayWsClient the admin session needs — injected so the
@@ -127,6 +207,8 @@ export interface RunOptions {
127
207
  maxPolls?: number;
128
208
  /** Injected for tests. */
129
209
  sleep?: (ms: number) => Promise<void>;
210
+ /** Injected for tests; defaults to createTerminalReader(rpc). */
211
+ reader?: TerminalReader;
130
212
  }
131
213
  /**
132
214
  * Poll the PTY and emit progress until the command finishes or the gateway