@mastra/agent-builder 0.0.0-rag-chunk-extract-llm-option-20250926183645 → 0.0.0-refactor-agent-information-for-recomposable-ui-20251112151814

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/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { Agent } from '@mastra/core/agent';
1
+ import { Agent, tryGenerateWithJsonFallback, tryStreamWithJsonFallback } from '@mastra/core/agent';
2
2
  import { Memory } from '@mastra/memory';
3
3
  import { TokenLimiter } from '@mastra/memory/processors';
4
4
  import { exec as exec$1, execFile as execFile$1, spawn as spawn$1 } from 'child_process';
@@ -10,7 +10,7 @@ import { z } from 'zod';
10
10
  import { existsSync, readFileSync } from 'fs';
11
11
  import { createRequire } from 'module';
12
12
  import { promisify } from 'util';
13
- import { openai as openai$1 } from '@ai-sdk/openai-v5';
13
+ import { ModelRouterLanguageModel } from '@mastra/core/llm';
14
14
  import { MemoryProcessor } from '@mastra/core/memory';
15
15
  import { tmpdir } from 'os';
16
16
  import { openai } from '@ai-sdk/openai';
@@ -501,11 +501,11 @@ async function renameAndCopyFile(sourceFile, targetFile) {
501
501
  var isValidMastraLanguageModel = (model) => {
502
502
  return model && typeof model === "object" && typeof model.modelId === "string";
503
503
  };
504
- var resolveTargetPath = (inputData, runtimeContext) => {
504
+ var resolveTargetPath = (inputData, requestContext) => {
505
505
  if (inputData.targetPath) {
506
506
  return inputData.targetPath;
507
507
  }
508
- const contextPath = runtimeContext.get("targetPath");
508
+ const contextPath = requestContext.get("targetPath");
509
509
  if (contextPath) {
510
510
  return contextPath;
511
511
  }
@@ -658,31 +658,9 @@ var createModelInstance = async (provider, modelId, version = "v2") => {
658
658
  const { google } = await import('@ai-sdk/google');
659
659
  return google(modelId);
660
660
  }
661
- },
662
- v2: {
663
- openai: async () => {
664
- const { openai: openai2 } = await import('@ai-sdk/openai-v5');
665
- return openai2(modelId);
666
- },
667
- anthropic: async () => {
668
- const { anthropic } = await import('@ai-sdk/anthropic-v5');
669
- return anthropic(modelId);
670
- },
671
- groq: async () => {
672
- const { groq } = await import('@ai-sdk/groq-v5');
673
- return groq(modelId);
674
- },
675
- xai: async () => {
676
- const { xai } = await import('@ai-sdk/xai-v5');
677
- return xai(modelId);
678
- },
679
- google: async () => {
680
- const { google } = await import('@ai-sdk/google-v5');
681
- return google(modelId);
682
- }
683
661
  }
684
662
  };
685
- const providerFn = providerMap[version][provider];
663
+ const providerFn = version === `v1` ? providerMap[version][provider] : () => new ModelRouterLanguageModel(`${provider}/${modelId}`);
686
664
  if (!providerFn) {
687
665
  console.error(`Unsupported provider: ${provider}`);
688
666
  return null;
@@ -696,13 +674,13 @@ var createModelInstance = async (provider, modelId, version = "v2") => {
696
674
  }
697
675
  };
698
676
  var resolveModel = async ({
699
- runtimeContext,
700
- defaultModel = openai$1("gpt-4.1"),
677
+ requestContext,
678
+ defaultModel = "openai/gpt-4.1",
701
679
  projectPath
702
680
  }) => {
703
- const modelFromContext = runtimeContext.get("model");
681
+ const modelFromContext = requestContext.get("model");
704
682
  if (modelFromContext) {
705
- console.info("Using model from runtime context");
683
+ console.info("Using model from request context");
706
684
  if (isValidMastraLanguageModel(modelFromContext)) {
707
685
  return modelFromContext;
708
686
  }
@@ -710,18 +688,18 @@ var resolveModel = async ({
710
688
  'Invalid model provided. Model must be a MastraLanguageModel instance (e.g., openai("gpt-4"), anthropic("claude-3-5-sonnet"), etc.)'
711
689
  );
712
690
  }
713
- const selectedModel = runtimeContext.get("selectedModel");
691
+ const selectedModel = requestContext.get("selectedModel");
714
692
  if (selectedModel?.provider && selectedModel?.modelId && projectPath) {
715
693
  console.info(`Resolving selected model: ${selectedModel.provider}/${selectedModel.modelId}`);
716
694
  const version = await detectAISDKVersion(projectPath);
717
695
  const modelInstance = await createModelInstance(selectedModel.provider, selectedModel.modelId, version);
718
696
  if (modelInstance) {
719
- runtimeContext.set("model", modelInstance);
697
+ requestContext.set("model", modelInstance);
720
698
  return modelInstance;
721
699
  }
722
700
  }
723
701
  console.info("Using default model");
724
- return defaultModel;
702
+ return typeof defaultModel === `string` ? new ModelRouterLanguageModel(defaultModel) : defaultModel;
725
703
  };
726
704
 
727
705
  // src/defaults.ts
@@ -890,7 +868,7 @@ You have access to an enhanced set of tools based on production coding agent pat
890
868
  ### Task Management
891
869
  - **taskManager**: Create and track multi-step coding tasks with states (pending, in_progress, completed, blocked). Use this for complex projects that require systematic progress tracking.
892
870
 
893
- ### Code Discovery & Analysis
871
+ ### Code Discovery & Analysis
894
872
  - **codeAnalyzer**: Analyze codebase structure, discover definitions (functions, classes, interfaces), map dependencies, and understand architectural patterns.
895
873
  - **smartSearch**: Intelligent search with context awareness, pattern matching, and relevance scoring.
896
874
 
@@ -928,12 +906,14 @@ import { LibSQLStore } from '@mastra/libsql';
928
906
  import { weatherTool } from '../tools/weather-tool';
929
907
 
930
908
  export const weatherAgent = new Agent({
909
+ id: 'weather-agent',
931
910
  name: 'Weather Agent',
932
911
  instructions: \${instructions},
933
912
  model: openai('gpt-4o-mini'),
934
913
  tools: { weatherTool },
935
914
  memory: new Memory({
936
915
  storage: new LibSQLStore({
916
+ id: 'mastra-memory-storage',
937
917
  url: 'file:../mastra.db', // ask user what database to use, use this as the default
938
918
  }),
939
919
  }),
@@ -962,8 +942,8 @@ export const weatherTool = createTool({
962
942
  conditions: z.string(),
963
943
  location: z.string(),
964
944
  }),
965
- execute: async ({ context }) => {
966
- return await getWeather(context.location);
945
+ execute: async (inputData) => {
946
+ return await getWeather(inputData.location);
967
947
  },
968
948
  });
969
949
  \`\`\`
@@ -981,7 +961,7 @@ const fetchWeather = createStep({
981
961
  city: z.string().describe('The city to get the weather for'),
982
962
  }),
983
963
  outputSchema: forecastSchema,
984
- execute: async ({ inputData }) => {
964
+ execute: async (inputData) => {
985
965
  if (!inputData) {
986
966
  throw new Error('Input data not found');
987
967
  }
@@ -1035,7 +1015,8 @@ const planActivities = createStep({
1035
1015
  outputSchema: z.object({
1036
1016
  activities: z.string(),
1037
1017
  }),
1038
- execute: async ({ inputData, mastra }) => {
1018
+ execute: async (inputData, context) => {
1019
+ const mastra = context?.mastra;
1039
1020
  const forecast = inputData;
1040
1021
 
1041
1022
  if (!forecast) {
@@ -1100,7 +1081,8 @@ export const mastra = new Mastra({
1100
1081
  workflows: { weatherWorkflow },
1101
1082
  agents: { weatherAgent },
1102
1083
  storage: new LibSQLStore({
1103
- // stores telemetry, evals, ... into memory storage, if it needs to persist, change to file:../mastra.db
1084
+ id: 'mastra-storage',
1085
+ // stores observability, evals, ... into memory storage, if it needs to persist, change to file:../mastra.db
1104
1086
  url: ":memory:",
1105
1087
  }),
1106
1088
  logger: new PinoLogger({
@@ -1144,8 +1126,8 @@ export const mastra = new Mastra({
1144
1126
  }).optional(),
1145
1127
  error: z.string().optional()
1146
1128
  }),
1147
- execute: async ({ context }) => {
1148
- return await _AgentBuilderDefaults.readFile({ ...context, projectPath });
1129
+ execute: async (inputData) => {
1130
+ return await _AgentBuilderDefaults.readFile({ ...inputData, projectPath });
1149
1131
  }
1150
1132
  }),
1151
1133
  writeFile: createTool({
@@ -1164,8 +1146,8 @@ export const mastra = new Mastra({
1164
1146
  message: z.string(),
1165
1147
  error: z.string().optional()
1166
1148
  }),
1167
- execute: async ({ context }) => {
1168
- return await _AgentBuilderDefaults.writeFile({ ...context, projectPath });
1149
+ execute: async (inputData) => {
1150
+ return await _AgentBuilderDefaults.writeFile({ ...inputData, projectPath });
1169
1151
  }
1170
1152
  }),
1171
1153
  listDirectory: createTool({
@@ -1196,8 +1178,8 @@ export const mastra = new Mastra({
1196
1178
  message: z.string(),
1197
1179
  error: z.string().optional()
1198
1180
  }),
1199
- execute: async ({ context }) => {
1200
- return await _AgentBuilderDefaults.listDirectory({ ...context, projectPath });
1181
+ execute: async (inputData) => {
1182
+ return await _AgentBuilderDefaults.listDirectory({ ...inputData, projectPath });
1201
1183
  }
1202
1184
  }),
1203
1185
  executeCommand: createTool({
@@ -1221,10 +1203,10 @@ export const mastra = new Mastra({
1221
1203
  executionTime: z.number().optional(),
1222
1204
  error: z.string().optional()
1223
1205
  }),
1224
- execute: async ({ context }) => {
1206
+ execute: async (inputData) => {
1225
1207
  return await _AgentBuilderDefaults.executeCommand({
1226
- ...context,
1227
- workingDirectory: context.workingDirectory || projectPath
1208
+ ...inputData,
1209
+ workingDirectory: inputData.workingDirectory || projectPath
1228
1210
  });
1229
1211
  }
1230
1212
  }),
@@ -1262,8 +1244,8 @@ export const mastra = new Mastra({
1262
1244
  ),
1263
1245
  message: z.string()
1264
1246
  }),
1265
- execute: async ({ context }) => {
1266
- return await _AgentBuilderDefaults.manageTaskList(context);
1247
+ execute: async (inputData) => {
1248
+ return await _AgentBuilderDefaults.manageTaskList(inputData);
1267
1249
  }
1268
1250
  }),
1269
1251
  // Advanced File Operations
@@ -1297,8 +1279,8 @@ export const mastra = new Mastra({
1297
1279
  ),
1298
1280
  message: z.string()
1299
1281
  }),
1300
- execute: async ({ context }) => {
1301
- return await _AgentBuilderDefaults.performMultiEdit({ ...context, projectPath });
1282
+ execute: async (inputData) => {
1283
+ return await _AgentBuilderDefaults.performMultiEdit({ ...inputData, projectPath });
1302
1284
  }
1303
1285
  }),
1304
1286
  replaceLines: createTool({
@@ -1322,8 +1304,8 @@ export const mastra = new Mastra({
1322
1304
  backup: z.string().optional(),
1323
1305
  error: z.string().optional()
1324
1306
  }),
1325
- execute: async ({ context }) => {
1326
- return await _AgentBuilderDefaults.replaceLines({ ...context, projectPath });
1307
+ execute: async (inputData) => {
1308
+ return await _AgentBuilderDefaults.replaceLines({ ...inputData, projectPath });
1327
1309
  }
1328
1310
  }),
1329
1311
  // File diagnostics tool to help debug line replacement issues
@@ -1351,8 +1333,8 @@ export const mastra = new Mastra({
1351
1333
  message: z.string(),
1352
1334
  error: z.string().optional()
1353
1335
  }),
1354
- execute: async ({ context }) => {
1355
- return await _AgentBuilderDefaults.showFileLines({ ...context, projectPath });
1336
+ execute: async (inputData) => {
1337
+ return await _AgentBuilderDefaults.showFileLines({ ...inputData, projectPath });
1356
1338
  }
1357
1339
  }),
1358
1340
  // Enhanced Pattern Search
@@ -1395,8 +1377,8 @@ export const mastra = new Mastra({
1395
1377
  patterns: z.array(z.string())
1396
1378
  })
1397
1379
  }),
1398
- execute: async ({ context }) => {
1399
- return await _AgentBuilderDefaults.performSmartSearch(context, projectPath);
1380
+ execute: async (inputData) => {
1381
+ return await _AgentBuilderDefaults.performSmartSearch(inputData, projectPath);
1400
1382
  }
1401
1383
  }),
1402
1384
  validateCode: createTool({
@@ -1429,8 +1411,8 @@ export const mastra = new Mastra({
1429
1411
  validationsFailed: z.array(z.string())
1430
1412
  })
1431
1413
  }),
1432
- execute: async ({ context }) => {
1433
- const { projectPath: validationProjectPath, validationType, files } = context;
1414
+ execute: async (inputData) => {
1415
+ const { projectPath: validationProjectPath, validationType, files } = inputData;
1434
1416
  const targetPath = validationProjectPath || projectPath;
1435
1417
  return await _AgentBuilderDefaults.validateCode({
1436
1418
  projectPath: targetPath,
@@ -1469,8 +1451,8 @@ export const mastra = new Mastra({
1469
1451
  suggestions: z.array(z.string()).optional(),
1470
1452
  error: z.string().optional()
1471
1453
  }),
1472
- execute: async ({ context }) => {
1473
- return await _AgentBuilderDefaults.webSearch(context);
1454
+ execute: async (inputData) => {
1455
+ return await _AgentBuilderDefaults.webSearch(inputData);
1474
1456
  }
1475
1457
  }),
1476
1458
  // Task Completion Signaling
@@ -1499,8 +1481,8 @@ export const mastra = new Mastra({
1499
1481
  summary: z.string(),
1500
1482
  confidence: z.number().min(0).max(100)
1501
1483
  }),
1502
- execute: async ({ context }) => {
1503
- return await _AgentBuilderDefaults.signalCompletion(context);
1484
+ execute: async (inputData) => {
1485
+ return await _AgentBuilderDefaults.signalCompletion(inputData);
1504
1486
  }
1505
1487
  }),
1506
1488
  manageProject: createTool({
@@ -1525,8 +1507,8 @@ export const mastra = new Mastra({
1525
1507
  details: z.string().optional(),
1526
1508
  error: z.string().optional()
1527
1509
  }),
1528
- execute: async ({ context }) => {
1529
- const { action, features, packages } = context;
1510
+ execute: async (inputData) => {
1511
+ const { action, features, packages } = inputData;
1530
1512
  try {
1531
1513
  switch (action) {
1532
1514
  case "create":
@@ -1587,8 +1569,8 @@ export const mastra = new Mastra({
1587
1569
  stdout: z.array(z.string()).optional().describe("Server output lines captured during startup"),
1588
1570
  error: z.string().optional()
1589
1571
  }),
1590
- execute: async ({ context }) => {
1591
- const { action, port } = context;
1572
+ execute: async (inputData) => {
1573
+ const { action, port } = inputData;
1592
1574
  try {
1593
1575
  switch (action) {
1594
1576
  case "start":
@@ -1673,8 +1655,8 @@ export const mastra = new Mastra({
1673
1655
  url: z.string(),
1674
1656
  method: z.string()
1675
1657
  }),
1676
- execute: async ({ context }) => {
1677
- const { method, url, baseUrl, headers, body, timeout } = context;
1658
+ execute: async (inputData) => {
1659
+ const { method, url, baseUrl, headers, body, timeout } = inputData;
1678
1660
  try {
1679
1661
  return await _AgentBuilderDefaults.makeHttpRequest({
1680
1662
  method,
@@ -1729,7 +1711,7 @@ export const mastra = new Mastra({
1729
1711
  /**
1730
1712
  * Get tools for a specific mode
1731
1713
  */
1732
- static async getToolsForMode(projectPath, mode = "code-editor") {
1714
+ static async listToolsForMode(projectPath, mode = "code-editor") {
1733
1715
  const allTools = await _AgentBuilderDefaults.DEFAULT_TOOLS(projectPath);
1734
1716
  if (mode === "template") {
1735
1717
  return _AgentBuilderDefaults.filterToolsForTemplateBuilder(allTools);
@@ -3108,7 +3090,8 @@ var ToolSummaryProcessor = class extends MemoryProcessor {
3108
3090
  constructor({ summaryModel }) {
3109
3091
  super({ name: "ToolSummaryProcessor" });
3110
3092
  this.summaryAgent = new Agent({
3111
- name: "ToolSummaryAgent",
3093
+ id: "tool-summary-agent",
3094
+ name: "Tool Summary Agent",
3112
3095
  description: "A summary agent that summarizes tool calls and results",
3113
3096
  instructions: "You are a summary agent that summarizes tool calls and results",
3114
3097
  model: summaryModel
@@ -3212,7 +3195,7 @@ ${config.instructions}` : "";
3212
3195
  model: config.model,
3213
3196
  tools: async () => {
3214
3197
  return {
3215
- ...await AgentBuilderDefaults.getToolsForMode(config.projectPath, config.mode),
3198
+ ...await AgentBuilderDefaults.listToolsForMode(config.projectPath, config.mode),
3216
3199
  ...config.tools || {}
3217
3200
  };
3218
3201
  },
@@ -3234,9 +3217,9 @@ ${config.instructions}` : "";
3234
3217
  * Enhanced generate method with AgentBuilder-specific configuration
3235
3218
  * Overrides the base Agent generate method to provide additional project context
3236
3219
  */
3237
- generate = async (messages, generateOptions = {}) => {
3220
+ generateLegacy = async (messages, generateOptions = {}) => {
3238
3221
  const { maxSteps, ...baseOptions } = generateOptions;
3239
- const originalInstructions = await this.getInstructions({ runtimeContext: generateOptions?.runtimeContext });
3222
+ const originalInstructions = await this.getInstructions({ requestContext: generateOptions?.requestContext });
3240
3223
  const additionalInstructions = baseOptions.instructions;
3241
3224
  let enhancedInstructions = originalInstructions;
3242
3225
  if (additionalInstructions) {
@@ -3257,15 +3240,15 @@ ${additionalInstructions}`;
3257
3240
  this.logger.debug(`[AgentBuilder:${this.name}] Starting generation with enhanced context`, {
3258
3241
  projectPath: this.builderConfig.projectPath
3259
3242
  });
3260
- return super.generate(messages, enhancedOptions);
3243
+ return super.generateLegacy(messages, enhancedOptions);
3261
3244
  };
3262
3245
  /**
3263
3246
  * Enhanced stream method with AgentBuilder-specific configuration
3264
3247
  * Overrides the base Agent stream method to provide additional project context
3265
3248
  */
3266
- stream = async (messages, streamOptions = {}) => {
3249
+ streamLegacy = async (messages, streamOptions = {}) => {
3267
3250
  const { maxSteps, ...baseOptions } = streamOptions;
3268
- const originalInstructions = await this.getInstructions({ runtimeContext: streamOptions?.runtimeContext });
3251
+ const originalInstructions = await this.getInstructions({ requestContext: streamOptions?.requestContext });
3269
3252
  const additionalInstructions = baseOptions.instructions;
3270
3253
  let enhancedInstructions = originalInstructions;
3271
3254
  if (additionalInstructions) {
@@ -3286,15 +3269,15 @@ ${additionalInstructions}`;
3286
3269
  this.logger.debug(`[AgentBuilder:${this.name}] Starting streaming with enhanced context`, {
3287
3270
  projectPath: this.builderConfig.projectPath
3288
3271
  });
3289
- return super.stream(messages, enhancedOptions);
3272
+ return super.streamLegacy(messages, enhancedOptions);
3290
3273
  };
3291
3274
  /**
3292
3275
  * Enhanced stream method with AgentBuilder-specific configuration
3293
3276
  * Overrides the base Agent stream method to provide additional project context
3294
3277
  */
3295
- async streamVNext(messages, streamOptions) {
3278
+ async stream(messages, streamOptions) {
3296
3279
  const { ...baseOptions } = streamOptions || {};
3297
- const originalInstructions = await this.getInstructions({ runtimeContext: streamOptions?.runtimeContext });
3280
+ const originalInstructions = await this.getInstructions({ requestContext: streamOptions?.requestContext });
3298
3281
  const additionalInstructions = baseOptions.instructions;
3299
3282
  let enhancedInstructions = originalInstructions;
3300
3283
  if (additionalInstructions) {
@@ -3314,11 +3297,11 @@ ${additionalInstructions}`;
3314
3297
  this.logger.debug(`[AgentBuilder:${this.name}] Starting streaming with enhanced context`, {
3315
3298
  projectPath: this.builderConfig.projectPath
3316
3299
  });
3317
- return super.streamVNext(messages, enhancedOptions);
3300
+ return super.stream(messages, enhancedOptions);
3318
3301
  }
3319
- async generateVNext(messages, options) {
3302
+ async generate(messages, options) {
3320
3303
  const { ...baseOptions } = options || {};
3321
- const originalInstructions = await this.getInstructions({ runtimeContext: options?.runtimeContext });
3304
+ const originalInstructions = await this.getInstructions({ requestContext: options?.requestContext });
3322
3305
  const additionalInstructions = baseOptions.instructions;
3323
3306
  let enhancedInstructions = originalInstructions;
3324
3307
  if (additionalInstructions) {
@@ -3338,7 +3321,7 @@ ${additionalInstructions}`;
3338
3321
  this.logger.debug(`[AgentBuilder:${this.name}] Starting streaming with enhanced context`, {
3339
3322
  projectPath: this.builderConfig.projectPath
3340
3323
  });
3341
- return super.generateVNext(messages, enhancedOptions);
3324
+ return super.generate(messages, enhancedOptions);
3342
3325
  }
3343
3326
  };
3344
3327
  var cloneTemplateStep = createStep({
@@ -3426,14 +3409,15 @@ var discoverUnitsStep = createStep({
3426
3409
  description: "Discover template units by analyzing the templates directory structure",
3427
3410
  inputSchema: CloneTemplateResultSchema,
3428
3411
  outputSchema: DiscoveryResultSchema,
3429
- execute: async ({ inputData, runtimeContext }) => {
3412
+ execute: async ({ inputData, requestContext }) => {
3430
3413
  const { templateDir } = inputData;
3431
- const targetPath = resolveTargetPath(inputData, runtimeContext);
3414
+ const targetPath = resolveTargetPath(inputData, requestContext);
3432
3415
  const tools = await AgentBuilderDefaults.DEFAULT_TOOLS(templateDir);
3433
3416
  console.info("targetPath", targetPath);
3434
- const model = await resolveModel({ runtimeContext, projectPath: targetPath, defaultModel: openai("gpt-4.1") });
3417
+ const model = await resolveModel({ requestContext, projectPath: targetPath, defaultModel: openai("gpt-4.1") });
3435
3418
  try {
3436
3419
  const agent = new Agent({
3420
+ id: "mastra-project-discoverer",
3437
3421
  model,
3438
3422
  instructions: `You are an expert at analyzing Mastra projects.
3439
3423
 
@@ -3491,10 +3475,12 @@ Return the actual exported names of the units, as well as the file names.`,
3491
3475
  networks: z.array(z.object({ name: z.string(), file: z.string() })).optional(),
3492
3476
  other: z.array(z.object({ name: z.string(), file: z.string() })).optional()
3493
3477
  });
3494
- const result = isV2 ? await agent.generateVNext(prompt, {
3495
- output,
3478
+ const result = isV2 ? await tryGenerateWithJsonFallback(agent, prompt, {
3479
+ structuredOutput: {
3480
+ schema: output
3481
+ },
3496
3482
  maxSteps: 100
3497
- }) : await agent.generate(prompt, {
3483
+ }) : await agent.generateLegacy(prompt, {
3498
3484
  experimental_output: output,
3499
3485
  maxSteps: 100
3500
3486
  });
@@ -3568,8 +3554,8 @@ var prepareBranchStep = createStep({
3568
3554
  description: "Create or switch to integration branch before modifications",
3569
3555
  inputSchema: PrepareBranchInputSchema,
3570
3556
  outputSchema: PrepareBranchResultSchema,
3571
- execute: async ({ inputData, runtimeContext }) => {
3572
- const targetPath = resolveTargetPath(inputData, runtimeContext);
3557
+ execute: async ({ inputData, requestContext }) => {
3558
+ const targetPath = resolveTargetPath(inputData, requestContext);
3573
3559
  try {
3574
3560
  const branchName = `feat/install-template-${inputData.slug}`;
3575
3561
  await gitCheckoutBranch(branchName, targetPath);
@@ -3593,10 +3579,10 @@ var packageMergeStep = createStep({
3593
3579
  description: "Merge template package.json dependencies into target project",
3594
3580
  inputSchema: PackageMergeInputSchema,
3595
3581
  outputSchema: PackageMergeResultSchema,
3596
- execute: async ({ inputData, runtimeContext }) => {
3582
+ execute: async ({ inputData, requestContext }) => {
3597
3583
  console.info("Package merge step starting...");
3598
3584
  const { slug, packageInfo } = inputData;
3599
- const targetPath = resolveTargetPath(inputData, runtimeContext);
3585
+ const targetPath = resolveTargetPath(inputData, requestContext);
3600
3586
  try {
3601
3587
  const targetPkgPath = join(targetPath, "package.json");
3602
3588
  let targetPkgRaw = "{}";
@@ -3670,9 +3656,9 @@ var installStep = createStep({
3670
3656
  description: "Install packages based on merged package.json",
3671
3657
  inputSchema: InstallInputSchema,
3672
3658
  outputSchema: InstallResultSchema,
3673
- execute: async ({ inputData, runtimeContext }) => {
3659
+ execute: async ({ inputData, requestContext }) => {
3674
3660
  console.info("Running install step...");
3675
- const targetPath = resolveTargetPath(inputData, runtimeContext);
3661
+ const targetPath = resolveTargetPath(inputData, requestContext);
3676
3662
  try {
3677
3663
  await spawnSWPM(targetPath, "install", []);
3678
3664
  const lock = ["pnpm-lock.yaml", "package-lock.json", "yarn.lock"].map((f) => join(targetPath, f)).find((f) => existsSync(f));
@@ -3698,10 +3684,10 @@ var programmaticFileCopyStep = createStep({
3698
3684
  description: "Programmatically copy template files to target project based on ordered units",
3699
3685
  inputSchema: FileCopyInputSchema,
3700
3686
  outputSchema: FileCopyResultSchema,
3701
- execute: async ({ inputData, runtimeContext }) => {
3687
+ execute: async ({ inputData, requestContext }) => {
3702
3688
  console.info("Programmatic file copy step starting...");
3703
3689
  const { orderedUnits, templateDir, commitSha, slug } = inputData;
3704
- const targetPath = resolveTargetPath(inputData, runtimeContext);
3690
+ const targetPath = resolveTargetPath(inputData, requestContext);
3705
3691
  try {
3706
3692
  const copiedFiles = [];
3707
3693
  const conflicts = [];
@@ -4050,12 +4036,12 @@ var intelligentMergeStep = createStep({
4050
4036
  description: "Use AgentBuilder to intelligently merge template files",
4051
4037
  inputSchema: IntelligentMergeInputSchema,
4052
4038
  outputSchema: IntelligentMergeResultSchema,
4053
- execute: async ({ inputData, runtimeContext }) => {
4039
+ execute: async ({ inputData, requestContext }) => {
4054
4040
  console.info("Intelligent merge step starting...");
4055
4041
  const { conflicts, copiedFiles, commitSha, slug, templateDir, branchName } = inputData;
4056
- const targetPath = resolveTargetPath(inputData, runtimeContext);
4042
+ const targetPath = resolveTargetPath(inputData, requestContext);
4057
4043
  try {
4058
- const model = await resolveModel({ runtimeContext, projectPath: targetPath, defaultModel: openai("gpt-4.1") });
4044
+ const model = await resolveModel({ requestContext, projectPath: targetPath, defaultModel: openai("gpt-4.1") });
4059
4045
  const copyFileTool = createTool({
4060
4046
  id: "copy-file",
4061
4047
  description: "Copy a file from template to target project (use only for edge cases - most files are already copied programmatically).",
@@ -4068,9 +4054,9 @@ var intelligentMergeStep = createStep({
4068
4054
  message: z.string(),
4069
4055
  error: z.string().optional()
4070
4056
  }),
4071
- execute: async ({ context }) => {
4057
+ execute: async (input) => {
4072
4058
  try {
4073
- const { sourcePath, destinationPath } = context;
4059
+ const { sourcePath, destinationPath } = input;
4074
4060
  const resolvedSourcePath = resolve(templateDir, sourcePath);
4075
4061
  const resolvedDestinationPath = resolve(targetPath, destinationPath);
4076
4062
  if (existsSync(resolvedSourcePath) && !existsSync(dirname(resolvedDestinationPath))) {
@@ -4240,7 +4226,7 @@ For each task:
4240
4226
  Start by listing your tasks and work through them systematically!
4241
4227
  `;
4242
4228
  const isV2 = model.specificationVersion === "v2";
4243
- const result = isV2 ? await agentBuilder.streamVNext(prompt) : await agentBuilder.stream(prompt);
4229
+ const result = isV2 ? await agentBuilder.stream(prompt) : await agentBuilder.streamLegacy(prompt);
4244
4230
  const actualResolutions = [];
4245
4231
  for await (const chunk of result.fullStream) {
4246
4232
  if (chunk.type === "step-finish" || chunk.type === "step-start") {
@@ -4318,10 +4304,10 @@ var validationAndFixStep = createStep({
4318
4304
  description: "Validate the merged template code and fix any issues using a specialized agent",
4319
4305
  inputSchema: ValidationFixInputSchema,
4320
4306
  outputSchema: ValidationFixResultSchema,
4321
- execute: async ({ inputData, runtimeContext }) => {
4307
+ execute: async ({ inputData, requestContext }) => {
4322
4308
  console.info("Validation and fix step starting...");
4323
4309
  const { commitSha, slug, orderedUnits, templateDir, copiedFiles, conflictsResolved, maxIterations = 5 } = inputData;
4324
- const targetPath = resolveTargetPath(inputData, runtimeContext);
4310
+ const targetPath = resolveTargetPath(inputData, requestContext);
4325
4311
  const hasChanges = copiedFiles.length > 0 || conflictsResolved && conflictsResolved.length > 0;
4326
4312
  if (!hasChanges) {
4327
4313
  console.info("\u23ED\uFE0F Skipping validation - no files copied or conflicts resolved");
@@ -4341,10 +4327,11 @@ var validationAndFixStep = createStep({
4341
4327
  );
4342
4328
  let currentIteration = 1;
4343
4329
  try {
4344
- const model = await resolveModel({ runtimeContext, projectPath: targetPath, defaultModel: openai("gpt-4.1") });
4345
- const allTools = await AgentBuilderDefaults.getToolsForMode(targetPath, "template");
4330
+ const model = await resolveModel({ requestContext, projectPath: targetPath, defaultModel: openai("gpt-4.1") });
4331
+ const allTools = await AgentBuilderDefaults.listToolsForMode(targetPath, "template");
4346
4332
  const validationAgent = new Agent({
4347
- name: "code-validator-fixer",
4333
+ id: "code-validator-fixer",
4334
+ name: "Code Validator Fixer",
4348
4335
  description: "Specialized agent for validating and fixing template integration issues",
4349
4336
  instructions: `You are a code validation and fixing specialist. Your job is to:
4350
4337
 
@@ -4482,9 +4469,11 @@ Start by running validateCode with all validation types to get a complete pictur
4482
4469
  Previous iterations may have fixed some issues, so start by re-running validateCode to see the current state, then fix any remaining issues.`;
4483
4470
  const isV2 = model.specificationVersion === "v2";
4484
4471
  const output = z.object({ success: z.boolean() });
4485
- const result = isV2 ? await validationAgent.streamVNext(iterationPrompt, {
4486
- output
4487
- }) : await validationAgent.stream(iterationPrompt, {
4472
+ const result = isV2 ? await tryStreamWithJsonFallback(validationAgent, iterationPrompt, {
4473
+ structuredOutput: {
4474
+ schema: output
4475
+ }
4476
+ }) : await validationAgent.streamLegacy(iterationPrompt, {
4488
4477
  experimental_output: output
4489
4478
  });
4490
4479
  let iterationErrors = 0;
@@ -4745,7 +4734,7 @@ var agentBuilderTemplateWorkflow = createWorkflow({
4745
4734
  }).commit();
4746
4735
  async function mergeTemplateBySlug(slug, targetPath) {
4747
4736
  const template = await getMastraTemplate(slug);
4748
- const run = await agentBuilderTemplateWorkflow.createRunAsync();
4737
+ const run = await agentBuilderTemplateWorkflow.createRun();
4749
4738
  return await run.start({
4750
4739
  inputData: {
4751
4740
  repo: template.githubUrl,
@@ -5052,7 +5041,7 @@ var planningIterationStep = createStep({
5052
5041
  outputSchema: PlanningIterationResultSchema,
5053
5042
  suspendSchema: PlanningIterationSuspendSchema,
5054
5043
  resumeSchema: PlanningIterationResumeSchema,
5055
- execute: async ({ inputData, resumeData, suspend, runtimeContext }) => {
5044
+ execute: async ({ inputData, resumeData, suspend, requestContext }) => {
5056
5045
  const {
5057
5046
  action,
5058
5047
  workflowName,
@@ -5065,7 +5054,7 @@ var planningIterationStep = createStep({
5065
5054
  } = inputData;
5066
5055
  console.info("Starting planning iteration...");
5067
5056
  const qaKey = "workflow-builder-qa";
5068
- let storedQAPairs = runtimeContext.get(qaKey) || [];
5057
+ let storedQAPairs = requestContext.get(qaKey) || [];
5069
5058
  const newAnswers = { ...userAnswers || {}, ...resumeData?.answers || {} };
5070
5059
  if (Object.keys(newAnswers).length > 0) {
5071
5060
  storedQAPairs = storedQAPairs.map((pair) => {
@@ -5078,10 +5067,10 @@ var planningIterationStep = createStep({
5078
5067
  }
5079
5068
  return pair;
5080
5069
  });
5081
- runtimeContext.set(qaKey, storedQAPairs);
5070
+ requestContext.set(qaKey, storedQAPairs);
5082
5071
  }
5083
5072
  try {
5084
- const model = await resolveModel({ runtimeContext });
5073
+ const model = await resolveModel({ requestContext });
5085
5074
  const planningAgent = new Agent({
5086
5075
  model,
5087
5076
  instructions: taskPlanningPrompts.planningAgent.instructions({
@@ -5111,8 +5100,10 @@ var planningIterationStep = createStep({
5111
5100
  projectStructure,
5112
5101
  research
5113
5102
  });
5114
- const result = await planningAgent.generateVNext(planningPrompt, {
5115
- output: PlanningAgentOutputSchema
5103
+ const result = await planningAgent.generate(planningPrompt, {
5104
+ structuredOutput: {
5105
+ schema: PlanningAgentOutputSchema
5106
+ }
5116
5107
  // maxSteps: 15,
5117
5108
  });
5118
5109
  const planResult = await result.object;
@@ -5136,7 +5127,7 @@ var planningIterationStep = createStep({
5136
5127
  answeredAt: null
5137
5128
  }));
5138
5129
  storedQAPairs = [...storedQAPairs, ...newQAPairs];
5139
- runtimeContext.set(qaKey, storedQAPairs);
5130
+ requestContext.set(qaKey, storedQAPairs);
5140
5131
  console.info(
5141
5132
  `Updated Q&A state: ${storedQAPairs.length} total question-answer pairs, ${storedQAPairs.filter((p) => p.answer).length} answered`
5142
5133
  );
@@ -5150,7 +5141,7 @@ var planningIterationStep = createStep({
5150
5141
  });
5151
5142
  }
5152
5143
  console.info(`Planning complete with ${planResult.tasks.length} tasks`);
5153
- runtimeContext.set(qaKey, storedQAPairs);
5144
+ requestContext.set(qaKey, storedQAPairs);
5154
5145
  console.info(
5155
5146
  `Final Q&A state: ${storedQAPairs.length} total question-answer pairs, ${storedQAPairs.filter((p) => p.answer).length} answered`
5156
5147
  );
@@ -5295,7 +5286,7 @@ const myStep = createStep({
5295
5286
  - \`mastra\`: Access to Mastra instance (agents, tools, other workflows)
5296
5287
  - \`getStepResult(stepInstance)\`: Get results from previous steps
5297
5288
  - \`getInitData()\`: Access original workflow input data
5298
- - \`runtimeContext\`: Runtime dependency injection context
5289
+ - \`requestContext\`: Runtime dependency injection context
5299
5290
  - \`runCount\`: Number of times this step has run (useful for retries)
5300
5291
 
5301
5292
  ### **\u{1F504} CONTROL FLOW METHODS**
@@ -5374,10 +5365,10 @@ const toolStep = createStep(myTool);
5374
5365
 
5375
5366
  // Method 2: Call tool in execute function
5376
5367
  const step = createStep({
5377
- execute: async ({ inputData, runtimeContext }) => {
5368
+ execute: async ({ inputData, requestContext }) => {
5378
5369
  const result = await myTool.execute({
5379
5370
  context: inputData,
5380
- runtimeContext
5371
+ requestContext
5381
5372
  });
5382
5373
  return result;
5383
5374
  }
@@ -5421,7 +5412,7 @@ export const mastra = new Mastra({
5421
5412
  sendEmailWorkflow, // Use camelCase for keys
5422
5413
  dataProcessingWorkflow
5423
5414
  },
5424
- storage: new LibSQLStore({ url: 'file:./mastra.db' }), // Required for suspend/resume
5415
+ storage: new LibSQLStore({ id: 'mastra-storage', url: 'file:./mastra.db' }), // Required for suspend/resume
5425
5416
  });
5426
5417
  \`\`\`
5427
5418
 
@@ -5469,7 +5460,7 @@ export const mastra = new Mastra({
5469
5460
  **Running Workflows:**
5470
5461
  \`\`\`typescript
5471
5462
  // Create and start run
5472
- const run = await workflow.createRunAsync();
5463
+ const run = await workflow.createRun();
5473
5464
  const result = await run.start({ inputData: {...} });
5474
5465
 
5475
5466
  // Stream execution for real-time monitoring
@@ -5493,7 +5484,7 @@ run.watch((event) => console.log(event));
5493
5484
  - Use workflows as steps: \`.then(otherWorkflow)\`
5494
5485
  - Enable complex workflow composition
5495
5486
 
5496
- **Runtime Context:**
5487
+ **Request Context:**
5497
5488
  - Pass shared data across all steps
5498
5489
  - Enable dependency injection patterns
5499
5490
 
@@ -5666,11 +5657,11 @@ var restrictedTaskManager = createTool({
5666
5657
  ),
5667
5658
  message: z.string()
5668
5659
  }),
5669
- execute: async ({ context }) => {
5660
+ execute: async (input) => {
5670
5661
  const adaptedContext = {
5671
- ...context,
5672
- action: context.action,
5673
- tasks: context.tasks?.map((task) => ({
5662
+ ...input,
5663
+ action: input.action,
5664
+ tasks: input.tasks?.map((task) => ({
5674
5665
  ...task,
5675
5666
  priority: task.priority || "medium"
5676
5667
  }))
@@ -5685,7 +5676,7 @@ var workflowDiscoveryStep = createStep({
5685
5676
  description: "Discover existing workflows in the project",
5686
5677
  inputSchema: WorkflowBuilderInputSchema,
5687
5678
  outputSchema: WorkflowDiscoveryResultSchema,
5688
- execute: async ({ inputData, runtimeContext: _runtimeContext }) => {
5679
+ execute: async ({ inputData, requestContext: _requestContext }) => {
5689
5680
  console.info("Starting workflow discovery...");
5690
5681
  const { projectPath = process.cwd() } = inputData;
5691
5682
  try {
@@ -5744,7 +5735,7 @@ var projectDiscoveryStep = createStep({
5744
5735
  description: "Analyze the project structure and setup",
5745
5736
  inputSchema: WorkflowDiscoveryResultSchema,
5746
5737
  outputSchema: ProjectDiscoveryResultSchema,
5747
- execute: async ({ inputData: _inputData, runtimeContext: _runtimeContext }) => {
5738
+ execute: async ({ inputData: _inputData, requestContext: _requestContext }) => {
5748
5739
  console.info("Starting project discovery...");
5749
5740
  try {
5750
5741
  const projectPath = process.cwd();
@@ -5806,10 +5797,10 @@ var workflowResearchStep = createStep({
5806
5797
  description: "Research Mastra workflows and gather relevant documentation",
5807
5798
  inputSchema: ProjectDiscoveryResultSchema,
5808
5799
  outputSchema: WorkflowResearchResultSchema,
5809
- execute: async ({ inputData, runtimeContext }) => {
5800
+ execute: async ({ inputData, requestContext }) => {
5810
5801
  console.info("Starting workflow research...");
5811
5802
  try {
5812
- const model = await resolveModel({ runtimeContext });
5803
+ const model = await resolveModel({ requestContext });
5813
5804
  const researchAgent = new Agent({
5814
5805
  model,
5815
5806
  instructions: workflowBuilderPrompts.researchAgent.instructions,
@@ -5821,8 +5812,10 @@ var workflowResearchStep = createStep({
5821
5812
  dependencies: inputData.dependencies,
5822
5813
  hasWorkflowsDir: inputData.structure.hasWorkflowsDir
5823
5814
  });
5824
- const result = await researchAgent.generateVNext(researchPrompt, {
5825
- output: WorkflowResearchResultSchema
5815
+ const result = await researchAgent.generate(researchPrompt, {
5816
+ structuredOutput: {
5817
+ schema: WorkflowResearchResultSchema
5818
+ }
5826
5819
  // stopWhen: stepCountIs(10),
5827
5820
  });
5828
5821
  const researchResult = await result.object;
@@ -5873,7 +5866,7 @@ var taskExecutionStep = createStep({
5873
5866
  outputSchema: TaskExecutionResultSchema,
5874
5867
  suspendSchema: TaskExecutionSuspendSchema,
5875
5868
  resumeSchema: TaskExecutionResumeSchema,
5876
- execute: async ({ inputData, resumeData, suspend, runtimeContext }) => {
5869
+ execute: async ({ inputData, resumeData, suspend, requestContext }) => {
5877
5870
  const {
5878
5871
  action,
5879
5872
  workflowName,
@@ -5888,7 +5881,7 @@ var taskExecutionStep = createStep({
5888
5881
  console.info(`Starting task execution for ${action}ing workflow: ${workflowName}`);
5889
5882
  console.info(`Executing ${tasks.length} tasks using AgentBuilder stream...`);
5890
5883
  try {
5891
- const model = await resolveModel({ runtimeContext });
5884
+ const model = await resolveModel({ requestContext });
5892
5885
  const currentProjectPath = projectPath || process.cwd();
5893
5886
  console.info("Pre-populating taskManager with planned tasks...");
5894
5887
  const taskManagerContext = {
@@ -5933,18 +5926,11 @@ ${workflowBuilderPrompts.validation.instructions}`
5933
5926
  tasks,
5934
5927
  resumeData
5935
5928
  });
5936
- const originalInstructions = await executionAgent.getInstructions({ runtimeContext });
5937
- const additionalInstructions = executionAgent.instructions;
5938
- let enhancedInstructions = originalInstructions;
5939
- if (additionalInstructions) {
5940
- enhancedInstructions = `${originalInstructions}
5941
-
5942
- ${additionalInstructions}`;
5943
- }
5929
+ const originalInstructions = await executionAgent.getInstructions({ requestContext });
5944
5930
  const enhancedOptions = {
5945
5931
  stopWhen: stepCountIs(100),
5946
5932
  temperature: 0.3,
5947
- instructions: enhancedInstructions
5933
+ instructions: originalInstructions
5948
5934
  };
5949
5935
  let finalResult = null;
5950
5936
  let allTasksCompleted = false;
@@ -5973,7 +5959,7 @@ ${additionalInstructions}`;
5973
5959
  })}
5974
5960
 
5975
5961
  ${workflowBuilderPrompts.validation.instructions}`;
5976
- const stream = await executionAgent.streamVNext(iterationPrompt, {
5962
+ const stream = await executionAgent.stream(iterationPrompt, {
5977
5963
  structuredOutput: {
5978
5964
  schema: TaskExecutionIterationInputSchema(tasks.length),
5979
5965
  model