diff --git a/src/__tests__/cli-argv.test.ts b/src/__tests__/cli-argv.test.ts index 1d914b0cda..a3d61d4cb9 100644 --- a/src/__tests__/cli-argv.test.ts +++ b/src/__tests__/cli-argv.test.ts @@ -272,47 +272,24 @@ describe('CLI argv parsing', () => { ); testWithBuiltCli( - 'warns on stderr that browser is deprecated, for the command and its subcommands', - () => { - const offline = [ - '--api-key', - 'fc-test', - '--api-url', - 'http://127.0.0.1:9', - ]; - for (const [args, status] of [ - [['browser', ...offline], 0], - [['browser', 'list', ...offline], 1], - ] as const) { - const result = spawnSync(process.execPath, [cliPath, ...args], { - encoding: 'utf8', - env: { ...process.env, FIRECRAWL_NO_UPDATE_CHECK: '1' }, - }); - expect(result.status).toBe(status); - expect(result.stderr).toContain( - '`firecrawl browser` is deprecated and will be removed' - ); - expect(result.stderr).toContain('firecrawl interact'); - expect(result.stdout).not.toContain('deprecated and will be removed'); - } - } - ); - - testWithBuiltCli( - 'shows the browser deprecation warning in browser help and subcommand help', + 'points every removed browser invocation to scrape and interact', () => { for (const args of [ + ['browser', 'open https://example.com'], + ['browser', 'launch-session', '--ttl', '600'], + ['browser', 'execute', '--python', 'print(1)'], + ['browser', 'close', '--session', 'abc'], ['browser', '--help'], - ['browser', 'list', '--help'], + ['help', 'browser'], ]) { const result = spawnSync(process.execPath, [cliPath, ...args], { encoding: 'utf8', env: { ...process.env, FIRECRAWL_NO_UPDATE_CHECK: '1' }, }); - expect(result.status).toBe(0); - expect(result.stdout).toContain( - '`firecrawl browser` is deprecated and will be removed' - ); + expect(result.status).toBe(1); + expect(result.stderr).toContain('`firecrawl browser` was removed'); + expect(result.stderr).toContain('firecrawl interact'); + expect(result.stdout).toBe(''); } } ); diff --git a/src/__tests__/commands/browser.test.ts b/src/__tests__/commands/browser.test.ts deleted file mode 100644 index 9a2eab9000..0000000000 --- a/src/__tests__/commands/browser.test.ts +++ /dev/null @@ -1,325 +0,0 @@ -/** - * Browser commands – minimal viable tests - */ - -import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { - handleBrowserLaunch, - handleBrowserExecute, - handleBrowserList, - handleBrowserClose, - handleBrowserQuickExecute, -} from '../../commands/browser'; -import { getClient } from '../../utils/client'; -import { initializeConfig } from '../../utils/config'; -import { setupTest, teardownTest } from '../utils/mock-client'; - -vi.mock('child_process', () => ({ spawn: vi.fn() })); - -vi.mock('../../utils/client', async () => { - const actual = await vi.importActual('../../utils/client'); - return { ...actual, getClient: vi.fn() }; -}); - -vi.mock('../../utils/browser-session', async () => { - const actual = await vi.importActual('../../utils/browser-session'); - return { - ...actual, - saveBrowserSession: vi.fn(), - loadBrowserSession: vi.fn().mockReturnValue({ - id: 'stored-session-id', - cdpUrl: 'wss://stored', - createdAt: '2025-01-01T00:00:00Z', - }), - clearBrowserSession: vi.fn(), - getSessionId: vi.fn((override?: string) => override || 'stored-session-id'), - }; -}); - -vi.mock('../../utils/output', () => ({ writeOutput: vi.fn() })); - -const mockExit = vi - .spyOn(process, 'exit') - .mockImplementation((() => {}) as any); -const mockConsoleError = vi - .spyOn(console, 'error') - .mockImplementation(() => {}); -const mockConsoleLog = vi.spyOn(console, 'log').mockImplementation(() => {}); - -describe('Browser Commands', () => { - let mockClient: any; - - beforeEach(() => { - setupTest(); - initializeConfig({ - apiKey: 'test-api-key', - apiUrl: 'https://api.firecrawl.dev', - }); - mockClient = { - browser: vi.fn(), - browserExecute: vi.fn(), - listBrowsers: vi.fn(), - deleteBrowser: vi.fn(), - }; - vi.mocked(getClient).mockReturnValue(mockClient as any); - }); - - afterEach(() => { - teardownTest(); - vi.clearAllMocks(); - }); - - it('launch passes origin cli to browser()', async () => { - mockClient.browser.mockResolvedValue({ - success: true, - id: 'session-123', - cdpUrl: 'wss://cdp.example.com/session-123', - }); - - await handleBrowserLaunch({}); - - expect(mockClient.browser).toHaveBeenCalledWith( - expect.objectContaining({ integration: 'cli' }) - ); - }); - - it('launch passes origin cli alongside other options', async () => { - mockClient.browser.mockResolvedValue({ - success: true, - id: 'session-123', - cdpUrl: 'wss://cdp.example.com/session-123', - }); - - await handleBrowserLaunch({ - ttl: 600, - ttlInactivity: 120, - profile: 'my-profile', - saveChanges: true, - }); - - expect(mockClient.browser).toHaveBeenCalledWith( - expect.objectContaining({ - integration: 'cli', - ttl: 600, - activityTtl: 120, - profile: { name: 'my-profile', saveChanges: true }, - }) - ); - }); - - it('launch saves session on success', async () => { - mockClient.browser.mockResolvedValue({ - success: true, - id: 'session-123', - cdpUrl: 'wss://cdp.example.com/session-123', - liveViewUrl: 'https://live.example.com/browser-id', - }); - - await handleBrowserLaunch({}); - - const { saveBrowserSession } = await import('../../utils/browser-session'); - expect(saveBrowserSession).toHaveBeenCalledWith( - expect.objectContaining({ id: 'session-123' }) - ); - }); - - it('launch exits 1 on failure', async () => { - mockClient.browser.mockResolvedValue({ - success: false, - error: 'Not authorized', - }); - - await handleBrowserLaunch({}); - - expect(mockExit).toHaveBeenCalledWith(1); - }); - - it('execute sends python code to correct session', async () => { - mockClient.browserExecute.mockResolvedValue({ - success: true, - result: 'Example Domain', - }); - - await handleBrowserExecute({ code: 'await page.title()' }); - - expect(mockClient.browserExecute).toHaveBeenCalledWith( - 'stored-session-id', - { - code: 'await page.title()', - language: 'bash', - } - ); - }); - - it('list returns sessions', async () => { - mockClient.listBrowsers.mockResolvedValue({ success: true, sessions: [] }); - - await handleBrowserList({}); - - expect(mockClient.listBrowsers).toHaveBeenCalledTimes(1); - }); - - it('close deletes and clears stored session', async () => { - mockClient.deleteBrowser.mockResolvedValue({ success: true }); - - await handleBrowserClose({}); - - expect(mockClient.deleteBrowser).toHaveBeenCalledWith('stored-session-id'); - const { clearBrowserSession } = await import('../../utils/browser-session'); - expect(clearBrowserSession).toHaveBeenCalled(); - }); - - it('quick execute skips launch when session exists', async () => { - // loadBrowserSession already returns a stored session (from mock) - // so quick execute should NOT call browser() to launch - await handleBrowserQuickExecute({ code: 'open https://example.com' }); - - expect(mockClient.browser).not.toHaveBeenCalled(); - }); - - it('quick execute auto-launches when no session exists', async () => { - const { loadBrowserSession, saveBrowserSession } = - await import('../../utils/browser-session'); - vi.mocked(loadBrowserSession).mockReturnValueOnce(null); // no session first call - vi.mocked(loadBrowserSession).mockReturnValue({ - // session exists after launch - id: 'new-session', - cdpUrl: 'wss://new', - createdAt: '2025-01-01T00:00:00Z', - }); - - mockClient.browser.mockResolvedValue({ - success: true, - id: 'new-session', - cdpUrl: 'wss://new', - }); - - await handleBrowserQuickExecute({ code: 'open https://example.com' }); - - expect(mockClient.browser).toHaveBeenCalledTimes(1); - expect(mockClient.browser).toHaveBeenCalledWith( - expect.objectContaining({ integration: 'cli' }) - ); - expect(saveBrowserSession).toHaveBeenCalledWith( - expect.objectContaining({ id: 'new-session' }) - ); - }); - - it('quick execute auto-launch passes origin cli with profile', async () => { - const { loadBrowserSession } = await import('../../utils/browser-session'); - vi.mocked(loadBrowserSession).mockReturnValueOnce(null); - vi.mocked(loadBrowserSession).mockReturnValue({ - id: 'new-session', - cdpUrl: 'wss://new', - createdAt: '2025-01-01T00:00:00Z', - }); - - mockClient.browser.mockResolvedValue({ - success: true, - id: 'new-session', - cdpUrl: 'wss://new', - }); - - await handleBrowserQuickExecute({ - code: 'open https://example.com', - profile: 'dev', - saveChanges: false, - }); - - expect(mockClient.browser).toHaveBeenCalledWith( - expect.objectContaining({ - integration: 'cli', - profile: { name: 'dev', saveChanges: false }, - }) - ); - }); - - it('quick execute retries with new session on 403 Forbidden', async () => { - const { clearBrowserSession, saveBrowserSession } = - await import('../../utils/browser-session'); - - // First execute call fails with 403 (stale cached session) - const forbiddenError = Object.assign(new Error('Forbidden'), { - status: 403, - }); - mockClient.browserExecute - .mockRejectedValueOnce(forbiddenError) - .mockResolvedValueOnce({ - success: true, - stdout: 'page loaded', - }); - - // Launch new session succeeds - mockClient.browser.mockResolvedValue({ - success: true, - id: 'fresh-session', - cdpUrl: 'wss://fresh', - }); - - await handleBrowserQuickExecute({ code: 'open https://example.com' }); - - expect(clearBrowserSession).toHaveBeenCalled(); - expect(mockClient.browser).toHaveBeenCalledTimes(1); - expect(saveBrowserSession).toHaveBeenCalledWith( - expect.objectContaining({ id: 'fresh-session' }) - ); - expect(mockClient.browserExecute).toHaveBeenCalledTimes(2); - }); - - it('quick execute retries with new session on 410 Gone', async () => { - const { clearBrowserSession } = await import('../../utils/browser-session'); - - const goneError = Object.assign(new Error('Gone'), { status: 410 }); - mockClient.browserExecute - .mockRejectedValueOnce(goneError) - .mockResolvedValueOnce({ - success: true, - stdout: 'page loaded', - }); - - mockClient.browser.mockResolvedValue({ - success: true, - id: 'fresh-session', - cdpUrl: 'wss://fresh', - }); - - await handleBrowserQuickExecute({ code: 'open https://example.com' }); - - expect(clearBrowserSession).toHaveBeenCalled(); - expect(mockClient.browser).toHaveBeenCalledTimes(1); - expect(mockClient.browserExecute).toHaveBeenCalledTimes(2); - }); - - it('quick execute retries on "session destroyed" error message', async () => { - const { clearBrowserSession } = await import('../../utils/browser-session'); - - mockClient.browserExecute - .mockRejectedValueOnce(new Error('session has been destroyed')) - .mockResolvedValueOnce({ - success: true, - stdout: 'ok', - }); - - mockClient.browser.mockResolvedValue({ - success: true, - id: 'fresh-session', - cdpUrl: 'wss://fresh', - }); - - await handleBrowserQuickExecute({ code: 'open https://example.com' }); - - expect(clearBrowserSession).toHaveBeenCalled(); - expect(mockClient.browserExecute).toHaveBeenCalledTimes(2); - }); - - it('quick execute exits on non-session errors without retry', async () => { - mockClient.browserExecute.mockRejectedValueOnce( - new Error('Network timeout') - ); - - await handleBrowserQuickExecute({ code: 'open https://example.com' }); - - expect(mockClient.browser).not.toHaveBeenCalled(); - expect(mockExit).toHaveBeenCalledWith(1); - }); -}); diff --git a/src/commands/browser.ts b/src/commands/browser.ts deleted file mode 100644 index c433cdeec1..0000000000 --- a/src/commands/browser.ts +++ /dev/null @@ -1,447 +0,0 @@ -/** - * Browser command implementation - * Manages cloud browser sessions via the Firecrawl SDK - */ - -import { spawn } from 'child_process'; -import { getClient } from '../utils/client'; -import { - saveBrowserSession, - loadBrowserSession, - clearBrowserSession, - getSessionId, -} from '../utils/browser-session'; -import { writeOutput } from '../utils/output'; - -export interface BrowserLaunchOptions { - ttl?: number; - ttlInactivity?: number; - profile?: string; - saveChanges?: boolean; - apiKey?: string; - apiUrl?: string; - output?: string; - json?: boolean; -} - -export interface BrowserExecuteOptions { - code: string; - language?: 'python' | 'node' | 'bash'; - session?: string; - apiKey?: string; - apiUrl?: string; - output?: string; - json?: boolean; -} - -export interface BrowserListOptions { - status?: 'active' | 'destroyed'; - apiKey?: string; - apiUrl?: string; - output?: string; - json?: boolean; -} - -export interface BrowserCloseOptions { - session?: string; - apiKey?: string; - apiUrl?: string; - output?: string; - json?: boolean; -} - -export interface BrowserQuickExecuteOptions { - code: string; - profile?: string; - saveChanges?: boolean; - apiKey?: string; - apiUrl?: string; - output?: string; - json?: boolean; -} - -/** - * Launch a new browser session - */ -export async function handleBrowserLaunch( - options: BrowserLaunchOptions -): Promise { - try { - const app = getClient({ apiKey: options.apiKey, apiUrl: options.apiUrl }); - - const args: { - ttl?: number; - activityTtl?: number; - profile?: { - name: string; - saveChanges?: boolean; - }; - integration?: string; - } = { integration: 'cli' }; - if (options.ttl !== undefined) args.ttl = options.ttl; - if (options.ttlInactivity !== undefined) - args.activityTtl = options.ttlInactivity; - if (options.profile) { - args.profile = { - name: options.profile, - saveChanges: options.saveChanges, - }; - } - - const data = await app.browser(args as Parameters[0]); - - if (!data.success) { - console.error('Error:', data.error || 'Unknown error'); - process.exit(1); - } - - // Save session for future commands - saveBrowserSession({ - id: data.id!, - cdpUrl: data.cdpUrl!, - createdAt: new Date().toISOString(), - }); - - if (options.json) { - const output = JSON.stringify(data, null, 2); - writeOutput(output, options.output, !!options.output); - } else { - const lines: string[] = []; - lines.push(`Session ID: ${data.id}`); - lines.push(`CDP URL: ${data.cdpUrl}`); - if ((data as any).interactiveLiveViewUrl) { - lines.push( - `Interactive Live View URL (recommended): ${(data as any).interactiveLiveViewUrl}` - ); - } - if (data.liveViewUrl) { - lines.push(`Live View URL: ${data.liveViewUrl}`); - } - writeOutput(lines.join('\n'), options.output, !!options.output); - } - } catch (error) { - console.error( - 'Error:', - error instanceof Error ? error.message : 'Unknown error occurred' - ); - process.exit(1); - } -} - -/** - * Execute a bash command locally with CDP_URL and SESSION_ID env vars. - * agent-browser reads CDP_URL from the environment automatically. - */ -export function executeBashLocally( - command: string, - session: { id: string; cdpUrl: string } -): Promise<{ stdout: string; stderr: string; exitCode: number }> { - return new Promise((resolve) => { - const child = spawn('sh', ['-c', command], { - env: { - ...process.env, - CDP_URL: session.cdpUrl, - SESSION_ID: session.id, - }, - stdio: ['inherit', 'pipe', 'pipe'], - }); - - let stdout = ''; - let stderr = ''; - - child.stdout.on('data', (data: Buffer) => { - stdout += data.toString(); - }); - child.stderr.on('data', (data: Buffer) => { - stderr += data.toString(); - }); - - child.on('close', (code: number | null) => { - resolve({ stdout, stderr, exitCode: code ?? 1 }); - }); - }); -} - -/** - * Detect if an error indicates an expired or destroyed browser session. - */ -function isSessionExpiredError(error: unknown): boolean { - const msg = - error instanceof Error - ? error.message.toLowerCase() - : String(error).toLowerCase(); - const status = (error as { status?: number }).status; - if (status === 403 || status === 410 || status === 404) return true; - return /destroyed|expired|not found|gone|session.*closed/i.test(msg); -} - -/** - * Execute code in a browser session - */ -export async function handleBrowserExecute( - options: BrowserExecuteOptions -): Promise { - try { - const sessionId = getSessionId(options.session); - const app = getClient({ apiKey: options.apiKey, apiUrl: options.apiUrl }); - - const data = await app.browserExecute(sessionId, { - code: options.code, - language: options.language || 'bash', - }); - - if (!data.success) { - console.error('Error:', data.error || 'Unknown error'); - process.exit(1); - } - - if (data.error) { - process.stderr.write(`Code error: ${data.error}\n`); - } - - if (options.json) { - const output = JSON.stringify(data, null, 2); - writeOutput(output, options.output, !!options.output); - } else { - const result = data.stdout || data.result || ''; - if (result) { - writeOutput(result.trimEnd(), options.output, !!options.output); - } - } - } catch (error) { - if (isSessionExpiredError(error)) { - const sessionId = - options.session || loadBrowserSession()?.id || 'unknown'; - console.error( - `Error: Session ${sessionId} has expired or been destroyed.\n` + - 'The session may have exceeded its TTL or been closed.\n' + - 'Start a new session with: firecrawl browser launch' - ); - const stored = loadBrowserSession(); - if (stored && !options.session) { - clearBrowserSession(); - } - } else { - console.error( - 'Error:', - error instanceof Error ? error.message : 'Unknown error occurred' - ); - } - process.exit(1); - } -} - -/** - * List browser sessions - */ -export async function handleBrowserList( - options: BrowserListOptions -): Promise { - try { - const app = getClient({ apiKey: options.apiKey, apiUrl: options.apiUrl }); - - const data = await app.listBrowsers( - options.status ? { status: options.status } : undefined - ); - - if (!data.success) { - console.error('Error:', data.error || 'Unknown error'); - process.exit(1); - } - - const sessions = data.sessions || []; - - if (options.json) { - const output = JSON.stringify(data, null, 2); - writeOutput(output, options.output, !!options.output); - } else { - if (sessions.length === 0) { - writeOutput( - 'No active browser sessions.', - options.output, - !!options.output - ); - } else { - const lines: string[] = []; - for (const s of sessions) { - const age = s.createdAt - ? `created ${new Date(s.createdAt).toLocaleString()}` - : ''; - lines.push(`${s.id} ${s.status} ${age}`); - } - writeOutput(lines.join('\n'), options.output, !!options.output); - } - } - } catch (error) { - console.error( - 'Error:', - error instanceof Error ? error.message : 'Unknown error occurred' - ); - process.exit(1); - } -} - -/** - * Shorthand: auto-launch a session if needed, then execute an agent-browser command. - * Enables `firecrawl browser "open example.com"` without a separate launch step. - */ -export async function handleBrowserQuickExecute( - options: BrowserQuickExecuteOptions -): Promise { - async function launchNewSession(): Promise { - const app = getClient({ apiKey: options.apiKey, apiUrl: options.apiUrl }); - - const launchArgs: { - profile?: { - name: string; - saveChanges?: boolean; - }; - integration?: string; - } = { integration: 'cli' }; - if (options.profile) { - launchArgs.profile = { - name: options.profile, - saveChanges: options.saveChanges, - }; - } - - const data = await app.browser( - launchArgs as Parameters[0] - ); - - if (!data.success) { - console.error('Error:', data.error || 'Failed to launch session'); - process.exit(1); - } - - saveBrowserSession({ - id: data.id!, - cdpUrl: data.cdpUrl!, - createdAt: new Date().toISOString(), - }); - - console.error(`Session launched: ${data.id}`); - } - - // Auto-launch if no active session - if (!loadBrowserSession()) { - try { - await launchNewSession(); - } catch (error) { - console.error( - 'Error:', - error instanceof Error ? error.message : 'Failed to launch session' - ); - process.exit(1); - } - } - - // Auto-prefix agent-browser if needed - let finalCode = options.code; - if (!finalCode.startsWith('agent-browser')) { - finalCode = `agent-browser ${finalCode}`; - } - - const executeOptions = { - code: finalCode, - language: 'bash' as const, - apiKey: options.apiKey, - apiUrl: options.apiUrl, - output: options.output, - json: options.json, - }; - - // Try executing; if the cached session is stale, launch a new one and retry - try { - const sessionId = getSessionId(); - const app = getClient({ apiKey: options.apiKey, apiUrl: options.apiUrl }); - - const data = await app.browserExecute(sessionId, { - code: executeOptions.code, - language: executeOptions.language, - }); - - if (!data.success) { - console.error('Error:', data.error || 'Unknown error'); - process.exit(1); - } - - if (data.error) { - process.stderr.write(`Code error: ${data.error}\n`); - } - - if (options.json) { - const output = JSON.stringify(data, null, 2); - writeOutput(output, options.output, !!options.output); - } else { - const result = data.stdout || data.result || ''; - if (result) { - writeOutput(result.trimEnd(), options.output, !!options.output); - } - } - } catch (error) { - if (isSessionExpiredError(error)) { - console.error('Cached session expired, launching a new one...'); - clearBrowserSession(); - - try { - await launchNewSession(); - } catch (launchError) { - console.error( - 'Error:', - launchError instanceof Error - ? launchError.message - : 'Failed to launch session' - ); - process.exit(1); - } - - // Retry with the new session - await handleBrowserExecute(executeOptions); - } else { - console.error( - 'Error:', - error instanceof Error ? error.message : 'Unknown error occurred' - ); - process.exit(1); - } - } -} - -/** - * Close a browser session - */ -export async function handleBrowserClose( - options: BrowserCloseOptions -): Promise { - try { - const sessionId = getSessionId(options.session); - const app = getClient({ apiKey: options.apiKey, apiUrl: options.apiUrl }); - - const data = await app.deleteBrowser(sessionId); - - if (!data.success) { - console.error('Error:', data.error || 'Unknown error'); - process.exit(1); - } - - // Clear stored session - const stored = loadBrowserSession(); - if (stored && stored.id === sessionId) { - clearBrowserSession(); - } - - console.log(`Session closed (${sessionId})`); - - if (options.json) { - const output = JSON.stringify({ success: true, id: sessionId }, null, 2); - writeOutput(output, options.output, !!options.output); - } - } catch (error) { - console.error( - 'Error:', - error instanceof Error ? error.message : 'Unknown error occurred' - ); - process.exit(1); - } -} diff --git a/src/index.ts b/src/index.ts index 1271d2f226..f8e4651a6d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -56,13 +56,6 @@ import { parseEndpointFeedbackEndpoint, } from './commands/feedback'; import { handleAgentCommand, handleAgentThreadCommand } from './commands/agent'; -import { - handleBrowserLaunch, - handleBrowserExecute, - handleBrowserList, - handleBrowserClose, - handleBrowserQuickExecute, -} from './commands/browser'; import { handleInteractExecute, handleInteractStop } from './commands/interact'; import { handleVersionCommand } from './commands/version'; import { handleLoginCommand } from './commands/login'; @@ -123,7 +116,6 @@ const AUTH_REQUIRED_COMMANDS = [ 'feedback', 'search-feedback', 'agent', - 'browser', 'credit-usage', 'monitor', ]; @@ -2225,307 +2217,6 @@ function createAgentCommand(): Command { return agentCmd; } -/** - * Create and configure the browser command (deprecated — prefer scrape + interact) - */ -function createBrowserCommand(): Command { - const deprecationWarning = - 'Warning: `firecrawl browser` is deprecated and will be removed in a future release. Use `firecrawl scrape `, then `firecrawl interact ""` or `firecrawl interact -c ""`. See `firecrawl interact --help`.'; - const browserCmd = new Command('browser') - .description( - '[Deprecated: prefer scrape + interact] Launch cloud browser sessions and execute code remotely via Playwright' - ) - .argument('[code]', 'Shorthand: auto-launch session + execute command') - .option( - '-k, --api-key ', - 'Firecrawl API key (overrides global --api-key)' - ) - .option('--api-url ', 'API URL (overrides global --api-url)') - .option( - '--profile ', - 'Name for a profile (survives close, reconnect by name later)' - ) - .option( - '--no-save-changes', - 'Load existing profile data without saving changes (default: saves changes)' - ) - .option('-o, --output ', 'Output file path (default: stdout)') - .option('--json', 'Output as JSON format', false) - .hook('preAction', () => { - process.stderr.write(`${deprecationWarning}\n`); - }) - .addHelpText('beforeAll', `${deprecationWarning}\n`) - .action(async (code, options) => { - if (code) { - await handleBrowserQuickExecute({ - code, - profile: options.profile, - saveChanges: options.saveChanges, - 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 ', - 'Total session TTL in seconds (default: 300)', - parseInt - ) - .option('--ttl-inactivity ', 'Inactivity TTL in seconds', parseInt) - .option( - '--profile ', - 'Name for a profile (survives close, reconnect by name later)' - ) - .option( - '--no-save-changes', - 'Load existing profile data without saving changes (default: saves changes)' - ) - .option( - '-k, --api-key ', - 'Firecrawl API key (overrides global --api-key)' - ) - .option('--api-url ', 'API URL (overrides global --api-url)') - .option('-o, --output ', '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 --ttl 600 - $ firecrawl browser launch-session --ttl 300 --ttl-inactivity 60 - $ firecrawl browser launch-session --profile my-session - $ firecrawl browser launch-session --profile my-session --no-save-changes - $ firecrawl browser launch-session -o session.json --json -` - ) - .action(async (options) => { - await handleBrowserLaunch({ - ttl: options.ttl, - ttlInactivity: options.ttlInactivity, - profile: options.profile, - saveChanges: options.saveChanges, - 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( - '', - '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 ', - 'Session ID (default: active session from last launch)' - ) - .option( - '-k, --api-key ', - 'Firecrawl API key (overrides global --api-key)' - ) - .option('--api-url ', 'API URL (overrides global --api-url)') - .option('-o, --output ', '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 "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 ', - 'Firecrawl API key (overrides global --api-key)' - ) - .option('--api-url ', 'API URL (overrides global --api-url)') - .option('-o, --output ', '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 ', - 'Session ID (default: active session from last launch)' - ) - .option( - '-k, --api-key ', - 'Firecrawl API key (overrides global --api-key)' - ) - .option('--api-url ', 'API URL (overrides global --api-url)') - .option('-o, --output ', 'Output file path (default: stdout)') - .option('--json', 'Output as JSON format', false) - .addHelpText( - 'after', - ` -Examples: - $ firecrawl browser close - $ firecrawl browser close --session -` - ) - .action(async (options) => { - await handleBrowserClose({ - session: options.session, - apiKey: options.apiKey, - apiUrl: options.apiUrl, - output: options.output, - json: options.json, - }); - }); - - return browserCmd; -} - /** * Create and configure the interact command */ @@ -2691,8 +2382,21 @@ program.addCommand(createSearchFeedbackCommand()); program.addCommand(createAgentCommand()); program.addCommand(createInteractCommand()); -// Hidden: deprecated browser command (still works, just not in --help) -program.addCommand(createBrowserCommand(), { hidden: true }); +const browserRemoved = (): never => { + console.error( + 'Error: `firecrawl browser` was removed. Use `firecrawl scrape `, then `firecrawl interact ""` or `firecrawl interact -c ""`. See `firecrawl interact --help`.' + ); + process.exit(1); +}; +program.addCommand( + new Command('browser') + .helpOption(false) + .allowUnknownOption() + .allowExcessArguments() + .on('beforeHelp', browserRemoved) + .action(browserRemoved), + { hidden: true } +); // Hidden: `firecrawl create ` — scaffolds Firecrawl starter projects. // Undocumented until `firecrawl-agent-cli` is published to npm; flip to diff --git a/src/utils/browser-session.ts b/src/utils/browser-session.ts deleted file mode 100644 index af4ccefb15..0000000000 --- a/src/utils/browser-session.ts +++ /dev/null @@ -1,107 +0,0 @@ -/** - * Browser session persistence utility - * Stores active browser session info in platform-specific config directory - */ - -import * as fs from 'fs'; -import * as path from 'path'; -import * as os from 'os'; - -export interface StoredBrowserSession { - id: string; - cdpUrl: string; - createdAt: string; -} - -/** - * Get the platform-specific config directory - */ -function getConfigDir(): string { - const homeDir = os.homedir(); - const platform = os.platform(); - - switch (platform) { - case 'darwin': - return path.join( - homeDir, - 'Library', - 'Application Support', - 'firecrawl-cli' - ); - case 'win32': - return path.join(homeDir, 'AppData', 'Roaming', 'firecrawl-cli'); - default: - return path.join(homeDir, '.config', 'firecrawl-cli'); - } -} - -/** - * Get the browser session file path - */ -function getSessionPath(): string { - return path.join(getConfigDir(), 'browser-session.json'); -} - -/** - * Ensure the config directory exists - */ -function ensureConfigDir(): void { - const configDir = getConfigDir(); - if (!fs.existsSync(configDir)) { - fs.mkdirSync(configDir, { recursive: true, mode: 0o700 }); - } -} - -/** - * Save active browser session to disk - */ -export function saveBrowserSession(session: StoredBrowserSession): void { - ensureConfigDir(); - const sessionPath = getSessionPath(); - fs.writeFileSync(sessionPath, JSON.stringify(session, null, 2), 'utf-8'); -} - -/** - * Load stored browser session from disk - */ -export function loadBrowserSession(): StoredBrowserSession | null { - try { - const sessionPath = getSessionPath(); - if (!fs.existsSync(sessionPath)) { - return null; - } - const data = fs.readFileSync(sessionPath, 'utf-8'); - return JSON.parse(data) as StoredBrowserSession; - } catch { - return null; - } -} - -/** - * Clear stored browser session from disk - */ -export function clearBrowserSession(): void { - try { - const sessionPath = getSessionPath(); - if (fs.existsSync(sessionPath)) { - fs.unlinkSync(sessionPath); - } - } catch { - // Ignore errors - } -} - -/** - * Resolve session ID from override flag or stored session - */ -export function getSessionId(overrideId?: string): string { - if (overrideId) return overrideId; - - const stored = loadBrowserSession(); - if (stored) return stored.id; - - throw new Error( - 'No active browser session. Launch one with: firecrawl browser launch\n' + - 'Or specify a session ID with: --session ' - ); -}