@reefclaw/openclaw-plugin 0.1.48 → 0.1.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +10 -6
  2. package/bridge/bridge.js +22 -16
  3. package/bridge/gateway/gateway-ws-client.d.ts +79 -1
  4. package/bridge/gateway/gateway-ws-client.js +99 -5
  5. package/bridge/gateway/heartbeat-cron.d.ts +64 -0
  6. package/bridge/gateway/heartbeat-cron.js +150 -1
  7. package/bridge/provider.d.ts +12 -0
  8. package/bridge/providers/connector-update-direct.d.ts +3 -0
  9. package/bridge/providers/connector-update-direct.js +11 -1
  10. package/bridge/providers/connector-update-openclaw.d.ts +268 -0
  11. package/bridge/providers/connector-update-openclaw.js +772 -0
  12. package/bridge/providers/connector-update.d.ts +115 -1
  13. package/bridge/providers/connector-update.js +228 -13
  14. package/bridge/providers/gateway.d.ts +52 -10
  15. package/bridge/providers/gateway.js +243 -34
  16. package/bridge/utils/skill-version.d.ts +6 -0
  17. package/bridge/utils/skill-version.js +10 -0
  18. package/config/first-start-venue.d.ts +147 -0
  19. package/config/first-start-venue.js +400 -0
  20. package/config/plugin-config-io.d.ts +9 -2
  21. package/config/plugin-config-io.js +29 -5
  22. package/connector-supervisor.d.ts +20 -0
  23. package/connector-supervisor.js +27 -1
  24. package/index.js +36 -1
  25. package/openclaw.plugin.json +333 -1
  26. package/package.json +1 -1
  27. package/release-integrity.json +10 -0
  28. package/release-notes.json +3 -1
  29. package/signals/stop-rules.d.ts +13 -0
  30. package/signals/stop-rules.js +35 -6
  31. package/signals/strategy-adapter.js +25 -6
  32. package/skills/reefclaw/SKILL.md +21 -8
  33. package/tools/assessment-validation.d.ts +10 -2
  34. package/tools/assessment-validation.js +19 -5
  35. package/tools/create-order.d.ts +4 -0
  36. package/tools/create-order.js +15 -0
  37. package/tools/intel-cache.d.ts +14 -0
  38. package/tools/intel-cache.js +59 -0
  39. package/tools/venue-quote-hint.d.ts +49 -0
  40. package/tools/venue-quote-hint.js +200 -0
