@reefclaw/openclaw-plugin 0.1.30 → 0.1.34
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bridge/bridge.d.ts +20 -1
- package/bridge/bridge.js +22 -8
- package/bridge/gateway/agent-scope.d.ts +47 -6
- package/bridge/gateway/agent-scope.js +89 -11
- package/bridge/gateway/gateway-config.d.ts +20 -0
- package/bridge/gateway/gateway-config.js +43 -5
- package/bridge/gateway/heartbeat-cron.d.ts +17 -0
- package/bridge/gateway/heartbeat-cron.js +42 -3
- 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 +51 -35
- package/bridge/providers/connector-update.d.ts +5 -0
- package/bridge/providers/connector-update.js +5 -1
- package/bridge/providers/gateway.d.ts +3 -0
- package/bridge/providers/gateway.js +94 -41
- package/bridge/providers/risk-calculator.d.ts +31 -0
- package/bridge/providers/risk-calculator.js +41 -1
- package/bridge/utils/skill-version.d.ts +1 -1
- package/bridge/utils/skill-version.js +4 -3
- package/bridge/utils/skills-snapshot-invalidation.d.ts +1 -1
- package/bridge/utils/skills-snapshot-invalidation.js +2 -2
- package/openclaw.plugin.json +1 -1
- package/package.json +1 -1
- package/release-notes.json +3 -1
package/bridge/heartbeat-runs.js
CHANGED
|
@@ -2,8 +2,10 @@
|
|
|
2
2
|
// + webapp POST). File reads live in heartbeat-transcript.ts / -state.ts.
|
|
3
3
|
//
|
|
4
4
|
// What it does, every 60s and ~4s after any cron-session turn ends:
|
|
5
|
-
// 1. list transcripts
|
|
6
|
-
//
|
|
5
|
+
// 1. list transcripts newer than the last scan watermark (minus slack) that
|
|
6
|
+
// are not yet recorded — from the agent database (OpenClaw >= 2026.9)
|
|
7
|
+
// and the sessions dir (*.jsonl, older gateways); with nothing to read,
|
|
8
|
+
// ask cron.runs whether beats ran anyway and WARN once if so;
|
|
7
9
|
// 2. keep the ones whose first user message carries the `[cron:…]`
|
|
8
10
|
// heartbeat marker (or whose trajectory key is a cron key); mark every
|
|
9
11
|
// other session (the main chat session, subagents) as skipped once so
|
|
@@ -23,7 +25,7 @@
|
|
|
23
25
|
// Deliberately NOT recorded: shock wakes and operator chat turns (they run in
|
|
24
26
|
// the main session, whose transcript is one long file). Heartbeats only.
|
|
25
27
|
import { logger } from './logger.js';
|
|
26
|
-
import { buildHeartbeatRunRecord, isCronSessionKey,
|
|
28
|
+
import { buildHeartbeatRunRecord, describeTranscriptStore, isCronSessionKey, listAllSessionCandidates, readCandidateCronMarker, readSession, resolveAgentDbPath, resolveSessionsDir, shrinkRecord, } from './heartbeat-transcript.js';
|
|
27
29
|
import { defaultStateFile, loadState, markRecorded, saveState } from './heartbeat-runs-state.js';
|
|
28
30
|
const TAG = 'heartbeat-runs';
|
|
29
31
|
/** Regular scan cadence. */
|
|
@@ -47,9 +49,13 @@ export const MAX_PER_SCAN = 5;
|
|
|
47
49
|
export const MAX_POST_ATTEMPTS = 5;
|
|
48
50
|
/** Cool down `cron.runs` for this long after it errors (older gateway). */
|
|
49
51
|
export const CRON_RUNS_COOLDOWN_MS = 60 * 60_000;
|
|
52
|
+
/** With nothing to read, ask `cron.runs` this often whether beats ran anyway
|
|
53
|
+
* (a store the recorder cannot read must not stay silent — Ardi, report #5). */
|
|
54
|
+
export const BLIND_PROBE_INTERVAL_MS = 10 * 60_000;
|
|
50
55
|
export class HeartbeatRunRecorder {
|
|
51
56
|
opts;
|
|
52
57
|
sessionsDir;
|
|
58
|
+
agentDbPath;
|
|
53
59
|
stateFile;
|
|
54
60
|
timer = null;
|
|
55
61
|
kickTimer = null;
|
|
@@ -59,16 +65,36 @@ export class HeartbeatRunRecorder {
|
|
|
59
65
|
attempts = new Map();
|
|
60
66
|
cronRunsUnavailableUntil = 0;
|
|
61
67
|
probeLogged = false;
|
|
68
|
+
store = null;
|
|
69
|
+
lastBlindProbeAt;
|
|
70
|
+
blindWarned = false;
|
|
62
71
|
/** Counters for a one-line health summary in logs. */
|
|
63
72
|
stats = { scans: 0, recorded: 0, posted: 0, postFailed: 0, skippedNonCron: 0, deferred: 0 };
|
|
64
73
|
constructor(opts) {
|
|
65
74
|
this.opts = opts;
|
|
66
75
|
this.sessionsDir = opts.sessionsDir ?? resolveSessionsDir();
|
|
76
|
+
this.agentDbPath = opts.agentDbPath ?? resolveAgentDbPath(this.sessionsDir);
|
|
67
77
|
this.stateFile = opts.stateFile ?? defaultStateFile();
|
|
78
|
+
this.lastBlindProbeAt = this.now();
|
|
68
79
|
}
|
|
69
80
|
now() {
|
|
70
81
|
return this.opts.now?.() ?? Date.now();
|
|
71
82
|
}
|
|
83
|
+
/** Which store(s) are readable; logs on first sight and whenever it changes
|
|
84
|
+
* (the database appears when a gateway is upgraded under a running bridge). */
|
|
85
|
+
detectStore() {
|
|
86
|
+
const next = describeTranscriptStore(this.sessionsDir, this.agentDbPath);
|
|
87
|
+
if (this.store?.label !== next.label) {
|
|
88
|
+
const changed = this.store !== null;
|
|
89
|
+
this.store = next;
|
|
90
|
+
if (changed)
|
|
91
|
+
logger.info(TAG, `transcript store changed: store=${next.label}`);
|
|
92
|
+
if (next.kind === 'sqlite-unsupported') {
|
|
93
|
+
logger.warn(TAG, `agent database present but this Node (${process.version}) has no node:sqlite — heartbeat telemetry stays empty until Node is upgraded (>= 22.13; OpenClaw >= 2026.9.3 needs 24)`);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return this.store;
|
|
97
|
+
}
|
|
72
98
|
start() {
|
|
73
99
|
if (this.stopped)
|
|
74
100
|
return;
|
|
@@ -79,7 +105,7 @@ export class HeartbeatRunRecorder {
|
|
|
79
105
|
this.kick(FIRST_SCAN_DELAY_MS);
|
|
80
106
|
this.timer = setInterval(() => void this.scan(), interval);
|
|
81
107
|
this.timer.unref?.();
|
|
82
|
-
logger.info(TAG, `Heartbeat flight recorder started (
|
|
108
|
+
logger.info(TAG, `Heartbeat flight recorder started (store=${this.detectStore().label}, every ${Math.round(interval / 1000)}s)`);
|
|
83
109
|
}
|
|
84
110
|
stop() {
|
|
85
111
|
this.stopped = true;
|
|
@@ -124,9 +150,12 @@ export class HeartbeatRunRecorder {
|
|
|
124
150
|
const state = loadState(this.stateFile);
|
|
125
151
|
const since = state.lastScanMtimeMs > 0 ? state.lastScanMtimeMs - SCAN_SLACK_MS : now - BOOTSTRAP_LOOKBACK_MS;
|
|
126
152
|
const exclude = new Set(state.recorded);
|
|
127
|
-
|
|
153
|
+
this.detectStore();
|
|
154
|
+
const candidates = listAllSessionCandidates({ sessionsDir: this.sessionsDir, dbPath: this.agentDbPath }, { minMtimeMs: since, exclude })
|
|
128
155
|
.filter((c) => now - c.mtimeMs >= SETTLE_MS)
|
|
129
156
|
.sort((a, b) => a.mtimeMs - b.mtimeMs);
|
|
157
|
+
if (candidates.length === 0)
|
|
158
|
+
await this.probeBlind(now, since, state);
|
|
130
159
|
let cronRuns; // undefined = not fetched yet
|
|
131
160
|
let dirty = false;
|
|
132
161
|
for (const c of candidates) {
|
|
@@ -221,10 +250,35 @@ export class HeartbeatRunRecorder {
|
|
|
221
250
|
}
|
|
222
251
|
return { processed, deferred };
|
|
223
252
|
}
|
|
224
|
-
/**
|
|
225
|
-
*
|
|
253
|
+
/** Nothing to read this scan — were there beats anyway? `cron.runs` knows;
|
|
254
|
+
* a finished, unrecorded run inside the window means the recorder cannot
|
|
255
|
+
* see the store it should be reading. Warn once per process. */
|
|
256
|
+
async probeBlind(now, since, state) {
|
|
257
|
+
if (this.blindWarned || now - this.lastBlindProbeAt < BLIND_PROBE_INTERVAL_MS)
|
|
258
|
+
return;
|
|
259
|
+
this.lastBlindProbeAt = now;
|
|
260
|
+
const runs = await this.fetchCronRunsSafe(now);
|
|
261
|
+
if (!runs)
|
|
262
|
+
return;
|
|
263
|
+
const recorded = new Set(state.recorded);
|
|
264
|
+
const missed = runs.filter((r) => (r.status === 'ok' || r.status === 'error') &&
|
|
265
|
+
r.runAtMs != null &&
|
|
266
|
+
r.runAtMs >= since &&
|
|
267
|
+
!(r.sessionId && recorded.has(r.sessionId)) &&
|
|
268
|
+
!(r.runId && recorded.has(r.runId)));
|
|
269
|
+
if (!missed.length)
|
|
270
|
+
return;
|
|
271
|
+
this.blindWarned = true;
|
|
272
|
+
logger.warn(TAG, `recorder is BLIND: cron.runs reports ${missed.length} finished heartbeat(s) since ${new Date(since).toISOString()} ` +
|
|
273
|
+
`but no transcript was found (store=${this.detectStore().label}) — heartbeat telemetry stays empty until the store is readable`);
|
|
274
|
+
}
|
|
275
|
+
/** Is this session a heartbeat? Session key first (the database carries it),
|
|
276
|
+
* head marker second (cheap), trajectory key third (covers a prompt without
|
|
277
|
+
* the marker), else not a heartbeat. */
|
|
226
278
|
classify(c) {
|
|
227
|
-
|
|
279
|
+
if (isCronSessionKey(c.sessionKey))
|
|
280
|
+
return c.sizeBytes === 0 ? 'unreadable' : 'cron';
|
|
281
|
+
const marker = readCandidateCronMarker(c);
|
|
228
282
|
if (marker === undefined) {
|
|
229
283
|
// Inconclusive head — fall back to the trajectory key when present.
|
|
230
284
|
if (c.trajectoryFile) {
|
|
@@ -103,13 +103,68 @@ export interface CronRunLogLite {
|
|
|
103
103
|
* bridge historically read a non-existent OPENCLAW_HOME; honour both). */
|
|
104
104
|
export declare function resolveOpenClawStateDir(env?: NodeJS.ProcessEnv): string;
|
|
105
105
|
export declare function resolveSessionsDir(agentId?: string, env?: NodeJS.ProcessEnv): string;
|
|
106
|
+
export declare const AGENT_DB_BASENAME = "openclaw-agent.sqlite";
|
|
107
|
+
/** The agent database beside a `<state>/agents/<id>/sessions` dir
|
|
108
|
+
* (OpenClaw's `resolveOpenClawAgentSqlitePath`: `agents/<id>/agent/openclaw-agent.sqlite`). */
|
|
109
|
+
export declare function resolveAgentDbPath(sessionsDir: string): string;
|
|
110
|
+
export interface SqliteStatement {
|
|
111
|
+
all(...params: unknown[]): unknown[];
|
|
112
|
+
run(...params: unknown[]): unknown;
|
|
113
|
+
}
|
|
114
|
+
export interface SqliteDatabase {
|
|
115
|
+
prepare(sql: string): SqliteStatement;
|
|
116
|
+
exec(sql: string): void;
|
|
117
|
+
close(): void;
|
|
118
|
+
}
|
|
119
|
+
export interface SqliteModule {
|
|
120
|
+
DatabaseSync: new (path: string, opts?: {
|
|
121
|
+
readOnly?: boolean;
|
|
122
|
+
}) => SqliteDatabase;
|
|
123
|
+
}
|
|
124
|
+
/** `node:sqlite`, or null when this Node has none. Cached. */
|
|
125
|
+
export declare function loadSqlite(): SqliteModule | null;
|
|
126
|
+
/** Test seam: swap the loader (pass null to simulate a Node without node:sqlite). */
|
|
127
|
+
export declare function setSqliteLoaderForTests(loader: (() => SqliteModule | null) | null): void;
|
|
128
|
+
export type TranscriptStoreKind = 'sqlite' | 'sqlite-unsupported' | 'jsonl';
|
|
129
|
+
export interface TranscriptStoreInfo {
|
|
130
|
+
kind: TranscriptStoreKind;
|
|
131
|
+
/** One-line label for logs, e.g. `sqlite(<db>)+jsonl(<dir>)`. Starts with the kind. */
|
|
132
|
+
label: string;
|
|
133
|
+
}
|
|
134
|
+
/** Which store(s) the recorder can read right now. `sqlite-unsupported` = the
|
|
135
|
+
* agent database exists but this Node has no node:sqlite (upgrade Node). */
|
|
136
|
+
export declare function describeTranscriptStore(sessionsDir: string, dbPath: string): TranscriptStoreInfo;
|
|
106
137
|
export interface SessionCandidate {
|
|
107
138
|
sessionId: string;
|
|
139
|
+
/** 'jsonl' = `<sessionId>.jsonl` (+ sidecar) in the sessions dir;
|
|
140
|
+
* 'sqlite' = rows in the agent database (OpenClaw >= 2026.9). */
|
|
141
|
+
source: 'jsonl' | 'sqlite';
|
|
142
|
+
/** The transcript file (jsonl) or the agent database (sqlite). */
|
|
108
143
|
file: string;
|
|
109
144
|
trajectoryFile: string | null;
|
|
145
|
+
/** The gateway's session key when the store carries it (sqlite) — a `:cron:`
|
|
146
|
+
* key identifies a heartbeat without reading the transcript. */
|
|
147
|
+
sessionKey: string | null;
|
|
110
148
|
mtimeMs: number;
|
|
149
|
+
/** File size (jsonl) or transcript event count (sqlite); 0 = nothing to read yet. */
|
|
111
150
|
sizeBytes: number;
|
|
112
151
|
}
|
|
152
|
+
/** Candidates from both stores, newest store first: a session present in the
|
|
153
|
+
* database wins over a same-id `.jsonl` (post-migration leftovers). Never throws. */
|
|
154
|
+
export declare function listAllSessionCandidates(paths: {
|
|
155
|
+
sessionsDir: string;
|
|
156
|
+
dbPath: string;
|
|
157
|
+
}, opts?: {
|
|
158
|
+
minMtimeMs?: number;
|
|
159
|
+
exclude?: Set<string>;
|
|
160
|
+
}): SessionCandidate[];
|
|
161
|
+
/** Every session in the agent database whose transcript changed at/after
|
|
162
|
+
* `minMtimeMs`, excluding `exclude`d ids. [] when the database is missing,
|
|
163
|
+
* locked, unreadable, or shaped unlike the 2026.9 schema. */
|
|
164
|
+
export declare function listSqliteSessionCandidates(dbPath: string, opts?: {
|
|
165
|
+
minMtimeMs?: number;
|
|
166
|
+
exclude?: Set<string>;
|
|
167
|
+
}): SessionCandidate[];
|
|
113
168
|
/** Every `<sessionId>.jsonl` transcript in `dir` (not sidecars, checkpoints,
|
|
114
169
|
* topic files or retired copies) modified at/after `minMtimeMs`, excluding
|
|
115
170
|
* `exclude`d session ids. Never throws — a missing dir yields []. */
|
|
@@ -122,6 +177,8 @@ export interface CronMarker {
|
|
|
122
177
|
jobName: string | null;
|
|
123
178
|
}
|
|
124
179
|
export declare function parseCronMarker(text: string | null | undefined): CronMarker | null;
|
|
180
|
+
/** `readCronMarker` for either store. */
|
|
181
|
+
export declare function readCandidateCronMarker(c: SessionCandidate): CronMarker | null | undefined;
|
|
125
182
|
/** Read only the head of a transcript and report whether its first user
|
|
126
183
|
* message carries the `[cron:…]` marker. `null` = inconclusive (no user
|
|
127
184
|
* message within the head) — callers then fall back to the trajectory key. */
|
|
@@ -205,5 +262,5 @@ export interface ReadSessionResult {
|
|
|
205
262
|
trajectory: ParsedTrajectory | null;
|
|
206
263
|
}
|
|
207
264
|
/** Read + parse a candidate's transcript and (when present) its trajectory.
|
|
208
|
-
* Never throws on a missing/torn file
|
|
265
|
+
* Never throws on a missing/torn file or an unreadable database — yields null. */
|
|
209
266
|
export declare function readSession(c: SessionCandidate): ReadSessionResult | null;
|
|
@@ -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
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
// Config precedence: CLI args > env vars > OpenClaw config > fallback env > defaults
|
|
9
9
|
// See config.ts for full resolution logic.
|
|
10
10
|
import { readFileSync } from 'fs';
|
|
11
|
-
import { resolve, dirname } from 'path';
|
|
11
|
+
import { resolve, dirname, join } from 'path';
|
|
12
12
|
import { fileURLToPath } from 'url';
|
|
13
13
|
import { logger, setLogLevel } from './logger.js';
|
|
14
14
|
import { Bridge } from './bridge.js';
|
|
@@ -122,37 +122,37 @@ function parseArgs() {
|
|
|
122
122
|
return { cli, gateway };
|
|
123
123
|
}
|
|
124
124
|
function printUsage() {
|
|
125
|
-
console.log(`
|
|
126
|
-
ReefClaw Skill — Bridge between OpenClaw and ReefClaw relay
|
|
127
|
-
|
|
128
|
-
Usage:
|
|
129
|
-
tsx src/index.ts [options]
|
|
130
|
-
|
|
131
|
-
Options:
|
|
132
|
-
--provider, -p <mock|gateway> Provider type (default: mock)
|
|
133
|
-
--token, -t <token> Connection token (or REEFCLAW_TOKEN env)
|
|
134
|
-
--user-id, -u <id> User ID (or REEFCLAW_USER_ID env)
|
|
135
|
-
--relay-url, -r <url> Relay URL (default: wss://reefclaw.radunlupsa.partykit.dev)
|
|
136
|
-
--gateway-url <url> OpenClaw gateway URL (or OPENCLAW_GATEWAY_URL env)
|
|
137
|
-
--gateway-token <token> OpenClaw gateway token (or OPENCLAW_GATEWAY_TOKEN env)
|
|
138
|
-
--symbol <symbol> Trading symbol (default: BTC/USDT, or REEFCLAW_SYMBOL env)
|
|
139
|
-
--agent-id <id> OpenClaw agent this bridge serves (default: main, or OPENCLAW_AGENT_ID env)
|
|
140
|
-
--log-level, -l <level> Log level: debug, info, warn, error (default: info)
|
|
141
|
-
--setup, -s [token] Run setup flow (validate token, test connection, save to config)
|
|
142
|
-
--help, -h Show this help
|
|
143
|
-
|
|
144
|
-
Relay config resolution (highest priority first):
|
|
145
|
-
1. CLI arguments (--token, --user-id, --relay-url)
|
|
146
|
-
2. Environment variables (REEFCLAW_TOKEN, REEFCLAW_USER_ID, REEFCLAW_RELAY_URL)
|
|
147
|
-
3. OpenClaw config file (~/.openclaw/openclaw.json → skills.entries.reefclaw)
|
|
148
|
-
4. Fallback env vars (MOCK_TOKEN, USER_ID)
|
|
149
|
-
5. Defaults (relay URL → wss://reefclaw.radunlupsa.partykit.dev)
|
|
150
|
-
|
|
151
|
-
Gateway config resolution (for --provider gateway):
|
|
152
|
-
1. CLI arguments (--gateway-url, --gateway-token, --symbol, --agent-id)
|
|
153
|
-
2. Environment variables (OPENCLAW_GATEWAY_URL, OPENCLAW_GATEWAY_TOKEN, REEFCLAW_SYMBOL, OPENCLAW_AGENT_ID)
|
|
154
|
-
3. OpenClaw config file (~/.openclaw/openclaw.json → gateway.auth.token, gateway.port)
|
|
155
|
-
4. Defaults (http://localhost:18789, BTC/USDT)
|
|
125
|
+
console.log(`
|
|
126
|
+
ReefClaw Skill — Bridge between OpenClaw and ReefClaw relay
|
|
127
|
+
|
|
128
|
+
Usage:
|
|
129
|
+
tsx src/index.ts [options]
|
|
130
|
+
|
|
131
|
+
Options:
|
|
132
|
+
--provider, -p <mock|gateway> Provider type (default: mock)
|
|
133
|
+
--token, -t <token> Connection token (or REEFCLAW_TOKEN env)
|
|
134
|
+
--user-id, -u <id> User ID (or REEFCLAW_USER_ID env)
|
|
135
|
+
--relay-url, -r <url> Relay URL (default: wss://reefclaw.radunlupsa.partykit.dev)
|
|
136
|
+
--gateway-url <url> OpenClaw gateway URL (or OPENCLAW_GATEWAY_URL env)
|
|
137
|
+
--gateway-token <token> OpenClaw gateway token (or OPENCLAW_GATEWAY_TOKEN env)
|
|
138
|
+
--symbol <symbol> Trading symbol (default: BTC/USDT, or REEFCLAW_SYMBOL env)
|
|
139
|
+
--agent-id <id> OpenClaw agent this bridge serves (default: main, or OPENCLAW_AGENT_ID env)
|
|
140
|
+
--log-level, -l <level> Log level: debug, info, warn, error (default: info)
|
|
141
|
+
--setup, -s [token] Run setup flow (validate token, test connection, save to config)
|
|
142
|
+
--help, -h Show this help
|
|
143
|
+
|
|
144
|
+
Relay config resolution (highest priority first):
|
|
145
|
+
1. CLI arguments (--token, --user-id, --relay-url)
|
|
146
|
+
2. Environment variables (REEFCLAW_TOKEN, REEFCLAW_USER_ID, REEFCLAW_RELAY_URL)
|
|
147
|
+
3. OpenClaw config file (~/.openclaw/openclaw.json → skills.entries.reefclaw)
|
|
148
|
+
4. Fallback env vars (MOCK_TOKEN, USER_ID)
|
|
149
|
+
5. Defaults (relay URL → wss://reefclaw.radunlupsa.partykit.dev)
|
|
150
|
+
|
|
151
|
+
Gateway config resolution (for --provider gateway):
|
|
152
|
+
1. CLI arguments (--gateway-url, --gateway-token, --symbol, --agent-id)
|
|
153
|
+
2. Environment variables (OPENCLAW_GATEWAY_URL, OPENCLAW_GATEWAY_TOKEN, REEFCLAW_SYMBOL, OPENCLAW_AGENT_ID)
|
|
154
|
+
3. OpenClaw config file (~/.openclaw/openclaw.json → gateway.auth.token, gateway.port)
|
|
155
|
+
4. Defaults (http://localhost:18789, BTC/USDT)
|
|
156
156
|
`);
|
|
157
157
|
}
|
|
158
158
|
// ---- Main ----
|
|
@@ -200,6 +200,10 @@ async function main() {
|
|
|
200
200
|
// Create provider
|
|
201
201
|
let provider;
|
|
202
202
|
let intelligenceUrlForWakes;
|
|
203
|
+
// The served agent's workspace + sessions (gateway/agent-scope.ts); undefined
|
|
204
|
+
// for the mock provider -> the bridge and recorder fall back to the legacy paths.
|
|
205
|
+
let bridgePaths;
|
|
206
|
+
let sessionsDir;
|
|
203
207
|
if (args.provider === 'mock') {
|
|
204
208
|
logger.info(TAG, 'Using MockProvider');
|
|
205
209
|
provider = new MockProvider();
|
|
@@ -227,6 +231,13 @@ async function main() {
|
|
|
227
231
|
logger.info(TAG, `Using GatewayProvider (url=${gwConfig.gatewayUrl}, symbol=${gwConfig.symbol})`);
|
|
228
232
|
provider = new GatewayProvider(gwConfig);
|
|
229
233
|
intelligenceUrlForWakes = gwConfig.intelligenceUrl;
|
|
234
|
+
if (gwConfig.agentWorkspaceDir && gwConfig.agentSessionsDir) {
|
|
235
|
+
bridgePaths = {
|
|
236
|
+
workspaceDir: gwConfig.agentWorkspaceDir,
|
|
237
|
+
sessionsJsonPath: join(gwConfig.agentSessionsDir, 'sessions.json'),
|
|
238
|
+
};
|
|
239
|
+
sessionsDir = gwConfig.agentSessionsDir;
|
|
240
|
+
}
|
|
230
241
|
}
|
|
231
242
|
// Create bridge
|
|
232
243
|
const connectorConfig = {
|
|
@@ -237,14 +248,19 @@ async function main() {
|
|
|
237
248
|
// same-box restart (instant takeover) vs a second box (rejected 4011).
|
|
238
249
|
instanceId: resolveRelayInstanceId(),
|
|
239
250
|
};
|
|
240
|
-
const bridge = new Bridge(provider, connectorConfig);
|
|
251
|
+
const bridge = new Bridge(provider, connectorConfig, bridgePaths);
|
|
241
252
|
// Shock-wake poller (WS3, docs/MARKET_ADAPTIVITY_PLAN.md) — watches intel's
|
|
242
253
|
// /api/shocks (the WS2 change-of-character flags) and delivers an
|
|
243
254
|
// out-of-band re-evaluation turn to the agent on a genuine market shift.
|
|
244
255
|
// Inert until the central gate agent_config.gates.shockWake leaves 'off'.
|
|
245
|
-
|
|
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
|
|
246
260
|
? new ShockWakePoller({ provider, token, intelligenceUrl: intelligenceUrlForWakes })
|
|
247
261
|
: null;
|
|
262
|
+
if (shockWakeOff)
|
|
263
|
+
logger.info(TAG, 'Shock-wake poller disabled (RC_SHOCK_WAKE=off)');
|
|
248
264
|
if (shockWake) {
|
|
249
265
|
// Delivery confirmation: any agent turn STARTING proves the main-session
|
|
250
266
|
// lane is alive — the gateway ack alone cannot (swallowed-turn class).
|
|
@@ -257,7 +273,7 @@ async function main() {
|
|
|
257
273
|
// (the mock has no OpenClaw sessions dir). Kill-switch: RC_HEARTBEAT_RECORDER=off.
|
|
258
274
|
const recorderOff = (process.env.RC_HEARTBEAT_RECORDER ?? 'on').trim().toLowerCase() === 'off';
|
|
259
275
|
const heartbeatRecorder = provider instanceof GatewayProvider && !recorderOff
|
|
260
|
-
? new HeartbeatRunRecorder({ source: provider, token })
|
|
276
|
+
? new HeartbeatRunRecorder({ source: provider, token, ...(sessionsDir ? { sessionsDir } : {}) })
|
|
261
277
|
: null;
|
|
262
278
|
if (recorderOff)
|
|
263
279
|
logger.info(TAG, 'Heartbeat flight recorder disabled (RC_HEARTBEAT_RECORDER=off)');
|
|
@@ -72,6 +72,11 @@ export interface StartOptions {
|
|
|
72
72
|
acknowledgeOpenPositions?: boolean;
|
|
73
73
|
/** Count of currently-open positions, as the skill sees them. */
|
|
74
74
|
openPositionCount: number;
|
|
75
|
+
/** The agent that owns the terminal. REQUIRED by OpenClaw 2026.9 when the
|
|
76
|
+
* gateway hosts several agents ("Multiple agents are configured, but this
|
|
77
|
+
* operation has no explicit owner"); omitted on a single-agent gateway so
|
|
78
|
+
* every existing box sends the byte-identical request. */
|
|
79
|
+
agentId?: string;
|
|
75
80
|
}
|
|
76
81
|
/**
|
|
77
82
|
* Guard the restart hazard. The installer restarts the gateway; with positions
|
|
@@ -192,7 +192,11 @@ export async function startConnectorUpdate(rpc, opts) {
|
|
|
192
192
|
}
|
|
193
193
|
let opened;
|
|
194
194
|
try {
|
|
195
|
-
opened = await rpc('terminal.open', {
|
|
195
|
+
opened = await rpc('terminal.open', {
|
|
196
|
+
cols: COLS,
|
|
197
|
+
rows: ROWS,
|
|
198
|
+
...(opts.agentId ? { agentId: opts.agentId } : {}),
|
|
199
|
+
});
|
|
196
200
|
}
|
|
197
201
|
catch (err) {
|
|
198
202
|
const outcome = describeOpenFailure(err);
|
|
@@ -45,6 +45,9 @@ export declare class GatewayProvider implements OpenClawProvider {
|
|
|
45
45
|
/** The OpenClaw agent this bridge serves: chat goes to it, and only its runs
|
|
46
46
|
* reach the dashboard (gateway/agent-scope.ts). */
|
|
47
47
|
private agentId;
|
|
48
|
+
/** The served agent's OpenClaw workspace (gateway-config.ts resolves it by
|
|
49
|
+
* OpenClaw's own rule); the legacy path for hand-built configs. */
|
|
50
|
+
private workspaceDir;
|
|
48
51
|
/** Emit the one-time rollout probe (gateway response shape) only on the first attempt. */
|
|
49
52
|
private loggedAgentIdentityProbe;
|
|
50
53
|
/** Last IDENTITY.md read (epoch ms) — TTL gate for the display-name re-read. */
|