@mearl/cloud-connector 2.0.2 → 2.2.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 CHANGED
@@ -44,6 +44,8 @@ mearl-cloud-connector <command> [server-url] [options] # 管理后台守护进
44
44
  - `--heartbeat <seconds>` —— 心跳间隔(默认 30 秒)
45
45
  - `--reconnect <ms>` —— 重连间隔(默认 5000 毫秒)
46
46
  - `--max-reconnect <n>` —— 最大重连次数,-1 表示无限(默认 -1)
47
+ - `--connector-id <id>` —— 覆盖本机稳定的 connector ID
48
+ - `--name <name>` —— 设置便于识别的 connector 名称(默认主机名)
47
49
  - `--fail-fast` —— 首次连接失败即退出(供 native-host 探测启动结果)
48
50
 
49
51
  **示例:**
@@ -53,7 +55,7 @@ mearl-cloud-connector <command> [server-url] [options] # 管理后台守护进
53
55
  mearl-cloud-connector "ws://localhost:8080/ws?token=xxx"
54
56
 
55
57
  # 后台启动一个自管理连接器,拥有独立日志文件
56
- mearl-cloud-connector start "wss://cloud.example.com/ws?token=xxx"
58
+ mearl-cloud-connector start "wss://cloud.example.com/ws?token=xxx" --name work-mac
57
59
 
58
60
  # 查看状态 / 列表 / 日志
59
61
  mearl-cloud-connector status
@@ -75,6 +77,7 @@ import { CloudConnector } from '@mearl/cloud-connector';
75
77
 
