メインコンテンツへ移動

LocalFilesystem

追加バージョン: @mastra/core@1.1.0

ローカル Filesystem のディレクトリにファイルを保存します。インターフェースの詳細は、WorkspaceFilesystem インターフェースを参照してください。

使用方法
使用方法への直接リンク

Workspace に LocalFilesystem を追加して 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
この Filesystem インスタンスの一意な識別子。

contained?:

boolean
= true
true の場合、すべてのファイル操作を basePath 内に制限します。パストラバーサル攻撃とシンボリックリンクによる脱出を防ぎます。封じ込めを参照してください。

allowedPaths?:

string[]
= []
Agent が basePath の外部でアクセスできる追加ディレクトリ。

instructions?:

string | ((opts: { defaultInstructions: string; requestContext?: RequestContext }) => string)
getInstructions() が返すデフォルトの指示を上書きするカスタム指示。完全に置き換えるには文字列を、現在の requestContext を参照してリクエストごとにカスタマイズするには拡張関数を渡します。

readOnly?:

boolean
= false
true の場合、すべての書き込み操作を禁止します。読み取り操作は引き続き許可されます。

プロパティ
プロパティへの直接リンク

id:

string
Filesystem インスタンスの識別子。

name:

string
Provider 名('LocalFilesystem')。

provider:

string
Provider 識別子('local')。

basePath:

string
ディスク上の絶対ベースパス。

readOnly:

boolean | undefined
Filesystem が読み取り専用モードかどうか。

allowedPaths:

readonly string[]
解決済みの許可パスの現在の集合。封じ込めが有効な場合でも、これらのパスには basePath の外部からアクセスできます。

メソッド
メソッドへの直接リンク

init()
initへの直接リンク

Filesystem を初期化します。ベースディレクトリが存在しない場合は作成します。

await filesystem.init()

workspace.init() から呼び出されます。

遅延初期化
遅延初期化への直接リンク

LocalFilesystem が未初期化の場合は、最初の操作時に初期化され、ベースディレクトリが自動作成されます。init() の明示的な呼び出しは任意ですが、最初の操作前にディレクトリを作成しておく場合に便利です。

destroy()
destroyへの直接リンク

Filesystem のリソースをクリーンアップします。

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への直接リンク

この Filesystem インスタンスのメタデータを返します。

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

getInstructions(opts?)
getinstructionsoptsへの直接リンク

この Filesystem でのパスの扱いを説明する文を返します。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 のパスを統一できます。