@mearl/cloud-connector 3.0.0-beta.4 → 3.0.0-beta.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -37
- package/dist/chunks/chunk-DAMMLS2C.js +379 -0
- package/dist/cli.js +5 -5
- package/dist/contracts.d.ts +2 -0
- package/dist/contracts.js +0 -0
- package/dist/endpoint.d.ts +6 -14
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -15
- package/dist/plugins.d.ts +17 -0
- package/package.json +12 -9
- package/dist/chunks/chunk-W7HPTSMK.js +0 -1000
- package/dist/qoder-auth.d.ts +0 -12
- package/dist/qoder.d.ts +0 -108
|
@@ -1,1000 +0,0 @@
|
|
|
1
|
-
// src/index.ts
|
|
2
|
-
import WebSocket from "ws";
|
|
3
|
-
import {
|
|
4
|
-
isHeartbeatMessage,
|
|
5
|
-
MAX_BUFFER_SIZE,
|
|
6
|
-
DEFAULT_HEARTBEAT_INTERVAL
|
|
7
|
-
} from "@mearl/cloud-types";
|
|
8
|
-
import { resolveActionTimeoutSec as resolveActionTimeoutSec2 } from "@mearl/client/action-timeouts";
|
|
9
|
-
|
|
10
|
-
// src/identity.ts
|
|
11
|
-
import { hostname } from "node:os";
|
|
12
|
-
import { randomUUID } from "node:crypto";
|
|
13
|
-
import { join } from "node:path";
|
|
14
|
-
import { DAEMON_HOME, readRecord, writeRecord } from "@mearl/daemon-core";
|
|
15
|
-
var IDENTITY_FILE = join(DAEMON_HOME, "cloud-connector-identity.json");
|
|
16
|
-
function resolveConnectorIdentity(options) {
|
|
17
|
-
const explicitId = options.connectorId?.trim() || process.env.MEARL_CONNECTOR_ID?.trim();
|
|
18
|
-
const explicitName = options.connectorName?.trim() || process.env.MEARL_CONNECTOR_NAME?.trim();
|
|
19
|
-
const stored = readRecord(IDENTITY_FILE);
|
|
20
|
-
const connectorId = explicitId || stored?.connectorId || randomUUID();
|
|
21
|
-
if (!explicitId && !stored?.connectorId) {
|
|
22
|
-
try {
|
|
23
|
-
writeRecord(IDENTITY_FILE, { pid: process.pid, connectorId });
|
|
24
|
-
} catch {
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
|
-
const name = explicitName || hostname() || `connector-${connectorId.slice(0, 8)}`;
|
|
28
|
-
if (!/^[A-Za-z0-9._:-]{1,128}$/.test(connectorId)) {
|
|
29
|
-
throw new Error('connectorId must contain only letters, numbers, ".", "_", ":", or "-"');
|
|
30
|
-
}
|
|
31
|
-
if (name.length > 128 || new RegExp("\\p{Cc}", "u").test(name)) {
|
|
32
|
-
throw new Error("connectorName must be 1-128 characters without control characters");
|
|
33
|
-
}
|
|
34
|
-
return { connectorId, name };
|
|
35
|
-
}
|
|
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 = "ai.mearl.qoder.pat";
|
|
102
|
-
function qoderAuthenticationHint(platform = process.platform) {
|
|
103
|
-
const lines = [
|
|
104
|
-
"Configure QODER_PERSONAL_ACCESS_TOKEN on the browser machine, then restart the connector.",
|
|
105
|
-
"Lookup order: process environment > MEARL_ENV_FILE > ~/.mearl/.env" + (platform === "darwin" ? ` > macOS Keychain (${QODER_KEYCHAIN_SERVICE}).` : ".")
|
|
106
|
-
];
|
|
107
|
-
if (platform === "darwin") {
|
|
108
|
-
lines.push(
|
|
109
|
-
`Enter the PAT interactively in a local terminal: security add-generic-password -U -a "$USER" -s ${QODER_KEYCHAIN_SERVICE} -w`
|
|
110
|
-
);
|
|
111
|
-
}
|
|
112
|
-
lines.push("Keep the PAT out of pairing URLs, chat messages and logs.");
|
|
113
|
-
return lines.join("\n");
|
|
114
|
-
}
|
|
115
|
-
function normalizeToken(value) {
|
|
116
|
-
const token = value?.trim();
|
|
117
|
-
if (!token || /[\r\n\0]/.test(token)) return void 0;
|
|
118
|
-
return token;
|
|
119
|
-
}
|
|
120
|
-
function envValue(text, key) {
|
|
121
|
-
for (const line of text.split(/\r?\n/)) {
|
|
122
|
-
const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$/.exec(line);
|
|
123
|
-
if (!match || match[1] !== key) continue;
|
|
124
|
-
let value = (match[2] ?? "").trim();
|
|
125
|
-
if (value.length >= 2 && (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'"))) {
|
|
126
|
-
value = value.slice(1, -1);
|
|
127
|
-
} else {
|
|
128
|
-
value = value.replace(/\s+#.*$/, "").trim();
|
|
129
|
-
}
|
|
130
|
-
return normalizeToken(value);
|
|
131
|
-
}
|
|
132
|
-
return void 0;
|
|
133
|
-
}
|
|
134
|
-
function readMacKeychainToken() {
|
|
135
|
-
const securityPath = "/usr/bin/security";
|
|
136
|
-
if (!existsSync(securityPath)) return void 0;
|
|
137
|
-
try {
|
|
138
|
-
const account = userInfo().username;
|
|
139
|
-
const result = spawnSync(
|
|
140
|
-
securityPath,
|
|
141
|
-
["find-generic-password", "-a", account, "-s", QODER_KEYCHAIN_SERVICE, "-w"],
|
|
142
|
-
{
|
|
143
|
-
encoding: "utf8",
|
|
144
|
-
stdio: ["ignore", "pipe", "ignore"],
|
|
145
|
-
timeout: 5e3,
|
|
146
|
-
windowsHide: true
|
|
147
|
-
}
|
|
148
|
-
);
|
|
149
|
-
return result.status === 0 ? normalizeToken(result.stdout) : void 0;
|
|
150
|
-
} catch {
|
|
151
|
-
return void 0;
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
function resolveQoderPersonalAccessToken(options = {}) {
|
|
155
|
-
const direct = normalizeToken(options.token);
|
|
156
|
-
if (direct) return direct;
|
|
157
|
-
const env = options.env ?? process.env;
|
|
158
|
-
const inherited = normalizeToken(env[QODER_TOKEN_KEY]);
|
|
159
|
-
if (inherited) return inherited;
|
|
160
|
-
const homeDirectory = options.homeDirectory ?? homedir();
|
|
161
|
-
const envFiles = [
|
|
162
|
-
...env.MEARL_ENV_FILE?.trim() ? [resolve(env.MEARL_ENV_FILE)] : [],
|
|
163
|
-
resolve(homeDirectory, ".mearl", ".env")
|
|
164
|
-
];
|
|
165
|
-
const readFile = options.readFile ?? ((file) => readFileSync(file, "utf8"));
|
|
166
|
-
for (const file of new Set(envFiles)) {
|
|
167
|
-
try {
|
|
168
|
-
const token = envValue(readFile(file), QODER_TOKEN_KEY);
|
|
169
|
-
if (token) return token;
|
|
170
|
-
} catch {
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
if ((options.platform ?? process.platform) !== "darwin") return void 0;
|
|
174
|
-
return normalizeToken((options.readKeychainToken ?? readMacKeychainToken)());
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
// src/qoder.ts
|
|
178
|
-
var QODER_TOOL_NAME = "mearl";
|
|
179
|
-
var DEFAULT_QODER_API_BASE_URL = "https://api.qoder.com";
|
|
180
|
-
var DEFAULT_DISCOVERY_WINDOW_MS = 60 * 60 * 1e3;
|
|
181
|
-
var DEFAULT_RECONNECT_INTERVAL_MS = 5e3;
|
|
182
|
-
var MAX_RECENT_SESSIONS = 100;
|
|
183
|
-
var MAX_RECENT_TOOL_EVENTS = 20;
|
|
184
|
-
var MAX_CACHED_RESULTS = 100;
|
|
185
|
-
var QoderApiError = class extends Error {
|
|
186
|
-
constructor(message, status) {
|
|
187
|
-
super(message);
|
|
188
|
-
this.status = status;
|
|
189
|
-
this.name = "QoderApiError";
|
|
190
|
-
}
|
|
191
|
-
status;
|
|
192
|
-
};
|
|
193
|
-
var QoderPairingExpiredError = class extends Error {
|
|
194
|
-
constructor() {
|
|
195
|
-
super(
|
|
196
|
-
'Qoder pairing is no longer pending. Generate a new pairing URL with `npx --@mearl:registry=https://registry.npmjs.org @mearl/setup --qoder-cloud --yes`, run the new connector command, and immediately invoke the mearl tool with action "pair". Do not reuse this URL.'
|
|
197
|
-
);
|
|
198
|
-
this.name = "QoderPairingExpiredError";
|
|
199
|
-
}
|
|
200
|
-
};
|
|
201
|
-
function isPendingActionNotFound(error) {
|
|
202
|
-
return error instanceof QoderApiError && /^Pending action\b.*\bwas not found\.?$/i.test(error.message.trim());
|
|
203
|
-
}
|
|
204
|
-
function safeJson(value) {
|
|
205
|
-
try {
|
|
206
|
-
return JSON.stringify(value ?? null);
|
|
207
|
-
} catch {
|
|
208
|
-
return JSON.stringify({ error: "Mearl returned a value that cannot be serialized" });
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
function isRecord(value) {
|
|
212
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
213
|
-
}
|
|
214
|
-
function asScreenshot(value) {
|
|
215
|
-
if (!isRecord(value) || typeof value.data !== "string" || !isRecord(value.meta)) return null;
|
|
216
|
-
const format = value.meta.format;
|
|
217
|
-
if (format !== "png" && format !== "jpeg") return null;
|
|
218
|
-
return { data: value.data, meta: { ...value.meta, format } };
|
|
219
|
-
}
|
|
220
|
-
function extractBatchScreenshots(value) {
|
|
221
|
-
if (!isRecord(value) || !Array.isArray(value.results)) return null;
|
|
222
|
-
const screenshots = [];
|
|
223
|
-
const results = value.results.map((result) => {
|
|
224
|
-
if (!isRecord(result) || result.action !== "page_screenshot") return result;
|
|
225
|
-
const screenshot = asScreenshot(result.data);
|
|
226
|
-
if (!screenshot) return result;
|
|
227
|
-
const data = { ...result.data };
|
|
228
|
-
delete data.data;
|
|
229
|
-
data.meta = screenshot.meta;
|
|
230
|
-
data.imageContentIndex = screenshots.length + 1;
|
|
231
|
-
screenshots.push(screenshot);
|
|
232
|
-
return { ...result, data };
|
|
233
|
-
});
|
|
234
|
-
if (screenshots.length === 0) return null;
|
|
235
|
-
return { metadata: { ...value, results }, screenshots };
|
|
236
|
-
}
|
|
237
|
-
function imageContentBlock(screenshot) {
|
|
238
|
-
return {
|
|
239
|
-
type: "image",
|
|
240
|
-
source: {
|
|
241
|
-
type: "base64",
|
|
242
|
-
media_type: `image/${screenshot.meta.format}`,
|
|
243
|
-
data: screenshot.data
|
|
244
|
-
}
|
|
245
|
-
};
|
|
246
|
-
}
|
|
247
|
-
function formatQoderToolResult(value) {
|
|
248
|
-
const directScreenshot = asScreenshot(value);
|
|
249
|
-
const nestedScreenshot = !directScreenshot && isRecord(value) ? asScreenshot(value.screenshot) : null;
|
|
250
|
-
const screenshot = directScreenshot ?? nestedScreenshot;
|
|
251
|
-
if (!screenshot) {
|
|
252
|
-
const batch = extractBatchScreenshots(value);
|
|
253
|
-
if (batch) {
|
|
254
|
-
return {
|
|
255
|
-
content: [
|
|
256
|
-
{ type: "text", text: safeJson(batch.metadata) },
|
|
257
|
-
...batch.screenshots.map(imageContentBlock)
|
|
258
|
-
],
|
|
259
|
-
fallbackContent: [{ type: "text", text: safeJson(value) }]
|
|
260
|
-
};
|
|
261
|
-
}
|
|
262
|
-
}
|
|
263
|
-
if (!screenshot) {
|
|
264
|
-
const content = [{ type: "text", text: safeJson(value) }];
|
|
265
|
-
return { content, fallbackContent: content };
|
|
266
|
-
}
|
|
267
|
-
let metadata;
|
|
268
|
-
if (directScreenshot) {
|
|
269
|
-
metadata = { meta: screenshot.meta };
|
|
270
|
-
} else {
|
|
271
|
-
metadata = { ...value, screenshot: { meta: screenshot.meta } };
|
|
272
|
-
}
|
|
273
|
-
return {
|
|
274
|
-
content: [{ type: "text", text: safeJson(metadata) }, imageContentBlock(screenshot)],
|
|
275
|
-
fallbackContent: [{ type: "text", text: safeJson(value) }]
|
|
276
|
-
};
|
|
277
|
-
}
|
|
278
|
-
function pairingCodeFromEvent(event) {
|
|
279
|
-
if (event.type !== "agent.custom_tool_use" || event.name !== QODER_TOOL_NAME) return null;
|
|
280
|
-
if (!isRecord(event.input) || event.input.action !== "pair") return null;
|
|
281
|
-
const payload = isRecord(event.input.payload) ? event.input.payload : isRecord(event.input.data) ? event.input.data : null;
|
|
282
|
-
return payload && typeof payload.code === "string" ? payload.code : null;
|
|
283
|
-
}
|
|
284
|
-
function qoderErrorMessage(status, body) {
|
|
285
|
-
try {
|
|
286
|
-
const parsed = JSON.parse(body);
|
|
287
|
-
const message = parsed.error?.message ?? parsed.message;
|
|
288
|
-
if (typeof message === "string" && message.trim()) return message.trim();
|
|
289
|
-
} catch {
|
|
290
|
-
}
|
|
291
|
-
return `Qoder API request failed with HTTP ${status}`;
|
|
292
|
-
}
|
|
293
|
-
var QoderApiClient = class {
|
|
294
|
-
constructor(token, baseUrl = DEFAULT_QODER_API_BASE_URL, fetchImpl = fetch) {
|
|
295
|
-
this.token = token;
|
|
296
|
-
this.fetchImpl = fetchImpl;
|
|
297
|
-
const parsed = new URL(baseUrl);
|
|
298
|
-
if (parsed.protocol !== "https:" && parsed.hostname !== "localhost" && parsed.hostname !== "127.0.0.1") {
|
|
299
|
-
throw new Error("Qoder API base URL must use https:// (localhost may use http:// for tests)");
|
|
300
|
-
}
|
|
301
|
-
this.baseUrl = parsed.toString().replace(/\/$/, "");
|
|
302
|
-
}
|
|
303
|
-
token;
|
|
304
|
-
fetchImpl;
|
|
305
|
-
baseUrl;
|
|
306
|
-
async request(path, init = {}) {
|
|
307
|
-
const response = await this.fetchImpl(`${this.baseUrl}${path}`, {
|
|
308
|
-
...init,
|
|
309
|
-
headers: {
|
|
310
|
-
Authorization: `Bearer ${this.token}`,
|
|
311
|
-
...init.headers
|
|
312
|
-
}
|
|
313
|
-
});
|
|
314
|
-
if (!response.ok) {
|
|
315
|
-
const body = await response.text();
|
|
316
|
-
const message = qoderErrorMessage(response.status, body);
|
|
317
|
-
throw new QoderApiError(
|
|
318
|
-
response.status === 401 ? `${message}
|
|
319
|
-
${qoderAuthenticationHint()}` : message,
|
|
320
|
-
response.status
|
|
321
|
-
);
|
|
322
|
-
}
|
|
323
|
-
return response;
|
|
324
|
-
}
|
|
325
|
-
async listSessions(createdAfter, signal) {
|
|
326
|
-
const query = new URLSearchParams({
|
|
327
|
-
limit: String(MAX_RECENT_SESSIONS),
|
|
328
|
-
order: "desc",
|
|
329
|
-
"created_at[gte]": createdAfter
|
|
330
|
-
});
|
|
331
|
-
const response = await this.request(`/api/v1/cloud/sessions?${query}`, { signal });
|
|
332
|
-
const body = await response.json();
|
|
333
|
-
return Array.isArray(body.data) ? body.data.filter((session) => typeof session.id === "string") : [];
|
|
334
|
-
}
|
|
335
|
-
async listCustomToolEvents(sessionId, createdAfter, signal) {
|
|
336
|
-
const query = new URLSearchParams({
|
|
337
|
-
limit: String(MAX_RECENT_TOOL_EVENTS),
|
|
338
|
-
order: "desc",
|
|
339
|
-
types: "agent.custom_tool_use",
|
|
340
|
-
"created_at[gte]": createdAfter
|
|
341
|
-
});
|
|
342
|
-
const response = await this.request(
|
|
343
|
-
`/api/v1/cloud/sessions/${encodeURIComponent(sessionId)}/events?${query}`,
|
|
344
|
-
{ signal }
|
|
345
|
-
);
|
|
346
|
-
const body = await response.json();
|
|
347
|
-
return Array.isArray(body.data) ? body.data : [];
|
|
348
|
-
}
|
|
349
|
-
async findPairingRequest(pairingCode, createdAfter, signal) {
|
|
350
|
-
const sessions = await this.listSessions(createdAfter, signal);
|
|
351
|
-
for (const session of sessions) {
|
|
352
|
-
const events = await this.listCustomToolEvents(session.id, createdAfter, signal);
|
|
353
|
-
const event = events.find((candidate) => pairingCodeFromEvent(candidate) === pairingCode);
|
|
354
|
-
if (event?.id) return { sessionId: session.id, event: { ...event, id: event.id } };
|
|
355
|
-
}
|
|
356
|
-
return null;
|
|
357
|
-
}
|
|
358
|
-
async sendCustomToolResult(sessionId, customToolUseId, content, isError = false, signal) {
|
|
359
|
-
const response = await this.request(
|
|
360
|
-
`/api/v1/cloud/sessions/${encodeURIComponent(sessionId)}/events`,
|
|
361
|
-
{
|
|
362
|
-
method: "POST",
|
|
363
|
-
headers: { "Content-Type": "application/json" },
|
|
364
|
-
signal,
|
|
365
|
-
body: JSON.stringify({
|
|
366
|
-
events: [
|
|
367
|
-
{
|
|
368
|
-
type: "user.custom_tool_result",
|
|
369
|
-
custom_tool_use_id: customToolUseId,
|
|
370
|
-
content,
|
|
371
|
-
is_error: isError
|
|
372
|
-
}
|
|
373
|
-
]
|
|
374
|
-
})
|
|
375
|
-
}
|
|
376
|
-
);
|
|
377
|
-
const body = await response.json();
|
|
378
|
-
return body.data?.[0]?.id;
|
|
379
|
-
}
|
|
380
|
-
async streamEvents(sessionId, lastEventId, signal, onFrame, onOpen) {
|
|
381
|
-
const response = await this.request(
|
|
382
|
-
`/api/v1/cloud/sessions/${encodeURIComponent(sessionId)}/events/stream`,
|
|
383
|
-
{
|
|
384
|
-
headers: {
|
|
385
|
-
Accept: "text/event-stream",
|
|
386
|
-
...lastEventId ? { "Last-Event-ID": lastEventId } : {}
|
|
387
|
-
},
|
|
388
|
-
signal
|
|
389
|
-
}
|
|
390
|
-
);
|
|
391
|
-
if (!response.body) throw new Error("Qoder event stream returned no response body");
|
|
392
|
-
onOpen?.();
|
|
393
|
-
await parseQoderSse(response.body, onFrame);
|
|
394
|
-
}
|
|
395
|
-
};
|
|
396
|
-
async function parseQoderSse(body, onFrame) {
|
|
397
|
-
const reader = body.getReader();
|
|
398
|
-
const decoder = new TextDecoder();
|
|
399
|
-
let buffer = "";
|
|
400
|
-
let frameLines = [];
|
|
401
|
-
const dispatch = async () => {
|
|
402
|
-
if (frameLines.length === 0) return;
|
|
403
|
-
let id;
|
|
404
|
-
let event;
|
|
405
|
-
const data = [];
|
|
406
|
-
for (const line of frameLines) {
|
|
407
|
-
if (!line || line.startsWith(":")) continue;
|
|
408
|
-
const separator = line.indexOf(":");
|
|
409
|
-
const field = separator === -1 ? line : line.slice(0, separator);
|
|
410
|
-
const value = separator === -1 ? "" : line.slice(separator + 1).replace(/^ /, "");
|
|
411
|
-
if (field === "id") id = value;
|
|
412
|
-
else if (field === "event") event = value;
|
|
413
|
-
else if (field === "data") data.push(value);
|
|
414
|
-
}
|
|
415
|
-
frameLines = [];
|
|
416
|
-
if (data.length === 0) return;
|
|
417
|
-
const parsed = JSON.parse(data.join("\n"));
|
|
418
|
-
await onFrame({ ...id ? { id } : {}, ...event ? { event } : {}, data: parsed });
|
|
419
|
-
};
|
|
420
|
-
while (true) {
|
|
421
|
-
const { done, value } = await reader.read();
|
|
422
|
-
buffer += decoder.decode(value, { stream: !done });
|
|
423
|
-
let newlineIndex;
|
|
424
|
-
while ((newlineIndex = buffer.indexOf("\n")) !== -1) {
|
|
425
|
-
const line = buffer.slice(0, newlineIndex).replace(/\r$/, "");
|
|
426
|
-
buffer = buffer.slice(newlineIndex + 1);
|
|
427
|
-
if (line === "") await dispatch();
|
|
428
|
-
else frameLines.push(line);
|
|
429
|
-
}
|
|
430
|
-
if (done) break;
|
|
431
|
-
}
|
|
432
|
-
if (buffer) frameLines.push(buffer.replace(/\r$/, ""));
|
|
433
|
-
await dispatch();
|
|
434
|
-
}
|
|
435
|
-
function defaultSleep(milliseconds, signal) {
|
|
436
|
-
return new Promise((resolve2, reject) => {
|
|
437
|
-
if (signal.aborted) {
|
|
438
|
-
reject(signal.reason ?? new Error("Aborted"));
|
|
439
|
-
return;
|
|
440
|
-
}
|
|
441
|
-
const onAbort = () => {
|
|
442
|
-
clearTimeout(timer);
|
|
443
|
-
reject(signal.reason ?? new Error("Aborted"));
|
|
444
|
-
};
|
|
445
|
-
const timer = setTimeout(() => {
|
|
446
|
-
signal.removeEventListener("abort", onAbort);
|
|
447
|
-
resolve2();
|
|
448
|
-
}, milliseconds);
|
|
449
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
450
|
-
});
|
|
451
|
-
}
|
|
452
|
-
async function defaultInvokeAction(action, payload, options) {
|
|
453
|
-
const client = await import("@mearl/client/local");
|
|
454
|
-
return client.invoke(action, payload, {
|
|
455
|
-
browser: options.browser,
|
|
456
|
-
timeoutSec: options.timeoutSec,
|
|
457
|
-
controlSource: "remote"
|
|
458
|
-
});
|
|
459
|
-
}
|
|
460
|
-
function toolInput(event) {
|
|
461
|
-
if (!isRecord(event.input) || typeof event.input.action !== "string") {
|
|
462
|
-
throw new Error("Qoder mearl tool input requires a string action");
|
|
463
|
-
}
|
|
464
|
-
const browser = typeof event.input.browser === "string" ? event.input.browser : void 0;
|
|
465
|
-
const timeoutSec = typeof event.input.timeoutSec === "number" && Number.isFinite(event.input.timeoutSec) ? event.input.timeoutSec : void 0;
|
|
466
|
-
const payloadValue = event.input.payload ?? event.input.data ?? {};
|
|
467
|
-
if (!isRecord(payloadValue)) {
|
|
468
|
-
throw new Error("Qoder mearl tool input payload must be an object");
|
|
469
|
-
}
|
|
470
|
-
return {
|
|
471
|
-
action: event.input.action,
|
|
472
|
-
payload: payloadValue,
|
|
473
|
-
...browser ? { browser } : {},
|
|
474
|
-
...timeoutSec === void 0 ? {} : { timeoutSec }
|
|
475
|
-
};
|
|
476
|
-
}
|
|
477
|
-
var QoderConnector = class {
|
|
478
|
-
constructor(options) {
|
|
479
|
-
this.options = options;
|
|
480
|
-
const token = resolveQoderPersonalAccessToken({ token: options.token });
|
|
481
|
-
if (!token) {
|
|
482
|
-
throw new Error(`Qoder authentication is required.
|
|
483
|
-
${qoderAuthenticationHint()}`);
|
|
484
|
-
}
|
|
485
|
-
this.api = new QoderApiClient(
|
|
486
|
-
token,
|
|
487
|
-
options.apiBaseUrl ?? DEFAULT_QODER_API_BASE_URL,
|
|
488
|
-
options.fetchImpl
|
|
489
|
-
);
|
|
490
|
-
this.now = options.now ?? Date.now;
|
|
491
|
-
this.sleep = options.sleep ?? defaultSleep;
|
|
492
|
-
this.invokeAction = options.invokeAction ?? defaultInvokeAction;
|
|
493
|
-
this.reconnectInterval = options.reconnectInterval ?? DEFAULT_RECONNECT_INTERVAL_MS;
|
|
494
|
-
this.maxReconnectAttempts = options.maxReconnectAttempts ?? -1;
|
|
495
|
-
}
|
|
496
|
-
options;
|
|
497
|
-
api;
|
|
498
|
-
now;
|
|
499
|
-
sleep;
|
|
500
|
-
invokeAction;
|
|
501
|
-
reconnectInterval;
|
|
502
|
-
maxReconnectAttempts;
|
|
503
|
-
abortController = null;
|
|
504
|
-
reconnectAttempts = 0;
|
|
505
|
-
running = false;
|
|
506
|
-
connected = false;
|
|
507
|
-
sessionId = null;
|
|
508
|
-
lastEventId;
|
|
509
|
-
cachedResults = /* @__PURE__ */ new Map();
|
|
510
|
-
connect() {
|
|
511
|
-
if (this.running) return;
|
|
512
|
-
this.running = true;
|
|
513
|
-
this.options.onStateChange?.({ state: "connecting" });
|
|
514
|
-
this.abortController = new AbortController();
|
|
515
|
-
void this.run(this.abortController.signal);
|
|
516
|
-
}
|
|
517
|
-
disconnect() {
|
|
518
|
-
this.running = false;
|
|
519
|
-
this.abortController?.abort();
|
|
520
|
-
this.abortController = null;
|
|
521
|
-
}
|
|
522
|
-
async run(signal) {
|
|
523
|
-
while (!signal.aborted) {
|
|
524
|
-
try {
|
|
525
|
-
if (!this.sessionId) {
|
|
526
|
-
const pairing = await this.findPairing(signal);
|
|
527
|
-
await this.completePairing(pairing, signal);
|
|
528
|
-
}
|
|
529
|
-
const sessionId = this.sessionId;
|
|
530
|
-
await this.api.streamEvents(
|
|
531
|
-
sessionId,
|
|
532
|
-
this.lastEventId,
|
|
533
|
-
signal,
|
|
534
|
-
async (frame) => this.handleFrame(sessionId, frame, signal),
|
|
535
|
-
() => {
|
|
536
|
-
this.reconnectAttempts = 0;
|
|
537
|
-
this.options.onStateChange?.({ state: "connected" });
|
|
538
|
-
}
|
|
539
|
-
);
|
|
540
|
-
if (!signal.aborted) throw new Error("Qoder event stream ended");
|
|
541
|
-
} catch (error) {
|
|
542
|
-
if (signal.aborted) return;
|
|
543
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
544
|
-
if (!this.connected && error instanceof QoderPairingExpiredError) {
|
|
545
|
-
this.running = false;
|
|
546
|
-
this.options.onStateChange?.({ state: "failed", reason: message });
|
|
547
|
-
if (this.options.onInitialConnectionFailed) {
|
|
548
|
-
this.options.onInitialConnectionFailed(message);
|
|
549
|
-
} else {
|
|
550
|
-
console.error(`[CloudConnector] Qoder connection error: ${message}`);
|
|
551
|
-
}
|
|
552
|
-
return;
|
|
553
|
-
}
|
|
554
|
-
if (!this.connected && this.options.failFast) {
|
|
555
|
-
this.options.onStateChange?.({ state: "failed", reason: message });
|
|
556
|
-
this.options.onInitialConnectionFailed?.(message);
|
|
557
|
-
this.running = false;
|
|
558
|
-
return;
|
|
559
|
-
}
|
|
560
|
-
this.reconnectAttempts += 1;
|
|
561
|
-
if (this.maxReconnectAttempts !== -1 && this.reconnectAttempts > this.maxReconnectAttempts) {
|
|
562
|
-
console.error(
|
|
563
|
-
`[CloudConnector] Qoder max reconnect attempts (${this.maxReconnectAttempts}) reached`
|
|
564
|
-
);
|
|
565
|
-
this.options.onStateChange?.({
|
|
566
|
-
state: "failed",
|
|
567
|
-
reason: message,
|
|
568
|
-
reconnectAttempt: this.reconnectAttempts
|
|
569
|
-
});
|
|
570
|
-
this.running = false;
|
|
571
|
-
return;
|
|
572
|
-
}
|
|
573
|
-
console.error(`[CloudConnector] Qoder connection error: ${message}`);
|
|
574
|
-
this.options.onStateChange?.({
|
|
575
|
-
state: "reconnecting",
|
|
576
|
-
reason: message,
|
|
577
|
-
reconnectAttempt: this.reconnectAttempts,
|
|
578
|
-
retryInMs: this.reconnectInterval
|
|
579
|
-
});
|
|
580
|
-
try {
|
|
581
|
-
await this.sleep(this.reconnectInterval, signal);
|
|
582
|
-
} catch {
|
|
583
|
-
return;
|
|
584
|
-
}
|
|
585
|
-
}
|
|
586
|
-
}
|
|
587
|
-
}
|
|
588
|
-
async findPairing(signal) {
|
|
589
|
-
const createdAt = this.options.endpoint.createdAt ?? this.now();
|
|
590
|
-
const createdAfter = new Date(createdAt - DEFAULT_DISCOVERY_WINDOW_MS).toISOString();
|
|
591
|
-
const pairing = await this.api.findPairingRequest(
|
|
592
|
-
this.options.endpoint.pairingCode,
|
|
593
|
-
createdAfter,
|
|
594
|
-
signal
|
|
595
|
-
);
|
|
596
|
-
if (!pairing) {
|
|
597
|
-
throw new Error(
|
|
598
|
-
'Qoder pairing request was not found. Ask the Agent to call the mearl tool with action "pair" and the code from this URL.'
|
|
599
|
-
);
|
|
600
|
-
}
|
|
601
|
-
return pairing;
|
|
602
|
-
}
|
|
603
|
-
async completePairing(pairing, signal) {
|
|
604
|
-
if (!this.connected) {
|
|
605
|
-
let resultEventId;
|
|
606
|
-
try {
|
|
607
|
-
resultEventId = await this.api.sendCustomToolResult(
|
|
608
|
-
pairing.sessionId,
|
|
609
|
-
pairing.event.id,
|
|
610
|
-
[
|
|
611
|
-
{
|
|
612
|
-
type: "text",
|
|
613
|
-
text: safeJson({
|
|
614
|
-
connected: true,
|
|
615
|
-
connectorId: this.options.identity.connectorId,
|
|
616
|
-
name: this.options.identity.name
|
|
617
|
-
})
|
|
618
|
-
}
|
|
619
|
-
],
|
|
620
|
-
false,
|
|
621
|
-
signal
|
|
622
|
-
);
|
|
623
|
-
} catch (error) {
|
|
624
|
-
if (isPendingActionNotFound(error)) throw new QoderPairingExpiredError();
|
|
625
|
-
throw error;
|
|
626
|
-
}
|
|
627
|
-
this.lastEventId = resultEventId ?? pairing.event.id;
|
|
628
|
-
this.sessionId = pairing.sessionId;
|
|
629
|
-
this.connected = true;
|
|
630
|
-
this.reconnectAttempts = 0;
|
|
631
|
-
this.options.onStateChange?.({ state: "connected" });
|
|
632
|
-
this.options.onConnected?.();
|
|
633
|
-
console.log(`[CloudConnector] Connected to Qoder session ${pairing.sessionId}`);
|
|
634
|
-
}
|
|
635
|
-
}
|
|
636
|
-
async handleFrame(sessionId, frame, signal) {
|
|
637
|
-
this.reconnectAttempts = 0;
|
|
638
|
-
this.options.onStateChange?.({ state: "connected", heartbeat: true });
|
|
639
|
-
const event = frame.data;
|
|
640
|
-
const eventId = event.id ?? frame.id;
|
|
641
|
-
if (event.type !== "agent.custom_tool_use" || event.name !== QODER_TOOL_NAME || !eventId) {
|
|
642
|
-
if (eventId) this.lastEventId = eventId;
|
|
643
|
-
return;
|
|
644
|
-
}
|
|
645
|
-
const cached = this.cachedResults.get(eventId) ?? await this.executeTool(event);
|
|
646
|
-
this.rememberResult(eventId, cached);
|
|
647
|
-
try {
|
|
648
|
-
this.lastEventId = await this.api.sendCustomToolResult(
|
|
649
|
-
sessionId,
|
|
650
|
-
eventId,
|
|
651
|
-
cached.content,
|
|
652
|
-
cached.isError,
|
|
653
|
-
signal
|
|
654
|
-
) ?? eventId;
|
|
655
|
-
} catch (error) {
|
|
656
|
-
if (error instanceof QoderApiError && error.status === 400 && cached.content !== cached.fallbackContent) {
|
|
657
|
-
this.lastEventId = await this.api.sendCustomToolResult(
|
|
658
|
-
sessionId,
|
|
659
|
-
eventId,
|
|
660
|
-
cached.fallbackContent,
|
|
661
|
-
cached.isError,
|
|
662
|
-
signal
|
|
663
|
-
) ?? eventId;
|
|
664
|
-
return;
|
|
665
|
-
}
|
|
666
|
-
if (error instanceof QoderApiError && error.status === 404) {
|
|
667
|
-
this.lastEventId = eventId;
|
|
668
|
-
return;
|
|
669
|
-
}
|
|
670
|
-
throw error;
|
|
671
|
-
}
|
|
672
|
-
}
|
|
673
|
-
async executeTool(event) {
|
|
674
|
-
try {
|
|
675
|
-
const input = toolInput(event);
|
|
676
|
-
if (input.action === "pair") {
|
|
677
|
-
throw new Error("This pairing request does not match the active connector");
|
|
678
|
-
}
|
|
679
|
-
const result = await this.invokeAction(input.action, input.payload, {
|
|
680
|
-
browser: input.browser,
|
|
681
|
-
timeoutSec: input.timeoutSec ?? resolveActionTimeoutSec(input.action, input.payload, 15)
|
|
682
|
-
});
|
|
683
|
-
return { ...formatQoderToolResult(result), isError: false };
|
|
684
|
-
} catch (error) {
|
|
685
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
686
|
-
const content = [{ type: "text", text: safeJson({ error: message }) }];
|
|
687
|
-
return { content, fallbackContent: content, isError: true };
|
|
688
|
-
}
|
|
689
|
-
}
|
|
690
|
-
rememberResult(eventId, result) {
|
|
691
|
-
this.cachedResults.set(eventId, result);
|
|
692
|
-
while (this.cachedResults.size > MAX_CACHED_RESULTS) {
|
|
693
|
-
const oldest = this.cachedResults.keys().next().value;
|
|
694
|
-
if (!oldest) break;
|
|
695
|
-
this.cachedResults.delete(oldest);
|
|
696
|
-
}
|
|
697
|
-
}
|
|
698
|
-
};
|
|
699
|
-
|
|
700
|
-
// src/index.ts
|
|
701
|
-
var CLOUD_CONNECTOR_VERSION = true ? "3.0.0-beta.4" : "unknown";
|
|
702
|
-
var DEFAULT_RECONNECT_INTERVAL = 5e3;
|
|
703
|
-
var BACKOFF_BASE_MS = 1e3;
|
|
704
|
-
var BACKOFF_MAX_MS = 3e4;
|
|
705
|
-
var SLOW_PROBE_INTERVAL_MS = 6e4;
|
|
706
|
-
var FAST_RECONNECT_ATTEMPTS = 5;
|
|
707
|
-
var CONNECTOR_REPLACED_REASON = "Connector replaced by a newer connection";
|
|
708
|
-
var CloudConnector = class {
|
|
709
|
-
options;
|
|
710
|
-
endpoint;
|
|
711
|
-
identity;
|
|
712
|
-
qoderConnector = null;
|
|
713
|
-
ws = null;
|
|
714
|
-
heartbeatTimer = null;
|
|
715
|
-
reconnectTimer = null;
|
|
716
|
-
reconnectAttempts = 0;
|
|
717
|
-
messageBuffer = "";
|
|
718
|
-
isManualClose = false;
|
|
719
|
-
shouldTryWss = false;
|
|
720
|
-
wssRetryAttempts = 0;
|
|
721
|
-
maxWssRetryAttempts = 1;
|
|
722
|
-
hasConnected = false;
|
|
723
|
-
lastConnectionError = null;
|
|
724
|
-
constructor(options) {
|
|
725
|
-
this.endpoint = requireConnectorEndpoint(options.serverUrl);
|
|
726
|
-
this.options = {
|
|
727
|
-
serverUrl: this.endpoint.serverUrl,
|
|
728
|
-
heartbeatInterval: options.heartbeatInterval ?? DEFAULT_HEARTBEAT_INTERVAL,
|
|
729
|
-
reconnectInterval: options.reconnectInterval ?? DEFAULT_RECONNECT_INTERVAL,
|
|
730
|
-
maxReconnectAttempts: options.maxReconnectAttempts ?? -1,
|
|
731
|
-
failFast: options.failFast ?? false,
|
|
732
|
-
onInitialConnectionFailed: options.onInitialConnectionFailed,
|
|
733
|
-
onConnected: options.onConnected,
|
|
734
|
-
onStateChange: options.onStateChange,
|
|
735
|
-
onSuperseded: options.onSuperseded
|
|
736
|
-
};
|
|
737
|
-
this.identity = resolveConnectorIdentity(options);
|
|
738
|
-
}
|
|
739
|
-
connect() {
|
|
740
|
-
if (this.endpoint.scheme === "qoder") {
|
|
741
|
-
if (this.qoderConnector) {
|
|
742
|
-
this.qoderConnector.connect();
|
|
743
|
-
return;
|
|
744
|
-
}
|
|
745
|
-
try {
|
|
746
|
-
this.qoderConnector = new QoderConnector({
|
|
747
|
-
endpoint: this.endpoint,
|
|
748
|
-
identity: this.identity,
|
|
749
|
-
reconnectInterval: this.options.reconnectInterval,
|
|
750
|
-
maxReconnectAttempts: this.options.maxReconnectAttempts,
|
|
751
|
-
failFast: this.options.failFast,
|
|
752
|
-
onConnected: () => {
|
|
753
|
-
this.hasConnected = true;
|
|
754
|
-
this.options.onConnected?.(this.options.serverUrl, this.identity);
|
|
755
|
-
},
|
|
756
|
-
onStateChange: (change) => this.emitState(change),
|
|
757
|
-
onInitialConnectionFailed: this.options.onInitialConnectionFailed
|
|
758
|
-
});
|
|
759
|
-
this.qoderConnector.connect();
|
|
760
|
-
} catch (error) {
|
|
761
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
762
|
-
if (this.options.onInitialConnectionFailed) {
|
|
763
|
-
this.options.onInitialConnectionFailed(message);
|
|
764
|
-
} else {
|
|
765
|
-
console.error(`[CloudConnector] Qoder connection error: ${message}`);
|
|
766
|
-
}
|
|
767
|
-
}
|
|
768
|
-
return;
|
|
769
|
-
}
|
|
770
|
-
if (this.ws && (this.ws.readyState === 0 || this.ws.readyState === 1)) {
|
|
771
|
-
return;
|
|
772
|
-
}
|
|
773
|
-
if (!this.hasConnected && this.reconnectAttempts === 0) {
|
|
774
|
-
this.emitState({ state: "connecting" });
|
|
775
|
-
}
|
|
776
|
-
let serverUrl = this.endpoint.transportUrl;
|
|
777
|
-
if (this.shouldTryWss && serverUrl.startsWith("ws://")) {
|
|
778
|
-
serverUrl = serverUrl.replace("ws://", "wss://");
|
|
779
|
-
console.log(`[CloudConnector] Retrying with wss://: ${serverUrl}`);
|
|
780
|
-
}
|
|
781
|
-
this.ws = new WebSocket(serverUrl);
|
|
782
|
-
this.ws.on("open", () => {
|
|
783
|
-
this.hasConnected = true;
|
|
784
|
-
this.lastConnectionError = null;
|
|
785
|
-
this.reconnectAttempts = 0;
|
|
786
|
-
this.shouldTryWss = false;
|
|
787
|
-
this.wssRetryAttempts = 0;
|
|
788
|
-
this.sendConnectorHello();
|
|
789
|
-
this.startHeartbeat();
|
|
790
|
-
this.emitState({ state: "connected" });
|
|
791
|
-
this.options.onConnected?.(this.options.serverUrl, this.identity);
|
|
792
|
-
console.log(`[CloudConnector] Connected to ${serverUrl}`);
|
|
793
|
-
});
|
|
794
|
-
this.ws.on("message", (data) => {
|
|
795
|
-
this.handleMessage(data);
|
|
796
|
-
});
|
|
797
|
-
this.ws.on("close", (code, reason) => {
|
|
798
|
-
this.handleClose(code, reason.toString(), serverUrl);
|
|
799
|
-
});
|
|
800
|
-
this.ws.on("error", (error) => {
|
|
801
|
-
console.error(`[CloudConnector] WebSocket error:`, error.message);
|
|
802
|
-
this.lastConnectionError = error.message;
|
|
803
|
-
if (error.message.includes("301") && !this.shouldTryWss && serverUrl.startsWith("ws://") && this.wssRetryAttempts < this.maxWssRetryAttempts) {
|
|
804
|
-
this.shouldTryWss = true;
|
|
805
|
-
this.wssRetryAttempts++;
|
|
806
|
-
this.ws = null;
|
|
807
|
-
console.log(
|
|
808
|
-
`[CloudConnector] Server requires wss://, retrying (${this.wssRetryAttempts}/${this.maxWssRetryAttempts})...`
|
|
809
|
-
);
|
|
810
|
-
setTimeout(() => this.connect(), 1e3);
|
|
811
|
-
}
|
|
812
|
-
});
|
|
813
|
-
}
|
|
814
|
-
disconnect() {
|
|
815
|
-
this.isManualClose = true;
|
|
816
|
-
this.qoderConnector?.disconnect();
|
|
817
|
-
this.qoderConnector = null;
|
|
818
|
-
this.stopHeartbeat();
|
|
819
|
-
if (this.reconnectTimer) {
|
|
820
|
-
clearTimeout(this.reconnectTimer);
|
|
821
|
-
this.reconnectTimer = null;
|
|
822
|
-
}
|
|
823
|
-
if (this.ws) {
|
|
824
|
-
this.ws.close();
|
|
825
|
-
this.ws = null;
|
|
826
|
-
}
|
|
827
|
-
}
|
|
828
|
-
handleMessage(data) {
|
|
829
|
-
this.messageBuffer += data.toString("utf-8");
|
|
830
|
-
if (this.messageBuffer.length > MAX_BUFFER_SIZE) {
|
|
831
|
-
console.error("[CloudConnector] Message buffer exceeds limit, closing connection");
|
|
832
|
-
this.disconnect();
|
|
833
|
-
return;
|
|
834
|
-
}
|
|
835
|
-
let newlineIndex;
|
|
836
|
-
while ((newlineIndex = this.messageBuffer.indexOf("\n")) !== -1) {
|
|
837
|
-
const line = this.messageBuffer.slice(0, newlineIndex);
|
|
838
|
-
this.messageBuffer = this.messageBuffer.slice(newlineIndex + 1);
|
|
839
|
-
if (!line.trim()) continue;
|
|
840
|
-
try {
|
|
841
|
-
const message = JSON.parse(line);
|
|
842
|
-
this.handleCloudMessage(message);
|
|
843
|
-
} catch (error) {
|
|
844
|
-
console.error(`[CloudConnector] Failed to parse message:`, line, error);
|
|
845
|
-
}
|
|
846
|
-
}
|
|
847
|
-
}
|
|
848
|
-
handleClose(code, reasonText, serverUrl) {
|
|
849
|
-
console.log(`[CloudConnector] Disconnected (${code}: ${reasonText})`);
|
|
850
|
-
this.stopHeartbeat();
|
|
851
|
-
this.messageBuffer = "";
|
|
852
|
-
if (this.shouldTryWss && serverUrl.startsWith("ws://")) return;
|
|
853
|
-
if (code === 1e3 && reasonText === CONNECTOR_REPLACED_REASON) {
|
|
854
|
-
this.isManualClose = true;
|
|
855
|
-
console.error("[CloudConnector] Superseded by a newer connector; exiting");
|
|
856
|
-
this.options.onSuperseded?.();
|
|
857
|
-
return;
|
|
858
|
-
}
|
|
859
|
-
if (this.options.failFast && !this.hasConnected) {
|
|
860
|
-
const message = this.lastConnectionError || reasonText || `Connection closed (${code})`;
|
|
861
|
-
this.emitState({ state: "failed", reason: message });
|
|
862
|
-
this.options.onInitialConnectionFailed?.(message);
|
|
863
|
-
return;
|
|
864
|
-
}
|
|
865
|
-
this.tryReconnect(this.lastConnectionError || reasonText || `Connection closed (${code})`);
|
|
866
|
-
}
|
|
867
|
-
async handleCloudMessage(message) {
|
|
868
|
-
if (isHeartbeatMessage(message)) {
|
|
869
|
-
this.emitState({ state: "connected", heartbeat: true });
|
|
870
|
-
if (message.type === "ping") {
|
|
871
|
-
this.sendHeartbeatResponse(message.timestamp);
|
|
872
|
-
}
|
|
873
|
-
return;
|
|
874
|
-
}
|
|
875
|
-
const request = message;
|
|
876
|
-
const { id, action, data, browser, timeoutSec } = request;
|
|
877
|
-
try {
|
|
878
|
-
const client = await import("@mearl/client/local");
|
|
879
|
-
const result = await client.invoke(action, data, {
|
|
880
|
-
browser,
|
|
881
|
-
timeoutSec: timeoutSec ?? resolveActionTimeoutSec2(action, data, 15),
|
|
882
|
-
controlSource: "remote",
|
|
883
|
-
...request.controlSessionId ? { controlSessionId: request.controlSessionId } : {}
|
|
884
|
-
});
|
|
885
|
-
this.sendResponse({ id, success: true, data: result });
|
|
886
|
-
} catch (error) {
|
|
887
|
-
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
888
|
-
this.sendResponse({ id, success: false, error: errorMessage });
|
|
889
|
-
}
|
|
890
|
-
}
|
|
891
|
-
sendResponse(response) {
|
|
892
|
-
if (this.ws && this.ws.readyState === 1) {
|
|
893
|
-
const message = JSON.stringify(response) + "\n";
|
|
894
|
-
const bytes = Buffer.byteLength(message, "utf-8");
|
|
895
|
-
if (bytes > MAX_BUFFER_SIZE) {
|
|
896
|
-
console.error(
|
|
897
|
-
`[CloudConnector] Response ${response.id} exceeds message limit (${bytes} > ${MAX_BUFFER_SIZE} bytes)`
|
|
898
|
-
);
|
|
899
|
-
this.ws.send(
|
|
900
|
-
JSON.stringify({
|
|
901
|
-
id: response.id,
|
|
902
|
-
success: false,
|
|
903
|
-
error: `Cloud response exceeds ${MAX_BUFFER_SIZE} byte message limit (${bytes} bytes). Reduce the result size; for screenshots use JPEG quality or a selector.`
|
|
904
|
-
}) + "\n"
|
|
905
|
-
);
|
|
906
|
-
return;
|
|
907
|
-
}
|
|
908
|
-
this.ws.send(message);
|
|
909
|
-
}
|
|
910
|
-
}
|
|
911
|
-
sendConnectorHello() {
|
|
912
|
-
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
|
|
913
|
-
const message = {
|
|
914
|
-
type: "connector_hello",
|
|
915
|
-
connectorId: this.identity.connectorId,
|
|
916
|
-
name: this.identity.name,
|
|
917
|
-
...CLOUD_CONNECTOR_VERSION === "unknown" ? {} : { version: CLOUD_CONNECTOR_VERSION }
|
|
918
|
-
};
|
|
919
|
-
this.ws.send(JSON.stringify(message) + "\n");
|
|
920
|
-
}
|
|
921
|
-
}
|
|
922
|
-
sendHeartbeatResponse(_timestamp) {
|
|
923
|
-
if (this.ws && this.ws.readyState === 1) {
|
|
924
|
-
this.ws.send(
|
|
925
|
-
JSON.stringify({ type: "pong", timestamp: Date.now() }) + "\n"
|
|
926
|
-
);
|
|
927
|
-
}
|
|
928
|
-
}
|
|
929
|
-
startHeartbeat() {
|
|
930
|
-
this.stopHeartbeat();
|
|
931
|
-
this.heartbeatTimer = setInterval(() => {
|
|
932
|
-
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
|
|
933
|
-
this.ws.send(
|
|
934
|
-
JSON.stringify({ type: "ping", timestamp: Date.now() }) + "\n"
|
|
935
|
-
);
|
|
936
|
-
}
|
|
937
|
-
}, this.options.heartbeatInterval * 1e3);
|
|
938
|
-
}
|
|
939
|
-
stopHeartbeat() {
|
|
940
|
-
if (this.heartbeatTimer) {
|
|
941
|
-
clearInterval(this.heartbeatTimer);
|
|
942
|
-
this.heartbeatTimer = null;
|
|
943
|
-
}
|
|
944
|
-
}
|
|
945
|
-
tryReconnect(reason) {
|
|
946
|
-
if (this.isManualClose) return;
|
|
947
|
-
if (this.reconnectTimer) return;
|
|
948
|
-
this.reconnectAttempts++;
|
|
949
|
-
if (this.options.maxReconnectAttempts !== -1 && this.reconnectAttempts > this.options.maxReconnectAttempts) {
|
|
950
|
-
console.log(
|
|
951
|
-
`[CloudConnector] Max reconnect attempts (${this.options.maxReconnectAttempts}) reached`
|
|
952
|
-
);
|
|
953
|
-
this.emitState({
|
|
954
|
-
state: "failed",
|
|
955
|
-
...reason ? { reason } : {},
|
|
956
|
-
reconnectAttempt: this.reconnectAttempts
|
|
957
|
-
});
|
|
958
|
-
return;
|
|
959
|
-
}
|
|
960
|
-
const isSlowProbe = this.reconnectAttempts > FAST_RECONNECT_ATTEMPTS;
|
|
961
|
-
const delay = isSlowProbe ? SLOW_PROBE_INTERVAL_MS : Math.min(BACKOFF_BASE_MS * Math.pow(2, this.reconnectAttempts - 1), BACKOFF_MAX_MS);
|
|
962
|
-
if (isSlowProbe) {
|
|
963
|
-
console.log(
|
|
964
|
-
`[CloudConnector] Slow probe reconnect in ${delay / 1e3}s (attempt ${this.reconnectAttempts})`
|
|
965
|
-
);
|
|
966
|
-
} else {
|
|
967
|
-
console.log(
|
|
968
|
-
`[CloudConnector] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts}/${FAST_RECONNECT_ATTEMPTS})`
|
|
969
|
-
);
|
|
970
|
-
}
|
|
971
|
-
this.emitState({
|
|
972
|
-
state: "reconnecting",
|
|
973
|
-
...reason ? { reason } : {},
|
|
974
|
-
reconnectAttempt: this.reconnectAttempts,
|
|
975
|
-
retryInMs: delay
|
|
976
|
-
});
|
|
977
|
-
this.reconnectTimer = setTimeout(() => {
|
|
978
|
-
this.reconnectTimer = null;
|
|
979
|
-
this.connect();
|
|
980
|
-
}, delay);
|
|
981
|
-
}
|
|
982
|
-
emitState(change) {
|
|
983
|
-
this.options.onStateChange?.(change);
|
|
984
|
-
}
|
|
985
|
-
};
|
|
986
|
-
|
|
987
|
-
export {
|
|
988
|
-
parseConnectorEndpoint,
|
|
989
|
-
isConnectorEndpoint,
|
|
990
|
-
requireConnectorEndpoint,
|
|
991
|
-
resolveConnectorIdentity,
|
|
992
|
-
QODER_TOOL_NAME,
|
|
993
|
-
DEFAULT_QODER_API_BASE_URL,
|
|
994
|
-
QoderApiError,
|
|
995
|
-
formatQoderToolResult,
|
|
996
|
-
QoderApiClient,
|
|
997
|
-
parseQoderSse,
|
|
998
|
-
QoderConnector,
|
|
999
|
-
CloudConnector
|
|
1000
|
-
};
|