@mearl/cloud-connector 2.7.2 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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-TJVSQ2IS.js";
57
6
 
58
7
  // src/daemon.ts
59
8
  import { fileURLToPath } from "node:url";
@@ -61,856 +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
- 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
- }
201
- function safeJson(value) {
202
- try {
203
- return JSON.stringify(value ?? null);
204
- } catch {
205
- return JSON.stringify({ error: "Mearl returned a value that cannot be serialized" });
206
- }
207
- }
208
- function isRecord(value) {
209
- return typeof value === "object" && value !== null && !Array.isArray(value);
210
- }
211
- function asScreenshot(value) {
212
- if (!isRecord(value) || typeof value.data !== "string" || !isRecord(value.meta)) return null;
213
- const format = value.meta.format;
214
- if (format !== "png" && format !== "jpeg") return null;
215
- return { data: value.data, meta: { ...value.meta, format } };
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
- }
244
- function formatQoderToolResult(value) {
245
- const directScreenshot = asScreenshot(value);
246
- const nestedScreenshot = !directScreenshot && isRecord(value) ? asScreenshot(value.screenshot) : null;
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
- }
260
- if (!screenshot) {
261
- const content = [{ type: "text", text: safeJson(value) }];
262
- return { content, fallbackContent: content };
263
- }
264
- let metadata;
265
- if (directScreenshot) {
266
- metadata = { meta: screenshot.meta };
267
- } else {
268
- metadata = { ...value, screenshot: { meta: screenshot.meta } };
269
- }
270
- return {
271
- content: [{ type: "text", text: safeJson(metadata) }, imageContentBlock(screenshot)],
272
- fallbackContent: [{ type: "text", text: safeJson(value) }]
273
- };
274
- }
275
- function pairingCodeFromEvent(event) {
276
- if (event.type !== "agent.custom_tool_use" || event.name !== QODER_TOOL_NAME) return null;
277
- if (!isRecord(event.input) || event.input.action !== "pair") return null;
278
- const payload = isRecord(event.input.payload) ? event.input.payload : isRecord(event.input.data) ? event.input.data : null;
279
- return payload && typeof payload.code === "string" ? payload.code : null;
280
- }
281
- function qoderErrorMessage(status, body) {
282
- try {
283
- const parsed = JSON.parse(body);
284
- const message = parsed.error?.message ?? parsed.message;
285
- if (typeof message === "string" && message.trim()) return message.trim();
286
- } catch {
287
- }
288
- return `Qoder API request failed with HTTP ${status}`;
289
- }
290
- var QoderApiClient = class {
291
- constructor(token, baseUrl = DEFAULT_QODER_API_BASE_URL, fetchImpl = fetch) {
292
- this.token = token;
293
- this.fetchImpl = fetchImpl;
294
- const parsed = new URL(baseUrl);
295
- if (parsed.protocol !== "https:" && parsed.hostname !== "localhost" && parsed.hostname !== "127.0.0.1") {
296
- throw new Error("Qoder API base URL must use https:// (localhost may use http:// for tests)");
297
- }
298
- this.baseUrl = parsed.toString().replace(/\/$/, "");
299
- }
300
- baseUrl;
301
- async request(path, init = {}) {
302
- const response = await this.fetchImpl(`${this.baseUrl}${path}`, {
303
- ...init,
304
- headers: {
305
- Authorization: `Bearer ${this.token}`,
306
- ...init.headers
307
- }
308
- });
309
- if (!response.ok) {
310
- const body = await response.text();
311
- throw new QoderApiError(qoderErrorMessage(response.status, body), response.status);
312
- }
313
- return response;
314
- }
315
- async listSessions(createdAfter, signal) {
316
- const query = new URLSearchParams({
317
- limit: String(MAX_RECENT_SESSIONS),
318
- order: "desc",
319
- "created_at[gte]": createdAfter
320
- });
321
- const response = await this.request(`/api/v1/cloud/sessions?${query}`, { signal });
322
- const body = await response.json();
323
- return Array.isArray(body.data) ? body.data.filter((session) => typeof session.id === "string") : [];
324
- }
325
- async listCustomToolEvents(sessionId, createdAfter, signal) {
326
- const query = new URLSearchParams({
327
- limit: String(MAX_RECENT_TOOL_EVENTS),
328
- order: "desc",
329
- types: "agent.custom_tool_use",
330
- "created_at[gte]": createdAfter
331
- });
332
- const response = await this.request(
333
- `/api/v1/cloud/sessions/${encodeURIComponent(sessionId)}/events?${query}`,
334
- { signal }
335
- );
336
- const body = await response.json();
337
- return Array.isArray(body.data) ? body.data : [];
338
- }
339
- async findPairingRequest(pairingCode, createdAfter, signal) {
340
- const sessions = await this.listSessions(createdAfter, signal);
341
- for (const session of sessions) {
342
- const events = await this.listCustomToolEvents(session.id, createdAfter, signal);
343
- const event = events.find((candidate) => pairingCodeFromEvent(candidate) === pairingCode);
344
- if (event?.id) return { sessionId: session.id, event: { ...event, id: event.id } };
345
- }
346
- return null;
347
- }
348
- async sendCustomToolResult(sessionId, customToolUseId, content, isError = false, signal) {
349
- const response = await this.request(
350
- `/api/v1/cloud/sessions/${encodeURIComponent(sessionId)}/events`,
351
- {
352
- method: "POST",
353
- headers: { "Content-Type": "application/json" },
354
- signal,
355
- body: JSON.stringify({
356
- events: [
357
- {
358
- type: "user.custom_tool_result",
359
- custom_tool_use_id: customToolUseId,
360
- content,
361
- is_error: isError
362
- }
363
- ]
364
- })
365
- }
366
- );
367
- const body = await response.json();
368
- return body.data?.[0]?.id;
369
- }
370
- async streamEvents(sessionId, lastEventId, signal, onFrame, onOpen) {
371
- const response = await this.request(
372
- `/api/v1/cloud/sessions/${encodeURIComponent(sessionId)}/events/stream`,
373
- {
374
- headers: {
375
- Accept: "text/event-stream",
376
- ...lastEventId ? { "Last-Event-ID": lastEventId } : {}
377
- },
378
- signal
379
- }
380
- );
381
- if (!response.body) throw new Error("Qoder event stream returned no response body");
382
- onOpen?.();
383
- await parseQoderSse(response.body, onFrame);
384
- }
385
- };
386
- async function parseQoderSse(body, onFrame) {
387
- const reader = body.getReader();
388
- const decoder = new TextDecoder();
389
- let buffer = "";
390
- let frameLines = [];
391
- const dispatch = async () => {
392
- if (frameLines.length === 0) return;
393
- let id;
394
- let event;
395
- const data = [];
396
- for (const line of frameLines) {
397
- if (!line || line.startsWith(":")) continue;
398
- const separator = line.indexOf(":");
399
- const field = separator === -1 ? line : line.slice(0, separator);
400
- const value = separator === -1 ? "" : line.slice(separator + 1).replace(/^ /, "");
401
- if (field === "id") id = value;
402
- else if (field === "event") event = value;
403
- else if (field === "data") data.push(value);
404
- }
405
- frameLines = [];
406
- if (data.length === 0) return;
407
- const parsed = JSON.parse(data.join("\n"));
408
- await onFrame({ ...id ? { id } : {}, ...event ? { event } : {}, data: parsed });
409
- };
410
- while (true) {
411
- const { done, value } = await reader.read();
412
- buffer += decoder.decode(value, { stream: !done });
413
- let newlineIndex;
414
- while ((newlineIndex = buffer.indexOf("\n")) !== -1) {
415
- const line = buffer.slice(0, newlineIndex).replace(/\r$/, "");
416
- buffer = buffer.slice(newlineIndex + 1);
417
- if (line === "") await dispatch();
418
- else frameLines.push(line);
419
- }
420
- if (done) break;
421
- }
422
- if (buffer) frameLines.push(buffer.replace(/\r$/, ""));
423
- await dispatch();
424
- }
425
- function defaultSleep(milliseconds, signal) {
426
- return new Promise((resolve2, reject) => {
427
- if (signal.aborted) {
428
- reject(signal.reason ?? new Error("Aborted"));
429
- return;
430
- }
431
- const onAbort = () => {
432
- clearTimeout(timer);
433
- reject(signal.reason ?? new Error("Aborted"));
434
- };
435
- const timer = setTimeout(() => {
436
- signal.removeEventListener("abort", onAbort);
437
- resolve2();
438
- }, milliseconds);
439
- signal.addEventListener("abort", onAbort, { once: true });
440
- });
441
- }
442
- async function defaultInvokeAction(action, payload, options) {
443
- const client = await import("@mearl/client/local");
444
- return client.invoke(action, payload, {
445
- browser: options.browser,
446
- timeoutSec: options.timeoutSec,
447
- controlSource: "remote"
448
- });
449
- }
450
- function toolInput(event) {
451
- if (!isRecord(event.input) || typeof event.input.action !== "string") {
452
- throw new Error("Qoder mearl tool input requires a string action");
453
- }
454
- const browser = typeof event.input.browser === "string" ? event.input.browser : void 0;
455
- const timeoutSec = typeof event.input.timeoutSec === "number" && Number.isFinite(event.input.timeoutSec) ? event.input.timeoutSec : void 0;
456
- const payloadValue = event.input.payload ?? event.input.data ?? {};
457
- if (!isRecord(payloadValue)) {
458
- throw new Error("Qoder mearl tool input payload must be an object");
459
- }
460
- return {
461
- action: event.input.action,
462
- payload: payloadValue,
463
- ...browser ? { browser } : {},
464
- ...timeoutSec === void 0 ? {} : { timeoutSec }
465
- };
466
- }
467
- var QoderConnector = class {
468
- constructor(options) {
469
- this.options = options;
470
- const token = resolveQoderPersonalAccessToken({ token: options.token });
471
- if (!token) {
472
- throw new Error(
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."
474
- );
475
- }
476
- this.api = new QoderApiClient(
477
- token,
478
- options.apiBaseUrl ?? DEFAULT_QODER_API_BASE_URL,
479
- options.fetchImpl
480
- );
481
- this.now = options.now ?? Date.now;
482
- this.sleep = options.sleep ?? defaultSleep;
483
- this.invokeAction = options.invokeAction ?? defaultInvokeAction;
484
- this.reconnectInterval = options.reconnectInterval ?? DEFAULT_RECONNECT_INTERVAL_MS;
485
- this.maxReconnectAttempts = options.maxReconnectAttempts ?? -1;
486
- }
487
- api;
488
- now;
489
- sleep;
490
- invokeAction;
491
- reconnectInterval;
492
- maxReconnectAttempts;
493
- abortController = null;
494
- reconnectAttempts = 0;
495
- running = false;
496
- connected = false;
497
- sessionId = null;
498
- lastEventId;
499
- cachedResults = /* @__PURE__ */ new Map();
500
- connect() {
501
- if (this.running) return;
502
- this.running = true;
503
- this.abortController = new AbortController();
504
- void this.run(this.abortController.signal);
505
- }
506
- disconnect() {
507
- this.running = false;
508
- this.abortController?.abort();
509
- this.abortController = null;
510
- }
511
- async run(signal) {
512
- while (!signal.aborted) {
513
- try {
514
- if (!this.sessionId) {
515
- const pairing = await this.findPairing(signal);
516
- await this.completePairing(pairing, signal);
517
- }
518
- const sessionId = this.sessionId;
519
- await this.api.streamEvents(
520
- sessionId,
521
- this.lastEventId,
522
- signal,
523
- async (frame) => this.handleFrame(sessionId, frame, signal),
524
- () => {
525
- this.reconnectAttempts = 0;
526
- }
527
- );
528
- if (!signal.aborted) throw new Error("Qoder event stream ended");
529
- } catch (error) {
530
- if (signal.aborted) return;
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
- }
541
- if (!this.connected && this.options.failFast) {
542
- this.options.onInitialConnectionFailed?.(message);
543
- this.running = false;
544
- return;
545
- }
546
- this.reconnectAttempts += 1;
547
- if (this.maxReconnectAttempts !== -1 && this.reconnectAttempts > this.maxReconnectAttempts) {
548
- console.error(
549
- `[CloudConnector] Qoder max reconnect attempts (${this.maxReconnectAttempts}) reached`
550
- );
551
- this.running = false;
552
- return;
553
- }
554
- console.error(`[CloudConnector] Qoder connection error: ${message}`);
555
- try {
556
- await this.sleep(this.reconnectInterval, signal);
557
- } catch {
558
- return;
559
- }
560
- }
561
- }
562
- }
563
- async findPairing(signal) {
564
- const createdAt = this.options.endpoint.createdAt ?? this.now();
565
- const createdAfter = new Date(createdAt - DEFAULT_DISCOVERY_WINDOW_MS).toISOString();
566
- const pairing = await this.api.findPairingRequest(
567
- this.options.endpoint.pairingCode,
568
- createdAfter,
569
- signal
570
- );
571
- if (!pairing) {
572
- throw new Error(
573
- 'Qoder pairing request was not found. Ask the Agent to call the mearl tool with action "pair" and the code from this URL.'
574
- );
575
- }
576
- return pairing;
577
- }
578
- async completePairing(pairing, signal) {
579
- if (!this.connected) {
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;
603
- this.sessionId = pairing.sessionId;
604
- this.connected = true;
605
- this.reconnectAttempts = 0;
606
- this.options.onConnected?.();
607
- console.log(`[CloudConnector] Connected to Qoder session ${pairing.sessionId}`);
608
- }
609
- }
610
- async handleFrame(sessionId, frame, signal) {
611
- this.reconnectAttempts = 0;
612
- const event = frame.data;
613
- const eventId = event.id ?? frame.id;
614
- if (event.type !== "agent.custom_tool_use" || event.name !== QODER_TOOL_NAME || !eventId) {
615
- if (eventId) this.lastEventId = eventId;
616
- return;
617
- }
618
- const cached = this.cachedResults.get(eventId) ?? await this.executeTool(event);
619
- this.rememberResult(eventId, cached);
620
- try {
621
- this.lastEventId = await this.api.sendCustomToolResult(
622
- sessionId,
623
- eventId,
624
- cached.content,
625
- cached.isError,
626
- signal
627
- ) ?? eventId;
628
- } catch (error) {
629
- if (error instanceof QoderApiError && error.status === 400 && cached.content !== cached.fallbackContent) {
630
- this.lastEventId = await this.api.sendCustomToolResult(
631
- sessionId,
632
- eventId,
633
- cached.fallbackContent,
634
- cached.isError,
635
- signal
636
- ) ?? eventId;
637
- return;
638
- }
639
- if (error instanceof QoderApiError && error.status === 404) {
640
- this.lastEventId = eventId;
641
- return;
642
- }
643
- throw error;
644
- }
645
- }
646
- async executeTool(event) {
647
- try {
648
- const input = toolInput(event);
649
- if (input.action === "pair") {
650
- throw new Error("This pairing request does not match the active connector");
651
- }
652
- const result = await this.invokeAction(input.action, input.payload, {
653
- browser: input.browser,
654
- timeoutSec: input.timeoutSec ?? resolveActionTimeoutSec(input.action, input.payload, 15)
655
- });
656
- return { ...formatQoderToolResult(result), isError: false };
657
- } catch (error) {
658
- const message = error instanceof Error ? error.message : String(error);
659
- const content = [{ type: "text", text: safeJson({ error: message }) }];
660
- return { content, fallbackContent: content, isError: true };
661
- }
662
- }
663
- rememberResult(eventId, result) {
664
- this.cachedResults.set(eventId, result);
665
- while (this.cachedResults.size > MAX_CACHED_RESULTS) {
666
- const oldest = this.cachedResults.keys().next().value;
667
- if (!oldest) break;
668
- this.cachedResults.delete(oldest);
669
- }
670
- }
671
- };
672
-
673
- // src/index.ts
674
- var CLOUD_CONNECTOR_VERSION = true ? "2.7.2" : "unknown";
675
- var DEFAULT_RECONNECT_INTERVAL = 5e3;
676
- var BACKOFF_BASE_MS = 1e3;
677
- var BACKOFF_MAX_MS = 3e4;
678
- var SLOW_PROBE_INTERVAL_MS = 6e4;
679
- var FAST_RECONNECT_ATTEMPTS = 5;
680
- var CloudConnector = class {
681
- options;
682
- endpoint;
683
- identity;
684
- qoderConnector = null;
685
- ws = null;
686
- heartbeatTimer = null;
687
- reconnectTimer = null;
688
- reconnectAttempts = 0;
689
- messageBuffer = "";
690
- isManualClose = false;
691
- shouldTryWss = false;
692
- wssRetryAttempts = 0;
693
- maxWssRetryAttempts = 1;
694
- hasConnected = false;
695
- lastConnectionError = null;
696
- constructor(options) {
697
- this.endpoint = requireConnectorEndpoint(options.serverUrl);
698
- this.options = {
699
- serverUrl: this.endpoint.serverUrl,
700
- heartbeatInterval: options.heartbeatInterval ?? DEFAULT_HEARTBEAT_INTERVAL,
701
- reconnectInterval: options.reconnectInterval ?? DEFAULT_RECONNECT_INTERVAL,
702
- maxReconnectAttempts: options.maxReconnectAttempts ?? -1,
703
- failFast: options.failFast ?? false,
704
- onInitialConnectionFailed: options.onInitialConnectionFailed,
705
- onConnected: options.onConnected
706
- };
707
- this.identity = resolveConnectorIdentity(options);
708
- }
709
- connect() {
710
- if (this.endpoint.scheme === "qoder") {
711
- if (this.qoderConnector) {
712
- this.qoderConnector.connect();
713
- return;
714
- }
715
- try {
716
- this.qoderConnector = new QoderConnector({
717
- endpoint: this.endpoint,
718
- identity: this.identity,
719
- reconnectInterval: this.options.reconnectInterval,
720
- maxReconnectAttempts: this.options.maxReconnectAttempts,
721
- failFast: this.options.failFast,
722
- onConnected: () => {
723
- this.hasConnected = true;
724
- this.options.onConnected?.(this.options.serverUrl, this.identity);
725
- },
726
- onInitialConnectionFailed: this.options.onInitialConnectionFailed
727
- });
728
- this.qoderConnector.connect();
729
- } catch (error) {
730
- const message = error instanceof Error ? error.message : String(error);
731
- if (this.options.onInitialConnectionFailed) {
732
- this.options.onInitialConnectionFailed(message);
733
- } else {
734
- console.error(`[CloudConnector] Qoder connection error: ${message}`);
735
- }
736
- }
737
- return;
738
- }
739
- if (this.ws && (this.ws.readyState === 0 || this.ws.readyState === 1)) {
740
- return;
741
- }
742
- let serverUrl = this.endpoint.transportUrl;
743
- if (this.shouldTryWss && serverUrl.startsWith("ws://")) {
744
- serverUrl = serverUrl.replace("ws://", "wss://");
745
- console.log(`[CloudConnector] Retrying with wss://: ${serverUrl}`);
746
- }
747
- this.ws = new WebSocket(serverUrl);
748
- this.ws.on("open", () => {
749
- this.hasConnected = true;
750
- this.lastConnectionError = null;
751
- this.reconnectAttempts = 0;
752
- this.shouldTryWss = false;
753
- this.wssRetryAttempts = 0;
754
- this.sendConnectorHello();
755
- this.startHeartbeat();
756
- this.options.onConnected?.(this.options.serverUrl, this.identity);
757
- console.log(`[CloudConnector] Connected to ${serverUrl}`);
758
- });
759
- this.ws.on("message", (data) => {
760
- this.handleMessage(data);
761
- });
762
- this.ws.on("close", (code, reason) => {
763
- console.log(`[CloudConnector] Disconnected (${code}: ${reason.toString()})`);
764
- this.stopHeartbeat();
765
- this.messageBuffer = "";
766
- if (this.shouldTryWss && serverUrl.startsWith("ws://")) {
767
- return;
768
- }
769
- if (this.options.failFast && !this.hasConnected) {
770
- const reasonText = reason.toString();
771
- const message = this.lastConnectionError || reasonText || `Connection closed (${code})`;
772
- this.options.onInitialConnectionFailed?.(message);
773
- return;
774
- }
775
- this.tryReconnect();
776
- });
777
- this.ws.on("error", (error) => {
778
- console.error(`[CloudConnector] WebSocket error:`, error.message);
779
- this.lastConnectionError = error.message;
780
- if (error.message.includes("301") && !this.shouldTryWss && serverUrl.startsWith("ws://") && this.wssRetryAttempts < this.maxWssRetryAttempts) {
781
- this.shouldTryWss = true;
782
- this.wssRetryAttempts++;
783
- this.ws = null;
784
- console.log(
785
- `[CloudConnector] Server requires wss://, retrying (${this.wssRetryAttempts}/${this.maxWssRetryAttempts})...`
786
- );
787
- setTimeout(() => this.connect(), 1e3);
788
- }
789
- });
790
- }
791
- disconnect() {
792
- this.isManualClose = true;
793
- this.qoderConnector?.disconnect();
794
- this.qoderConnector = null;
795
- this.stopHeartbeat();
796
- if (this.reconnectTimer) {
797
- clearTimeout(this.reconnectTimer);
798
- this.reconnectTimer = null;
799
- }
800
- if (this.ws) {
801
- this.ws.close();
802
- this.ws = null;
803
- }
804
- }
805
- handleMessage(data) {
806
- this.messageBuffer += data.toString("utf-8");
807
- if (this.messageBuffer.length > MAX_BUFFER_SIZE) {
808
- console.error("[CloudConnector] Message buffer exceeds limit, closing connection");
809
- this.disconnect();
810
- return;
811
- }
812
- let newlineIndex;
813
- while ((newlineIndex = this.messageBuffer.indexOf("\n")) !== -1) {
814
- const line = this.messageBuffer.slice(0, newlineIndex);
815
- this.messageBuffer = this.messageBuffer.slice(newlineIndex + 1);
816
- if (!line.trim()) continue;
817
- try {
818
- const message = JSON.parse(line);
819
- this.handleCloudMessage(message);
820
- } catch (error) {
821
- console.error(`[CloudConnector] Failed to parse message:`, line, error);
822
- }
823
- }
824
- }
825
- async handleCloudMessage(message) {
826
- if (isHeartbeatMessage(message)) {
827
- if (message.type === "ping") {
828
- this.sendHeartbeatResponse(message.timestamp);
829
- }
830
- return;
831
- }
832
- const request = message;
833
- const { id, action, data, browser, timeoutSec } = request;
834
- try {
835
- const client = await import("@mearl/client/local");
836
- const result = await client.invoke(action, data, {
837
- browser,
838
- timeoutSec: timeoutSec ?? resolveActionTimeoutSec2(action, data, 15),
839
- controlSource: "remote"
840
- });
841
- this.sendResponse({ id, success: true, data: result });
842
- } catch (error) {
843
- const errorMessage = error instanceof Error ? error.message : String(error);
844
- this.sendResponse({ id, success: false, error: errorMessage });
845
- }
846
- }
847
- sendResponse(response) {
848
- if (this.ws && this.ws.readyState === 1) {
849
- this.ws.send(JSON.stringify(response) + "\n");
850
- }
851
- }
852
- sendConnectorHello() {
853
- if (this.ws && this.ws.readyState === WebSocket.OPEN) {
854
- const message = {
855
- type: "connector_hello",
856
- connectorId: this.identity.connectorId,
857
- name: this.identity.name,
858
- ...CLOUD_CONNECTOR_VERSION === "unknown" ? {} : { version: CLOUD_CONNECTOR_VERSION }
859
- };
860
- this.ws.send(JSON.stringify(message) + "\n");
861
- }
862
- }
863
- sendHeartbeatResponse(_timestamp) {
864
- if (this.ws && this.ws.readyState === 1) {
865
- this.ws.send(
866
- JSON.stringify({ type: "pong", timestamp: Date.now() }) + "\n"
867
- );
868
- }
869
- }
870
- startHeartbeat() {
871
- this.stopHeartbeat();
872
- this.heartbeatTimer = setInterval(() => {
873
- if (this.ws && this.ws.readyState === WebSocket.OPEN) {
874
- this.ws.send(
875
- JSON.stringify({ type: "ping", timestamp: Date.now() }) + "\n"
876
- );
877
- }
878
- }, this.options.heartbeatInterval * 1e3);
879
- }
880
- stopHeartbeat() {
881
- if (this.heartbeatTimer) {
882
- clearInterval(this.heartbeatTimer);
883
- this.heartbeatTimer = null;
884
- }
885
- }
886
- tryReconnect() {
887
- if (this.isManualClose) return;
888
- if (this.reconnectTimer) return;
889
- this.reconnectAttempts++;
890
- if (this.options.maxReconnectAttempts !== -1 && this.reconnectAttempts > this.options.maxReconnectAttempts) {
891
- console.log(
892
- `[CloudConnector] Max reconnect attempts (${this.options.maxReconnectAttempts}) reached`
893
- );
894
- return;
895
- }
896
- const isSlowProbe = this.reconnectAttempts > FAST_RECONNECT_ATTEMPTS;
897
- const delay = isSlowProbe ? SLOW_PROBE_INTERVAL_MS : Math.min(BACKOFF_BASE_MS * Math.pow(2, this.reconnectAttempts - 1), BACKOFF_MAX_MS);
898
- if (isSlowProbe) {
899
- console.log(
900
- `[CloudConnector] Slow probe reconnect in ${delay / 1e3}s (attempt ${this.reconnectAttempts})`
901
- );
902
- } else {
903
- console.log(
904
- `[CloudConnector] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts}/${FAST_RECONNECT_ATTEMPTS})`
905
- );
906
- }
907
- this.reconnectTimer = setTimeout(() => {
908
- this.reconnectTimer = null;
909
- this.connect();
910
- }, delay);
911
- }
912
- };
913
-
914
16
  // src/paths.ts
