@mearl/cloud-connector 2.9.5 → 2.9.6

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
@@ -22,7 +22,7 @@ pnpm add -g @mearl/cloud-connector
22
22
 
23
23
  ```bash
24
24
  mearl-cloud-connector <server-url> [options] # 前台运行
25
- mearl-cloud-connector <command> [server-url] [options] # 管理后台守护进程
25
+ mearl-cloud-connector <command> [server-url|pid] [options] # 管理后台守护进程
26
26
  ```
27
27
 
28
28
  **参数:**
@@ -34,10 +34,12 @@ mearl-cloud-connector <command> [server-url] [options] # 管理后台守护进
34
34
  **子命令:**
35
35
 
36
36
  - `start <server-url>` —— 后台启动守护进程(幂等:已有存活连接器则复用)
37
- - `stop <server-url>` —— 停止指定 `server-url` 的后台连接器
37
+ - `stop <server-url|pid>` —— 按端点或 `list` / `status` 展示的 PID 停止后台连接器;
38
+ PID 必须与当前连接器注册记录匹配,实例已被替换时不会停止新实例
38
39
  - `stop --all` —— 停止所有后台连接器
39
40
  - `restart <server-url>` —— 重启指定连接器
40
- - `status [server-url]` —— 查看某连接器状态;省略 `server-url` 时列出全部
41
+ - `status [server-url]` —— 查看连接器健康状态、最近心跳及重试信息;省略
42
+ `server-url` 时汇总全部
41
43
  - `list` —— 列出所有正在运行的连接器
42
44
  - `logs <server-url>` —— 打印某连接器日志末尾
43
45
 
@@ -70,12 +72,18 @@ mearl-cloud-connector logs "wss://cloud.example.com/ws?token=xxx"
70
72
 
71
73
  # 停止
72
74
  mearl-cloud-connector stop "wss://cloud.example.com/ws?token=xxx"
75
+ mearl-cloud-connector stop 12345
73
76
  mearl-cloud-connector stop --all
74
77
 
75
78
  # 自定义心跳和重连配置
76
79
  mearl-cloud-connector start "ws://localhost:8080/ws?token=xxx" --heartbeat 60 --max-reconnect 10
