mastra 0.10.21 → 0.10.22-alpha.0

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.
Files changed (102) hide show
  1. package/dist/analytics/index.js +1 -0
  2. package/dist/answer-relevancy-scorer-CTIL35GQ.js +22 -0
  3. package/dist/answer-relevancy-scorer-CTIL35GQ.js.map +1 -0
  4. package/dist/bias-detection-scorer-IWHTLHDC.js +23 -0
  5. package/dist/bias-detection-scorer-IWHTLHDC.js.map +1 -0
  6. package/dist/{chunk-KBXIE32B.js → chunk-MTFODRSK.js} +2 -2
  7. package/dist/{chunk-KBXIE32B.js.map → chunk-MTFODRSK.js.map} +1 -1
  8. package/dist/chunk-QKQ47GQZ.js +9 -0
  9. package/dist/chunk-QKQ47GQZ.js.map +1 -0
  10. package/dist/commands/actions/add-scorer.d.ts +2 -0
  11. package/dist/commands/actions/add-scorer.d.ts.map +1 -0
  12. package/dist/commands/actions/build-project.d.ts +2 -0
  13. package/dist/commands/actions/build-project.d.ts.map +1 -0
  14. package/dist/commands/actions/create-project.d.ts +2 -0
  15. package/dist/commands/actions/create-project.d.ts.map +1 -0
  16. package/dist/commands/actions/deploy-project.d.ts +2 -0
  17. package/dist/commands/actions/deploy-project.d.ts.map +1 -0
  18. package/dist/commands/actions/init-project.d.ts +2 -0
  19. package/dist/commands/actions/init-project.d.ts.map +1 -0
  20. package/dist/commands/actions/lint-project.d.ts +2 -0
  21. package/dist/commands/actions/lint-project.d.ts.map +1 -0
  22. package/dist/commands/actions/list-scorers.d.ts +2 -0
  23. package/dist/commands/actions/list-scorers.d.ts.map +1 -0
  24. package/dist/commands/actions/start-dev-server.d.ts +2 -0
  25. package/dist/commands/actions/start-dev-server.d.ts.map +1 -0
  26. package/dist/commands/actions/start-project.d.ts +2 -0
  27. package/dist/commands/actions/start-project.d.ts.map +1 -0
  28. package/dist/commands/create/create.js +2 -1
  29. package/dist/commands/dev/telemetry-resolver.js +2 -0
  30. package/dist/commands/dev/telemetry-resolver.js.map +1 -1
  31. package/dist/commands/scorers/add-new-scorer.d.ts +4 -0
  32. package/dist/commands/scorers/add-new-scorer.d.ts.map +1 -0
  33. package/dist/commands/scorers/available-scorers.d.ts +3 -0
  34. package/dist/commands/scorers/available-scorers.d.ts.map +1 -0
  35. package/dist/commands/scorers/file-utils.d.ts +5 -0
  36. package/dist/commands/scorers/file-utils.d.ts.map +1 -0
  37. package/dist/commands/scorers/list-all-scorers.d.ts +2 -0
  38. package/dist/commands/scorers/list-all-scorers.d.ts.map +1 -0
  39. package/dist/commands/scorers/types.d.ts +9 -0
  40. package/dist/commands/scorers/types.d.ts.map +1 -0
  41. package/dist/completeness-scorer-KH4LU4BW.js +23 -0
  42. package/dist/completeness-scorer-KH4LU4BW.js.map +1 -0
  43. package/dist/content-similarity-scorer-NB76ISB5.js +22 -0
  44. package/dist/content-similarity-scorer-NB76ISB5.js.map +1 -0
  45. package/dist/faithfulness-scorer-F6GLSRTV.js +28 -0
  46. package/dist/faithfulness-scorer-F6GLSRTV.js.map +1 -0
  47. package/dist/hallucination-scorer-NJW7PTKD.js +28 -0
  48. package/dist/hallucination-scorer-NJW7PTKD.js.map +1 -0
  49. package/dist/index.d.ts +5 -1
  50. package/dist/index.d.ts.map +1 -1
  51. package/dist/index.js +712 -389
  52. package/dist/index.js.map +1 -1
  53. package/dist/keyword-coverage-scorer-63AEWDTL.js +22 -0
  54. package/dist/keyword-coverage-scorer-63AEWDTL.js.map +1 -0
  55. package/dist/templates/scorers/answer-relevancy-scorer.d.ts +2 -0
  56. package/dist/templates/scorers/answer-relevancy-scorer.d.ts.map +1 -0
  57. package/dist/templates/scorers/answer-relevancy-scorer.ts +15 -0
  58. package/dist/templates/scorers/bias-detection-scorer.d.ts +2 -0
  59. package/dist/templates/scorers/bias-detection-scorer.d.ts.map +1 -0
  60. package/dist/templates/scorers/bias-detection-scorer.ts +16 -0
  61. package/dist/templates/scorers/completeness-scorer.d.ts +2 -0
  62. package/dist/templates/scorers/completeness-scorer.d.ts.map +1 -0
  63. package/dist/templates/scorers/completeness-scorer.ts +16 -0
  64. package/dist/templates/scorers/content-similarity-scorer.d.ts +2 -0
  65. package/dist/templates/scorers/content-similarity-scorer.d.ts.map +1 -0
  66. package/dist/templates/scorers/content-similarity-scorer.ts +15 -0
  67. package/dist/templates/scorers/faithfulness-scorer.d.ts +2 -0
  68. package/dist/templates/scorers/faithfulness-scorer.d.ts.map +1 -0
  69. package/dist/templates/scorers/faithfulness-scorer.ts +21 -0
  70. package/dist/templates/scorers/hallucination-scorer.d.ts +2 -0
  71. package/dist/templates/scorers/hallucination-scorer.d.ts.map +1 -0
  72. package/dist/templates/scorers/hallucination-scorer.ts +21 -0
  73. package/dist/templates/scorers/keyword-coverage-scorer.d.ts +2 -0
  74. package/dist/templates/scorers/keyword-coverage-scorer.d.ts.map +1 -0
  75. package/dist/templates/scorers/keyword-coverage-scorer.ts +15 -0
  76. package/dist/templates/scorers/textual-difference-scorer.d.ts +2 -0
  77. package/dist/templates/scorers/textual-difference-scorer.d.ts.map +1 -0
  78. package/dist/templates/scorers/textual-difference-scorer.ts +16 -0
  79. package/dist/templates/scorers/tone-consistency-scorer.d.ts +2 -0
  80. package/dist/templates/scorers/tone-consistency-scorer.d.ts.map +1 -0
  81. package/dist/templates/scorers/tone-consistency-scorer.ts +16 -0
  82. package/dist/templates/scorers/toxicity-detection-scorer.d.ts +2 -0
  83. package/dist/templates/scorers/toxicity-detection-scorer.d.ts.map +1 -0
  84. package/dist/templates/scorers/toxicity-detection-scorer.ts +16 -0
  85. package/dist/textual-difference-scorer-2MUWQ22U.js +23 -0
  86. package/dist/textual-difference-scorer-2MUWQ22U.js.map +1 -0
  87. package/dist/tone-consistency-scorer-ZEXVRFCP.js +23 -0
  88. package/dist/tone-consistency-scorer-ZEXVRFCP.js.map +1 -0
  89. package/dist/toxicity-detection-scorer-RMTLQCHI.js +23 -0
  90. package/dist/toxicity-detection-scorer-RMTLQCHI.js.map +1 -0
  91. package/dist/utils/string.d.ts.map +1 -1
  92. package/package.json +6 -6
  93. package/dist/starter-files/config.d.ts +0 -26
  94. package/dist/starter-files/config.d.ts.map +0 -1
  95. package/dist/starter-files/config.ts +0 -25
  96. package/dist/starter-files/mastra-pg.docker-compose.yaml +0 -15
  97. package/dist/utils/find-api-keys.d.ts +0 -5
  98. package/dist/utils/find-api-keys.d.ts.map +0 -1
  99. package/dist/utils/get-engine-path.d.ts +0 -2
  100. package/dist/utils/get-engine-path.d.ts.map +0 -1
  101. package/dist/utils/get-env.d.ts +0 -2
  102. package/dist/utils/get-env.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -1,14 +1,19 @@
