跳至主要內容

LocalFilesystem

新增於: @mastra/core@1.1.0

將檔案儲存在本機檔案系統的目錄中。介面詳情請參閱 WorkspaceFilesystem 介面

使用方式
「使用方式」的直接連結

LocalFilesystem 加入 Workspace,並指派給 Agent。Agent 接著就能在執行任務時讀取、寫入及管理檔案:

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
= Auto-generated
此檔案系統執行個體的唯一識別碼

contained?:

boolean
= true
設為 true 時,所有檔案操作都會限制在 basePath 內,以防止路徑周遊攻擊和 symlink 逸出。請參閱範圍限制

allowedPaths?:

string[]
= []
Agent 可在 basePath 以外存取的其他目錄。

instructions?:

string | ((opts: { defaultInstructions: string; requestContext?: RequestContext }) => string)
自訂指示,用於覆寫 getInstructions() 傳回的預設指示。傳入字串可完全取代預設指示;傳入函式則可存取目前的 requestContext 並擴充指示,以便針對每個要求自訂。

readOnly?:

boolean
= false
設為 true 時,會封鎖所有寫入操作,但仍允許讀取操作。

屬性
「屬性」的直接連結

id:

string
檔案系統執行個體識別碼

name:

string
Provider 名稱('LocalFilesystem')。

provider:

string
Provider 識別碼('local')。

basePath:

string
磁碟上的絕對基底路徑

readOnly:

boolean | undefined
檔案系統是否處於唯讀模式

allowedPaths:

readonly string[]
目前已解析的允許路徑集合。啟用範圍限制時,這些路徑可位於 basePath 之外。

方法
「方法」的直接連結

init()
「init」的直接連結

初始化檔案系統。如果基底目錄不存在,則建立該目錄。

await filesystem.init()

workspace.init() 呼叫。

延遲初始化
「延遲初始化」的直接連結

如果尚未初始化,LocalFilesystem 會在第一次操作時進行初始化,並自動建立基底目錄。你可以選擇明確呼叫 init();若要在第一次操作前預先建立目錄,這麼做會很有用。

destroy()
「destroy」的直接連結

清除檔案系統資源。

await filesystem.destroy()

workspace.destroy() 呼叫。

setAllowedPaths(pathsOrUpdater)
「setallowedpathspathsorupdater」的直接連結

在執行階段更新允許的路徑。可接受新的路徑陣列(取代目前陣列),或接受更新程式回呼函式;該函式會收到目前路徑並傳回新的集合。

// 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?)
「readfilepath-options」的直接連結

讀取檔案內容。

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?)
「writefilepath-content-options」的直接連結

將內容寫入檔案。

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
若上層目錄不存在則建立

overwrite?:

boolean
覆寫現有檔案

expectedMtime?:

Date
提供此值時,如果檔案目前的修改時間不相符,寫入會因 StaleFileError 而失敗。可用於樂觀並行控制,以偵測讀取與寫入之間的外部修改。

appendFile(path, content)
「appendfilepath-content」的直接連結

將內容附加至現有檔案。

await filesystem.appendFile('/logs/app.log', 'New log entry\n')

參數:

path:

string
相對於 basePath 的檔案路徑。

content:

string | Buffer
要附加的內容

deleteFile(path, options?)
「deletefilepath-options」的直接連結

刪除檔案。

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?)
「copyfilesrc-dest-options」的直接連結

將檔案複製到新位置。

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?)
「movefilesrc-dest-options」的直接連結

移動檔案或重新命名。

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?)
「mkdirpath-options」的直接連結

建立目錄。

await filesystem.mkdir('/docs/api')
await filesystem.mkdir('/deeply/nested/path', { recursive: true })

參數:

path:

string
目錄路徑

options?:

Options
設定選項。
Options

recursive?:

boolean
建立上層目錄

rmdir(path, options?)
「rmdirpath-options」的直接連結

移除目錄。

await filesystem.rmdir('/docs/old')
await filesystem.rmdir('/docs/nested', { recursive: true })

參數:

path:

string
目錄路徑

options?:

Options
設定選項。
Options

recursive?:

boolean
以遞迴方式移除內容

force?:

boolean
目錄不存在時不擲回錯誤

readdir(path, options?)
「readdirpath-options」的直接連結

列出目錄內容。

const entries = await filesystem.readdir('/docs')
// [{ name: 'guide.md', type: 'file' }, { name: 'api', type: 'directory' }]

exists(path)
「existspath」的直接連結

檢查路徑是否存在。

const exists = await filesystem.exists('/docs/guide.md')

stat(path)
「statpath」的直接連結

取得檔案或目錄的中繼資料。

const stat = await filesystem.stat('/docs/guide.md')
// { type: 'file', size: 1234, modifiedAt: Date, createdAt: Date, path: '/docs/guide.md' }

getInfo()
「getinfo」的直接連結

傳回此檔案系統執行個體的中繼資料。

const info = filesystem.getInfo()
// { id: '...', name: 'LocalFilesystem', provider: 'local', basePath: '/workspace', readOnly: false }

getInstructions(opts?)
「getinstructionsopts」的直接連結

傳回此檔案系統中路徑運作方式的說明。指派給 Agent 時,此說明會注入 Agent 的系統訊息。

const instructions = filesystem.getInstructions()
// 'Local filesystem at "/workspace". Files at workspace path "/foo" are stored at "/workspace/foo" on disk.'

當建構函式的 instructions 選項是函式時,傳入 requestContext 即可針對每個要求自訂:

const instructions = filesystem.getInstructions({ requestContext })

參數:

opts.requestContext?:

RequestContext
如果建構函式中提供了 instructions 函式,便會轉傳給該函式。

傳回值: string

若要覆寫預設輸出,請將 instructions 選項傳入建構函式。請參閱建構函式參數

路徑解析
「路徑解析」的直接連結

basePath 的運作方式
「how-basepath-works」的直接連結

basePath 選項會設定所有檔案操作的根目錄。傳給 readFile() 等方法的檔案路徑會相對於此基底解析:

  • 移除開頭斜線:/docs/guide.mddocs/guide.md
  • 正規化路徑並與 basePath 結合
  • 結果:./workspace + docs/guide.md./workspace/docs/guide.md
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
直接執行指令碼執行指令的所在位置相對於該位置

當同一個相對路徑解析到不同位置時,可能會造成混淆。

若要讓所有執行環境都使用一致的路徑,請使用包含絕對路徑的環境變數:

import { LocalFilesystem } from '@mastra/core/workspace'

const filesystem = new LocalFilesystem({
basePath: process.env.WORKSPACE_PATH!,
})

在環境中將 WORKSPACE_PATH 設為絕對路徑,例如 /home/user/my-project/workspace。如此一來,無論如何執行程式碼,Workspace 路徑都能保持一致。