@mearl/cloud-connector 2.6.1 → 2.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +36 -2
- package/dist/__tests__/endpoint.test.d.ts +1 -0
- package/dist/__tests__/qoder-auth.test.d.ts +1 -0
- package/dist/__tests__/qoder.test.d.ts +1 -0
- package/dist/cli.js +646 -14
- package/dist/endpoint.d.ts +20 -0
- package/dist/index.d.ts +5 -1
- package/dist/index.js +649 -7
- package/dist/qoder-auth.d.ts +11 -0
- package/dist/qoder.d.ts +106 -0
- package/package.json +7 -6
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,551 @@ 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
|
+
|
|
106
|
+
// src/qoder-auth.ts
|
|
107
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
108
|
+
import { homedir, userInfo } from "node:os";
|
|
109
|
+
import { resolve } from "node:path";
|
|
110
|
+
import { spawnSync } from "node:child_process";
|
|
111
|
+
var QODER_TOKEN_KEY = "QODER_PERSONAL_ACCESS_TOKEN";
|
|
112
|
+
var QODER_KEYCHAIN_SERVICE = "com.mearl.qoder.pat";
|
|
113
|
+
function normalizeToken(value) {
|
|
114
|
+
const token = value?.trim();
|
|
115
|
+
if (!token || /[\r\n\0]/.test(token)) return void 0;
|
|
116
|
+
return token;
|
|
117
|
+
}
|
|
118
|
+
function envValue(text, key) {
|
|
119
|
+
for (const line of text.split(/\r?\n/)) {
|
|
120
|
+
const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$/.exec(line);
|
|
121
|
+
if (!match || match[1] !== key) continue;
|
|
122
|
+
let value = (match[2] ?? "").trim();
|
|
123
|
+
if (value.length >= 2 && (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'"))) {
|
|
124
|
+
value = value.slice(1, -1);
|
|
125
|
+
} else {
|
|
126
|
+
value = value.replace(/\s+#.*$/, "").trim();
|
|
127
|
+
}
|
|
128
|
+
return normalizeToken(value);
|
|
129
|
+
}
|
|
130
|
+
return void 0;
|
|
131
|
+
}
|
|
132
|
+
function readMacKeychainToken() {
|
|
133
|
+
const securityPath = "/usr/bin/security";
|
|
134
|
+
if (!existsSync(securityPath)) return void 0;
|
|
135
|
+
try {
|
|
136
|
+
const account = userInfo().username;
|
|
137
|
+
const result = spawnSync(
|
|
138
|
+
securityPath,
|
|
139
|
+
["find-generic-password", "-a", account, "-s", QODER_KEYCHAIN_SERVICE, "-w"],
|
|
140
|
+
{
|
|
141
|
+
encoding: "utf8",
|
|
142
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
143
|
+
timeout: 5e3,
|
|
144
|
+
windowsHide: true
|
|
145
|
+
}
|
|
146
|
+
);
|
|
147
|
+
return result.status === 0 ? normalizeToken(result.stdout) : void 0;
|
|
148
|
+
} catch {
|
|
149
|
+
return void 0;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
function resolveQoderPersonalAccessToken(options = {}) {
|
|
153
|
+
const direct = normalizeToken(options.token);
|
|
154
|
+
if (direct) return direct;
|
|
155
|
+
const env = options.env ?? process.env;
|
|
156
|
+
const inherited = normalizeToken(env[QODER_TOKEN_KEY]);
|
|
157
|
+
if (inherited) return inherited;
|
|
158
|
+
const homeDirectory = options.homeDirectory ?? homedir();
|
|
159
|
+
const envFiles = [
|
|
160
|
+
...env.MEARL_ENV_FILE?.trim() ? [resolve(env.MEARL_ENV_FILE)] : [],
|
|
161
|
+
resolve(homeDirectory, ".mearl", ".env")
|
|
162
|
+
];
|
|
163
|
+
const readFile = options.readFile ?? ((file) => readFileSync(file, "utf8"));
|
|
164
|
+
for (const file of new Set(envFiles)) {
|
|
165
|
+
try {
|
|
166
|
+
const token = envValue(readFile(file), QODER_TOKEN_KEY);
|
|
167
|
+
if (token) return token;
|
|
168
|
+
} catch {
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
if ((options.platform ?? process.platform) !== "darwin") return void 0;
|
|
172
|
+
return normalizeToken((options.readKeychainToken ?? readMacKeychainToken)());
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// src/qoder.ts
|
|
176
|
+
var QODER_TOOL_NAME = "mearl";
|
|
177
|
+
var DEFAULT_QODER_API_BASE_URL = "https://api.qoder.com";
|
|
178
|
+
var DEFAULT_DISCOVERY_WINDOW_MS = 60 * 60 * 1e3;
|
|
179
|
+
var DEFAULT_RECONNECT_INTERVAL_MS = 5e3;
|
|
180
|
+
var MAX_RECENT_SESSIONS = 100;
|
|
181
|
+
var MAX_RECENT_TOOL_EVENTS = 20;
|
|
182
|
+
var MAX_CACHED_RESULTS = 100;
|
|
183
|
+
var QoderApiError = class extends Error {
|
|
184
|
+
constructor(message, status) {
|
|
185
|
+
super(message);
|
|
186
|
+
this.status = status;
|
|
187
|
+
this.name = "QoderApiError";
|
|
188
|
+
}
|
|
189
|
+
};
|
|
190
|
+
function safeJson(value) {
|
|
191
|
+
try {
|
|
192
|
+
return JSON.stringify(value ?? null);
|
|
193
|
+
} catch {
|
|
194
|
+
return JSON.stringify({ error: "Mearl returned a value that cannot be serialized" });
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
function isRecord(value) {
|
|
198
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
199
|
+
}
|
|
200
|
+
function asScreenshot(value) {
|
|
201
|
+
if (!isRecord(value) || typeof value.data !== "string" || !isRecord(value.meta)) return null;
|
|
202
|
+
const format = value.meta.format;
|
|
203
|
+
if (format !== "png" && format !== "jpeg") return null;
|
|
204
|
+
return { data: value.data, meta: { ...value.meta, format } };
|
|
205
|
+
}
|
|
206
|
+
function extractBatchScreenshots(value) {
|
|
207
|
+
if (!isRecord(value) || !Array.isArray(value.results)) return null;
|
|
208
|
+
const screenshots = [];
|
|
209
|
+
const results = value.results.map((result) => {
|
|
210
|
+
if (!isRecord(result) || result.action !== "page_screenshot") return result;
|
|
211
|
+
const screenshot = asScreenshot(result.data);
|
|
212
|
+
if (!screenshot) return result;
|
|
213
|
+
const data = { ...result.data };
|
|
214
|
+
delete data.data;
|
|
215
|
+
data.meta = screenshot.meta;
|
|
216
|
+
data.imageContentIndex = screenshots.length + 1;
|
|
217
|
+
screenshots.push(screenshot);
|
|
218
|
+
return { ...result, data };
|
|
219
|
+
});
|
|
220
|
+
if (screenshots.length === 0) return null;
|
|
221
|
+
return { metadata: { ...value, results }, screenshots };
|
|
222
|
+
}
|
|
223
|
+
function imageContentBlock(screenshot) {
|
|
224
|
+
return {
|
|
225
|
+
type: "image",
|
|
226
|
+
source: {
|
|
227
|
+
type: "base64",
|
|
228
|
+
media_type: `image/${screenshot.meta.format}`,
|
|
229
|
+
data: screenshot.data
|
|
230
|
+
}
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
function formatQoderToolResult(value) {
|
|
234
|
+
const directScreenshot = asScreenshot(value);
|
|
235
|
+
const nestedScreenshot = !directScreenshot && isRecord(value) ? asScreenshot(value.screenshot) : null;
|
|
236
|
+
const screenshot = directScreenshot ?? nestedScreenshot;
|
|
237
|
+
if (!screenshot) {
|
|
238
|
+
const batch = extractBatchScreenshots(value);
|
|
239
|
+
if (batch) {
|
|
240
|
+
return {
|
|
241
|
+
content: [
|
|
242
|
+
{ type: "text", text: safeJson(batch.metadata) },
|
|
243
|
+
...batch.screenshots.map(imageContentBlock)
|
|
244
|
+
],
|
|
245
|
+
fallbackContent: [{ type: "text", text: safeJson(value) }]
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
if (!screenshot) {
|
|
250
|
+
const content = [{ type: "text", text: safeJson(value) }];
|
|
251
|
+
return { content, fallbackContent: content };
|
|
252
|
+
}
|
|
253
|
+
let metadata;
|
|
254
|
+
if (directScreenshot) {
|
|
255
|
+
metadata = { meta: screenshot.meta };
|
|
256
|
+
} else {
|
|
257
|
+
metadata = { ...value, screenshot: { meta: screenshot.meta } };
|
|
258
|
+
}
|
|
259
|
+
return {
|
|
260
|
+
content: [{ type: "text", text: safeJson(metadata) }, imageContentBlock(screenshot)],
|
|
261
|
+
fallbackContent: [{ type: "text", text: safeJson(value) }]
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
function pairingCodeFromEvent(event) {
|
|
265
|
+
if (event.type !== "agent.custom_tool_use" || event.name !== QODER_TOOL_NAME) return null;
|
|
266
|
+
if (!isRecord(event.input) || event.input.action !== "pair") return null;
|
|
267
|
+
const payload = isRecord(event.input.payload) ? event.input.payload : isRecord(event.input.data) ? event.input.data : null;
|
|
268
|
+
return payload && typeof payload.code === "string" ? payload.code : null;
|
|
269
|
+
}
|
|
270
|
+
function qoderErrorMessage(status, body) {
|
|
271
|
+
try {
|
|
272
|
+
const parsed = JSON.parse(body);
|
|
273
|
+
const message = parsed.error?.message ?? parsed.message;
|
|
274
|
+
if (typeof message === "string" && message.trim()) return message.trim();
|
|
275
|
+
} catch {
|
|
276
|
+
}
|
|
277
|
+
return `Qoder API request failed with HTTP ${status}`;
|
|
278
|
+
}
|
|
279
|
+
var QoderApiClient = class {
|
|
280
|
+
constructor(token, baseUrl = DEFAULT_QODER_API_BASE_URL, fetchImpl = fetch) {
|
|
281
|
+
this.token = token;
|
|
282
|
+
this.fetchImpl = fetchImpl;
|
|
283
|
+
const parsed = new URL(baseUrl);
|
|
284
|
+
if (parsed.protocol !== "https:" && parsed.hostname !== "localhost" && parsed.hostname !== "127.0.0.1") {
|
|
285
|
+
throw new Error("Qoder API base URL must use https:// (localhost may use http:// for tests)");
|
|
286
|
+
}
|
|
287
|
+
this.baseUrl = parsed.toString().replace(/\/$/, "");
|
|
288
|
+
}
|
|
289
|
+
baseUrl;
|
|
290
|
+
async request(path, init = {}) {
|
|
291
|
+
const response = await this.fetchImpl(`${this.baseUrl}${path}`, {
|
|
292
|
+
...init,
|
|
293
|
+
headers: {
|
|
294
|
+
Authorization: `Bearer ${this.token}`,
|
|
295
|
+
...init.headers
|
|
296
|
+
}
|
|
297
|
+
});
|
|
298
|
+
if (!response.ok) {
|
|
299
|
+
const body = await response.text();
|
|
300
|
+
throw new QoderApiError(qoderErrorMessage(response.status, body), response.status);
|
|
301
|
+
}
|
|
302
|
+
return response;
|
|
303
|
+
}
|
|
304
|
+
async listSessions(createdAfter, signal) {
|
|
305
|
+
const query = new URLSearchParams({
|
|
306
|
+
limit: String(MAX_RECENT_SESSIONS),
|
|
307
|
+
order: "desc",
|
|
308
|
+
"created_at[gte]": createdAfter
|
|
309
|
+
});
|
|
310
|
+
const response = await this.request(`/api/v1/cloud/sessions?${query}`, { signal });
|
|
311
|
+
const body = await response.json();
|
|
312
|
+
return Array.isArray(body.data) ? body.data.filter((session) => typeof session.id === "string") : [];
|
|
313
|
+
}
|
|
314
|
+
async listCustomToolEvents(sessionId, createdAfter, signal) {
|
|
315
|
+
const query = new URLSearchParams({
|
|
316
|
+
limit: String(MAX_RECENT_TOOL_EVENTS),
|
|
317
|
+
order: "desc",
|
|
318
|
+
types: "agent.custom_tool_use",
|
|
319
|
+
"created_at[gte]": createdAfter
|
|
320
|
+
});
|
|
321
|
+
const response = await this.request(
|
|
322
|
+
`/api/v1/cloud/sessions/${encodeURIComponent(sessionId)}/events?${query}`,
|
|
323
|
+
{ signal }
|
|
324
|
+
);
|
|
325
|
+
const body = await response.json();
|
|
326
|
+
return Array.isArray(body.data) ? body.data : [];
|
|
327
|
+
}
|
|
328
|
+
async findPairingRequest(pairingCode, createdAfter, signal) {
|
|
329
|
+
const sessions = await this.listSessions(createdAfter, signal);
|
|
330
|
+
for (const session of sessions) {
|
|
331
|
+
const events = await this.listCustomToolEvents(session.id, createdAfter, signal);
|
|
332
|
+
const event = events.find((candidate) => pairingCodeFromEvent(candidate) === pairingCode);
|
|
333
|
+
if (event?.id) return { sessionId: session.id, event: { ...event, id: event.id } };
|
|
334
|
+
}
|
|
335
|
+
return null;
|
|
336
|
+
}
|
|
337
|
+
async sendCustomToolResult(sessionId, customToolUseId, content, isError = false, signal) {
|
|
338
|
+
const response = await this.request(
|
|
339
|
+
`/api/v1/cloud/sessions/${encodeURIComponent(sessionId)}/events`,
|
|
340
|
+
{
|
|
341
|
+
method: "POST",
|
|
342
|
+
headers: { "Content-Type": "application/json" },
|
|
343
|
+
signal,
|
|
344
|
+
body: JSON.stringify({
|
|
345
|
+
events: [
|
|
346
|
+
{
|
|
347
|
+
type: "user.custom_tool_result",
|
|
348
|
+
custom_tool_use_id: customToolUseId,
|
|
349
|
+
content,
|
|
350
|
+
is_error: isError
|
|
351
|
+
}
|
|
352
|
+
]
|
|
353
|
+
})
|
|
354
|
+
}
|
|
355
|
+
);
|
|
356
|
+
const body = await response.json();
|
|
357
|
+
return body.data?.[0]?.id;
|
|
358
|
+
}
|
|
359
|
+
async streamEvents(sessionId, lastEventId, signal, onFrame, onOpen) {
|
|
360
|
+
const response = await this.request(
|
|
361
|
+
`/api/v1/cloud/sessions/${encodeURIComponent(sessionId)}/events/stream`,
|
|
362
|
+
{
|
|
363
|
+
headers: {
|
|
364
|
+
Accept: "text/event-stream",
|
|
365
|
+
...lastEventId ? { "Last-Event-ID": lastEventId } : {}
|
|
366
|
+
},
|
|
367
|
+
signal
|
|
368
|
+
}
|
|
369
|
+
);
|
|
370
|
+
if (!response.body) throw new Error("Qoder event stream returned no response body");
|
|
371
|
+
onOpen?.();
|
|
372
|
+
await parseQoderSse(response.body, onFrame);
|
|
373
|
+
}
|
|
374
|
+
};
|
|
375
|
+
async function parseQoderSse(body, onFrame) {
|
|
376
|
+
const reader = body.getReader();
|
|
377
|
+
const decoder = new TextDecoder();
|
|
378
|
+
let buffer = "";
|
|
379
|
+
let frameLines = [];
|
|
380
|
+
const dispatch = async () => {
|
|
381
|
+
if (frameLines.length === 0) return;
|
|
382
|
+
let id;
|
|
383
|
+
let event;
|
|
384
|
+
const data = [];
|
|
385
|
+
for (const line of frameLines) {
|
|
386
|
+
if (!line || line.startsWith(":")) continue;
|
|
387
|
+
const separator = line.indexOf(":");
|
|
388
|
+
const field = separator === -1 ? line : line.slice(0, separator);
|
|
389
|
+
const value = separator === -1 ? "" : line.slice(separator + 1).replace(/^ /, "");
|
|
390
|
+
if (field === "id") id = value;
|
|
391
|
+
else if (field === "event") event = value;
|
|
392
|
+
else if (field === "data") data.push(value);
|
|
393
|
+
}
|
|
394
|
+
frameLines = [];
|
|
395
|
+
if (data.length === 0) return;
|
|
396
|
+
const parsed = JSON.parse(data.join("\n"));
|
|
397
|
+
await onFrame({ ...id ? { id } : {}, ...event ? { event } : {}, data: parsed });
|
|
398
|
+
};
|
|
399
|
+
while (true) {
|
|
400
|
+
const { done, value } = await reader.read();
|
|
401
|
+
buffer += decoder.decode(value, { stream: !done });
|
|
402
|
+
let newlineIndex;
|
|
403
|
+
while ((newlineIndex = buffer.indexOf("\n")) !== -1) {
|
|
404
|
+
const line = buffer.slice(0, newlineIndex).replace(/\r$/, "");
|
|
405
|
+
buffer = buffer.slice(newlineIndex + 1);
|
|
406
|
+
if (line === "") await dispatch();
|
|
407
|
+
else frameLines.push(line);
|
|
408
|
+
}
|
|
409
|
+
if (done) break;
|
|
410
|
+
}
|
|
411
|
+
if (buffer) frameLines.push(buffer.replace(/\r$/, ""));
|
|
412
|
+
await dispatch();
|
|
413
|
+
}
|
|
414
|
+
function defaultSleep(milliseconds, signal) {
|
|
415
|
+
return new Promise((resolve2, reject) => {
|
|
416
|
+
if (signal.aborted) {
|
|
417
|
+
reject(signal.reason ?? new Error("Aborted"));
|
|
418
|
+
return;
|
|
419
|
+
}
|
|
420
|
+
const onAbort = () => {
|
|
421
|
+
clearTimeout(timer);
|
|
422
|
+
reject(signal.reason ?? new Error("Aborted"));
|
|
423
|
+
};
|
|
424
|
+
const timer = setTimeout(() => {
|
|
425
|
+
signal.removeEventListener("abort", onAbort);
|
|
426
|
+
resolve2();
|
|
427
|
+
}, milliseconds);
|
|
428
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
async function defaultInvokeAction(action, payload, options) {
|
|
432
|
+
const client = await import("@mearl/client/local");
|
|
433
|
+
return client.invoke(action, payload, {
|
|
434
|
+
browser: options.browser,
|
|
435
|
+
timeoutSec: options.timeoutSec,
|
|
436
|
+
controlSource: "remote"
|
|
437
|
+
});
|
|
438
|
+
}
|
|
439
|
+
function toolInput(event) {
|
|
440
|
+
if (!isRecord(event.input) || typeof event.input.action !== "string") {
|
|
441
|
+
throw new Error("Qoder mearl tool input requires a string action");
|
|
442
|
+
}
|
|
443
|
+
const browser = typeof event.input.browser === "string" ? event.input.browser : void 0;
|
|
444
|
+
const timeoutSec = typeof event.input.timeoutSec === "number" && Number.isFinite(event.input.timeoutSec) ? event.input.timeoutSec : void 0;
|
|
445
|
+
const payloadValue = event.input.payload ?? event.input.data ?? {};
|
|
446
|
+
if (!isRecord(payloadValue)) {
|
|
447
|
+
throw new Error("Qoder mearl tool input payload must be an object");
|
|
448
|
+
}
|
|
449
|
+
return {
|
|
450
|
+
action: event.input.action,
|
|
451
|
+
payload: payloadValue,
|
|
452
|
+
...browser ? { browser } : {},
|
|
453
|
+
...timeoutSec === void 0 ? {} : { timeoutSec }
|
|
454
|
+
};
|
|
455
|
+
}
|
|
456
|
+
var QoderConnector = class {
|
|
457
|
+
constructor(options) {
|
|
458
|
+
this.options = options;
|
|
459
|
+
const token = resolveQoderPersonalAccessToken({ token: options.token });
|
|
460
|
+
if (!token) {
|
|
461
|
+
throw new Error(
|
|
462
|
+
"Qoder authentication is required. Set QODER_PERSONAL_ACCESS_TOKEN, add it to ~/.mearl/.env, or configure the macOS Keychain item com.mearl.qoder.pat, then retry."
|
|
463
|
+
);
|
|
464
|
+
}
|
|
465
|
+
this.api = new QoderApiClient(
|
|
466
|
+
token,
|
|
467
|
+
options.apiBaseUrl ?? DEFAULT_QODER_API_BASE_URL,
|
|
468
|
+
options.fetchImpl
|
|
469
|
+
);
|
|
470
|
+
this.now = options.now ?? Date.now;
|
|
471
|
+
this.sleep = options.sleep ?? defaultSleep;
|
|
472
|
+
this.invokeAction = options.invokeAction ?? defaultInvokeAction;
|
|
473
|
+
this.reconnectInterval = options.reconnectInterval ?? DEFAULT_RECONNECT_INTERVAL_MS;
|
|
474
|
+
this.maxReconnectAttempts = options.maxReconnectAttempts ?? -1;
|
|
475
|
+
}
|
|
476
|
+
api;
|
|
477
|
+
now;
|
|
478
|
+
sleep;
|
|
479
|
+
invokeAction;
|
|
480
|
+
reconnectInterval;
|
|
481
|
+
maxReconnectAttempts;
|
|
482
|
+
abortController = null;
|
|
483
|
+
reconnectAttempts = 0;
|
|
484
|
+
running = false;
|
|
485
|
+
connected = false;
|
|
486
|
+
sessionId = null;
|
|
487
|
+
lastEventId;
|
|
488
|
+
cachedResults = /* @__PURE__ */ new Map();
|
|
489
|
+
connect() {
|
|
490
|
+
if (this.running) return;
|
|
491
|
+
this.running = true;
|
|
492
|
+
this.abortController = new AbortController();
|
|
493
|
+
void this.run(this.abortController.signal);
|
|
494
|
+
}
|
|
495
|
+
disconnect() {
|
|
496
|
+
this.running = false;
|
|
497
|
+
this.abortController?.abort();
|
|
498
|
+
this.abortController = null;
|
|
499
|
+
}
|
|
500
|
+
async run(signal) {
|
|
501
|
+
while (!signal.aborted) {
|
|
502
|
+
try {
|
|
503
|
+
if (!this.sessionId) {
|
|
504
|
+
const pairing = await this.findPairing(signal);
|
|
505
|
+
await this.completePairing(pairing, signal);
|
|
506
|
+
}
|
|
507
|
+
const sessionId = this.sessionId;
|
|
508
|
+
await this.api.streamEvents(
|
|
509
|
+
sessionId,
|
|
510
|
+
this.lastEventId,
|
|
511
|
+
signal,
|
|
512
|
+
async (frame) => this.handleFrame(sessionId, frame, signal),
|
|
513
|
+
() => {
|
|
514
|
+
this.reconnectAttempts = 0;
|
|
515
|
+
}
|
|
516
|
+
);
|
|
517
|
+
if (!signal.aborted) throw new Error("Qoder event stream ended");
|
|
518
|
+
} catch (error) {
|
|
519
|
+
if (signal.aborted) return;
|
|
520
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
521
|
+
if (!this.connected && this.options.failFast) {
|
|
522
|
+
this.options.onInitialConnectionFailed?.(message);
|
|
523
|
+
this.running = false;
|
|
524
|
+
return;
|
|
525
|
+
}
|
|
526
|
+
this.reconnectAttempts += 1;
|
|
527
|
+
if (this.maxReconnectAttempts !== -1 && this.reconnectAttempts > this.maxReconnectAttempts) {
|
|
528
|
+
console.error(
|
|
529
|
+
`[CloudConnector] Qoder max reconnect attempts (${this.maxReconnectAttempts}) reached`
|
|
530
|
+
);
|
|
531
|
+
this.running = false;
|
|
532
|
+
return;
|
|
533
|
+
}
|
|
534
|
+
console.error(`[CloudConnector] Qoder connection error: ${message}`);
|
|
535
|
+
try {
|
|
536
|
+
await this.sleep(this.reconnectInterval, signal);
|
|
537
|
+
} catch {
|
|
538
|
+
return;
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
async findPairing(signal) {
|
|
544
|
+
const createdAt = this.options.endpoint.createdAt ?? this.now();
|
|
545
|
+
const createdAfter = new Date(createdAt - DEFAULT_DISCOVERY_WINDOW_MS).toISOString();
|
|
546
|
+
const pairing = await this.api.findPairingRequest(
|
|
547
|
+
this.options.endpoint.pairingCode,
|
|
548
|
+
createdAfter,
|
|
549
|
+
signal
|
|
550
|
+
);
|
|
551
|
+
if (!pairing) {
|
|
552
|
+
throw new Error(
|
|
553
|
+
'Qoder pairing request was not found. Ask the Agent to call the mearl tool with action "pair" and the code from this URL.'
|
|
554
|
+
);
|
|
555
|
+
}
|
|
556
|
+
return pairing;
|
|
557
|
+
}
|
|
558
|
+
async completePairing(pairing, signal) {
|
|
559
|
+
if (!this.connected) {
|
|
560
|
+
this.lastEventId = await this.api.sendCustomToolResult(
|
|
561
|
+
pairing.sessionId,
|
|
562
|
+
pairing.event.id,
|
|
563
|
+
[
|
|
564
|
+
{
|
|
565
|
+
type: "text",
|
|
566
|
+
text: safeJson({
|
|
567
|
+
connected: true,
|
|
568
|
+
connectorId: this.options.identity.connectorId,
|
|
569
|
+
name: this.options.identity.name
|
|
570
|
+
})
|
|
571
|
+
}
|
|
572
|
+
],
|
|
573
|
+
false,
|
|
574
|
+
signal
|
|
575
|
+
) ?? pairing.event.id;
|
|
576
|
+
this.sessionId = pairing.sessionId;
|
|
577
|
+
this.connected = true;
|
|
578
|
+
this.reconnectAttempts = 0;
|
|
579
|
+
this.options.onConnected?.();
|
|
580
|
+
console.log(`[CloudConnector] Connected to Qoder session ${pairing.sessionId}`);
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
async handleFrame(sessionId, frame, signal) {
|
|
584
|
+
this.reconnectAttempts = 0;
|
|
585
|
+
const event = frame.data;
|
|
586
|
+
const eventId = event.id ?? frame.id;
|
|
587
|
+
if (event.type !== "agent.custom_tool_use" || event.name !== QODER_TOOL_NAME || !eventId) {
|
|
588
|
+
if (eventId) this.lastEventId = eventId;
|
|
589
|
+
return;
|
|
590
|
+
}
|
|
591
|
+
const cached = this.cachedResults.get(eventId) ?? await this.executeTool(event);
|
|
592
|
+
this.rememberResult(eventId, cached);
|
|
593
|
+
try {
|
|
594
|
+
this.lastEventId = await this.api.sendCustomToolResult(
|
|
595
|
+
sessionId,
|
|
596
|
+
eventId,
|
|
597
|
+
cached.content,
|
|
598
|
+
cached.isError,
|
|
599
|
+
signal
|
|
600
|
+
) ?? eventId;
|
|
601
|
+
} catch (error) {
|
|
602
|
+
if (error instanceof QoderApiError && error.status === 400 && cached.content !== cached.fallbackContent) {
|
|
603
|
+
this.lastEventId = await this.api.sendCustomToolResult(
|
|
604
|
+
sessionId,
|
|
605
|
+
eventId,
|
|
606
|
+
cached.fallbackContent,
|
|
607
|
+
cached.isError,
|
|
608
|
+
signal
|
|
609
|
+
) ?? eventId;
|
|
610
|
+
return;
|
|
611
|
+
}
|
|
612
|
+
if (error instanceof QoderApiError && error.status === 404) {
|
|
613
|
+
this.lastEventId = eventId;
|
|
614
|
+
return;
|
|
615
|
+
}
|
|
616
|
+
throw error;
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
async executeTool(event) {
|
|
620
|
+
try {
|
|
621
|
+
const input = toolInput(event);
|
|
622
|
+
if (input.action === "pair") {
|
|
623
|
+
throw new Error("This pairing request does not match the active connector");
|
|
624
|
+
}
|
|
625
|
+
const result = await this.invokeAction(input.action, input.payload, {
|
|
626
|
+
browser: input.browser,
|
|
627
|
+
timeoutSec: input.timeoutSec ?? resolveActionTimeoutSec(input.action, input.payload, 15)
|
|
628
|
+
});
|
|
629
|
+
return { ...formatQoderToolResult(result), isError: false };
|
|
630
|
+
} catch (error) {
|
|
631
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
632
|
+
const content = [{ type: "text", text: safeJson({ error: message }) }];
|
|
633
|
+
return { content, fallbackContent: content, isError: true };
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
rememberResult(eventId, result) {
|
|
637
|
+
this.cachedResults.set(eventId, result);
|
|
638
|
+
while (this.cachedResults.size > MAX_CACHED_RESULTS) {
|
|
639
|
+
const oldest = this.cachedResults.keys().next().value;
|
|
640
|
+
if (!oldest) break;
|
|
641
|
+
this.cachedResults.delete(oldest);
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
};
|
|
645
|
+
|
|
48
646
|
// src/index.ts
|
|
49
|
-
var CLOUD_CONNECTOR_VERSION = true ? "2.
|
|
647
|
+
var CLOUD_CONNECTOR_VERSION = true ? "2.7.1" : "unknown";
|
|
50
648
|
var DEFAULT_RECONNECT_INTERVAL = 5e3;
|
|
51
649
|
var BACKOFF_BASE_MS = 1e3;
|
|
52
650
|
var BACKOFF_MAX_MS = 3e4;
|
|
@@ -54,7 +652,9 @@ var SLOW_PROBE_INTERVAL_MS = 6e4;
|
|
|
54
652
|
var FAST_RECONNECT_ATTEMPTS = 5;
|
|
55
653
|
var CloudConnector = class {
|
|
56
654
|
options;
|
|
655
|
+
endpoint;
|
|
57
656
|
identity;
|
|
657
|
+
qoderConnector = null;
|
|
58
658
|
ws = null;
|
|
59
659
|
heartbeatTimer = null;
|
|
60
660
|
reconnectTimer = null;
|
|
@@ -67,8 +667,9 @@ var CloudConnector = class {
|
|
|
67
667
|
hasConnected = false;
|
|
68
668
|
lastConnectionError = null;
|
|
69
669
|
constructor(options) {
|
|
670
|
+
this.endpoint = requireConnectorEndpoint(options.serverUrl);
|
|
70
671
|
this.options = {
|
|
71
|
-
serverUrl:
|
|
672
|
+
serverUrl: this.endpoint.serverUrl,
|
|
72
673
|
heartbeatInterval: options.heartbeatInterval ?? DEFAULT_HEARTBEAT_INTERVAL,
|
|
73
674
|
reconnectInterval: options.reconnectInterval ?? DEFAULT_RECONNECT_INTERVAL,
|
|
74
675
|
maxReconnectAttempts: options.maxReconnectAttempts ?? -1,
|
|
@@ -79,10 +680,39 @@ var CloudConnector = class {
|
|
|
79
680
|
this.identity = resolveConnectorIdentity(options);
|
|
80
681
|
}
|
|
81
682
|
connect() {
|
|
683
|
+
if (this.endpoint.scheme === "qoder") {
|
|
684
|
+
if (this.qoderConnector) {
|
|
685
|
+
this.qoderConnector.connect();
|
|
686
|
+
return;
|
|
687
|
+
}
|
|
688
|
+
try {
|
|
689
|
+
this.qoderConnector = new QoderConnector({
|
|
690
|
+
endpoint: this.endpoint,
|
|
691
|
+
identity: this.identity,
|
|
692
|
+
reconnectInterval: this.options.reconnectInterval,
|
|
693
|
+
maxReconnectAttempts: this.options.maxReconnectAttempts,
|
|
694
|
+
failFast: this.options.failFast,
|
|
695
|
+
onConnected: () => {
|
|
696
|
+
this.hasConnected = true;
|
|
697
|
+
this.options.onConnected?.(this.options.serverUrl, this.identity);
|
|
698
|
+
},
|
|
699
|
+
onInitialConnectionFailed: this.options.onInitialConnectionFailed
|
|
700
|
+
});
|
|
701
|
+
this.qoderConnector.connect();
|
|
702
|
+
} catch (error) {
|
|
703
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
704
|
+
if (this.options.onInitialConnectionFailed) {
|
|
705
|
+
this.options.onInitialConnectionFailed(message);
|
|
706
|
+
} else {
|
|
707
|
+
console.error(`[CloudConnector] Qoder connection error: ${message}`);
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
return;
|
|
711
|
+
}
|
|
82
712
|
if (this.ws && (this.ws.readyState === 0 || this.ws.readyState === 1)) {
|
|
83
713
|
return;
|
|
84
714
|
}
|
|
85
|
-
let serverUrl = this.
|
|
715
|
+
let serverUrl = this.endpoint.transportUrl;
|
|
86
716
|
if (this.shouldTryWss && serverUrl.startsWith("ws://")) {
|
|
87
717
|
serverUrl = serverUrl.replace("ws://", "wss://");
|
|
88
718
|
console.log(`[CloudConnector] Retrying with wss://: ${serverUrl}`);
|
|
@@ -133,6 +763,8 @@ var CloudConnector = class {
|
|
|
133
763
|
}
|
|
134
764
|
disconnect() {
|
|
135
765
|
this.isManualClose = true;
|
|
766
|
+
this.qoderConnector?.disconnect();
|
|
767
|
+
this.qoderConnector = null;
|
|
136
768
|
this.stopHeartbeat();
|
|
137
769
|
if (this.reconnectTimer) {
|
|
138
770
|
clearTimeout(this.reconnectTimer);
|
|
@@ -176,8 +808,8 @@ var CloudConnector = class {
|
|
|
176
808
|
const client = await import("@mearl/client/local");
|
|
177
809
|
const result = await client.invoke(action, data, {
|
|
178
810
|
browser,
|
|
179
|
-
timeoutSec: timeoutSec ??
|
|
180
|
-
controlSource: "
|
|
811
|
+
timeoutSec: timeoutSec ?? resolveActionTimeoutSec2(action, data, 15),
|
|
812
|
+
controlSource: "remote"
|
|
181
813
|
});
|
|
182
814
|
this.sendResponse({ id, success: true, data: result });
|
|
183
815
|
} catch (error) {
|
|
@@ -360,16 +992,13 @@ function runForeground(options) {
|
|
|
360
992
|
}
|
|
361
993
|
|
|
362
994
|
// src/cli.ts
|
|
363
|
-
var CLOUD_CONNECTOR_VERSION2 = true ? "2.
|
|
995
|
+
var CLOUD_CONNECTOR_VERSION2 = true ? "2.7.1" : "unknown";
|
|
364
996
|
var args = process.argv.slice(2);
|
|
365
997
|
if (args.includes("--version") || args.includes("-v")) {
|
|
366
998
|
console.log(CLOUD_CONNECTOR_VERSION2);
|
|
367
999
|
process.exit(0);
|
|
368
1000
|
}
|
|
369
1001
|
var SUBCOMMANDS = ["start", "stop", "restart", "status", "list", "logs"];
|
|
370
|
-
function isWsUrl(value) {
|
|
371
|
-
return !!value && (value.startsWith("ws://") || value.startsWith("wss://"));
|
|
372
|
-
}
|
|
373
1002
|
function showHelp() {
|
|
374
1003
|
console.error(`mearl-cloud-connector v${CLOUD_CONNECTOR_VERSION2}
|
|
375
1004
|
|
|
@@ -387,7 +1016,7 @@ Commands:
|
|
|
387
1016
|
logs <server-url> Print the tail of a connector's log
|
|
388
1017
|
|
|
389
1018
|
Arguments:
|
|
390
|
-
server-url
|
|
1019
|
+
server-url Connector URL (ws://, wss://, or qoder://)
|
|
391
1020
|
|
|
392
1021
|
Options:
|
|
393
1022
|
--foreground, -f Run in the foreground instead of daemonizing
|
|
@@ -404,6 +1033,9 @@ Examples:
|
|
|
404
1033
|
# Run in the foreground (Ctrl+C to stop) — also how native-host launches it
|
|
405
1034
|
mearl-cloud-connector "ws://localhost:8080/ws?token=xxx"
|
|
406
1035
|
|
|
1036
|
+
# Complete a Qoder custom-tool pairing created by @mearl/setup
|
|
1037
|
+
mearl-cloud-connector "qoder://pair/pairing-code-1234?created=1786723200000"
|
|
1038
|
+
|
|
407
1039
|
# Start/stop a self-managed background connector with its own log file
|
|
408
1040
|
mearl-cloud-connector start "wss://cloud.example.com/ws?token=xxx"
|
|
409
1041
|
mearl-cloud-connector status
|
|
@@ -432,7 +1064,7 @@ function parseConnectorOptions(rest) {
|
|
|
432
1064
|
return options;
|
|
433
1065
|
}
|
|
434
1066
|
function optionArgs(rest) {
|
|
435
|
-
return rest.filter((arg) => !
|
|
1067
|
+
return rest.filter((arg) => !isConnectorEndpoint(arg) && arg !== "--foreground" && arg !== "-f");
|
|
436
1068
|
}
|
|
437
1069
|
function exitHelp(message) {
|
|
438
1070
|
console.error(`Error: ${message}`);
|
|
@@ -455,9 +1087,9 @@ async function main() {
|
|
|
455
1087
|
rest = args.slice(1);
|
|
456
1088
|
}
|
|
457
1089
|
const foregroundFlag = rest.includes("--foreground") || rest.includes("-f");
|
|
458
|
-
const serverUrl = rest.find(
|
|
1090
|
+
const serverUrl = rest.find(isConnectorEndpoint);
|
|
459
1091
|
if (foregroundFlag || !command && serverUrl) {
|
|
460
|
-
if (!serverUrl) exitHelp("server-url must
|
|
1092
|
+
if (!serverUrl) exitHelp("server-url must use ws://, wss://, or qoder://");
|
|
461
1093
|
const options = {
|
|
462
1094
|
serverUrl,
|
|
463
1095
|
...parseConnectorOptions(optionArgs(rest))
|