@@ -93,6 +93,17 @@ export function hasConfiguredChannels(cfg) {
93
93
  * delivery `announce` can only fail at run time, so switch it to `none`.
94
94
  * Runs on every bridge start (cheap: one cron.list), independent of the
95
95
  * once-per-install marker, because the job predates this fix on every box.
96
+ *
97
+ * ★ `cron.update` needs operator.admin, which the long-lived session holds
98
+ * only when the process started with the heartbeat ensure owed, so on a box
99
+ * with a marker this patch is refused and nothing changes. That is
100
+ * DELIBERATE (2026-09-29 review): the "no channel" signal
101
+ * (hasConfiguredChannels) reads only the top-level openclaw.json and
102
+ * misreads an env-only Telegram token, `$include`d channels and a moved
103
+ * config dir as "none". Widening the repair (an admin side-session was
104
+ * tried) would silently switch off heartbeat summaries that work today. A
105
+ * wider repair must key off the job's own recorded delivery failure, never
106
+ * this guess.
96
107
  */
97
108
  export async function reconcileHeartbeatDelivery(opts) {
98
109
  if (opts.channelsConfigured !== false)
@@ -180,6 +191,18 @@ function markerAdoptedForeignJob(markerPath) {
180
191
  return false;
181
192
  }
182
193
  }
194
+ /**
195
+ * Is the once-per-install ensure still owed on this box? True with no marker,
196
+ * and with a marker from the old rule that adopted a job that is not
197
+ * ReefClaw's (re-checked once). ensureHeartbeatCron runs exactly when this is
198
+ * true, and the bridge requests operator.admin exactly when this is true:
199
+ * both read this one function so they cannot drift. (They did: the re-check
200
+ * ran on a read/write-only session, so its cron.add failed on the scope and
201
+ * the adopted box kept getting no ReefClaw beat.)
202
+ */
203
+ export function heartbeatEnsureOwed(markerPath) {
204
+ return !existsSync(markerPath) || markerAdoptedForeignJob(markerPath);
205
+ }
183
206
  /**
184
207
  * Ensure a heartbeat cron exists. Non-fatal by contract: every failure path
185
208
  * returns 'failed' rather than throwing, and only success writes the marker so
@@ -209,7 +232,7 @@ export async function ensureHeartbeatCron(opts) {
209
232
  const agentId = opts.agentId?.trim().toLowerCase() || undefined;
210
233
  const agentIsDefault = opts.agentIsDefault ?? true;
211
234
  try {
212
- if (existsSync(markerPath) && !markerAdoptedForeignJob(markerPath))
235
+ if (!heartbeatEnsureOwed(markerPath))
213
236
  return 'already_ensured';
214
237
  // includeDisabled: a job the user disabled still means "exists" — re-adding
215
238
  // a duplicate next to a deliberately-disabled one is worse than doing nothing.
@@ -275,6 +298,21 @@ export async function ensureHeartbeatCron(opts) {
275
298
  `A heartbeat without it would run on the default agent, not '${agentId}'. Upgrade OpenClaw, or create the job yourself with the agent set.`);
276
299
  return 'failed';
277
300
  }
301
+ // The failed call may still have created the job (a timeout, a dropped
302
+ // socket). Look again before the retry so it can never add a second job
303
+ // beside it. No usable list = no retry: the next connect lists again and
304
+ // either finds the job or creates it.
305
+ const relist = (await rpc.sendRpc('cron.list', { includeDisabled: true }));
306
+ if (!Array.isArray(relist?.jobs)) {
307
+ log('Heartbeat cron: skipped (the add failed and cron.list returned no job list to check it against)');
308
+ return 'failed';
309
+ }
310
+ const landed = relist.jobs.find((j) => isReefclawHeartbeatJob(j) && cronJobBelongsToAgent(j, agentId, agentIsDefault));
311
+ if (landed) {
312
+ writeMarker(markerPath, { ensuredAt: new Date().toISOString(), created: HEARTBEAT_CRON_NAME, delivery: 'announce' });
313
+ log(`Heartbeat cron: created (${String(landed.name)}; the add reported an error but the job exists)`);
314
+ return 'created';
315
+ }
278
316
  log(`Heartbeat cron: announce delivery rejected (${addErr instanceof Error ? addErr.message.split('\n')[0] : String(addErr)}) — retrying without delivery`);
279
317
  try {
280
318
  await rpc.sendRpc('cron.add', { ...baseJob, delivery: { mode: 'none' } });
@@ -301,3 +339,114 @@ function writeMarker(markerPath, data) {
301
339
  mkdirSync(dirname(markerPath), { recursive: true });
302
340
  writeFileSync(markerPath, JSON.stringify(data, null, 2) + '\n', 'utf-8');
303
341
  }
342
+ /** How long a fresh install waits for the full trading instructions before
343
+ * starting its first market check. Past this, the first check is left to the
344
+ * regular schedule (one interval later), exactly as before. */
345
+ export const FIRST_BEAT_MAX_WAIT_MS = 120_000;
346
+ const FIRST_BEAT_POLL_MS = 5_000;
347
+ /**
348
+ * Start the FIRST market check right away on a fresh install instead of one
349
+ * full interval (15 min) after connecting.
350
+ *
351
+ * Why (2026-09-29): a new user connected, saw "You're connected", and then
352
+ * nothing happened for 15 minutes — the job's first run is scheduled one
353
+ * interval after creation. Call this ONLY when ensureHeartbeatCron returned
354
+ * 'created' (a brand-new job, once per install): it must never add beats to
355
+ * an existing agent.
356
+ *
357
+ * Rules:
358
+ * • Waits (≤ FIRST_BEAT_MAX_WAIT_MS) until the full trading SKILL.md is what
359
+ * the agent reads. A beat on the bootstrap instructions would be a wasted
360
+ * run; if they never arrive, the first check stays on the schedule (old
361
+ * behaviour).
362
+ * • `cron.run` needs operator.admin, which the bridge's session holds only
363
+ * when the process started with the ensure owed; call this with the client
364
+ * that created the job.
365
+ * • ONE cron.run call, never retried: a timeout or a dropped socket may
366
+ * still have started the run, and a second call would start a second beat.
367
+ * • Never throws; every failure leaves the regular schedule untouched.
368
+ */
369
+ export async function runFirstHeartbeat(opts) {
370
+ const maxWaitMs = opts.maxWaitMs ?? FIRST_BEAT_MAX_WAIT_MS;
371
+ const pollMs = Math.max(1, opts.pollMs ?? FIRST_BEAT_POLL_MS);
372
+ const sleep = opts.sleep ??
373
+ ((ms) => new Promise((resolve) => {
374
+ const t = setTimeout(resolve, ms);
375
+ t.unref?.();
376
+ }));
377
+ const ready = () => {
378
+ try {
379
+ return opts.instructionsReady();
380
+ }
381
+ catch {
382
+ return false;
383
+ }
384
+ };
385
+ const active = () => {
386
+ if (!opts.isActive)
387
+ return true;
388
+ try {
389
+ return opts.isActive();
390
+ }
391
+ catch {
392
+ return false;
393
+ }
394
+ };
395
+ const inactive = () => {
396
+ opts.log('Heartbeat cron: first market check not started (the gateway connection it was started on is gone) — it runs on the regular schedule');
397
+ return 'inactive';
398
+ };
399
+ const agentId = opts.agentId?.trim().toLowerCase() || undefined;
400
+ const agentIsDefault = opts.agentIsDefault ?? true;
401
+ try {
402
+ let waited = 0;
403
+ while (!ready() && waited < maxWaitMs) {
404
+ if (!active())
405
+ return inactive();
406
+ await sleep(pollMs);
407
+ waited += pollMs;
408
+ }
409
+ if (!ready()) {
410
+ opts.log('Heartbeat cron: first market check left to the regular schedule (the full trading instructions have not arrived yet)');
411
+ return 'not_ready';
412
+ }
413
+ if (!active())
414
+ return inactive();
415
+ const listResp = (await opts.rpc.sendRpc('cron.list', { includeDisabled: true }));
416
+ const jobs = Array.isArray(listResp?.jobs) ? listResp.jobs : [];
417
+ const job = jobs.find((j) => j?.name === HEARTBEAT_CRON_NAME && cronJobBelongsToAgent(j, agentId, agentIsDefault));
418
+ if (!job || typeof job.id !== 'string' || job.enabled === false) {
419
+ opts.log('Heartbeat cron: first market check not started (the new job is missing or disabled)');
420
+ return 'not_found';
421
+ }
422
+ if (!active())
423
+ return inactive();
424
+ let runResp;
425
+ try {
426
+ runResp = (await opts.rpc.sendRpc('cron.run', { id: job.id }));
427
+ }
428
+ catch (err) {
429
+ // Sent, but no answer we can trust: a timeout or a dropped socket may
430
+ // still have started the run. Report it as unknown (never retried).
431
+ opts.log(`Heartbeat cron: could not confirm the first market check started (${err instanceof Error ? err.message.split('\n')[0] : String(err)}) — if it did not, it runs on the regular schedule`);
432
+ return 'unknown';
433
+ }
434
+ // OpenClaw answers a run it did not start with ran:false + a reason
435
+ // instead of an error ('already-running' = a run is under way anyway).
436
+ if (runResp && typeof runResp === 'object' && (runResp.ran === false || runResp.ok === false)) {
437
+ const reason = typeof runResp.reason === 'string' && runResp.reason ? runResp.reason : 'no reason given';
438
+ if (reason === 'already-running') {
439
+ opts.log('Heartbeat cron: first market check already running');
440
+ return 'started';
441
+ }
442
+ opts.log(`Heartbeat cron: first market check not started now (${reason}) — it runs on the regular schedule`);
443
+ return 'not_run';
444
+ }
445
+ opts.log('Heartbeat cron: first market check started now (the next ones follow on the regular schedule)');
446
+ return 'started';
447
+ }
448
+ catch (err) {
449
+ opts.log(`Heartbeat cron: could not start the first market check now (${err instanceof Error ? err.message.split('\n')[0] : String(err)}) — it runs on the regular schedule`);
450
+ return 'failed';
451
+ }
452
+ }
@@ -152,6 +152,18 @@ export interface OpenClawProvider {
152
152
  received: boolean;
153
153
  error?: string;
154
154
  }>;
155
+ /**
156
+ * Hold the bridge's "instructions updated" chat notice while this install's
157
+ * FIRST market check is pending (the heartbeat job was just created and the
158
+ * early run has not started or given up yet): that check reads the new
159
+ * instructions itself, and the notice would be a second agent turn at the
160
+ * same moment. Returns true when the notice was taken (the provider calls
161
+ * `send` if the first check ends without starting, on the next connect if
162
+ * the socket is down at that moment; the latest call wins), false when
163
+ * nothing is pending and the caller should send it now. Absent = never
164
+ * pending.
165
+ */
166
+ deferToFirstMarketCheck?(send: () => void): boolean;
155
167
  /** Close a specific position by symbol (non-emergency, single-symbol close) */
156
168
  closePosition(symbol: string): Promise<{
157
169
  closed: boolean;
@@ -66,6 +66,9 @@ export interface DirectRunDeps {
66
66
  now?: () => number;
67
67
  setTimer?: typeof setTimeout;
68
68
  clearTimer?: typeof clearTimeout;
69
+ /** Exact plugin release, for the manual line of an "installed elsewhere"
70
+ * verdict only. Never reaches the argv. */
71
+ pluginVersion?: string | null;
69
72
  }
70
73
  /**
71
74
  * Run the installer directly and finish the job: files placed → ask the
@@ -36,7 +36,7 @@ import { existsSync, readFileSync } from 'node:fs';
36
36
  import { homedir } from 'node:os';
37
37
  import { posix, win32 } from 'node:path';
38
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';
39
+ import { ALREADY_INSTALLED_MARKER, CONNECT_PACKAGE, INSTALLER_NOT_RESTARTED_MARKER, RESTART_REASON_AFTER_UPDATE, describeInstalledElsewhere, installerReportedAlreadyInstalled, installerReportedNoRestart, isExactConnectVersion, manualUpdateHint, requestGatewayRestart, } from './connector-update.js';
40
40
  const TAG = 'connector-update';
41
41
  /** The installer flag that selects the files-only mode (installer/src/files-only.ts). */
42
42
  export const FILES_ONLY_FLAG = '--files-only';
@@ -254,6 +254,16 @@ export async function runDirectConnectorUpdate(rpc, version, emit, deps = {}) {
254
254
  // 'exit' can precede the last stdout flush; the outcome is taken on 'close'.
255
255
  child.on('close', (code, signal) => {
256
256
  void (async () => {
257
+ // ★ The installer's "this copy is not mine" refusal FIRST, before any
258
+ // exit-code mapping: files-only exits 1 on it, which read as "The
259
+ // updater exited with code 1" — a fault to retry, when the truth is
260
+ // that OpenClaw installed this copy and nothing here will ever update
261
+ // it. Nothing was laid, so nothing is restarted onto it.
262
+ if (installerReportedAlreadyInstalled(output)) {
263
+ logger.info(TAG, `direct update: installer refused — ${ALREADY_INSTALLED_MARKER} (exit ${code ?? 'null'}); no restart`);
264
+ settle(describeInstalledElsewhere({ exitCode: code, output, pluginVersion: deps.pluginVersion }));
265
+ return;
266
+ }
257
267
  if (timedOut) {
258
268
  settle({
259
269
  ok: false,
@@ -0,0 +1,268 @@
1
+ import type { GatewayHelloInfo } from '../gateway/gateway-ws-client.js';
2
+ import { type ConnectorUpdateOutcome } from './connector-update.js';
3
+ /** The only package this path installs. */
4
+ export declare const PACKAGE = "@reefclaw/openclaw-plugin";
5
+ /** The only plugin id this path updates (sent as `expectedPluginId`). */
6
+ export declare const PLUGIN_ID = "reefclaw-paper-trading";
7
+ /** The only install source this path uses or updates. */
8
+ export declare const SOURCE = "clawhub";
9
+ /** First OpenClaw whose `plugins.install` takes `mode: 'update'`. */
10
+ export declare const MIN_OPENCLAW_FOR_PLUGIN_UPDATE = "2026.9.5";
11
+ /** OpenClaw's own CLI allows plugins.install this long. */
12
+ export declare const INSTALL_TIMEOUT_MS = 600000;
13
+ /** Retries after an explicitly transient refusal — never after a transport loss. */
14
+ export declare const MAX_INSTALL_RETRIES = 3;
15
+ /** Cap on any single wait between retries, whatever retryAfterMs asks. */
16
+ export declare const RETRY_WAIT_CAP_MS = 10000;
17
+ export declare const CAPABILITY_CONSENT_CODE = "PLUGIN_CAPABILITY_CONSENT_REQUIRED";
18
+ export declare const INSTALL_POLICY_CODE = "install_policy_warning_acknowledgement_required";
19
+ export interface OpenClawInstallRequest {
20
+ source: typeof SOURCE;
21
+ packageName: typeof PACKAGE;
22
+ version: string;
23
+ mode: 'update';
24
+ expectedPluginId: typeof PLUGIN_ID;
25
+ [key: string]: unknown;
26
+ }
27
+ /**
28
+ * The ONE request this path can ever send. The only variable is an exact
29
+ * release, validated here; anything else throws. Exactly these keys — never
30
+ * `enable` (9.7 only; 9.5/9.6 reject it), never an acknowledgement flag.
31
+ */
32
+ export declare function buildOpenClawInstallRequest(version: string): OpenClawInstallRequest;
33
+ export interface GatewayRpcOptions {
34
+ timeoutMs?: number;
35
+ onEvent?: (event: string, payload: unknown) => void;
36
+ }
37
+ /** The admin session's sendRpc (injected — keeps this module unit-testable). */
38
+ export type GatewayRpc = (method: string, params: Record<string, unknown>, opts?: GatewayRpcOptions) => Promise<unknown>;
39
+ /**
40
+ * Env var through which the supervising plugin hands the connector it spawns
41
+ * the release the GATEWAY PROCESS LOADED (processRuntime().release, stamped at
42
+ * register time) — the only first-hand answer to "is the pinned release
43
+ * running?". Non-secret. The supervisor's launch()
44
+ * (plugin/src/connector-supervisor.ts) is where it gets set; absent (a plugin
45
+ * that does not pass it yet, a connector run some other way) → the release is
46
+ * not confirmed, and a box whose disk already holds the pinned release is
47
+ * restarted rather than reported up to date — never a false "nothing to
48
+ * update" while the old code runs.
49
+ */
50
+ export declare const RUNNING_RELEASE_ENV = "REEFCLAW_PLUGIN_RUNNING_RELEASE";
51
+ /** The release the supervising plugin says the gateway loaded, or null. */
52
+ export declare function resolveLoadedPluginRelease(env?: NodeJS.ProcessEnv): string | null;
53
+ /**
54
+ * The plugin release whose files this connector was STARTED from. The ClawHub
55
+ * package ships the connector at <pluginRoot>/bridge/index.js with the stamped
56
+ * release manifest one directory up (plugin-package/scripts/assemble.mjs), and
57
+ * the plugin's supervisor spawns it from there — so the manifest beside the
58
+ * bridge's parent names the files it started from. Any other layout (the
59
+ * connect installer's ~/.reefclaw/bridge, a source tree, the repo's unstamped
60
+ * 0.1.0) → null = unknown, never a guess.
61
+ *
62
+ * Evidence, not proof, of what the gateway runs: the supervisor respawns an
63
+ * exited connector from the SAME directory, so where OpenClaw replaced the
64
+ * files in place after an install whose restart never happened, a respawned
65
+ * connector reads the NEW manifest here while the gateway still runs the old
66
+ * plugin. It can therefore show that an OLDER release is running (R < X → a
67
+ * restart), or a newer one (R > X → never restarted onto an older copy), but
68
+ * never that the pinned one is — that takes resolveLoadedPluginRelease.
69
+ */
70
+ export declare function resolveRunningPluginRelease(entryPath?: string | undefined, readText?: (path: string) => string): string | null;
71
+ export interface RunningPluginRelease {
72
+ /** Exact release, or null = unknown. */
73
+ version: string | null;
74
+ /** True only when `version` came from the plugin process (RUNNING_RELEASE_ENV)
75
+ * — the one source that may report the pinned release as RUNNING. */
76
+ loadedByGateway: boolean;
77
+ }
78
+ export declare function getRunningPluginRelease(): RunningPluginRelease;
79
+ /** plugins.inspect could not be used (unknown method, scope, transport, …). */
80
+ export declare const INSPECT_UNAVAILABLE: "unavailable";
81
+ export interface InstalledPluginView {
82
+ pluginId: string | null;
83
+ /** `plugin.version` — the version ON DISK, not necessarily the running one. */
84
+ diskVersion: string | null;
85
+ /** `source.kind`: 'clawhub' | 'npm' | 'path' | … ; null when no record. */
86
+ sourceKind: string | null;
87
+ /** `source.packageName`, else parsed from `source.spec` (`clawhub:<pkg>@<v>`). */
88
+ packageName: string | null;
89
+ /** The exact release the install RECORD pins (`source.version`, else the
90
+ * `@<v>` of `source.spec`); null when it pins none (or not exactly). The
91
+ * live update re-pinned it to the new release (L3), so it is what
92
+ * corroborates "the install finished", beyond files on disk. */
93
+ recordVersion: string | null;
94
+ }
95
+ /** `clawhub:@reefclaw/openclaw-plugin@0.1.49` → `@reefclaw/openclaw-plugin`. */
96
+ export declare function packageFromSpec(spec: unknown): string | null;
97
+ /** `clawhub:@reefclaw/openclaw-plugin@0.1.49` → `0.1.49`; an unpinned spec, a
98
+ * tag or a range → null. */
99
+ export declare function versionFromSpec(spec: unknown): string | null;
100
+ /** Defensive read of a plugins.inspect reply (L6 keys: ok, plugin{id,version,…},
101
+ * source{kind,spec,packageName,…}, …). Null when it is not a usable answer. */
102
+ export declare function readInspectResult(result: unknown): InstalledPluginView | null;
103
+ export type InstallConfirmation = {
104
+ confirmed: true;
105
+ } | {
106
+ confirmed: false;
107
+ why: string;
108
+ };
109
+ /**
110
+ * Pure: may a restart be put onto what plugins.inspect shows now? Only when
111
+ * the pinned release X is on disk AND the install record agrees it is
112
+ * ReefClaw's ClawHub package pinned to X. Files reach the disk before an
113
+ * install's dependency / runtime stages are done, and a restart replaces the
114
+ * process — killing an install still in flight and booting a half-installed
115
+ * copy — so the record is the corroboration. A record that pins no exact
116
+ * release is accepted only when the install call itself answered ok (our
117
+ * operation demonstrably ended); after a refusal or a lost reply it is not.
118
+ */
119
+ export declare function confirmInstalledAt(view: InstalledPluginView | null, X: string, opts: {
120
+ installReplied: boolean;
121
+ }): InstallConfirmation;
122
+ /** Ask OpenClaw how this plugin was installed. Any failure → INSPECT_UNAVAILABLE
123
+ * (the installer path, today's behaviour, decides). Never throws. */
124
+ export declare function inspectInstalledPlugin(rpc: (method: string, params: Record<string, unknown>) => Promise<unknown>): Promise<unknown>;
125
+ export type ConnectorUpdatePlan = {
126
+ path: 'openclaw';
127
+ reason: string;
128
+ installed: InstalledPluginView;
129
+ } | {
130
+ path: 'installer';
131
+ reason: string;
132
+ } | {
133
+ path: 'blocked';
134
+ reason: string;
135
+ outcome: ConnectorUpdateOutcome;
136
+ };
137
+ /**
138
+ * Pure: which update path a box takes, from its plugins.inspect answer (or
139
+ * INSPECT_UNAVAILABLE).
140
+ * - 'openclaw' — a ClawHub install of exactly our package: this module.
141
+ * - 'blocked' — only on a POSITIVE finding that nothing here may update
142
+ * the copy: an npm install (it updates through OpenClaw and
143
+ * stays on npm — the owner gets the npm: line), or a
144
+ * ClawHub install of a package that is not ours.
145
+ * - 'installer' — everything else: no usable answer (older OpenClaw,
146
+ * unknown method, error), no install source, a `path`
147
+ * install (the connect installer's linked copy) and ANY
148
+ * other or unrecognised source kind. Today's PTY / direct
149
+ * path, unchanged. This is the safe direction: which kind
150
+ * OpenClaw reports for the installer's own `--link` copy is
151
+ * not pinned by a live capture, and a wrong guess must not
152
+ * strand that box or send its owner to lay a second ClawHub
153
+ * copy beside a load-path one (the duplicate-install / 4011
154
+ * case). The installer's own duplicate guard is the
155
+ * authority on "is this copy mine": it refuses a foreign
156
+ * copy with ALREADY_INSTALLED_MARKER, which ends `blocked`
157
+ * with no restart (describeInstalledElsewhere).
158
+ */
159
+ export declare function planConnectorUpdate(inspect: unknown, opts?: {
160
+ pluginVersion?: string | null;
161
+ }): ConnectorUpdatePlan;
162
+ /** OpenClaw's calendar version (YYYY.M.D, optionally followed by a suffix
163
+ * such as `-2` or `-beta.1`) → numbers; null when it is not one. The suffix
164
+ * is ignored: OpenClaw ships post-release builds as `2026.7.1-2`. */
165
+ export declare function parseOpenClawVersion(v: unknown): [number, number, number] | null;
166
+ export type PluginUpdateCapability = {
167
+ ok: true;
168
+ } | {
169
+ ok: false;
170
+ reported: string | null;
171
+ why: string;
172
+ };
173
+ /** Can this gateway take `plugins.install` with `mode: 'update'`? From the
174
+ * admin session's hello-ok: `server.version` ≥ 2026.9.5 (unknown or
175
+ * unreadable → no), and — when the gateway lists its methods — both
176
+ * plugins.install and plugins.inspect among them. */
177
+ export declare function checkPluginUpdateCapability(hello: GatewayHelloInfo | null | undefined): PluginUpdateCapability;
178
+ export interface GatewayErrorView {
179
+ code: string | null;
180
+ message: string;
181
+ details: Record<string, unknown>;
182
+ retryable: boolean;
183
+ retryAfterMs: number | null;
184
+ }
185
+ /** The structured fields of a GatewayRpcError (gateway-ws-client.ts), read by
186
+ * shape so this module needs no runtime import of the client. Null = not a
187
+ * gateway answer at all: a TRANSPORT failure (timeout, closed, not connected). */
188
+ export declare function readGatewayError(err: unknown): GatewayErrorView | null;
189
+ /** The surface a capability-consent error says widened (`details.widened`),
190
+ * rendered short: `tools: a, b (+3 more)`. Shape-tolerant. */
191
+ export declare function describeWidenedSurface(widened: unknown): string;
192
+ /** INVALID_REQUEST about `mode` / extra properties: a gateway older than
193
+ * 2026.9.5 slipped past the hello-ok gate (closed params schema). */
194
+ export declare function isModeRejection(error: GatewayErrorView): boolean;
195
+ export type InstallAttempt = {
196
+ ok: true;
197
+ payload: unknown;
198
+ } | {
199
+ ok: false;
200
+ error: unknown;
201
+ };
202
+ export type InstallFailureVerdict = {
203
+ kind: 'retry';
204
+ waitMs: number;
205
+ why: string;
206
+ } | {
207
+ kind: 'final';
208
+ outcome: ConnectorUpdateOutcome;
209
+ };
210
+ /**
211
+ * Pure: what a failed install attempt means. Consulted twice by the run:
212
+ * - BEFORE the re-inspect, only for its `retry` verdict — a refusal before
213
+ * anything ran (the canary's "same request again" class). The disk says
214
+ * nothing about our request then, so it is resent and never read as ours.
215
+ * - AFTER a re-inspect that does NOT confirm the pinned release (confirmed
216
+ * on disk and in the record it is a success, whatever the reply said).
217
+ * Mirrors the canary's ladder (scripts/canary-plugins-install.mjs decide) with
218
+ * the operator's-box differences: no acknowledgement is ever given, and a
219
+ * transport loss is never resent.
220
+ */
221
+ export declare function classifyInstallFailure(attempt: InstallAttempt, ctx: {
222
+ diskVersion: string | null;
223
+ pinned: string;
224
+ retryWaitCapMs?: number;
225
+ }): InstallFailureVerdict;
226
+ export interface OpenClawUpdateContext {
227
+ /** The plugins.inspect answer the route was decided on. */
228
+ inspect: unknown;
229
+ /** Exact plugin release from /api/release (fetchPinnedRelease) — nowhere else. */
230
+ pinnedPluginVersion: string | null | undefined;
231
+ /** The admin session's hello-ok self-description. */
232
+ hello: GatewayHelloInfo | null | undefined;
233
+ /** The release this process runs (getRunningPluginRelease().version); null = unknown. */
234
+ runningRelease: string | null | undefined;
235
+ /** getRunningPluginRelease().loadedByGateway: `runningRelease` came from the
236
+ * plugin process itself. Only then can the pinned release be reported as
237
+ * running ("nothing to update"); otherwise D == X restarts. */
238
+ runningReleaseLoadedByGateway?: boolean;
239
+ }
240
+ export interface OpenClawUpdateDeps {
241
+ /** Injected for tests. */
242
+ sleep?: (ms: number) => Promise<void>;
243
+ maxRetries?: number;
244
+ retryWaitCapMs?: number;
245
+ installTimeoutMs?: number;
246
+ }
247
+ /**
248
+ * Update a ClawHub-installed copy of the plugin to the pinned release and
249
+ * restart the gateway onto it. `emit` receives the intermediate frames
250
+ * (`started` + progress) and the final one; refusals decided before anything
251
+ * ran are returned, not emitted (as in the direct path). The caller has
252
+ * applied the per-host opt-out, the position guard and the one-update-at-a-
253
+ * time lock, holds the operator.admin session `rpc` runs on, and tears it down
254
+ * after this returns. Never throws.
255
+ *
256
+ * With X = pinned release, D = on disk (plugins.inspect), R = running:
257
+ * D > X → blocked: never a downgrade.
258
+ * R > X → blocked: never restarted onto an older copy.
259
+ * D == X, R == X from the
260
+ * plugin process itself → completed: already up to date, no restart.
261
+ * D == X otherwise → restart only (recovers "installed, not
262
+ * restarted"), once the install record agrees.
263
+ * D < X → capability gate → install → (a refusal before
264
+ * anything ran is retried, never taken for
265
+ * success) → RE-INSPECT → restart iff disk AND
266
+ * record show X, whatever the install replied.
267
+ */
268
+ export declare function runOpenClawPluginUpdate(rpc: GatewayRpc, ctx: OpenClawUpdateContext, emit: (outcome: ConnectorUpdateOutcome) => void, deps?: OpenClawUpdateDeps): Promise<ConnectorUpdateOutcome>;