@mastra/agent-builder 0.0.0-experimental-agent-builder-20250815195917 → 0.0.1-alpha.1

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/src/index.ts CHANGED
@@ -1,187 +1,3 @@
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 { mergeTemplateWorkflow } 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 mergeTemplateWorkflow.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
- * Private constructor - use AgentBuilder.create() instead
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': mergeTemplateWorkflow,
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
- };
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
- }
1
+ export * from './agent';
2
+ export * from './workflows';
3
+ export * from './defaults';
@@ -116,18 +116,27 @@ export class ToolSummaryProcessor extends MemoryProcessor {
116
116
 
117
117
  // Execute all non-cached summaries in parallel
118
118
  if (summaryTasks.length > 0) {
119
- const summaryResults = await Promise.all(summaryTasks.map(task => task.promise));
119
+ const summaryResults = await Promise.allSettled(summaryTasks.map(task => task.promise));
120
120
 
121
121
  // Apply the results back to the content and cache them
122
122
  summaryTasks.forEach((task, index) => {
123
- const summaryResult = summaryResults[index];
124
- const summaryText = summaryResult.text;
125
-
126
- // Cache the summary for future use
127
- this.summaryCache.set(task.cacheKey, summaryText);
128
-
129
- // Apply to content
130
- task.content.result = `Tool call summary: ${summaryText}`;
123
+ const result = summaryResults[index];
124
+ if (!result) return;
125
+
126
+ if (result.status === 'fulfilled') {
127
+ const summaryResult = result.value;
128
+ const summaryText = summaryResult.text;
129
+
130
+ // Cache the summary for future use
131
+ this.summaryCache.set(task.cacheKey, summaryText);
132
+
133
+ // Apply to content
134
+ task.content.result = `Tool call summary: ${summaryText}`;
135
+ } else if (result.status === 'rejected') {
136
+ // Handle failed summary - use fallback or log error
137
+ console.warn(`Failed to generate summary for tool call:`, result.reason);
138
+ task.content.result = `Tool call summary: [Summary generation failed]`;
139
+ }
131
140
  });
132
141
  }
133
142
 
@@ -11,7 +11,7 @@ export class WriteToDiskProcessor extends MemoryProcessor {
11
11
  }
12
12
 
13
13
  async process(messages: CoreMessage[]): Promise<CoreMessage[]> {
14
- await writeFile(`${this.prefix}-${Date.now()}.json`, JSON.stringify(messages, null, 2));
14
+ await writeFile(`${this.prefix}-${Date.now()}-${process.pid}.json`, JSON.stringify(messages, null, 2));
15
15
  return messages;
16
16
  }
17
17
  }
package/src/types.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import type { MastraLanguageModel, ToolsInput } from '@mastra/core/agent';
2
+ import type { MastraStorage } from '@mastra/core/storage';
3
+ import type { MastraVector } from '@mastra/core/vector';
2
4
  import { z } from 'zod';
3
5
 
4
6
  /**
@@ -8,9 +10,9 @@ export interface AgentBuilderConfig {
8
10
  /** The language model to use for agent generation */
9
11
  model: MastraLanguageModel;
10
12
  /** Storage provider for memory (optional) */
11
- storage?: any;
13
+ storage?: MastraStorage;
12
14
  /** Vector provider for memory (optional) */
13
- vectorProvider?: any;
15
+ vectorProvider?: MastraVector;
14
16
  /** Additional tools to include beyond the default set */
15
17
  tools?: ToolsInput;
16
18
  /** Custom instructions to append to the default system prompt */
@@ -98,7 +100,7 @@ export const TemplateManifestSchema = z.object({
98
100
  units: z.array(TemplateUnitSchema),
99
101
  });
100
102
 
