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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
"""
Main Firecrawl v2 API client.

This module provides the main client class that orchestrates all v2 functionality.
"""

import os
from pathlib import Path
from typing import Optional, List, Dict, Any, Callable, Union, Literal, BinaryIO
from .types import (
    ClientConfig,
    ParseOptions,
    ScrapeOptions,
    Document,
    SearchRequest,
    SearchData,
    SourceOption,
    CategoryOption,
    CrawlRequest,
    CrawlResponse,
    CrawlJob,
    CrawlParamsRequest,
    PDFParser,
    CrawlParamsData,
    WebhookConfig,
    AgentWebhookConfig,
    MonitorWebhookConfig,
    CrawlErrorsResponse,
    ActiveCrawlsResponse,
    MapOptions,
    MapData,
    FormatOption,
    WaitAction,
    ScreenshotAction,
    ClickAction,
    WriteAction,
    PressAction,
    ScrollAction,
    ScrapeAction,
    ExecuteJavascriptAction,
    PDFAction,
    Location,
    PaginationConfig,
    AgentOptions,
    Monitor,
    MonitorCheck,
    MonitorCheckDetail,
    MonitorCreateRequest,
    MonitorNotification,
    MonitorSchedule,
    MonitorTarget,
    MonitorUpdateRequest,
)
from .utils.http_client import HttpClient
from .utils.error_handler import FirecrawlError
from .methods import scrape as scrape_module
from .methods import parse as parse_module
from .methods import crawl as crawl_module  
from .methods import batch as batch_module
from .methods import search as search_module
from .methods import map as map_module
from .methods import batch as batch_methods
from .methods import usage as usage_methods
from .methods import extract as extract_module
from .methods import agent as agent_module
from .methods import browser as browser_module
from .methods import monitor as monitor_module
from .watcher import Watcher

# Kwargs that map to ScrapeOptions fields. Used by async crawl normalization
# to extract scrape kwargs from **kwargs before building CrawlRequest.
# Does not include "integration" (crawl-level param, not a scrape option).
_SCRAPE_OPTION_KEYS = frozenset({
    "formats", "headers", "include_tags", "exclude_tags",
    "only_main_content", "timeout", "wait_for", "mobile",
    "parsers", "actions", "location", "skip_tls_verification",
    "remove_base64_images", "fast_mode", "use_mock", "block_ads",
    "proxy", "max_age", "store_in_cache", "lockdown", "profile",
})


