@mearl/cloud-connector 2.6.0 → 2.7.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,5 +1,60 @@
1
1
  #!/usr/bin/env node
2
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
+ }
57
+
3
58
  // src/daemon.ts
4
59
  import { fileURLToPath } from "node:url";
5
60
  import {
@@ -16,7 +71,7 @@ import {
16
71
  MAX_BUFFER_SIZE,
17
72
  DEFAULT_HEARTBEAT_INTERVAL
18
73
  } from "@mearl/cloud-types";
19
- import { resolveActionTimeoutSec } from "@mearl/client/action-timeouts";
74
+ import { resolveActionTimeoutSec as resolveActionTimeoutSec2 } from "@mearl/client/action-timeouts";
20
75
 
21
76
  // src/identity.ts
22
77
  import { hostname } from "node:os";
@@ -45,8 +100,451 @@ function resolveConnectorIdentity(options) {
45
100
  return { connectorId, name };
46
101
  }
47
102
 
103
+ // src/qoder.ts
104
+ import { resolveActionTimeoutSec } from "@mearl/client/action-timeouts";
105
+ var QODER_TOOL_NAME = "mearl";
106
+ var DEFAULT_QODER_API_BASE_URL = "https://api.qoder.com";
107
+ var DEFAULT_DISCOVERY_WINDOW_MS = 60 * 60 * 1e3;
108
+ var DEFAULT_RECONNECT_INTERVAL_MS = 5e3;
109
+ var MAX_RECENT_SESSIONS = 100;
110
+ var MAX_RECENT_TOOL_EVENTS = 20;
111
+ var MAX_CACHED_RESULTS = 100;
112
+ var QoderApiError = class extends Error {
113
+ constructor(message, status) {
114
+ super(message);
115
+ this.status = status;
116
+ this.name = "QoderApiError";
117
+ }
118
+ };
119
+ function safeJson(value) {
120
+ try {
121
+ return JSON.stringify(value ?? null);
122
+ } catch {
123
+ return JSON.stringify({ error: "Mearl returned a value that cannot be serialized" });
124
+ }
125
+ }
126
+ function isRecord(value) {
127
+ return typeof value === "object" && value !== null && !Array.isArray(value);
128
+ }
129
+ function asScreenshot(value) {
130
+ if (!isRecord(value) || typeof value.data !== "string" || !isRecord(value.meta)) return null;
131
+ const format = value.meta.format;
132
+ if (format !== "png" && format !== "jpeg") return null;
133
+ return { data: value.data, meta: { ...value.meta, format } };
134
+ }
135
+ function formatQoderToolResult(value) {
136
+ const directScreenshot = asScreenshot(value);
137
+ const nestedScreenshot = !directScreenshot && isRecord(value) ? asScreenshot(value.screenshot) : null;
138
+ const screenshot = directScreenshot ?? nestedScreenshot;
139
+ if (!screenshot) {
140
+ const content = [{ type: "text", text: safeJson(value) }];
141
+ return { content, fallbackContent: content };
142
+ }
143
+ let metadata;
144
+ if (directScreenshot) {
145
+ metadata = { meta: screenshot.meta };
146
+ } else {
147
+ metadata = { ...value, screenshot: { meta: screenshot.meta } };
148
+ }
149
+ return {
150
+ content: [
151
+ { type: "text", text: safeJson(metadata) },
152
+ {
153
+ type: "image",
154
+ source: {
155
+ type: "base64",
156
+ media_type: `image/${screenshot.meta.format}`,
157
+ data: screenshot.data
158
+ }
159
+ }
160
+ ],
161
+ fallbackContent: [{ type: "text", text: safeJson(value) }]
162
+ };
163
+ }
164
+ function pairingCodeFromEvent(event) {
165
+ if (event.type !== "agent.custom_tool_use" || event.name !== QODER_TOOL_NAME) return null;
166
+ if (!isRecord(event.input) || event.input.action !== "pair") return null;
167
+ const payload = isRecord(event.input.payload) ? event.input.payload : isRecord(event.input.data) ? event.input.data : null;
168
+ return payload && typeof payload.code === "string" ? payload.code : null;
169
+ }
170
+ function qoderErrorMessage(status, body) {
171
+ try {
172
+ const parsed = JSON.parse(body);
173
+ const message = parsed.error?.message ?? parsed.message;
174
+ if (typeof message === "string" && message.trim()) return message.trim();
175
+ } catch {
176
+ }
177
+ return `Qoder API request failed with HTTP ${status}`;
178
+ }
179
+ var QoderApiClient = class {
180
+ constructor(token, baseUrl = DEFAULT_QODER_API_BASE_URL, fetchImpl = fetch) {
181
+ this.token = token;
182
+ this.fetchImpl = fetchImpl;
183
+ const parsed = new URL(baseUrl);
184
+ if (parsed.protocol !== "https:" && parsed.hostname !== "localhost" && parsed.hostname !== "127.0.0.1") {
185
+ throw new Error("Qoder API base URL must use https:// (localhost may use http:// for tests)");
186
+ }
187
+ this.baseUrl = parsed.toString().replace(/\/$/, "");
188
+ }
189
+ baseUrl;
190
+ async request(path, init = {}) {
191
+ const response = await this.fetchImpl(`${this.baseUrl}${path}`, {
192
+ ...init,
193
+ headers: {
194
+ Authorization: `Bearer ${this.token}`,
195
+ ...init.headers
196
+ }
197
+ });
198
+ if (!response.ok) {
199
+ const body = await response.text();
200
+ throw new QoderApiError(qoderErrorMessage(response.status, body), response.status);
201
+ }
202
+ return response;
203
+ }
204
+ async listSessions(createdAfter, signal) {
205
+ const query = new URLSearchParams({
206
+ limit: String(MAX_RECENT_SESSIONS),
207
+ order: "desc",
208
+ "created_at[gte]": createdAfter
209
+ });
210
+ const response = await this.request(`/api/v1/cloud/sessions?${query}`, { signal });
211
+ const body = await response.json();
212
+ return Array.isArray(body.data) ? body.data.filter((session) => typeof session.id === "string") : [];
213
+ }
214
+ async listCustomToolEvents(sessionId, createdAfter, signal) {
215
+ const query = new URLSearchParams({
216
+ limit: String(MAX_RECENT_TOOL_EVENTS),
217
+ order: "desc",
218
+ types: "agent.custom_tool_use",
219
+ "created_at[gte]": createdAfter
220
+ });
221
+ const response = await this.request(
222
+ `/api/v1/cloud/sessions/${encodeURIComponent(sessionId)}/events?${query}`,
223
+ { signal }
224
+ );
225
+ const body = await response.json();
226
+ return Array.isArray(body.data) ? body.data : [];
227
+ }
228
+ async findPairingRequest(pairingCode, createdAfter, signal) {
229
+ const sessions = await this.listSessions(createdAfter, signal);
230
+ for (const session of sessions) {
231
+ const events = await this.listCustomToolEvents(session.id, createdAfter, signal);
232
+ const event = events.find((candidate) => pairingCodeFromEvent(candidate) === pairingCode);
233
+ if (event?.id) return { sessionId: session.id, event: { ...event, id: event.id } };
234
+ }
235
+ return null;
236
+ }
237
+ async sendCustomToolResult(sessionId, customToolUseId, content, isError = false, signal) {
238
+ const response = await this.request(
239
+ `/api/v1/cloud/sessions/${encodeURIComponent(sessionId)}/events`,
240
+ {
241
+ method: "POST",
242
+ headers: { "Content-Type": "application/json" },
243
+ signal,
244
+ body: JSON.stringify({
245
+ events: [
246
+ {
247
+ type: "user.custom_tool_result",
248
+ custom_tool_use_id: customToolUseId,
249
+ content,
250
+ is_error: isError
251
+ }
252
+ ]
253
+ })
254
+ }
255
+ );
256
+ const body = await response.json();
257
+ return body.data?.[0]?.id;
258
+ }
259
+ async streamEvents(sessionId, lastEventId, signal, onFrame, onOpen) {
260
+ const response = await this.request(
261
+ `/api/v1/cloud/sessions/${encodeURIComponent(sessionId)}/events/stream`,
262
+ {
263
+ headers: {
264
+ Accept: "text/event-stream",
265
+ ...lastEventId ? { "Last-Event-ID": lastEventId } : {}
266
+ },
267
+ signal
268
+ }
269
+ );
270
+ if (!response.body) throw new Error("Qoder event stream returned no response body");
271
+ onOpen?.();
272
+ await parseQoderSse(response.body, onFrame);
273
+ }
274
+ };
275
+ async function parseQoderSse(body, onFrame) {
276
+ const reader = body.getReader();
277
+ const decoder = new TextDecoder();
278
+ let buffer = "";
279
+ let frameLines = [];
280
+ const dispatch = async () => {
281
+ if (frameLines.length === 0) return;
282
+ let id;
283
+ let event;
284
+ const data = [];
285
+ for (const line of frameLines) {
286
+ if (!line || line.startsWith(":")) continue;
287
+ const separator = line.indexOf(":");
288
+ const field = separator === -1 ? line : line.slice(0, separator);
289
+ const value = separator === -1 ? "" : line.slice(separator + 1).replace(/^ /, "");
290
+ if (field === "id") id = value;
291
+ else if (field === "event") event = value;
292
+ else if (field === "data") data.push(value);
293
+ }
294
+ frameLines = [];
295
+ if (data.length === 0) return;
296
+ const parsed = JSON.parse(data.join("\n"));
297
+ await onFrame({ ...id ? { id } : {}, ...event ? { event } : {}, data: parsed });
298
+ };
299
+ while (true) {
300
+ const { done, value } = await reader.read();
301
+ buffer += decoder.decode(value, { stream: !done });
302
+ let newlineIndex;
303
+ while ((newlineIndex = buffer.indexOf("\n")) !== -1) {
304
+ const line = buffer.slice(0, newlineIndex).replace(/\r$/, "");
305
+ buffer = buffer.slice(newlineIndex + 1);
306
+ if (line === "") await dispatch();
307
+ else frameLines.push(line);
308
+ }
309
+ if (done) break;
310
+ }
311
+ if (buffer) frameLines.push(buffer.replace(/\r$/, ""));
312
+ await dispatch();
313
+ }
314
+ function defaultSleep(milliseconds, signal) {
315
+ return new Promise((resolve, reject) => {
316
+ if (signal.aborted) {
317
+ reject(signal.reason ?? new Error("Aborted"));
318
+ return;
319
+ }
320
+ const onAbort = () => {
321
+ clearTimeout(timer);
322
+ reject(signal.reason ?? new Error("Aborted"));
323
+ };
324
+ const timer = setTimeout(() => {
325
+ signal.removeEventListener("abort", onAbort);
326
+ resolve();
327
+ }, milliseconds);
328
+ signal.addEventListener("abort", onAbort, { once: true });
329
+ });
330
+ }
331
+ async function defaultInvokeAction(action, payload, options) {
332
+ const client = await import("@mearl/client/local");
333
+ return client.invoke(action, payload, {
334
+ browser: options.browser,
335
+ timeoutSec: options.timeoutSec,
336
+ controlSource: "remote"
337
+ });
338
+ }
339
+ function toolInput(event) {
340
+ if (!isRecord(event.input) || typeof event.input.action !== "string") {
341
+ throw new Error("Qoder mearl tool input requires a string action");
342
+ }
343
+ const browser = typeof event.input.browser === "string" ? event.input.browser : void 0;
344
+ const timeoutSec = typeof event.input.timeoutSec === "number" && Number.isFinite(event.input.timeoutSec) ? event.input.timeoutSec : void 0;
345
+ const payloadValue = event.input.payload ?? event.input.data ?? {};
346
+ if (!isRecord(payloadValue)) {
347
+ throw new Error("Qoder mearl tool input payload must be an object");
348
+ }
349
+ return {
350
+ action: event.input.action,
351
+ payload: payloadValue,
352
+ ...browser ? { browser } : {},
353
+ ...timeoutSec === void 0 ? {} : { timeoutSec }
354
+ };
355
+ }
356
+ var QoderConnector = class {
357
+ constructor(options) {
358
+ this.options = options;
359
+ const token = options.token?.trim() || process.env.QODER_PERSONAL_ACCESS_TOKEN?.trim();
360
+ if (!token) {
361
+ throw new Error(
362
+ "Qoder authentication is required. Set QODER_PERSONAL_ACCESS_TOKEN and run the connector again."
363
+ );
364
+ }
365
+ this.api = new QoderApiClient(
366
+ token,
367
+ options.apiBaseUrl ?? DEFAULT_QODER_API_BASE_URL,
368
+ options.fetchImpl
369
+ );
370
+ this.now = options.now ?? Date.now;
371
+ this.sleep = options.sleep ?? defaultSleep;
372
+ this.invokeAction = options.invokeAction ?? defaultInvokeAction;
373
+ this.reconnectInterval = options.reconnectInterval ?? DEFAULT_RECONNECT_INTERVAL_MS;
374
+ this.maxReconnectAttempts = options.maxReconnectAttempts ?? -1;
375
+ }
376
+ api;
377
+ now;
378
+ sleep;
379
+ invokeAction;
380
+ reconnectInterval;
381
+ maxReconnectAttempts;
382
+ abortController = null;
383
+ reconnectAttempts = 0;
384
+ running = false;
385
+ connected = false;
386
+ sessionId = null;
387
+ lastEventId;
388
+ cachedResults = /* @__PURE__ */ new Map();
389
+ connect() {
390
+ if (this.running) return;
391
+ this.running = true;
392
+ this.abortController = new AbortController();
393
+ void this.run(this.abortController.signal);
394
+ }
395
+ disconnect() {
396
+ this.running = false;
397
+ this.abortController?.abort();
398
+ this.abortController = null;
399
+ }
400
+ async run(signal) {
401
+ while (!signal.aborted) {
402
+ try {
403
+ if (!this.sessionId) {
404
+ const pairing = await this.findPairing(signal);
405
+ await this.completePairing(pairing, signal);
406
+ }
407
+ const sessionId = this.sessionId;
408
+ await this.api.streamEvents(
409
+ sessionId,
410
+ this.lastEventId,
411
+ signal,
412
+ async (frame) => this.handleFrame(sessionId, frame, signal),
413
+ () => {
414
+ this.reconnectAttempts = 0;
415
+ }
416
+ );
417
+ if (!signal.aborted) throw new Error("Qoder event stream ended");
418
+ } catch (error) {
419
+ if (signal.aborted) return;
420
+ const message = error instanceof Error ? error.message : String(error);
421
+ if (!this.connected && this.options.failFast) {
422
+ this.options.onInitialConnectionFailed?.(message);
423
+ this.running = false;
424
+ return;
425
+ }
426
+ this.reconnectAttempts += 1;
427
+ if (this.maxReconnectAttempts !== -1 && this.reconnectAttempts > this.maxReconnectAttempts) {
428
+ console.error(
429
+ `[CloudConnector] Qoder max reconnect attempts (${this.maxReconnectAttempts}) reached`
430
+ );
431
+ this.running = false;
432
+ return;
433
+ }
434
+ console.error(`[CloudConnector] Qoder connection error: ${message}`);
435
+ try {
436
+ await this.sleep(this.reconnectInterval, signal);
437
+ } catch {
438
+ return;
439
+ }
440
+ }
441
+ }
442
+ }
443
+ async findPairing(signal) {
444
+ const createdAt = this.options.endpoint.createdAt ?? this.now();
445
+ const createdAfter = new Date(createdAt - DEFAULT_DISCOVERY_WINDOW_MS).toISOString();
446
+ const pairing = await this.api.findPairingRequest(
447
+ this.options.endpoint.pairingCode,
448
+ createdAfter,
449
+ signal
450
+ );
451
+ if (!pairing) {
452
+ throw new Error(
453
+ 'Qoder pairing request was not found. Ask the Agent to call the mearl tool with action "pair" and the code from this URL.'
454
+ );
455
+ }
456
+ return pairing;
457
+ }
458
+ async completePairing(pairing, signal) {
459
+ if (!this.connected) {
460
+ this.lastEventId = await this.api.sendCustomToolResult(
461
+ pairing.sessionId,
462
+ pairing.event.id,
463
+ [
464
+ {
465
+ type: "text",
466
+ text: safeJson({
467
+ connected: true,
468
+ connectorId: this.options.identity.connectorId,
469
+ name: this.options.identity.name
470
+ })
471
+ }
472
+ ],
473
+ false,
474
+ signal
475
+ ) ?? pairing.event.id;
476
+ this.sessionId = pairing.sessionId;
477
+ this.connected = true;
478
+ this.reconnectAttempts = 0;
479
+ this.options.onConnected?.();
480
+ console.log(`[CloudConnector] Connected to Qoder session ${pairing.sessionId}`);
481
+ }
482
+ }
483
+ async handleFrame(sessionId, frame, signal) {
484
+ this.reconnectAttempts = 0;
485
+ const event = frame.data;
486
+ const eventId = event.id ?? frame.id;
487
+ if (event.type !== "agent.custom_tool_use" || event.name !== QODER_TOOL_NAME || !eventId) {
488
+ if (eventId) this.lastEventId = eventId;
489
+ return;
490
+ }
491
+ const cached = this.cachedResults.get(eventId) ?? await this.executeTool(event);
492
+ this.rememberResult(eventId, cached);
493
+ try {
494
+ this.lastEventId = await this.api.sendCustomToolResult(
495
+ sessionId,
496
+ eventId,
497
+ cached.content,
498
+ cached.isError,
499
+ signal
500
+ ) ?? eventId;
501
+ } catch (error) {
502
+ if (error instanceof QoderApiError && error.status === 400 && cached.content !== cached.fallbackContent) {
503
+ this.lastEventId = await this.api.sendCustomToolResult(
504
+ sessionId,
505
+ eventId,
506
+ cached.fallbackContent,
507
+ cached.isError,
508
+ signal
509
+ ) ?? eventId;
510
+ return;
511
+ }
512
+ if (error instanceof QoderApiError && error.status === 404) {
513
+ this.lastEventId = eventId;
514
+ return;
515
+ }
516
+ throw error;
517
+ }
518
+ }
519
+ async executeTool(event) {
520
+ try {
521
+ const input = toolInput(event);
522
+ if (input.action === "pair") {
523
+ throw new Error("This pairing request does not match the active connector");
524
+ }
525
+ const result = await this.invokeAction(input.action, input.payload, {
526
+ browser: input.browser,
527
+ timeoutSec: input.timeoutSec ?? resolveActionTimeoutSec(input.action, input.payload, 15)
528
+ });
529
+ return { ...formatQoderToolResult(result), isError: false };
530
+ } catch (error) {
531
+ const message = error instanceof Error ? error.message : String(error);
532
+ const content = [{ type: "text", text: safeJson({ error: message }) }];
533
+ return { content, fallbackContent: content, isError: true };
534
+ }
535
+ }
536
+ rememberResult(eventId, result) {
537
+ this.cachedResults.set(eventId, result);
538
+ while (this.cachedResults.size > MAX_CACHED_RESULTS) {
539
+ const oldest = this.cachedResults.keys().next().value;
540
+ if (!oldest) break;
541
+ this.cachedResults.delete(oldest);
542
+ }
543
+ }
544
+ };
545
+
48
546
  // src/index.ts
49
- var CLOUD_CONNECTOR_VERSION = true ? "2.6.0" : "unknown";
547
+ var CLOUD_CONNECTOR_VERSION = true ? "2.7.0" : "unknown";
50
548
  var DEFAULT_RECONNECT_INTERVAL = 5e3;
51
549
  var BACKOFF_BASE_MS = 1e3;
52
550
  var BACKOFF_MAX_MS = 3e4;
@@ -54,7 +552,9 @@ var SLOW_PROBE_INTERVAL_MS = 6e4;
54
552
  var FAST_RECONNECT_ATTEMPTS = 5;
55
553
  var CloudConnector = class {
56
554
  options;
555
+ endpoint;
57
556
  identity;
557
+ qoderConnector = null;
58
558
  ws = null;
59
559
  heartbeatTimer = null;
60
560
  reconnectTimer = null;
@@ -67,8 +567,9 @@ var CloudConnector = class {
67
567
  hasConnected = false;
68
568
  lastConnectionError = null;
69
569
  constructor(options) {
570
+ this.endpoint = requireConnectorEndpoint(options.serverUrl);
70
571
  this.options = {
71
- serverUrl: options.serverUrl,
572
+ serverUrl: this.endpoint.serverUrl,
72
573
  heartbeatInterval: options.heartbeatInterval ?? DEFAULT_HEARTBEAT_INTERVAL,
73
574
  reconnectInterval: options.reconnectInterval ?? DEFAULT_RECONNECT_INTERVAL,
74
575
  maxReconnectAttempts: options.maxReconnectAttempts ?? -1,
@@ -79,10 +580,39 @@ var CloudConnector = class {
79
580
  this.identity = resolveConnectorIdentity(options);
80
581
  }
81
582
  connect() {
583
+ if (this.endpoint.scheme === "qoder") {
584
+ if (this.qoderConnector) {
585
+ this.qoderConnector.connect();
586
+ return;
587
+ }
588
+ try {
589
+ this.qoderConnector = new QoderConnector({
590
+ endpoint: this.endpoint,
591
+ identity: this.identity,
592
+ reconnectInterval: this.options.reconnectInterval,
593
+ maxReconnectAttempts: this.options.maxReconnectAttempts,
594
+ failFast: this.options.failFast,
595
+ onConnected: () => {
596
+ this.hasConnected = true;
597
+ this.options.onConnected?.(this.options.serverUrl, this.identity);
598
+ },
599
+ onInitialConnectionFailed: this.options.onInitialConnectionFailed
600
+ });
601
+ this.qoderConnector.connect();
602
+ } catch (error) {
603
+ const message = error instanceof Error ? error.message : String(error);
604
+ if (this.options.onInitialConnectionFailed) {
605
+ this.options.onInitialConnectionFailed(message);
606
+ } else {
607
+ console.error(`[CloudConnector] Qoder connection error: ${message}`);
608
+ }
609
+ }
610
+ return;
611
+ }
82
612
  if (this.ws && (this.ws.readyState === 0 || this.ws.readyState === 1)) {
83
613
  return;
84
614
  }
85
- let serverUrl = this.options.serverUrl;
615
+ let serverUrl = this.endpoint.transportUrl;
86
616
  if (this.shouldTryWss && serverUrl.startsWith("ws://")) {
87
617
  serverUrl = serverUrl.replace("ws://", "wss://");
88
618
  console.log(`[CloudConnector] Retrying with wss://: ${serverUrl}`);
@@ -133,6 +663,8 @@ var CloudConnector = class {
133
663
  }
134
664
  disconnect() {
135
665
  this.isManualClose = true;
666
+ this.qoderConnector?.disconnect();
667
+ this.qoderConnector = null;
136
668
  this.stopHeartbeat();
137
669
  if (this.reconnectTimer) {
138
670
  clearTimeout(this.reconnectTimer);
@@ -176,8 +708,8 @@ var CloudConnector = class {
176
708
  const client = await import("@mearl/client/local");
177
709
  const result = await client.invoke(action, data, {
178
710
  browser,
179
- timeoutSec: timeoutSec ?? resolveActionTimeoutSec(action, data, 15),
180
- controlSource: "cloud"
711
+ timeoutSec: timeoutSec ?? resolveActionTimeoutSec2(action, data, 15),
712
+ controlSource: "remote"
181
713
  });
182
714
  this.sendResponse({ id, success: true, data: result });
183
715
  } catch (error) {
@@ -360,16 +892,13 @@ function runForeground(options) {
360
892
  }
361
893
 
362
894
  // src/cli.ts
363
- var CLOUD_CONNECTOR_VERSION2 = true ? "2.6.0" : "unknown";
895
+ var CLOUD_CONNECTOR_VERSION2 = true ? "2.7.0" : "unknown";
364
896
  var args = process.argv.slice(2);
365
897
  if (args.includes("--version") || args.includes("-v")) {
366
898
  console.log(CLOUD_CONNECTOR_VERSION2);
367
899
  process.exit(0);
368
900
  }
369
901
  var SUBCOMMANDS = ["start", "stop", "restart", "status", "list", "logs"];
370
- function isWsUrl(value) {
371
- return !!value && (value.startsWith("ws://") || value.startsWith("wss://"));
372
- }
373
902
  function showHelp() {
374
903
  console.error(`mearl-cloud-connector v${CLOUD_CONNECTOR_VERSION2}
375
904
 
@@ -387,7 +916,7 @@ Commands:
387
916
  logs <server-url> Print the tail of a connector's log
388
917
 
389
918
  Arguments:
390
- server-url WebSocket server URL (ws://host:port or wss://host:port)
919
+ server-url Connector URL (ws://, wss://, or qoder://)
391
920
 
392
921
  Options:
393
922
  --foreground, -f Run in the foreground instead of daemonizing
@@ -404,6 +933,9 @@ Examples:
404
933
  # Run in the foreground (Ctrl+C to stop) — also how native-host launches it
405
934
  mearl-cloud-connector "ws://localhost:8080/ws?token=xxx"
406
935
 
936
+ # Complete a Qoder custom-tool pairing created by @mearl/setup
937
+ mearl-cloud-connector "qoder://pair/pairing-code-1234?created=1786723200000"
938
+
407
939
  # Start/stop a self-managed background connector with its own log file
408
940
  mearl-cloud-connector start "wss://cloud.example.com/ws?token=xxx"
409
941
  mearl-cloud-connector status
@@ -432,7 +964,7 @@ function parseConnectorOptions(rest) {
432
964
  return options;
433
965
  }
434
966
  function optionArgs(rest) {
435
- return rest.filter((arg) => !isWsUrl(arg) && arg !== "--foreground" && arg !== "-f");
967
+ return rest.filter((arg) => !isConnectorEndpoint(arg) && arg !== "--foreground" && arg !== "-f");
436
968
  }
437
969
  function exitHelp(message) {
438
970
  console.error(`Error: ${message}`);
@@ -455,9 +987,9 @@ async function main() {
455
987
  rest = args.slice(1);
456
988
  }
457
989
  const foregroundFlag = rest.includes("--foreground") || rest.includes("-f");
458
- const serverUrl = rest.find(isWsUrl);
990
+ const serverUrl = rest.find(isConnectorEndpoint);
459
991
  if (foregroundFlag || !command && serverUrl) {
460
- if (!serverUrl) exitHelp("server-url must start with ws:// or wss://");
992
+ if (!serverUrl) exitHelp("server-url must use ws://, wss://, or qoder://");
461
993
  const options = {
462
994
  serverUrl,
463
995
  ...parseConnectorOptions(optionArgs(rest))
@@ -0,0 +1,20 @@
1
+ export type ConnectorEndpointScheme = 'ws' | 'wss' | 'qoder';
2
+ export interface WebSocketConnectorEndpoint {
3
+ /** User-facing URL retained for daemon identity and lifecycle commands. */
4
+ serverUrl: string;
5
+ /** WebSocket URL used for the network connection. */
6
+ transportUrl: string;
7
+ scheme: 'ws' | 'wss';
8
+ }
9
+ export interface QoderConnectorEndpoint {
10
+ /** User-facing URL retained for daemon identity and lifecycle commands. */
11
+ serverUrl: string;
12
+ scheme: 'qoder';
13
+ pairingCode: string;
14
+ createdAt?: number;
15
+ }
16
+ export type ConnectorEndpoint = WebSocketConnectorEndpoint | QoderConnectorEndpoint;
17
+ /** Parse a connector endpoint without changing its user-facing daemon identity. */
18
+ export declare function parseConnectorEndpoint(value: string | undefined): ConnectorEndpoint | null;
19
+ export declare function isConnectorEndpoint(value: string | undefined): value is string;
20
+ export declare function requireConnectorEndpoint(value: string): ConnectorEndpoint;
package/dist/index.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import { type ConnectorIdentity } from './identity.js';
2
+ export { isConnectorEndpoint, parseConnectorEndpoint, requireConnectorEndpoint, type ConnectorEndpoint, type ConnectorEndpointScheme, type QoderConnectorEndpoint, type WebSocketConnectorEndpoint, } from './endpoint.js';
3
+ export { DEFAULT_QODER_API_BASE_URL, QODER_TOOL_NAME, QoderApiClient, QoderApiError, QoderConnector, formatQoderToolResult, parseQoderSse, type QoderContentBlock, type QoderPairingRequest, type QoderPublicEvent, type QoderSseFrame, } from './qoder.js';
2
4
  export interface CloudConnectorOptions {
3
5
  serverUrl: string;
4
6
  heartbeatInterval?: number;
@@ -9,7 +11,7 @@ export interface CloudConnectorOptions {
9
11
  connectorName?: string;
10
12
  onInitialConnectionFailed?: (message: string) => void;
11
13
  /**
12
- * Fired every time the WebSocket connection is (re)established. Used by the
14
+ * Fired every time the transport connection is (re)established. Used by the
13
15
  * foreground runner to (re)write this connector's registry record once it is
14
16
  * actually connected — the signal other managers use to discover/adopt it.
15
17
  */
@@ -17,7 +19,9 @@ export interface CloudConnectorOptions {
17
19
  }
18
20
  export declare class CloudConnector {
19
21
  private options;
22
+ private endpoint;
20
23
  private identity;
24
+ private qoderConnector;
21
25
  private ws;
22
26
  private heartbeatTimer;
23
27
  private reconnectTimer;