跳到主要内容

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
= 自动生成
此文件系统实例的唯一标识符

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
文件系统实例标识符

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 路径都保持一致。