> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # 构建开发助手 在本指南中,你将构建一个结合所有 Workspace 功能的完整开发助手: - 用于文件管理的[文件系统](https://mastra.zisheng.pro/docs/workspace/filesystem) - 用于执行代码的 [Sandbox](https://mastra.zisheng.pro/docs/workspace/sandbox) - 用于编码标准的 [Skill](https://mastra.zisheng.pro/docs/workspace/skills) - 用于查找示例的[搜索](https://mastra.zisheng.pro/docs/workspace/search) 你将设置一个包含示例项目的 Workspace,并以 Skill 形式添加编码标准。然后,你会创建一个遵循 TDD 实践编写代码的 Agent。最终,该 Agent 能够读取现有代码并编写新的实现,然后在 Sandbox 中运行测试,并根据结果反复改进。 ## 前提条件 - 已安装 Node.js `v22.13.0` 或更高版本 - 受支持的 [Model Provider](https://mastra.zisheng.pro/models) 提供的 API 密钥 - 现有的 Mastra 项目(按照[安装指南](https://mastra.zisheng.pro/guides/getting-started/quickstart)设置新项目) ### 安装 Vitest 开发助手将使用 [Vitest](https://vitest.dev/) 在 Workspace Sandbox 中运行测试。将它作为开发依赖项安装到项目: **npm**: ```bash npm install -D vitest ``` **pnpm**: ```bash pnpm add -D vitest ``` **Yarn**: ```bash yarn add --dev vitest ``` **Bun**: ```bash bun add --dev vitest ``` ## 设置 Workspace 该 Workspace 使用本地文件系统管理文档文件。Agent 会读取和写入 Workspace 目录中的文件。在 `src/mastra/index.ts` 文件中导入 [`Workspace`](https://mastra.zisheng.pro/reference/workspace/workspace-class)、[`LocalFilesystem`](https://mastra.zisheng.pro/reference/workspace/local-filesystem) 和 [`LocalSandbox`](https://mastra.zisheng.pro/reference/workspace/local-sandbox) 类。 此外,启用 BM25 搜索索引,并从 `skills` 目录加载 Skill。 ```typescript import { Mastra } from '@mastra/core' import { resolve } from 'node:path' import { Workspace, LocalFilesystem, LocalSandbox } from '@mastra/core/workspace' const workspace = new Workspace({ filesystem: new LocalFilesystem({ basePath: resolve(import.meta.dirname, '../../workspace') }), sandbox: new LocalSandbox({ workingDirectory: resolve(import.meta.dirname, '../../workspace') }), skills: ['skills'], bm25: true, autoIndexPaths: ['docs', 'src'], }) export const mastra = new Mastra({ workspace, }) ``` 在项目根目录新建名为 `workspace` 的文件夹。所有文件都会存储在这里,并由 Agent 管理。 ## 添加示例项目文件 Workspace 使用以下文件夹结构: - `workspace/src/`:示例项目的源代码 - `workspace/tests/`:测试文件 - `workspace/docs/`:项目文档 - `workspace/skills/`:以 [Agent Skill](https://agentskills.io) 形式提供的编码标准和指南 首先创建包含一些实用函数的 `workspace/src/utils/string-helpers.ts` 文件,以及对应的测试文件 `workspace/tests/string-helpers.test.ts`。 ```typescript export function capitalize(str: string): string { if (!str) return str return str.charAt(0).toUpperCase() + str.slice(1) } export function slugify(str: string): string { return str .toLowerCase() .replace(/[^\w\s-]/g, '') .replace(/\s+/g, '-') } ``` ```typescript import { describe, it, expect } from 'vitest' import { capitalize, slugify } from '../src/utils/string-helpers' describe('String Helpers', () => { describe('capitalize', () => { it('capitalizes first letter', () => { expect(capitalize('hello')).toBe('Hello') }) }) describe('slugify', () => { it('converts to lowercase and replaces spaces', () => { expect(slugify('Hello World')).toBe('hello-world') }) }) }) ``` 在 `workspace/skills/coding-standards/SKILL.md` 创建 Skill 定义。它会告诉 Agent 如何编写和测试代码: ```markdown --- name: coding-standards description: Project coding standards and testing guidelines --- # Coding Standards ## Code quality - Functions under 50 lines - Use descriptive variable names - Always add TypeScript types ## Testing - Test all exported functions - Use AAA pattern: Arrange, Act, Assert - Cover happy paths and edge cases ## Before committing 1. Write implementation 2. Write comprehensive tests 3. Run tests: `npm test` 4. All tests must pass ``` 在 `workspace/skills/coding-standards/references/testing-guide.md` 创建参考文件,其中包含详细的测试模式: ````markdown # Testing Guide ## AAA pattern ```typescript it('descriptive test name', () => { // Arrange: Set up test data const input = 'test' // Act: Execute the function const result = doSomething(input) // Assert: Verify the result expect(result).toBe('expected') }) ``` ## What to test - Happy paths (normal inputs) - Edge cases (empty, null, boundary values) - Error cases (invalid inputs, exceptions) ```` ## 创建开发助手 Workspace 设置完成后,就可以创建开发助手 Agent。该 Agent 将包含使用测试驱动开发(TDD)添加新功能的说明。 新建文件 `src/mastra/agents/dev-assistant.ts` 并定义 Agent: ```typescript import { Agent } from '@mastra/core/agent' export const devAssistant = new Agent({ id: 'dev-assistant', name: 'Dev Assistant', instructions: `You are a development assistant. When adding features: 1. Activate 'coding-standards' skill 2. Search workspace for similar code examples 3. Write the implementation following standards 4. Write comprehensive tests. Leave existing tests in place, only add your new tests 5. Execute the command \`npx vitest run\` to validate that all tests pass 6. Update documentation if needed For every new feature: Write code → Write tests → Run tests → Update docs Always explain your reasoning and steps.`, model: 'openai/gpt-5.6-sol', }) ``` 在 `src/mastra/index.ts` 中导入该 Agent,并将其注册到 `Mastra` 实例: ```typescript import { Mastra } from '@mastra/core' import { resolve } from 'node:path' import { Workspace, LocalFilesystem, LocalSandbox } from '@mastra/core/workspace' import { devAssistant } from './agents/dev-assistant' const workspace = new Workspace({ filesystem: new LocalFilesystem({ basePath: resolve(import.meta.dirname, '../../workspace') }), sandbox: new LocalSandbox({ workingDirectory: resolve(import.meta.dirname, '../../workspace') }), skills: ['skills'], bm25: true, autoIndexPaths: ['docs', 'src'], }) export const mastra = new Mastra({ workspace, agents: { devAssistant }, }) ``` ## 测试助手 启动 [Studio](https://mastra.zisheng.pro/docs/studio/overview) 并与 Agent 交互,查看它的实际表现。 **npm**: ```bash npm run dev ``` **pnpm**: ```bash pnpm run dev ``` **Yarn**: ```bash yarn dev ``` **Bun**: ```bash bun run dev ``` 打开 [localhost:4111](http://localhost:4111),然后转到开发助手。 尝试让 Agent 使用 TDD 添加一个新函数: ```text Add a 'truncate' function to string-helpers.ts that shortens strings to a max length. Add '...' if truncated. Follow TDD: write tests first, then implementation. ``` 由于 Agent 回答并不确定,实际输出会有所不同。不过,你应该会看到 Agent 遵循类似下面的流程: 1. 激活 coding-standards Skill 2. 在 Workspace 中搜索类似的代码模式 3. 先编写测试,例如: ```typescript describe('truncate', () => { it('truncates long strings', () => { expect(truncate('Hello World', 5)).toBe('He...') }) it('keeps short strings unchanged', () => { expect(truncate('Hi', 10)).toBe('Hi') }) it('handles edge cases', () => { expect(truncate('', 5)).toBe('') }) }) ``` 4. 编写实现,例如: ```typescript export function truncate(str: string, maxLength: number): string { if (!str || maxLength < 0) return str if (str.length <= maxLength) return str if (maxLength === 0) return '...' return str.slice(0, maxLength - 3) + '...' } ``` 5. 运行测试并确认全部通过 ## 后续步骤 你可以扩展此助手: - 为不同语言或框架添加更多 Skill - 为后端、前端或 DevOps 创建专用 Agent - 与 GitHub 集成,自动审查 PR - 构建 CI/CD 自动化 - 添加多 Agent Workflow