@browsa/mcp 0.7.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -3,16 +3,520 @@
3
3
  // src/server.ts
4
4
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
5
5
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
6
- import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
6
+ import {
7
+ CallToolRequestSchema,
8
+ GetPromptRequestSchema,
9
+ ListPromptsRequestSchema,
10
+ ListToolsRequestSchema
11
+ } from "@modelcontextprotocol/sdk/types.js";
12
+
13
+ // src/captcha/catalogue-snapshot.json
14
+ var catalogue_snapshot_default = {
15
+ asOf: "2026-11-21",
16
+ service: "https://captcha.browsa.io",
17
+ types: [
18
+ {
19
+ type: "ImageToTextTask",
20
+ title: "Image text",
21
+ kind: "recognition",
22
+ family: "image_text",
23
+ status: "live",
24
+ required: [],
25
+ oneOf: [
26
+ [
27
+ "body",
28
+ "images"
29
+ ]
30
+ ],
31
+ optional: [
32
+ "module",
33
+ "websiteURL"
34
+ ],
35
+ proxy: "none",
36
+ credits: 4e-3
37
+ },
38
+ {
39
+ type: "ReCaptchaV2Classification",
40
+ title: "reCAPTCHA v2 grid classification",
41
+ kind: "recognition",
42
+ family: "recaptcha_grid",
43
+ status: "live",
44
+ required: [
45
+ "image",
46
+ "question"
47
+ ],
48
+ oneOf: [],
49
+ optional: [
50
+ "size",
51
+ "escalate",
52
+ "websiteURL"
53
+ ],
54
+ proxy: "none",
55
+ credits: 0.01
56
+ },
57
+ {
58
+ type: "AwsWafClassification",
59
+ title: "AWS WAF grid classification",
60
+ kind: "recognition",
61
+ family: "aws_waf",
62
+ status: "live",
63
+ required: [
64
+ "images",
65
+ "question"
66
+ ],
67
+ oneOf: [],
68
+ optional: [
69
+ "websiteURL"
70
+ ],
71
+ proxy: "none",
72
+ credits: 0.01
73
+ },
74
+ {
75
+ type: "VisionEngine",
76
+ title: "Slider gap (vision model)",
77
+ kind: "recognition",
78
+ family: "slider",
79
+ status: "off",
80
+ offReason: "switched off until a measured run passes",
81
+ required: [
82
+ "module",
83
+ "imageBackground"
84
+ ],
85
+ oneOf: [],
86
+ optional: [
87
+ "image"
88
+ ],
89
+ proxy: "none",
90
+ credits: 8e-3
91
+ },
92
+ {
93
+ type: "GeeTestSlide",
94
+ title: "GeeTest slide (v3 and v4)",
95
+ kind: "recognition",
96
+ family: "geetest_slide",
97
+ status: "live",
98
+ required: [
99
+ "version",
100
+ "imageBackground",
101
+ "imageFull",
102
+ "imageSlice",
103
+ "top",
104
+ "bgCssWidth"
105
+ ],
106
+ oneOf: [],
107
+ optional: [
108
+ "cssWidth",
109
+ "shuffled",
110
+ "sliceCssWidth",
111
+ "websiteURL"
112
+ ],
113
+ proxy: "none",
114
+ credits: 8e-3
115
+ },
116
+ {
117
+ type: "AltchaTask",
118
+ title: "ALTCHA proof of work",
119
+ kind: "recognition",
120
+ family: "altcha",
121
+ status: "off",
122
+ offReason: "switched off until a measured run passes",
123
+ required: [
124
+ "challenge"
125
+ ],
126
+ oneOf: [],
127
+ optional: [
128
+ "websiteURL"
129
+ ],
130
+ proxy: "none",
131
+ credits: 4e-3
132
+ },
133
+ {
134
+ type: "RotateTask",
135
+ title: "Rotate the disc",
136
+ kind: "recognition",
137
+ family: "rotate",
138
+ status: "off",
139
+ offReason: "switched off until a measured run passes",
140
+ required: [
141
+ "imageDisc",
142
+ "imageBackground"
143
+ ],
144
+ oneOf: [],
145
+ optional: [
146
+ "discCssWidth",
147
+ "bgCssWidth",
148
+ "websiteURL"
149
+ ],
150
+ proxy: "none",
151
+ credits: 8e-3
152
+ },
153
+ {
154
+ type: "ClickOrderTask",
155
+ title: "Click in order",
156
+ kind: "recognition",
157
+ family: "click_order",
158
+ status: "off",
159
+ offReason: "switched off until a measured run passes",
160
+ required: [
161
+ "image"
162
+ ],
163
+ oneOf: [],
164
+ optional: [
165
+ "references",
166
+ "order",
167
+ "count",
168
+ "websiteURL"
169
+ ],
170
+ proxy: "none",
171
+ credits: 0.01
172
+ },
173
+ {
174
+ type: "TextCaptchaTask",
175
+ title: "Question in words",
176
+ kind: "recognition",
177
+ family: "text_question",
178
+ status: "live",
179
+ required: [
180
+ "comment"
181
+ ],
182
+ oneOf: [],
183
+ optional: [
184
+ "websiteURL"
185
+ ],
186
+ proxy: "none",
187
+ credits: 4e-3
188
+ },
189
+ {
190
+ type: "BoundingBoxTask",
191
+ title: "Box around an object",
192
+ kind: "recognition",
193
+ family: "bounding_box",
194
+ status: "live",
195
+ required: [
196
+ "body",
197
+ "comment"
198
+ ],
199
+ oneOf: [],
200
+ optional: [
201
+ "many",
202
+ "websiteURL"
203
+ ],
204
+ proxy: "none",
205
+ credits: 0.01
206
+ },
207
+ {
208
+ type: "DrawAroundTask",
209
+ title: "Line drawn around an object",
210
+ kind: "recognition",
211
+ family: "draw_around",
212
+ status: "off",
213
+ offReason: "switched off until a measured run passes",
214
+ required: [
215
+ "body",
216
+ "comment"
217
+ ],
218
+ oneOf: [],
219
+ optional: [
220
+ "many",
221
+ "websiteURL"
222
+ ],
223
+ proxy: "none",
224
+ credits: 0.01
225
+ },
226
+ {
227
+ type: "DragDropTask",
228
+ title: "Drag pieces into the picture",
229
+ kind: "recognition",
230
+ family: "drag_drop",
231
+ status: "live",
232
+ required: [
233
+ "body",
234
+ "pieces"
235
+ ],
236
+ oneOf: [],
237
+ optional: [
238
+ "websiteURL"
239
+ ],
240
+ proxy: "none",
241
+ credits: 0.01
242
+ },
243
+ {
244
+ type: "AntiTurnstileTaskProxyLess",
245
+ title: "Cloudflare Turnstile token",
246
+ kind: "token",
247
+ family: "turnstile",
248
+ status: "live",
249
+ required: [
250
+ "websiteURL",
251
+ "websiteKey"
252
+ ],
253
+ oneOf: [],
254
+ optional: [
255
+ "metadata",
256
+ "userAgent"
257
+ ],
258
+ proxy: "none",
259
+ credits: 8e-3
260
+ },
261
+ {
262
+ type: "AntiTurnstileTask",
263
+ title: "Cloudflare Turnstile token (your proxy)",
264
+ kind: "token",
265
+ family: "turnstile",
266
+ status: "live",
267
+ required: [
268
+ "websiteURL",
269
+ "websiteKey",
270
+ "proxy"
271
+ ],
272
+ oneOf: [],
273
+ optional: [
274
+ "metadata",
275
+ "userAgent"
276
+ ],
277
+ proxy: "required",
278
+ credits: 8e-3
279
+ },
280
+ {
281
+ type: "ReCaptchaV3TaskProxyLess",
282
+ title: "reCAPTCHA v3 token",
283
+ kind: "token",
284
+ family: "recaptcha_v3",
285
+ status: "live",
286
+ required: [
287
+ "websiteURL",
288
+ "websiteKey"
289
+ ],
290
+ oneOf: [],
291
+ optional: [
292
+ "pageAction",
293
+ "apiDomain",
294
+ "minScore",
295
+ "enterprisePayload",
296
+ "userAgent"
297
+ ],
298
+ proxy: "none",
299
+ credits: 8e-3
300
+ },
301
+ {
302
+ type: "ReCaptchaV3Task",
303
+ title: "reCAPTCHA v3 token (your proxy)",
304
+ kind: "token",
305
+ family: "recaptcha_v3",
306
+ status: "live",
307
+ required: [
308
+ "websiteURL",
309
+ "websiteKey",
310
+ "proxy"
311
+ ],
312
+ oneOf: [],
313
+ optional: [
314
+ "pageAction",
315
+ "apiDomain",
316
+ "minScore",
317
+ "enterprisePayload",
318
+ "userAgent"
319
+ ],
320
+ proxy: "required",
321
+ credits: 8e-3
322
+ },
323
+ {
324
+ type: "ReCaptchaV3EnterpriseTaskProxyLess",
325
+ title: "reCAPTCHA v3 Enterprise token",
326
+ kind: "token",
327
+ family: "recaptcha_v3_enterprise",
328
+ status: "live",
329
+ required: [
330
+ "websiteURL",
331
+ "websiteKey"
332
+ ],
333
+ oneOf: [],
334
+ optional: [
335
+ "pageAction",
336
+ "apiDomain",
337
+ "minScore",
338
+ "enterprisePayload",
339
+ "userAgent"
340
+ ],
341
+ proxy: "none",
342
+ credits: 0.012
343
+ },
344
+ {
345
+ type: "ReCaptchaV3EnterpriseTask",
346
+ title: "reCAPTCHA v3 Enterprise token (your proxy)",
347
+ kind: "token",
348
+ family: "recaptcha_v3_enterprise",
349
+ status: "live",
350
+ required: [
351
+ "websiteURL",
352
+ "websiteKey",
353
+ "proxy"
354
+ ],
355
+ oneOf: [],
356
+ optional: [
357
+ "pageAction",
358
+ "apiDomain",
359
+ "minScore",
360
+ "enterprisePayload",
361
+ "userAgent"
362
+ ],
363
+ proxy: "required",
364
+ credits: 0.012
365
+ },
366
+ {
367
+ type: "ReCaptchaV2TaskProxyLess",
368
+ title: "reCAPTCHA v2 token",
369
+ kind: "token",
370
+ family: "recaptcha_v2",
371
+ status: "live",
372
+ required: [
373
+ "websiteURL",
374
+ "websiteKey"
375
+ ],
376
+ oneOf: [],
377
+ optional: [
378
+ "isInvisible",
379
+ "apiDomain",
380
+ "enterprisePayload",
381
+ "userAgent"
382
+ ],
383
+ proxy: "none",
384
+ credits: 0.01
385
+ },
386
+ {
387
+ type: "ReCaptchaV2Task",
388
+ title: "reCAPTCHA v2 token (your proxy)",
389
+ kind: "token",
390
+ family: "recaptcha_v2",
391
+ status: "live",
392
+ required: [
393
+ "websiteURL",
394
+ "websiteKey",
395
+ "proxy"
396
+ ],
397
+ oneOf: [],
398
+ optional: [
399
+ "isInvisible",
400
+ "apiDomain",
401
+ "enterprisePayload",
402
+ "userAgent"
403
+ ],
404
+ proxy: "required",
405
+ credits: 0.01
406
+ },
407
+ {
408
+ type: "ReCaptchaV2EnterpriseTaskProxyLess",
409
+ title: "reCAPTCHA v2 Enterprise token",
410
+ kind: "token",
411
+ family: "recaptcha_v2_enterprise",
412
+ status: "live",
413
+ required: [
414
+ "websiteURL",
415
+ "websiteKey"
416
+ ],
417
+ oneOf: [],
418
+ optional: [
419
+ "isInvisible",
420
+ "apiDomain",
421
+ "enterprisePayload",
422
+ "userAgent"
423
+ ],
424
+ proxy: "none",
425
+ credits: 0.012
426
+ },
427
+ {
428
+ type: "ReCaptchaV2EnterpriseTask",
429
+ title: "reCAPTCHA v2 Enterprise token (your proxy)",
430
+ kind: "token",
431
+ family: "recaptcha_v2_enterprise",
432
+ status: "live",
433
+ required: [
434
+ "websiteURL",
435
+ "websiteKey",
436
+ "proxy"
437
+ ],
438
+ oneOf: [],
439
+ optional: [
440
+ "isInvisible",
441
+ "apiDomain",
442
+ "enterprisePayload",
443
+ "userAgent"
444
+ ],
445
+ proxy: "required",
446
+ credits: 0.012
447
+ },
448
+ {
449
+ type: "AntiCloudflareTask",
450
+ title: "Cloudflare full-page check",
451
+ kind: "token",
452
+ family: "cloudflare",
453
+ status: "live",
454
+ required: [
455
+ "websiteURL",
456
+ "proxy"
457
+ ],
458
+ oneOf: [],
459
+ optional: [
460
+ "userAgent"
461
+ ],
462
+ proxy: "required",
463
+ credits: 0.012
464
+ }
465
+ ]
466
+ };
467
+
468
+ // src/captcha/client.ts
469
+ import { BrowsaError } from "browsa";
7
470
 
8
471
  // src/config.ts
9
- var VERSION = "0.7.0";
10
- var API_KEY = process.env.BROWSA_API_KEY;
472
+ var VERSION = "0.8.1";
473
+ var API_KEY = process.env.BROWSA_API_KEY?.trim() || void 0;
11
474
  var BASE_URL = (process.env.BROWSA_BASE_URL || "https://browsa.io").replace(/\/+$/, "");
12
475
  var BASE_URL_SET = !!process.env.BROWSA_BASE_URL;
13
476
  var DEFAULT_COUNTRY = process.env.BROWSA_COUNTRY || void 0;
14
477
  var KEYS_URL = "https://app.browsa.io/dashboard/keys";
