> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt # MastraBrowser class `MastraBrowser` class 是瀏覽器自動化 Provider 的抽象基底 class。其共用介面涵蓋啟動瀏覽器、隔離 thread、串流 screencast,以及輸入事件。 你不會直接建立 `MastraBrowser` instance,而是使用 Provider 實作: - [`AgentBrowser`](https://mastra.zisheng.pro/zh-HK/reference/browser/agent-browser):使用 ref 的確定性瀏覽器自動化 - [`StagehandBrowser`](https://mastra.zisheng.pro/zh-HK/reference/browser/stagehand-browser):使用自然語言的 AI 瀏覽器自動化 - [`BrowserViewer`](https://mastra.zisheng.pro/zh-HK/reference/browser/browser-viewer):透過注入 CDP URL 進行以 CLI 為基礎的瀏覽器自動化 ## 使用範例 ```typescript import { Agent } from '@mastra/core/agent' import { AgentBrowser } from '@mastra/agent-browser' const browser = new AgentBrowser({ headless: true, viewport: { width: 1280, height: 720 }, scope: 'thread', }) export const browserAgent = new Agent({ id: 'browser-agent', name: 'Browser Agent', instructions: 'You can browse the web to find information.', model: 'openai/gpt-5.6-sol', browser, }) ``` ## Constructor 參數 **headless** (`boolean`): 是否以 headless 模式執行瀏覽器(不顯示 UI)。 (Default: `true`) **viewport** (`{ width: number; height: number } | 'window'`): 瀏覽器 viewport 尺寸,用於控制瀏覽器視窗大小。設為 'window' 可配合實際瀏覽器視窗,而非使用固定尺寸;agent-browser Provider 及透過 CDP 連線時的 Stagehand 均支援此設定。 (Default: `{ width: 1280, height: 720 }`) **timeout** (`number`): 預設逾時時間(毫秒)。每個 Provider 都會自行定義其語意及預設值,詳情請參閱相應 Provider 的參考文件。 **cdpUrl** (`string | (() => string | Promise)`): CDP WebSocket URL、HTTP endpoint,或同步/非同步 Provider function。提供此項時,系統會連線至現有瀏覽器,而不會啟動新瀏覽器。HTTP endpoint 會在內部解析成 WebSocket。不能與 scope: 'thread' 一併使用(會自動採用 shared scope)。 **scope** (`'shared' | 'thread'`): 各 thread 之間的瀏覽器 instance scope。'shared' 表示所有 thread 共用一個瀏覽器 instance;'thread' 表示每個 thread 都有自己的瀏覽器 instance(完全隔離)。 (Default: `'thread' (or 'shared' when cdpUrl is provided)`) **onLaunch** (`(args: { browser: MastraBrowser }) => void | Promise`): 瀏覽器進入 'ready' 狀態後呼叫的 callback。 **onClose** (`(args: { browser: MastraBrowser }) => void | Promise`): 關閉瀏覽器前呼叫的 callback。 **screencast** (`ScreencastOptions`): 串流瀏覽器 frame 的設定。 **screencast.format** (`'jpeg' | 'png'`): Screencast frame 的影像格式。 **screencast.quality** (`number`): 影像品質(1–100),只適用於 JPEG 格式。 **screencast.maxWidth** (`number`): Screencast frame 的最大寬度。 **screencast.maxHeight** (`number`): Screencast frame 的最大高度。 **screencast.everyNthFrame** (`number`): 每隔 N 個 frame 擷取一次,以減少頻寬用量。 ## Properties 以下 property(`id`、`name`、`provider`)屬於 abstract,必須由具體的 Provider 實作定義: **id** (`string`): 此瀏覽器 instance 的唯一識別碼。屬於 abstract,由 Provider 定義。 **name** (`string`): 方便閱讀的瀏覽器 Provider 名稱(例如 'AgentBrowser'、'StagehandBrowser')。屬於 abstract,由 Provider 定義。 **provider** (`string`): Provider 識別碼(例如 'vercel-labs/agent-browser'、'browserbase/stagehand')。屬於 abstract,由 Provider 定義。 **headless** (`boolean`): 瀏覽器是否正以 headless 模式執行。 **status** (`BrowserStatus`): 目前的瀏覽器狀態:'pending'、'launching'、'ready'、'error'、'closing' 或 'closed'。 ## Methods ### 生命週期 #### `ensureReady()` 確保瀏覽器已啟動並可供使用。系統會在執行 Tool 前自動呼叫此方法。此方法在基底 class 中實作。 ```typescript await browser.ensureReady() ``` #### `close()` 關閉瀏覽器並清理所有資源。此方法在基底 class 中實作,並以能安全處理 race condition 的方式運作。 ```typescript await browser.close() ``` #### `isBrowserRunning()` 檢查瀏覽器目前是否正在執行。 ```typescript const isRunning = browser.isBrowserRunning() ``` **傳回:** `boolean` ### Thread 管理 #### `setCurrentThread(threadId)` 設定瀏覽器操作目前使用的 thread ID。Agent runtime 會在內部使用此方法。 ```typescript browser.setCurrentThread('thread-123') ``` #### `getCurrentThread()` 取得目前的 thread ID。 ```typescript const threadId = browser.getCurrentThread() ``` **Returns:** `string` #### `hasThreadSession(threadId)` 檢查某個 thread 是否有使用中的瀏覽器 session。 ```typescript const hasSession = browser.hasThreadSession('thread-123') ``` **Returns:** `boolean` #### `closeThreadSession(threadId)` 關閉指定 thread 的瀏覽器 session。使用 'thread' scope 時,會關閉該 thread 的瀏覽器 instance;使用 'shared' scope 時,則會清除 thread 狀態。 ```typescript await browser.closeThreadSession('thread-123') ``` ### Tools #### `getTools()` 傳回供 Agent 使用的瀏覽器 Tool。每個 Provider 會按其模型傳回不同的 Tool。 ```typescript const tools = browser.getTools() ``` **傳回:** `Record` ### Screencast #### `startScreencast(options?, threadId?)` 開始串流瀏覽器 frame。傳回會發出 frame event 的 `ScreencastStream`。 ```typescript const stream = await browser.startScreencast({ format: 'jpeg', quality: 80 }, 'thread-123') stream.on('frame', frame => { console.log('Frame received:', frame.data.length, 'bytes') }) stream.on('stop', reason => { console.log('Screencast stopped:', reason) }) ``` **傳回:** `Promise` ### 輸入注入 #### `injectMouseEvent(params, threadId?)` 將滑鼠事件注入瀏覽器。Studio 會使用此方法進行即時互動。 ```typescript await browser.injectMouseEvent({ type: 'mousePressed', x: 100, y: 200, button: 'left', clickCount: 1, }) ``` #### `injectKeyboardEvent(params, threadId?)` 將鍵盤事件注入瀏覽器。Studio 會使用此方法進行即時互動。 ```typescript await browser.injectKeyboardEvent({ type: 'keyDown', key: 'Enter', code: 'Enter', }) ``` ### 狀態 #### `getState(threadId?)` 取得目前的瀏覽器狀態,包括 URL 及分頁。 ```typescript const state = await browser.getState('thread-123') console.log('Current URL:', state.currentUrl) console.log('Tabs:', state.tabs) ``` **Returns:** `Promise` ```typescript interface BrowserState { currentUrl: string | null tabs: BrowserTabState[] activeTabIndex: number } interface BrowserTabState { id: string url: string title: string } ``` #### `getCurrentUrl(threadId?)` 取得目前頁面的 URL。 ```typescript const url = await browser.getCurrentUrl() ``` **Returns:** `Promise` ## 瀏覽器 scope `scope` 選項控制瀏覽器 instance 如何在各個對話 thread 之間共用: | Scope | 說明 | 使用情境 | | ---------- | --------------------------- | ---------------- | | `'shared'` | 所有 thread 共用一個瀏覽器 instance | 適合互不衝突的工作,成本效益較高 | | `'thread'` | 每個 thread 都有自己的瀏覽器 instance | 為同時使用的用戶提供完全隔離 | ```typescript // Shared browser for all threads const sharedBrowser = new AgentBrowser({ scope: 'shared', }) // Isolated browser per thread const isolatedBrowser = new AgentBrowser({ scope: 'thread', }) ``` 使用 `cdpUrl` 連線至外部瀏覽器時,由於無法產生新的瀏覽器 instance,scope 會自動退回 `'shared'`。 ## 雲端瀏覽器 Provider 使用 `cdpUrl` 選項連線至雲端瀏覽器服務: ```typescript // Static CDP URL const browser = new AgentBrowser({ cdpUrl: 'wss://browser.example.com/ws', }) // Dynamic CDP URL (e.g., session-based) const browser = new AgentBrowser({ cdpUrl: async () => { const session = await createBrowserSession() return session.wsUrl }, }) ``` ## 相關內容 - [AgentBrowser](https://mastra.zisheng.pro/zh-HK/reference/browser/agent-browser):確定性瀏覽器自動化 - [StagehandBrowser](https://mastra.zisheng.pro/zh-HK/reference/browser/stagehand-browser):AI 瀏覽器自動化 - [瀏覽器概覽](https://mastra.zisheng.pro/zh-HK/docs/browser/overview):瀏覽器自動化概念指南