@reefclaw/openclaw-plugin 0.1.50 → 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.
Files changed (38) hide show
  1. package/README.md +6 -2
  2. package/bridge/config.js +10 -3
  3. package/bridge/gateway/heartbeat-cron.d.ts +96 -2
  4. package/bridge/gateway/heartbeat-cron.js +274 -16
  5. package/bridge/gateway/tool-discovery.d.ts +1 -1
  6. package/bridge/gateway/tool-discovery.js +4 -0
  7. package/bridge/heartbeat-runs.d.ts +24 -0
  8. package/bridge/heartbeat-runs.js +106 -5
  9. package/bridge/heartbeat-transcript.d.ts +18 -1
  10. package/bridge/heartbeat-transcript.js +103 -19
  11. package/bridge/index.js +2 -2
  12. package/bridge/providers/emergency-commands.d.ts +26 -1
  13. package/bridge/providers/emergency-commands.js +74 -4
  14. package/bridge/providers/gateway.d.ts +27 -0
  15. package/bridge/providers/gateway.js +155 -14
  16. package/bridge/setup.js +6 -3
  17. package/bridge/types.d.ts +12 -0
  18. package/bridge/utils/relay-host.d.ts +16 -0
  19. package/bridge/utils/relay-host.js +30 -1
  20. package/config/late-wiring.d.ts +37 -0
  21. package/config/late-wiring.js +111 -0
  22. package/config/operator-halt.d.ts +60 -0
  23. package/config/operator-halt.js +160 -0
  24. package/config/plugin-config-io.d.ts +7 -0
  25. package/config/tool-gate.js +3 -0
  26. package/index.js +255 -45
  27. package/openclaw.plugin.json +8 -2
  28. package/package.json +1 -1
  29. package/release-integrity.json +15 -0
  30. package/release-notes.json +4 -1
  31. package/skills/reefclaw/SKILL.md +1 -1
  32. package/strategy/builtin-strategies.js +2 -2
  33. package/tools/get-market-intel.js +2 -1
  34. package/tools/get-risk-summary.d.ts +5 -0
  35. package/tools/get-risk-summary.js +5 -0
  36. package/tools/intel-api.d.ts +10 -0
  37. package/tools/intel-api.js +13 -1
  38. package/tools/score-setup.js +4 -2
@@ -18,6 +18,9 @@ export declare const SCAN_SLACK_MS: number;
18
18
  export declare const BOOTSTRAP_LOOKBACK_MS: number;
19
19
  /** Records processed per scan (bounds CPU + POST burst on a backfill). */
20
20
  export declare const MAX_PER_SCAN = 5;
21
+ /** Transcripts parsed per scan, recorded or skipped (bounds a backfill of
22
+ * the user's own frequent jobs when cron.list can't name them). */
23
+ export declare const MAX_PARSES_PER_SCAN = 20;
21
24
  /** Give up on a run after this many failed POST cycles. */
22
25
  export declare const MAX_POST_ATTEMPTS = 5;
23
26
  /** While the bridge's edge gate is closed a record is DEFERRED (no attempt
@@ -30,11 +33,20 @@ export declare const CRON_RUNS_COOLDOWN_MS: number;
30
33
  * (a store the recorder cannot read must not stay silent — Ardi, report #5). */
31
34
  export declare const BLIND_PROBE_INTERVAL_MS: number;
32
35
  export type { AgentRunLifecycleData };
36
+ /** A `cron.list` row, as far as telling ReefClaw's jobs apart needs it. */
37
+ export interface CronJobLite {
38
+ id?: unknown;
39
+ name?: unknown;
40
+ payload?: unknown;
41
+ }
33
42
  /** What the recorder needs from the provider — kept narrow so it is trivially
34
43
  * mockable and the provider stays the only thing that talks to the gateway. */