class FirecrawlClient:
    """
    Main Firecrawl v2 API client.

    This client provides a clean, modular interface to all Firecrawl functionality.
    """

    @staticmethod
    def _is_cloud_service(url: str) -> bool:
        return "api.firecrawl.dev" in url.lower()

    def __init__(
        self,
        api_key: Optional[str] = None,
        api_url: str = "https://api.firecrawl.dev",
        timeout: Optional[float] = None,
        max_retries: int = 3,
        backoff_factor: float = 0.5
    ):
        """
        Initialize the Firecrawl client.

        Args:
            api_key: Firecrawl API key (or set FIRECRAWL_API_KEY env var)
            api_url: Base URL for the Firecrawl API
            timeout: Request timeout in seconds
            max_retries: Maximum number of retries for failed requests
            backoff_factor: Exponential backoff factor for retries (e.g. 0.5 means wait 0.5s, then 1s, then 2s between retries)
        """
        if api_key is None:
            api_key = os.getenv("FIRECRAWL_API_KEY")

        if self._is_cloud_service(api_url) and not api_key:
            raise ValueError(
                "API key is required for the cloud API. Set FIRECRAWL_API_KEY environment variable "
                "or pass api_key parameter."
            )

        self.config = ClientConfig(
            api_key=api_key,
            api_url=api_url,
            timeout=timeout,
            max_retries=max_retries,
            backoff_factor=backoff_factor
        )

        self.http_client = HttpClient(
            api_key,
            api_url,
            timeout=timeout,
            max_retries=max_retries,
            backoff_factor=backoff_factor,
        )
    
    def scrape(
        self,
        url: str,
        *,
        formats: Optional[List['FormatOption']] = None,
        headers: Optional[Dict[str, str]] = None,
        include_tags: Optional[List[str]] = None,
        exclude_tags: Optional[List[str]] = None,
        only_main_content: Optional[bool] = None,
        timeout: Optional[int] = None,
        wait_for: Optional[int] = None,
        mobile: Optional[bool] = None,
        parsers: Optional[Union[List[str], List[Union[str, PDFParser]]]] = None,
        actions: Optional[List[Union['WaitAction', 'ScreenshotAction', 'ClickAction', 'WriteAction', 'PressAction', 'ScrollAction', 'ScrapeAction', 'ExecuteJavascriptAction', 'PDFAction']]] = None,
        location: Optional['Location'] = None,
        skip_tls_verification: Optional[bool] = None,
        remove_base64_images: Optional[bool] = None,
        fast_mode: Optional[bool] = None,
        use_mock: Optional[str] = None,
        block_ads: Optional[bool] = None,
        proxy: Optional[str] = None,
        max_age: Optional[int] = None,
        store_in_cache: Optional[bool] = None,
        lockdown: Optional[bool] = None,
        profile: Optional[Dict[str, Any]] = None,
        integration: Optional[str] = None,
    ) -> Document:
        """
        Scrape a single URL and return the document.
        Args:
            url: URL to scrape
            formats: List of formats to scrape
            headers: Dictionary of headers to use
            include_tags: List of tags to include
            exclude_tags: List of tags to exclude
            only_main_content: Whether to only scrape the main content
            timeout: Timeout in milliseconds
            wait_for: Wait for a specific element to be present
            mobile: Whether to use mobile mode
            parsers: List of parsers to use
            actions: List of actions to perform
            location: Location to scrape
            skip_tls_verification: Whether to skip TLS verification
            remove_base64_images: Whether to remove base64 images
            fast_mode: Whether to use fast mode
            use_mock: Whether to use mock mode
            block_ads: Whether to block ads
            proxy: Proxy to use
            max_age: Maximum age of the cache
            store_in_cache: Whether to store the result in the cache
            lockdown: Serve only previously cached results; never make outbound requests. Returns 404 SCRAPE_LOCKDOWN_CACHE_MISS on cache miss.
            profile: Browser profile for persistent state (e.g. {"name": "my-profile", "saveChanges": True})
        Returns:
            Document
        """
        options = ScrapeOptions(
            **{k: v for k, v in dict(
                formats=formats,
                headers=headers,
                include_tags=include_tags,
                exclude_tags=exclude_tags,
                only_main_content=only_main_content,
                timeout=timeout,
                wait_for=wait_for,
                mobile=mobile,
                parsers=parsers,
                actions=actions,
                location=location,
                skip_tls_verification=skip_tls_verification,
                remove_base64_images=remove_base64_images,
                fast_mode=fast_mode,
                use_mock=use_mock,
                block_ads=block_ads,
                proxy=proxy,
                max_age=max_age,
                store_in_cache=store_in_cache,
                lockdown=lockdown,
                profile=profile,
                integration=integration,
            ).items() if v is not None}
        ) if any(v is not None for v in [formats, headers, include_tags, exclude_tags, only_main_content, timeout, wait_for, mobile, parsers, actions, location, skip_tls_verification, remove_base64_images, fast_mode, use_mock, block_ads, proxy, max_age, store_in_cache, lockdown, profile, integration]) else None
        return scrape_module.scrape(self.http_client, url, options)

    def interact(
        self,
        job_id: str,
        code: Optional[str] = None,
        *,
        prompt: Optional[str] = None,
        language: Literal["python", "node", "bash"] = "node",
        timeout: Optional[int] = None,
        origin: Optional[str] = None,
    ):
        """
        Interact with the browser session associated with a scrape job.

        Either ``code`` or ``prompt`` must be provided.

        Args:
            job_id: Scrape job ID
            code: Code to execute (optional if prompt is provided)
            prompt: Natural-language instruction for the browser agent (optional if code is provided)
            language: Programming language ("python", "node", or "bash")
            timeout: Execution timeout in seconds (1-300)
            origin: Optional request origin tag

        Returns:
            BrowserExecuteResponse with execution result
        """
        return scrape_module.interact(
            self.http_client,
            job_id,
            code,
            prompt=prompt,
            language=language,
            timeout=timeout,
            origin=origin,
        )

    def stop_interaction(self, job_id: str):
        """
        Stop the interaction session associated with a scrape job.

        Args:
            job_id: Scrape job ID

        Returns:
            BrowserDeleteResponse
        """
        return scrape_module.stop_interaction(self.http_client, job_id)

    def stop_interactive_browser(self, job_id: str):
        """Deprecated alias for stop_interaction()."""
        return self.stop_interaction(job_id)

    def scrape_execute(
        self,
        job_id: str,
        code: Optional[str] = None,
        *,
        prompt: Optional[str] = None,
        language: Literal["python", "node", "bash"] = "node",
        timeout: Optional[int] = None,
        origin: Optional[str] = None,
    ):
        """Deprecated alias for interact()."""
        return self.interact(
            job_id,
            code,
            prompt=prompt,
            language=language,
            timeout=timeout,
            origin=origin,
        )

    def delete_scrape_browser(self, job_id: str):
        """Deprecated alias for stop_interaction()."""
        return self.stop_interaction(job_id)

    def scrape_url(self, url: str, **kwargs):
        """V1 compatibility alias for agent recovery. Prefer scrape()."""
        return self.scrape(url, **kwargs)

    def crawl_url(self, url: str, **kwargs):
        """V1 compatibility alias for agent recovery. Prefer crawl()."""
        return self.crawl(url, **kwargs)

    def map_url(self, url: str, **kwargs):
        """V1 compatibility alias for agent recovery. Prefer map()."""
        return self.map(url, **kwargs)

    def async_crawl_url(self, url: str, **kwargs):
        """V1 compatibility alias for agent recovery. Prefer start_crawl()."""
        return self.start_crawl(url, **kwargs)

    def check_crawl_status(self, id: str, **kwargs):
        """V1 compatibility alias for agent recovery. Prefer get_crawl_status()."""
        return self.get_crawl_status(id, **kwargs)

    def check_crawl_errors(self, id: str):
        """V1 compatibility alias for agent recovery. Prefer get_crawl_errors()."""
        return self.get_crawl_errors(id)

    def batch_scrape_urls(self, urls, **kwargs):
        """V1 compatibility alias for agent recovery. Prefer batch_scrape()."""
        return self.batch_scrape(urls, **kwargs)

    def async_batch_scrape_urls(self, urls, **kwargs):
        """V1 compatibility alias for agent recovery. Prefer start_batch_scrape()."""
        return self.start_batch_scrape(urls, **kwargs)

    def check_batch_scrape_status(self, id: str, **kwargs):
        """V1 compatibility alias for agent recovery. Prefer get_batch_scrape_status()."""
        return self.get_batch_scrape_status(id, **kwargs)

    def check_batch_scrape_errors(self, id: str):
        """V1 compatibility alias for agent recovery. Prefer get_batch_scrape_errors()."""
        return self.get_batch_scrape_errors(id)

    def parse(
        self,
        file: Union[str, Path, bytes, bytearray, BinaryIO],
        *,
        filename: Optional[str] = None,
        content_type: Optional[str] = None,
        options: Optional[ParseOptions] = None,
    ) -> Document:
        """
        Parse an uploaded file using the v2 parse endpoint.

        Args:
            file: File path, bytes, bytearray, or binary file-like object
            filename: Optional explicit filename (required for raw bytes without extension)
            content_type: Optional explicit MIME type
            options: Parse-compatible options. Parse rejects change tracking and
                browser-only options such as actions, wait_for, location, and mobile.

        Returns:
            Document
        """
        return parse_module.parse(
            self.http_client,
            file,
            options=options,
            filename=filename,
            content_type=content_type,
        )


    def search(
        self,
        query: str,
        *,
        sources: Optional[List[SourceOption]] = None,
        categories: Optional[List[CategoryOption]] = None,
        include_domains: Optional[List[str]] = None,
        exclude_domains: Optional[List[str]] = None,
        limit: Optional[int] = None,
        tbs: Optional[str] = None,
        location: Optional[str] = None,
        ignore_invalid_urls: Optional[bool] = None,
        timeout: Optional[int] = None,
        scrape_options: Optional[ScrapeOptions] = None,
        integration: Optional[str] = None,
    ) -> SearchData:
        """
        Search for documents.

        Args:
            query: Search query string
            limit: Maximum number of results to return (default: 5)
            tbs: Time-based search filter
            location: Location string for search
            timeout: Request timeout in milliseconds (default: 300000)
            page_options: Options for scraping individual pages

        Returns:
            SearchData containing the search results
        """
        request = SearchRequest(
            query=query,
            sources=sources,
            categories=categories,
            include_domains=include_domains,
            exclude_domains=exclude_domains,
            limit=limit,
            tbs=tbs,
            location=location,
            ignore_invalid_urls=ignore_invalid_urls,
            timeout=timeout,
            scrape_options=scrape_options,
            integration=integration,
        )

        return search_module.search(self.http_client, request)
    
    def crawl(
        self,
        url: str,
        *,
        prompt: Optional[str] = None,
        exclude_paths: Optional[List[str]] = None,
        include_paths: Optional[List[str]] = None,
        max_discovery_depth: Optional[int] = None,
        sitemap: Optional[Literal["only", "include", "skip"]] = None,
        ignore_sitemap: Optional[bool] = None,
        ignore_query_parameters: bool = False,
        limit: Optional[int] = None,
        crawl_entire_domain: bool = False,
        allow_external_links: bool = False,
        allow_subdomains: bool = False,
        ignore_robots_txt: bool = False,
        delay: Optional[int] = None,
        max_concurrency: Optional[int] = None,
        webhook: Optional[Union[str, WebhookConfig]] = None,
        scrape_options: Optional[ScrapeOptions] = None,
        formats: Optional[List['FormatOption']] = None,
        headers: Optional[Dict[str, str]] = None,
        include_tags: Optional[List[str]] = None,
        exclude_tags: Optional[List[str]] = None,
        only_main_content: Optional[bool] = None,
        wait_for: Optional[int] = None,
        mobile: Optional[bool] = None,
        parsers: Optional[Union[List[str], List[Union[str, PDFParser]]]] = None,
        actions: Optional[List[Union['WaitAction', 'ScreenshotAction', 'ClickAction', 'WriteAction', 'PressAction', 'ScrollAction', 'ScrapeAction', 'ExecuteJavascriptAction', 'PDFAction']]] = None,
        location: Optional['Location'] = None,
        skip_tls_verification: Optional[bool] = None,
        remove_base64_images: Optional[bool] = None,
        fast_mode: Optional[bool] = None,
        use_mock: Optional[str] = None,
        block_ads: Optional[bool] = None,
        proxy: Optional[str] = None,
        max_age: Optional[int] = None,
        store_in_cache: Optional[bool] = None,
        lockdown: Optional[bool] = None,
        profile: Optional[Dict[str, Any]] = None,
        regex_on_full_url: bool = False,
        deduplicate_similar_urls: bool = True,
        zero_data_retention: bool = False,
        poll_interval: int = 2,
        timeout: Optional[int] = None,
        request_timeout: Optional[float] = None,
        integration: Optional[str] = None,
    ) -> CrawlJob:
        """
        Start a crawl job and wait for it to complete.

        Args:
            url: Target URL to start crawling from
            prompt: Optional prompt to guide the crawl
            exclude_paths: Patterns of URLs to exclude
            include_paths: Patterns of URLs to include
            max_discovery_depth: Maximum depth for finding new URLs
            sitemap: Sitemap usage mode ("only" | "include" | "skip")
            ignore_sitemap: Deprecated alias for sitemap ("skip" when true, "include" when false)
            ignore_query_parameters: Ignore URL parameters
            limit: Maximum pages to crawl
            crawl_entire_domain: Follow parent directory links
            allow_external_links: Follow external domain links
            allow_subdomains: Follow subdomains
            ignore_robots_txt: Whether to ignore robots.txt rules
            delay: Delay in seconds between scrapes
            max_concurrency: Maximum number of concurrent scrapes
            webhook: Webhook configuration for notifications
            scrape_options: Page scraping configuration (takes precedence over direct scrape kwargs)
            formats: Output formats (convenience kwarg, ignored if scrape_options is set)
            headers: HTTP headers for scraping (convenience kwarg)
            include_tags: HTML tags to include (convenience kwarg)
            exclude_tags: HTML tags to exclude (convenience kwarg)
            only_main_content: Restrict to main content (convenience kwarg)
            wait_for: Wait condition in ms (convenience kwarg)
            mobile: Emulate mobile viewport (convenience kwarg)
            parsers: Parser list (convenience kwarg)
            actions: Browser actions (convenience kwarg)
            location: Location settings (convenience kwarg)
            skip_tls_verification: Skip TLS verification (convenience kwarg)
            remove_base64_images: Remove base64 images (convenience kwarg)
            fast_mode: Prefer faster modes (convenience kwarg)
            use_mock: Use mock source (convenience kwarg)
            block_ads: Block ads (convenience kwarg)
            proxy: Proxy setting (convenience kwarg)
            max_age: Cache max age (convenience kwarg)
            store_in_cache: Cache results (convenience kwarg)
            lockdown: Serve only cached results (convenience kwarg)
            profile: Browser profile (convenience kwarg)
            regex_on_full_url: Apply includePaths/excludePaths regex to the full URL (including query parameters) instead of just the pathname
            deduplicate_similar_urls: Whether to deduplicate similar URLs during crawl (default: True)
            zero_data_retention: Whether to delete data after 24 hours
            poll_interval: Seconds between status checks
            timeout: Maximum seconds to wait for the entire crawl job to complete (None for no timeout)
            request_timeout: Timeout (in seconds) for each individual HTTP request, including pagination requests when fetching results. If there are multiple pages, each page request gets this timeout

        Returns:
            CrawlJob when job completes

        Raises:
            ValueError: If request is invalid
            Exception: If the crawl fails to start or complete
            TimeoutError: If timeout is reached
        """
        if scrape_options is None:
            scrape_kwargs = {k: v for k, v in dict(
                formats=formats, headers=headers, include_tags=include_tags,
                exclude_tags=exclude_tags, only_main_content=only_main_content,
                wait_for=wait_for, mobile=mobile, parsers=parsers, actions=actions,
                location=location, skip_tls_verification=skip_tls_verification,
                remove_base64_images=remove_base64_images, fast_mode=fast_mode,
                use_mock=use_mock, block_ads=block_ads, proxy=proxy,
                max_age=max_age, store_in_cache=store_in_cache, lockdown=lockdown,
                profile=profile,
            ).items() if v is not None}
            if scrape_kwargs:
                scrape_options = ScrapeOptions(**scrape_kwargs)

        resolved_sitemap = sitemap
        if resolved_sitemap is None and ignore_sitemap is not None:
            resolved_sitemap = "skip" if ignore_sitemap else "include"

        request_kwargs = {
            "url": url,
            "prompt": prompt,
            "exclude_paths": exclude_paths,
            "include_paths": include_paths,
            "max_discovery_depth": max_discovery_depth,
            "ignore_query_parameters": ignore_query_parameters,
            "limit": limit,
            "crawl_entire_domain": crawl_entire_domain,
            "allow_external_links": allow_external_links,
            "allow_subdomains": allow_subdomains,
            "ignore_robots_txt": ignore_robots_txt,
            "delay": delay,
            "max_concurrency": max_concurrency,
            "webhook": webhook,
            "scrape_options": scrape_options,
            "regex_on_full_url": regex_on_full_url,
            "deduplicate_similar_urls": deduplicate_similar_urls,
            "zero_data_retention": zero_data_retention,
            "integration": integration,
        }
        if resolved_sitemap is not None:
            request_kwargs["sitemap"] = resolved_sitemap

        request = CrawlRequest(**request_kwargs)

        return crawl_module.crawl(
            self.http_client,
            request,
            poll_interval=poll_interval,
            timeout=timeout,
            request_timeout=request_timeout,
        )
    
    def start_crawl(
        self,
        url: str,
        *,
        prompt: Optional[str] = None,
        exclude_paths: Optional[List[str]] = None,
        include_paths: Optional[List[str]] = None,
        max_discovery_depth: Optional[int] = None,
        sitemap: Optional[Literal["only", "include", "skip"]] = None,
        ignore_sitemap: Optional[bool] = None,
        ignore_query_parameters: bool = False,
        limit: Optional[int] = None,
        crawl_entire_domain: bool = False,
        allow_external_links: bool = False,
        allow_subdomains: bool = False,
        ignore_robots_txt: bool = False,
        delay: Optional[int] = None,
        max_concurrency: Optional[int] = None,
        webhook: Optional[Union[str, WebhookConfig]] = None,
        scrape_options: Optional[ScrapeOptions] = None,
        formats: Optional[List['FormatOption']] = None,
        headers: Optional[Dict[str, str]] = None,
        include_tags: Optional[List[str]] = None,
        exclude_tags: Optional[List[str]] = None,
        only_main_content: Optional[bool] = None,
        timeout: Optional[int] = None,
        wait_for: Optional[int] = None,
        mobile: Optional[bool] = None,
        parsers: Optional[Union[List[str], List[Union[str, PDFParser]]]] = None,
        actions: Optional[List[Union['WaitAction', 'ScreenshotAction', 'ClickAction', 'WriteAction', 'PressAction', 'ScrollAction', 'ScrapeAction', 'ExecuteJavascriptAction', 'PDFAction']]] = None,
        location: Optional['Location'] = None,
        skip_tls_verification: Optional[bool] = None,
        remove_base64_images: Optional[bool] = None,
        fast_mode: Optional[bool] = None,
        use_mock: Optional[str] = None,
        block_ads: Optional[bool] = None,
        proxy: Optional[str] = None,
        max_age: Optional[int] = None,
        store_in_cache: Optional[bool] = None,
        lockdown: Optional[bool] = None,
        profile: Optional[Dict[str, Any]] = None,
        regex_on_full_url: bool = False,
        deduplicate_similar_urls: bool = True,
        zero_data_retention: bool = False,
        integration: Optional[str] = None,
    ) -> CrawlResponse:
        """
        Start an asynchronous crawl job.

        Args:
            url: Target URL to start crawling from
            prompt: Optional prompt to guide the crawl
            exclude_paths: Patterns of URLs to exclude
            include_paths: Patterns of URLs to include
            max_discovery_depth: Maximum depth for finding new URLs
            sitemap: Sitemap usage mode ("only" | "include" | "skip")
            ignore_sitemap: Deprecated alias for sitemap ("skip" when true, "include" when false)
            ignore_query_parameters: Ignore URL parameters
            limit: Maximum pages to crawl
            crawl_entire_domain: Follow parent directory links
            allow_external_links: Follow external domain links
            allow_subdomains: Follow subdomains
            ignore_robots_txt: Whether to ignore robots.txt rules
            delay: Delay in seconds between scrapes
            max_concurrency: Maximum number of concurrent scrapes
            webhook: Webhook configuration for notifications
            scrape_options: Page scraping configuration (takes precedence over direct scrape kwargs)
            formats: Output formats (convenience kwarg, ignored if scrape_options is set)
            headers: HTTP headers for scraping (convenience kwarg)
            include_tags: HTML tags to include (convenience kwarg)
            exclude_tags: HTML tags to exclude (convenience kwarg)
            only_main_content: Restrict to main content (convenience kwarg)
            timeout: Scrape timeout in milliseconds (convenience kwarg)
            wait_for: Wait condition in ms (convenience kwarg)
            mobile: Emulate mobile viewport (convenience kwarg)
            parsers: Parser list (convenience kwarg)
            actions: Browser actions (convenience kwarg)
            location: Location settings (convenience kwarg)
            skip_tls_verification: Skip TLS verification (convenience kwarg)
            remove_base64_images: Remove base64 images (convenience kwarg)
            fast_mode: Prefer faster modes (convenience kwarg)
            use_mock: Use mock source (convenience kwarg)
            block_ads: Block ads (convenience kwarg)
            proxy: Proxy setting (convenience kwarg)
            max_age: Cache max age (convenience kwarg)
            store_in_cache: Cache results (convenience kwarg)
            lockdown: Serve only cached results (convenience kwarg)
            profile: Browser profile (convenience kwarg)
            regex_on_full_url: Apply includePaths/excludePaths regex to the full URL (including query parameters) instead of just the pathname
            deduplicate_similar_urls: Whether to deduplicate similar URLs during crawl (default: True)
            zero_data_retention: Whether to delete data after 24 hours

        Returns:
            CrawlResponse with job information

        Raises:
            ValueError: If request is invalid
            Exception: If the crawl operation fails to start
        """
        if scrape_options is None:
            scrape_kwargs = {k: v for k, v in dict(
                formats=formats, headers=headers, include_tags=include_tags,
                exclude_tags=exclude_tags, only_main_content=only_main_content,
                timeout=timeout, wait_for=wait_for, mobile=mobile,
                parsers=parsers, actions=actions,
                location=location, skip_tls_verification=skip_tls_verification,
                remove_base64_images=remove_base64_images, fast_mode=fast_mode,
                use_mock=use_mock, block_ads=block_ads, proxy=proxy,
                max_age=max_age, store_in_cache=store_in_cache, lockdown=lockdown,
                profile=profile,
            ).items() if v is not None}
            if scrape_kwargs:
                scrape_options = ScrapeOptions(**scrape_kwargs)

        resolved_sitemap = sitemap
        if resolved_sitemap is None and ignore_sitemap is not None:
            resolved_sitemap = "skip" if ignore_sitemap else "include"

        request_kwargs = {
            "url": url,
            "prompt": prompt,
            "exclude_paths": exclude_paths,
            "include_paths": include_paths,
            "max_discovery_depth": max_discovery_depth,
            "ignore_query_parameters": ignore_query_parameters,
            "limit": limit,
            "crawl_entire_domain": crawl_entire_domain,
            "allow_external_links": allow_external_links,
            "allow_subdomains": allow_subdomains,
            "ignore_robots_txt": ignore_robots_txt,
            "delay": delay,
            "max_concurrency": max_concurrency,
            "webhook": webhook,
            "scrape_options": scrape_options,
            "regex_on_full_url": regex_on_full_url,
            "deduplicate_similar_urls": deduplicate_similar_urls,
            "zero_data_retention": zero_data_retention,
            "integration": integration,
        }
        if resolved_sitemap is not None:
            request_kwargs["sitemap"] = resolved_sitemap

        request = CrawlRequest(**request_kwargs)

        return crawl_module.start_crawl(self.http_client, request)
    
    def get_crawl_status(
        self,
        job_id: str,
        pagination_config: Optional[PaginationConfig] = None,
        *,
        request_timeout: Optional[float] = None,
    ) -> CrawlJob:
        """
        Get the status of a crawl job.
        
        Args:
            job_id: ID of the crawl job
            pagination_config: Optional configuration for pagination behavior
            request_timeout: Timeout (in seconds) for each individual HTTP request. When auto-pagination 
                is enabled (default) and there are multiple pages of results, this timeout applies to 
                each page request separately, not to the entire operation
            
        Returns:
            CrawlJob with current status and data
            
        Raises:
            Exception: If the status check fails
        """
        return crawl_module.get_crawl_status(
            self.http_client,
            job_id,
            pagination_config=pagination_config,
            request_timeout=request_timeout,
        )

    def get_crawl_status_page(
        self,
        next_url: str,
        *,
        request_timeout: Optional[float] = None,
    ) -> CrawlJob:
        """
        Fetch a single page of crawl results using a next URL.

        Args:
            next_url: Opaque next URL from a prior crawl status response
            request_timeout: Timeout (in seconds) for the HTTP request

        Returns:
            CrawlJob with the page data and next URL (if any)
        """
        return crawl_module.get_crawl_status_page(
            self.http_client,
            next_url,
            request_timeout=request_timeout,
        )
    
    def get_crawl_errors(self, crawl_id: str) -> CrawlErrorsResponse:
        """
        Retrieve error details and robots.txt blocks for a given crawl job.
        
        Args:
            crawl_id: The ID of the crawl job
        
        Returns:
            CrawlErrorsResponse containing per-URL errors and robots-blocked URLs
        """
        return crawl_module.get_crawl_errors(self.http_client, crawl_id)
    
    def get_active_crawls(self) -> ActiveCrawlsResponse:
        """
        Get a list of currently active crawl jobs.
        
        Returns:
            ActiveCrawlsResponse containing a list of active crawl jobs.
        """
        return crawl_module.get_active_crawls(self.http_client)
    
    def active_crawls(self) -> ActiveCrawlsResponse:
        """
        List currently active crawl jobs for the authenticated team.
        
        Returns:
            ActiveCrawlsResponse containing the list of active crawl jobs
        """
        return self.get_active_crawls()

    def map(
        self,
        url: str,
        *,
        search: Optional[str] = None,
        include_subdomains: Optional[bool] = None,
        ignore_query_parameters: Optional[bool] = None,
        limit: Optional[int] = None,
        sitemap: Optional[Literal["only", "include", "skip"]] = None,
        timeout: Optional[int] = None,
        integration: Optional[str] = None,
        location: Optional[Location] = None,
    ) -> MapData:
        """Map a URL and return discovered links.

        Args:
            url: Root URL to explore
            search: Optional substring filter for discovered links
            include_subdomains: Whether to include subdomains
            ignore_query_parameters: Whether to ignore query parameters when mapping
            limit: Maximum number of links to return
            sitemap: Sitemap usage mode ("only" | "include" | "skip")
            timeout: Request timeout in milliseconds

        Returns:
            MapData containing the discovered links
        """
        options = MapOptions(
            search=search,
            include_subdomains=include_subdomains,
            ignore_query_parameters=ignore_query_parameters,
            limit=limit,
            sitemap=sitemap if sitemap is not None else "include",
            timeout=timeout,
            integration=integration,
            location=location
        ) if any(v is not None for v in [search, include_subdomains, ignore_query_parameters, limit, sitemap, timeout, integration, location]) else None

        return map_module.map(self.http_client, url, options)

    def create_monitor(
        self,
        name: str,
        schedule: Union[MonitorSchedule, Dict[str, Any]],
        targets: List[Union[MonitorTarget, Dict[str, Any]]],
        *,
        webhook: Optional[Union[MonitorWebhookConfig, Dict[str, Any]]] = None,
        notification: Optional[MonitorNotification] = None,
        retention_days: Optional[int] = None,
        goal: Optional[str] = None,
        judge_enabled: Optional[bool] = None,
    ) -> Monitor:
        """Create a scheduled monitor."""
        if isinstance(schedule, dict):
            schedule = MonitorSchedule(**schedule)
        request = MonitorCreateRequest(
            name=name,
            schedule=schedule,
            targets=targets,
            webhook=webhook,
            notification=notification,
            retention_days=retention_days,
            goal=goal,
            judge_enabled=judge_enabled,
        )
        return monitor_module.create_monitor(self.http_client, request)

    def list_monitors(
        self,
        *,
        limit: Optional[int] = None,
        offset: Optional[int] = None,
    ) -> List[Monitor]:
        """List monitors for the authenticated team."""
        return monitor_module.list_monitors(self.http_client, limit=limit, offset=offset)

    def get_monitor(self, monitor_id: str) -> Monitor:
        """Get a monitor by ID."""
        return monitor_module.get_monitor(self.http_client, monitor_id)

    def update_monitor(
        self,
        monitor_id: str,
        *,
        name: Optional[str] = None,
        status: Optional[Literal["active", "paused"]] = None,
        schedule: Optional[Union[MonitorSchedule, Dict[str, Any]]] = None,
        webhook: Optional[Union[MonitorWebhookConfig, Dict[str, Any]]] = None,
        notification: Optional[Union[MonitorNotification, Dict[str, Any]]] = None,
        targets: Optional[List[Union[MonitorTarget, Dict[str, Any]]]] = None,
        retention_days: Optional[int] = None,
        goal: Optional[str] = None,
        judge_enabled: Optional[bool] = None,
    ) -> Monitor:
        """Update a monitor."""
        if isinstance(schedule, dict):
            schedule = MonitorSchedule(**schedule)
        request = MonitorUpdateRequest(
            name=name,
            status=status,
            schedule=schedule,
            webhook=webhook,
            notification=notification,
            targets=targets,
            retention_days=retention_days,
            goal=goal,
            judge_enabled=judge_enabled,
        )
        return monitor_module.update_monitor(self.http_client, monitor_id, request)

    def delete_monitor(self, monitor_id: str) -> bool:
        """Delete a monitor."""
        return monitor_module.delete_monitor(self.http_client, monitor_id)

    def run_monitor(self, monitor_id: str) -> MonitorCheck:
        """Run a monitor manually."""
        return monitor_module.run_monitor(self.http_client, monitor_id)

    def list_monitor_checks(
        self,
        monitor_id: str,
        *,
        limit: Optional[int] = None,
        offset: Optional[int] = None,
    ) -> List[MonitorCheck]:
        """List checks for a monitor."""
        return monitor_module.list_monitor_checks(
            self.http_client,
            monitor_id,
            limit=limit,
            offset=offset,
        )

    def get_monitor_check(
        self,
        monitor_id: str,
        check_id: str,
        *,
        limit: Optional[int] = None,
        skip: Optional[int] = None,
        status: Optional[Literal["same", "new", "changed", "removed", "error"]] = None,
        pagination_config: Optional[PaginationConfig] = None,
    ) -> MonitorCheckDetail:
        """Get a monitor check with page results, auto-paginated by default."""
        return monitor_module.get_monitor_check(
            self.http_client,
            monitor_id,
            check_id,
            limit=limit,
            skip=skip,
            status=status,
            pagination_config=pagination_config,
        )
    
    def cancel_crawl(self, crawl_id: str) -> bool:
        """
        Cancel a crawl job.
        
        Args:
            crawl_id: The ID of the crawl job to cancel
            
        Returns:
            bool: True if the crawl was cancelled, False otherwise
        """
        return crawl_module.cancel_crawl(self.http_client, crawl_id)

    def crawl_params_preview(self, url: str, prompt: str) -> CrawlParamsData:
        """Derive crawl parameters from natural-language prompt.

        Args:
            url: Root URL
            prompt: Instruction describing how to crawl

        Returns:
            CrawlParamsData with normalized crawl configuration
        """
        request = CrawlParamsRequest(url=url, prompt=prompt)
        return crawl_module.crawl_params_preview(self.http_client, request)

    def start_extract(
        self,
        urls: Optional[List[str]] = None,
        *,
        prompt: Optional[str] = None,
        schema: Optional[Dict[str, Any]] = None,
        system_prompt: Optional[str] = None,
        allow_external_links: Optional[bool] = None,
        enable_web_search: Optional[bool] = None,
        show_sources: Optional[bool] = None,
        scrape_options: Optional['ScrapeOptions'] = None,
        ignore_invalid_urls: Optional[bool] = None,
        integration: Optional[str] = None,
        agent: Optional[AgentOptions] = None,
    ):
        """Start an extract job (non-blocking).

        .. deprecated::
            The extract endpoint is in maintenance mode and its use is discouraged.
            Review https://docs.firecrawl.dev/developer-guides/usage-guides/choosing-the-data-extractor
            to find a replacement.

        Args:
            urls: URLs to extract from (optional)
            prompt: Natural-language instruction for extraction
            schema: Target JSON schema for the output
            system_prompt: Optional system instruction
            allow_external_links: Allow hyperlinks in output
            enable_web_search: Whether to augment with web search
            show_sources: Include per-field/source mapping when available
            scrape_options: Scrape options applied prior to extraction
            ignore_invalid_urls: Skip invalid URLs instead of failing
            integration: Integration tag/name
            agent: Agent configuration
        Returns:
            Response payload with job id/status (poll with get_extract_status)
        """
        return extract_module.start_extract(
            self.http_client,
            urls,
            prompt=prompt,
            schema=schema,
            system_prompt=system_prompt,
            allow_external_links=allow_external_links,
            enable_web_search=enable_web_search,
            show_sources=show_sources,
            scrape_options=scrape_options,
            ignore_invalid_urls=ignore_invalid_urls,
            integration=integration,
            agent=agent,
        )

    def extract(
        self,
        urls: Optional[List[str]] = None,
        *,
        prompt: Optional[str] = None,
        schema: Optional[Dict[str, Any]] = None,
        system_prompt: Optional[str] = None,
        allow_external_links: Optional[bool] = None,
        enable_web_search: Optional[bool] = None,
        show_sources: Optional[bool] = None,
        scrape_options: Optional['ScrapeOptions'] = None,
        ignore_invalid_urls: Optional[bool] = None,
        poll_interval: int = 2,
        timeout: Optional[int] = None,
        integration: Optional[str] = None,
        agent: Optional[AgentOptions] = None,
    ):
        """Extract structured data and wait until completion.

        .. deprecated::
            The extract endpoint is in maintenance mode and its use is discouraged.
            Review https://docs.firecrawl.dev/developer-guides/usage-guides/choosing-the-data-extractor
            to find a replacement.

        Args:
            urls: URLs to extract from (optional)
            prompt: Natural-language instruction for extraction
            schema: Target JSON schema for the output
            system_prompt: Optional system instruction
            allow_external_links: Allow hyperlinks in output
            enable_web_search: Whether to augment with web search
            show_sources: Include per-field/source mapping when available
            scrape_options: Scrape options applied prior to extraction
            ignore_invalid_urls: Skip invalid URLs instead of failing
            poll_interval: Seconds between status checks
            timeout: Maximum seconds to wait (None for no timeout)
            integration: Integration tag/name
            agent: Agent configuration
        Returns:
            Final extract response when completed
        """
        return extract_module.extract(
            self.http_client,
            urls,
            prompt=prompt,
            schema=schema,
            system_prompt=system_prompt,
            allow_external_links=allow_external_links,
            enable_web_search=enable_web_search,
            show_sources=show_sources,
            scrape_options=scrape_options,
            ignore_invalid_urls=ignore_invalid_urls,
            poll_interval=poll_interval,
            timeout=timeout,
            integration=integration,
            agent=agent,
        )

    def start_batch_scrape(
        self,
        urls: List[str],
        *,
        formats: Optional[List['FormatOption']] = None,
        headers: Optional[Dict[str, str]] = None,
        include_tags: Optional[List[str]] = None,
        exclude_tags: Optional[List[str]] = None,
        only_main_content: Optional[bool] = None,
        timeout: Optional[int] = None,
        wait_for: Optional[int] = None,
        mobile: Optional[bool] = None,
        parsers: Optional[Union[List[str], List[Union[str, PDFParser]]]] = None,
        actions: Optional[List[Union['WaitAction', 'ScreenshotAction', 'ClickAction', 'WriteAction', 'PressAction', 'ScrollAction', 'ScrapeAction', 'ExecuteJavascriptAction', 'PDFAction']]] = None,
        location: Optional['Location'] = None,
        skip_tls_verification: Optional[bool] = None,
        remove_base64_images: Optional[bool] = None,
        fast_mode: Optional[bool] = None,
        use_mock: Optional[str] = None,
        block_ads: Optional[bool] = None,
        proxy: Optional[str] = None,
        max_age: Optional[int] = None,
        store_in_cache: Optional[bool] = None,
        lockdown: Optional[bool] = None,
        webhook: Optional[Union[str, WebhookConfig]] = None,
        append_to_id: Optional[str] = None,
        ignore_invalid_urls: Optional[bool] = None,
        max_concurrency: Optional[int] = None,
        zero_data_retention: Optional[bool] = None,
        integration: Optional[str] = None,
        idempotency_key: Optional[str] = None,
    ):
        """Start a batch scrape job over multiple URLs (non-blocking).

        Args:
            urls: List of URLs to scrape
            formats: Output formats to collect per URL
            headers: HTTP headers
            include_tags: HTML tags to include
            exclude_tags: HTML tags to exclude
            only_main_content: Restrict scraping to main content
            timeout: Per-request timeout in milliseconds
            wait_for: Wait condition in milliseconds
            mobile: Emulate mobile viewport
            parsers: Parser list (e.g., ["pdf"])
            actions: Browser actions to perform
            location: Location settings
            skip_tls_verification: Skip TLS verification
            remove_base64_images: Remove base64 images from output
            fast_mode: Prefer faster scraping modes
            use_mock: Use a mock data source (internal/testing)
            block_ads: Block ads during scraping
            proxy: Proxy setting
            max_age: Cache max age
            store_in_cache: Whether to store results in cache
            lockdown: Serve only previously cached results; never make outbound requests.
            webhook: Webhook configuration
            append_to_id: Append to an existing batch job
            ignore_invalid_urls: Skip invalid URLs without failing
            max_concurrency: Max concurrent scrapes
            zero_data_retention: Delete data after 24 hours
            integration: Integration tag/name
            idempotency_key: Header used to deduplicate starts

        Returns:
            Response payload with job id (poll with get_batch_scrape_status)
        """
        options = ScrapeOptions(
            **{k: v for k, v in dict(
                formats=formats,
                headers=headers,
                include_tags=include_tags,
                exclude_tags=exclude_tags,
                only_main_content=only_main_content,
                timeout=timeout,
                wait_for=wait_for,
                mobile=mobile,
                parsers=parsers,
                actions=actions,
                location=location,
                skip_tls_verification=skip_tls_verification,
                remove_base64_images=remove_base64_images,
                fast_mode=fast_mode,
                use_mock=use_mock,
                block_ads=block_ads,
                proxy=proxy,
                max_age=max_age,
                store_in_cache=store_in_cache,
                lockdown=lockdown,
            ).items() if v is not None}
        ) if any(v is not None for v in [formats, headers, include_tags, exclude_tags, only_main_content, timeout, wait_for, mobile, parsers, actions, location, skip_tls_verification, remove_base64_images, fast_mode, use_mock, block_ads, proxy, max_age, store_in_cache, lockdown]) else None

        return batch_module.start_batch_scrape(
            self.http_client,
            urls,
            options=options,
            webhook=webhook,
            append_to_id=append_to_id,
            ignore_invalid_urls=ignore_invalid_urls,
            max_concurrency=max_concurrency,
            zero_data_retention=zero_data_retention,
            integration=integration,
            idempotency_key=idempotency_key,
        )

    def get_batch_scrape_status(
        self, 
        job_id: str,
        pagination_config: Optional[PaginationConfig] = None
    ):
        """Get current status and any scraped data for a batch job.

        Args:
            job_id: Batch job ID
            pagination_config: Optional configuration for pagination behavior

        Returns:
            Status payload including counts and partial data
        """
        return batch_module.get_batch_scrape_status(
            self.http_client, 
            job_id,
            pagination_config=pagination_config
        )

    def get_batch_scrape_status_page(
        self,
        next_url: str,
        *,
        request_timeout: Optional[float] = None,
    ):
        """Fetch a single page of batch scrape results using a next URL.

        Args:
            next_url: Opaque next URL from a prior batch scrape status response
            request_timeout: Timeout (in seconds) for the HTTP request

        Returns:
            BatchScrapeJob with the page data and next URL (if any)
        """
        return batch_module.get_batch_scrape_status_page(
            self.http_client,
            next_url,
            request_timeout=request_timeout,
        )

    def cancel_batch_scrape(self, job_id: str) -> bool:
        """Cancel a running batch scrape job.

        Args:
            job_id: Batch job ID

        Returns:
            True if the job was cancelled
        """
        return batch_module.cancel_batch_scrape(self.http_client, job_id)

    def get_batch_scrape_errors(self, job_id: str):
        """Retrieve error details for a batch scrape job.

        Args:
            job_id: Batch job ID

        Returns:
            Errors and robots-blocked URLs for the job
        """
        return batch_methods.get_batch_scrape_errors(self.http_client, job_id)

    def get_extract_status(self, job_id: str):
        """Get the current status (and data if completed) of an extract job.

        .. deprecated::
            The extract endpoint is in maintenance mode and its use is discouraged.
            Review https://docs.firecrawl.dev/developer-guides/usage-guides/choosing-the-data-extractor
            to find a replacement.

        Args:
            job_id: Extract job ID

        Returns:
            Extract response payload with status and optional data
        """
        return extract_module.get_extract_status(self.http_client, job_id)

    def start_agent(
        self,
        urls: Optional[List[str]] = None,
        *,
        prompt: str,
        schema: Optional[Any] = None,
        integration: Optional[str] = None,
        max_credits: Optional[int] = None,
        strict_constrain_to_urls: Optional[bool] = None,
        model: Optional[Literal["spark-1-pro", "spark-1-mini"]] = None,
        webhook: Optional[Union[str, AgentWebhookConfig]] = None,
    ):
        """Start an agent job (non-blocking).

        Args:
            urls: URLs to process (optional)
            prompt: Natural-language instruction for the agent
            schema: Target JSON schema for the output (dict or Pydantic BaseModel)
            integration: Integration tag/name
            max_credits: Maximum credits to use (optional)
            model: Model to use for the agent ("spark-1-pro" or "spark-1-mini")
            webhook: Webhook URL or configuration for notifications
        Returns:
            Response payload with job id/status (poll with get_agent_status)
        """
        return agent_module.start_agent(
            self.http_client,
            urls,
            prompt=prompt,
            schema=schema,
            integration=integration,
            max_credits=max_credits,
            strict_constrain_to_urls=strict_constrain_to_urls,
            model=model,
            webhook=webhook,
        )

    def agent(
        self,
        urls: Optional[List[str]] = None,
        *,
        prompt: str,
        schema: Optional[Any] = None,
        integration: Optional[str] = None,
        poll_interval: int = 2,
        timeout: Optional[int] = None,
        max_credits: Optional[int] = None,
        strict_constrain_to_urls: Optional[bool] = None,
        model: Optional[Literal["spark-1-pro", "spark-1-mini"]] = None,
        webhook: Optional[Union[str, AgentWebhookConfig]] = None,
    ):
        """Run an agent and wait until completion.

        Args:
            urls: URLs to process (optional)
            prompt: Natural-language instruction for the agent
            schema: Target JSON schema for the output (dict or Pydantic BaseModel)
            integration: Integration tag/name
            poll_interval: Seconds between status checks
            timeout: Maximum seconds to wait (None for no timeout)
            max_credits: Maximum credits to use (optional)
            model: Model to use for the agent ("spark-1-pro" or "spark-1-mini")
            webhook: Webhook URL or configuration for notifications
        Returns:
            Final agent response when completed
        """
        return agent_module.agent(
            self.http_client,
            urls,
            prompt=prompt,
            schema=schema,
            integration=integration,
            poll_interval=poll_interval,
            timeout=timeout,
            max_credits=max_credits,
            strict_constrain_to_urls=strict_constrain_to_urls,
            model=model,
            webhook=webhook,
        )

    def get_agent_status(self, job_id: str):
        """Get the current status (and data if completed) of an agent job.

        Args:
            job_id: Agent job ID

        Returns:
            Agent response payload with status and optional data
        """
        return agent_module.get_agent_status(self.http_client, job_id)

    def cancel_agent(self, job_id: str) -> bool:
        """Cancel a running agent job.

        Args:
            job_id: Agent job ID

        Returns:
            True if the agent was cancelled
        """
        return agent_module.cancel_agent(self.http_client, job_id)

    def get_concurrency(self):
        """Get current concurrency and maximum allowed for this team/key (v2)."""
        return usage_methods.get_concurrency(self.http_client)

    def get_credit_usage(self):
        """Get remaining credits for this team/key (v2)."""
        return usage_methods.get_credit_usage(self.http_client)

    def get_token_usage(self):
        """Get recent token usage metrics (v2)."""
        return usage_methods.get_token_usage(self.http_client)

    def get_credit_usage_historical(self, by_api_key: bool = False):
        """Get historical credit usage (v2)."""
        return usage_methods.get_credit_usage_historical(self.http_client, by_api_key)

    def get_token_usage_historical(self, by_api_key: bool = False):
        """Get historical token usage (v2)."""
        return usage_methods.get_token_usage_historical(self.http_client, by_api_key)

    def get_queue_status(self):
        """Get metrics about the team's scrape queue."""
        return usage_methods.get_queue_status(self.http_client)

    # Browser
    def browser(
        self,
        *,
        ttl: Optional[int] = None,
        activity_ttl: Optional[int] = None,
        stream_web_view: Optional[bool] = None,
        profile: Optional[Dict[str, Any]] = None,
    ):
        """Create a new browser session.

        Args:
            ttl: Total time-to-live in seconds (30-3600, default 300)
            activity_ttl: Inactivity TTL in seconds (10-3600)
            stream_web_view: Whether to enable webview streaming
            profile: Profile config with ``name`` (str) and
                optional ``save_changes`` (bool, default ``True``)

        Returns:
            BrowserCreateResponse with session id and CDP URL
        """
        return browser_module.browser(
            self.http_client,
            ttl=ttl,
            activity_ttl=activity_ttl,
            stream_web_view=stream_web_view,
            profile=profile,
        )

    def browser_execute(
        self,
        session_id: str,
        code: str,
        *,
        language: Literal["python", "node", "bash"] = "bash",
        timeout: Optional[int] = None,
    ):
        """Execute code in a browser session.

        Args:
            session_id: Browser session ID
            code: Code to execute
            language: Programming language ("python", "node", or "bash")
            timeout: Execution timeout in seconds (1-300, default 30)

        Returns:
            BrowserExecuteResponse with execution result
        """
        return browser_module.browser_execute(
            self.http_client,
            session_id,
            code,
            language=language,
            timeout=timeout,
        )

    def delete_browser(self, session_id: str):
        """Delete a browser session.

        Args:
            session_id: Browser session ID

        Returns:
            BrowserDeleteResponse
        """
        return browser_module.delete_browser(self.http_client, session_id)

    def list_browsers(
        self,
        *,
        status: Optional[Literal["active", "destroyed"]] = None,
    ):
        """List browser sessions.

        Args:
            status: Filter by session status ("active" or "destroyed")

        Returns:
            BrowserListResponse with list of sessions
        """
        return browser_module.list_browsers(
            self.http_client,
            status=status,
        )

    def watcher(
        self,
        job_id: str,
        *,
        kind: Literal["crawl", "batch"] = "crawl",
        poll_interval: int = 2,
        timeout: Optional[int] = None,
    ) -> Watcher:
        """Create a watcher for crawl or batch jobs.

        Args:
            job_id: Job ID to watch
            kind: Job kind ("crawl" or "batch")
            poll_interval: Seconds between status checks
            timeout: Maximum seconds to watch (None for no timeout)

        Returns:
            Watcher instance
        """
        return Watcher(self, job_id, kind=kind, poll_interval=poll_interval, timeout=timeout)

    def batch_scrape(
        self,
        urls: List[str],
        *,
        formats: Optional[List['FormatOption']] = None,
        headers: Optional[Dict[str, str]] = None,
        include_tags: Optional[List[str]] = None,
        exclude_tags: Optional[List[str]] = None,
        only_main_content: Optional[bool] = None,
        timeout: Optional[int] = None,
        wait_for: Optional[int] = None,
        mobile: Optional[bool] = None,
        parsers: Optional[Union[List[str], List[Union[str, PDFParser]]]] = None,
        actions: Optional[List[Union['WaitAction', 'ScreenshotAction', 'ClickAction', 'WriteAction', 'PressAction', 'ScrollAction', 'ScrapeAction', 'ExecuteJavascriptAction', 'PDFAction']]] = None,
        location: Optional['Location'] = None,
        skip_tls_verification: Optional[bool] = None,
        remove_base64_images: Optional[bool] = None,
        fast_mode: Optional[bool] = None,
        use_mock: Optional[str] = None,
        block_ads: Optional[bool] = None,
        proxy: Optional[str] = None,
        max_age: Optional[int] = None,
        store_in_cache: Optional[bool] = None,
        lockdown: Optional[bool] = None,
        webhook: Optional[Union[str, WebhookConfig]] = None,
        append_to_id: Optional[str] = None,
        ignore_invalid_urls: Optional[bool] = None,
        max_concurrency: Optional[int] = None,
        zero_data_retention: Optional[bool] = None,
        integration: Optional[str] = None,
        idempotency_key: Optional[str] = None,
        poll_interval: int = 2,
        wait_timeout: Optional[int] = None,
    ):
        """
        Start a batch scrape job and wait until completion.
        """
        options = ScrapeOptions(
            **{k: v for k, v in dict(
                formats=formats,
                headers=headers,
                include_tags=include_tags,
                exclude_tags=exclude_tags,
                only_main_content=only_main_content,
                timeout=timeout,
                wait_for=wait_for,
                mobile=mobile,
                parsers=parsers,
                actions=actions,
                location=location,
                skip_tls_verification=skip_tls_verification,
                remove_base64_images=remove_base64_images,
                fast_mode=fast_mode,
                use_mock=use_mock,
                block_ads=block_ads,
                proxy=proxy,
                max_age=max_age,
                store_in_cache=store_in_cache,
                lockdown=lockdown,
            ).items() if v is not None}
        ) if any(v is not None for v in [formats, headers, include_tags, exclude_tags, only_main_content, timeout, wait_for, mobile, parsers, actions, location, skip_tls_verification, remove_base64_images, fast_mode, use_mock, block_ads, proxy, max_age, store_in_cache, lockdown]) else None

        return batch_module.batch_scrape(
            self.http_client,
            urls,
            options=options,
            webhook=webhook,
            append_to_id=append_to_id,
            ignore_invalid_urls=ignore_invalid_urls,
            max_concurrency=max_concurrency,
            zero_data_retention=zero_data_retention,
            integration=integration,
            idempotency_key=idempotency_key,
            poll_interval=poll_interval,
            timeout=wait_timeout,
        )