@mearl/cloud-connector 2.7.1 → 2.7.3

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/dist/cli.js CHANGED
@@ -1,59 +1,8 @@
1
1
  #!/usr/bin/env node
2
-
3
- // src/endpoint.ts
4
- var PAIRING_CODE_PATTERN = /^[A-Za-z0-9_-]{16,128}$/;
5
- function parseQoderEndpoint(serverUrl, parsed) {
6
- if (parsed.hostname !== "pair" || parsed.port || parsed.username || parsed.password || parsed.hash) {
7
- return null;
8
- }
9
- const pathSegments = parsed.pathname.split("/").filter(Boolean);
10
- if (pathSegments.length !== 1 || !PAIRING_CODE_PATTERN.test(pathSegments[0])) return null;
11
- const allowedParams = /* @__PURE__ */ new Set(["created"]);
12
- if ([...parsed.searchParams.keys()].some((key) => !allowedParams.has(key))) return null;
13
- const createdValues = parsed.searchParams.getAll("created");
14
- if (createdValues.length > 1) return null;
15
- const createdValue = createdValues[0] ?? null;
16
- if (createdValue !== null && !/^\d{13}$/.test(createdValue)) return null;
17
- const createdAt = createdValue === null ? void 0 : Number(createdValue);
18
- if (createdAt !== void 0 && (!Number.isSafeInteger(createdAt) || createdAt <= 0)) return null;
19
- return {
20
- serverUrl,
21
- scheme: "qoder",
22
- pairingCode: pathSegments[0],
23
- ...createdAt === void 0 ? {} : { createdAt }
24
- };
25
- }
26
- function parseConnectorEndpoint(value) {
27
- if (!value) return null;
28
- const serverUrl = value.trim();
29
- if (!serverUrl) return null;
30
- try {
31
- const parsed = new URL(serverUrl);
32
- if (parsed.protocol === "qoder:") return parseQoderEndpoint(serverUrl, parsed);
33
- if (parsed.protocol !== "ws:" && parsed.protocol !== "wss:" || !parsed.hostname || parsed.hash) {
34
- return null;
35
- }
36
- return {
37
- serverUrl,
38
- transportUrl: serverUrl,
39
- scheme: parsed.protocol === "wss:" ? "wss" : "ws"
40
- };
41
- } catch {
42
- return null;
43
- }
44
- }
45
- function isConnectorEndpoint(value) {
46
- return parseConnectorEndpoint(value) !== null;
47
- }
48
- function requireConnectorEndpoint(value) {
49
- const endpoint = parseConnectorEndpoint(value);
50
- if (!endpoint) {
51
- throw new Error(
52
- "serverUrl must use ws://, wss://, or qoder://pair/<code> without a URL fragment"
53
- );
54
- }
55
- return endpoint;
56
- }
2
+ import {
3
+ CloudConnector,
4
+ isConnectorEndpoint
5
+ } from "./chunks/chunk-RAKQ2NQJ.js";
57
6
 
58
7
  // src/daemon.ts
59
8
  import { fileURLToPath } from "node:url";
@@ -61,829 +10,9 @@ import {
61
10
  createDaemon,
62
11
  readLiveRecords,
63
12
  removeRecord,
64
- writeRecord as writeRecord2
13
+ writeRecord
65
14
  } from "@mearl/daemon-core";
66
15
 
