> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # LocalFilesystem **添加于:** `@mastra/core@1.1.0` 将文件存储在本地文件系统的一个目录中。有关接口的详细信息,请参阅 [WorkspaceFilesystem 接口](https://mastra.zisheng.pro/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/reference/workspace/filesystem) - [Workspace 类](https://mastra.zisheng.pro/reference/workspace/workspace-class) - [Workspace 概述](https://mastra.zisheng.pro/docs/workspace/overview)