77
80
  ```
78
81
 
82
+ `status` 将连接器标记为 `starting`、`healthy`、`reconnecting`、`degraded`、`failed`
83
+ 或 `unknown`。其中 `healthy` 表示进程存活、传输已连接且 WebSocket 最近收到过有效心跳;
84
+ 旧版本创建、尚未包含连接状态字段的运行记录显示为 `unknown`,重启该连接器后即可补齐。
85
+ 输出中的 token 会被隐藏。
86
+
79
87
  `start` 会在连接成功后返回,后台进程继续运行。Qoder 配对时请紧接着提交 setup 输出的
80
88
  `pair` 工具调用;如果配对工具调用已经结束、取消或过期,需要重新生成配对 URL,旧 URL
81
89
  不能重复使用。
@@ -112,9 +120,10 @@ process.on('SIGINT', () => {
112
120
 
113
121
  每个连接器实例在 `~/.mearl/connectors/` 下按 `server-url` 哈希生成一对文件:
114
122
 
115
- - `<hash>.json` —— 连接记录(含 `serverUrl`、`pid`、`startedAt`、`connectorId`
116
- 和 `name`)。**连接器进程是该记录的唯一写入方**:连上时写入、优雅退出时删除
117
- (崩溃残留的记录会被读取方按 pid 存活性自动清理)。
123
+ - `<hash>.json` —— 连接记录(含身份、进程、连接状态、最近心跳和重试信息)。daemon
124
+ manager 在拉起子进程后立即写入 `starting` 占位,连接器进程随后持续更新自己的状态;
125
+ 删除记录时会核对 pid,避免退出中的旧进程删除新实例记录。崩溃残留会被读取方按 pid
126
+ 存活性自动清理。
118
127
  - `<hash>.log` —— 守护进程日志(`logs` 子命令读取,或 `tail -f` 跟踪);超过 5MB 会在下次启动时滚动为 `<hash>.log.1`。
119
128
 
120
129
  native-host 与守护进程 CLI 都通过这套共享路径(由 [`@mearl/daemon-core`](../../daemon-core) 派生)读取注册表,因此一方启动的连接器另一方也能发现、复用或停止。
@@ -191,3 +200,5 @@ Chrome Extension / CDP
191
200
  - 连接器需要保持运行才能转发云端请求。被 native-host 托管时,连接器以 `detached` 方式启动,会**在插件重载/更新后继续存活**;自管理时由 `start`/`stop` 子命令掌控生命周期。
192
201
  - 前台模式若想交给外部进程管理器(systemd / PM2)托管,加 `--foreground` 让其在前台运行并由管理器负责守护重启。
193
202
  - 支持断线自动重连(可在配置中调整);瞬时断连期间连接记录会保留,仅在进程退出时清除。
203
+ - 云端响应超过单条消息上限时会返回结构化错误并保持连接。截图过大时可指定元素范围,
204
+ 或使用 `format: "jpeg"` 和较低的 `quality` 重试。
package/dist/bin.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -489,6 +489,7 @@ var QoderConnector = class {
489
489
  connect() {
490
490
  if (this.running) return;
491
491
  this.running = true;
492
+ this.options.onStateChange?.({ state: "connecting" });
492
493
  this.abortController = new AbortController();
493
494
  void this.run(this.abortController.signal);
494
495
  }
@@ -512,6 +513,7 @@ var QoderConnector = class {
512
513
  async (frame) => this.handleFrame(sessionId, frame, signal),
513
514
  () => {
514
515
  this.reconnectAttempts = 0;
516
+ this.options.onStateChange?.({ state: "connected" });
515
517
  }
516
518
  );
517
519
  if (!signal.aborted) throw new Error("Qoder event stream ended");
@@ -520,6 +522,7 @@ var QoderConnector = class {
520
522
  const message = error instanceof Error ? error.message : String(error);
521
523
  if (!this.connected && error instanceof QoderPairingExpiredError) {
522
524
  this.running = false;
525
+ this.options.onStateChange?.({ state: "failed", reason: message });
523
526
  if (this.options.onInitialConnectionFailed) {
524
527
  this.options.onInitialConnectionFailed(message);
525
528
  } else {
@@ -528,6 +531,7 @@ var QoderConnector = class {
528
531
  return;
529
532
  }
530
533
  if (!this.connected && this.options.failFast) {
534
+ this.options.onStateChange?.({ state: "failed", reason: message });
531
535
  this.options.onInitialConnectionFailed?.(message);
532
536
  this.running = false;
533
537
  return;
@@ -537,10 +541,21 @@ var QoderConnector = class {
537
541
  console.error(
538
542
  `[CloudConnector] Qoder max reconnect attempts (${this.maxReconnectAttempts}) reached`
539
543
  );
544
+ this.options.onStateChange?.({
545
+ state: "failed",
546
+ reason: message,
547
+ reconnectAttempt: this.reconnectAttempts
548
+ });
540
549
  this.running = false;
541
550
  return;
542
551
  }
543
552
  console.error(`[CloudConnector] Qoder connection error: ${message}`);
553
+ this.options.onStateChange?.({
554
+ state: "reconnecting",
555
+ reason: message,
556
+ reconnectAttempt: this.reconnectAttempts,
557
+ retryInMs: this.reconnectInterval
558
+ });
544
559
  try {
545
560
  await this.sleep(this.reconnectInterval, signal);
546
561
  } catch {
@@ -592,12 +607,14 @@ var QoderConnector = class {
592
607
  this.sessionId = pairing.sessionId;
593
608
  this.connected = true;
594
609
  this.reconnectAttempts = 0;
610
+ this.options.onStateChange?.({ state: "connected" });
595
611
  this.options.onConnected?.();
596
612
  console.log(`[CloudConnector] Connected to Qoder session ${pairing.sessionId}`);
597
613
  }
598
614
  }
599
615
  async handleFrame(sessionId, frame, signal) {
600
616
  this.reconnectAttempts = 0;
617
+ this.options.onStateChange?.({ state: "connected", heartbeat: true });
601
618
  const event = frame.data;
602
619
  const eventId = event.id ?? frame.id;
603
620
  if (event.type !== "agent.custom_tool_use" || event.name !== QODER_TOOL_NAME || !eventId) {
@@ -660,12 +677,13 @@ var QoderConnector = class {
660
677
  };
661
678
 
662
679
  // src/index.ts
663
- var CLOUD_CONNECTOR_VERSION = true ? "2.9.5" : "unknown";
680
+ var CLOUD_CONNECTOR_VERSION = true ? "2.9.6" : "unknown";
664
681
  var DEFAULT_RECONNECT_INTERVAL = 5e3;
665
682
  var BACKOFF_BASE_MS = 1e3;
666
683
  var BACKOFF_MAX_MS = 3e4;
667
684
  var SLOW_PROBE_INTERVAL_MS = 6e4;
668
685
  var FAST_RECONNECT_ATTEMPTS = 5;
686
+ var CONNECTOR_REPLACED_REASON = "Connector replaced by a newer connection";
669
687
  var CloudConnector = class {
670
688
  options;
671
689
  endpoint;
@@ -691,7 +709,9 @@ var CloudConnector = class {
691
709
  maxReconnectAttempts: options.maxReconnectAttempts ?? -1,
692
710
  failFast: options.failFast ?? false,
693
711
  onInitialConnectionFailed: options.onInitialConnectionFailed,
694
- onConnected: options.onConnected
712
+ onConnected: options.onConnected,
713
+ onStateChange: options.onStateChange,
714
+ onSuperseded: options.onSuperseded
695
715
  };
696
716
  this.identity = resolveConnectorIdentity(options);
697
717
  }
@@ -712,6 +732,7 @@ var CloudConnector = class {
712
732
  this.hasConnected = true;
713
733
  this.options.onConnected?.(this.options.serverUrl, this.identity);
714
734
  },
735
+ onStateChange: (change) => this.emitState(change),
715
736
  onInitialConnectionFailed: this.options.onInitialConnectionFailed
716
737
  });
717
738
  this.qoderConnector.connect();
@@ -728,6 +749,9 @@ var CloudConnector = class {
728
749
  if (this.ws && (this.ws.readyState === 0 || this.ws.readyState === 1)) {
729
750
  return;
730
751
  }
752
+ if (!this.hasConnected && this.reconnectAttempts === 0) {
753
+ this.emitState({ state: "connecting" });
754
+ }
731
755
  let serverUrl = this.endpoint.transportUrl;
732
756
  if (this.shouldTryWss && serverUrl.startsWith("ws://")) {
733
757
  serverUrl = serverUrl.replace("ws://", "wss://");
@@ -742,6 +766,7 @@ var CloudConnector = class {
742
766
  this.wssRetryAttempts = 0;
743
767
  this.sendConnectorHello();
744
768
  this.startHeartbeat();
769
+ this.emitState({ state: "connected" });
745
770
  this.options.onConnected?.(this.options.serverUrl, this.identity);
746
771
  console.log(`[CloudConnector] Connected to ${serverUrl}`);
747
772
  });
@@ -749,19 +774,7 @@ var CloudConnector = class {
749
774
  this.handleMessage(data);
750
775
  });
751
776
  this.ws.on("close", (code, reason) => {
752
- console.log(`[CloudConnector] Disconnected (${code}: ${reason.toString()})`);
753
- this.stopHeartbeat();
754
- this.messageBuffer = "";
755
- if (this.shouldTryWss && serverUrl.startsWith("ws://")) {
756
- return;
757
- }
758
- if (this.options.failFast && !this.hasConnected) {
759
- const reasonText = reason.toString();
760
- const message = this.lastConnectionError || reasonText || `Connection closed (${code})`;
761
- this.options.onInitialConnectionFailed?.(message);
762
- return;
763
- }
764
- this.tryReconnect();
777
+ this.handleClose(code, reason.toString(), serverUrl);
765
778
  });
766
779
  this.ws.on("error", (error) => {
767
780
  console.error(`[CloudConnector] WebSocket error:`, error.message);
@@ -811,8 +824,28 @@ var CloudConnector = class {
811
824
  }
812
825
  }
813
826
  }
827
+ handleClose(code, reasonText, serverUrl) {
828
+ console.log(`[CloudConnector] Disconnected (${code}: ${reasonText})`);
829
+ this.stopHeartbeat();
830
+ this.messageBuffer = "";
831
+ if (this.shouldTryWss && serverUrl.startsWith("ws://")) return;
832
+ if (code === 1e3 && reasonText === CONNECTOR_REPLACED_REASON) {
833
+ this.isManualClose = true;
834
+ console.error("[CloudConnector] Superseded by a newer connector; exiting");
835
+ this.options.onSuperseded?.();
836
+ return;
837
+ }
838
+ if (this.options.failFast && !this.hasConnected) {
839
+ const message = this.lastConnectionError || reasonText || `Connection closed (${code})`;
840
+ this.emitState({ state: "failed", reason: message });
841
+ this.options.onInitialConnectionFailed?.(message);
842
+ return;
843
+ }
844
+ this.tryReconnect(this.lastConnectionError || reasonText || `Connection closed (${code})`);
845
+ }
814
846
  async handleCloudMessage(message) {
815
847
  if (isHeartbeatMessage(message)) {
848
+ this.emitState({ state: "connected", heartbeat: true });
816
849
  if (message.type === "ping") {
817
850
  this.sendHeartbeatResponse(message.timestamp);
818
851
  }
@@ -835,7 +868,22 @@ var CloudConnector = class {
835
868
  }
836
869
  sendResponse(response) {
837
870
  if (this.ws && this.ws.readyState === 1) {
838
- this.ws.send(JSON.stringify(response) + "\n");
871
+ const message = JSON.stringify(response) + "\n";
872
+ const bytes = Buffer.byteLength(message, "utf-8");
873
+ if (bytes > MAX_BUFFER_SIZE) {
874
+ console.error(
875
+ `[CloudConnector] Response ${response.id} exceeds message limit (${bytes} > ${MAX_BUFFER_SIZE} bytes)`
876
+ );
877
+ this.ws.send(
878
+ JSON.stringify({
879
+ id: response.id,
880
+ success: false,
881
+ error: `Cloud response exceeds ${MAX_BUFFER_SIZE} byte message limit (${bytes} bytes). Reduce the result size; for screenshots use JPEG quality or a selector.`
882
+ }) + "\n"
883
+ );
884
+ return;
885
+ }
886
+ this.ws.send(message);
839
887
  }
840
888
  }
841
889
  sendConnectorHello() {
@@ -872,7 +920,7 @@ var CloudConnector = class {
872
920
  this.heartbeatTimer = null;
873
921
  }
874
922
  }
875
- tryReconnect() {
923
+ tryReconnect(reason) {
876
924
  if (this.isManualClose) return;
877
925
  if (this.reconnectTimer) return;
878
926
  this.reconnectAttempts++;
@@ -880,6 +928,11 @@ var CloudConnector = class {
880
928
  console.log(
881
929
  `[CloudConnector] Max reconnect attempts (${this.options.maxReconnectAttempts}) reached`
882
930
  );
931
+ this.emitState({
932
+ state: "failed",
933
+ ...reason ? { reason } : {},
934
+ reconnectAttempt: this.reconnectAttempts
935
+ });
883
936
  return;
884
937
  }
885
938
  const isSlowProbe = this.reconnectAttempts > FAST_RECONNECT_ATTEMPTS;
@@ -893,17 +946,27 @@ var CloudConnector = class {
893
946
  `[CloudConnector] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts}/${FAST_RECONNECT_ATTEMPTS})`
894
947
  );
895
948
  }
949
+ this.emitState({
950
+ state: "reconnecting",
951
+ ...reason ? { reason } : {},
952
+ reconnectAttempt: this.reconnectAttempts,
953
+ retryInMs: delay
954
+ });
896
955
  this.reconnectTimer = setTimeout(() => {
897
956
  this.reconnectTimer = null;
898
957
  this.connect();
899
958
  }, delay);
900
959
  }
960
+ emitState(change) {
961
+ this.options.onStateChange?.(change);
962
+ }
901
963
  };
902
964
 
903
965
  export {
904
966
  parseConnectorEndpoint,
905
967
  isConnectorEndpoint,
906
968
  requireConnectorEndpoint,
969
+ resolveConnectorIdentity,
907
970
  QODER_TOOL_NAME,
908
971
  DEFAULT_QODER_API_BASE_URL,
909
972
  QoderApiError,
package/dist/cli.d.ts CHANGED
@@ -1,4 +1,3 @@
1
- #!/usr/bin/env node
2
1
  import type { CloudConnectorOptions } from './index.js';
3
2
  declare const SUBCOMMANDS: readonly ["start", "stop", "restart", "status", "list", "logs"];
4
3
  type Subcommand = (typeof SUBCOMMANDS)[number];
@@ -10,6 +9,7 @@ export interface ParsedCloudConnectorArgs {
10
9
  options?: CloudConnectorOptions;
11
10
  serverUrl?: string;
12
11
  stopAll: boolean;
12
+ stopPid?: number;
13
13
  version: boolean;
14
14
  }
15
15
  export declare function parseCloudConnectorArgs(argv: string[]): ParsedCloudConnectorArgs;
package/dist/cli.js CHANGED
@@ -1,21 +1,23 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  CloudConnector,
4
- isConnectorEndpoint
5
- } from "./chunks/chunk-JSS4P4BA.js";
4
+ isConnectorEndpoint,
5
+ resolveConnectorIdentity
6
+ } from "./chunks/chunk-QK642AP7.js";
6
7
 
7
8
  // src/cli.ts
8
- import path from "node:path";
9
- import { fileURLToPath as fileURLToPath2 } from "node:url";
10
9
  import { Command, CommanderError, InvalidArgumentError } from "commander";
11
10
 
12
11
  // src/daemon.ts
13
12
  import { fileURLToPath } from "node:url";
14
13
  import {
14
+ claimRecord,
15
15
  createDaemon,
16
+ isAlive,
17
+ readRecord,
16
18
  readLiveRecords,
17
- removeRecord,
18
- writeRecord
19
+ removeRecordIfPid,
20
+ writeRecordIfPid
19
21
  } from "@mearl/daemon-core";
20
22
 
21
23
  // src/paths.ts
@@ -32,6 +34,57 @@ function logFileFor(serverUrl) {
32
34
  // src/daemon.ts
33
35
  var SCRIPT_PATH = fileURLToPath(import.meta.url);
34
36
  var CONNECT_TIMEOUT_MS = 6e4;
37
+ var DEFAULT_HEARTBEAT_INTERVAL_SEC = 30;
38
+ function redactedServerUrl(serverUrl) {
39
+ try {
40
+ const parsed = new URL(serverUrl);
41
+ for (const key of parsed.searchParams.keys()) {
42
+ if (/token/i.test(key)) parsed.searchParams.set(key, "redacted");
43
+ }
44
+ return parsed.toString();
45
+ } catch {
46
+ return serverUrl.replace(/([?&][^=&\s]*token[^=&\s]*=)[^&\s]*/gi, "$1redacted");
47
+ }
48
+ }
49
+ function resolveConnectorHealth(record, now = Date.now()) {
50
+ switch (record.connectionState) {
51
+ case "connecting":
52
+ return "starting";
53
+ case "reconnecting":
54
+ return "reconnecting";
55
+ case "failed":
56
+ return "failed";
57
+ case "connected": {
58
+ if (record.serverUrl.startsWith("qoder://")) return "healthy";
59
+ const freshness = record.lastHeartbeatAt ?? record.connectedAt;
60
+ if (!freshness) return "degraded";
61
+ const timestamp = Date.parse(freshness);
62
+ const staleAfterMs = Math.max(record.heartbeatIntervalSec ?? DEFAULT_HEARTBEAT_INTERVAL_SEC, 1) * 3e3;
63
+ return Number.isFinite(timestamp) && now - timestamp <= staleAfterMs ? "healthy" : "degraded";
64
+ }
65
+ default:
66
+ return record.daemonState === "starting" ? "starting" : "unknown";
67
+ }
68
+ }
69
+ function formatConnectorStatus(record, now = Date.now()) {
70
+ const health = resolveConnectorHealth(record, now);
71
+ const lines = [
72
+ ` status: ${health}`,
73
+ ` pid: ${record.pid}`,
74
+ ` server: ${redactedServerUrl(record.serverUrl)}`
75
+ ];
76
+ if (health === "unknown") lines.push(" note: restart to enable health reporting");
77
+ if (record.startedAt) lines.push(` started at: ${record.startedAt}`);
78
+ if (record.connectedAt) lines.push(` connected: ${record.connectedAt}`);
79
+ if (record.lastHeartbeatAt) lines.push(` heartbeat: ${record.lastHeartbeatAt}`);
80
+ if (record.lastDisconnectedAt) lines.push(` disconnected: ${record.lastDisconnectedAt}`);
81
+ if (record.lastError) lines.push(` last error: ${record.lastError}`);
82
+ if (record.reconnectAttempt !== void 0) {
83
+ lines.push(` retry: attempt ${record.reconnectAttempt}`);
84
+ }
85
+ if (record.nextRetryAt) lines.push(` next retry: ${record.nextRetryAt}`);
86
+ return lines;
87
+ }
35
88
  function daemonFor(serverUrl, foregroundArgs = []) {
36
89
  return createDaemon({
37
90
  name: "CloudConnector",
@@ -41,7 +94,14 @@ function daemonFor(serverUrl, foregroundArgs = []) {
41
94
  // The foreground child is launched as `cli.js --foreground <serverUrl> [opts]`.
42
95
  foregroundArgs: [serverUrl, ...foregroundArgs],
43
96
  readyTimeoutMs: CONNECT_TIMEOUT_MS,
44
- formatInfo: (rec) => ` server: ${rec.serverUrl}`
97
+ startingRecord: (pid, startedAt) => ({
98
+ pid,
99
+ serverUrl,
100
+ startedAt,
101
+ connectionState: "connecting",
102
+ stateUpdatedAt: startedAt
103
+ }),
104
+ formatInfo: (rec) => formatConnectorStatus(rec).join("\n")
45
105
  });
46
106
  }
47
107
  function startDaemon(serverUrl, passthroughArgs) {
@@ -50,26 +110,55 @@ function startDaemon(serverUrl, passthroughArgs) {
50
110
  function stopDaemon(serverUrl) {
51
111
  return daemonFor(serverUrl).stop();
52
112
  }
113
+ async function stopDaemonByPid(pid) {
114
+ const record = liveConnectorRecords().find((candidate) => candidate.pid === pid);
115
+ if (!record) {
116
+ console.log(`[CloudConnector] No running connector registered for pid ${pid}`);
117
+ return;
118
+ }
119
+ await daemonFor(record.serverUrl).stop(pid);
120
+ }
53
121
  function restartDaemon(serverUrl, passthroughArgs) {
54
122
  return daemonFor(serverUrl, passthroughArgs).restart();
55
123
  }
56
124
  function statusDaemon(serverUrl) {
57
125
  if (serverUrl) {
58
- daemonFor(serverUrl).status();
126
+ const record = daemonFor(serverUrl).running();
127
+ if (!record) {
128
+ console.log("[CloudConnector] Status: stopped");
129
+ return;
130
+ }
131
+ console.log(`[CloudConnector] Status: ${resolveConnectorHealth(record)}`);
132
+ console.log(formatConnectorStatus(record).slice(1).join("\n"));
133
+ return;
134
+ }
135
+ const records = liveConnectorRecords();
136
+ if (records.length === 0) {
137
+ console.log("[CloudConnector] No running connectors");
59
138
  return;
60
139
  }
61
- listDaemons();
140
+ console.log(`[CloudConnector] ${records.length} connector status(es):`);
141
+ records.forEach((record, index) => {
142
+ if (index > 0) console.log("");
143
+ console.log(formatConnectorStatus(record).join("\n"));
144
+ });
145
+ }
146
+ function liveConnectorRecords() {
147
+ return readLiveRecords(CONNECTORS_DIR).sort(
148
+ (left, right) => left.serverUrl.localeCompare(right.serverUrl)
149
+ );
62
150
  }
63
151
  function listDaemons() {
64
- const records = readLiveRecords(CONNECTORS_DIR);
152
+ const records = liveConnectorRecords();
65
153
  if (records.length === 0) {
66
154
  console.log("[CloudConnector] No running connectors");
67
155
  return;
68
156
  }
69
157
  console.log(`[CloudConnector] ${records.length} running connector(s):`);
70
- for (const rec of records) {
71
- const since = rec.startedAt ? ` (since ${rec.startedAt})` : "";
72
- console.log(` pid ${rec.pid} ${rec.serverUrl}${since}`);
158
+ for (const record of records) {
159
+ console.log(
160
+ ` [${resolveConnectorHealth(record)}] pid ${record.pid} ${redactedServerUrl(record.serverUrl)}`
161
+ );
73
162
  }
74
163
  }
75
164
  async function stopAllDaemons() {
@@ -89,24 +178,115 @@ function runForeground(options) {
89
178
  const serverUrl = options.serverUrl;
90
179
  const configFile = configFileFor(serverUrl);
91
180
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
92
- const writeOwnRecord = (_serverUrl, identity) => {
181
+ const identity = resolveConnectorIdentity(options);
182
+ let hasConnected = false;
183
+ let connectedAt;
184
+ let lastHeartbeatAt;
185
+ let lastDisconnectedAt;
186
+ const initialRecord = {
187
+ serverUrl,
188
+ pid: process.pid,
189
+ startedAt,
190
+ connectorId: identity.connectorId,
191
+ name: identity.name,
192
+ connectionState: "connecting",
193
+ stateUpdatedAt: startedAt,
194
+ daemonState: "starting",
195
+ heartbeatIntervalSec: options.heartbeatInterval ?? DEFAULT_HEARTBEAT_INTERVAL_SEC
196
+ };
197
+ const existing = readRecord(configFile);
198
+ if (existing && existing.pid !== process.pid && isAlive(existing.pid)) {
199
+ console.log(`[CloudConnector] Already running for this server (pid ${existing.pid})`);
200
+ return;
201
+ }
202
+ if (existing && existing.pid !== process.pid) removeRecordIfPid(configFile, existing.pid);
203
+ let ownsRecord = existing?.pid === process.pid;
204
+ for (let attempt = 0; !ownsRecord && attempt < 2; attempt++) {
205
+ if (claimRecord(configFile, initialRecord)) {
206
+ ownsRecord = true;
207
+ break;
208
+ }
209
+ const owner = readRecord(configFile);
210
+ if (owner?.pid === process.pid) {
211
+ ownsRecord = true;
212
+ break;
213
+ }
214
+ if (owner) {
215
+ if (isAlive(owner.pid)) {
216
+ console.log(`[CloudConnector] Already running for this server (pid ${owner.pid})`);
217
+ return;
218
+ }
219
+ removeRecordIfPid(configFile, owner.pid);
220
+ }
221
+ }
222
+ if (!ownsRecord) {
223
+ const owner = readRecord(configFile);
224
+ if (owner && owner.pid !== process.pid && isAlive(owner.pid)) {
225
+ console.log(`[CloudConnector] Already running for this server (pid ${owner.pid})`);
226
+ } else {
227
+ console.error("[CloudConnector] Failed to claim connector registry record");
228
+ }
229
+ return;
230
+ }
231
+ if (!writeRecordIfPid(configFile, process.pid, initialRecord)) {
232
+ console.error("[CloudConnector] Connector registry ownership changed during startup");
233
+ return;
234
+ }
235
+ const writeState = (change) => {
93
236
  try {
94
- writeRecord(configFile, {
237
+ const now = (/* @__PURE__ */ new Date()).toISOString();
238
+ if (change.state === "connected") {
239
+ hasConnected = true;
240
+ if (change.heartbeat) lastHeartbeatAt = now;
241
+ else {
242
+ connectedAt = now;
243
+ lastHeartbeatAt = void 0;
244
+ }
245
+ } else if (change.state === "reconnecting" || change.state === "failed") {
246
+ lastDisconnectedAt = now;
247
+ }
248
+ const record = {
95
249
  serverUrl,
96
250
  pid: process.pid,
97
251
  startedAt,
98
252
  connectorId: identity.connectorId,
99
- name: identity.name
100
- });
253
+ name: identity.name,
254
+ connectionState: change.state,
255
+ stateUpdatedAt: now,
256
+ heartbeatIntervalSec: options.heartbeatInterval ?? DEFAULT_HEARTBEAT_INTERVAL_SEC,
257
+ ...hasConnected ? {} : { daemonState: "starting" },
258
+ ...connectedAt ? { connectedAt } : {},
259
+ ...lastHeartbeatAt ? { lastHeartbeatAt } : {},
260
+ ...lastDisconnectedAt ? { lastDisconnectedAt } : {},
261
+ ...change.reason ? { lastError: change.reason } : {},
262
+ ...change.reconnectAttempt === void 0 ? {} : { reconnectAttempt: change.reconnectAttempt },
263
+ ...change.retryInMs === void 0 ? {} : { nextRetryAt: new Date(Date.now() + change.retryInMs).toISOString() }
264
+ };
265
+ writeRecordIfPid(configFile, process.pid, record);
101
266
  } catch (error) {
102
267
  console.error(`[CloudConnector] Failed to write registry record: ${String(error)}`);
103
268
  }
104
269
  };
270
+ const removeOwnRecord = () => {
271
+ removeRecordIfPid(configFile, process.pid);
272
+ };
105
273
  const connector = new CloudConnector({
106
274
  ...options,
107
- onConnected: writeOwnRecord,
275
+ connectorId: identity.connectorId,
276
+ connectorName: identity.name,
277
+ onConnected: options.onConnected,
278
+ onStateChange: (change) => {
279
+ writeState(change);
280
+ options.onStateChange?.(change);
281
+ },
282
+ onSuperseded: () => {
283
+ removeOwnRecord();
284
+ options.onSuperseded?.();
285
+ process.exit(0);
286
+ },
108
287
  onInitialConnectionFailed: (message) => {
109
288
  console.error(`[CloudConnector] Initial connection failed: ${message}`);
289
+ removeOwnRecord();
110
290
  process.exit(1);
111
291
  }
112
292
  });
@@ -118,7 +298,7 @@ function runForeground(options) {
118
298
  console.log(`
