> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-TW/llms.txt # Workspace 類別 **新增於:** `@mastra/core@1.1.0` `Workspace` 類別結合檔案系統與 Sandbox,為 Agent 提供檔案儲存及指令執行能力。它也支援對已建立索引的內容進行 BM25 與向量搜尋。 ## 使用範例 ```typescript import { Workspace, LocalFilesystem, LocalSandbox } from '@mastra/core/workspace' const workspace = new Workspace({ id: 'my-workspace', name: 'My Workspace', filesystem: new LocalFilesystem({ basePath: './workspace', }), sandbox: new LocalSandbox({ workingDirectory: './workspace', }), bm25: true, autoIndexPaths: ['docs'], }) ``` ## 建構函式參數 **id** (`string`): Workspace 的唯一識別碼 (Default: `自動產生`) **name** (`string`): 易讀名稱。 (Default: `workspace-{id}`) **filesystem** (`WorkspaceFilesystem | WorkspaceFilesystemResolver`): 檔案系統 Provider 執行個體,或接收 requestContext 並為每個請求傳回檔案系統的解析器函式。請參閱 動態檔案系統。 **sandbox** (`WorkspaceSandbox | WorkspaceSandboxResolver`): Sandbox Provider 執行個體,或接收 requestContext 並為每個請求傳回 Sandbox 的解析器函式。請參閱 動態 Sandbox。 **instructions.dynamicSandbox** (`'placeholder' | 'resolve' | (({ requestContext }) => string)`): 控制以解析器為後端的 sandbox 如何提供 Workspace 指示。'placeholder'(預設)會在不呼叫解析器的情況下產生穩定文字;'resolve' 會呼叫解析器並使用 Sandbox 自身的指示;函式則不進行解析而傳回自訂文字。此設定不影響靜態 Sandbox。 (Default: `'placeholder'`) **sandboxCacheKey** (`({ requestContext }) => string | undefined`): 以解析器為後端的 sandbox 所使用的穩定快取鍵。設定後,已解析的 Sandbox 會依快取鍵進行記憶化,而不是依 RequestContext 執行個體記憶,讓背景處理程序 Tool 可在後續請求中連線至同一個 Sandbox。此設定不影響靜態 Sandbox。 **bm25** (`boolean | BM25Config`): 啟用 BM25 關鍵字搜尋。傳入 true 可使用預設值,或傳入設定物件。 (Default: `undefined`) **vectorStore** (`MastraVector`): 語意搜尋使用的向量儲存空間 **embedder** (`Embedder`): 將文字轉換為向量的函式。設定 vectorStore 時必須提供。可接受單一文字函式 (text: string) => Promise\,或具備 batch: true 屬性及選用 maxBatchSize 的批次函式 (texts: string\[]) => Promise\。請參閱 批次嵌入。 **autoIndexPaths** (`string[]`): 在 init() 時自動建立索引的路徑或 glob 模式。支援如 '\*\*/\*.md' 的 glob 模式以選擇性建立索引。 **skills** (`string[] | ((context: SkillsContext) => string[] | Promise)`): SKILL.md 檔案所在的路徑。可以是靜態陣列,也可以是動態解析路徑的非同步函式。支援如 './\*\*/skills' 的 glob 模式進行探索。 **skillSource** (`SkillSource`): Skill 探索使用的自訂 Skill 來源。提供後會使用此來源取代 Workspace 檔案系統。可使用 VersionedSkillSource,從內容可定址的 blob 儲存空間提供已發布的 Skill 版本。 **onMount** (`OnMountHook`): 每個檔案系統掛載至 Sandbox 前呼叫的預掛載 hook。傳回 false 可略過掛載;如果 hook 已處理掛載,請傳回 { success: true };傳回 undefined 則使用預設掛載行為。 **searchIndexName** (`string`): 向量儲存空間的自訂索引名稱。必須是有效的 SQL 識別碼(以字母或底線開頭,只能包含字母、數字或底線,最多 63 個字元)。預設為清理過的 '{id}\_search'。 **tools** (`WorkspaceToolsConfig`): 各 Tool 的設定,用於啟用 Tool 並設定安全選項 **tools.enabled** (`boolean`): Agent 是否可使用此 Tool **tools.requireApproval** (`boolean`): Tool 執行前是否需要使用者核准 **tools.name** (`string`): 此 Tool 對外公開時使用的自訂名稱。會取代預設的 mastra\_workspace\_\* 名稱,但設定鍵仍必須使用原始 WORKSPACE\_TOOLS 常數。 **tools.requireReadBeforeWrite** (`boolean`): 寫入 Tool:要求先讀取檔案以防止覆寫 **tools.maxOutputTokens** (`number`): Tool 輸出的最大 Token 數。超過此限制的輸出會使用 tiktoken 截斷。 **tools.writeLockTimeoutMs** (`number`): 寫入 Tool 在失敗前等待取得各檔案寫入鎖定的最長時間,單位為毫秒。對速度較慢或冷啟動的檔案系統(例如遠端 Sandbox)可提高此值。 **tools.hooks** (`WorkspaceToolHooks`): 每次呼叫已啟用的 Workspace Tool 前後執行的 hook。請參閱下方的 Tool hook。 **operationTimeout** (`number`): 操作逾時時間,單位為毫秒 ## Tool 設定 `tools` 選項接受 `WorkspaceToolsConfig` 物件,用來控制啟用哪些 Workspace Tool 及其安全設定。 ```typescript import { Workspace } from '@mastra/core/workspace' import { WORKSPACE_TOOLS } from '@mastra/core/workspace' const workspace = new Workspace({ id: 'my-workspace', name: 'My Workspace', tools: { // Global defaults (apply to all tools) enabled: true, requireApproval: false, // Per-tool overrides using WORKSPACE_TOOLS constants [WORKSPACE_TOOLS.FILESYSTEM.WRITE_FILE]: { requireApproval: true, }, }, }) ``` 設定物件分為兩個部分: - **全域預設值**(`enabled`、`requireApproval`):除非遭到覆寫,否則套用至所有 Tool - **各 Tool 覆寫值**:使用 `WORKSPACE_TOOLS` 常數作為鍵來設定個別 Tool 更多範例請參閱 [Workspace 概觀](https://mastra.zisheng.pro/zh-TW/docs/workspace/overview)。 ### Tool 名稱重新對應 在個別 Tool 設定中設定 `name` 屬性,即可重新命名 Workspace Tool。設定鍵仍維持原始常數,只有向 Agent 公開的名稱會變更。 ```typescript import { Workspace } from '@mastra/core/workspace' import { WORKSPACE_TOOLS } from '@mastra/core/workspace' const workspace = new Workspace({ id: 'my-workspace', name: 'My Workspace', tools: { [WORKSPACE_TOOLS.FILESYSTEM.READ_FILE]: { name: 'view' }, [WORKSPACE_TOOLS.FILESYSTEM.GREP]: { name: 'search_content' }, }, }) ``` 所有 Workspace Tool 的名稱都必須唯一。設定與其他 Tool 預設或自訂名稱衝突的自訂名稱時,會擲回錯誤。 ### Tool hook 設定 `tools.hooks`,即可在每次呼叫已啟用的 Workspace Tool 前後執行邏輯。hook 會在名稱重新對應後執行,因此其內容同時包含公開的 `toolName` 與原始 `workspaceToolName`。 ```typescript import { Workspace } from '@mastra/core/workspace' const workspace = new Workspace({ id: 'my-workspace', tools: { hooks: { beforeToolCall: ({ toolName, workspaceToolName, input }) => { console.log(`Running ${toolName} (${workspaceToolName})`, input) }, afterToolCall: ({ toolName, output, error }) => { console.log(`Finished ${toolName}`, { output, error }) }, }, }, }) ``` **beforeToolCall** (`(context: WorkspaceToolHookContext) => void | WorkspaceToolBeforeHookResult | Promise`): 在 Workspace Tool 執行前執行。接收 { toolName, workspaceToolName, input, context }。傳回 { proceed: false, output } 可略過 Tool 呼叫,並以 output 作為結果。 **afterToolCall** (`(context: WorkspaceToolAfterHookContext) => void | Promise`): 在 Workspace Tool 執行後執行。接收 { toolName, workspaceToolName, input, context, output, error }。Tool 擲回錯誤時,output 為 undefined,並會改為設定 error。 如果所屬 Agent 也定義了 [Tool hook](https://mastra.zisheng.pro/zh-TW/reference/agents/agent),Workspace hook 會在 Agent hook 包裝器內執行。順序為 Agent `beforeToolCall` → Workspace `beforeToolCall` → Tool → Workspace `afterToolCall` → Agent `afterToolCall`。 ## 屬性 **id** (`string`): Workspace 識別碼 **name** (`string`): Workspace 名稱 **status** (`WorkspaceStatus`): 'pending' | 'initializing' | 'ready' | 'paused' | 'error' | 'destroying' | 'destroyed' **filesystem** (`WorkspaceFilesystem | undefined`): 靜態檔案系統 Provider。設定解析器函式時傳回 undefined;請使用 hasFilesystemConfig() 檢查是否可用。 **sandbox** (`WorkspaceSandbox | undefined`): 靜態 Sandbox Provider。設定解析器函式時傳回 undefined;請使用 hasSandboxConfig() 檢查是否可用。 **skills** (`WorkspaceSkills | undefined`): 用於存取 SKILL.md 檔案的 Skill 介面 **canBM25** (`boolean`): BM25 搜尋是否可用 **canVector** (`boolean`): 向量搜尋是否可用 **canHybrid** (`boolean`): 混合搜尋是否可用 ## 方法 ### 生命週期 #### `init()` 初始化 Workspace 並準備資源。 ```typescript await workspace.init() ``` 在大多數情況下,可選擇是否呼叫 `init()`: - **Sandbox**:第一次呼叫 `executeCommand()` 時會自動啟動。使用 `init()` 可避免第一個指令的延遲。 - **檔案系統**:建立基底目錄並執行各 Provider 的特定設定。部分 Provider 會在第一次操作時自動建立目錄。 - **搜尋**:只有使用 `autoIndexPaths` 自動建立索引時才需要。 初始化會執行下列操作: - 啟動檔案系統 Provider(必要時建立基底目錄) - 啟動 Sandbox Provider(建立工作目錄,並依設定建立隔離環境) - 為 `autoIndexPaths` 中的檔案建立搜尋索引 #### `destroy()` 銷毀 Workspace 並清除資源。 ```typescript await workspace.destroy() ``` `destroy()` 會依序關閉 Workspace 擁有的資源:語言伺服器、瀏覽器、Sandbox Provider 與檔案系統 Provider。它也會清除快取的 Sandbox 參照。 應用程式不再使用 Workspace 時,請呼叫 `destroy()`。`mastra.shutdown()` 會在關閉期間為已註冊的 Workspace 呼叫此方法。若要從 Mastra 登錄中移除 Workspace,請使用 [`mastra.removeWorkspace()`](https://mastra.zisheng.pro/zh-TW/reference/core/removeWorkspace)。 `LocalFilesystem.destroy()` 不會刪除磁碟上的檔案。以解析器為後端的檔案系統與 Sandbox Provider 由應用程式擁有,因此必須由應用程式清除。 ### 搜尋操作 #### `index(path, content, options?)` 為內容建立搜尋索引。 ```typescript await workspace.index('/docs/guide.md', 'Guide content...') ``` #### `search(query, options?)` 搜尋已建立索引的內容。 ```typescript const results = await workspace.search('password reset', { topK: 10, mode: 'hybrid', }) ``` ### 公用方法 #### `getInfo()` 取得 Workspace 資訊。 ```typescript const info = await workspace.getInfo() // { id, name, status, createdAt, lastAccessedAt, filesystem?, sandbox? } ``` 傳入 `resolveDynamicProviders: false`,即可將以解析器為後端的 Provider 回報為執行階段定義,而不呼叫其解析器。 ```typescript const info = await workspace.getInfo({ resolveDynamicProviders: false }) ``` **參數:** **options.includeFileCount** (`boolean`): 是否計算檔案總數。對大型 Workspace 而言,這項操作可能較慢。 **options.requestContext** (`RequestContext`): 啟用 resolveDynamicProviders 時傳給動態 Provider 解析器。 **options.resolveDynamicProviders** (`boolean`): 是否呼叫動態 Provider 解析器。如果只需要中繼資料,並希望以解析器為後端的 Provider 回報為 dynamic,請設為 false。 (Default: `true`) #### `getInstructions(opts?)` 傳回檔案系統與 Sandbox Provider 的合併指示。這些指示會插入 Agent 的系統訊息,協助 Agent 理解執行環境。 ```typescript const instructions = workspace.getInstructions() ``` 當 Provider 的 `instructions` 選項是函式時,傳入 `requestContext` 即可啟用各請求的自訂內容: ```typescript const instructions = workspace.getInstructions({ requestContext }) ``` **參數:** **opts.requestContext** (`RequestContext`): 如果檔案系統或 Sandbox Provider 設定了 instructions 函式,會轉傳給該函式。 **傳回:** `string` #### `getInstructionsAsync(opts?)` 傳回合併的 Workspace 指示。Workspace 使用以解析器為後端的 Provider 時,請使用此方法。執行階段定義的檔案系統會按請求解析;除非將 `instructions.dynamicSandbox` 設為 `'resolve'`,否則執行階段定義的 Sandbox 會提供穩定的預留位置文字。 ```typescript const instructions = await workspace.getInstructionsAsync({ requestContext }) ``` **參數:** **opts.requestContext** (`RequestContext`): 傳給動態檔案系統解析器;當 instructions.dynamicSandbox 為 'resolve' 時,也會傳給動態 Sandbox 解析器。 **傳回:** `Promise` 若要覆寫預設輸出,請將 `instructions` 選項傳給 [LocalFilesystem](https://mastra.zisheng.pro/zh-TW/reference/workspace/local-filesystem) 或 [LocalSandbox](https://mastra.zisheng.pro/zh-TW/reference/workspace/local-sandbox)。 #### `getToolsConfig()` 取得目前的 Tool 設定。 ```typescript const config = workspace.getToolsConfig() ``` **傳回:** `WorkspaceToolsConfig | undefined` #### `setToolsConfig(config?)` 在執行階段取代各 Tool 的設定。這會完整取代設定,不會與先前設定合併。傳入 `undefined` 可重設為預設值。變更會在 Agent 下次互動(下次呼叫 `createWorkspaceTools()`)時生效。 ```typescript import { WORKSPACE_TOOLS } from '@mastra/core/workspace' // Disable write tools for read-only mode workspace.setToolsConfig({ [WORKSPACE_TOOLS.FILESYSTEM.WRITE_FILE]: { enabled: false }, [WORKSPACE_TOOLS.FILESYSTEM.EDIT_FILE]: { enabled: false }, }) // Reset to defaults workspace.setToolsConfig(undefined) ``` **參數:** **config** (`WorkspaceToolsConfig | undefined`): 要套用的新 Tool 設定。傳入 undefined 可重設為預設值。 ### 動態檔案系統 #### `hasFilesystemConfig()` 檢查是否已將檔案系統設定為靜態執行個體或解析器函式。請使用此方法,而不要直接檢查 `workspace.filesystem`,因為以解析器為基礎的 Workspace 會從 `filesystem` 屬性傳回 `undefined`。 ```typescript if (workspace.hasFilesystemConfig()) { // Filesystem tools are available } ``` **傳回:** `boolean` #### `resolveFilesystem({ requestContext })` 為請求情境解析檔案系統。設定解析器函式時,會使用提供的 `requestContext` 呼叫該函式;設定靜態檔案系統時,則直接傳回該檔案系統。若未設定檔案系統,會傳回 `undefined`。 ```typescript import { RequestContext } from '@mastra/core/request-context' const ctx = new RequestContext([['agent-role', 'admin']]) const fs = await workspace.resolveFilesystem({ requestContext: ctx }) ``` **參數:** **requestContext** (`RequestContext`): 要傳給解析器函式的請求情境。 **傳回:** `Promise` ### 動態 Sandbox #### `hasSandboxConfig()` 檢查是否已將 Sandbox 設定為靜態執行個體或解析器函式。請使用此方法,而不要直接檢查 `workspace.sandbox`,因為以解析器為基礎的 Workspace 會從 `sandbox` 屬性傳回 `undefined`。 ```typescript if (workspace.hasSandboxConfig()) { // Sandbox tools are available } ``` **傳回:** `boolean` #### `resolveSandbox({ requestContext })` 為請求情境解析 Sandbox。設定解析器函式時,會使用提供的 `requestContext` 呼叫該函式;設定靜態 Sandbox 時,則直接傳回該 Sandbox。若未設定 Sandbox,會傳回 `undefined`。 ```typescript import { RequestContext } from '@mastra/core/request-context' const ctx = new RequestContext([['user-id', 'alice']]) const sandbox = await workspace.resolveSandbox({ requestContext: ctx }) ``` **參數:** **requestContext** (`RequestContext`): 要傳給解析器函式的請求情境。 **傳回:** `Promise` #### `clearSandboxCache(cacheKey?)` 清除由 `sandboxCacheKey` 快取、以解析器為後端的 Sandbox。傳入快取鍵可清除單一項目;省略則清除所有具快取鍵的 Sandbox 項目。 此方法不會清除各 `RequestContext` 的弱式快取。這些項目由垃圾回收機制管理。 Workspace 不擁有解析器傳回的 Sandbox。此方法只會捨棄 Workspace 參照;請在自己的生命週期程式碼中銷毀 Sandbox。 ```typescript workspace.clearSandboxCache('thread-123') workspace.clearSandboxCache() ``` **參數:** **cacheKey** (`string`): 要清除的快取鍵。省略此值可清除所有具快取鍵的 Sandbox 項目。 **傳回:** `void` ## Agent Tool Workspace 會依據設定向 Agent 提供 Tool。 ### 檔案系統 Tool 設定檔案系統時新增: | Tool | 說明 | | ----------------------------- | ---------------------------------------------------------------------------------------- | | `mastra_workspace_read_file` | 讀取檔案內容。文字檔會以文字傳回(可選擇行範圍)。圖片與 PDF 會以模型可直接檢視的原生媒體部分傳回。除非傳入明確的 `encoding`,否則其他二進位檔只會傳回中繼資料。 | | `mastra_workspace_write_file` | 使用新內容建立或覆寫檔案。會自動建立上層目錄。 | | `mastra_workspace_edit_file` | 透過尋找及取代文字來編輯現有檔案,適合不重寫整個檔案的精準變更。 | | `mastra_workspace_list_files` | 以樹狀結構列出目錄內容。支援具深度限制的遞迴列出、glob 模式及 `.gitignore` 篩選(預設啟用)。 | | `mastra_workspace_delete` | 刪除檔案或目錄。支援遞迴刪除目錄。 | | `mastra_workspace_file_stat` | 取得檔案或目錄的中繼資料,包括大小、類型與修改時間。 | | `mastra_workspace_mkdir` | 建立目錄。若上層目錄不存在,會自動建立。 | | `mastra_workspace_grep` | 使用正規表示式模式搜尋檔案內容。支援 glob 篩選、前後文行及不區分大小寫的搜尋。 | 使用靜態檔案系統時,若檔案系統處於唯讀模式,便不會包含寫入 Tool(`write_file`、`edit_file`、`delete`、`mkdir`)。使用 [執行階段定義的檔案系統](https://mastra.zisheng.pro/zh-TW/docs/workspace/filesystem)時,一律會包含寫入 Tool,並在執行階段強制執行唯讀限制。 `read_file` Tool 接受 `mediaTypes` 與 `maxMediaBytes` 選項,用來控制哪些 MIME 類型會以原生媒體部分提供給模型,以及這些檔案可有多大: **mediaTypes** (`string[] | ((mimeType: string) => boolean) | false`): 要以媒體部分(檔案/圖片部分)而非文字提供給模型的 MIME 類型。接受 glob 陣列(例如 \['image/\*'])、自訂判斷函式,或使用 false 停用媒體偵測。預設為各 Provider 都能安全支援的圖片格式交集加上 PDF。只在呼叫端未傳入明確 encoding 時套用。 (Default: `['image/png', 'image/jpeg', 'image/webp', 'application/pdf']`) **maxMediaBytes** (`number`): 要內嵌為媒體部分的檔案大小上限,單位為位元組。超過此大小的檔案只會輸出中繼資料,不會完整進行 base64 編碼後放入上下文,並在重新載入時持久保存至儲存空間。 (Default: `10 * 1024 * 1024(10 MiB)`) ```typescript const workspace = new Workspace({ filesystem: new LocalFilesystem({ basePath: './workspace' }), tools: { [WORKSPACE_TOOLS.FILESYSTEM.READ_FILE]: { // Broaden to any image (including SVG, BMP, HEIC) — may fail on some providers mediaTypes: ['image/*'], // Raise the inline-media cap to 25 MiB maxMediaBytes: 25 * 1024 * 1024, }, }, }) ``` ### Sandbox Tool 設定 Sandbox 時新增: | Tool | 說明 | | ------------------------------------- | --------------------------------------------------------------------------------------------------------- | | `mastra_workspace_execute_command` | 執行 shell 指令。傳回 stdout、stderr 與結束程式碼。Sandbox 具備處理程序管理器時,可接受 `background: true` 以產生長時間執行的處理程序並傳回 PID。 | | `mastra_workspace_get_process_output` | 依 PID 取得背景處理程序的 stdout、stderr 與狀態。接受 `tail` 以限制輸出行數,並接受 `wait: true` 以封鎖至處理程序結束。只有 Sandbox 具備處理程序管理器時才可用。 | | `mastra_workspace_kill_process` | 依 PID 終止背景處理程序。傳回最後 50 行輸出。只有 Sandbox 具備處理程序管理器時才可用。 | 使用靜態 Sandbox 時,會以 capability 檢查(`executeCommand`、`processes`)決定公開哪些 Tool 變體。使用 [執行階段定義的 Sandbox](https://mastra.zisheng.pro/zh-TW/docs/workspace/sandbox)時,會註冊所有 Sandbox Tool;若解析出的 Sandbox 未實作要求的 capability,執行階段會擲回明確錯誤。 `execute_command` Tool 接受 `backgroundProcesses` 選項,用於背景處理程序的生命週期回呼: **backgroundProcesses** (`BackgroundProcessesConfig`): 處理背景處理程序的設定。只在 Sandbox 支援背景執行時適用。 **backgroundProcesses.onStdout** (`(data: string, meta: BackgroundProcessMeta) => void`): 接收背景處理程序 stdout 區塊的回呼函式 **backgroundProcesses.onStderr** (`(data: string, meta: BackgroundProcessMeta) => void`): 接收背景處理程序 stderr 區塊的回呼函式 **backgroundProcesses.onExit** (`(meta: BackgroundProcessExitMeta) => void`): 背景處理程序結束時呼叫的回呼。中繼資料包含 pid、exitCode、stdout 與 stderr。 **backgroundProcesses.abortSignal** (`AbortSignal | null | false`): 背景處理程序的中止訊號。undefined(預設)會使用 Agent 的訊號;null 或 false 會停用中止功能,讓處理程序在 Agent 關閉後繼續執行。 使用範例請參閱 [背景處理程序回呼](https://mastra.zisheng.pro/zh-TW/docs/workspace/sandbox)。 ### 搜尋 Tool 設定 BM25 或向量搜尋時新增: | Tool | 說明 | | ------------------------- | ---------------------------------------------- | | `mastra_workspace_search` | 使用關鍵字(BM25)、語意(向量)或混合搜尋來搜尋已建立索引的內容。傳回含分數的排序結果。 | | `mastra_workspace_index` | 為內容建立搜尋索引,並將內容與路徑關聯以供後續擷取。 | 檔案系統處於唯讀模式時,不會包含 `index` Tool。 ### Skill Tool 設定 Skill 時新增: | Tool | 說明 | | -------------- | --------------------------------------------- | | `skill` | 依名稱或路徑啟用 Skill。傳回 Skill 的完整指示、參考資料、指令碼與資產。 | | `skill_search` | 跨 Skill 內容搜尋。接受用於篩選的選用 Skill 名稱清單與 `topK` 參數。 | | `skill_read` | 從 Skill 目錄讀取特定檔案(參考資料、指令碼或資產)。 | 多個 Skill 使用相同名稱時,`list()` 會傳回全部結果。以名稱呼叫 `get()` 時,會套用優先順序(local > managed > external)。如果兩個 Skill 的名稱與來源類型都相同,`get()` 會擲回錯誤。將 Skill 完整路徑傳給 `get()` 可略過優先順序判定。詳情請參閱 [同名 Skill](https://mastra.zisheng.pro/zh-TW/docs/workspace/skills)。