1
1
  #! /usr/bin/env node
2
- import { DepsService, create, checkPkgJson, checkAndInstallCoreDeps, interactivePrompt, init, logger, FileService } from './chunk-KBXIE32B.js';
3
- export { create } from './chunk-KBXIE32B.js';
2
+ import { DepsService, create, checkPkgJson, checkAndInstallCoreDeps, interactivePrompt, init, logger, FileService } from './chunk-MTFODRSK.js';
3
+ export { create } from './chunk-MTFODRSK.js';
4
4
  import { PosthogAnalytics, setAnalytics } from './chunk-OQQFOUQW.js';
5
5
  export { PosthogAnalytics } from './chunk-OQQFOUQW.js';
6
+ import { __glob } from './chunk-QKQ47GQZ.js';
6
7
  import { Command } from 'commander';
7
- import { config } from 'dotenv';
8
- import { join, dirname } from 'path';
8
+ import color from 'picocolors';
9
+ import * as p2 from '@clack/prompts';
10
+ import fs, { readFileSync } from 'fs';
11
+ import path, { join, dirname } from 'path';
9
12
  import { getServerOptions, FileService as FileService$2, getBundlerOptions, getWatcherInputOptions, writeTelemetryConfig, createWatcher } from '@mastra/deployer/build';
10
13
  import { Bundler } from '@mastra/deployer/bundler';
11
14
  import { getDeployer, FileService as FileService$1 } from '@mastra/deployer';
15
+ import { config } from 'dotenv';
16
+ import stripJsonComments from 'strip-json-comments';
12
17
  import process2 from 'process';
13
18
  import { isWebContainer } from '@webcontainer/env';
14
19
  import { execa } from 'execa';
@@ -16,10 +21,267 @@ import getPort from 'get-port';
16
21
  import { writeFile } from 'fs/promises';
17
22
  import { fileURLToPath } from 'url';
18
23
  import * as fsExtra from 'fs-extra';
19
- import fs, { readFileSync } from 'fs';
20
- import stripJsonComments from 'strip-json-comments';
21
24
  import { spawn } from 'child_process';
22
25
 
