@reefclaw/openclaw-plugin 0.1.29 → 0.1.33

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) {
package/bridge/index.js CHANGED
@@ -8,7 +8,7 @@
8
8
  // Config precedence: CLI args > env vars > OpenClaw config > fallback env > defaults
9
9
  // See config.ts for full resolution logic.
10
10
  import { readFileSync } from 'fs';
11
- import { resolve, dirname } from 'path';
11
+ import { resolve, dirname, join } from 'path';
12
12
  import { fileURLToPath } from 'url';
13
13
  import { logger, setLogLevel } from './logger.js';
14
14
  import { Bridge } from './bridge.js';
@@ -122,37 +122,37 @@ function parseArgs() {
122
122
  return { cli, gateway };
123
123
  }
124
124
  function printUsage() {
125
- console.log(`
126
- ReefClaw Skill — Bridge between OpenClaw and ReefClaw relay
127
-
128
- Usage:
129
- tsx src/index.ts [options]
130
-
131
- Options:
132
- --provider, -p <mock|gateway> Provider type (default: mock)
133
- --token, -t <token> Connection token (or REEFCLAW_TOKEN env)
134
- --user-id, -u <id> User ID (or REEFCLAW_USER_ID env)
135
- --relay-url, -r <url> Relay URL (default: wss://reefclaw.radunlupsa.partykit.dev)
136
- --gateway-url <url> OpenClaw gateway URL (or OPENCLAW_GATEWAY_URL env)
137
- --gateway-token <token> OpenClaw gateway token (or OPENCLAW_GATEWAY_TOKEN env)
138
- --symbol <symbol> Trading symbol (default: BTC/USDT, or REEFCLAW_SYMBOL env)
139
- --agent-id <id> OpenClaw agent this bridge serves (default: main, or OPENCLAW_AGENT_ID env)
140
- --log-level, -l <level> Log level: debug, info, warn, error (default: info)
141
- --setup, -s [token] Run setup flow (validate token, test connection, save to config)
142
- --help, -h Show this help
143
-
144
- Relay config resolution (highest priority first):
145
- 1. CLI arguments (--token, --user-id, --relay-url)
146
- 2. Environment variables (REEFCLAW_TOKEN, REEFCLAW_USER_ID, REEFCLAW_RELAY_URL)
147
- 3. OpenClaw config file (~/.openclaw/openclaw.json → skills.entries.reefclaw)
148
- 4. Fallback env vars (MOCK_TOKEN, USER_ID)
149
- 5. Defaults (relay URL → wss://reefclaw.radunlupsa.partykit.dev)
150
-
151
- Gateway config resolution (for --provider gateway):
152
- 1. CLI arguments (--gateway-url, --gateway-token, --symbol, --agent-id)
153
- 2. Environment variables (OPENCLAW_GATEWAY_URL, OPENCLAW_GATEWAY_TOKEN, REEFCLAW_SYMBOL, OPENCLAW_AGENT_ID)
154
- 3. OpenClaw config file (~/.openclaw/openclaw.json → gateway.auth.token, gateway.port)
155
- 4. Defaults (http://localhost:18789, BTC/USDT)
125
+ console.log(`
126
+ ReefClaw Skill — Bridge between OpenClaw and ReefClaw relay
127
+
128
+ Usage:
129
+ tsx src/index.ts [options]
130
+
131
+ Options:
132
+ --provider, -p <mock|gateway> Provider type (default: mock)
133
+ --token, -t <token> Connection token (or REEFCLAW_TOKEN env)
134
+ --user-id, -u <id> User ID (or REEFCLAW_USER_ID env)
135
+ --relay-url, -r <url> Relay URL (default: wss://reefclaw.radunlupsa.partykit.dev)
136
+ --gateway-url <url> OpenClaw gateway URL (or OPENCLAW_GATEWAY_URL env)
137
+ --gateway-token <token> OpenClaw gateway token (or OPENCLAW_GATEWAY_TOKEN env)
138
+ --symbol <symbol> Trading symbol (default: BTC/USDT, or REEFCLAW_SYMBOL env)
139
+ --agent-id <id> OpenClaw agent this bridge serves (default: main, or OPENCLAW_AGENT_ID env)
140
+ --log-level, -l <level> Log level: debug, info, warn, error (default: info)
141
+ --setup, -s [token] Run setup flow (validate token, test connection, save to config)
142
+ --help, -h Show this help
143
+
144
+ Relay config resolution (highest priority first):
145
+ 1. CLI arguments (--token, --user-id, --relay-url)
146
+ 2. Environment variables (REEFCLAW_TOKEN, REEFCLAW_USER_ID, REEFCLAW_RELAY_URL)
147
+ 3. OpenClaw config file (~/.openclaw/openclaw.json → skills.entries.reefclaw)
148
+ 4. Fallback env vars (MOCK_TOKEN, USER_ID)
149
+ 5. Defaults (relay URL → wss://reefclaw.radunlupsa.partykit.dev)
150
+
151
+ Gateway config resolution (for --provider gateway):
152
+ 1. CLI arguments (--gateway-url, --gateway-token, --symbol, --agent-id)
153
+ 2. Environment variables (OPENCLAW_GATEWAY_URL, OPENCLAW_GATEWAY_TOKEN, REEFCLAW_SYMBOL, OPENCLAW_AGENT_ID)
154
+ 3. OpenClaw config file (~/.openclaw/openclaw.json → gateway.auth.token, gateway.port)
155
+ 4. Defaults (http://localhost:18789, BTC/USDT)
156
156
  `);
157
157
  }
158
158
  // ---- Main ----
@@ -200,6 +200,10 @@ async function main() {
200
200
  // Create provider
201
201
  let provider;
202
202
  let intelligenceUrlForWakes;
203
+ // The served agent's workspace + sessions (gateway/agent-scope.ts); undefined
204
+ // for the mock provider -> the bridge and recorder fall back to the legacy paths.
205
+ let bridgePaths;
206
+ let sessionsDir;
203
207
  if (args.provider === 'mock') {
204
208
  logger.info(TAG, 'Using MockProvider');
205
209
  provider = new MockProvider();
@@ -227,6 +231,13 @@ async function main() {
227
231
  logger.info(TAG, `Using GatewayProvider (url=${gwConfig.gatewayUrl}, symbol=${gwConfig.symbol})`);
228
232
  provider = new GatewayProvider(gwConfig);
229
233
  intelligenceUrlForWakes = gwConfig.intelligenceUrl;
234
+ if (gwConfig.agentWorkspaceDir && gwConfig.agentSessionsDir) {
235
+ bridgePaths = {
236
+ workspaceDir: gwConfig.agentWorkspaceDir,
237
+ sessionsJsonPath: join(gwConfig.agentSessionsDir, 'sessions.json'),
238
+ };
239
+ sessionsDir = gwConfig.agentSessionsDir;
240
+ }
230
241
  }
231
242
  // Create bridge
232
243
  const connectorConfig = {
@@ -237,7 +248,7 @@ async function main() {
237
248
  // same-box restart (instant takeover) vs a second box (rejected 4011).
238
249
  instanceId: resolveRelayInstanceId(),
239
250
  };
240
- const bridge = new Bridge(provider, connectorConfig);
251
+ const bridge = new Bridge(provider, connectorConfig, bridgePaths);
241
252
  // Shock-wake poller (WS3, docs/MARKET_ADAPTIVITY_PLAN.md) — watches intel's
242
253
  // /api/shocks (the WS2 change-of-character flags) and delivers an
243
254
  // out-of-band re-evaluation turn to the agent on a genuine market shift.
@@ -257,7 +268,7 @@ async function main() {
257
268
  // (the mock has no OpenClaw sessions dir). Kill-switch: RC_HEARTBEAT_RECORDER=off.
258
269
  const recorderOff = (process.env.RC_HEARTBEAT_RECORDER ?? 'on').trim().toLowerCase() === 'off';
259
270
  const heartbeatRecorder = provider instanceof GatewayProvider && !recorderOff
260
- ? new HeartbeatRunRecorder({ source: provider, token })
271
+ ? new HeartbeatRunRecorder({ source: provider, token, ...(sessionsDir ? { sessionsDir } : {}) })
261
272
  : null;
262
273
  if (recorderOff)
263
274
  logger.info(TAG, 'Heartbeat flight recorder disabled (RC_HEARTBEAT_RECORDER=off)');
@@ -72,6 +72,11 @@ export interface StartOptions {
72
72
  acknowledgeOpenPositions?: boolean;
73
73
  /** Count of currently-open positions, as the skill sees them. */
74
74
  openPositionCount: number;
75
+ /** The agent that owns the terminal. REQUIRED by OpenClaw 2026.9 when the
76
+ * gateway hosts several agents ("Multiple agents are configured, but this
77
+ * operation has no explicit owner"); omitted on a single-agent gateway so
78
+ * every existing box sends the byte-identical request. */
79
+ agentId?: string;
75
80
  }
76
81
  /**
77
82
  * Guard the restart hazard. The installer restarts the gateway; with positions
@@ -192,7 +192,11 @@ export async function startConnectorUpdate(rpc, opts) {
192
192
  }
193
193
  let opened;
194
194
  try {
195
- opened = await rpc('terminal.open', { cols: COLS, rows: ROWS });
195
+ opened = await rpc('terminal.open', {
196
+ cols: COLS,
197
+ rows: ROWS,
198
+ ...(opts.agentId ? { agentId: opts.agentId } : {}),
199
+ });
196
200
  }
197
201
  catch (err) {
198
202
  const outcome = describeOpenFailure(err);
@@ -45,6 +45,9 @@ export declare class GatewayProvider implements OpenClawProvider {
45
45
  /** The OpenClaw agent this bridge serves: chat goes to it, and only its runs
46
46
  * reach the dashboard (gateway/agent-scope.ts). */
47
47
  private agentId;
48
+ /** The served agent's OpenClaw workspace (gateway-config.ts resolves it by
49
+ * OpenClaw's own rule); the legacy path for hand-built configs. */
50
+ private workspaceDir;
48
51
  /** Emit the one-time rollout probe (gateway response shape) only on the first attempt. */
49
52
  private loggedAgentIdentityProbe;
50
53
  /** Last IDENTITY.md read (epoch ms) — TTL gate for the display-name re-read. */
@@ -32,14 +32,19 @@ const TAG = 'gateway';
32
32
  const DAY_NAV_FILENAME = 'day-start-nav.json';
33
33
  const LEGACY_DAY_NAV_FILENAME = 'session-nav.json';
34
34
  const TRADING_MODE_FILENAME = 'trading-mode.json';
35
- function getDayNavPath() {
36
- return join(homedir(), '.openclaw', 'workspace', DAY_NAV_FILENAME);
35
+ /** The legacy single-agent workspace - what every box used before the bridge
36
+ * learned to follow a non-default agent (gateway/agent-scope.ts). Still the
37
+ * path for the default agent, so existing day-NAV/trading-mode files are
38
+ * read from exactly where they were written. */
39
+ const LEGACY_WORKSPACE_DIR = join(homedir(), '.openclaw', 'workspace');
40
+ function getDayNavPath(workspaceDir) {
41
+ return join(workspaceDir, DAY_NAV_FILENAME);
37
42
  }
38
- function getLegacyDayNavPath() {
39
- return join(homedir(), '.openclaw', 'workspace', LEGACY_DAY_NAV_FILENAME);
43
+ function getLegacyDayNavPath(workspaceDir) {
44
+ return join(workspaceDir, LEGACY_DAY_NAV_FILENAME);
40
45
  }
41
- function getTradingModePath() {
42
- return join(homedir(), '.openclaw', 'workspace', TRADING_MODE_FILENAME);
46
+ function getTradingModePath(workspaceDir) {
47
+ return join(workspaceDir, TRADING_MODE_FILENAME);
43
48
  }
44
49
  function todayDateStr() {
45
50
  return new Date().toISOString().slice(0, 10);
@@ -70,8 +75,8 @@ export function shouldSyncPluginSessionNav(pluginNav, currentNav) {
70
75
  && pluginNav > 0
71
76
  && Math.abs(currentNav - pluginNav) > 0.001;
72
77
  }
73
- function loadSessionStartNav() {
74
- for (const path of [getDayNavPath(), getLegacyDayNavPath()]) {
78
+ function loadSessionStartNav(workspaceDir) {
79
+ for (const path of [getDayNavPath(workspaceDir), getLegacyDayNavPath(workspaceDir)]) {
75
80
  try {
76
81
  const raw = readFileSync(path, 'utf-8');
77
82
  const data = JSON.parse(raw);
@@ -95,9 +100,9 @@ function loadSessionStartNav() {
95
100
  * trading_mode event in fetchFreshBalance() — but until then, this prevents
96
101
  * the visible PAPER flash.
97
102
  */
98
- function loadLastTradingMode() {
103
+ function loadLastTradingMode(workspaceDir) {
99
104
  try {
100
- const raw = readFileSync(getTradingModePath(), 'utf-8');
105
+ const raw = readFileSync(getTradingModePath(workspaceDir), 'utf-8');
101
106
  const data = JSON.parse(raw);
102
107
  if (isTradingMode(data.mode)) {
103
108
  return data.mode;
@@ -108,25 +113,23 @@ function loadLastTradingMode() {
108
113
  return null;
109
114
  }
110
115
  }
111
- function saveLastTradingMode(mode) {
116
+ function saveLastTradingMode(workspaceDir, mode) {
112
117
  try {
113
- const dir = join(homedir(), '.openclaw', 'workspace');
114
- mkdirSync(dir, { recursive: true });
118
+ mkdirSync(workspaceDir, { recursive: true });
115
119
  const data = { mode, savedAt: new Date().toISOString() };
116
- writeFileSync(getTradingModePath(), JSON.stringify(data, null, 2), 'utf-8');
120
+ writeFileSync(getTradingModePath(workspaceDir), JSON.stringify(data, null, 2), 'utf-8');
117
121
  }
118
122
  catch {
119
123
  /* non-fatal — next save will retry */
120
124
  }
121
125
  }
122
- function saveSessionStartNav(nav) {
126
+ function saveSessionStartNav(workspaceDir, nav) {
123
127
  try {
124
- const dir = join(homedir(), '.openclaw', 'workspace');
125
- mkdirSync(dir, { recursive: true });
128
+ mkdirSync(workspaceDir, { recursive: true });
126
129
  const data = { date: todayDateStr(), sessionStartNav: nav };
127
- writeFileSync(getDayNavPath(), JSON.stringify(data, null, 2), 'utf-8');
130
+ writeFileSync(getDayNavPath(workspaceDir), JSON.stringify(data, null, 2), 'utf-8');
128
131
  try {
129
- unlinkSync(getLegacyDayNavPath());
132
+ unlinkSync(getLegacyDayNavPath(workspaceDir));
130
133
  }
131
134
  catch { /* legacy file already gone */ }
132
135
  }
@@ -167,6 +170,11 @@ export class GatewayProvider {
167
170
  agentId() {
168
171
  return this.config.agentId ?? DEFAULT_AGENT_ID;
169
172
  }
173
+ /** The served agent's OpenClaw workspace (gateway-config.ts resolves it by
174
+ * OpenClaw's own rule); the legacy path for hand-built configs. */
175
+ workspaceDir() {
176
+ return this.config.agentWorkspaceDir ?? LEGACY_WORKSPACE_DIR;
177
+ }
170
178
  /** Emit the one-time rollout probe (gateway response shape) only on the first attempt. */
171
179
  loggedAgentIdentityProbe = false;
172
180
  /** Last IDENTITY.md read (epoch ms) — TTL gate for the display-name re-read. */
@@ -310,7 +318,7 @@ export class GatewayProvider {
310
318
  // mode change. Falls back to 'PAPER' only on first-ever boot (or after
311
319
  // file is corrupt/deleted). Prevents the "dashboard flashes PAPER on every
312
320
  // skill restart" UX bug — see saveLastTradingMode() comment above.
313
- tradingMode = loadLastTradingMode() ?? 'PAPER';
321
+ tradingMode = 'PAPER';
314
322
  listeners = {
315
323
  ticker: new Set(),
316
324
  candle: new Set(),
@@ -339,6 +347,9 @@ export class GatewayProvider {
339
347
  };
340
348
  constructor(config) {
341
349
  this.config = config;
350
+ // Field initialisers run before parameter properties are assigned, so the
351
+ // workspace-dependent restore happens here, not on the field.
352
+ this.tradingMode = loadLastTradingMode(this.workspaceDir()) ?? 'PAPER';
342
353
  // Extract quote currency from symbol (e.g. "BTC/USDT" -> "USDT")
343
354
  const parts = config.symbol.split('/');
344
355
  this.quoteCurrency = parts.length > 1 ? parts[1] : 'USDT';
@@ -768,7 +779,14 @@ export class GatewayProvider {
768
779
  return { ok: false, status: 'failed', message: 'Not connected to the OpenClaw gateway.' };
769
780
  }
770
781
  const openPositionCount = this.positions.filter((p) => Math.abs(Number(p.contracts) || 0) > 0).length;
771
- const guardArgs = { acknowledgeOpenPositions: args.acknowledgeOpenPositions, openPositionCount };
782
+ const guardArgs = {
783
+ acknowledgeOpenPositions: args.acknowledgeOpenPositions,
784
+ openPositionCount,
785
+ // On a multi-agent gateway OpenClaw 2026.9 refuses an owner-less
786
+ // terminal.open ("no explicit owner"); the PTY belongs to the agent we
787
+ // serve. Single-agent boxes keep the historical request.
788
+ ...(this.config.agentSharedGateway ? { agentId: this.agentId() } : {}),
789
+ };
772
790
  // Position guard FIRST — never open an admin session for a request that is
773
791
  // going to be refused anyway.
774
792
  const blocked = checkPositionGuard(guardArgs);
@@ -999,7 +1017,7 @@ export class GatewayProvider {
999
1017
  // the marker exists, every session runs on operator.read/write alone.
1000
1018
  this.wsClient = new GatewayWsClient({
1001
1019
  ...this.config,
1002
- requestAdminScope: !existsSync(join(homedir(), '.openclaw', 'workspace', 'heartbeat-cron-ensured.json')),
1020
+ requestAdminScope: !existsSync(join(this.workspaceDir(), 'heartbeat-cron-ensured.json')),
1003
1021
  });
1004
1022
  this.wireWsEvents();
1005
1023
  // Wait for WS handshake to complete (or fail)
@@ -1361,8 +1379,13 @@ export class GatewayProvider {
1361
1379
  if (ws) {
1362
1380
  void ensureHeartbeatCron({
1363
1381
  rpc: ws,
1364
- markerPath: join(homedir(), '.openclaw', 'workspace', 'heartbeat-cron-ensured.json'),
1382
+ markerPath: join(this.workspaceDir(), 'heartbeat-cron-ensured.json'),
1365
1383
  log: (msg) => logger.info(TAG, msg),
1384
+ // Scoped to the agent we serve: on a shared gateway the business
1385
+ // agent's own heartbeat must not suppress the trading agent's, and
1386
+ // a non-default agent's job carries agentId so it runs THERE.
1387
+ agentId: this.agentId(),
1388
+ agentIsDefault: this.config.agentIsDefault ?? true,
1366
1389
  }).then((outcome) => {
1367
1390
  // A transient failure retries on the next (re)connect, not just next boot.
1368
1391
  if (outcome === 'failed')
@@ -1801,7 +1824,7 @@ export class GatewayProvider {
1801
1824
  // Try loading from file first (persisted across restarts within same day).
1802
1825
  // loadSessionStartNav() itself returns null on a different day, so on a
1803
1826
  // fresh UTC day this falls through to recompute.
1804
- const saved = loadSessionStartNav();
1827
+ const saved = loadSessionStartNav(this.workspaceDir());
1805
1828
  if (saved !== null) {
1806
1829
  this.sessionStartNav = saved;
1807
1830
  this.sessionDate = today;
@@ -1811,7 +1834,7 @@ export class GatewayProvider {
1811
1834
  // First anchor of the (UTC) day — compute and persist.
1812
1835
  this.sessionStartNav = this.computeEquity();
1813
1836
  this.sessionDate = today;
1814
- saveSessionStartNav(this.sessionStartNav);
1837
+ saveSessionStartNav(this.workspaceDir(), this.sessionStartNav);
1815
1838
  logger.info(TAG, `Session start NAV: ${this.sessionStartNav} ${this.quoteCurrency} (wallet=${this.balance.total}, positions=${this.positions.length})`);
1816
1839
  }
1817
1840
  onPollerOpenOrders(orders) {
@@ -1934,7 +1957,7 @@ export class GatewayProvider {
1934
1957
  // up reading the correct value instead of the 'PAPER' constructor
1935
1958
  // default. Cheap, idempotent — safe to write on every balance fetch
1936
1959
  // even when no transition happened.
1937
- saveLastTradingMode(mode);
1960
+ saveLastTradingMode(this.workspaceDir(), mode);
1938
1961
  if (mode !== this.tradingMode) {
1939
1962
  const prevMode = this.tradingMode;
1940
1963
  this.tradingMode = mode;
@@ -1954,11 +1977,11 @@ export class GatewayProvider {
1954
1977
  this.hasReceivedPositions = false;
1955
1978
  this.pendingEmptyPoll = false;
1956
1979
  try {
1957
- unlinkSync(getDayNavPath());
1980
+ unlinkSync(getDayNavPath(this.workspaceDir()));
1958
1981
  }
1959
1982
  catch { /* ok if missing */ }
1960
1983
  try {
1961
- unlinkSync(getLegacyDayNavPath());
1984
+ unlinkSync(getLegacyDayNavPath(this.workspaceDir()));
1962
1985
  }
1963
1986
  catch { /* ok if missing */ }
1964
1987
  logger.info(TAG, `Session start NAV reset on mode change (${prevMode} → ${this.tradingMode})`);
@@ -2007,7 +2030,7 @@ export class GatewayProvider {
2007
2030
  // Stamp the day so the PAPER self-seed path (shouldAnchorSessionNav
2008
2031
  // re-anchors on a stale sessionDate) doesn't flap against the sync.
2009
2032
  this.sessionDate = todayDateStr();
2010
- saveSessionStartNav(pluginNav);
2033
+ saveSessionStartNav(this.workspaceDir(), pluginNav);
2011
2034
  logger.info(TAG, `Session start NAV synced from plugin: ${prev.toFixed(4)} -> ${pluginNav} (${this.tradingMode} mode)`);
2012
2035
  }
2013
2036
  }
@@ -2389,7 +2412,8 @@ export class GatewayProvider {
2389
2412
  resolveAgentNameFromIdentity() {
2390
2413
  const candidates = [
2391
2414
  process.env.OPENCLAW_WORKSPACE ? join(process.env.OPENCLAW_WORKSPACE, 'IDENTITY.md') : undefined,
2392
- join(homedir(), '.openclaw', 'workspace', 'IDENTITY.md'),
2415
+ join(this.workspaceDir(), 'IDENTITY.md'),
2416
+ join(LEGACY_WORKSPACE_DIR, 'IDENTITY.md'),
2393
2417
  ].filter((p) => !!p);
2394
2418
  for (const p of candidates) {
2395
2419
  try {
@@ -1,7 +1,7 @@
1
1
  /** Extract version from SKILL.md frontmatter */
2
2
  export declare function parseSkillVersion(content: string): string | null;
3
3
  /** Read current SKILL.md version from disk */
4
- export declare function readLocalSkillVersion(): string | null;
4
+ export declare function readLocalSkillVersion(workspaceDir?: string): string | null;
5
5
  /** Versions of the AGENT-VISIBLE reefclaw SKILL.md copies under the
6
6
  * plugin-extension layout (`~/.openclaw/extensions/<plugin>/skills/<skill>/`)
7
7
  * — what OpenClaw's skill loader actually reads on chat-channel installs.
@@ -2,16 +2,17 @@
2
2
  import { readFileSync, readdirSync } from 'fs';
3
3
  import { join } from 'path';
4
4
  import { homedir } from 'os';
5
- const SKILL_MD_PATH = join(homedir(), '.openclaw', 'workspace', 'SKILL.md');
5
+ /** Legacy single-agent location; callers serving another agent pass its workspace. */
6
+ const DEFAULT_WORKSPACE_DIR = join(homedir(), '.openclaw', 'workspace');
6
7
  /** Extract version from SKILL.md frontmatter */
7
8
  export function parseSkillVersion(content) {
8
9
  const match = content.match(/^---[\s\S]*?version:\s*(\S+)[\s\S]*?---/);
9
10
  return match ? match[1] : null;
10
11
  }
11
12
  /** Read current SKILL.md version from disk */
12
- export function readLocalSkillVersion() {
13
+ export function readLocalSkillVersion(workspaceDir = DEFAULT_WORKSPACE_DIR) {
13
14
  try {
14
- const content = readFileSync(SKILL_MD_PATH, 'utf-8');
15
+ const content = readFileSync(join(workspaceDir, 'SKILL.md'), 'utf-8');
15
16
  return parseSkillVersion(content);
16
17
  }
17
18
  catch {
@@ -1,5 +1,5 @@
1
1
  /** Default location of OpenClaw's session index. */
2
- export declare function defaultSessionsJsonPath(): string;
2
+ export declare function defaultSessionsJsonPath(agentId?: string): string;
3
3
  export type SnapshotInvalidationOutcome =
4
4
  /** Removed the key from >= 1 session entry — the agent will re-read SKILL.md. */
5
5
  'invalidated'
@@ -28,8 +28,8 @@ import { existsSync, readFileSync, writeFileSync } from 'fs';
28
28
  import { join } from 'path';
29
29
  import { homedir } from 'os';
30
30
  /** Default location of OpenClaw's session index. */
31
- export function defaultSessionsJsonPath() {
32
- return join(homedir(), '.openclaw', 'agents', 'main', 'sessions', 'sessions.json');
31
+ export function defaultSessionsJsonPath(agentId = 'main') {
32
+ return join(homedir(), '.openclaw', 'agents', agentId, 'sessions', 'sessions.json');
33
33
  }
34
34
  /**
35
35
  * Surgically delete every `skillsSnapshot` key from sessions.json, preserving
@@ -355,6 +355,12 @@ export function startReadinessReporter(opts) {
355
355
  publicApi: opts.publicApi,
356
356
  toolCount: opts.toolCount,
357
357
  resolveStopProtection: opts.resolveStopProtection,
358
+ // The dashboard's update banner reads these off EVERY post (boot and
359
+ // periodic). 0.1.28-0.1.29 received them here and dropped them, so
360
+ // every updated box posted agent:{} without a version and the banner
361
+ // went silent for it (found 2026-09-16 on the rig).
362
+ pluginVersion: opts.pluginVersion,
363
+ installChannel: opts.installChannel,
358
364
  }, bootWarmup, { state });
359
365
  await postReadiness(opts.apiBaseUrl, opts.token, report, fetchImpl, timeoutMs);
360
366
  if (report.overall === 'fail') {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "id": "reefclaw-paper-trading",
3
3
  "name": "ReefClaw Trading",
4
- "version": "0.1.29",
4
+ "version": "0.1.33",
5
5
  "description": "Supervised trading plugin for the ReefClaw dashboard. It runs on YOUR machine and starts in PAPER mode with no API keys. It cannot trade real funds until you supply exchange credentials and step PAPER→MICRO_LIVE→LIVE yourself from the dashboard — the agent cannot make that change (the tool is refused without operator provenance). Exchange keys stay local, are used only to sign requests to the exchange, and are never transmitted to ReefClaw (asserted by a test in this package). Trading telemetry — positions, fills, decision journal — is sent to ReefClaw to render the dashboard. Every live position carries exchange-native protective stops. Remote updates to the agent's trading instructions are applied only after an Ed25519 signature is verified against a public key pinned in this build.",
6
6
  "author": "ReefClaw",
7
7
  "activation": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reefclaw/openclaw-plugin",
3
- "version": "0.1.29",
3
+ "version": "0.1.33",
4
4
  "description": "ReefClaw supervised trading plugin for OpenClaw. Runs entirely on YOUR machine and starts in PAPER mode — it cannot trade real funds until you supply exchange credentials and walk the PAPER→MICRO_LIVE→LIVE ladder yourself from the ReefClaw dashboard (the agent cannot make that change; it is refused without operator provenance). Your exchange API keys stay on your machine to sign requests to the exchange and are NEVER sent to ReefClaw — a test in the package asserts this. What does reach ReefClaw is trading telemetry for the dashboard (positions, fills, decision journal). Live trading always carries exchange-native protective stops. Trading instructions can be updated remotely, and every update must carry a valid Ed25519 signature verified against a key pinned in this build before it is applied. Install: npx --yes @reefclaw/connect, or from ClawHub on OpenClaw 2026.8.1+ (Control UI Plugins > Discover, or /plugins install clawhub:@reefclaw/openclaw-plugin then the same with --accept-capabilities after reviewing the listed capabilities)",
5
5
  "type": "module",
6
6
  "main": "index.js",
@@ -2,5 +2,7 @@
2
2
  "_comment": "One line per released plugin version, shown in the dashboard's update banner. Baked into the webapp at build by webapp/scripts/generate-skill-content.mjs (LATEST_PLUGIN_NOTES = the entry for plugin-package/package.json#version). Add a line in the same PR that bumps the version.",
3
3
  "0.1.27": "Fixes paper positions showing as closed at $0 in the Journal while still open, and adds a 2-minute grace to the position reconciler.",
4
4
  "0.1.28": "Fixes the connector's gateway handshake on OpenClaw 2026.9+ (it now connects as OpenClaw's local-backend client) and adds in-app update notices with one-click updates.",
5
- "0.1.29": "Paper stop and target fills now use the price the decision was made on when the cached order book is stale (paper P&L gets more honest); on a gateway with several agents the connector shows only its own agent's runs; one-click updates can be switched off per box."
5
+ "0.1.29": "Paper stop and target fills now use the price the decision was made on when the cached order book is stale (paper P&L gets more honest); on a gateway with several agents the connector shows only its own agent's runs; one-click updates can be switched off per box.",
6
+ "0.1.30": "Restores the connector's version reporting, so the dashboard's update notice works again for boxes that already updated (0.1.28 and 0.1.29 reported no version and could not be nudged).",
7
+ "0.1.33": "Adds npx @reefclaw/connect --agent <id> for gateways that host several agents: the trading skill, heartbeat and dashboard attach to that agent and the trading tools are denied to the others."
6
8
  }