@agentproto/collect 0.0.0 → 0.1.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 +599 -2
- package/dist/chunk-FQLYZIVI.mjs +405 -0
- package/dist/chunk-FQLYZIVI.mjs.map +1 -0
- package/dist/chunk-SOLT3HJH.mjs +213 -0
- package/dist/chunk-SOLT3HJH.mjs.map +1 -0
- package/dist/chunk-SYTQ6RN6.mjs +98 -0
- package/dist/chunk-SYTQ6RN6.mjs.map +1 -0
- package/dist/connector-DUNy3vSU.d.ts +981 -0
- package/dist/connectors.d.ts +104 -0
- package/dist/connectors.mjs +1197 -0
- package/dist/connectors.mjs.map +1 -0
- package/dist/engine-BRXHKg5A.d.ts +384 -0
- package/dist/index.d.ts +88 -583
- package/dist/index.mjs +1463 -317
- package/dist/index.mjs.map +1 -1
- package/dist/node.d.ts +526 -0
- package/dist/node.mjs +2322 -0
- package/dist/node.mjs.map +1 -0
- package/package.json +13 -2
package/dist/node.mjs
ADDED
|
@@ -0,0 +1,2322 @@
|
|
|
1
|
+
import { STORE_SCHEMA_VERSION, StoreVersionError, makeReader, assertSafeName, lastWins, sha256Bytes, rawRef, RawIndexEntry, parseRawRef, sourceOf, dropRedone, observationRedoKey, actorRedoKey, pickupRedoKey, itemSeenKeys, recipeHash, RunRecord, TaskRecord, PlanEntry, SamplingRecord, EventRecord, StoreLockedError } from './chunk-SOLT3HJH.mjs';
|
|
2
|
+
import { CollectItem, Observation, Actor, Pickup, Recipe, RunReport, TransportError, MissingSecretError } from './chunk-FQLYZIVI.mjs';
|
|
3
|
+
import { randomBytes } from 'crypto';
|
|
4
|
+
import { createReadStream } from 'fs';
|
|
5
|
+
import { mkdir, appendFile, rm, rename, link, writeFile, open, stat, readdir, readFile } from 'fs/promises';
|
|
6
|
+
import { hostname } from 'os';
|
|
7
|
+
import { join, dirname } from 'path';
|
|
8
|
+
import { createInterface } from 'readline';
|
|
9
|
+
import { gunzipSync, gzipSync } from 'zlib';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* @agentproto/collect
|
|
13
|
+
* Schemas, ids, URL canonicalisation and text fingerprints for collected public content.
|
|
14
|
+
*/
|
|
15
|
+
var StoreNotFoundError = class extends Error {
|
|
16
|
+
constructor(path) {
|
|
17
|
+
super(`no collect store at ${path} (missing collect.json); create it with initStore()`);
|
|
18
|
+
this.path = path;
|
|
19
|
+
this.name = "StoreNotFoundError";
|
|
20
|
+
}
|
|
21
|
+
path;
|
|
22
|
+
code = "STORE_NOT_FOUND";
|
|
23
|
+
};
|
|
24
|
+
var StoreMigrationError = class extends Error {
|
|
25
|
+
code = "STORE_MIGRATION";
|
|
26
|
+
constructor(message) {
|
|
27
|
+
super(message);
|
|
28
|
+
this.name = "StoreMigrationError";
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
var LOCK_FILE = "collect.lock";
|
|
32
|
+
function defaultPidAlive(pid) {
|
|
33
|
+
try {
|
|
34
|
+
process.kill(pid, 0);
|
|
35
|
+
return true;
|
|
36
|
+
} catch (e) {
|
|
37
|
+
return e.code === "EPERM";
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
var isEnoent = (e) => e?.code === "ENOENT";
|
|
41
|
+
var isEexist = (e) => e?.code === "EEXIST";
|
|
42
|
+
async function exists(path) {
|
|
43
|
+
try {
|
|
44
|
+
await stat(path);
|
|
45
|
+
return true;
|
|
46
|
+
} catch (e) {
|
|
47
|
+
if (isEnoent(e)) return false;
|
|
48
|
+
throw e;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
async function readdirOrEmpty(path) {
|
|
52
|
+
try {
|
|
53
|
+
return await readdir(path);
|
|
54
|
+
} catch (e) {
|
|
55
|
+
if (isEnoent(e)) return [];
|
|
56
|
+
throw e;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
async function readFileOrUndefined(path) {
|
|
60
|
+
try {
|
|
61
|
+
return await readFile(path);
|
|
62
|
+
} catch (e) {
|
|
63
|
+
if (isEnoent(e)) return void 0;
|
|
64
|
+
throw e;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
async function writeAtomic(path, data) {
|
|
68
|
+
await mkdir(dirname(path), { recursive: true });
|
|
69
|
+
const tmp = `${path}.${randomBytes(4).toString("hex")}.tmp`;
|
|
70
|
+
await writeFile(tmp, data);
|
|
71
|
+
await rename(tmp, path);
|
|
72
|
+
}
|
|
73
|
+
async function createExclusive(path, data) {
|
|
74
|
+
await mkdir(dirname(path), { recursive: true });
|
|
75
|
+
const tmp = `${path}.${randomBytes(6).toString("hex")}.tmp`;
|
|
76
|
+
await writeFile(tmp, data);
|
|
77
|
+
try {
|
|
78
|
+
await link(tmp, path);
|
|
79
|
+
return true;
|
|
80
|
+
} catch (e) {
|
|
81
|
+
if (isEexist(e)) return false;
|
|
82
|
+
throw e;
|
|
83
|
+
} finally {
|
|
84
|
+
await rm(tmp, { force: true });
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
async function hasTornTail(path) {
|
|
88
|
+
let fh;
|
|
89
|
+
try {
|
|
90
|
+
fh = await open(path, "r");
|
|
91
|
+
} catch (e) {
|
|
92
|
+
if (isEnoent(e)) return false;
|
|
93
|
+
throw e;
|
|
94
|
+
}
|
|
95
|
+
try {
|
|
96
|
+
const { size } = await fh.stat();
|
|
97
|
+
if (size === 0) return false;
|
|
98
|
+
const buf = Buffer.alloc(1);
|
|
99
|
+
await fh.read(buf, 0, 1, size - 1);
|
|
100
|
+
return buf[0] !== 10;
|
|
101
|
+
} finally {
|
|
102
|
+
await fh.close();
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
async function readVersion(root) {
|
|
106
|
+
const file = join(root, "collect.json");
|
|
107
|
+
const buf = await readFileOrUndefined(file);
|
|
108
|
+
if (!buf) return void 0;
|
|
109
|
+
let v;
|
|
110
|
+
try {
|
|
111
|
+
v = JSON.parse(buf.toString("utf8")).schemaVersion;
|
|
112
|
+
} catch {
|
|
113
|
+
throw new StoreMigrationError(`${file} is not valid JSON`);
|
|
114
|
+
}
|
|
115
|
+
if (typeof v !== "number" || !Number.isInteger(v) || v < 0) {
|
|
116
|
+
throw new StoreMigrationError(`${file} has no valid schemaVersion`);
|
|
117
|
+
}
|
|
118
|
+
return v;
|
|
119
|
+
}
|
|
120
|
+
async function writeVersion(root, version) {
|
|
121
|
+
await writeAtomic(join(root, "collect.json"), `${JSON.stringify({ schemaVersion: version })}
|
|
122
|
+
`);
|
|
123
|
+
}
|
|
124
|
+
async function initStore(path, options = {}) {
|
|
125
|
+
if (await readVersion(path) === void 0) {
|
|
126
|
+
await createExclusive(join(path, "collect.json"), `${JSON.stringify({ schemaVersion: STORE_SCHEMA_VERSION })}
|
|
127
|
+
`);
|
|
128
|
+
}
|
|
129
|
+
return openStore(path, options);
|
|
130
|
+
}
|
|
131
|
+
async function openStore(path, options = {}) {
|
|
132
|
+
let version = await readVersion(path);
|
|
133
|
+
if (version === void 0) throw new StoreNotFoundError(path);
|
|
134
|
+
if (version > STORE_SCHEMA_VERSION) throw new StoreVersionError(version, STORE_SCHEMA_VERSION);
|
|
135
|
+
const store = new DiskStore(path, options.now ?? (() => (/* @__PURE__ */ new Date()).toISOString()), options.pidAlive ?? defaultPidAlive);
|
|
136
|
+
if (version < STORE_SCHEMA_VERSION) {
|
|
137
|
+
const lock = await store.lockOnly();
|
|
138
|
+
try {
|
|
139
|
+
version = await readVersion(path);
|
|
140
|
+
if (version === void 0) throw new StoreNotFoundError(path);
|
|
141
|
+
if (version > STORE_SCHEMA_VERSION) throw new StoreVersionError(version, STORE_SCHEMA_VERSION);
|
|
142
|
+
while (version < STORE_SCHEMA_VERSION) {
|
|
143
|
+
const step = options.migrations?.[version];
|
|
144
|
+
if (!step) throw new StoreMigrationError(`no migration from store schema version ${version} to ${version + 1}`);
|
|
145
|
+
await step({ root: path });
|
|
146
|
+
version += 1;
|
|
147
|
+
await writeVersion(path, version);
|
|
148
|
+
}
|
|
149
|
+
} finally {
|
|
150
|
+
await lock.release();
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
await store.reloadSeen();
|
|
154
|
+
return store;
|
|
155
|
+
}
|
|
156
|
+
function seenText(m) {
|
|
157
|
+
return [...m].map(([k, v]) => `${v === void 0 ? k : `${k} ${v}`}
|
|
158
|
+
`).join("");
|
|
159
|
+
}
|
|
160
|
+
var DiskStore = class {
|
|
161
|
+
constructor(root, now, pidAlive) {
|
|
162
|
+
this.root = root;
|
|
163
|
+
this.now = now;
|
|
164
|
+
this.pidAlive = pidAlive;
|
|
165
|
+
}
|
|
166
|
+
root;
|
|
167
|
+
now;
|
|
168
|
+
pidAlive;
|
|
169
|
+
/** Writes of this process, run one after the other. */
|
|
170
|
+
queue = Promise.resolve();
|
|
171
|
+
lockToken;
|
|
172
|
+
/** Log files whose tail was checked for a torn line since this handle started. */
|
|
173
|
+
tailChecked = /* @__PURE__ */ new Set();
|
|
174
|
+
/** Dedup key to the id of the item that owns it (`undefined` for a line written without an owner). */
|
|
175
|
+
seen = /* @__PURE__ */ new Map();
|
|
176
|
+
p(...parts) {
|
|
177
|
+
return join(this.root, ...parts);
|
|
178
|
+
}
|
|
179
|
+
enqueue(fn) {
|
|
180
|
+
const run = this.queue.then(fn);
|
|
181
|
+
this.queue = run.catch(() => void 0);
|
|
182
|
+
return run;
|
|
183
|
+
}
|
|
184
|
+
async drain() {
|
|
185
|
+
await this.queue;
|
|
186
|
+
}
|
|
187
|
+
/** Append one JSON line. Runs inside the queue. A torn tail left by a crash is closed with a newline first, so it stays one skipped line. */
|
|
188
|
+
async appendLine(path, text) {
|
|
189
|
+
await mkdir(dirname(path), { recursive: true });
|
|
190
|
+
if (!this.tailChecked.has(path)) {
|
|
191
|
+
if (await hasTornTail(path)) await appendFile(path, "\n");
|
|
192
|
+
this.tailChecked.add(path);
|
|
193
|
+
}
|
|
194
|
+
try {
|
|
195
|
+
await appendFile(path, `${text}
|
|
196
|
+
`);
|
|
197
|
+
} catch (e) {
|
|
198
|
+
this.tailChecked.delete(path);
|
|
199
|
+
throw e;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
append(path, record) {
|
|
203
|
+
const text = JSON.stringify(record);
|
|
204
|
+
return this.enqueue(() => this.appendLine(path, text));
|
|
205
|
+
}
|
|
206
|
+
/** Lines of a JSONL file as records. Unreadable lines are reported through `onSkip`. Does not wait for the queue. */
|
|
207
|
+
async *readLines(path, schema, onSkip) {
|
|
208
|
+
if (!await exists(path)) return;
|
|
209
|
+
const rl = createInterface({ input: createReadStream(path, { encoding: "utf8" }), crlfDelay: Infinity });
|
|
210
|
+
for await (const line of rl) {
|
|
211
|
+
if (line.trim() === "") continue;
|
|
212
|
+
let value;
|
|
213
|
+
try {
|
|
214
|
+
value = JSON.parse(line);
|
|
215
|
+
} catch {
|
|
216
|
+
onSkip();
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
const parsed = schema.safeParse(value);
|
|
220
|
+
if (parsed.success) yield parsed.data;
|
|
221
|
+
else onSkip();
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
lines(path, schema) {
|
|
225
|
+
const self = this;
|
|
226
|
+
return makeReader(async function* (onSkip) {
|
|
227
|
+
await self.drain();
|
|
228
|
+
yield* self.readLines(path, schema, onSkip);
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
async *readMulti(dir, source, schema, onSkip) {
|
|
232
|
+
const names = source !== void 0 ? [`${assertSafeName("source", source)}.jsonl`] : (await readdirOrEmpty(this.p(dir))).filter((n) => n.endsWith(".jsonl")).sort();
|
|
233
|
+
for (const name of names) yield* this.readLines(this.p(dir, name), schema, onSkip);
|
|
234
|
+
}
|
|
235
|
+
multi(dir, source, schema) {
|
|
236
|
+
const self = this;
|
|
237
|
+
return makeReader(async function* (onSkip) {
|
|
238
|
+
await self.drain();
|
|
239
|
+
yield* self.readMulti(dir, source, schema, onSkip);
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
async *readItems(source, onSkip) {
|
|
243
|
+
yield* lastWins(this.readMulti("items", source, CollectItem, onSkip), (i) => i.id);
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Replace the in-memory seen set with the content of `seen.idx`, streamed.
|
|
247
|
+
* A last line without a newline is a torn append: it is ignored, and when we
|
|
248
|
+
* hold the lock the file is rewritten without it. This differs on purpose from
|
|
249
|
+
* the JSONL logs, where a torn line is skipped on read and closed with a
|
|
250
|
+
* newline on append: a half-written key is a valid but wrong key, so it must
|
|
251
|
+
* never count as seen. The cost is that a key whose only missing byte was the
|
|
252
|
+
* newline is forgotten and may be added again (a spurious re-fetch, no corruption).
|
|
253
|
+
*/
|
|
254
|
+
async reloadSeen() {
|
|
255
|
+
await this.enqueue(async () => {
|
|
256
|
+
const path = this.p("seen.idx");
|
|
257
|
+
const next = /* @__PURE__ */ new Map();
|
|
258
|
+
const add = (line) => {
|
|
259
|
+
const tab = line.indexOf(" ");
|
|
260
|
+
const key = tab < 0 ? line : line.slice(0, tab);
|
|
261
|
+
const owner = tab < 0 ? void 0 : line.slice(tab + 1) || void 0;
|
|
262
|
+
if (!next.has(key) || next.get(key) === void 0 && owner !== void 0) next.set(key, owner);
|
|
263
|
+
};
|
|
264
|
+
const torn = await hasTornTail(path);
|
|
265
|
+
if (await exists(path)) {
|
|
266
|
+
const rl = createInterface({ input: createReadStream(path, { encoding: "utf8" }), crlfDelay: Infinity });
|
|
267
|
+
let last;
|
|
268
|
+
for await (const line of rl) {
|
|
269
|
+
if (last !== void 0 && last !== "") add(last);
|
|
270
|
+
last = line;
|
|
271
|
+
}
|
|
272
|
+
if (last !== void 0 && last !== "" && !torn) add(last);
|
|
273
|
+
}
|
|
274
|
+
if (torn && this.lockToken) await writeAtomic(path, seenText(next));
|
|
275
|
+
this.seen.clear();
|
|
276
|
+
for (const [k, v] of next) this.seen.set(k, v);
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
async schemaVersion() {
|
|
280
|
+
return await readVersion(this.root) ?? STORE_SCHEMA_VERSION;
|
|
281
|
+
}
|
|
282
|
+
async putRaw(input) {
|
|
283
|
+
const bytes = new Uint8Array(input.bytes);
|
|
284
|
+
const hash = await sha256Bytes(bytes);
|
|
285
|
+
const ref = rawRef(input.connector, input.fetchedAt, hash, input.ext);
|
|
286
|
+
const entry = RawIndexEntry.parse({
|
|
287
|
+
ref,
|
|
288
|
+
connector: input.connector,
|
|
289
|
+
hash,
|
|
290
|
+
ext: input.ext,
|
|
291
|
+
bytes: bytes.byteLength,
|
|
292
|
+
url: input.url,
|
|
293
|
+
fetchedAt: input.fetchedAt,
|
|
294
|
+
httpStatus: input.httpStatus,
|
|
295
|
+
contentType: input.contentType,
|
|
296
|
+
transport: input.transport,
|
|
297
|
+
runId: input.runId,
|
|
298
|
+
taskId: input.taskId,
|
|
299
|
+
failure: input.failure
|
|
300
|
+
});
|
|
301
|
+
const stored = await this.enqueue(async () => {
|
|
302
|
+
const path = this.p(ref);
|
|
303
|
+
let isNew = true;
|
|
304
|
+
const existing = await readFileOrUndefined(path);
|
|
305
|
+
if (existing) {
|
|
306
|
+
try {
|
|
307
|
+
isNew = await sha256Bytes(new Uint8Array(gunzipSync(existing))) !== hash;
|
|
308
|
+
} catch {
|
|
309
|
+
isNew = true;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
if (isNew) await writeAtomic(path, gzipSync(bytes));
|
|
313
|
+
await this.appendLine(this.p("raw", "index.jsonl"), JSON.stringify(entry));
|
|
314
|
+
return isNew;
|
|
315
|
+
});
|
|
316
|
+
return { ref, hash, stored };
|
|
317
|
+
}
|
|
318
|
+
async getRaw(ref) {
|
|
319
|
+
parseRawRef(ref);
|
|
320
|
+
await this.drain();
|
|
321
|
+
const buf = await readFileOrUndefined(this.p(ref));
|
|
322
|
+
return buf && new Uint8Array(gunzipSync(buf));
|
|
323
|
+
}
|
|
324
|
+
rawIndex() {
|
|
325
|
+
return this.lines(this.p("raw", "index.jsonl"), RawIndexEntry);
|
|
326
|
+
}
|
|
327
|
+
async upsertItem(item) {
|
|
328
|
+
const parsed = CollectItem.parse(item);
|
|
329
|
+
await this.append(this.p("items", `${sourceOf(parsed.id)}.jsonl`), parsed);
|
|
330
|
+
}
|
|
331
|
+
/** Streams the one source file and keeps the last match: no map of ids is built. */
|
|
332
|
+
async getItem(id) {
|
|
333
|
+
await this.drain();
|
|
334
|
+
let found;
|
|
335
|
+
for await (const i of this.readLines(this.p("items", `${sourceOf(id)}.jsonl`), CollectItem, () => {
|
|
336
|
+
})) {
|
|
337
|
+
if (i.id === id) found = i;
|
|
338
|
+
}
|
|
339
|
+
return found;
|
|
340
|
+
}
|
|
341
|
+
/** Last line per id wins. The unique ids of the files read are buffered in a map; `compact` keeps files small. */
|
|
342
|
+
items(source) {
|
|
343
|
+
const self = this;
|
|
344
|
+
return makeReader(async function* (onSkip) {
|
|
345
|
+
await self.drain();
|
|
346
|
+
yield* self.readItems(source, onSkip);
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
async appendObservation(o) {
|
|
350
|
+
const parsed = Observation.parse(o);
|
|
351
|
+
await this.append(this.p("observations", `${sourceOf(parsed.itemId)}.jsonl`), parsed);
|
|
352
|
+
}
|
|
353
|
+
observations(source) {
|
|
354
|
+
return dropRedone(this.multi("observations", source, Observation), observationRedoKey);
|
|
355
|
+
}
|
|
356
|
+
async appendActor(a) {
|
|
357
|
+
const parsed = Actor.parse(a);
|
|
358
|
+
await this.append(this.p("actors", `${sourceOf(parsed.ref)}.jsonl`), parsed);
|
|
359
|
+
}
|
|
360
|
+
actors(source) {
|
|
361
|
+
return dropRedone(this.multi("actors", source, Actor), actorRedoKey);
|
|
362
|
+
}
|
|
363
|
+
async appendPickup(p) {
|
|
364
|
+
await this.append(this.p("pickups.jsonl"), Pickup.parse(p));
|
|
365
|
+
}
|
|
366
|
+
pickups() {
|
|
367
|
+
return dropRedone(this.lines(this.p("pickups.jsonl"), Pickup), pickupRedoKey);
|
|
368
|
+
}
|
|
369
|
+
async seenHas(key) {
|
|
370
|
+
return this.seen.has(key);
|
|
371
|
+
}
|
|
372
|
+
/** Persisted first, then added to the in-memory set. */
|
|
373
|
+
async seenGet(key) {
|
|
374
|
+
return this.seen.get(key);
|
|
375
|
+
}
|
|
376
|
+
async seenAdd(key, itemId) {
|
|
377
|
+
if (key.includes("\n") || key.includes(" ")) throw new Error("a seen key cannot contain a newline or a tab");
|
|
378
|
+
if (itemId !== void 0 && (itemId.includes("\n") || itemId.includes(" "))) {
|
|
379
|
+
throw new Error("an item id cannot contain a newline or a tab");
|
|
380
|
+
}
|
|
381
|
+
await this.enqueue(async () => {
|
|
382
|
+
if (this.seen.has(key) && (this.seen.get(key) !== void 0 || itemId === void 0)) return;
|
|
383
|
+
await this.appendLine(this.p("seen.idx"), itemId === void 0 ? key : `${key} ${itemId}`);
|
|
384
|
+
this.seen.set(key, itemId);
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
async seenKeys() {
|
|
388
|
+
await this.drain();
|
|
389
|
+
return [...this.seen.keys()];
|
|
390
|
+
}
|
|
391
|
+
/** Runs entirely inside the write queue, reading the items without waiting on it. */
|
|
392
|
+
async rebuildSeenIndex() {
|
|
393
|
+
await this.enqueue(async () => {
|
|
394
|
+
const keys = /* @__PURE__ */ new Map();
|
|
395
|
+
for await (const item of this.readItems(void 0, () => {
|
|
396
|
+
})) {
|
|
397
|
+
for (const k of itemSeenKeys(item)) if (!keys.has(k)) keys.set(k, item.id);
|
|
398
|
+
}
|
|
399
|
+
await writeAtomic(this.p("seen.idx"), seenText(keys));
|
|
400
|
+
this.tailChecked.delete(this.p("seen.idx"));
|
|
401
|
+
this.seen.clear();
|
|
402
|
+
for (const [k, v] of keys) this.seen.set(k, v);
|
|
403
|
+
});
|
|
404
|
+
}
|
|
405
|
+
runDir(runId) {
|
|
406
|
+
return this.p("runs", assertSafeName("run id", runId));
|
|
407
|
+
}
|
|
408
|
+
async createRun(runId, recipe, extra) {
|
|
409
|
+
const dir = this.runDir(runId);
|
|
410
|
+
const parsed = Recipe.parse(recipe);
|
|
411
|
+
const record = { runId, createdAt: this.now(), recipeHash: await recipeHash(parsed), recipe: parsed, ...extra?.connectorModules ? { connectorModules: extra.connectorModules } : {}, ...extra?.origin ? { origin: extra.origin } : {} };
|
|
412
|
+
return this.enqueue(async () => {
|
|
413
|
+
if (!await createExclusive(join(dir, "recipe.json"), `${JSON.stringify(record, null, 2)}
|
|
414
|
+
`)) {
|
|
415
|
+
throw new Error(`run ${runId} already exists`);
|
|
416
|
+
}
|
|
417
|
+
return record;
|
|
418
|
+
});
|
|
419
|
+
}
|
|
420
|
+
async getRun(runId) {
|
|
421
|
+
await this.drain();
|
|
422
|
+
const buf = await readFileOrUndefined(join(this.runDir(runId), "recipe.json"));
|
|
423
|
+
return buf && RunRecord.parse(JSON.parse(buf.toString("utf8")));
|
|
424
|
+
}
|
|
425
|
+
async listRuns() {
|
|
426
|
+
await this.drain();
|
|
427
|
+
const out = [];
|
|
428
|
+
for (const n of (await readdirOrEmpty(this.p("runs"))).sort()) if (await exists(this.p("runs", n, "recipe.json"))) out.push(n);
|
|
429
|
+
return out;
|
|
430
|
+
}
|
|
431
|
+
appendRunLine(runId, file, record) {
|
|
432
|
+
const dir = this.runDir(runId);
|
|
433
|
+
const text = JSON.stringify(record);
|
|
434
|
+
return this.enqueue(async () => {
|
|
435
|
+
if (!await exists(join(dir, "recipe.json"))) throw new Error(`unknown run ${runId}`);
|
|
436
|
+
await this.appendLine(join(dir, file), text);
|
|
437
|
+
});
|
|
438
|
+
}
|
|
439
|
+
async appendTask(runId, task) {
|
|
440
|
+
await this.appendRunLine(runId, "tasks.jsonl", TaskRecord.parse(task));
|
|
441
|
+
}
|
|
442
|
+
tasks(runId) {
|
|
443
|
+
const self = this;
|
|
444
|
+
return makeReader(async function* (onSkip) {
|
|
445
|
+
await self.drain();
|
|
446
|
+
yield* lastWins(self.readLines(join(self.runDir(runId), "tasks.jsonl"), TaskRecord, onSkip), (t) => t.taskId);
|
|
447
|
+
});
|
|
448
|
+
}
|
|
449
|
+
async writePlan(runId, plan) {
|
|
450
|
+
const text = plan.map((p) => `${JSON.stringify(PlanEntry.parse(p))}
|
|
451
|
+
`).join("");
|
|
452
|
+
const dir = this.runDir(runId);
|
|
453
|
+
await this.enqueue(async () => {
|
|
454
|
+
if (!await exists(join(dir, "recipe.json"))) throw new Error(`unknown run ${runId}`);
|
|
455
|
+
await writeAtomic(join(dir, "plan.jsonl"), text);
|
|
456
|
+
});
|
|
457
|
+
}
|
|
458
|
+
async readPlan(runId) {
|
|
459
|
+
await this.drain();
|
|
460
|
+
const buf = await readFileOrUndefined(join(this.runDir(runId), "plan.jsonl"));
|
|
461
|
+
if (!buf) return void 0;
|
|
462
|
+
const out = [];
|
|
463
|
+
for (const line of buf.toString("utf8").split("\n")) {
|
|
464
|
+
if (line.trim() === "") continue;
|
|
465
|
+
out.push(PlanEntry.parse(JSON.parse(line)));
|
|
466
|
+
}
|
|
467
|
+
return out;
|
|
468
|
+
}
|
|
469
|
+
async appendSampling(runId, r) {
|
|
470
|
+
await this.appendRunLine(runId, "sampling.jsonl", SamplingRecord.parse(r));
|
|
471
|
+
}
|
|
472
|
+
async appendSamplingBatch(runId, rs) {
|
|
473
|
+
if (rs.length === 0) return;
|
|
474
|
+
const dir = this.runDir(runId);
|
|
475
|
+
const text = rs.map((r) => JSON.stringify(SamplingRecord.parse(r))).join("\n");
|
|
476
|
+
await this.enqueue(async () => {
|
|
477
|
+
if (!await exists(join(dir, "recipe.json"))) throw new Error(`unknown run ${runId}`);
|
|
478
|
+
await this.appendLine(join(dir, "sampling.jsonl"), text);
|
|
479
|
+
});
|
|
480
|
+
}
|
|
481
|
+
sampling(runId) {
|
|
482
|
+
return this.lines(join(this.runDir(runId), "sampling.jsonl"), SamplingRecord);
|
|
483
|
+
}
|
|
484
|
+
async appendEvent(runId, e) {
|
|
485
|
+
await this.appendRunLine(runId, "events.jsonl", EventRecord.parse(e));
|
|
486
|
+
}
|
|
487
|
+
events(runId) {
|
|
488
|
+
return this.lines(join(this.runDir(runId), "events.jsonl"), EventRecord);
|
|
489
|
+
}
|
|
490
|
+
async writeReport(runId, report) {
|
|
491
|
+
const parsed = RunReport.parse(report);
|
|
492
|
+
const dir = this.runDir(runId);
|
|
493
|
+
await this.enqueue(async () => {
|
|
494
|
+
if (!await exists(join(dir, "recipe.json"))) throw new Error(`unknown run ${runId}`);
|
|
495
|
+
await writeAtomic(join(dir, "report.json"), `${JSON.stringify(parsed, null, 2)}
|
|
496
|
+
`);
|
|
497
|
+
});
|
|
498
|
+
}
|
|
499
|
+
async readReport(runId) {
|
|
500
|
+
await this.drain();
|
|
501
|
+
const buf = await readFileOrUndefined(join(this.runDir(runId), "report.json"));
|
|
502
|
+
return buf && RunReport.parse(JSON.parse(buf.toString("utf8")));
|
|
503
|
+
}
|
|
504
|
+
async readLock(path) {
|
|
505
|
+
const buf = await readFileOrUndefined(path);
|
|
506
|
+
if (!buf) return void 0;
|
|
507
|
+
try {
|
|
508
|
+
const v = JSON.parse(buf.toString("utf8"));
|
|
509
|
+
return typeof v.pid === "number" && typeof v.token === "string" ? v : void 0;
|
|
510
|
+
} catch {
|
|
511
|
+
return void 0;
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
/**
|
|
515
|
+
* Take `collect.lock`. The file is created already holding its content
|
|
516
|
+
* (`{ pid, at, host, token }`): a tmp file is written, then hard-linked to
|
|
517
|
+
* `collect.lock`, so a lock file never exists empty and EEXIST means held. A
|
|
518
|
+
* second acquire throws `StoreLockedError`.
|
|
519
|
+
*
|
|
520
|
+
* A lock is stale when it was written on this host by a pid that is not
|
|
521
|
+
* alive (see `pidAlive`); a stale lock is broken automatically. To break it
|
|
522
|
+
* the file is renamed to `collect.lock.stale-<token>`, which only one process
|
|
523
|
+
* wins; the renamed file is read again and must still be that dead holder's
|
|
524
|
+
* (same pid and token), otherwise it is linked back and the store is reported
|
|
525
|
+
* as locked. A lock from another host, or an unreadable one, is never broken.
|
|
526
|
+
*/
|
|
527
|
+
async lockOnly() {
|
|
528
|
+
const path = this.p(LOCK_FILE);
|
|
529
|
+
const record = { pid: process.pid, at: this.now(), host: hostname(), token: randomBytes(8).toString("hex") };
|
|
530
|
+
const locked = (holder) => new StoreLockedError(
|
|
531
|
+
holder ? `store is locked by pid ${holder.pid} since ${holder.at}` : "store is locked (unreadable lock file)",
|
|
532
|
+
holder && { pid: holder.pid, at: holder.at, host: holder.host }
|
|
533
|
+
);
|
|
534
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
535
|
+
if (await createExclusive(path, JSON.stringify(record))) {
|
|
536
|
+
this.lockToken = record.token;
|
|
537
|
+
return {
|
|
538
|
+
release: async () => {
|
|
539
|
+
if (this.lockToken !== record.token) return;
|
|
540
|
+
this.lockToken = void 0;
|
|
541
|
+
const current = await this.readLock(path);
|
|
542
|
+
if (current?.token === record.token) await rm(path, { force: true });
|
|
543
|
+
}
|
|
544
|
+
};
|
|
545
|
+
}
|
|
546
|
+
const holder = await this.readLock(path);
|
|
547
|
+
if (!holder) {
|
|
548
|
+
if (await exists(path)) throw locked();
|
|
549
|
+
continue;
|
|
550
|
+
}
|
|
551
|
+
if (holder.host !== record.host || this.pidAlive(holder.pid)) throw locked(holder);
|
|
552
|
+
const grave = `${path}.stale-${record.token}`;
|
|
553
|
+
try {
|
|
554
|
+
await rename(path, grave);
|
|
555
|
+
} catch (e) {
|
|
556
|
+
if (isEnoent(e)) continue;
|
|
557
|
+
throw e;
|
|
558
|
+
}
|
|
559
|
+
const moved = await this.readLock(grave);
|
|
560
|
+
if (moved && moved.pid === holder.pid && moved.token === holder.token) {
|
|
561
|
+
await rm(grave, { force: true });
|
|
562
|
+
continue;
|
|
563
|
+
}
|
|
564
|
+
try {
|
|
565
|
+
await link(grave, path);
|
|
566
|
+
} catch (e) {
|
|
567
|
+
if (!isEexist(e)) throw e;
|
|
568
|
+
}
|
|
569
|
+
await rm(grave, { force: true });
|
|
570
|
+
throw locked(moved);
|
|
571
|
+
}
|
|
572
|
+
throw new StoreLockedError("store lock could not be acquired");
|
|
573
|
+
}
|
|
574
|
+
/** Lock the store, then reload the seen index from disk so a handle opened before another writer wrote is correct. */
|
|
575
|
+
async acquireLock() {
|
|
576
|
+
const lock = await this.lockOnly();
|
|
577
|
+
try {
|
|
578
|
+
await this.reloadSeen();
|
|
579
|
+
} catch (e) {
|
|
580
|
+
await lock.release().catch(() => void 0);
|
|
581
|
+
throw e;
|
|
582
|
+
}
|
|
583
|
+
return lock;
|
|
584
|
+
}
|
|
585
|
+
};
|
|
586
|
+
|
|
587
|
+
// src/node/http-transport.ts
|
|
588
|
+
var MiB = 1024 * 1024;
|
|
589
|
+
var DEFAULT_UA = "agentproto-collect";
|
|
590
|
+
var systemClock = {
|
|
591
|
+
now: () => Date.now(),
|
|
592
|
+
sleep: (ms, signal) => new Promise((resolve) => {
|
|
593
|
+
if (signal?.aborted) return resolve();
|
|
594
|
+
const t = setTimeout(done, ms);
|
|
595
|
+
const onAbort = () => {
|
|
596
|
+
clearTimeout(t);
|
|
597
|
+
done();
|
|
598
|
+
};
|
|
599
|
+
function done() {
|
|
600
|
+
signal?.removeEventListener("abort", onAbort);
|
|
601
|
+
resolve();
|
|
602
|
+
}
|
|
603
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
604
|
+
})
|
|
605
|
+
};
|
|
606
|
+
var INTERSTITIAL_MARKERS = [
|
|
607
|
+
/<title>\s*just a moment/i,
|
|
608
|
+
/<title>\s*attention required/i,
|
|
609
|
+
/<title>\s*access denied/i,
|
|
610
|
+
/<title>\s*(?:are you a robot|robot check|security check|verifying you are human|human verification)/i,
|
|
611
|
+
/verify (?:that )?you are (?:a )?human/i,
|
|
612
|
+
/checking (?:if the site connection is secure|your browser)/i,
|
|
613
|
+
/enable javascript and cookies to continue/i,
|
|
614
|
+
/unusual traffic from your computer network/i,
|
|
615
|
+
/cf-chl-|challenge-platform|__cf_chl/i
|
|
616
|
+
];
|
|
617
|
+
var WIDGET_MARKERS = [/g-recaptcha|h-captcha|hcaptcha\.com|cf-turnstile|px-captcha|geo\.captcha-delivery\.com/i];
|
|
618
|
+
var CHALLENGE_STATUSES = /* @__PURE__ */ new Set([403, 429, 503]);
|
|
619
|
+
var CHALLENGE_SCAN_BYTES = 64 * 1024;
|
|
620
|
+
var WIDGET_ONLY_MAX_BYTES = 4 * 1024;
|
|
621
|
+
var WIDGET_ONLY_MAX_TEXT = 120;
|
|
622
|
+
function visibleText(html) {
|
|
623
|
+
return html.replace(/<(script|style|noscript)\b[\s\S]*?<\/\1>/gi, " ").replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim();
|
|
624
|
+
}
|
|
625
|
+
function looksLikeChallenge(status, headers, body) {
|
|
626
|
+
if (headers["cf-mitigated"]?.toLowerCase() === "challenge") return true;
|
|
627
|
+
const type = headers["content-type"]?.toLowerCase() ?? "";
|
|
628
|
+
if (type && !type.includes("html") && !type.includes("text/plain")) return false;
|
|
629
|
+
const head = new TextDecoder().decode(body.subarray(0, CHALLENGE_SCAN_BYTES));
|
|
630
|
+
const interstitial = INTERSTITIAL_MARKERS.some((re) => re.test(head));
|
|
631
|
+
const widget = WIDGET_MARKERS.some((re) => re.test(head));
|
|
632
|
+
if (!interstitial && !widget) return false;
|
|
633
|
+
if (CHALLENGE_STATUSES.has(status)) return true;
|
|
634
|
+
return body.byteLength < WIDGET_ONLY_MAX_BYTES && visibleText(head).length < WIDGET_ONLY_MAX_TEXT;
|
|
635
|
+
}
|
|
636
|
+
function extOf(headers) {
|
|
637
|
+
const t = headers["content-type"]?.toLowerCase() ?? "";
|
|
638
|
+
if (t.includes("json")) return "json";
|
|
639
|
+
if (t.includes("html")) return "html";
|
|
640
|
+
if (t.includes("xml")) return "xml";
|
|
641
|
+
if (t.startsWith("text/")) return "txt";
|
|
642
|
+
return "bin";
|
|
643
|
+
}
|
|
644
|
+
var MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
|
|
645
|
+
var DAY = "(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)";
|
|
646
|
+
var LONG_DAY = "(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)";
|
|
647
|
+
var MON = "(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)";
|
|
648
|
+
var TIME = "(\\d{2}):(\\d{2}):(\\d{2})";
|
|
649
|
+
var DATE_FORMS = [
|
|
650
|
+
{ re: new RegExp(`^${DAY}, (\\d{2}) ${MON} (\\d{4}) ${TIME} GMT$`), order: [1, 2, 3, 4, 5, 6] },
|
|
651
|
+
{ re: new RegExp(`^${LONG_DAY}, (\\d{2})-${MON}-(\\d{2}) ${TIME} GMT$`), order: [1, 2, 3, 4, 5, 6] },
|
|
652
|
+
{ re: new RegExp(`^${DAY} ${MON} ( \\d|\\d{2}) ${TIME} (\\d{4})$`), order: [2, 1, 6, 3, 4, 5] }
|
|
653
|
+
];
|
|
654
|
+
function parseRetryAfter(value, now) {
|
|
655
|
+
if (value === void 0) return void 0;
|
|
656
|
+
const v = value.trim();
|
|
657
|
+
if (/^\d{1,10}$/.test(v)) return Number(v) * 1e3;
|
|
658
|
+
for (const { re, order } of DATE_FORMS) {
|
|
659
|
+
const m = re.exec(v);
|
|
660
|
+
if (!m) continue;
|
|
661
|
+
const [d, mo, y, h, mi, se] = order.map((i) => m[i]);
|
|
662
|
+
let year = Number(y);
|
|
663
|
+
if (y.length === 2) {
|
|
664
|
+
year += 2e3;
|
|
665
|
+
if (year > new Date(now).getUTCFullYear() + 50) year -= 100;
|
|
666
|
+
}
|
|
667
|
+
const at = Date.UTC(year, MONTHS.indexOf(mo.toLowerCase()), Number(d.trim()), Number(h), Number(mi), Number(se));
|
|
668
|
+
return Number.isNaN(at) ? void 0 : Math.max(0, at - now);
|
|
669
|
+
}
|
|
670
|
+
return void 0;
|
|
671
|
+
}
|
|
672
|
+
function shown(url) {
|
|
673
|
+
try {
|
|
674
|
+
const u = new URL(url);
|
|
675
|
+
return `${u.origin}${u.pathname}`;
|
|
676
|
+
} catch {
|
|
677
|
+
return "invalid URL";
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
var RETRY_AFTER = /* @__PURE__ */ new WeakMap();
|
|
681
|
+
var REDIRECT = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
|
|
682
|
+
var SAFE = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS", "PUT", "DELETE"]);
|
|
683
|
+
var ALWAYS_CREDENTIAL = ["authorization", "cookie", "proxy-authorization"];
|
|
684
|
+
var BODY_HEADERS = ["content-type", "content-length", "content-encoding"];
|
|
685
|
+
var MAX_MS = 36e5;
|
|
686
|
+
var MAX_BYTES = 2 ** 30;
|
|
687
|
+
function bounded(name, value, min, max, integer = false) {
|
|
688
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > max || integer && !Number.isInteger(value)) {
|
|
689
|
+
throw new RangeError(`${name} must be ${integer ? "an integer" : "a finite number"} between ${min} and ${max}, got ${String(value)}`);
|
|
690
|
+
}
|
|
691
|
+
return value;
|
|
692
|
+
}
|
|
693
|
+
function createHttpTransport(options = {}) {
|
|
694
|
+
const timeoutMs = bounded("timeoutMs", options.timeoutMs ?? 3e4, 1, MAX_MS);
|
|
695
|
+
const maxAttempts = bounded("maxAttempts", options.maxAttempts ?? 3, 1, 10, true);
|
|
696
|
+
const baseDelayMs = bounded("baseDelayMs", options.baseDelayMs ?? 500, 0, MAX_MS);
|
|
697
|
+
const maxBackoffMs = bounded("maxBackoffMs", options.maxBackoffMs ?? 1e4, 0, MAX_MS);
|
|
698
|
+
const maxRetryAfterMs = bounded("maxRetryAfterMs", options.maxRetryAfterMs ?? 3e4, 0, MAX_MS);
|
|
699
|
+
const minIntervalMs = bounded("minIntervalMs", options.minIntervalMs ?? 1e3, 0, MAX_MS);
|
|
700
|
+
const maxBytes = bounded("maxBytes", options.maxBytes ?? 10 * MiB, 1, MAX_BYTES, true);
|
|
701
|
+
const maxRedirects = bounded("maxRedirects", options.maxRedirects ?? 10, 0, 50, true);
|
|
702
|
+
const userAgent = options.userAgent ?? DEFAULT_UA;
|
|
703
|
+
const random = options.random ?? Math.random;
|
|
704
|
+
const clock = options.clock ?? systemClock;
|
|
705
|
+
const doFetch = options.fetch ?? globalThis.fetch;
|
|
706
|
+
const hosts = /* @__PURE__ */ new Map();
|
|
707
|
+
async function gate(url, signal) {
|
|
708
|
+
if (minIntervalMs <= 0) return;
|
|
709
|
+
let host;
|
|
710
|
+
try {
|
|
711
|
+
host = new URL(url).host.toLowerCase();
|
|
712
|
+
} catch {
|
|
713
|
+
return;
|
|
714
|
+
}
|
|
715
|
+
let g = hosts.get(host);
|
|
716
|
+
if (!g) hosts.set(host, g = { tail: Promise.resolve() });
|
|
717
|
+
const state = g;
|
|
718
|
+
const mine = state.tail.then(async () => {
|
|
719
|
+
for (; ; ) {
|
|
720
|
+
if (signal.aborted) return;
|
|
721
|
+
const wait = state.lastStart === void 0 ? 0 : state.lastStart + minIntervalMs - clock.now();
|
|
722
|
+
if (wait <= 0) break;
|
|
723
|
+
await clock.sleep(wait, signal);
|
|
724
|
+
}
|
|
725
|
+
state.lastStart = clock.now();
|
|
726
|
+
});
|
|
727
|
+
state.tail = mine.catch(() => void 0);
|
|
728
|
+
let onAbort;
|
|
729
|
+
const aborted = new Promise((resolve) => {
|
|
730
|
+
onAbort = () => resolve();
|
|
731
|
+
if (signal.aborted) resolve();
|
|
732
|
+
else signal.addEventListener("abort", onAbort, { once: true });
|
|
733
|
+
});
|
|
734
|
+
try {
|
|
735
|
+
await Promise.race([mine, aborted]);
|
|
736
|
+
} finally {
|
|
737
|
+
signal.removeEventListener("abort", onAbort);
|
|
738
|
+
}
|
|
739
|
+
if (signal.aborted) throw signal.reason ?? new Error("aborted");
|
|
740
|
+
}
|
|
741
|
+
async function readBody(res, strict, url, status, controller) {
|
|
742
|
+
const declared = Number(res.headers.get("content-length"));
|
|
743
|
+
if (strict && Number.isFinite(declared) && declared > maxBytes) {
|
|
744
|
+
controller.abort();
|
|
745
|
+
throw new TransportError("http", `response of ${declared} bytes exceeds the ${maxBytes} byte cap (${shown(url)})`, { status, url });
|
|
746
|
+
}
|
|
747
|
+
const chunks = [];
|
|
748
|
+
let total = 0;
|
|
749
|
+
if (res.body) {
|
|
750
|
+
const reader = res.body.getReader();
|
|
751
|
+
try {
|
|
752
|
+
for (; ; ) {
|
|
753
|
+
const { done, value } = await reader.read();
|
|
754
|
+
if (done) break;
|
|
755
|
+
if (total + value.byteLength > maxBytes) {
|
|
756
|
+
if (strict) {
|
|
757
|
+
controller.abort();
|
|
758
|
+
throw new TransportError("http", `response exceeds the ${maxBytes} byte cap (${shown(url)})`, { status, url });
|
|
759
|
+
}
|
|
760
|
+
chunks.push(value.subarray(0, maxBytes - total));
|
|
761
|
+
total = maxBytes;
|
|
762
|
+
await reader.cancel().catch(() => void 0);
|
|
763
|
+
break;
|
|
764
|
+
}
|
|
765
|
+
chunks.push(value);
|
|
766
|
+
total += value.byteLength;
|
|
767
|
+
}
|
|
768
|
+
} catch (e) {
|
|
769
|
+
if (strict || e instanceof TransportError) throw e;
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
const out = new Uint8Array(total);
|
|
773
|
+
let at = 0;
|
|
774
|
+
for (const c of chunks) {
|
|
775
|
+
out.set(c, at);
|
|
776
|
+
at += c.byteLength;
|
|
777
|
+
}
|
|
778
|
+
return out;
|
|
779
|
+
}
|
|
780
|
+
async function once(req) {
|
|
781
|
+
const timeout = bounded("timeoutMs", req.timeoutMs ?? timeoutMs, 1, MAX_MS);
|
|
782
|
+
const controller = new AbortController();
|
|
783
|
+
const timer = setTimeout(() => controller.abort(new Error("timeout")), timeout);
|
|
784
|
+
const onCaller = () => controller.abort(req.signal?.reason);
|
|
785
|
+
if (req.signal?.aborted) onCaller();
|
|
786
|
+
req.signal?.addEventListener("abort", onCaller, { once: true });
|
|
787
|
+
const lower = {};
|
|
788
|
+
for (const [k, v] of Object.entries(req.headers ?? {})) lower[k.toLowerCase()] = v;
|
|
789
|
+
if (!lower["user-agent"]) lower["user-agent"] = userAgent;
|
|
790
|
+
if (!lower["accept"]) lower["accept"] = "*/*";
|
|
791
|
+
const credentials = /* @__PURE__ */ new Set([...ALWAYS_CREDENTIAL, ...(req.credentialHeaders ?? []).map((h) => h.toLowerCase())]);
|
|
792
|
+
let url = req.url;
|
|
793
|
+
let method = (req.method ?? "GET").toUpperCase();
|
|
794
|
+
let body = req.body;
|
|
795
|
+
try {
|
|
796
|
+
for (let hop = 0; ; hop++) {
|
|
797
|
+
try {
|
|
798
|
+
await gate(url, controller.signal);
|
|
799
|
+
} catch (e) {
|
|
800
|
+
throw networkError(e, url, req.signal, timeout);
|
|
801
|
+
}
|
|
802
|
+
let res;
|
|
803
|
+
try {
|
|
804
|
+
res = await doFetch(url, { method, headers: lower, body, redirect: "manual", signal: controller.signal });
|
|
805
|
+
} catch (e) {
|
|
806
|
+
throw networkError(e, url, req.signal, timeout);
|
|
807
|
+
}
|
|
808
|
+
const status = res.status;
|
|
809
|
+
if (REDIRECT.has(status) && res.headers.get("location")) {
|
|
810
|
+
await res.body?.cancel().catch(() => void 0);
|
|
811
|
+
if (hop >= maxRedirects) throw new TransportError("http", `more than ${maxRedirects} redirects (${shown(url)})`, { status, url });
|
|
812
|
+
let next;
|
|
813
|
+
try {
|
|
814
|
+
next = new URL(res.headers.get("location"), url);
|
|
815
|
+
} catch {
|
|
816
|
+
throw new TransportError("http", `invalid redirect target from ${shown(url)}`, { status, url });
|
|
817
|
+
}
|
|
818
|
+
if (next.protocol !== "http:" && next.protocol !== "https:") {
|
|
819
|
+
throw new TransportError("http", `redirect to a non-http URL from ${shown(url)}`, { status, url });
|
|
820
|
+
}
|
|
821
|
+
if (next.origin !== new URL(url).origin) {
|
|
822
|
+
if (req.urlCredential) {
|
|
823
|
+
throw new TransportError("blocked", `refused a redirect to another origin: the request carries a credential in its URL (${shown(url)})`, {
|
|
824
|
+
url
|
|
825
|
+
});
|
|
826
|
+
}
|
|
827
|
+
for (const h of credentials) delete lower[h];
|
|
828
|
+
}
|
|
829
|
+
if (status === 303 || (status === 301 || status === 302) && method === "POST") {
|
|
830
|
+
if (method !== "HEAD") method = "GET";
|
|
831
|
+
body = void 0;
|
|
832
|
+
for (const h of BODY_HEADERS) delete lower[h];
|
|
833
|
+
}
|
|
834
|
+
url = next.toString();
|
|
835
|
+
continue;
|
|
836
|
+
}
|
|
837
|
+
let bytes;
|
|
838
|
+
try {
|
|
839
|
+
bytes = await readBody(res, status >= 200 && status < 300, url, status, controller);
|
|
840
|
+
} catch (e) {
|
|
841
|
+
if (e instanceof TransportError) throw e;
|
|
842
|
+
throw networkError(e, url, req.signal, timeout);
|
|
843
|
+
}
|
|
844
|
+
if (req.signal?.aborted) throw networkError(req.signal.reason, url, req.signal, timeout);
|
|
845
|
+
const headers = {};
|
|
846
|
+
res.headers.forEach((v, k) => {
|
|
847
|
+
headers[k.toLowerCase()] = v;
|
|
848
|
+
});
|
|
849
|
+
return classify({ status, headers, body: bytes, url });
|
|
850
|
+
}
|
|
851
|
+
} finally {
|
|
852
|
+
clearTimeout(timer);
|
|
853
|
+
req.signal?.removeEventListener("abort", onCaller);
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
function networkError(e, url, caller, timeout) {
|
|
857
|
+
if (caller?.aborted) return new TransportError("network", `request aborted (${shown(url)})`, { url, origin: e });
|
|
858
|
+
if (e instanceof Error && e.message === "timeout") {
|
|
859
|
+
return new TransportError("network", `timed out after ${timeout} ms (${shown(url)})`, { url, origin: e });
|
|
860
|
+
}
|
|
861
|
+
const inner = e instanceof Error && e.cause instanceof Error ? e.cause : void 0;
|
|
862
|
+
const code = inner && "code" in inner ? String(inner.code) : void 0;
|
|
863
|
+
const why = code ?? inner?.message ?? (e instanceof Error ? e.message : "request failed");
|
|
864
|
+
return new TransportError("network", `network error: ${why} (${shown(url)})`, { url, origin: e });
|
|
865
|
+
}
|
|
866
|
+
function classify(res) {
|
|
867
|
+
const { status, headers, body, url } = res;
|
|
868
|
+
const keep = { status, url, body, ext: extOf(headers), contentType: headers["content-type"] };
|
|
869
|
+
if (looksLikeChallenge(status, headers, body)) {
|
|
870
|
+
throw new TransportError("challenge", `verification page (HTTP ${status}, ${shown(url)})`, keep);
|
|
871
|
+
}
|
|
872
|
+
if (status >= 200 && status < 300) {
|
|
873
|
+
if (body.byteLength === 0) throw new TransportError("empty", `empty body (HTTP ${status}, ${shown(url)})`, keep);
|
|
874
|
+
return res;
|
|
875
|
+
}
|
|
876
|
+
const err = status === 401 || status === 403 ? new TransportError("blocked", `blocked (HTTP ${status}, ${shown(url)})`, keep) : new TransportError("http", `HTTP ${status} (${shown(url)})`, keep);
|
|
877
|
+
if (status === 429 || status === 503) {
|
|
878
|
+
const wait = parseRetryAfter(headers["retry-after"], clock.now());
|
|
879
|
+
if (wait !== void 0) RETRY_AFTER.set(err, wait);
|
|
880
|
+
}
|
|
881
|
+
throw err;
|
|
882
|
+
}
|
|
883
|
+
return {
|
|
884
|
+
async request(req) {
|
|
885
|
+
const retryable = SAFE.has((req.method ?? "GET").toUpperCase()) || options.retryUnsafeMethods === true;
|
|
886
|
+
for (let attempt = 1; ; attempt++) {
|
|
887
|
+
try {
|
|
888
|
+
return await once(req);
|
|
889
|
+
} catch (e) {
|
|
890
|
+
const err = e instanceof TransportError ? e : new TransportError("network", "request failed", { url: req.url, origin: e });
|
|
891
|
+
const again = retryable && attempt < maxAttempts && !req.signal?.aborted && (err.cause === "network" || err.cause === "http" && err.status !== void 0 && (err.status === 429 || err.status >= 500));
|
|
892
|
+
if (!again) throw err;
|
|
893
|
+
const hinted = RETRY_AFTER.get(err);
|
|
894
|
+
let wait;
|
|
895
|
+
if (hinted !== void 0) {
|
|
896
|
+
if (hinted > maxRetryAfterMs) {
|
|
897
|
+
throw new TransportError("http", `${err.message}; Retry-After ${Math.round(hinted / 1e3)}s exceeds the ${Math.round(maxRetryAfterMs / 1e3)}s cap`, {
|
|
898
|
+
status: err.status,
|
|
899
|
+
url: err.url,
|
|
900
|
+
body: err.body,
|
|
901
|
+
ext: err.ext,
|
|
902
|
+
contentType: err.contentType
|
|
903
|
+
});
|
|
904
|
+
}
|
|
905
|
+
wait = hinted;
|
|
906
|
+
} else {
|
|
907
|
+
const step = Math.min(baseDelayMs * 2 ** (attempt - 1), maxBackoffMs);
|
|
908
|
+
wait = step / 2 + random() * step / 2;
|
|
909
|
+
}
|
|
910
|
+
await clock.sleep(wait, req.signal);
|
|
911
|
+
if (req.signal?.aborted) throw new TransportError("network", `request aborted (${shown(req.url)})`, { url: req.url });
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
};
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
// src/node/api-transport.ts
|
|
919
|
+
var REDACTED = "[redacted]";
|
|
920
|
+
function createApiTransport(options) {
|
|
921
|
+
const { http, secrets, auth } = options;
|
|
922
|
+
return {
|
|
923
|
+
async request(req) {
|
|
924
|
+
const secret = await secrets.get(auth.secret);
|
|
925
|
+
if (!secret) throw new MissingSecretError(auth.secret);
|
|
926
|
+
let url = req.url;
|
|
927
|
+
const headers = { ...req.headers ?? {} };
|
|
928
|
+
const credentialHeaders = [...req.credentialHeaders ?? []];
|
|
929
|
+
if (auth.type === "query") {
|
|
930
|
+
let u;
|
|
931
|
+
try {
|
|
932
|
+
u = new URL(url);
|
|
933
|
+
} catch {
|
|
934
|
+
throw new TransportError("network", "invalid request URL (it must be absolute)");
|
|
935
|
+
}
|
|
936
|
+
u.searchParams.set(auth.name, secret);
|
|
937
|
+
url = u.toString();
|
|
938
|
+
} else {
|
|
939
|
+
const name = auth.type === "bearer" ? "Authorization" : auth.name;
|
|
940
|
+
for (const k of Object.keys(headers)) if (k.toLowerCase() === name.toLowerCase()) delete headers[k];
|
|
941
|
+
headers[name] = auth.type === "bearer" ? `Bearer ${secret}` : `${auth.prefix ?? ""}${secret}`;
|
|
942
|
+
credentialHeaders.push(name.toLowerCase());
|
|
943
|
+
}
|
|
944
|
+
try {
|
|
945
|
+
const res = await http.request({ ...req, url, headers, credentialHeaders, urlCredential: req.urlCredential || auth.type === "query" });
|
|
946
|
+
return {
|
|
947
|
+
...res,
|
|
948
|
+
url: clean(res.url, auth, secret),
|
|
949
|
+
headers: Object.fromEntries(Object.entries(res.headers).map(([k, v]) => [k, scrub(v, secret)])),
|
|
950
|
+
body: redactBytes(res.body, secret)
|
|
951
|
+
};
|
|
952
|
+
} catch (e) {
|
|
953
|
+
throw redactError(e, auth, secret);
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
};
|
|
957
|
+
}
|
|
958
|
+
function clean(url, auth, secret) {
|
|
959
|
+
let out = url;
|
|
960
|
+
if (auth.type === "query") {
|
|
961
|
+
try {
|
|
962
|
+
const u = new URL(url);
|
|
963
|
+
u.searchParams.delete(auth.name);
|
|
964
|
+
out = u.toString();
|
|
965
|
+
} catch {
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
return scrub(out, secret);
|
|
969
|
+
}
|
|
970
|
+
function scrub(text, secret) {
|
|
971
|
+
const forms = /* @__PURE__ */ new Set([secret, encodeURIComponent(secret), new URLSearchParams({ k: secret }).toString().slice(2)]);
|
|
972
|
+
let out = text;
|
|
973
|
+
for (const f of forms) out = out.split(f).join(REDACTED);
|
|
974
|
+
return out;
|
|
975
|
+
}
|
|
976
|
+
function redactBytes(bytes, secret) {
|
|
977
|
+
const enc = new TextEncoder();
|
|
978
|
+
const forms = [.../* @__PURE__ */ new Set([secret, encodeURIComponent(secret), new URLSearchParams({ k: secret }).toString().slice(2)])].map((f) => enc.encode(f));
|
|
979
|
+
const marker = enc.encode(REDACTED);
|
|
980
|
+
let out = bytes;
|
|
981
|
+
for (const needle of forms) {
|
|
982
|
+
const parts = [];
|
|
983
|
+
let from = 0;
|
|
984
|
+
for (let i = indexOf(out, needle, 0); i !== -1; i = indexOf(out, needle, from)) {
|
|
985
|
+
parts.push(out.subarray(from, i), marker);
|
|
986
|
+
from = i + needle.length;
|
|
987
|
+
}
|
|
988
|
+
if (parts.length === 0) continue;
|
|
989
|
+
parts.push(out.subarray(from));
|
|
990
|
+
const joined = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
|
|
991
|
+
let at = 0;
|
|
992
|
+
for (const p of parts) {
|
|
993
|
+
joined.set(p, at);
|
|
994
|
+
at += p.length;
|
|
995
|
+
}
|
|
996
|
+
out = joined;
|
|
997
|
+
}
|
|
998
|
+
return out;
|
|
999
|
+
}
|
|
1000
|
+
function indexOf(hay, needle, from) {
|
|
1001
|
+
if (needle.length === 0) return -1;
|
|
1002
|
+
outer: for (let i = from; i <= hay.length - needle.length; i++) {
|
|
1003
|
+
for (let j = 0; j < needle.length; j++) if (hay[i + j] !== needle[j]) continue outer;
|
|
1004
|
+
return i;
|
|
1005
|
+
}
|
|
1006
|
+
return -1;
|
|
1007
|
+
}
|
|
1008
|
+
function redactError(e, auth, secret) {
|
|
1009
|
+
if (e instanceof MissingSecretError) return e;
|
|
1010
|
+
if (e instanceof TransportError) {
|
|
1011
|
+
const body = e.body ? redactBytes(e.body, secret) : void 0;
|
|
1012
|
+
return new TransportError(e.cause, scrub(e.message, secret), {
|
|
1013
|
+
status: e.status,
|
|
1014
|
+
url: e.url === void 0 ? void 0 : clean(e.url, auth, secret),
|
|
1015
|
+
body,
|
|
1016
|
+
ext: e.ext,
|
|
1017
|
+
contentType: e.contentType === void 0 ? void 0 : scrub(e.contentType, secret)
|
|
1018
|
+
});
|
|
1019
|
+
}
|
|
1020
|
+
const message = e instanceof Error ? scrub(e.message, secret) : "request failed";
|
|
1021
|
+
return new TransportError("network", message);
|
|
1022
|
+
}
|
|
1023
|
+
|
|
1024
|
+
// src/node/mcp-client.ts
|
|
1025
|
+
var McpError = class extends Error {
|
|
1026
|
+
constructor(kind, message, options = {}) {
|
|
1027
|
+
super(message, options.origin === void 0 ? void 0 : { cause: options.origin });
|
|
1028
|
+
this.kind = kind;
|
|
1029
|
+
this.name = "McpError";
|
|
1030
|
+
this.code = options.code;
|
|
1031
|
+
this.status = options.status;
|
|
1032
|
+
this.data = options.data;
|
|
1033
|
+
}
|
|
1034
|
+
kind;
|
|
1035
|
+
/** JSON-RPC error code, when the failure is a JSON-RPC error. */
|
|
1036
|
+
code;
|
|
1037
|
+
/** HTTP status of the response the failure came with, when there was one. */
|
|
1038
|
+
status;
|
|
1039
|
+
data;
|
|
1040
|
+
};
|
|
1041
|
+
var DEFAULT_PROTOCOL_VERSION = "2025-06-18";
|
|
1042
|
+
var DEFAULT_TIMEOUT_MS = 3e4;
|
|
1043
|
+
var MARK = "[redacted]";
|
|
1044
|
+
var AUTH_SCHEMES = /^(bearer|basic|digest|token|negotiate|apikey|api-key)$/i;
|
|
1045
|
+
var REDACTED_NOTICE = "[redacted: the remote text carried a credential]";
|
|
1046
|
+
function percentDecode(text) {
|
|
1047
|
+
return text.replace(/(?:%[0-9a-fA-F]{2})+/g, (run) => {
|
|
1048
|
+
try {
|
|
1049
|
+
return decodeURIComponent(run);
|
|
1050
|
+
} catch {
|
|
1051
|
+
return run;
|
|
1052
|
+
}
|
|
1053
|
+
});
|
|
1054
|
+
}
|
|
1055
|
+
function unescapeJson(text) {
|
|
1056
|
+
return text.replace(/\\u([0-9a-fA-F]{4})/g, (_m, h) => String.fromCharCode(parseInt(h, 16))).replace(/\\x([0-9a-fA-F]{2})/g, (_m, h) => String.fromCharCode(parseInt(h, 16))).replace(/\\(["\\/bfnrt])/g, (_m, c) => ({ b: "\b", f: "\f", n: "\n", r: "\r", t: " " })[c] ?? c);
|
|
1057
|
+
}
|
|
1058
|
+
function decodedViews(text) {
|
|
1059
|
+
const views = [text];
|
|
1060
|
+
let cur = text;
|
|
1061
|
+
for (let i = 0; i < 3; i++) {
|
|
1062
|
+
const next = percentDecode(unescapeJson(cur));
|
|
1063
|
+
if (next === cur) break;
|
|
1064
|
+
views.push(next);
|
|
1065
|
+
cur = next;
|
|
1066
|
+
}
|
|
1067
|
+
for (const v of [...views]) if (v.includes("+")) views.push(v.replace(/\+/g, " "));
|
|
1068
|
+
return views;
|
|
1069
|
+
}
|
|
1070
|
+
function createScrubber(values) {
|
|
1071
|
+
const raws = /* @__PURE__ */ new Set();
|
|
1072
|
+
for (const v of values) {
|
|
1073
|
+
if (!v) continue;
|
|
1074
|
+
raws.add(v);
|
|
1075
|
+
for (const part of v.split(/\s+/)) if (part !== v && part.length >= 4 && !AUTH_SCHEMES.test(part)) raws.add(part);
|
|
1076
|
+
}
|
|
1077
|
+
const sorted = [...raws].sort((a, b) => b.length - a.length);
|
|
1078
|
+
const carries = (text2) => decodedViews(text2).some((view) => sorted.some((r) => view.includes(r)));
|
|
1079
|
+
const text = (t) => {
|
|
1080
|
+
if (sorted.length === 0) return t;
|
|
1081
|
+
let out = t;
|
|
1082
|
+
for (const r of sorted) if (out.includes(r)) out = out.split(r).join(MARK);
|
|
1083
|
+
return carries(out) ? REDACTED_NOTICE : out;
|
|
1084
|
+
};
|
|
1085
|
+
const blocks = (texts) => {
|
|
1086
|
+
const each = texts.map(text);
|
|
1087
|
+
if (sorted.length === 0 || texts.length < 2) return each;
|
|
1088
|
+
const joined = each.join("");
|
|
1089
|
+
const bounds = [];
|
|
1090
|
+
let offset = 0;
|
|
1091
|
+
for (const t of each) {
|
|
1092
|
+
bounds.push([offset, offset + t.length]);
|
|
1093
|
+
offset += t.length;
|
|
1094
|
+
}
|
|
1095
|
+
const touched = /* @__PURE__ */ new Set();
|
|
1096
|
+
for (const r of sorted) {
|
|
1097
|
+
for (let from = 0; ; ) {
|
|
1098
|
+
const at = joined.indexOf(r, from);
|
|
1099
|
+
if (at < 0) break;
|
|
1100
|
+
const end = at + r.length;
|
|
1101
|
+
bounds.forEach(([a, b], i) => {
|
|
1102
|
+
if (b > a && a < end && b > at) touched.add(i);
|
|
1103
|
+
});
|
|
1104
|
+
from = end;
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
if (touched.size === 0 && carries(joined)) bounds.forEach(([a, b], i) => b > a && touched.add(i));
|
|
1108
|
+
return each.map((t, i) => touched.has(i) ? REDACTED_NOTICE : t);
|
|
1109
|
+
};
|
|
1110
|
+
const walk = (v, keys) => {
|
|
1111
|
+
if (typeof v === "string") return text(v);
|
|
1112
|
+
if (Array.isArray(v)) return v.map((x) => walk(x, keys));
|
|
1113
|
+
if (v && typeof v === "object") return Object.fromEntries(Object.entries(v).map(([k, x]) => [keys ? text(k) : k, walk(x, keys)]));
|
|
1114
|
+
return v;
|
|
1115
|
+
};
|
|
1116
|
+
const schema = (v) => {
|
|
1117
|
+
if (Array.isArray(v)) return v.map(schema);
|
|
1118
|
+
if (v && typeof v === "object") {
|
|
1119
|
+
return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, (k === "description" || k === "title") && typeof x === "string" ? text(x) : schema(x)]));
|
|
1120
|
+
}
|
|
1121
|
+
return v;
|
|
1122
|
+
};
|
|
1123
|
+
const tool = (t) => {
|
|
1124
|
+
const o = t;
|
|
1125
|
+
const out = { ...o };
|
|
1126
|
+
if (typeof o.title === "string") out.title = text(o.title);
|
|
1127
|
+
if (typeof o.description === "string") out.description = text(o.description);
|
|
1128
|
+
if (o.inputSchema !== void 0) out.inputSchema = schema(o.inputSchema);
|
|
1129
|
+
if (o.outputSchema !== void 0) out.outputSchema = schema(o.outputSchema);
|
|
1130
|
+
return out;
|
|
1131
|
+
};
|
|
1132
|
+
return { text, blocks, values: (v, keys = true) => walk(v, keys), tool, carries };
|
|
1133
|
+
}
|
|
1134
|
+
function createRedactor(values) {
|
|
1135
|
+
return createScrubber(values).text;
|
|
1136
|
+
}
|
|
1137
|
+
var CONTROL_FIELDS = /* @__PURE__ */ new Set(["type", "mimeType"]);
|
|
1138
|
+
function scrubResult(result, scrubber) {
|
|
1139
|
+
const out = { ...result };
|
|
1140
|
+
if (Array.isArray(result.content)) {
|
|
1141
|
+
const blocks = result.content.map(
|
|
1142
|
+
(b) => b && typeof b === "object" ? Object.fromEntries(Object.entries(b).map(([k, v]) => [k, CONTROL_FIELDS.has(k) || k === "text" && b.type === "text" ? v : scrubber.values(v)])) : b
|
|
1143
|
+
);
|
|
1144
|
+
const textIdx = blocks.map((b, i) => b && b.type === "text" && typeof b.text === "string" ? i : -1).filter((i) => i >= 0);
|
|
1145
|
+
const scrubbed = scrubber.blocks(textIdx.map((i) => blocks[i].text));
|
|
1146
|
+
textIdx.forEach((i, n) => {
|
|
1147
|
+
blocks[i].text = scrubbed[n];
|
|
1148
|
+
});
|
|
1149
|
+
out.content = blocks;
|
|
1150
|
+
}
|
|
1151
|
+
if (result.structuredContent !== void 0) out.structuredContent = scrubber.values(result.structuredContent);
|
|
1152
|
+
return out;
|
|
1153
|
+
}
|
|
1154
|
+
function isResponseTo(m, id) {
|
|
1155
|
+
if (!m || typeof m !== "object" || Array.isArray(m)) return false;
|
|
1156
|
+
const r = m;
|
|
1157
|
+
return r.id === id && r.method === void 0 && ("result" in r || "error" in r);
|
|
1158
|
+
}
|
|
1159
|
+
var SseParser = class {
|
|
1160
|
+
decoder = new TextDecoder();
|
|
1161
|
+
line = "";
|
|
1162
|
+
skipLf = false;
|
|
1163
|
+
data = [];
|
|
1164
|
+
event = "";
|
|
1165
|
+
push(chunk) {
|
|
1166
|
+
const text = typeof chunk === "string" ? chunk : this.decoder.decode(chunk, { stream: true });
|
|
1167
|
+
const events = [];
|
|
1168
|
+
for (const ch of text) {
|
|
1169
|
+
if (this.skipLf) {
|
|
1170
|
+
this.skipLf = false;
|
|
1171
|
+
if (ch === "\n") continue;
|
|
1172
|
+
}
|
|
1173
|
+
if (ch !== "\r" && ch !== "\n") {
|
|
1174
|
+
this.line += ch;
|
|
1175
|
+
continue;
|
|
1176
|
+
}
|
|
1177
|
+
this.skipLf = ch === "\r";
|
|
1178
|
+
const line = this.line;
|
|
1179
|
+
this.line = "";
|
|
1180
|
+
if (line === "") {
|
|
1181
|
+
if (this.data.length > 0) events.push({ event: this.event || "message", data: this.data.join("\n") });
|
|
1182
|
+
this.data = [];
|
|
1183
|
+
this.event = "";
|
|
1184
|
+
continue;
|
|
1185
|
+
}
|
|
1186
|
+
if (line.startsWith(":")) continue;
|
|
1187
|
+
const colon = line.indexOf(":");
|
|
1188
|
+
const field = colon < 0 ? line : line.slice(0, colon);
|
|
1189
|
+
let value = colon < 0 ? "" : line.slice(colon + 1);
|
|
1190
|
+
if (value.startsWith(" ")) value = value.slice(1);
|
|
1191
|
+
if (field === "event") this.event = value;
|
|
1192
|
+
else if (field === "data") this.data.push(value);
|
|
1193
|
+
}
|
|
1194
|
+
return events;
|
|
1195
|
+
}
|
|
1196
|
+
};
|
|
1197
|
+
function parseSseMessages(text) {
|
|
1198
|
+
const out = [];
|
|
1199
|
+
for (const e of new SseParser().push(`${text}
|
|
1200
|
+
|
|
1201
|
+
`)) {
|
|
1202
|
+
if (e.event !== "message") continue;
|
|
1203
|
+
try {
|
|
1204
|
+
out.push(JSON.parse(e.data));
|
|
1205
|
+
} catch {
|
|
1206
|
+
}
|
|
1207
|
+
}
|
|
1208
|
+
return out;
|
|
1209
|
+
}
|
|
1210
|
+
function createMcpClient(options) {
|
|
1211
|
+
const doFetch = options.fetch ?? fetch;
|
|
1212
|
+
const requestedProtocol = options.protocolVersion ?? DEFAULT_PROTOCOL_VERSION;
|
|
1213
|
+
const defaultTimeout = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
1214
|
+
let negotiated;
|
|
1215
|
+
let nextId = 0;
|
|
1216
|
+
let sessionId;
|
|
1217
|
+
let ready;
|
|
1218
|
+
let reiniting;
|
|
1219
|
+
let generation = 0;
|
|
1220
|
+
const secrets = [...Object.values(options.headers ?? {}), ...options.redact ?? []];
|
|
1221
|
+
try {
|
|
1222
|
+
const u = new URL(options.endpoint);
|
|
1223
|
+
if (u.username) secrets.push(decodeURIComponent(u.username));
|
|
1224
|
+
if (u.password) secrets.push(decodeURIComponent(u.password));
|
|
1225
|
+
for (const v of u.searchParams.values()) secrets.push(v);
|
|
1226
|
+
} catch {
|
|
1227
|
+
}
|
|
1228
|
+
const scrubber = createScrubber(secrets);
|
|
1229
|
+
const scrub2 = scrubber.text;
|
|
1230
|
+
const protocol = () => negotiated ?? requestedProtocol;
|
|
1231
|
+
const REDIRECTS = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
|
|
1232
|
+
async function fetchSameOrigin(url, init) {
|
|
1233
|
+
let target = url;
|
|
1234
|
+
for (let hop = 0; hop < 6; hop++) {
|
|
1235
|
+
const res = await doFetch(target, { ...init, redirect: "manual" });
|
|
1236
|
+
const location = REDIRECTS.has(res.status) ? res.headers.get("location") : null;
|
|
1237
|
+
if (!location) return res;
|
|
1238
|
+
void res.body?.cancel().catch(() => void 0);
|
|
1239
|
+
let next;
|
|
1240
|
+
try {
|
|
1241
|
+
next = new URL(location, target);
|
|
1242
|
+
} catch {
|
|
1243
|
+
throw remoteError("http", `HTTP ${res.status}: redirect with an invalid location; refused`, { status: res.status });
|
|
1244
|
+
}
|
|
1245
|
+
if (next.origin !== new URL(target).origin) {
|
|
1246
|
+
throw remoteError("http", `HTTP ${res.status}: redirect to another origin; refused, nothing was sent there`, { status: res.status });
|
|
1247
|
+
}
|
|
1248
|
+
target = next.toString();
|
|
1249
|
+
}
|
|
1250
|
+
throw remoteError("http", "too many redirects; refused");
|
|
1251
|
+
}
|
|
1252
|
+
function remoteError(kind, message, extra = {}) {
|
|
1253
|
+
return new McpError(kind, scrub2(message), { ...extra, ...extra.data === void 0 ? {} : { data: scrubber.values(extra.data) } });
|
|
1254
|
+
}
|
|
1255
|
+
function scrubbedCause(e) {
|
|
1256
|
+
const copy = new Error(scrub2(e instanceof Error ? e.message : String(e)));
|
|
1257
|
+
copy.name = e instanceof Error ? e.name : "Error";
|
|
1258
|
+
return copy;
|
|
1259
|
+
}
|
|
1260
|
+
function rpcError(method, e, status) {
|
|
1261
|
+
return remoteError("rpc", `${method}: ${e.message ?? "JSON-RPC error"} (${e.code ?? "no code"})`, { code: e.code, status, data: e.data });
|
|
1262
|
+
}
|
|
1263
|
+
async function send(body, call, withSession) {
|
|
1264
|
+
const timeoutMs = call.timeoutMs ?? defaultTimeout;
|
|
1265
|
+
const timeout = AbortSignal.timeout(timeoutMs);
|
|
1266
|
+
const signals = [timeout, call.detached ? void 0 : options.signal, call.signal].filter((s) => s !== void 0);
|
|
1267
|
+
const signal = AbortSignal.any(signals);
|
|
1268
|
+
const method = String(body.method ?? "request");
|
|
1269
|
+
const id = body.id;
|
|
1270
|
+
const usedSession = withSession ? sessionId : void 0;
|
|
1271
|
+
try {
|
|
1272
|
+
const res = await fetchSameOrigin(options.endpoint, {
|
|
1273
|
+
method: "POST",
|
|
1274
|
+
headers: {
|
|
1275
|
+
"content-type": "application/json",
|
|
1276
|
+
accept: "application/json, text/event-stream",
|
|
1277
|
+
"mcp-protocol-version": protocol(),
|
|
1278
|
+
...usedSession ? { "mcp-session-id": usedSession } : {},
|
|
1279
|
+
...options.headers
|
|
1280
|
+
},
|
|
1281
|
+
body: JSON.stringify(body),
|
|
1282
|
+
signal
|
|
1283
|
+
});
|
|
1284
|
+
if (id === void 0) {
|
|
1285
|
+
await res.arrayBuffer().catch(() => void 0);
|
|
1286
|
+
if (!res.ok) throw remoteError("http", `${method}: HTTP ${res.status}`, { status: res.status });
|
|
1287
|
+
return { headers: res.headers, usedSession };
|
|
1288
|
+
}
|
|
1289
|
+
const type = res.headers.get("content-type") ?? "";
|
|
1290
|
+
let reply;
|
|
1291
|
+
if (res.ok && type.includes("text/event-stream") && res.body) {
|
|
1292
|
+
reply = await readReply(res.body, id);
|
|
1293
|
+
} else {
|
|
1294
|
+
const text = await res.text();
|
|
1295
|
+
const found = jsonMessages(text, type).find((m) => isResponseTo(m, id));
|
|
1296
|
+
if (!res.ok) {
|
|
1297
|
+
const rpc = jsonMessages(text, type).find((m) => m.error);
|
|
1298
|
+
if (rpc?.error) throw rpcError(method, rpc.error, res.status);
|
|
1299
|
+
throw remoteError("http", `${method}: HTTP ${res.status}`, { status: res.status });
|
|
1300
|
+
}
|
|
1301
|
+
reply = found;
|
|
1302
|
+
}
|
|
1303
|
+
if (!reply) throw remoteError("protocol", `${method}: the reply carries no response to request ${id}`, { status: res.status });
|
|
1304
|
+
if (reply.error) throw rpcError(method, reply.error, res.status);
|
|
1305
|
+
return { reply, headers: res.headers, usedSession };
|
|
1306
|
+
} catch (e) {
|
|
1307
|
+
if (e instanceof McpError) throw e;
|
|
1308
|
+
const origin = scrubbedCause(e);
|
|
1309
|
+
if (timeout.aborted) throw new McpError("timeout", `${method}: no reply within ${timeoutMs} ms`, { origin });
|
|
1310
|
+
if (signal.aborted) throw new McpError("aborted", `${method}: aborted`, { origin });
|
|
1311
|
+
throw new McpError("network", scrub2(`${method}: ${e instanceof Error ? e.message : String(e)}`), { origin });
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
function jsonMessages(text, contentType) {
|
|
1315
|
+
const onlyObjects = (list) => list.filter((m) => !!m && typeof m === "object" && !Array.isArray(m));
|
|
1316
|
+
if (contentType.includes("text/event-stream")) return onlyObjects(parseSseMessages(text));
|
|
1317
|
+
try {
|
|
1318
|
+
const v = JSON.parse(text);
|
|
1319
|
+
return onlyObjects(Array.isArray(v) ? v : [v]);
|
|
1320
|
+
} catch {
|
|
1321
|
+
return onlyObjects(parseSseMessages(text));
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
async function readReply(stream, id) {
|
|
1325
|
+
const reader = stream.getReader();
|
|
1326
|
+
const parser = new SseParser();
|
|
1327
|
+
try {
|
|
1328
|
+
for (; ; ) {
|
|
1329
|
+
const { done, value } = await reader.read();
|
|
1330
|
+
if (value) {
|
|
1331
|
+
for (const e of parser.push(value)) {
|
|
1332
|
+
if (e.event !== "message") continue;
|
|
1333
|
+
let msg;
|
|
1334
|
+
try {
|
|
1335
|
+
msg = JSON.parse(e.data);
|
|
1336
|
+
} catch {
|
|
1337
|
+
continue;
|
|
1338
|
+
}
|
|
1339
|
+
if (isResponseTo(msg, id)) return msg;
|
|
1340
|
+
}
|
|
1341
|
+
}
|
|
1342
|
+
if (done) {
|
|
1343
|
+
for (const e of parser.push("\n")) {
|
|
1344
|
+
if (e.event !== "message") continue;
|
|
1345
|
+
try {
|
|
1346
|
+
const msg = JSON.parse(e.data);
|
|
1347
|
+
if (isResponseTo(msg, id)) return msg;
|
|
1348
|
+
} catch {
|
|
1349
|
+
}
|
|
1350
|
+
}
|
|
1351
|
+
return void 0;
|
|
1352
|
+
}
|
|
1353
|
+
}
|
|
1354
|
+
} finally {
|
|
1355
|
+
void reader.cancel().catch(() => void 0);
|
|
1356
|
+
}
|
|
1357
|
+
}
|
|
1358
|
+
async function handshake(call) {
|
|
1359
|
+
const init = await send(
|
|
1360
|
+
{
|
|
1361
|
+
jsonrpc: "2.0",
|
|
1362
|
+
id: ++nextId,
|
|
1363
|
+
method: "initialize",
|
|
1364
|
+
params: { protocolVersion: requestedProtocol, capabilities: {}, clientInfo: options.clientInfo ?? { name: "agentproto-collect", version: "0.0.0" } }
|
|
1365
|
+
},
|
|
1366
|
+
call,
|
|
1367
|
+
false
|
|
1368
|
+
);
|
|
1369
|
+
const result = init.reply?.result;
|
|
1370
|
+
if (!result || typeof result !== "object" || Array.isArray(result) || typeof result.protocolVersion !== "string" || !result.protocolVersion) {
|
|
1371
|
+
throw new McpError("protocol", "initialize: the result carries no protocolVersion");
|
|
1372
|
+
}
|
|
1373
|
+
const sid = init.headers.get("mcp-session-id") || void 0;
|
|
1374
|
+
negotiated = result.protocolVersion;
|
|
1375
|
+
sessionId = sid;
|
|
1376
|
+
generation++;
|
|
1377
|
+
try {
|
|
1378
|
+
await send({ jsonrpc: "2.0", method: "notifications/initialized", params: {} }, call, true);
|
|
1379
|
+
} catch (e) {
|
|
1380
|
+
invalidate();
|
|
1381
|
+
throw e;
|
|
1382
|
+
}
|
|
1383
|
+
}
|
|
1384
|
+
function invalidate() {
|
|
1385
|
+
sessionId = void 0;
|
|
1386
|
+
negotiated = void 0;
|
|
1387
|
+
ready = void 0;
|
|
1388
|
+
}
|
|
1389
|
+
async function shared(call, current, start) {
|
|
1390
|
+
const other = current();
|
|
1391
|
+
if (!other) return start();
|
|
1392
|
+
if (!call.detached) return other;
|
|
1393
|
+
const limit = call.timeoutMs ?? defaultTimeout;
|
|
1394
|
+
let waited = false;
|
|
1395
|
+
let timer;
|
|
1396
|
+
const deadline = new Promise((_resolve, reject) => {
|
|
1397
|
+
timer = setTimeout(() => {
|
|
1398
|
+
waited = true;
|
|
1399
|
+
reject(new McpError("timeout", `waiting for the session: no result within ${limit} ms`));
|
|
1400
|
+
}, limit);
|
|
1401
|
+
});
|
|
1402
|
+
try {
|
|
1403
|
+
await Promise.race([other, deadline]);
|
|
1404
|
+
} catch (e) {
|
|
1405
|
+
if (waited) throw e;
|
|
1406
|
+
return shared(call, current, start);
|
|
1407
|
+
} finally {
|
|
1408
|
+
clearTimeout(timer);
|
|
1409
|
+
}
|
|
1410
|
+
}
|
|
1411
|
+
function initialize(call = {}) {
|
|
1412
|
+
return shared(
|
|
1413
|
+
call,
|
|
1414
|
+
() => ready,
|
|
1415
|
+
() => {
|
|
1416
|
+
ready = handshake(call).catch((e) => {
|
|
1417
|
+
ready = void 0;
|
|
1418
|
+
throw e;
|
|
1419
|
+
});
|
|
1420
|
+
return ready;
|
|
1421
|
+
}
|
|
1422
|
+
);
|
|
1423
|
+
}
|
|
1424
|
+
function reinitialise(call) {
|
|
1425
|
+
return shared(
|
|
1426
|
+
call,
|
|
1427
|
+
() => reiniting,
|
|
1428
|
+
() => {
|
|
1429
|
+
invalidate();
|
|
1430
|
+
reiniting = initialize(call).finally(() => {
|
|
1431
|
+
reiniting = void 0;
|
|
1432
|
+
});
|
|
1433
|
+
return reiniting;
|
|
1434
|
+
}
|
|
1435
|
+
);
|
|
1436
|
+
}
|
|
1437
|
+
async function request(method, params, call) {
|
|
1438
|
+
await initialize(call);
|
|
1439
|
+
const usedSession = sessionId;
|
|
1440
|
+
const usedGeneration = generation;
|
|
1441
|
+
const attempt = () => send({ jsonrpc: "2.0", id: ++nextId, method, params }, call, true);
|
|
1442
|
+
try {
|
|
1443
|
+
return (await attempt()).reply?.result;
|
|
1444
|
+
} catch (e) {
|
|
1445
|
+
if (e instanceof McpError && e.status === 404 && usedSession) {
|
|
1446
|
+
await (generation === usedGeneration || reiniting ? reinitialise(call) : initialize(call));
|
|
1447
|
+
const replayGeneration = generation;
|
|
1448
|
+
try {
|
|
1449
|
+
return (await attempt()).reply?.result;
|
|
1450
|
+
} catch (again) {
|
|
1451
|
+
if (generation === replayGeneration) invalidate();
|
|
1452
|
+
throw again;
|
|
1453
|
+
}
|
|
1454
|
+
}
|
|
1455
|
+
throw e;
|
|
1456
|
+
}
|
|
1457
|
+
}
|
|
1458
|
+
return {
|
|
1459
|
+
initialize,
|
|
1460
|
+
async listTools(call = {}) {
|
|
1461
|
+
const tools = [];
|
|
1462
|
+
let cursor;
|
|
1463
|
+
for (let page = 0; page < 50; page++) {
|
|
1464
|
+
const result = await request("tools/list", cursor ? { cursor } : {}, call);
|
|
1465
|
+
tools.push(...result?.tools ?? []);
|
|
1466
|
+
cursor = result?.nextCursor;
|
|
1467
|
+
if (!cursor) break;
|
|
1468
|
+
}
|
|
1469
|
+
return tools.map((t) => scrubber.tool(t));
|
|
1470
|
+
},
|
|
1471
|
+
async callTool(name, args = {}, call = {}) {
|
|
1472
|
+
const result = await request("tools/call", { name, arguments: args }, call);
|
|
1473
|
+
if (!result || typeof result !== "object") throw new McpError("protocol", `tools/call ${scrub2(name)}: empty result`);
|
|
1474
|
+
return call.scrub === false ? result : scrubResult(result, scrubber);
|
|
1475
|
+
},
|
|
1476
|
+
async close() {
|
|
1477
|
+
if (!sessionId) return;
|
|
1478
|
+
const sid = sessionId;
|
|
1479
|
+
sessionId = void 0;
|
|
1480
|
+
ready = void 0;
|
|
1481
|
+
try {
|
|
1482
|
+
await fetchSameOrigin(options.endpoint, {
|
|
1483
|
+
method: "DELETE",
|
|
1484
|
+
headers: { "mcp-session-id": sid, "mcp-protocol-version": protocol(), ...options.headers },
|
|
1485
|
+
signal: AbortSignal.timeout(5e3)
|
|
1486
|
+
});
|
|
1487
|
+
} catch {
|
|
1488
|
+
}
|
|
1489
|
+
},
|
|
1490
|
+
get sessionId() {
|
|
1491
|
+
return sessionId;
|
|
1492
|
+
},
|
|
1493
|
+
get protocolVersion() {
|
|
1494
|
+
return protocol();
|
|
1495
|
+
},
|
|
1496
|
+
scrub: scrub2,
|
|
1497
|
+
scrubResult: (r) => scrubResult(r, scrubber),
|
|
1498
|
+
scrubValue: (v, keys = false) => scrubber.values(v, keys)
|
|
1499
|
+
};
|
|
1500
|
+
}
|
|
1501
|
+
|
|
1502
|
+
// src/node/browser-transport.ts
|
|
1503
|
+
function textOf(result) {
|
|
1504
|
+
return (result.content ?? []).filter((b) => b.type === "text" && typeof b.text === "string").map((b) => b.text).join("\n");
|
|
1505
|
+
}
|
|
1506
|
+
function tryJson(text) {
|
|
1507
|
+
try {
|
|
1508
|
+
return { ok: true, value: JSON.parse(text) };
|
|
1509
|
+
} catch {
|
|
1510
|
+
return { ok: false };
|
|
1511
|
+
}
|
|
1512
|
+
}
|
|
1513
|
+
function isRecord(v) {
|
|
1514
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
1515
|
+
}
|
|
1516
|
+
function truncatedError(reason) {
|
|
1517
|
+
const why = typeof reason === "string" && reason ? reason : "no reason given";
|
|
1518
|
+
return new TransportError("empty", `the page returned a truncated result (${why}); it is not used`);
|
|
1519
|
+
}
|
|
1520
|
+
function unwrapValueJson(result) {
|
|
1521
|
+
const text = textOf(result);
|
|
1522
|
+
const parsed = text ? tryJson(text) : { ok: false };
|
|
1523
|
+
const body = parsed.ok ? parsed.value : isRecord(result.structuredContent) ? result.structuredContent : void 0;
|
|
1524
|
+
if (!isRecord(body) || !("value" in body || "truncated" in body)) {
|
|
1525
|
+
throw new TransportError("empty", "the page returned an unreadable result");
|
|
1526
|
+
}
|
|
1527
|
+
if (body.truncated === true) throw truncatedError(body.reason ?? body.truncatedReason ?? body.message);
|
|
1528
|
+
return body.value;
|
|
1529
|
+
}
|
|
1530
|
+
function unwrapFenced(result) {
|
|
1531
|
+
const text = textOf(result);
|
|
1532
|
+
const fence = /```json\s*([\s\S]*?)```/i.exec(text);
|
|
1533
|
+
const parsed = tryJson(fence ? fence[1].trim() : text.trim());
|
|
1534
|
+
if (!parsed.ok) throw new TransportError("empty", "the page returned an unreadable result");
|
|
1535
|
+
return parsed.value;
|
|
1536
|
+
}
|
|
1537
|
+
function idFrom(v) {
|
|
1538
|
+
if (typeof v === "string" && v) return v;
|
|
1539
|
+
if (typeof v === "number" && Number.isFinite(v)) return String(v);
|
|
1540
|
+
return void 0;
|
|
1541
|
+
}
|
|
1542
|
+
function tabIdFromJson(result) {
|
|
1543
|
+
const text = textOf(result);
|
|
1544
|
+
const parsed = text ? tryJson(text) : { ok: false };
|
|
1545
|
+
const candidates = [];
|
|
1546
|
+
if (parsed.ok) candidates.push(parsed.value);
|
|
1547
|
+
if (result.structuredContent !== void 0) candidates.push(result.structuredContent);
|
|
1548
|
+
for (const c of candidates) {
|
|
1549
|
+
if (!isRecord(c)) continue;
|
|
1550
|
+
const inner = isRecord(c.value) ? c.value : isRecord(c.tab) ? c.tab : void 0;
|
|
1551
|
+
for (const src of [c, inner]) {
|
|
1552
|
+
if (!src) continue;
|
|
1553
|
+
const id = idFrom(src.tabId) ?? idFrom(src.id) ?? idFrom(src.targetId);
|
|
1554
|
+
if (id) return id;
|
|
1555
|
+
}
|
|
1556
|
+
}
|
|
1557
|
+
const m = /tab[ _-]?id\W{0,4}([\w-]+)/i.exec(text);
|
|
1558
|
+
return m?.[1];
|
|
1559
|
+
}
|
|
1560
|
+
function listFromJson(result) {
|
|
1561
|
+
const text = textOf(result);
|
|
1562
|
+
const parsed = text ? tryJson(text) : { ok: false };
|
|
1563
|
+
let body = parsed.ok ? parsed.value : result.structuredContent;
|
|
1564
|
+
if (isRecord(body) && "value" in body) body = body.value;
|
|
1565
|
+
if (isRecord(body) && Array.isArray(body.tabs)) body = body.tabs;
|
|
1566
|
+
if (!Array.isArray(body)) return [];
|
|
1567
|
+
const out = [];
|
|
1568
|
+
for (const t of body) {
|
|
1569
|
+
if (!isRecord(t)) continue;
|
|
1570
|
+
const id = idFrom(t.tabId) ?? idFrom(t.id) ?? idFrom(t.targetId);
|
|
1571
|
+
if (id && typeof t.url === "string") out.push({ id, url: t.url, ...t.active === true || t.selected === true ? { selected: true } : {} });
|
|
1572
|
+
}
|
|
1573
|
+
return out;
|
|
1574
|
+
}
|
|
1575
|
+
var TAB_TOOLS_PROFILE = {
|
|
1576
|
+
name: "tab-tools",
|
|
1577
|
+
tools: { newTab: "browser_new_tab", navigate: "browser_navigate", evaluate: "browser_evaluate", closeTab: "browser_close_tab", listTabs: "browser_list_owned_tabs" },
|
|
1578
|
+
script: "expression",
|
|
1579
|
+
addressing: "explicit",
|
|
1580
|
+
args: {
|
|
1581
|
+
newTab: (url, instance) => ({ url, focus: false, ...instance ? { instance } : {} }),
|
|
1582
|
+
navigate: (tabId, url, instance) => ({ url, tabId, ...instance ? { instance } : {} }),
|
|
1583
|
+
evaluate: (tabId, expression, instance) => ({ expression, tabId, ...instance ? { instance } : {} }),
|
|
1584
|
+
closeTab: (tabId, instance) => ({ tabId, ...instance ? { instance } : {} }),
|
|
1585
|
+
listTabs: (instance) => instance ? { instance } : {}
|
|
1586
|
+
},
|
|
1587
|
+
tabId: tabIdFromJson,
|
|
1588
|
+
tabs: listFromJson,
|
|
1589
|
+
value: unwrapValueJson
|
|
1590
|
+
};
|
|
1591
|
+
function urlOfListing(rest) {
|
|
1592
|
+
let text = rest.trim();
|
|
1593
|
+
for (; ; ) {
|
|
1594
|
+
const next = text.replace(/\s+(\[selected\]|isolatedContext=\S+|webauthn=\S+)$/, "");
|
|
1595
|
+
if (next === text) break;
|
|
1596
|
+
text = next;
|
|
1597
|
+
}
|
|
1598
|
+
if (text.endsWith(")")) {
|
|
1599
|
+
const at = text.lastIndexOf(" (");
|
|
1600
|
+
const url = at >= 0 ? text.slice(at + 2, -1) : "";
|
|
1601
|
+
if (/^[a-z][a-z0-9+.-]*:/i.test(url)) return url;
|
|
1602
|
+
}
|
|
1603
|
+
return text;
|
|
1604
|
+
}
|
|
1605
|
+
function listFromPages(result) {
|
|
1606
|
+
const structured = isRecord(result.structuredContent) ? result.structuredContent.pages : void 0;
|
|
1607
|
+
if (Array.isArray(structured)) {
|
|
1608
|
+
const out2 = [];
|
|
1609
|
+
for (const p of structured) {
|
|
1610
|
+
if (!isRecord(p)) continue;
|
|
1611
|
+
const id = idFrom(p.id);
|
|
1612
|
+
if (id && typeof p.url === "string") out2.push({ id, url: p.url, ...p.selected === true ? { selected: true } : {} });
|
|
1613
|
+
}
|
|
1614
|
+
if (out2.length) return out2;
|
|
1615
|
+
}
|
|
1616
|
+
const out = [];
|
|
1617
|
+
for (const line of textOf(result).split(/\r?\n/)) {
|
|
1618
|
+
const m = /^\s*(\d+):\s+(.*)$/.exec(line);
|
|
1619
|
+
if (m) out.push({ id: m[1], url: urlOfListing(m[2]), .../\[selected\](?:\s+\S+=\S+)*\s*$/.test(m[2]) ? { selected: true } : {} });
|
|
1620
|
+
}
|
|
1621
|
+
return out;
|
|
1622
|
+
}
|
|
1623
|
+
var CHROME_DEVTOOLS_PROFILE = {
|
|
1624
|
+
name: "chrome-devtools",
|
|
1625
|
+
tools: { newTab: "new_page", navigate: "navigate_page", evaluate: "evaluate_script", closeTab: "close_page", listTabs: "list_pages" },
|
|
1626
|
+
script: "function",
|
|
1627
|
+
addressing: "explicit",
|
|
1628
|
+
verifyRouting: true,
|
|
1629
|
+
args: {
|
|
1630
|
+
newTab: (url) => ({ url, background: true }),
|
|
1631
|
+
navigate: (tab, url) => ({ pageId: Number(tab), type: "url", url }),
|
|
1632
|
+
evaluate: (tab, code) => ({ pageId: Number(tab), function: code }),
|
|
1633
|
+
closeTab: (tab) => ({ pageId: Number(tab) }),
|
|
1634
|
+
listTabs: () => ({})
|
|
1635
|
+
},
|
|
1636
|
+
// The new page is the listed one that carries the marker; the transport looks it up by exact URL.
|
|
1637
|
+
tabId: () => void 0,
|
|
1638
|
+
tabs: listFromPages,
|
|
1639
|
+
value: unwrapFenced
|
|
1640
|
+
};
|
|
1641
|
+
var CHROME_DEVTOOLS_INDEX_PROFILE = {
|
|
1642
|
+
name: "chrome-devtools-index",
|
|
1643
|
+
tools: { newTab: "new_page", navigate: "navigate_page", evaluate: "evaluate_script", closeTab: "close_page", selectTab: "select_page", listTabs: "list_pages" },
|
|
1644
|
+
script: "function",
|
|
1645
|
+
addressing: "selected",
|
|
1646
|
+
args: {
|
|
1647
|
+
newTab: (url) => ({ url, background: true }),
|
|
1648
|
+
navigate: (_tab, url) => ({ type: "url", url }),
|
|
1649
|
+
evaluate: (_tab, code) => ({ function: code }),
|
|
1650
|
+
closeTab: (tab) => ({ pageIdx: Number(tab) }),
|
|
1651
|
+
selectTab: (tab) => ({ pageIdx: Number(tab), bringToFront: false }),
|
|
1652
|
+
listTabs: () => ({})
|
|
1653
|
+
},
|
|
1654
|
+
tabId() {
|
|
1655
|
+
return void 0;
|
|
1656
|
+
},
|
|
1657
|
+
tabs: listFromPages,
|
|
1658
|
+
value: unwrapFenced
|
|
1659
|
+
};
|
|
1660
|
+
function browserProfile(name) {
|
|
1661
|
+
if (name === "tab-tools") return TAB_TOOLS_PROFILE;
|
|
1662
|
+
if (name === "chrome-devtools") return CHROME_DEVTOOLS_PROFILE;
|
|
1663
|
+
if (name === "chrome-devtools-index") return CHROME_DEVTOOLS_INDEX_PROFILE;
|
|
1664
|
+
throw new Error(`unknown browser profile "${name}" (use chrome-devtools, chrome-devtools-index or tab-tools)`);
|
|
1665
|
+
}
|
|
1666
|
+
function requiredTools(profile, overrides = {}) {
|
|
1667
|
+
const t = { ...profile.tools, ...overrides };
|
|
1668
|
+
const names = [t.newTab, t.navigate, t.evaluate, t.closeTab];
|
|
1669
|
+
if (t.selectTab) names.push(t.selectTab);
|
|
1670
|
+
if ((profile.addressing === "selected" || profile.verifyRouting) && t.listTabs) names.push(t.listTabs);
|
|
1671
|
+
return names;
|
|
1672
|
+
}
|
|
1673
|
+
var CHALLENGE_SCRIPT = `
|
|
1674
|
+
const __check = () => {
|
|
1675
|
+
const body = document.body ? String(document.body.innerText || "") : "";
|
|
1676
|
+
// Containers only a verification page has.
|
|
1677
|
+
const strong = ["#challenge-form", "#cf-challenge-running", "#challenge-running", "#px-captcha", "#sec-if-cpt-container", "#captcha-form", 'form[action*="captcha" i]'];
|
|
1678
|
+
// Widgets a normal page can carry too (a reCAPTCHA badge, a turnstile on a sign-up form): they only count on a short page.
|
|
1679
|
+
const widgets = [".cf-turnstile", 'iframe[src*="challenges.cloudflare.com"]', 'iframe[src*="hcaptcha.com"]', 'iframe[src*="recaptcha"]', ".g-recaptcha", ".h-captcha"];
|
|
1680
|
+
for (const s of body.length < 3000 ? strong.concat(widgets) : strong) {
|
|
1681
|
+
let el = null;
|
|
1682
|
+
try { el = document.querySelector(s); } catch (e) {}
|
|
1683
|
+
if (el) return { challenge: true, marker: s };
|
|
1684
|
+
}
|
|
1685
|
+
const title = String(document.title || "").toLowerCase();
|
|
1686
|
+
for (const t of ["just a moment", "attention required", "access denied", "are you a robot", "security check", "verify you are human"]) {
|
|
1687
|
+
if (title.includes(t)) return { challenge: true, marker: "title: " + t };
|
|
1688
|
+
}
|
|
1689
|
+
if (body.length < 3000) {
|
|
1690
|
+
const text = body.toLowerCase();
|
|
1691
|
+
for (const t of ["verify you are human", "verifying you are human", "checking your browser", "checking if the site connection is secure", "unusual traffic from your computer", "are you a robot", "press & hold", "please enable javascript and cookies to continue", "complete the security check", "captcha"]) {
|
|
1692
|
+
if (text.includes(t)) return { challenge: true, marker: "text: " + t };
|
|
1693
|
+
}
|
|
1694
|
+
}
|
|
1695
|
+
return { challenge: false };
|
|
1696
|
+
};
|
|
1697
|
+
const __r = __check();
|
|
1698
|
+
__r.url = String(location.href);
|
|
1699
|
+
return __r;
|
|
1700
|
+
`;
|
|
1701
|
+
var HTML_STRONG_MARKERS = ["px-captcha", "cf-challenge-running", "sec-if-cpt-container"];
|
|
1702
|
+
var HTML_WIDGET_MARKERS = ["cf-turnstile", "challenges.cloudflare.com", "g-recaptcha", "h-captcha", "recaptcha/", "hcaptcha.com"];
|
|
1703
|
+
var REFUSAL_STATUSES = /* @__PURE__ */ new Set([403, 429, 503]);
|
|
1704
|
+
var TEXT_CHALLENGE_MARKERS = [
|
|
1705
|
+
"verify you are human",
|
|
1706
|
+
"verifying you are human",
|
|
1707
|
+
"checking your browser",
|
|
1708
|
+
"just a moment...",
|
|
1709
|
+
"unusual traffic from your computer",
|
|
1710
|
+
"are you a robot",
|
|
1711
|
+
"please enable javascript and cookies to continue",
|
|
1712
|
+
"complete the security check",
|
|
1713
|
+
"captcha"
|
|
1714
|
+
];
|
|
1715
|
+
function detectChallengeInBody(status, contentType, body) {
|
|
1716
|
+
const html = /html/i.test(contentType ?? "") || /^\s*<(!doctype|html)/i.test(body);
|
|
1717
|
+
if (!html && status >= 200 && status < 300) return void 0;
|
|
1718
|
+
const lower = body.toLowerCase();
|
|
1719
|
+
if (html) {
|
|
1720
|
+
for (const m of HTML_STRONG_MARKERS) if (lower.includes(m)) return m;
|
|
1721
|
+
const visible = lower.replace(/<script[\s\S]*?<\/script>|<style[\s\S]*?<\/style>|<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
|
|
1722
|
+
if (REFUSAL_STATUSES.has(status) || visible.length < 3e3) {
|
|
1723
|
+
for (const m of HTML_WIDGET_MARKERS) if (lower.includes(m)) return m;
|
|
1724
|
+
}
|
|
1725
|
+
}
|
|
1726
|
+
if (body.length < 4e3) {
|
|
1727
|
+
for (const m of TEXT_CHALLENGE_MARKERS) if (lower.includes(m)) return m;
|
|
1728
|
+
}
|
|
1729
|
+
return void 0;
|
|
1730
|
+
}
|
|
1731
|
+
function fetchScript(url, method, headers, maxChars) {
|
|
1732
|
+
return `
|
|
1733
|
+
const url = ${JSON.stringify(url)};
|
|
1734
|
+
try {
|
|
1735
|
+
const r = await fetch(url, { method: ${JSON.stringify(method)}, headers: ${JSON.stringify(headers)}, credentials: "include", redirect: "follow", mode: "same-origin", cache: "no-store" });
|
|
1736
|
+
const headers = {};
|
|
1737
|
+
r.headers.forEach((v, k) => { headers[k] = v; });
|
|
1738
|
+
// A demanded verification is reported from the headers alone: the body is not read.
|
|
1739
|
+
const flagged = /challenge/i.test(headers["cf-mitigated"] || "") || /^(captcha|challenge)$/i.test(headers["x-amzn-waf-action"] || "");
|
|
1740
|
+
if (flagged || ${JSON.stringify(method)} === "HEAD") {
|
|
1741
|
+
if (r.body) { try { await r.body.cancel(); } catch (e) {} }
|
|
1742
|
+
return { ok: true, status: r.status, url: r.url, headers, body: "", tooLarge: false };
|
|
1743
|
+
}
|
|
1744
|
+
if (!r.body) {
|
|
1745
|
+
const whole = await r.text();
|
|
1746
|
+
const big = whole.length > ${maxChars};
|
|
1747
|
+
return { ok: true, status: r.status, url: r.url, headers, body: big ? "" : whole, head: big ? whole.slice(0, 4000) : undefined, tooLarge: big };
|
|
1748
|
+
}
|
|
1749
|
+
// Only a bounded prefix is read: a large body is cut off, not downloaded.
|
|
1750
|
+
const reader = r.body.getReader();
|
|
1751
|
+
const decoder = new TextDecoder();
|
|
1752
|
+
let text = "";
|
|
1753
|
+
let tooLarge = false;
|
|
1754
|
+
for (;;) {
|
|
1755
|
+
const { done, value } = await reader.read();
|
|
1756
|
+
if (done) break;
|
|
1757
|
+
text += decoder.decode(value, { stream: true });
|
|
1758
|
+
if (text.length > ${maxChars}) {
|
|
1759
|
+
tooLarge = true;
|
|
1760
|
+
try { await reader.cancel(); } catch (e) {}
|
|
1761
|
+
break;
|
|
1762
|
+
}
|
|
1763
|
+
}
|
|
1764
|
+
return { ok: true, status: r.status, url: r.url, headers, body: tooLarge ? "" : text, head: tooLarge ? text.slice(0, 4000) : undefined, tooLarge };
|
|
1765
|
+
} catch (e) {
|
|
1766
|
+
return { ok: false, error: String((e && e.message) || e) };
|
|
1767
|
+
}
|
|
1768
|
+
`;
|
|
1769
|
+
}
|
|
1770
|
+
function challengeInHeaders(headers) {
|
|
1771
|
+
if (!headers) return void 0;
|
|
1772
|
+
const h = (name) => headers[name] ?? headers[name.toLowerCase()];
|
|
1773
|
+
if (/challenge/i.test(h("cf-mitigated") ?? "")) return "cf-mitigated: challenge";
|
|
1774
|
+
const waf = h("x-amzn-waf-action");
|
|
1775
|
+
if (waf && /^(captcha|challenge)$/i.test(waf)) return `x-amzn-waf-action: ${waf.toLowerCase()}`;
|
|
1776
|
+
return void 0;
|
|
1777
|
+
}
|
|
1778
|
+
var systemClock2 = {
|
|
1779
|
+
now: () => Date.now(),
|
|
1780
|
+
sleep: (ms, signal) => new Promise((resolve, reject) => {
|
|
1781
|
+
if (signal?.aborted) return reject(signal.reason);
|
|
1782
|
+
const t = setTimeout(() => {
|
|
1783
|
+
signal?.removeEventListener("abort", onAbort);
|
|
1784
|
+
resolve();
|
|
1785
|
+
}, ms);
|
|
1786
|
+
const onAbort = () => {
|
|
1787
|
+
clearTimeout(t);
|
|
1788
|
+
reject(signal.reason);
|
|
1789
|
+
};
|
|
1790
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1791
|
+
})
|
|
1792
|
+
};
|
|
1793
|
+
var originOf = (url) => {
|
|
1794
|
+
try {
|
|
1795
|
+
const u = new URL(url);
|
|
1796
|
+
return u.protocol === "http:" || u.protocol === "https:" ? u.origin : void 0;
|
|
1797
|
+
} catch {
|
|
1798
|
+
return void 0;
|
|
1799
|
+
}
|
|
1800
|
+
};
|
|
1801
|
+
function sameDocument(a, b) {
|
|
1802
|
+
const norm = (u) => {
|
|
1803
|
+
try {
|
|
1804
|
+
const x = new URL(u);
|
|
1805
|
+
x.hash = "";
|
|
1806
|
+
return x.href.replace(/\/$/, "");
|
|
1807
|
+
} catch {
|
|
1808
|
+
return u;
|
|
1809
|
+
}
|
|
1810
|
+
};
|
|
1811
|
+
return norm(a) === norm(b);
|
|
1812
|
+
}
|
|
1813
|
+
function createBrowserTransport(options) {
|
|
1814
|
+
const { client, profile, instance, proxy } = options;
|
|
1815
|
+
const tools = { ...profile.tools, ...options.tools };
|
|
1816
|
+
const clock = options.pace?.clock ?? systemClock2;
|
|
1817
|
+
const random = options.pace?.random ?? Math.random;
|
|
1818
|
+
const minMs = Math.max(0, options.pace?.minMs ?? 2e3);
|
|
1819
|
+
const maxMs = Math.max(minMs, options.pace?.maxMs ?? 6e3);
|
|
1820
|
+
const pollMin = Math.max(1, options.pace?.pollMinMs ?? 500);
|
|
1821
|
+
const pollMax = Math.max(pollMin, options.pace?.pollMaxMs ?? 1500);
|
|
1822
|
+
const maxPages = options.maxPages ?? 100;
|
|
1823
|
+
const navTimeout = options.navigationTimeoutMs ?? 6e4;
|
|
1824
|
+
const evalTimeout = options.evaluateTimeoutMs ?? 3e4;
|
|
1825
|
+
const cleanupTimeout = options.cleanupTimeoutMs ?? 5e3;
|
|
1826
|
+
const lateGrace = options.lateCreateGraceMs ?? 3e3;
|
|
1827
|
+
const maxBodyChars = options.maxBodyChars ?? 5e6;
|
|
1828
|
+
const selecting = profile.addressing === "selected";
|
|
1829
|
+
const tabs = /* @__PURE__ */ new Map();
|
|
1830
|
+
const pending = /* @__PURE__ */ new Set();
|
|
1831
|
+
const creating = /* @__PURE__ */ new Set();
|
|
1832
|
+
let used = 0;
|
|
1833
|
+
let seq = 0;
|
|
1834
|
+
let lastActionAt;
|
|
1835
|
+
let expectedCount;
|
|
1836
|
+
let internalOpen = false;
|
|
1837
|
+
let paceChain = Promise.resolve();
|
|
1838
|
+
let lockTail = Promise.resolve();
|
|
1839
|
+
function acquire(deadlineMs) {
|
|
1840
|
+
let release;
|
|
1841
|
+
const mine = new Promise((resolve) => {
|
|
1842
|
+
release = resolve;
|
|
1843
|
+
});
|
|
1844
|
+
const before = lockTail;
|
|
1845
|
+
lockTail = before.then(() => mine);
|
|
1846
|
+
if (deadlineMs === void 0) return before.then(() => ({ release, held: true }));
|
|
1847
|
+
return new Promise((resolve) => {
|
|
1848
|
+
let late = false;
|
|
1849
|
+
const timer = setTimeout(() => {
|
|
1850
|
+
late = true;
|
|
1851
|
+
release();
|
|
1852
|
+
resolve({ release: () => void 0, held: false });
|
|
1853
|
+
}, deadlineMs);
|
|
1854
|
+
void before.then(() => {
|
|
1855
|
+
clearTimeout(timer);
|
|
1856
|
+
if (!late) resolve({ release, held: true });
|
|
1857
|
+
});
|
|
1858
|
+
});
|
|
1859
|
+
}
|
|
1860
|
+
async function locked(fn) {
|
|
1861
|
+
const { release } = await acquire();
|
|
1862
|
+
try {
|
|
1863
|
+
return await fn();
|
|
1864
|
+
} finally {
|
|
1865
|
+
release();
|
|
1866
|
+
}
|
|
1867
|
+
}
|
|
1868
|
+
async function lockedCleanup(fn) {
|
|
1869
|
+
const { release, held } = await acquire(cleanupTimeout);
|
|
1870
|
+
try {
|
|
1871
|
+
return await fn(held);
|
|
1872
|
+
} finally {
|
|
1873
|
+
release();
|
|
1874
|
+
}
|
|
1875
|
+
}
|
|
1876
|
+
const leftOpenIds = /* @__PURE__ */ new Set();
|
|
1877
|
+
function pause(signal) {
|
|
1878
|
+
const turn = paceChain.then(async () => {
|
|
1879
|
+
if (lastActionAt !== void 0) {
|
|
1880
|
+
const target = minMs + random() * (maxMs - minMs);
|
|
1881
|
+
const wait = Math.round(lastActionAt + target - clock.now());
|
|
1882
|
+
if (wait > 0) await clock.sleep(wait, signal ?? options.signal);
|
|
1883
|
+
}
|
|
1884
|
+
lastActionAt = clock.now();
|
|
1885
|
+
});
|
|
1886
|
+
paceChain = turn.catch(() => void 0);
|
|
1887
|
+
return turn;
|
|
1888
|
+
}
|
|
1889
|
+
function fail(e, what) {
|
|
1890
|
+
if (e instanceof TransportError) throw e;
|
|
1891
|
+
if (e instanceof McpError) {
|
|
1892
|
+
const cause = e.kind === "http" && (e.status === 401 || e.status === 403) ? "blocked" : "network";
|
|
1893
|
+
throw new TransportError(cause, `browser ${what}: ${e.message}`, { origin: e, ...e.status ? { status: e.status } : {} });
|
|
1894
|
+
}
|
|
1895
|
+
throw new TransportError("network", `browser ${what}: ${client.scrub(e instanceof Error ? e.message : String(e))}`);
|
|
1896
|
+
}
|
|
1897
|
+
async function call(tool, args, o) {
|
|
1898
|
+
const opts = { timeoutMs: o.timeoutMs, signal: o.detached ? void 0 : o.signal ?? options.signal, detached: o.detached, scrub: false };
|
|
1899
|
+
let result;
|
|
1900
|
+
try {
|
|
1901
|
+
result = proxy ? await client.callTool(proxy.tool, { alias: proxy.alias, toolName: tool, args }, opts) : await client.callTool(tool, args, opts);
|
|
1902
|
+
} catch (e) {
|
|
1903
|
+
return fail(e, tool);
|
|
1904
|
+
}
|
|
1905
|
+
if (proxy) result = unwrapProxy(result);
|
|
1906
|
+
if (result.isError) {
|
|
1907
|
+
const msg = textOf(client.scrubResult(result)).replace(/\s+/g, " ").trim().slice(0, 300) || "the tool reported an error";
|
|
1908
|
+
throw new TransportError("network", `browser ${tool}: ${msg}`);
|
|
1909
|
+
}
|
|
1910
|
+
return result;
|
|
1911
|
+
}
|
|
1912
|
+
function unwrapProxy(result) {
|
|
1913
|
+
if (result.isError) return result;
|
|
1914
|
+
const text = textOf(result);
|
|
1915
|
+
if (!text.startsWith("{")) return result;
|
|
1916
|
+
const parsed = tryJson(text);
|
|
1917
|
+
if (parsed.ok && isRecord(parsed.value) && Array.isArray(parsed.value.content)) return parsed.value;
|
|
1918
|
+
return result;
|
|
1919
|
+
}
|
|
1920
|
+
function known(page) {
|
|
1921
|
+
const entry = tabs.get(page.id);
|
|
1922
|
+
if (!entry) throw new TransportError("network", `browser page ${page.id} was not opened by this transport (or is already closed)`);
|
|
1923
|
+
return entry;
|
|
1924
|
+
}
|
|
1925
|
+
const cleanup = { timeoutMs: cleanupTimeout, detached: true };
|
|
1926
|
+
async function listTabs(o) {
|
|
1927
|
+
if (!tools.listTabs || !profile.args.listTabs || !profile.tabs) return void 0;
|
|
1928
|
+
try {
|
|
1929
|
+
return profile.tabs(await call(tools.listTabs, profile.args.listTabs(instance), o));
|
|
1930
|
+
} catch {
|
|
1931
|
+
return void 0;
|
|
1932
|
+
}
|
|
1933
|
+
}
|
|
1934
|
+
const lostOwnership = (why) => new TransportError("blocked", `${why}: ownership of the page cannot be re-established (the chrome-devtools profile needs a browser session that no other client drives); nothing was done`);
|
|
1935
|
+
async function relist(o) {
|
|
1936
|
+
const listed = await listTabs(o);
|
|
1937
|
+
if (!listed) throw new TransportError("network", `browser ${tools.listTabs ?? "list"}: cannot list the pages, so ownership cannot be checked`);
|
|
1938
|
+
return listed;
|
|
1939
|
+
}
|
|
1940
|
+
function shiftAfter(index) {
|
|
1941
|
+
for (const e of tabs.values()) {
|
|
1942
|
+
const n = Number(e.tab);
|
|
1943
|
+
if (n > index) e.tab = String(n - 1);
|
|
1944
|
+
}
|
|
1945
|
+
}
|
|
1946
|
+
async function establish(entry, o) {
|
|
1947
|
+
let listed = await relist(o);
|
|
1948
|
+
if (expectedCount !== void 0 && listed.length !== expectedCount && pending.size > 0) {
|
|
1949
|
+
await sweepMarked();
|
|
1950
|
+
listed = await relist(o);
|
|
1951
|
+
}
|
|
1952
|
+
if (expectedCount === void 0 || listed.length !== expectedCount) throw lostOwnership("the set of pages changed");
|
|
1953
|
+
const mine = listed.find((t) => t.id === entry.tab);
|
|
1954
|
+
if (!mine) throw lostOwnership("the page is gone");
|
|
1955
|
+
if (entry.url === entry.marker && mine.url !== entry.marker) throw lostOwnership("another page is at the index of this one");
|
|
1956
|
+
return { mine, moved: !sameDocument(mine.url, entry.url) };
|
|
1957
|
+
}
|
|
1958
|
+
async function ensureOurs(entry, signal) {
|
|
1959
|
+
if (!selecting) return false;
|
|
1960
|
+
const o = { timeoutMs: navTimeout, signal };
|
|
1961
|
+
const { mine, moved } = await establish(entry, o);
|
|
1962
|
+
if (moved) entry.url = mine.url;
|
|
1963
|
+
if (mine.selected) return moved;
|
|
1964
|
+
if (!tools.selectTab || !profile.args.selectTab) throw lostOwnership("the page is not selected");
|
|
1965
|
+
await call(tools.selectTab, profile.args.selectTab(mine.id, instance), o);
|
|
1966
|
+
const after = await relist(o);
|
|
1967
|
+
const now = after.find((t) => t.selected);
|
|
1968
|
+
if (after.length !== expectedCount || !now || now.id !== mine.id) throw lostOwnership("the selection changed");
|
|
1969
|
+
return moved;
|
|
1970
|
+
}
|
|
1971
|
+
async function syncUrl(entry, signal) {
|
|
1972
|
+
const { mine } = await establish(entry, { timeoutMs: navTimeout, signal });
|
|
1973
|
+
entry.url = mine.url;
|
|
1974
|
+
return mine.url;
|
|
1975
|
+
}
|
|
1976
|
+
function asBody(script) {
|
|
1977
|
+
try {
|
|
1978
|
+
const AsyncFunction = Object.getPrototypeOf(async function() {
|
|
1979
|
+
}).constructor;
|
|
1980
|
+
new AsyncFunction(`return (${script}
|
|
1981
|
+
)`);
|
|
1982
|
+
return `return (${script}
|
|
1983
|
+
)`;
|
|
1984
|
+
} catch {
|
|
1985
|
+
return script;
|
|
1986
|
+
}
|
|
1987
|
+
}
|
|
1988
|
+
function wrap(script) {
|
|
1989
|
+
const body = asBody(script);
|
|
1990
|
+
return profile.script === "expression" ? `(async () => {
|
|
1991
|
+
${body}
|
|
1992
|
+
})()` : `async () => {
|
|
1993
|
+
${body}
|
|
1994
|
+
}`;
|
|
1995
|
+
}
|
|
1996
|
+
async function evalRaw(entry, script, o) {
|
|
1997
|
+
const result = await call(tools.evaluate, profile.args.evaluate(entry.tab, wrap(script), instance), { timeoutMs: o.timeoutMs ?? evalTimeout, signal: o.signal });
|
|
1998
|
+
let value;
|
|
1999
|
+
try {
|
|
2000
|
+
value = profile.value(result);
|
|
2001
|
+
} catch (e) {
|
|
2002
|
+
throw e instanceof TransportError ? new TransportError(e.cause, client.scrub(e.message), { status: e.status, url: e.url }) : e;
|
|
2003
|
+
}
|
|
2004
|
+
return client.scrubValue(value, !o.ownKeys);
|
|
2005
|
+
}
|
|
2006
|
+
function challengeError(entry, r) {
|
|
2007
|
+
return new TransportError("challenge", `verification page detected on ${client.scrub(entry.url)} (${r.marker ?? "marker"}); not bypassed`, { url: client.scrub(entry.url) });
|
|
2008
|
+
}
|
|
2009
|
+
async function run(entry, script, o = {}) {
|
|
2010
|
+
const moved = await ensureOurs(entry, o.signal);
|
|
2011
|
+
if (moved && !o.check) {
|
|
2012
|
+
used++;
|
|
2013
|
+
const r = await evalRaw(entry, CHALLENGE_SCRIPT, o);
|
|
2014
|
+
if (r?.challenge) throw challengeError(entry, r);
|
|
2015
|
+
}
|
|
2016
|
+
return evalRaw(entry, script, o);
|
|
2017
|
+
}
|
|
2018
|
+
function takeBudget() {
|
|
2019
|
+
if (used >= maxPages) throw new TransportError("blocked", `page cap reached (${maxPages} pages in this run)`);
|
|
2020
|
+
used++;
|
|
2021
|
+
}
|
|
2022
|
+
async function navigate(entry, url, o = {}) {
|
|
2023
|
+
if (!o.free && !o.reserved) takeBudget();
|
|
2024
|
+
await ensureOurs(entry, o.signal);
|
|
2025
|
+
await call(tools.navigate, profile.args.navigate(entry.tab, url, instance), { timeoutMs: navTimeout, signal: o.signal });
|
|
2026
|
+
entry.url = url;
|
|
2027
|
+
if (selecting) await syncUrl(entry, o.signal);
|
|
2028
|
+
}
|
|
2029
|
+
async function inspect(entry, expected, o = {}) {
|
|
2030
|
+
const r = await run(entry, CHALLENGE_SCRIPT, { ...o, check: true });
|
|
2031
|
+
let href = typeof r?.url === "string" && r.url ? r.url : entry.url;
|
|
2032
|
+
if (selecting) href = await syncUrl(entry, o.signal);
|
|
2033
|
+
else entry.url = href;
|
|
2034
|
+
if (!sameDocument(href, expected)) used++;
|
|
2035
|
+
if (r?.challenge) throw challengeError(entry, r);
|
|
2036
|
+
}
|
|
2037
|
+
async function closeTab(id) {
|
|
2038
|
+
const entry = tabs.get(id);
|
|
2039
|
+
if (!entry) return;
|
|
2040
|
+
if (!selecting) {
|
|
2041
|
+
await call(tools.closeTab, profile.args.closeTab(entry.tab, instance), cleanup);
|
|
2042
|
+
tabs.delete(id);
|
|
2043
|
+
return;
|
|
2044
|
+
}
|
|
2045
|
+
let index;
|
|
2046
|
+
try {
|
|
2047
|
+
index = (await establish(entry, cleanup)).mine.id;
|
|
2048
|
+
} catch (e) {
|
|
2049
|
+
tabs.delete(id);
|
|
2050
|
+
throw e;
|
|
2051
|
+
}
|
|
2052
|
+
await call(tools.closeTab, profile.args.closeTab(index, instance), cleanup);
|
|
2053
|
+
tabs.delete(id);
|
|
2054
|
+
if (expectedCount !== void 0) expectedCount--;
|
|
2055
|
+
shiftAfter(Number(index));
|
|
2056
|
+
}
|
|
2057
|
+
async function sweepMarked() {
|
|
2058
|
+
if (pending.size === 0) return;
|
|
2059
|
+
const listed = await listTabs(cleanup);
|
|
2060
|
+
if (!listed) return;
|
|
2061
|
+
const tracked = new Set([...tabs.values()].map((t) => t.tab));
|
|
2062
|
+
const orphans = listed.filter((t) => pending.has(t.url) && !tracked.has(t.id));
|
|
2063
|
+
orphans.sort((a, b) => Number(b.id) - Number(a.id));
|
|
2064
|
+
for (const t of orphans) {
|
|
2065
|
+
try {
|
|
2066
|
+
await call(tools.closeTab, profile.args.closeTab(t.id, instance), cleanup);
|
|
2067
|
+
} catch {
|
|
2068
|
+
continue;
|
|
2069
|
+
}
|
|
2070
|
+
pending.delete(t.url);
|
|
2071
|
+
if (selecting) shiftAfter(Number(t.id));
|
|
2072
|
+
}
|
|
2073
|
+
}
|
|
2074
|
+
async function baseline() {
|
|
2075
|
+
const o = { timeoutMs: navTimeout };
|
|
2076
|
+
let listed = await relist(o);
|
|
2077
|
+
if (pending.size > 0) {
|
|
2078
|
+
await sweepMarked();
|
|
2079
|
+
listed = await relist(o);
|
|
2080
|
+
}
|
|
2081
|
+
if (tabs.size === 0 || expectedCount === void 0) {
|
|
2082
|
+
expectedCount = listed.length;
|
|
2083
|
+
return;
|
|
2084
|
+
}
|
|
2085
|
+
if (listed.length !== expectedCount) throw lostOwnership("the set of pages changed");
|
|
2086
|
+
}
|
|
2087
|
+
const inner = {
|
|
2088
|
+
async open(url) {
|
|
2089
|
+
const uncounted = internalOpen;
|
|
2090
|
+
internalOpen = false;
|
|
2091
|
+
const blank = url === "about:blank";
|
|
2092
|
+
if (!blank && !originOf(url)) throw new TransportError("blocked", `cannot open ${url}: only http and https pages`);
|
|
2093
|
+
if (!uncounted) takeBudget();
|
|
2094
|
+
try {
|
|
2095
|
+
const marker = `data:text/html,collect-${globalThis.crypto.randomUUID()}`;
|
|
2096
|
+
if (selecting) await baseline();
|
|
2097
|
+
pending.add(marker);
|
|
2098
|
+
const create = call(tools.newTab, profile.args.newTab(marker, instance), { timeoutMs: navTimeout });
|
|
2099
|
+
creating.add(create);
|
|
2100
|
+
void create.then(
|
|
2101
|
+
() => creating.delete(create),
|
|
2102
|
+
() => creating.delete(create)
|
|
2103
|
+
);
|
|
2104
|
+
let tab;
|
|
2105
|
+
try {
|
|
2106
|
+
const created = await create;
|
|
2107
|
+
if (selecting) {
|
|
2108
|
+
const listed = await relist({ timeoutMs: navTimeout });
|
|
2109
|
+
const found = listed.filter((t) => t.url === marker);
|
|
2110
|
+
if (found.length !== 1) throw lostOwnership("the new page cannot be identified");
|
|
2111
|
+
if (listed.length !== (expectedCount ?? -1) + 1) {
|
|
2112
|
+
await call(tools.closeTab, profile.args.closeTab(found[0].id, instance), cleanup).catch(() => void 0);
|
|
2113
|
+
pending.delete(marker);
|
|
2114
|
+
throw lostOwnership("another page appeared while opening");
|
|
2115
|
+
}
|
|
2116
|
+
tab = found[0].id;
|
|
2117
|
+
expectedCount = listed.length;
|
|
2118
|
+
} else {
|
|
2119
|
+
let id2 = profile.tabId(created);
|
|
2120
|
+
if (!id2) id2 = profile.tabs?.(created)?.find((t) => t.url === marker)?.id;
|
|
2121
|
+
if (!id2) id2 = (await listTabs({ timeoutMs: navTimeout }))?.find((t) => t.url === marker)?.id;
|
|
2122
|
+
if (!id2) throw new TransportError("network", `browser ${tools.newTab}: the result carries no tab id`);
|
|
2123
|
+
tab = id2;
|
|
2124
|
+
}
|
|
2125
|
+
} catch (e) {
|
|
2126
|
+
await sweepMarked().catch(() => void 0);
|
|
2127
|
+
throw e;
|
|
2128
|
+
}
|
|
2129
|
+
pending.delete(marker);
|
|
2130
|
+
const id = `${tab}#${++seq}`;
|
|
2131
|
+
const entry = { tab, url: marker, marker };
|
|
2132
|
+
tabs.set(id, entry);
|
|
2133
|
+
const page = { id, url };
|
|
2134
|
+
try {
|
|
2135
|
+
if (profile.verifyRouting) {
|
|
2136
|
+
const here = await evalRaw(entry, "return location.href", {});
|
|
2137
|
+
if (here !== marker) {
|
|
2138
|
+
throw new TransportError("blocked", "the server did not route a call to the page it was named for: either page-id routing is off, or this server names pages by index (then use --browser-profile chrome-devtools-index); refusing to go on, nothing was done");
|
|
2139
|
+
}
|
|
2140
|
+
}
|
|
2141
|
+
if (!blank) {
|
|
2142
|
+
await navigate(entry, url, { reserved: true });
|
|
2143
|
+
await inspect(entry, url);
|
|
2144
|
+
}
|
|
2145
|
+
return page;
|
|
2146
|
+
} catch (e) {
|
|
2147
|
+
await closeTab(id).catch(() => void 0);
|
|
2148
|
+
throw e;
|
|
2149
|
+
}
|
|
2150
|
+
} catch (e) {
|
|
2151
|
+
if (!uncounted) used = Math.max(0, used - 1);
|
|
2152
|
+
throw e;
|
|
2153
|
+
}
|
|
2154
|
+
},
|
|
2155
|
+
async evaluate(page, script) {
|
|
2156
|
+
const entry = known(page);
|
|
2157
|
+
const before = entry.url;
|
|
2158
|
+
const value = await run(entry, script);
|
|
2159
|
+
await inspect(entry, before);
|
|
2160
|
+
return value;
|
|
2161
|
+
},
|
|
2162
|
+
async fetchInPage(page, request) {
|
|
2163
|
+
const entry = known(page);
|
|
2164
|
+
const method = (request.method ?? "GET").toUpperCase();
|
|
2165
|
+
if (method !== "GET" && method !== "HEAD") {
|
|
2166
|
+
throw new TransportError("blocked", `the browser transport is read-only: ${method} is not allowed`, { url: client.scrub(request.url) });
|
|
2167
|
+
}
|
|
2168
|
+
const origin = originOf(request.url);
|
|
2169
|
+
if (!origin) throw new TransportError("blocked", `cannot fetch ${request.url}: only http and https URLs`, { url: client.scrub(request.url) });
|
|
2170
|
+
if (originOf(entry.url) !== origin) {
|
|
2171
|
+
await navigate(entry, `${origin}/`, { signal: request.signal });
|
|
2172
|
+
await inspect(entry, `${origin}/`, { signal: request.signal });
|
|
2173
|
+
}
|
|
2174
|
+
const headers = Object.fromEntries(Object.entries(request.headers ?? {}).filter(([k]) => k.toLowerCase() !== "cookie"));
|
|
2175
|
+
const beforeFetch = entry.url;
|
|
2176
|
+
const r = await run(entry, fetchScript(request.url, method, headers, maxBodyChars), { signal: request.signal, ownKeys: true });
|
|
2177
|
+
await inspect(entry, beforeFetch, { signal: request.signal });
|
|
2178
|
+
if (!r || !r.ok) {
|
|
2179
|
+
throw new TransportError("blocked", `in-page fetch of ${request.url} failed (cross-origin or CORS): ${r?.error ?? "no detail"}`, { url: client.scrub(request.url) });
|
|
2180
|
+
}
|
|
2181
|
+
const status = r.status ?? 0;
|
|
2182
|
+
const byHeader = challengeInHeaders(r.headers);
|
|
2183
|
+
if (byHeader) throw new TransportError("challenge", `verification demanded by the response of ${request.url} (${byHeader}); not bypassed`, { url: client.scrub(request.url), status });
|
|
2184
|
+
if (r.tooLarge) {
|
|
2185
|
+
const inHead = detectChallengeInBody(status, r.headers?.["content-type"], r.head ?? "");
|
|
2186
|
+
if (inHead) throw new TransportError("challenge", `verification page in the response of ${request.url} (${inHead}); not bypassed`, { url: client.scrub(request.url), status });
|
|
2187
|
+
throw new TransportError("empty", `response of ${request.url} is larger than ${maxBodyChars} characters`, { url: client.scrub(request.url) });
|
|
2188
|
+
}
|
|
2189
|
+
const body = r.body ?? "";
|
|
2190
|
+
const marker = detectChallengeInBody(status, r.headers?.["content-type"], body);
|
|
2191
|
+
if (marker) throw new TransportError("challenge", `verification page in the response of ${request.url} (${marker}); not bypassed`, { url: client.scrub(request.url), status });
|
|
2192
|
+
return { status, headers: r.headers ?? {}, body: new TextEncoder().encode(body), url: client.scrub(r.url ?? request.url) };
|
|
2193
|
+
},
|
|
2194
|
+
async close(page) {
|
|
2195
|
+
try {
|
|
2196
|
+
await closeTab(page.id);
|
|
2197
|
+
} catch (e) {
|
|
2198
|
+
fail(e, tools.closeTab);
|
|
2199
|
+
}
|
|
2200
|
+
},
|
|
2201
|
+
async closeAll() {
|
|
2202
|
+
for (const id of [...tabs.keys()]) await closeTab(id).catch(() => void 0);
|
|
2203
|
+
if (creating.size > 0) await Promise.race([Promise.allSettled([...creating]), clock.sleep(cleanupTimeout)]).catch(() => void 0);
|
|
2204
|
+
await sweepMarked().catch(() => void 0);
|
|
2205
|
+
if (pending.size > 0 && await listTabs(cleanup) !== void 0) {
|
|
2206
|
+
await clock.sleep(lateGrace).catch(() => void 0);
|
|
2207
|
+
await sweepMarked().catch(() => void 0);
|
|
2208
|
+
}
|
|
2209
|
+
},
|
|
2210
|
+
async probe() {
|
|
2211
|
+
internalOpen = true;
|
|
2212
|
+
const page = await inner.open("about:blank");
|
|
2213
|
+
let value;
|
|
2214
|
+
let failure;
|
|
2215
|
+
try {
|
|
2216
|
+
const entry = known(page);
|
|
2217
|
+
await navigate(entry, "data:text/html,collect-probe", { free: true });
|
|
2218
|
+
const probed = await run(entry, "return [1+1, location.href]");
|
|
2219
|
+
if (!Array.isArray(probed) || probed[1] !== "data:text/html,collect-probe") {
|
|
2220
|
+
throw new TransportError("blocked", "the probe script did not run on the probe tab (is page-id routing off?)");
|
|
2221
|
+
}
|
|
2222
|
+
value = probed[0];
|
|
2223
|
+
} catch (e) {
|
|
2224
|
+
failure = e;
|
|
2225
|
+
}
|
|
2226
|
+
let closeFailure;
|
|
2227
|
+
try {
|
|
2228
|
+
await closeTab(page.id);
|
|
2229
|
+
} catch (e) {
|
|
2230
|
+
closeFailure = e;
|
|
2231
|
+
}
|
|
2232
|
+
if (failure) throw failure;
|
|
2233
|
+
if (closeFailure) {
|
|
2234
|
+
const why = closeFailure instanceof Error ? closeFailure.message : String(closeFailure);
|
|
2235
|
+
throw new TransportError("network", `the probe tab could not be closed: ${client.scrub(why)}`, { origin: closeFailure });
|
|
2236
|
+
}
|
|
2237
|
+
return value;
|
|
2238
|
+
}
|
|
2239
|
+
};
|
|
2240
|
+
const api = {
|
|
2241
|
+
// Pacing first, outside the lock: a wait never holds the ownership lock.
|
|
2242
|
+
open: async (url) => {
|
|
2243
|
+
await pause();
|
|
2244
|
+
return locked(() => inner.open(url));
|
|
2245
|
+
},
|
|
2246
|
+
evaluate: async (page, script) => {
|
|
2247
|
+
await pause();
|
|
2248
|
+
return locked(() => inner.evaluate(page, script));
|
|
2249
|
+
},
|
|
2250
|
+
fetchInPage: async (page, request) => {
|
|
2251
|
+
await pause(request.signal);
|
|
2252
|
+
return locked(() => inner.fetchInPage(page, request));
|
|
2253
|
+
},
|
|
2254
|
+
async scroll(page, opts = {}) {
|
|
2255
|
+
const entry = known(page);
|
|
2256
|
+
const steps = Math.max(1, opts.steps ?? 1);
|
|
2257
|
+
const pixels = opts.pixels ?? 0;
|
|
2258
|
+
for (let i = 0; i < steps; i++) {
|
|
2259
|
+
await pause();
|
|
2260
|
+
await locked(async () => {
|
|
2261
|
+
const before = entry.url;
|
|
2262
|
+
await run(entry, `window.scrollBy(0, ${pixels > 0 ? pixels : "window.innerHeight"}); return true;`);
|
|
2263
|
+
await inspect(entry, before);
|
|
2264
|
+
});
|
|
2265
|
+
}
|
|
2266
|
+
},
|
|
2267
|
+
async waitFor(page, opts) {
|
|
2268
|
+
const entry = known(page);
|
|
2269
|
+
if (!opts.selector && !opts.predicate) throw new TransportError("network", "waitFor needs a selector or a predicate");
|
|
2270
|
+
const timeoutMs = opts.timeoutMs ?? 15e3;
|
|
2271
|
+
const check = opts.selector ? `return document.querySelector(${JSON.stringify(opts.selector)}) !== null;` : `return Boolean(await (async () => {
|
|
2272
|
+
${opts.predicate}
|
|
2273
|
+
})());`;
|
|
2274
|
+
const what = opts.selector ?? "the predicate";
|
|
2275
|
+
await pause();
|
|
2276
|
+
const startedAt = clock.now();
|
|
2277
|
+
const left = () => timeoutMs - (clock.now() - startedAt);
|
|
2278
|
+
for (; ; ) {
|
|
2279
|
+
const found = await locked(async () => {
|
|
2280
|
+
const before = entry.url;
|
|
2281
|
+
let hit = false;
|
|
2282
|
+
try {
|
|
2283
|
+
hit = await run(entry, check, { timeoutMs: Math.max(1, Math.min(evalTimeout, left())) });
|
|
2284
|
+
} catch (e) {
|
|
2285
|
+
if (left() <= 0) throw new TransportError("empty", `timed out after ${timeoutMs} ms waiting for ${what}`);
|
|
2286
|
+
throw e;
|
|
2287
|
+
}
|
|
2288
|
+
await inspect(entry, before);
|
|
2289
|
+
return hit;
|
|
2290
|
+
});
|
|
2291
|
+
if (found) return;
|
|
2292
|
+
if (left() <= 0) throw new TransportError("empty", `timed out after ${timeoutMs} ms waiting for ${what}`);
|
|
2293
|
+
await clock.sleep(Math.min(left(), Math.round(pollMin + random() * (pollMax - pollMin))), options.signal);
|
|
2294
|
+
}
|
|
2295
|
+
},
|
|
2296
|
+
// Cleanup takes the lock with its own deadline.
|
|
2297
|
+
close: (page) => lockedCleanup(async (held) => {
|
|
2298
|
+
if (selecting && !held) {
|
|
2299
|
+
if (tabs.has(page.id)) leftOpenIds.add(page.id);
|
|
2300
|
+
throw new TransportError("blocked", "the tab was left open: the ownership lock could not be taken in time, and it cannot be closed by index without it");
|
|
2301
|
+
}
|
|
2302
|
+
return inner.close(page);
|
|
2303
|
+
}),
|
|
2304
|
+
closeAll: () => lockedCleanup(async (held) => {
|
|
2305
|
+
if (selecting && !held) {
|
|
2306
|
+
for (const id of tabs.keys()) leftOpenIds.add(id);
|
|
2307
|
+
return;
|
|
2308
|
+
}
|
|
2309
|
+
return inner.closeAll();
|
|
2310
|
+
}),
|
|
2311
|
+
probe: () => locked(() => inner.probe()),
|
|
2312
|
+
openPages: () => [...tabs.entries()].map(([id, e]) => ({ id, url: client.scrub(e.url) })),
|
|
2313
|
+
leftOpen: () => [...leftOpenIds].filter((id) => tabs.has(id)).map((id) => ({ id, url: client.scrub(tabs.get(id).url) })),
|
|
2314
|
+
pagesUsed: () => used,
|
|
2315
|
+
canList: async () => await listTabs(cleanup) !== void 0
|
|
2316
|
+
};
|
|
2317
|
+
return api;
|
|
2318
|
+
}
|
|
2319
|
+
|
|
2320
|
+
export { CHALLENGE_SCRIPT, CHROME_DEVTOOLS_INDEX_PROFILE, CHROME_DEVTOOLS_PROFILE, DEFAULT_PROTOCOL_VERSION, McpError, REDACTED_NOTICE, SseParser, StoreMigrationError, StoreNotFoundError, TAB_TOOLS_PROFILE, browserProfile, challengeInHeaders, createApiTransport, createBrowserTransport, createHttpTransport, createMcpClient, createRedactor, createScrubber, detectChallengeInBody, initStore, openStore, parseRetryAfter, parseSseMessages, requiredTools };
|
|
2321
|
+
//# sourceMappingURL=node.mjs.map
|
|
2322
|
+
//# sourceMappingURL=node.mjs.map
|