76
78
  const connector = new CloudConnector({
77
79
  serverUrl: 'wss://cloud.example.com/ws?token=xxx',
80
+ connectorName: 'work-mac',
78
81
  heartbeatInterval: 30,
79
82
  reconnectInterval: 5000,
80
83
  maxReconnectAttempts: -1,
@@ -92,9 +95,16 @@ process.on('SIGINT', () => {
92
95
 
93
96
  ## 运行时文件
94
97
 
98
+ 连接器首次运行时会生成稳定的 connector ID,并保存到
99
+ `~/.mearl/cloud-connector-identity.json`。名称默认取主机名,可通过 `--name` 或
100
+ `MEARL_CONNECTOR_NAME` 设置;ID 可通过 `--connector-id` 或
101
+ `MEARL_CONNECTOR_ID` 设置。相同 ID 的新连接会替换旧连接,适合进程重启和网络重连。
102
+
95
103
  每个连接器实例在 `~/.mearl/connectors/` 下按 `server-url` 哈希生成一对文件:
96
104
 
97
- - `<hash>.json` —— 连接记录(含 `serverUrl`、`pid`、`startedAt`)。**连接器进程是该记录的唯一写入方**:连上时写入、优雅退出时删除(崩溃残留的记录会被读取方按 pid 存活性自动清理)。
105
+ - `<hash>.json` —— 连接记录(含 `serverUrl`、`pid`、`startedAt`、`connectorId`
106
+ 和 `name`)。**连接器进程是该记录的唯一写入方**:连上时写入、优雅退出时删除
107
+ (崩溃残留的记录会被读取方按 pid 存活性自动清理)。
98
108
  - `<hash>.log` —— 守护进程日志(`logs` 子命令读取,或 `tail -f` 跟踪);超过 5MB 会在下次启动时滚动为 `<hash>.log.1`。
99
109
 
100
110
  native-host 与守护进程 CLI 都通过这套共享路径(由 [`@mearl/daemon-core`](../../daemon-core) 派生)读取注册表,因此一方启动的连接器另一方也能发现、复用或停止。
@@ -104,12 +114,15 @@ native-host 与守护进程 CLI 都通过这套共享路径(由 [`@mearl/daemo
104
114
  ## 前置条件
105
115
 
106
116
  1. **安装 @mearl/native-host**
117
+
107
118
  ```bash
108
119
  npm install -g @mearl/native-host
109
120
  ```
121
+
110
122
  或使用本项目的 monorepo 构建产物。
111
123
 
112
124
  2. **确保 native-host 已初始化**
125
+
113
126
  ```bash
114
127
  mearl-native-host --init
115
128
  ```
package/dist/cli.js CHANGED
@@ -6,7 +6,7 @@ import {
6
6
  createDaemon,
7
7
  readLiveRecords,
8
8
  removeRecord,
9
- writeRecord
9
+ writeRecord as writeRecord2
10
10
  } from "@mearl/daemon-core";
11
11
 
12
12
  // src/index.ts
@@ -17,6 +17,36 @@ import {
17
17
  DEFAULT_HEARTBEAT_INTERVAL
18
18
  } from "@mearl/cloud-types";
19
19
  import { resolveActionTimeoutSec } from "@mearl/client/action-timeouts";
20
+
21
+ // src/identity.ts
22
+ import { hostname } from "node:os";
23
+ import { randomUUID } from "node:crypto";
24
+ import { join } from "node:path";
25
+ import { DAEMON_HOME, readRecord, writeRecord } from "@mearl/daemon-core";
26
+ var IDENTITY_FILE = join(DAEMON_HOME, "cloud-connector-identity.json");
27
+ function resolveConnectorIdentity(options) {
28
+ const explicitId = options.connectorId?.trim() || process.env.MEARL_CONNECTOR_ID?.trim();
29
+ const explicitName = options.connectorName?.trim() || process.env.MEARL_CONNECTOR_NAME?.trim();
30
+ const stored = readRecord(IDENTITY_FILE);
31
+ const connectorId = explicitId || stored?.connectorId || randomUUID();
32
+ if (!explicitId && !stored?.connectorId) {
33
+ try {
34
+ writeRecord(IDENTITY_FILE, { pid: process.pid, connectorId });
35
+ } catch {
36
+ }
37
+ }
38
+ const name = explicitName || hostname() || `connector-${connectorId.slice(0, 8)}`;
39
+ if (!/^[A-Za-z0-9._:-]{1,128}$/.test(connectorId)) {
40
+ throw new Error('connectorId must contain only letters, numbers, ".", "_", ":", or "-"');
41
+ }
42
+ if (name.length > 128 || /\p{Cc}/u.test(name)) {
43
+ throw new Error("connectorName must be 1-128 characters without control characters");
44
+ }
45
+ return { connectorId, name };
46
+ }
47
+
48
+ // src/index.ts
49
+ var CLOUD_CONNECTOR_VERSION = true ? "2.2.0" : "unknown";
20
50
  var DEFAULT_RECONNECT_INTERVAL = 5e3;
21
51
  var BACKOFF_BASE_MS = 1e3;
22
52
  var BACKOFF_MAX_MS = 3e4;
@@ -24,6 +54,7 @@ var SLOW_PROBE_INTERVAL_MS = 6e4;
24
54
  var FAST_RECONNECT_ATTEMPTS = 5;
25
55
  var CloudConnector = class {
26
56
  options;
57
+ identity;
27
58
  ws = null;
28
59
  heartbeatTimer = null;
29
60
  reconnectTimer = null;
@@ -45,6 +76,7 @@ var CloudConnector = class {
45
76
  onInitialConnectionFailed: options.onInitialConnectionFailed,
46
77
  onConnected: options.onConnected
47
78
  };
79
+ this.identity = resolveConnectorIdentity(options);
48
80
  }
49
81
  connect() {
50
82
  if (this.ws && (this.ws.readyState === 0 || this.ws.readyState === 1)) {
@@ -57,14 +89,15 @@ var CloudConnector = class {
57
89
  }
58
90
  this.ws = new WebSocket(serverUrl);
59
91
  this.ws.on("open", () => {
60
- console.log(`[CloudConnector] Connected to ${serverUrl}`);
61
92
  this.hasConnected = true;
62
93
  this.lastConnectionError = null;
63
94
  this.reconnectAttempts = 0;
64
95
  this.shouldTryWss = false;
65
96
  this.wssRetryAttempts = 0;
97
+ this.sendConnectorHello();
66
98
  this.startHeartbeat();
67
- this.options.onConnected?.(this.options.serverUrl);
99
+ this.options.onConnected?.(this.options.serverUrl, this.identity);
100
+ console.log(`[CloudConnector] Connected to ${serverUrl}`);
68
101
  });
69
102
  this.ws.on("message", (data) => {
70
103
  this.handleMessage(data);
@@ -143,7 +176,8 @@ var CloudConnector = class {
143
176
  const client = await import("@mearl/client");
144
177
  const result = await client.invoke(action, data, {
145
178
  browser,
146
- timeoutSec: timeoutSec ?? resolveActionTimeoutSec(action, data, 15)
179
+ timeoutSec: timeoutSec ?? resolveActionTimeoutSec(action, data, 15),
180
+ controlSource: "cloud"
147
181
  });
148
182
  this.sendResponse({ id, success: true, data: result });
149
183
  } catch (error) {
@@ -156,6 +190,17 @@ var CloudConnector = class {
156
190
  this.ws.send(JSON.stringify(response) + "\n");
157
191
  }
158
192
  }
193
+ sendConnectorHello() {
194
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) {
195
+ const message = {
196
+ type: "connector_hello",
197
+ connectorId: this.identity.connectorId,
198
+ name: this.identity.name,
199
+ ...CLOUD_CONNECTOR_VERSION === "unknown" ? {} : { version: CLOUD_CONNECTOR_VERSION }
200
+ };
201
+ this.ws.send(JSON.stringify(message) + "\n");
202
+ }
203
+ }
159
204
  sendHeartbeatResponse(_timestamp) {
160
205
  if (this.ws && this.ws.readyState === 1) {
161
206
  this.ws.send(
@@ -278,9 +323,15 @@ function runForeground(options) {
278
323
  const serverUrl = options.serverUrl;
279
324
  const configFile = configFileFor(serverUrl);
280
325
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
281
- const writeOwnRecord = () => {
326
+ const writeOwnRecord = (_serverUrl, identity) => {
282
327
  try {
283
- writeRecord(configFile, { serverUrl, pid: process.pid, startedAt });
328
+ writeRecord2(configFile, {
329
+ serverUrl,
330
+ pid: process.pid,
331
+ startedAt,
332
+ connectorId: identity.connectorId,
333
+ name: identity.name
334
+ });
284
335
  } catch (error) {
285
336
  console.error(`[CloudConnector] Failed to write registry record: ${String(error)}`);
286
337
  }
@@ -309,10 +360,10 @@ function runForeground(options) {
309
360
  }
310
361
 
311
362
  // src/cli.ts
312
- var CLOUD_CONNECTOR_VERSION = true ? "2.0.2" : "unknown";
363
+ var CLOUD_CONNECTOR_VERSION2 = true ? "2.2.0" : "unknown";
313
364
  var args = process.argv.slice(2);
314
365
  if (args.includes("--version") || args.includes("-v")) {
315
- console.log(CLOUD_CONNECTOR_VERSION);
366
+ console.log(CLOUD_CONNECTOR_VERSION2);
316
367
  process.exit(0);
317
368
  }
318
369
  var SUBCOMMANDS = ["start", "stop", "restart", "status", "list", "logs"];
@@ -320,7 +371,7 @@ function isWsUrl(value) {
320
371
  return !!value && (value.startsWith("ws://") || value.startsWith("wss://"));
321
372
  }
322
373
  function showHelp() {
323
- console.error(`mearl-cloud-connector v${CLOUD_CONNECTOR_VERSION}
374
+ console.error(`mearl-cloud-connector v${CLOUD_CONNECTOR_VERSION2}
324
375
 
325
376
  Usage:
326
377
  mearl-cloud-connector <server-url> [options] # run in the foreground
@@ -343,6 +394,8 @@ Options:
343
394
  --heartbeat <seconds> Heartbeat interval (default: 30)
344
395
  --reconnect <ms> Reconnect interval in ms (default: 5000)
345
396
  --max-reconnect <n> Max reconnect attempts, -1 for unlimited (default: -1)
397
+ --connector-id <id> Override this machine's stable connector id
398
+ --name <name> Human-readable connector name (default: hostname)
346
399
  --fail-fast Exit if the FIRST connection fails (used by native-host)
347
400
  --version, -v Show version
348
401
  --help, -h Show this help message
@@ -368,6 +421,10 @@ function parseConnectorOptions(rest) {
368
421
  options.reconnectInterval = parseInt(rest[++i], 10);
369
422
  } else if (arg === "--max-reconnect" && i + 1 < rest.length) {
370
423
  options.maxReconnectAttempts = parseInt(rest[++i], 10);
424
+ } else if (arg === "--connector-id" && i + 1 < rest.length) {
425
+ options.connectorId = rest[++i];
426
+ } else if (arg === "--name" && i + 1 < rest.length) {
427
+ options.connectorName = rest[++i];
371
428
  } else if (arg === "--fail-fast") {
372
429
  options.failFast = true;
373
430
  }
package/dist/daemon.d.ts CHANGED
@@ -2,6 +2,8 @@ import { type DaemonRecord } from '@mearl/daemon-core';
2
2
  import { CloudConnectorOptions } from './index.js';
3
3
  export interface ConnectorRecord extends DaemonRecord {
4
4
  serverUrl: string;
5
+ connectorId?: string;
6
+ name?: string;
5
7
  }
6
8
  /** Start a background connector for a serverUrl (idempotent — reuses a live one). */
7
9
  export declare function startDaemon(serverUrl: string, passthroughArgs: string[]): Promise<void>;
@@ -0,0 +1,8 @@
1
+ export interface ConnectorIdentity {
2
+ connectorId: string;
3
+ name: string;
4
+ }
5
+ export declare function resolveConnectorIdentity(options: {
6
+ connectorId?: string;
7
+ connectorName?: string;
8
+ }): ConnectorIdentity;
package/dist/index.d.ts CHANGED
@@ -1,19 +1,23 @@
1
+ import { type ConnectorIdentity } from './identity.js';
1
2
  export interface CloudConnectorOptions {
2
3
  serverUrl: string;
3
4
  heartbeatInterval?: number;
4
5
  reconnectInterval?: number;
5
6
  maxReconnectAttempts?: number;
6
7
  failFast?: boolean;
8
+ connectorId?: string;
9
+ connectorName?: string;
7
10
  onInitialConnectionFailed?: (message: string) => void;
8
11
  /**
9
12
  * Fired every time the WebSocket connection is (re)established. Used by the
10
13
  * foreground runner to (re)write this connector's registry record once it is
11
14
  * actually connected — the signal other managers use to discover/adopt it.
12
15
  */
13
- onConnected?: (serverUrl: string) => void;
16
+ onConnected?: (serverUrl: string, identity: ConnectorIdentity) => void;
14
17
  }
15
18
  export declare class CloudConnector {
16
19
  private options;
20
+ private identity;
17
21
  private ws;
18
22
  private heartbeatTimer;
19
23
  private reconnectTimer;
@@ -31,6 +35,7 @@ export declare class CloudConnector {
31
35
  private handleMessage;
32
36
  private handleCloudMessage;
33
37
  private sendResponse;
38
+ private sendConnectorHello;
34
39
  private sendHeartbeatResponse;
35
40
  private startHeartbeat;
36
41
  private stopHeartbeat;
package/dist/index.js CHANGED
@@ -6,6 +6,36 @@ import {
6
6
  DEFAULT_HEARTBEAT_INTERVAL
7
7
  } from "@mearl/cloud-types";
8
8
  import { resolveActionTimeoutSec } from "@mearl/client/action-timeouts";
9
+
10
+ // src/identity.ts
11
+ import { hostname } from "node:os";
12
+ import { randomUUID } from "node:crypto";
13
+ import { join } from "node:path";
14
+ import { DAEMON_HOME, readRecord, writeRecord } from "@mearl/daemon-core";
15
+ var IDENTITY_FILE = join(DAEMON_HOME, "cloud-connector-identity.json");
16
+ function resolveConnectorIdentity(options) {
17
+ const explicitId = options.connectorId?.trim() || process.env.MEARL_CONNECTOR_ID?.trim();
18
+ const explicitName = options.connectorName?.trim() || process.env.MEARL_CONNECTOR_NAME?.trim();
19
+ const stored = readRecord(IDENTITY_FILE);
20
+ const connectorId = explicitId || stored?.connectorId || randomUUID();
21
+ if (!explicitId && !stored?.connectorId) {
22
+ try {
23
+ writeRecord(IDENTITY_FILE, { pid: process.pid, connectorId });
24
+ } catch {
25
+ }
26
+ }
27
+ const name = explicitName || hostname() || `connector-${connectorId.slice(0, 8)}`;
28
+ if (!/^[A-Za-z0-9._:-]{1,128}$/.test(connectorId)) {
29
+ throw new Error('connectorId must contain only letters, numbers, ".", "_", ":", or "-"');
30
+ }
31
+ if (name.length > 128 || /\p{Cc}/u.test(name)) {
32
+ throw new Error("connectorName must be 1-128 characters without control characters");
33
+ }
34
+ return { connectorId, name };
35
+ }
36
+
37
+ // src/index.ts
38
+ var CLOUD_CONNECTOR_VERSION = true ? "2.2.0" : "unknown";
9
39
  var DEFAULT_RECONNECT_INTERVAL = 5e3;
10
40
  var BACKOFF_BASE_MS = 1e3;
11
41
  var BACKOFF_MAX_MS = 3e4;
@@ -13,6 +43,7 @@ var SLOW_PROBE_INTERVAL_MS = 6e4;
13
43
  var FAST_RECONNECT_ATTEMPTS = 5;
14
44
  var CloudConnector = class {
15
45
  options;
46
+ identity;
16
47
  ws = null;
17
48
  heartbeatTimer = null;
18
49
  reconnectTimer = null;
@@ -34,6 +65,7 @@ var CloudConnector = class {
34
65
  onInitialConnectionFailed: options.onInitialConnectionFailed,
35
66
  onConnected: options.onConnected
36
67
  };
68
+ this.identity = resolveConnectorIdentity(options);
37
69
  }
38
70
  connect() {
39
71
  if (this.ws && (this.ws.readyState === 0 || this.ws.readyState === 1)) {
@@ -46,14 +78,15 @@ var CloudConnector = class {
46
78
  }
47
79
  this.ws = new WebSocket(serverUrl);
48
80
  this.ws.on("open", () => {
49
- console.log(`[CloudConnector] Connected to ${serverUrl}`);
50
81
  this.hasConnected = true;
51
82
  this.lastConnectionError = null;
52
83
  this.reconnectAttempts = 0;
53
84
  this.shouldTryWss = false;
54
85
  this.wssRetryAttempts = 0;
86
+ this.sendConnectorHello();
55
87
  this.startHeartbeat();
56
- this.options.onConnected?.(this.options.serverUrl);
88
+ this.options.onConnected?.(this.options.serverUrl, this.identity);
89
+ console.log(`[CloudConnector] Connected to ${serverUrl}`);
57
90
  });
58
91
  this.ws.on("message", (data) => {
59
92
  this.handleMessage(data);
@@ -132,7 +165,8 @@ var CloudConnector = class {
132
165
  const client = await import("@mearl/client");
133
166
  const result = await client.invoke(action, data, {
134
167
  browser,
135
- timeoutSec: timeoutSec ?? resolveActionTimeoutSec(action, data, 15)
168
+ timeoutSec: timeoutSec ?? resolveActionTimeoutSec(action, data, 15),
169
+ controlSource: "cloud"
136
170
  });
137
171
  this.sendResponse({ id, success: true, data: result });
138
172
  } catch (error) {
@@ -145,6 +179,17 @@ var CloudConnector = class {
145
179
  this.ws.send(JSON.stringify(response) + "\n");
146
180
  }
147
181
  }
182
+ sendConnectorHello() {
183
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) {
184
+ const message = {
185
+ type: "connector_hello",
186
+ connectorId: this.identity.connectorId,
187
+ name: this.identity.name,
188
+ ...CLOUD_CONNECTOR_VERSION === "unknown" ? {} : { version: CLOUD_CONNECTOR_VERSION }
189
+ };
190
+ this.ws.send(JSON.stringify(message) + "\n");
191
+ }
192
+ }
148
193
  sendHeartbeatResponse(_timestamp) {
149
194
  if (this.ws && this.ws.readyState === 1) {
150
195
  this.ws.send(
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mearl/cloud-connector",
3
- "version": "2.0.2",
3
+ "version": "2.2.0",
4
4
  "description": "Cloud connector for Mearl — bridges cloud WebSocket server to local native-host",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -28,9 +28,9 @@
28
28
  },
29
29
  "dependencies": {
30
30
  "ws": "^8.18.0",
31
- "@mearl/client": "2.0.2",
32
- "@mearl/cloud-types": "2.0.2",
33
- "@mearl/daemon-core": "2.0.2"
31
+ "@mearl/client": "2.2.0",
32
+ "@mearl/cloud-types": "2.2.0",
33
+ "@mearl/daemon-core": "2.2.0"
34
34
  },
35
35
  "devDependencies": {
36
36
  "@types/node": "^24.9.1",