Skip to main content

工作区类

🌐 Workspace Class

Workspace 类结合了文件系统和沙箱,为代理提供文件存储和命令执行功能。它还支持对索引内容进行 BM25 和向量搜索。

🌐 The Workspace class combines a filesystem and sandbox to provide agents with file storage and command execution capabilities. It also supports BM25 and vector search for indexed content.

使用示例
Direct link to 使用示例

🌐 Usage Example

import { Workspace, LocalFilesystem, LocalSandbox } from '@mastra/core/workspace';

const workspace = new Workspace({
id: 'my-workspace',
name: 'My Workspace',
filesystem: new LocalFilesystem({
basePath: './workspace',
}),
sandbox: new LocalSandbox({
workingDirectory: './workspace',
}),
bm25: true,
autoIndexPaths: ['/docs'],
});

构造函数参数
Direct link to 构造函数参数

🌐 Constructor parameters

id?:

string
= Auto-generated
Unique identifier for the workspace

name?:

string
= workspace-{id}
Human-readable name

filesystem?:

WorkspaceFilesystem
Filesystem provider instance (e.g., LocalFilesystem)

sandbox?:

WorkspaceSandbox
Sandbox provider instance (e.g., LocalSandbox)

bm25?:

boolean | BM25Config
= undefined
Enable BM25 keyword search. Pass true for defaults or a config object.

vectorStore?:

MastraVector
Vector store for semantic search

embedder?:

(text: string) => Promise<number[]>
Embedder function for generating vectors. Required when vectorStore is provided.

autoIndexPaths?:

string[]
Paths to auto-index on init()

skills?:

string[] | ((context: SkillsContext) => string[] | Promise<string[]>)
Paths where SKILL.md files are located. This can be a static array or an async function that resolves paths dynamically.

tools?:

WorkspaceToolsConfig
Per-tool configuration for enabling tools and setting safety options

operationTimeout?:

number
Timeout for operations in milliseconds

工具配置
Direct link to 工具配置

🌐 Tool configuration

tools 选项接受一个 WorkspaceToolsConfig 对象,用于控制启用哪些工作区工具及其安全设置。

🌐 The tools option accepts a WorkspaceToolsConfig object that controls which workspace tools are enabled and their safety settings.

import { WORKSPACE_TOOLS } from '@mastra/core/workspace';

tools: {
// Global defaults (apply to all tools)
enabled: true,
requireApproval: false,

// Per-tool overrides using WORKSPACE_TOOLS constants
[WORKSPACE_TOOLS.FILESYSTEM.WRITE_FILE]: {
requireApproval: true,
},
}

配置对象有两个部分:

🌐 The config object has two parts:

  • 全局默认值enabledrequireApproval)- 适用于所有工具,除非被覆盖
  • 每个工具的覆盖设置 - 使用 WORKSPACE_TOOLS 常量作为键来配置单个工具

请参阅工作区概览以获取更多示例。

🌐 See workspace overview for more examples.

每个工具的选项
Direct link to 每个工具的选项

🌐 Per-tool options

每个工具都可以配置以下选项:

🌐 Each tool can be configured with these options:

enabled?:

boolean
= true
Whether the tool is available to agents

requireApproval?:

boolean
= false
Whether the tool requires user approval before execution

requireReadBeforeWrite?:

boolean
= false
For write tools: require reading the file first to prevent overwrites

属性
Direct link to 属性

🌐 Properties

id:

string
Workspace identifier

name:

string
Workspace name

status:

WorkspaceStatus
'pending' | 'initializing' | 'ready' | 'error' | 'destroying' | 'destroyed'

filesystem:

WorkspaceFilesystem | undefined
The filesystem provider

sandbox:

WorkspaceSandbox | undefined
The sandbox provider

skills:

WorkspaceSkills | undefined
Skills interface for accessing SKILL.md files

canBM25:

boolean
Whether BM25 search is available

canVector:

boolean
Whether vector search is available

canHybrid:

boolean
Whether hybrid search is available

方法
Direct link to 方法

🌐 Methods

生命周期
Direct link to 生命周期

🌐 Lifecycle

init()
Direct link to init

初始化工作区并准备资源。

🌐 Initialize the workspace and prepare resources.

await workspace.init();

在大多数情况下,调用 init() 是可选的:

