@reefclaw/openclaw-plugin 0.1.51 → 0.1.53

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.
@@ -24,10 +24,17 @@
24
24
  //
25
25
  // Deliberately NOT recorded: shock wakes and operator chat turns (they run in
26
26
  // the main session, whose transcript is one long file). Heartbeats only.
27
+ // ★ And only ReefClaw's cron jobs (isReefclawCronJob): every other automation
28
+ // on the user's OpenClaw — its own memory job, the user's reminders — is
29
+ // skipped for good, never built into a record, shown on the dashboard or
30
+ // uploaded (and when cron.list knows the job, never read past the head).
31
+ // Until 2026-10-22 every cron session was recorded, and a customer's nightly
32
+ // memory job reached our database with their private notes.
33
+ import { isReefclawCronJob, isReefclawCronRun } from './gateway/heartbeat-cron.js';
27
34
  import { logger } from './logger.js';
28
35
  import { resolveWebappBaseUrl } from './utils/base-url.js';
29
36
  import { noteWebappResponse, webappEdgeTracker, webappUserAgent } from './utils/webapp-edge.js';
30
- import { buildHeartbeatRunRecord, describeTranscriptStore, isCronSessionKey, listAllSessionCandidates, readCandidateCronMarker, readSession, resolveAgentDbPath, resolveSessionsDir, shrinkRecord, } from './heartbeat-transcript.js';
37
+ import { buildHeartbeatRunRecord, cronJobIdFromKey, describeTranscriptStore, isCronSessionKey, listAllSessionCandidates, readCandidateCronMarker, readSession, resolveAgentDbPath, resolveSessionsDir, shrinkRecord, } from './heartbeat-transcript.js';
31
38
  import { defaultStateFile, loadState, markRecorded, saveState } from './heartbeat-runs-state.js';
32
39
  const TAG = 'heartbeat-runs';
33
40
  /** Regular scan cadence. */
@@ -47,6 +54,9 @@ export const SCAN_SLACK_MS = 15 * 60_000;
47
54
  export const BOOTSTRAP_LOOKBACK_MS = 6 * 60 * 60_000;
48
55
  /** Records processed per scan (bounds CPU + POST burst on a backfill). */
49
56
  export const MAX_PER_SCAN = 5;
57
+ /** Transcripts parsed per scan, recorded or skipped (bounds a backfill of
58
+ * the user's own frequent jobs when cron.list can't name them). */
59
+ export const MAX_PARSES_PER_SCAN = 20;
50
60
  /** Give up on a run after this many failed POST cycles. */
51
61
  export const MAX_POST_ATTEMPTS = 5;
52
62
  /** While the bridge's edge gate is closed a record is DEFERRED (no attempt
@@ -76,8 +86,10 @@ export class HeartbeatRunRecorder {
76
86
  store = null;
77
87
  lastBlindProbeAt;
78
88
  blindWarned = false;
89
+ /** Non-ReefClaw jobs already logged as skipped (one line per job). */
90
+ foreignJobsLogged = new Set();
79
91
  /** Counters for a one-line health summary in logs. */
