> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt # LocalFilesystem **新增於:** `@mastra/core@1.1.0` 將檔案儲存在本機檔案系統的目錄中。介面詳情請參閱 [WorkspaceFilesystem 介面](https://mastra.zisheng.pro/zh-HK/reference/workspace/filesystem)。 ## 使用方式 將 `LocalFilesystem` 加入 Workspace 並指派給 Agent。Agent 隨後便可在執行工作期間讀取、寫入及管理檔案: ```typescript import { Agent } from '@mastra/core/agent' import { Workspace, LocalFilesystem } from '@mastra/core/workspace' const workspace = new Workspace({ filesystem: new LocalFilesystem({ basePath: './workspace', }), }) const agent = new Agent({ id: 'file-agent', model: 'openai/gpt-5.6-sol', workspace, }) // The agent now has filesystem tools available const response = await agent.generate('List all files in the workspace') ``` ## 建構函式參數 **basePath** (`string`): 磁碟上的基礎目錄路徑。所有檔案路徑均相對於此目錄解析。 **id** (`string`): 此檔案系統實例的唯一識別碼 (Default: `自動產生`) **contained** (`boolean`): 設為 true 時,所有檔案操作均限制在 basePath 內,以防止路徑遍歷攻擊及符號連結逸出。請參閱範圍限制。 (Default: `true`) **allowedPaths** (`string[]`): Agent 可在 basePath 以外存取的其他目錄。 (Default: `[]`) **instructions** (`string | ((opts: { defaultInstructions: string; requestContext?: RequestContext }) => string)`): 自訂指示,用以覆寫 getInstructions() 傳回的預設指示。傳入字串可完全取代預設指示;傳入函式則可在存取目前 requestContext 的情況下擴充指示,以針對每個請求自訂設定。 **readOnly** (`boolean`): 設為 true 時,所有寫入操作均會被封鎖,但仍允許讀取操作。 (Default: `false`) ## 屬性 **id** (`string`): 檔案系統實例識別碼 **name** (`string`): Provider 名稱 ('LocalFilesystem') **provider** (`string`): Provider 識別碼 ('local') **basePath** (`string`): 磁碟上的絕對基礎路徑 **readOnly** (`boolean | undefined`): 檔案系統是否處於唯讀模式 **allowedPaths** (`readonly string[]`): 目前已解析的允許路徑集合。啟用範圍限制時,這些路徑可位於 basePath 以外。 ## 方法 ### `init()` 初始化檔案系統。如果基礎目錄不存在,便會建立該目錄。 ```typescript await filesystem.init() ``` 由 `workspace.init()` 呼叫。 ### 延遲初始化 如果尚未初始化,LocalFilesystem 會在第一次操作時初始化,並自動建立基礎目錄。你可選擇明確呼叫 `init()`,以便在第一次操作前預先建立目錄。 ### `destroy()` 清理檔案系統資源。 ```typescript await filesystem.destroy() ``` 由 `workspace.destroy()` 呼叫。 ### `setAllowedPaths(pathsOrUpdater)` 在執行階段更新允許的路徑。可接受新的路徑陣列(取代目前陣列),或接受更新器回呼函式;該函式會接收目前路徑並傳回新集合。 ```typescript // Set directly filesystem.setAllowedPaths(['/home/user/.config']) // Update with callback filesystem.setAllowedPaths(prev => [...prev, '/home/user/documents']) // Clear all allowed paths filesystem.setAllowedPaths([]) ``` **參數:** **pathsOrUpdater** (`string[] | ((current: readonly string[]) => string[])`): 新的允許路徑陣列,或接收目前路徑的更新器函式 ### `readFile(path, options?)` 讀取檔案內容。 ```typescript const content = await filesystem.readFile('/docs/guide.md') const buffer = await filesystem.readFile('/image.png', { encoding: 'binary' }) ``` **參數:** **path** (`string`): 相對於 basePath 的檔案路徑 **options** (`Options`): 設定選項。 **options.encoding** (`'utf-8' | 'binary'`): 文字或二進制編碼 ### `writeFile(path, content, options?)` 將內容寫入檔案。 ```typescript await filesystem.writeFile('/docs/new.md', '# New Document') await filesystem.writeFile('/nested/path/file.md', content, { recursive: true }) ``` **參數:** **path** (`string`): 相對於 basePath 的檔案路徑 **content** (`string | Buffer`): 檔案內容 **options** (`Options`): 設定選項。 **options.recursive** (`boolean`): 如果上層目錄不存在,便建立該目錄 **options.overwrite** (`boolean`): 覆寫現有檔案 **options.expectedMtime** (`Date`): 如有提供,當檔案目前的修改時間不相符時,寫入便會失敗並出現 StaleFileError。可用於樂觀並行控制,以偵測讀取與寫入之間的外部修改。 ### `appendFile(path, content)` 將內容附加至現有檔案。 ```typescript await filesystem.appendFile('/logs/app.log', 'New log entry\n') ``` **參數:** **path** (`string`): 相對於 basePath 的檔案路徑 **content** (`string | Buffer`): 要附加的內容 ### `deleteFile(path, options?)` 刪除檔案。 ```typescript await filesystem.deleteFile('/docs/old.md') await filesystem.deleteFile('/docs/maybe.md', { force: true }) // Don't throw if missing ``` **參數:** **path** (`string`): 檔案路徑 **options** (`Options`): 設定選項。 **options.force** (`boolean`): 檔案不存在時不要擲回錯誤 ### `copyFile(src, dest, options?)` 將檔案複製到新位置。 ```typescript await filesystem.copyFile('/docs/template.md', '/docs/new-doc.md') await filesystem.copyFile('/src/config.json', '/backup/config.json', { overwrite: false }) ``` **參數:** **src** (`string`): 來源檔案路徑 **dest** (`string`): 目標檔案路徑 **options** (`Options`): 設定選項。 **options.overwrite** (`boolean`): 如果目標已存在便覆寫 ### `moveFile(src, dest, options?)` 移動檔案或重新命名。 ```typescript await filesystem.moveFile('/docs/draft.md', '/docs/final.md') await filesystem.moveFile('/temp/upload.txt', '/files/document.txt') ``` **參數:** **src** (`string`): 來源檔案路徑 **dest** (`string`): 目標檔案路徑 **options** (`Options`): 設定選項。 **options.overwrite** (`boolean`): 如果目標已存在便覆寫 ### `mkdir(path, options?)` 建立目錄。 ```typescript await filesystem.mkdir('/docs/api') await filesystem.mkdir('/deeply/nested/path', { recursive: true }) ``` **參數:** **path** (`string`): 目錄路徑 **options** (`Options`): 設定選項。 **options.recursive** (`boolean`): 建立上層目錄 ### `rmdir(path, options?)` 移除目錄。 ```typescript await filesystem.rmdir('/docs/old') await filesystem.rmdir('/docs/nested', { recursive: true }) ``` **參數:** **path** (`string`): 目錄路徑 **options** (`Options`): 設定選項。 **options.recursive** (`boolean`): 遞迴移除內容 **options.force** (`boolean`): 目錄不存在時不要擲回錯誤 ### `readdir(path, options?)` 列出目錄內容。 ```typescript const entries = await filesystem.readdir('/docs') // [{ name: 'guide.md', type: 'file' }, { name: 'api', type: 'directory' }] ``` ### `exists(path)` 檢查路徑是否存在。 ```typescript const exists = await filesystem.exists('/docs/guide.md') ``` ### `stat(path)` 取得檔案或目錄的中繼資料。 ```typescript const stat = await filesystem.stat('/docs/guide.md') // { type: 'file', size: 1234, modifiedAt: Date, createdAt: Date, path: '/docs/guide.md' } ``` ### `getInfo()` 傳回此檔案系統實例的中繼資料。 ```typescript const info = filesystem.getInfo() // { id: '...', name: 'LocalFilesystem', provider: 'local', basePath: '/workspace', readOnly: false } ``` ### `getInstructions(opts?)` 傳回此檔案系統中路徑運作方式的說明。指派給 Agent 後,此內容會注入 Agent 的系統訊息。 ```typescript const instructions = filesystem.getInstructions() // 'Local filesystem at "/workspace". Files at workspace path "/foo" are stored at "/workspace/foo" on disk.' ``` 當建構函式的 `instructions` 選項是函式時,傳入 `requestContext` 即可為每個請求啟用自訂設定: ```typescript const instructions = filesystem.getInstructions({ requestContext }) ``` **參數:** **opts.requestContext** (`RequestContext`): 如果建構函式有提供 instructions 函式,便會轉交給該函式。 **傳回:** `string` 如要覆寫預設輸出,請將 `instructions` 選項傳入建構函式。請參閱[建構函式參數](#constructor-parameters)。 ## 路徑解析 ### `basePath` 的運作方式 `basePath` 選項會設定所有檔案操作的根目錄。傳入 `readFile()` 等方法的檔案路徑,會相對於此基礎目錄解析: - 移除開頭的斜線:`/docs/guide.md` → `docs/guide.md` - 將路徑正規化,並與 basePath 合併 - 結果:`./workspace` + `docs/guide.md` → `./workspace/docs/guide.md` ```typescript const filesystem = new LocalFilesystem({ basePath: './workspace', }) // These all resolve to ./workspace/docs/guide.md await filesystem.readFile('/docs/guide.md') await filesystem.readFile('docs/guide.md') ``` ### 相對路徑與執行內容 當 `basePath` 使用相對路徑時,會由 `process.cwd()` 開始解析。在 Mastra 項目中,cwd 會因程式碼的執行方式而有所不同: | 執行內容 | 工作目錄 | `./workspace` 解析為 | | -------------- | ---------------------- | ------------------------------- | | `mastra dev` | `./src/mastra/public/` | `./src/mastra/public/workspace` | | `mastra start` | `./.mastra/output/` | `./.mastra/output/workspace` | | 直接執行指令碼 | 你執行指令的所在位置 | 相對於該位置 | 同一個相對路徑可能會解析至不同位置,因而造成混淆。 ### 建議:使用絕對路徑 為確保所有執行內容中的路徑一致,請使用包含絕對路徑的環境變數: ```typescript import { LocalFilesystem } from '@mastra/core/workspace' const filesystem = new LocalFilesystem({ basePath: process.env.WORKSPACE_PATH!, }) ``` 在環境中將 `WORKSPACE_PATH` 設為 `/home/user/my-project/workspace` 之類的絕對路徑。這可確保無論以何種方式執行程式碼,Workspace 路徑都保持一致。 ## 相關內容 - [WorkspaceFilesystem 介面](https://mastra.zisheng.pro/zh-HK/reference/workspace/filesystem) - [Workspace 類別](https://mastra.zisheng.pro/zh-HK/reference/workspace/workspace-class) - [Workspace 概覽](https://mastra.zisheng.pro/zh-HK/docs/workspace/overview)