67
- // src/index.ts
68
- import WebSocket from "ws";
69
- import {
70
- isHeartbeatMessage,
71
- MAX_BUFFER_SIZE,
72
- DEFAULT_HEARTBEAT_INTERVAL
73
- } from "@mearl/cloud-types";
74
- import { resolveActionTimeoutSec as resolveActionTimeoutSec2 } from "@mearl/client/action-timeouts";
75
-
76
- // src/identity.ts
77
- import { hostname } from "node:os";
78
- import { randomUUID } from "node:crypto";
79
- import { join } from "node:path";
80
- import { DAEMON_HOME, readRecord, writeRecord } from "@mearl/daemon-core";
81
- var IDENTITY_FILE = join(DAEMON_HOME, "cloud-connector-identity.json");
82
- function resolveConnectorIdentity(options) {
83
- const explicitId = options.connectorId?.trim() || process.env.MEARL_CONNECTOR_ID?.trim();
84
- const explicitName = options.connectorName?.trim() || process.env.MEARL_CONNECTOR_NAME?.trim();
85
- const stored = readRecord(IDENTITY_FILE);
86
- const connectorId = explicitId || stored?.connectorId || randomUUID();
87
- if (!explicitId && !stored?.connectorId) {
88
- try {
89
- writeRecord(IDENTITY_FILE, { pid: process.pid, connectorId });
90
- } catch {
91
- }
92
- }
93
- const name = explicitName || hostname() || `connector-${connectorId.slice(0, 8)}`;
94
- if (!/^[A-Za-z0-9._:-]{1,128}$/.test(connectorId)) {
95
- throw new Error('connectorId must contain only letters, numbers, ".", "_", ":", or "-"');
96
- }
97
- if (name.length > 128 || /\p{Cc}/u.test(name)) {
98
- throw new Error("connectorName must be 1-128 characters without control characters");
99
- }
100
- return { connectorId, name };
101
- }
102
-
103
- // src/qoder.ts
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
176
- var QODER_TOOL_NAME = "mearl";
177
- var DEFAULT_QODER_API_BASE_URL = "https://api.qoder.com";
178
- var DEFAULT_DISCOVERY_WINDOW_MS = 60 * 60 * 1e3;
179
- var DEFAULT_RECONNECT_INTERVAL_MS = 5e3;
180
- var MAX_RECENT_SESSIONS = 100;
181
- var MAX_RECENT_TOOL_EVENTS = 20;
182
- var MAX_CACHED_RESULTS = 100;
183
- var QoderApiError = class extends Error {
184
- constructor(message, status) {
185
- super(message);
186
- this.status = status;
187
- this.name = "QoderApiError";
188
- }
189
- };
190
- function safeJson(value) {
191
- try {
192
- return JSON.stringify(value ?? null);
193
- } catch {
194
- return JSON.stringify({ error: "Mearl returned a value that cannot be serialized" });
195
- }
196
- }
197
- function isRecord(value) {
198
- return typeof value === "object" && value !== null && !Array.isArray(value);
199
- }
200
- function asScreenshot(value) {
201
- if (!isRecord(value) || typeof value.data !== "string" || !isRecord(value.meta)) return null;
202
- const format = value.meta.format;
203
- if (format !== "png" && format !== "jpeg") return null;
204
- return { data: value.data, meta: { ...value.meta, format } };
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
- }
233
- function formatQoderToolResult(value) {
234
- const directScreenshot = asScreenshot(value);
235
- const nestedScreenshot = !directScreenshot && isRecord(value) ? asScreenshot(value.screenshot) : null;
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
- }
249
- if (!screenshot) {
250
- const content = [{ type: "text", text: safeJson(value) }];
251
- return { content, fallbackContent: content };
252
- }
253
- let metadata;
254
- if (directScreenshot) {
255
- metadata = { meta: screenshot.meta };
256
- } else {
257
- metadata = { ...value, screenshot: { meta: screenshot.meta } };
258
- }
259
- return {
260
- content: [{ type: "text", text: safeJson(metadata) }, imageContentBlock(screenshot)],
261
- fallbackContent: [{ type: "text", text: safeJson(value) }]
262
- };
263
- }
264
- function pairingCodeFromEvent(event) {
265
- if (event.type !== "agent.custom_tool_use" || event.name !== QODER_TOOL_NAME) return null;
266
- if (!isRecord(event.input) || event.input.action !== "pair") return null;
267
- const payload = isRecord(event.input.payload) ? event.input.payload : isRecord(event.input.data) ? event.input.data : null;
268
- return payload && typeof payload.code === "string" ? payload.code : null;
269
- }
270
- function qoderErrorMessage(status, body) {
271
- try {
272
- const parsed = JSON.parse(body);
273
- const message = parsed.error?.message ?? parsed.message;
274
- if (typeof message === "string" && message.trim()) return message.trim();
275
- } catch {
276
- }
277
- return `Qoder API request failed with HTTP ${status}`;
278
- }
279
- var QoderApiClient = class {
280
- constructor(token, baseUrl = DEFAULT_QODER_API_BASE_URL, fetchImpl = fetch) {
281
- this.token = token;
282
- this.fetchImpl = fetchImpl;
283
- const parsed = new URL(baseUrl);
284
- if (parsed.protocol !== "https:" && parsed.hostname !== "localhost" && parsed.hostname !== "127.0.0.1") {
285
- throw new Error("Qoder API base URL must use https:// (localhost may use http:// for tests)");
286
- }
287
- this.baseUrl = parsed.toString().replace(/\/$/, "");
288
- }
289
- baseUrl;
290
- async request(path, init = {}) {
291
- const response = await this.fetchImpl(`${this.baseUrl}${path}`, {
292
- ...init,
293
- headers: {
294
- Authorization: `Bearer ${this.token}`,
295
- ...init.headers
296
- }
297
- });
298
- if (!response.ok) {
299
- const body = await response.text();
300
- throw new QoderApiError(qoderErrorMessage(response.status, body), response.status);
301
- }
302
- return response;
303
- }
304
- async listSessions(createdAfter, signal) {
305
- const query = new URLSearchParams({
306
- limit: String(MAX_RECENT_SESSIONS),
307
- order: "desc",
308
- "created_at[gte]": createdAfter
309
- });
310
- const response = await this.request(`/api/v1/cloud/sessions?${query}`, { signal });
311
- const body = await response.json();
312
- return Array.isArray(body.data) ? body.data.filter((session) => typeof session.id === "string") : [];
313
- }
314
- async listCustomToolEvents(sessionId, createdAfter, signal) {
315
- const query = new URLSearchParams({
316
- limit: String(MAX_RECENT_TOOL_EVENTS),
317
- order: "desc",
318
- types: "agent.custom_tool_use",
319
- "created_at[gte]": createdAfter
320
- });
321
- const response = await this.request(
322
- `/api/v1/cloud/sessions/${encodeURIComponent(sessionId)}/events?${query}`,
323
- { signal }
324
- );
325
- const body = await response.json();
326
- return Array.isArray(body.data) ? body.data : [];
327
- }
328
- async findPairingRequest(pairingCode, createdAfter, signal) {
329
- const sessions = await this.listSessions(createdAfter, signal);
330
- for (const session of sessions) {
331
- const events = await this.listCustomToolEvents(session.id, createdAfter, signal);
332
- const event = events.find((candidate) => pairingCodeFromEvent(candidate) === pairingCode);
333
- if (event?.id) return { sessionId: session.id, event: { ...event, id: event.id } };
334
- }
335
- return null;
336
- }
337
- async sendCustomToolResult(sessionId, customToolUseId, content, isError = false, signal) {
338
- const response = await this.request(
339
- `/api/v1/cloud/sessions/${encodeURIComponent(sessionId)}/events`,
340
- {
341
- method: "POST",
342
- headers: { "Content-Type": "application/json" },
343
- signal,
344
- body: JSON.stringify({
345
- events: [
346
- {
347
- type: "user.custom_tool_result",
348
- custom_tool_use_id: customToolUseId,
349
- content,
350
- is_error: isError
351
- }
352
- ]
353
- })
354
- }
355
- );
356
- const body = await response.json();
357
- return body.data?.[0]?.id;
358
- }
359
- async streamEvents(sessionId, lastEventId, signal, onFrame, onOpen) {
360
- const response = await this.request(
361
- `/api/v1/cloud/sessions/${encodeURIComponent(sessionId)}/events/stream`,
362
- {
363
- headers: {
364
- Accept: "text/event-stream",
365
- ...lastEventId ? { "Last-Event-ID": lastEventId } : {}
366
- },
367
- signal
368
- }
369
- );
370
- if (!response.body) throw new Error("Qoder event stream returned no response body");
371
- onOpen?.();
372
- await parseQoderSse(response.body, onFrame);
373
- }
374
- };
375
- async function parseQoderSse(body, onFrame) {
376
- const reader = body.getReader();
377
- const decoder = new TextDecoder();
378
- let buffer = "";
379
- let frameLines = [];
380
- const dispatch = async () => {
381
- if (frameLines.length === 0) return;
382
- let id;
383
- let event;
384
- const data = [];
385
- for (const line of frameLines) {
386
- if (!line || line.startsWith(":")) continue;
387
- const separator = line.indexOf(":");
388
- const field = separator === -1 ? line : line.slice(0, separator);
389
- const value = separator === -1 ? "" : line.slice(separator + 1).replace(/^ /, "");
390
- if (field === "id") id = value;
391
- else if (field === "event") event = value;
392
- else if (field === "data") data.push(value);
393
- }
394
- frameLines = [];
395
- if (data.length === 0) return;
396
- const parsed = JSON.parse(data.join("\n"));
397
- await onFrame({ ...id ? { id } : {}, ...event ? { event } : {}, data: parsed });
398
- };
399
- while (true) {
400
- const { done, value } = await reader.read();
401
- buffer += decoder.decode(value, { stream: !done });
402
- let newlineIndex;
403
- while ((newlineIndex = buffer.indexOf("\n")) !== -1) {
404
- const line = buffer.slice(0, newlineIndex).replace(/\r$/, "");
405
- buffer = buffer.slice(newlineIndex + 1);
406
- if (line === "") await dispatch();
407
- else frameLines.push(line);
408
- }
409
- if (done) break;
410
- }
411
- if (buffer) frameLines.push(buffer.replace(/\r$/, ""));
412
- await dispatch();
413
- }
414
- function defaultSleep(milliseconds, signal) {
415
- return new Promise((resolve2, reject) => {
416
- if (signal.aborted) {
417
- reject(signal.reason ?? new Error("Aborted"));
418
- return;
419
- }
420
- const onAbort = () => {
421
- clearTimeout(timer);
422
- reject(signal.reason ?? new Error("Aborted"));
423
- };
424
- const timer = setTimeout(() => {
425
- signal.removeEventListener("abort", onAbort);
426
- resolve2();
427
- }, milliseconds);
428
- signal.addEventListener("abort", onAbort, { once: true });
429
- });
430
- }
431
- async function defaultInvokeAction(action, payload, options) {
432
- const client = await import("@mearl/client/local");
433
- return client.invoke(action, payload, {
434
- browser: options.browser,
435
- timeoutSec: options.timeoutSec,
436
- controlSource: "remote"
437
- });
438
- }
439
- function toolInput(event) {
440
- if (!isRecord(event.input) || typeof event.input.action !== "string") {
441
- throw new Error("Qoder mearl tool input requires a string action");
442
- }
443
- const browser = typeof event.input.browser === "string" ? event.input.browser : void 0;
444
- const timeoutSec = typeof event.input.timeoutSec === "number" && Number.isFinite(event.input.timeoutSec) ? event.input.timeoutSec : void 0;
445
- const payloadValue = event.input.payload ?? event.input.data ?? {};
446
- if (!isRecord(payloadValue)) {
447
- throw new Error("Qoder mearl tool input payload must be an object");
448
- }
449
- return {
450
- action: event.input.action,
451
- payload: payloadValue,
452
- ...browser ? { browser } : {},
453
- ...timeoutSec === void 0 ? {} : { timeoutSec }
454
- };
455
- }
456
- var QoderConnector = class {
457
- constructor(options) {
458
- this.options = options;
459
- const token = resolveQoderPersonalAccessToken({ token: options.token });
460
- if (!token) {
461
- throw new Error(
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."
463
- );
464
- }
465
- this.api = new QoderApiClient(
466
- token,
467
- options.apiBaseUrl ?? DEFAULT_QODER_API_BASE_URL,
468
- options.fetchImpl
469
- );
470
- this.now = options.now ?? Date.now;
471
- this.sleep = options.sleep ?? defaultSleep;
472
- this.invokeAction = options.invokeAction ?? defaultInvokeAction;
473
- this.reconnectInterval = options.reconnectInterval ?? DEFAULT_RECONNECT_INTERVAL_MS;
474
- this.maxReconnectAttempts = options.maxReconnectAttempts ?? -1;
475
- }
476
- api;
477
- now;
478
- sleep;
479
- invokeAction;
480
- reconnectInterval;
481
- maxReconnectAttempts;
482
- abortController = null;
483
- reconnectAttempts = 0;
484
- running = false;
485
- connected = false;
486
- sessionId = null;
487
- lastEventId;
488
- cachedResults = /* @__PURE__ */ new Map();
489
- connect() {
490
- if (this.running) return;
491
- this.running = true;
492
- this.abortController = new AbortController();
493
- void this.run(this.abortController.signal);
494
- }
495
- disconnect() {
496
- this.running = false;
497
- this.abortController?.abort();
498
- this.abortController = null;
499
- }
500
- async run(signal) {
501
- while (!signal.aborted) {
502
- try {
503
- if (!this.sessionId) {
504
- const pairing = await this.findPairing(signal);
505
- await this.completePairing(pairing, signal);
506
- }
507
- const sessionId = this.sessionId;
508
- await this.api.streamEvents(
509
- sessionId,
510
- this.lastEventId,
511
- signal,
512
- async (frame) => this.handleFrame(sessionId, frame, signal),
513
- () => {
514
- this.reconnectAttempts = 0;
515
- }
516
- );
517
- if (!signal.aborted) throw new Error("Qoder event stream ended");
518
- } catch (error) {
519
- if (signal.aborted) return;
520
- const message = error instanceof Error ? error.message : String(error);
521
- if (!this.connected && this.options.failFast) {
522
- this.options.onInitialConnectionFailed?.(message);
523
- this.running = false;
524
- return;
525
- }
526
- this.reconnectAttempts += 1;
527
- if (this.maxReconnectAttempts !== -1 && this.reconnectAttempts > this.maxReconnectAttempts) {
528
- console.error(
529
- `[CloudConnector] Qoder max reconnect attempts (${this.maxReconnectAttempts}) reached`
530
- );
531
- this.running = false;
532
- return;
533
- }
534
- console.error(`[CloudConnector] Qoder connection error: ${message}`);
535
- try {
536
- await this.sleep(this.reconnectInterval, signal);
537
- } catch {
538
- return;
539
- }
540
- }
541
- }
542
- }
543
- async findPairing(signal) {
544
- const createdAt = this.options.endpoint.createdAt ?? this.now();
545
- const createdAfter = new Date(createdAt - DEFAULT_DISCOVERY_WINDOW_MS).toISOString();
546
- const pairing = await this.api.findPairingRequest(
547
- this.options.endpoint.pairingCode,
548
- createdAfter,
549
- signal
550
- );
551
- if (!pairing) {
552
- throw new Error(
553
- 'Qoder pairing request was not found. Ask the Agent to call the mearl tool with action "pair" and the code from this URL.'
554
- );
555
- }
556
- return pairing;
557
- }
558
- async completePairing(pairing, signal) {
559
- if (!this.connected) {
560
- this.lastEventId = await this.api.sendCustomToolResult(
561
- pairing.sessionId,
562
- pairing.event.id,
563
- [
564
- {
565
- type: "text",
566
- text: safeJson({
567
- connected: true,
568
- connectorId: this.options.identity.connectorId,
569
- name: this.options.identity.name
570
- })
571
- }
572
- ],
573
- false,
574
- signal
575
- ) ?? pairing.event.id;
576
- this.sessionId = pairing.sessionId;
577
- this.connected = true;
578
- this.reconnectAttempts = 0;
579
- this.options.onConnected?.();
580
- console.log(`[CloudConnector] Connected to Qoder session ${pairing.sessionId}`);
581
- }
582
- }
583
- async handleFrame(sessionId, frame, signal) {
584
- this.reconnectAttempts = 0;
585
- const event = frame.data;
586
- const eventId = event.id ?? frame.id;
587
- if (event.type !== "agent.custom_tool_use" || event.name !== QODER_TOOL_NAME || !eventId) {
588
- if (eventId) this.lastEventId = eventId;
589
- return;
590
- }
591
- const cached = this.cachedResults.get(eventId) ?? await this.executeTool(event);
592
- this.rememberResult(eventId, cached);
593
- try {
594
- this.lastEventId = await this.api.sendCustomToolResult(
595
- sessionId,
596
- eventId,
597
- cached.content,
598
- cached.isError,
599
- signal
600
- ) ?? eventId;
601
- } catch (error) {
602
- if (error instanceof QoderApiError && error.status === 400 && cached.content !== cached.fallbackContent) {
603
- this.lastEventId = await this.api.sendCustomToolResult(
604
- sessionId,
605
- eventId,
606
- cached.fallbackContent,
607
- cached.isError,
608
- signal
609
- ) ?? eventId;
610
- return;
611
- }
612
- if (error instanceof QoderApiError && error.status === 404) {
613
- this.lastEventId = eventId;
614
- return;
615
- }
616
- throw error;
617
- }
618
- }
619
- async executeTool(event) {
620
- try {
621
- const input = toolInput(event);
622
- if (input.action === "pair") {
623
- throw new Error("This pairing request does not match the active connector");
624
- }
625
- const result = await this.invokeAction(input.action, input.payload, {
626
- browser: input.browser,
627
- timeoutSec: input.timeoutSec ?? resolveActionTimeoutSec(input.action, input.payload, 15)
628
- });
629
- return { ...formatQoderToolResult(result), isError: false };
630
- } catch (error) {
631
- const message = error instanceof Error ? error.message : String(error);
632
- const content = [{ type: "text", text: safeJson({ error: message }) }];
633
- return { content, fallbackContent: content, isError: true };
634
- }
635
- }
636
- rememberResult(eventId, result) {
637
- this.cachedResults.set(eventId, result);
638
- while (this.cachedResults.size > MAX_CACHED_RESULTS) {
639
- const oldest = this.cachedResults.keys().next().value;
640
- if (!oldest) break;
641
- this.cachedResults.delete(oldest);
642
- }
643
- }
644
- };
645
-
646
- // src/index.ts
647
- var CLOUD_CONNECTOR_VERSION = true ? "2.7.1" : "unknown";
648
- var DEFAULT_RECONNECT_INTERVAL = 5e3;
649
- var BACKOFF_BASE_MS = 1e3;
650
- var BACKOFF_MAX_MS = 3e4;
651
- var SLOW_PROBE_INTERVAL_MS = 6e4;
652
- var FAST_RECONNECT_ATTEMPTS = 5;
653
- var CloudConnector = class {
654
- options;
655
- endpoint;
656
- identity;
657
- qoderConnector = null;
658
- ws = null;
659
- heartbeatTimer = null;
660
- reconnectTimer = null;
661
- reconnectAttempts = 0;
662
- messageBuffer = "";
663
- isManualClose = false;
664
- shouldTryWss = false;
665
- wssRetryAttempts = 0;
666
- maxWssRetryAttempts = 1;
667
- hasConnected = false;
668
- lastConnectionError = null;
669
- constructor(options) {
670
- this.endpoint = requireConnectorEndpoint(options.serverUrl);
671
- this.options = {
672
- serverUrl: this.endpoint.serverUrl,
673
- heartbeatInterval: options.heartbeatInterval ?? DEFAULT_HEARTBEAT_INTERVAL,
674
- reconnectInterval: options.reconnectInterval ?? DEFAULT_RECONNECT_INTERVAL,
675
- maxReconnectAttempts: options.maxReconnectAttempts ?? -1,
676
- failFast: options.failFast ?? false,
677
- onInitialConnectionFailed: options.onInitialConnectionFailed,
678
- onConnected: options.onConnected
679
- };
680
- this.identity = resolveConnectorIdentity(options);
681
- }
682
- connect() {
683
- if (this.endpoint.scheme === "qoder") {
684
- if (this.qoderConnector) {
685
- this.qoderConnector.connect();
686
- return;
687
- }
688
- try {
689
- this.qoderConnector = new QoderConnector({
690
- endpoint: this.endpoint,
691
- identity: this.identity,
692
- reconnectInterval: this.options.reconnectInterval,
693
- maxReconnectAttempts: this.options.maxReconnectAttempts,
694
- failFast: this.options.failFast,
695
- onConnected: () => {
696
- this.hasConnected = true;
697
- this.options.onConnected?.(this.options.serverUrl, this.identity);
698
- },
699
- onInitialConnectionFailed: this.options.onInitialConnectionFailed
700
- });
701
- this.qoderConnector.connect();
702
- } catch (error) {
703
- const message = error instanceof Error ? error.message : String(error);
704
- if (this.options.onInitialConnectionFailed) {
705
- this.options.onInitialConnectionFailed(message);
706
- } else {
707
- console.error(`[CloudConnector] Qoder connection error: ${message}`);
708
- }
709
- }
710
- return;
711
- }
712
- if (this.ws && (this.ws.readyState === 0 || this.ws.readyState === 1)) {
713
- return;
714
- }
715
- let serverUrl = this.endpoint.transportUrl;
716
- if (this.shouldTryWss && serverUrl.startsWith("ws://")) {
717
- serverUrl = serverUrl.replace("ws://", "wss://");
718
- console.log(`[CloudConnector] Retrying with wss://: ${serverUrl}`);
719
- }
720
- this.ws = new WebSocket(serverUrl);
721
- this.ws.on("open", () => {
722
- this.hasConnected = true;
723
- this.lastConnectionError = null;
724
- this.reconnectAttempts = 0;
725
- this.shouldTryWss = false;
726
- this.wssRetryAttempts = 0;
727
- this.sendConnectorHello();
728
- this.startHeartbeat();
729
- this.options.onConnected?.(this.options.serverUrl, this.identity);
730
- console.log(`[CloudConnector] Connected to ${serverUrl}`);
731
- });
732
- this.ws.on("message", (data) => {
733
- this.handleMessage(data);
734
- });
735
- this.ws.on("close", (code, reason) => {
736
- console.log(`[CloudConnector] Disconnected (${code}: ${reason.toString()})`);
737
- this.stopHeartbeat();
738
- this.messageBuffer = "";
739
- if (this.shouldTryWss && serverUrl.startsWith("ws://")) {
740
- return;
741
- }
742
- if (this.options.failFast && !this.hasConnected) {
743
- const reasonText = reason.toString();
744
- const message = this.lastConnectionError || reasonText || `Connection closed (${code})`;
745
- this.options.onInitialConnectionFailed?.(message);
746
- return;
747
- }
748
- this.tryReconnect();
749
- });
750
- this.ws.on("error", (error) => {
751
- console.error(`[CloudConnector] WebSocket error:`, error.message);
752
- this.lastConnectionError = error.message;
753
- if (error.message.includes("301") && !this.shouldTryWss && serverUrl.startsWith("ws://") && this.wssRetryAttempts < this.maxWssRetryAttempts) {
754
- this.shouldTryWss = true;
755
- this.wssRetryAttempts++;
756
- this.ws = null;
757
- console.log(
758
- `[CloudConnector] Server requires wss://, retrying (${this.wssRetryAttempts}/${this.maxWssRetryAttempts})...`
759
- );
760
- setTimeout(() => this.connect(), 1e3);
761
- }
762
- });
763
- }
764
- disconnect() {
765
- this.isManualClose = true;
766
- this.qoderConnector?.disconnect();
767
- this.qoderConnector = null;
768
- this.stopHeartbeat();
769
- if (this.reconnectTimer) {
770
- clearTimeout(this.reconnectTimer);
771
- this.reconnectTimer = null;
772
- }
773
- if (this.ws) {
774
- this.ws.close();
775
- this.ws = null;
776
- }
777
- }
778
- handleMessage(data) {
779
- this.messageBuffer += data.toString("utf-8");
780
- if (this.messageBuffer.length > MAX_BUFFER_SIZE) {
781
- console.error("[CloudConnector] Message buffer exceeds limit, closing connection");
782
- this.disconnect();
783
- return;
784
- }
785
- let newlineIndex;
786
- while ((newlineIndex = this.messageBuffer.indexOf("\n")) !== -1) {
787
- const line = this.messageBuffer.slice(0, newlineIndex);
788
- this.messageBuffer = this.messageBuffer.slice(newlineIndex + 1);
789
- if (!line.trim()) continue;
790
- try {
791
- const message = JSON.parse(line);
792
- this.handleCloudMessage(message);
793
- } catch (error) {
794
- console.error(`[CloudConnector] Failed to parse message:`, line, error);
795
- }
796
- }
797
- }
798
- async handleCloudMessage(message) {
799
- if (isHeartbeatMessage(message)) {
800
- if (message.type === "ping") {
801
- this.sendHeartbeatResponse(message.timestamp);
802
- }
803
- return;
804
- }
805
- const request = message;
806
- const { id, action, data, browser, timeoutSec } = request;
807
- try {
808
- const client = await import("@mearl/client/local");
809
- const result = await client.invoke(action, data, {
810
- browser,
811
- timeoutSec: timeoutSec ?? resolveActionTimeoutSec2(action, data, 15),
812
- controlSource: "remote"
813
- });
814
- this.sendResponse({ id, success: true, data: result });
815
- } catch (error) {
816
- const errorMessage = error instanceof Error ? error.message : String(error);
817
- this.sendResponse({ id, success: false, error: errorMessage });
818
- }
819
- }
820
- sendResponse(response) {
821
- if (this.ws && this.ws.readyState === 1) {
822
- this.ws.send(JSON.stringify(response) + "\n");
823
- }
824
- }
825
- sendConnectorHello() {
826
- if (this.ws && this.ws.readyState === WebSocket.OPEN) {
827
- const message = {
828
- type: "connector_hello",
829
- connectorId: this.identity.connectorId,
830
- name: this.identity.name,
831
- ...CLOUD_CONNECTOR_VERSION === "unknown" ? {} : { version: CLOUD_CONNECTOR_VERSION }
832
- };
833
- this.ws.send(JSON.stringify(message) + "\n");
834
- }
835
- }
836
- sendHeartbeatResponse(_timestamp) {
837
- if (this.ws && this.ws.readyState === 1) {
838
- this.ws.send(
839
- JSON.stringify({ type: "pong", timestamp: Date.now() }) + "\n"
840
- );
841
- }
842
- }
843
- startHeartbeat() {
844
- this.stopHeartbeat();
845
- this.heartbeatTimer = setInterval(() => {
846
- if (this.ws && this.ws.readyState === WebSocket.OPEN) {
847
- this.ws.send(
848
- JSON.stringify({ type: "ping", timestamp: Date.now() }) + "\n"
849
- );
850
- }
851
- }, this.options.heartbeatInterval * 1e3);
852
- }
853
- stopHeartbeat() {
854
- if (this.heartbeatTimer) {
855
- clearInterval(this.heartbeatTimer);
856
- this.heartbeatTimer = null;
857
- }
858
- }
859
- tryReconnect() {
860
- if (this.isManualClose) return;
861
- if (this.reconnectTimer) return;
862
- this.reconnectAttempts++;
863
- if (this.options.maxReconnectAttempts !== -1 && this.reconnectAttempts > this.options.maxReconnectAttempts) {
864
- console.log(
865
- `[CloudConnector] Max reconnect attempts (${this.options.maxReconnectAttempts}) reached`
866
- );
867
- return;
868
- }
869
- const isSlowProbe = this.reconnectAttempts > FAST_RECONNECT_ATTEMPTS;
870
- const delay = isSlowProbe ? SLOW_PROBE_INTERVAL_MS : Math.min(BACKOFF_BASE_MS * Math.pow(2, this.reconnectAttempts - 1), BACKOFF_MAX_MS);
871
- if (isSlowProbe) {
872
- console.log(
873
- `[CloudConnector] Slow probe reconnect in ${delay / 1e3}s (attempt ${this.reconnectAttempts})`
874
- );
875
- } else {
876
- console.log(
877
- `[CloudConnector] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts}/${FAST_RECONNECT_ATTEMPTS})`
878
- );
879
- }
880
- this.reconnectTimer = setTimeout(() => {
881
- this.reconnectTimer = null;
882
- this.connect();
883
- }, delay);
884
- }
885
- };
886
-
887
16
  // src/paths.ts
