@mastra/agent-builder 0.0.1-alpha.1 → 0.0.1-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -0
- package/dist/agent/index.d.ts +5885 -0
- package/dist/agent/index.d.ts.map +1 -0
- package/dist/defaults.d.ts +6529 -0
- package/dist/defaults.d.ts.map +1 -0
- package/dist/index.d.ts +4 -4
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1810 -36
- package/dist/index.js.map +1 -0
- package/dist/processors/tool-summary.d.ts +29 -0
- package/dist/processors/tool-summary.d.ts.map +1 -0
- package/dist/processors/write-file.d.ts +10 -0
- package/dist/processors/write-file.d.ts.map +1 -0
- package/dist/types.d.ts +1121 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/utils.d.ts +63 -0
- package/dist/utils.d.ts.map +1 -0
- package/dist/workflows/index.d.ts +5 -0
- package/dist/workflows/index.d.ts.map +1 -0
- package/dist/workflows/shared/schema.d.ts +139 -0
- package/dist/workflows/shared/schema.d.ts.map +1 -0
- package/dist/workflows/task-planning/prompts.d.ts +37 -0
- package/dist/workflows/task-planning/prompts.d.ts.map +1 -0
- package/dist/workflows/task-planning/schema.d.ts +548 -0
- package/dist/workflows/task-planning/schema.d.ts.map +1 -0
- package/dist/workflows/task-planning/task-planning.d.ts +992 -0
- package/dist/workflows/task-planning/task-planning.d.ts.map +1 -0
- package/dist/workflows/template-builder/template-builder.d.ts +1910 -0
- package/dist/workflows/template-builder/template-builder.d.ts.map +1 -0
- package/dist/workflows/workflow-builder/prompts.d.ts +44 -0
- package/dist/workflows/workflow-builder/prompts.d.ts.map +1 -0
- package/dist/workflows/workflow-builder/schema.d.ts +1170 -0
- package/dist/workflows/workflow-builder/schema.d.ts.map +1 -0
- package/dist/workflows/workflow-builder/tools.d.ts +309 -0
- package/dist/workflows/workflow-builder/tools.d.ts.map +1 -0
- package/dist/workflows/workflow-builder/workflow-builder.d.ts +2714 -0
- package/dist/workflows/workflow-builder/workflow-builder.d.ts.map +1 -0
- package/dist/workflows/workflow-map.d.ts +3735 -0
- package/dist/workflows/workflow-map.d.ts.map +1 -0
- package/package.json +20 -9
- package/.turbo/turbo-build.log +0 -12
- package/dist/_tsup-dts-rollup.d.cts +0 -14933
- package/dist/_tsup-dts-rollup.d.ts +0 -14933
- package/dist/index.cjs +0 -4357
- package/dist/index.d.cts +0 -4
- package/eslint.config.js +0 -11
- package/integration-tests/CHANGELOG.md +0 -9
- package/integration-tests/README.md +0 -154
- package/integration-tests/docker-compose.yml +0 -39
- package/integration-tests/package.json +0 -38
- package/integration-tests/src/agent-template-behavior.test.ts +0 -103
- package/integration-tests/src/fixtures/minimal-mastra-project/env.example +0 -6
- package/integration-tests/src/fixtures/minimal-mastra-project/package.json +0 -17
- package/integration-tests/src/fixtures/minimal-mastra-project/src/mastra/agents/weather.ts +0 -34
- package/integration-tests/src/fixtures/minimal-mastra-project/src/mastra/index.ts +0 -15
- package/integration-tests/src/fixtures/minimal-mastra-project/src/mastra/mcp/index.ts +0 -46
- package/integration-tests/src/fixtures/minimal-mastra-project/src/mastra/tools/weather.ts +0 -14
- package/integration-tests/src/fixtures/minimal-mastra-project/tsconfig.json +0 -17
- package/integration-tests/src/template-integration.test.ts +0 -312
- package/integration-tests/tsconfig.json +0 -9
- package/integration-tests/vitest.config.ts +0 -18
- package/src/agent/index.ts +0 -187
- package/src/agent-builder.test.ts +0 -313
- package/src/defaults.ts +0 -2876
- package/src/index.ts +0 -3
- package/src/processors/tool-summary.ts +0 -145
- package/src/processors/write-file.ts +0 -17
- package/src/types.ts +0 -305
- package/src/utils.ts +0 -409
- package/src/workflows/index.ts +0 -1
- package/src/workflows/template-builder.ts +0 -1682
- package/tsconfig.json +0 -5
- package/vitest.config.ts +0 -11
|
@@ -1,312 +0,0 @@
|
|
|
1
|
-
import type { ChildProcess } from 'node:child_process';
|
|
2
|
-
import { spawn, execSync } from 'node:child_process';
|
|
3
|
-
import { randomUUID } from 'node:crypto';
|
|
4
|
-
import { mkdtempSync, mkdirSync, rmSync, cpSync, existsSync, readFileSync } from 'node:fs';
|
|
5
|
-
import { join, resolve } from 'node:path';
|
|
6
|
-
import { Mastra } from '@mastra/core';
|
|
7
|
-
import { describe, expect, it, beforeAll, afterAll } from 'vitest';
|
|
8
|
-
import { fetchMastraTemplates } from '../../src/utils';
|
|
9
|
-
import { agentBuilderTemplateWorkflow } from '../../src/workflows';
|
|
10
|
-
|
|
11
|
-
function exec(cmd: string, cwd?: string): string {
|
|
12
|
-
return execSync(cmd, { stdio: 'pipe', cwd, encoding: 'utf-8' });
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
function initGitRepo(repoDir: string) {
|
|
16
|
-
exec('git init -q', repoDir);
|
|
17
|
-
exec('git config user.email "test@example.com"', repoDir);
|
|
18
|
-
exec('git config user.name "Test User"', repoDir);
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
function commitAll(repoDir: string, message: string) {
|
|
22
|
-
exec('git add .', repoDir);
|
|
23
|
-
exec(`git commit -m "${message}" -q`, repoDir);
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
describe('Template Workflow Integration Tests', () => {
|
|
27
|
-
const integrationProjectsDir = resolve(__dirname, '../integration-projects');
|
|
28
|
-
mkdirSync(integrationProjectsDir, { recursive: true });
|
|
29
|
-
const tempRoot = mkdtempSync(join(integrationProjectsDir, 'template-workflow-test-'));
|
|
30
|
-
const fixtureProjectPath = resolve(__dirname, 'fixtures/minimal-mastra-project');
|
|
31
|
-
const targetRepo = join(tempRoot, 'test-project');
|
|
32
|
-
let mastraServer: ChildProcess;
|
|
33
|
-
let port = 4199;
|
|
34
|
-
let mastraInstance: Mastra;
|
|
35
|
-
|
|
36
|
-
beforeAll(async () => {
|
|
37
|
-
mastraInstance = new Mastra({
|
|
38
|
-
workflows: {
|
|
39
|
-
agentBuilderTemplateWorkflow,
|
|
40
|
-
},
|
|
41
|
-
});
|
|
42
|
-
|
|
43
|
-
// Copy the fixture mastra project into temp directory
|
|
44
|
-
mkdirSync(targetRepo, { recursive: true });
|
|
45
|
-
cpSync(fixtureProjectPath, targetRepo, { recursive: true });
|
|
46
|
-
|
|
47
|
-
// Initialize git in target
|
|
48
|
-
initGitRepo(targetRepo);
|
|
49
|
-
|
|
50
|
-
// Verify .gitignore was copied
|
|
51
|
-
const gitignorePath = join(targetRepo, '.gitignore');
|
|
52
|
-
expect(existsSync(gitignorePath)).toBe(true);
|
|
53
|
-
|
|
54
|
-
commitAll(targetRepo, 'chore: initial mastra project');
|
|
55
|
-
|
|
56
|
-
// Install dependencies in the test project
|
|
57
|
-
console.log('Installing dependencies in test project...');
|
|
58
|
-
exec('pnpm install', targetRepo);
|
|
59
|
-
});
|
|
60
|
-
|
|
61
|
-
afterAll(async () => {
|
|
62
|
-
// Kill the Mastra server if it's running
|
|
63
|
-
if (mastraServer?.pid) {
|
|
64
|
-
try {
|
|
65
|
-
process.kill(-mastraServer.pid, 'SIGTERM');
|
|
66
|
-
// Wait a bit for graceful shutdown
|
|
67
|
-
await new Promise(resolve => setTimeout(resolve, 1000));
|
|
68
|
-
} catch (e) {
|
|
69
|
-
console.warn('Failed to kill Mastra server:', e);
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
// Cleanup temp directory
|
|
74
|
-
try {
|
|
75
|
-
rmSync(tempRoot, { recursive: true, force: true });
|
|
76
|
-
} catch {
|
|
77
|
-
// Ignore cleanup errors
|
|
78
|
-
}
|
|
79
|
-
});
|
|
80
|
-
|
|
81
|
-
it('should merge csv-to-questions template and validate functionality', async () => {
|
|
82
|
-
// Skip test if no OPENAI_API_KEY available
|
|
83
|
-
if (!process.env.OPENAI_API_KEY) {
|
|
84
|
-
console.log('Skipping test: OPENAI_API_KEY not set');
|
|
85
|
-
return;
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
// Get the csv-to-questions template info
|
|
89
|
-
const templates = await fetchMastraTemplates();
|
|
90
|
-
const csvTemplate = templates.find(t => t.slug === 'csv-to-questions');
|
|
91
|
-
expect(csvTemplate).toBeDefined();
|
|
92
|
-
|
|
93
|
-
console.log(`Starting template merge workflow in ${targetRepo}`);
|
|
94
|
-
|
|
95
|
-
const templateWorkflow = mastraInstance.getWorkflow(`agentBuilderTemplateWorkflow`);
|
|
96
|
-
|
|
97
|
-
// Run the merge template workflow
|
|
98
|
-
const workflowRun = await templateWorkflow.createRunAsync();
|
|
99
|
-
const result = await workflowRun.start({
|
|
100
|
-
inputData: {
|
|
101
|
-
repo: csvTemplate!.githubUrl,
|
|
102
|
-
slug: 'csv-to-questions',
|
|
103
|
-
targetPath: targetRepo,
|
|
104
|
-
},
|
|
105
|
-
});
|
|
106
|
-
|
|
107
|
-
console.log('Workflow result:', JSON.stringify(result, null, 2));
|
|
108
|
-
|
|
109
|
-
// Verify the workflow succeeded
|
|
110
|
-
expect(result).toBeDefined();
|
|
111
|
-
expect(result.status).toBe('success');
|
|
112
|
-
expect(result.result?.success).toBe(true);
|
|
113
|
-
expect(result.result?.applied).toBe(true);
|
|
114
|
-
expect(result.result?.branchName).toBe('feat/install-template-csv-to-questions');
|
|
115
|
-
|
|
116
|
-
// Verify the template branch was created
|
|
117
|
-
const branches = exec('git branch', targetRepo);
|
|
118
|
-
expect(branches).toContain('feat/install-template-csv-to-questions');
|
|
119
|
-
|
|
120
|
-
// Verify expected template files were created
|
|
121
|
-
const expectedPaths = [
|
|
122
|
-
'src/mastra/agents/csvQuestionAgent.ts',
|
|
123
|
-
'src/mastra/tools/csvFetcherTool.ts',
|
|
124
|
-
'src/mastra/workflows/csvToQuestionsWorkflow.ts',
|
|
125
|
-
];
|
|
126
|
-
|
|
127
|
-
for (const expectedPath of expectedPaths) {
|
|
128
|
-
const fullPath = join(targetRepo, expectedPath);
|
|
129
|
-
expect(existsSync(fullPath), `Expected ${expectedPath} to exist`).toBe(true);
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
// Verify package.json was updated
|
|
133
|
-
const packageJsonPath = join(targetRepo, 'package.json');
|
|
134
|
-
const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));
|
|
135
|
-
expect(packageJson.scripts).toBeDefined();
|
|
136
|
-
|
|
137
|
-
// Check for template-specific scripts or dependencies
|
|
138
|
-
const hasTemplateScript = Object.keys(packageJson.scripts || {}).some(
|
|
139
|
-
key => key.includes('csv-to-questions') || key.includes('template'),
|
|
140
|
-
);
|
|
141
|
-
expect(hasTemplateScript).toBe(true);
|
|
142
|
-
|
|
143
|
-
console.log('Template merge completed successfully');
|
|
144
|
-
}, 600000); // 10 minute timeout for full workflow
|
|
145
|
-
|
|
146
|
-
it('should start Mastra server and validate both original and new agents work', async () => {
|
|
147
|
-
// Skip test if no OPENAI_API_KEY available
|
|
148
|
-
if (!process.env.OPENAI_API_KEY) {
|
|
149
|
-
console.log('Skipping test: OPENAI_API_KEY not set');
|
|
150
|
-
return;
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
console.log('Starting Mastra server...');
|
|
154
|
-
|
|
155
|
-
// Start the Mastra server
|
|
156
|
-
mastraServer = spawn('pnpm', ['dev'], {
|
|
157
|
-
stdio: 'pipe',
|
|
158
|
-
cwd: targetRepo,
|
|
159
|
-
detached: true,
|
|
160
|
-
});
|
|
161
|
-
|
|
162
|
-
// Wait for server to be ready
|
|
163
|
-
await new Promise<void>((resolve, reject) => {
|
|
164
|
-
let output = '';
|
|
165
|
-
const timeout = setTimeout(() => {
|
|
166
|
-
reject(new Error('Mastra server failed to start within timeout'));
|
|
167
|
-
}, 600000);
|
|
168
|
-
|
|
169
|
-
mastraServer.stdout?.on('data', data => {
|
|
170
|
-
output += data.toString();
|
|
171
|
-
console.log('Server output:', data.toString());
|
|
172
|
-
if (output.includes('http://localhost:') || output.includes(`localhost:${port}`)) {
|
|
173
|
-
clearTimeout(timeout);
|
|
174
|
-
resolve();
|
|
175
|
-
}
|
|
176
|
-
});
|
|
177
|
-
|
|
178
|
-
mastraServer.stderr?.on('data', data => {
|
|
179
|
-
const errorStr = data.toString();
|
|
180
|
-
console.error('Mastra server error:', errorStr);
|
|
181
|
-
// Don't reject on warnings, only on actual errors
|
|
182
|
-
if (errorStr.toLowerCase().includes('error') && !errorStr.toLowerCase().includes('warning')) {
|
|
183
|
-
clearTimeout(timeout);
|
|
184
|
-
reject(new Error(`Mastra server error: ${errorStr}`));
|
|
185
|
-
}
|
|
186
|
-
});
|
|
187
|
-
|
|
188
|
-
mastraServer.on('exit', code => {
|
|
189
|
-
clearTimeout(timeout);
|
|
190
|
-
if (code !== 0) {
|
|
191
|
-
reject(new Error(`Mastra server exited with code ${code}`));
|
|
192
|
-
}
|
|
193
|
-
});
|
|
194
|
-
});
|
|
195
|
-
|
|
196
|
-
console.log(`Mastra server started on port ${port}`);
|
|
197
|
-
|
|
198
|
-
// Test the original weather agent (from fixture)
|
|
199
|
-
console.log('Testing original weather agent...');
|
|
200
|
-
const weatherResponse = await fetch(`http://localhost:${port}/api/agents/weatherAgent/generate`, {
|
|
201
|
-
method: 'POST',
|
|
202
|
-
headers: { 'Content-Type': 'application/json' },
|
|
203
|
-
body: JSON.stringify({
|
|
204
|
-
messages: [{ role: 'user', content: 'What is the weather in San Francisco?' }],
|
|
205
|
-
threadId: randomUUID(),
|
|
206
|
-
resourceId: 'test-resource',
|
|
207
|
-
}),
|
|
208
|
-
});
|
|
209
|
-
|
|
210
|
-
expect(weatherResponse.ok).toBe(true);
|
|
211
|
-
const weatherResult = await weatherResponse.json();
|
|
212
|
-
expect(weatherResult).toBeDefined();
|
|
213
|
-
expect(weatherResult.text || weatherResult.content).toContain('weather');
|
|
214
|
-
|
|
215
|
-
// Test the new CSV agent (from template)
|
|
216
|
-
console.log('Testing new CSV agent...');
|
|
217
|
-
const csvResponse = await fetch(`http://localhost:${port}/api/agents/csvQuestionAgent/generate`, {
|
|
218
|
-
method: 'POST',
|
|
219
|
-
headers: { 'Content-Type': 'application/json' },
|
|
220
|
-
body: JSON.stringify({
|
|
221
|
-
messages: [
|
|
222
|
-
{
|
|
223
|
-
role: 'user',
|
|
224
|
-
content: 'I want to analyze a CSV file with sales data. Can you help me?',
|
|
225
|
-
},
|
|
226
|
-
],
|
|
227
|
-
threadId: randomUUID(),
|
|
228
|
-
resourceId: 'test-resource',
|
|
229
|
-
}),
|
|
230
|
-
});
|
|
231
|
-
|
|
232
|
-
expect(csvResponse.ok).toBe(true);
|
|
233
|
-
const csvResult = await csvResponse.json();
|
|
234
|
-
expect(csvResult).toBeDefined();
|
|
235
|
-
expect(csvResult.text || csvResult.content).toMatch(/csv|data|analyze/i);
|
|
236
|
-
|
|
237
|
-
// Test workflows endpoint to ensure new workflow is registered
|
|
238
|
-
console.log('Testing workflows endpoint...');
|
|
239
|
-
const workflowsResponse = await fetch(`http://localhost:${port}/api/workflows`);
|
|
240
|
-
expect(workflowsResponse.ok).toBe(true);
|
|
241
|
-
const workflows = await workflowsResponse.json();
|
|
242
|
-
expect(workflows).toBeDefined();
|
|
243
|
-
|
|
244
|
-
// Check if the CSV workflow is registered (workflows is an object, not array)
|
|
245
|
-
const hasCSVWorkflow =
|
|
246
|
-
workflows &&
|
|
247
|
-
('csvToQuestionsWorkflow' in workflows || Object.values(workflows).some((w: any) => w.name?.includes('csv')));
|
|
248
|
-
expect(hasCSVWorkflow).toBe(true);
|
|
249
|
-
|
|
250
|
-
console.log('All agent and workflow tests passed!');
|
|
251
|
-
}, 600000); // 10 minute timeout for server startup and testing
|
|
252
|
-
|
|
253
|
-
it('should validate git history shows proper template integration', async () => {
|
|
254
|
-
// Check git log for template commits
|
|
255
|
-
const gitLog = exec('git log --oneline', targetRepo);
|
|
256
|
-
expect(gitLog).toContain('feat(template): register components from csv-to-questions@');
|
|
257
|
-
expect(gitLog).toContain('feat(template): copy 6 files from csv-to-questions@');
|
|
258
|
-
expect(gitLog).toContain('fix(template): resolve validation errors for csv-to-questions@');
|
|
259
|
-
|
|
260
|
-
// Verify we're on the template branch
|
|
261
|
-
const currentBranch = exec('git branch --show-current', targetRepo);
|
|
262
|
-
expect(currentBranch.trim()).toBe('feat/install-template-csv-to-questions');
|
|
263
|
-
|
|
264
|
-
// Verify the original default branch still exists
|
|
265
|
-
const allBranches = exec('git branch', targetRepo);
|
|
266
|
-
expect(allBranches).toMatch(/\b(main|master)\b/);
|
|
267
|
-
|
|
268
|
-
console.log('Git history validation completed');
|
|
269
|
-
});
|
|
270
|
-
|
|
271
|
-
it('should handle merge conflicts gracefully when running workflow twice', async () => {
|
|
272
|
-
// Skip test if no OPENAI_API_KEY available
|
|
273
|
-
if (!process.env.OPENAI_API_KEY) {
|
|
274
|
-
console.log('Skipping test: OPENAI_API_KEY not set');
|
|
275
|
-
return;
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
// Switch back to default branch
|
|
279
|
-
const defaultBranch = exec('git branch', targetRepo).includes('main') ? 'main' : 'master';
|
|
280
|
-
exec(`git checkout ${defaultBranch}`, targetRepo);
|
|
281
|
-
|
|
282
|
-
// Try to merge the same template again (should handle gracefully)
|
|
283
|
-
const templates = await fetchMastraTemplates();
|
|
284
|
-
const csvTemplate = templates.find(t => t.slug === 'csv-to-questions');
|
|
285
|
-
|
|
286
|
-
console.log('Testing duplicate template merge...');
|
|
287
|
-
|
|
288
|
-
const templateWorkflow = mastraInstance.getWorkflow(`agentBuilderTemplateWorkflow`);
|
|
289
|
-
const workflowRun = await templateWorkflow.createRunAsync();
|
|
290
|
-
const result = await workflowRun.start({
|
|
291
|
-
inputData: {
|
|
292
|
-
repo: csvTemplate!.githubUrl,
|
|
293
|
-
slug: 'csv-to-questions',
|
|
294
|
-
targetPath: targetRepo,
|
|
295
|
-
},
|
|
296
|
-
});
|
|
297
|
-
|
|
298
|
-
// The workflow should still succeed but handle the existing files intelligently
|
|
299
|
-
expect(result.status).toBe('success');
|
|
300
|
-
|
|
301
|
-
console.log(JSON.stringify(result, null, 2));
|
|
302
|
-
|
|
303
|
-
if (result.status === 'success') {
|
|
304
|
-
expect(result.result.success).toBe(true);
|
|
305
|
-
expect(result.result.applied).toBe(true);
|
|
306
|
-
// Should create a new branch with a different name or handle existing branch
|
|
307
|
-
expect(result.result.branchName).toMatch(/feat\/install-template-csv-to-questions/);
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
console.log('Duplicate merge test completed');
|
|
311
|
-
}, 600000);
|
|
312
|
-
});
|
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
import { defineConfig } from 'vitest/config';
|
|
2
|
-
|
|
3
|
-
export default defineConfig({
|
|
4
|
-
test: {
|
|
5
|
-
pool: 'forks',
|
|
6
|
-
globals: true,
|
|
7
|
-
environment: 'node',
|
|
8
|
-
include: ['src/**/*.test.ts'],
|
|
9
|
-
testTimeout: 120000,
|
|
10
|
-
hookTimeout: 60000,
|
|
11
|
-
coverage: {
|
|
12
|
-
provider: 'v8',
|
|
13
|
-
reporter: ['text', 'json'],
|
|
14
|
-
},
|
|
15
|
-
reporters: 'dot',
|
|
16
|
-
bail: 1,
|
|
17
|
-
},
|
|
18
|
-
});
|
package/src/agent/index.ts
DELETED
|
@@ -1,187 +0,0 @@
|
|
|
1
|
-
import type { CoreMessage } from '@mastra/core';
|
|
2
|
-
import { Agent } from '@mastra/core/agent';
|
|
3
|
-
import type { AiMessageType, AgentGenerateOptions, AgentStreamOptions } from '@mastra/core/agent';
|
|
4
|
-
import { Memory } from '@mastra/memory';
|
|
5
|
-
import { TokenLimiter } from '@mastra/memory/processors';
|
|
6
|
-
import { AgentBuilderDefaults } from '../defaults';
|
|
7
|
-
import { ToolSummaryProcessor } from '../processors/tool-summary';
|
|
8
|
-
import { WriteToDiskProcessor } from '../processors/write-file';
|
|
9
|
-
import type { AgentBuilderConfig, GenerateAgentOptions } from '../types';
|
|
10
|
-
import { agentBuilderTemplateWorkflow } from '../workflows';
|
|
11
|
-
|
|
12
|
-
// =============================================================================
|
|
13
|
-
// Template Merge Workflow Implementation
|
|
14
|
-
// =============================================================================
|
|
15
|
-
//
|
|
16
|
-
// This workflow implements a comprehensive template merging system that:
|
|
17
|
-
// 1. Clones template repositories at specific refs (tags/commits)
|
|
18
|
-
// 2. Discovers units (agents, workflows, MCP servers/tools) in templates
|
|
19
|
-
// 3. Topologically orders units based on dependencies
|
|
20
|
-
// 4. Analyzes conflicts and creates safety classifications
|
|
21
|
-
// 5. Applies changes with git branching and checkpoints per unit
|
|
22
|
-
//
|
|
23
|
-
// The workflow follows the "auto-decide vs ask" principles:
|
|
24
|
-
// - Auto: adding new files, missing deps, appending arrays, new scripts with template:slug:* namespace
|
|
25
|
-
// - Prompt: overwriting files, major upgrades, renaming conflicts, new ports, postInstall commands
|
|
26
|
-
// - Block: removing files, downgrading deps, changing TS target/module, modifying CI/CD secrets
|
|
27
|
-
//
|
|
28
|
-
// Usage with Mastra templates (see https://mastra.ai/api/templates.json):
|
|
29
|
-
// const run = await agentBuilderTemplateWorkflow.createRunAsync();
|
|
30
|
-
// const result = await run.start({
|
|
31
|
-
// inputData: {
|
|
32
|
-
// repo: 'https://github.com/mastra-ai/template-pdf-questions',
|
|
33
|
-
// ref: 'main', // optional
|
|
34
|
-
// targetPath: './my-project', // optional, defaults to cwd
|
|
35
|
-
// }
|
|
36
|
-
// });
|
|
37
|
-
// // The workflow will automatically analyze and merge the template structure
|
|
38
|
-
//
|
|
39
|
-
// =============================================================================
|
|
40
|
-
|
|
41
|
-
export class AgentBuilder extends Agent {
|
|
42
|
-
private builderConfig: AgentBuilderConfig;
|
|
43
|
-
|
|
44
|
-
/**
|
|
45
|
-
* Constructor for AgentBuilder
|
|
46
|
-
*/
|
|
47
|
-
constructor(config: AgentBuilderConfig) {
|
|
48
|
-
const additionalInstructions = config.instructions ? `## Priority Instructions \n\n${config.instructions}` : '';
|
|
49
|
-
const combinedInstructions = additionalInstructions + AgentBuilderDefaults.DEFAULT_INSTRUCTIONS(config.projectPath);
|
|
50
|
-
|
|
51
|
-
const agentConfig = {
|
|
52
|
-
name: 'agent-builder',
|
|
53
|
-
description:
|
|
54
|
-
'An AI agent specialized in generating Mastra agents, tools, and workflows from natural language requirements.',
|
|
55
|
-
instructions: combinedInstructions,
|
|
56
|
-
model: config.model,
|
|
57
|
-
tools: async () => {
|
|
58
|
-
return {
|
|
59
|
-
...(await AgentBuilderDefaults.DEFAULT_TOOLS(config.projectPath, config.mode)),
|
|
60
|
-
...(config.tools || {}),
|
|
61
|
-
};
|
|
62
|
-
},
|
|
63
|
-
workflows: {
|
|
64
|
-
'merge-template': agentBuilderTemplateWorkflow,
|
|
65
|
-
},
|
|
66
|
-
memory: new Memory({
|
|
67
|
-
options: AgentBuilderDefaults.DEFAULT_MEMORY_CONFIG,
|
|
68
|
-
processors: [
|
|
69
|
-
new WriteToDiskProcessor({ prefix: 'before-filter' }),
|
|
70
|
-
new ToolSummaryProcessor({ summaryModel: config.summaryModel || config.model }),
|
|
71
|
-
new TokenLimiter(100000),
|
|
72
|
-
new WriteToDiskProcessor({ prefix: 'after-filter' }),
|
|
73
|
-
],
|
|
74
|
-
}),
|
|
75
|
-
};
|
|
76
|
-
|
|
77
|
-
super(agentConfig);
|
|
78
|
-
this.builderConfig = config;
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
/**
|
|
82
|
-
* Enhanced generate method with AgentBuilder-specific configuration
|
|
83
|
-
* Overrides the base Agent generate method to provide additional project context
|
|
84
|
-
*/
|
|
85
|
-
generate: Agent['generate'] = async (
|
|
86
|
-
messages: string | string[] | CoreMessage[] | AiMessageType[],
|
|
87
|
-
generateOptions: (GenerateAgentOptions & AgentGenerateOptions<any, any>) | undefined = {},
|
|
88
|
-
): Promise<any> => {
|
|
89
|
-
const { ...baseOptions } = generateOptions;
|
|
90
|
-
|
|
91
|
-
const originalInstructions = await this.getInstructions({ runtimeContext: generateOptions?.runtimeContext });
|
|
92
|
-
const additionalInstructions = baseOptions.instructions;
|
|
93
|
-
|
|
94
|
-
let enhancedInstructions = originalInstructions as string;
|
|
95
|
-
if (additionalInstructions) {
|
|
96
|
-
enhancedInstructions = `${originalInstructions}\n\n${additionalInstructions}`;
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
const enhancedContext = [...(baseOptions.context || [])];
|
|
100
|
-
|
|
101
|
-
const enhancedOptions = {
|
|
102
|
-
...baseOptions,
|
|
103
|
-
maxSteps: 300, // Higher default for code generation
|
|
104
|
-
temperature: 0.3, // Lower temperature for more consistent code generation
|
|
105
|
-
instructions: enhancedInstructions,
|
|
106
|
-
context: enhancedContext,
|
|
107
|
-
} satisfies AgentGenerateOptions<any, any>;
|
|
108
|
-
|
|
109
|
-
this.logger.debug(`[AgentBuilder:${this.name}] Starting generation with enhanced context`, {
|
|
110
|
-
projectPath: this.builderConfig.projectPath,
|
|
111
|
-
});
|
|
112
|
-
|
|
113
|
-
return super.generate(messages, enhancedOptions);
|
|
114
|
-
};
|
|
115
|
-
|
|
116
|
-
/**
|
|
117
|
-
* Enhanced stream method with AgentBuilder-specific configuration
|
|
118
|
-
* Overrides the base Agent stream method to provide additional project context
|
|
119
|
-
*/
|
|
120
|
-
stream: Agent['stream'] = async (
|
|
121
|
-
messages: string | string[] | CoreMessage[] | AiMessageType[],
|
|
122
|
-
streamOptions: (GenerateAgentOptions & AgentStreamOptions<any, any>) | undefined = {},
|
|
123
|
-
): Promise<any> => {
|
|
124
|
-
const { ...baseOptions } = streamOptions;
|
|
125
|
-
|
|
126
|
-
const originalInstructions = await this.getInstructions({ runtimeContext: streamOptions?.runtimeContext });
|
|
127
|
-
const additionalInstructions = baseOptions.instructions;
|
|
128
|
-
|
|
129
|
-
let enhancedInstructions = originalInstructions as string;
|
|
130
|
-
if (additionalInstructions) {
|
|
131
|
-
enhancedInstructions = `${originalInstructions}\n\n${additionalInstructions}`;
|
|
132
|
-
}
|
|
133
|
-
const enhancedContext = [...(baseOptions.context || [])];
|
|
134
|
-
|
|
135
|
-
const enhancedOptions = {
|
|
136
|
-
...baseOptions,
|
|
137
|
-
maxSteps: 100, // Higher default for code generation
|
|
138
|
-
temperature: 0.3, // Lower temperature for more consistent code generation
|
|
139
|
-
instructions: enhancedInstructions,
|
|
140
|
-
context: enhancedContext,
|
|
141
|
-
};
|
|
142
|
-
|
|
143
|
-
this.logger.debug(`[AgentBuilder:${this.name}] Starting streaming with enhanced context`, {
|
|
144
|
-
projectPath: this.builderConfig.projectPath,
|
|
145
|
-
});
|
|
146
|
-
|
|
147
|
-
return super.stream(messages, enhancedOptions);
|
|
148
|
-
};
|
|
149
|
-
|
|
150
|
-
/**
|
|
151
|
-
* Generate a Mastra agent from natural language requirements
|
|
152
|
-
*/
|
|
153
|
-
async generateAgent(
|
|
154
|
-
requirements: string,
|
|
155
|
-
options?: {
|
|
156
|
-
outputFormat?: 'code' | 'explanation' | 'both';
|
|
157
|
-
runtimeContext?: any;
|
|
158
|
-
},
|
|
159
|
-
) {
|
|
160
|
-
const prompt = `Generate a Mastra agent based on these requirements: ${requirements}
|
|
161
|
-
|
|
162
|
-
Please provide:
|
|
163
|
-
1. Complete agent code with proper configuration
|
|
164
|
-
2. Any custom tools the agent needs
|
|
165
|
-
3. Example usage
|
|
166
|
-
4. Testing recommendations
|
|
167
|
-
|
|
168
|
-
${options?.outputFormat === 'explanation' ? 'Focus on explaining the approach and architecture.' : ''}
|
|
169
|
-
${options?.outputFormat === 'code' ? 'Focus on providing complete, working code.' : ''}
|
|
170
|
-
${!options?.outputFormat || options.outputFormat === 'both' ? 'Provide both explanation and complete code.' : ''}`;
|
|
171
|
-
|
|
172
|
-
return this.generate(prompt, {
|
|
173
|
-
runtimeContext: options?.runtimeContext,
|
|
174
|
-
});
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
/**
|
|
178
|
-
* Get the default configuration for AgentBuilder
|
|
179
|
-
*/
|
|
180
|
-
static defaultConfig(projectPath?: string) {
|
|
181
|
-
return {
|
|
182
|
-
instructions: AgentBuilderDefaults.DEFAULT_INSTRUCTIONS(projectPath),
|
|
183
|
-
memoryConfig: AgentBuilderDefaults.DEFAULT_MEMORY_CONFIG,
|
|
184
|
-
tools: AgentBuilderDefaults.DEFAULT_TOOLS,
|
|
185
|
-
};
|
|
186
|
-
}
|
|
187
|
-
}
|