create-mastra 0.0.0-vnext-inngest-20250508122351 → 0.0.0-vnextAgentNetwork-20250527091247

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
@@ -17,7 +17,6 @@ import fs4 from 'node:fs/promises';
17
17
  import { execa } from 'execa';
18
18
  import fsExtra3, { readJSON, ensureFile, writeJSON } from 'fs-extra/esm';
19
19
  import prettier from 'prettier';
20
- import { Transform } from 'node:stream';
21
20
  import pino from 'pino';
22
21
  import pretty from 'pino-pretty';
23
22
  import fsExtra from 'fs-extra';
@@ -416,6 +415,283 @@ ${color2.gray($)} ${s}
416
415
  `);let m=0,w=0;p(),i=setInterval(()=>{const L=color2.magenta(s[m]),O=".".repeat(Math.floor(w)).slice(0,3);process.stdout.write(srcExports.cursor.move(-999,0)),process.stdout.write(srcExports.erase.down(1)),process.stdout.write(`${L} ${o}${O}`),m=m+1<s.length?m+1:0,w=w<s.length?w+.125:0;},n);},x=(g="",m=0)=>{o=g??o,r=false,clearInterval(i);const w=m===0?color2.green(M):m===1?color2.red(P):color2.red(V);process.stdout.write(srcExports.cursor.move(-999,0)),process.stdout.write(srcExports.erase.down(1)),process.stdout.write(`${w} ${o}
