@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.
- package/README.md +6 -2
- package/bridge/config.js +10 -3
- package/bridge/gateway/heartbeat-cron.d.ts +96 -2
- package/bridge/gateway/heartbeat-cron.js +274 -16
- package/bridge/gateway/tool-discovery.d.ts +1 -1
- package/bridge/gateway/tool-discovery.js +4 -0
- package/bridge/heartbeat-runs.d.ts +24 -0
- package/bridge/heartbeat-runs.js +106 -5
- package/bridge/heartbeat-transcript.d.ts +18 -1
- package/bridge/heartbeat-transcript.js +103 -19
- package/bridge/index.js +2 -2
- package/bridge/providers/emergency-commands.d.ts +26 -1
- package/bridge/providers/emergency-commands.js +74 -4
- package/bridge/providers/gateway.d.ts +27 -0
- package/bridge/providers/gateway.js +155 -14
- package/bridge/setup.js +6 -3
- package/bridge/types.d.ts +12 -0
- package/bridge/utils/relay-host.d.ts +16 -0
- package/bridge/utils/relay-host.js +30 -1
- package/config/late-wiring.d.ts +37 -0
- package/config/late-wiring.js +111 -0
- package/config/operator-halt.d.ts +60 -0
- package/config/operator-halt.js +160 -0
- package/config/plugin-config-io.d.ts +7 -0
- package/config/tool-gate.js +3 -0
- package/index.js +255 -45
- package/openclaw.plugin.json +8 -2
- package/package.json +1 -1
- package/release-integrity.json +15 -0
- package/release-notes.json +4 -1
- package/skills/reefclaw/SKILL.md +1 -1
- package/strategy/builtin-strategies.js +2 -2
- package/tools/get-market-intel.js +2 -1
- package/tools/get-risk-summary.d.ts +5 -0
- package/tools/get-risk-summary.js +5 -0
- package/tools/intel-api.d.ts +10 -0
- package/tools/intel-api.js +13 -1
- package/tools/score-setup.js +4 -2
package/README.md
CHANGED
|
@@ -8,6 +8,8 @@ This file is the plain-language ledger of what the package does on the machine i
|
|
|
8
8
|
|
|
9
9
|
- **The plugin** loads into the OpenClaw gateway at startup (`activation.onStartup` in the manifest) and registers the trading tools listed under `contracts.tools`. The manifest also declares each of those tools a member of OpenClaw's "coding" tool profile (`toolMetadata`, one entry per tool and nothing else), so agents whose OpenClaw uses that profile can see them. That is a declaration in this package's own manifest: no OpenClaw config file is edited for it.
|
|
10
10
|
- **One connector process** (the `bridge/` folder) is started and supervised by the plugin. It holds the outbound connection to the ReefClaw relay, runs the agent's scheduled heartbeat, and delivers signed instruction updates. If it exits, the plugin restarts it.
|
|
11
|
+
- **Pause, Kill and Flatten are enforced on this box.** When the operator presses one of them in the dashboard, the connector records a halt in `~/.reefclaw/plugin-config.json` (`operatorHalt`) through the operator-only `set_operator_halt` tool, and while it is set `create_order` refuses new orders. `close_position`, stops and protective orders keep working; a partial exit through `create_order` waits until Resume, which clears the halt. When Flatten has to close through `create_order` (no `close_position` on the gateway), it closes before it sets the halt. `RC_OPERATOR_HALT_GATE=off` is a break-glass switch that stops the enforcement.
|
|
12
|
+
- **Keeping the heartbeat's instructions current.** When the connector starts and the `reefclaw-heartbeat` job still carries, byte for byte, an instruction text an earlier version of this package wrote, it replaces that text, and nothing else in the job, with the current one, over a short-lived `operator.admin` gateway session it opens only when needed: for that write, and on older OpenClaw versions where listing scheduled jobs itself needs it. A job whose text was changed is never touched. `RC_HEARTBEAT_MESSAGE_REFRESH=off`, or switching one-click updates off, stops it.
|
|
11
13
|
- **One-click update, for a copy OpenClaw installed from ClawHub.** When the operator presses Update in the ReefClaw dashboard, the connector asks the LOCAL gateway, over the `operator.admin` session it already uses for gateway restarts, to install from ClawHub exactly the version of this package (`@reefclaw/openclaw-plugin`) that ReefClaw's release endpoint names (`plugins.install` with `mode: "update"`), then restarts the gateway so that version loads. It never installs any other package or version, and never runs without that click. A copy placed by the connect installer is updated by that installer instead, pinned to the exact release the same endpoint names.
|
|
12
14
|
- **First start on a fresh box.** When the connection saved in OpenClaw's config (`~/.openclaw/openclaw.json` by default) carries the exchange picked during onboarding (`skills.entries.reefclaw.config.venue`) and ReefClaw has never run on this box (no plugin state, credential transport key or first-start marker, and `plugin-config.json` absent or holding only what the connect installer wrote), the plugin applies it once. For Hyperliquid it writes the keyless Hyperliquid `exchange` block into `~/.reefclaw/plugin-config.json`, the same block the dashboard's exchange switch writes, and nothing else there; Binance is the default and writes nothing. It never overwrites an existing setting, never adds keys and never enables live trading. Separately, whenever OpenClaw keeps its state somewhere other than `~/.openclaw`, the plugin leaves a small marker (`first-start.json`) in that state dir on the first start that finds none, whether or not an exchange was saved (a box upgrading to this release gets one too), so a later start is never mistaken for a first one; it is never rewritten. `RC_FIRST_START_VENUE=off` switches all of this off, the marker included.
|
|
13
15
|
- The agent starts in **PAPER mode**: real market data, simulated fills, no exchange account and no API keys. Moving to real money is a separate step the **operator** takes from the dashboard (PAPER → MICRO_LIVE → LIVE), and the tools that change mode or store credentials refuse calls that do not carry an operator-provenance secret — a per-boot value the plugin mints in memory and hands only to the connector it supervises (never a file, argv or environment variable, so it cannot be read back from the config or supplied in conversation). While trading is live a new entry without a protective stop is refused whatever the settings say.
|
|
@@ -16,11 +18,11 @@ This file is the plain-language ledger of what the package does on the machine i
|
|
|
16
18
|
|
|
17
19
|
| Path | What | Why |
|
|
18
20
|
| --- | --- | --- |
|
|
19
|
-
| `~/.reefclaw/plugin-config.json` (owner-only permissions) | Trading mode, per-box switches, the exchange in use (on a fresh box's first start, the keyless Hyperliquid block when that was picked during onboarding), and exchange credentials once the operator adds them | The only place exchange keys ever live; used only to sign requests to the exchange |
|
|
21
|
+
| `~/.reefclaw/plugin-config.json` (owner-only permissions) | Trading mode, per-box switches, the operator's Pause / Kill halt, the exchange in use (on a fresh box's first start, the keyless Hyperliquid block when that was picked during onboarding), and exchange credentials once the operator adds them | The only place exchange keys ever live; used only to sign requests to the exchange |
|
|
20
22
|
| `~/.reefclaw/credential-transport-key.json` | A key pair used to receive exchange credentials from the dashboard in encrypted form | So credentials cross the relay encrypted to this box; the private half never leaves it |
|
|
21
23
|
| Other files under `~/.reefclaw/` | Paper-trading state, the protective-order ledger, position state, a cached copy of the account's central config, market-data caches | Local bookkeeping so a restart resumes where it left off |
|
|
22
24
|
| `~/.openclaw/openclaw.json` → `skills.entries.reefclaw.config` only | The connection token, user id and relay URL the operator pasted, and the exchange picked during onboarding (`venue`) | So the connector can reach the operator's own dashboard room. Nothing else in that file is touched, and **nothing under `gateway` is ever written** |
|
|
23
|
-
| OpenClaw's cron store | One heartbeat job (`reefclaw-heartbeat`), created through the gateway's own cron API | The scheduled position review; remove it with the OpenClaw cron commands |
|
|
25
|
+
| OpenClaw's cron store | One heartbeat job (`reefclaw-heartbeat`), created through the gateway's own cron API; its instruction text is updated when it is still an earlier ReefClaw default | The scheduled position review; remove it with the OpenClaw cron commands |
|
|
24
26
|
| The `reefclaw` skill's `SKILL.md` in the agent workspace, in `~/.openclaw/skills/`, and in this package's `skills/` folder | The agent's trading instructions, kept identical in the places OpenClaw reads them | The bundled copy is a bootstrap; the full instructions arrive after connect and are applied only after their Ed25519 signature verifies against a key pinned in this build |
|
|
25
27
|
| The agent's `sessions.json` (older OpenClaw builds only) | One cached skills-snapshot key is cleared after an instruction update | So the running session re-reads the updated skill; nothing else in that file changes |
|
|
26
28
|
| `first-start.json` in `<OpenClaw state dir>/plugins/reefclaw-paper-trading/`, only when OpenClaw keeps its state outside `~/.openclaw` | A first-start timestamp and a one-line note, written on the first start that finds none (whether or not an exchange was saved) and never overwritten | So the exchange picked during onboarding is applied on the first start only, even where the home directory is reset between restarts |
|
|
@@ -55,6 +57,8 @@ Network access is outbound only: the relay (WebSocket), `www.reefclaw.com`, the
|
|
|
55
57
|
| --- | --- |
|
|
56
58
|
| `REEFCLAW_ALLOW_CONNECTOR_UPDATE=0` (or `connectorUpdate: "off"` in `plugin-config.json`) | The dashboard's one-click update is refused on this box, by either route (connect installer or ClawHub) |
|
|
57
59
|
| `RC_HEARTBEAT_RECORDER=off` | Heartbeat transcripts are not read or reported |
|
|
60
|
+
| `RC_HEARTBEAT_MESSAGE_REFRESH=off` | The connector never rewrites the heartbeat job's instructions |
|
|
61
|
+
| `RC_OPERATOR_HALT_GATE=off` | Break-glass: the dashboard's Pause / Kill / Flatten no longer block new entries on this box |
|
|
58
62
|
| `RC_SHOCK_WAKE=off` | Shock wakes are never constructed, whatever the account setting says |
|
|
59
63
|
| `RC_FIRST_START_VENUE=off` | First start neither reads nor applies the exchange saved with the connection, and writes no first-start marker |
|
|
60
64
|
| `SKILL_OTA_REQUIRE_SIGNATURE=off` | Break-glass: accept an *unsigned* instruction update on this box (a forged signature is still always refused) |
|
package/bridge/config.js
CHANGED
|
@@ -7,10 +7,11 @@ import { homedir } from 'os';
|
|
|
7
7
|
import JSON5 from 'json5';
|
|
8
8
|
import { logger } from './logger.js';
|
|
9
9
|
import { sanitizeRelayUrl } from './utils/base-url.js';
|
|
10
|
+
import { migrateRetiredRelayUrl } from './utils/relay-host.js';
|
|
10
11
|
const TAG = 'config';
|
|
11
12
|
const OPENCLAW_DIR = join(homedir(), '.openclaw');
|
|
12
13
|
const CONFIG_PATH = join(OPENCLAW_DIR, 'openclaw.json');
|
|
13
|
-
const DEFAULT_RELAY_URL = 'wss://reefclaw.
|
|
14
|
+
const DEFAULT_RELAY_URL = 'wss://relay.reefclaw.com';
|
|
14
15
|
// ---- Read/write OpenClaw config ----
|
|
15
16
|
//
|
|
16
17
|
// Scope contract — writeOpenClawConfig touches ONLY
|
|
@@ -188,13 +189,19 @@ export function resolveConfig(args) {
|
|
|
188
189
|
|| null;
|
|
189
190
|
// wss required for a public relay; ws only to a private host (`partykit
|
|
190
191
|
// dev`) — the socket's auth query carries the rc_ token (audit H4).
|
|
191
|
-
const
|
|
192
|
+
const configuredRelayUrl = sanitizeRelayUrl(args.relayUrl
|
|
192
193
|
|| process.env.REEFCLAW_RELAY_URL
|
|
193
194
|
|| savedConfig?.relayUrl
|
|
194
195
|
|| process.env.RELAY_URL
|
|
195
196
|
|| DEFAULT_RELAY_URL, DEFAULT_RELAY_URL, 'relayUrl');
|
|
197
|
+
// A box onboarded before the relay left PartyKit still names the old host;
|
|
198
|
+
// follow it to its replacement rather than dialling a deleted endpoint.
|
|
199
|
+
const migrated = migrateRetiredRelayUrl(configuredRelayUrl);
|
|
200
|
+
if (migrated.retiredHost) {
|
|
201
|
+
logger.info(TAG, `relay host ${migrated.retiredHost} is retired — connecting to ${migrated.url} instead`);
|
|
202
|
+
}
|
|
196
203
|
if (savedConfig?.token && !args.token && !process.env.REEFCLAW_TOKEN) {
|
|
197
204
|
logger.info(TAG, 'Using token from OpenClaw config');
|
|
198
205
|
}
|
|
199
|
-
return { token, userId, relayUrl };
|
|
206
|
+
return { token, userId, relayUrl: migrated.url };
|
|
200
207
|
}
|
|
@@ -2,6 +2,8 @@ export declare const HEARTBEAT_CRON_NAME = "reefclaw-heartbeat";
|
|
|
2
2
|
export declare const HEARTBEAT_EVERY_MS: number;
|
|
3
3
|
export declare const HEARTBEAT_TIMEOUT_SECONDS = 780;
|
|
4
4
|
export declare const HEARTBEAT_MESSAGE: string;
|
|
5
|
+
/** True for a message that is byte-identical to one of our superseded defaults. */
|
|
6
|
+
export declare function isSupersededHeartbeatMessage(message: unknown): boolean;
|
|
5
7
|
export interface CronRpcClient {
|
|
6
8
|
sendRpc(method: string, params?: Record<string, unknown>): Promise<unknown>;
|
|
7
9
|
}
|
|
@@ -20,8 +22,16 @@ export interface CronRpcClient {
|
|
|
20
22
|
*/
|
|
21
23
|
export declare function hasConfiguredChannels(cfg: unknown): boolean | undefined;
|
|
22
24
|
/**
|
|
23
|
-
* Repair an existing heartbeat job
|
|
24
|
-
*
|
|
25
|
+
* Repair an existing heartbeat job's announce delivery. On a box WITHOUT a
|
|
26
|
+
* chat channel announce can only fail at run time, so switch it to `none`;
|
|
27
|
+
* anywhere else make it best-effort (HEARTBEAT_ANNOUNCE_DELIVERY), so a
|
|
28
|
+
* channel with no recipient yet stops failing the beat. The best-effort
|
|
29
|
+
* patch is attempted only on a session holding operator.admin (`adminScope`)
|
|
30
|
+
* and only when the job has no bestEffort setting at all — an explicit
|
|
31
|
+
* `false` is an operator's choice. Without admin it is skipped silently, so
|
|
32
|
+
* boxes created before this fix are NOT repaired by it (the recorder's
|
|
33
|
+
* delivery-phase rule covers what they record; the operator can run
|
|
34
|
+
* `openclaw cron edit <id> --best-effort-deliver`).
|
|
25
35
|
* Runs on every bridge start (cheap: one cron.list), independent of the
|
|
26
36
|
* once-per-install marker, because the job predates this fix on every box.
|
|
27
37
|
*
|
|
@@ -40,9 +50,46 @@ export declare function reconcileHeartbeatDelivery(opts: {
|
|
|
40
50
|
rpc: CronRpcClient;
|
|
41
51
|
log: (msg: string) => void;
|
|
42
52
|
channelsConfigured: boolean | undefined;
|
|
53
|
+
/** The session was opened with operator.admin (heartbeatEnsureOwed at
|
|
54
|
+
* connect). Absent = true (legacy callers). */
|
|
55
|
+
adminScope?: boolean;
|
|
43
56
|
agentId?: string;
|
|
44
57
|
agentIsDefault?: boolean;
|
|
45
58
|
}): Promise<'patched' | 'unchanged' | 'skipped' | 'failed'>;
|
|
59
|
+
/** A gateway session that may call cron.update (operator.admin). `close`
|
|
60
|
+
* tears down a session opened only for this; a shared one passes a no-op. */
|
|
61
|
+
export interface HeartbeatAdminSession {
|
|
62
|
+
rpc: CronRpcClient;
|
|
63
|
+
close: () => void;
|
|
64
|
+
}
|
|
65
|
+
export type RefreshHeartbeatMessageOutcome = 'refreshed' | 'current' | 'untouched' | 'failed';
|
|
66
|
+
/**
|
|
67
|
+
* Bring OUR untouched heartbeat job up to date with HEARTBEAT_MESSAGE.
|
|
68
|
+
*
|
|
69
|
+
* Why (2026-10-24): the message reaches a job only when it is created (once
|
|
70
|
+
* per install), so every box created from a superseded default kept a beat
|
|
71
|
+
* with no entry check, and the small-model ones never traded. Only a message
|
|
72
|
+
* BYTE-IDENTICAL to one we shipped is replaced (isSupersededHeartbeatMessage):
|
|
73
|
+
* an edited job, a user's own job and the older Decision Loop message are
|
|
74
|
+
* left exactly as they are, so a box that trades today does not change.
|
|
75
|
+
* Nothing else of the job changes either: cron.update REPLACES the payload
|
|
76
|
+
* block, so the full stored payload goes back with only `message` swapped (a
|
|
77
|
+
* partial payload would drop timeoutSeconds and toolsAllow), and the enabled
|
|
78
|
+
* state is never touched — a job the user switched off stays off.
|
|
79
|
+
*
|
|
80
|
+
* cron.list runs on the long-lived read/write session; the admin session is
|
|
81
|
+
* opened only when a job needs the update, and the job is checked again on
|
|
82
|
+
* that session right before the write. Runs on every bridge start (one
|
|
83
|
+
* cron.list). Never throws.
|
|
84
|
+
*/
|
|
85
|
+
export declare function refreshHeartbeatMessage(opts: {
|
|
86
|
+
rpc: CronRpcClient;
|
|
87
|
+
/** Opened only when a job needs the update; null = no admin scope granted. */
|
|
88
|
+
openAdmin: () => Promise<HeartbeatAdminSession | null>;
|
|
89
|
+
log: (msg: string) => void;
|
|
90
|
+
agentId?: string;
|
|
91
|
+
agentIsDefault?: boolean;
|
|
92
|
+
}): Promise<RefreshHeartbeatMessageOutcome>;
|
|
46
93
|
/**
|
|
47
94
|
* Whether an existing cron job counts as "the heartbeat already exists".
|
|
48
95
|
* Union of the two matchers already in the codebase: the old setup path
|
|
@@ -69,6 +116,27 @@ export declare function isReefclawHeartbeatJob(job: {
|
|
|
69
116
|
name?: unknown;
|
|
70
117
|
payload?: unknown;
|
|
71
118
|
} | null | undefined): boolean;
|
|
119
|
+
/**
|
|
120
|
+
* Is this cron job ReefClaw's — the only kind whose runs the heartbeat
|
|
121
|
+
* recorder may read or upload? Every other automation on the user's OpenClaw
|
|
122
|
+
* (OpenClaw's own memory consolidation, a user's private reminders) is theirs,
|
|
123
|
+
* not ours: on 2026-10-22 a customer's nightly memory job was uploaded with
|
|
124
|
+
* their private notes. ReefClaw's = named after ReefClaw (`reefclaw-heartbeat`,
|
|
125
|
+
* a user's own `reef-*` trading jobs — Ardi), or instructions naming ReefClaw.
|
|
126
|
+
* Wider than isReefclawHeartbeatJob on purpose: that one decides which job the
|
|
127
|
+
* bridge may ADOPT as the heartbeat; this one decides whose runs are ours.
|
|
128
|
+
*/
|
|
129
|
+
export declare function isReefclawCronJob(job: {
|
|
130
|
+
name?: unknown;
|
|
131
|
+
payload?: unknown;
|
|
132
|
+
} | null | undefined): boolean;
|
|
133
|
+
/** The same verdict from a run alone, for when its job is unknown (a one-shot
|
|
134
|
+
* job already deleted, or cron.list unavailable): the job name carried in the
|
|
135
|
+
* run's `[cron:<id> <name>]` marker, else the run's prompt (the job message). */
|
|
136
|
+
export declare function isReefclawCronRun(run: {
|
|
137
|
+
jobName?: string | null;
|
|
138
|
+
prompt?: string | null;
|
|
139
|
+
}): boolean;
|
|
72
140
|
/** The job whose state the dashboard shows as the agent's heartbeat: ours by
|
|
73
141
|
* name first, then any ReefClaw heartbeat, then (legacy display fallback)
|
|
74
142
|
* anything heartbeat-named. */
|
|
@@ -103,6 +171,32 @@ export declare function cronJobBelongsToAgent(job: {
|
|
|
103
171
|
* error naming the field. Creating the job WITHOUT it would put the trading
|
|
104
172
|
* heartbeat on the wrong (default) agent, so that case fails loudly instead. */
|
|
105
173
|
export declare function isAgentIdRejection(err: unknown): boolean;
|
|
174
|
+
/**
|
|
175
|
+
* The heartbeat's announce delivery. `bestEffort` (OpenClaw cron
|
|
176
|
+
* `delivery.bestEffort`, CLI `--best-effort-deliver`: "Do not fail the job if
|
|
177
|
+
* delivery fails") makes a target that cannot be resolved a logged warning
|
|
178
|
+
* and the run `ok`, while a box whose chat works still gets the summary.
|
|
179
|
+
*
|
|
180
|
+
* ★ 2026-10-14 (a new user's first evening): Telegram configured but never
|
|
181
|
+
* chatted with, so channel `last` resolved to Telegram with no chat id and
|
|
182
|
+
* every beat failed AFTER its work completed — "Delivering to Telegram
|
|
183
|
+
* requires target <chatId>". The no-channel guard (hasConfiguredChannels)
|
|
184
|
+
* cannot see this case: a channel exists, it just has no recipient yet.
|
|
185
|
+
*
|
|
186
|
+
* Trade-off (accepted): OpenClaw also skips its own opt-in cron failure
|
|
187
|
+
* alerts / failureDestination for a bestEffort job — for every error, not
|
|
188
|
+
* only delivery ones. The run status itself stays `error` for a failed turn
|
|
189
|
+
* (OpenClaw re-applies the outcome), so our recorder, model health and fleet
|
|
190
|
+
* alarms are unaffected; they are what watches ReefClaw beats.
|
|
191
|
+
*/
|
|
192
|
+
export declare const HEARTBEAT_ANNOUNCE_DELIVERY: {
|
|
193
|
+
readonly mode: "announce";
|
|
194
|
+
readonly channel: "last";
|
|
195
|
+
readonly bestEffort: true;
|
|
196
|
+
};
|
|
197
|
+
/** A gateway that predates `delivery.bestEffort` answers with a schema error
|
|
198
|
+
* naming the field; the job is then created with plain announce, as before. */
|
|
199
|
+
export declare function isBestEffortRejection(err: unknown): boolean;
|
|
106
200
|
export declare function ensureHeartbeatCron(opts: {
|
|
107
201
|
rpc: CronRpcClient;
|
|
108
202
|
markerPath: string;
|
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
// completion. Without it, a user who deliberately deleted their heartbeat cron
|
|
14
14
|
// would get it resurrected on every bridge boot — the old setup-time path ran
|
|
15
15
|
// once, and that operator-override behaviour must be preserved.
|
|
16
|
+
import { createHash } from 'crypto';
|
|
16
17
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
|
|
17
18
|
import { dirname } from 'path';
|
|
18
19
|
export const HEARTBEAT_CRON_NAME = 'reefclaw-heartbeat';
|
|
@@ -34,20 +35,37 @@ export const HEARTBEAT_TIMEOUT_SECONDS = 780;
|
|
|
34
35
|
// measured costs on prod (2026-08-04): the agent paged the whole ~110KB
|
|
35
36
|
// SKILL.md through sed/rg every beat (~100KB of tool output before any
|
|
36
37
|
// trading work), and Steps 0-9 predate the pinned-plan/exit-gate discipline —
|
|
37
|
-
// Step 8's exit rules are the scratch-the-winners instructions.
|
|
38
|
-
//
|
|
39
|
-
//
|
|
40
|
-
//
|
|
41
|
-
//
|
|
38
|
+
// Step 8's exit rules are the scratch-the-winners instructions.
|
|
39
|
+
// NOTE: the ensure writes this message only when it CREATES the job (once per
|
|
40
|
+
// install). A job still carrying one of our earlier defaults byte-for-byte is
|
|
41
|
+
// brought up to date on connect by refreshHeartbeatMessage below; an edited
|
|
42
|
+
// job, or one on the Decision Loop message, is never touched.
|
|
42
43
|
// ★ The mandatory items are ENUMERATED here on purpose. The first (softer)
|
|
43
44
|
// version of this message — "Run the HEARTBEAT.md checklist" — produced
|
|
44
45
|
// 85-second beats on gpt-5.4-mini that skipped record_position_reviews,
|
|
45
46
|
// get_wave9_status, and the liquidity batch entirely (observed on prod
|
|
46
47
|
// 2026-08-04 12:25/12:40 UTC): the checklist being in context is not enough,
|
|
47
48
|
// the beat prompt itself must name what cannot be skipped.
|
|
48
|
-
|
|
49
|
+
// ★ 2026-10-24: item (5), the ENTRY CHECK. The enumerated list had no entry
|
|
50
|
+
// step, and small models run exactly the list: a new user's agent
|
|
51
|
+
// (qwen3.7-flash) made 125 beats with 0 scan_pairs / 0 create_order, and the
|
|
52
|
+
// ClawHub canary (deepseek-v4-flash) 418 beats with none, while the boxes
|
|
53
|
+
// whose beat is the old Decision Loop message ran scan_pairs every beat and
|
|
54
|
+
// traded daily. It is worded as a MINIMUM so a model that already runs its
|
|
55
|
+
// own entry process is not narrowed by it, and it keeps every quality gate:
|
|
56
|
+
// scan_pairs at min_score 5 (SKILL.md G2), score_setup (the operator's
|
|
57
|
+
// Explore / Balanced / Selective GO bar lives there — an entry opens only on
|
|
58
|
+
// GO / STRONG_GO), get_sizing for the amount, and the full create_order
|
|
59
|
+
// field set named inline so no model invents or re-reads SKILL.md for it.
|
|
60
|
+
// It never relies on the agent seeing a Pause: the plugin refuses
|
|
61
|
+
// create_order while the operator has paused or stopped trading
|
|
62
|
+
// (plugin/src/config/operator-halt.ts). The checklist is named by its
|
|
63
|
+
// folder, not by a relative path: `skills/reefclaw/` resolves under the
|
|
64
|
+
// workspace, and a ClawHub install keeps its skill elsewhere
|
|
65
|
+
// (~/.openclaw/plugin-skills/reefclaw/), so that read failed there.
|
|
66
|
+
export const HEARTBEAT_MESSAGE = 'Heartbeat. FIRST read HEARTBEAT.md from the folder that holds your ReefClaw SKILL.md (e.g. skills/reefclaw/HEARTBEAT.md; one read call) ' +
|
|
49
67
|
'and execute EVERY checkbox in it. If that read fails, the items below ARE the checklist — do not look anywhere else for it, ' +
|
|
50
|
-
'and do NOT re-read SKILL.md from disk
|
|
68
|
+
'and do NOT re-read SKILL.md from disk: item (5) names everything an entry needs. ' +
|
|
51
69
|
'NON-SKIPPABLE every beat: (1) query_trades({hours:1}) stop-watcher reconcile; ' +
|
|
52
70
|
'(2) get_wave9_status() once, unconditionally; ' +
|
|
53
71
|
'(3) if ANY position is open and the Position Decision Journal is enabled (record_position_reviews reports off-mode when it is not): ' +
|
|
@@ -56,10 +74,50 @@ export const HEARTBEAT_MESSAGE = 'Heartbeat. FIRST read the checklist file skill
|
|
|
56
74
|
'plus get_resting_liquidity + get_liquidation_levels + get_liquidation_pulse for ALL positions in one parallel batch; ' +
|
|
57
75
|
"(4) the Market Assessment reads — every tool takes ONE object argument, e.g. get_regime({symbol:'BTCUSDT'}), " +
|
|
58
76
|
"get_market_structure({symbol:'BTC/USDT'}), get_market_intel({category:'news'}), get_crypto_metrics({symbol:'BTC/USDT'}); " +
|
|
59
|
-
|
|
77
|
+
'(5) the ENTRY CHECK — a minimum, never a limit on your own entry process. get_risk_summary() and get_liquidation_pulse() first; ' +
|
|
78
|
+
'no new entry when get_risk_summary shows operator_halt, heat is elevated or higher, a risk limit is breached, or an active cascade runs against the side. Otherwise ' +
|
|
79
|
+
'scan_pairs({min_score:5}) once and take the top-ranked setup without a reentry_caution, passing its symbol as printed to the read tools: ' +
|
|
80
|
+
"get_setup_detail({symbol}) gives direction, entry, stop and its first target; " +
|
|
81
|
+
"score_setup({symbol, direction:'LONG' or 'SHORT', setup_type:'<its strategy>', entry_price, stop_price, target_price}) gives the verdict. " +
|
|
82
|
+
'Open it ONLY on GO or STRONG_GO, after the Pre-Entry checks in HEARTBEAT.md (track record, funding, learnings): ' +
|
|
83
|
+
'get_sizing({symbol}) → amount = fetch_balance equity × sizePct ÷ |entry − stop|, at most 0.4 × equity ÷ entry; then ' +
|
|
84
|
+
"create_order({symbol written BASE/QUOTE (Binance prints BTCUSDT: write BTC/USDT; Hyperliquid already prints BTC/USDC), side:'buy' for long or 'sell' for short, " +
|
|
85
|
+
"type:'market', amount, stopPrice, target_price, invalidation_price (usually the stop), realization_rule ({type:'fixed_target'} unless you plan otherwise), " +
|
|
86
|
+
'setup_type, thesis (1-2 sentences), regime, regime_confidence (get_setup_detail gives 0-1: multiply by 100), scorecard_verdict, confluence_score}); ' +
|
|
87
|
+
'if it rejects the size, retry ONCE at the effective max it names ÷ entry. ' +
|
|
88
|
+
'Otherwise say in ONE line why not. If create_order answers operator_halt or entitlement_expired, make no further entry this beat. ' +
|
|
89
|
+
"Where tools are reached through tool_call, pass {id:'<tool name>', args:{...}}. " +
|
|
60
90
|
'Manage open positions by their pinned plan (invalidation_price / realization_rule) — do not re-argue the entry thesis each beat. ' +
|
|
61
91
|
'Check tradingMode from fetch_balance — the source of truth for paper vs live. ' +
|
|
62
92
|
'Batch independent tool calls in parallel. Trading tools only: no subagents, no web browsing.';
|
|
93
|
+
/**
|
|
94
|
+
* sha256 of every EARLIER default HEARTBEAT_MESSAGE without the entry check,
|
|
95
|
+
* byte-exact as shipped (git history of this file; OpenClaw stores the
|
|
96
|
+
* message verbatim — verified on the canary fleet 2026-10-24). A job whose
|
|
97
|
+
* message hashes to one of these is our untouched default, so it can be
|
|
98
|
+
* brought up to date. The 2026-07-22..24 "full Decision Loop (Steps 0-9)"
|
|
99
|
+
* message is deliberately NOT here: the Decision Loop includes the entry
|
|
100
|
+
* scan, and boxes still on it trade.
|
|
101
|
+
*/
|
|
102
|
+
const SUPERSEDED_HEARTBEAT_MESSAGE_SHA256 = new Set([
|
|
103
|
+
'1b0bea9637111ddcf786d7fdb3cf2f1c2ceab3558b40abfaa8e0ed22f37f5615', // 251bef68 2026-08-04
|
|
104
|
+
'358cc3ec6b3b7ed647ac07c93e38cc3d79d1ffeebfc553db4beb7e27a34bdeb7', // da9f867a 2026-08-04
|
|
105
|
+
'09fdd0d906dcfa2847d5d7a28f0732081246536bc3e8fab620c38b8434a88323', // fb5dc39a 2026-08-04 .. c635209e 2026-09-27
|
|
106
|
+
'df932f264b8a2fcd5d648cca913252b44fbf228b6f6e192cf43ae4d2facb9f66', // f2ccab02 2026-09-27
|
|
107
|
+
'475a3a5b57811a5ebc6b2f195403b7cba1a68fd9df8fe33ffa69f75ff8432610', // 5f44b304 2026-09-27
|
|
108
|
+
'aef39fabcc76b8a2fa7ee4738b58a937ed17efdcd51c4f1022da6ac4b8b8aff8', // 595edbd1 2026-09-27 .. 100c1042 2026-10-22
|
|
109
|
+
// Interim drafts of item (5), never released: they ran only on the
|
|
110
|
+
// onboard-050c canary (2026-10-24/25 tests), which then gets the final text
|
|
111
|
+
// like any box.
|
|
112
|
+
'b0a6ba3c205b3f9a44254d2ae9b203d6808573660c962cdd6e2004ca6a2ba5f2',
|
|
113
|
+
'880bbcecf4c812fbe4de681808e61d5a512605aa73a6cbf38548e07d70a9557c',
|
|
114
|
+
]);
|
|
115
|
+
/** True for a message that is byte-identical to one of our superseded defaults. */
|
|
116
|
+
export function isSupersededHeartbeatMessage(message) {
|
|
117
|
+
if (typeof message !== 'string' || message.length === 0)
|
|
118
|
+
return false;
|
|
119
|
+
return SUPERSEDED_HEARTBEAT_MESSAGE_SHA256.has(createHash('sha256').update(message, 'utf8').digest('hex'));
|
|
120
|
+
}
|
|
63
121
|
/**
|
|
64
122
|
* Does this OpenClaw have at least one chat channel configured? Read from
|
|
65
123
|
* openclaw.json `channels` (telegram / discord / whatsapp / … entries).
|
|
@@ -89,8 +147,16 @@ export function hasConfiguredChannels(cfg) {
|
|
|
89
147
|
return false;
|
|
90
148
|
}
|
|
91
149
|
/**
|
|
92
|
-
* Repair an existing heartbeat job
|
|
93
|
-
*
|
|
150
|
+
* Repair an existing heartbeat job's announce delivery. On a box WITHOUT a
|
|
151
|
+
* chat channel announce can only fail at run time, so switch it to `none`;
|
|
152
|
+
* anywhere else make it best-effort (HEARTBEAT_ANNOUNCE_DELIVERY), so a
|
|
153
|
+
* channel with no recipient yet stops failing the beat. The best-effort
|
|
154
|
+
* patch is attempted only on a session holding operator.admin (`adminScope`)
|
|
155
|
+
* and only when the job has no bestEffort setting at all — an explicit
|
|
156
|
+
* `false` is an operator's choice. Without admin it is skipped silently, so
|
|
157
|
+
* boxes created before this fix are NOT repaired by it (the recorder's
|
|
158
|
+
* delivery-phase rule covers what they record; the operator can run
|
|
159
|
+
* `openclaw cron edit <id> --best-effort-deliver`).
|
|
94
160
|
* Runs on every bridge start (cheap: one cron.list), independent of the
|
|
95
161
|
* once-per-install marker, because the job predates this fix on every box.
|
|
96
162
|
*
|
|
@@ -106,7 +172,9 @@ export function hasConfiguredChannels(cfg) {
|
|
|
106
172
|
* this guess.
|
|
107
173
|
*/
|
|
108
174
|
export async function reconcileHeartbeatDelivery(opts) {
|
|
109
|
-
|
|
175
|
+
// Best-effort repair needs a cron.update this session may not be allowed;
|
|
176
|
+
// without admin it would only log a refusal on every bridge start.
|
|
177
|
+
if (opts.channelsConfigured !== false && opts.adminScope === false)
|
|
110
178
|
return 'skipped';
|
|
111
179
|
const agentId = opts.agentId?.trim().toLowerCase() || undefined;
|
|
112
180
|
const agentIsDefault = opts.agentIsDefault ?? true;
|
|
@@ -116,11 +184,22 @@ export async function reconcileHeartbeatDelivery(opts) {
|
|
|
116
184
|
const job = jobs.find((j) => isReefclawHeartbeatJob(j) && cronJobBelongsToAgent(j, agentId, agentIsDefault));
|
|
117
185
|
if (!job || typeof job.id !== 'string')
|
|
118
186
|
return 'unchanged';
|
|
119
|
-
const
|
|
120
|
-
if (mode !== 'announce')
|
|
187
|
+
const delivery = job.delivery;
|
|
188
|
+
if (delivery?.mode !== 'announce')
|
|
121
189
|
return 'unchanged';
|
|
122
|
-
|
|
123
|
-
|
|
190
|
+
if (opts.channelsConfigured === false) {
|
|
191
|
+
await opts.rpc.sendRpc('cron.update', { id: job.id, patch: { delivery: { mode: 'none' } } });
|
|
192
|
+
opts.log(`Heartbeat cron: no chat channel is configured — delivery switched from announce to none (${String(job.name)})`);
|
|
193
|
+
return 'patched';
|
|
194
|
+
}
|
|
195
|
+
// A channel exists (or the config is unreadable): keep announcing, but a
|
|
196
|
+
// missing recipient must not fail the beat. Unlike the switch to `none`
|
|
197
|
+
// this can never silence a summary that is delivered today, so it needs
|
|
198
|
+
// no channel guess — every announce job gets it.
|
|
199
|
+
if (delivery.bestEffort !== undefined)
|
|
200
|
+
return 'unchanged';
|
|
201
|
+
await opts.rpc.sendRpc('cron.update', { id: job.id, patch: { delivery: { bestEffort: true } } });
|
|
202
|
+
opts.log(`Heartbeat cron: announce delivery set to best-effort — a missing chat recipient no longer fails the beat (${String(job.name)})`);
|
|
124
203
|
return 'patched';
|
|
125
204
|
}
|
|
126
205
|
catch (err) {
|
|
@@ -128,6 +207,116 @@ export async function reconcileHeartbeatDelivery(opts) {
|
|
|
128
207
|
return 'failed';
|
|
129
208
|
}
|
|
130
209
|
}
|
|
210
|
+
/**
|
|
211
|
+
* Bring OUR untouched heartbeat job up to date with HEARTBEAT_MESSAGE.
|
|
212
|
+
*
|
|
213
|
+
* Why (2026-10-24): the message reaches a job only when it is created (once
|
|
214
|
+
* per install), so every box created from a superseded default kept a beat
|
|
215
|
+
* with no entry check, and the small-model ones never traded. Only a message
|
|
216
|
+
* BYTE-IDENTICAL to one we shipped is replaced (isSupersededHeartbeatMessage):
|
|
217
|
+
* an edited job, a user's own job and the older Decision Loop message are
|
|
218
|
+
* left exactly as they are, so a box that trades today does not change.
|
|
219
|
+
* Nothing else of the job changes either: cron.update REPLACES the payload
|
|
220
|
+
* block, so the full stored payload goes back with only `message` swapped (a
|
|
221
|
+
* partial payload would drop timeoutSeconds and toolsAllow), and the enabled
|
|
222
|
+
* state is never touched — a job the user switched off stays off.
|
|
223
|
+
*
|
|
224
|
+
* cron.list runs on the long-lived read/write session; the admin session is
|
|
225
|
+
* opened only when a job needs the update, and the job is checked again on
|
|
226
|
+
* that session right before the write. Runs on every bridge start (one
|
|
227
|
+
* cron.list). Never throws.
|
|
228
|
+
*/
|
|
229
|
+
export async function refreshHeartbeatMessage(opts) {
|
|
230
|
+
const agentId = opts.agentId?.trim().toLowerCase() || undefined;
|
|
231
|
+
const agentIsDefault = opts.agentIsDefault ?? true;
|
|
232
|
+
const listJobs = async (rpc) => {
|
|
233
|
+
const resp = (await rpc.sendRpc('cron.list', { includeDisabled: true }));
|
|
234
|
+
return Array.isArray(resp?.jobs) ? resp.jobs : null;
|
|
235
|
+
};
|
|
236
|
+
const payloadOf = (job) => job.payload != null && typeof job.payload === 'object' ? job.payload : undefined;
|
|
237
|
+
const ours = (job) => cronJobBelongsToAgent(job, agentId, agentIsDefault);
|
|
238
|
+
const due = (jobs) => jobs.filter((j) => typeof j?.id === 'string' && ours(j) && payloadOf(j)?.kind === 'agentTurn' && isSupersededHeartbeatMessage(payloadOf(j)?.message));
|
|
239
|
+
let admin = null;
|
|
240
|
+
let adminTried = false;
|
|
241
|
+
const adminSession = async () => {
|
|
242
|
+
if (!adminTried) {
|
|
243
|
+
adminTried = true;
|
|
244
|
+
admin = await opts.openAdmin();
|
|
245
|
+
}
|
|
246
|
+
return admin;
|
|
247
|
+
};
|
|
248
|
+
const noAdmin = () => {
|
|
249
|
+
opts.log('Heartbeat cron: instructions not updated (the gateway gave no admin session) — retried on the next bridge start');
|
|
250
|
+
return 'failed';
|
|
251
|
+
};
|
|
252
|
+
try {
|
|
253
|
+
let jobs;
|
|
254
|
+
try {
|
|
255
|
+
jobs = await listJobs(opts.rpc);
|
|
256
|
+
}
|
|
257
|
+
catch (err) {
|
|
258
|
+
// OpenClaw 2026.7.x scoped cron.list itself to operator.admin.
|
|
259
|
+
if (!/missing scopes?:/i.test(err instanceof Error ? err.message : String(err)))
|
|
260
|
+
throw err;
|
|
261
|
+
const a = await adminSession();
|
|
262
|
+
if (!a)
|
|
263
|
+
return noAdmin();
|
|
264
|
+
jobs = await listJobs(a.rpc);
|
|
265
|
+
}
|
|
266
|
+
if (!jobs) {
|
|
267
|
+
opts.log('Heartbeat cron: instructions check skipped (cron.list returned no job list)');
|
|
268
|
+
return 'failed';
|
|
269
|
+
}
|
|
270
|
+
if (due(jobs).length === 0) {
|
|
271
|
+
return jobs.some((j) => ours(j) && payloadOf(j)?.message === HEARTBEAT_MESSAGE) ? 'current' : 'untouched';
|
|
272
|
+
}
|
|
273
|
+
const a = await adminSession();
|
|
274
|
+
if (!a)
|
|
275
|
+
return noAdmin();
|
|
276
|
+
// Checked again on the session that writes: a job edited since the first
|
|
277
|
+
// list is left alone.
|
|
278
|
+
const fresh = await listJobs(a.rpc);
|
|
279
|
+
if (!fresh) {
|
|
280
|
+
opts.log('Heartbeat cron: instructions not updated (cron.list returned no job list) — retried on the next bridge start');
|
|
281
|
+
return 'failed';
|
|
282
|
+
}
|
|
283
|
+
const confirmed = due(fresh);
|
|
284
|
+
if (confirmed.length === 0)
|
|
285
|
+
return 'untouched';
|
|
286
|
+
for (const job of confirmed) {
|
|
287
|
+
const payload = { ...payloadOf(job), message: HEARTBEAT_MESSAGE };
|
|
288
|
+
await a.rpc.sendRpc('cron.update', { id: job.id, patch: { payload } });
|
|
289
|
+
}
|
|
290
|
+
// Read it back: a gateway that accepted the update but ignored or
|
|
291
|
+
// reshaped the payload must not be reported as done (and every other
|
|
292
|
+
// field of the job must still be there).
|
|
293
|
+
const after = (await listJobs(a.rpc)) ?? [];
|
|
294
|
+
const stuck = (job) => {
|
|
295
|
+
const now = after.find((j) => j?.id === job.id);
|
|
296
|
+
const p = now ? payloadOf(now) : undefined;
|
|
297
|
+
if (!p || p.message !== HEARTBEAT_MESSAGE)
|
|
298
|
+
return false;
|
|
299
|
+
return Object.keys(payloadOf(job) ?? {}).every((k) => k in p);
|
|
300
|
+
};
|
|
301
|
+
const notStuck = confirmed.filter((job) => !stuck(job));
|
|
302
|
+
for (const job of confirmed.filter(stuck)) {
|
|
303
|
+
opts.log(`Heartbeat cron: instructions updated — each beat now includes the entry check (${String(job.name)})`);
|
|
304
|
+
}
|
|
305
|
+
if (notStuck.length > 0) {
|
|
306
|
+
opts.log(`Heartbeat cron: instructions update did not stick for ${notStuck.map((j) => String(j.name)).join(', ')} — ` +
|
|
307
|
+
'the job is as the gateway keeps it; retried on the next bridge start');
|
|
308
|
+
return 'failed';
|
|
309
|
+
}
|
|
310
|
+
return 'refreshed';
|
|
311
|
+
}
|
|
312
|
+
catch (err) {
|
|
313
|
+
opts.log(`Heartbeat cron: instructions update failed (${err instanceof Error ? err.message.split('\n')[0] : String(err)}) — retried on the next bridge start`);
|
|
314
|
+
return 'failed';
|
|
315
|
+
}
|
|
316
|
+
finally {
|
|
317
|
+
admin?.close();
|
|
318
|
+
}
|
|
319
|
+
}
|
|
131
320
|
/**
|
|
132
321
|
* Whether an existing cron job counts as "the heartbeat already exists".
|
|
133
322
|
* Union of the two matchers already in the codebase: the old setup path
|
|
@@ -168,6 +357,42 @@ export function isReefclawHeartbeatJob(job) {
|
|
|
168
357
|
const msg = typeof payload?.message === 'string' ? payload.message : typeof payload?.text === 'string' ? payload.text : '';
|
|
169
358
|
return REEFCLAW_BEAT_MESSAGE.test(msg);
|
|
170
359
|
}
|
|
360
|
+
/** Instructions that make an automation ReefClaw's: the product name, a
|
|
361
|
+
* ReefClaw-only tool, or the Decision Loop of the pre-2026-08 beat message. */
|
|
362
|
+
const REEFCLAW_JOB_TEXT = /reef\s*claw|Decision Loop|record_position_reviews|query_trades|get_wave9_status/i;
|
|
363
|
+
/** `reefclaw-*` / `ReefClaw …`, or a user's own `reef-*` / `reef_*` job —
|
|
364
|
+
* never a bare "reef" ("Reef tank check" is not ours). */
|
|
365
|
+
const REEFCLAW_JOB_NAME = /reef\s*claw|^reef[-_]/i;
|
|
366
|
+
/**
|
|
367
|
+
* Is this cron job ReefClaw's — the only kind whose runs the heartbeat
|
|
368
|
+
* recorder may read or upload? Every other automation on the user's OpenClaw
|
|
369
|
+
* (OpenClaw's own memory consolidation, a user's private reminders) is theirs,
|
|
370
|
+
* not ours: on 2026-10-22 a customer's nightly memory job was uploaded with
|
|
371
|
+
* their private notes. ReefClaw's = named after ReefClaw (`reefclaw-heartbeat`,
|
|
372
|
+
* a user's own `reef-*` trading jobs — Ardi), or instructions naming ReefClaw.
|
|
373
|
+
* Wider than isReefclawHeartbeatJob on purpose: that one decides which job the
|
|
374
|
+
* bridge may ADOPT as the heartbeat; this one decides whose runs are ours.
|
|
375
|
+
*/
|
|
376
|
+
export function isReefclawCronJob(job) {
|
|
377
|
+
// Any job the bridge may adopt as THE heartbeat is ours too, or its beats
|
|
378
|
+
// would be skipped while the dashboard reads its state.
|
|
379
|
+
if (isReefclawHeartbeatJob(job))
|
|
380
|
+
return true;
|
|
381
|
+
const name = job?.name;
|
|
382
|
+
if (typeof name === 'string' && REEFCLAW_JOB_NAME.test(name))
|
|
383
|
+
return true;
|
|
384
|
+
const payload = job?.payload;
|
|
385
|
+
const msg = typeof payload?.message === 'string' ? payload.message : typeof payload?.text === 'string' ? payload.text : '';
|
|
386
|
+
return REEFCLAW_JOB_TEXT.test(msg);
|
|
387
|
+
}
|
|
388
|
+
/** The same verdict from a run alone, for when its job is unknown (a one-shot
|
|
389
|
+
* job already deleted, or cron.list unavailable): the job name carried in the
|
|
390
|
+
* run's `[cron:<id> <name>]` marker, else the run's prompt (the job message). */
|
|
391
|
+
export function isReefclawCronRun(run) {
|
|
392
|
+
if (typeof run.jobName === 'string' && REEFCLAW_JOB_NAME.test(run.jobName))
|
|
393
|
+
return true;
|
|
394
|
+
return typeof run.prompt === 'string' && REEFCLAW_JOB_TEXT.test(run.prompt);
|
|
395
|
+
}
|
|
171
396
|
/** The job whose state the dashboard shows as the agent's heartbeat: ours by
|
|
172
397
|
* name first, then any ReefClaw heartbeat, then (legacy display fallback)
|
|
173
398
|
* anything heartbeat-named. */
|
|
@@ -227,6 +452,31 @@ export function isAgentIdRejection(err) {
|
|
|
227
452
|
const msg = err instanceof Error ? err.message : String(err);
|
|
228
453
|
return /agentId/i.test(msg) && /additional|unknown|unexpected|invalid|not allowed|schema|must not/i.test(msg);
|
|
229
454
|
}
|
|
455
|
+
/**
|
|
456
|
+
* The heartbeat's announce delivery. `bestEffort` (OpenClaw cron
|
|
457
|
+
* `delivery.bestEffort`, CLI `--best-effort-deliver`: "Do not fail the job if
|
|
458
|
+
* delivery fails") makes a target that cannot be resolved a logged warning
|
|
459
|
+
* and the run `ok`, while a box whose chat works still gets the summary.
|
|
460
|
+
*
|
|
461
|
+
* ★ 2026-10-14 (a new user's first evening): Telegram configured but never
|
|
462
|
+
* chatted with, so channel `last` resolved to Telegram with no chat id and
|
|
463
|
+
* every beat failed AFTER its work completed — "Delivering to Telegram
|
|
464
|
+
* requires target <chatId>". The no-channel guard (hasConfiguredChannels)
|
|
465
|
+
* cannot see this case: a channel exists, it just has no recipient yet.
|
|
466
|
+
*
|
|
467
|
+
* Trade-off (accepted): OpenClaw also skips its own opt-in cron failure
|
|
468
|
+
* alerts / failureDestination for a bestEffort job — for every error, not
|
|
469
|
+
* only delivery ones. The run status itself stays `error` for a failed turn
|
|
470
|
+
* (OpenClaw re-applies the outcome), so our recorder, model health and fleet
|
|
471
|
+
* alarms are unaffected; they are what watches ReefClaw beats.
|
|
472
|
+
*/
|
|
473
|
+
export const HEARTBEAT_ANNOUNCE_DELIVERY = { mode: 'announce', channel: 'last', bestEffort: true };
|
|
474
|
+
/** A gateway that predates `delivery.bestEffort` answers with a schema error
|
|
475
|
+
* naming the field; the job is then created with plain announce, as before. */
|
|
476
|
+
export function isBestEffortRejection(err) {
|
|
477
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
478
|
+
return /bestEffort/i.test(msg) && /additional|unknown|unexpected|invalid|not allowed|schema|must not/i.test(msg);
|
|
479
|
+
}
|
|
230
480
|
export async function ensureHeartbeatCron(opts) {
|
|
231
481
|
const { rpc, markerPath, log } = opts;
|
|
232
482
|
const agentId = opts.agentId?.trim().toLowerCase() || undefined;
|
|
@@ -290,7 +540,15 @@ export async function ensureHeartbeatCron(opts) {
|
|
|
290
540
|
return 'created';
|
|
291
541
|
}
|
|
292
542
|
try {
|
|
293
|
-
|
|
543
|
+
try {
|
|
544
|
+
await rpc.sendRpc('cron.add', { ...baseJob, delivery: HEARTBEAT_ANNOUNCE_DELIVERY });
|
|
545
|
+
}
|
|
546
|
+
catch (bestEffortErr) {
|
|
547
|
+
if (!isBestEffortRejection(bestEffortErr))
|
|
548
|
+
throw bestEffortErr;
|
|
549
|
+
log('Heartbeat cron: this OpenClaw does not accept delivery.bestEffort — creating with plain announce');
|
|
550
|
+
await rpc.sendRpc('cron.add', { ...baseJob, delivery: { mode: 'announce', channel: 'last' } });
|
|
551
|
+
}
|
|
294
552
|
}
|
|
295
553
|
catch (addErr) {
|
|
296
554
|
if (agentId && !agentIsDefault && isAgentIdRejection(addErr)) {
|
|
@@ -3,7 +3,7 @@ import { GatewayHttpClient, GatewayHttpError } from './gateway-http-client.js';
|
|
|
3
3
|
* Logical tool names used by ReefClaw internally.
|
|
4
4
|
* Each maps to one or more candidate actual tool names on the gateway.
|
|
5
5
|
*/
|
|
6
|
-
export type LogicalTool = 'fetch_ticker' | 'fetch_balance' | 'fetch_ohlcv' | 'fetch_positions' | 'fetch_open_orders' | 'cancel_all_orders' | 'cancel_order' | 'close_position' | 'create_order' | 'get_market_structure' | 'get_crypto_metrics' | 'get_market_intel' | 'set_trading_mode' | 'set_exchange_credentials' | 'test_exchange_credentials' | 'clear_exchange_credentials' | 'hl_provision_agent_wallet' | 'hl_agent_wallet_status' | 'hl_submit_agent_approval' | 'get_bracket_config' | 'set_bracket_requirement';
|
|
6
|
+
export type LogicalTool = 'fetch_ticker' | 'fetch_balance' | 'fetch_ohlcv' | 'fetch_positions' | 'fetch_open_orders' | 'cancel_all_orders' | 'cancel_order' | 'close_position' | 'create_order' | 'get_market_structure' | 'get_crypto_metrics' | 'get_market_intel' | 'set_trading_mode' | 'set_exchange_credentials' | 'test_exchange_credentials' | 'clear_exchange_credentials' | 'hl_provision_agent_wallet' | 'hl_agent_wallet_status' | 'hl_submit_agent_approval' | 'get_bracket_config' | 'set_bracket_requirement' | 'set_operator_halt';
|
|
7
7
|
/**
|
|
8
8
|
* Build the test args used when probing each logical tool.
|
|
9
9
|
*
|
|
@@ -25,6 +25,7 @@ const OPTIONAL_TOOLS = [
|
|
|
25
25
|
'hl_submit_agent_approval',
|
|
26
26
|
'get_bracket_config',
|
|
27
27
|
'set_bracket_requirement',
|
|
28
|
+
'set_operator_halt',
|
|
28
29
|
];
|
|
29
30
|
/**
|
|
30
31
|
* Candidate actual tool names to probe for each logical tool.
|
|
@@ -52,6 +53,7 @@ const CANDIDATES = {
|
|
|
52
53
|
hl_submit_agent_approval: ['hl_submit_agent_approval'],
|
|
53
54
|
get_bracket_config: ['get_bracket_config'],
|
|
54
55
|
set_bracket_requirement: ['set_bracket_requirement'],
|
|
56
|
+
set_operator_halt: ['set_operator_halt'],
|
|
55
57
|
};
|
|
56
58
|
/** Default probe symbol when the caller does not supply the configured one.
|
|
57
59
|
* Kept for back-compat with pre-symbol callers; real deployments should pass
|
|
@@ -126,6 +128,8 @@ export function buildProbeArgs(symbol = DEFAULT_PROBE_SYMBOL) {
|
|
|
126
128
|
// Bracket-config probes: no-arg read; set with an invalid flag triggers early-return.
|
|
127
129
|
get_bracket_config: {},
|
|
128
130
|
set_bracket_requirement: { flag: '__probe__', value: false },
|
|
131
|
+
// No mode = a read: the probe can never set or clear a halt.
|
|
132
|
+
set_operator_halt: {},
|
|
129
133
|
};
|
|
130
134
|
}
|
|
131
135
|
// ---- Discovery logic ----
|