@mearl/cloud-connector 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,141 @@
1
+ # @mearl/cloud-connector
2
+
3
+ 本地连接器,用于将本地的 native-host 通过 WebSocket 连接到云端 Server。
4
+
5
+ ## 安装
6
+
7
+ ```bash
8
+ npm install -g @mearl/cloud-connector
9
+ # 或
10
+ pnpm add -g @mearl/cloud-connector
11
+ ```
12
+
13
+ ## 两种管理模式
14
+
15
+ 连接器同时支持两种生命周期管理方式,二者通过同一份共享注册表互通(见[运行时文件](#运行时文件)),不会对同一个 `server-url` 重复建连:
16
+
17
+ 1. **被 native-host 托管** —— 在浏览器插件面板里点击连接时,native-host 会自动以**前台进程**方式拉起连接器并监听其状态。无需手动操作。
18
+ 2. **自管理(守护进程)** —— 在终端用 `start` / `stop` 等子命令把连接器作为后台守护进程管理,拥有独立日志文件,便于在无插件面板的场景(如远程机器、排查问题)下使用。
19
+
20
+ ## 使用
21
+
22
+ ```bash
23
+ mearl-cloud-connector <server-url> [options] # 前台运行
24
+ mearl-cloud-connector <command> [server-url] [options] # 管理后台守护进程
25
+ ```
26
+
27
+ **参数:**
28
+
29
+ - `server-url` —— 云端 WebSocket Server 地址(包含 token,如 `ws://host:port/ws?token=xxx`)
30
+
31
+ **子命令:**
32
+
33
+ - `start <server-url>` —— 后台启动守护进程(幂等:已有存活连接器则复用)
34
+ - `stop <server-url>` —— 停止指定 `server-url` 的后台连接器
35
+ - `stop --all` —— 停止所有后台连接器
36
+ - `restart <server-url>` —— 重启指定连接器
37
+ - `status [server-url]` —— 查看某连接器状态;省略 `server-url` 时列出全部
38
+ - `list` —— 列出所有正在运行的连接器
39
+ - `logs <server-url>` —— 打印某连接器日志末尾
40
+
41
+ **选项:**
42
+
43
+ - `--foreground` / `-f` —— 前台运行(不守护化)
44
+ - `--heartbeat <seconds>` —— 心跳间隔(默认 30 秒)
45
+ - `--reconnect <ms>` —— 重连间隔(默认 5000 毫秒)
46
+ - `--max-reconnect <n>` —— 最大重连次数,-1 表示无限(默认 -1)
47
+ - `--fail-fast` —— 首次连接失败即退出(供 native-host 探测启动结果)
48
+
49
+ **示例:**
50
+
51
+ ```bash
52
+ # 前台运行(Ctrl+C 停止)—— 也是 native-host 拉起连接器的方式
53
+ mearl-cloud-connector "ws://localhost:8080/ws?token=xxx"
54
+
55
+ # 后台启动一个自管理连接器,拥有独立日志文件
56
+ mearl-cloud-connector start "wss://cloud.example.com/ws?token=xxx"
57
+
58
+ # 查看状态 / 列表 / 日志
59
+ mearl-cloud-connector status
60
+ mearl-cloud-connector list
61
+ mearl-cloud-connector logs "wss://cloud.example.com/ws?token=xxx"
62
+
63
+ # 停止
64
+ mearl-cloud-connector stop "wss://cloud.example.com/ws?token=xxx"
65
+ mearl-cloud-connector stop --all
66
+
67
+ # 自定义心跳和重连配置
68
+ mearl-cloud-connector "ws://localhost:8080/ws?token=xxx" --heartbeat 60 --max-reconnect 10
69
+ ```
70
+
71
+ ### 编程方式
72
+
73
+ ```typescript
74
+ import { CloudConnector } from '@mearl/cloud-connector';
75
+
76
+ const connector = new CloudConnector({
77
+ serverUrl: 'wss://cloud.example.com/ws?token=xxx',
78
+ heartbeatInterval: 30,
79
+ reconnectInterval: 5000,
80
+ maxReconnectAttempts: -1,
81
+ onConnected: url => console.log('connected to', url),
82
+ });
83
+
84
+ connector.connect();
85
+
86
+ // 优雅关闭
87
+ process.on('SIGINT', () => {
88
+ connector.disconnect();
89
+ process.exit(0);
90
+ });
91
+ ```
92
+
93
+ ## 运行时文件
94
+
95
+ 每个连接器实例在 `~/.mearl/connectors/` 下按 `server-url` 哈希生成一对文件:
96
+
97
+ - `<hash>.json` —— 连接记录(含 `serverUrl`、`pid`、`startedAt`)。**连接器进程是该记录的唯一写入方**:连上时写入、优雅退出时删除(崩溃残留的记录会被读取方按 pid 存活性自动清理)。
98
+ - `<hash>.log` —— 守护进程日志(`logs` 子命令读取,或 `tail -f` 跟踪);超过 5MB 会在下次启动时滚动为 `<hash>.log.1`。
99
+
100
+ native-host 与守护进程 CLI 都通过这套共享路径(由 [`@mearl/daemon-core`](../../daemon-core) 派生)读取注册表,因此一方启动的连接器另一方也能发现、复用或停止。
101
+
102
+ > 前台运行(含 native-host 托管)时日志输出到 stdout/stderr,不写独立日志文件;只有守护进程模式才落盘到 `<hash>.log`。
103
+
104
+ ## 前置条件
105
+
106
+ 1. **安装 @mearl/native-host**
107
+ ```bash
108
+ npm install -g @mearl/native-host
109
+ ```
110
+ 或使用本项目的 monorepo 构建产物。
111
+
112
+ 2. **确保 native-host 已初始化**
113
+ ```bash
114
+ mearl-native-host --init
115
+ ```
116
+
117
+ 3. **确保 Chrome 浏览器正在运行**,且:
118
+ - 已安装 Mearl 浏览器插件,或
119
+ - 已在 `chrome://inspect/#remote-debugging` 启用远程调试(Chrome 145+)
120
+
121
+ ## 架构
122
+
123
+ ```
124
+ 云端 Agent
125
+ ↓
126
+ @mearl/cloud-client
127
+ ↓
128
+ @mearl/cloud-server
129
+ ↓ (WebSocket)
130
+ @mearl/cloud-connector (本进程)
131
+ ↓ (Unix Socket)
132
+ @mearl/native-host
133
+ ↓
134
+ Chrome Extension / CDP
135
+ ```
136
+
137
+ ## 注意事项
138
+
139
+ - 连接器需要保持运行才能转发云端请求。被 native-host 托管时,连接器以 `detached` 方式启动,会**在插件重载/更新后继续存活**;自管理时由 `start`/`stop` 子命令掌控生命周期。
140
+ - 前台模式若想交给外部进程管理器(systemd / PM2)托管,加 `--foreground` 让其在前台运行并由管理器负责守护重启。
141
+ - 支持断线自动重连(可在配置中调整);瞬时断连期间连接记录会保留,仅在进程退出时清除。
@@ -0,0 +1 @@
1
+ export {};
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,449 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/daemon.ts
4
+ import { fileURLToPath } from "node:url";
5
+ import {
6
+ createDaemon,
7
+ readLiveRecords,
8
+ removeRecord,
9
+ writeRecord
10
+ } from "@mearl/daemon-core";
11
+
12
+ // src/index.ts
13
+ import WebSocket from "ws";
14
+ import {
15
+ isHeartbeatMessage,
16
+ MAX_BUFFER_SIZE,
17
+ DEFAULT_HEARTBEAT_INTERVAL
18
+ } from "@mearl/cloud-types";
19
+ import { resolveActionTimeoutSec } from "@mearl/client/action-timeouts";
20
+ var DEFAULT_RECONNECT_INTERVAL = 5e3;
21
+ var BACKOFF_BASE_MS = 1e3;
22
+ var BACKOFF_MAX_MS = 3e4;
23
+ var SLOW_PROBE_INTERVAL_MS = 6e4;
24
+ var FAST_RECONNECT_ATTEMPTS = 5;
25
+ var CloudConnector = class {
26
+ options;
27
+ ws = null;
28
+ heartbeatTimer = null;
29
+ reconnectTimer = null;
30
+ reconnectAttempts = 0;
31
+ messageBuffer = "";
32
+ isManualClose = false;
33
+ shouldTryWss = false;
34
+ wssRetryAttempts = 0;
35
+ maxWssRetryAttempts = 1;
36
+ hasConnected = false;
37
+ lastConnectionError = null;
38
+ constructor(options) {
39
+ this.options = {
40
+ serverUrl: options.serverUrl,
41
+ heartbeatInterval: options.heartbeatInterval ?? DEFAULT_HEARTBEAT_INTERVAL,
42
+ reconnectInterval: options.reconnectInterval ?? DEFAULT_RECONNECT_INTERVAL,
43
+ maxReconnectAttempts: options.maxReconnectAttempts ?? -1,
44
+ failFast: options.failFast ?? false,
45
+ onInitialConnectionFailed: options.onInitialConnectionFailed,
46
+ onConnected: options.onConnected
47
+ };
48
+ }
49
+ connect() {
50
+ if (this.ws && (this.ws.readyState === 0 || this.ws.readyState === 1)) {
51
+ return;
52
+ }
53
+ let serverUrl = this.options.serverUrl;
54
+ if (this.shouldTryWss && serverUrl.startsWith("ws://")) {
55
+ serverUrl = serverUrl.replace("ws://", "wss://");
56
+ console.log(`[CloudConnector] Retrying with wss://: ${serverUrl}`);
57
+ }
58
+ this.ws = new WebSocket(serverUrl);
59
+ this.ws.on("open", () => {
60
+ console.log(`[CloudConnector] Connected to ${serverUrl}`);
61
+ this.hasConnected = true;
62
+ this.lastConnectionError = null;
63
+ this.reconnectAttempts = 0;
64
+ this.shouldTryWss = false;
65
+ this.wssRetryAttempts = 0;
66
+ this.startHeartbeat();
67
+ this.options.onConnected?.(this.options.serverUrl);
68
+ });
69
+ this.ws.on("message", (data) => {
70
+ this.handleMessage(data);
71
+ });
72
+ this.ws.on("close", (code, reason) => {
73
+ console.log(`[CloudConnector] Disconnected (${code}: ${reason.toString()})`);
74
+ this.stopHeartbeat();
75
+ this.messageBuffer = "";
76
+ if (this.shouldTryWss && serverUrl.startsWith("ws://")) {
77
+ return;
78
+ }
79
+ if (this.options.failFast && !this.hasConnected) {
80
+ const reasonText = reason.toString();
81
+ const message = this.lastConnectionError || reasonText || `Connection closed (${code})`;
82
+ this.options.onInitialConnectionFailed?.(message);
83
+ return;
84
+ }
85
+ this.tryReconnect();
86
+ });
87
+ this.ws.on("error", (error) => {
88
+ console.error(`[CloudConnector] WebSocket error:`, error.message);
89
+ this.lastConnectionError = error.message;
90
+ if (error.message.includes("301") && !this.shouldTryWss && serverUrl.startsWith("ws://") && this.wssRetryAttempts < this.maxWssRetryAttempts) {
91
+ this.shouldTryWss = true;
92
+ this.wssRetryAttempts++;
93
+ this.ws = null;
94
+ console.log(
95
+ `[CloudConnector] Server requires wss://, retrying (${this.wssRetryAttempts}/${this.maxWssRetryAttempts})...`
96
+ );
97
+ setTimeout(() => this.connect(), 1e3);
98
+ }
99
+ });
100
+ }
101
+ disconnect() {
102
+ this.isManualClose = true;
103
+ this.stopHeartbeat();
104
+ if (this.reconnectTimer) {
105
+ clearTimeout(this.reconnectTimer);
106
+ this.reconnectTimer = null;
107
+ }
108
+ if (this.ws) {
109
+ this.ws.close();
110
+ this.ws = null;
111
+ }
112
+ }
113
+ handleMessage(data) {
114
+ this.messageBuffer += data.toString("utf-8");
115
+ if (this.messageBuffer.length > MAX_BUFFER_SIZE) {
116
+ console.error("[CloudConnector] Message buffer exceeds limit, closing connection");
117
+ this.disconnect();
118
+ return;
119
+ }
120
+ let newlineIndex;
121
+ while ((newlineIndex = this.messageBuffer.indexOf("\n")) !== -1) {
122
+ const line = this.messageBuffer.slice(0, newlineIndex);
123
+ this.messageBuffer = this.messageBuffer.slice(newlineIndex + 1);
124
+ if (!line.trim()) continue;
125
+ try {
126
+ const message = JSON.parse(line);
127
+ this.handleCloudMessage(message);
128
+ } catch (error) {
129
+ console.error(`[CloudConnector] Failed to parse message:`, line, error);
130
+ }
131
+ }
132
+ }
133
+ async handleCloudMessage(message) {
134
+ if (isHeartbeatMessage(message)) {
135
+ if (message.type === "ping") {
136
+ this.sendHeartbeatResponse(message.timestamp);
137
+ }
138
+ return;
139
+ }
140
+ const request = message;
141
+ const { id, action, data, browser, timeoutSec } = request;
142
+ try {
143
+ const client = await import("@mearl/client");
144
+ const result = await client.invoke(action, data, {
145
+ browser,
146
+ timeoutSec: timeoutSec ?? resolveActionTimeoutSec(action, data, 15)
147
+ });
148
+ this.sendResponse({ id, success: true, data: result });
149
+ } catch (error) {
150
+ const errorMessage = error instanceof Error ? error.message : String(error);
151
+ this.sendResponse({ id, success: false, error: errorMessage });
152
+ }
153
+ }
154
+ sendResponse(response) {
155
+ if (this.ws && this.ws.readyState === 1) {
156
+ this.ws.send(JSON.stringify(response) + "\n");
157
+ }
158
+ }
159
+ sendHeartbeatResponse(_timestamp) {
160
+ if (this.ws && this.ws.readyState === 1) {
161
+ this.ws.send(
162
+ JSON.stringify({ type: "pong", timestamp: Date.now() }) + "\n"
163
+ );
164
+ }
165
+ }
166
+ startHeartbeat() {
167
+ this.stopHeartbeat();
168
+ this.heartbeatTimer = setInterval(() => {
169
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) {
170
+ this.ws.send(
171
+ JSON.stringify({ type: "ping", timestamp: Date.now() }) + "\n"
172
+ );
173
+ }
174
+ }, this.options.heartbeatInterval * 1e3);
175
+ }
176
+ stopHeartbeat() {
177
+ if (this.heartbeatTimer) {
178
+ clearInterval(this.heartbeatTimer);
179
+ this.heartbeatTimer = null;
180
+ }
181
+ }
182
+ tryReconnect() {
183
+ if (this.isManualClose) return;
184
+ if (this.reconnectTimer) return;
185
+ this.reconnectAttempts++;
186
+ if (this.options.maxReconnectAttempts !== -1 && this.reconnectAttempts > this.options.maxReconnectAttempts) {
187
+ console.log(
188
+ `[CloudConnector] Max reconnect attempts (${this.options.maxReconnectAttempts}) reached`
189
+ );
190
+ return;
191
+ }
192
+ const isSlowProbe = this.reconnectAttempts > FAST_RECONNECT_ATTEMPTS;
193
+ const delay = isSlowProbe ? SLOW_PROBE_INTERVAL_MS : Math.min(BACKOFF_BASE_MS * Math.pow(2, this.reconnectAttempts - 1), BACKOFF_MAX_MS);
194
+ if (isSlowProbe) {
195
+ console.log(
196
+ `[CloudConnector] Slow probe reconnect in ${delay / 1e3}s (attempt ${this.reconnectAttempts})`
197
+ );
198
+ } else {
199
+ console.log(
200
+ `[CloudConnector] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts}/${FAST_RECONNECT_ATTEMPTS})`
201
+ );
202
+ }
203
+ this.reconnectTimer = setTimeout(() => {
204
+ this.reconnectTimer = null;
205
+ this.connect();
206
+ }, delay);
207
+ }
208
+ };
209
+
210
+ // src/paths.ts
211
+ import { keyedConfigFile, keyedDir, keyedLogFile } from "@mearl/daemon-core";
212
+ var CONNECTORS_SUBDIR = "connectors";
213
+ var CONNECTORS_DIR = keyedDir(CONNECTORS_SUBDIR);
214
+ function configFileFor(serverUrl) {
215
+ return keyedConfigFile(CONNECTORS_SUBDIR, serverUrl);
216
+ }
217
+ function logFileFor(serverUrl) {
218
+ return keyedLogFile(CONNECTORS_SUBDIR, serverUrl);
219
+ }
220
+
221
+ // src/daemon.ts
222
+ var SCRIPT_PATH = fileURLToPath(import.meta.url);
223
+ var CONNECT_TIMEOUT_MS = 6e4;
224
+ function daemonFor(serverUrl, foregroundArgs = []) {
225
+ return createDaemon({
226
+ name: "CloudConnector",
227
+ scriptPath: SCRIPT_PATH,
228
+ configFile: configFileFor(serverUrl),
229
+ logFile: logFileFor(serverUrl),
230
+ // The foreground child is launched as `cli.js --foreground <serverUrl> [opts]`.
231
+ foregroundArgs: [serverUrl, ...foregroundArgs],
232
+ readyTimeoutMs: CONNECT_TIMEOUT_MS,
233
+ formatInfo: (rec) => ` server: ${rec.serverUrl}`
234
+ });
235
+ }
236
+ function startDaemon(serverUrl, passthroughArgs) {
237
+ return daemonFor(serverUrl, passthroughArgs).start();
238
+ }
239
+ function stopDaemon(serverUrl) {
240
+ return daemonFor(serverUrl).stop();
241
+ }
242
+ function restartDaemon(serverUrl, passthroughArgs) {
243
+ return daemonFor(serverUrl, passthroughArgs).restart();
244
+ }
245
+ function statusDaemon(serverUrl) {
246
+ if (serverUrl) {
247
+ daemonFor(serverUrl).status();
248
+ return;
249
+ }
250
+ listDaemons();
251
+ }
252
+ function listDaemons() {
253
+ const records = readLiveRecords(CONNECTORS_DIR);
254
+ if (records.length === 0) {
255
+ console.log("[CloudConnector] No running connectors");
256
+ return;
257
+ }
258
+ console.log(`[CloudConnector] ${records.length} running connector(s):`);
259
+ for (const rec of records) {
260
+ const since = rec.startedAt ? ` (since ${rec.startedAt})` : "";
261
+ console.log(` pid ${rec.pid} ${rec.serverUrl}${since}`);
262
+ }
263
+ }
264
+ async function stopAllDaemons() {
265
+ const records = readLiveRecords(CONNECTORS_DIR);
266
+ if (records.length === 0) {
267
+ console.log("[CloudConnector] No running connectors");
268
+ return;
269
+ }
270
+ for (const rec of records) {
271
+ await daemonFor(rec.serverUrl).stop();
272
+ }
273
+ }
274
+ function printLogs(serverUrl) {
275
+ daemonFor(serverUrl).logs();
276
+ }
277
+ function runForeground(options) {
278
+ const serverUrl = options.serverUrl;
279
+ const configFile = configFileFor(serverUrl);
280
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
281
+ const writeOwnRecord = () => {
282
+ try {
283
+ writeRecord(configFile, { serverUrl, pid: process.pid, startedAt });
284
+ } catch (error) {
285
+ console.error(`[CloudConnector] Failed to write registry record: ${String(error)}`);
286
+ }
287
+ };
288
+ const connector = new CloudConnector({
289
+ ...options,
290
+ onConnected: writeOwnRecord,
291
+ onInitialConnectionFailed: (message) => {
292
+ console.error(`[CloudConnector] Initial connection failed: ${message}`);
293
+ process.exit(1);
294
+ }
295
+ });
296
+ connector.connect();
297
+ let shuttingDown = false;
298
+ const shutdown = (signal) => {
299
+ if (shuttingDown) return;
300
+ shuttingDown = true;
301
+ console.log(`
302
+ [CloudConnector] Received ${signal}, shutting down...`);
303
+ connector.disconnect();
304
+ removeRecord(configFile);
305
+ process.exit(0);
306
+ };
307
+ process.on("SIGINT", () => shutdown("SIGINT"));
308
+ process.on("SIGTERM", () => shutdown("SIGTERM"));
309
+ }
310
+
311
+ // src/cli.ts
312
+ var CLOUD_CONNECTOR_VERSION = true ? "2.0.0" : "unknown";
313
+ var args = process.argv.slice(2);
314
+ if (args.includes("--version") || args.includes("-v")) {
315
+ console.log(CLOUD_CONNECTOR_VERSION);
316
+ process.exit(0);
317
+ }
318
+ var SUBCOMMANDS = ["start", "stop", "restart", "status", "list", "logs"];
319
+ function isWsUrl(value) {
320
+ return !!value && (value.startsWith("ws://") || value.startsWith("wss://"));
321
+ }
322
+ function showHelp() {
323
+ console.error(`mearl-cloud-connector v${CLOUD_CONNECTOR_VERSION}
324
+
325
+ Usage:
326
+ mearl-cloud-connector <server-url> [options] # run in the foreground
327
+ mearl-cloud-connector <command> [server-url] [options] # manage a background connector
328
+
329
+ Commands:
330
+ start <server-url> Start a background connector (daemonize; idempotent)
331
+ stop <server-url> Stop the background connector for <server-url>
332
+ stop --all Stop every background connector
333
+ restart <server-url> Restart the background connector for <server-url>
334
+ status [server-url] Show one connector's status, or list all if omitted
335
+ list List every running connector
336
+ logs <server-url> Print the tail of a connector's log
337
+
338
+ Arguments:
339
+ server-url WebSocket server URL (ws://host:port or wss://host:port)
340
+
341
+ Options:
342
+ --foreground, -f Run in the foreground instead of daemonizing
343
+ --heartbeat <seconds> Heartbeat interval (default: 30)
344
+ --reconnect <ms> Reconnect interval in ms (default: 5000)
345
+ --max-reconnect <n> Max reconnect attempts, -1 for unlimited (default: -1)
346
+ --fail-fast Exit if the FIRST connection fails (used by native-host)
347
+ --version, -v Show version
348
+ --help, -h Show this help message
349
+
350
+ Examples:
351
+ # Run in the foreground (Ctrl+C to stop) — also how native-host launches it
352
+ mearl-cloud-connector "ws://localhost:8080/ws?token=xxx"
353
+
354
+ # Start/stop a self-managed background connector with its own log file
355
+ mearl-cloud-connector start "wss://cloud.example.com/ws?token=xxx"
356
+ mearl-cloud-connector status
357
+ mearl-cloud-connector logs "wss://cloud.example.com/ws?token=xxx"
358
+ mearl-cloud-connector stop "wss://cloud.example.com/ws?token=xxx"
359
+ `);
360
+ }
361
+ function parseConnectorOptions(rest) {
362
+ const options = {};
363
+ for (let i = 0; i < rest.length; i++) {
364
+ const arg = rest[i];
365
+ if (arg === "--heartbeat" && i + 1 < rest.length) {
366
+ options.heartbeatInterval = parseInt(rest[++i], 10);
367
+ } else if (arg === "--reconnect" && i + 1 < rest.length) {
368
+ options.reconnectInterval = parseInt(rest[++i], 10);
369
+ } else if (arg === "--max-reconnect" && i + 1 < rest.length) {
370
+ options.maxReconnectAttempts = parseInt(rest[++i], 10);
371
+ } else if (arg === "--fail-fast") {
372
+ options.failFast = true;
373
+ }
374
+ }
375
+ return options;
376
+ }
377
+ function optionArgs(rest) {
378
+ return rest.filter((arg) => !isWsUrl(arg) && arg !== "--foreground" && arg !== "-f");
379
+ }
380
+ function exitHelp(message) {
381
+ console.error(`Error: ${message}`);
382
+ showHelp();
383
+ process.exit(1);
384
+ }
385
+ async function main() {
386
+ process.stdout.on("error", () => {
387
+ });
388
+ process.stderr.on("error", () => {
389
+ });
390
+ if (args.length === 0 || args.includes("--help") || args.includes("-h")) {
391
+ showHelp();
392
+ process.exit(args.length === 0 ? 1 : 0);
393
+ }
394
+ let command = null;
395
+ let rest = args;
396
+ if (args[0] && SUBCOMMANDS.includes(args[0])) {
397
+ command = args[0];
398
+ rest = args.slice(1);
399
+ }
400
+ const foregroundFlag = rest.includes("--foreground") || rest.includes("-f");
401
+ const serverUrl = rest.find(isWsUrl);
402
+ if (foregroundFlag || !command && serverUrl) {
403
+ if (!serverUrl) exitHelp("server-url must start with ws:// or wss://");
404
+ const options = {
405
+ serverUrl,
406
+ ...parseConnectorOptions(optionArgs(rest))
407
+ };
408
+ console.log("[CloudConnector] Starting...");
409
+ console.log(`[CloudConnector] Connecting to: ${serverUrl}`);
410
+ runForeground(options);
411
+ return;
412
+ }
413
+ switch (command) {
414
+ case "start":
415
+ if (!serverUrl) exitHelp("`start` requires a server-url");
416
+ await startDaemon(serverUrl, optionArgs(rest));
417
+ break;
418
+ case "stop":
419
+ if (rest.includes("--all")) {
420
+ await stopAllDaemons();
421
+ } else if (serverUrl) {
422
+ await stopDaemon(serverUrl);
423
+ } else {
424
+ exitHelp("`stop` requires a server-url or --all");
425
+ }
426
+ break;
427
+ case "restart":
428
+ if (!serverUrl) exitHelp("`restart` requires a server-url");
429
+ await restartDaemon(serverUrl, optionArgs(rest));
430
+ break;
431
+ case "status":
432
+ statusDaemon(serverUrl);
433
+ break;
434
+ case "list":
435
+ listDaemons();
436
+ break;
437
+ case "logs":
438
+ if (!serverUrl) exitHelp("`logs` requires a server-url");
439
+ printLogs(serverUrl);
440
+ break;
441
+ default:
442
+ showHelp();
443
+ process.exit(1);
444
+ }
445
+ }
446
+ main().catch((error) => {
447
+ console.error("[CloudConnector] Fatal error:", error);
448
+ process.exit(1);
449
+ });
@@ -0,0 +1,33 @@
1
+ import { type DaemonRecord } from '@mearl/daemon-core';
2
+ import { CloudConnectorOptions } from './index.js';
3
+ export interface ConnectorRecord extends DaemonRecord {
4
+ serverUrl: string;
5
+ }
6
+ /** Start a background connector for a serverUrl (idempotent — reuses a live one). */
7
+ export declare function startDaemon(serverUrl: string, passthroughArgs: string[]): Promise<void>;
8
+ /** Stop the background connector for a serverUrl. */
9
+ export declare function stopDaemon(serverUrl: string): Promise<void>;
10
+ /** Restart the background connector for a serverUrl. */
11
+ export declare function restartDaemon(serverUrl: string, passthroughArgs: string[]): Promise<void>;
12
+ /** Show status for one connector, or list all running connectors when no url is given. */
13
+ export declare function statusDaemon(serverUrl?: string): void;
14
+ /** Print every running connector (across all serverUrls), pruning dead records. */
15
+ export declare function listDaemons(): void;
16
+ /** Stop every running connector. */
17
+ export declare function stopAllDaemons(): Promise<void>;
18
+ /** Tail the log for a connector. */
19
+ export declare function printLogs(serverUrl: string): void;
20
+ /**
21
+ * Run the connector in the current process. Used by BOTH the detached daemon
22
+ * child (`--foreground`) and a direct `cloud-connector <url>` invocation (e.g.
23
+ * native-host spawns the connector this way).
24
+ *
25
+ * The connector is the SOLE writer of its own registry record: it writes the
26
+ * record on every (re)connect and removes it on graceful shutdown, so any
27
+ * manager — the daemon CLI, a fresh native-host adopting it after a reload —
28
+ * can discover it through the shared registry. The record is intentionally kept
29
+ * across transient disconnects (the connector reconnects with backoff); it is
30
+ * only removed when the process exits cleanly. A crash leaves a stale record,
31
+ * which readers prune via the pid liveness check.
32
+ */
33
+ export declare function runForeground(options: CloudConnectorOptions): void;
@@ -0,0 +1,38 @@
1
+ export interface CloudConnectorOptions {
2
+ serverUrl: string;
3
+ heartbeatInterval?: number;
4
+ reconnectInterval?: number;
5
+ maxReconnectAttempts?: number;
6
+ failFast?: boolean;
7
+ onInitialConnectionFailed?: (message: string) => void;
8
+ /**
9
+ * Fired every time the WebSocket connection is (re)established. Used by the
10
+ * foreground runner to (re)write this connector's registry record once it is
11
+ * actually connected — the signal other managers use to discover/adopt it.
12
+ */
13
+ onConnected?: (serverUrl: string) => void;
14
+ }
15
+ export declare class CloudConnector {
16
+ private options;
17
+ private ws;
18
+ private heartbeatTimer;
19
+ private reconnectTimer;
20
+ private reconnectAttempts;
21
+ private messageBuffer;
22
+ private isManualClose;
23
+ private shouldTryWss;
24
+ private wssRetryAttempts;
25
+ private readonly maxWssRetryAttempts;
26
+ private hasConnected;
27
+ private lastConnectionError;
28
+ constructor(options: CloudConnectorOptions);
29
+ connect(): void;
30
+ disconnect(): void;
31
+ private handleMessage;
32
+ private handleCloudMessage;
33
+ private sendResponse;
34
+ private sendHeartbeatResponse;
35
+ private startHeartbeat;
36
+ private stopHeartbeat;
37
+ private tryReconnect;
38
+ }
package/dist/index.js ADDED
@@ -0,0 +1,200 @@
1
+ // src/index.ts
2
+ import WebSocket from "ws";
3
+ import {
4
+ isHeartbeatMessage,
5
+ MAX_BUFFER_SIZE,
6
+ DEFAULT_HEARTBEAT_INTERVAL
7
+ } from "@mearl/cloud-types";
8
+ import { resolveActionTimeoutSec } from "@mearl/client/action-timeouts";
9
+ var DEFAULT_RECONNECT_INTERVAL = 5e3;
10
+ var BACKOFF_BASE_MS = 1e3;
11
+ var BACKOFF_MAX_MS = 3e4;
12
+ var SLOW_PROBE_INTERVAL_MS = 6e4;
13
+ var FAST_RECONNECT_ATTEMPTS = 5;
14
+ var CloudConnector = class {
15
+ options;
16
+ ws = null;
17
+ heartbeatTimer = null;
18
+ reconnectTimer = null;
19
+ reconnectAttempts = 0;
20
+ messageBuffer = "";
21
+ isManualClose = false;
22
+ shouldTryWss = false;
23
+ wssRetryAttempts = 0;
24
+ maxWssRetryAttempts = 1;
25
+ hasConnected = false;
26
+ lastConnectionError = null;
27
+ constructor(options) {
28
+ this.options = {
29
+ serverUrl: options.serverUrl,
30
+ heartbeatInterval: options.heartbeatInterval ?? DEFAULT_HEARTBEAT_INTERVAL,
31
+ reconnectInterval: options.reconnectInterval ?? DEFAULT_RECONNECT_INTERVAL,
32
+ maxReconnectAttempts: options.maxReconnectAttempts ?? -1,
33
+ failFast: options.failFast ?? false,
34
+ onInitialConnectionFailed: options.onInitialConnectionFailed,
35
+ onConnected: options.onConnected
36
+ };
37
+ }
38
+ connect() {
39
+ if (this.ws && (this.ws.readyState === 0 || this.ws.readyState === 1)) {
40
+ return;
41
+ }
42
+ let serverUrl = this.options.serverUrl;
43
+ if (this.shouldTryWss && serverUrl.startsWith("ws://")) {
44
+ serverUrl = serverUrl.replace("ws://", "wss://");
45
+ console.log(`[CloudConnector] Retrying with wss://: ${serverUrl}`);
46
+ }
47
+ this.ws = new WebSocket(serverUrl);
48
+ this.ws.on("open", () => {
49
+ console.log(`[CloudConnector] Connected to ${serverUrl}`);
50
+ this.hasConnected = true;
51
+ this.lastConnectionError = null;
52
+ this.reconnectAttempts = 0;
53
+ this.shouldTryWss = false;
54
+ this.wssRetryAttempts = 0;
55
+ this.startHeartbeat();
56
+ this.options.onConnected?.(this.options.serverUrl);
57
+ });
58
+ this.ws.on("message", (data) => {
59
+ this.handleMessage(data);
60
+ });
61
+ this.ws.on("close", (code, reason) => {
62
+ console.log(`[CloudConnector] Disconnected (${code}: ${reason.toString()})`);
63
+ this.stopHeartbeat();
64
+ this.messageBuffer = "";
65
+ if (this.shouldTryWss && serverUrl.startsWith("ws://")) {
66
+ return;
67
+ }
68
+ if (this.options.failFast && !this.hasConnected) {
69
+ const reasonText = reason.toString();
70
+ const message = this.lastConnectionError || reasonText || `Connection closed (${code})`;
71
+ this.options.onInitialConnectionFailed?.(message);
72
+ return;
73
+ }
74
+ this.tryReconnect();
75
+ });
76
+ this.ws.on("error", (error) => {
77
+ console.error(`[CloudConnector] WebSocket error:`, error.message);
78
+ this.lastConnectionError = error.message;
79
+ if (error.message.includes("301") && !this.shouldTryWss && serverUrl.startsWith("ws://") && this.wssRetryAttempts < this.maxWssRetryAttempts) {
80
+ this.shouldTryWss = true;
81
+ this.wssRetryAttempts++;
82
+ this.ws = null;
83
+ console.log(
84
+ `[CloudConnector] Server requires wss://, retrying (${this.wssRetryAttempts}/${this.maxWssRetryAttempts})...`
85
+ );
86
+ setTimeout(() => this.connect(), 1e3);
87
+ }
88
+ });
89
+ }
90
+ disconnect() {
91
+ this.isManualClose = true;
92
+ this.stopHeartbeat();
93
+ if (this.reconnectTimer) {
94
+ clearTimeout(this.reconnectTimer);
95
+ this.reconnectTimer = null;
96
+ }
97
+ if (this.ws) {
98
+ this.ws.close();
99
+ this.ws = null;
100
+ }
101
+ }
102
+ handleMessage(data) {
103
+ this.messageBuffer += data.toString("utf-8");
104
+ if (this.messageBuffer.length > MAX_BUFFER_SIZE) {
105
+ console.error("[CloudConnector] Message buffer exceeds limit, closing connection");
106
+ this.disconnect();
107
+ return;
108
+ }
109
+ let newlineIndex;
110
+ while ((newlineIndex = this.messageBuffer.indexOf("\n")) !== -1) {
111
+ const line = this.messageBuffer.slice(0, newlineIndex);
112
+ this.messageBuffer = this.messageBuffer.slice(newlineIndex + 1);
113
+ if (!line.trim()) continue;
114
+ try {
115
+ const message = JSON.parse(line);
116
+ this.handleCloudMessage(message);
117
+ } catch (error) {
118
+ console.error(`[CloudConnector] Failed to parse message:`, line, error);
119
+ }
120
+ }
121
+ }
122
+ async handleCloudMessage(message) {
123
+ if (isHeartbeatMessage(message)) {
124
+ if (message.type === "ping") {
125
+ this.sendHeartbeatResponse(message.timestamp);
126
+ }
127
+ return;
128
+ }
129
+ const request = message;
130
+ const { id, action, data, browser, timeoutSec } = request;
131
+ try {
132
+ const client = await import("@mearl/client");
133
+ const result = await client.invoke(action, data, {
134
+ browser,
135
+ timeoutSec: timeoutSec ?? resolveActionTimeoutSec(action, data, 15)
136
+ });
137
+ this.sendResponse({ id, success: true, data: result });
138
+ } catch (error) {
139
+ const errorMessage = error instanceof Error ? error.message : String(error);
140
+ this.sendResponse({ id, success: false, error: errorMessage });
141
+ }
142
+ }
143
+ sendResponse(response) {
144
+ if (this.ws && this.ws.readyState === 1) {
145
+ this.ws.send(JSON.stringify(response) + "\n");
146
+ }
147
+ }
148
+ sendHeartbeatResponse(_timestamp) {
149
+ if (this.ws && this.ws.readyState === 1) {
150
+ this.ws.send(
151
+ JSON.stringify({ type: "pong", timestamp: Date.now() }) + "\n"
152
+ );
153
+ }
154
+ }
155
+ startHeartbeat() {
156
+ this.stopHeartbeat();
157
+ this.heartbeatTimer = setInterval(() => {
158
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) {
159
+ this.ws.send(
160
+ JSON.stringify({ type: "ping", timestamp: Date.now() }) + "\n"
161
+ );
162
+ }
163
+ }, this.options.heartbeatInterval * 1e3);
164
+ }
165
+ stopHeartbeat() {
166
+ if (this.heartbeatTimer) {
167
+ clearInterval(this.heartbeatTimer);
168
+ this.heartbeatTimer = null;
169
+ }
170
+ }
171
+ tryReconnect() {
172
+ if (this.isManualClose) return;
173
+ if (this.reconnectTimer) return;
174
+ this.reconnectAttempts++;
175
+ if (this.options.maxReconnectAttempts !== -1 && this.reconnectAttempts > this.options.maxReconnectAttempts) {
176
+ console.log(
177
+ `[CloudConnector] Max reconnect attempts (${this.options.maxReconnectAttempts}) reached`
178
+ );
179
+ return;
180
+ }
181
+ const isSlowProbe = this.reconnectAttempts > FAST_RECONNECT_ATTEMPTS;
182
+ const delay = isSlowProbe ? SLOW_PROBE_INTERVAL_MS : Math.min(BACKOFF_BASE_MS * Math.pow(2, this.reconnectAttempts - 1), BACKOFF_MAX_MS);
183
+ if (isSlowProbe) {
184
+ console.log(
185
+ `[CloudConnector] Slow probe reconnect in ${delay / 1e3}s (attempt ${this.reconnectAttempts})`
186
+ );
187
+ } else {
188
+ console.log(
189
+ `[CloudConnector] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts}/${FAST_RECONNECT_ATTEMPTS})`
190
+ );
191
+ }
192
+ this.reconnectTimer = setTimeout(() => {
193
+ this.reconnectTimer = null;
194
+ this.connect();
195
+ }, delay);
196
+ }
197
+ };
198
+ export {
199
+ CloudConnector
200
+ };
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Subdir under ~/.mearl holding one record/log per connector instance,
3
+ * keyed by serverUrl. This directory is the SHARED contract between the
4
+ * connector (the sole writer of its own record) and native-host (a reader that
5
+ * adopts/lists connectors) — both derive paths through these helpers so they
6
+ * never disagree on where a connector's record lives.
7
+ */
8
+ export declare const CONNECTORS_SUBDIR = "connectors";
9
+ /** Directory containing all per-connector records and logs. */
10
+ export declare const CONNECTORS_DIR: string;
11
+ /** Record file for a given serverUrl: ~/.mearl/connectors/<hash>.json */
12
+ export declare function configFileFor(serverUrl: string): string;
13
+ /** Log file for a given serverUrl: ~/.mearl/connectors/<hash>.log */
14
+ export declare function logFileFor(serverUrl: string): string;
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@mearl/cloud-connector",
3
+ "version": "2.0.0",
4
+ "description": "Cloud connector for Mearl — bridges cloud WebSocket server to local native-host",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
14
+ "bin": {
15
+ "mearl-cloud-connector": "./dist/cli.js"
16
+ },
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "keywords": [
21
+ "mearl",
22
+ "cloud-connector",
23
+ "websocket"
24
+ ],
25
+ "license": "ISC",
26
+ "publishConfig": {
27
+ "registry": "https://registry.npmjs.org"
28
+ },
29
+ "dependencies": {
30
+ "ws": "^8.18.0",
31
+ "@mearl/daemon-core": "2.0.0",
32
+ "@mearl/cloud-types": "2.0.0",
33
+ "@mearl/client": "2.0.0"
34
+ },
35
+ "devDependencies": {
36
+ "@types/node": "^24.9.1",
37
+ "@types/ws": "^8.5.13",
38
+ "esbuild": "^0.25.2",
39
+ "typescript": "^5.8.3"
40
+ },
41
+ "scripts": {
42
+ "build": "rm -rf dist/ && node build.mjs",
43
+ "dev": "tsc --watch",
44
+ "typecheck": "tsc --noEmit",
45
+ "test": "vitest run"
46
+ }
47
+ }