15
- var NO_KEY_MESSAGE = "BROWSA_API_KEY is not set. Add it to this MCP server's env (mint one at " + KEYS_URL + "), then restart the server.";
478
+ var NO_KEY_MESSAGE = "BROWSA_API_KEY is not set. Create a key at " + KEYS_URL + ", add it to this MCP server's env, then restart the server.";
479
+ function cliFlag(argv = process.argv.slice(2)) {
480
+ if (argv.includes("--help") || argv.includes("-h")) return "help";
481
+ if (argv.includes("--version") || argv.includes("-v") || argv.includes("-V")) return "version";
482
+ return void 0;
483
+ }
484
+ var HELP = `browsa-mcp ${VERSION}: MCP server for Browsa (stdio)
485
+
486
+ Cloud browsers (Phantom) for an MCP client, and captcha solving for a browser of your own.
487
+ An MCP client starts this command; it speaks MCP on stdin and stdout.
488
+
489
+ Usage:
490
+ npx -y @browsa/mcp [--tools=<groups>]
491
+ npx -y @browsa/mcp --help | --version
492
+
493
+ Options:
494
+ --tools=<groups> Optional tool groups, comma separated (same as BROWSA_MCP_TOOLS):
495
+ tasks, robots, schedules, webhooks, cdp, captcha, captcha_page, admin, or all.
496
+ -name takes a group or a tool off; -core takes the nine core tools off.
497
+ -h, --help Print this and exit
498
+ -v, --version Print the version and exit
499
+
500
+ Environment:
501
+ BROWSA_API_KEY Your Browsa API key. Create a key at ${KEYS_URL}
502
+ Without it the tools are listed; detect_captcha, captcha_allowance
503
+ and list_captcha_types still answer.
504
+ BROWSA_MCP_TOOLS Optional tool groups, as --tools
505
+ BROWSA_BASE_URL Default https://browsa.io
506
+ BROWSA_COUNTRY Default exit country for open
507
+ BROWSA_LLM, BROWSA_LLM_KEY_ID, BROWSA_LLM_API_KEY Model settings for the tasks group
508
+ BROWSA_CAPTCHA_URL Default https://captcha.browsa.io
509
+ BROWSA_CAPTCHA_MAX_CREDITS, BROWSA_CAPTCHA_RATE_PER_MINUTE, BROWSA_CAPTCHA_CONCURRENCY
510
+ Local limits for captcha solves (off unless set)
511
+ BROWSA_MCP_RETRIES Default 2; 0 for none
512
+ BROWSA_MCP_REDACT=off Show URL tokens (debugging only)
513
+
514
+ Core tools (on by default): open, observe, act, read, screenshot, secrets, handoff, flow, close
515
+
516
+ Docs: https://browsa.io/guides/mcp-server
517
+ Source: https://github.com/browsa-io/browsa/tree/main/browsa-mcp
518
+ `;
519
+ var INSTRUCTIONS = "Browsa gives you a real cloud browser (Phantom) and, for a browser of your own, captcha solving. Browser tools: open a page, observe it as text (one line per element with an id), act on an id, read a container, and close the browser when done; a browser left open keeps running until its ttl. act answers with a status on its first line and, when something stopped, a `next:` line: follow it. Type saved secrets with act secret (their values never reach you); call handoff when a person has to step in. Opening a browser, tasks, robots and captcha solves spend the workspace's credits; reads and lists are free. Tools that are not listed are in optional groups: the error names the BROWSA_MCP_TOOLS setting that turns one on. Without BROWSA_API_KEY only detect_captcha, captcha_allowance and list_captcha_types answer.";
16
520
  var REDACT = !/^(0|off|false|no)$/i.test(process.env.BROWSA_MCP_REDACT ?? "");
