@reefclaw/openclaw-plugin 0.1.33 → 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/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/gateway.js +40 -11
- package/bridge/providers/risk-calculator.d.ts +31 -0
- package/bridge/providers/risk-calculator.js +41 -1
- package/openclaw.plugin.json +1 -1
- package/package.json +1 -1
- package/release-notes.json +2 -1
|
@@ -27,12 +27,15 @@ export interface PollerCallbacks {
|
|
|
27
27
|
onCandle: (data: CandleData) => void;
|
|
28
28
|
/** Raw CCXT positions from fetch_positions — fires every 3s */
|
|
29
29
|
onPositions: (positions: CcxtPosition[]) => void;
|
|
30
|
-
/** Parsed balance from fetch_balance — fires every 10s
|
|
30
|
+
/** Parsed balance from fetch_balance — fires every 10s. `extras` carries the
|
|
31
|
+
* plugin-computed day figures that ride on the same response when present. */
|
|
31
32
|
onBalance: (balance: {
|
|
32
33
|
currency: string;
|
|
33
34
|
total: number;
|
|
34
35
|
available: number;
|
|
35
36
|
locked: number;
|
|
37
|
+
}, extras?: {
|
|
38
|
+
realizedPnlToday?: number;
|
|
36
39
|
}) => void;
|
|
37
40
|
/** Parsed open orders from fetch_open_orders — fires every 3s */
|
|
38
41
|
onOpenOrders: (orders: OrderData[]) => void;
|
|
@@ -134,6 +137,11 @@ export declare class Poller {
|
|
|
134
137
|
private pollOhlcv;
|
|
135
138
|
private pollPositions;
|
|
136
139
|
private pollBalance;
|
|
140
|
+
/** Poll positions NOW (same ban-gate + in-flight guard as the timer). The
|
|
141
|
+
* RED-zone guard calls this when the wallet/positions snapshot is torn by a
|
|
142
|
+
* fresh fill, so the tear closes in ~100 ms instead of waiting out the
|
|
143
|
+
* 10 s cadence (Ardi, report #6). No-op while paused/stopped/in-flight. */
|
|
144
|
+
refreshPositionsNow(): Promise<void>;
|
|
137
145
|
private pollOpenOrders;
|
|
138
146
|
private pollMarketStructure;
|
|
139
147
|
/**
|
package/bridge/gateway/poller.js
CHANGED
|
@@ -378,7 +378,17 @@ export class Poller {
|
|
|
378
378
|
const tool = this.toolMap.fetch_balance;
|
|
379
379
|
const result = await this.http.invoke(tool, {});
|
|
380
380
|
const balance = mapCcxtBalance(result.data, this.quoteCurrency);
|
|
381
|
-
|
|
381
|
+
const realized = result.data?.realizedPnlToday;
|
|
382
|
+
this.callbacks.onBalance(balance, typeof realized === 'number' && Number.isFinite(realized) ? { realizedPnlToday: realized } : undefined);
|
|
383
|
+
}
|
|
384
|
+
/** Poll positions NOW (same ban-gate + in-flight guard as the timer). The
|
|
385
|
+
* RED-zone guard calls this when the wallet/positions snapshot is torn by a
|
|
386
|
+
* fresh fill, so the tear closes in ~100 ms instead of waiting out the
|
|
387
|
+
* 10 s cadence (Ardi, report #6). No-op while paused/stopped/in-flight. */
|
|
388
|
+
refreshPositionsNow() {
|
|
389
|
+
if (!this.toolMap.fetch_positions)
|
|
390
|
+
return Promise.resolve();
|
|
391
|
+
return this.guardedExec('fetch_positions', () => this.pollPositions());
|
|
382
392
|
}
|
|
383
393
|
async pollOpenOrders() {
|
|
384
394
|
const tool = this.toolMap.fetch_open_orders;
|
|
@@ -22,6 +22,9 @@ export declare const MAX_PER_SCAN = 5;
|
|
|
22
22
|
export declare const MAX_POST_ATTEMPTS = 5;
|
|
23
23
|
/** Cool down `cron.runs` for this long after it errors (older gateway). */
|
|
24
24
|
export declare const CRON_RUNS_COOLDOWN_MS: number;
|
|
25
|
+
/** With nothing to read, ask `cron.runs` this often whether beats ran anyway
|
|
26
|
+
* (a store the recorder cannot read must not stay silent — Ardi, report #5). */
|
|
27
|
+
export declare const BLIND_PROBE_INTERVAL_MS: number;
|
|
25
28
|
export type { AgentRunLifecycleData };
|
|
26
29
|
/** What the recorder needs from the provider — kept narrow so it is trivially
|
|
27
30
|
* mockable and the provider stays the only thing that talks to the gateway. */
|
|
@@ -41,6 +44,9 @@ export interface HeartbeatRunRecorderOptions {
|
|
|
41
44
|
token: string;
|
|
42
45
|
webappUrl?: string;
|
|
43
46
|
sessionsDir?: string;
|
|
47
|
+
/** The agent database (OpenClaw >= 2026.9 transcript store); derived from
|
|
48
|
+
* `sessionsDir` when omitted. */
|
|
49
|
+
agentDbPath?: string;
|
|
44
50
|
stateFile?: string;
|
|
45
51
|
fetchImpl?: typeof fetch;
|
|
46
52
|
now?: () => number;
|
|
@@ -58,6 +64,7 @@ export interface PostOutcome {
|
|
|
58
64
|
export declare class HeartbeatRunRecorder {
|
|
59
65
|
private readonly opts;
|
|
60
66
|
private readonly sessionsDir;
|
|
67
|
+
private readonly agentDbPath;
|
|
61
68
|
private readonly stateFile;
|
|
62
69
|
private timer;
|
|
63
70
|
private kickTimer;
|
|
@@ -67,6 +74,9 @@ export declare class HeartbeatRunRecorder {
|
|
|
67
74
|
private readonly attempts;
|
|
68
75
|
private cronRunsUnavailableUntil;
|
|
69
76
|
private probeLogged;
|
|
77
|
+
private store;
|
|
78
|
+
private lastBlindProbeAt;
|
|
79
|
+
private blindWarned;
|
|
70
80
|
/** Counters for a one-line health summary in logs. */
|
|
71
81
|
readonly stats: {
|
|
72
82
|
scans: number;
|
|
@@ -78,6 +88,9 @@ export declare class HeartbeatRunRecorder {
|
|
|
78
88
|
};
|
|
79
89
|
constructor(opts: HeartbeatRunRecorderOptions);
|
|
80
90
|
private now;
|
|
91
|
+
/** Which store(s) are readable; logs on first sight and whenever it changes
|
|
92
|
+
* (the database appears when a gateway is upgraded under a running bridge). */
|
|
93
|
+
private detectStore;
|
|
81
94
|
start(): void;
|
|
82
95
|
stop(): void;
|
|
83
96
|
/** A cron-session turn ended → scan shortly (debounced). */
|
|
@@ -88,8 +101,13 @@ export declare class HeartbeatRunRecorder {
|
|
|
88
101
|
processed: number;
|
|
89
102
|
deferred: number;
|
|
90
103
|
}>;
|
|
91
|
-
/**
|
|
92
|
-
*
|
|
104
|
+
/** Nothing to read this scan — were there beats anyway? `cron.runs` knows;
|
|
105
|
+
* a finished, unrecorded run inside the window means the recorder cannot
|
|
106
|
+
* see the store it should be reading. Warn once per process. */
|
|
107
|
+
private probeBlind;
|
|
108
|
+
/** Is this session a heartbeat? Session key first (the database carries it),
|
|
109
|
+
* head marker second (cheap), trajectory key third (covers a prompt without
|
|
110
|
+
* the marker), else not a heartbeat. */
|
|
93
111
|
private classify;
|
|
94
112
|
private fetchCronRunsSafe;
|
|
95
113
|
/** POST one record to the webapp. Never throws. */
|
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
|
@@ -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).
|
|
@@ -16,7 +16,7 @@ import { EventParser, mapCcxtBalance, mapCcxtOrder, extractLiquidationFields, ex
|
|
|
16
16
|
import { Poller } from '../gateway/poller.js';
|
|
17
17
|
import { ensureHeartbeatCron, isHeartbeatLikeName } from '../gateway/heartbeat-cron.js';
|
|
18
18
|
import { parseIdentityName } from '../utils/identity-name.js';
|
|
19
|
-
import { computeEquity as _computeEquity, computePositionNotional as _computePositionNotional, computeRiskMetrics as _computeRiskMetrics, DEFAULT_RISK_LIMITS, DRAWDOWN_ZONE_THRESHOLDS, TENANT_LIMIT_BOUNDS, boundedNum, validateDrawdownLadder, } from './risk-calculator.js';
|
|
19
|
+
import { assessDrawdownPlausibility, computeEquity as _computeEquity, computePositionNotional as _computePositionNotional, computeRiskMetrics as _computeRiskMetrics, DEFAULT_RISK_LIMITS, DRAWDOWN_ZONE_THRESHOLDS, TENANT_LIMIT_BOUNDS, boundedNum, validateDrawdownLadder, } from './risk-calculator.js';
|
|
20
20
|
import { executeKill as _executeKill, executeFlatten as _executeFlatten, executePause as _executePause, executeResume as _executeResume, cancelPendingProposals, withProposalDetail, } from './emergency-commands.js';
|
|
21
21
|
import { executeSetTradingMode, executeGetBracketConfig, executeSetBracketRequirement, executeSetExchangeCredentials, executeTestExchangeCredentials, executeClearExchangeCredentials, executeProvisionHlAgentWallet, executeHlAgentWalletStatus, executeSubmitHlAgentApproval, } from './onboarding-commands.js';
|
|
22
22
|
import { startConnectorUpdate, runConnectorUpdate, openAdminGatewaySession, checkPositionGuard, describeUpdateDisabled, } from './connector-update.js';
|
|
@@ -1258,7 +1258,7 @@ export class GatewayProvider {
|
|
|
1258
1258
|
logger.error(TAG, `positions handler failed: ${formatError(err)}`);
|
|
1259
1259
|
});
|
|
1260
1260
|
},
|
|
1261
|
-
onBalance: (balance) => this.onPollerBalance(balance),
|
|
1261
|
+
onBalance: (balance, extras) => this.onPollerBalance(balance, extras),
|
|
1262
1262
|
onOpenOrders: (orders) => this.onPollerOpenOrders(orders),
|
|
1263
1263
|
onMarketStructure: (data) => this.onPollerMarketStructure(data),
|
|
1264
1264
|
onCryptoMetrics: (data) => this.onPollerCryptoMetrics(data),
|
|
@@ -1775,7 +1775,12 @@ export class GatewayProvider {
|
|
|
1775
1775
|
const action = isClose ? 'CLOSE' : 'OPEN';
|
|
1776
1776
|
this.emitTradeJournal(pos.symbol, side, action, quantity, fillPrice);
|
|
1777
1777
|
}
|
|
1778
|
-
onPollerBalance(balance) {
|
|
1778
|
+
onPollerBalance(balance, extras) {
|
|
1779
|
+
// Keep today's realized P&L as fresh as the wallet: the RED-zone
|
|
1780
|
+
// plausibility bound (assessDrawdownPlausibility) needs it on every
|
|
1781
|
+
// evaluation, and fetchFreshBalance() only runs on a reconnect snapshot.
|
|
1782
|
+
if (typeof extras?.realizedPnlToday === 'number')
|
|
1783
|
+
this.realizedPnlToday = extras.realizedPnlToday;
|
|
1779
1784
|
// Defensive guard: never downgrade a known-good wallet balance to zero.
|
|
1780
1785
|
// Binance Futures 429 rate-limits were causing fetchBalance responses
|
|
1781
1786
|
// to come back with an empty currency map; mapCcxtBalance then returned
|
|
@@ -2577,10 +2582,13 @@ export class GatewayProvider {
|
|
|
2577
2582
|
// only — a $186 account with a $20 short showed as -89% drawdown, triggering
|
|
2578
2583
|
// an auto-flatten loop every minute. If we don't have fresh wallet data we
|
|
2579
2584
|
// cannot trust the drawdown number; wait for the next poll.
|
|
2580
|
-
// 3.
|
|
2581
|
-
//
|
|
2582
|
-
//
|
|
2583
|
-
//
|
|
2585
|
+
// 3. Plausibility bound (Ardi, report #6 — replaces the old "-50% feels
|
|
2586
|
+
// impossible" constant): a book cannot lose more than what is open
|
|
2587
|
+
// (at entry) plus what it already realized today. A claimed loss
|
|
2588
|
+
// beyond that is a calculation artifact — log loudly and refuse
|
|
2589
|
+
// instead of closing real positions on it. True at every account
|
|
2590
|
+
// size, paper and live alike; the -50% constant only remains as the
|
|
2591
|
+
// fallback while today's realized P&L is still unknown.
|
|
2584
2592
|
// 4. Persistence debounce (issue #213): the balance poll and the position
|
|
2585
2593
|
// snapshot are not atomic. In PAPER mode the simulator deducts FULL
|
|
2586
2594
|
// NOTIONAL from the wallet at open, so in the seconds after a fill the
|
|
@@ -2629,19 +2637,40 @@ export class GatewayProvider {
|
|
|
2629
2637
|
// component is the worse failure direction, so the tear only ever BUYS
|
|
2630
2638
|
// TIME; past the ceiling the ordinary #213 debounce governs again.
|
|
2631
2639
|
const tornSnapshotBlocks = !positionsCoverLatestFill && redForMs < MAX_TORN_SNAPSHOT_DEFER_MS;
|
|
2640
|
+
// Ardi #6: the claimed loss versus what THIS book could have lost —
|
|
2641
|
+
// computed from the same snapshot, so a torn one (missing notional)
|
|
2642
|
+
// shows up as a loss the known positions cannot explain.
|
|
2643
|
+
const plausibility = assessDrawdownPlausibility({
|
|
2644
|
+
sessionStartNav: this.sessionStartNav,
|
|
2645
|
+
equity: this.computeEquity(),
|
|
2646
|
+
positions: this.positions,
|
|
2647
|
+
realizedPnlToday: this.realizedPnlToday,
|
|
2648
|
+
});
|
|
2649
|
+
const impossibleForBook = plausibility.verdict === 'impossible' ||
|
|
2650
|
+
(plausibility.verdict === 'unknown' && metrics.utilization.dailyDrawdown < IMPOSSIBLE_DRAWDOWN);
|
|
2632
2651
|
if (uptimeMs < STARTUP_GRACE_PERIOD_MS) {
|
|
2633
2652
|
logger.warn(TAG, `RED zone drawdown detected (${metrics.drawdownZoneMessage}) but within startup grace period (${Math.round(uptimeMs / 1000)}s) — skipping auto-flatten`);
|
|
2634
2653
|
}
|
|
2635
2654
|
else if (!this.hasReceivedBalance || this.balance.total <= 0) {
|
|
2636
2655
|
logger.warn(TAG, `RED zone drawdown detected (${metrics.drawdownZoneMessage}) but balance data is stale/missing (received=${this.hasReceivedBalance}, total=${this.balance.total}) — skipping auto-flatten, waiting for fresh wallet data`);
|
|
2637
2656
|
}
|
|
2638
|
-
else if (
|
|
2639
|
-
|
|
2657
|
+
else if (tornSnapshotBlocks) {
|
|
2658
|
+
// The snapshot is torn BY DEFINITION (a fill debited the wallet after
|
|
2659
|
+
// the last positions refresh) — the verdict is not evidence of
|
|
2660
|
+
// anything yet. Close the tear now instead of waiting out the 10 s
|
|
2661
|
+
// poll, and say so at info: this is the expected paper fill race,
|
|
2662
|
+
// not an alarm (it read as one — Ardi #6).
|
|
2663
|
+
logger.info(TAG, `RED verdict on a torn snapshot (${metrics.drawdownZoneMessage}; fill ${Math.round((Date.now() - this.lastFillAt) / 1000)}s ago, positions from ${Math.round((Date.now() - this.positionsUpdatedAt) / 1000)}s ago) — refreshing positions before judging it`);
|
|
2664
|
+
void this.poller?.refreshPositionsNow().catch((err) => {
|
|
2665
|
+
logger.debug(TAG, `positions refresh after torn snapshot failed: ${formatError(err)}`);
|
|
2666
|
+
});
|
|
2667
|
+
}
|
|
2668
|
+
else if (impossibleForBook) {
|
|
2669
|
+
logger.error(TAG, `RED zone drawdown ${(metrics.utilization.dailyDrawdown * 100).toFixed(1)}% is more than this book could have lost (claimed ${plausibility.claimedLossUsd.toFixed(2)} vs open-at-entry ${plausibility.entryGrossUsd.toFixed(2)} + realized-today ${plausibility.realizedLossUsd?.toFixed(2) ?? 'unknown'}${plausibility.verdict === 'unknown' ? `; sanity floor ${IMPOSSIBLE_DRAWDOWN * 100}%` : ''}) — refusing auto-flatten, equity input is wrong (balance.total=${this.balance.total}, sessionStartNav=${this.sessionStartNav}, positions=${this.positions.length})`);
|
|
2640
2670
|
}
|
|
2641
2671
|
else if (this.redZoneStreak < REQUIRED_RED_STREAK ||
|
|
2642
2672
|
redForMs < MIN_RED_PERSISTENCE_MS ||
|
|
2643
|
-
!survivedPositionsRefresh
|
|
2644
|
-
tornSnapshotBlocks) {
|
|
2673
|
+
!survivedPositionsRefresh) {
|
|
2645
2674
|
logger.warn(TAG, `RED zone drawdown detected (${metrics.drawdownZoneMessage}) — deferring auto-flatten until the verdict persists (streak ${this.redZoneStreak}/${REQUIRED_RED_STREAK}, ${Math.round(redForMs / 1000)}s/${MIN_RED_PERSISTENCE_MS / 1000}s, survivedPositionsRefresh=${survivedPositionsRefresh}, positionsCoverLatestFill=${positionsCoverLatestFill}, tornSnapshotBlocks=${tornSnapshotBlocks}). A fresh entry's notional reads as phantom drawdown until the position snapshot catches up (issues #213/#248); a real drawdown will persist and flatten on a later evaluation.`);
|
|
2646
2675
|
}
|
|
2647
2676
|
else {
|
|
@@ -102,6 +102,37 @@ export declare function applyVolatilityAdjustment(baseLimits: RiskLimits, volFac
|
|
|
102
102
|
export declare function getDrawdownZone(drawdownRatio: number, thresholds?: DrawdownThresholds): DrawdownZone;
|
|
103
103
|
/** Human-readable message for a drawdown zone. */
|
|
104
104
|
export declare function getDrawdownZoneMessage(zone: DrawdownZone, ratio: number): string;
|
|
105
|
+
export interface DrawdownPlausibility {
|
|
106
|
+
/** 'impossible' = the claimed loss exceeds what this book could have lost;
|
|
107
|
+
* 'unknown' = no session anchor or today's realized P&L not known yet. */
|
|
108
|
+
verdict: 'plausible' | 'impossible' | 'unknown';
|
|
109
|
+
claimedLossUsd: number;
|
|
110
|
+
/** Σ |contracts| × contractSize × entryPrice — what computeEquity adds back. */
|
|
111
|
+
entryGrossUsd: number;
|
|
112
|
+
realizedLossUsd: number | null;
|
|
113
|
+
boundUsd: number | null;
|
|
114
|
+
}
|
|
115
|
+
/** Fees, funding and mark noise on the open book — the bound is not exact. A
|
|
116
|
+
* torn snapshot is missing a whole entry's notional (≥ the 2.5% RED threshold
|
|
117
|
+
* of NAV by construction), so 1% of NAV of slack cannot hide one. */
|
|
118
|
+
export declare const PLAUSIBILITY_SLACK_RATIO = 0.01;
|
|
119
|
+
/**
|
|
120
|
+
* Can this book have lost what the drawdown claims? Without leverage a
|
|
121
|
+
* position cannot lose more than its ENTRY notional (a long can go to zero; a
|
|
122
|
+
* short past +100% is stopped by brackets long before), and what is no longer
|
|
123
|
+
* open can only have contributed what was realized today. Anything beyond
|
|
124
|
+
* `entryGross + realizedLoss` was never lost — it is notional the snapshot does
|
|
125
|
+
* not know about (paper debits full notional at open; positions catch up on
|
|
126
|
+
* their own poll). Entry notional, NOT mark: a long that has fallen far has a
|
|
127
|
+
* mark notional smaller than its own loss and would be refused wrongly.
|
|
128
|
+
* Refuse-only by construction: this can never license a flatten.
|
|
129
|
+
*/
|
|
130
|
+
export declare function assessDrawdownPlausibility(i: {
|
|
131
|
+
sessionStartNav: number;
|
|
132
|
+
equity: number;
|
|
133
|
+
positions: CcxtPosition[];
|
|
134
|
+
realizedPnlToday: number | null | undefined;
|
|
135
|
+
}): DrawdownPlausibility;
|
|
105
136
|
/**
|
|
106
137
|
* Compute true equity: wallet + entry_notional (margin held) + unrealized P&L per position.
|
|
107
138
|
*
|
|
@@ -140,9 +140,49 @@ export function getDrawdownZoneMessage(zone, ratio) {
|
|
|
140
140
|
case 'GREEN': return `Green zone (${pct}%) — full trading`;
|
|
141
141
|
case 'YELLOW': return `Yellow zone (${pct}%) — position sizes halved`;
|
|
142
142
|
case 'ORANGE': return `Orange zone (${pct}%) — new entries blocked, exits only`;
|
|
143
|
-
|
|
143
|
+
// The bridge's zone ARMS the auto-flatten; entry rejection is the plugin's
|
|
144
|
+
// own pre-trade zone (plugin/src/risk/pre-trade-check.ts), computed from
|
|
145
|
+
// its consistent equity. "all orders rejected" here read as an event that
|
|
146
|
+
// never happened (Ardi, report #6).
|
|
147
|
+
case 'RED': return `Red zone (${pct}%) — auto-flatten armed`;
|
|
144
148
|
}
|
|
145
149
|
}
|
|
150
|
+
/** Fees, funding and mark noise on the open book — the bound is not exact. A
|
|
151
|
+
* torn snapshot is missing a whole entry's notional (≥ the 2.5% RED threshold
|
|
152
|
+
* of NAV by construction), so 1% of NAV of slack cannot hide one. */
|
|
153
|
+
export const PLAUSIBILITY_SLACK_RATIO = 0.01;
|
|
154
|
+
/**
|
|
155
|
+
* Can this book have lost what the drawdown claims? Without leverage a
|
|
156
|
+
* position cannot lose more than its ENTRY notional (a long can go to zero; a
|
|
157
|
+
* short past +100% is stopped by brackets long before), and what is no longer
|
|
158
|
+
* open can only have contributed what was realized today. Anything beyond
|
|
159
|
+
* `entryGross + realizedLoss` was never lost — it is notional the snapshot does
|
|
160
|
+
* not know about (paper debits full notional at open; positions catch up on
|
|
161
|
+
* their own poll). Entry notional, NOT mark: a long that has fallen far has a
|
|
162
|
+
* mark notional smaller than its own loss and would be refused wrongly.
|
|
163
|
+
* Refuse-only by construction: this can never license a flatten.
|
|
164
|
+
*/
|
|
165
|
+
export function assessDrawdownPlausibility(i) {
|
|
166
|
+
let entryGrossUsd = 0;
|
|
167
|
+
for (const pos of i.positions) {
|
|
168
|
+
entryGrossUsd += Math.abs(pos.contracts ?? 0) * (pos.contractSize ?? 1) * (pos.entryPrice ?? 0);
|
|
169
|
+
}
|
|
170
|
+
const claimedLossUsd = i.sessionStartNav > 0 ? Math.max(0, i.sessionStartNav - i.equity) : 0;
|
|
171
|
+
const realizedKnown = typeof i.realizedPnlToday === 'number' && Number.isFinite(i.realizedPnlToday);
|
|
172
|
+
if (i.sessionStartNav <= 0 || !realizedKnown) {
|
|
173
|
+
return { verdict: 'unknown', claimedLossUsd, entryGrossUsd, realizedLossUsd: null, boundUsd: null };
|
|
174
|
+
}
|
|
175
|
+
const realizedLossUsd = Math.max(0, -i.realizedPnlToday);
|
|
176
|
+
const boundUsd = entryGrossUsd + realizedLossUsd;
|
|
177
|
+
const slack = i.sessionStartNav * PLAUSIBILITY_SLACK_RATIO;
|
|
178
|
+
return {
|
|
179
|
+
verdict: claimedLossUsd > boundUsd + slack ? 'impossible' : 'plausible',
|
|
180
|
+
claimedLossUsd,
|
|
181
|
+
entryGrossUsd,
|
|
182
|
+
realizedLossUsd,
|
|
183
|
+
boundUsd,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
146
186
|
// ---- Pure functions ----
|
|
147
187
|
/**
|
|
148
188
|
* Compute true equity: wallet + entry_notional (margin held) + unrealized P&L per position.
|
package/openclaw.plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"id": "reefclaw-paper-trading",
|
|
3
3
|
"name": "ReefClaw Trading",
|
|
4
|
-
"version": "0.1.
|
|
4
|
+
"version": "0.1.34",
|
|
5
5
|
"description": "Supervised trading plugin for the ReefClaw dashboard. It runs on YOUR machine and starts in PAPER mode with no API keys. It cannot trade real funds until you supply exchange credentials and step PAPER→MICRO_LIVE→LIVE yourself from the dashboard — the agent cannot make that change (the tool is refused without operator provenance). Exchange keys stay local, are used only to sign requests to the exchange, and are never transmitted to ReefClaw (asserted by a test in this package). Trading telemetry — positions, fills, decision journal — is sent to ReefClaw to render the dashboard. Every live position carries exchange-native protective stops. Remote updates to the agent's trading instructions are applied only after an Ed25519 signature is verified against a public key pinned in this build.",
|
|
6
6
|
"author": "ReefClaw",
|
|
7
7
|
"activation": {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@reefclaw/openclaw-plugin",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.34",
|
|
4
4
|
"description": "ReefClaw supervised trading plugin for OpenClaw. Runs entirely on YOUR machine and starts in PAPER mode — it cannot trade real funds until you supply exchange credentials and walk the PAPER→MICRO_LIVE→LIVE ladder yourself from the ReefClaw dashboard (the agent cannot make that change; it is refused without operator provenance). Your exchange API keys stay on your machine to sign requests to the exchange and are NEVER sent to ReefClaw — a test in the package asserts this. What does reach ReefClaw is trading telemetry for the dashboard (positions, fills, decision journal). Live trading always carries exchange-native protective stops. Trading instructions can be updated remotely, and every update must carry a valid Ed25519 signature verified against a key pinned in this build before it is applied. Install: npx --yes @reefclaw/connect, or from ClawHub on OpenClaw 2026.8.1+ (Control UI Plugins > Discover, or /plugins install clawhub:@reefclaw/openclaw-plugin then the same with --accept-capabilities after reviewing the listed capabilities)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "index.js",
|
package/release-notes.json
CHANGED
|
@@ -4,5 +4,6 @@
|
|
|
4
4
|
"0.1.28": "Fixes the connector's gateway handshake on OpenClaw 2026.9+ (it now connects as OpenClaw's local-backend client) and adds in-app update notices with one-click updates.",
|
|
5
5
|
"0.1.29": "Paper stop and target fills now use the price the decision was made on when the cached order book is stale (paper P&L gets more honest); on a gateway with several agents the connector shows only its own agent's runs; one-click updates can be switched off per box.",
|
|
6
6
|
"0.1.30": "Restores the connector's version reporting, so the dashboard's update notice works again for boxes that already updated (0.1.28 and 0.1.29 reported no version and could not be nudged).",
|
|
7
|
-
"0.1.33": "Adds npx @reefclaw/connect --agent <id> for gateways that host several agents: the trading skill, heartbeat and dashboard attach to that agent and the trading tools are denied to the others."
|
|
7
|
+
"0.1.33": "Adds npx @reefclaw/connect --agent <id> for gateways that host several agents: the trading skill, heartbeat and dashboard attach to that agent and the trading tools are denied to the others.",
|
|
8
|
+
"0.1.34": "The heartbeat flight recorder now reads OpenClaw 2026.9's SQLite transcript store (it recorded nothing on those gateways) and warns when it cannot see beats; a RED-zone drawdown is re-checked on a fresh position snapshot before it is judged, and a loss larger than the open book plus today's realized losses is refused as a calculation error instead of trusting a -50% constant; RC_SHOCK_WAKE=off switches shock wakes off per box; the README lists what the connector sends and how to read the risk log."
|
|
8
9
|
}
|