@reefclaw/openclaw-plugin 0.1.39 → 0.1.40

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.
@@ -0,0 +1,79 @@
1
+ import { spawn as nodeSpawn } from 'node:child_process';
2
+ import { type ConnectorUpdateOutcome, type TerminalRpc } from './connector-update.js';
3
+ /** The installer flag that selects the files-only mode (installer/src/files-only.ts). */
4
+ export declare const FILES_ONLY_FLAG = "--files-only";
5
+ /**
6
+ * ★ The first connector release whose installer understands `--files-only`.
7
+ * An OLDER installer ignores unknown flags and runs the FULL install — the
8
+ * `openclaw` CLI inside the container, the double plugin stack — so the
9
+ * direct path refuses to run anything older, whatever the release endpoint
10
+ * says. Bump only when a release before it could never be pinned again.
11
+ */
12
+ export declare const FILES_ONLY_MIN_CONNECT_VERSION = "0.1.53";
13
+ export declare function compareExactVersions(a: string, b: string): number;
14
+ /** True when `version` (exact) has a files-only installer. */
15
+ export declare function supportsFilesOnly(version: string): boolean;
16
+ /**
17
+ * The ONE argument vector this path can ever run. The only variable is an
18
+ * exact version, validated before it is placed; anything else throws.
19
+ */
20
+ export declare function directUpdateArgs(version: string): string[];
21
+ /**
22
+ * Where npx is. Preferred: next to the node binary running this process
23
+ * (`process.execPath`) — every standard install (official Docker image, nvm,
24
+ * nodesource, Homebrew) puts `npx` beside `node`, and it is the node the
25
+ * gateway itself runs on, so the installer's Node floor is met by
26
+ * construction. Fallback: `npx` on PATH. Pure (injected `exists`).
27
+ */
28
+ export declare function resolveNpx(execPath?: string, platform?: NodeJS.Platform, exists?: (p: string) => boolean): string;
29
+ /** PATH for the child: the node binary's directory first, so the installer's
30
+ * own `npm install` children resolve the same node/npm/npx this process runs
31
+ * on even under a service manager whose PATH omits it (nvm under systemd). */
32
+ export declare function childPath(execPath: string, basePath: string | undefined, platform?: NodeJS.Platform): string;
33
+ /** What the bridge can see of its surroundings — read once, judged by the
34
+ * pure `isInsideContainer`. Mirrors installer/src/gateway-restart.ts
35
+ * (readContainerProbe / detectContainer) without the host-command parts. */
36
+ export interface ContainerProbe {
37
+ /** `/.dockerenv` exists (Docker creates it in every container). */
38
+ dockerEnv: boolean;
39
+ /** Contents of /proc/1/cgroup, '' when unreadable. */
40
+ cgroup: string;
41
+ env: NodeJS.ProcessEnv;
42
+ }
43
+ export declare function readContainerProbe(): ContainerProbe;
44
+ /**
45
+ * A host-restartable container (Docker / Podman / Kubernetes) — where the PTY
46
+ * path would run the full installer, and with it the `openclaw` CLI, INSIDE
47
+ * the live gateway. System containers with their own init (LXC, nspawn) are
48
+ * ordinary boxes for this purpose. Pure.
49
+ */
50
+ export declare function isInsideContainer(probe: ContainerProbe): boolean;
51
+ /** Only ever this much of the installer's output is kept (the tail), so a
52
+ * chatty npm cannot grow the bridge's memory or the relay frames. */
53
+ export declare const MAX_OUTPUT_BYTES: number;
54
+ export declare function appendTail(buffer: string, chunk: string, max?: number): string;
55
+ export interface DirectRunDeps {
56
+ /** Injected for tests. */
57
+ spawn?: typeof nodeSpawn;
58
+ /** Injected for tests; defaults to resolveNpx(). */
59
+ npx?: string;
60
+ env?: NodeJS.ProcessEnv;
61
+ cwd?: string;
62
+ /** Hard cap on the installer's run; it is killed past it. */
63
+ timeoutMs?: number;
64
+ /** Minimum gap between two progress frames to the dashboard. */
65
+ emitThrottleMs?: number;
66
+ now?: () => number;
67
+ setTimer?: typeof setTimeout;
68
+ clearTimer?: typeof clearTimeout;
69
+ }
70
+ /**
71
+ * Run the installer directly and finish the job: files placed → ask the
72
+ * gateway to restart itself. Resolves with the final outcome; `emit` receives
73
+ * every intermediate one (started + progress), exactly like runConnectorUpdate.
74
+ *
75
+ * `rpc` is the operator.admin session the caller already opened (the restart
76
+ * RPC needs that scope). The position guard and the per-host opt-out have
77
+ * been applied by the caller.
78
+ */
79
+ export declare function runDirectConnectorUpdate(rpc: TerminalRpc, version: string, emit: (outcome: ConnectorUpdateOutcome) => void, deps?: DirectRunDeps): Promise<ConnectorUpdateOutcome>;
@@ -0,0 +1,311 @@
1
+ // Direct connector update: the bridge runs the installer ITSELF, as its own
2
+ // child process, instead of typing it into a gateway PTY.
3
+ //
4
+ // WHY THIS EXISTS: the PTY path (connector-update.ts) needs the gateway's
5
+ // `terminal.*` RPC family, which OpenClaw < 2026.7 does not have at all — the
6
+ // rig (OpenClaw 2026.6.9 in Docker) answered every dashboard click with
7
+ // `unknown method: terminal.open` and could only be updated by hand
8
+ // (2026-09-20, 2026-09-21). The bridge does not need the gateway's shell: it
9
+ // is spawned BY the gateway (plugin/src/connector-supervisor.ts), so it
10
+ // already runs as the gateway's user, with the gateway's environment and the
11
+ // gateway's own node binary. A child process of the bridge is exactly the
12
+ // process a PTY would have given us, minus the PTY.
13
+ //
14
+ // Two further reasons this is the path of choice inside a container:
15
+ // - the installer is run with `--files-only`, which NEVER executes the
16
+ // `openclaw` CLI — inside a live gateway container every CLI invocation
17
+ // boots a second plugin stack against the same state files and relay
18
+ // room (2026-07-27, 2026-09-19, 2026-09-20 with a live book open);
19
+ // - the restart is the gateway's own `update.run` self-restart
20
+ // (requestGatewayRestart), the one restart that reloads code in a
21
+ // container (OpenClaw respawns the process and exits; the container
22
+ // supervisor brings the new one up) and exits into Restart=always under
23
+ // systemd.
24
+ //
25
+ // ★★ SECURITY — the same rule as connector-update.ts, restated for this file:
26
+ // the command is a FIXED CONSTANT. The executable is npx (resolved next to the
27
+ // node binary running this process, else on PATH), the argument vector is
28
+ // `-y @reefclaw/connect@<exact version> --files-only`, built by
29
+ // `directUpdateArgs` from a MAJOR.MINOR.PATCH version that has exactly one
30
+ // source (ReefClaw's public release endpoint). No shell is involved
31
+ // (`shell: false`), nothing from the browser, relay, agent or config reaches
32
+ // the argv, and no secret is placed on it. The RPC that reaches this module
33
+ // carries NO command field.
34
+ import { spawn as nodeSpawn } from 'node:child_process';
35
+ import { existsSync, readFileSync } from 'node:fs';
36
+ import { homedir } from 'node:os';
37
+ import { posix, win32 } from 'node:path';
38
+ import { logger } from '../logger.js';
39
+ import { CONNECT_PACKAGE, INSTALLER_NOT_RESTARTED_MARKER, RESTART_REASON_AFTER_UPDATE, installerReportedNoRestart, isExactConnectVersion, manualUpdateHint, requestGatewayRestart, } from './connector-update.js';
40
+ const TAG = 'connector-update';
41
+ /** The installer flag that selects the files-only mode (installer/src/files-only.ts). */
42
+ export const FILES_ONLY_FLAG = '--files-only';
43
+ /**
44
+ * ★ The first connector release whose installer understands `--files-only`.
45
+ * An OLDER installer ignores unknown flags and runs the FULL install — the
46
+ * `openclaw` CLI inside the container, the double plugin stack — so the
47
+ * direct path refuses to run anything older, whatever the release endpoint
48
+ * says. Bump only when a release before it could never be pinned again.
49
+ */
50
+ export const FILES_ONLY_MIN_CONNECT_VERSION = '0.1.53';
51
+ export function compareExactVersions(a, b) {
52
+ const pa = a.split('.').map(Number);
53
+ const pb = b.split('.').map(Number);
54
+ for (let i = 0; i < 3; i += 1) {
55
+ if (pa[i] !== pb[i])
56
+ return pa[i] < pb[i] ? -1 : 1;
57
+ }
58
+ return 0;
59
+ }
60
+ /** True when `version` (exact) has a files-only installer. */
61
+ export function supportsFilesOnly(version) {
62
+ return isExactConnectVersion(version) && compareExactVersions(version, FILES_ONLY_MIN_CONNECT_VERSION) >= 0;
63
+ }
64
+ /**
65
+ * The ONE argument vector this path can ever run. The only variable is an
66
+ * exact version, validated before it is placed; anything else throws.
67
+ */
68
+ export function directUpdateArgs(version) {
69
+ if (!isExactConnectVersion(version)) {
70
+ throw new Error(`refusing to build an update command for a non-exact version: ${JSON.stringify(version)}`);
71
+ }
72
+ return ['-y', `${CONNECT_PACKAGE}@${version}`, FILES_ONLY_FLAG];
73
+ }
74
+ /**
75
+ * Where npx is. Preferred: next to the node binary running this process
76
+ * (`process.execPath`) — every standard install (official Docker image, nvm,
77
+ * nodesource, Homebrew) puts `npx` beside `node`, and it is the node the
78
+ * gateway itself runs on, so the installer's Node floor is met by
79
+ * construction. Fallback: `npx` on PATH. Pure (injected `exists`).
80
+ */
81
+ export function resolveNpx(execPath = process.execPath, platform = process.platform, exists = existsSync) {
82
+ const path = platform === 'win32' ? win32 : posix;
83
+ const name = platform === 'win32' ? 'npx.cmd' : 'npx';
84
+ const beside = path.join(path.dirname(execPath), name);
85
+ return exists(beside) ? beside : name;
86
+ }
87
+ /** PATH for the child: the node binary's directory first, so the installer's
88
+ * own `npm install` children resolve the same node/npm/npx this process runs
89
+ * on even under a service manager whose PATH omits it (nvm under systemd). */
90
+ export function childPath(execPath, basePath, platform = process.platform) {
91
+ const path = platform === 'win32' ? win32 : posix;
92
+ const bin = path.dirname(execPath);
93
+ const rest = (basePath ?? '').split(path.delimiter).filter((p) => p.length > 0 && p !== bin);
94
+ return [bin, ...rest].join(path.delimiter);
95
+ }
96
+ export function readContainerProbe() {
97
+ let cgroup = '';
98
+ try {
99
+ cgroup = readFileSync('/proc/1/cgroup', 'utf-8');
100
+ }
101
+ catch {
102
+ /* not Linux, or unreadable — the other tells decide */
103
+ }
104
+ return { dockerEnv: existsSync('/.dockerenv'), cgroup, env: process.env };
105
+ }
106
+ /**
107
+ * A host-restartable container (Docker / Podman / Kubernetes) — where the PTY
108
+ * path would run the full installer, and with it the `openclaw` CLI, INSIDE
109
+ * the live gateway. System containers with their own init (LXC, nspawn) are
110
+ * ordinary boxes for this purpose. Pure.
111
+ */
112
+ export function isInsideContainer(probe) {
113
+ const c = (probe.env.container ?? '').trim().toLowerCase();
114
+ if (c === 'lxc' || c === 'systemd-nspawn' || c === 'lxc-libvirt')
115
+ return false;
116
+ const hinted = (probe.env.OPENCLAW_CONTAINER_HINT?.trim() || probe.env.OPENCLAW_CONTAINER?.trim() || '').length > 0;
117
+ return (hinted ||
118
+ probe.dockerEnv ||
119
+ c === 'docker' ||
120
+ c === 'podman' ||
121
+ /\b(docker|containerd|kubepods|libpod|podman)\b/.test(probe.cgroup));
122
+ }
123
+ /** Only ever this much of the installer's output is kept (the tail), so a
124
+ * chatty npm cannot grow the bridge's memory or the relay frames. */
125
+ export const MAX_OUTPUT_BYTES = 64 * 1024;
126
+ export function appendTail(buffer, chunk, max = MAX_OUTPUT_BYTES) {
127
+ const next = buffer + chunk;
128
+ return next.length > max ? next.slice(next.length - max) : next;
129
+ }
130
+ /** The message the PTY path uses for the same verdict — kept identical so the
131
+ * dashboard copy does not depend on which path ran. */
132
+ function notRestartedOutcome(exitCode, output, refused) {
133
+ return {
134
+ ok: true,
135
+ status: 'completed',
136
+ exitCode,
137
+ output,
138
+ restartRequired: true,
139
+ message: 'Connector files updated, but the gateway was NOT restarted, so the previous version is still running. '
140
+ + 'If OpenClaw runs in Docker, restart the container from the host machine (docker restart <container>); '
141
+ + `otherwise restart OpenClaw. The new version loads then. (Self-restart refused: ${refused.message})`,
142
+ };
143
+ }
144
+ /**
145
+ * Run the installer directly and finish the job: files placed → ask the
146
+ * gateway to restart itself. Resolves with the final outcome; `emit` receives
147
+ * every intermediate one (started + progress), exactly like runConnectorUpdate.
148
+ *
149
+ * `rpc` is the operator.admin session the caller already opened (the restart
150
+ * RPC needs that scope). The position guard and the per-host opt-out have
151
+ * been applied by the caller.
152
+ */
153
+ export async function runDirectConnectorUpdate(rpc, version, emit, deps = {}) {
154
+ if (!supportsFilesOnly(version)) {
155
+ // Not a retryable condition on this box: the release endpoint pins an
156
+ // installer that would run the full install here. Refuse, say why.
157
+ const outcome = {
158
+ ok: false,
159
+ status: 'blocked',
160
+ message: `The pinned connector release (${version}) predates files-only updates (${FILES_ONLY_MIN_CONNECT_VERSION}), `
161
+ + `which this box needs, so the update was not started. ${manualUpdateHint(version)}.`,
162
+ };
163
+ logger.warn(TAG, outcome.message);
164
+ return outcome;
165
+ }
166
+ const spawn = deps.spawn ?? nodeSpawn;
167
+ const npx = deps.npx ?? resolveNpx();
168
+ const args = directUpdateArgs(version);
169
+ const timeoutMs = deps.timeoutMs ?? 10 * 60_000;
170
+ const throttleMs = deps.emitThrottleMs ?? 750;
171
+ const now = deps.now ?? Date.now;
172
+ const setTimer = deps.setTimer ?? setTimeout;
173
+ const clearTimer = deps.clearTimer ?? clearTimeout;
174
+ const baseEnv = deps.env ?? process.env;
175
+ const env = { ...baseEnv, PATH: childPath(process.execPath, baseEnv.PATH) };
176
+ const cwd = deps.cwd ?? homedir();
177
+ logger.info(TAG, `direct update: ${npx} ${args.join(' ')} (cwd=${cwd})`);
178
+ let child;
179
+ try {
180
+ child = spawn(npx, args, { cwd, env, stdio: ['ignore', 'pipe', 'pipe'], shell: false });
181
+ }
182
+ catch (err) {
183
+ const reason = err instanceof Error ? err.message : String(err);
184
+ const outcome = {
185
+ ok: false,
186
+ status: 'failed',
187
+ message: `Could not start the updater on the box (${reason}). ${manualUpdateHint(version)}.`,
188
+ };
189
+ logger.warn(TAG, outcome.message);
190
+ return outcome;
191
+ }
192
+ const started = {
193
+ ok: true,
194
+ status: 'started',
195
+ message: 'Update started on the box. The agent restarts when it finishes, so the dashboard will reconnect on its own.',
196
+ };
197
+ emit(started);
198
+ logger.info(TAG, `direct update started (pid ${child.pid ?? 'unknown'})`);
199
+ return new Promise((resolve) => {
200
+ let output = '';
201
+ // The first progress frame goes out at once; later ones are throttled.
202
+ let lastEmitAt = Number.NEGATIVE_INFINITY;
203
+ let pendingEmit = null;
204
+ let settled = false;
205
+ let timedOut = false;
206
+ const flushProgress = () => {
207
+ pendingEmit = null;
208
+ if (settled)
209
+ return;
210
+ lastEmitAt = now();
211
+ emit({ ok: true, status: 'started', output, message: 'Updating…' });
212
+ };
213
+ const onData = (chunk) => {
214
+ output = appendTail(output, chunk.toString());
215
+ if (settled)
216
+ return;
217
+ const due = lastEmitAt + throttleMs - now();
218
+ if (due <= 0)
219
+ flushProgress();
220
+ else if (!pendingEmit)
221
+ pendingEmit = setTimer(flushProgress, due);
222
+ };
223
+ child.stdout?.on('data', onData);
224
+ child.stderr?.on('data', onData);
225
+ const killTimer = setTimer(() => {
226
+ timedOut = true;
227
+ logger.warn(TAG, `direct update exceeded ${timeoutMs} ms — killing pid ${child.pid ?? 'unknown'}`);
228
+ try {
229
+ child.kill('SIGKILL');
230
+ }
231
+ catch {
232
+ /* already gone */
233
+ }
234
+ }, timeoutMs);
235
+ const settle = (outcome) => {
236
+ if (settled)
237
+ return;
238
+ settled = true;
239
+ clearTimer(killTimer);
240
+ if (pendingEmit)
241
+ clearTimer(pendingEmit);
242
+ emit(outcome);
243
+ resolve(outcome);
244
+ };
245
+ child.on('error', (err) => {
246
+ // ENOENT (no npx where we looked) arrives here, not from spawn().
247
+ settle({
248
+ ok: false,
249
+ status: 'failed',
250
+ output,
251
+ message: `Could not start the updater on the box (${err.message}). ${manualUpdateHint(version)}.`,
252
+ });
253
+ });
254
+ // 'exit' can precede the last stdout flush; the outcome is taken on 'close'.
255
+ child.on('close', (code, signal) => {
256
+ void (async () => {
257
+ if (timedOut) {
258
+ settle({
259
+ ok: false,
260
+ status: 'failed',
261
+ output,
262
+ message: 'The update did not finish in time and was stopped. Check the box directly before retrying.',
263
+ });
264
+ return;
265
+ }
266
+ if (code !== 0) {
267
+ settle({
268
+ ok: false,
269
+ status: 'completed',
270
+ exitCode: code,
271
+ output,
272
+ message: code === null
273
+ ? `The updater was interrupted${signal ? ` (${signal})` : ''}. The connector was left as it was.`
274
+ : `The updater exited with code ${code}. The connector was left as it was.`,
275
+ });
276
+ return;
277
+ }
278
+ if (!installerReportedNoRestart(output)) {
279
+ // A files-only run always ends on the marker. Its absence means the
280
+ // installer did something else (an unexpected build) — do not guess
281
+ // that the files are in place, and do not restart on top of it.
282
+ settle({
283
+ ok: false,
284
+ status: 'failed',
285
+ exitCode: code,
286
+ output,
287
+ message: `The updater finished without the "${INSTALLER_NOT_RESTARTED_MARKER}" verdict a files-only update ends on, `
288
+ + 'so it is not clear what it did. Check the plugin version on the dashboard in a few minutes; '
289
+ + `if it did not change, ${manualUpdateHint(version)}.`,
290
+ });
291
+ return;
292
+ }
293
+ // Files in place. Finish the job from here: the gateway restarts
294
+ // ITSELF (update.run — the reason that reloads code, see
295
+ // connector-update.ts RESTART_REASON_AFTER_UPDATE).
296
+ const kicked = await requestGatewayRestart(rpc, { reason: RESTART_REASON_AFTER_UPDATE });
297
+ if (kicked.status === 'restarting') {
298
+ settle({
299
+ ok: true,
300
+ status: 'restarting',
301
+ exitCode: code,
302
+ output,
303
+ message: `Connector files updated. ${kicked.message}`,
304
+ });
305
+ return;
306
+ }
307
+ settle(notRestartedOutcome(code, output, kicked));
308
+ })();
309
+ });
310
+ });
311
+ }
@@ -68,6 +68,12 @@ export interface ConnectorUpdateOutcome {
68
68
  * the gateway (its output carries INSTALLER_NOT_RESTARTED_MARKER) — the
69
69
  * previous version is still running until the operator restarts it. */
70
70
  restartRequired?: boolean;
71
+ /** A `blocked` verdict about the gateway's TERMINAL only (no terminal RPC,
72
+ * terminal disabled, sandboxed agent): the box itself can still be updated
73
+ * by the connector running the installer directly
74
+ * (connector-update-direct.ts). The provider falls through to that path;
75
+ * the verdict is not shown. */
76
+ directFallback?: true;
71
77
  }