417
416
  `),S(),t();};return {start:f,stop:x,message:(g="")=>{o=g??o;}}};function ye(){const s=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp(s,"g")}const ve=async(s,n)=>{const t={},i=Object.keys(s);for(const r of i){const o=s[r],c=await o({results:t})?.catch(l=>{throw l});if(typeof n?.onCancel=="function"&&lD(c)){t[r]="canceled",n.onCancel({results:t});continue}t[r]=c;}return t};
418
417
 
418
+ var shellQuote$1 = {};
419
+
420
+ var quote;
421
+ var hasRequiredQuote;
422
+
423
+ function requireQuote () {
424
+ if (hasRequiredQuote) return quote;
425
+ hasRequiredQuote = 1;
426
+
427
+ quote = function quote(xs) {
428
+ return xs.map(function (s) {
429
+ if (s === '') {
430
+ return '\'\'';
431
+ }
432
+ if (s && typeof s === 'object') {
433
+ return s.op.replace(/(.)/g, '\\$1');
434
+ }
435
+ if ((/["\s]/).test(s) && !(/'/).test(s)) {
436
+ return "'" + s.replace(/(['\\])/g, '\\$1') + "'";
437
+ }
438
+ if ((/["'\s]/).test(s)) {
439
+ return '"' + s.replace(/(["\\$`!])/g, '\\$1') + '"';
440
+ }
441
+ return String(s).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}])/g, '$1\\$2');
442
+ }).join(' ');
443
+ };
444
+ return quote;
445
+ }
446
+
447
+ var parse;
448
+ var hasRequiredParse;
449
+
450
+ function requireParse () {
451
+ if (hasRequiredParse) return parse;
452
+ hasRequiredParse = 1;
453
+
454
+ // '<(' is process substitution operator and
455
+ // can be parsed the same as control operator
456
+ var CONTROL = '(?:' + [
457
+ '\\|\\|',
458
+ '\\&\\&',
459
+ ';;',
460
+ '\\|\\&',
461
+ '\\<\\(',
462
+ '\\<\\<\\<',
463
+ '>>',
464
+ '>\\&',
465
+ '<\\&',
466
+ '[&;()|<>]'
467
+ ].join('|') + ')';
468
+ var controlRE = new RegExp('^' + CONTROL + '$');
469
+ var META = '|&;()<> \\t';
470
+ var SINGLE_QUOTE = '"((\\\\"|[^"])*?)"';
471
+ var DOUBLE_QUOTE = '\'((\\\\\'|[^\'])*?)\'';
472
+ var hash = /^#$/;
473
+
474
+ var SQ = "'";
475
+ var DQ = '"';
476
+ var DS = '$';
477
+
478
+ var TOKEN = '';
479
+ var mult = 0x100000000; // Math.pow(16, 8);
480
+ for (var i = 0; i < 4; i++) {
481
+ TOKEN += (mult * Math.random()).toString(16);
482
+ }
483
+ var startsWithToken = new RegExp('^' + TOKEN);
484
+
485
+ function matchAll(s, r) {
486
+ var origIndex = r.lastIndex;
487
+
488
+ var matches = [];
489
+ var matchObj;
490
+
491
+ while ((matchObj = r.exec(s))) {
492
+ matches.push(matchObj);
493
+ if (r.lastIndex === matchObj.index) {
494
+ r.lastIndex += 1;
495
+ }
496
+ }
497
+
498
+ r.lastIndex = origIndex;
499
+
500
+ return matches;
501
+ }
502
+
503
+ function getVar(env, pre, key) {
504
+ var r = typeof env === 'function' ? env(key) : env[key];
505
+ if (typeof r === 'undefined' && key != '') {
506
+ r = '';
507
+ } else if (typeof r === 'undefined') {
508
+ r = '$';
509
+ }
510
+
511
+ if (typeof r === 'object') {
512
+ return pre + TOKEN + JSON.stringify(r) + TOKEN;
513
+ }
514
+ return pre + r;
515
+ }
516
+
517
+ function parseInternal(string, env, opts) {
518
+ if (!opts) {
519
+ opts = {};
520
+ }
521
+ var BS = opts.escape || '\\';
522
+ var BAREWORD = '(\\' + BS + '[\'"' + META + ']|[^\\s\'"' + META + '])+';
523
+
524
+ var chunker = new RegExp([
525
+ '(' + CONTROL + ')', // control chars
526
+ '(' + BAREWORD + '|' + SINGLE_QUOTE + '|' + DOUBLE_QUOTE + ')+'
527
+ ].join('|'), 'g');
528
+
529
+ var matches = matchAll(string, chunker);
530
+
531
+ if (matches.length === 0) {
532
+ return [];
533
+ }
534
+ if (!env) {
535
+ env = {};
536
+ }
537
+
538
+ var commented = false;
539
+
540
+ return matches.map(function (match) {
541
+ var s = match[0];
542
+ if (!s || commented) {
543
+ return void 0;
544
+ }
545
+ if (controlRE.test(s)) {
546
+ return { op: s };
547
+ }
548
+
549
+ // Hand-written scanner/parser for Bash quoting rules:
550
+ //
551
+ // 1. inside single quotes, all characters are printed literally.
552
+ // 2. inside double quotes, all characters are printed literally
553
+ // except variables prefixed by '$' and backslashes followed by
554
+ // either a double quote or another backslash.
555
+ // 3. outside of any quotes, backslashes are treated as escape
556
+ // characters and not printed (unless they are themselves escaped)
557
+ // 4. quote context can switch mid-token if there is no whitespace
558
+ // between the two quote contexts (e.g. all'one'"token" parses as
559
+ // "allonetoken")
560
+ var quote = false;
561
+ var esc = false;
562
+ var out = '';
563
+ var isGlob = false;
564
+ var i;
565
+
566
+ function parseEnvVar() {
567
+ i += 1;
568
+ var varend;
569
+ var varname;
570
+ var char = s.charAt(i);
571
+
572
+ if (char === '{') {
573
+ i += 1;
574
+ if (s.charAt(i) === '}') {
575
+ throw new Error('Bad substitution: ' + s.slice(i - 2, i + 1));
576
+ }
577
+ varend = s.indexOf('}', i);
578
+ if (varend < 0) {
579
+ throw new Error('Bad substitution: ' + s.slice(i));
580
+ }
581
+ varname = s.slice(i, varend);
582
+ i = varend;
583
+ } else if ((/[*@#?$!_-]/).test(char)) {
584
+ varname = char;
585
+ i += 1;
586
+ } else {
587
+ var slicedFromI = s.slice(i);
588
+ varend = slicedFromI.match(/[^\w\d_]/);
589
+ if (!varend) {
590
+ varname = slicedFromI;
591
+ i = s.length;
592
+ } else {
593
+ varname = slicedFromI.slice(0, varend.index);
594
+ i += varend.index - 1;
595
+ }
596
+ }
597
+ return getVar(env, '', varname);
598
+ }
599
+
600
+ for (i = 0; i < s.length; i++) {
601
+ var c = s.charAt(i);
602
+ isGlob = isGlob || (!quote && (c === '*' || c === '?'));
603
+ if (esc) {
604
+ out += c;
605
+ esc = false;
606
+ } else if (quote) {
607
+ if (c === quote) {
608
+ quote = false;
609
+ } else if (quote == SQ) {
610
+ out += c;
611
+ } else { // Double quote
612
+ if (c === BS) {
613
+ i += 1;
614
+ c = s.charAt(i);
615
+ if (c === DQ || c === BS || c === DS) {
616
+ out += c;
617
+ } else {
618
+ out += BS + c;
619
+ }
620
+ } else if (c === DS) {
621
+ out += parseEnvVar();
622
+ } else {
623
+ out += c;
624
+ }
625
+ }
626
+ } else if (c === DQ || c === SQ) {
627
+ quote = c;
628
+ } else if (controlRE.test(c)) {
629
+ return { op: s };
630
+ } else if (hash.test(c)) {
631
+ commented = true;
632
+ var commentObj = { comment: string.slice(match.index + i + 1) };
633
+ if (out.length) {
634
+ return [out, commentObj];
635
+ }
636
+ return [commentObj];
637
+ } else if (c === BS) {
638
+ esc = true;
639
+ } else if (c === DS) {
640
+ out += parseEnvVar();
641
+ } else {
642
+ out += c;
643
+ }
644
+ }
645
+
646
+ if (isGlob) {
647
+ return { op: 'glob', pattern: out };
648
+ }
649
+
650
+ return out;
651
+ }).reduce(function (prev, arg) { // finalize parsed arguments
652
+ // TODO: replace this whole reduce with a concat
653
+ return typeof arg === 'undefined' ? prev : prev.concat(arg);
654
+ }, []);
655
+ }
656
+
657
+ parse = function parse(s, env, opts) {
658
+ var mapped = parseInternal(s, env, opts);
659
+ if (typeof env !== 'function') {
660
+ return mapped;
661
+ }
662
+ return mapped.reduce(function (acc, s) {
663
+ if (typeof s === 'object') {
664
+ return acc.concat(s);
665
+ }
666
+ var xs = s.split(RegExp('(' + TOKEN + '.*?' + TOKEN + ')', 'g'));
667
+ if (xs.length === 1) {
668
+ return acc.concat(xs[0]);
669
+ }
670
+ return acc.concat(xs.filter(Boolean).map(function (x) {
671
+ if (startsWithToken.test(x)) {
672
+ return JSON.parse(x.split(TOKEN)[1]);
673
+ }
674
+ return x;
675
+ }));
676
+ }, []);
677
+ };
678
+ return parse;
679
+ }
680
+
681
+ var hasRequiredShellQuote;
682
+
683
+ function requireShellQuote () {
684
+ if (hasRequiredShellQuote) return shellQuote$1;
685
+ hasRequiredShellQuote = 1;
686
+
687
+ shellQuote$1.quote = requireQuote();
688
+ shellQuote$1.parse = requireParse();
689
+ return shellQuote$1;
690
+ }
691
+
692
+ var shellQuoteExports = requireShellQuote();
693
+ var shellQuote = /*@__PURE__*/getDefaultExportFromCjs(shellQuoteExports);
694
+
419
695
  // eslint-disable-next-line no-warning-comments
420
696
  // TODO: Use a better method when it's added to Node.js (https://github.com/nodejs/node/pull/40240)
421
697
  // Lots of optionals here to support Deno.
@@ -789,46 +1065,65 @@ function yoctoSpinner(options) {
789
1065
  }
790
1066
 
791
1067
  var LogLevel = {
792
- INFO: "info"};
793
- var Logger = class {
794
- logger;
1068
+ INFO: "info",
1069
+ ERROR: "error"};
1070
+ var MastraLogger = class {
1071
+ name;
1072
+ level;
795
1073
  transports;
796
1074
  constructor(options = {}) {
797
- this.transports = options.transports || {};
798
- const transportsAry = Object.entries(this.transports);
1075
+ this.name = options.name || "Mastra";
1076
+ this.level = options.level || LogLevel.ERROR;
1077
+ this.transports = new Map(Object.entries(options.transports || {}));
1078
+ }
1079
+ getTransports() {
1080
+ return this.transports;
1081
+ }
1082
+ async getLogs(transportId) {
1083
+ if (!transportId || !this.transports.has(transportId)) {
1084
+ return [];
1085
+ }
1086
+ return this.transports.get(transportId).getLogs() ?? [];
1087
+ }
1088
+ async getLogsByRunId({ transportId, runId }) {
1089
+ if (!transportId || !this.transports.has(transportId) || !runId) {
1090
+ return [];
1091
+ }
1092
+ return this.transports.get(transportId).getLogsByRunId({ runId }) ?? [];
1093
+ }
1094
+ };
1095
+
1096
+ var PinoLogger = class extends MastraLogger {
1097
+ logger;
1098
+ constructor(options = {}) {
1099
+ super(options);
1100
+ let prettyStream = void 0;
1101
+ if (!options.overrideDefaultTransports) {
1102
+ prettyStream = pretty({
1103
+ colorize: true,
1104
+ levelFirst: true,
1105
+ ignore: "pid,hostname",
1106
+ colorizeObjects: true,
1107
+ translateTime: "SYS:standard",
1108
+ singleLine: false
1109
+ });
1110
+ }
1111
+ const transportsAry = [...this.getTransports().entries()];
799
1112
  this.logger = pino(
800
1113
  {
801
1114
  name: options.name || "app",
802
1115
  level: options.level || LogLevel.INFO,
803
1116
  formatters: {
804
- level: (label) => {
805
- return {
806
- level: label
807
- };
808
- }
1117
+ level: (label) => ({ level: label })
809
1118
  }
810
1119
  },
811
- options.overrideDefaultTransports ? options?.transports?.default : transportsAry.length === 0 ? pretty({
812
- colorize: true,
813
- levelFirst: true,
814
- ignore: "pid,hostname",
815
- colorizeObjects: true,
816
- translateTime: "SYS:standard",
817
- singleLine: false
818
- }) : pino.multistream([
1120
+ options.overrideDefaultTransports ? options?.transports?.default : transportsAry.length === 0 ? prettyStream : pino.multistream([
819
1121
  ...transportsAry.map(([, transport]) => ({
820
1122
  stream: transport,
821
1123
  level: options.level || LogLevel.INFO
822
1124
  })),
823
1125
  {
824
- stream: pretty({
825
- colorize: true,
826
- levelFirst: true,
827
- ignore: "pid,hostname",
828
- colorizeObjects: true,
829
- translateTime: "SYS:standard",
830
- singleLine: false
831
- }),
1126
+ stream: prettyStream,
832
1127
  level: options.level || LogLevel.INFO
833
1128
  }
834
1129
  ])
@@ -846,31 +1141,7 @@ var Logger = class {
846
1141
  error(message, args = {}) {
847
1142
  this.logger.error(args, message);
848
1143
  }
849
- // Stream creation for process output handling
850
- createStream() {
851
- return new Transform({
852
- transform: (chunk, _encoding, callback) => {
853
- const line = chunk.toString().trim();
854
- if (line) {
855
- this.info(line);
856
- }
857
- callback(null, chunk);
858
- }
859
- });
860
- }
861
- async getLogs(transportId) {
862
- if (!transportId || !this.transports[transportId]) {
863
- return [];
864
- }
865
- return this.transports[transportId].getLogs();
866
- }
867
- async getLogsByRunId({ runId, transportId }) {
868
- return this.transports[transportId]?.getLogsByRunId({ runId });
869
- }
870
1144
  };
871
- function createLogger(options) {
872
- return new Logger(options);
873
- }
874
1145
 
875
1146
  var DepsService = class {
876
1147
  packageManager;
@@ -1001,29 +1272,55 @@ function getPackageManagerInstallCommand(pm) {
1001
1272
  }
1002
1273
  }
1003
1274
  var args = ["-y", "@mastra/mcp-docs-server@latest"];
1004
- var mcpConfig = {
1005
- mcpServers: {
1006
- mastra: process.platform === `win32` ? {
1007
- command: "cmd",
1008
- args: ["/c", "npx", ...args]
1009
- } : {
1010
- command: "npx",
1011
- args
1012
- }
1275
+ var createMcpConfig = (editor) => {
1276
+ if (editor === "vscode") {
1277
+ return {
1278
+ servers: {
1279
+ mastra: process.platform === `win32` ? {
1280
+ command: "cmd",
1281
+ args: ["/c", "npx", ...args],
1282
+ type: "stdio"
1283
+ } : {
1284
+ command: "npx",
1285
+ args,
1286
+ type: "stdio"
1287
+ }
1288
+ }
1289
+ };
1013
1290
  }
1291
+ return {
1292
+ mcpServers: {
1293
+ mastra: process.platform === `win32` ? {
1294
+ command: "cmd",
1295
+ args: ["/c", "npx", ...args]
1296
+ } : {
1297
+ command: "npx",
1298
+ args
1299
+ }
1300
+ }
1301
+ };
1014
1302
  };
1015
- function makeConfig(original) {
1303
+ function makeConfig(original, editor) {
1304
+ if (editor === "vscode") {
1305
+ return {
1306
+ ...original,
1307
+ servers: {
1308
+ ...original?.servers || {},
1309
+ ...createMcpConfig(editor).servers
1310
+ }
1311
+ };
1312
+ }
1016
1313
  return {
1017
1314
  ...original,
1018
1315
  mcpServers: {
1019
1316
  ...original?.mcpServers || {},
1020
- ...mcpConfig.mcpServers
1317
+ ...createMcpConfig(editor).mcpServers
1021
1318
  }
1022
1319
  };
1023
1320
  }
1024
- async function writeMergedConfig(configPath) {
1321
+ async function writeMergedConfig(configPath, editor) {
1025
1322
  const configExists = existsSync(configPath);
1026
- const config = makeConfig(configExists ? await readJSON(configPath) : {});
1323
+ const config = makeConfig(configExists ? await readJSON(configPath) : {}, editor);
1027
1324
  await ensureFile(configPath);
1028
1325
  await writeJSON(configPath, config, {
1029
1326
  spaces: 2
@@ -1031,26 +1328,27 @@ async function writeMergedConfig(configPath) {
1031
1328
  }
1032
1329
  var windsurfGlobalMCPConfigPath = path.join(os.homedir(), ".codeium", "windsurf", "mcp_config.json");
1033
1330
  var cursorGlobalMCPConfigPath = path.join(os.homedir(), ".cursor", "mcp.json");
1034
- async function installMastraDocsMCPServer({
1035
- editor,
1036
- directory
1037
- }) {
1331
+ path.join(process.cwd(), ".vscode", "mcp.json");
1332
+ async function installMastraDocsMCPServer({ editor, directory }) {
1038
1333
  if (editor === `cursor`) {
1039
- await writeMergedConfig(path.join(directory, ".cursor", "mcp.json"));
1334
+ await writeMergedConfig(path.join(directory, ".cursor", "mcp.json"), "cursor");
1335
+ }
1336
+ if (editor === `vscode`) {
1337
+ await writeMergedConfig(path.join(directory, ".vscode", "mcp.json"), "vscode");
1040
1338
  }
1041
1339
  if (editor === `cursor-global`) {
1042
1340
  const alreadyInstalled = await globalMCPIsAlreadyInstalled(editor);
1043
1341
  if (alreadyInstalled) {
1044
1342
  return;
1045
1343
  }
1046
- await writeMergedConfig(cursorGlobalMCPConfigPath);
1344
+ await writeMergedConfig(cursorGlobalMCPConfigPath, "cursor-global");
1047
1345
  }
1048
1346
  if (editor === `windsurf`) {
1049
1347
  const alreadyInstalled = await globalMCPIsAlreadyInstalled(editor);
1050
1348
  if (alreadyInstalled) {
1051
1349
  return;
1052
1350
  }
1053
- await writeMergedConfig(windsurfGlobalMCPConfigPath);
1351
+ await writeMergedConfig(windsurfGlobalMCPConfigPath, editor);
1054
1352
  }
1055
1353
  }
1056
1354
  async function globalMCPIsAlreadyInstalled(editor) {
@@ -1181,7 +1479,7 @@ var FileService = class {
1181
1479
  fs3__default__default.writeFileSync(filePath, fileContent);
1182
1480
  }
1183
1481
  };
1184
- createLogger({
1482
+ new PinoLogger({
1185
1483
  name: "Mastra CLI",
1186
1484
  level: "debug"
1187
1485
  });
@@ -1207,7 +1505,7 @@ var getProviderImportAndModelItem = (llmProvider) => {
1207
1505
  let modelItem = "";
1208
1506
  if (llmProvider === "openai") {
1209
1507
  providerImport = `import { openai } from '${getAISDKPackage(llmProvider)}';`;
1210
- modelItem = `openai('gpt-4o')`;
1508
+ modelItem = `openai('gpt-4o-mini')`;
1211
1509
  } else if (llmProvider === "anthropic") {
1212
1510
  providerImport = `import { anthropic } from '${getAISDKPackage(llmProvider)}';`;
1213
1511
  modelItem = `anthropic('claude-3-5-sonnet-20241022')`;
@@ -1242,7 +1540,7 @@ ${providerImport}
1242
1540
  import { Agent } from '@mastra/core/agent';
1243
1541
  import { Memory } from '@mastra/memory';
1244
1542
  import { LibSQLStore } from '@mastra/libsql';
1245
- ${addExampleTool ? `import { weatherTool } from '../tools';` : ""}
1543
+ ${addExampleTool ? `import { weatherTool } from '../tools/weather-tool';` : ""}
1246
1544
 
1247
1545
  export const weatherAgent = new Agent({
1248
1546
  name: 'Weather Agent',
@@ -1252,14 +1550,7 @@ export const weatherAgent = new Agent({
1252
1550
  memory: new Memory({
1253
1551
  storage: new LibSQLStore({
1254
1552
  url: "file:../mastra.db", // path is relative to the .mastra/output directory
1255
- }),
1256
- options: {
1257
- lastMessages: 10,
1258
- semanticRecall: false,
1259
- threads: {
1260
- generateTitle: false
1261
- }
1262
- }
1553
+ })
1263
1554
  })
1264
1555
  });
1265
1556
  `;
@@ -1274,7 +1565,7 @@ async function writeWorkflowSample(destPath, llmProvider) {
1274
1565
  const { providerImport, modelItem } = getProviderImportAndModelItem(llmProvider);
1275
1566
  const content = `${providerImport}
1276
1567
  import { Agent } from '@mastra/core/agent';
1277
- import { Step, Workflow } from '@mastra/core/workflows';
1568
+ import { createStep, createWorkflow } from '@mastra/core/workflows';
1278
1569
  import { z } from 'zod';
1279
1570
 
1280
1571
  const llm = ${modelItem};
@@ -1327,80 +1618,106 @@ const agent = new Agent({
1327
1618
  \`,
1328
1619
  });
1329
1620
 
1330
- const forecastSchema = z.array(
1331
- z.object({
1332
- date: z.string(),
1333
- maxTemp: z.number(),
1334
- minTemp: z.number(),
1335
- precipitationChance: z.number(),
1336
- condition: z.string(),
1337
- location: z.string(),
1338
- }),
1339
- );
1621
+ const forecastSchema = z.object({
1622
+ date: z.string(),
1623
+ maxTemp: z.number(),
1624
+ minTemp: z.number(),
1625
+ precipitationChance: z.number(),
1626
+ condition: z.string(),
1627
+ location: z.string(),
1628
+ })
1340
1629
 
1341
- const fetchWeather = new Step({
1630
+ function getWeatherCondition(code: number): string {
1631
+ const conditions: Record<number, string> = {
1632
+ 0: 'Clear sky',
1633
+ 1: 'Mainly clear',
1634
+ 2: 'Partly cloudy',
1635
+ 3: 'Overcast',
1636
+ 45: 'Foggy',
1637
+ 48: 'Depositing rime fog',
1638
+ 51: 'Light drizzle',
1639
+ 53: 'Moderate drizzle',
1640
+ 55: 'Dense drizzle',
1641
+ 61: 'Slight rain',
1642
+ 63: 'Moderate rain',
1643
+ 65: 'Heavy rain',
1644
+ 71: 'Slight snow fall',
1645
+ 73: 'Moderate snow fall',
1646
+ 75: 'Heavy snow fall',
1647
+ 95: 'Thunderstorm',
1648
+ }
1649
+ return conditions[code] || 'Unknown'
1650
+ }
1651
+
1652
+ const fetchWeather = createStep({
1342
1653
  id: 'fetch-weather',
1343
1654
  description: 'Fetches weather forecast for a given city',
1344
1655
  inputSchema: z.object({
1345
1656
  city: z.string().describe('The city to get the weather for'),
1346
1657
  }),
1347
1658
  outputSchema: forecastSchema,
1348
- execute: async ({ context }) => {
1349
- const triggerData = context?.getStepResult<{ city: string }>('trigger');
1350
-
1351
- if (!triggerData) {
1352
- throw new Error('Trigger data not found');
1659
+ execute: async ({ inputData }) => {
1660
+ if (!inputData) {
1661
+ throw new Error('Input data not found');
1353
1662
  }
1354
1663
 
1355
- const geocodingUrl = \`https://geocoding-api.open-meteo.com/v1/search?name=\${encodeURIComponent(triggerData.city)}&count=1\`;
1664
+ const geocodingUrl = \`https://geocoding-api.open-meteo.com/v1/search?name=\${encodeURIComponent(inputData.city)}&count=1\`;
1356
1665
  const geocodingResponse = await fetch(geocodingUrl);
1357
1666
  const geocodingData = (await geocodingResponse.json()) as {
1358
1667
  results: { latitude: number; longitude: number; name: string }[];
1359
1668
  };
1360
1669
 
1361
1670
  if (!geocodingData.results?.[0]) {
1362
- throw new Error(\`Location '\${triggerData.city}' not found\`);
1671
+ throw new Error(\`Location '\${inputData.city}' not found\`);
1363
1672
  }
1364
1673
 
1365
1674
  const { latitude, longitude, name } = geocodingData.results[0];
1366
1675
 
1367
- const weatherUrl = \`https://api.open-meteo.com/v1/forecast?latitude=\${latitude}&longitude=\${longitude}&daily=temperature_2m_max,temperature_2m_min,precipitation_probability_mean,weathercode&timezone=auto\`;
1676
+ const weatherUrl = \`https://api.open-meteo.com/v1/forecast?latitude=\${latitude}&longitude=\${longitude}&current=precipitation,weathercode&timezone=auto,&hourly=precipitation_probability,temperature_2m\`;
1368
1677
  const response = await fetch(weatherUrl);
1369
1678
  const data = (await response.json()) as {
1370
- daily: {
1371
- time: string[];
1372
- temperature_2m_max: number[];
1373
- temperature_2m_min: number[];
1374
- precipitation_probability_mean: number[];
1375
- weathercode: number[];
1376
- };
1377
- };
1679
+ current: {
1680
+ time: string
1681
+ precipitation: number
1682
+ weathercode: number
1683
+ }
1684
+ hourly: {
1685
+ precipitation_probability: number[]
1686
+ temperature_2m: number[]
1687
+ }
1688
+ }
1378
1689
 
1379
- const forecast = data.daily.time.map((date: string, index: number) => ({
1380
- date,
1381
- maxTemp: data.daily.temperature_2m_max[index],
1382
- minTemp: data.daily.temperature_2m_min[index],
1383
- precipitationChance: data.daily.precipitation_probability_mean[index],
1384
- condition: getWeatherCondition(data.daily.weathercode[index]!),
1385
- location: name,
1386
- }));
1690
+ const forecast = {
1691
+ date: new Date().toISOString(),
1692
+ maxTemp: Math.max(...data.hourly.temperature_2m),
1693
+ minTemp: Math.min(...data.hourly.temperature_2m),
1694
+ condition: getWeatherCondition(data.current.weathercode),
1695
+ precipitationChance: data.hourly.precipitation_probability.reduce(
1696
+ (acc, curr) => Math.max(acc, curr),
1697
+ 0
1698
+ ),
1699
+ }
1387
1700
 
1388
1701
  return forecast;
1389
1702
  },
1390
1703
  });
1391
1704
 
1392
1705
 
1393
- const planActivities = new Step({
1706
+ const planActivities = createStep({
1394
1707
  id: 'plan-activities',
1395
1708
  description: 'Suggests activities based on weather conditions',
1396
- execute: async ({ context, mastra }) => {
1397
- const forecast = context?.getStepResult(fetchWeather);
1709
+ inputSchema: forecastSchema,
1710
+ outputSchema: z.object({
1711
+ activities: z.string(),
1712
+ }),
1713
+ execute: async ({ inputData }) => {
1714
+ const forecast = inputData
1398
1715
 
1399
- if (!forecast || forecast.length === 0) {
1400
- throw new Error('Forecast data not found');
1716
+ if (!forecast) {
1717
+ throw new Error('Forecast data not found')
1401
1718
  }
1402
1719
 
1403
- const prompt = \`Based on the following weather forecast for \${forecast[0]?.location}, suggest appropriate activities:
1720
+ const prompt = \`Based on the following weather forecast for \${forecast.location}, suggest appropriate activities:
1404
1721
  \${JSON.stringify(forecast, null, 2)}
1405
1722
  \`;
1406
1723
 
@@ -1424,35 +1741,16 @@ const planActivities = new Step({
1424
1741
  },
1425
1742
  });
1426
1743
 
1427
- function getWeatherCondition(code: number): string {
1428
- const conditions: Record<number, string> = {
1429
- 0: 'Clear sky',
1430
- 1: 'Mainly clear',
1431
- 2: 'Partly cloudy',
1432
- 3: 'Overcast',
1433
- 45: 'Foggy',
1434
- 48: 'Depositing rime fog',
1435
- 51: 'Light drizzle',
1436
- 53: 'Moderate drizzle',
1437
- 55: 'Dense drizzle',
1438
- 61: 'Slight rain',
1439
- 63: 'Moderate rain',
1440
- 65: 'Heavy rain',
1441
- 71: 'Slight snow fall',
1442
- 73: 'Moderate snow fall',
1443
- 75: 'Heavy snow fall',
1444
- 95: 'Thunderstorm',
1445
- };
1446
- return conditions[code] || 'Unknown';
1447
- }
1448
-
1449
- const weatherWorkflow = new Workflow({
1450
- name: 'weather-workflow',
1451
- triggerSchema: z.object({
1744
+ const weatherWorkflow = createWorkflow({
1745
+ id: 'weather-workflow',
1746
+ inputSchema: z.object({
1452
1747
  city: z.string().describe('The city to get the weather for'),
1453
1748
  }),
1749
+ outputSchema: z.object({
1750
+ activities: z.string(),
1751
+ })
1454
1752
  })
1455
- .step(fetchWeather)
1753
+ .then(fetchWeather)
1456
1754
  .then(planActivities);
1457
1755
 
1458
1756
  weatherWorkflow.commit();
@@ -1514,10 +1812,10 @@ export const mastra = new Mastra()
1514
1812
  destPath,
1515
1813
  `
1516
1814
  import { Mastra } from '@mastra/core/mastra';
1517
- import { createLogger } from '@mastra/core/logger';
1815
+ import { PinoLogger } from '@mastra/loggers';
1518
1816
  import { LibSQLStore } from '@mastra/libsql';
1519
- ${addWorkflow ? `import { weatherWorkflow } from './workflows';` : ""}
1520
- ${addAgent ? `import { weatherAgent } from './agents';` : ""}
1817
+ ${addWorkflow ? `import { weatherWorkflow } from './workflows/weather-workflow';` : ""}
1818
+ ${addAgent ? `import { weatherAgent } from './agents/weather-agent';` : ""}
1521
1819
 
1522
1820
  export const mastra = new Mastra({
1523
1821
  ${filteredExports.join("\n ")}
@@ -1525,7 +1823,7 @@ export const mastra = new Mastra({
1525
1823
  // stores telemetry, evals, ... into memory storage, if it needs to persist, change to file:../mastra.db
1526
1824
  url: ":memory:",
1527
1825
  }),
1528
- logger: createLogger({
1826
+ logger: new PinoLogger({
1529
1827
  name: 'Mastra',
1530
1828
  level: 'info',
1531
1829
  }),
@@ -1561,7 +1859,9 @@ var writeAPIKey = async ({
1561
1859
  apiKey = "your-api-key"
1562
1860
  }) => {
1563
1861
  const key = await getAPIKey(provider);
1564
- await exec(`echo ${key}=${apiKey} >> .env.development`);
1862
+ const escapedKey = shellQuote.quote([key]);
1863
+ const escapedApiKey = shellQuote.quote([apiKey]);
1864
+ await exec(`echo ${escapedKey}=${escapedApiKey} >> .env`);
1565
1865
  };
1566
1866
  var createMastraDir = async (directory) => {
1567
1867
  let dir = directory.trim().split("/").filter((item) => item !== "");
@@ -1575,7 +1875,7 @@ var createMastraDir = async (directory) => {
1575
1875
  }
1576
1876
  };
1577
1877
  var writeCodeSample = async (dirPath, component, llmProvider, importComponents) => {
1578
- const destPath = dirPath + `/${component}/index.ts`;
1878
+ const destPath = dirPath + `/${component}/weather-${component.slice(0, -1)}.ts`;
1579
1879
  try {
1580
1880
  await writeCodeSampleForComponents(llmProvider, component, destPath, importComponents);
1581
1881
  } catch (err) {
@@ -1755,6 +2055,10 @@ var init = async ({
1755
2055
  if (needsMemory) {
1756
2056
  await depService.installPackages(["@mastra/memory"]);
1757
2057
  }
2058
+ const needsLoggers = await depService.checkDependencies(["@mastra/loggers"]) !== `ok`;
2059
+ if (needsLoggers) {
2060
+ await depService.installPackages(["@mastra/loggers"]);
2061
+ }
1758
2062
  }
1759
2063
  const key = await getAPIKey(llmProvider || "openai");
1760
2064
  const aiSdkPackage = getAISDKPackage(llmProvider);
@@ -1774,7 +2078,7 @@ var init = async ({
1774
2078
  ${color2.green("Mastra initialized successfully!")}
1775
2079
 
1776
2080
  Add your ${color2.cyan(key)} as an environment variable
1777
- in your ${color2.cyan(".env.development")} file
2081
+ in your ${color2.cyan(".env")} file
1778
2082
  `);
1779
2083
  } else {
1780
2084
  me(`
@@ -1864,6 +2168,7 @@ var createMastraProject = async ({
1864
2168
  s2.message("Creating project");
1865
2169
  await exec3(`npm init -y`);
1866
2170
  await exec3(`npm pkg set type="module"`);
2171
+ await exec3(`npm pkg set engines.node=">=20.9.0"`);
1867
2172
  const depsService = new DepsService();
1868
2173
  await depsService.addScriptsToPackageJson({
1869
2174
  dev: "mastra dev",
@@ -1935,16 +2240,18 @@ var create = async (args2) => {
1935
2240
  components,
1936
2241
  llmProvider,
1937
2242
  addExample,
1938
- llmApiKey
2243
+ llmApiKey,
2244
+ configureEditorWithDocsMCP: args2.mcpServer
1939
2245
  });
1940
2246
  postCreate({ projectName });
1941
2247
  };
1942
2248
  var postCreate = ({ projectName }) => {
2249
+ const packageManager = getPackageManager();
1943
2250
  ge(`
1944
2251
  ${color2.green("To start your project:")}
1945
2252
 
1946
2253
  ${color2.cyan("cd")} ${projectName}
1947
- ${color2.cyan("npm run dev")}
2254
+ ${color2.cyan(`${packageManager} run dev`)}
1948
2255
  `);
1949
2256
  };
1950
2257
 
@@ -1960,7 +2267,7 @@ async function getCreateVersionTag() {
1960
2267
  const pkgPath = fileURLToPath(import.meta.resolve("create-mastra/package.json"));
1961
2268
  const json = await fsExtra.readJSON(pkgPath);
1962
2269
  const { stdout } = await execa("npm", ["dist-tag", "create-mastra"]);
1963
- const tagLine = stdout.split("\n").find((distLine) => distLine.includes(`: ${json.version}`));
2270
+ const tagLine = stdout.split("\n").find((distLine) => distLine.endsWith(`: ${json.version}`));
1964
2271
  const tag = tagLine ? tagLine.split(":")[0].trim() : "latest";
1965
2272
  return tag;
1966
2273
  } catch {
@@ -1989,16 +2296,17 @@ program.version(`${version}`, "-v, --version").description(`create-mastra ${vers
1989
2296
  program.name("create-mastra").description("Create a new Mastra project").argument("[project-name]", "Directory name of the project").option(
1990
2297
  "-p, --project-name <string>",
1991
2298
  "Project name that will be used in package.json and as the project directory name."
1992
- ).option("--default", "Quick start with defaults(src, OpenAI, no examples)").option("-c, --components <components>", "Comma-separated list of components (agents, tools, workflows)").option("-l, --llm <model-provider>", "Default model provider (openai, anthropic, groq, google, or cerebras)").option("-k, --llm-api-key <api-key>", "API key for the model provider").option("-e, --example", "Include example code").option("-n, --no-example", "Do not include example code").option("-t, --timeout [timeout]", "Configurable timeout for package installation, defaults to 60000 ms").option("-d, --dir <directory>", "Target directory for Mastra source code (default: src/)").action(async (projectNameArg, args) => {
2299
+ ).option("--default", "Quick start with defaults(src, OpenAI, no examples)").option("-c, --components <components>", "Comma-separated list of components (agents, tools, workflows)").option("-l, --llm <model-provider>", "Default model provider (openai, anthropic, groq, google, or cerebras)").option("-k, --llm-api-key <api-key>", "API key for the model provider").option("-e, --example", "Include example code").option("-n, --no-example", "Do not include example code").option("-t, --timeout [timeout]", "Configurable timeout for package installation, defaults to 60000 ms").option("-d, --dir <directory>", "Target directory for Mastra source code (default: src/)").option("-m, --mcp <mcp>", "MCP Server for code editor (cursor, cursor-global, windsurf, vscode)").action(async (projectNameArg, args) => {
1993
2300
  const projectName = projectNameArg || args.projectName;
1994
2301
  const timeout = args?.timeout ? args?.timeout === true ? 6e4 : parseInt(args?.timeout, 10) : void 0;
1995
2302
  if (args.default) {
1996
2303
  await create({
1997
2304
  components: ["agents", "tools", "workflows"],
1998
2305
  llmProvider: "openai",
1999
- addExample: false,
2306
+ addExample: true,
2000
2307
  createVersionTag,
2001
- timeout
2308
+ timeout,
2309
+ mcpServer: args.mcp
2002
2310
  });
2003
2311
  return;
2004
2312
  }
@@ -2010,7 +2318,8 @@ program.name("create-mastra").description("Create a new Mastra project").argumen
2010
2318
  createVersionTag,
2011
2319
  timeout,
2012
2320
  projectName,
2013
- directory: args.dir
2321
+ directory: args.dir,
2322
+ mcpServer: args.mcp
2014
2323
  });
2015
2324
  });
2016
2325
  program.parse(process.argv);