888
17
  import { keyedConfigFile, keyedDir, keyedLogFile } from "@mearl/daemon-core";
889
18
  var CONNECTORS_SUBDIR = "connectors";
@@ -957,7 +86,7 @@ function runForeground(options) {
957
86
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
958
87
  const writeOwnRecord = (_serverUrl, identity) => {
959
88
  try {
960
- writeRecord2(configFile, {
89
+ writeRecord(configFile, {
961
90
  serverUrl,
962
91
  pid: process.pid,
963
92
  startedAt,
@@ -992,15 +121,15 @@ function runForeground(options) {
992
121
  }
993
122
 
994
123
  // src/cli.ts
995
- var CLOUD_CONNECTOR_VERSION2 = true ? "2.7.1" : "unknown";
124
+ var CLOUD_CONNECTOR_VERSION = true ? "2.7.3" : "unknown";
996
125
  var args = process.argv.slice(2);
997
126
  if (args.includes("--version") || args.includes("-v")) {
998
- console.log(CLOUD_CONNECTOR_VERSION2);
127
+ console.log(CLOUD_CONNECTOR_VERSION);
999
128
  process.exit(0);
1000
129
  }
1001
130
  var SUBCOMMANDS = ["start", "stop", "restart", "status", "list", "logs"];
1002
131
  function showHelp() {
1003
- console.error(`mearl-cloud-connector v${CLOUD_CONNECTOR_VERSION2}
132
+ console.error(`mearl-cloud-connector v${CLOUD_CONNECTOR_VERSION}
1004
133
 
1005
134
  Usage:
1006
135
  mearl-cloud-connector <server-url> [options] # run in the foreground
@@ -1030,14 +159,16 @@ Options:
1030
159
  --help, -h Show this help message
1031
160
 
1032
161
  Examples:
1033
- # Run in the foreground (Ctrl+C to stop) — also how native-host launches it
1034
- mearl-cloud-connector "ws://localhost:8080/ws?token=xxx"
162
+ # Start a self-managed background connector with its own log file (recommended)
163
+ mearl-cloud-connector start "wss://cloud.example.com/ws?token=xxx"
1035
164
 
1036
- # Complete a Qoder custom-tool pairing created by @mearl/setup
1037
- mearl-cloud-connector "qoder://pair/pairing-code-1234?created=1786723200000"
165
+ # Complete a Qoder custom-tool pairing, then keep the connector in the background
166
+ mearl-cloud-connector start "qoder://pair/pairing-code-1234?created=1786723200000"
1038
167
 
1039
- # Start/stop a self-managed background connector with its own log file
1040
- mearl-cloud-connector start "wss://cloud.example.com/ws?token=xxx"
168
+ # Run in the foreground for diagnostics or an external process manager
169
+ mearl-cloud-connector "ws://localhost:8080/ws?token=xxx"
170
+
171
+ # Inspect or stop background connectors
1041
172
  mearl-cloud-connector status
1042
173
  mearl-cloud-connector logs "wss://cloud.example.com/ws?token=xxx"
1043
174
  mearl-cloud-connector stop "wss://cloud.example.com/ws?token=xxx"