@reefclaw/openclaw-plugin 0.1.30 → 0.1.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,21 @@
1
1
  import type { OpenClawProvider } from './provider.js';
2
2
  import type { ConnectorConfig } from './types.js';
3
+ /** Agent-specific filesystem locations the bridge writes to. */
4
+ export interface BridgePaths {
5
+ /** The agent's OpenClaw workspace (SKILL.md lives at its root). */
6
+ workspaceDir: string;
7
+ /** The agent's `sessions.json` (skills-snapshot invalidation after an update). */
8
+ sessionsJsonPath: string;
9
+ }
10
+ /** The single-agent layout every box used before multi-agent attach. */
11
+ export declare function defaultBridgePaths(): BridgePaths;
3
12
  export declare class Bridge {
4
13
  private readonly provider;
14
+ /** Where the served agent's SKILL.md and session index live. The legacy
15
+ * single-agent paths by default; index.ts passes the resolved agent's
16
+ * (gateway/agent-scope.ts) so a trading agent beside a business agent
17
+ * gets its updates in ITS workspace. */
18
+ private readonly paths;
5
19
  private connector;
6
20
  private readonly seqs;
7
21
  private throttleBuffer;
@@ -34,7 +48,12 @@ export declare class Bridge {
34
48
  * timer) double-applying / double-notifying during the one-time bootstrap→
35
49
  * full transition. The chain that starts (attempt 1) owns the flag. */
36
50
  private skillPullInFlight;
37
- constructor(provider: OpenClawProvider, connectorConfig: ConnectorConfig);
51
+ constructor(provider: OpenClawProvider, connectorConfig: ConnectorConfig,
52
+ /** Where the served agent's SKILL.md and session index live. The legacy
53
+ * single-agent paths by default; index.ts passes the resolved agent's
54
+ * (gateway/agent-scope.ts) so a trading agent beside a business agent
55
+ * gets its updates in ITS workspace. */
56
+ paths?: BridgePaths);
38
57
  /** Start the bridge: connect to relay + start provider */
39
58
  start(): void;
40
59
  /** Stop the bridge: disconnect + stop provider */
package/bridge/bridge.js CHANGED
@@ -70,8 +70,16 @@ function isBootstrapSkillVersion(version) {
70
70
  return true;
71
71
  return compareSemver('1.0.0', version) > 0; // '1.0.0' > version ⟺ version < 1.0.0
72
72
  }
73
+ /** The single-agent layout every box used before multi-agent attach. */
74
+ export function defaultBridgePaths() {
75
+ return {
76
+ workspaceDir: join(homedir(), '.openclaw', 'workspace'),
77
+ sessionsJsonPath: join(homedir(), '.openclaw', 'agents', 'main', 'sessions', 'sessions.json'),
78
+ };
79
+ }
73
80
  export class Bridge {
74
81
  provider;
82
+ paths;
75
83
  connector;
76
84
  seqs = {
77
85
  market_data: 0,
@@ -112,9 +120,15 @@ export class Bridge {
112
120
  * timer) double-applying / double-notifying during the one-time bootstrap→
113
121
  * full transition. The chain that starts (attempt 1) owns the flag. */
114
122
  skillPullInFlight = false;
115
- constructor(provider, connectorConfig) {
123
+ constructor(provider, connectorConfig,
124
+ /** Where the served agent's SKILL.md and session index live. The legacy
125
+ * single-agent paths by default; index.ts passes the resolved agent's
126
+ * (gateway/agent-scope.ts) so a trading agent beside a business agent
127
+ * gets its updates in ITS workspace. */
128
+ paths = defaultBridgePaths()) {
116
129
  this.provider = provider;
117
- this.currentSkillVersion = readLocalSkillVersion();
130
+ this.paths = paths;
131
+ this.currentSkillVersion = readLocalSkillVersion(this.paths.workspaceDir);
118
132
  logger.info(TAG, `Local SKILL.md version: ${this.currentSkillVersion ?? 'unknown'}`);
119
133
  this.connectionToken = connectorConfig.token;
120
134
  this.connector = new Connector(connectorConfig, {
@@ -1031,10 +1045,10 @@ export class Bridge {
1031
1045
  * installed skill dir, clear session cache, notify agent. */
1032
1046
  async applySkillUpdate(env) {
1033
1047
  const { version, content } = env;
1034
- const workspacePath = join(homedir(), '.openclaw', 'workspace');
1048
+ const workspacePath = this.paths.workspaceDir;
1035
1049
  const skillMdPath = join(workspacePath, 'SKILL.md');
1036
1050
  const tempPath = join(workspacePath, 'SKILL.md.tmp');
1037
- const sessionsJsonPath = join(homedir(), '.openclaw', 'agents', 'main', 'sessions', 'sessions.json');
1051
+ const sessionsJsonPath = this.paths.sessionsJsonPath;
1038
1052
  // True only when the Ed25519 signature was actually checked AND passed —
1039
1053
  // gates the replay-clock write below. An update applied UNVERIFIED
1040
1054
  // (enforcement off) must never advance the clock: an unsigned push with a
@@ -1199,7 +1213,7 @@ export class Bridge {
1199
1213
  if (!result?.content)
1200
1214
  return null;
1201
1215
  // Re-read local version (may have changed since startup) + downgrade guard.
1202
- this.currentSkillVersion = readLocalSkillVersion();
1216
+ this.currentSkillVersion = readLocalSkillVersion(this.paths.workspaceDir);
1203
1217
  if (compareSemver(result.version, this.currentSkillVersion) < 0) {
1204
1218
  const message = `refusing downgrade: relay v${result.version} is older than local v${this.currentSkillVersion ?? 'unknown'}`;
1205
1219
  logger.warn(TAG, `SKILL.md pull: ${message}`);
@@ -1266,7 +1280,7 @@ export class Bridge {
1266
1280
  this.skillPullInFlight = false;
1267
1281
  return;
1268
1282
  }
1269
- this.currentSkillVersion = readLocalSkillVersion();
1283
+ this.currentSkillVersion = readLocalSkillVersion(this.paths.workspaceDir);
1270
1284
  // The workspace tracker alone is NOT proof the agent has the full skill:
1271
1285
  // a plugin (re)install resets the agent-visible extension copy to the
1272
1286
  // bundled bootstrap while the workspace copy survives (observed live
@@ -1338,7 +1352,7 @@ export class Bridge {
1338
1352
  this.bootstrapHealTimer = setInterval(() => {
1339
1353
  // Re-read from disk: the file may have been upgraded out-of-band (relay
1340
1354
  // OTA push, manual SFTP) since we last cached it.
1341
- this.currentSkillVersion = readLocalSkillVersion();
1355
+ this.currentSkillVersion = readLocalSkillVersion(this.paths.workspaceDir);
1342
1356
  if (!isBootstrapSkillVersion(this.currentSkillVersion)) {
1343
1357
  this.stopBootstrapHeal();
1344
1358
  return;
@@ -1363,7 +1377,7 @@ export class Bridge {
1363
1377
  * channel for updates once the store is populated). */
1364
1378
  async handleConnectAck(payload) {
1365
1379
  // Re-read local version (may have changed since startup)
1366
- this.currentSkillVersion = readLocalSkillVersion();
1380
+ this.currentSkillVersion = readLocalSkillVersion(this.paths.workspaceDir);
1367
1381
  // Fresh-user self-heal: while still on the thin bootstrap SKILL.md, pull the
1368
1382
  // full instructions from the webapp on this (re)connect. Guarded (in-flight)
1369
1383
  // + downgrade-checked, so it's a strict no-op once upgraded.
@@ -7,15 +7,55 @@ export declare function normalizeAgentId(value: unknown): string | undefined;
7
7
  /** `agent:<agentId>:<rest>` → `<agentId>`. Undefined when the key carries no
8
8
  * agent scope (legacy keys, `global`, `unknown`, missing). */
9
9
  export declare function resolveAgentIdFromSessionKey(sessionKey: unknown): string | undefined;
10
+ type AgentEntry = {
11
+ id?: unknown;
12
+ default?: unknown;
13
+ workspace?: unknown;
14
+ };
15
+ /** The roster as OpenClaw reads it (agent-scope-config.ts
16
+ * `readAgentRosterProperty`, 2026.9.x): `agents.entries` — an object keyed
17
+ * by agent id — wins when present, else the older `agents.list` array. The
18
+ * 2026.9 gateway migrates a `list` into `entries` on boot, so a reader that
19
+ * only knows `list` sees NO agents on a freshly booted gateway. */
20
+ export declare function listAgentEntries(cfg: unknown): AgentEntry[];
10
21
  /**
11
22
  * OpenClaw's own rule for the gateway's default agent (agent-scope-config.ts
12
- * `resolveDefaultAgentId`): the `agents.list` entry flagged `default: true`,
13
- * else the first entry, else `main`. The installer places the ReefClaw skill
14
- * in that agent's workspace and the heartbeat cron runs on it, so with no
15
- * override the default agent IS the trading agent. Nobody has to configure
16
- * anything; an override exists for hand-built multi-agent setups.
23
+ * `resolveDefaultAgentId`, 2026.9.x): exactly one entry flagged
24
+ * `default: true` (ignored under `agents.ownership: "explicit"`), else the
25
+ * SOLE agent, else `main` when the config lists no (valid) agent at all —
26
+ * OpenClaw errors on an empty roster; `main` is the friendlier reading of a
27
+ * degenerate config. With several agents and no marker OpenClaw refuses to
28
+ * pick ("agent selection required"), and so does this: undefined. (2026.6.x
29
+ * still fell back to the first entry; the installer refuses that ambiguous
30
+ * case instead of guessing.) The
31
+ * installer places the ReefClaw skill in the default agent's workspace unless
32
+ * told otherwise, so with no override the default agent IS the trading agent.
17
33
  */
18
- export declare function resolveDefaultAgentIdFromConfig(cfg: unknown): string;
34
+ export declare function resolveDefaultAgentIdFromConfig(cfg: unknown): string | undefined;
35
+ /** `~` / `~/x` -> under the home dir; anything else unchanged (trimmed). */
36
+ export declare function expandUserPath(p: string, home?: string): string;
37
+ /** OpenClaw's state dir: OPENCLAW_STATE_DIR, else OPENCLAW_HOME, else ~/.openclaw. */
38
+ export declare function resolveOpenClawStateDir(env?: NodeJS.ProcessEnv, home?: string): string;
39
+ /**
40
+ * The workspace directory OpenClaw gives an agent - mirrors its
41
+ * `resolveAgentWorkspaceDir` (agent-scope-config.ts, 2026.6.11 and 2026.9.4):
42
+ * the entry's own `workspace` if set; the default agent (marker / sole /
43
+ * implicit main — see resolveDefaultAgentIdFromConfig) inherits
44
+ * `agents.defaults.workspace` or the legacy `<state>/workspace`; every other
45
+ * agent gets `<agents.defaults.workspace>/<id>` or `<state>/workspace-<id>`.
46
+ * With no resolvable default NO agent inherits the legacy dir (2026.9.x).
47
+ * The gateway exposes no RPC for this, so the bridge has to know the rule:
48
+ * it is where the trading skill, IDENTITY.md and the heartbeat marker live.
49
+ */
50
+ export declare function resolveAgentWorkspaceDir(input: {
51
+ cfg: unknown;
52
+ agentId: string;
53
+ env?: NodeJS.ProcessEnv;
54
+ home?: string;
55
+ }): string;
56
+ /** `<state>/agents/<id>/sessions` - where OpenClaw keeps the agent's session
57
+ * index and transcripts (the heartbeat flight recorder reads them). */
58
+ export declare function resolveAgentSessionsDir(agentId: string, env?: NodeJS.ProcessEnv, home?: string): string;
19
59
  /** The agent an event belongs to, when the payload says. An explicit
20
60
  * `agentId` field wins (future-proofing; today's gateway sends only the
21
61
  * session key). */
@@ -28,3 +68,4 @@ export declare function isForeignAgentEvent(payload: {
28
68
  agentId?: unknown;
29
69
  sessionKey?: unknown;
30
70
  }, ownAgentId: string): boolean;
71
+ export {};
@@ -15,6 +15,8 @@
15
15
  // gateways omit it; legacy/unscoped keys such as `global`) is treated as our
16
16
  // own. Dropping it would blind the chat on exactly the single-agent boxes
17
17
  // that cannot leak anything.
18
+ import { join } from 'node:path';
19
+ import { homedir } from 'node:os';
18
20
  /** OpenClaw's default agent id, the one the installer sets the trading agent
19
21
  * up as, and the id the bridge has always addressed chat to. */
20
22
  export const DEFAULT_AGENT_ID = 'main';
@@ -36,23 +38,99 @@ export function resolveAgentIdFromSessionKey(sessionKey) {
36
38
  return undefined;
37
39
  return normalizeAgentId(key.split(':')[1]);
38
40
  }
41
+ /** The roster as OpenClaw reads it (agent-scope-config.ts
42
+ * `readAgentRosterProperty`, 2026.9.x): `agents.entries` — an object keyed
43
+ * by agent id — wins when present, else the older `agents.list` array. The
44
+ * 2026.9 gateway migrates a `list` into `entries` on boot, so a reader that
45
+ * only knows `list` sees NO agents on a freshly booted gateway. */
46
+ export function listAgentEntries(cfg) {
47
+ const agents = cfg?.agents;
48
+ if (!agents || typeof agents !== 'object')
49
+ return [];
50
+ const entries = agents.entries;
51
+ if (entries !== undefined && entries !== null && typeof entries === 'object' && !Array.isArray(entries)) {
52
+ return Object.entries(entries).flatMap(([id, entry]) => entry && typeof entry === 'object' && !Array.isArray(entry) ? [{ ...entry, id }] : []);
53
+ }
54
+ const list = agents.list;
55
+ if (!Array.isArray(list))
56
+ return [];
57
+ return list.filter((e) => !!e && typeof e === 'object' && !Array.isArray(e));
58
+ }
39
59
  /**
40
60
  * OpenClaw's own rule for the gateway's default agent (agent-scope-config.ts
41
- * `resolveDefaultAgentId`): the `agents.list` entry flagged `default: true`,
42
- * else the first entry, else `main`. The installer places the ReefClaw skill
43
- * in that agent's workspace and the heartbeat cron runs on it, so with no
44
- * override the default agent IS the trading agent. Nobody has to configure
45
- * anything; an override exists for hand-built multi-agent setups.
61
+ * `resolveDefaultAgentId`, 2026.9.x): exactly one entry flagged
62
+ * `default: true` (ignored under `agents.ownership: "explicit"`), else the
63
+ * SOLE agent, else `main` when the config lists no (valid) agent at all —
64
+ * OpenClaw errors on an empty roster; `main` is the friendlier reading of a
65
+ * degenerate config. With several agents and no marker OpenClaw refuses to
66
+ * pick ("agent selection required"), and so does this: undefined. (2026.6.x
67
+ * still fell back to the first entry; the installer refuses that ambiguous
68
+ * case instead of guessing.) The
69
+ * installer places the ReefClaw skill in the default agent's workspace unless
70
+ * told otherwise, so with no override the default agent IS the trading agent.
46
71
  */
47
72
  export function resolveDefaultAgentIdFromConfig(cfg) {
48
- const list = cfg?.agents?.list;
49
- if (!Array.isArray(list))
50
- return DEFAULT_AGENT_ID;
51
- const entries = list.filter((e) => !!e && typeof e === 'object' && !Array.isArray(e));
73
+ const entries = listAgentEntries(cfg);
74
+ const ownership = cfg?.agents?.ownership;
75
+ if (ownership !== 'explicit') {
76
+ const marked = entries.filter((e) => e.default === true);
77
+ if (marked.length === 1)
78
+ return normalizeAgentId(marked[0].id) ?? DEFAULT_AGENT_ID;
79
+ }
80
+ if (entries.length === 1)
81
+ return normalizeAgentId(entries[0].id) ?? DEFAULT_AGENT_ID;
52
82
  if (entries.length === 0)
53
83
  return DEFAULT_AGENT_ID;
54
- const chosen = entries.find((e) => e.default === true) ?? entries[0];
55
- return normalizeAgentId(chosen.id) ?? DEFAULT_AGENT_ID;
84
+ return undefined;
85
+ }
86
+ /** `~` / `~/x` -> under the home dir; anything else unchanged (trimmed). */
87
+ export function expandUserPath(p, home = homedir()) {
88
+ const t = p.trim();
89
+ if (t === '~')
90
+ return home;
91
+ if (t.startsWith('~/') || t.startsWith('~\\'))
92
+ return join(home, t.slice(2));
93
+ return t;
94
+ }
95
+ /** OpenClaw's state dir: OPENCLAW_STATE_DIR, else OPENCLAW_HOME, else ~/.openclaw. */
96
+ export function resolveOpenClawStateDir(env = process.env, home = homedir()) {
97
+ const explicit = env.OPENCLAW_STATE_DIR?.trim() || env.OPENCLAW_HOME?.trim();
98
+ return explicit ? expandUserPath(explicit, home) : join(home, '.openclaw');
99
+ }
100
+ /**
101
+ * The workspace directory OpenClaw gives an agent - mirrors its
102
+ * `resolveAgentWorkspaceDir` (agent-scope-config.ts, 2026.6.11 and 2026.9.4):
103
+ * the entry's own `workspace` if set; the default agent (marker / sole /
104
+ * implicit main — see resolveDefaultAgentIdFromConfig) inherits
105
+ * `agents.defaults.workspace` or the legacy `<state>/workspace`; every other
106
+ * agent gets `<agents.defaults.workspace>/<id>` or `<state>/workspace-<id>`.
107
+ * With no resolvable default NO agent inherits the legacy dir (2026.9.x).
108
+ * The gateway exposes no RPC for this, so the bridge has to know the rule:
109
+ * it is where the trading skill, IDENTITY.md and the heartbeat marker live.
110
+ */
111
+ export function resolveAgentWorkspaceDir(input) {
112
+ const env = input.env ?? process.env;
113
+ const home = input.home ?? homedir();
114
+ const id = normalizeAgentId(input.agentId) ?? DEFAULT_AGENT_ID;
115
+ const entry = listAgentEntries(input.cfg).find((e) => normalizeAgentId(e.id) === id);
116
+ const configured = typeof entry?.workspace === 'string' ? entry.workspace.trim() : '';
117
+ if (configured)
118
+ return expandUserPath(configured, home);
119
+ const rawFallback = input.cfg?.agents?.defaults?.workspace;
120
+ const fallback = typeof rawFallback === 'string' ? rawFallback.trim() : '';
121
+ const stateDir = resolveOpenClawStateDir(env, home);
122
+ const inherited = resolveDefaultAgentIdFromConfig(input.cfg);
123
+ if (inherited !== undefined && id === inherited) {
124
+ return fallback ? expandUserPath(fallback, home) : join(stateDir, 'workspace');
125
+ }
126
+ if (fallback)
127
+ return join(expandUserPath(fallback, home), id);
128
+ return join(stateDir, `workspace-${id}`);
129
+ }
130
+ /** `<state>/agents/<id>/sessions` - where OpenClaw keeps the agent's session
131
+ * index and transcripts (the heartbeat flight recorder reads them). */
132
+ export function resolveAgentSessionsDir(agentId, env = process.env, home = homedir()) {
133
+ return join(resolveOpenClawStateDir(env, home), 'agents', normalizeAgentId(agentId) ?? DEFAULT_AGENT_ID, 'sessions');
56
134
  }
57
135
  /** The agent an event belongs to, when the payload says. An explicit
58
136
  * `agentId` field wins (future-proofing; today's gateway sends only the
@@ -20,6 +20,22 @@ export interface GatewayConfig {
20
20
  * its run events reach the dashboard (gateway/agent-scope.ts). Optional so
21
21
  * a hand-built config stays valid; consumers default to 'main'. */
22
22
  agentId?: string;
23
+ /** True when `agentId` is the gateway's default agent (the one that inherits
24
+ * the legacy ~/.openclaw/workspace and runs crons created without an
25
+ * agentId). Absent = true, the historical single-agent shape. */
26
+ agentIsDefault?: boolean;
27
+ /** True when the gateway hosts more than one agent. OpenClaw 2026.9 then
28
+ * demands an explicit owner on terminal.open (the one-click update PTY);
29
+ * a single-agent gateway gets the historical, owner-less request. */
30
+ agentSharedGateway?: boolean;
31
+ /** The agent's OpenClaw workspace (SKILL.md, IDENTITY.md, the heartbeat
32
+ * marker, ReefClaw's day-NAV/trading-mode files). Absent = the legacy
33
+ * ~/.openclaw/workspace. Resolved by OpenClaw's own rule
34
+ * (gateway/agent-scope.ts resolveAgentWorkspaceDir); OPENCLAW_WORKSPACE
35
+ * overrides it. */
36
+ agentWorkspaceDir?: string;
37
+ /** `<state>/agents/<id>/sessions` - session index + transcripts. */
38
+ agentSessionsDir?: string;
23
39
  /** Per-host switch for the dashboard's one-click connector update, which
24
40
  * opens a PTY on this box (providers/connector-update.ts). Absent = allowed. */
25
41
  allowConnectorUpdate?: boolean;
@@ -56,6 +72,10 @@ export declare function resolveGatewayConfig(args: GatewayCliArgs): {
56
72
  intelligenceUrl: string;
57
73
  venue: VenueId;
58
74
  agentId: string;
75
+ agentIsDefault: boolean;
76
+ agentSharedGateway: boolean;
77
+ agentWorkspaceDir: string;
78
+ agentSessionsDir: string;
59
79
  allowConnectorUpdate: boolean;
60
80
  };
61
81
  /**
@@ -7,8 +7,10 @@ import { homedir } from 'os';
7
7
  import JSON5 from 'json5';
8
8
  import { parseVenue, VENUE_DEFAULT_SYMBOL } from '@reefclaw/shared';
9
9
  import { logger } from '../logger.js';
10
- import { normalizeAgentId, resolveDefaultAgentIdFromConfig } from './agent-scope.js';
10
+ import { normalizeAgentId, resolveDefaultAgentIdFromConfig, resolveAgentWorkspaceDir, resolveAgentSessionsDir, expandUserPath, listAgentEntries, } from './agent-scope.js';
11
11
  const TAG = 'gateway-config';
12
+ /** What the bridge serves when the config resolves no default agent. */
13
+ const DEFAULT_AGENT_ID_FALLBACK = 'main';
12
14
  const DEFAULT_GATEWAY_PORT = 18789;
13
15
  const DEFAULT_GATEWAY_HOST = 'localhost';
14
16
  /**
@@ -155,8 +157,31 @@ export function resolveGatewayConfig(args) {
155
157
  const overrideAgentId = normalizeAgentId(args.agentId)
156
158
  ?? normalizeAgentId(process.env.OPENCLAW_AGENT_ID)
157
159
  ?? normalizeAgentId(pluginConfig?.agentId);
158
- const agentId = overrideAgentId ?? resolveDefaultAgentIdFromConfig(ocConfig);
159
- const agentIdSource = overrideAgentId ? 'configured override' : 'gateway default agent';
160
+ // undefined = several agents and none marked default (OpenClaw itself
161
+ // refuses to pick there). Without an override the bridge falls back to
162
+ // 'main' and says so — the installer stops that configuration at install
163
+ // time, so this is only reachable on a hand-edited box.
164
+ const defaultAgentId = resolveDefaultAgentIdFromConfig(ocConfig);
165
+ const agentId = overrideAgentId ?? defaultAgentId ?? DEFAULT_AGENT_ID_FALLBACK;
166
+ const agentIdSource = overrideAgentId
167
+ ? 'configured override'
168
+ : defaultAgentId
169
+ ? 'gateway default agent'
170
+ : 'no default agent resolvable — falling back; set OPENCLAW_AGENT_ID or plugin-config agentId';
171
+ if (!overrideAgentId && !defaultAgentId) {
172
+ logger.warn(TAG, `This gateway hosts several agents and none is marked default; serving '${agentId}' — set OPENCLAW_AGENT_ID (or agentId in plugin-config.json) to the trading agent.`);
173
+ }
174
+ const agentIsDefault = defaultAgentId !== undefined && agentId === defaultAgentId;
175
+ const agentSharedGateway = listAgentEntries(ocConfig).length > 1;
176
+ // Where OpenClaw keeps this agent's workspace + sessions. The default agent
177
+ // inherits the legacy paths every existing box uses; a trading agent that
178
+ // lives beside a business agent gets its own (`workspace-<id>`,
179
+ // `agents/<id>/sessions`). OPENCLAW_WORKSPACE stays the explicit override.
180
+ const envWorkspace = process.env.OPENCLAW_WORKSPACE?.trim();
181
+ const agentWorkspaceDir = envWorkspace
182
+ ? expandUserPath(envWorkspace)
183
+ : resolveAgentWorkspaceDir({ cfg: ocConfig, agentId });
184
+ const agentSessionsDir = resolveAgentSessionsDir(agentId);
160
185
  // --- One-click connector update switch ---
161
186
  // env > plugin-config.json connectorUpdate > allowed. A per-host opt-out
162
187
  // for the dashboard's "Update connector" (which opens a PTY on this box);
@@ -165,9 +190,22 @@ export function resolveGatewayConfig(args) {
165
190
  ?? parseOnOffSwitch(pluginConfig?.connectorUpdate)
166
191
  ?? true;
167
192
  logger.info(TAG, `Intelligence service: ${intelligenceUrl} (venue=${venue})`);
168
- logger.info(TAG, `Agent: ${agentId} (${agentIdSource}); one-click connector update: ${allowConnectorUpdate ? 'allowed' : 'DISABLED on this box'}`);
193
+ logger.info(TAG, `Agent: ${agentId} (${agentIdSource}${agentIsDefault ? '' : ', not the gateway default'}; workspace ${agentWorkspaceDir}); ` +
194
+ `one-click connector update: ${allowConnectorUpdate ? 'allowed' : 'DISABLED on this box'}`);
169
195
  logger.debug(TAG, `Resolved: url=${gatewayUrl}, token=${gatewayToken ? '***' : '(none)'}, symbol=${symbol}`);
170
- return { gatewayUrl, gatewayToken, symbol, intelligenceUrl, venue, agentId, allowConnectorUpdate };
196
+ return {
197
+ gatewayUrl,
198
+ gatewayToken,
199
+ symbol,
200
+ intelligenceUrl,
201
+ venue,
202
+ agentId,
203
+ agentIsDefault,
204
+ agentSharedGateway,
205
+ agentWorkspaceDir,
206
+ agentSessionsDir,
207
+ allowConnectorUpdate,
208
+ };
171
209
  }
172
210
  /**
173
211
  * Validate that the resolved config has all required fields.
@@ -21,8 +21,25 @@ export type EnsureHeartbeatOutcome = 'already_ensured' | 'found_existing' | 'cre
21
21
  * returns 'failed' rather than throwing, and only success writes the marker so
22
22
  * a transient gateway error retries on the next boot.
23
23
  */
24
+ /** True when an existing cron job runs on the agent we serve. A job without an
25
+ * agentId belongs to the gateway's DEFAULT agent (OpenClaw's rule), so on a
26
+ * shared gateway a business agent's own heartbeat must not count as ours -
27
+ * that is how a trading agent installed beside one ended up with no beat. */
28
+ export declare function cronJobBelongsToAgent(job: {
29
+ agentId?: unknown;
30
+ } | null | undefined, agentId: string | undefined, agentIsDefault: boolean): boolean;
31
+ /** A gateway too old to accept `agentId` on cron.add answers with a schema
32
+ * error naming the field. Creating the job WITHOUT it would put the trading
33
+ * heartbeat on the wrong (default) agent, so that case fails loudly instead. */
34
+ export declare function isAgentIdRejection(err: unknown): boolean;
24
35
  export declare function ensureHeartbeatCron(opts: {
25
36
  rpc: CronRpcClient;
26
37
  markerPath: string;
27
38
  log: (msg: string) => void;
39
+ /** The agent the bridge serves (gateway/agent-scope.ts). Absent = legacy
40
+ * single-agent behaviour: any heartbeat-like job counts, no agentId sent. */
41
+ agentId?: string;
42
+ /** False when `agentId` is NOT the gateway default - the job then carries
43
+ * agentId so OpenClaw runs it on that agent (session key agent:<id>:cron:...). */
44
+ agentIsDefault?: boolean;
28
45
  }): Promise<EnsureHeartbeatOutcome>;
@@ -74,8 +74,29 @@ export function isHeartbeatLikeName(name) {
74
74
  * returns 'failed' rather than throwing, and only success writes the marker so
75
75
  * a transient gateway error retries on the next boot.
76
76
  */
77
+ /** True when an existing cron job runs on the agent we serve. A job without an
78
+ * agentId belongs to the gateway's DEFAULT agent (OpenClaw's rule), so on a
79
+ * shared gateway a business agent's own heartbeat must not count as ours -
80
+ * that is how a trading agent installed beside one ended up with no beat. */
81
+ export function cronJobBelongsToAgent(job, agentId, agentIsDefault) {
82
+ if (!agentId)
83
+ return true;
84
+ const owner = typeof job?.agentId === 'string' && job.agentId.trim() ? job.agentId.trim().toLowerCase() : undefined;
85
+ if (owner === undefined)
86
+ return agentIsDefault;
87
+ return owner === agentId.trim().toLowerCase();
88
+ }
89
+ /** A gateway too old to accept `agentId` on cron.add answers with a schema
90
+ * error naming the field. Creating the job WITHOUT it would put the trading
91
+ * heartbeat on the wrong (default) agent, so that case fails loudly instead. */
92
+ export function isAgentIdRejection(err) {
93
+ const msg = err instanceof Error ? err.message : String(err);
94
+ return /agentId/i.test(msg) && /additional|unknown|unexpected|invalid|not allowed|schema|must not/i.test(msg);
95
+ }
77
96
  export async function ensureHeartbeatCron(opts) {
78
97
  const { rpc, markerPath, log } = opts;
98
+ const agentId = opts.agentId?.trim().toLowerCase() || undefined;
99
+ const agentIsDefault = opts.agentIsDefault ?? true;
79
100
  try {
80
101
  if (existsSync(markerPath))
81
102
  return 'already_ensured';
@@ -87,7 +108,7 @@ export async function ensureHeartbeatCron(opts) {
87
108
  log('Heartbeat cron: skipped (cron.list returned no job list)');
88
109
  return 'failed';
89
110
  }
90
- const existing = jobs.find((j) => isHeartbeatLikeName(j?.name));
111
+ const existing = jobs.find((j) => isHeartbeatLikeName(j?.name) && cronJobBelongsToAgent(j, agentId, agentIsDefault));
91
112
  if (existing) {
92
113
  writeMarker(markerPath, { ensuredAt: new Date().toISOString(), found: String(existing.name) });
93
114
  log(`Heartbeat cron: already exists (${String(existing.name)})`);
@@ -105,6 +126,10 @@ export async function ensureHeartbeatCron(opts) {
105
126
  // the results on the dashboard anyway.
106
127
  const baseJob = {
107
128
  name: HEARTBEAT_CRON_NAME,
129
+ // Only a NON-default agent needs the field: the default agent is what a
130
+ // job without agentId runs on, and omitting it keeps every existing
131
+ // single-agent box byte-identical to before.
132
+ ...(agentId && !agentIsDefault ? { agentId } : {}),
108
133
  enabled: true,
109
134
  schedule: { kind: 'every', everyMs: HEARTBEAT_EVERY_MS },
110
135
  sessionTarget: 'isolated',
@@ -126,12 +151,26 @@ export async function ensureHeartbeatCron(opts) {
126
151
  await rpc.sendRpc('cron.add', { ...baseJob, delivery: { mode: 'announce', channel: 'last' } });
127
152
  }
128
153
  catch (addErr) {
154
+ if (agentId && !agentIsDefault && isAgentIdRejection(addErr)) {
155
+ log(`Heartbeat cron: NOT created - this OpenClaw rejects agentId on cron.add (${addErr instanceof Error ? addErr.message.split('\n')[0] : String(addErr)}). ` +
156
+ `A heartbeat without it would run on the default agent, not '${agentId}'. Upgrade OpenClaw, or create the job yourself with the agent set.`);
157
+ return 'failed';
158
+ }
129
159
  log(`Heartbeat cron: announce delivery rejected (${addErr instanceof Error ? addErr.message.split('\n')[0] : String(addErr)}) — retrying without delivery`);
130
- await rpc.sendRpc('cron.add', { ...baseJob, delivery: { mode: 'none' } });
160
+ try {
161
+ await rpc.sendRpc('cron.add', { ...baseJob, delivery: { mode: 'none' } });
162
+ }
163
+ catch (retryErr) {
164
+ if (agentId && !agentIsDefault && isAgentIdRejection(retryErr)) {
165
+ log(`Heartbeat cron: NOT created - this OpenClaw rejects agentId on cron.add; a heartbeat without it would run on the default agent, not '${agentId}'.`);
166
+ return 'failed';
167
+ }
168
+ throw retryErr;
169
+ }
131
170
  delivery = 'none';
132
171
  }
133
172
  writeMarker(markerPath, { ensuredAt: new Date().toISOString(), created: HEARTBEAT_CRON_NAME, delivery });
134
- log(`Heartbeat cron: created (${HEARTBEAT_CRON_NAME}, every 15m, delivery=${delivery})`);
173
+ log(`Heartbeat cron: created (${HEARTBEAT_CRON_NAME}, every 15m, delivery=${delivery}${agentId && !agentIsDefault ? `, agent=${agentId}` : ''})`);
135
174
  return 'created';
136
175
  }
137
176
  catch (err) {
@@ -27,12 +27,15 @@ export interface PollerCallbacks {
27
27
  onCandle: (data: CandleData) => void;
28
28
  /** Raw CCXT positions from fetch_positions — fires every 3s */
29
29
  onPositions: (positions: CcxtPosition[]) => void;
30
- /** Parsed balance from fetch_balance — fires every 10s */
30
+ /** Parsed balance from fetch_balance — fires every 10s. `extras` carries the
31
+ * plugin-computed day figures that ride on the same response when present. */
31
32
  onBalance: (balance: {
32
33
  currency: string;
33
34
  total: number;
34
35
  available: number;
35
36
  locked: number;
37
+ }, extras?: {
38
+ realizedPnlToday?: number;
36
39
  }) => void;
37
40
  /** Parsed open orders from fetch_open_orders — fires every 3s */
38
41
  onOpenOrders: (orders: OrderData[]) => void;
@@ -134,6 +137,11 @@ export declare class Poller {
134
137
  private pollOhlcv;
135
138
  private pollPositions;
136
139
  private pollBalance;
140
+ /** Poll positions NOW (same ban-gate + in-flight guard as the timer). The
141
+ * RED-zone guard calls this when the wallet/positions snapshot is torn by a
142
+ * fresh fill, so the tear closes in ~100 ms instead of waiting out the
143
+ * 10 s cadence (Ardi, report #6). No-op while paused/stopped/in-flight. */
144
+ refreshPositionsNow(): Promise<void>;
137
145
  private pollOpenOrders;
138
146
  private pollMarketStructure;
139
147
  /**
@@ -378,7 +378,17 @@ export class Poller {
378
378
  const tool = this.toolMap.fetch_balance;
379
379
  const result = await this.http.invoke(tool, {});
380
380
  const balance = mapCcxtBalance(result.data, this.quoteCurrency);
381
- this.callbacks.onBalance(balance);
381
+ const realized = result.data?.realizedPnlToday;
382
+ this.callbacks.onBalance(balance, typeof realized === 'number' && Number.isFinite(realized) ? { realizedPnlToday: realized } : undefined);
383
+ }
384
+ /** Poll positions NOW (same ban-gate + in-flight guard as the timer). The
385
+ * RED-zone guard calls this when the wallet/positions snapshot is torn by a
386
+ * fresh fill, so the tear closes in ~100 ms instead of waiting out the
387
+ * 10 s cadence (Ardi, report #6). No-op while paused/stopped/in-flight. */
388
+ refreshPositionsNow() {
389
+ if (!this.toolMap.fetch_positions)
390
+ return Promise.resolve();
391
+ return this.guardedExec('fetch_positions', () => this.pollPositions());
382
392
  }
383
393
  async pollOpenOrders() {
384
394
  const tool = this.toolMap.fetch_open_orders;
@@ -22,6 +22,9 @@ export declare const MAX_PER_SCAN = 5;
22
22
  export declare const MAX_POST_ATTEMPTS = 5;
23
23
  /** Cool down `cron.runs` for this long after it errors (older gateway). */
24
24
  export declare const CRON_RUNS_COOLDOWN_MS: number;
25
+ /** With nothing to read, ask `cron.runs` this often whether beats ran anyway
26
+ * (a store the recorder cannot read must not stay silent — Ardi, report #5). */
27
+ export declare const BLIND_PROBE_INTERVAL_MS: number;
25
28
  export type { AgentRunLifecycleData };
26
29
  /** What the recorder needs from the provider — kept narrow so it is trivially
27
30
  * mockable and the provider stays the only thing that talks to the gateway. */
@@ -41,6 +44,9 @@ export interface HeartbeatRunRecorderOptions {
41
44
  token: string;
42
45
  webappUrl?: string;
43
46
  sessionsDir?: string;
47
+ /** The agent database (OpenClaw >= 2026.9 transcript store); derived from
48
+ * `sessionsDir` when omitted. */
49
+ agentDbPath?: string;
44
50
  stateFile?: string;
45
51
  fetchImpl?: typeof fetch;
46
52
  now?: () => number;
@@ -58,6 +64,7 @@ export interface PostOutcome {
58
64
  export declare class HeartbeatRunRecorder {
59
65
  private readonly opts;
60
66
  private readonly sessionsDir;
67
+ private readonly agentDbPath;
61
68
  private readonly stateFile;
62
69
  private timer;
63
70
  private kickTimer;
@@ -67,6 +74,9 @@ export declare class HeartbeatRunRecorder {
67
74
  private readonly attempts;
68
75
  private cronRunsUnavailableUntil;
69
76
  private probeLogged;
77
+ private store;
78
+ private lastBlindProbeAt;
79
+ private blindWarned;
70
80
  /** Counters for a one-line health summary in logs. */
71
81
  readonly stats: {
72
82
  scans: number;
@@ -78,6 +88,9 @@ export declare class HeartbeatRunRecorder {
78
88
  };
79
89
  constructor(opts: HeartbeatRunRecorderOptions);
80
90
  private now;
91
+ /** Which store(s) are readable; logs on first sight and whenever it changes
92
+ * (the database appears when a gateway is upgraded under a running bridge). */
93
+ private detectStore;
81
94
  start(): void;
82
95
  stop(): void;
83
96
  /** A cron-session turn ended → scan shortly (debounced). */
@@ -88,8 +101,13 @@ export declare class HeartbeatRunRecorder {
88
101
  processed: number;
89
102
  deferred: number;
90
103
  }>;
91
- /** Is this session a heartbeat? Head marker first (cheap), trajectory key
92
- * second (covers a prompt without the marker), else not a heartbeat. */
104
+ /** Nothing to read this scan — were there beats anyway? `cron.runs` knows;
105
+ * a finished, unrecorded run inside the window means the recorder cannot
106
+ * see the store it should be reading. Warn once per process. */
107
+ private probeBlind;
108
+ /** Is this session a heartbeat? Session key first (the database carries it),
109
+ * head marker second (cheap), trajectory key third (covers a prompt without
110
+ * the marker), else not a heartbeat. */
93
111
  private classify;
94
112
  private fetchCronRunsSafe;
95
113
  /** POST one record to the webapp. Never throws. */