@mearl/cloud-connector 2.6.1 → 2.7.1

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/index.js CHANGED
@@ -5,7 +5,7 @@ import {
5
5
  MAX_BUFFER_SIZE,
6
6
  DEFAULT_HEARTBEAT_INTERVAL
7
7
  } from "@mearl/cloud-types";
8
- import { resolveActionTimeoutSec } from "@mearl/client/action-timeouts";
8
+ import { resolveActionTimeoutSec as resolveActionTimeoutSec2 } from "@mearl/client/action-timeouts";
9
9
 
10
10
  // src/identity.ts
11
11
  import { hostname } from "node:os";
@@ -34,8 +34,606 @@ function resolveConnectorIdentity(options) {
34
34
  return { connectorId, name };
35
35
  }
36
36
 
37
+ // src/endpoint.ts
38
+ var PAIRING_CODE_PATTERN = /^[A-Za-z0-9_-]{16,128}$/;
39
+ function parseQoderEndpoint(serverUrl, parsed) {
40
+ if (parsed.hostname !== "pair" || parsed.port || parsed.username || parsed.password || parsed.hash) {
41
+ return null;
42
+ }
43
+ const pathSegments = parsed.pathname.split("/").filter(Boolean);
44
+ if (pathSegments.length !== 1 || !PAIRING_CODE_PATTERN.test(pathSegments[0])) return null;
45
+ const allowedParams = /* @__PURE__ */ new Set(["created"]);
46
+ if ([...parsed.searchParams.keys()].some((key) => !allowedParams.has(key))) return null;
47
+ const createdValues = parsed.searchParams.getAll("created");
48
+ if (createdValues.length > 1) return null;
49
+ const createdValue = createdValues[0] ?? null;
50
+ if (createdValue !== null && !/^\d{13}$/.test(createdValue)) return null;
51
+ const createdAt = createdValue === null ? void 0 : Number(createdValue);
52
+ if (createdAt !== void 0 && (!Number.isSafeInteger(createdAt) || createdAt <= 0)) return null;
53
+ return {
54
+ serverUrl,
55
+ scheme: "qoder",
56
+ pairingCode: pathSegments[0],
57
+ ...createdAt === void 0 ? {} : { createdAt }
58
+ };
59
+ }
60
+ function parseConnectorEndpoint(value) {
61
+ if (!value) return null;
62
+ const serverUrl = value.trim();
63
+ if (!serverUrl) return null;
64
+ try {
65
+ const parsed = new URL(serverUrl);
66
+ if (parsed.protocol === "qoder:") return parseQoderEndpoint(serverUrl, parsed);
67
+ if (parsed.protocol !== "ws:" && parsed.protocol !== "wss:" || !parsed.hostname || parsed.hash) {
68
+ return null;
69
+ }
70
+ return {
71
+ serverUrl,
72
+ transportUrl: serverUrl,
73
+ scheme: parsed.protocol === "wss:" ? "wss" : "ws"
74
+ };
75
+ } catch {
76
+ return null;
77
+ }
78
+ }
79
+ function isConnectorEndpoint(value) {
80
+ return parseConnectorEndpoint(value) !== null;
81
+ }
82
+ function requireConnectorEndpoint(value) {
83
+ const endpoint = parseConnectorEndpoint(value);
84
+ if (!endpoint) {
85
+ throw new Error(
86
+ "serverUrl must use ws://, wss://, or qoder://pair/<code> without a URL fragment"
87
+ );
88
+ }
89
+ return endpoint;
90
+ }
91
+
92
+ // src/qoder.ts
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
165
+ var QODER_TOOL_NAME = "mearl";
166
+ var DEFAULT_QODER_API_BASE_URL = "https://api.qoder.com";
167
+ var DEFAULT_DISCOVERY_WINDOW_MS = 60 * 60 * 1e3;
168
+ var DEFAULT_RECONNECT_INTERVAL_MS = 5e3;
169
+ var MAX_RECENT_SESSIONS = 100;
170
+ var MAX_RECENT_TOOL_EVENTS = 20;
171
+ var MAX_CACHED_RESULTS = 100;
172
+ var QoderApiError = class extends Error {
173
+ constructor(message, status) {
174
+ super(message);
175
+ this.status = status;
176
+ this.name = "QoderApiError";
177
+ }
178
+ };
179
+ function safeJson(value) {
180
+ try {
181
+ return JSON.stringify(value ?? null);
182
+ } catch {
183
+ return JSON.stringify({ error: "Mearl returned a value that cannot be serialized" });
184
+ }
185
+ }
186
+ function isRecord(value) {
187
+ return typeof value === "object" && value !== null && !Array.isArray(value);
188
+ }
189
+ function asScreenshot(value) {
190
+ if (!isRecord(value) || typeof value.data !== "string" || !isRecord(value.meta)) return null;
191
+ const format = value.meta.format;
192
+ if (format !== "png" && format !== "jpeg") return null;
193
+ return { data: value.data, meta: { ...value.meta, format } };
194
+ }
195
+ function extractBatchScreenshots(value) {
196
+ if (!isRecord(value) || !Array.isArray(value.results)) return null;
197
+ const screenshots = [];
198
+ const results = value.results.map((result) => {
199
+ if (!isRecord(result) || result.action !== "page_screenshot") return result;
200
+ const screenshot = asScreenshot(result.data);
201
+ if (!screenshot) return result;
202
+ const data = { ...result.data };
203
+ delete data.data;
204
+ data.meta = screenshot.meta;
205
+ data.imageContentIndex = screenshots.length + 1;
206
+ screenshots.push(screenshot);
207
+ return { ...result, data };
208
+ });
209
+ if (screenshots.length === 0) return null;
210
+ return { metadata: { ...value, results }, screenshots };
211
+ }
212
+ function imageContentBlock(screenshot) {
213
+ return {
214
+ type: "image",
215
+ source: {
216
+ type: "base64",
217
+ media_type: `image/${screenshot.meta.format}`,
218
+ data: screenshot.data
219
+ }
220
+ };
221
+ }
222
+ function formatQoderToolResult(value) {
223
+ const directScreenshot = asScreenshot(value);
224
+ const nestedScreenshot = !directScreenshot && isRecord(value) ? asScreenshot(value.screenshot) : null;
225
+ const screenshot = directScreenshot ?? nestedScreenshot;
226
+ if (!screenshot) {
227
+ const batch = extractBatchScreenshots(value);
228
+ if (batch) {
229
+ return {
230
+ content: [
231
+ { type: "text", text: safeJson(batch.metadata) },
232
+ ...batch.screenshots.map(imageContentBlock)
233
+ ],
234
+ fallbackContent: [{ type: "text", text: safeJson(value) }]
235
+ };
236
+ }
237
+ }
238
+ if (!screenshot) {
239
+ const content = [{ type: "text", text: safeJson(value) }];
240
+ return { content, fallbackContent: content };
241
+ }
242
+ let metadata;
243
+ if (directScreenshot) {
244
+ metadata = { meta: screenshot.meta };
245
+ } else {
246
+ metadata = { ...value, screenshot: { meta: screenshot.meta } };
247
+ }
248
+ return {
249
+ content: [{ type: "text", text: safeJson(metadata) }, imageContentBlock(screenshot)],
250
+ fallbackContent: [{ type: "text", text: safeJson(value) }]
251
+ };
252
+ }
253
+ function pairingCodeFromEvent(event) {
254
+ if (event.type !== "agent.custom_tool_use" || event.name !== QODER_TOOL_NAME) return null;
255
+ if (!isRecord(event.input) || event.input.action !== "pair") return null;
256
+ const payload = isRecord(event.input.payload) ? event.input.payload : isRecord(event.input.data) ? event.input.data : null;
257
+ return payload && typeof payload.code === "string" ? payload.code : null;
258
+ }
259
+ function qoderErrorMessage(status, body) {
260
+ try {
261
+ const parsed = JSON.parse(body);
262
+ const message = parsed.error?.message ?? parsed.message;
263
+ if (typeof message === "string" && message.trim()) return message.trim();
264
+ } catch {
265
+ }
266
+ return `Qoder API request failed with HTTP ${status}`;
267
+ }
268
+ var QoderApiClient = class {
269
+ constructor(token, baseUrl = DEFAULT_QODER_API_BASE_URL, fetchImpl = fetch) {
270
+ this.token = token;
271
+ this.fetchImpl = fetchImpl;
272
+ const parsed = new URL(baseUrl);
273
+ if (parsed.protocol !== "https:" && parsed.hostname !== "localhost" && parsed.hostname !== "127.0.0.1") {
274
+ throw new Error("Qoder API base URL must use https:// (localhost may use http:// for tests)");
275
+ }
276
+ this.baseUrl = parsed.toString().replace(/\/$/, "");
277
+ }
278
+ baseUrl;
279
+ async request(path, init = {}) {
280
+ const response = await this.fetchImpl(`${this.baseUrl}${path}`, {
281
+ ...init,
282
+ headers: {
283
+ Authorization: `Bearer ${this.token}`,
284
+ ...init.headers
285
+ }
286
+ });
287
+ if (!response.ok) {
288
+ const body = await response.text();
289
+ throw new QoderApiError(qoderErrorMessage(response.status, body), response.status);
290
+ }
291
+ return response;
292
+ }
293
+ async listSessions(createdAfter, signal) {
294
+ const query = new URLSearchParams({
295
+ limit: String(MAX_RECENT_SESSIONS),
296
+ order: "desc",
297
+ "created_at[gte]": createdAfter
298
+ });
299
+ const response = await this.request(`/api/v1/cloud/sessions?${query}`, { signal });
300
+ const body = await response.json();
301
+ return Array.isArray(body.data) ? body.data.filter((session) => typeof session.id === "string") : [];
302
+ }
303
+ async listCustomToolEvents(sessionId, createdAfter, signal) {
304
+ const query = new URLSearchParams({
305
+ limit: String(MAX_RECENT_TOOL_EVENTS),
306
+ order: "desc",
307
+ types: "agent.custom_tool_use",
308
+ "created_at[gte]": createdAfter
309
+ });
310
+ const response = await this.request(
311
+ `/api/v1/cloud/sessions/${encodeURIComponent(sessionId)}/events?${query}`,
312
+ { signal }
313
+ );
314
+ const body = await response.json();
315
+ return Array.isArray(body.data) ? body.data : [];
316
+ }
317
+ async findPairingRequest(pairingCode, createdAfter, signal) {
318
+ const sessions = await this.listSessions(createdAfter, signal);
319
+ for (const session of sessions) {
320
+ const events = await this.listCustomToolEvents(session.id, createdAfter, signal);
321
+ const event = events.find((candidate) => pairingCodeFromEvent(candidate) === pairingCode);
322
+ if (event?.id) return { sessionId: session.id, event: { ...event, id: event.id } };
323
+ }
324
+ return null;
325
+ }
326
+ async sendCustomToolResult(sessionId, customToolUseId, content, isError = false, signal) {
327
+ const response = await this.request(
328
+ `/api/v1/cloud/sessions/${encodeURIComponent(sessionId)}/events`,
329
+ {
330
+ method: "POST",
331
+ headers: { "Content-Type": "application/json" },
332
+ signal,
333
+ body: JSON.stringify({
334
+ events: [
335
+ {
336
+ type: "user.custom_tool_result",
337
+ custom_tool_use_id: customToolUseId,
338
+ content,
339
+ is_error: isError
340
+ }
341
+ ]
342
+ })
343
+ }
344
+ );
345
+ const body = await response.json();
346
+ return body.data?.[0]?.id;
347
+ }
348
+ async streamEvents(sessionId, lastEventId, signal, onFrame, onOpen) {
349
+ const response = await this.request(
350
+ `/api/v1/cloud/sessions/${encodeURIComponent(sessionId)}/events/stream`,
351
+ {
352
+ headers: {
353
+ Accept: "text/event-stream",
354
+ ...lastEventId ? { "Last-Event-ID": lastEventId } : {}
355
+ },
356
+ signal
357
+ }
358
+ );
359
+ if (!response.body) throw new Error("Qoder event stream returned no response body");
360
+ onOpen?.();
361
+ await parseQoderSse(response.body, onFrame);
362
+ }
363
+ };
364
+ async function parseQoderSse(body, onFrame) {
365
+ const reader = body.getReader();
366
+ const decoder = new TextDecoder();
367
+ let buffer = "";
368
+ let frameLines = [];
369
+ const dispatch = async () => {
370
+ if (frameLines.length === 0) return;
371
+ let id;
372
+ let event;
373
+ const data = [];
374
+ for (const line of frameLines) {
375
+ if (!line || line.startsWith(":")) continue;
376
+ const separator = line.indexOf(":");
377
+ const field = separator === -1 ? line : line.slice(0, separator);
378
+ const value = separator === -1 ? "" : line.slice(separator + 1).replace(/^ /, "");
379
+ if (field === "id") id = value;
380
+ else if (field === "event") event = value;
381
+ else if (field === "data") data.push(value);
382
+ }
383
+ frameLines = [];
384
+ if (data.length === 0) return;
385
+ const parsed = JSON.parse(data.join("\n"));
386
+ await onFrame({ ...id ? { id } : {}, ...event ? { event } : {}, data: parsed });
387
+ };
388
+ while (true) {
389
+ const { done, value } = await reader.read();
390
+ buffer += decoder.decode(value, { stream: !done });
391
+ let newlineIndex;
392
+ while ((newlineIndex = buffer.indexOf("\n")) !== -1) {
393
+ const line = buffer.slice(0, newlineIndex).replace(/\r$/, "");
394
+ buffer = buffer.slice(newlineIndex + 1);
395
+ if (line === "") await dispatch();
396
+ else frameLines.push(line);
397
+ }
398
+ if (done) break;
399
+ }
400
+ if (buffer) frameLines.push(buffer.replace(/\r$/, ""));
401
+ await dispatch();
402
+ }
403
+ function defaultSleep(milliseconds, signal) {
404
+ return new Promise((resolve2, reject) => {
405
+ if (signal.aborted) {
406
+ reject(signal.reason ?? new Error("Aborted"));
407
+ return;
408
+ }
409
+ const onAbort = () => {
410
+ clearTimeout(timer);
411
+ reject(signal.reason ?? new Error("Aborted"));
412
+ };
413
+ const timer = setTimeout(() => {
414
+ signal.removeEventListener("abort", onAbort);
415
+ resolve2();
416
+ }, milliseconds);
417
+ signal.addEventListener("abort", onAbort, { once: true });
418
+ });
419
+ }
420
+ async function defaultInvokeAction(action, payload, options) {
421
+ const client = await import("@mearl/client/local");
422
+ return client.invoke(action, payload, {
423
+ browser: options.browser,
424
+ timeoutSec: options.timeoutSec,
425
+ controlSource: "remote"
426
+ });
427
+ }
428
+ function toolInput(event) {
429
+ if (!isRecord(event.input) || typeof event.input.action !== "string") {
430
+ throw new Error("Qoder mearl tool input requires a string action");
431
+ }
432
+ const browser = typeof event.input.browser === "string" ? event.input.browser : void 0;
433
+ const timeoutSec = typeof event.input.timeoutSec === "number" && Number.isFinite(event.input.timeoutSec) ? event.input.timeoutSec : void 0;
434
+ const payloadValue = event.input.payload ?? event.input.data ?? {};
435
+ if (!isRecord(payloadValue)) {
436
+ throw new Error("Qoder mearl tool input payload must be an object");
437
+ }
438
+ return {
439
+ action: event.input.action,
440
+ payload: payloadValue,
441
+ ...browser ? { browser } : {},
442
+ ...timeoutSec === void 0 ? {} : { timeoutSec }
443
+ };
444
+ }
445
+ var QoderConnector = class {
446
+ constructor(options) {
447
+ this.options = options;
448
+ const token = resolveQoderPersonalAccessToken({ token: options.token });
449
+ if (!token) {
450
+ throw new Error(
451
+ "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."
452
+ );
453
+ }
454
+ this.api = new QoderApiClient(
455
+ token,
456
+ options.apiBaseUrl ?? DEFAULT_QODER_API_BASE_URL,
457
+ options.fetchImpl
458
+ );
459
+ this.now = options.now ?? Date.now;
460
+ this.sleep = options.sleep ?? defaultSleep;
461
+ this.invokeAction = options.invokeAction ?? defaultInvokeAction;
462
+ this.reconnectInterval = options.reconnectInterval ?? DEFAULT_RECONNECT_INTERVAL_MS;
463
+ this.maxReconnectAttempts = options.maxReconnectAttempts ?? -1;
464
+ }
465
+ api;
466
+ now;
467
+ sleep;
468
+ invokeAction;
469
+ reconnectInterval;
470
+ maxReconnectAttempts;
471
+ abortController = null;
472
+ reconnectAttempts = 0;
473
+ running = false;
474
+ connected = false;
475
+ sessionId = null;
476
+ lastEventId;
477
+ cachedResults = /* @__PURE__ */ new Map();
478
+ connect() {
479
+ if (this.running) return;
480
+ this.running = true;
481
+ this.abortController = new AbortController();
482
+ void this.run(this.abortController.signal);
483
+ }
484
+ disconnect() {
485
+ this.running = false;
486
+ this.abortController?.abort();
487
+ this.abortController = null;
488
+ }
489
+ async run(signal) {
490
+ while (!signal.aborted) {
491
+ try {
492
+ if (!this.sessionId) {
493
+ const pairing = await this.findPairing(signal);
494
+ await this.completePairing(pairing, signal);
495
+ }
496
+ const sessionId = this.sessionId;
497
+ await this.api.streamEvents(
498
+ sessionId,
499
+ this.lastEventId,
500
+ signal,
501
+ async (frame) => this.handleFrame(sessionId, frame, signal),
502
+ () => {
503
+ this.reconnectAttempts = 0;
504
+ }
505
+ );
506
+ if (!signal.aborted) throw new Error("Qoder event stream ended");
507
+ } catch (error) {
508
+ if (signal.aborted) return;
509
+ const message = error instanceof Error ? error.message : String(error);
510
+ if (!this.connected && this.options.failFast) {
511
+ this.options.onInitialConnectionFailed?.(message);
512
+ this.running = false;
513
+ return;
514
+ }
515
+ this.reconnectAttempts += 1;
516
+ if (this.maxReconnectAttempts !== -1 && this.reconnectAttempts > this.maxReconnectAttempts) {
517
+ console.error(
518
+ `[CloudConnector] Qoder max reconnect attempts (${this.maxReconnectAttempts}) reached`
519
+ );
520
+ this.running = false;
521
+ return;
522
+ }
523
+ console.error(`[CloudConnector] Qoder connection error: ${message}`);
524
+ try {
525
+ await this.sleep(this.reconnectInterval, signal);
526
+ } catch {
527
+ return;
528
+ }
529
+ }
530
+ }
531
+ }
532
+ async findPairing(signal) {
533
+ const createdAt = this.options.endpoint.createdAt ?? this.now();
534
+ const createdAfter = new Date(createdAt - DEFAULT_DISCOVERY_WINDOW_MS).toISOString();
535
+ const pairing = await this.api.findPairingRequest(
536
+ this.options.endpoint.pairingCode,
537
+ createdAfter,
538
+ signal
539
+ );
540
+ if (!pairing) {
541
+ throw new Error(
542
+ 'Qoder pairing request was not found. Ask the Agent to call the mearl tool with action "pair" and the code from this URL.'
543
+ );
544
+ }
545
+ return pairing;
546
+ }
547
+ async completePairing(pairing, signal) {
548
+ if (!this.connected) {
549
+ this.lastEventId = await this.api.sendCustomToolResult(
550
+ pairing.sessionId,
551
+ pairing.event.id,
552
+ [
553
+ {
554
+ type: "text",
555
+ text: safeJson({
556
+ connected: true,
557
+ connectorId: this.options.identity.connectorId,
558
+ name: this.options.identity.name
559
+ })
560
+ }
561
+ ],
562
+ false,
563
+ signal
564
+ ) ?? pairing.event.id;
565
+ this.sessionId = pairing.sessionId;
566
+ this.connected = true;
567
+ this.reconnectAttempts = 0;
568
+ this.options.onConnected?.();
569
+ console.log(`[CloudConnector] Connected to Qoder session ${pairing.sessionId}`);
570
+ }
571
+ }
572
+ async handleFrame(sessionId, frame, signal) {
573
+ this.reconnectAttempts = 0;
574
+ const event = frame.data;
575
+ const eventId = event.id ?? frame.id;
576
+ if (event.type !== "agent.custom_tool_use" || event.name !== QODER_TOOL_NAME || !eventId) {
577
+ if (eventId) this.lastEventId = eventId;
578
+ return;
579
+ }
580
+ const cached = this.cachedResults.get(eventId) ?? await this.executeTool(event);
581
+ this.rememberResult(eventId, cached);
582
+ try {
583
+ this.lastEventId = await this.api.sendCustomToolResult(
584
+ sessionId,
585
+ eventId,
586
+ cached.content,
587
+ cached.isError,
588
+ signal
589
+ ) ?? eventId;
590
+ } catch (error) {
591
+ if (error instanceof QoderApiError && error.status === 400 && cached.content !== cached.fallbackContent) {
592
+ this.lastEventId = await this.api.sendCustomToolResult(
593
+ sessionId,
594
+ eventId,
595
+ cached.fallbackContent,
596
+ cached.isError,
597
+ signal
598
+ ) ?? eventId;
599
+ return;
600
+ }
601
+ if (error instanceof QoderApiError && error.status === 404) {
602
+ this.lastEventId = eventId;
603
+ return;
604
+ }
605
+ throw error;
606
+ }
607
+ }
608
+ async executeTool(event) {
609
+ try {
610
+ const input = toolInput(event);
611
+ if (input.action === "pair") {
612
+ throw new Error("This pairing request does not match the active connector");
613
+ }
614
+ const result = await this.invokeAction(input.action, input.payload, {
615
+ browser: input.browser,
616
+ timeoutSec: input.timeoutSec ?? resolveActionTimeoutSec(input.action, input.payload, 15)
617
+ });
618
+ return { ...formatQoderToolResult(result), isError: false };
619
+ } catch (error) {
620
+ const message = error instanceof Error ? error.message : String(error);
621
+ const content = [{ type: "text", text: safeJson({ error: message }) }];
622
+ return { content, fallbackContent: content, isError: true };
623
+ }
624
+ }
625
+ rememberResult(eventId, result) {
626
+ this.cachedResults.set(eventId, result);
627
+ while (this.cachedResults.size > MAX_CACHED_RESULTS) {
628
+ const oldest = this.cachedResults.keys().next().value;
629
+ if (!oldest) break;
630
+ this.cachedResults.delete(oldest);
631
+ }
632
+ }
633
+ };
634
+
37
635
  // src/index.ts