119
299
  [CloudConnector] Received ${signal}, shutting down...`);
120
300
  connector.disconnect();
121
- removeRecord(configFile);
301
+ removeOwnRecord();
122
302
  process.exit(0);
123
303
  };
124
304
  process.on("SIGINT", () => shutdown("SIGINT"));
@@ -126,7 +306,7 @@ function runForeground(options) {
126
306
  }
127
307
 
128
308
  // src/cli.ts
129
- var CLOUD_CONNECTOR_VERSION = true ? "2.9.5" : "unknown";
309
+ var CLOUD_CONNECTOR_VERSION = true ? "2.9.6" : "unknown";
130
310
  var SUBCOMMANDS = ["start", "stop", "restart", "status", "list", "logs"];
131
311
  var CONNECTION_OPTION_NAMES = /* @__PURE__ */ new Set([
132
312
  "foreground",
@@ -142,11 +322,11 @@ function showHelp() {
142
322
 
143
323
  Usage:
144
324
  mearl-cloud-connector <server-url> [options]
145
- mearl-cloud-connector <command> [server-url] [options]
325
+ mearl-cloud-connector <command> [server-url|pid] [options]
146
326
 
147
327
  Commands:
148
328
  start <server-url> Start a background connector
149
- stop <server-url> Stop one background connector
329
+ stop <server-url|pid> Stop one registered background connector
150
330
  stop --all Stop every background connector
151
331
  restart <server-url> Restart a background connector
152
332
  status [server-url] Show one connector's status, or list all
@@ -177,6 +357,11 @@ function integerOption(label, minimum) {
177
357
  function optionUsed(program, name) {
178
358
  return program.getOptionValueSource(name) === "cli";
179
359
  }
360
+ function parseConnectorPid(value) {
361
+ if (!/^[1-9]\d*$/.test(value)) return void 0;
362
+ const pid = Number(value);
363
+ return Number.isSafeInteger(pid) ? pid : void 0;
364
+ }
180
365
  function assertAllowedOptions(program, command) {
181
366
  const allowed = command === null || command === "start" || command === "restart" ? CONNECTION_OPTION_NAMES : command === "stop" ? /* @__PURE__ */ new Set(["all"]) : /* @__PURE__ */ new Set();
182
367
  for (const option of program.options) {
@@ -246,20 +431,24 @@ function parseCloudConnectorArgs(argv) {
246
431
  throw new Error(`Unknown command: ${first}`);
247
432
  }
248
433
  const command = bareEndpoint || first === void 0 ? null : first;
249
- const serverUrl = bareEndpoint ? first : second;
250
- if (serverUrl !== void 0 && !isConnectorEndpoint(serverUrl)) {
251
- throw new Error("server-url must use ws://, wss://, or qoder://");
434
+ const target = bareEndpoint ? first : second;
435
+ const stopPid = command === "stop" && target ? parseConnectorPid(target) : void 0;
436
+ const serverUrl = target && isConnectorEndpoint(target) ? target : void 0;
437
+ if (target !== void 0 && !serverUrl && stopPid === void 0) {
438
+ throw new Error(
439
+ command === "stop" ? "stop target must be a ws://, wss://, or qoder:// server-url, or a positive pid" : "server-url must use ws://, wss://, or qoder://"
440
+ );
252
441
  }
253
442
  assertAllowedOptions(program, command);
254
443
  if (command === null && !serverUrl) throw new Error("a command or server-url is required");
255
444
  if ((command === "start" || command === "restart" || command === "logs") && !serverUrl) {
256
445
  throw new Error(`\`${command}\` requires a server-url`);
