-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathindex.ts
More file actions
1125 lines (1045 loc) · 35.4 KB
/
index.ts
File metadata and controls
1125 lines (1045 loc) · 35.4 KB
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
#!/usr/bin/env node
/**
* Firecrawl CLI
* Entry point for the CLI application
*/
import { Command } from 'commander';
import { handleScrapeCommand } from './commands/scrape';
import { initializeConfig, updateConfig } from './utils/config';
import { getClient } from './utils/client';
import { configure, viewConfig } from './commands/config';
import { handleCreditUsageCommand } from './commands/credit-usage';
import { handleCrawlCommand } from './commands/crawl';
import { handleMapCommand } from './commands/map';
import { handleSearchCommand } from './commands/search';
import { handleAgentCommand } from './commands/agent';
import {
handleBrowserLaunch,
handleBrowserExecute,
handleBrowserList,
handleBrowserClose,
handleBrowserQuickExecute,
} from './commands/browser';
import { handleVersionCommand } from './commands/version';
import { handleLoginCommand } from './commands/login';
import { handleLogoutCommand } from './commands/logout';
import { handleInitCommand } from './commands/init';
import { handleSetupCommand } from './commands/setup';
import type { SetupSubcommand } from './commands/setup';
import { handleEnvPullCommand } from './commands/env';
import { handleStatusCommand } from './commands/status';
import { isUrl, normalizeUrl } from './utils/url';
import { parseScrapeOptions } from './utils/options';
import { isJobId } from './utils/job';
import { ensureAuthenticated, printBanner } from './utils/auth';
import packageJson from '../package.json';
import type { SearchSource, SearchCategory } from './types/search';
import type { ScrapeFormat } from './types/scrape';
// Initialize global configuration from environment variables
initializeConfig();
// Commands that require authentication
const AUTH_REQUIRED_COMMANDS = [
'scrape',
'crawl',
'map',
'search',
'agent',
'browser',
'credit-usage',
];
const program = new Command();
program
.name('firecrawl')
.description('CLI tool for Firecrawl web scraping')
.version(packageJson.version)
.option(
'-k, --api-key <key>',
'Firecrawl API key (or set FIRECRAWL_API_KEY env var)'
)
.option('--api-url <url>', 'API URL (or set FIRECRAWL_API_URL env var)')
.option('--status', 'Show version, auth status, concurrency, and credits')
.allowUnknownOption() // Allow unknown options when URL is passed directly
.hook('preAction', async (thisCommand, actionCommand) => {
// Update global config if API key or URL is provided via global option
const globalOptions = thisCommand.opts();
const commandOptions = actionCommand.opts();
if (globalOptions.apiKey) {
updateConfig({ apiKey: globalOptions.apiKey });
}
if (globalOptions.apiUrl) {
updateConfig({ apiUrl: globalOptions.apiUrl });
}
// Check if this command requires authentication
const commandName = actionCommand.name();
if (AUTH_REQUIRED_COMMANDS.includes(commandName)) {
// Skip auth for custom API URLs (e.g., local development)
// Check both global and command-level options
const { isCustomApiUrl } = await import('./utils/config');
const effectiveApiUrl = commandOptions.apiUrl || globalOptions.apiUrl;
if (!isCustomApiUrl(effectiveApiUrl)) {
// Ensure user is authenticated (prompts for login if needed)
await ensureAuthenticated();
}
}
});
/**
* Create and configure the scrape command
*/
function createScrapeCommand(): Command {
const scrapeCmd = new Command('scrape')
.description('Scrape a URL using Firecrawl')
.argument('[url]', 'URL to scrape')
.argument(
'[formats...]',
'Output format(s) as positional args (e.g., markdown screenshot links)'
)
.option(
'-u, --url <url>',
'URL to scrape (alternative to positional argument)'
)
.option('-H, --html', 'Output raw HTML (shortcut for --format html)')
.option(
'-f, --format <formats>',
'Output format(s). Multiple formats can be specified with commas (e.g., "markdown,links,images"). Available: markdown, html, rawHtml, links, images, screenshot, summary, changeTracking, json, attributes, branding. Single format outputs raw content; multiple formats output JSON.'
)
.option('--only-main-content', 'Include only main content', false)
.option(
'--wait-for <ms>',
'Wait time before scraping in milliseconds',
parseInt
)
.option('-S, --summary', 'Output summary (shortcut for --format summary)')
.option('--screenshot', 'Take a screenshot', false)
.option('--include-tags <tags>', 'Comma-separated list of tags to include')
.option('--exclude-tags <tags>', 'Comma-separated list of tags to exclude')
.option(
'-k, --api-key <key>',
'Firecrawl API key (overrides global --api-key)'
)
.option('--api-url <url>', 'API URL (overrides global --api-url)')
.option('-o, --output <path>', 'Output file path (default: stdout)')
.option('--json', 'Output as JSON format', false)
.option('--pretty', 'Pretty print JSON output', false)
.option(
'--timing',
'Show request timing and other useful information',
false
)
.option(
'--max-age <milliseconds>',
'Maximum age of cached content in milliseconds',
parseInt
)
.option(
'--country <code>',
'ISO country code for geo-targeted scraping (e.g., US, DE, BR)'
)
.option(
'--languages <codes>',
'Comma-separated language codes for scraping (e.g., en,es)'
)
.action(async (positionalUrl, positionalFormats, options) => {
// Use positional URL if provided, otherwise use --url option
const url = positionalUrl || options.url;
if (!url) {
console.error(
'Error: URL is required. Provide it as argument or use --url option.'
);
process.exit(1);
}
// Merge formats: positional formats take precedence, then --format flag, then default to markdown
let format: string;
if (positionalFormats && positionalFormats.length > 0) {
// Positional formats: join them with commas for parseFormats
format = positionalFormats.join(',');
} else if (options.html) {
// Handle --html shortcut flag
format = 'html';
} else if (options.summary) {
// Handle --summary shortcut flag
format = 'summary';
} else if (options.format) {
// Use --format option
format = options.format;
} else {
// Default to markdown
format = 'markdown';
}
const scrapeOptions = parseScrapeOptions({ ...options, url, format });
await handleScrapeCommand(scrapeOptions);
});
return scrapeCmd;
}
// Add scrape command to main program
program.addCommand(createScrapeCommand());
/**
* Create and configure the crawl command
*/
function createCrawlCommand(): Command {
const crawlCmd = new Command('crawl')
.description('Crawl a website using Firecrawl')
.argument('[url-or-job-id]', 'URL to crawl or job ID to check status')
.option(
'-u, --url <url>',
'URL to crawl (alternative to positional argument)'
)
.option('--status', 'Check status of existing crawl job', false)
.option(
'--wait',
'Wait for crawl to complete before returning results',
false
)
.option(
'--poll-interval <seconds>',
'Polling interval in seconds when waiting (default: 5)',
parseFloat
)
.option(
'--timeout <seconds>',
'Timeout in seconds when waiting (default: no timeout)',
parseFloat
)
.option('--progress', 'Show progress dots while waiting', false)
.option('--limit <number>', 'Maximum number of pages to crawl', parseInt)
.option('--max-depth <number>', 'Maximum crawl depth', parseInt)
.option(
'--exclude-paths <paths>',
'Comma-separated list of paths to exclude'
)
.option(
'--include-paths <paths>',
'Comma-separated list of paths to include'
)
.option('--sitemap <mode>', 'Sitemap handling: skip, include', 'include')
.option(
'--ignore-query-parameters',
'Ignore query parameters when crawling',
false
)
.option('--crawl-entire-domain', 'Crawl entire domain', false)
.option('--allow-external-links', 'Allow external links', false)
.option('--allow-subdomains', 'Allow subdomains', false)
.option('--delay <ms>', 'Delay between requests in milliseconds', parseInt)
.option(
'--max-concurrency <number>',
'Maximum concurrent requests',
parseInt
)
.option(
'-k, --api-key <key>',
'Firecrawl API key (overrides global --api-key)'
)
.option('--api-url <url>', 'API URL (overrides global --api-url)')
.option('-o, --output <path>', 'Output file path (default: stdout)')
.option('--pretty', 'Pretty print JSON output', false)
.action(async (positionalUrlOrJobId, options) => {
// Use positional argument if provided, otherwise use --url option
const urlOrJobId = positionalUrlOrJobId || options.url;
if (!urlOrJobId) {
console.error(
'Error: URL or job ID is required. Provide it as argument or use --url option.'
);
process.exit(1);
}
// Auto-detect if it's a job ID (UUID format)
const isStatusCheck = options.status || isJobId(urlOrJobId);
const crawlOptions = {
urlOrJobId,
status: isStatusCheck,
wait: options.wait,
pollInterval: options.pollInterval,
timeout: options.timeout,
progress: options.progress,
output: options.output,
pretty: options.pretty,
apiKey: options.apiKey,
apiUrl: options.apiUrl,
limit: options.limit,
maxDepth: options.maxDepth,
excludePaths: options.excludePaths
? options.excludePaths.split(',').map((p: string) => p.trim())
: undefined,
includePaths: options.includePaths
? options.includePaths.split(',').map((p: string) => p.trim())
: undefined,
sitemap: options.sitemap,
ignoreQueryParameters: options.ignoreQueryParameters,
crawlEntireDomain: options.crawlEntireDomain,
allowExternalLinks: options.allowExternalLinks,
allowSubdomains: options.allowSubdomains,
delay: options.delay,
maxConcurrency: options.maxConcurrency,
};
await handleCrawlCommand(crawlOptions);
});
return crawlCmd;
}
/**
* Create and configure the map command
*/
function createMapCommand(): Command {
const mapCmd = new Command('map')
.description('Map URLs on a website using Firecrawl')
.argument('[url]', 'URL to map')
.option(
'-u, --url <url>',
'URL to map (alternative to positional argument)'
)
.option('--wait', 'Wait for map to complete', false)
.option('--limit <number>', 'Maximum URLs to discover', parseInt)
.option('--search <query>', 'Search query to filter URLs')
.option(
'--sitemap <mode>',
'Sitemap handling: only, include, skip',
'include'
)
.option('--include-subdomains', 'Include subdomains', false)
.option('--ignore-query-parameters', 'Ignore query parameters', false)
.option('--timeout <seconds>', 'Timeout in seconds', parseFloat)
.option(
'-k, --api-key <key>',
'Firecrawl API key (overrides global --api-key)'
)
.option('--api-url <url>', 'API URL (overrides global --api-url)')
.option('-o, --output <path>', 'Output file path (default: stdout)')
.option('--json', 'Output as JSON format', false)
.option('--pretty', 'Pretty print JSON output', false)
.action(async (positionalUrl, options) => {
// Use positional URL if provided, otherwise use --url option
const url = positionalUrl || options.url;
if (!url) {
console.error(
'Error: URL is required. Provide it as argument or use --url option.'
);
process.exit(1);
}
const mapOptions = {
urlOrJobId: url,
wait: options.wait,
output: options.output,
json: options.json,
pretty: options.pretty,
apiKey: options.apiKey,
apiUrl: options.apiUrl,
limit: options.limit,
search: options.search,
sitemap: options.sitemap,
includeSubdomains: options.includeSubdomains,
ignoreQueryParameters: options.ignoreQueryParameters,
timeout: options.timeout,
};
await handleMapCommand(mapOptions);
});
return mapCmd;
}
/**
* Create and configure the search command
*/
function createSearchCommand(): Command {
const searchCmd = new Command('search')
.description('Search the web using Firecrawl')
.argument('<query>', 'Search query')
.option(
'--limit <number>',
'Maximum number of results (default: 5, max: 100)',
parseInt
)
.option(
'--sources <sources>',
'Comma-separated sources to search: web, images, news (default: web)'
)
.option(
'--categories <categories>',
'Comma-separated categories to filter: github, research, pdf'
)
.option(
'--tbs <value>',
'Time-based search: qdr:h (hour), qdr:d (day), qdr:w (week), qdr:m (month), qdr:y (year)'
)
.option(
'--location <location>',
'Location for geo-targeting (e.g., "Germany", "San Francisco,California,United States")'
)
.option(
'--country <code>',
'ISO country code for geo-targeting (default: US)'
)
.option(
'--timeout <ms>',
'Timeout in milliseconds (default: 60000)',
parseInt
)
.option(
'--ignore-invalid-urls',
'Exclude URLs invalid for other Firecrawl endpoints',
false
)
.option('--scrape', 'Enable scraping of search results', false)
.option(
'--scrape-formats <formats>',
'Comma-separated scrape formats when --scrape is enabled: markdown, html, rawHtml, links, etc. (default: markdown)'
)
.option(
'--only-main-content',
'Include only main content when scraping',
true
)
.option(
'-k, --api-key <key>',
'Firecrawl API key (overrides global --api-key)'
)
.option('--api-url <url>', 'API URL (overrides global --api-url)')
.option('-o, --output <path>', 'Output file path (default: stdout)')
// .option(
// '-p, --pretty',
// 'Output as pretty JSON (default: human-readable)',
// false
// )
.option('--json', 'Output as compact JSON', false)
.action(async (query, options) => {
// Parse sources
let sources: SearchSource[] | undefined;
if (options.sources) {
sources = options.sources
.split(',')
.map((s: string) => s.trim().toLowerCase()) as SearchSource[];
// Validate sources
const validSources = ['web', 'images', 'news'];
for (const source of sources) {
if (!validSources.includes(source)) {
console.error(
`Error: Invalid source "${source}". Valid sources: ${validSources.join(', ')}`
);
process.exit(1);
}
}
}
// Parse categories
let categories: SearchCategory[] | undefined;
if (options.categories) {
categories = options.categories
.split(',')
.map((c: string) => c.trim().toLowerCase()) as SearchCategory[];
// Validate categories
const validCategories = ['github', 'research', 'pdf'];
for (const category of categories) {
if (!validCategories.includes(category)) {
console.error(
`Error: Invalid category "${category}". Valid categories: ${validCategories.join(', ')}`
);
process.exit(1);
}
}
}
// Parse scrape formats
let scrapeFormats: ScrapeFormat[] | undefined;
if (options.scrapeFormats) {
scrapeFormats = options.scrapeFormats
.split(',')
.map((f: string) => f.trim()) as ScrapeFormat[];
}
const searchOptions = {
query,
limit: options.limit,
sources,
categories,
tbs: options.tbs,
location: options.location,
country: options.country,
timeout: options.timeout,
ignoreInvalidUrls: options.ignoreInvalidUrls,
scrape: options.scrape,
scrapeFormats,
onlyMainContent: options.onlyMainContent,
apiKey: options.apiKey,
apiUrl: options.apiUrl,
output: options.output,
json: options.json,
pretty: options.pretty,
};
await handleSearchCommand(searchOptions);
});
return searchCmd;
}
/**
* Create and configure the agent command
*/
function createAgentCommand(): Command {
const agentCmd = new Command('agent')
.description('Run an AI agent to extract data from the web')
.argument(
'<prompt-or-job-id>',
'Natural language prompt describing data to extract, or job ID to check status'
)
.option('--urls <urls>', 'Comma-separated URLs to focus extraction on')
.option(
'--model <model>',
'Model to use: spark-1-mini (default, cheaper) or spark-1-pro (higher accuracy)'
)
.option(
'--schema <json>',
'JSON schema for structured output (inline JSON string)'
)
.option(
'--schema-file <path>',
'Path to JSON schema file for structured output'
)
.option(
'--max-credits <number>',
'Maximum credits to spend (job fails if exceeded)',
parseInt
)
.option('--status', 'Check status of existing agent job', false)
.option(
'--wait',
'Wait for agent to complete before returning results',
false
)
.option(
'--poll-interval <seconds>',
'Polling interval in seconds when waiting (default: 5)',
parseFloat
)
.option(
'--timeout <seconds>',
'Timeout in seconds when waiting (default: no timeout)',
parseFloat
)
.option(
'-k, --api-key <key>',
'Firecrawl API key (overrides global --api-key)'
)
.option('--api-url <url>', 'API URL (overrides global --api-url)')
.option('-o, --output <path>', 'Output file path (default: stdout)')
.option('--json', 'Output as JSON format', false)
.option('--pretty', 'Pretty print JSON output', false)
.action(async (promptOrJobId, options) => {
// Auto-detect if it's a job ID (UUID format)
const isStatusCheck = options.status || isJobId(promptOrJobId);
// Parse URLs
let urls: string[] | undefined;
if (options.urls) {
urls = options.urls
.split(',')
.map((u: string) => u.trim())
.filter((u: string) => u.length > 0);
}
// Parse inline schema
let schema: Record<string, unknown> | undefined;
if (options.schema) {
try {
schema = JSON.parse(options.schema) as Record<string, unknown>;
} catch {
console.error('Error: Invalid JSON in --schema option');
process.exit(1);
}
}
// Validate model
const validModels = ['spark-1-pro', 'spark-1-mini'];
if (options.model && !validModels.includes(options.model)) {
console.error(
`Error: Invalid model "${options.model}". Valid models: ${validModels.join(', ')}`
);
process.exit(1);
}
const agentOptions = {
prompt: promptOrJobId,
urls,
schema,
schemaFile: options.schemaFile,
model: options.model,
maxCredits: options.maxCredits,
status: isStatusCheck,
wait: options.wait,
pollInterval: options.pollInterval,
timeout: options.timeout,
apiKey: options.apiKey,
apiUrl: options.apiUrl,
output: options.output,
json: options.json,
pretty: options.pretty,
};
await handleAgentCommand(agentOptions);
});
return agentCmd;
}
/**
* Create and configure the browser command
*/
function createBrowserCommand(): Command {
const browserCmd = new Command('browser')
.description(
'Launch cloud browser sessions and execute Python, JavaScript, or bash code remotely via Playwright'
)
.argument('[code]', 'Shorthand: auto-launch session + execute command')
.option(
'-k, --api-key <key>',
'Firecrawl API key (overrides global --api-key)'
)
.option('--api-url <url>', 'API URL (overrides global --api-url)')
.option('-o, --output <path>', 'Output file path (default: stdout)')
.option('--json', 'Output as JSON format', false)
.action(async (code, options) => {
if (code) {
await handleBrowserQuickExecute({
code,
apiKey: options.apiKey,
apiUrl: options.apiUrl,
output: options.output,
json: options.json,
});
}
})
.addHelpText(
'after',
`
Shorthand (auto-launches session if needed):
$ firecrawl browser "open https://example.com"
$ firecrawl browser "snapshot"
$ firecrawl browser "click @e5"
$ firecrawl browser "scrape"
Explicit subcommands:
$ firecrawl browser launch-session
$ firecrawl browser execute "open https://example.com"
$ firecrawl browser list active
$ firecrawl browser close
By default, commands are sent to agent-browser (pre-installed in every sandbox).
Use --python or --node to run Playwright code instead.
$ firecrawl browser execute --python 'print(await page.title())'
$ firecrawl browser execute --node 'await page.title()'
See all agent-browser commands:
$ firecrawl browser execute "--help"
`
);
browserCmd
.command('launch-session')
.description(
'Launch a new cloud browser session (without executing a command)'
)
.option(
'--ttl <seconds>',
'Total session TTL in seconds (default: 300)',
parseInt
)
.option('--ttl-inactivity <seconds>', 'Inactivity TTL in seconds', parseInt)
.option('--stream', 'Enable live view streaming', false)
.option(
'-k, --api-key <key>',
'Firecrawl API key (overrides global --api-key)'
)
.option('--api-url <url>', 'API URL (overrides global --api-url)')
.option('-o, --output <path>', 'Output file path (default: stdout)')
.option('--json', 'Output as JSON format', false)
.addHelpText(
'after',
`
Output:
Prints the Session ID and CDP URL. The session is auto-saved so
subsequent execute/close commands target it automatically.
Tip: Use the shorthand to launch + execute in one step:
$ firecrawl browser "open https://example.com"
Examples:
$ firecrawl browser launch-session
$ firecrawl browser launch-session --stream --ttl 600
$ firecrawl browser launch-session --ttl 300 --ttl-inactivity 60
$ firecrawl browser launch-session -o session.json --json
`
)
.action(async (options) => {
await handleBrowserLaunch({
ttl: options.ttl,
ttlInactivity: options.ttlInactivity,
stream: options.stream,
apiKey: options.apiKey,
apiUrl: options.apiUrl,
output: options.output,
json: options.json,
});
});
browserCmd
.command('execute')
.description(
'Execute agent-browser commands (default), or Playwright Python/JS in a session'
)
.argument(
'<code>',
'agent-browser command (default) or Playwright code (with --python/--node)'
)
.option('--python', 'Execute as Playwright Python code', false)
.option('--node', 'Execute as Playwright JavaScript code', false)
.option(
'--bash',
'Execute bash in the sandbox (agent-browser pre-installed, CDP_URL auto-injected)',
false
)
.option(
'--session <id>',
'Session ID (default: active session from last launch)'
)
.option(
'-k, --api-key <key>',
'Firecrawl API key (overrides global --api-key)'
)
.option('--api-url <url>', 'API URL (overrides global --api-url)')
.option('-o, --output <path>', 'Output file path (default: stdout)')
.option('--json', 'Output as JSON format', false)
.addHelpText(
'after',
`
How it works:
By default, commands are sent to agent-browser (pre-installed in every sandbox).
You don't need to type "agent-browser" — it's added automatically.
agent-browser examples (default):
$ firecrawl browser execute "open https://example.com"
$ firecrawl browser execute "snapshot"
$ firecrawl browser execute "click @e5"
$ firecrawl browser execute "scrape"
You can still pass the full command if you prefer:
$ firecrawl browser execute "agent-browser snapshot"
Use --bash for arbitrary bash commands (not just agent-browser):
$ firecrawl browser execute --bash 'ls /tmp'
Python examples (use --python):
$ firecrawl browser execute --python 'print(await page.title())'
$ firecrawl browser execute --python '
await page.goto("https://news.ycombinator.com")
title = await page.title()
items = await page.query_selector_all(".titleline > a")
for item in items[:5]:
print(await item.inner_text())
'
JavaScript examples (use --node):
$ firecrawl browser execute --node 'await page.goto("https://example.com"); await page.title()'
Target a specific session:
$ firecrawl browser execute --session <id> "snapshot"
Note: --python, --node, and --bash are mutually exclusive.
`
)
.action(async (code, options) => {
const flagCount = [options.python, options.node, options.bash].filter(
Boolean
).length;
if (flagCount > 1) {
console.error(
'Error: Only one of --python, --node, or --bash can be specified'
);
process.exit(1);
}
const language = options.python
? 'python'
: options.node
? 'node'
: 'bash';
// In default/bash mode, auto-prefix "agent-browser" if not already present
let finalCode = code;
if (
language === 'bash' &&
!options.bash &&
!finalCode.startsWith('agent-browser')
) {
finalCode = `agent-browser ${finalCode}`;
}
await handleBrowserExecute({
code: finalCode,
language,
session: options.session,
apiKey: options.apiKey,
apiUrl: options.apiUrl,
output: options.output,
json: options.json,
});
});
browserCmd
.command('list [status]')
.description(
'List browser sessions (optionally filter by: active, destroyed)'
)
.option(
'-k, --api-key <key>',
'Firecrawl API key (overrides global --api-key)'
)
.option('--api-url <url>', 'API URL (overrides global --api-url)')
.option('-o, --output <path>', 'Output file path (default: stdout)')
.option('--json', 'Output as JSON format', false)
.addHelpText(
'after',
`
Examples:
$ firecrawl browser list
$ firecrawl browser list active
$ firecrawl browser list destroyed
$ firecrawl browser list --json
`
)
.action(async (status, options) => {
if (status && !['active', 'destroyed'].includes(status)) {
console.error(
`Error: Invalid status "${status}". Use "active" or "destroyed".`
);
process.exit(1);
}
await handleBrowserList({
status,
apiKey: options.apiKey,
apiUrl: options.apiUrl,
output: options.output,
json: options.json,
});
});
browserCmd
.command('close')
.description('Close a browser session')
.option(
'--session <id>',
'Session ID (default: active session from last launch)'
)
.option(
'-k, --api-key <key>',
'Firecrawl API key (overrides global --api-key)'
)
.option('--api-url <url>', 'API URL (overrides global --api-url)')
.option('-o, --output <path>', 'Output file path (default: stdout)')
.option('--json', 'Output as JSON format', false)
.addHelpText(
'after',
`
Examples:
$ firecrawl browser close
$ firecrawl browser close --session <id>
`
)
.action(async (options) => {
await handleBrowserClose({
session: options.session,
apiKey: options.apiKey,
apiUrl: options.apiUrl,
output: options.output,
json: options.json,
});
});
return browserCmd;
}
// Add crawl, map, search, agent, and browser commands to main program
program.addCommand(createCrawlCommand());
program.addCommand(createMapCommand());
program.addCommand(createSearchCommand());
program.addCommand(createAgentCommand());
program.addCommand(createBrowserCommand());
program
.command('config')
.description('Configure Firecrawl (login if not authenticated)')
.option(
'-k, --api-key <key>',
'Provide API key directly (skips interactive flow)'
)
.option('--api-url <url>', 'API URL (default: https://api.firecrawl.dev)')
.option(
'--web-url <url>',
'Web URL for browser login (default: https://firecrawl.dev)'
)
.option(
'-m, --method <method>',
'Login method: "browser" or "manual" (default: interactive prompt)'
)
.option('-b, --browser', 'Login via browser (shortcut for --method browser)')
.action(async (options) => {
await configure({
apiKey: options.apiKey,
apiUrl: options.apiUrl,
webUrl: options.webUrl,
method: options.browser ? 'browser' : options.method,
});
});
program
.command('view-config')
.description('View current configuration and authentication status')
.action(async () => {
await viewConfig();
});
program
.command('login')
.description('Login to Firecrawl (alias for config)')
.option(
'-k, --api-key <key>',
'Provide API key directly (skips interactive flow)'
)
.option('--api-url <url>', 'API URL (default: https://api.firecrawl.dev)')
.option(
'--web-url <url>',
'Web URL for browser login (default: https://firecrawl.dev)'
)
.option(
'-m, --method <method>',
'Login method: "browser" or "manual" (default: interactive prompt)'
)
.option('-b, --browser', 'Login via browser (shortcut for --method browser)')
.action(async (options) => {
await handleLoginCommand({
apiKey: options.apiKey,
apiUrl: options.apiUrl,
webUrl: options.webUrl,
method: options.browser ? 'browser' : options.method,
});
});
program
.command('logout')
.description('Logout and clear stored credentials')
.action(async () => {
await handleLogoutCommand();
});
program
.command('init')
.description(
'Install CLI globally, authenticate, and add skills in one step (npx -y firecrawl-cli init)'
)
.option('--all', 'Install skills to all detected agents (implies --yes)')
.option('-y, --yes', 'Skip confirmation prompts for skills installation')
.option('-g, --global', 'Install skills globally (user-level)')
.option('-a, --agent <agent>', 'Install skills to a specific agent')
.option(
'-k, --api-key <key>',
'Authenticate with this API key (skips interactive login)'
)
.option(
'-b, --browser',
'Authenticate via browser without prompting (recommended for agents)'
)
.option('--skip-install', 'Skip global CLI installation')
.option('--skip-auth', 'Skip authentication')
.option('--skip-skills', 'Skip skills installation')
.action(async (options) => {
await handleInitCommand({
global: options.global,
agent: options.agent,
all: options.all,
yes: options.yes,
apiKey: options.apiKey,
browser: options.browser,
skipInstall: options.skipInstall,
skipAuth: options.skipAuth,
skipSkills: options.skipSkills,
});
});
program
.command('setup')
.description('Set up individual firecrawl integrations (skills, mcp)')
.argument('<subcommand>', 'What to set up: "skills" or "mcp"')
.option('-g, --global', 'Install globally (user-level)')
.option('-a, --agent <agent>', 'Install to a specific agent')
.action(async (subcommand: SetupSubcommand, options) => {
await handleSetupCommand(subcommand, options);
});
program
.command('env')
.description('Pull FIRECRAWL_API_KEY into a local .env file')
.option('-f, --file <path>', 'Target env file (default: .env)')
.option('--overwrite', 'Overwrite existing FIRECRAWL_API_KEY if present')
.action(async (options) => {