17
521
  var GROUPS = {
18
522
  tasks: ["run_task", "get_job", "cancel_job", "respond_to_job", "list_job_files"],
@@ -21,9 +525,11 @@ var GROUPS = {
21
525
  webhooks: ["list_webhooks", "create_webhook", "delete_webhook"],
22
526
  cdp: ["start_browser", "stop_browser"],
23
527
  captcha: ["solve_captcha_task", "list_captcha_types", "report_captcha_result"],
528
+ captcha_page: ["detect_captcha", "solve_captcha_on_page", "captcha_allowance"],
24
529
  admin: ["credits", "list_browsers", "list_identities", "proxy_network", "list_llm_keys", "list_models"]
25
530
  };
26
531
  var CORE_TOOLS = ["open", "observe", "act", "read", "screenshot", "secrets", "handoff", "flow", "close"];
532
+ var NO_KEY_TOOLS = ["detect_captcha", "captcha_allowance", "list_captcha_types"];
27
533
  function toolsSetting(argv) {
28
534
  for (let i = 0; i < argv.length; i++) {
29
535
  const a = argv[i];
@@ -34,21 +540,1083 @@ function toolsSetting(argv) {
34
540
  }
35
541
  function enabledExtras(setting = toolsSetting(process.argv.slice(2))) {
36
542
  const tools2 = /* @__PURE__ */ new Set();
543
+ const core = new Set(CORE_TOOLS);
37
544
  const unknown = [];
38
545
  const all = Object.values(GROUPS).flat();
39
- for (const raw of setting.split(/[,\s]+/)) {
40
- const w = raw.trim().toLowerCase();
41
- if (!w || w === "core") continue;
546
+ const words = setting.split(/[,\s]+/).map((w) => w.trim()).filter(Boolean);
547
+ for (const raw of words) {
548
+ const w = raw.toLowerCase();
549
+ if (w.startsWith("-") || w === "core") continue;
42
550
  if (w === "all") all.forEach((t) => tools2.add(t));
43
551
  else if (GROUPS[w]) GROUPS[w].forEach((t) => tools2.add(t));
44
552
  else if (all.includes(w)) tools2.add(w);
45
- else unknown.push(raw.trim());
553
+ else if (!CORE_TOOLS.includes(w)) unknown.push(raw);
554
+ }
555
+ for (const raw of words) {
556
+ if (!raw.startsWith("-")) continue;
557
+ const w = raw.slice(1).toLowerCase();
558
+ if (w === "core") core.clear();
559
+ else if (GROUPS[w]) GROUPS[w].forEach((t) => tools2.delete(t));
560
+ else if (all.includes(w)) tools2.delete(w);
561
+ else if (CORE_TOOLS.includes(w)) core.delete(w);
562
+ else unknown.push(raw);
563
+ }
564
+ return { tools: tools2, core, unknown };
565
+ }
566
+ function numEnv(name, fallback, min = 0, max = Number.MAX_SAFE_INTEGER) {
567
+ const raw = (process.env[name] ?? "").trim();
568
+ if (!raw) return fallback;
569
+ const n = Number(raw);
570
+ if (!Number.isFinite(n) || n < min) return fallback;
571
+ return Math.min(n, max);
572
+ }
573
+
574
+ // src/retry.ts
575
+ var RETRIES = numEnv("BROWSA_MCP_RETRIES", 2, 0, 5);
576
+ var BASE_MS = numEnv("BROWSA_MCP_RETRY_BASE_MS", 500, 1, 1e4);
577
+ var CAP_MS = 8e3;
578
+ var MAX_RETRY_AFTER_MS = 3e4;
579
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
580
+ function backoffMs(attempt, base = BASE_MS, random = Math.random) {
581
+ return Math.round(random() * Math.min(CAP_MS, base * 2 ** attempt));
582
+ }
583
+ function retryAfterMs(value, now = Date.now()) {
584
+ if (!value) return null;
585
+ const v = value.trim();
586
+ if (/^\d+(\.\d+)?$/.test(v)) return Math.round(Number(v) * 1e3);
587
+ const at = Date.parse(v);
588
+ return Number.isFinite(at) ? Math.max(0, at - now) : null;
589
+ }
590
+ var defaultIsApiAnswer = (b) => !!b && typeof b === "object" && typeof b.code === "string";
591
+ async function fetchRetry(url, init, opts) {
592
+ const max = opts.retries ?? RETRIES;
593
+ const isApi = opts.isApiAnswer ?? defaultIsApiAnswer;
594
+ for (let attempt = 0; ; attempt++) {
595
+ let resp;
596
+ try {
597
+ resp = await fetch(url, init());
598
+ } catch (e) {
599
+ if (!opts.idempotent || attempt >= max || e?.name === "TimeoutError") throw e;
600
+ await sleep(backoffMs(attempt));
601
+ continue;
602
+ }
603
+ if (attempt >= max) return resp;
604
+ const after = retryAfterMs(resp.headers.get("retry-after"));
605
+ let again = resp.status === 429;
606
+ if (!again && resp.status >= 500 && opts.idempotent) {
607
+ again = after !== null || !isApi(await resp.clone().json().catch(() => null));
608
+ }
609
+ if (!again) return resp;
610
+ if (after !== null && after > MAX_RETRY_AFTER_MS) return resp;
611
+ await resp.body?.cancel().catch(() => {
612
+ });
613
+ await sleep(after ?? backoffMs(attempt));
614
+ }
615
+ }
616
+
617
+ // src/captcha/client.ts
618
+ var CAPTCHA_URL = (process.env.BROWSA_CAPTCHA_URL || (BASE_URL_SET ? `${BASE_URL}/captcha-api` : "https://captcha.browsa.io")).replace(/\/+$/, "");
619
+ var POLL_MS = numEnv("BROWSA_CAPTCHA_POLL_MS", 3e3, 1);
620
+ var WAIT_S = 20;
621
+ var IDEMPOTENT = /* @__PURE__ */ new Set(["types", "errors", "health", "getTaskResult", "getBalance"]);
622
+ async function captchaCall(method, payload, opts = {}) {
623
+ const timeoutMs = opts.timeoutMs ?? 3e4;
624
+ const retries = opts.retries ?? RETRIES;
625
+ const init = () => payload === null ? { method: "GET", headers: { Accept: "application/json", "User-Agent": "browsa-mcp" }, signal: AbortSignal.timeout(timeoutMs) } : {
626
+ method: "POST",
627
+ headers: { "Content-Type": "application/json", Accept: "application/json", "User-Agent": "browsa-mcp" },
628
+ body: JSON.stringify({ clientKey: API_KEY, ...payload }),
629
+ signal: AbortSignal.timeout(timeoutMs)
630
+ };
631
+ const isApiAnswer = (b) => !!b && typeof b === "object" && "errorId" in b;
632
+ for (let attempt = 0; ; attempt++) {
633
+ const resp = await fetchRetry(`${CAPTCHA_URL}/${method}`, init, { idempotent: IDEMPOTENT.has(method), isApiAnswer, retries });
634
+ const body = await resp.json().catch(() => null);
635
+ if (!isApiAnswer(body)) {
636
+ throw new BrowsaError(`captcha API: unexpected answer (HTTP ${resp.status})`, { code: `HTTP_${resp.status}`, status: resp.status });
637
+ }
638
+ if (body.errorCode === "ERROR_RATE_LIMIT" && attempt < retries) {
639
+ await sleep(backoffMs(attempt, 1e3));
640
+ continue;
641
+ }
642
+ return body;
643
+ }
644
+ }
645
+ async function runCaptchaTask(task, timeoutMs) {
646
+ const started = Date.now();
647
+ const deadline = started + timeoutMs;
648
+ const hold = () => Math.max(0, Math.min(WAIT_S, Math.floor((deadline - Date.now()) / 1e3)));
649
+ const solved = (taskId, b) => ({
650
+ state: "solved",
651
+ taskId,
652
+ body: b,
653
+ seconds: typeof b.solveSeconds === "number" ? b.solveSeconds : Math.round((Date.now() - started) / 100) / 10
654
+ });
655
+ const created = await captchaCall("createTask", { task, ...hold() ? { waitSeconds: hold() } : {} });
656
+ if (created.errorId) return { state: "error", body: created };
657
+ if (created.status === "ready" && created.solution) return solved(created.taskId, created);
658
+ while (Date.now() < deadline) {
659
+ const wait = hold();
660
+ if (!wait) await sleep(Math.min(POLL_MS, Math.max(0, deadline - Date.now())));
661
+ const asked = Date.now();
662
+ const r = await captchaCall("getTaskResult", { taskId: created.taskId, ...wait ? { waitSeconds: wait } : {} });
663
+ if (r.errorId) return { state: "error", body: { taskId: created.taskId, ...r } };
664
+ if (r.status === "ready") return solved(created.taskId, r);
665
+ if (wait && Date.now() - asked < 1e3) {
666
+ await sleep(Math.min(POLL_MS, Math.max(0, deadline - Date.now())));
667
+ }
668
+ }
669
+ return { state: "timeout", taskId: created.taskId, timeoutMs };
670
+ }
671
+
672
+ // src/captcha/catalogue.ts
673
+ var TTL_MS = 60 * 60 * 1e3;
674
+ var PINNED = /^bundled$/i.test((process.env.BROWSA_CAPTCHA_CATALOGUE ?? "").trim());
675
+ var current = { source: "bundled", asOf: catalogue_snapshot_default.asOf, types: catalogue_snapshot_default.types };
676
+ var RETRY_AFTER_FAIL_MS = 60 * 1e3;
677
+ var fetchedAt = 0;
678
+ var failedAt = 0;
679
+ var pending = null;
680
+ function catalogue() {
681
+ return current;
682
+ }
683
+ function typeInfo(name, cat = current) {
684
+ return cat.types.find((t) => t.type === name);
685
+ }
686
+ function fromApi(body, asOf) {
687
+ if (!body || body.errorId || !Array.isArray(body.types) || !body.types.length) return null;
688
+ const names = (ps) => (ps ?? []).map((p) => String(p.name));
689
+ return {
690
+ source: "live",
691
+ asOf,
692
+ types: body.types.map((t) => ({
693
+ type: String(t.type),
694
+ title: String(t.title ?? t.type),
695
+ kind: String(t.kind ?? ""),
696
+ family: String(t.family ?? ""),
697
+ status: String(t.status ?? ""),
698
+ ...t.offReason ? { offReason: String(t.offReason) } : {},
699
+ required: names(t.required),
700
+ oneOf: (t.requiredOneOf ?? []).map(names),
701
+ optional: names(t.optional),
702
+ proxy: String(t.proxy ?? "none"),
703
+ credits: typeof t.price?.creditsPerSolve === "number" ? t.price.creditsPerSolve : null
704
+ }))
705
+ };
706
+ }
707
+ function refreshCatalogue() {
708
+ if (PINNED || Date.now() - fetchedAt < TTL_MS || Date.now() - failedAt < RETRY_AFTER_FAIL_MS) return Promise.resolve();
709
+ pending ??= (async () => {
710
+ try {
711
+ const live = fromApi(await captchaCall("types", null, { timeoutMs: 5e3, retries: 0 }), (/* @__PURE__ */ new Date()).toISOString());
712
+ if (live) {
713
+ current = live;
714
+ fetchedAt = Date.now();
715
+ } else failedAt = Date.now();
716
+ } catch {
717
+ failedAt = Date.now();
718
+ } finally {
719
+ pending = null;
720
+ }
721
+ })();
722
+ return pending;
723
+ }
724
+
725
+ // src/captcha/tools.ts
726
+ import { BrowsaError as BrowsaError2 } from "browsa";
727
+
728
+ // src/captcha/apply.ts
729
+ var js = (v) => JSON.stringify(v ?? null).replace(/</g, "\\u003c").replace(/[\u2028\u2029]/g, (c) => c === "\u2028" ? "\\u2028" : "\\u2029");
730
+ var HELPERS = `
731
+ const out = { applied: false, fields: 0, callback: "none" };
732
+ const put = (el) => { el.value = token; for (const ev of ["input", "change"]) el.dispatchEvent(new Event(ev, { bubbles: true })); out.fields += 1; };
733
+ const call = (fn, label) => { try { fn(token); out.callback = "called " + label; } catch (e) { out.callback = "threw in " + label + ": " + (e && e.message); } };
734
+ const named = (name) => { const f = String(name).split(".").reduce((o, k) => (o == null ? o : o[k]), window); if (typeof f === "function") call(f, name); else out.callback = "not a function: " + name; };`;
735
+ function turnstileExpression(token, hints = {}) {
736
+ return `(() => {
737
+ const token = ${js(token)};
738
+ const wanted = ${js(hints.callback ?? null)};
739
+ const fieldName = ${js(hints.responseField || "cf-turnstile-response")};${HELPERS}
740
+ const widgets = Array.from(document.querySelectorAll(".cf-turnstile"));
741
+ let fields = Array.from(document.querySelectorAll("input[name='" + fieldName + "'], textarea[name='" + fieldName + "']"));
742
+ if (!fields.length) {
743
+ const host = widgets[0] || document.querySelector("form");
744
+ if (host) { const i = document.createElement("input"); i.type = "hidden"; i.name = fieldName; host.appendChild(i); fields = [i]; out.created_field = true; }
745
+ }
746
+ fields.forEach(put);
747
+ for (const w of widgets) w.querySelectorAll("[name='g-recaptcha-response']").forEach(put);
748
+ if (window.turnstile && typeof window.turnstile.getResponse === "function") { try { window.turnstile.getResponse = () => token; out.get_response = "answers this token"; } catch (e) {} }
749
+ const cb = wanted || widgets.map((w) => w.getAttribute("data-callback")).find(Boolean);
750
+ if (cb) named(cb);
751
+ out.applied = out.fields > 0 || out.callback.indexOf("called") === 0;
752
+ return out;
753
+ })()`;
754
+ }
755
+ function recaptchaExpression(token, hints = {}, v3 = false) {
756
+ return `(() => {
757
+ const token = ${js(token)};
758
+ const wanted = ${js(hints.callback ?? null)};
759
+ const v3 = ${v3 ? "true" : "false"};${HELPERS}
760
+ const widgets = Array.from(document.querySelectorAll(".g-recaptcha"));
761
+ let fields = Array.from(document.querySelectorAll("textarea[name='g-recaptcha-response'], textarea[id^='g-recaptcha-response'], input[name='g-recaptcha-response']"));
762
+ if (!fields.length && !v3) {
763
+ const host = widgets[0] || document.querySelector("form");
764
+ if (host) { const t = document.createElement("textarea"); t.name = "g-recaptcha-response"; t.style.display = "none"; host.appendChild(t); fields = [t]; out.created_field = true; }
765
+ }
766
+ fields.forEach(put);
767
+ const apis = [window.grecaptcha, window.grecaptcha && window.grecaptcha.enterprise].filter(Boolean);
768
+ for (const g of apis) {
769
+ try { if (typeof g.getResponse === "function") { g.getResponse = () => token; out.get_response = "answers this token"; } } catch (e) {}
770
+ try { if (v3 && typeof g.execute === "function") { g.execute = () => Promise.resolve(token); out.execute = "answers this token"; } } catch (e) {}
46
771
  }
47
- return { tools: tools2, unknown };
772
+ let cb = wanted || widgets.map((w) => w.getAttribute("data-callback")).find(Boolean);
773
+ if (cb) named(cb);
774
+ else if (!v3) {
775
+ const seen = new Set();
776
+ const find = (o, depth) => {
777
+ if (!o || typeof o !== "object" || depth > 5 || seen.has(o)) return null;
778
+ if (typeof Node !== "undefined" && o instanceof Node) return null;
779
+ seen.add(o);
780
+ for (const k of Object.keys(o)) {
781
+ let v; try { v = o[k]; } catch (e) { continue; }
782
+ if (k === "callback" && (typeof v === "function" || typeof v === "string")) return v;
783
+ const r = find(v, depth + 1);
784
+ if (r) return r;
785
+ }
786
+ return null;
787
+ };
788
+ const cfg = window.___grecaptcha_cfg;
789
+ const found = cfg && cfg.clients ? find(cfg.clients, 0) : null;
790
+ if (typeof found === "function") call(found, "the widget's callback");
791
+ else if (typeof found === "string") named(found);
792
+ }
793
+ out.applied = out.fields > 0 || out.callback.indexOf("called") === 0 || !!out.execute;
794
+ return out;
795
+ })()`;
796
+ }
797
+ var TOKEN_STEPS = [
798
+ "Evaluate apply.expression in the page's main frame.",
799
+ 'If its result has callback "called ...", the page has the token: wait for the page to move on. Otherwise submit the form the widget is in.',
800
+ "Check the page's own answer. applied false means no field or callback was found: the widget may be in another frame, or not rendered yet."
801
+ ];
802
+ function buildApply(type, solution, websiteURL, hints = {}) {
803
+ const s = solution ?? {};
804
+ if (/Cloudflare/i.test(type) || s.cookies && typeof s.cookies === "object") {
805
+ let host = "";
806
+ try {
807
+ host = new URL(String(websiteURL)).hostname;
808
+ } catch {
809
+ }
810
+ const cookies = Object.entries(s.cookies ?? (s.token ? { cf_clearance: s.token } : {})).map(([name, value]) => ({ name, value: String(value), domain: host, path: "/", secure: true }));
811
+ return {
812
+ how: "cookies",
813
+ cookies,
814
+ ...s.userAgent ? { user_agent: String(s.userAgent) } : {},
815
+ steps: [
816
+ "Set these cookies in your browser for that domain, and send exactly this user agent.",
817
+ "Re-request the URL through the same proxy the task used. Do not reload the challenge page: a reload asks for a new check.",
818
+ "The cookie only works from the address that passed the check."
819
+ ]
820
+ };
821
+ }
822
+ if (typeof s.token === "string" && /Turnstile/i.test(type)) {
823
+ return { how: "evaluate", expression: turnstileExpression(s.token, hints), steps: TOKEN_STEPS, valid_seconds: 300 };
824
+ }
825
+ if (typeof s.gRecaptchaResponse === "string") {
826
+ const v3 = /V3/i.test(type);
827
+ return {
828
+ how: "evaluate",
829
+ expression: recaptchaExpression(s.gRecaptchaResponse, hints, v3),
830
+ valid_seconds: 120,
831
+ steps: v3 ? [
832
+ "Evaluate apply.expression in the page's main frame: the page's next grecaptcha.execute() call answers this token.",
833
+ "Then do the page's own action (its button): its script sends the token.",
834
+ "A v3 token is scored by the site; check the page's own answer."
835
+ ] : TOKEN_STEPS
836
+ };
837
+ }
838
+ return { how: "manual", steps: ["This solution has no page step this server knows: use its fields as the page's own code would."] };
839
+ }
840
+
841
+ // src/captcha/detect.ts
842
+ var MAX_HTML = 3e6;
843
+ var ENT = { amp: "&", quot: '"', apos: "'", lt: "<", gt: ">", "#39": "'", "#x27": "'", "#34": '"', "#38": "&" };
844
+ var decode = (s) => s.replace(/&(amp|quot|apos|lt|gt|#39|#x27|#34|#38);/gi, (_, e) => ENT[e.toLowerCase()] ?? _);
845
+ var TAG = /<\/form\s*>|<([a-zA-Z][a-zA-Z0-9-]*)((?:\s+[^\s"'<>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'<>]+))?)*)\s*\/?>/g;
846
+ var ATTR = /([^\s"'<>\/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'<>]+)))?/g;
847
+ function attrsOf(raw) {
848
+ const out = {};
849
+ for (const m of raw.matchAll(ATTR)) {
850
+ const k = m[1].toLowerCase();
851
+ if (!(k in out)) out[k] = decode(m[2] ?? m[3] ?? m[4] ?? "");
852
+ }
853
+ return out;
854
+ }
855
+ function scan(input) {
856
+ const truncated = input.length > MAX_HTML;
857
+ let html = truncated ? input.slice(0, MAX_HTML) : input;
858
+ html = html.replace(/<!--[\s\S]*?-->/g, " ");
859
+ const title = decode((/<title\b[^>]*>([\s\S]*?)<\/title>/i.exec(html)?.[1] ?? "").replace(/\s+/g, " ").trim());
860
+ const scripts = [];
861
+ html = html.replace(/(<script\b[^>]*>)([\s\S]*?)<\/script\s*>/gi, (_, open2, body) => {
862
+ const type = /\btype\s*=\s*["']?([^"'\s>]+)/i.exec(open2)?.[1]?.toLowerCase() ?? "";
863
+ if (body.trim() && (!type || /javascript|ecmascript|^module$/.test(type))) scripts.push(body);
864
+ return open2;
865
+ });
866
+ html = html.replace(/<(style|pre|code|xmp|noscript|template|svg)\b[^>]*>[\s\S]*?<\/\1\s*>/gi, " ");
867
+ html = html.replace(/(<textarea\b[^>]*>)[\s\S]*?<\/textarea\s*>/gi, "$1");
868
+ const tags = [];
869
+ let form = -1;
870
+ let forms = 0;
871
+ for (const m of html.matchAll(TAG)) {
872
+ if (!m[1]) {
873
+ form = -1;
874
+ continue;
875
+ }
876
+ const name = m[1].toLowerCase();
877
+ if (name === "form") form = forms++;
878
+ tags.push({ name, attrs: attrsOf(m[2] ?? ""), form });
879
+ }
880
+ return { tags, scripts, title, truncated };
881
+ }
882
+ function parseUrl(raw, base, from) {
883
+ const v = (raw || "").trim();
884
+ if (!v || /^(data|blob|javascript|about):/i.test(v)) return null;
885
+ try {
886
+ const u = new URL(v.startsWith("//") ? `https:${v}` : v, base || "https://page.invalid/");
887
+ return { url: u.href, host: u.hostname.toLowerCase(), path: u.pathname, search: u.searchParams, from };
888
+ } catch {
889
+ return null;
890
+ }
891
+ }
892
+ var hasClass = (t, cls) => (t.attrs.class ?? "").split(/\s+/).includes(cls);
893
+ var hostIs = (h, re) => re.test(h);
894
+ var uniq = (xs) => [...new Set(xs)];
895
+ var TURNSTILE_KEY = /^(0x[0-9A-Za-z_-]{18,}|[123]x0{8,}[0-9A-Za-z]{2})$/;
896
+ var TURNSTILE_KEY_IN = /(0x4[0-9A-Za-z_-]{18,}|[123]x0{8,}[0-9A-Za-z]{2})/;
897
+ var RECAPTCHA_KEY = /^6L[0-9A-Za-z_-]{38}$/;
898
+ var TEST_KEYS = /^([123]x0{8,}[0-9A-Za-z]{2}|6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI|10000000-ffff-ffff-ffff-000000000001)$/;
899
+ var CHECK_TITLE = /just a moment|un instant|einen moment|un momento|um momento|attention required|checking your browser|ちょっと待|請稍候|请稍候/i;
900
+ var OTHER_FRAMES = [
901
+ [/(^|\.)(arkoselabs\.com|funcaptcha\.com)$/, "arkose", "Arkose (FunCaptcha)"],
902
+ [/(^|\.)mtcaptcha\.com$/, "mtcaptcha", "MTCaptcha"],
903
+ [/(^|\.)captcha\.(qcloud|qq)\.com$|(^|\.)turing\.captcha\.qcloud\.com$/, "tencent", "Tencent captcha"],
904
+ [/(^|\.)friendlycaptcha\.(com|eu)$/, "friendly_captcha", "Friendly Captcha"],
905
+ [/(^|\.)captchafox\.com$/, "captchafox", "CaptchaFox"],
906
+ [/(^|\.)leminnow\.com$/, "lemin", "Lemin"]
907
+ ];
908
+ var PX_HOSTS = /(^|\.)(px-cdn\.net|px-cloud\.net|perimeterx\.net|pxchk\.net|px-cdn\.com|humansecurity\.com)$/;
909
+ var PX_PATH = /\/px\/[A-Za-z0-9]+\/(captcha|init)/i;
910
+ function near(script, at, re, span = 600) {
911
+ return re.exec(script.slice(at, at + span))?.[1];
912
+ }
913
+ function detectCaptchas(input) {
914
+ const { tags, scripts, title, truncated } = scan(String(input.html ?? ""));
915
+ const pageUrl = /^https?:\/\//i.test(input.url ?? "") ? String(input.url) : void 0;
916
+ const res = [];
917
+ for (const t of tags) {
918
+ if (t.name === "script" && t.attrs.src) {
919
+ const r = parseUrl(t.attrs.src, pageUrl, "script");
920
+ if (r) res.push(r);
921
+ }
922
+ if (t.name === "iframe" && t.attrs.src) {
923
+ const r = parseUrl(t.attrs.src, pageUrl, "frame");
924
+ if (r) res.push(r);
925
+ }
926
+ }
927
+ for (const u of input.resources ?? []) {
928
+ const r = parseUrl(String(u), pageUrl, "resource");
929
+ if (r) res.push(r);
930
+ }
931
+ const code = scripts.join("\n;\n");
932
+ const findings = [];
933
+ const urlMissing = pageUrl ? [] : ["websiteURL: pass url, the address of the page"];
934
+ const base = () => ({ params: pageUrl ? { websiteURL: pageUrl } : {}, page: {}, missing: [...urlMissing], evidence: [], notes: [] });
935
+ const cfOpt = /\b_cf_chl_opt\b/.test(code);
936
+ const cfOrchestrate = res.some((r) => /\/cdn-cgi\/challenge-platform\/.*\/orchestrate\/(chl_page|managed|jsch)\//.test(r.path));
937
+ const cfForm = tags.some((t) => t.attrs.id === "challenge-form" || t.attrs.id === "challenge-error-text" || t.attrs.id === "cf-challenge-running");
938
+ const cfPage = cfOpt || cfOrchestrate || CHECK_TITLE.test(title) && cfForm;
939
+ if (cfPage) {
940
+ const f = { kind: "cloudflare", name: "Cloudflare check page", ...base(), confidence: cfOpt || cfOrchestrate ? "high" : "medium" };
941
+ if (cfOpt) f.evidence.push("script: window._cf_chl_opt");
942
+ if (cfOrchestrate) f.evidence.push("script: /cdn-cgi/challenge-platform/.../orchestrate/");
943
+ if (CHECK_TITLE.test(title)) f.evidence.push(`title: ${title.slice(0, 60)}`);
944
+ f.missing.push("proxy: your proxy URL (the cookie only works from the address that passed the check)");
945
+ f.notes.push("The answer is a cookie, not a token: set it, send the same user agent, and request the page again.");
946
+ findings.push(f);
947
+ }
948
+ {
949
+ const widgets = tags.filter((t) => hasClass(t, "cf-turnstile"));
950
+ const frames = res.filter((r) => r.host === "challenges.cloudflare.com" && /\/turnstile\//.test(r.path) && !/\/api\.js$/.test(r.path));
951
+ const api = res.some((r) => r.host === "challenges.cloudflare.com" && /\/turnstile\/v0\/api\.js$/.test(r.path));
952
+ const field = tags.some((t) => t.attrs.name === "cf-turnstile-response");
953
+ const byKey = /* @__PURE__ */ new Map();
954
+ const get = (key) => {
955
+ let f = byKey.get(key);
956
+ if (!f) {
957
+ f = { kind: "turnstile", name: "Cloudflare Turnstile", ...base(), confidence: "high" };
958
+ f.params.websiteKey = key;
959
+ byKey.set(key, f);
960
+ }
961
+ return f;
962
+ };
963
+ for (const r of frames) {
964
+ const key = TURNSTILE_KEY_IN.exec(r.path)?.[1];
965
+ if (key) get(key).evidence.push(`${r.from}: challenges.cloudflare.com widget frame with the key`);
966
+ }
967
+ for (const w of widgets) {
968
+ const key = (w.attrs["data-sitekey"] ?? "").trim();
969
+ if (!TURNSTILE_KEY.test(key)) continue;
970
+ const f = get(key);
971
+ f.evidence.push(`<${w.name} class="cf-turnstile" data-sitekey>`);
972
+ const meta = {};
973
+ if (w.attrs["data-action"]) meta.action = w.attrs["data-action"];
974
+ if (w.attrs["data-cdata"]) meta.cdata = w.attrs["data-cdata"];
975
+ if (Object.keys(meta).length) f.params.metadata = meta;
976
+ if (w.attrs["data-callback"]) f.page.callback = w.attrs["data-callback"];
977
+ if (w.attrs["data-response-field-name"]) f.page.responseField = w.attrs["data-response-field-name"];
978
+ }
979
+ for (const m of code.matchAll(/\bturnstile\s*\.\s*render\s*\(/g)) {
980
+ const key = near(code, m.index, /sitekey["']?\s*:\s*["']([^"']+)["']/);
981
+ if (!key || !TURNSTILE_KEY.test(key)) continue;
982
+ const f = get(key);
983
+ f.evidence.push("script: turnstile.render({sitekey})");
984
+ const action = near(code, m.index, /\baction["']?\s*:\s*["']([^"']+)["']/);
985
+ const cdata = near(code, m.index, /\bcData["']?\s*:\s*["']([^"']+)["']/);
986
+ if (action || cdata) f.params.metadata = { ...f.params.metadata ?? {}, ...action ? { action } : {}, ...cdata ? { cdata } : {} };
987
+ const cb = near(code, m.index, /\bcallback["']?\s*:\s*([A-Za-z_$][\w$.]*)\s*[,}]/);
988
+ if (cb && !f.page.callback && !/^function$/.test(cb)) f.page.callback = cb;
989
+ }
990
+ for (const f of byKey.values()) findings.push(f);
991
+ if (!byKey.size && !cfPage && (api || field || widgets.length)) {
992
+ const f = { kind: "turnstile", name: "Cloudflare Turnstile", ...base(), confidence: widgets.length || field ? "medium" : "low" };
993
+ if (api) f.evidence.push("script: challenges.cloudflare.com/turnstile/v0/api.js");
994
+ if (field) f.evidence.push("input name=cf-turnstile-response");
995
+ if (widgets.length) f.evidence.push("class cf-turnstile without data-sitekey");
996
+ f.missing.push("websiteKey: not in the HTML; pass resources (the page's frame URLs): the challenges.cloudflare.com frame address holds the key (0x...)");
997
+ findings.push(f);
998
+ }
999
+ }
1000
+ {
1001
+ const G = /^(www\.)?(google\.com|recaptcha\.net)$/;
1002
+ const apis = res.filter((r) => hostIs(r.host, G) && /\/recaptcha\/(api|enterprise)\.js$/.test(r.path));
1003
+ const anchors = res.filter((r) => hostIs(r.host, G) && /\/recaptcha\/(api2|enterprise)\/anchor$/.test(r.path));
1004
+ const widgets = tags.filter((t) => hasClass(t, "g-recaptcha"));
1005
+ const field = tags.some((t) => t.attrs.name === "g-recaptcha-response");
1006
+ const enterprise = apis.some((r) => /enterprise\.js$/.test(r.path)) || anchors.some((r) => /\/enterprise\//.test(r.path)) || /\bgrecaptcha\s*\.\s*enterprise\b/.test(code);
1007
+ const net = [...apis, ...anchors].some((r) => /recaptcha\.net$/.test(r.host));
1008
+ const keys = /* @__PURE__ */ new Map();
1009
+ const get = (key) => {
1010
+ let k = keys.get(key);
1011
+ if (!k) {
1012
+ k = { v3: false, invisible: false, evidence: [], sure: false };
1013
+ keys.set(key, k);
1014
+ }
1015
+ return k;
1016
+ };
1017
+ for (const r of anchors) {
1018
+ const key = r.search.get("k") ?? "";
1019
+ if (!RECAPTCHA_KEY.test(key)) continue;
1020
+ const k = get(key);
1021
+ k.sure = true;
1022
+ if (r.search.get("size") === "invisible") k.invisible = true;
1023
+ k.evidence.push(`${r.from}: recaptcha anchor frame, k=`);
1024
+ }
1025
+ for (const r of apis) {
1026
+ const render = r.search.get("render") ?? "";
1027
+ if (!RECAPTCHA_KEY.test(render)) continue;
1028
+ const k = get(render);
1029
+ k.v3 = true;
1030
+ k.sure = true;
1031
+ k.evidence.push(`script: recaptcha/${/enterprise/.test(r.path) ? "enterprise" : "api"}.js?render=<key>`);
1032
+ }
1033
+ for (const w of widgets) {
1034
+ const key = (w.attrs["data-sitekey"] ?? "").trim();
1035
+ if (!RECAPTCHA_KEY.test(key)) continue;
1036
+ const k = get(key);
1037
+ k.evidence.push(`<${w.name} class="g-recaptcha" data-sitekey>`);
1038
+ if ((w.attrs["data-size"] ?? "").toLowerCase() === "invisible") k.invisible = true;
1039
+ if (w.attrs["data-callback"]) k.callback = w.attrs["data-callback"];
1040
+ if (w.attrs["data-action"]) {
1041
+ k.v3 = true;
1042
+ k.action = w.attrs["data-action"];
1043
+ }
1044
+ }
1045
+ for (const m of code.matchAll(/\bgrecaptcha\s*(?:\.\s*enterprise\s*)?\.\s*execute\s*\(\s*["']([^"']+)["']/g)) {
1046
+ if (!RECAPTCHA_KEY.test(m[1])) continue;
1047
+ const k = get(m[1]);
1048
+ k.v3 = true;
1049
+ k.action ??= near(code, m.index, /\baction["']?\s*:\s*["']([^"']+)["']/, 300);
1050
+ k.evidence.push("script: grecaptcha.execute(key, {action})");
1051
+ }
1052
+ for (const m of code.matchAll(/\bgrecaptcha\s*(?:\.\s*enterprise\s*)?\.\s*render\s*\(/g)) {
1053
+ const key = near(code, m.index, /sitekey["']?\s*:\s*["']([^"']+)["']/);
1054
+ if (!key || !RECAPTCHA_KEY.test(key)) continue;
1055
+ const k = get(key);
1056
+ if (near(code, m.index, /\bsize["']?\s*:\s*["'](invisible)["']/)) k.invisible = true;
1057
+ const cb = near(code, m.index, /\bcallback["']?\s*:\s*([A-Za-z_$][\w$.]*)\s*[,}]/);
1058
+ if (cb && !k.callback && cb !== "function") k.callback = cb;
1059
+ k.evidence.push("script: grecaptcha.render({sitekey})");
1060
+ }
1061
+ for (const [key, k] of keys) {
1062
+ const fam = `recaptcha_${k.v3 ? "v3" : "v2"}${enterprise ? "_enterprise" : ""}`;
1063
+ const f = { kind: fam, name: `reCAPTCHA ${k.v3 ? "v3" : "v2"}${enterprise ? " Enterprise" : ""}`, ...base(), confidence: "high" };
1064
+ f.params.websiteKey = key;
1065
+ if (k.v3) {
1066
+ if (k.action) f.params.pageAction = k.action;
1067
+ } else if (k.invisible) f.params.isInvisible = true;
1068
+ if (net) f.params.apiDomain = "recaptcha.net";
1069
+ if (k.callback) f.page.callback = k.callback;
1070
+ f.evidence.push(...uniq(k.evidence));
1071
+ if (k.v3 && !k.action) f.notes.push("pageAction was not found in the HTML: read it from the page's grecaptcha.execute call, the site may check it.");
1072
+ if (!k.v3 && !k.sure && widgets.some((w) => w.attrs["data-sitekey"] === key && w.name === "button")) {
1073
+ f.notes.push("A key bound to a button can be v2 invisible or v3: if the token is refused, solve again as the other version.");
1074
+ }
1075
+ findings.push(f);
1076
+ }
1077
+ if (!keys.size && (apis.length || widgets.length || field)) {
1078
+ const v3ish = apis.some((r) => {
1079
+ const x = r.search.get("render");
1080
+ return !!x && x !== "explicit" && x !== "onload";
1081
+ });
1082
+ const f = {
1083
+ kind: `recaptcha_${v3ish ? "v3" : "v2"}${enterprise ? "_enterprise" : ""}`,
1084
+ name: `reCAPTCHA${enterprise ? " Enterprise" : ""}`,
1085
+ ...base(),
1086
+ confidence: widgets.length || field ? "medium" : "low"
1087
+ };
1088
+ if (apis.length) f.evidence.push("script: recaptcha api.js");
1089
+ if (widgets.length) f.evidence.push("class g-recaptcha without data-sitekey");
1090
+ if (field) f.evidence.push("textarea name=g-recaptcha-response");
1091
+ f.missing.push("websiteKey: not in the HTML; pass resources (the page's frame URLs): the recaptcha anchor frame has it as k=");
1092
+ f.notes.push("The version (v2 or v3) could not be told without the key's frame or script.");
1093
+ findings.push(f);
1094
+ }
1095
+ }
1096
+ {
1097
+ const gt = res.filter((r) => /(^|\.)(geetest|geevisit)\.com$/.test(r.host));
1098
+ const init3 = /\binitGeetest\s*\(/.test(code);
1099
+ const init4 = /\binitGeetest4\s*\(/.test(code);
1100
+ if (gt.length || init3 || init4) {
1101
+ const v4 = init4 || gt.some((r) => /^gcaptcha4\./.test(r.host) || /\/v4\/|gt4\.js/.test(r.path));
1102
+ const f = { kind: "geetest_slide", name: `GeeTest v${v4 ? 4 : 3}`, ...base(), confidence: "high" };
1103
+ f.missing = [];
1104
+ f.params = { version: v4 ? 4 : 3 };
1105
+ if (gt.length) f.evidence.push(`${gt[0].from}: ${gt[0].host}`);
1106
+ if (init3 || init4) f.evidence.push(`script: ${init4 ? "initGeetest4" : "initGeetest"}()`);
1107
+ f.missing.push(v4 ? "imageBackground, imageSlice, top, bgCssWidth: the puzzle's two pictures and the piece's position, from the open widget" : "imageBackground, imageFull: GeeTest's two pictures as served, from the open widget");
1108
+ f.notes.push("Only the slide puzzle is answered, and only as a distance to drag: the drag is yours to make.");
1109
+ findings.push(f);
1110
+ }
1111
+ const waf = res.filter((r) => /(^|\.)awswaf\.com$/.test(r.host));
1112
+ const wafCaptcha = waf.some((r) => /captcha\.js$/.test(r.path)) || tags.some((t) => t.name === "awswaf-captcha") || /\bAwsWafCaptcha\s*\.\s*renderCaptcha\s*\(/.test(code) || waf.length > 0 && tags.some((t) => /\bamzn-captcha-/.test(t.attrs.class ?? ""));
1113
+ if (wafCaptcha) {
1114
+ const f = { kind: "aws_waf", name: "AWS WAF captcha", ...base(), confidence: "high" };
1115
+ f.missing = [];
1116
+ f.params = {};
1117
+ f.evidence.push(waf.length ? `${waf[0].from}: ${waf[0].host}` : "awswaf-captcha element");
1118
+ f.missing.push('images, question: the grid picture and "aws:grid:<object>" from the open puzzle');
1119
+ f.notes.push("The answer is the tiles to click: the clicks are yours to make.");
1120
+ findings.push(f);
1121
+ }
1122
+ const dd = res.filter((r) => /(^|\.)captcha-delivery\.com$/.test(r.host) && /\/captcha\//.test(r.path));
1123
+ if (dd.length) {
1124
+ const f = { kind: "slider", name: "DataDome slider", ...base(), confidence: "high" };
1125
+ f.missing = ["imageBackground: the puzzle picture with the gap, from the frame"];
1126
+ f.params = { module: "slider_1" };
1127
+ f.evidence.push(`${dd[0].from}: ${dd[0].host}/captcha/`);
1128
+ findings.push(f);
1129
+ }
1130
+ }
1131
+ {
1132
+ const hints = (t, keys) => keys.map((k) => t.attrs[k] ?? "").join(" ").toLowerCase();
1133
+ const inputs = tags.filter((t) => t.name === "input" && ["text", ""].includes((t.attrs.type ?? "text").toLowerCase()));
1134
+ const capInputs = inputs.filter((t) => hints(t, ["placeholder", "name", "id", "aria-label", "class"]).includes("captcha") && !/g-recaptcha|h-captcha|cf-turnstile/.test(hints(t, ["name", "id", "class"])));
1135
+ const imgs = tags.filter((t) => t.name === "img");
1136
+ const about = (t) => `${hints(t, ["alt", "id", "class", "title", "name"])} ${/^data:/i.test(t.attrs.src ?? "") ? "" : (t.attrs.src ?? "").toLowerCase()}`;
1137
+ const strong = imgs.find((t) => about(t).includes("captcha") && !(t.attrs.src ?? "").toLowerCase().split("?")[0].endsWith(".svg") && !/recaptcha|hcaptcha|logo|badge|icon/.test(about(t)));
1138
+ const inline = imgs.find((t) => /^(data:image\/(?!svg)|blob:)/i.test(t.attrs.src ?? ""));
1139
+ let img;
1140
+ let confidence = "high";
1141
+ if (strong && capInputs.length) img = strong;
1142
+ else if (strong) {
1143
+ const answer2 = inputs.find((t) => t.form >= 0 && t.form === strong.form && /captcha|answer|code|characters|text/.test(hints(t, ["placeholder", "name", "id", "aria-label"])));
1144
+ if (answer2) {
1145
+ img = strong;
1146
+ confidence = "medium";
1147
+ }
1148
+ } else if (capInputs.length && inline) img = inline;
1149
+ if (img) {
1150
+ const f = { kind: "image_text", name: "Image text captcha", ...base(), confidence };
1151
+ f.missing = [];
1152
+ const src = img.attrs.src ?? "";
1153
+ f.evidence.push(`<img ${img.attrs.id ? `id="${img.attrs.id}" ` : ""}src="${src.slice(0, 80)}${src.length > 80 ? "..." : ""}"> with an answer field`);
1154
+ f.missing.push(/^data:image\//i.test(src) ? "body: the picture; its src is a data: URL, pass that as body" : "body: the picture as base64 (take it from the element in your browser, e.g. a screenshot of the <img>)");
1155
+ f.notes.push("The answer is text to type into the page's field.");
1156
+ findings.push(f);
1157
+ }
1158
+ }
1159
+ {
1160
+ const add = (kind, name, evidence, extra) => {
1161
+ let f = findings.find((x) => x.kind === kind);
1162
+ if (!f) {
1163
+ f = { kind, name, params: {}, page: {}, missing: [], evidence: [], confidence: "high", notes: [] };
1164
+ findings.push(f);
1165
+ }
1166
+ f.evidence.push(evidence);
1167
+ extra?.(f);
1168
+ };
1169
+ const hc = tags.filter((t) => hasClass(t, "h-captcha") && t.attrs["data-sitekey"]);
1170
+ const hcRes = res.filter((r) => /(^|\.)hcaptcha\.com$/.test(r.host));
1171
+ for (const w of hc) add("hcaptcha", "hCaptcha", `<${w.name} class="h-captcha" data-sitekey>`, (f) => {
1172
+ f.params.websiteKey = w.attrs["data-sitekey"];
1173
+ });
1174
+ if (hcRes.length) add("hcaptcha", "hCaptcha", `${hcRes[0].from}: ${hcRes[0].host}`);
1175
+ for (const [re, kind, name] of OTHER_FRAMES) {
1176
+ const r = res.find((x) => re.test(x.host));
1177
+ if (r) add(kind, name, `${r.from}: ${r.host}`);
1178
+ }
1179
+ const sel = [
1180
+ [(t) => t.attrs.id === "FunCaptcha" || /^arkose/i.test(t.attrs.id ?? "") || "data-pkey" in t.attrs, "arkose", "Arkose (FunCaptcha)", "Arkose element"],
1181
+ [(t) => hasClass(t, "frc-captcha"), "friendly_captcha", "Friendly Captcha", "class frc-captcha"],
1182
+ [(t) => hasClass(t, "mtcaptcha"), "mtcaptcha", "MTCaptcha", "class mtcaptcha"],
1183
+ [(t) => t.attrs.id === "div_for_keycaptcha", "keycaptcha", "KeyCaptcha", "id div_for_keycaptcha"],
1184
+ [(t) => t.attrs.id === "lemin-cropped-captcha", "lemin", "Lemin", "id lemin-cropped-captcha"],
1185
+ [(t) => hasClass(t, "captchafox"), "captchafox", "CaptchaFox", "class captchafox"],
1186
+ [(t) => t.name === "altcha-widget", "altcha", "ALTCHA", "<altcha-widget>"]
1187
+ ];
1188
+ for (const [test, kind, name, ev] of sel) if (tags.some(test)) add(kind, name, ev);
1189
+ const px = tags.some((t) => t.attrs.id === "px-captcha");
1190
+ const pxRes = res.some((r) => PX_HOSTS.test(r.host) || PX_PATH.test(r.path));
1191
+ if (px) {
1192
+ add("press_and_hold", "HUMAN press and hold", "id px-captcha", (f) => {
1193
+ if (!pxRes) f.confidence = "medium";
1194
+ f.notes.push("Passed by pressing and holding the button with real pointer input: there is nothing to solve remotely.");
1195
+ });
1196
+ }
1197
+ const altcha = findings.find((f) => f.kind === "altcha");
1198
+ if (altcha) altcha.notes.push(`A proof of work the page's own script does when its checkbox is clicked: click it and wait for "verified".`);
1199
+ }
1200
+ for (const f of findings) {
1201
+ f.evidence = uniq(f.evidence).slice(0, 4);
1202
+ const key = String(f.params.websiteKey ?? "");
1203
+ if (key && TEST_KEYS.test(key)) f.notes.push("This is the provider's public test key: it passes (or fails) for everyone by design, so solving it proves nothing.");
1204
+ }
1205
+ return { findings, truncated };
1206
+ }
1207
+
1208
+ // src/captcha/guards.ts
1209
+ function limitsFromEnv() {
1210
+ const whole = (n) => n === null ? null : Math.max(1, Math.floor(n));
1211
+ return {
1212
+ maxCredits: numEnv("BROWSA_CAPTCHA_MAX_CREDITS", null),
1213
+ ratePerMinute: whole(numEnv("BROWSA_CAPTCHA_RATE_PER_MINUTE", null, 1)),
1214
+ concurrency: whole(numEnv("BROWSA_CAPTCHA_CONCURRENCY", null, 1))
1215
+ };
1216
+ }
1217
+ var WINDOW_MS = 6e4;
1218
+ var round = (n) => Math.round(n * 1e6) / 1e6;
1219
+ var Guard = class {
1220
+ constructor(limits, now = Date.now) {
1221
+ this.limits = limits;
1222
+ this.now = now;
1223
+ }
1224
+ limits;
1225
+ now;
1226
+ spent = 0;
1227
+ reserved = 0;
1228
+ running = 0;
1229
+ solves = 0;
1230
+ starts = [];
1231
+ get configured() {
1232
+ const l = this.limits;
1233
+ return l.maxCredits !== null || l.ratePerMinute !== null || l.concurrency !== null;
1234
+ }
1235
+ recent() {
1236
+ const from = this.now() - WINDOW_MS;
1237
+ this.starts = this.starts.filter((t) => t > from);
1238
+ return this.starts;
1239
+ }
1240
+ /** Asks to start one solve that costs `price` credits when it succeeds. */
1241
+ begin(price) {
1242
+ const l = this.limits;
1243
+ if (l.concurrency !== null && this.running >= l.concurrency) {
1244
+ return { ok: false, refusal: {
1245
+ limit: "concurrency",
1246
+ retry_after_seconds: 5,
1247
+ retry: "when a running solve ends (a token solve takes seconds to about 2 minutes)",
1248
+ message: `${this.running} captcha solves are running and BROWSA_CAPTCHA_CONCURRENCY is ${l.concurrency}`
1249
+ } };
1250
+ }
1251
+ if (l.ratePerMinute !== null && this.recent().length >= l.ratePerMinute) {
1252
+ const wait = Math.max(1, Math.ceil((this.starts[0] + WINDOW_MS - this.now()) / 1e3));
1253
+ return { ok: false, refusal: {
1254
+ limit: "rate",
1255
+ retry_after_seconds: wait,
1256
+ retry: `in ${wait} s`,
1257
+ message: `${this.starts.length} solves started in the last minute and BROWSA_CAPTCHA_RATE_PER_MINUTE is ${l.ratePerMinute}`
1258
+ } };
1259
+ }
1260
+ if (l.maxCredits !== null && this.spent + this.reserved + price > l.maxCredits + 1e-9) {
1261
+ const waiting = this.reserved > 0;
1262
+ return { ok: false, refusal: {
1263
+ limit: "spend_cap",
1264
+ retry_after_seconds: waiting ? 5 : null,
1265
+ retry: waiting ? "when the running solves end: a failed solve gives its reserved credits back" : "not in this session: raise BROWSA_CAPTCHA_MAX_CREDITS in this server's env and restart it",
1266
+ message: `this solve costs ${price} credits; the session has spent ${round(this.spent)}${this.reserved ? ` and holds ${round(this.reserved)} for running solves` : ""}, and BROWSA_CAPTCHA_MAX_CREDITS is ${l.maxCredits}`
1267
+ } };
1268
+ }
1269
+ this.running += 1;
1270
+ this.reserved += price;
1271
+ this.starts.push(this.now());
1272
+ let open2 = true;
1273
+ return { ok: true, ticket: { done: (credits) => {
1274
+ if (!open2) return;
1275
+ open2 = false;
1276
+ this.running -= 1;
1277
+ this.reserved = Math.max(0, this.reserved - price);
1278
+ if (credits > 0) {
1279
+ this.spent += credits;
1280
+ this.solves += 1;
1281
+ }
1282
+ } } };
1283
+ }
1284
+ /** What is left, for the agent. Limits that are not set say so. */
1285
+ allowance() {
1286
+ const l = this.limits;
1287
+ const used = this.recent().length;
1288
+ return {
1289
+ spent_credits: round(this.spent),
1290
+ solved: this.solves,
1291
+ spend_cap: l.maxCredits === null ? "not set" : { max_credits: l.maxCredits, remaining_credits: round(Math.max(0, l.maxCredits - this.spent - this.reserved)), reserved_credits: round(this.reserved) },
1292
+ rate: l.ratePerMinute === null ? "not set" : {
1293
+ per_minute: l.ratePerMinute,
1294
+ remaining: Math.max(0, l.ratePerMinute - used),
1295
+ ...used ? { oldest_frees_in_seconds: Math.max(1, Math.ceil((this.starts[0] + WINDOW_MS - this.now()) / 1e3)) } : {}
1296
+ },
1297
+ concurrency: l.concurrency === null ? "not set" : { max: l.concurrency, running: this.running, free: Math.max(0, l.concurrency - this.running) }
1298
+ };
1299
+ }
1300
+ };
1301
+ var guard = new Guard(limitsFromEnv());
1302
+
1303
+ // src/captcha/tools.ts
1304
+ var captchaPageTools = [
1305
+ {
1306
+ name: "detect_captcha",
1307
+ description: "Find the captchas in a page's HTML, for a browser of your own. Runs locally: sends nothing, needs no key, free. Returns each one's task type, site key and parameters, whether Browsa's captcha API takes it (status), and what is missing.",
1308
+ inputSchema: {
1309
+ type: "object",
1310
+ required: ["html"],
1311
+ properties: {
1312
+ html: { type: "string", description: "The page's HTML, e.g. document.documentElement.outerHTML." },
1313
+ url: { type: "string", description: "The page's address." },
1314
+ resources: { type: "array", items: { type: "string" }, description: "The page's frame and script URLs; site keys are often only there." }
1315
+ }
1316
+ }
1317
+ },
1318
+ {
1319
+ name: "solve_captcha_on_page",
1320
+ description: "Solve a token captcha that is on a page in your own browser (the catalogue's token types, e.g. Turnstile, reCAPTCHA v2 and v3) through Browsa's captcha API. Returns the solution, its cost, and apply: a JavaScript expression to evaluate in that page (sets the token, calls the page's callback), or cookies to set and re-request with. It does not touch your browser and cannot click. Picture puzzles: send the image to solve_captcha_task. Charged only when solved.",
1321
+ inputSchema: {
1322
+ type: "object",
1323
+ properties: {
1324
+ captcha: { type: "object", description: "One entry of detect_captcha's captchas, or {type, params: {websiteURL, websiteKey, ...}}." },
1325
+ html: { type: "string", description: "Instead of captcha: the page's HTML; detection runs first." },
1326
+ url: { type: "string", description: "With html: the page's address." },
1327
+ resources: { type: "array", items: { type: "string" }, description: "With html: frame and script URLs." },
1328
+ proxy: { type: "string", description: "Your proxy, http://user:pass@host:port, for types that need one (detect_captcha lists it under missing)." },
1329
+ timeout_seconds: { type: "number", description: "Default 180, at most 600." }
1330
+ }
1331
+ }
1332
+ },
1333
+ {
1334
+ name: "captcha_allowance",
1335
+ description: "This server's local captcha limits: credits spent and left under the session cap, rate and concurrency. Free, no request.",
1336
+ inputSchema: { type: "object", properties: {} }
1337
+ }
1338
+ ];
1339
+ var CAPTCHA_PAGE_TOOLS = captchaPageTools.map((t) => t.name);
1340
+ var FAMILY_TYPES = {
1341
+ turnstile: ["AntiTurnstileTaskProxyLess"],
1342
+ recaptcha_v2: ["ReCaptchaV2TaskProxyLess"],
1343
+ recaptcha_v2_enterprise: ["ReCaptchaV2EnterpriseTaskProxyLess"],
1344
+ recaptcha_v3: ["ReCaptchaV3TaskProxyLess"],
1345
+ recaptcha_v3_enterprise: ["ReCaptchaV3EnterpriseTaskProxyLess"],
1346
+ cloudflare: ["AntiCloudflareTask"],
1347
+ geetest_slide: ["GeeTestSlide"],
1348
+ aws_waf: ["AwsWafClassification"],
1349
+ slider: ["VisionEngine"],
1350
+ image_text: ["ImageToTextTask"],
1351
+ altcha: ["AltchaTask"]
1352
+ };
1353
+ function annotate(f, cat) {
1354
+ const info = (FAMILY_TYPES[f.kind] ?? []).map((n) => typeInfo(n, cat)).find(Boolean);
1355
+ const notes = [...f.notes];
1356
+ if (!info) {
1357
+ return {
1358
+ kind: f.kind,
1359
+ name: f.name,
1360
+ type: null,
1361
+ status: "not_in_catalogue",
1362
+ solve_with: null,
1363
+ ready: false,
1364
+ params: f.params,
1365
+ missing: [],
1366
+ confidence: f.confidence,
1367
+ evidence: f.evidence,
1368
+ notes: [...notes, "The captcha API has no task type for this captcha."]
1369
+ };
1370
+ }
1371
+ if (info.status !== "live") notes.push(`This type is switched off in the catalogue${info.offReason ? `: ${info.offReason}` : ""}.`);
1372
+ const token = info.kind === "token";
1373
+ const out = {
1374
+ kind: f.kind,
1375
+ name: f.name,
1376
+ type: info.type,
1377
+ status: info.status,
1378
+ solve_with: token ? "solve_captcha_on_page" : "solve_captcha_task",
1379
+ ready: token && info.status === "live" && f.missing.every((m) => m.startsWith("proxy:")),
1380
+ params: f.params,
1381
+ missing: f.missing,
1382
+ credits_per_solve: info.credits,
1383
+ confidence: f.confidence,
1384
+ evidence: f.evidence
1385
+ };
1386
+ if (Object.keys(f.page).length) out.page = f.page;
1387
+ if (notes.length) out.notes = notes;
1388
+ return out;
1389
+ }
1390
+ function detect(args) {
1391
+ const cat = catalogue();
1392
+ const { findings, truncated } = detectCaptchas({
1393
+ html: String(args.html ?? ""),
1394
+ url: typeof args.url === "string" ? args.url : void 0,
1395
+ resources: Array.isArray(args.resources) ? args.resources.map(String) : void 0
1396
+ });
1397
+ return { captchas: findings.map((f) => annotate(f, cat)), truncated, cat };
1398
+ }
1399
+ var answer = (o) => ({ text: JSON.stringify(o) });
1400
+ var refuse = (message, extra = {}) => ({ isError: true, text: JSON.stringify({ error: message, ...extra }) });
1401
+ function detectTool(args) {
1402
+ if (typeof args.html !== "string" || !args.html.trim()) return refuse("html is required: the page's HTML as text");
1403
+ const { captchas, truncated, cat } = detect(args);
1404
+ return answer({
1405
+ found: captchas.length,
1406
+ captchas,
1407
+ ...captchas.length ? {} : { note: "No captcha in this HTML. A widget inside a frame is only seen through its frame URL: pass resources." },
1408
+ ...truncated ? { truncated: "only the first 3,000,000 characters were read" } : {},
1409
+ catalogue: { source: cat.source, as_of: cat.asOf }
1410
+ });
1411
+ }
1412
+ function limitRefusal(r) {
1413
+ return refuse(`refused by this server's local limit (${r.limit}): ${r.message}`, {
1414
+ code: "LOCAL_LIMIT",
1415
+ limit: r.limit,
1416
+ retry_after_seconds: r.retry_after_seconds,
1417
+ retry: r.retry,
1418
+ charged: false,
1419
+ allowance: guard.allowance()
1420
+ });
1421
+ }
1422
+ async function guardedSolve(price, run) {
1423
+ const g = guard.begin(price);
1424
+ if (!g.ok) return { refused: limitRefusal(g.refusal) };
1425
+ let credits = 0;
1426
+ try {
1427
+ const r = await run();
1428
+ credits = r.credits;
1429
+ return { value: r.value };
1430
+ } finally {
1431
+ g.ticket.done(credits);
1432
+ }
1433
+ }
1434
+ function priceOf(type) {
1435
+ const cat = catalogue();
1436
+ return typeInfo(type, cat)?.credits ?? Math.max(0, ...cat.types.map((t) => t.credits ?? 0));
1437
+ }
1438
+ function chargedCredits(body, type) {
1439
+ const c = body?.cost;
1440
+ if (c && c.charged === false) return 0;
1441
+ if (c && typeof c.credits === "number") return c.credits;
1442
+ if (c && c.unit === "credits" && typeof c.amount === "number") return c.amount;
1443
+ return priceOf(type);
1444
+ }
1445
+ var reportToolListed = false;
1446
+ function setReportToolListed(v) {
1447
+ reportToolListed = v;
1448
+ }
1449
+ async function solveOnPage(args) {
1450
+ await refreshCatalogue();
1451
+ const cat = catalogue();
1452
+ let picked = null;
1453
+ if (args.captcha && typeof args.captcha === "object") {
1454
+ const c = args.captcha;
1455
+ picked = { type: typeof c.type === "string" ? c.type : null, params: { ...c.params ?? {} }, page: c.page, missing: [] };
1456
+ for (const k of ["websiteURL", "websiteKey", "pageAction", "isInvisible", "metadata", "apiDomain", "userAgent"]) {
1457
+ if (c[k] !== void 0 && picked.params[k] === void 0) picked.params[k] = c[k];
1458
+ }
1459
+ if (!picked.type && typeof c.kind === "string") picked.type = (FAMILY_TYPES[c.kind] ?? []).find((n) => typeInfo(n, cat)) ?? null;
1460
+ } else if (typeof args.html === "string" && args.html.trim()) {
1461
+ const { captchas } = detect(args);
1462
+ const tokens = captchas.filter((c) => c.solve_with === "solve_captcha_on_page" && c.status === "live");
1463
+ if (tokens.length !== 1) {
1464
+ return refuse(
1465
+ tokens.length ? "more than one token captcha is in this HTML: pass the one to solve as captcha" : captchas.length ? "no captcha in this HTML can be solved by this tool" : "no captcha was found in this HTML",
1466
+ { code: tokens.length ? "SEVERAL_CAPTCHAS" : captchas.length ? "NOT_SOLVABLE_HERE" : "NO_CAPTCHA", charged: false, captchas }
1467
+ );
1468
+ }
1469
+ picked = { type: tokens[0].type, params: { ...tokens[0].params }, page: tokens[0].page, missing: tokens[0].missing };
1470
+ } else {
1471
+ return refuse("pass captcha (an entry from detect_captcha) or html with url", { charged: false });
1472
+ }
1473
+ if (!picked.type) return refuse("the captcha API has no task type for this captcha", { code: "NOT_IN_CATALOGUE", charged: false });
1474
+ let type = picked.type;
1475
+ const proxy = typeof args.proxy === "string" && args.proxy.trim() ? args.proxy.trim() : picked.params.proxy;
1476
+ if (proxy && /ProxyLess$/i.test(type) && typeInfo(type.replace(/ProxyLess$/i, ""), cat)) type = type.replace(/ProxyLess$/i, "");
1477
+ const info = typeInfo(type, cat);
1478
+ if (!info) {
1479
+ return refuse(
1480
+ `${type} is not a type in the catalogue (names are case-sensitive)`,
1481
+ { code: "NOT_IN_CATALOGUE", charged: false, token_types: cat.types.filter((t) => t.kind === "token" && t.status === "live").map((t) => t.type) }
1482
+ );
1483
+ }
1484
+ if (info.kind !== "token") {
1485
+ return refuse(
1486
+ `${type} is answered from a picture, not from the page's address: send the image with solve_captcha_task`,
1487
+ { code: "NOT_A_TOKEN_TYPE", charged: false, required: [...info.required, ...info.oneOf.map((g) => g.join(" or "))] }
1488
+ );
1489
+ }
1490
+ if (info.status !== "live") {
1491
+ return refuse(`${type} is switched off in the catalogue${info.offReason ? `: ${info.offReason}` : ""}`, { code: "TYPE_OFF", charged: false });
1492
+ }
1493
+ const task = { ...picked.params, type };
1494
+ if (proxy) task.proxy = proxy;
1495
+ const missing = info.required.filter((p) => task[p] === void 0 || task[p] === "");
1496
+ if (missing.length) {
1497
+ return refuse(`${type} needs ${missing.join(", ")}`, {
1498
+ code: "MISSING_PARAMETER",
1499
+ charged: false,
1500
+ missing,
1501
+ ...picked.missing?.length ? { where: picked.missing } : {}
1502
+ });
1503
+ }
1504
+ const timeoutMs = Math.min(Math.max(Number(args.timeout_seconds) || 180, 5), 600) * 1e3;
1505
+ const r = await guardedSolve(priceOf(type), async () => {
1506
+ const o2 = await runCaptchaTask(task, timeoutMs);
1507
+ return { credits: o2.state === "solved" ? chargedCredits(o2.body, type) : 0, value: o2 };
1508
+ });
1509
+ if ("refused" in r) return r.refused;
1510
+ const o = r.value;
1511
+ if (o.state === "error") {
1512
+ const b = o.body;
1513
+ return refuse(b.errorDescription || b.errorCode, {
1514
+ code: b.errorCode,
1515
+ ...b.taskId ? { task_id: b.taskId } : {},
1516
+ charged: b.charged === true,
1517
+ ...b.fix ? { fix: b.fix } : {},
1518
+ allowance: guard.allowance()
1519
+ });
1520
+ }
1521
+ if (o.state === "timeout") {
1522
+ return refuse(
1523
+ `no solution after ${Math.round(o.timeoutMs / 1e3)}s; the task may still finish (charged only if solved)`,
1524
+ { code: "TIMEOUT", task_id: o.taskId, allowance: guard.allowance() }
1525
+ );
1526
+ }
1527
+ const apply = buildApply(type, o.body.solution, String(task.websiteURL ?? ""), picked.page ?? {});
1528
+ return answer({
1529
+ task_id: o.taskId,
1530
+ type,
1531
+ solution: o.body.solution,
1532
+ seconds: o.seconds,
1533
+ cost: o.body.cost ?? { charged: true, credits: chargedCredits(o.body, type), note: "The catalogue's price: the API's answer carried no cost." },
1534
+ apply,
1535
+ allowance: guard.allowance(),
1536
+ next: `do apply.steps in your browser, then check the page's own answer${reportToolListed ? "; then report_captcha_result" : ""}`
1537
+ });
1538
+ }
1539
+ async function callCaptchaPage(name, args) {
1540
+ try {
1541
+ switch (name) {
1542
+ case "detect_captcha":
1543
+ return detectTool(args);
1544
+ case "solve_captcha_on_page":
1545
+ return await solveOnPage(args);
1546
+ case "captcha_allowance":
1547
+ return answer({ ...guard.allowance(), ...guard.configured ? {} : { note: "No local limit is set (BROWSA_CAPTCHA_MAX_CREDITS, BROWSA_CAPTCHA_RATE_PER_MINUTE, BROWSA_CAPTCHA_CONCURRENCY). The workspace's own limits still apply." } });
1548
+ default:
1549
+ return refuse(`unknown tool: ${name}`);
1550
+ }
1551
+ } catch (e) {
1552
+ if (e instanceof BrowsaError2) return refuse(e.message, { code: e.code, status: e.status });
1553
+ const msg = e.message || String(e);
1554
+ if (e?.name === "TimeoutError" || /fetch failed|network|ECONN|ENOTFOUND|EAI_AGAIN/i.test(msg)) {
1555
+ return refuse(`could not reach the captcha API (${msg}); try again when the network is back`, { code: "NETWORK", allowance: guard.allowance() });
1556
+ }
1557
+ return refuse(msg);
1558
+ }
1559
+ }
1560
+
1561
+ // src/annotations.ts
1562
+ var read = (title, extra = {}) => ({ title, readOnlyHint: true, destructiveHint: false, ...extra });
1563
+ var write = (title, extra = {}) => ({ title, readOnlyHint: false, destructiveHint: false, ...extra });
1564
+ var destructive = (title, extra = {}) => ({ title, readOnlyHint: false, destructiveHint: true, ...extra });
1565
+ var ANNOTATIONS = {
1566
+ // core
1567
+ open: write("Open a browser"),
1568
+ observe: read("Read the page as text"),
1569
+ act: destructive("Act on the page"),
1570
+ read: read("Read a container"),
1571
+ screenshot: read("Take a screenshot"),
1572
+ secrets: read("List saved secrets"),
1573
+ handoff: write("Hand over to a person"),
1574
+ flow: destructive("Record or replay a flow"),
1575
+ close: destructive("Close the browser", { idempotentHint: true }),
1576
+ // tasks
1577
+ run_task: destructive("Run an agent task"),
1578
+ get_job: read("Get a job"),
1579
+ cancel_job: destructive("Cancel a job", { idempotentHint: true }),
1580
+ respond_to_job: write("Answer a job's question"),
1581
+ list_job_files: read("List a job's files"),
1582
+ // robots
1583
+ list_robots: read("List robots"),
1584
+ run_robot: destructive("Run a robot"),
1585
+ get_robot_run: read("Get a robot run"),
1586
+ // schedules
1587
+ create_schedule: write("Create a schedule"),
1588
+ list_schedules: read("List schedules"),
1589
+ // webhooks
1590
+ list_webhooks: read("List webhooks"),
1591
+ create_webhook: write("Create a webhook"),
1592
+ delete_webhook: destructive("Delete a webhook", { idempotentHint: true }),
1593
+ // cdp
1594
+ start_browser: write("Start a browser for CDP"),
1595
+ stop_browser: destructive("Stop a browser", { idempotentHint: true }),
1596
+ // captcha
1597
+ solve_captcha_task: write("Solve a captcha task"),
1598
+ list_captcha_types: read("List captcha types"),
1599
+ report_captcha_result: write("Report a captcha result"),
1600
+ // captcha_page
1601
+ detect_captcha: read("Find the captcha in a page", { idempotentHint: true, openWorldHint: false }),
1602
+ solve_captcha_on_page: write("Solve a captcha for your browser"),
1603
+ captcha_allowance: read("Captcha allowance left", { openWorldHint: false }),
1604
+ // admin
1605
+ credits: read("Credit balance"),
1606
+ list_browsers: read("List browsers"),
1607
+ list_identities: read("List identities"),
1608
+ proxy_network: read("Proxy network"),
1609
+ list_llm_keys: read("List saved LLM keys"),
1610
+ list_models: read("List models")
1611
+ };
1612
+ function annotate2(tool) {
1613
+ const a = ANNOTATIONS[tool.name];
1614
+ if (!a) throw new Error(`tool ${tool.name} has no annotations (src/annotations.ts)`);
1615
+ return { ...tool, annotations: a };
48
1616
  }
49
1617
 
50
1618
  // src/api.ts
51
- import { BrowsaError } from "browsa";
1619
+ import { BrowsaError as BrowsaError3 } from "browsa";
52
1620
  function headers(json) {
53
1621
  const h = { "X-API-Key": API_KEY ?? "", Accept: "application/json", "User-Agent": `browsa-mcp/${VERSION}` };
54
1622
  if (json) h["Content-Type"] = "application/json";
@@ -57,7 +1625,7 @@ function headers(json) {
57
1625
  async function parse(resp) {
58
1626
  const body = await resp.json().catch(() => ({}));
59
1627
  if (!resp.ok) {
60
- throw new BrowsaError(body?.error || body?.message || `HTTP ${resp.status}`, {
1628
+ throw new BrowsaError3(body?.error || body?.message || `HTTP ${resp.status}`, {
61
1629
  code: body?.code ?? `HTTP_${resp.status}`,
62
1630
  requestId: body?.request_id,
63
1631
  status: resp.status
@@ -66,18 +1634,26 @@ async function parse(resp) {
66
1634
  return body;
67
1635
  }
68
1636
  async function apiGet(path, timeoutMs = 9e4) {
69
- return parse(await fetch(`${BASE_URL}${path}`, { headers: headers(false), signal: AbortSignal.timeout(timeoutMs) }));
1637
+ return parse(await fetchRetry(
1638
+ `${BASE_URL}${path}`,
1639
+ () => ({ headers: headers(false), signal: AbortSignal.timeout(timeoutMs) }),
1640
+ { idempotent: true }
1641
+ ));
70
1642
  }
71
1643
  async function apiPost(path, payload, timeoutMs = 9e4) {
72
- return parse(await fetch(`${BASE_URL}${path}`, {
1644
+ return parse(await fetchRetry(`${BASE_URL}${path}`, () => ({
73
1645
  method: "POST",
74
1646
  headers: headers(true),
75
1647
  body: JSON.stringify(payload ?? {}),
76
1648
  signal: AbortSignal.timeout(timeoutMs)
77
- }));
1649
+ }), { idempotent: false }));
78
1650
  }
79
1651
  async function apiDelete(path, timeoutMs = 3e4) {
80
- return parse(await fetch(`${BASE_URL}${path}`, { method: "DELETE", headers: headers(false), signal: AbortSignal.timeout(timeoutMs) }));
1652
+ return parse(await fetchRetry(
1653
+ `${BASE_URL}${path}`,
1654
+ () => ({ method: "DELETE", headers: headers(false), signal: AbortSignal.timeout(timeoutMs) }),
1655
+ { idempotent: true }
1656
+ ));
81
1657
  }
82
1658
 
83
1659
  // src/flow.ts
@@ -493,7 +2069,7 @@ function forget(id) {
493
2069
  }
494
2070
  function explain(e, tool, browserId) {
495
2071
  if (e instanceof ToolError) return e.message;
496
- if (!(e instanceof BrowsaError)) {
2072
+ if (!(e instanceof BrowsaError3)) {
497
2073
  const msg = e?.name === "TimeoutError" ? "the API did not answer in time" : e?.message || String(e);
498
2074
  return `error: ${msg}
499
2075
  next: try again; if it keeps failing, observe to see the page`;
@@ -517,7 +2093,7 @@ next: ${s}`;
517
2093
  case code === "STALE":
518
2094
  return next("the page changed; call observe and use the new ids");
519
2095
  case (e.status === 401 || code === "INVALID_API_KEY" || code === "MISSING_API_KEY"):
520
- return next(`BROWSA_API_KEY was refused; mint a key at ${KEYS_URL} and restart the server`);
2096
+ return next(`BROWSA_API_KEY was refused; create a key at ${KEYS_URL} and restart the server`);
521
2097
  case (e.status === 402 || /CREDIT/.test(code)):
522
2098
  return next("not enough credits; top up at https://app.browsa.io/dashboard/billing");
523
2099
  case e.status === 429:
@@ -700,7 +2276,7 @@ flow: ${n}`;
700
2276
  function tsv(cells) {
701
2277
  return cells.map((c) => String(c ?? "").replace(/[\t\r\n]+/g, " ")).join(" ");
702
2278
  }
703
- async function read(args) {
2279
+ async function read2(args) {
704
2280
  const b = browserOf(args);
705
2281
  const id = Math.floor(Number(args.id));
706
2282
  if (!id) throw new ToolError("error: id is required\nnext: an id of a container from observe");
@@ -781,7 +2357,7 @@ async function secrets() {
781
2357
  try {
782
2358
  body = await apiGet("/v1/secrets");
783
2359
  } catch (e) {
784
- if (e instanceof BrowsaError && (e.status === 404 || e.status === 503 || e.status === 405)) {
2360
+ if (e instanceof BrowsaError3 && (e.status === 404 || e.status === 503 || e.status === 405)) {
785
2361
  return "secrets: not available on this Browsa server yet\nnext: type values yourself, or call handoff for a login";
786
2362
  }
787
2363
  throw e;
@@ -927,7 +2503,7 @@ async function close(args) {
927
2503
  try {
928
2504
  await apiDelete(`/v1/agents/${encodeURIComponent(b.id)}`);
929
2505
  } catch (e) {
930
- if (!(e instanceof BrowsaError && (e.status === 404 || e.code === "AGENT_NOT_RUNNING"))) throw e;
2506
+ if (!(e instanceof BrowsaError3 && (e.status === 404 || e.code === "AGENT_NOT_RUNNING"))) throw e;
931
2507
  }
932
2508
  forget(b.id);
933
2509
  return `ok: closed ${b.id}${dropped}`;
@@ -943,7 +2519,7 @@ async function callCore(name, args) {
943
2519
  case "act":
944
2520
  return { text: await act(args) };
945
2521
  case "read":
946
- return { text: await read(args) };
2522
+ return { text: await read2(args) };
947
2523
  case "screenshot":
948
2524
  return await screenshot(args);
949
2525
  case "secrets":
@@ -963,7 +2539,6 @@ async function callCore(name, args) {
963
2539
 
964
2540
  // src/legacy.ts
965
2541
  import { Client } from "browsa";
966
- var CAPTCHA_URL = (process.env.BROWSA_CAPTCHA_URL || (BASE_URL_SET ? `${BASE_URL}/captcha-api` : "https://captcha.browsa.io")).replace(/\/+$/, "");
967
2542
  var DEFAULT_LLM = process.env.BROWSA_LLM || void 0;
968
2543
  var BYOK_DEFAULT_LLM = "claude-opus-5-5";
969
2544
  var DEFAULT_LLM_KEY = process.env.BROWSA_LLM_API_KEY || void 0;
@@ -1275,7 +2850,7 @@ var legacyTools = [
1275
2850
  },
1276
2851
  {
1277
2852
  name: "report_captcha_result",
1278
- description: "Tell Browsa whether the site accepted a solution from solve_captcha_task: correct=true records that it worked, correct=false that the site refused it. Reports are recorded and used to improve solving. A task can be reported once, within 15 minutes of the solve. Report only what the site itself answered.",
2853
+ description: "Tell Browsa whether the site accepted a solution from solve_captcha_task: correct=true records that it worked, correct=false that the site refused it. An incorrect report refunds that solve once, within the workspace's report limits; the answer says whether it did (refunded). A task can be reported once, within 15 minutes of the solve. Report only what the site itself answered.",
1279
2854
  inputSchema: {
1280
2855
  type: "object",
1281
2856
  required: ["task_id", "correct"],
@@ -1320,7 +2895,7 @@ async function submitWithHostedFallback(choice, submit) {
1320
2895
  try {
1321
2896
  return { result: await submit(choice), fellBack: false };
1322
2897
  } catch (e) {
1323
- if (e instanceof BrowsaError && canFallBackToHosted(e, choice)) {
2898
+ if (e instanceof BrowsaError3 && canFallBackToHosted(e, choice)) {
1324
2899
  return { result: await submit(HOSTED), fellBack: true };
1325
2900
  }
1326
2901
  throw e;
@@ -1355,7 +2930,7 @@ async function proxyNetwork() {
1355
2930
  const body = await resp.json().catch(() => ({}));
1356
2931
  if (resp.status === 404) return { enabled: false, tiers: [] };
1357
2932
  if (!resp.ok) {
1358
- throw new BrowsaError(body?.error || `HTTP ${resp.status}`, { code: body?.code, requestId: body?.request_id, status: resp.status });
2933
+ throw new BrowsaError3(body?.error || `HTTP ${resp.status}`, { code: body?.code, requestId: body?.request_id, status: resp.status });
1359
2934
  }
1360
2935
  const tiers = body?.enabled === true && Array.isArray(body?.tiers) ? body.tiers : [];
1361
2936
  return {
@@ -1505,64 +3080,43 @@ var CAPTCHA_ALIASES = {
1505
3080
  imagetotexttask: ["ImageToTextTask", "ImageToTextTask"],
1506
3081
  recaptchav2classification: ["ReCaptchaV2Classification", "ReCaptchaV2Classification"]
1507
3082
  };
1508
- async function captchaCall(method, payload) {
1509
- const resp = await fetch(`${CAPTCHA_URL}/${method}`, payload === null ? { method: "GET", headers: { Accept: "application/json", "User-Agent": "browsa-mcp" }, signal: AbortSignal.timeout(3e4) } : {
1510
- method: "POST",
1511
- headers: { "Content-Type": "application/json", Accept: "application/json", "User-Agent": "browsa-mcp" },
1512
- body: JSON.stringify({ clientKey: API_KEY, ...payload }),
1513
- signal: AbortSignal.timeout(3e4)
1514
- });
1515
- const body = await resp.json().catch(() => null);
1516
- if (!body || typeof body !== "object" || !("errorId" in body)) {
1517
- throw new BrowsaError(`captcha API: unexpected answer (HTTP ${resp.status})`, { code: `HTTP_${resp.status}`, status: resp.status });
1518
- }
1519
- return body;
1520
- }
1521
3083
  async function solveCaptchaTask(args) {
1522
3084
  const task = { ...args.task ?? {} };
1523
3085
  if (typeof task.type !== "string" || !task.type) return fail("task.type is required");
1524
3086
  const pair = CAPTCHA_ALIASES[task.type.toLowerCase()];
1525
3087
  if (pair) task.type = task.proxy || task.proxyAddress ? pair[1] : pair[0];
1526
3088
  const timeoutMs = Math.min(Math.max(Number(args.timeout_seconds) || 180, 5), 600) * 1e3;
1527
- const failed = (b) => fail(b.errorDescription || b.errorCode, {
1528
- code: b.errorCode,
1529
- task_id: b.taskId,
1530
- charged: b.charged === true,
1531
- ...b.fix ? { fix: b.fix } : {},
1532
- ...b.errorCode === "ERROR_TASK_NOT_SUPPORTED" ? { measured_types: "https://browsa.io/captcha", next: "call list_captcha_types for the type names and their parameters" } : {}
3089
+ const r = await guardedSolve(priceOf(task.type), async () => {
3090
+ const o2 = await runCaptchaTask(task, timeoutMs);
3091
+ return { credits: o2.state === "solved" ? chargedCredits(o2.body, task.type) : 0, value: o2 };
1533
3092
  });
1534
- const started = Date.now();
1535
- const deadline = started + timeoutMs;
1536
- const hold = () => Math.max(0, Math.min(CAPTCHA_WAIT_S, Math.floor((deadline - Date.now()) / 1e3)));
1537
- const solved = (b) => ok({
1538
- task_id: created.taskId,
3093
+ if ("refused" in r) return { isError: true, content: [{ type: "text", text: r.refused.text }] };
3094
+ const o = r.value;
3095
+ if (o.state === "error") {
3096
+ const b = o.body;
3097
+ return fail(b.errorDescription || b.errorCode, {
3098
+ code: b.errorCode,
3099
+ task_id: b.taskId,
3100
+ charged: b.charged === true,
3101
+ ...b.fix ? { fix: b.fix } : {},
3102
+ ...b.errorCode === "ERROR_TASK_NOT_SUPPORTED" ? { measured_types: "https://browsa.io/captcha", next: "call list_captcha_types for the type names and their parameters" } : {}
3103
+ });
3104
+ }
3105
+ if (o.state === "timeout") {
3106
+ return fail(
3107
+ `no solution after ${Math.round(timeoutMs / 1e3)}s; the task may still finish (charged only if solved)`,
3108
+ { code: "TIMEOUT", task_id: o.taskId }
3109
+ );
3110
+ }
3111
+ return ok({
3112
+ task_id: o.taskId,
1539
3113
  type: task.type,
1540
- solution: b.solution,
1541
- seconds: typeof b.solveSeconds === "number" ? b.solveSeconds : Math.round((Date.now() - started) / 100) / 10,
1542
- ...b.cost ? { cost: b.cost } : {},
3114
+ solution: o.body.solution,
3115
+ seconds: o.seconds,
3116
+ ...o.body.cost ? { cost: o.body.cost } : {},
1543
3117
  next: "when the site has answered, call report_captcha_result with correct=true or correct=false"
1544
3118
  });
1545
- const created = await captchaCall("createTask", { task, ...hold() ? { waitSeconds: hold() } : {} });
1546
- if (created.errorId) return failed(created);
1547
- if (created.status === "ready" && created.solution) return solved(created);
1548
- while (Date.now() < deadline) {
1549
- const wait = hold();
1550
- if (!wait) await new Promise((r2) => setTimeout(r2, Math.min(CAPTCHA_POLL_MS, Math.max(0, deadline - Date.now()))));
1551
- const asked = Date.now();
1552
- const r = await captchaCall("getTaskResult", { taskId: created.taskId, ...wait ? { waitSeconds: wait } : {} });
1553
- if (r.errorId) return failed(r);
1554
- if (r.status === "ready") return solved(r);
1555
- if (wait && Date.now() - asked < 1e3) {
1556
- await new Promise((res) => setTimeout(res, Math.min(CAPTCHA_POLL_MS, Math.max(0, deadline - Date.now()))));
1557
- }
1558
- }
1559
- return fail(
1560
- `no solution after ${Math.round(timeoutMs / 1e3)}s; the task may still finish (charged only if solved)`,
1561
- { code: "TIMEOUT", task_id: created.taskId }
1562
- );
1563
3119
  }
1564
- var CAPTCHA_POLL_MS = Number(process.env.BROWSA_CAPTCHA_POLL_MS) || 3e3;
1565
- var CAPTCHA_WAIT_S = 20;
1566
3120
  async function listCaptchaTypes(args) {
1567
3121
  const r = await captchaCall("types", null);
1568
3122
  if (r.errorId || !Array.isArray(r.types)) return fail(r.errorDescription || "the type catalogue is not available", { code: r.errorCode });
@@ -1778,7 +3332,7 @@ async function callLegacy(name, args) {
1778
3332
  return fail(`unknown tool: ${name}`);
1779
3333
  }
1780
3334
  } catch (e) {
1781
- if (e instanceof BrowsaError) {
3335
+ if (e instanceof BrowsaError3) {
1782
3336
  const keyErr = choice ? llmKeyError(e, choice) : null;
1783
3337
  if (keyErr) return keyErr;
1784
3338
  return fail(e.message, {
@@ -1791,6 +3345,67 @@ async function callLegacy(name, args) {
1791
3345
  }
1792
3346
  }
1793
3347
 
3348
+ // src/prompts.ts
3349
+ var PROMPTS = [
3350
+ {
3351
+ name: "solve_captcha_on_my_page",
3352
+ title: "Solve the captcha on my current page",
3353
+ description: "For a browser of your own: detect the captcha, solve it, apply the answer, verify.",
3354
+ arguments: [{ name: "url", description: "The page, when it is not the one already open." }],
3355
+ needs: ["detect_captcha", "solve_captcha_on_page"],
3356
+ text: (a) => [
3357
+ `Solve the captcha on ${a.url ? `the page ${a.url}` : "the page that is open in my browser"}, using my own browser tools for the page and Browsa's tools for the captcha.`,
3358
+ "",
3359
+ "1. Detect. With my browser tools, read the page's address, its HTML (document.documentElement.outerHTML) and the URLs of its frames and scripts. Call detect_captcha with html, url and resources. It runs locally and is free.",
3360
+ "2. Decide. Take the entry with ready true. If none is ready, tell me what its missing list asks for, or that the type is not in the catalogue, and stop. An entry with solve_with solve_captcha_task is a picture puzzle: this recipe does not cover it.",
3361
+ "3. Solve. Call solve_captcha_on_page with that entry as captcha (add proxy when the entry asks for one). Note cost in the answer. On a refusal with code LOCAL_LIMIT, wait retry_after_seconds, or stop when it is null.",
3362
+ "4. Apply. Do apply.steps in my browser: evaluate apply.expression in the page's main frame, or set apply.cookies and request the page again. Do not reload the page between solving and applying.",
3363
+ "5. Verify. Read the page again: say whether the site accepted the answer, quoting what the page shows. If it refused, solve once more at most, then stop and tell me.",
3364
+ "",
3365
+ "Report: the captcha type, whether the site accepted it, the credits it cost, and the allowance left."
3366
+ ].join("\n")
3367
+ },
3368
+ {
3369
+ name: "what_captcha_is_this",
3370
+ title: "What captcha is on this page?",
3371
+ description: "Detect only: which captcha a page has, and whether Browsa's captcha API takes it. Free.",
3372
+ arguments: [{ name: "url", description: "The page, when it is not the one already open." }],
3373
+ needs: ["detect_captcha"],
3374
+ text: (a) => [
3375
+ `Tell me which captcha is on ${a.url ? `the page ${a.url}` : "the page that is open in my browser"}. Solve nothing and spend nothing.`,
3376
+ "",
3377
+ "With my browser tools, read the page's address, its HTML and the URLs of its frames and scripts, then call detect_captcha with html, url and resources.",
3378
+ "For each entry say: the provider's name, the task type, its status in the catalogue, the price per solve, what is missing, and how sure the detection is (confidence, evidence). If nothing is found, say so and say that a widget inside a frame only shows through its frame URL."
3379
+ ].join("\n")
3380
+ },
3381
+ {
3382
+ name: "pass_check_in_browsa_browser",
3383
+ title: "Get past a check in a Browsa browser",
3384
+ description: "For a Browsa cloud browser: open the page, solve the check in place, hand over to a person if it stays.",
3385
+ arguments: [{ name: "url", description: "The page to open.", required: true }],
3386
+ needs: ["open", "act", "observe", "handoff"],
3387
+ text: (a) => [
3388
+ `Open ${a.url || "the page"} in a Browsa browser and get to its real content.`,
3389
+ "",
3390
+ "1. open the url. Read the first view.",
3391
+ "2. If an act or observe answer starts with challenge, call act with action solve_captcha once, then observe.",
3392
+ "3. If the check is still there, call handoff with the reason and give me the link; continue when the next observe says the page moved on.",
3393
+ "4. Tell me what the page shows now, then close the browser unless I asked to keep it."
3394
+ ].join("\n")
3395
+ }
3396
+ ];
3397
+ function listPrompts(listed2) {
3398
+ return PROMPTS.filter((p) => p.needs.every((t) => listed2.has(t))).map(({ name, title, description, arguments: args }) => ({ name, title, description, ...args ? { arguments: args } : {} }));
3399
+ }
3400
+ function getPrompt(name, args, listed2) {
3401
+ const p = PROMPTS.find((x) => x.name === name && x.needs.every((t) => listed2.has(t)));
3402
+ if (!p) return null;
3403
+ return {
3404
+ description: p.description,
3405
+ messages: [{ role: "user", content: { type: "text", text: p.text(args ?? {}) } }]
3406
+ };
3407
+ }
3408
+
1794
3409
  // src/redact.ts
1795
3410
  var SENSITIVE = /^(?:.*[_.-])?(?:token|access_?token|refresh_?token|id_?token|auth|authorization|key|api_?key|apikey|secret|client_?secret|password|passwd|pwd|pass|session|session_?id|sessionid|sid|jsessionid|phpsessid|code|otp|ticket|signature|sig|credential|jwt|assertion|saml_?response|nonce)(?:[_.-].*)?$/i;
1796
3411
  var SAFE = /* @__PURE__ */ new Set(["country_code", "countrycode", "zip_code", "zipcode", "postal_code", "postcode", "currency_code", "lang_code", "keyword", "keywords", "keys", "token_type", "key_type"]);
@@ -1815,18 +3430,33 @@ function redactUrls(text) {
1815
3430
  }
1816
3431
 
1817
3432
  // src/server.ts
1818
- if (!API_KEY) {
1819
- console.error("[browsa-mcp] BROWSA_API_KEY is not set: tools are listed, but every call will fail until it is.");
1820
- console.error(` Mint one at ${KEYS_URL}`);
3433
+ var FLAG = cliFlag();
3434
+ if (!FLAG && !API_KEY) {
3435
+ console.error("[browsa-mcp] BROWSA_API_KEY is not set: tools are listed, but calls that reach Browsa will fail until it is.");
3436
+ console.error(` Create a key at ${KEYS_URL}`);
1821
3437
  }
1822
3438
  var extras = enabledExtras();
1823
- for (const w of extras.unknown) {
3439
+ for (const w of FLAG ? [] : extras.unknown) {
1824
3440
  console.error(`[browsa-mcp] BROWSA_MCP_TOOLS: unknown group or tool "${w}" (groups: ${Object.keys(GROUPS).join(", ")}, all)`);
1825
3441
  }
1826
- var tools = [...coreTools, ...legacyTools.filter((t) => extras.tools.has(t.name))];
3442
+ var tools = [
3443
+ ...coreTools.filter((t) => extras.core.has(t.name)),
3444
+ ...captchaPageTools.filter((t) => extras.tools.has(t.name)),
3445
+ ...legacyTools.filter((t) => extras.tools.has(t.name))
3446
+ ].map((t) => annotate2(t));
1827
3447
  var listed = new Set(tools.map((t) => t.name));
1828
- var server = new Server({ name: "browsa", version: VERSION }, { capabilities: { tools: {} } });
3448
+ setReportToolListed(listed.has("report_captcha_result"));
3449
+ var server = new Server(
3450
+ { name: "browsa", title: "Browsa", version: VERSION },
3451
+ { capabilities: { tools: {}, prompts: {} }, instructions: INSTRUCTIONS }
3452
+ );
1829
3453
  server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools }));
3454
+ server.setRequestHandler(ListPromptsRequestSchema, async () => ({ prompts: listPrompts(listed) }));
3455
+ server.setRequestHandler(GetPromptRequestSchema, async (req) => {
3456
+ const p = getPrompt(req.params.name, req.params.arguments ?? {}, listed);
3457
+ if (!p) throw new Error(`unknown prompt: ${req.params.name}`);
3458
+ return p;
3459
+ });
1830
3460
  var clean = (s) => REDACT ? redactUrls(s) : s;
1831
3461
  server.setRequestHandler(CallToolRequestSchema, async (req) => {
1832
3462
  const name = req.params.name;
@@ -1834,10 +3464,15 @@ server.setRequestHandler(CallToolRequestSchema, async (req) => {
1834
3464
  if (!listed.has(name)) {
1835
3465
  const group = Object.entries(GROUPS).find(([, t]) => t.includes(name))?.[0];
1836
3466
  const text = group ? `error: ${name} is in the optional group "${group}"
1837
- next: set BROWSA_MCP_TOOLS=${group} (or all) in this server's env and restart it` : `error: unknown tool ${name}`;
3467
+ next: set BROWSA_MCP_TOOLS=${group} (or all) in this server's env and restart it` : CORE_TOOLS.includes(name) ? `error: ${name} is a core tool and the core tools are switched off
3468
+ next: take "-core" out of BROWSA_MCP_TOOLS in this server's env and restart it` : `error: unknown tool ${name}`;
1838
3469
  return { isError: true, content: [{ type: "text", text }] };
1839
3470
  }
1840
- if (!API_KEY) return { isError: true, content: [{ type: "text", text: NO_KEY_MESSAGE }] };
3471
+ if (!API_KEY && !NO_KEY_TOOLS.includes(name)) return { isError: true, content: [{ type: "text", text: NO_KEY_MESSAGE }] };
3472
+ if (CAPTCHA_PAGE_TOOLS.includes(name)) {
3473
+ const r2 = await callCaptchaPage(name, args);
3474
+ return { ...r2.isError ? { isError: true } : {}, content: [{ type: "text", text: clean(r2.text) }] };
3475
+ }
1841
3476
  if (CORE_TOOLS.includes(name)) {
1842
3477
  const r2 = await callCore(name, args);
1843
3478
  const content = [];
@@ -1852,9 +3487,16 @@ next: set BROWSA_MCP_TOOLS=${group} (or all) in this server's env and restart it
1852
3487
  async function main() {
1853
3488
  const transport = new StdioServerTransport();
1854
3489
  await server.connect(transport);
3490
+ if (GROUPS.captcha_page.some((t) => listed.has(t))) void refreshCatalogue();
1855
3491
  console.error(`[browsa-mcp] ${VERSION} ready (tools=${tools.length})`);
1856
3492
  }
1857
- main().catch((e) => {
1858
- console.error("[browsa-mcp] fatal:", e);
1859
- process.exit(1);
1860
- });
3493
+ if (FLAG === "version") {
3494
+ console.log(VERSION);
3495
+ } else if (FLAG === "help") {
3496
+ console.log(HELP);
3497
+ } else {
3498
+ main().catch((e) => {
3499
+ console.error("[browsa-mcp] fatal:", e);
3500
+ process.exit(1);
3501
+ });
3502
+ }