257
446
  }
258
- if (command === "stop" && !serverUrl && !cliOptions.all) {
259
- throw new Error("`stop` requires a server-url or --all");
447
+ if (command === "stop" && !serverUrl && stopPid === void 0 && !cliOptions.all) {
448
+ throw new Error("`stop` requires a server-url, pid, or --all");
260
449
  }
261
- if (command === "stop" && serverUrl && cliOptions.all) {
262
- throw new Error("`stop` accepts either a server-url or --all, not both");
450
+ if (command === "stop" && (serverUrl || stopPid !== void 0) && cliOptions.all) {
451
+ throw new Error("`stop` accepts either a server-url, pid, or --all, not both");
263
452
  }
264
453
  const foreground = command === null || cliOptions.foreground === true;
265
454
  return {
@@ -270,6 +459,7 @@ function parseCloudConnectorArgs(argv) {
270
459
  ...serverUrl ? { serverUrl } : {},
271
460
  ...foreground && serverUrl ? { options: connectorOptions(serverUrl, cliOptions) } : {},
272
461
  stopAll: command === "stop" && cliOptions.all === true,
462
+ ...stopPid === void 0 ? {} : { stopPid },
273
463
  version: false
274
464
  };
275
465
  }
@@ -310,6 +500,7 @@ async function main(argv = process.argv.slice(2)) {
310
500
  break;
311
501
  case "stop":
312
502
  if (parsed.stopAll) await stopAllDaemons();
503
+ else if (parsed.stopPid !== void 0) await stopDaemonByPid(parsed.stopPid);
313
504
  else await stopDaemon(parsed.serverUrl);
314
505
  break;
315
506
  case "restart":
@@ -327,16 +518,11 @@ async function main(argv = process.argv.slice(2)) {
327
518
  }
328
519
  return 0;
329
520
  }
330
- var currentFile = fileURLToPath2(import.meta.url);
331
- if (process.argv[1] && path.resolve(process.argv[1]) === currentFile) {
332
- main().then((code) => {
333
- process.exitCode = code;
334
- }).catch((error) => {
335
- console.error("[CloudConnector] Fatal error:", error);
336
- process.exitCode = 1;
337
- });
521
+
522
+ // src/bin.ts
523
+ try {
524
+ process.exitCode = await main();
525
+ } catch (error) {
526
+ console.error("[CloudConnector] Fatal error:", error);
527
+ process.exitCode = 1;
338
528
  }
339
- export {
340
- main,
341
- parseCloudConnectorArgs
342
- };
package/dist/daemon.d.ts CHANGED
@@ -1,14 +1,28 @@
1
1
  import { type DaemonRecord } from '@mearl/daemon-core';
2
- import { CloudConnectorOptions } from './index.js';
2
+ import { type CloudConnectorOptions, type CloudConnectorRuntimeState } from './index.js';
3
3
  export interface ConnectorRecord extends DaemonRecord {
4
4
  serverUrl: string;
5
5
  connectorId?: string;
6
6
  name?: string;
7
+ connectionState?: CloudConnectorRuntimeState;
8
+ stateUpdatedAt?: string;
9
+ connectedAt?: string;
10
+ lastHeartbeatAt?: string;
11
+ lastDisconnectedAt?: string;
12
+ lastError?: string;
13
+ reconnectAttempt?: number;
14
+ nextRetryAt?: string;
15
+ heartbeatIntervalSec?: number;
7
16
  }
17
+ export type ConnectorHealth = 'starting' | 'healthy' | 'reconnecting' | 'degraded' | 'failed' | 'unknown';
18
+ export declare function resolveConnectorHealth(record: ConnectorRecord, now?: number): ConnectorHealth;
19
+ export declare function formatConnectorStatus(record: ConnectorRecord, now?: number): string[];
8
20
  /** Start a background connector for a serverUrl (idempotent — reuses a live one). */
9
21
  export declare function startDaemon(serverUrl: string, passthroughArgs: string[]): Promise<void>;
10
22
  /** Stop the background connector for a serverUrl. */
11
23
  export declare function stopDaemon(serverUrl: string): Promise<void>;
24
+ /** Stop a connector by a pid owned by the shared connector registry. */
25
+ export declare function stopDaemonByPid(pid: number): Promise<void>;
12
26
  /** Restart the background connector for a serverUrl. */
13
27
  export declare function restartDaemon(serverUrl: string, passthroughArgs: string[]): Promise<void>;
14
28
  /** Show status for one connector, or list all running connectors when no url is given. */
@@ -24,12 +38,10 @@ export declare function printLogs(serverUrl: string): void;
24
38
  * child (`--foreground`) and a direct `cloud-connector <url>` invocation (e.g.
25
39
  * native-host spawns the connector this way).
26
40
  *
27
- * The connector is the SOLE writer of its own registry record: it writes the
28
- * record on every (re)connect and removes it on graceful shutdown, so any
29
- * manager — the daemon CLI, a fresh native-host adopting it after a reload —
30
- * can discover it through the shared registry. The record is intentionally kept
31
- * across transient disconnects (the connector reconnects with backoff); it is
32
- * only removed when the process exits cleanly. A crash leaves a stale record,
33
- * which readers prune via the pid liveness check.
41
+ * The daemon manager may reserve the registry record during process startup;
42
+ * this foreground process claims or adopts that reservation and then persists
43
+ * transport health on each connection transition. Records remain across
44
+ * transient disconnects and are removed only by their owning pid on shutdown.
45
+ * Readers prune records left behind by crashed processes via liveness checks.
34
46
  */
35
47
  export declare function runForeground(options: CloudConnectorOptions): void;
package/dist/index.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import { type ConnectorIdentity } from './identity.js';
2
+ import type { CloudConnectorStateChange } from './state.js';
2
3
  export { isConnectorEndpoint, parseConnectorEndpoint, requireConnectorEndpoint, type ConnectorEndpoint, type ConnectorEndpointScheme, type QoderConnectorEndpoint, type WebSocketConnectorEndpoint, } from './endpoint.js';
3
4
  export { DEFAULT_QODER_API_BASE_URL, QODER_TOOL_NAME, QoderApiClient, QoderApiError, QoderConnector, formatQoderToolResult, parseQoderSse, type QoderContentBlock, type QoderPairingRequest, type QoderPublicEvent, type QoderSseFrame, } from './qoder.js';
5
+ export type { CloudConnectorRuntimeState, CloudConnectorStateChange } from './state.js';
4
6
  export interface CloudConnectorOptions {
5
7
  serverUrl: string;
6
8
  heartbeatInterval?: number;
@@ -10,10 +12,10 @@ export interface CloudConnectorOptions {
10
12
  connectorId?: string;
11
13
  connectorName?: string;
12
14
  onInitialConnectionFailed?: (message: string) => void;
15
+ onStateChange?: (change: CloudConnectorStateChange) => void;
16
+ onSuperseded?: () => void;
13
17
  /**
14
- * Fired every time the transport connection is (re)established. Used by the
15
- * foreground runner to (re)write this connector's registry record once it is
16
- * actually connected — the signal other managers use to discover/adopt it.
18
+ * Fired every time the transport connection is established or re-established.
17
19
  */
18
20
  onConnected?: (serverUrl: string, identity: ConnectorIdentity) => void;
19
21
  }
@@ -37,6 +39,7 @@ export declare class CloudConnector {
37
39
  connect(): void;
38
40
  disconnect(): void;
39
41
  private handleMessage;
42
+ private handleClose;
40
43
  private handleCloudMessage;
41
44
  private sendResponse;
42
45
  private sendConnectorHello;
@@ -44,4 +47,5 @@ export declare class CloudConnector {
44
47
  private startHeartbeat;
45
48
  private stopHeartbeat;
46
49
  private tryReconnect;
50
+ private emitState;
47
51
  }
package/dist/index.js CHANGED
@@ -10,7 +10,7 @@ import {
10
10
  parseConnectorEndpoint,
11
11
  parseQoderSse,
12
12
  requireConnectorEndpoint
13
- } from "./chunks/chunk-JSS4P4BA.js";
13
+ } from "./chunks/chunk-QK642AP7.js";
14
14
  export {
15
15
  CloudConnector,
16
16
  DEFAULT_QODER_API_BASE_URL,
package/dist/paths.d.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  /**
2
2
  * Subdir under ~/.mearl holding one record/log per connector instance,
3
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.
4
+ * connector, daemon manager, and native-host. All participants derive paths
5
+ * through these helpers so they never disagree on where a connector's record
6
+ * lives.
7
7
  */
8
8
  export declare const CONNECTORS_SUBDIR = "connectors";
9
9
  /** Directory containing all per-connector records and logs. */
package/dist/qoder.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { CloudConnectorStateChange } from './state.js';
1
2
  import type { ConnectorIdentity } from './identity.js';
2
3
  import type { QoderConnectorEndpoint } from './endpoint.js';
3
4
  export declare const QODER_TOOL_NAME = "mearl";
@@ -77,6 +78,7 @@ export interface QoderConnectorOptions {
77
78
  }) => Promise<unknown>;
78
79
  onConnected?: () => void;
79
80
  onInitialConnectionFailed?: (message: string) => void;
81
+ onStateChange?: (change: CloudConnectorStateChange) => void;
80
82
  }
81
83
  export declare class QoderConnector {
82
84
  private readonly options;
@@ -0,0 +1,8 @@
1
+ export type CloudConnectorRuntimeState = 'connecting' | 'connected' | 'reconnecting' | 'failed';
2
+ export interface CloudConnectorStateChange {
3
+ state: CloudConnectorRuntimeState;
4
+ heartbeat?: boolean;
5
+ reason?: string;
6
+ reconnectAttempt?: number;
7
+ retryInMs?: number;
8
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mearl/cloud-connector",
3
- "version": "2.9.5",
3
+ "version": "2.9.6",
4
4
  "description": "Cloud connector for Mearl — bridges cloud agents to a local native-host",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -36,9 +36,9 @@
36
36
  "dependencies": {
37
37
  "commander": "^15.0.0",
38
38
  "ws": "^8.18.0",
39
- "@mearl/daemon-core": "2.9.5",
40
- "@mearl/client": "2.9.5",
41
- "@mearl/cloud-types": "2.9.5"
39
+ "@mearl/cloud-types": "2.9.6",
40
+ "@mearl/client": "2.9.6",
41
+ "@mearl/daemon-core": "2.9.6"
42
42
  },
43
43
  "devDependencies": {
44
44
  "@types/node": "^24.9.1",