26
+ // src/utils/string.ts
27
+ var toCamelCase = (str) => {
28
+ return str.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
29
+ };
30
+
31
+ // src/commands/scorers/available-scorers.ts
32
+ var AVAILABLE_SCORERS = [
33
+ // Accuracy and Reliability scorers
34
+ {
35
+ id: "answer-relevancy",
36
+ name: "Answer Relevancy",
37
+ description: "Evaluates how well responses address the input query using LLM",
38
+ category: "accuracy-and-reliability",
39
+ filename: "answer-relevancy-scorer.ts"
40
+ },
41
+ {
42
+ id: "faithfulness",
43
+ name: "Faithfulness",
44
+ description: "Measures how accurately responses represent provided context",
45
+ category: "accuracy-and-reliability",
46
+ filename: "faithfulness-scorer.ts"
47
+ },
48
+ {
49
+ id: "hallucination",
50
+ name: "Hallucination Detection",
51
+ description: "Detects facts or claims not present in provided context",
52
+ category: "accuracy-and-reliability",
53
+ filename: "hallucination-scorer.ts"
54
+ },
55
+ {
56
+ id: "completeness",
57
+ name: "Completeness",
58
+ description: "Checks if responses include all necessary information",
59
+ category: "accuracy-and-reliability",
60
+ filename: "completeness-scorer.ts"
61
+ },
62
+ {
63
+ id: "content-similarity",
64
+ name: "Content Similarity",
65
+ description: "Evaluates consistency of information across different phrasings",
66
+ category: "accuracy-and-reliability",
67
+ filename: "content-similarity-scorer.ts"
68
+ },
69
+ {
70
+ id: "textual-difference",
71
+ name: "Textual Difference",
72
+ description: "Measures textual differences between strings",
73
+ category: "accuracy-and-reliability",
74
+ filename: "textual-difference-scorer.ts"
75
+ },
76
+ // Output Quality scorers
77
+ {
78
+ id: "tone-consistency",
79
+ name: "Tone Consistency",
80
+ description: "Measures consistency in formality, complexity, and style",
81
+ category: "output-quality",
82
+ filename: "tone-consistency-scorer.ts"
83
+ },
84
+ {
85
+ id: "toxicity-detection",
86
+ name: "Toxicity Detection",
87
+ description: "Detects harmful or inappropriate content in responses",
88
+ category: "output-quality",
89
+ filename: "toxicity-detection-scorer.ts"
90
+ },
91
+ {
92
+ id: "bias-detection",
93
+ name: "Bias Detection",
94
+ description: "Detects potential biases in output",
95
+ category: "output-quality",
96
+ filename: "bias-detection-scorer.ts"
97
+ },
98
+ {
99
+ id: "keyword-coverage",
100
+ name: "Keyword Coverage",
101
+ description: "Assesses how well output covers important keywords from input",
102
+ category: "output-quality",
103
+ filename: "keyword-coverage-scorer.ts"
104
+ }
105
+ ];
106
+ var DEFAULT_SCORERS_DIR = "src/mastra/scorers";
107
+ function writeScorer(filename, content, customPath) {
108
+ const rootDir = process.cwd();
109
+ const scorersPath = customPath || DEFAULT_SCORERS_DIR;
110
+ const fullPath = path.join(rootDir, scorersPath);
111
+ if (!fs.existsSync(fullPath)) {
112
+ try {
113
+ fs.mkdirSync(fullPath, { recursive: true });
114
+ p2.log.success(`Created scorers directory at ${scorersPath}`);
115
+ } catch (error) {
116
+ const errorMessage = error instanceof Error ? error.message : String(error);
117
+ throw new Error(`Failed to create directory: ${errorMessage}`);
118
+ }
119
+ }
120
+ const filePath = path.join(fullPath, filename);
121
+ if (fs.existsSync(filePath)) {
122
+ throw new Error(`Skipped: Scorer ${filename} already exists at ${scorersPath}`);
123
+ }
124
+ try {
125
+ fs.writeFileSync(filePath, content);
126
+ return { ok: true, message: `Created scorer at ${path.relative(rootDir, filePath)}` };
127
+ } catch (error) {
128
+ const errorMessage = error instanceof Error ? error.message : String(error);
129
+ throw new Error(`Failed to write scorer: ${errorMessage}`);
130
+ }
131
+ }
132
+
133
+ // import("../../templates/scorers/**/*") in src/commands/scorers/add-new-scorer.ts
134
+ var globImport_templates_scorers = __glob({
135
+ "../../templates/scorers/answer-relevancy-scorer.ts": () => import('./answer-relevancy-scorer-CTIL35GQ.js'),
136
+ "../../templates/scorers/bias-detection-scorer.ts": () => import('./bias-detection-scorer-IWHTLHDC.js'),
137
+ "../../templates/scorers/completeness-scorer.ts": () => import('./completeness-scorer-KH4LU4BW.js'),
138
+ "../../templates/scorers/content-similarity-scorer.ts": () => import('./content-similarity-scorer-NB76ISB5.js'),
139
+ "../../templates/scorers/faithfulness-scorer.ts": () => import('./faithfulness-scorer-F6GLSRTV.js'),
140
+ "../../templates/scorers/hallucination-scorer.ts": () => import('./hallucination-scorer-NJW7PTKD.js'),
141
+ "../../templates/scorers/keyword-coverage-scorer.ts": () => import('./keyword-coverage-scorer-63AEWDTL.js'),
142
+ "../../templates/scorers/textual-difference-scorer.ts": () => import('./textual-difference-scorer-2MUWQ22U.js'),
143
+ "../../templates/scorers/tone-consistency-scorer.ts": () => import('./tone-consistency-scorer-ZEXVRFCP.js'),
144
+ "../../templates/scorers/toxicity-detection-scorer.ts": () => import('./toxicity-detection-scorer-RMTLQCHI.js')
145
+ });
146
+
147
+ // src/commands/scorers/add-new-scorer.ts
148
+ async function selectScorer() {
149
+ const options = [];
150
+ for (const scorer of AVAILABLE_SCORERS) {
151
+ options.push({
152
+ value: scorer.id,
153
+ label: `${scorer.name}`,
154
+ hint: `${scorer.description}`
155
+ });
156
+ }
157
+ const selectedIds = await p2.multiselect({
158
+ message: "Choose a scorer to add:",
159
+ options
160
+ });
161
+ if (p2.isCancel(selectedIds) || typeof selectedIds !== "object") {
162
+ p2.log.info("Scorer selection cancelled.");
163
+ return null;
164
+ }
165
+ if (!Array.isArray(selectedIds)) {
166
+ return null;
167
+ }
168
+ const selectedScorers = selectedIds.map((scorerId) => {
169
+ const foundScorer = AVAILABLE_SCORERS.find((s) => s.id === scorerId);
170
+ return foundScorer;
171
+ }).filter((item) => item != void 0);
172
+ return selectedScorers;
173
+ }
174
+ async function addNewScorer(scorerId, customDir) {
175
+ const depService = new DepsService();
176
+ const needsEvals = await depService.checkDependencies(["@mastra/evals"]) !== `ok`;
177
+ if (needsEvals) {
178
+ await depService.installPackages(["@mastra/evals"]);
179
+ }
180
+ if (!scorerId) {
181
+ await showInteractivePrompt(customDir);
182
+ return;
183
+ }
184
+ const foundScorer = AVAILABLE_SCORERS.find((scorer) => scorer.id === scorerId.toLowerCase());
185
+ if (!foundScorer) {
186
+ p2.log.error(`Scorer for ${scorerId} not available`);
187
+ return;
188
+ }
189
+ const { id, filename } = foundScorer;
190
+ try {
191
+ const res = await initializeScorer(id, filename, customDir);
192
+ if (!res.ok) {
193
+ return;
194
+ }
195
+ p2.log.success(res.message);
196
+ showSuccessNote();
197
+ } catch (error) {
198
+ const errorMessage = error instanceof Error ? error.message : String(error);
199
+ if (errorMessage.includes("Skipped")) {
200
+ return p2.log.warning(errorMessage);
201
+ }
202
+ p2.log.error(errorMessage);
203
+ }
204
+ }
205
+ async function initializeScorer(scorerId, filename, customPath) {
206
+ try {
207
+ const templateModule = await globImport_templates_scorers(`../../templates/scorers/${filename}`);
208
+ const key = `${toCamelCase(scorerId)}Scorer`;
209
+ const templateContent = templateModule[key];
210
+ const res = writeScorer(filename, templateContent, customPath);
211
+ return res;
212
+ } catch (error) {
213
+ throw error;
214
+ }
215
+ }
216
+ function showSuccessNote() {
217
+ p2.note(`
218
+ ${color.green("To use: Add the Scorer to your workflow or agent!")}
219
+ `);
220
+ }
221
+ async function showInteractivePrompt(providedCustomDir) {
222
+ let selectedScorers = await selectScorer();
223
+ if (!selectedScorers) {
224
+ return;
225
+ }
226
+ let customPath = providedCustomDir;
227
+ if (!providedCustomDir) {
228
+ const useCustomDir = await p2.confirm({
229
+ message: `Would you like to use a custom directory?${color.gray("(Default: src/mastra/scorers)")}`,
230
+ initialValue: false
231
+ });
232
+ if (p2.isCancel(useCustomDir)) {
233
+ p2.log.info("Operation cancelled.");
234
+ return;
235
+ }
236
+ if (useCustomDir) {
237
+ const dirPath = await p2.text({
238
+ message: "Enter the directory path (relative to project root):",
239
+ placeholder: "src/scorers"
240
+ });
241
+ if (p2.isCancel(dirPath)) {
242
+ p2.log.info("Operation cancelled.");
243
+ return;
244
+ }
245
+ customPath = dirPath;
246
+ }
247
+ }
248
+ const result = await Promise.allSettled(
249
+ selectedScorers.map((scorer) => {
250
+ const { id, filename } = scorer;
251
+ return initializeScorer(id, filename, customPath);
252
+ })
253
+ );
254
+ result.forEach((op) => {
255
+ if (op.status === "fulfilled") {
256
+ p2.log.success(op.value.message);
257
+ return;
258
+ }
259
+ const errorMessage = String(op.reason);
260
+ const coreError = errorMessage.replace("Error:", "").trim();
261
+ if (coreError.includes("Skipped")) {
262
+ return p2.log.warning(coreError);
263
+ }
264
+ p2.log.error(coreError);
265
+ });
266
+ const containsSuccessfulWrites = result.some((item) => item.status === "fulfilled");
267
+ if (containsSuccessfulWrites) {
268
+ showSuccessNote();
269
+ }
270
+ return;
271
+ }
272
+
273
+ // src/commands/actions/add-scorer.ts
274
+ var origin = process.env.MASTRA_ANALYTICS_ORIGIN;
275
+ var addScorer = async (scorerName, args) => {
276
+ await analytics.trackCommandExecution({
277
+ command: "scorers-add",
278
+ args: { ...args, scorerName },
279
+ execution: async () => {
280
+ await addNewScorer(scorerName, args.dir);
281
+ },
282
+ origin
283
+ });
284
+ };
23
285
  var BuildBundler = class extends Bundler {
24
286
  customEnvFile;
25
287
  constructor(customEnvFile) {
@@ -123,8 +385,8 @@ async function build({
123
385
  const defaultTools = [defaultToolsPath, ...defaultToolsIgnorePaths];
124
386
  const discoveredTools = [defaultTools, ...tools ?? []];
125
387
  try {
126
- const fs2 = new FileService();
127
- const mastraEntryFile = fs2.getFirstExistingFile([join(mastraDir, "index.ts"), join(mastraDir, "index.js")]);
388
+ const fs3 = new FileService();
389
+ const mastraEntryFile = fs3.getFirstExistingFile([join(mastraDir, "index.ts"), join(mastraDir, "index.js")]);
128
390
  const platformDeployer = await getDeployer(mastraEntryFile, outputDirectory);
129
391
  if (!platformDeployer) {
130
392
  const deployer = new BuildBundler(env);
@@ -149,12 +411,65 @@ async function build({
149
411
  process.exit(1);
150
412
  }
151
413
  }
414
+
415
+ // src/commands/actions/build-project.ts
416
+ var buildProject = async (args) => {
417
+ await analytics.trackCommandExecution({
418
+ command: "mastra build",
419
+ args,
420
+ execution: async () => {
421
+ await build({
422
+ dir: args?.dir,
423
+ root: args?.root,
424
+ tools: args?.tools ? args.tools.split(",") : [],
425
+ env: args?.env
426
+ });
427
+ },
428
+ origin: origin2
429
+ });
430
+ };
431
+
432
+ // src/commands/actions/create-project.ts
433
+ var origin3 = process.env.MASTRA_ANALYTICS_ORIGIN;
434
+ var createProject = async (projectNameArg, args) => {
435
+ const projectName = projectNameArg || args.projectName;
436
+ await analytics.trackCommandExecution({
437
+ command: "create",
438
+ args: { ...args, projectName },
439
+ execution: async () => {
440
+ const timeout = args?.timeout ? args?.timeout === true ? 6e4 : parseInt(args?.timeout, 10) : void 0;
441
+ if (args.default) {
442
+ await create({
443
+ components: ["agents", "tools", "workflows"],
444
+ llmProvider: "openai",
445
+ addExample: true,
446
+ timeout,
447
+ mcpServer: args.mcp,
448
+ template: args.template
449
+ });
450
+ return;
451
+ }
452
+ await create({
453
+ components: args.components ? args.components.split(",") : [],
454
+ llmProvider: args.llm,
455
+ addExample: args.example,
456
+ llmApiKey: args["llm-api-key"],
457
+ timeout,
458
+ projectName,
459
+ directory: args.dir,
460
+ mcpServer: args.mcp,
461
+ template: args.template
462
+ });
463
+ },
464
+ origin: origin3
465
+ });
466
+ };
152
467
  async function deploy({ dir: dir2 }) {
153
468
  let mastraDir = dir2 || join(process.cwd(), "src/mastra");
154
469
  try {
155
470
  const outputDirectory = join(process.cwd(), ".mastra");
156
- const fs2 = new FileService();
157
- const mastraEntryFile = fs2.getFirstExistingFile([join(mastraDir, "index.ts"), join(mastraDir, "index.js")]);
471
+ const fs3 = new FileService();
472
+ const mastraEntryFile = fs3.getFirstExistingFile([join(mastraDir, "index.ts"), join(mastraDir, "index.js")]);
158
473
  const deployer = await getDeployer(mastraEntryFile, outputDirectory);
159
474
  if (!deployer) {
160
475
  logger.warn("No deployer found.");
@@ -180,56 +495,337 @@ async function deploy({ dir: dir2 }) {
180
495
  logger.warn("No deployer found.");
181
496
  }
182
497
  }
183
- var DevBundler = class extends Bundler {
184
- customEnvFile;
185
- constructor(customEnvFile) {
186
- super("Dev");
187
- this.customEnvFile = customEnvFile;
188
- }
189
- getEnvFiles() {
190
- const possibleFiles = [".env.development", ".env.local", ".env"];
191
- if (this.customEnvFile) {
192
- possibleFiles.unshift(this.customEnvFile);
498
+
499
+ // src/commands/actions/deploy-project.ts
500
+ var deployProject = async (args) => {
501
+ config({ path: [".env", ".env.production"] });
502
+ await analytics.trackCommandExecution({
503
+ command: "mastra deploy",
504
+ args,
505
+ execution: async () => {
506
+ logger.warn(`DEPRECATED: The deploy command is deprecated.
507
+ Please use the mastra build command instead.
508
+ Then deploy .mastra/output to your target platform.
509
+ `);
510
+ await deploy({ dir: args.dir });
511
+ },
512
+ origin: origin2
513
+ });
514
+ };
515
+
516
+ // src/commands/actions/init-project.ts
517
+ var origin4 = process.env.MASTRA_ANALYTICS_ORIGIN;
518
+ var initProject = async (args) => {
519
+ await analytics.trackCommandExecution({
520
+ command: "init",
521
+ args,
522
+ execution: async () => {
523
+ await checkPkgJson();
524
+ await checkAndInstallCoreDeps(args?.example || args?.default);
525
+ if (!Object.keys(args).length) {
526
+ const result = await interactivePrompt();
527
+ await init({
528
+ ...result,
529
+ llmApiKey: result?.llmApiKey,
530
+ components: ["agents", "tools", "workflows"],
531
+ addExample: true
532
+ });
533
+ return;
534
+ }
535
+ if (args?.default) {
536
+ await init({
537
+ directory: "src/",
538
+ components: ["agents", "tools", "workflows"],
539
+ llmProvider: "openai",
540
+ addExample: true,
541
+ configureEditorWithDocsMCP: args.mcp
542
+ });
543
+ return;
544
+ }
545
+ const componentsArr = args.components ? args.components.split(",") : [];
546
+ await init({
547
+ directory: args.dir,
548
+ components: componentsArr,
549
+ llmProvider: args.llm,
550
+ addExample: args.example,
551
+ llmApiKey: args["llm-api-key"],
552
+ configureEditorWithDocsMCP: args.mcp
553
+ });
554
+ return;
555
+ },
556
+ origin: origin4
557
+ });
558
+ };
559
+
560
+ // src/commands/lint/rules/mastraCoreRule.ts
561
+ var mastraCoreRule = {
562
+ name: "mastra-core",
563
+ description: "Checks if @mastra/core is installed",
564
+ async run(context) {
565
+ const hasCore = context.mastraPackages.some((pkg) => pkg.name === "@mastra/core");
566
+ if (!hasCore) {
567
+ logger.error("@mastra/core is not installed. This package is required for Mastra to work properly.");
568
+ return false;
193
569
  }
194
- try {
195
- const fileService = new FileService$1();
196
- const envFile = fileService.getFirstExistingFile(possibleFiles);
197
- return Promise.resolve([envFile]);
198
- } catch {
570
+ return true;
571
+ }
572
+ };
573
+ function readNextConfig(dir) {
574
+ const nextConfigPath = join(dir, "next.config.js");
575
+ try {
576
+ const nextConfigContent = readFileSync(nextConfigPath, "utf-8");
577
+ const configMatch = nextConfigContent.match(/const nextConfig = ({[\s\S]*?});/);
578
+ if (!configMatch?.[1]) {
579
+ return null;
199
580
  }
200
- return Promise.resolve([]);
581
+ const configStr = configMatch[1].replace(/\n/g, "").replace(/\s+/g, " ");
582
+ return eval(`(${configStr})`);
583
+ } catch {
584
+ return null;
201
585
  }
202
- async prepare(outputDirectory) {
203
- await super.prepare(outputDirectory);
204
- const __filename = fileURLToPath(import.meta.url);
205
- const __dirname = dirname(__filename);
206
- const playgroundServePath = join(outputDirectory, this.outputDir, "playground");
207
- await fsExtra.copy(join(dirname(__dirname), "src/playground/dist"), playgroundServePath, {
208
- overwrite: true
209
- });
586
+ }
587
+ function isNextJsProject(dir2) {
588
+ const nextConfigPath2 = join(dir2, "next.config.js");
589
+ try {
590
+ readFileSync(nextConfigPath2, "utf-8");
591
+ return true;
592
+ } catch {
593
+ return false;
210
594
  }
211
- async watch(entryFile, outputDirectory, toolsPaths) {
212
- const __filename = fileURLToPath(import.meta.url);
213
- const __dirname = dirname(__filename);
214
- const envFiles = await this.getEnvFiles();
215
- let sourcemapEnabled = false;
216
- let transpilePackages = [];
217
- try {
218
- const bundlerOptions = await getBundlerOptions(entryFile, outputDirectory);
219
- sourcemapEnabled = !!bundlerOptions?.sourcemap;
220
- transpilePackages = bundlerOptions?.transpilePackages ?? [];
221
- } catch (error) {
222
- this.logger.debug("Failed to get bundler options, sourcemap will be disabled", { error });
595
+ }
596
+ var nextConfigRule = {
597
+ name: "next-config",
598
+ description: "Checks if Next.js config is properly configured for Mastra packages",
599
+ async run(context) {
600
+ if (!isNextJsProject(context.rootDir)) {
601
+ return true;
223
602
  }
224
- const inputOptions = await getWatcherInputOptions(
225
- entryFile,
226
- "node",
227
- {
228
- "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV || "development")
229
- },
230
- { sourcemap: sourcemapEnabled, transpilePackages }
231
- );
232
- const toolsInputOptions = await this.getToolsInputOptions(toolsPaths);
603
+ const nextConfig = readNextConfig(context.rootDir);
604
+ if (!nextConfig) {
605
+ return false;
606
+ }
607
+ const serverExternals = nextConfig.serverExternalPackages || [];
608
+ const hasMastraExternals = serverExternals.some(
609
+ (pkg) => pkg === "@mastra/*" || pkg === "@mastra/core" || pkg.startsWith("@mastra/")
610
+ );
611
+ if (!hasMastraExternals) {
612
+ logger.error("next.config.js is missing Mastra packages in serverExternalPackages");
613
+ logger.error("Please add the following to your next.config.js:");
614
+ logger.error(' serverExternalPackages: ["@mastra/*"],');
615
+ return false;
616
+ }
617
+ logger.info("Next.js config is properly configured for Mastra packages");
618
+ return true;
619
+ }
620
+ };
621
+ function readTsConfig(dir2) {
622
+ const tsConfigPath = join(dir2, "tsconfig.json");
623
+ try {
624
+ const tsConfigContent = readFileSync(tsConfigPath, "utf-8");
625
+ const cleanTsConfigContent = stripJsonComments(tsConfigContent);
626
+ return JSON.parse(cleanTsConfigContent);
627
+ } catch {
628
+ return null;
629
+ }
630
+ }
631
+ var tsConfigRule = {
632
+ name: "ts-config",
633
+ description: "Checks if TypeScript config is properly configured for Mastra packages",
634
+ async run(context) {
635
+ const tsConfig = readTsConfig(context.rootDir);
636
+ if (!tsConfig) {
637
+ logger.warn("No tsconfig.json found. This might cause issues with Mastra packages.");
638
+ return true;
639
+ }
640
+ const { module, moduleResolution } = tsConfig.compilerOptions || {};
641
+ const isValidConfig = moduleResolution === "bundler" || module === "CommonJS";
642
+ if (!isValidConfig) {
643
+ logger.error("tsconfig.json has invalid configuration");
644
+ logger.error("Please set either:");
645
+ logger.error(' "compilerOptions": {');
646
+ logger.error(' "moduleResolution": "bundler"');
647
+ logger.error(" }");
648
+ logger.error("or");
649
+ logger.error(' "compilerOptions": {');
650
+ logger.error(' "module": "CommonJS"');
651
+ logger.error(" }");
652
+ logger.error("For the recommended TypeScript configuration, see:");
653
+ logger.error("https://mastra.ai/en/docs/getting-started/installation#initialize-typescript");
654
+ return false;
655
+ }
656
+ logger.info("TypeScript config is properly configured for Mastra packages");
657
+ return true;
658
+ }
659
+ };
660
+
661
+ // src/commands/lint/rules/index.ts
662
+ var rules = [nextConfigRule, tsConfigRule, mastraCoreRule];
663
+
664
+ // src/commands/lint/index.ts
665
+ function readPackageJson(dir2) {
666
+ const packageJsonPath = join(dir2, "package.json");
667
+ try {
668
+ const packageJsonContent = readFileSync(packageJsonPath, "utf-8");
669
+ return JSON.parse(packageJsonContent);
670
+ } catch (error) {
671
+ if (error instanceof Error) {
672
+ logger.error(`Failed to read package.json: ${error.message}`);
673
+ }
674
+ throw error;
675
+ }
676
+ }
677
+ function getMastraPackages(packageJson) {
678
+ const allDependencies = {
679
+ ...packageJson.dependencies,
680
+ ...packageJson.devDependencies
681
+ };
682
+ const mastraPackages = Object.entries(allDependencies).filter(
683
+ ([name]) => name.startsWith("@mastra/") || name === "mastra"
684
+ );
685
+ return mastraPackages.map(([name, version2]) => ({
686
+ name,
687
+ version: version2,
688
+ isAlpha: version2.includes("alpha")
689
+ }));
690
+ }
691
+ async function lint({ dir: dir2, root, tools }) {
692
+ try {
693
+ const rootDir = root || process.cwd();
694
+ const mastraDir = dir2 ? dir2.startsWith("/") ? dir2 : join(process.cwd(), dir2) : join(process.cwd(), "src", "mastra");
695
+ const outputDirectory = join(rootDir, ".mastra");
696
+ const defaultToolsPath = join(mastraDir, "tools");
697
+ const discoveredTools = [defaultToolsPath, ...tools ?? []];
698
+ const packageJson = readPackageJson(rootDir);
699
+ const mastraPackages = getMastraPackages(packageJson);
700
+ const context = {
701
+ rootDir,
702
+ mastraDir,
703
+ outputDirectory,
704
+ discoveredTools,
705
+ packageJson,
706
+ mastraPackages
707
+ };
708
+ const results = await Promise.all(rules.map((rule) => rule.run(context)));
709
+ const allRulesPassed = results.every((result) => result);
710
+ if (allRulesPassed) {
711
+ const fileService = new FileService();
712
+ const mastraEntryFile = fileService.getFirstExistingFile([
713
+ join(mastraDir, "index.ts"),
714
+ join(mastraDir, "index.js")
715
+ ]);
716
+ const platformDeployer = await getDeployer(mastraEntryFile, outputDirectory);
717
+ if (!platformDeployer) {
718
+ const deployer = new BuildBundler();
719
+ await deployer.lint(mastraEntryFile, outputDirectory, discoveredTools);
720
+ } else {
721
+ await platformDeployer.lint(mastraEntryFile, outputDirectory, discoveredTools);
722
+ }
723
+ }
724
+ return allRulesPassed;
725
+ } catch (error) {
726
+ if (error instanceof Error) {
727
+ logger.error(`Lint check failed: ${error.message}`);
728
+ }
729
+ return false;
730
+ }
731
+ }
732
+
733
+ // src/commands/actions/lint-project.ts
734
+ var lintProject = async (args) => {
735
+ await analytics.trackCommandExecution({
736
+ command: "lint",
737
+ args,
738
+ execution: async () => {
739
+ await lint({ dir: args.dir, root: args.root, tools: args.tools ? args.tools.split(",") : [] });
740
+ },
741
+ origin: origin2
742
+ });
743
+ };
744
+ function listAllScorers() {
745
+ p2.intro(color.inverse(" Available Scorers "));
746
+ const groupedScorers = AVAILABLE_SCORERS.reduce(
747
+ (acc, scorer) => {
748
+ if (!acc[scorer.category]) {
749
+ acc[scorer.category] = [];
750
+ }
751
+ acc[scorer.category].push(scorer);
752
+ return acc;
753
+ },
754
+ {}
755
+ );
756
+ for (const [category, scorers] of Object.entries(groupedScorers)) {
757
+ const categoryLabel = category === "accuracy-and-reliability" ? "Accuracy and Reliability" : "Output Quality";
758
+ p2.log.info(`${color.bold(color.cyan(categoryLabel))} Scorers:`);
759
+ for (const scorer of scorers) {
760
+ p2.log.message(` ${color.bold(scorer.name)} ${color.dim(`(${scorer.id})`)}
761
+ ${color.dim(scorer.description)}
762
+ `);
763
+ }
764
+ }
765
+ }
766
+
767
+ // src/commands/actions/list-scorers.ts
768
+ var origin5 = process.env.MASTRA_ANALYTICS_ORIGIN;
769
+ var listScorers = async (args) => {
770
+ await analytics.trackCommandExecution({
771
+ command: "scorers-list",
772
+ args,
773
+ execution: async () => {
774
+ await listAllScorers();
775
+ },
776
+ origin: origin5
777
+ });
778
+ };
779
+ var DevBundler = class extends Bundler {
780
+ customEnvFile;
781
+ constructor(customEnvFile) {
782
+ super("Dev");
783
+ this.customEnvFile = customEnvFile;
784
+ }
785
+ getEnvFiles() {
786
+ const possibleFiles = [".env.development", ".env.local", ".env"];
787
+ if (this.customEnvFile) {
788
+ possibleFiles.unshift(this.customEnvFile);
789
+ }
790
+ try {
791
+ const fileService = new FileService$1();
792
+ const envFile = fileService.getFirstExistingFile(possibleFiles);
793
+ return Promise.resolve([envFile]);
794
+ } catch {
795
+ }
796
+ return Promise.resolve([]);
797
+ }
798
+ async prepare(outputDirectory) {
799
+ await super.prepare(outputDirectory);
800
+ const __filename = fileURLToPath(import.meta.url);
801
+ const __dirname = dirname(__filename);
802
+ const playgroundServePath = join(outputDirectory, this.outputDir, "playground");
803
+ await fsExtra.copy(join(dirname(__dirname), "src/playground/dist"), playgroundServePath, {
804
+ overwrite: true
805
+ });
806
+ }
807
+ async watch(entryFile, outputDirectory, toolsPaths) {
808
+ const __filename = fileURLToPath(import.meta.url);
809
+ const __dirname = dirname(__filename);
810
+ const envFiles = await this.getEnvFiles();
811
+ let sourcemapEnabled = false;
812
+ let transpilePackages = [];
813
+ try {
814
+ const bundlerOptions = await getBundlerOptions(entryFile, outputDirectory);
815
+ sourcemapEnabled = !!bundlerOptions?.sourcemap;
816
+ transpilePackages = bundlerOptions?.transpilePackages ?? [];
817
+ } catch (error) {
818
+ this.logger.debug("Failed to get bundler options, sourcemap will be disabled", { error });
819
+ }
820
+ const inputOptions = await getWatcherInputOptions(
821
+ entryFile,
822
+ "node",
823
+ {
824
+ "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV || "development")
825
+ },
826
+ { sourcemap: sourcemapEnabled, transpilePackages }
827
+ );
828
+ const toolsInputOptions = await this.getToolsInputOptions(toolsPaths);
233
829
  const outputDir = join(outputDirectory, this.outputDir);
234
830
  await writeTelemetryConfig({
235
831
  entryFile,
@@ -501,185 +1097,35 @@ async function dev({
501
1097
  });
502
1098
  }
503
1099
 
504
- // src/commands/lint/rules/mastraCoreRule.ts
505
- var mastraCoreRule = {
506
- name: "mastra-core",
507
- description: "Checks if @mastra/core is installed",
508
- async run(context) {
509
- const hasCore = context.mastraPackages.some((pkg) => pkg.name === "@mastra/core");
510
- if (!hasCore) {
511
- logger.error("@mastra/core is not installed. This package is required for Mastra to work properly.");
512
- return false;
513
- }
514
- return true;
1100
+ // src/commands/actions/start-dev-server.ts
1101
+ var startDevServer = async (args) => {
1102
+ analytics.trackCommand({
1103
+ command: "dev",
1104
+ origin: origin2
1105
+ });
1106
+ if (args?.port) {
1107
+ logger.warn("The --port option is deprecated. Use the server key in the Mastra instance instead.");
515
1108
  }
1109
+ dev({
1110
+ port: args?.port ? parseInt(args.port) : null,
1111
+ dir: args?.dir,
1112
+ root: args?.root,
1113
+ tools: args?.tools ? args.tools.split(",") : [],
1114
+ env: args?.env,
1115
+ inspect: args?.inspect && !args?.inspectBrk,
1116
+ inspectBrk: args?.inspectBrk,
1117
+ customArgs: args?.customArgs ? args.customArgs.split(",") : []
1118
+ }).catch((err) => {
1119
+ logger.error(err.message);
1120
+ });
516
1121
  };
517
- function readNextConfig(dir) {
518
- const nextConfigPath = join(dir, "next.config.js");
1122
+ async function start(options = {}) {
1123
+ const outputDir = options.dir || ".mastra/output";
1124
+ const telemetry = options.telemetry ?? true;
519
1125
  try {
520
- const nextConfigContent = readFileSync(nextConfigPath, "utf-8");
521
- const configMatch = nextConfigContent.match(/const nextConfig = ({[\s\S]*?});/);
522
- if (!configMatch?.[1]) {
523
- return null;
524
- }
525
- const configStr = configMatch[1].replace(/\n/g, "").replace(/\s+/g, " ");
526
- return eval(`(${configStr})`);
527
- } catch {
528
- return null;
529
- }
530
- }
531
- function isNextJsProject(dir2) {
532
- const nextConfigPath2 = join(dir2, "next.config.js");
533
- try {
534
- readFileSync(nextConfigPath2, "utf-8");
535
- return true;
536
- } catch {
537
- return false;
538
- }
539
- }
540
- var nextConfigRule = {
541
- name: "next-config",
542
- description: "Checks if Next.js config is properly configured for Mastra packages",
543
- async run(context) {
544
- if (!isNextJsProject(context.rootDir)) {
545
- return true;
546
- }
547
- const nextConfig = readNextConfig(context.rootDir);
548
- if (!nextConfig) {
549
- return false;
550
- }
551
- const serverExternals = nextConfig.serverExternalPackages || [];
552
- const hasMastraExternals = serverExternals.some(
553
- (pkg) => pkg === "@mastra/*" || pkg === "@mastra/core" || pkg.startsWith("@mastra/")
554
- );
555
- if (!hasMastraExternals) {
556
- logger.error("next.config.js is missing Mastra packages in serverExternalPackages");
557
- logger.error("Please add the following to your next.config.js:");
558
- logger.error(' serverExternalPackages: ["@mastra/*"],');
559
- return false;
560
- }
561
- logger.info("Next.js config is properly configured for Mastra packages");
562
- return true;
563
- }
564
- };
565
- function readTsConfig(dir2) {
566
- const tsConfigPath = join(dir2, "tsconfig.json");
567
- try {
568
- const tsConfigContent = readFileSync(tsConfigPath, "utf-8");
569
- const cleanTsConfigContent = stripJsonComments(tsConfigContent);
570
- return JSON.parse(cleanTsConfigContent);
571
- } catch {
572
- return null;
573
- }
574
- }
575
- var tsConfigRule = {
576
- name: "ts-config",
577
- description: "Checks if TypeScript config is properly configured for Mastra packages",
578
- async run(context) {
579
- const tsConfig = readTsConfig(context.rootDir);
580
- if (!tsConfig) {
581
- logger.warn("No tsconfig.json found. This might cause issues with Mastra packages.");
582
- return true;
583
- }
584
- const { module, moduleResolution } = tsConfig.compilerOptions || {};
585
- const isValidConfig = moduleResolution === "bundler" || module === "CommonJS";
586
- if (!isValidConfig) {
587
- logger.error("tsconfig.json has invalid configuration");
588
- logger.error("Please set either:");
589
- logger.error(' "compilerOptions": {');
590
- logger.error(' "moduleResolution": "bundler"');
591
- logger.error(" }");
592
- logger.error("or");
593
- logger.error(' "compilerOptions": {');
594
- logger.error(' "module": "CommonJS"');
595
- logger.error(" }");
596
- logger.error("For the recommended TypeScript configuration, see:");
597
- logger.error("https://mastra.ai/en/docs/getting-started/installation#initialize-typescript");
598
- return false;
599
- }
600
- logger.info("TypeScript config is properly configured for Mastra packages");
601
- return true;
602
- }
603
- };
604
-
605
- // src/commands/lint/rules/index.ts
606
- var rules = [nextConfigRule, tsConfigRule, mastraCoreRule];
607
-
608
- // src/commands/lint/index.ts
609
- function readPackageJson(dir2) {
610
- const packageJsonPath = join(dir2, "package.json");
611
- try {
612
- const packageJsonContent = readFileSync(packageJsonPath, "utf-8");
613
- return JSON.parse(packageJsonContent);
614
- } catch (error) {
615
- if (error instanceof Error) {
616
- logger.error(`Failed to read package.json: ${error.message}`);
617
- }
618
- throw error;
619
- }
620
- }
621
- function getMastraPackages(packageJson) {
622
- const allDependencies = {
623
- ...packageJson.dependencies,
624
- ...packageJson.devDependencies
625
- };
626
- const mastraPackages = Object.entries(allDependencies).filter(
627
- ([name]) => name.startsWith("@mastra/") || name === "mastra"
628
- );
629
- return mastraPackages.map(([name, version2]) => ({
630
- name,
631
- version: version2,
632
- isAlpha: version2.includes("alpha")
633
- }));
634
- }
635
- async function lint({ dir: dir2, root, tools }) {
636
- try {
637
- const rootDir = root || process.cwd();
638
- const mastraDir = dir2 ? dir2.startsWith("/") ? dir2 : join(process.cwd(), dir2) : join(process.cwd(), "src", "mastra");
639
- const outputDirectory = join(rootDir, ".mastra");
640
- const defaultToolsPath = join(mastraDir, "tools");
641
- const discoveredTools = [defaultToolsPath, ...tools ?? []];
642
- const packageJson = readPackageJson(rootDir);
643
- const mastraPackages = getMastraPackages(packageJson);
644
- const context = {
645
- rootDir,
646
- mastraDir,
647
- outputDirectory,
648
- discoveredTools,
649
- packageJson,
650
- mastraPackages
651
- };
652
- const results = await Promise.all(rules.map((rule) => rule.run(context)));
653
- const allRulesPassed = results.every((result) => result);
654
- if (allRulesPassed) {
655
- const fileService = new FileService();
656
- const mastraEntryFile = fileService.getFirstExistingFile([
657
- join(mastraDir, "index.ts"),
658
- join(mastraDir, "index.js")
659
- ]);
660
- const platformDeployer = await getDeployer(mastraEntryFile, outputDirectory);
661
- if (!platformDeployer) {
662
- const deployer = new BuildBundler();
663
- await deployer.lint(mastraEntryFile, outputDirectory, discoveredTools);
664
- } else {
665
- await platformDeployer.lint(mastraEntryFile, outputDirectory, discoveredTools);
666
- }
667
- }
668
- return allRulesPassed;
669
- } catch (error) {
670
- if (error instanceof Error) {
671
- logger.error(`Lint check failed: ${error.message}`);
672
- }
673
- return false;
674
- }
675
- }
676
- async function start(options = {}) {
677
- const outputDir = options.dir || ".mastra/output";
678
- const telemetry = options.telemetry ?? true;
679
- try {
680
- const outputPath = join(process.cwd(), outputDir);
681
- if (!fs.existsSync(outputPath)) {
682
- throw new Error(`Output directory ${outputPath} does not exist`);
1126
+ const outputPath = join(process.cwd(), outputDir);
1127
+ if (!fs.existsSync(outputPath)) {
1128
+ throw new Error(`Output directory ${outputPath} does not exist`);
683
1129
  }
684
1130
  const commands = [];
685
1131
  if (telemetry && !isWebContainer()) {
@@ -713,6 +1159,21 @@ async function start(options = {}) {
713
1159
  }
714
1160
  }
715
1161
 
1162
+ // src/commands/actions/start-project.ts
1163
+ var startProject = async (args) => {
1164
+ await analytics.trackCommandExecution({
1165
+ command: "start",
1166
+ args,
1167
+ execution: async () => {
1168
+ await start({
1169
+ dir: args.dir,
1170
+ telemetry: !args.noTelemetry
1171
+ });
1172
+ },
1173
+ origin: origin2
1174
+ });
1175
+ };
1176
+
716
1177
  // src/index.ts
717
1178
  var depsService = new DepsService();
718
1179
  var version = await depsService.getPackageVersion();
@@ -723,16 +1184,14 @@ var analytics = new PosthogAnalytics({
723
1184
  });
724
1185
  setAnalytics(analytics);
725
1186
  var program = new Command();
726
- var origin = process.env.MASTRA_ANALYTICS_ORIGIN;
727
- program.version(`${version}`, "-v, --version").description(`Mastra CLI ${version}`).action(() => {
728
- try {
729
- analytics.trackCommand({
730
- command: "version",
731
- origin
732
- });
733
- console.log(`Mastra CLI: ${version}`);
734
- } catch {
735
- }
1187
+ var origin2 = process.env.MASTRA_ANALYTICS_ORIGIN;
1188
+ program.name("mastra").version(`${version}`, "-v, --version").addHelpText(
1189
+ "before",
1190
+ `
1191
+ ${color.bold(color.cyan("Mastra"))} is a typescript framework for building AI applications, agents, and workflows.
1192
+ `
1193
+ ).action(() => {
1194
+ program.help();
736
1195
  });
737
1196
  program.command("create [project-name]").description("Create a new Mastra project").option("--default", "Quick start with defaults(src, OpenAI, 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(
738
1197
  "-p, --project-name <string>",
@@ -740,157 +1199,21 @@ program.command("create [project-name]").description("Create a new Mastra projec
740
1199
  ).option("-m, --mcp <editor>", "MCP Server for code editor (cursor, cursor-global, windsurf, vscode)").option(
741
1200
  "--template [template-name]",
742
1201
  "Create project from a template (use template name, public GitHub URL, or leave blank to select from list)"
743
- ).action(async (projectNameArg, args) => {
744
- const projectName = projectNameArg || args.projectName;
745
- await analytics.trackCommandExecution({
746
- command: "create",
747
- args: { ...args, projectName },
748
- execution: async () => {
749
- const timeout = args?.timeout ? args?.timeout === true ? 6e4 : parseInt(args?.timeout, 10) : void 0;
750
- if (args.default) {
751
- await create({
752
- components: ["agents", "tools", "workflows"],
753
- llmProvider: "openai",
754
- addExample: true,
755
- timeout,
756
- mcpServer: args.mcp,
757
- template: args.template
758
- });
759
- return;
760
- }
761
- await create({
762
- components: args.components ? args.components.split(",") : [],
763
- llmProvider: args.llm,
764
- addExample: args.example,
765
- llmApiKey: args["llm-api-key"],
766
- timeout,
767
- projectName,
768
- directory: args.dir,
769
- mcpServer: args.mcp,
770
- template: args.template
771
- });
772
- },
773
- origin
774
- });
775
- });
776
- program.command("init").description("Initialize Mastra in your project").option("--default", "Quick start with defaults(src, OpenAI, examples)").option("-d, --dir <directory>", "Directory for Mastra files to (defaults to src/)").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("-m, --mcp <editor>", "MCP Server for code editor (cursor, cursor-global, windsurf, vscode)").action(async (args) => {
777
- await analytics.trackCommandExecution({
778
- command: "init",
779
- args,
780
- execution: async () => {
781
- await checkPkgJson();
782
- await checkAndInstallCoreDeps(args?.example || args?.default);
783
- if (!Object.keys(args).length) {
784
- const result = await interactivePrompt();
785
- await init({
786
- ...result,
787
- llmApiKey: result?.llmApiKey,
788
- components: ["agents", "tools", "workflows"],
789
- addExample: true
790
- });
791
- return;
792
- }
793
- if (args?.default) {
794
- await init({
795
- directory: "src/",
796
- components: ["agents", "tools", "workflows"],
797
- llmProvider: "openai",
798
- addExample: true,
799
- configureEditorWithDocsMCP: args.mcp
800
- });
801
- return;
802
- }
803
- const componentsArr = args.components ? args.components.split(",") : [];
804
- await init({
805
- directory: args.dir,
806
- components: componentsArr,
807
- llmProvider: args.llm,
808
- addExample: args.example,
809
- llmApiKey: args["llm-api-key"],
810
- configureEditorWithDocsMCP: args.mcp
811
- });
812
- return;
813
- },
814
- origin
815
- });
816
- });
817
- program.command("lint").description("Lint your Mastra project").option("-d, --dir <path>", "Path to your Mastra folder").option("-r, --root <path>", "Path to your root folder").option("-t, --tools <toolsDirs>", "Comma-separated list of paths to tool files to include").action(async (args) => {
818
- await analytics.trackCommandExecution({
819
- command: "lint",
820
- args,
821
- execution: async () => {
822
- await lint({ dir: args.dir, root: args.root, tools: args.tools ? args.tools.split(",") : [] });
823
- },
824
- origin
825
- });
826
- });
1202
+ ).action(createProject);
1203
+ program.command("init").description("Initialize Mastra in your project").option("--default", "Quick start with defaults(src, OpenAI, examples)").option("-d, --dir <directory>", "Directory for Mastra files to (defaults to src/)").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("-m, --mcp <editor>", "MCP Server for code editor (cursor, cursor-global, windsurf, vscode)").action(initProject);
1204
+ program.command("lint").description("Lint your Mastra project").option("-d, --dir <path>", "Path to your Mastra folder").option("-r, --root <path>", "Path to your root folder").option("-t, --tools <toolsDirs>", "Comma-separated list of paths to tool files to include").action(lintProject);
827
1205
  program.command("dev").description("Start mastra server").option("-d, --dir <dir>", "Path to your mastra folder").option("-r, --root <root>", "Path to your root folder").option("-t, --tools <toolsDirs>", "Comma-separated list of paths to tool files to include").option("-p, --port <port>", "deprecated: Port number for the development server (defaults to 4111)").option("-e, --env <env>", "Custom env file to include in the dev server").option("-i, --inspect", "Start the dev server in inspect mode").option("-b, --inspect-brk", "Start the dev server in inspect mode and break at the beginning of the script").option(
828
1206
  "-c, --custom-args <args>",
829
1207
  "Comma-separated list of custom arguments to pass to the dev server. IE: --experimental-transform-types"
830
- ).action((args) => {
831
- analytics.trackCommand({
832
- command: "dev",
833
- origin
834
- });
835
- if (args?.port) {
836
- logger.warn("The --port option is deprecated. Use the server key in the Mastra instance instead.");
837
- }
838
- dev({
839
- port: args?.port ? parseInt(args.port) : null,
840
- dir: args?.dir,
841
- root: args?.root,
842
- tools: args?.tools ? args.tools.split(",") : [],
843
- env: args?.env,
844
- inspect: args?.inspect && !args?.inspectBrk,
845
- inspectBrk: args?.inspectBrk,
846
- customArgs: args?.customArgs ? args.customArgs.split(",") : []
847
- }).catch((err) => {
848
- logger.error(err.message);
849
- });
850
- });
851
- program.command("build").description("Build your Mastra project").option("-d, --dir <path>", "Path to your Mastra Folder").option("-r, --root <path>", "Path to your root folder").option("-t, --tools <toolsDirs>", "Comma-separated list of paths to tool files to include").option("-e, --env <env>", "Custom env file to include in the build").action(async (args) => {
852
- await analytics.trackCommandExecution({
853
- command: "mastra build",
854
- args,
855
- execution: async () => {
856
- await build({
857
- dir: args?.dir,
858
- root: args?.root,
859
- tools: args?.tools ? args.tools.split(",") : [],
860
- env: args?.env
861
- });
862
- },
863
- origin
864
- });
865
- });
866
- program.command("deploy").description("Deploy your Mastra project").option("-d, --dir <path>", "Path to directory").action(async (args) => {
867
- config({ path: [".env", ".env.production"] });
868
- await analytics.trackCommandExecution({
869
- command: "mastra deploy",
870
- args,
871
- execution: async () => {
872
- logger.warn(`DEPRECATED: The deploy command is deprecated.
873
- Please use the mastra build command instead.
874
- Then deploy .mastra/output to your target platform.
875
- `);
876
- await deploy({ dir: args.dir });
877
- },
878
- origin
879
- });
880
- });
881
- program.command("start").description("Start your built Mastra application").option("-d, --dir <path>", "Path to your built Mastra output directory (default: .mastra/output)").option("-nt, --no-telemetry", "Disable telemetry on start").action(async (args) => {
882
- await analytics.trackCommandExecution({
883
- command: "start",
884
- args,
885
- execution: async () => {
886
- await start({
887
- dir: args.dir,
888
- telemetry: !args.noTelemetry
889
- });
890
- },
891
- origin
892
- });
893
- });
1208
+ ).action(startDevServer);
1209
+ program.command("build").description("Build your Mastra project").option("-d, --dir <path>", "Path to your Mastra Folder").option("-r, --root <path>", "Path to your root folder").option("-t, --tools <toolsDirs>", "Comma-separated list of paths to tool files to include").option("-e, --env <env>", "Custom env file to include in the build").action(buildProject);
1210
+ program.command("deploy").description("Deploy your Mastra project").option("-d, --dir <path>", "Path to directory").action(deployProject);
1211
+ program.command("start").description("Start your built Mastra application").option("-d, --dir <path>", "Path to your built Mastra output directory (default: .mastra/output)").option("-nt, --no-telemetry", "Disable telemetry on start").action(startProject);
1212
+ var scorersCommand = program.command("scorers").description("Manage scorers for evaluating AI outputs");
1213
+ scorersCommand.command("add [scorer-name]").description("Add a new scorer to your project").option("-d, --dir <path>", "Path to your Mastra directory (default: auto-detect)").action(addScorer);
1214
+ scorersCommand.command("list").description("List available scorer templates").action(listScorers);
894
1215
  program.parse(process.argv);
1216
+
1217
+ export { analytics, origin2 as origin };
895
1218
  //# sourceMappingURL=index.js.map
896
1219
  //# sourceMappingURL=index.js.map