72
78
  /**
73
79
  * Map a gateway error from `terminal.open` onto an operator-readable outcome.
@@ -152,6 +152,7 @@ export function describeOpenFailure(err) {
152
152
  return {
153
153
  ok: false,
154
154
  status: 'blocked',
155
+ directFallback: true,
155
156
  message: 'This box has the OpenClaw terminal disabled, so ReefClaw cannot run the update for you. '
156
157
  + `Instead, ${manualUpdateHint()}.`,
157
158
  };
@@ -160,6 +161,7 @@ export function describeOpenFailure(err) {
160
161
  return {
161
162
  ok: false,
162
163
  status: 'blocked',
164
+ directFallback: true,
163
165
  message: 'This agent runs in a sandbox, and OpenClaw does not support terminals inside one yet. '
164
166
  + `Instead, ${manualUpdateHint()}.`,
165
167
  };
@@ -181,11 +183,15 @@ export function describeOpenFailure(err) {
181
183
  // No terminal RPC at all: OpenClaw < 2026.7 has no `terminal.*` methods, so
182
184
  // the gateway answers `unknown method: terminal.open`. That is a fact about
183
185
  // 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).
186
+ // changes it (the rig on 2026.6.9 looped on exactly this, 2026-09-20). The
187
+ // connector does not need the terminal, though: `directFallback` sends the
188
+ // provider down connector-update-direct.ts, and this copy is only what an
189
+ // older provider would have shown.
185
190
  if (/unknown method/.test(lower)) {
186
191
  return {
187
192
  ok: false,
188
193
  status: 'blocked',
194
+ directFallback: true,
189
195
  message: 'This box runs an OpenClaw older than 2026.7, which has no terminal API, so ReefClaw cannot run the '
190
196
  + 'update for you. Upgrade OpenClaw to enable one-click updates; until then, paste the manual command '
191
197
  + `to your agent, or ${manualUpdateHint()}.`,
@@ -274,6 +274,11 @@ export declare class GatewayProvider implements OpenClawProvider {
274
274
  updateConnector(args: {
275
275
  acknowledgeOpenPositions?: boolean;
276
276
  }): Promise<ConnectorUpdateOutcome>;
277
+ /** The direct (no-PTY) update. Resolves the RPC with the `started` frame as
278
+ * soon as the installer is running (or the refusal), streams the rest as
279
+ * connector_update events, and tears the admin session down at the end —
280
+ * the same contract as the PTY path. */
281
+ private runDirectUpdate;
277
282
  /**
278
283
  * Operator-triggered gateway self-restart through OpenClaw's own
279
284
  * `gateway.restart.request` RPC. The one door on a Docker / unmanaged box:
@@ -20,6 +20,7 @@ import { assessDrawdownPlausibility, computeEquity as _computeEquity, computePos
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
22
  import { startConnectorUpdate, runConnectorUpdate, fetchPinnedConnectVersion, openAdminGatewaySession, checkPositionGuard, describeUpdateDisabled, requestGatewayRestart, RESTART_REASON_OPERATOR, } from './connector-update.js';
23
+ import { isInsideContainer, readContainerProbe, runDirectConnectorUpdate } from './connector-update-direct.js';
23
24
  import { DEFAULT_AGENT_ID, isForeignAgentEvent, resolveAgentEventOwner } from '../gateway/agent-scope.js';
24
25
  const TAG = 'gateway';
25
26
  // ---- Day-start NAV persistence ----
@@ -815,7 +816,22 @@ export class GatewayProvider {
815
816
  if (!session.ok)
816
817
  return session.outcome;
817
818
  const rpc = (method, params) => admin.sendRpc(method, params);
819
+ // Inside a container the PTY path is the wrong tool even where the
820
+ // terminal RPC exists: the full installer runs the `openclaw` CLI inside
821
+ // the live gateway (a second plugin stack) and cannot restart the
822
+ // container. The connector runs the files-only installer itself and has
823
+ // the gateway restart itself (connector-update-direct.ts).
824
+ if (isInsideContainer(readContainerProbe())) {
825
+ logger.info(TAG, 'connector.update: container detected — running the installer directly (files-only)');
826
+ return this.runDirectUpdate(rpc, pinned.version, admin);
827
+ }
818
828
  const started = await startConnectorUpdate(rpc, guardArgs, pinned.version);
829
+ if (started.status === 'blocked' && started.directFallback) {
830
+ // The gateway has no usable terminal (OpenClaw < 2026.7, terminal
831
+ // disabled, sandboxed agent). The connector does not need one.
832
+ logger.info(TAG, `connector.update: no gateway terminal (${started.message}) — running the installer directly`);
833
+ return this.runDirectUpdate(rpc, pinned.version, admin);
834
+ }
819
835
  if (started.status !== 'started' || !started.sessionId) {
820
836
  admin.destroy();
821
837
  return started;
@@ -828,6 +844,30 @@ export class GatewayProvider {
828
844
  });
829
845
  return started;
830
846
  }
847
+ /** The direct (no-PTY) update. Resolves the RPC with the `started` frame as
848
+ * soon as the installer is running (or the refusal), streams the rest as
849
+ * connector_update events, and tears the admin session down at the end —
850
+ * the same contract as the PTY path. */
851
+ runDirectUpdate(rpc, version, admin) {
852
+ return new Promise((resolve) => {
853
+ let answered = false;
854
+ const answer = (outcome) => {
855
+ if (answered)
856
+ return;
857
+ answered = true;
858
+ resolve(outcome);
859
+ };
860
+ void runDirectConnectorUpdate(rpc, version, (outcome) => {
861
+ // The first frame (`started`) is the RPC reply; every frame, including
862
+ // that one, also goes out as an event so the dashboard's pane fills.
863
+ this.emitConnectorUpdate(outcome);
864
+ if (outcome.status === 'started')
865
+ answer(outcome);
866
+ })
867
+ .then((final) => answer(final))
868
+ .finally(() => admin.destroy());
869
+ });
870
+ }
831
871
  /**
832
872
  * Operator-triggered gateway self-restart through OpenClaw's own
833
873
  * `gateway.restart.request` RPC. The one door on a Docker / unmanaged box:
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "id": "reefclaw-paper-trading",
3
3
  "name": "ReefClaw Trading",
4
- "version": "0.1.39",
4
+ "version": "0.1.40",
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.39",
3
+ "version": "0.1.40",
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",
@@ -10,5 +10,6 @@
10
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
11
  "0.1.37": "Updates now finish on Docker and other unmanaged gateways: the connector asks the gateway to restart itself through OpenClaw's own restart request, so a one-click update no longer ends with 'files installed, restart it from the host', and the dashboard offers 'Restart now' if that ever does happen. The installer no longer re-registers an already-registered plugin on an update, which is what used to start a second plugin process inside a container.",
12
12
  "0.1.38": "Fixes the restart that 0.1.37 introduced for Docker and other unmanaged gateways: the connector now asks for OpenClaw's update restart, the one kind that replaces the running process so the new files actually load (the previous kind restarted in place and kept the old code while reporting success). The installer no longer claims a self-restart it cannot verify; the connector or the dashboard's Restart now button performs it, waiting for an in-progress agent run to finish first.",
13
- "0.1.39": "wave9: a refusal by the plugin's own risk gate no longer burns the whole trading day (the authorization is released and a fresh one can be requested inside the window; a wrong-side stop still latches). wave9 evidence: the previous day's funding settlement stamped a few milliseconds late no longer makes the whole night's evidence read as incomplete. Model health: the model note OpenClaw 2026.9 writes at the start of every session no longer counts as a model switch, so the model dot can be green. Readiness: the plugin now reports whether its own files match the release (an install-location class, the process start time and fingerprints of three of its own files; never a path, never file contents; switch RC_READINESS_INTEGRITY=off), so a stale or modified install can be told apart from the release without touching the box."
13
+ "0.1.39": "wave9: a refusal by the plugin's own risk gate no longer burns the whole trading day (the authorization is released and a fresh one can be requested inside the window; a wrong-side stop still latches). wave9 evidence: the previous day's funding settlement stamped a few milliseconds late no longer makes the whole night's evidence read as incomplete. Model health: the model note OpenClaw 2026.9 writes at the start of every session no longer counts as a model switch, so the model dot can be green. Readiness: the plugin now reports whether its own files match the release (an install-location class, the process start time and fingerprints of three of its own files; never a path, never file contents; switch RC_READINESS_INTEGRITY=off), so a stale or modified install can be told apart from the release without touching the box.",
14
+ "0.1.40": "One-click updates now work on boxes without a gateway terminal (OpenClaw older than 2026.7, terminal disabled) and inside Docker: the connector runs the installer itself in a files-only mode that never touches the OpenClaw CLI or config, then asks the gateway to restart itself. The installer gains --files-only for the same purpose."
14
15
  }
@@ -101,7 +101,7 @@ When a user gives you this message (or just a bare `Here's my ReefClaw token: rc
101
101
  If the ReefClaw trading tools are not present yet, the **user** installs them by running this once, in a terminal on the machine running OpenClaw (inside the container, if OpenClaw runs in Docker):
102
102
 
103
103
  ```
104
- npx --yes @reefclaw/connect@0.1.52
104
+ npx --yes @reefclaw/connect@0.1.53
105
105
  ```
106
106
 
107
107
  That is the whole install. It places the plugin, sets up the connector, restarts the gateway where it can, and prints what it changed. If its closing lines say **GATEWAY NOT RESTARTED**, the plugin is on disk but not running yet: restarting is the user's step (in Docker, `docker restart <container>` from the host; otherwise restarting OpenClaw). Tell the user exactly that and stop — do not restart, signal or kill any process, do not run docker or service commands, and do not edit the gateway config, even if you could. The plugin reports its own version to ReefClaw after the restart; never post readiness, version or health reports yourself. The version is pinned on purpose: the line names the exact connector release this plugin was published with, so what runs on the machine is reviewable and never "whatever the registry serves today". It needs no ReefClaw token — the connection is the separate paste step above, and the connector picks it up on its own.