🌐 Calling init() is optional in most cases:

  • 沙盒:在第一次 executeCommand() 调用时自动启动。使用 init() 可避免首次命令延迟。
  • 文件系统:仅在基础目录尚不存在时需要。
  • 搜索:仅在使用 autoIndexPaths 进行自动索引时才需要。

初始化执行:

🌐 Initialization performs:

  • 启动文件系统提供程序(如有需要则创建基础目录)
  • 启动沙箱提供程序(创建工作目录,如果配置了则设置隔离)
  • autoIndexPaths 为搜索索引文件

destroy()
Direct link to destroy

销毁工作区并清理资源。

🌐 Destroy the workspace and clean up resources.

await workspace.destroy();

搜索操作
Direct link to 搜索操作

🌐 Search operations

index(path, content, options?)
Direct link to indexpath-content-options

供搜索使用的索引内容。

🌐 Index content for search.

await workspace.index('/docs/guide.md', 'Guide content...');

search(query, options?)
Direct link to searchquery-options

搜索已编入索引的内容。

🌐 Search indexed content.

const results = await workspace.search('password reset', {
topK: 10,
mode: 'hybrid',
});

实用程序
Direct link to 实用程序

🌐 Utility

getInfo()
Direct link to getinfo

获取工作区信息。

🌐 Get workspace information.

const info = await workspace.getInfo();
// { id, name, status, createdAt, lastAccessedAt, filesystem?, sandbox? }

getPathContext()
Direct link to getpathcontext

获取有关文件系统和沙箱路径的信息,包括代理的使用说明。

🌐 Get information about filesystem and sandbox paths, including instructions for agents.

const context = workspace.getPathContext();
// { filesystem?, sandbox?, instructions }

返回值: PathContext

interface PathContext {
filesystem?: {
provider: string;
basePath?: string;
};
sandbox?: {
provider: string;
workingDirectory?: string;
};
instructions: string;
}

instructions 字段包含由提供商生成的描述,这些描述结合了文件系统和沙盒的信息。这些说明包含在工具描述中,以帮助代理理解执行环境。

🌐 The instructions field contains provider-generated descriptions combined from the filesystem and sandbox. These instructions are included in tool descriptions to help agents understand the execution context.

getToolsConfig()
Direct link to gettoolsconfig

获取工具配置。

🌐 Get the tools configuration.

const config = workspace.getToolsConfig();

代理工具
Direct link to 代理工具

🌐 Agent tools

工作区根据配置为代理提供工具。

🌐 A workspace provides tools to agents based on what is configured.

文件系统工具
Direct link to 文件系统工具

🌐 Filesystem tools

在配置文件系统时添加:

🌐 Added when a filesystem is configured:

工具描述
mastra_workspace_read_file读取文件内容。支持可选的行范围,用于读取大型文件的特定部分。
mastra_workspace_write_file创建或覆盖文件并写入新内容。会自动创建父目录。
mastra_workspace_edit_file通过查找和替换文本来编辑现有文件。适用于无需重写整个文件的针对性修改。
mastra_workspace_list_files以树状结构列出目录内容。支持递归列出,并可设置深度限制。
mastra_workspace_delete删除文件或目录。支持对目录的递归删除。
mastra_workspace_file_stat获取文件或目录的元数据,包括大小、类型和修改时间。
mastra_workspace_mkdir创建目录。如果父目录不存在,会自动创建它们。

当文件系统处于只读模式时,写入工具(write_fileedit_filedeletemkdir)将被排除。

🌐 Write tools (write_file, edit_file, delete, mkdir) are excluded when the filesystem is in read-only mode.

沙箱工具
Direct link to 沙箱工具

🌐 Sandbox tools

在配置沙盒时添加:

🌐 Added when a sandbox is configured:

工具描述
mastra_workspace_execute_command执行带参数的 shell 命令。返回标准输出、标准错误和退出代码。支持超时和输出流处理。

搜索工具
Direct link to 搜索工具

🌐 Search tools

当配置了 BM25 或向量搜索时添加:

🌐 Added when BM25 or vector search is configured:

工具描述
mastra_workspace_search使用关键字(BM25)、语义(向量)或混合搜索来搜索已编制索引的内容。返回带有分数的排序结果。
mastra_workspace_index为搜索建立内容索引。将内容与路径关联以便后续检索。

当文件系统处于只读模式时,index 工具将被排除在外。

🌐 The index tool is excluded when the filesystem is in read-only mode.

🌐 Related