@mearl/cloud-connector 2.7.0 → 2.7.2

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
@@ -1,6 +1,6 @@
1
1
  # @mearl/cloud-connector
2
2
 
3
- 本地连接器,用于把云端 Agent 的操作转发到本地 native-host。原有云服务使用 WebSocket;
3
+ 本地连接器,用于把云端 Agent 的操作转发到本地 native-host。普通云模式使用 WebSocket;
4
4
  Qoder Cloud Agent 使用官方 Session API、SSE 事件流和 Client-Side 自定义工具。
5
5
 
6
6
  ## 安装
@@ -54,14 +54,14 @@ mearl-cloud-connector <command> [server-url] [options] # 管理后台守护进
54
54
  **示例:**
55
55
 
56
56
  ```bash
57
- # 前台运行(Ctrl+C 停止)—— 也是 native-host 拉起连接器的方式
58
- mearl-cloud-connector "ws://localhost:8080/ws?token=xxx"
57
+ # 后台启动一个自管理连接器,拥有独立日志文件(推荐)
58
+ mearl-cloud-connector start "wss://cloud.example.com/ws?token=xxx" --name work-mac
59
59
 
60
- # Qoder 异常接管;该地址由 npx @mearl/setup qoder --yes 生成
61
- mearl-cloud-connector "qoder://pair/pairing-code-1234?created=1786723200000"
60
+ # Qoder 配对模式;地址由 npx @mearl/setup --qoder-cloud --yes 生成
61
+ mearl-cloud-connector start "qoder://pair/pairing-code-1234?created=1786723200000"
62
62
 
63
- # 后台启动一个自管理连接器,拥有独立日志文件
64
- mearl-cloud-connector start "wss://cloud.example.com/ws?token=xxx" --name work-mac
63
+ # 前台运行,仅用于排障或交给 systemd / PM2 等外部进程管理器
64
+ mearl-cloud-connector "ws://localhost:8080/ws?token=xxx"
65
65
 
66
66
  # 查看状态 / 列表 / 日志
67
67
  mearl-cloud-connector status
@@ -73,9 +73,13 @@ mearl-cloud-connector stop "wss://cloud.example.com/ws?token=xxx"
73
73
  mearl-cloud-connector stop --all
74
74
 
75
75
  # 自定义心跳和重连配置
76
- mearl-cloud-connector "ws://localhost:8080/ws?token=xxx" --heartbeat 60 --max-reconnect 10
76
+ mearl-cloud-connector start "ws://localhost:8080/ws?token=xxx" --heartbeat 60 --max-reconnect 10
77
77
  ```
78
78
 
79
+ `start` 会在连接成功后返回,后台进程继续运行。Qoder 配对时请紧接着提交 setup 输出的
80
+ `pair` 工具调用;如果配对工具调用已经结束、取消或过期,需要重新生成配对 URL,旧 URL
81
+ 不能重复使用。
82
+
79
83
  ### 编程方式
80
84
 
81
85
  ```typescript
@@ -117,12 +121,20 @@ native-host 与守护进程 CLI 都通过这套共享路径(由 [`@mearl/daemo
117
121
 
118
122
  > 前台运行(含 native-host 托管)时日志输出到 stdout/stderr,不写独立日志文件;只有守护进程模式才落盘到 `<hash>.log`。
119
123
 
120
- Qoder 配对还要求在本地环境提供 `QODER_PERSONAL_ACCESS_TOKEN`。PAT 只用于访问 Qoder
121
- Cloud Session API,连接器不会把它写入 `qoder://` URL、注册表或日志。配对完成后,连接器
124
+ Qoder 配对还要求在本地提供 `QODER_PERSONAL_ACCESS_TOKEN`。连接器依次读取当前进程环境、
125
+ `MEARL_ENV_FILE`、`~/.mearl/.env`;macOS 还会读取当前用户钥匙串中 service 为
126
+ `com.mearl.qoder.pat` 的通用密码。PAT 只用于访问 Qoder Cloud Session API,连接器不会把它
127
+ 写入 `qoder://` URL、进程参数、注册表或日志。配对完成后,连接器
122
128
  保持 SSE 连接,收到 `agent.custom_tool_use` 后调用现有本地 Mearl action,并以
