@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/README.md +33 -7
- package/dist/__tests__/endpoint.test.d.ts +1 -0
- package/dist/__tests__/qoder.test.d.ts +1 -0
- package/dist/cli.js +546 -14
- package/dist/endpoint.d.ts +20 -0
- package/dist/index.d.ts +5 -1
- package/dist/index.js +549 -7
- package/dist/qoder.d.ts +106 -0
- package/package.json +7 -6
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,506 @@ 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
|
+
var QODER_TOOL_NAME = "mearl";
|
|
95
|
+
var DEFAULT_QODER_API_BASE_URL = "https://api.qoder.com";
|
|
96
|
+
var DEFAULT_DISCOVERY_WINDOW_MS = 60 * 60 * 1e3;
|
|
97
|
+
var DEFAULT_RECONNECT_INTERVAL_MS = 5e3;
|
|
98
|
+
var MAX_RECENT_SESSIONS = 100;
|
|
99
|
+
var MAX_RECENT_TOOL_EVENTS = 20;
|
|
100
|
+
var MAX_CACHED_RESULTS = 100;
|
|
101
|
+
var QoderApiError = class extends Error {
|
|
102
|
+
constructor(message, status) {
|
|
103
|
+
super(message);
|
|
104
|
+
this.status = status;
|
|
105
|
+
this.name = "QoderApiError";
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
function safeJson(value) {
|
|
109
|
+
try {
|
|
110
|
+
return JSON.stringify(value ?? null);
|
|
111
|
+
} catch {
|
|
112
|
+
return JSON.stringify({ error: "Mearl returned a value that cannot be serialized" });
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
function isRecord(value) {
|
|
116
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
117
|
+
}
|
|
118
|
+
function asScreenshot(value) {
|
|
119
|
+
if (!isRecord(value) || typeof value.data !== "string" || !isRecord(value.meta)) return null;
|
|
120
|
+
const format = value.meta.format;
|
|
121
|
+
if (format !== "png" && format !== "jpeg") return null;
|
|
122
|
+
return { data: value.data, meta: { ...value.meta, format } };
|
|
123
|
+
}
|
|
124
|
+
function formatQoderToolResult(value) {
|
|
125
|
+
const directScreenshot = asScreenshot(value);
|
|
126
|
+
const nestedScreenshot = !directScreenshot && isRecord(value) ? asScreenshot(value.screenshot) : null;
|
|
127
|
+
const screenshot = directScreenshot ?? nestedScreenshot;
|
|
128
|
+
if (!screenshot) {
|
|
129
|
+
const content = [{ type: "text", text: safeJson(value) }];
|
|
130
|
+
return { content, fallbackContent: content };
|
|
131
|
+
}
|
|
132
|
+
let metadata;
|
|
133
|
+
if (directScreenshot) {
|
|
134
|
+
metadata = { meta: screenshot.meta };
|
|
135
|
+
} else {
|
|
136
|
+
metadata = { ...value, screenshot: { meta: screenshot.meta } };
|
|
137
|
+
}
|
|
138
|
+
return {
|
|
139
|
+
content: [
|
|
140
|
+
{ type: "text", text: safeJson(metadata) },
|
|
141
|
+
{
|
|
142
|
+
type: "image",
|
|
143
|
+
source: {
|
|
144
|
+
type: "base64",
|
|
145
|
+
media_type: `image/${screenshot.meta.format}`,
|
|
146
|
+
data: screenshot.data
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
],
|
|
150
|
+
fallbackContent: [{ type: "text", text: safeJson(value) }]
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
function pairingCodeFromEvent(event) {
|
|
154
|
+
if (event.type !== "agent.custom_tool_use" || event.name !== QODER_TOOL_NAME) return null;
|
|
155
|
+
if (!isRecord(event.input) || event.input.action !== "pair") return null;
|
|
156
|
+
const payload = isRecord(event.input.payload) ? event.input.payload : isRecord(event.input.data) ? event.input.data : null;
|
|
157
|
+
return payload && typeof payload.code === "string" ? payload.code : null;
|
|
158
|
+
}
|
|
159
|
+
function qoderErrorMessage(status, body) {
|
|
160
|
+
try {
|
|
161
|
+
const parsed = JSON.parse(body);
|
|
162
|
+
const message = parsed.error?.message ?? parsed.message;
|
|
163
|
+
if (typeof message === "string" && message.trim()) return message.trim();
|
|
164
|
+
} catch {
|
|
165
|
+
}
|
|
166
|
+
return `Qoder API request failed with HTTP ${status}`;
|
|
167
|
+
}
|
|
168
|
+
var QoderApiClient = class {
|
|
169
|
+
constructor(token, baseUrl = DEFAULT_QODER_API_BASE_URL, fetchImpl = fetch) {
|
|
170
|
+
this.token = token;
|
|
171
|
+
this.fetchImpl = fetchImpl;
|
|
172
|
+
const parsed = new URL(baseUrl);
|
|
173
|
+
if (parsed.protocol !== "https:" && parsed.hostname !== "localhost" && parsed.hostname !== "127.0.0.1") {
|
|
174
|
+
throw new Error("Qoder API base URL must use https:// (localhost may use http:// for tests)");
|
|
175
|
+
}
|
|
176
|
+
this.baseUrl = parsed.toString().replace(/\/$/, "");
|
|
177
|
+
}
|
|
178
|
+
baseUrl;
|
|
179
|
+
async request(path, init = {}) {
|
|
180
|
+
const response = await this.fetchImpl(`${this.baseUrl}${path}`, {
|
|
181
|
+
...init,
|
|
182
|
+
headers: {
|
|
183
|
+
Authorization: `Bearer ${this.token}`,
|
|
184
|
+
...init.headers
|
|
185
|
+
}
|
|
186
|
+
});
|
|
187
|
+
if (!response.ok) {
|
|
188
|
+
const body = await response.text();
|
|
189
|
+
throw new QoderApiError(qoderErrorMessage(response.status, body), response.status);
|
|
190
|
+
}
|
|
191
|
+
return response;
|
|
192
|
+
}
|
|
193
|
+
async listSessions(createdAfter, signal) {
|
|
194
|
+
const query = new URLSearchParams({
|
|
195
|
+
limit: String(MAX_RECENT_SESSIONS),
|
|
196
|
+
order: "desc",
|
|
197
|
+
"created_at[gte]": createdAfter
|
|
198
|
+
});
|
|
199
|
+
const response = await this.request(`/api/v1/cloud/sessions?${query}`, { signal });
|
|
200
|
+
const body = await response.json();
|
|
201
|
+
return Array.isArray(body.data) ? body.data.filter((session) => typeof session.id === "string") : [];
|
|
202
|
+
}
|
|
203
|
+
async listCustomToolEvents(sessionId, createdAfter, signal) {
|
|
204
|
+
const query = new URLSearchParams({
|
|
205
|
+
limit: String(MAX_RECENT_TOOL_EVENTS),
|
|
206
|
+
order: "desc",
|
|
207
|
+
types: "agent.custom_tool_use",
|
|
208
|
+
"created_at[gte]": createdAfter
|
|
209
|
+
});
|
|
210
|
+
const response = await this.request(
|
|
211
|
+
`/api/v1/cloud/sessions/${encodeURIComponent(sessionId)}/events?${query}`,
|
|
212
|
+
{ signal }
|
|
213
|
+
);
|
|
214
|
+
const body = await response.json();
|
|
215
|
+
return Array.isArray(body.data) ? body.data : [];
|
|
216
|
+
}
|
|
217
|
+
async findPairingRequest(pairingCode, createdAfter, signal) {
|
|
218
|
+
const sessions = await this.listSessions(createdAfter, signal);
|
|
219
|
+
for (const session of sessions) {
|
|
220
|
+
const events = await this.listCustomToolEvents(session.id, createdAfter, signal);
|
|
221
|
+
const event = events.find((candidate) => pairingCodeFromEvent(candidate) === pairingCode);
|
|
222
|
+
if (event?.id) return { sessionId: session.id, event: { ...event, id: event.id } };
|
|
223
|
+
}
|
|
224
|
+
return null;
|
|
225
|
+
}
|
|
226
|
+
async sendCustomToolResult(sessionId, customToolUseId, content, isError = false, signal) {
|
|
227
|
+
const response = await this.request(
|
|
228
|
+
`/api/v1/cloud/sessions/${encodeURIComponent(sessionId)}/events`,
|
|
229
|
+
{
|
|
230
|
+
method: "POST",
|
|
231
|
+
headers: { "Content-Type": "application/json" },
|
|
232
|
+
signal,
|
|
233
|
+
body: JSON.stringify({
|
|
234
|
+
events: [
|
|
235
|
+
{
|
|
236
|
+
type: "user.custom_tool_result",
|
|
237
|
+
custom_tool_use_id: customToolUseId,
|
|
238
|
+
content,
|
|
239
|
+
is_error: isError
|
|
240
|
+
}
|
|
241
|
+
]
|
|
242
|
+
})
|
|
243
|
+
}
|
|
244
|
+
);
|
|
245
|
+
const body = await response.json();
|
|
246
|
+
return body.data?.[0]?.id;
|
|
247
|
+
}
|
|
248
|
+
async streamEvents(sessionId, lastEventId, signal, onFrame, onOpen) {
|
|
249
|
+
const response = await this.request(
|
|
250
|
+
`/api/v1/cloud/sessions/${encodeURIComponent(sessionId)}/events/stream`,
|
|
251
|
+
{
|
|
252
|
+
headers: {
|
|
253
|
+
Accept: "text/event-stream",
|
|
254
|
+
...lastEventId ? { "Last-Event-ID": lastEventId } : {}
|
|
255
|
+
},
|
|
256
|
+
signal
|
|
257
|
+
}
|
|
258
|
+
);
|
|
259
|
+
if (!response.body) throw new Error("Qoder event stream returned no response body");
|
|
260
|
+
onOpen?.();
|
|
261
|
+
await parseQoderSse(response.body, onFrame);
|
|
262
|
+
}
|
|
263
|
+
};
|
|
264
|
+
async function parseQoderSse(body, onFrame) {
|
|
265
|
+
const reader = body.getReader();
|
|
266
|
+
const decoder = new TextDecoder();
|
|
267
|
+
let buffer = "";
|
|
268
|
+
let frameLines = [];
|
|
269
|
+
const dispatch = async () => {
|
|
270
|
+
if (frameLines.length === 0) return;
|
|
271
|
+
let id;
|
|
272
|
+
let event;
|
|
273
|
+
const data = [];
|
|
274
|
+
for (const line of frameLines) {
|
|
275
|
+
if (!line || line.startsWith(":")) continue;
|
|
276
|
+
const separator = line.indexOf(":");
|
|
277
|
+
const field = separator === -1 ? line : line.slice(0, separator);
|
|
278
|
+
const value = separator === -1 ? "" : line.slice(separator + 1).replace(/^ /, "");
|
|
279
|
+
if (field === "id") id = value;
|
|
280
|
+
else if (field === "event") event = value;
|
|
281
|
+
else if (field === "data") data.push(value);
|
|
282
|
+
}
|
|
283
|
+
frameLines = [];
|
|
284
|
+
if (data.length === 0) return;
|
|
285
|
+
const parsed = JSON.parse(data.join("\n"));
|
|
286
|
+
await onFrame({ ...id ? { id } : {}, ...event ? { event } : {}, data: parsed });
|
|
287
|
+
};
|
|
288
|
+
while (true) {
|
|
289
|
+
const { done, value } = await reader.read();
|
|
290
|
+
buffer += decoder.decode(value, { stream: !done });
|
|
291
|
+
let newlineIndex;
|
|
292
|
+
while ((newlineIndex = buffer.indexOf("\n")) !== -1) {
|
|
293
|
+
const line = buffer.slice(0, newlineIndex).replace(/\r$/, "");
|
|
294
|
+
buffer = buffer.slice(newlineIndex + 1);
|
|
295
|
+
if (line === "") await dispatch();
|
|
296
|
+
else frameLines.push(line);
|
|
297
|
+
}
|
|
298
|
+
if (done) break;
|
|
299
|
+
}
|
|
300
|
+
if (buffer) frameLines.push(buffer.replace(/\r$/, ""));
|
|
301
|
+
await dispatch();
|
|
302
|
+
}
|
|
303
|
+
function defaultSleep(milliseconds, signal) {
|
|
304
|
+
return new Promise((resolve, reject) => {
|
|
305
|
+
if (signal.aborted) {
|
|
306
|
+
reject(signal.reason ?? new Error("Aborted"));
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
const onAbort = () => {
|
|
310
|
+
clearTimeout(timer);
|
|
311
|
+
reject(signal.reason ?? new Error("Aborted"));
|
|
312
|
+
};
|
|
313
|
+
const timer = setTimeout(() => {
|
|
314
|
+
signal.removeEventListener("abort", onAbort);
|
|
315
|
+
resolve();
|
|
316
|
+
}, milliseconds);
|
|
317
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
async function defaultInvokeAction(action, payload, options) {
|
|
321
|
+
const client = await import("@mearl/client/local");
|
|
322
|
+
return client.invoke(action, payload, {
|
|
323
|
+
browser: options.browser,
|
|
324
|
+
timeoutSec: options.timeoutSec,
|
|
325
|
+
controlSource: "remote"
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
function toolInput(event) {
|
|
329
|
+
if (!isRecord(event.input) || typeof event.input.action !== "string") {
|
|
330
|
+
throw new Error("Qoder mearl tool input requires a string action");
|
|
331
|
+
}
|
|
332
|
+
const browser = typeof event.input.browser === "string" ? event.input.browser : void 0;
|
|
333
|
+
const timeoutSec = typeof event.input.timeoutSec === "number" && Number.isFinite(event.input.timeoutSec) ? event.input.timeoutSec : void 0;
|
|
334
|
+
const payloadValue = event.input.payload ?? event.input.data ?? {};
|
|
335
|
+
if (!isRecord(payloadValue)) {
|
|
336
|
+
throw new Error("Qoder mearl tool input payload must be an object");
|
|
337
|
+
}
|
|
338
|
+
return {
|
|
339
|
+
action: event.input.action,
|
|
340
|
+
payload: payloadValue,
|
|
341
|
+
...browser ? { browser } : {},
|
|
342
|
+
...timeoutSec === void 0 ? {} : { timeoutSec }
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
var QoderConnector = class {
|
|
346
|
+
constructor(options) {
|
|
347
|
+
this.options = options;
|
|
348
|
+
const token = options.token?.trim() || process.env.QODER_PERSONAL_ACCESS_TOKEN?.trim();
|
|
349
|
+
if (!token) {
|
|
350
|
+
throw new Error(
|
|
351
|
+
"Qoder authentication is required. Set QODER_PERSONAL_ACCESS_TOKEN and run the connector again."
|
|
352
|
+
);
|
|
353
|
+
}
|
|
354
|
+
this.api = new QoderApiClient(
|
|
355
|
+
token,
|
|
356
|
+
options.apiBaseUrl ?? DEFAULT_QODER_API_BASE_URL,
|
|
357
|
+
options.fetchImpl
|
|
358
|
+
);
|
|
359
|
+
this.now = options.now ?? Date.now;
|
|
360
|
+
this.sleep = options.sleep ?? defaultSleep;
|
|
361
|
+
this.invokeAction = options.invokeAction ?? defaultInvokeAction;
|
|
362
|
+
this.reconnectInterval = options.reconnectInterval ?? DEFAULT_RECONNECT_INTERVAL_MS;
|
|
363
|
+
this.maxReconnectAttempts = options.maxReconnectAttempts ?? -1;
|
|
364
|
+
}
|
|
365
|
+
api;
|
|
366
|
+
now;
|
|
367
|
+
sleep;
|
|
368
|
+
invokeAction;
|
|
369
|
+
reconnectInterval;
|
|
370
|
+
maxReconnectAttempts;
|
|
371
|
+
abortController = null;
|
|
372
|
+
reconnectAttempts = 0;
|
|
373
|
+
running = false;
|
|
374
|
+
connected = false;
|
|
375
|
+
sessionId = null;
|
|
376
|
+
lastEventId;
|
|
377
|
+
cachedResults = /* @__PURE__ */ new Map();
|
|
378
|
+
connect() {
|
|
379
|
+
if (this.running) return;
|
|
380
|
+
this.running = true;
|
|
381
|
+
this.abortController = new AbortController();
|
|
382
|
+
void this.run(this.abortController.signal);
|
|
383
|
+
}
|
|
384
|
+
disconnect() {
|
|
385
|
+
this.running = false;
|
|
386
|
+
this.abortController?.abort();
|
|
387
|
+
this.abortController = null;
|
|
388
|
+
}
|
|
389
|
+
async run(signal) {
|
|
390
|
+
while (!signal.aborted) {
|
|
391
|
+
try {
|
|
392
|
+
if (!this.sessionId) {
|
|
393
|
+
const pairing = await this.findPairing(signal);
|
|
394
|
+
await this.completePairing(pairing, signal);
|
|
395
|
+
}
|
|
396
|
+
const sessionId = this.sessionId;
|
|
397
|
+
await this.api.streamEvents(
|
|
398
|
+
sessionId,
|
|
399
|
+
this.lastEventId,
|
|
400
|
+
signal,
|
|
401
|
+
async (frame) => this.handleFrame(sessionId, frame, signal),
|
|
402
|
+
() => {
|
|
403
|
+
this.reconnectAttempts = 0;
|
|
404
|
+
}
|
|
405
|
+
);
|
|
406
|
+
if (!signal.aborted) throw new Error("Qoder event stream ended");
|
|
407
|
+
} catch (error) {
|
|
408
|
+
if (signal.aborted) return;
|
|
409
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
410
|
+
if (!this.connected && this.options.failFast) {
|
|
411
|
+
this.options.onInitialConnectionFailed?.(message);
|
|
412
|
+
this.running = false;
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
this.reconnectAttempts += 1;
|
|
416
|
+
if (this.maxReconnectAttempts !== -1 && this.reconnectAttempts > this.maxReconnectAttempts) {
|
|
417
|
+
console.error(
|
|
418
|
+
`[CloudConnector] Qoder max reconnect attempts (${this.maxReconnectAttempts}) reached`
|
|
419
|
+
);
|
|
420
|
+
this.running = false;
|
|
421
|
+
return;
|
|
422
|
+
}
|
|
423
|
+
console.error(`[CloudConnector] Qoder connection error: ${message}`);
|
|
424
|
+
try {
|
|
425
|
+
await this.sleep(this.reconnectInterval, signal);
|
|
426
|
+
} catch {
|
|
427
|
+
return;
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
async findPairing(signal) {
|
|
433
|
+
const createdAt = this.options.endpoint.createdAt ?? this.now();
|
|
434
|
+
const createdAfter = new Date(createdAt - DEFAULT_DISCOVERY_WINDOW_MS).toISOString();
|
|
435
|
+
const pairing = await this.api.findPairingRequest(
|
|
436
|
+
this.options.endpoint.pairingCode,
|
|
437
|
+
createdAfter,
|
|
438
|
+
signal
|
|
439
|
+
);
|
|
440
|
+
if (!pairing) {
|
|
441
|
+
throw new Error(
|
|
442
|
+
'Qoder pairing request was not found. Ask the Agent to call the mearl tool with action "pair" and the code from this URL.'
|
|
443
|
+
);
|
|
444
|
+
}
|
|
445
|
+
return pairing;
|
|
446
|
+
}
|
|
447
|
+
async completePairing(pairing, signal) {
|
|
448
|
+
if (!this.connected) {
|
|
449
|
+
this.lastEventId = await this.api.sendCustomToolResult(
|
|
450
|
+
pairing.sessionId,
|
|
451
|
+
pairing.event.id,
|
|
452
|
+
[
|
|
453
|
+
{
|
|
454
|
+
type: "text",
|
|
455
|
+
text: safeJson({
|
|
456
|
+
connected: true,
|
|
457
|
+
connectorId: this.options.identity.connectorId,
|
|
458
|
+
name: this.options.identity.name
|
|
459
|
+
})
|
|
460
|
+
}
|
|
461
|
+
],
|
|
462
|
+
false,
|
|
463
|
+
signal
|
|
464
|
+
) ?? pairing.event.id;
|
|
465
|
+
this.sessionId = pairing.sessionId;
|
|
466
|
+
this.connected = true;
|
|
467
|
+
this.reconnectAttempts = 0;
|
|
468
|
+
this.options.onConnected?.();
|
|
469
|
+
console.log(`[CloudConnector] Connected to Qoder session ${pairing.sessionId}`);
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
async handleFrame(sessionId, frame, signal) {
|
|
473
|
+
this.reconnectAttempts = 0;
|
|
474
|
+
const event = frame.data;
|
|
475
|
+
const eventId = event.id ?? frame.id;
|
|
476
|
+
if (event.type !== "agent.custom_tool_use" || event.name !== QODER_TOOL_NAME || !eventId) {
|
|
477
|
+
if (eventId) this.lastEventId = eventId;
|
|
478
|
+
return;
|
|
479
|
+
}
|
|
480
|
+
const cached = this.cachedResults.get(eventId) ?? await this.executeTool(event);
|
|
481
|
+
this.rememberResult(eventId, cached);
|
|
482
|
+
try {
|
|
483
|
+
this.lastEventId = await this.api.sendCustomToolResult(
|
|
484
|
+
sessionId,
|
|
485
|
+
eventId,
|
|
486
|
+
cached.content,
|
|
487
|
+
cached.isError,
|
|
488
|
+
signal
|
|
489
|
+
) ?? eventId;
|
|
490
|
+
} catch (error) {
|
|
491
|
+
if (error instanceof QoderApiError && error.status === 400 && cached.content !== cached.fallbackContent) {
|
|
492
|
+
this.lastEventId = await this.api.sendCustomToolResult(
|
|
493
|
+
sessionId,
|
|
494
|
+
eventId,
|
|
495
|
+
cached.fallbackContent,
|
|
496
|
+
cached.isError,
|
|
497
|
+
signal
|
|
498
|
+
) ?? eventId;
|
|
499
|
+
return;
|
|
500
|
+
}
|
|
501
|
+
if (error instanceof QoderApiError && error.status === 404) {
|
|
502
|
+
this.lastEventId = eventId;
|
|
503
|
+
return;
|
|
504
|
+
}
|
|
505
|
+
throw error;
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
async executeTool(event) {
|
|
509
|
+
try {
|
|
510
|
+
const input = toolInput(event);
|
|
511
|
+
if (input.action === "pair") {
|
|
512
|
+
throw new Error("This pairing request does not match the active connector");
|
|
513
|
+
}
|
|
514
|
+
const result = await this.invokeAction(input.action, input.payload, {
|
|
515
|
+
browser: input.browser,
|
|
516
|
+
timeoutSec: input.timeoutSec ?? resolveActionTimeoutSec(input.action, input.payload, 15)
|
|
517
|
+
});
|
|
518
|
+
return { ...formatQoderToolResult(result), isError: false };
|
|
519
|
+
} catch (error) {
|
|
520
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
521
|
+
const content = [{ type: "text", text: safeJson({ error: message }) }];
|
|
522
|
+
return { content, fallbackContent: content, isError: true };
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
rememberResult(eventId, result) {
|
|
526
|
+
this.cachedResults.set(eventId, result);
|
|
527
|
+
while (this.cachedResults.size > MAX_CACHED_RESULTS) {
|
|
528
|
+
const oldest = this.cachedResults.keys().next().value;
|
|
529
|
+
if (!oldest) break;
|
|
530
|
+
this.cachedResults.delete(oldest);
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
};
|
|
534
|
+
|
|
37
535
|
// src/index.ts
|
|
38
|
-
var CLOUD_CONNECTOR_VERSION = true ? "2.
|
|
536
|
+
var CLOUD_CONNECTOR_VERSION = true ? "2.7.0" : "unknown";
|
|
39
537
|
var DEFAULT_RECONNECT_INTERVAL = 5e3;
|
|
40
538
|
var BACKOFF_BASE_MS = 1e3;
|
|
41
539
|
var BACKOFF_MAX_MS = 3e4;
|
|
@@ -43,7 +541,9 @@ var SLOW_PROBE_INTERVAL_MS = 6e4;
|
|
|
43
541
|
var FAST_RECONNECT_ATTEMPTS = 5;
|
|
44
542
|
var CloudConnector = class {
|
|
45
543
|
options;
|
|
544
|
+
endpoint;
|
|
46
545
|
identity;
|
|
546
|
+
qoderConnector = null;
|
|
47
547
|
ws = null;
|
|
48
548
|
heartbeatTimer = null;
|
|
49
549
|
reconnectTimer = null;
|
|
@@ -56,8 +556,9 @@ var CloudConnector = class {
|
|
|
56
556
|
hasConnected = false;
|
|
57
557
|
lastConnectionError = null;
|
|
58
558
|
constructor(options) {
|
|
559
|
+
this.endpoint = requireConnectorEndpoint(options.serverUrl);
|
|
59
560
|
this.options = {
|
|
60
|
-
serverUrl:
|
|
561
|
+
serverUrl: this.endpoint.serverUrl,
|
|
61
562
|
heartbeatInterval: options.heartbeatInterval ?? DEFAULT_HEARTBEAT_INTERVAL,
|
|
62
563
|
reconnectInterval: options.reconnectInterval ?? DEFAULT_RECONNECT_INTERVAL,
|
|
63
564
|
maxReconnectAttempts: options.maxReconnectAttempts ?? -1,
|
|
@@ -68,10 +569,39 @@ var CloudConnector = class {
|
|
|
68
569
|
this.identity = resolveConnectorIdentity(options);
|
|
69
570
|
}
|
|
70
571
|
connect() {
|
|
572
|
+
if (this.endpoint.scheme === "qoder") {
|
|
573
|
+
if (this.qoderConnector) {
|
|
574
|
+
this.qoderConnector.connect();
|
|
575
|
+
return;
|
|
576
|
+
}
|
|
577
|
+
try {
|
|
578
|
+
this.qoderConnector = new QoderConnector({
|
|
579
|
+
endpoint: this.endpoint,
|
|
580
|
+
identity: this.identity,
|
|
581
|
+
reconnectInterval: this.options.reconnectInterval,
|
|
582
|
+
maxReconnectAttempts: this.options.maxReconnectAttempts,
|
|
583
|
+
failFast: this.options.failFast,
|
|
584
|
+
onConnected: () => {
|
|
585
|
+
this.hasConnected = true;
|
|
586
|
+
this.options.onConnected?.(this.options.serverUrl, this.identity);
|
|
587
|
+
},
|
|
588
|
+
onInitialConnectionFailed: this.options.onInitialConnectionFailed
|
|
589
|
+
});
|
|
590
|
+
this.qoderConnector.connect();
|
|
591
|
+
} catch (error) {
|
|
592
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
593
|
+
if (this.options.onInitialConnectionFailed) {
|
|
594
|
+
this.options.onInitialConnectionFailed(message);
|
|
595
|
+
} else {
|
|
596
|
+
console.error(`[CloudConnector] Qoder connection error: ${message}`);
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
return;
|
|
600
|
+
}
|
|
71
601
|
if (this.ws && (this.ws.readyState === 0 || this.ws.readyState === 1)) {
|
|
72
602
|
return;
|
|
73
603
|
}
|
|
74
|
-
let serverUrl = this.
|
|
604
|
+
let serverUrl = this.endpoint.transportUrl;
|
|
75
605
|
if (this.shouldTryWss && serverUrl.startsWith("ws://")) {
|
|
76
606
|
serverUrl = serverUrl.replace("ws://", "wss://");
|
|
77
607
|
console.log(`[CloudConnector] Retrying with wss://: ${serverUrl}`);
|
|
@@ -122,6 +652,8 @@ var CloudConnector = class {
|
|
|
122
652
|
}
|
|
123
653
|
disconnect() {
|
|
124
654
|
this.isManualClose = true;
|
|
655
|
+
this.qoderConnector?.disconnect();
|
|
656
|
+
this.qoderConnector = null;
|
|
125
657
|
this.stopHeartbeat();
|
|
126
658
|
if (this.reconnectTimer) {
|
|
127
659
|
clearTimeout(this.reconnectTimer);
|
|
@@ -165,8 +697,8 @@ var CloudConnector = class {
|
|
|
165
697
|
const client = await import("@mearl/client/local");
|
|
166
698
|
const result = await client.invoke(action, data, {
|
|
167
699
|
browser,
|
|
168
|
-
timeoutSec: timeoutSec ??
|
|
169
|
-
controlSource: "
|
|
700
|
+
timeoutSec: timeoutSec ?? resolveActionTimeoutSec2(action, data, 15),
|
|
701
|
+
controlSource: "remote"
|
|
170
702
|
});
|
|
171
703
|
this.sendResponse({ id, success: true, data: result });
|
|
172
704
|
} catch (error) {
|
|
@@ -241,5 +773,15 @@ var CloudConnector = class {
|
|
|
241
773
|
}
|
|
242
774
|
};
|
|
243
775
|
export {
|
|
244
|
-
CloudConnector
|
|
776
|
+
CloudConnector,
|
|
777
|
+
DEFAULT_QODER_API_BASE_URL,
|
|
778
|
+
QODER_TOOL_NAME,
|
|
779
|
+
QoderApiClient,
|
|
780
|
+
QoderApiError,
|
|
781
|
+
QoderConnector,
|
|
782
|
+
formatQoderToolResult,
|
|
783
|
+
isConnectorEndpoint,
|
|
784
|
+
parseConnectorEndpoint,
|
|
785
|
+
parseQoderSse,
|
|
786
|
+
requireConnectorEndpoint
|
|
245
787
|
};
|