35
44
  export interface HeartbeatRunSource {
36
45
  /** `cron.runs` for the heartbeat job, newest first; null when unavailable. */
37
46
  fetchCronRuns(limit: number): Promise<CronRunLogLite[] | null>;
47
+ /** `cron.list` (disabled jobs included); null when unavailable. Absent →
48
+ * runs are judged by their own marker name / prompt. */
49
+ fetchCronJobs?(): Promise<readonly CronJobLite[] | null>;
38
50
  /** Dashboard hook: the provider stores a compact summary + model health. */
39
51
  noteHeartbeatRun(record: HeartbeatRunRecord): void;
40
52
  /** Active trading book, for the record's mode tag. */
@@ -64,6 +76,8 @@ export interface PostOutcome {
64
76
  terminal: boolean;
65
77
  status: number | null;
66
78
  error?: string;
79
+ /** The webapp accepted the POST but did not store the run (its reason). */
80
+ skipped?: string;
67
81
  }
68
82
  export declare class HeartbeatRunRecorder {
69
83
  private readonly opts;
@@ -83,6 +97,8 @@ export declare class HeartbeatRunRecorder {
83
97
  private store;
84
98
  private lastBlindProbeAt;
85
99
  private blindWarned;
100
+ /** Non-ReefClaw jobs already logged as skipped (one line per job). */
101
+ private readonly foreignJobsLogged;
86
102
  /** Counters for a one-line health summary in logs. */
87
103
  readonly stats: {
88
104
  scans: number;
@@ -90,6 +106,7 @@ export declare class HeartbeatRunRecorder {
90
106
  posted: number;
91
107
  postFailed: number;
92
108
  skippedNonCron: number;
109
+ skippedForeign: number;
93
110
  deferred: number;
94
111
  };
95
112
  constructor(opts: HeartbeatRunRecorderOptions);
@@ -115,6 +132,13 @@ export declare class HeartbeatRunRecorder {
115
132
  * head marker second (cheap), trajectory key third (covers a prompt without
116
133
  * the marker), else not a heartbeat. */
117
134
  private classify;
135
+ /** Does this cron run belong to a ReefClaw job? The live job definition
136
+ * decides when cron.list has it (the job id may only be in the trajectory
137
+ * key); otherwise the run's marker name, else its prompt. */
138
+ private judgeRun;
139
+ /** Mark a non-ReefClaw run done for good (one log line per job). */
140
+ private skipForeign;
141
+ private fetchCronJobsSafe;
118
142
  private fetchCronRunsSafe;
119
143
  /** POST one record to the webapp. Never throws. */
120
144
  post(record: HeartbeatRunRecord): Promise<PostOutcome>;
@@ -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;
@@ -260,7 +275,9 @@ export interface BuildRecordInput {
260
275
  }
261
276
  /** OpenClaw run-log errors raised AFTER the agent turn, by the delivery of
262
277
  * its final reply (announce to a chat channel). On a box with no channel
263
- * every beat ends this way; the trading work itself completed. */
278
+ * every beat ends this way; the trading work itself completed. "requires
279
+ * target" is a channel that exists with no recipient yet (Telegram set up,
280
+ * never chatted with — 2026-10-14), from OpenClaw's missingTargetMessage. */
264
281
  export declare function isDeliveryPhaseError(text: string | null | undefined): boolean;
265
282
  export declare function buildHeartbeatRunRecord(i: BuildRecordInput): HeartbeatRunRecord;
266
283
  /** Shrink a record until its JSON fits `maxBytes`: first shorter tool
@@ -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;
@@ -760,28 +825,40 @@ function clean(s) {
760
825
  }
761
826
  /** OpenClaw run-log errors raised AFTER the agent turn, by the delivery of
762
827
  * its final reply (announce to a chat channel). On a box with no channel
763
- * every beat ends this way; the trading work itself completed. */
828
+ * every beat ends this way; the trading work itself completed. "requires
829
+ * target" is a channel that exists with no recipient yet (Telegram set up,
830
+ * never chatted with — 2026-10-14), from OpenClaw's missingTargetMessage. */
764
831
  export function isDeliveryPhaseError(text) {
765
832
  if (!text)
766
833
  return false;
767
- return /channel is required|no configured channels|no resolvable (recipient|owner|channel)|announce delivery/i.test(text);
834
+ return /channel is required|no configured channels|no resolvable (recipient|owner|channel)|announce delivery|delivering to .+ requires target/i.test(text);
768
835
  }
769
836
  export function buildHeartbeatRunRecord(i) {
770
837
  const t = i.transcript;
771
838
  const tj = i.trajectory;
772
839
  const rl = i.runLog;
773
- const cronFromKey = tj?.sessionKey && isCronSessionKey(tj.sessionKey)
774
- ? /(?:^|:)cron:([^:]+)/i.exec(tj.sessionKey)?.[1] ?? null
775
- : null;
776
- const cronJobId = t.cron?.jobId ?? cronFromKey;
840
+ const cronJobId = t.cron?.jobId ?? cronJobIdFromKey(tj?.sessionKey);
777
841
  const trigger = cronJobId ? 'cron' : 'unknown';
778
842
  // Status: the run log is authoritative, then the trajectory's terminal
779
843
  // event, then what the transcript itself shows.
780
844
  // A delivery-only failure (announce with no channel) after a completed
781
845
  // turn is NOT a failed beat — 2026-09-27, every channel-less box.
782
846
  const runLogError = clean(rl?.error);
783
- const deliveryOnly = rl?.status === 'error' &&
784
- isDeliveryPhaseError(runLogError) &&
847
+ // ★ The turn itself must not have failed. On a job without
848
+ // delivery.bestEffort, OpenClaw reports the DELIVERY error even when the
849
+ // agent turn died first (a retired model), replacing the model's error in
850
+ // the run log — so a delivery-phase run error proves nothing on its own.
851
+ // An errored assistant message still counts in assistantCount, so the
852
+ // completed-turn check below cannot catch it either (2026-10-15 review).
853
+ const endedStatus = tj?.ended?.status ?? null;
854
+ const turnFailed = t.lastStopReason === 'error' ||
855
+ t.lastErrorMessage != null ||
856
+ tj?.ended?.timedOut === true ||
857
+ tj?.ended?.promptError != null ||
858
+ (endedStatus != null && endedStatus !== 'success' && endedStatus !== 'ok');
859
+ const deliveryPhase = rl?.status === 'error' && isDeliveryPhaseError(runLogError);
860
+ const deliveryOnly = deliveryPhase &&
861
+ !turnFailed &&
785
862
  (t.complete || t.finalText != null || t.assistantCount > 0);
786
863
  let status;
787
864
  if (rl?.status === 'ok' || deliveryOnly)
@@ -825,7 +902,13 @@ export function buildHeartbeatRunRecord(i) {
825
902
  .map((e) => ({ ...e, detail: scrubSecrets(e.detail) }))
826
903
  .sort((a, b) => (a.at ?? 0) - (b.at ?? 0))
827
904
  .slice(0, MODEL_EVENTS_MAX);
828
- const errorText = (deliveryOnly ? null : runLogError) ?? clean(tj?.ended?.promptError) ?? clean(t.lastErrorMessage);
905
+ // A delivery-phase run-log error on a failed turn hides the turn's own
906
+ // error: show the turn's error first, the delivery text only as a fallback.
907
+ const errorText = deliveryOnly
908
+ ? clean(tj?.ended?.promptError) ?? clean(t.lastErrorMessage)
909
+ : deliveryPhase
910
+ ? clean(tj?.ended?.promptError) ?? clean(t.lastErrorMessage) ?? runLogError
911
+ : runLogError ?? clean(tj?.ended?.promptError) ?? clean(t.lastErrorMessage);
829
912
  const summaryClip = t.finalText ? clip(scrubSecrets(t.finalText), SUMMARY_MAX) : null;
830
913
  const toolCalls = t.toolCalls.map((c) => ({
831
914
  ...c,
@@ -913,12 +996,13 @@ export function readSession(c) {
913
996
  * same parsers. A session with no transcript rows yet yields null. */
914
997
  function readSqliteSession(c) {
915
998
  return withDb(c.file, null, (db) => {
916
- const lines = db.prepare('SELECT event_json AS e FROM transcript_events WHERE session_id = ? ORDER BY seq').all(c.sessionId)
917
- .map((r) => (typeof r.e === 'string' ? r.e : ''))
918
- .filter(Boolean);
999
+ const { lines, unread } = transcriptLines(db, c.sessionId);
919
1000
  if (!lines.length)
920
1001
  return null;
921
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;
922
1006
  const tj = db.prepare('SELECT event_json AS e FROM trajectory_runtime_events WHERE session_id = ? ORDER BY seq').all(c.sessionId)
923
1007
  .map((r) => (typeof r.e === 'string' ? r.e : ''))
924
1008
  .filter(Boolean);
package/bridge/index.js CHANGED
@@ -135,7 +135,7 @@ Options:
135
135
  --provider, -p <mock|gateway> Provider type (default: mock)
136
136
  --token, -t <token> Connection token (or REEFCLAW_TOKEN env)
137
137
  --user-id, -u <id> User ID (or REEFCLAW_USER_ID env)
138
- --relay-url, -r <url> Relay URL (default: wss://reefclaw.radunlupsa.partykit.dev)
138
+ --relay-url, -r <url> Relay URL (default: wss://relay.reefclaw.com)
139
139
  --gateway-url <url> OpenClaw gateway URL (or OPENCLAW_GATEWAY_URL env)
140
140
  --gateway-token <token> OpenClaw gateway token (or OPENCLAW_GATEWAY_TOKEN env)
141
141
  --symbol <symbol> Trading symbol (default: BTC/USDT, or REEFCLAW_SYMBOL env)
@@ -149,7 +149,7 @@ Relay config resolution (highest priority first):
149
149
  2. Environment variables (REEFCLAW_TOKEN, REEFCLAW_USER_ID, REEFCLAW_RELAY_URL)
150
150
  3. OpenClaw config file (~/.openclaw/openclaw.json → skills.entries.reefclaw)
151
151
  4. Fallback env vars (MOCK_TOKEN, USER_ID)
152
- 5. Defaults (relay URL → wss://reefclaw.radunlupsa.partykit.dev)
152
+ 5. Defaults (relay URL → wss://relay.reefclaw.com)
153
153
 
154
154
  Gateway config resolution (for --provider gateway):
155
155
  1. CLI arguments (--gateway-url, --gateway-token, --symbol, --agent-id)
@@ -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.