101
- export const MergeInputSchema = z.object({
103
+ export const AgentBuilderInputSchema = z.object({
102
104
  repo: z.string().describe('Git URL or local path of the template repo'),
103
105
  ref: z.string().optional().describe('Tag/branch/commit to checkout (defaults to main/master)'),
104
106
  slug: z.string().optional().describe('Slug for branch/scripts; defaults to inferred from repo'),
@@ -112,9 +114,192 @@ export const MergePlanSchema = z.object({
112
114
  units: z.array(TemplateUnitSchema),
113
115
  });
114
116
 
117
+ // File copy schemas and types
118
+ export const CopiedFileSchema = z.object({
119
+ source: z.string(),
120
+ destination: z.string(),
121
+ unit: z.object({
122
+ kind: z.enum(UNIT_KINDS),
123
+ id: z.string(),
124
+ }),
125
+ });
126
+
127
+ export const ConflictSchema = z.object({
128
+ unit: z.object({
129
+ kind: z.enum(UNIT_KINDS),
130
+ id: z.string(),
131
+ }),
132
+ issue: z.string(),
133
+ sourceFile: z.string(),
134
+ targetFile: z.string(),
135
+ });
136
+
137
+ export const FileCopyInputSchema = z.object({
138
+ orderedUnits: z.array(TemplateUnitSchema),
139
+ templateDir: z.string(),
140
+ commitSha: z.string(),
141
+ slug: z.string(),
142
+ targetPath: z.string().optional(),
143
+ });
144
+
145
+ export const FileCopyResultSchema = z.object({
146
+ success: z.boolean(),
147
+ copiedFiles: z.array(CopiedFileSchema),
148
+ conflicts: z.array(ConflictSchema),
149
+ message: z.string(),
150
+ error: z.string().optional(),
151
+ });
152
+
153
+ // Intelligent merge schemas and types
154
+ export const ConflictResolutionSchema = z.object({
155
+ unit: z.object({
156
+ kind: z.enum(UNIT_KINDS),
157
+ id: z.string(),
158
+ }),
159
+ issue: z.string(),
160
+ resolution: z.string(),
161
+ });
162
+
163
+ export const IntelligentMergeInputSchema = z.object({
164
+ conflicts: z.array(ConflictSchema),
165
+ copiedFiles: z.array(CopiedFileSchema),
166
+ templateDir: z.string(),
167
+ commitSha: z.string(),
168
+ slug: z.string(),
169
+ targetPath: z.string().optional(),
170
+ branchName: z.string().optional(),
171
+ });
172
+
173
+ export const IntelligentMergeResultSchema = z.object({
174
+ success: z.boolean(),
175
+ applied: z.boolean(),
176
+ message: z.string(),
177
+ conflictsResolved: z.array(ConflictResolutionSchema),
178
+ error: z.string().optional(),
179
+ });
180
+
181
+ // Validation schemas and types
182
+ export const ValidationResultsSchema = z.object({
183
+ valid: z.boolean(),
184
+ errorsFixed: z.number(),
185
+ remainingErrors: z.number(),
186
+ });
187
+
188
+ export const ValidationFixInputSchema = z.object({
189
+ commitSha: z.string(),
190
+ slug: z.string(),
191
+ targetPath: z.string().optional(),
192
+ templateDir: z.string(),
193
+ orderedUnits: z.array(TemplateUnitSchema),
194
+ copiedFiles: z.array(CopiedFileSchema),
195
+ conflictsResolved: z.array(ConflictResolutionSchema).optional(),
196
+ maxIterations: z.number().optional().default(5),
197
+ });
198
+
199
+ export const ValidationFixResultSchema = z.object({
200
+ success: z.boolean(),
201
+ applied: z.boolean(),
202
+ message: z.string(),
203
+ validationResults: ValidationResultsSchema,
204
+ error: z.string().optional(),
205
+ });
206
+
207
+ // Final workflow result schema
115
208
  export const ApplyResultSchema = z.object({
116
209
  success: z.boolean(),
117
210
  applied: z.boolean(),
118
211
  branchName: z.string().optional(),
212
+ message: z.string(),
213
+ validationResults: ValidationResultsSchema.optional(),
214
+ error: z.string().optional(),
215
+ errors: z.array(z.string()).optional(),
216
+ stepResults: z
217
+ .object({
218
+ cloneSuccess: z.boolean().optional(),
219
+ analyzeSuccess: z.boolean().optional(),
220
+ discoverSuccess: z.boolean().optional(),
221
+ orderSuccess: z.boolean().optional(),
222
+ prepareBranchSuccess: z.boolean().optional(),
223
+ packageMergeSuccess: z.boolean().optional(),
224
+ installSuccess: z.boolean().optional(),
225
+ copySuccess: z.boolean().optional(),
226
+ mergeSuccess: z.boolean().optional(),
227
+ validationSuccess: z.boolean().optional(),
228
+ filesCopied: z.number(),
229
+ conflictsSkipped: z.number(),
230
+ conflictsResolved: z.number(),
231
+ })
232
+ .optional(),
233
+ });
234
+
235
+ export const CloneTemplateResultSchema = z.object({
236
+ templateDir: z.string(),
237
+ commitSha: z.string(),
238
+ slug: z.string(),
239
+ success: z.boolean().optional(),
240
+ error: z.string().optional(),
241
+ });
242
+
243
+ // Package analysis schemas and types
244
+ export const PackageAnalysisSchema = z.object({
245
+ name: z.string().optional(),
246
+ version: z.string().optional(),
247
+ description: z.string().optional(),
248
+ dependencies: z.record(z.string()).optional(),
249
+ devDependencies: z.record(z.string()).optional(),
250
+ peerDependencies: z.record(z.string()).optional(),
251
+ scripts: z.record(z.string()).optional(),
252
+ success: z.boolean().optional(),
253
+ error: z.string().optional(),
254
+ });
255
+
256
+ // Discovery step schemas and types
257
+ export const DiscoveryResultSchema = z.object({
258
+ units: z.array(TemplateUnitSchema),
259
+ success: z.boolean().optional(),
260
+ error: z.string().optional(),
261
+ });
262
+
263
+ // Unit ordering schemas and types
264
+ export const OrderedUnitsSchema = z.object({
265
+ orderedUnits: z.array(TemplateUnitSchema),
266
+ success: z.boolean().optional(),
267
+ error: z.string().optional(),
268
+ });
269
+
270
+ // Package merge schemas and types
271
+ export const PackageMergeInputSchema = z.object({
272
+ commitSha: z.string(),
273
+ slug: z.string(),
274
+ targetPath: z.string().optional(),
275
+ packageInfo: PackageAnalysisSchema,
276
+ });
277
+
278
+ export const PackageMergeResultSchema = z.object({
279
+ success: z.boolean(),
280
+ applied: z.boolean(),
281
+ message: z.string(),
282
+ error: z.string().optional(),
283
+ });
284
+
285
+ // Install schemas and types
286
+ export const InstallInputSchema = z.object({
287
+ targetPath: z.string().describe('Path to the project to install packages in'),
288
+ });
289
+
290
+ export const InstallResultSchema = z.object({
291
+ success: z.boolean(),
292
+ error: z.string().optional(),
293
+ });
294
+
295
+ export const PrepareBranchInputSchema = z.object({
296
+ slug: z.string(),
297
+ commitSha: z.string().optional(), // from clone-template if relevant
298
+ targetPath: z.string().optional(),
299
+ });
300
+
301
+ export const PrepareBranchResultSchema = z.object({
302
+ branchName: z.string(),
303
+ success: z.boolean().optional(),
119
304
  error: z.string().optional(),
120
305
  });