123
129
  `user.custom_tool_result` 回传。截图会优先作为 base64 图片内容块回传;若 Cloud API 拒绝
124
130
  图片块,则退回完整 JSON 文本,避免丢失数据。
125
131
 
132
+ macOS 可在本地终端交互式写入钥匙串,PAT 不会进入 shell 历史:
133
+
134
+ ```bash
135
+ security add-generic-password -U -a "$USER" -s com.mearl.qoder.pat -w
136
+ ```
137
+
126
138
  ## 前置条件
127
139
 
128
140
  1. **安装并初始化本地 Mearl 环境**
@@ -159,7 +171,8 @@ Cloud Session API,连接器不会把它写入 `qoder://` URL、注册表或日
159
171
  Chrome Extension / CDP
160
172
  ```
161
173
 
162
- Qoder 异常接管路径不经过 `@mearl/cloud-server`:
174
+ Qoder 配对信息由 `mearl-cloud-server start` 统一生成;配对后的运行时转发不经过常驻
175
+ cloud-server 服务:
163
176
 
164
177
  ```
165
178
  Qoder Cloud Agent(mearl Client-Side 自定义工具)
@@ -0,0 +1 @@
1
+ export {};
package/dist/cli.js CHANGED
@@ -102,6 +102,77 @@ function resolveConnectorIdentity(options) {
102
102
 
103
103
  // src/qoder.ts
104
104
  import { resolveActionTimeoutSec } from "@mearl/client/action-timeouts";
105
+
106
+ // src/qoder-auth.ts
107
+ import { existsSync, readFileSync } from "node:fs";
108
+ import { homedir, userInfo } from "node:os";
109
+ import { resolve } from "node:path";
110
+ import { spawnSync } from "node:child_process";
111
+ var QODER_TOKEN_KEY = "QODER_PERSONAL_ACCESS_TOKEN";
112
+ var QODER_KEYCHAIN_SERVICE = "com.mearl.qoder.pat";
113
+ function normalizeToken(value) {
114
+ const token = value?.trim();
115
+ if (!token || /[\r\n\0]/.test(token)) return void 0;
116
+ return token;
117
+ }
118
+ function envValue(text, key) {
119
+ for (const line of text.split(/\r?\n/)) {
120
+ const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$/.exec(line);
121
+ if (!match || match[1] !== key) continue;
122
+ let value = (match[2] ?? "").trim();
123
+ if (value.length >= 2 && (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'"))) {
124
+ value = value.slice(1, -1);
125
+ } else {
126
+ value = value.replace(/\s+#.*$/, "").trim();
127
+ }
128
+ return normalizeToken(value);
129
+ }
130
+ return void 0;
131
+ }
132
+ function readMacKeychainToken() {
133
+ const securityPath = "/usr/bin/security";
134
+ if (!existsSync(securityPath)) return void 0;
135
+ try {
136
+ const account = userInfo().username;
137
+ const result = spawnSync(
138
+ securityPath,
139
+ ["find-generic-password", "-a", account, "-s", QODER_KEYCHAIN_SERVICE, "-w"],
140
+ {
141
+ encoding: "utf8",
142
+ stdio: ["ignore", "pipe", "ignore"],
143
+ timeout: 5e3,
144
+ windowsHide: true
145
+ }
146
+ );
147
+ return result.status === 0 ? normalizeToken(result.stdout) : void 0;
148
+ } catch {
149
+ return void 0;
150
+ }
151
+ }
152
+ function resolveQoderPersonalAccessToken(options = {}) {
153
+ const direct = normalizeToken(options.token);
154
+ if (direct) return direct;
155
+ const env = options.env ?? process.env;
156
+ const inherited = normalizeToken(env[QODER_TOKEN_KEY]);
157
+ if (inherited) return inherited;
158
+ const homeDirectory = options.homeDirectory ?? homedir();
159
+ const envFiles = [
160
+ ...env.MEARL_ENV_FILE?.trim() ? [resolve(env.MEARL_ENV_FILE)] : [],
161
+ resolve(homeDirectory, ".mearl", ".env")
162
+ ];
163
+ const readFile = options.readFile ?? ((file) => readFileSync(file, "utf8"));
164
+ for (const file of new Set(envFiles)) {
165
+ try {
166
+ const token = envValue(readFile(file), QODER_TOKEN_KEY);
167
+ if (token) return token;
168
+ } catch {
169
+ }
170
+ }
171
+ if ((options.platform ?? process.platform) !== "darwin") return void 0;
172
+ return normalizeToken((options.readKeychainToken ?? readMacKeychainToken)());
173
+ }
174
+
175
+ // src/qoder.ts
105
176
  var QODER_TOOL_NAME = "mearl";
106
177
  var DEFAULT_QODER_API_BASE_URL = "https://api.qoder.com";
107
178
  var DEFAULT_DISCOVERY_WINDOW_MS = 60 * 60 * 1e3;
@@ -116,6 +187,17 @@ var QoderApiError = class extends Error {
116
187
  this.name = "QoderApiError";
117
188
  }
118
189
  };
190
+ var QoderPairingExpiredError = class extends Error {
191
+ constructor() {
192
+ super(
193
+ 'Qoder pairing is no longer pending. Generate a new pairing URL with `npx @mearl/setup --qoder-cloud --yes`, run the new connector command, and immediately invoke the mearl tool with action "pair". Do not reuse this URL.'
194
+ );
195
+ this.name = "QoderPairingExpiredError";
196
+ }
197
+ };
198
+ function isPendingActionNotFound(error) {
199
+ return error instanceof QoderApiError && /^Pending action\b.*\bwas not found\.?$/i.test(error.message.trim());
200
+ }
119
201
  function safeJson(value) {
120
202
  try {
121
203
  return JSON.stringify(value ?? null);
@@ -132,10 +214,49 @@ function asScreenshot(value) {
132
214
  if (format !== "png" && format !== "jpeg") return null;
133
215
  return { data: value.data, meta: { ...value.meta, format } };
134
216
  }
217
+ function extractBatchScreenshots(value) {
218
+ if (!isRecord(value) || !Array.isArray(value.results)) return null;
219
+ const screenshots = [];
220
+ const results = value.results.map((result) => {
221
+ if (!isRecord(result) || result.action !== "page_screenshot") return result;
222
+ const screenshot = asScreenshot(result.data);
223
+ if (!screenshot) return result;
224
+ const data = { ...result.data };
225
+ delete data.data;
226
+ data.meta = screenshot.meta;
227
+ data.imageContentIndex = screenshots.length + 1;
228
+ screenshots.push(screenshot);
229
+ return { ...result, data };
230
+ });
231
+ if (screenshots.length === 0) return null;
232
+ return { metadata: { ...value, results }, screenshots };
233
+ }
234
+ function imageContentBlock(screenshot) {
235
+ return {
236
+ type: "image",
237
+ source: {
238
+ type: "base64",
239
+ media_type: `image/${screenshot.meta.format}`,
240
+ data: screenshot.data
241
+ }
242
+ };
243
+ }
135
244
  function formatQoderToolResult(value) {
136
245
  const directScreenshot = asScreenshot(value);
137
246
  const nestedScreenshot = !directScreenshot && isRecord(value) ? asScreenshot(value.screenshot) : null;
138
247
  const screenshot = directScreenshot ?? nestedScreenshot;
248
+ if (!screenshot) {
249
+ const batch = extractBatchScreenshots(value);
250
+ if (batch) {
251
+ return {
252
+ content: [
253
+ { type: "text", text: safeJson(batch.metadata) },
254
+ ...batch.screenshots.map(imageContentBlock)
255
+ ],
256
+ fallbackContent: [{ type: "text", text: safeJson(value) }]
257
+ };
258
+ }
259
+ }
139
260
  if (!screenshot) {
140
261
  const content = [{ type: "text", text: safeJson(value) }];
141
262
  return { content, fallbackContent: content };
@@ -147,17 +268,7 @@ function formatQoderToolResult(value) {
147
268
  metadata = { ...value, screenshot: { meta: screenshot.meta } };
148
269
  }
149
270
  return {
150
- content: [
151
- { type: "text", text: safeJson(metadata) },
152
- {
153
- type: "image",
154
- source: {
155
- type: "base64",
156
- media_type: `image/${screenshot.meta.format}`,
157
- data: screenshot.data
158
- }
159
- }
160
- ],
271
+ content: [{ type: "text", text: safeJson(metadata) }, imageContentBlock(screenshot)],
161
272
  fallbackContent: [{ type: "text", text: safeJson(value) }]
162
273
  };
163
274
  }
@@ -312,7 +423,7 @@ async function parseQoderSse(body, onFrame) {
312
423
  await dispatch();
313
424
  }
314
425
  function defaultSleep(milliseconds, signal) {
315
- return new Promise((resolve, reject) => {
426
+ return new Promise((resolve2, reject) => {
316
427
  if (signal.aborted) {
317
428
  reject(signal.reason ?? new Error("Aborted"));
318
429
  return;
@@ -323,7 +434,7 @@ function defaultSleep(milliseconds, signal) {
323
434
  };
324
435
  const timer = setTimeout(() => {
325
436
  signal.removeEventListener("abort", onAbort);
326
- resolve();
437
+ resolve2();
327
438
  }, milliseconds);
328
439
  signal.addEventListener("abort", onAbort, { once: true });
329
440
  });
@@ -356,10 +467,10 @@ function toolInput(event) {
356
467
  var QoderConnector = class {
357
468
  constructor(options) {
358
469
  this.options = options;
359
- const token = options.token?.trim() || process.env.QODER_PERSONAL_ACCESS_TOKEN?.trim();
470
+ const token = resolveQoderPersonalAccessToken({ token: options.token });
360
471
  if (!token) {
361
472
  throw new Error(
362
- "Qoder authentication is required. Set QODER_PERSONAL_ACCESS_TOKEN and run the connector again."
473
+ "Qoder authentication is required. Set QODER_PERSONAL_ACCESS_TOKEN, add it to ~/.mearl/.env, or configure the macOS Keychain item com.mearl.qoder.pat, then retry."
363
474
  );
364
475
  }
365
476
  this.api = new QoderApiClient(
@@ -418,6 +529,15 @@ var QoderConnector = class {
418
529
  } catch (error) {
419
530
  if (signal.aborted) return;
420
531
  const message = error instanceof Error ? error.message : String(error);
532
+ if (!this.connected && error instanceof QoderPairingExpiredError) {
533
+ this.running = false;
534
+ if (this.options.onInitialConnectionFailed) {
535
+ this.options.onInitialConnectionFailed(message);
536
+ } else {
537
+ console.error(`[CloudConnector] Qoder connection error: ${message}`);
538
+ }
539
+ return;
540
+ }
421
541
  if (!this.connected && this.options.failFast) {
422
542
  this.options.onInitialConnectionFailed?.(message);
423
543
  this.running = false;
@@ -457,22 +577,29 @@ var QoderConnector = class {
457
577
  }
458
578
  async completePairing(pairing, signal) {
459
579
  if (!this.connected) {
460
- this.lastEventId = await this.api.sendCustomToolResult(
461
- pairing.sessionId,
462
- pairing.event.id,
463
- [
464
- {
465
- type: "text",
466
- text: safeJson({
467
- connected: true,
468
- connectorId: this.options.identity.connectorId,
469
- name: this.options.identity.name
470
- })
471
- }
472
- ],
473
- false,
474
- signal
475
- ) ?? pairing.event.id;
580
+ let resultEventId;
581
+ try {
582
+ resultEventId = await this.api.sendCustomToolResult(
583
+ pairing.sessionId,
584
+ pairing.event.id,
585
+ [
586
+ {
587
+ type: "text",
588
+ text: safeJson({
589
+ connected: true,
590
+ connectorId: this.options.identity.connectorId,
591
+ name: this.options.identity.name
592
+ })
593
+ }
594
+ ],
595
+ false,
596
+ signal
597
+ );
598
+ } catch (error) {
599
+ if (isPendingActionNotFound(error)) throw new QoderPairingExpiredError();
600
+ throw error;
601
+ }
602
+ this.lastEventId = resultEventId ?? pairing.event.id;
476
603
  this.sessionId = pairing.sessionId;
477
604
  this.connected = true;
478
605
  this.reconnectAttempts = 0;
@@ -544,7 +671,7 @@ var QoderConnector = class {
544
671
  };
545
672
 
546
673
  // src/index.ts
547
- var CLOUD_CONNECTOR_VERSION = true ? "2.7.0" : "unknown";
674
+ var CLOUD_CONNECTOR_VERSION = true ? "2.7.2" : "unknown";
548
675
  var DEFAULT_RECONNECT_INTERVAL = 5e3;
549
676
  var BACKOFF_BASE_MS = 1e3;
550
677
  var BACKOFF_MAX_MS = 3e4;
@@ -892,7 +1019,7 @@ function runForeground(options) {
892
1019
  }
893
1020
 
894
1021
  // src/cli.ts
895
- var CLOUD_CONNECTOR_VERSION2 = true ? "2.7.0" : "unknown";
1022
+ var CLOUD_CONNECTOR_VERSION2 = true ? "2.7.2" : "unknown";
896
1023
  var args = process.argv.slice(2);
897
1024
  if (args.includes("--version") || args.includes("-v")) {
898
1025
  console.log(CLOUD_CONNECTOR_VERSION2);
@@ -930,14 +1057,16 @@ Options:
930
1057
  --help, -h Show this help message
931
1058
 
932
1059
  Examples:
933
- # Run in the foreground (Ctrl+C to stop) — also how native-host launches it
934
- mearl-cloud-connector "ws://localhost:8080/ws?token=xxx"
1060
+ # Start a self-managed background connector with its own log file (recommended)
1061
+ mearl-cloud-connector start "wss://cloud.example.com/ws?token=xxx"
935
1062
 
936
- # Complete a Qoder custom-tool pairing created by @mearl/setup
937
- mearl-cloud-connector "qoder://pair/pairing-code-1234?created=1786723200000"
1063
+ # Complete a Qoder custom-tool pairing, then keep the connector in the background
1064
+ mearl-cloud-connector start "qoder://pair/pairing-code-1234?created=1786723200000"
938
1065
 
939
- # Start/stop a self-managed background connector with its own log file
940
- mearl-cloud-connector start "wss://cloud.example.com/ws?token=xxx"
1066
+ # Run in the foreground for diagnostics or an external process manager
1067
+ mearl-cloud-connector "ws://localhost:8080/ws?token=xxx"
1068
+
1069
+ # Inspect or stop background connectors
941
1070
  mearl-cloud-connector status
942
1071
  mearl-cloud-connector logs "wss://cloud.example.com/ws?token=xxx"
943
1072
  mearl-cloud-connector stop "wss://cloud.example.com/ws?token=xxx"
package/dist/index.js CHANGED
@@ -91,6 +91,77 @@ function requireConnectorEndpoint(value) {
91
91
 
92
92
  // src/qoder.ts
93
93
  import { resolveActionTimeoutSec } from "@mearl/client/action-timeouts";
94
+
95
+ // src/qoder-auth.ts
96
+ import { existsSync, readFileSync } from "node:fs";
97
+ import { homedir, userInfo } from "node:os";
98
+ import { resolve } from "node:path";
99
+ import { spawnSync } from "node:child_process";
100
+ var QODER_TOKEN_KEY = "QODER_PERSONAL_ACCESS_TOKEN";
101
+ var QODER_KEYCHAIN_SERVICE = "com.mearl.qoder.pat";
102
+ function normalizeToken(value) {
103
+ const token = value?.trim();
104
+ if (!token || /[\r\n\0]/.test(token)) return void 0;
105
+ return token;
106
+ }
107
+ function envValue(text, key) {
108
+ for (const line of text.split(/\r?\n/)) {
109
+ const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$/.exec(line);
110
+ if (!match || match[1] !== key) continue;
111
+ let value = (match[2] ?? "").trim();
112
+ if (value.length >= 2 && (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'"))) {
113
+ value = value.slice(1, -1);
114
+ } else {
115
+ value = value.replace(/\s+#.*$/, "").trim();
116
+ }
117
+ return normalizeToken(value);
118
+ }
119
+ return void 0;
120
+ }
121
+ function readMacKeychainToken() {
122
+ const securityPath = "/usr/bin/security";
123
+ if (!existsSync(securityPath)) return void 0;
124
+ try {
125
+ const account = userInfo().username;
126
+ const result = spawnSync(
127
+ securityPath,
128
+ ["find-generic-password", "-a", account, "-s", QODER_KEYCHAIN_SERVICE, "-w"],
129
+ {
130
+ encoding: "utf8",
131
+ stdio: ["ignore", "pipe", "ignore"],
132
+ timeout: 5e3,
133
+ windowsHide: true
134
+ }
135
+ );
136
+ return result.status === 0 ? normalizeToken(result.stdout) : void 0;
137
+ } catch {
138
+ return void 0;
139
+ }
140
+ }
141
+ function resolveQoderPersonalAccessToken(options = {}) {
142
+ const direct = normalizeToken(options.token);
143
+ if (direct) return direct;
144
+ const env = options.env ?? process.env;
145
+ const inherited = normalizeToken(env[QODER_TOKEN_KEY]);
146
+ if (inherited) return inherited;
147
+ const homeDirectory = options.homeDirectory ?? homedir();
148
+ const envFiles = [
149
+ ...env.MEARL_ENV_FILE?.trim() ? [resolve(env.MEARL_ENV_FILE)] : [],
150
+ resolve(homeDirectory, ".mearl", ".env")
151
+ ];
152
+ const readFile = options.readFile ?? ((file) => readFileSync(file, "utf8"));
153
+ for (const file of new Set(envFiles)) {
154
+ try {
155
+ const token = envValue(readFile(file), QODER_TOKEN_KEY);
156
+ if (token) return token;
157
+ } catch {
158
+ }
159
+ }
160
+ if ((options.platform ?? process.platform) !== "darwin") return void 0;
161
+ return normalizeToken((options.readKeychainToken ?? readMacKeychainToken)());
162
+ }
163
+
164
+ // src/qoder.ts
94
165
  var QODER_TOOL_NAME = "mearl";
95
166
  var DEFAULT_QODER_API_BASE_URL = "https://api.qoder.com";
96
167
  var DEFAULT_DISCOVERY_WINDOW_MS = 60 * 60 * 1e3;
@@ -105,6 +176,17 @@ var QoderApiError = class extends Error {
105
176
  this.name = "QoderApiError";
106
177
  }
107
178
  };
179
+ var QoderPairingExpiredError = class extends Error {
180
+ constructor() {
181
+ super(
182
+ 'Qoder pairing is no longer pending. Generate a new pairing URL with `npx @mearl/setup --qoder-cloud --yes`, run the new connector command, and immediately invoke the mearl tool with action "pair". Do not reuse this URL.'
183
+ );
184
+ this.name = "QoderPairingExpiredError";
185
+ }
186
+ };
187
+ function isPendingActionNotFound(error) {
188
+ return error instanceof QoderApiError && /^Pending action\b.*\bwas not found\.?$/i.test(error.message.trim());
189
+ }
108
190
  function safeJson(value) {
109
191
  try {
110
192
  return JSON.stringify(value ?? null);
@@ -121,10 +203,49 @@ function asScreenshot(value) {
121
203
  if (format !== "png" && format !== "jpeg") return null;
122
204
  return { data: value.data, meta: { ...value.meta, format } };
123
205
  }
206
+ function extractBatchScreenshots(value) {
207
+ if (!isRecord(value) || !Array.isArray(value.results)) return null;
208
+ const screenshots = [];
209
+ const results = value.results.map((result) => {
210
+ if (!isRecord(result) || result.action !== "page_screenshot") return result;
211
+ const screenshot = asScreenshot(result.data);
212
+ if (!screenshot) return result;
213
+ const data = { ...result.data };
214
+ delete data.data;
215
+ data.meta = screenshot.meta;
216
+ data.imageContentIndex = screenshots.length + 1;
217
+ screenshots.push(screenshot);
218
+ return { ...result, data };
219
+ });
220
+ if (screenshots.length === 0) return null;
221
+ return { metadata: { ...value, results }, screenshots };
222
+ }
223
+ function imageContentBlock(screenshot) {
224
+ return {
225
+ type: "image",
226
+ source: {
227
+ type: "base64",
228
+ media_type: `image/${screenshot.meta.format}`,
229
+ data: screenshot.data
230
+ }
231
+ };
232
+ }
124
233
  function formatQoderToolResult(value) {
125
234
  const directScreenshot = asScreenshot(value);
126
235
  const nestedScreenshot = !directScreenshot && isRecord(value) ? asScreenshot(value.screenshot) : null;
127
236
  const screenshot = directScreenshot ?? nestedScreenshot;
237
+ if (!screenshot) {
238
+ const batch = extractBatchScreenshots(value);
239
+ if (batch) {
240
+ return {
241
+ content: [
242
+ { type: "text", text: safeJson(batch.metadata) },
243
+ ...batch.screenshots.map(imageContentBlock)
244
+ ],
245
+ fallbackContent: [{ type: "text", text: safeJson(value) }]
246
+ };
247
+ }
248
+ }
128
249
  if (!screenshot) {
129
250
  const content = [{ type: "text", text: safeJson(value) }];
130
251
  return { content, fallbackContent: content };
@@ -136,17 +257,7 @@ function formatQoderToolResult(value) {
136
257
  metadata = { ...value, screenshot: { meta: screenshot.meta } };
137
258
  }
138
259
  return {
139
- content: [
140
- { type: "text", text: safeJson(metadata) },
141
- {
142
- type: "image",
143
- source: {
144
- type: "base64",
145
- media_type: `image/${screenshot.meta.format}`,
146
- data: screenshot.data
147
- }
148
- }
149
- ],
260
+ content: [{ type: "text", text: safeJson(metadata) }, imageContentBlock(screenshot)],
150
261
  fallbackContent: [{ type: "text", text: safeJson(value) }]
151
262
  };
152
263
  }
@@ -301,7 +412,7 @@ async function parseQoderSse(body, onFrame) {
301
412
  await dispatch();
302
413
  }
303
414
  function defaultSleep(milliseconds, signal) {
304
- return new Promise((resolve, reject) => {
415
+ return new Promise((resolve2, reject) => {
305
416
  if (signal.aborted) {
306
417
  reject(signal.reason ?? new Error("Aborted"));
307
418
  return;
@@ -312,7 +423,7 @@ function defaultSleep(milliseconds, signal) {
312
423
  };
313
424
  const timer = setTimeout(() => {
314
425
  signal.removeEventListener("abort", onAbort);
315
- resolve();
426
+ resolve2();
316
427
  }, milliseconds);
317
428
  signal.addEventListener("abort", onAbort, { once: true });
318
429
  });
@@ -345,10 +456,10 @@ function toolInput(event) {
345
456
  var QoderConnector = class {
346
457
  constructor(options) {
347
458
  this.options = options;
348
- const token = options.token?.trim() || process.env.QODER_PERSONAL_ACCESS_TOKEN?.trim();
459
+ const token = resolveQoderPersonalAccessToken({ token: options.token });
349
460
  if (!token) {
350
461
  throw new Error(
351
- "Qoder authentication is required. Set QODER_PERSONAL_ACCESS_TOKEN and run the connector again."
462
+ "Qoder authentication is required. Set QODER_PERSONAL_ACCESS_TOKEN, add it to ~/.mearl/.env, or configure the macOS Keychain item com.mearl.qoder.pat, then retry."
352
463
  );
353
464
  }
354
465
  this.api = new QoderApiClient(
@@ -407,6 +518,15 @@ var QoderConnector = class {
407
518
  } catch (error) {
408
519
  if (signal.aborted) return;
409
520
  const message = error instanceof Error ? error.message : String(error);
521
+ if (!this.connected && error instanceof QoderPairingExpiredError) {
522
+ this.running = false;
523
+ if (this.options.onInitialConnectionFailed) {
524
+ this.options.onInitialConnectionFailed(message);
525
+ } else {
526
+ console.error(`[CloudConnector] Qoder connection error: ${message}`);
527
+ }
528
+ return;
529
+ }
410
530
  if (!this.connected && this.options.failFast) {
411
531
  this.options.onInitialConnectionFailed?.(message);
412
532
  this.running = false;
@@ -446,22 +566,29 @@ var QoderConnector = class {
446
566
  }
447
567
  async completePairing(pairing, signal) {
448
568
  if (!this.connected) {
449
- this.lastEventId = await this.api.sendCustomToolResult(
450
- pairing.sessionId,
451
- pairing.event.id,
452
- [
453
- {
454
- type: "text",
455
- text: safeJson({
456
- connected: true,
457
- connectorId: this.options.identity.connectorId,
458
- name: this.options.identity.name
459
- })
460
- }
461
- ],
462
- false,
463
- signal
464
- ) ?? pairing.event.id;
569
+ let resultEventId;
570
+ try {
571
+ resultEventId = await this.api.sendCustomToolResult(
572
+ pairing.sessionId,
573
+ pairing.event.id,
574
+ [
575
+ {
576
+ type: "text",
577
+ text: safeJson({
578
+ connected: true,
579
+ connectorId: this.options.identity.connectorId,
580
+ name: this.options.identity.name
581
+ })
582
+ }
583
+ ],
584
+ false,
585
+ signal
586
+ );
587
+ } catch (error) {
588
+ if (isPendingActionNotFound(error)) throw new QoderPairingExpiredError();
589
+ throw error;
590
+ }
591
+ this.lastEventId = resultEventId ?? pairing.event.id;
465
592
  this.sessionId = pairing.sessionId;
466
593
  this.connected = true;
467
594
  this.reconnectAttempts = 0;
@@ -533,7 +660,7 @@ var QoderConnector = class {
533
660
  };
534
661
 
535
662
  // src/index.ts
536
- var CLOUD_CONNECTOR_VERSION = true ? "2.7.0" : "unknown";
663
+ var CLOUD_CONNECTOR_VERSION = true ? "2.7.2" : "unknown";
537
664
  var DEFAULT_RECONNECT_INTERVAL = 5e3;
538
665
  var BACKOFF_BASE_MS = 1e3;
539
666
  var BACKOFF_MAX_MS = 3e4;
@@ -0,0 +1,11 @@
1
+ interface QoderTokenResolverOptions {
2
+ token?: string;
3
+ env?: NodeJS.ProcessEnv;
4
+ homeDirectory?: string;
5
+ platform?: NodeJS.Platform;
6
+ readFile?: (file: string) => string;
7
+ readKeychainToken?: () => string | undefined;
8
+ }
9
+ /** Resolve a PAT without putting it in a pairing URL, process argument, registry, or log. */
10
+ export declare function resolveQoderPersonalAccessToken(options?: QoderTokenResolverOptions): string | undefined;
11
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mearl/cloud-connector",
3
- "version": "2.7.0",
3
+ "version": "2.7.2",
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",
@@ -29,9 +29,9 @@
29
29
  },
30
30
  "dependencies": {
31
31
  "ws": "^8.18.0",
32
- "@mearl/cloud-types": "2.7.0",
33
- "@mearl/client": "2.7.0",
34
- "@mearl/daemon-core": "2.7.0"
32
+ "@mearl/daemon-core": "2.7.2",
33
+ "@mearl/client": "2.7.2",
34
+ "@mearl/cloud-types": "2.7.2"
35
35
  },
36
36
  "devDependencies": {
37
37
  "@types/node": "^24.9.1",