915
17
  import { keyedConfigFile, keyedDir, keyedLogFile } from "@mearl/daemon-core";
916
18
  var CONNECTORS_SUBDIR = "connectors";
@@ -984,7 +86,7 @@ function runForeground(options) {
984
86
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
985
87
  const writeOwnRecord = (_serverUrl, identity) => {
986
88
  try {
987
- writeRecord2(configFile, {
89
+ writeRecord(configFile, {
988
90
  serverUrl,
989
91
  pid: process.pid,
990
92
  startedAt,
@@ -1019,15 +121,15 @@ function runForeground(options) {
1019
121
  }
1020
122
 
1021
123
  // src/cli.ts
1022
- var CLOUD_CONNECTOR_VERSION2 = true ? "2.7.2" : "unknown";
124
+ var CLOUD_CONNECTOR_VERSION = true ? "2.8.0" : "unknown";
1023
125
  var args = process.argv.slice(2);
1024
126
  if (args.includes("--version") || args.includes("-v")) {
1025
- console.log(CLOUD_CONNECTOR_VERSION2);
127
+ console.log(CLOUD_CONNECTOR_VERSION);
1026
128
  process.exit(0);
1027
129
  }
1028
130
  var SUBCOMMANDS = ["start", "stop", "restart", "status", "list", "logs"];
1029
131
  function showHelp() {
1030
- console.error(`mearl-cloud-connector v${CLOUD_CONNECTOR_VERSION2}
132
+ console.error(`mearl-cloud-connector v${CLOUD_CONNECTOR_VERSION}
1031
133
 
1032
134
  Usage:
1033
135
  mearl-cloud-connector <server-url> [options] # run in the foreground