38
- var CLOUD_CONNECTOR_VERSION = true ? "2.6.1" : "unknown";
636
+ var CLOUD_CONNECTOR_VERSION = true ? "2.7.1" : "unknown";
39
637
  var DEFAULT_RECONNECT_INTERVAL = 5e3;
40
638
  var BACKOFF_BASE_MS = 1e3;
41
639
  var BACKOFF_MAX_MS = 3e4;
@@ -43,7 +641,9 @@ var SLOW_PROBE_INTERVAL_MS = 6e4;
43
641
  var FAST_RECONNECT_ATTEMPTS = 5;
44
642
  var CloudConnector = class {
45
643
  options;
644
+ endpoint;
46
645
  identity;
646
+ qoderConnector = null;
47
647
  ws = null;
48
648
  heartbeatTimer = null;
49
649
  reconnectTimer = null;
@@ -56,8 +656,9 @@ var CloudConnector = class {
56
656
  hasConnected = false;
57
657
  lastConnectionError = null;
58
658
  constructor(options) {
659
+ this.endpoint = requireConnectorEndpoint(options.serverUrl);
59
660
  this.options = {
60
- serverUrl: options.serverUrl,
661
+ serverUrl: this.endpoint.serverUrl,
61
662
  heartbeatInterval: options.heartbeatInterval ?? DEFAULT_HEARTBEAT_INTERVAL,
62
663
  reconnectInterval: options.reconnectInterval ?? DEFAULT_RECONNECT_INTERVAL,
63
664
  maxReconnectAttempts: options.maxReconnectAttempts ?? -1,
@@ -68,10 +669,39 @@ var CloudConnector = class {
68
669
  this.identity = resolveConnectorIdentity(options);
69
670
  }
70
671
  connect() {
672
+ if (this.endpoint.scheme === "qoder") {
673
+ if (this.qoderConnector) {
674
+ this.qoderConnector.connect();
675
+ return;
676
+ }
677
+ try {
678
+ this.qoderConnector = new QoderConnector({
679
+ endpoint: this.endpoint,
680
+ identity: this.identity,
681
+ reconnectInterval: this.options.reconnectInterval,
682
+ maxReconnectAttempts: this.options.maxReconnectAttempts,
683
+ failFast: this.options.failFast,
684
+ onConnected: () => {
685
+ this.hasConnected = true;
686
+ this.options.onConnected?.(this.options.serverUrl, this.identity);
687
+ },
688
+ onInitialConnectionFailed: this.options.onInitialConnectionFailed
689
+ });
690
+ this.qoderConnector.connect();
691
+ } catch (error) {
692
+ const message = error instanceof Error ? error.message : String(error);
693
+ if (this.options.onInitialConnectionFailed) {
694
+ this.options.onInitialConnectionFailed(message);
695
+ } else {
696
+ console.error(`[CloudConnector] Qoder connection error: ${message}`);
697
+ }
698
+ }
699
+ return;
700
+ }
71
701
  if (this.ws && (this.ws.readyState === 0 || this.ws.readyState === 1)) {
72
702
  return;
73
703
  }
74
- let serverUrl = this.options.serverUrl;
704
+ let serverUrl = this.endpoint.transportUrl;
75
705
  if (this.shouldTryWss && serverUrl.startsWith("ws://")) {
76
706
  serverUrl = serverUrl.replace("ws://", "wss://");
77
707
  console.log(`[CloudConnector] Retrying with wss://: ${serverUrl}`);
@@ -122,6 +752,8 @@ var CloudConnector = class {
122
752
  }
123
753
  disconnect() {
124
754
  this.isManualClose = true;
755
+ this.qoderConnector?.disconnect();
756
+ this.qoderConnector = null;
125
757
  this.stopHeartbeat();
126
758
  if (this.reconnectTimer) {
127
759
  clearTimeout(this.reconnectTimer);
@@ -165,8 +797,8 @@ var CloudConnector = class {
165
797
  const client = await import("@mearl/client/local");
166
798
  const result = await client.invoke(action, data, {
167
799
  browser,
168
- timeoutSec: timeoutSec ?? resolveActionTimeoutSec(action, data, 15),
169
- controlSource: "cloud"
800
+ timeoutSec: timeoutSec ?? resolveActionTimeoutSec2(action, data, 15),
801
+ controlSource: "remote"
170
802
  });
171
803
  this.sendResponse({ id, success: true, data: result });
172
804
  } catch (error) {
@@ -241,5 +873,15 @@ var CloudConnector = class {
241
873
  }
242
874
  };
243
875
  export {
244
- CloudConnector
876
+ CloudConnector,
877
+ DEFAULT_QODER_API_BASE_URL,
878
+ QODER_TOOL_NAME,
879
+ QoderApiClient,
880
+ QoderApiError,
881
+ QoderConnector,
882
+ formatQoderToolResult,
883
+ isConnectorEndpoint,
884
+ parseConnectorEndpoint,
885
+ parseQoderSse,
886
+ requireConnectorEndpoint
245
887
  };