跳到主要内容

Workspace

Workspace 为 Agent 提供文件系统访问和命令执行能力。通过 mastra devmastra build 发现的 File-based Agent 会自动获得默认 Workspace,因此无需额外配置即可读写文件和运行 shell 命令。

本页介绍基于文件的约定。有关 Workspace Provider、Tool、搜索、生命周期和 sandbox 的详细信息,请参阅 Workspace

默认 Workspace
默认 Workspace的直接链接

如果没有 workspace.ts,只要构建过程提供了每个 Agent 专属的 Workspace 路径,File-based Agent 就会获得默认 Workspace。默认 Workspace 使用:

这会自动为 Agent 提供文件 Tool 和 shell Tool。每个 Agent 都有独立的默认 Workspace;子 Agent 会在父级 Agent 的 Workspace 路径下获得嵌套的 Workspace 目录。

快速开始
快速开始的直接链接

使用默认 Workspace 时,不要添加文件。从如下 Agent 目录开始:

Default workspace
src/mastra/agents/weather/
├── config.ts
└── instructions.md

仅在需要自定义 Workspace 时添加 workspace.ts

src/mastra/agents/weather/workspace.ts
import { Workspace, LocalFilesystem, LocalSandbox } from '@mastra/core/workspace'

export default new Workspace({
name: 'weather-workspace',
filesystem: new LocalFilesystem({ basePath: './data/weather' }),
sandbox: new LocalSandbox({ workingDirectory: './data/weather' }),
})

有关完整配置,请查看 Workspace 参考

何时自定义 Workspace
何时自定义 Workspace的直接链接

当默认本地目录无法满足需求时,请自定义 Workspace。常见原因包括:

  • 将文件 Tool 指向其他文件系统根目录。
  • 在其他 sandbox Provider 中运行 shell 命令。
  • 使用 BM25 或向量搜索添加 Workspace 搜索。
  • 在多个 Agent 之间共享一个 Workspace。

有关 Provider 模式和运行时行为,请参阅 Workspace 概览sandbox 指南Workspace 搜索

运行时边界
运行时边界的直接链接

Workspace 文件系统控制文件 Tool 可以读写的内容。sandbox 控制 shell 命令的运行位置。应用运行时代码(包括 tools/ 中的代码)仍会在应用/server 进程中运行,除非它显式调用 Workspace 或 sandbox API。

种子文件
种子文件的直接链接

添加 workspace/ 目录,为 Agent 提供初始文件。Mastra 会在构建时将 workspace/ 下的文件镜像到 Agent 的默认运行时 Workspace,因此 Agent 启动时这些文件已存在于磁盘上。

Seed files
src/mastra/agents/weather/
├── config.ts
└── workspace/
├── README.md
└── data/
└── cities.json

这些文件会复制到 bundle 中的 Workspace 路径,Workspace 文件 Tool 和 sandbox 命令可以在那里读取它们。镜像期间会跳过符号链接的种子文件。

与 config 的优先级
与 config 的优先级的直接链接

config.workspace 优先于 workspace.ts;否则使用默认的 File-based Workspace。有关完整的合并表,请参阅 config.ts 优先级