@reefclaw/openclaw-plugin 0.1.33 → 0.1.35
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 +65 -0
- package/bridge/config.d.ts +8 -9
- package/bridge/config.js +39 -74
- package/bridge/gateway/heartbeat-cron.js +1 -1
- package/bridge/gateway/poller.d.ts +9 -1
- package/bridge/gateway/poller.js +11 -1
- package/bridge/heartbeat-runs.d.ts +20 -2
- package/bridge/heartbeat-runs.js +62 -8
- package/bridge/heartbeat-transcript.d.ts +58 -1
- package/bridge/heartbeat-transcript.js +187 -18
- package/bridge/index.js +6 -1
- package/bridge/providers/connector-update.d.ts +40 -9
- package/bridge/providers/connector-update.js +91 -26
- package/bridge/providers/gateway.d.ts +13 -15
- package/bridge/providers/gateway.js +72 -57
- package/bridge/providers/onboarding-commands.js +3 -3
- package/bridge/providers/risk-calculator.d.ts +31 -0
- package/bridge/providers/risk-calculator.js +41 -1
- package/config/brackets-config.js +1 -1
- package/config/plugin-config-io.d.ts +1 -1
- package/config/user-data-stream-config.js +1 -1
- package/connector-supervisor.d.ts +2 -2
- package/connector-supervisor.js +3 -3
- package/index.js +5 -5
- package/live/proposal-decision-listener.d.ts +1 -1
- package/openclaw.plugin.json +2 -2
- package/package.json +2 -2
- package/plugin-version.d.ts +1 -1
- package/plugin-version.js +3 -3
- package/release-notes.json +3 -1
- package/skills/reefclaw/SKILL.md +5 -4
- package/tools/cancel-all-orders.js +1 -1
- package/tools/create-order.js +1 -1
|
@@ -32,13 +32,26 @@
|
|
|
32
32
|
// marker (or a `:cron:` trajectory sessionKey) is how a heartbeat session
|
|
33
33
|
// is told apart from the main chat session in the same directory.
|
|
34
34
|
//
|
|
35
|
+
// ★ OpenClaw >= 2026.9 keeps transcripts in SQLite, not JSONL (verified against
|
|
36
|
+
// the openclaw@2026.9.4 npm tarball, 2026-09-17, after Ardi's report #5):
|
|
37
|
+
// ~/.openclaw/agents/<id>/agent/openclaw-agent.sqlite
|
|
38
|
+
// session_windows(session_id PK, session_key, transcript_updated_at, …)
|
|
39
|
+
// transcript_events(session_id, seq, event_json, created_at) — one event
|
|
40
|
+
// per row, event_json = JSON.stringify(event) = one former JSONL line
|
|
41
|
+
// trajectory_runtime_events(session_id, seq, run_id, event_json, …)
|
|
42
|
+
// Live *.jsonl are no longer written (deleted sessions keep a
|
|
43
|
+
// `.jsonl.deleted.<ts>` archive), so a JSONL-only reader finds nothing and
|
|
44
|
+
// the recorder goes silent. Both stores are read here; the rows feed the
|
|
45
|
+
// SAME parsers as the files.
|
|
46
|
+
//
|
|
35
47
|
// ★ THIS MODULE MUST NEVER IMPORT NETWORK CODE (no fetch, no ws, no relay, no
|
|
36
48
|
// provider). ClawHub's static analyzer flags a sensitive-looking file read
|
|
37
49
|
// paired with a network send IN THE SAME FILE as potential exfiltration (see
|
|
38
50
|
// utils/skills-snapshot-invalidation.ts). The POST lives in heartbeat-runs.ts.
|
|
39
51
|
import { existsSync, readdirSync, readFileSync, statSync, openSync, readSync, closeSync } from 'node:fs';
|
|
40
|
-
import { join } from 'node:path';
|
|
52
|
+
import { dirname, join } from 'node:path';
|
|
41
53
|
import { homedir } from 'node:os';
|
|
54
|
+
import { createRequire } from 'node:module';
|
|
42
55
|
import { redactTokens } from '@reefclaw/shared';
|
|
43
56
|
// ---- Size caps (keep a record well under the relay/webapp body limits) -----
|
|
44
57
|
/** Max tool calls kept per record (the census still counts every call). */
|
|
@@ -67,7 +80,126 @@ export function resolveOpenClawStateDir(env = process.env) {
|
|
|
67
80
|
export function resolveSessionsDir(agentId = 'main', env = process.env) {
|
|
68
81
|
return join(resolveOpenClawStateDir(env), 'agents', agentId, 'sessions');
|
|
69
82
|
}
|
|
83
|
+
export const AGENT_DB_BASENAME = 'openclaw-agent.sqlite';
|
|
84
|
+
/** The agent database beside a `<state>/agents/<id>/sessions` dir
|
|
85
|
+
* (OpenClaw's `resolveOpenClawAgentSqlitePath`: `agents/<id>/agent/openclaw-agent.sqlite`). */
|
|
86
|
+
export function resolveAgentDbPath(sessionsDir) {
|
|
87
|
+
return join(dirname(sessionsDir), 'agent', AGENT_DB_BASENAME);
|
|
88
|
+
}
|
|
89
|
+
let sqliteModule;
|
|
90
|
+
let sqliteLoader = () => {
|
|
91
|
+
try {
|
|
92
|
+
// A builtin since Node 22.13 (unflagged); the OpenClaw >= 2026.9.3 floor is
|
|
93
|
+
// Node 24. require() keeps this module synchronous and lets an older Node
|
|
94
|
+
// simply report the store as unsupported instead of failing at import.
|
|
95
|
+
return createRequire(import.meta.url)('node:sqlite');
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
/** `node:sqlite`, or null when this Node has none. Cached. */
|
|
102
|
+
export function loadSqlite() {
|
|
103
|
+
if (sqliteModule === undefined)
|
|
104
|
+
sqliteModule = sqliteLoader();
|
|
105
|
+
return sqliteModule;
|
|
106
|
+
}
|
|
107
|
+
/** Test seam: swap the loader (pass null to simulate a Node without node:sqlite). */
|
|
108
|
+
export function setSqliteLoaderForTests(loader) {
|
|
109
|
+
sqliteLoader = loader ?? (() => createRequire(import.meta.url)('node:sqlite'));
|
|
110
|
+
sqliteModule = undefined;
|
|
111
|
+
}
|
|
112
|
+
function openReadOnly(dbPath) {
|
|
113
|
+
// existsSync first: a pre-2026.9 box never even loads node:sqlite (and its
|
|
114
|
+
// one-time ExperimentalWarning on Node 22/24 stays out of that journal).
|
|
115
|
+
if (!existsSync(dbPath))
|
|
116
|
+
return null;
|
|
117
|
+
const mod = loadSqlite();
|
|
118
|
+
if (!mod)
|
|
119
|
+
return null;
|
|
120
|
+
try {
|
|
121
|
+
return new mod.DatabaseSync(dbPath, { readOnly: true });
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
/** Run `fn` against a read-only handle; any failure (locked, schema drift,
|
|
128
|
+
* unsupported Node) yields `fallback` — the recorder must never crash on it. */
|
|
129
|
+
function withDb(dbPath, fallback, fn) {
|
|
130
|
+
const db = openReadOnly(dbPath);
|
|
131
|
+
if (!db)
|
|
132
|
+
return fallback;
|
|
133
|
+
try {
|
|
134
|
+
return fn(db);
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
return fallback;
|
|
138
|
+
}
|
|
139
|
+
finally {
|
|
140
|
+
try {
|
|
141
|
+
db.close();
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
/* ignore */
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
/** Which store(s) the recorder can read right now. `sqlite-unsupported` = the
|
|
149
|
+
* agent database exists but this Node has no node:sqlite (upgrade Node). */
|
|
150
|
+
export function describeTranscriptStore(sessionsDir, dbPath) {
|
|
151
|
+
if (!existsSync(dbPath))
|
|
152
|
+
return { kind: 'jsonl', label: `jsonl(${sessionsDir})` };
|
|
153
|
+
if (!loadSqlite())
|
|
154
|
+
return { kind: 'sqlite-unsupported', label: `sqlite-unsupported(${dbPath}; this Node has no node:sqlite)+jsonl(${sessionsDir})` };
|
|
155
|
+
return { kind: 'sqlite', label: `sqlite(${dbPath})+jsonl(${sessionsDir})` };
|
|
156
|
+
}
|
|
70
157
|
const SESSION_FILE_RE = /^([a-z0-9][a-z0-9._-]{0,127})\.jsonl$/i;
|
|
158
|
+
/** Candidates from both stores, newest store first: a session present in the
|
|
159
|
+
* database wins over a same-id `.jsonl` (post-migration leftovers). Never throws. */
|
|
160
|
+
export function listAllSessionCandidates(paths, opts = {}) {
|
|
161
|
+
const out = listSqliteSessionCandidates(paths.dbPath, opts);
|
|
162
|
+
const seen = new Set(out.map((c) => c.sessionId));
|
|
163
|
+
for (const c of listSessionCandidates(paths.sessionsDir, opts)) {
|
|
164
|
+
if (!seen.has(c.sessionId))
|
|
165
|
+
out.push(c);
|
|
166
|
+
}
|
|
167
|
+
return out;
|
|
168
|
+
}
|
|
169
|
+
/** Every session in the agent database whose transcript changed at/after
|
|
170
|
+
* `minMtimeMs`, excluding `exclude`d ids. [] when the database is missing,
|
|
171
|
+
* locked, unreadable, or shaped unlike the 2026.9 schema. */
|
|
172
|
+
export function listSqliteSessionCandidates(dbPath, opts = {}) {
|
|
173
|
+
return withDb(dbPath, [], (db) => {
|
|
174
|
+
const rows = db
|
|
175
|
+
.prepare(`SELECT w.session_id AS id, w.session_key AS key,
|
|
176
|
+
COALESCE(w.transcript_updated_at, w.updated_at, w.created_at) AS mtime
|
|
177
|
+
FROM session_windows w
|
|
178
|
+
WHERE COALESCE(w.transcript_updated_at, w.updated_at, w.created_at) >= ?`)
|
|
179
|
+
.all(opts.minMtimeMs ?? 0);
|
|
180
|
+
const countEvents = db.prepare('SELECT COUNT(*) AS n FROM transcript_events WHERE session_id = ?');
|
|
181
|
+
const hasTrajectory = db.prepare('SELECT 1 AS x FROM trajectory_runtime_events WHERE session_id = ? LIMIT 1');
|
|
182
|
+
const out = [];
|
|
183
|
+
for (const r of rows) {
|
|
184
|
+
if (typeof r.id !== 'string' || !r.id)
|
|
185
|
+
continue;
|
|
186
|
+
if (opts.exclude?.has(r.id))
|
|
187
|
+
continue;
|
|
188
|
+
const mtime = typeof r.mtime === 'number' && Number.isFinite(r.mtime) ? r.mtime : 0;
|
|
189
|
+
const n = countEvents.all(r.id)[0]?.n;
|
|
190
|
+
out.push({
|
|
191
|
+
sessionId: r.id,
|
|
192
|
+
source: 'sqlite',
|
|
193
|
+
file: dbPath,
|
|
194
|
+
trajectoryFile: hasTrajectory.all(r.id).length ? dbPath : null,
|
|
195
|
+
sessionKey: typeof r.key === 'string' ? r.key : null,
|
|
196
|
+
mtimeMs: mtime,
|
|
197
|
+
sizeBytes: typeof n === 'number' ? n : 0,
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
return out;
|
|
201
|
+
});
|
|
202
|
+
}
|
|
71
203
|
/** Every `<sessionId>.jsonl` transcript in `dir` (not sidecars, checkpoints,
|
|
72
204
|
* topic files or retired copies) modified at/after `minMtimeMs`, excluding
|
|
73
205
|
* `exclude`d session ids. Never throws — a missing dir yields []. */
|
|
@@ -108,8 +240,10 @@ export function listSessionCandidates(dir, opts = {}) {
|
|
|
108
240
|
const traj = join(dir, `${sessionId}.trajectory.jsonl`);
|
|
109
241
|
out.push({
|
|
110
242
|
sessionId,
|
|
243
|
+
source: 'jsonl',
|
|
111
244
|
file,
|
|
112
245
|
trajectoryFile: existsSync(traj) ? traj : null,
|
|
246
|
+
sessionKey: null,
|
|
113
247
|
mtimeMs: st.mtimeMs,
|
|
114
248
|
sizeBytes: st.size,
|
|
115
249
|
});
|
|
@@ -127,6 +261,37 @@ export function parseCronMarker(text) {
|
|
|
127
261
|
const jobName = m[2]?.trim();
|
|
128
262
|
return { jobId: m[1], jobName: jobName ? jobName : null };
|
|
129
263
|
}
|
|
264
|
+
/** Head events of a session in the agent database (cheap: bounded by seq). */
|
|
265
|
+
const SQLITE_HEAD_EVENTS = 20;
|
|
266
|
+
/** `readCronMarker` for either store. */
|
|
267
|
+
export function readCandidateCronMarker(c) {
|
|
268
|
+
if (c.source === 'jsonl')
|
|
269
|
+
return readCronMarker(c.file);
|
|
270
|
+
return withDb(c.file, undefined, (db) => {
|
|
271
|
+
const rows = db
|
|
272
|
+
.prepare('SELECT event_json AS e FROM transcript_events WHERE session_id = ? ORDER BY seq LIMIT ?')
|
|
273
|
+
.all(c.sessionId, SQLITE_HEAD_EVENTS);
|
|
274
|
+
return markerInLines(rows.map((r) => (typeof r.e === 'string' ? r.e : '')));
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
function markerInLines(lines) {
|
|
278
|
+
for (const line of lines) {
|
|
279
|
+
if (!line.trim())
|
|
280
|
+
continue;
|
|
281
|
+
let rec;
|
|
282
|
+
try {
|
|
283
|
+
rec = JSON.parse(line);
|
|
284
|
+
}
|
|
285
|
+
catch {
|
|
286
|
+
continue;
|
|
287
|
+
}
|
|
288
|
+
const r = rec;
|
|
289
|
+
if (r?.type !== 'message' || r.message?.role !== 'user')
|
|
290
|
+
continue;
|
|
291
|
+
return parseCronMarker(firstText(r.message.content));
|
|
292
|
+
}
|
|
293
|
+
return undefined;
|
|
294
|
+
}
|
|
130
295
|
/** Read only the head of a transcript and report whether its first user
|
|
131
296
|
* message carries the `[cron:…]` marker. `null` = inconclusive (no user
|
|
132
297
|
* message within the head) — callers then fall back to the trajectory key. */
|
|
@@ -152,22 +317,7 @@ export function readCronMarker(file, headBytes = 32 * 1024) {
|
|
|
152
317
|
// The last line may be cut mid-record when the file exceeds the head; only
|
|
153
318
|
// parse complete lines in that case.
|
|
154
319
|
const complete = readAll || head.endsWith('\n') ? lines : lines.slice(0, -1);
|
|
155
|
-
|
|
156
|
-
if (!line.trim())
|
|
157
|
-
continue;
|
|
158
|
-
let rec;
|
|
159
|
-
try {
|
|
160
|
-
rec = JSON.parse(line);
|
|
161
|
-
}
|
|
162
|
-
catch {
|
|
163
|
-
continue;
|
|
164
|
-
}
|
|
165
|
-
const r = rec;
|
|
166
|
-
if (r?.type !== 'message' || r.message?.role !== 'user')
|
|
167
|
-
continue;
|
|
168
|
-
return parseCronMarker(firstText(r.message.content));
|
|
169
|
-
}
|
|
170
|
-
return undefined;
|
|
320
|
+
return markerInLines(complete);
|
|
171
321
|
}
|
|
172
322
|
function num(v) {
|
|
173
323
|
return typeof v === 'number' && Number.isFinite(v) ? v : null;
|
|
@@ -665,8 +815,10 @@ export function shrinkRecord(record, maxBytes = RECORD_MAX_BYTES) {
|
|
|
665
815
|
return { ...r, toolCalls: r.toolCalls.slice(0, keep), summary: r.summary ? clip(r.summary, 1000).text : null };
|
|
666
816
|
}
|
|
667
817
|
/** Read + parse a candidate's transcript and (when present) its trajectory.
|
|
668
|
-
* Never throws on a missing/torn file
|
|
818
|
+
* Never throws on a missing/torn file or an unreadable database — yields null. */
|
|
669
819
|
export function readSession(c) {
|
|
820
|
+
if (c.source === 'sqlite')
|
|
821
|
+
return readSqliteSession(c);
|
|
670
822
|
let text;
|
|
671
823
|
try {
|
|
672
824
|
text = readFileSync(c.file, 'utf8');
|
|
@@ -686,3 +838,20 @@ export function readSession(c) {
|
|
|
686
838
|
}
|
|
687
839
|
return { transcript, trajectory };
|
|
688
840
|
}
|
|
841
|
+
/** The database rows re-joined as the JSONL they used to be, through the
|
|
842
|
+
* same parsers. A session with no transcript rows yet yields null. */
|
|
843
|
+
function readSqliteSession(c) {
|
|
844
|
+
return withDb(c.file, null, (db) => {
|
|
845
|
+
const lines = db.prepare('SELECT event_json AS e FROM transcript_events WHERE session_id = ? ORDER BY seq').all(c.sessionId)
|
|
846
|
+
.map((r) => (typeof r.e === 'string' ? r.e : ''))
|
|
847
|
+
.filter(Boolean);
|
|
848
|
+
if (!lines.length)
|
|
849
|
+
return null;
|
|
850
|
+
const transcript = parseSessionTranscript(lines.join('\n'));
|
|
851
|
+
const tj = db.prepare('SELECT event_json AS e FROM trajectory_runtime_events WHERE session_id = ? ORDER BY seq').all(c.sessionId)
|
|
852
|
+
.map((r) => (typeof r.e === 'string' ? r.e : ''))
|
|
853
|
+
.filter(Boolean);
|
|
854
|
+
const trajectory = tj.length ? parseTrajectory(tj.join('\n')) : null;
|
|
855
|
+
return { transcript, trajectory };
|
|
856
|
+
});
|
|
857
|
+
}
|
package/bridge/index.js
CHANGED
|
@@ -253,9 +253,14 @@ async function main() {
|
|
|
253
253
|
// /api/shocks (the WS2 change-of-character flags) and delivers an
|
|
254
254
|
// out-of-band re-evaluation turn to the agent on a genuine market shift.
|
|
255
255
|
// Inert until the central gate agent_config.gates.shockWake leaves 'off'.
|
|
256
|
-
|
|
256
|
+
// Per-box kill-switch RC_SHOCK_WAKE=off: never constructed, so the central
|
|
257
|
+
// gate cannot arm out-of-band model turns on this box.
|
|
258
|
+
const shockWakeOff = (process.env.RC_SHOCK_WAKE ?? 'on').trim().toLowerCase() === 'off';
|
|
259
|
+
const shockWake = intelligenceUrlForWakes && !shockWakeOff
|
|
257
260
|
? new ShockWakePoller({ provider, token, intelligenceUrl: intelligenceUrlForWakes })
|
|
258
261
|
: null;
|
|
262
|
+
if (shockWakeOff)
|
|
263
|
+
logger.info(TAG, 'Shock-wake poller disabled (RC_SHOCK_WAKE=off)');
|
|
259
264
|
if (shockWake) {
|
|
260
265
|
// Delivery confirmation: any agent turn STARTING proves the main-session
|
|
261
266
|
// lane is alive — the gateway ack alone cannot (swallowed-turn class).
|
|
@@ -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`
|
|
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
|
|
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.
|
|
12
|
-
*
|
|
13
|
+
* The exact line written to the PTY. `$?` is expanded by the remote shell,
|
|
14
|
+
* not by us.
|
|
15
|
+
*/
|
|
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.
|
|
13
42
|
*/
|
|
14
|
-
export declare function
|
|
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 =
|
|
@@ -90,7 +119,9 @@ export declare function checkPositionGuard(opts: StartOptions): ConnectorUpdateO
|
|
|
90
119
|
* Open a PTY and write the update command to it. Returns as soon as the command
|
|
91
120
|
* is running — the caller polls `readTerminalText` for output.
|
|
92
121
|
*/
|
|
93
|
-
export declare function startConnectorUpdate(rpc: TerminalRpc, opts: StartOptions
|
|
122
|
+
export declare function startConnectorUpdate(rpc: TerminalRpc, opts: StartOptions,
|
|
123
|
+
/** Exact connector release to install — from fetchPinnedConnectVersion, nowhere else. */
|
|
124
|
+
version: string): Promise<ConnectorUpdateOutcome>;
|
|
94
125
|
/** Read the current screen contents. Returns null when the session is gone. */
|
|
95
126
|
export declare function readTerminalText(rpc: TerminalRpc, sessionId: string): Promise<string | null>;
|
|
96
127
|
/** Best-effort PTY cleanup. Never throws — cleanup failure must not mask an outcome. */
|
|
@@ -15,11 +15,16 @@
|
|
|
15
15
|
// This module can run a command on the trader's machine, initiated from our
|
|
16
16
|
// dashboard. That is only acceptable because the command is a FIXED CONSTANT:
|
|
17
17
|
//
|
|
18
|
-
// -
|
|
19
|
-
//
|
|
20
|
-
//
|
|
21
|
-
//
|
|
22
|
-
//
|
|
18
|
+
// - The command shape is fixed (`connectorUpdateCommand`). Its ONLY variable
|
|
19
|
+
// is an exact release version, and that version has exactly one source:
|
|
20
|
+
// ReefClaw's release endpoint (`fetchPinnedConnectVersion`, a public HTTPS
|
|
21
|
+
// GET of build-time constants; release versions are public data), validated
|
|
22
|
+
// as MAJOR.MINOR.PATCH before use. Nothing from the browser, the
|
|
23
|
+
// relay, the agent, or any config file reaches the string, and there is no
|
|
24
|
+
// args/flags parameter. A missing or malformed version refuses the update;
|
|
25
|
+
// it never falls back to an unpinned install. The moment a caller could
|
|
26
|
+
// influence the string this would stop being an update button and become
|
|
27
|
+
// a remote shell, which is why the RPC carries none.
|
|
23
28
|
// - The RPC that reaches this module carries NO command field. Adding one is
|
|
24
29
|
// not a feature request to accept; it is the vulnerability.
|
|
25
30
|
// - No secret is ever placed on the command line. `@reefclaw/connect` takes
|
|
@@ -43,31 +48,89 @@
|
|
|
43
48
|
// `gateway.terminal.enabled=false` is honoured too (`describeOpenFailure`).
|
|
44
49
|
// - terminal.* needs operator.admin: the update opens a separate short-lived
|
|
45
50
|
// admin session and checks the granted scopes before `terminal.open`.
|
|
46
|
-
// - Residual trust:
|
|
47
|
-
// is the registry plus the publisher account (2FA), exactly
|
|
48
|
-
//
|
|
49
|
-
// (the SKILL.md OTA already carries the Ed25519 key for it)
|
|
51
|
+
// - Residual trust: the exact version still resolves on the npm registry, so
|
|
52
|
+
// the trust root is the registry plus the publisher account (2FA), exactly
|
|
53
|
+
// as for a manual install of that version. An offline signature over the
|
|
54
|
+
// release (the SKILL.md OTA already carries the Ed25519 key for it) is the
|
|
55
|
+
// planned next step.
|
|
50
56
|
// - The updater overwrites local modifications to the placed bridge/plugin,
|
|
51
57
|
// as any reinstall would. Self-hosters carrying patches: switch it off.
|
|
52
58
|
import { logger } from '../logger.js';
|
|
53
59
|
const TAG = 'connector-update';
|
|
60
|
+
/** The npm package the update runs. Fixed. */
|
|
61
|
+
export const CONNECT_PACKAGE = '@reefclaw/connect';
|
|
62
|
+
/** Exact release versions only — no tags, ranges or pre-release suffixes. */
|
|
63
|
+
const EXACT_VERSION_RE = /^\d{1,4}\.\d{1,4}\.\d{1,4}$/;
|
|
64
|
+
export function isExactConnectVersion(v) {
|
|
65
|
+
return typeof v === 'string' && EXACT_VERSION_RE.test(v);
|
|
66
|
+
}
|
|
54
67
|
/**
|
|
55
|
-
* The ONE command this feature can ever run.
|
|
56
|
-
*
|
|
57
|
-
* `-y`
|
|
58
|
-
* update. No user input, no interpolation, no exceptions.
|
|
68
|
+
* The ONE command shape this feature can ever run. The only variable part is
|
|
69
|
+
* an exact version, validated against EXACT_VERSION_RE; anything else throws.
|
|
70
|
+
* `-y` keeps the package runner from stopping at its install prompt.
|
|
59
71
|
*/
|
|
60
|
-
export
|
|
72
|
+
export function connectorUpdateCommand(version) {
|
|
73
|
+
if (!isExactConnectVersion(version)) {
|
|
74
|
+
throw new Error(`refusing to build an update command for a non-exact version: ${JSON.stringify(version)}`);
|
|
75
|
+
}
|
|
76
|
+
return `npx -y ${CONNECT_PACKAGE}@${version}`;
|
|
77
|
+
}
|
|
61
78
|
/** Marker printed after the command so we can detect completion + exit code. */
|
|
62
79
|
export const DONE_SENTINEL = '__RC_CONNECTOR_UPDATE_DONE__';
|
|
63
80
|
/**
|
|
64
|
-
* The exact line written to the PTY.
|
|
65
|
-
*
|
|
81
|
+
* The exact line written to the PTY. `$?` is expanded by the remote shell,
|
|
82
|
+
* not by us.
|
|
83
|
+
*/
|
|
84
|
+
export function buildUpdateCommandLine(version) {
|
|
85
|
+
return `${connectorUpdateCommand(version)}; printf '\\n${DONE_SENTINEL}%s\\n' "$?"`;
|
|
86
|
+
}
|
|
87
|
+
/** Manual-fallback copy for the refusals below: the operator runs the same
|
|
88
|
+
* pinned command from a shell on the box. `version` is unknown when the
|
|
89
|
+
* refusal happened before the release lookup. */
|
|
90
|
+
export function manualUpdateHint(version) {
|
|
91
|
+
return version
|
|
92
|
+
? `run this from a shell on the box: npx -y ${CONNECT_PACKAGE}@${version}`
|
|
93
|
+
: `run the ReefClaw connect installer from a shell on the box, pinned to the version the dashboard's update notice shows (${CONNECT_PACKAGE}@<version>)`;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Ask ReefClaw which connector release an update installs: `connectVersion` on
|
|
97
|
+
* the PUBLIC `/api/release` endpoint, baked by the webapp at build from the
|
|
98
|
+
* released installer (the same constants ride the authenticated config
|
|
99
|
+
* channel as `release.connectVersion`). No credential is needed or sent —
|
|
100
|
+
* release versions are public data, and an update must keep working on a box
|
|
101
|
+
* whose connection token is stale. Any failure, or anything that is not an
|
|
102
|
+
* exact version, refuses the update — this feature never falls back to an
|
|
103
|
+
* unpinned install.
|
|
66
104
|
*/
|
|
67
|
-
export function
|
|
68
|
-
|
|
105
|
+
export async function fetchPinnedConnectVersion(opts) {
|
|
106
|
+
const refuse = (why) => ({
|
|
107
|
+
ok: false,
|
|
108
|
+
outcome: {
|
|
109
|
+
ok: false,
|
|
110
|
+
status: 'blocked',
|
|
111
|
+
message: `Could not confirm the connector version to install (${why}), so the update was not started — ` +
|
|
112
|
+
`it only ever installs an exact, ReefClaw-confirmed release. Try again shortly, or ${manualUpdateHint()}.`,
|
|
113
|
+
},
|
|
114
|
+
});
|
|
115
|
+
// www matches every other webapp call the bridge makes (reefclaw.com
|
|
116
|
+
// 307-redirects to it).
|
|
117
|
+
const base = (opts.webappUrl ?? process.env.REEFCLAW_API_URL ?? 'https://www.reefclaw.com').replace(/\/$/, '');
|
|
118
|
+
try {
|
|
119
|
+
const doFetch = opts.fetchImpl ?? fetch;
|
|
120
|
+
const res = await doFetch(`${base}/api/release`, { signal: AbortSignal.timeout(15_000) });
|
|
121
|
+
if (!res.ok)
|
|
122
|
+
return refuse(`ReefClaw answered HTTP ${res.status}`);
|
|
123
|
+
const body = (await res.json());
|
|
124
|
+
const version = body?.connectVersion;
|
|
125
|
+
if (!isExactConnectVersion(version))
|
|
126
|
+
return refuse('ReefClaw did not report an exact release version');
|
|
127
|
+
return { ok: true, version };
|
|
128
|
+
}
|
|
129
|
+
catch (err) {
|
|
130
|
+
return refuse(err instanceof Error ? err.message : String(err));
|
|
131
|
+
}
|
|
69
132
|
}
|
|
70
|
-
/** Terminal grid we request. Wide enough that
|
|
133
|
+
/** Terminal grid we request. Wide enough that package-manager output does not wrap into
|
|
71
134
|
* unreadable soup in the dashboard's output pane. */
|
|
72
135
|
const COLS = 120;
|
|
73
136
|
const ROWS = 40;
|
|
@@ -90,7 +153,7 @@ export function describeOpenFailure(err) {
|
|
|
90
153
|
ok: false,
|
|
91
154
|
status: 'blocked',
|
|
92
155
|
message: 'This box has the OpenClaw terminal disabled, so ReefClaw cannot run the update for you. '
|
|
93
|
-
+
|
|
156
|
+
+ `Instead, ${manualUpdateHint()}.`,
|
|
94
157
|
};
|
|
95
158
|
}
|
|
96
159
|
if (lower.includes('sandbox')) {
|
|
@@ -98,7 +161,7 @@ export function describeOpenFailure(err) {
|
|
|
98
161
|
ok: false,
|
|
99
162
|
status: 'blocked',
|
|
100
163
|
message: 'This agent runs in a sandbox, and OpenClaw does not support terminals inside one yet. '
|
|
101
|
-
+
|
|
164
|
+
+ `Instead, ${manualUpdateHint()}.`,
|
|
102
165
|
};
|
|
103
166
|
}
|
|
104
167
|
// Scope refusal: terminal.* requires operator.admin on OpenClaw >= 2026.7
|
|
@@ -112,7 +175,7 @@ export function describeOpenFailure(err) {
|
|
|
112
175
|
status: 'blocked',
|
|
113
176
|
message: 'The gateway refused to open a terminal for the connector (it needs the operator.admin scope). '
|
|
114
177
|
+ 'One-click updates need a connector released 2026-09-14 or later — update once by pasting the manual '
|
|
115
|
-
+
|
|
178
|
+
+ `command to your agent, or ${manualUpdateHint()}. After that, updates are one click.`,
|
|
116
179
|
};
|
|
117
180
|
}
|
|
118
181
|
return {
|
|
@@ -128,7 +191,7 @@ export function describeUpdateDisabled() {
|
|
|
128
191
|
ok: false,
|
|
129
192
|
status: 'blocked',
|
|
130
193
|
message: 'One-click updates are switched off on this box (REEFCLAW_ALLOW_CONNECTOR_UPDATE=0). '
|
|
131
|
-
+ `
|
|
194
|
+
+ `Instead, ${manualUpdateHint()}.`,
|
|
132
195
|
};
|
|
133
196
|
}
|
|
134
197
|
/**
|
|
@@ -184,7 +247,9 @@ export function checkPositionGuard(opts) {
|
|
|
184
247
|
* Open a PTY and write the update command to it. Returns as soon as the command
|
|
185
248
|
* is running — the caller polls `readTerminalText` for output.
|
|
186
249
|
*/
|
|
187
|
-
export async function startConnectorUpdate(rpc, opts
|
|
250
|
+
export async function startConnectorUpdate(rpc, opts,
|
|
251
|
+
/** Exact connector release to install — from fetchPinnedConnectVersion, nowhere else. */
|
|
252
|
+
version) {
|
|
188
253
|
const blocked = checkPositionGuard(opts);
|
|
189
254
|
if (blocked) {
|
|
190
255
|
logger.info(TAG, `update refused: ${opts.openPositionCount} open position(s), no acknowledgement`);
|
|
@@ -214,7 +279,7 @@ export async function startConnectorUpdate(rpc, opts) {
|
|
|
214
279
|
logger.info(TAG, `terminal opened (shell=${opened.shell} cwd=${opened.cwd} confined=${opened.confined})`);
|
|
215
280
|
try {
|
|
216
281
|
// `\r` submits the line — terminal.input is raw keystrokes, not a command API.
|
|
217
|
-
await rpc('terminal.input', { sessionId, data: `${buildUpdateCommandLine()}\r` });
|
|
282
|
+
await rpc('terminal.input', { sessionId, data: `${buildUpdateCommandLine(version)}\r` });
|
|
218
283
|
}
|
|
219
284
|
catch (err) {
|
|
220
285
|
const reason = err instanceof Error ? err.message : String(err);
|
|
@@ -263,7 +328,7 @@ export function describeMissingAdminScope(granted) {
|
|
|
263
328
|
ok: false,
|
|
264
329
|
status: 'blocked',
|
|
265
330
|
message: `This gateway did not grant the connector the operator.admin scope it needs to open a terminal (granted: ${list}). `
|
|
266
|
-
+
|
|
331
|
+
+ `One-click updates are unavailable on this box — ${manualUpdateHint()}.`,
|
|
267
332
|
};
|
|
268
333
|
}
|
|
269
334
|
/** Connect a fresh admin-scoped client and wait for hello-ok. Resolves with the
|
|
@@ -261,10 +261,11 @@ export declare class GatewayProvider implements OpenClawProvider {
|
|
|
261
261
|
* Operator-only. Update the ReefClaw connector on this box to the latest
|
|
262
262
|
* published version.
|
|
263
263
|
*
|
|
264
|
-
* Runs
|
|
265
|
-
*
|
|
266
|
-
*
|
|
267
|
-
*
|
|
264
|
+
* Runs the connect installer over the gateway's PTY, pinned to the exact
|
|
265
|
+
* connector release ReefClaw's public release endpoint reports. The
|
|
266
|
+
* RPC carries no command/version/args parameter and never should — the
|
|
267
|
+
* version is looked up server-side by this process, never taken from the
|
|
268
|
+
* caller (see providers/connector-update.ts).
|
|
268
269
|
*
|
|
269
270
|
* The installer restarts the gateway when it finishes, which kills both the
|
|
270
271
|
* PTY and this process's own transport. That is the SUCCESS path: we report
|
|
@@ -300,18 +301,15 @@ export declare class GatewayProvider implements OpenClawProvider {
|
|
|
300
301
|
private startToolRetry;
|
|
301
302
|
private createPoller;
|
|
302
303
|
private wireWsEvents;
|
|
303
|
-
/**
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
*
|
|
307
|
-
* the
|
|
308
|
-
*
|
|
309
|
-
|
|
310
|
-
* only when it demonstrably withheld the one we need. On the supported
|
|
311
|
-
* range the scope survives and nothing is written. */
|
|
312
|
-
private deviceIdentityRelaxationApplied;
|
|
304
|
+
/** The gateway withheld `operator.write` from this connection (or rejected
|
|
305
|
+
* the handshake for missing device identity). The connector used to react
|
|
306
|
+
* by writing OpenClaw's legacy auth-relaxation flags itself (2026-07-29 →
|
|
307
|
+
* 2026-09-19). It no longer touches the gateway's auth settings at all: it
|
|
308
|
+
* reports the exact manual remedy once per process and leaves the decision
|
|
309
|
+
* to the operator. */
|
|
310
|
+
private writeScopeRemedyReported;
|
|
313
311
|
/** Handshake rejected outright for missing device identity (see
|
|
314
|
-
* isDeviceIdentityRejection). Same
|
|
312
|
+
* isDeviceIdentityRejection). Same report as the withheld-write-scope
|
|
315
313
|
* case, keyed on the rejection instead of on hello-ok scopes. */
|
|
316
314
|
private onHandshakeRejectedForDeviceIdentity;
|
|
317
315
|
private checkGrantedScopes;
|