80
- stats = { scans: 0, recorded: 0, posted: 0, postFailed: 0, skippedNonCron: 0, deferred: 0 };
92
+ stats = { scans: 0, recorded: 0, posted: 0, postFailed: 0, skippedNonCron: 0, skippedForeign: 0, deferred: 0 };
81
93
  constructor(opts) {
82
94
  this.opts = opts;
83
95
  this.sessionsDir = opts.sessionsDir ?? resolveSessionsDir();
@@ -165,6 +177,8 @@ export class HeartbeatRunRecorder {
165
177
  if (candidates.length === 0)
166
178
  await this.probeBlind(now, since, state);
167
179
  let cronRuns; // undefined = not fetched yet
180
+ let cronJobs; // same
181
+ let parses = 0;
168
182
  let dirty = false;
169
183
  for (const c of candidates) {
170
184
  if (processed >= MAX_PER_SCAN) {
@@ -182,6 +196,18 @@ export class HeartbeatRunRecorder {
182
196
  deferred++;
183
197
  continue;
184
198
  }
199
+ // ReefClaw's runs only: the user's own automations are skipped for
200
+ // good — never built into a record, shown or posted, and when
201
+ // cron.list knows the job, never read past the head.
202
+ if (cronJobs === undefined)
203
+ cronJobs = await this.fetchCronJobsSafe();
204
+ const headJobId = cronJobIdFromKey(c.sessionKey) ?? readCandidateCronMarker(c)?.jobId ?? null;
205
+ const knownJob = headJobId ? cronJobs?.get(headJobId) : undefined;
206
+ if (knownJob && !isReefclawCronJob(knownJob)) {
207
+ this.skipForeign(state, c.sessionId, headJobId);
208
+ dirty = true;
209
+ continue;
210
+ }
185
211
  // Edge-denied host (the bridge's own backoff, skill/src/utils/
186
212
  // webapp-edge.ts): posting would be one more 403 feeding the block
187
213
  // and would burn an attempt. Defer without counting — and BEFORE the
@@ -197,11 +223,28 @@ export class HeartbeatRunRecorder {
197
223
  continue;
198
224
  }
199
225
  }
226
+ // Bound the synchronous parsing per scan: skipped runs don't count
227
+ // toward MAX_PER_SCAN, and a frequent job of the user's would
228
+ // otherwise be parsed in bulk on a backfill.
229
+ if (parses >= MAX_PARSES_PER_SCAN) {
230
+ deferred++;
231
+ continue;
232
+ }
233
+ parses++;
200
234
  const parsed = readSession(c);
201
235
  if (!parsed) {
202
236
  deferred++;
203
237
  continue;
204
238
  }
239
+ if (!knownJob) {
240
+ // Job unknown to cron.list: the run's own marker name / prompt decide.
241
+ const run = this.judgeRun(c, parsed, cronJobs);
242
+ if (!run.ours) {
243
+ this.skipForeign(state, c.sessionId, run.jobId);
244
+ dirty = true;
245
+ continue;
246
+ }
247
+ }
205
248
  const { transcript, trajectory } = parsed;
206
249
  const finished = transcript.complete || trajectory?.ended != null;
207
250
  if (!finished && now - c.mtimeMs < INCOMPLETE_AFTER_MS) {
@@ -220,7 +263,7 @@ export class HeartbeatRunRecorder {
220
263
  mode: this.opts.source.getTradingBook(),
221
264
  fallbackStartedAtMs: c.mtimeMs,
222
265
  });
223
- record = shrinkRecord(record);
266
+ record = { ...shrinkRecord(record), reefclawJob: true };
224
267
  try {
225
268
  this.opts.source.noteHeartbeatRun(record);
226
269
  }
@@ -229,7 +272,14 @@ export class HeartbeatRunRecorder {
229
272
  }
230
273
  const outcome = await this.post(record);
231
274
  processed++;
232
- if (outcome.ok) {
275
+ if (outcome.ok && outcome.skipped) {
276
+ markRecorded(state, c.sessionId);
277
+ this.attempts.delete(c.sessionId);
278
+ this.firstAttemptAt.delete(c.sessionId);
279
+ dirty = true;
280
+ logger.warn(TAG, `Heartbeat run ${c.sessionId.slice(0, 8)} NOT stored by the webapp (${outcome.skipped}) — shown on the dashboard, not in the journal`);
281
+ }
282
+ else if (outcome.ok) {
233
283
  this.stats.posted++;
234
284
  this.stats.recorded++;
235
285
  markRecorded(state, c.sessionId);
@@ -320,6 +370,48 @@ export class HeartbeatRunRecorder {
320
370
  }
321
371
  return marker ? 'cron' : 'not-cron';
322
372
  }
373
+ /** Does this cron run belong to a ReefClaw job? The live job definition
374
+ * decides when cron.list has it (the job id may only be in the trajectory
375
+ * key); otherwise the run's marker name, else its prompt. */
376
+ judgeRun(c, parsed, jobs) {
377
+ const { transcript, trajectory } = parsed;
378
+ const jobId = cronJobIdFromKey(c.sessionKey) ?? transcript.cron?.jobId ?? cronJobIdFromKey(trajectory?.sessionKey);
379
+ const job = jobId ? jobs?.get(jobId) : undefined;
380
+ const ours = job
381
+ ? isReefclawCronJob(job)
382
+ : isReefclawCronRun({ jobName: transcript.cron?.jobName ?? null, prompt: transcript.firstUserText });
383
+ return { ours, jobId };
384
+ }
385
+ /** Mark a non-ReefClaw run done for good (one log line per job). */
386
+ skipForeign(state, sessionId, jobId) {
387
+ markRecorded(state, sessionId);
388
+ this.attempts.delete(sessionId);
389
+ this.firstAttemptAt.delete(sessionId);
390
+ this.stats.skippedForeign++;
391
+ const key = jobId ?? sessionId;
392
+ if (this.foreignJobsLogged.has(key))
393
+ return;
394
+ this.foreignJobsLogged.add(key);
395
+ logger.info(TAG, `Not recording cron job ${key.slice(0, 8)}: not a ReefClaw automation (only ReefClaw heartbeats are recorded)`);
396
+ }
397
+ async fetchCronJobsSafe() {
398
+ if (!this.opts.source.fetchCronJobs)
399
+ return null;
400
+ try {
401
+ const jobs = await this.opts.source.fetchCronJobs();
402
+ if (!jobs)
403
+ return null;
404
+ const byId = new Map();
405
+ for (const j of jobs)
406
+ if (typeof j?.id === 'string' && j.id)
407
+ byId.set(j.id, j);
408
+ return byId;
409
+ }
410
+ catch (err) {
411
+ logger.debug(TAG, `cron.list failed: ${err instanceof Error ? err.message : String(err)}`);
412
+ return null;
413
+ }
414
+ }
323
415
  async fetchCronRunsSafe(now) {
324
416
  if (now < this.cronRunsUnavailableUntil)
325
417
  return null;
@@ -359,7 +451,16 @@ export class HeartbeatRunRecorder {
359
451
  });
360
452
  if (res.ok) {
361
453
  noteWebappResponse(res, '/api/internal/heartbeat-runs', undefined, startedAt);
362
- return { ok: true, terminal: false, status: res.status };
454
+ let skipped;
455
+ try {
456
+ const j = (await res.json());
457
+ if (typeof j?.skipped === 'string')
458
+ skipped = j.skipped;
459
+ }
460
+ catch {
461
+ /* not JSON — a plain success */
462
+ }
463
+ return { ok: true, terminal: false, status: res.status, ...(skipped ? { skipped } : {}) };
363
464
  }
364
465
  let text = '';
365
466
  try {
@@ -46,6 +46,9 @@ export interface HeartbeatTokens {
46
46
  export interface HeartbeatRunRecord {
47
47
  /** The isolated cron session id — one per beat, the idempotency key. */
48
48
  runId: string;
49
+ /** Set by a bridge that already judged the run's job to be ReefClaw's
50
+ * (heartbeat-runs.ts); the webapp trusts it over its own heuristics. */
51
+ reefclawJob?: true;
49
52
  cronJobId: string | null;
50
53
  cronJobName: string | null;
51
54
  trigger: 'cron' | 'unknown';
@@ -130,6 +133,12 @@ export interface SqliteModule {
130
133
  export declare function loadSqlite(): SqliteModule | null;
131
134
  /** Test seam: swap the loader (pass null to simulate a Node without node:sqlite). */
132
135
  export declare function setSqliteLoaderForTests(loader: (() => SqliteModule | null) | null): void;
136
+ /** One `transcript_events.event_zstd` value back to the JSON line it holds. */
137
+ export type ZstdDecompress = (compressed: Uint8Array) => string;
138
+ /** The zstd decompressor, or null when this Node has none. Cached. */
139
+ export declare function loadZstd(): ZstdDecompress | null;
140
+ /** Test seam: swap the loader (null restores the real one). */
141
+ export declare function setZstdLoaderForTests(loader: (() => ZstdDecompress | null) | null): void;
133
142
  export type TranscriptStoreKind = 'sqlite' | 'sqlite-unsupported' | 'jsonl';
134
143
  export interface TranscriptStoreInfo {
135
144
  kind: TranscriptStoreKind;
@@ -200,6 +209,10 @@ export interface ParsedTranscript {
200
209
  headerAtMs: number | null;
201
210
  cron: CronMarker | null;
202
211
  firstUserAtMs: number | null;
212
+ /** The first user message (the cron job's prompt), clipped. Used only to
213
+ * tell ReefClaw's runs from the user's own automations — never part of a
214
+ * record, never uploaded. */
215
+ firstUserText: string | null;
203
216
  lastAtMs: number | null;
204
217
  toolCalls: HeartbeatToolCall[];
205
218
  /** Total calls seen (may exceed toolCalls.length once the cap trims). */
@@ -249,6 +262,8 @@ export interface ParsedTrajectory {
249
262
  }
250
263
  export declare function parseTrajectory(text: string): ParsedTrajectory;
251
264
  export declare function isCronSessionKey(key: string | null | undefined): boolean;
265
+ /** The job id in a cron session key (`agent:<agentId>:cron:<jobId>:run:<sessionId>`). */
266
+ export declare function cronJobIdFromKey(key: string | null | undefined): string | null;
252
267
  export interface BuildRecordInput {
253
268
  sessionId: string;
254
269
  transcript: ParsedTranscript;
@@ -129,6 +129,32 @@ export function setSqliteLoaderForTests(loader) {
129
129
  sqliteLoader = loader ?? (() => createRequire(import.meta.url)('node:sqlite'));
130
130
  sqliteModule = undefined;
131
131
  }
132
+ const realZstdLoader = () => {
133
+ try {
134
+ // zlib.zstdDecompressSync: Node >= 22.15 / 23.8, so every Node an
135
+ // OpenClaw >= 2026.9.3 runs on (24). Looked up at runtime so an older
136
+ // Node only loses the compressed rows instead of failing at import.
137
+ const zlib = createRequire(import.meta.url)('node:zlib');
138
+ const fn = zlib.zstdDecompressSync;
139
+ return typeof fn === 'function' ? (buf) => fn(buf).toString('utf8') : null;
140
+ }
141
+ catch {
142
+ return null;
143
+ }
144
+ };
145
+ let zstdDecompress;
146
+ let zstdLoader = realZstdLoader;
147
+ /** The zstd decompressor, or null when this Node has none. Cached. */
148
+ export function loadZstd() {
149
+ if (zstdDecompress === undefined)
150
+ zstdDecompress = zstdLoader();
151
+ return zstdDecompress;
152
+ }
153
+ /** Test seam: swap the loader (null restores the real one). */
154
+ export function setZstdLoaderForTests(loader) {
155
+ zstdLoader = loader ?? realZstdLoader;
156
+ zstdDecompress = undefined;
157
+ }
132
158
  function openReadOnly(dbPath) {
133
159
  // existsSync first: a pre-2026.9 box never even loads node:sqlite (and its
134
160
  // one-time ExperimentalWarning on Node 22/24 stays out of that journal).
@@ -287,12 +313,42 @@ const SQLITE_HEAD_EVENTS = 20;
287
313
  export function readCandidateCronMarker(c) {
288
314
  if (c.source === 'jsonl')
289
315
  return readCronMarker(c.file);
290
- return withDb(c.file, undefined, (db) => {
291
- const rows = db
292
- .prepare('SELECT event_json AS e FROM transcript_events WHERE session_id = ? ORDER BY seq LIMIT ?')
293
- .all(c.sessionId, SQLITE_HEAD_EVENTS);
294
- return markerInLines(rows.map((r) => (typeof r.e === 'string' ? r.e : '')));
295
- });
316
+ return withDb(c.file, undefined, (db) => markerInLines(transcriptLines(db, c.sessionId, SQLITE_HEAD_EVENTS).lines));
317
+ }
318
+ /**
319
+ * A session's transcript rows as JSON lines, in seq order. ★ OpenClaw >=
320
+ * 2026.9.6 keeps a large event ONLY compressed — event_json NULL, the line in
321
+ * event_zstd. Reading event_json alone dropped ~40% of every beat, tool calls
322
+ * and the final report among them, so a finished beat looked unfinished
323
+ * (canary, 2026-10-24: 15 of 32 calls seen, the run recorded `incomplete`).
324
+ * Older stores have no event_zstd column. `unread` = compressed rows this
325
+ * Node could not decode (no zstd, or a bad blob).
326
+ */
327
+ function transcriptLines(db, sessionId, limit) {
328
+ const compressedStore = db.prepare('PRAGMA table_info(transcript_events)').all().some((col) => col.name === 'event_zstd');
329
+ const sql = `SELECT event_json AS e${compressedStore ? ', event_zstd AS z' : ''} FROM transcript_events WHERE session_id = ? ORDER BY seq${limit ? ' LIMIT ?' : ''}`;
330
+ const rows = (limit ? db.prepare(sql).all(sessionId, limit) : db.prepare(sql).all(sessionId));
331
+ const decompress = compressedStore ? loadZstd() : null;
332
+ const lines = [];
333
+ let unread = 0;
334
+ for (const r of rows) {
335
+ if (typeof r.e === 'string' && r.e) {
336
+ lines.push(r.e);
337
+ }
338
+ else if (r.z instanceof Uint8Array && r.z.length > 0) {
339
+ try {
340
+ const line = decompress ? decompress(r.z) : '';
341
+ if (line)
342
+ lines.push(line);
343
+ else
344
+ unread++;
345
+ }
346
+ catch {
347
+ unread++;
348
+ }
349
+ }
350
+ }
351
+ return { lines, unread };
296
352
  }
297
353
  function markerInLines(lines) {
298
354
  for (const line of lines) {
@@ -411,6 +467,7 @@ export function parseSessionTranscript(text) {
411
467
  headerAtMs: null,
412
468
  cron: null,
413
469
  firstUserAtMs: null,
470
+ firstUserText: null,
414
471
  lastAtMs: null,
415
472
  toolCalls: [],
416
473
  toolCallTotal: 0,
@@ -508,7 +565,9 @@ export function parseSessionTranscript(text) {
508
565
  if (!firstUserSeen) {
509
566
  firstUserSeen = true;
510
567
  out.firstUserAtMs = mAt;
511
- out.cron = parseCronMarker(firstText(m.content));
568
+ const prompt = firstText(m.content);
569
+ out.cron = parseCronMarker(prompt);
570
+ out.firstUserText = prompt ? clip(prompt, 2_000).text : null;
512
571
  }
513
572
  }
514
573
  else if (role === 'assistant') {
@@ -752,6 +811,12 @@ function describeFallbackStep(d) {
752
811
  export function isCronSessionKey(key) {
753
812
  return typeof key === 'string' && /(^|:)cron:/i.test(key);
754
813
  }
814
+ /** The job id in a cron session key (`agent:<agentId>:cron:<jobId>:run:<sessionId>`). */
815
+ export function cronJobIdFromKey(key) {
816
+ if (!isCronSessionKey(key))
817
+ return null;
818
+ return /(?:^|:)cron:([^:]+)/i.exec(key)?.[1] ?? null;
819
+ }
755
820
  function clean(s) {
756
821
  if (typeof s !== 'string')
757
822
  return null;
@@ -772,10 +837,7 @@ export function buildHeartbeatRunRecord(i) {
772
837
  const t = i.transcript;
773
838
  const tj = i.trajectory;
774
839
  const rl = i.runLog;
775
- const cronFromKey = tj?.sessionKey && isCronSessionKey(tj.sessionKey)
776
- ? /(?:^|:)cron:([^:]+)/i.exec(tj.sessionKey)?.[1] ?? null
777
- : null;
778
- const cronJobId = t.cron?.jobId ?? cronFromKey;
840
+ const cronJobId = t.cron?.jobId ?? cronJobIdFromKey(tj?.sessionKey);
779
841
  const trigger = cronJobId ? 'cron' : 'unknown';
780
842
  // Status: the run log is authoritative, then the trajectory's terminal
781
843
  // event, then what the transcript itself shows.
@@ -934,12 +996,13 @@ export function readSession(c) {
934
996
  * same parsers. A session with no transcript rows yet yields null. */
935
997
  function readSqliteSession(c) {
936
998
  return withDb(c.file, null, (db) => {
937
- const lines = db.prepare('SELECT event_json AS e FROM transcript_events WHERE session_id = ? ORDER BY seq').all(c.sessionId)
938
- .map((r) => (typeof r.e === 'string' ? r.e : ''))
939
- .filter(Boolean);
999
+ const { lines, unread } = transcriptLines(db, c.sessionId);
940
1000
  if (!lines.length)
941
1001
  return null;
942
1002
  const transcript = parseSessionTranscript(lines.join('\n'));
1003
+ // Rows this Node could not read: the record is partial, say so.
1004
+ if (unread > 0)
1005
+ transcript.truncated = true;
943
1006
  const tj = db.prepare('SELECT event_json AS e FROM trajectory_runtime_events WHERE session_id = ? ORDER BY seq').all(c.sessionId)
944
1007
  .map((r) => (typeof r.e === 'string' ? r.e : ''))
945
1008
  .filter(Boolean);
@@ -1,4 +1,4 @@
1
- import type { GatewayHttpClient } from '../gateway/gateway-http-client.js';
1
+ import { type GatewayHttpClient } from '../gateway/gateway-http-client.js';
2
2
  import type { ToolMap } from '../gateway/tool-discovery.js';
3
3
  import type { OrderData } from '../types.js';
4
4
  import type { CcxtPosition } from '../gateway/poller.js';
@@ -80,6 +80,31 @@ export interface ProposalCancelSummary {
80
80
  export declare function cancelPendingProposals(operatorToken: string | undefined, reason: 'kill_switch' | 'flatten' | 'pause' | 'mode_disabled', fetchImpl?: typeof fetch): Promise<ProposalCancelSummary>;
81
81
  /** Fold a proposal-cancel summary into an EmergencyResult's details line. */
82
82
  export declare function withProposalDetail(result: EmergencyResult, summary: ProposalCancelSummary): EmergencyResult;
83
+ export type OperatorHaltMode = 'ACTIVE' | 'PAUSED' | 'STOPPED';
84
+ export interface OperatorHaltOutcome {
85
+ ok: boolean;
86
+ mode?: OperatorHaltMode;
87
+ /** The plugin has no set_operator_halt (older than this connector). */
88
+ unsupported?: boolean;
89
+ error?: string;
90
+ }
91
+ /**
92
+ * Set (PAUSED / STOPPED / ACTIVE) or, with `mode` omitted, read the plugin's
93
+ * operator halt — the state create_order refuses new entries under
94
+ * (plugin/src/config/operator-halt.ts). Until 2026-10-24 Pause / Kill /
95
+ * Flatten only changed this connector's agentMode, so an agent could open a
96
+ * position minutes after the operator pressed them. Operator provenance is
97
+ * attached like every other operator tool. Never throws.
98
+ */
99
+ export declare function setOperatorHalt(ctx: {
100
+ http: GatewayHttpClient | null;
101
+ toolMap: ToolMap;
102
+ operatorToken: string | undefined;
103
+ }, mode?: OperatorHaltMode): Promise<OperatorHaltOutcome>;
104
+ /** Fold the halt outcome into a command result: an emergency command that
105
+ * could not block new entries did not fully execute, and the dashboard must
106
+ * say so (it renders `executed:false` as Failed, with these details). */
107
+ export declare function withHaltDetail(result: EmergencyResult, halt: OperatorHaltOutcome, mode: OperatorHaltMode): EmergencyResult;
83
108
  /**
84
109
  * Pause: prevent new entries, keep existing positions.
85
110
  * Returns the new agent mode if the transition is valid.
@@ -2,6 +2,7 @@
2
2
  // Functions return results — callers apply state changes (agentMode, emitAgentState).
3
3
  import { logger } from '../logger.js';
4
4
  import { resolveWebappBaseUrl } from '../utils/base-url.js';
5
+ import { GatewayHttpError } from '../gateway/gateway-http-client.js';
5
6
  const TAG = 'emergency';
6
7
  /** Distinct human-readable reasons from the rejected entries of an
7
8
  * allSettled batch — surfaced in EmergencyResult.details so the dashboard
@@ -195,18 +196,37 @@ export async function executeFlatten(ctx, cachedPositions) {
195
196
  return Promise.reject(new Error('No close_position or create_order tool available'));
196
197
  }
197
198
  }));
198
- const succeeded = results.filter((r) => r.status === 'fulfilled').length;
199
- const failed = results.filter((r) => r.status === 'rejected').length;
199
+ // A call can SUCCEED at the transport and still close nothing: close_position
200
+ // answers { error } on a refusal, and the create_order fallback can be refused
201
+ // (risk gate, operator halt) inside a 200 envelope. Counting those as closed
202
+ // reported "Closed N/N" while N positions stayed open (2026-10-24 review).
203
+ const reasons = results.map((r) => {
204
+ if (r.status === 'rejected')
205
+ return r.reason instanceof Error ? r.reason.message : String(r.reason);
206
+ const data = r.value?.data;
207
+ if (data && typeof data === 'object' && (data.ok === false || (typeof data.error === 'string' && data.error))) {
208
+ return typeof data.error === 'string' && data.error ? data.error : 'the close was refused';
209
+ }
210
+ return null;
211
+ });
212
+ const failedReasons = reasons.filter((x) => x !== null);
213
+ const succeeded = reasons.length - failedReasons.length;
214
+ const failed = failedReasons.length;
215
+ const reasonsText = () => {
216
+ const distinct = [...new Set(failedReasons)];
217
+ const shown = distinct.slice(0, 3).join('; ');
218
+ return distinct.length > 3 ? `${shown}; …` : shown;
219
+ };
200
220
  // Any un-closed position = NOT executed. "Closed 1/5" rendering as a green
201
221
  // "Flattened" would leave the operator believing they're flat while 4 real
202
222
  // positions stay live — the dashboard must show Failed + which/why.
203
223
  if (succeeded === 0 && openPositions.length > 0) {
204
- const details = `Failed to close any of ${openPositions.length} position(s): ${rejectionReasons(results)}`;
224
+ const details = `Failed to close any of ${openPositions.length} position(s): ${reasonsText()}`;
205
225
  logger.error(TAG, details);
206
226
  return { action: 'flatten', executed: false, timestamp: new Date().toISOString(), details };
207
227
  }
208
228
  if (failed > 0) {
209
- const details = `Closed ${succeeded}/${openPositions.length} positions (${failed} failed: ${rejectionReasons(results)})`;
229
+ const details = `Closed ${succeeded}/${openPositions.length} positions (${failed} failed: ${reasonsText()})`;
210
230
  logger.error(TAG, details);
211
231
  return { action: 'flatten', executed: false, timestamp: new Date().toISOString(), details };
212
232
  }
@@ -309,6 +329,56 @@ export function withProposalDetail(result, summary) {
309
329
  details: result.details ? `${result.details}. ${summary.detail}` : summary.detail,
310
330
  };
311
331
  }
332
+ /**
333
+ * Set (PAUSED / STOPPED / ACTIVE) or, with `mode` omitted, read the plugin's
334
+ * operator halt — the state create_order refuses new entries under
335
+ * (plugin/src/config/operator-halt.ts). Until 2026-10-24 Pause / Kill /
336
+ * Flatten only changed this connector's agentMode, so an agent could open a
337
+ * position minutes after the operator pressed them. Operator provenance is
338
+ * attached like every other operator tool. Never throws.
339
+ */
340
+ export async function setOperatorHalt(ctx, mode) {
341
+ if (!ctx.http)
342
+ return { ok: false, error: 'not connected to the OpenClaw gateway' };
343
+ // By its fixed name when discovery missed it (a probe timeout must not leave
344
+ // Pause / Kill / Resume without the halt for the life of the process).
345
+ const tool = ctx.toolMap.set_operator_halt ?? 'set_operator_halt';
346
+ try {
347
+ const res = await ctx.http.invoke(tool, {
348
+ ...(mode ? { mode } : {}),
349
+ operator_token: ctx.operatorToken,
350
+ });
351
+ const d = res.data;
352
+ if (d?.ok === true && (d.mode === 'ACTIVE' || d.mode === 'PAUSED' || d.mode === 'STOPPED'))
353
+ return { ok: true, mode: d.mode };
354
+ return { ok: false, error: typeof d?.error === 'string' && d.error ? d.error : 'set_operator_halt refused the call' };
355
+ }
356
+ catch (err) {
357
+ // A plugin older than this connector has no such tool: the gateway answers 404.
358
+ if (err instanceof GatewayHttpError && err.status === 404) {
359
+ return { ok: false, unsupported: true, error: 'this ReefClaw plugin cannot block new entries yet — update ReefClaw' };
360
+ }
361
+ const reason = err instanceof Error ? err.message : String(err);
362
+ logger.error(TAG, `set_operator_halt${mode ? ` ${mode}` : ' (read)'} failed: ${reason}`);
363
+ return { ok: false, error: reason };
364
+ }
365
+ }
366
+ /** Fold the halt outcome into a command result: an emergency command that
367
+ * could not block new entries did not fully execute, and the dashboard must
368
+ * say so (it renders `executed:false` as Failed, with these details). */
369
+ export function withHaltDetail(result, halt, mode) {
370
+ if (halt.ok)
371
+ return result;
372
+ const what = mode === 'ACTIVE' ? 'could NOT lift the block on new entries' : 'could NOT block new entries';
373
+ const detail = `${what}: ${halt.error ?? 'unknown error'}`;
374
+ const details = result.details ? `${result.details}. ${detail}` : detail;
375
+ // An older plugin cannot hold a halt at all: Kill / Flatten still did their
376
+ // exchange work, so that verdict stands with the warning. Pause has no other
377
+ // effect, so it did not execute.
378
+ if (halt.unsupported && mode === 'STOPPED')
379
+ return { ...result, details };
380
+ return { ...result, executed: false, details };
381
+ }
312
382
  // ---- Sync commands (pure state transitions) ----
313
383
  /**
314
384
  * Pause: prevent new entries, keep existing positions.
@@ -35,6 +35,10 @@ export declare class GatewayProvider implements OpenClawProvider {
35
35
  private eventParser;
36
36
  private toolMap;
37
37
  private agentMode;
38
+ /** The plugin's operator halt as last confirmed (null = not read yet / no
39
+ * such tool). Unlike agentMode it survives restarts — it is what
40
+ * create_order actually enforces (plugin/src/config/operator-halt.ts). */
41
+ private operatorHalt;
38
42
  private lastKnownStrategy;
39
43
  /** Agent display name + live model id, resolved from the gateway (best-effort).
40
44
  * Surfaced in agent_state so the dashboard header can show the real agent +
@@ -233,6 +237,12 @@ export declare class GatewayProvider implements OpenClawProvider {
233
237
  private executeFlatten;
234
238
  private executePause;
235
239
  private executeResume;
240
+ /** Set the plugin's operator halt and remember what it confirmed. */
241
+ private applyOperatorHalt;
242
+ /** The plugin's halt survives restarts; this connector's agentMode does
243
+ * not. Read it back so the dashboard shows the stop the order path still
244
+ * enforces (and Resume is offered). Never throws. */
245
+ private syncOperatorHalt;
236
246
  handleChat(content: string): Promise<{
237
247
  received: boolean;
238
248
  error?: string;
@@ -342,6 +352,15 @@ export declare class GatewayProvider implements OpenClawProvider {
342
352
  acknowledgeOpenPositions?: boolean;
343
353
  }): Promise<ConnectorUpdateOutcome>;
344
354
  private emitConnectorUpdate;
355
+ /**
356
+ * Replace a superseded default heartbeat message with the current one
357
+ * (refreshHeartbeatMessage: byte-identical defaults only). cron.update is
358
+ * operator.admin: a session opened with the ensure owed already holds it;
359
+ * otherwise a short-lived admin session is opened for the write, the same
360
+ * way the one-click update and the restart do — and only when a job
361
+ * actually needs it. Kill-switch: RC_HEARTBEAT_MESSAGE_REFRESH=off.
362
+ */
363
+ private refreshHeartbeatInstructions;
345
364
  /** Operator-only. Approval/balance status of the provisioned HL wallet. */
346
365
  getHlAgentWalletStatus(): Promise<HlAgentWalletStatusOutcome>;
347
366
  /** Operator-only. Read the current bracket-orders config from the plugin. */
@@ -485,6 +504,14 @@ export declare class GatewayProvider implements OpenClawProvider {
485
504
  * refresh is in flight. Fire-and-forget: the RPC completion re-emits
486
505
  * agent_state, so callers stay synchronous. */
487
506
  private maybeRefreshHeartbeatHealth;
507
+ /** The gateway's cron jobs (`cron.list`, disabled ones included), so the
508
+ * recorder can keep to ReefClaw's (isReefclawCronJob). Null when the RPC is
509
+ * unavailable — the recorder then judges each run by its marker / prompt. */
510
+ fetchCronJobs(): Promise<Array<{
511
+ id?: unknown;
512
+ name?: unknown;
513
+ payload?: unknown;
514
+ }> | null>;
488
515
  /** The gateway's cron run log for the heartbeat job (`cron.runs`, newest
489
516
  * first), normalised to the recorder's shape. Returns null when the RPC or
490
517
  * the job id is unavailable (older gateway / scope) — the recorder then