mastra 1.8.2-alpha.2 → 1.9.0-alpha.11

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 (73) hide show
  1. package/CHANGELOG.md +253 -0
  2. package/dist/analytics/index.d.ts +1 -1
  3. package/dist/analytics/index.d.ts.map +1 -1
  4. package/dist/analytics/index.js +1 -1
  5. package/dist/{chunk-SDL4FTWG.js → chunk-SRICB6YH.js} +7 -7
  6. package/dist/chunk-SRICB6YH.js.map +1 -0
  7. package/dist/{chunk-5AV57UDP.js → chunk-VZVGRGA5.js} +9 -6
  8. package/dist/chunk-VZVGRGA5.js.map +1 -0
  9. package/dist/commands/api/client.d.ts +17 -0
  10. package/dist/commands/api/client.d.ts.map +1 -0
  11. package/dist/commands/api/errors.d.ts +15 -0
  12. package/dist/commands/api/errors.d.ts.map +1 -0
  13. package/dist/commands/api/headers.d.ts +2 -0
  14. package/dist/commands/api/headers.d.ts.map +1 -0
  15. package/dist/commands/api/index.d.ts +15 -0
  16. package/dist/commands/api/index.d.ts.map +1 -0
  17. package/dist/commands/api/input.d.ts +8 -0
  18. package/dist/commands/api/input.d.ts.map +1 -0
  19. package/dist/commands/api/normalizers.d.ts +3 -0
  20. package/dist/commands/api/normalizers.d.ts.map +1 -0
  21. package/dist/commands/api/output.d.ts +17 -0
  22. package/dist/commands/api/output.d.ts.map +1 -0
  23. package/dist/commands/api/response-normalizer.d.ts +2 -0
  24. package/dist/commands/api/response-normalizer.d.ts.map +1 -0
  25. package/dist/commands/api/route-metadata.generated.d.ts +3419 -0
  26. package/dist/commands/api/route-metadata.generated.d.ts.map +1 -0
  27. package/dist/commands/api/schema.d.ts +6 -0
  28. package/dist/commands/api/schema.d.ts.map +1 -0
  29. package/dist/commands/api/target.d.ts +14 -0
  30. package/dist/commands/api/target.d.ts.map +1 -0
  31. package/dist/commands/api/types.d.ts +37 -0
  32. package/dist/commands/api/types.d.ts.map +1 -0
  33. package/dist/commands/create/create.js +2 -2
  34. package/dist/commands/lint/rules/nextConfigRule.d.ts.map +1 -1
  35. package/dist/commands/worker/WorkerBundler.d.ts +13 -0
  36. package/dist/commands/worker/WorkerBundler.d.ts.map +1 -0
  37. package/dist/commands/worker/build.d.ts +8 -0
  38. package/dist/commands/worker/build.d.ts.map +1 -0
  39. package/dist/commands/worker/dev.d.ts +12 -0
  40. package/dist/commands/worker/dev.d.ts.map +1 -0
  41. package/dist/commands/worker/start.d.ts +8 -0
  42. package/dist/commands/worker/start.d.ts.map +1 -0
  43. package/dist/docs/SKILL.md +1 -1
  44. package/dist/docs/assets/SOURCE_MAP.json +3 -3
  45. package/dist/docs/references/reference-cli-mastra.md +464 -0
  46. package/dist/index.d.ts.map +1 -1
  47. package/dist/index.js +6805 -562
  48. package/dist/index.js.map +1 -1
  49. package/dist/studio/assets/{index-DNHDjLYs.js → index-2eY8UKa1.js} +1 -1
  50. package/dist/studio/assets/{index-CdggTBzd.js → index-6gc7Fonr.js} +1 -1
  51. package/dist/studio/assets/{index-ZpLrnVFB.js → index-B8eGTIzu.js} +1 -1
  52. package/dist/studio/assets/{index-CaD7ddjV.js → index-BJ7zEgSR.js} +1 -1
  53. package/dist/studio/assets/{index-BiigrE1w.js → index-Bcu_d_3x.js} +1 -1
  54. package/dist/studio/assets/{index-u_lqiE2u.js → index-CGPxkRq9.js} +1 -1
  55. package/dist/studio/assets/{index-CQWUz_Ua.js → index-CNLFWvch.js} +1 -1
  56. package/dist/studio/assets/{index-DNfvq-Ph.js → index-Cf97qh-b.js} +1 -1
  57. package/dist/studio/assets/{index-LVEEbtZn.js → index-CtftAbVZ.js} +1 -1
  58. package/dist/studio/assets/{index-mTon5-ys.js → index-D6xudyP7.js} +1 -1
  59. package/dist/studio/assets/{index-BPGtLMXv.js → index-DMTuYxa2.js} +1 -1
  60. package/dist/studio/assets/{index-DZf7g_uc.js → index-DZd1PCZF.js} +1 -1
  61. package/dist/studio/assets/{index-DX5l222Z.js → index-Dj1K_nag.js} +1 -1
  62. package/dist/studio/assets/{index-Cmdv7FN5.js → index-DjXO-DHz.js} +1 -1
  63. package/dist/studio/assets/{index-BmR9ljo2.js → index-DkbdC7th.js} +1 -1
  64. package/dist/studio/assets/{index-DBAgKJUH.js → index-a_px0bC1.js} +1 -1
  65. package/dist/studio/assets/{index-DAO3kR5r.js → index-gKulGpC4.js} +1 -1
  66. package/dist/studio/assets/{index-DI9zd2Nn.js → index-kvSk6ZoN.js} +1 -1
  67. package/dist/studio/assets/{main-DqVfM6wN.js → main-Bpbn3nDi.js} +239 -230
  68. package/dist/studio/assets/style-BBkwofEK.css +1 -0
  69. package/dist/studio/index.html +2 -2
  70. package/package.json +8 -5
  71. package/dist/chunk-5AV57UDP.js.map +0 -1
  72. package/dist/chunk-SDL4FTWG.js.map +0 -1
  73. package/dist/studio/assets/style-2Gc7zkTG.css +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,258 @@
1
1
  # mastra
2
2
 
3
+ ## 1.9.0-alpha.11
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated the generated project template and runtime bootstrap to use `MastraStorageExporter` and `MastraPlatformExporter` from `@mastra/observability`. ([#16223](https://github.com/mastra-ai/mastra/pull/16223))
8
+
9
+ - dependencies updates: ([#16399](https://github.com/mastra-ai/mastra/pull/16399))
10
+ - Updated dependency [`@babel/parser@^7.29.3` ↗︎](https://www.npmjs.com/package/@babel/parser/v/7.29.3) (from `^7.28.4`, in `dependencies`)
11
+ - Updated dependency [`@babel/types@^7.29.0` ↗︎](https://www.npmjs.com/package/@babel/types/v/7.29.0) (from `^7.28.4`, in `dependencies`)
12
+
13
+ - Removed the unintended search input from the Traces page in Studio. ([#16418](https://github.com/mastra-ai/mastra/pull/16418))
14
+
15
+ - Updated dependencies [[`7ad5585`](https://github.com/mastra-ai/mastra/commit/7ad55856406f1de398dc713f6a9eaa78b2784bb6), [`210ea7a`](https://github.com/mastra-ai/mastra/commit/210ea7af559791b73a44fc9c12179908aaa3183f), [`83218c8`](https://github.com/mastra-ai/mastra/commit/83218c88b37773c9424fbe733b37be556e55e94d), [`265ec9f`](https://github.com/mastra-ai/mastra/commit/265ec9f887b5c81255c873a76ff7796f16e4f99b), [`6ce80bf`](https://github.com/mastra-ai/mastra/commit/6ce80bf4872a891e0bddf8b80561a80584efb14b), [`9268531`](https://github.com/mastra-ai/mastra/commit/9268531e7ec4be98beeba3b3ae8be0a7ea380662), [`13ead79`](https://github.com/mastra-ai/mastra/commit/13ead79149486b88144db7e11e6ff551caef5be1), [`bd36d8e`](https://github.com/mastra-ai/mastra/commit/bd36d8eb6de8c9a0310352649dbd4b06703c2299), [`8ac9141`](https://github.com/mastra-ai/mastra/commit/8ac9141439caa8fdd674944c4d84f29b3c730296)]:
16
+ - @mastra/core@1.33.0-alpha.10
17
+ - @mastra/deployer@1.33.0-alpha.10
18
+
19
+ ## 1.9.0-alpha.10
20
+
21
+ ## 1.9.0-alpha.9
22
+
23
+ ### Patch Changes
24
+
25
+ - Updated dependencies [[`5688881`](https://github.com/mastra-ai/mastra/commit/5688881669c7ed157f31ac77f6fc5f8d95ceea32)]:
26
+ - @mastra/core@1.33.0-alpha.9
27
+ - @mastra/deployer@1.33.0-alpha.9
28
+
29
+ ## 1.9.0-alpha.8
30
+
31
+ ### Patch Changes
32
+
33
+ - Updated dependencies [[`7c275a8`](https://github.com/mastra-ai/mastra/commit/7c275a810595e1a6c41ccc39720531ab65734700), [`890b24c`](https://github.com/mastra-ai/mastra/commit/890b24cc7d32ed6aa4dfe253e54dc6bf4099f690), [`0f48ebf`](https://github.com/mastra-ai/mastra/commit/0f48ebfc7ac7897b2092a189f45751924cf56d1c), [`f180e49`](https://github.com/mastra-ai/mastra/commit/f180e4990e71b04c9a475b523584071712f0048f), [`9260e01`](https://github.com/mastra-ai/mastra/commit/9260e015276fb1b500f7878ee452b47476bf1583), [`2f6c54e`](https://github.com/mastra-ai/mastra/commit/2f6c54e17c041cac1def54baaa6b771647836414), [`e06a159`](https://github.com/mastra-ai/mastra/commit/e06a1598ca07a6c3778aefc2a2d288363c6294ff), [`db34bc6`](https://github.com/mastra-ai/mastra/commit/db34bc6fb36cf125bda0c46be4d3fdc774b70cc4)]:
34
+ - @mastra/core@1.33.0-alpha.8
35
+ - @mastra/deployer@1.33.0-alpha.8
36
+
37
+ ## 1.9.0-alpha.7
38
+
39
+ ### Minor Changes
40
+
41
+ - Scope `mastra worker` as `build` / `start` / `dev` subcommands, mirroring the server's `mastra build` / `mastra start` / `mastra dev` shape. ([#16309](https://github.com/mastra-ai/mastra/pull/16309))
42
+
43
+ Previously `mastra worker [name]` both bundled and ran in one shot. Splitting it into discrete `build` and `start` steps makes the worker lifecycle match the server lifecycle: bundle once on CI, ship the artifact, then start it (with `[name]` setting `MASTRA_WORKERS`) on the target host.
44
+
45
+ **New surface:**
46
+ - `mastra worker build` — bundles a role-agnostic worker artifact.
47
+ - `mastra worker start [name]` — runs the built worker. `[name]` sets `MASTRA_WORKERS` for the spawned process.
48
+ - `mastra worker dev [name]` — build + start in one step (the closest equivalent of the old `mastra worker [name]`).
49
+
50
+ **Output location:** by default the worker bundle writes to `.mastra/output/index.mjs`, the same path as `mastra build`. In a split deployment (one host runs the server, another runs the worker) that's what you want — each host bundles only the role it ships. Running both `mastra build` and `mastra worker build` back-to-back in the same project will overwrite, by design.
51
+
52
+ If you want both bundles to coexist on disk in the same project, pass `--output-dir <path>` to `mastra worker build` to redirect the worker bundle anywhere — relative or absolute. When a custom path is given, `prepare` wipes only that target so adjacent build artifacts (including `.mastra/output/`) are left alone:
53
+
54
+ ```sh
55
+ mastra build # writes .mastra/output/index.mjs (server)
56
+ mastra worker build --output-dir dist/worker # writes dist/worker/index.mjs
57
+ mastra worker start --dir dist/worker # runs the worker bundle from there
58
+ ```
59
+
60
+ **Breaking change:** `mastra worker [name]` no longer works. Use `mastra worker dev [name]` for the same one-shot behavior, or split it into `mastra worker build` + `mastra worker start [name]` for production deployments.
61
+
62
+ - Worker review fixes: ([#16309](https://github.com/mastra-ai/mastra/pull/16309))
63
+ - Step-execution endpoint (`POST /workflows/:id/runs/:runId/steps/execute`) is
64
+ now gated by Mastra's standard `requiresAuth: true` + `authenticateToken`
65
+ pipeline rather than a parallel "worker secret" body field. The previously
66
+ introduced `workerSecret` config knob and `MASTRA_WORKER_SECRET` env var
67
+ have been removed (they were never released). To gate the endpoint on a
68
+ standalone-worker deployment, configure an auth provider on the server's
69
+ `Mastra` instance — without one the framework currently treats
70
+ `requiresAuth: true` as a no-op for this route.
71
+ - `HttpRemoteStrategy` now sends credentials as a normal `Authorization:
72
+ Bearer <token>` header. The token comes from the new
73
+ `MASTRA_WORKER_AUTH_TOKEN` env var or an explicit `auth` constructor option.
74
+ - Honor the caller's `abortSignal` in `HttpRemoteStrategy` by combining it
75
+ with the per-request timeout via `AbortSignal.any` (with a manual fallback
76
+ for runtimes that don't expose it).
77
+ - Implement comma-separated name filtering for the `MASTRA_WORKERS` env var.
78
+ `MASTRA_WORKERS=scheduler,backgroundTasks` now boots only those named
79
+ workers; `MASTRA_WORKERS=false` still disables all workers.
80
+ - Restore `Mastra.startEventEngine` / `stopEventEngine` as `@deprecated`
81
+ aliases for the renamed `startWorkers` / `stopWorkers`.
82
+ - `BackgroundTaskWorker` now subscribes to PubSub in `start()` instead of
83
+ `init()`, matching the lifecycle of the other workers and making
84
+ `isRunning` accurately reflect subscription state.
85
+ - `RedisStreamsPubSub` adds a `maxDeliveryAttempts` option (default 5) that
86
+ drops events after the configured number of failed deliveries instead of
87
+ redelivering forever, and replaces empty `catch {}` blocks with
88
+ `logger.warn`/`logger.debug` calls.
89
+ - `RedisStreamsPubSub.unsubscribe(topic, cb)` now honors the topic argument
90
+ so the same callback can be subscribed to multiple topics independently.
91
+ - `PullTransport` guards the async router callback against unhandled promise
92
+ rejections by attaching a `.catch` that nacks the message.
93
+ - Drop the dead `MASTRA_WORKER_NAME` env var injection in the CLI worker
94
+ spawn (the bundle entrypoint already passes the worker name directly).
95
+ - Add a real cross-process e2e auth suite
96
+ (`pubsub/redis-streams/src/auth-e2e.test.ts`) covering happy path, wrong
97
+ token, missing token, anonymous direct hits, and the no-auth-provider
98
+ pin-down behavior.
99
+ - Step-execution route now has a response schema, satisfying
100
+ `schema-consistency.test.ts`.
101
+ - Internal type cleanups (drop several `as any` casts in worker strategies
102
+ and `BackgroundTaskWorker`).
103
+ - `RedisStreamsPubSub.maxDeliveryAttempts` now rejects negative / NaN values
104
+ at construction. `0` still means "no cap" for back-compat but emits a
105
+ one-time warning; pass `Infinity` to disable the cap explicitly.
106
+ - `PullTransport` accepts a logger and uses it for unhandled router-callback
107
+ rejections instead of `console.error`.
108
+ - `BackgroundTaskWorker.start()` now throws if `init()` was not called,
109
+ matching the contract of the other workers.
110
+ - Cross-process integration tests now spawn a single user-owned project
111
+ (`test-fixtures/cli-project/src/mastra/index.ts`) through two generic
112
+ entries that mirror what `BuildBundler` and `WorkerBundler` emit. The
113
+ previous one-off `server.entry.ts` / `worker.entry.ts` /
114
+ `scheduler.entry.ts` / `background.entry.ts` files have been deleted —
115
+ they implied users hand-roll entry files, which they don't. Worker role
116
+ is selected via `MASTRA_WORKERS` exactly as in production.
117
+
118
+ Push-capable PubSub:
119
+ - The `PubSub` abstract class now declares a `supportedModes` getter
120
+ (defaulting to `['pull']` for backward compatibility) so consumers can
121
+ tell whether a broker delivers events through a pull loop, an in-process
122
+ push, or an out-of-process HTTP push. `EventEmitterPubSub` reports
123
+ `['pull', 'push']` (EventEmitter dispatches synchronously and works for
124
+ either path), `@mastra/redis-streams` reports `['pull']`.
125
+ - `Mastra` now exposes a public `handleWorkflowEvent(event)` method backed
126
+ by a shared `WorkflowEventProcessor`. It is the single entry point used
127
+ by the existing pull-mode `OrchestrationWorker`, by in-process push
128
+ pubsubs (auto-wired during `startWorkers()`), and by the new
129
+ `POST /api/workflows/events` route which lets push-mode brokers (GCP
130
+ Pub/Sub push, SNS, EventBridge) deliver events over HTTP.
131
+ - When the configured pubsub does not support `'pull'`, Mastra
132
+ automatically skips creating an `OrchestrationWorker` and
133
+ `OrchestrationWorker.init()` throws a clear error if it is constructed
134
+ against a push-only pubsub.
135
+ - `WorkflowEventProcessor` gains a `handle(event)` method that returns a
136
+ structured `{ ok, retry }` result. The original `process(event, ack?)`
137
+ method is preserved as a thin wrapper for back-compat.
138
+
139
+ Public-API example for a push-capable PubSub:
140
+
141
+ ```ts
142
+ import { Mastra } from '@mastra/core/mastra';
143
+ import { EventEmitterPubSub } from '@mastra/core/pubsub';
144
+
145
+ const mastra = new Mastra({
146
+ // A push-capable broker (GCP Pub/Sub push, SNS, EventEmitter, …).
147
+ // EventEmitterPubSub reports supportedModes = ['pull', 'push'].
148
+ pubsub: new EventEmitterPubSub(),
149
+ workflows: { myWorkflow },
150
+ });
151
+
152
+ // In-process push pubsubs are auto-wired here. For out-of-process
153
+ // push (e.g. HTTP webhook from a cloud broker), POST the event to
154
+ // /api/workflows/events on your Mastra server instead.
155
+ await mastra.startWorkers();
156
+
157
+ // Direct invocation (e.g. inside an HTTP handler that bridges from a
158
+ // cloud broker's push delivery):
159
+ await mastra.handleWorkflowEvent({
160
+ id: 'evt-1',
161
+ type: 'workflow.start',
162
+ runId: 'run-1',
163
+ createdAt: new Date(),
164
+ data: { workflowId: 'myWorkflow', inputData: { name: 'world' } },
165
+ });
166
+ ```
167
+
168
+ CI follow-ups:
169
+ - `Mastra` only auto-registers `SchedulerWorker` when storage is configured.
170
+ Without storage the worker would crash on startup (`deps.storage.getStore`
171
+ on undefined); the scheduler now silently no-ops in that case, matching the
172
+ pre-worker scheduler behavior.
173
+ - `SchedulerWorker.init` defensively logs and returns when called without
174
+ storage instead of throwing a TypeError.
175
+ - `RECEIVE_WORKFLOW_EVENT_ROUTE` (`POST /workflows/events`) `createdAt` is
176
+ now a plain `z.string()` on the wire and the handler converts it to a
177
+ `Date` (validating "Invalid Date" -> 400). The previous
178
+ `union(...).transform().refine()` schema couldn't be exercised by the
179
+ shared adapter test suite because the generator didn't unwrap Zod 4's
180
+ `ZodPipe`.
181
+ - `_test-utils/route-test-utils` recognizes Zod 4's `number_format` check
182
+ (used for `int()` / `safeint()`), and `generateContextualValue` now
183
+ produces a valid ISO timestamp for `createdAt` / `updatedAt` fields.
184
+
185
+ ### Patch Changes
186
+
187
+ - Fixed Next.js config linting so project config files are parsed without executing code. #16180 ([#16184](https://github.com/mastra-ai/mastra/pull/16184))
188
+
189
+ - Updated dependencies [[`6742347`](https://github.com/mastra-ai/mastra/commit/6742347d71955d7639adc9ddf6ff8282de7ee3ba), [`7b0ad1f`](https://github.com/mastra-ai/mastra/commit/7b0ad1f5c53dc118c6da12ae82ae2587037dc2b8), [`62666c3`](https://github.com/mastra-ai/mastra/commit/62666c367eaeac3941ead454b1d38810cc855721), [`4af2160`](https://github.com/mastra-ai/mastra/commit/4af2160322f4718cac421930cce85641e9512389), [`136c959`](https://github.com/mastra-ai/mastra/commit/136c9592fb0eeb0cd212f28629d8a29b7557a2fc), [`4df7cc7`](https://github.com/mastra-ai/mastra/commit/4df7cc79342fd065fe7fdeef93c094db14b12bcd), [`aca3121`](https://github.com/mastra-ai/mastra/commit/aca31211233dac25459f140ea4fcfb3a5af64c18), [`9cdf38e`](https://github.com/mastra-ai/mastra/commit/9cdf38e58506e1109c8b38f97cd7770978a4218e), [`990851e`](https://github.com/mastra-ai/mastra/commit/990851edcb0e30be5c2c18b6532f1a876cc2d335), [`6068a6c`](https://github.com/mastra-ai/mastra/commit/6068a6c42950fad3ebfc92346417896ba60803d2), [`00106be`](https://github.com/mastra-ai/mastra/commit/00106bede59b81e5b0e9cd6aad8d3b5dbc336387), [`e2a079c`](https://github.com/mastra-ai/mastra/commit/e2a079cc3755b1895f7bd5dc36e9be81b11c7c22), [`534a456`](https://github.com/mastra-ai/mastra/commit/534a456a25e4df1e5407e7e632f4cb3b1fa14f9d), [`36bae07`](https://github.com/mastra-ai/mastra/commit/36bae07c0e70b1b3006f2fd20830e8883dcbd066)]:
190
+ - @mastra/core@1.33.0-alpha.7
191
+ - @mastra/deployer@1.33.0-alpha.7
192
+
193
+ ## 1.9.0-alpha.6
194
+
195
+ ### Patch Changes
196
+
197
+ - Updated dependencies [[`b560d6f`](https://github.com/mastra-ai/mastra/commit/b560d6f88b9b904b15c10f75c949eb145bc27684), [`36b3bbf`](https://github.com/mastra-ai/mastra/commit/36b3bbf5a8d59f7e23d47e29340e76c681b4929c), [`b275631`](https://github.com/mastra-ai/mastra/commit/b275631dc10541a482b2e2d4a3e3cfa843bd5fa1)]:
198
+ - @mastra/core@1.33.0-alpha.6
199
+ - @mastra/deployer@1.33.0-alpha.6
200
+
201
+ ## 1.9.0-alpha.5
202
+
203
+ ### Patch Changes
204
+
205
+ - Updated dependencies [[`bae019e`](https://github.com/mastra-ai/mastra/commit/bae019ecb6694da96909f7ec7b9eb3a0a33aa887), [`33f5061`](https://github.com/mastra-ai/mastra/commit/33f5061cd1c0335020c3faae61ce96de822854fa), [`99869ec`](https://github.com/mastra-ai/mastra/commit/99869ecb1f2aa6dfcc44fa4e843e5ee0344efa64), [`d86f031`](https://github.com/mastra-ai/mastra/commit/d86f031eb6b0b2570145afafea664e59bf688962)]:
206
+ - @mastra/core@1.33.0-alpha.5
207
+ - @mastra/deployer@1.33.0-alpha.5
208
+
209
+ ## 1.9.0-alpha.4
210
+
211
+ ### Minor Changes
212
+
213
+ - Updated the Studio observability UI with a filterable metrics dashboard and saved filter persistence. ([#15747](https://github.com/mastra-ai/mastra/pull/15747))
214
+
215
+ **Metrics dashboard filters**
216
+
217
+ The metrics page now includes a dimensional filter toolbar for `rootEntityType`, `entityName`, `entityId`, `tags`, `serviceName`, `environment`, and common identity/correlation IDs such as `threadId`, `resourceId`, `userId`, `organizationId`, `runId`, `sessionId`, `requestId`, and `experimentId`. Active metrics filters are reflected in the URL and can be saved to the Metrics page's own localStorage key.
218
+
219
+ **Memory card**
220
+
221
+ A new **Memory** card shows thread and resource activity in one tabbed card. Rows include run counts, token usage, and cost for the active date range and filters. The dashboard also restores the Total Threads and Total Resources KPI cards.
222
+
223
+ **Drilldowns**
224
+
225
+ Metrics cards can now link into Traces or Logs while preserving the active date range and relevant filters:
226
+ - Latency, Trace Volume, Token Usage by Agent, and Model Usage & Cost expose header drilldown actions.
227
+ - Token Usage by Agent, Trace Volume, and Model Usage & Cost rows/bars drill into Traces scoped to the clicked entity.
228
+ - Trace Volume error segments can drill into Logs with `level=error`.
229
+ - Memory rows drill into Traces scoped to the clicked `threadId` or `resourceId`.
230
+ - Latency chart points narrow Traces to the clicked time bucket.
231
+
232
+ Metrics-to-Traces drilldowns open the branch-oriented trace list so nested agent, workflow, and tool spans are visible. KPI cards remain non-clickable.
233
+
234
+ ### Patch Changes
235
+
236
+ - Updated dependencies [[`9f17410`](https://github.com/mastra-ai/mastra/commit/9f1741080def23d42ee50b39887a385ae316a3c6), [`c6eb39e`](https://github.com/mastra-ai/mastra/commit/c6eb39ea6dca381c6563cb240237fbe608e02f93), [`900d086`](https://github.com/mastra-ai/mastra/commit/900d086bb737b9cf2fcf68f11b0389b801a2738c), [`4c0e286`](https://github.com/mastra-ai/mastra/commit/4c0e28637c9cfb4f416549b55e97ebfa13319dfc), [`25184ff`](https://github.com/mastra-ai/mastra/commit/25184ffaf1293ec95119426eb1a1f8d38831b96c), [`aebde9c`](https://github.com/mastra-ai/mastra/commit/aebde9cfacf56592c6b6350cae721740fe090b8a)]:
237
+ - @mastra/core@1.33.0-alpha.4
238
+ - @mastra/deployer@1.33.0-alpha.4
239
+
240
+ ## 1.9.0-alpha.3
241
+
242
+ ### Minor Changes
243
+
244
+ - Added `mastra api`, a machine-readable runtime CLI for calling Mastra server resources with JSON input and output. ([#16128](https://github.com/mastra-ai/mastra/pull/16128))
245
+
246
+ The new API CLI supports agents, workflows, tools, MCP servers, memory threads, working memory, observability traces/logs/scores, datasets, and experiments. It includes schema-aware request handling so a single JSON input is split into path, query, and body fields based on server route contracts, plus ergonomic raw-input wrapping for tool execution.
247
+
248
+ Exposed a route-derived server API schema manifest at runtime and generated CLI route metadata from it, enabling `--schema` output, response-shape-aware normalization, and server-aligned pagination output.
249
+
250
+ ### Patch Changes
251
+
252
+ - Updated dependencies [[`087e413`](https://github.com/mastra-ai/mastra/commit/087e4133e5d6efa36619e9556c16750e4179c047), [`087e413`](https://github.com/mastra-ai/mastra/commit/087e4133e5d6efa36619e9556c16750e4179c047), [`087e413`](https://github.com/mastra-ai/mastra/commit/087e4133e5d6efa36619e9556c16750e4179c047)]:
253
+ - @mastra/core@1.33.0-alpha.3
254
+ - @mastra/deployer@1.33.0-alpha.3
255
+
3
256
  ## 1.8.2-alpha.2
4
257
 
5
258
  ### Patch Changes
@@ -34,6 +34,6 @@ export declare class PosthogAnalytics {
34
34
  execution: () => Promise<T>;
35
35
  origin?: CLI_ORIGIN;
36
36
  }): Promise<T>;
37
- shutdown(): Promise<void>;
37
+ shutdown(timeoutMs?: number): Promise<void>;
38
38
  }
39
39
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/analytics/index.ts"],"names":[],"mappings":"AAmBA,MAAM,MAAM,UAAU,GAAG,cAAc,GAAG,KAAK,CAAC;AAIhD,wBAAgB,YAAY,IAAI,gBAAgB,GAAG,IAAI,CAEtD;AAED,wBAAgB,YAAY,CAAC,QAAQ,EAAE,gBAAgB,GAAG,IAAI,CAE7D;AAED,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,MAAM,CAAC,CAAU;IACzB,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,cAAc,CAAS;gBAEnB,EACV,OAAO,EACP,MAAM,EACN,IAAgC,GACjC,EAAE;QACD,OAAO,EAAE,MAAM,CAAC;QAChB,MAAM,EAAE,MAAM,CAAC;QACf,IAAI,EAAE,MAAM,CAAC;KACd;IAgCD,OAAO,CAAC,cAAc;IAQtB,OAAO,CAAC,iBAAiB;IAezB,OAAO,CAAC,kBAAkB;IAS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@
1
- export { PosthogAnalytics, getAnalytics, setAnalytics } from '../chunk-SDL4FTWG.js';
1
+ export { PosthogAnalytics, getAnalytics, setAnalytics } from '../chunk-SRICB6YH.js';
2
2
  //# sourceMappingURL=index.js.map
3
3
  //# sourceMappingURL=index.js.map
@@ -782,7 +782,7 @@ import { PinoLogger } from '@mastra/loggers';
782
782
  import { LibSQLStore } from '@mastra/libsql';
783
783
  import { DuckDBStore } from "@mastra/duckdb";
784
784
  import { MastraCompositeStore } from '@mastra/core/storage';
785
- import { Observability, DefaultExporter, CloudExporter, SensitiveDataFilter } from '@mastra/observability';
785
+ import { Observability, MastraStorageExporter, MastraPlatformExporter, SensitiveDataFilter } from '@mastra/observability';
786
786
  ${addWorkflow ? `import { weatherWorkflow } from './workflows/weather-workflow';` : ""}
787
787
  ${addAgent ? `import { weatherAgent } from './agents/weather-agent';` : ""}
788
788
  ${addScorers ? `import { toolCallAppropriatenessScorer, completenessScorer, translationScorer } from './scorers/weather-scorer';` : ""}
@@ -808,8 +808,8 @@ export const mastra = new Mastra({
808
808
  default: {
809
809
  serviceName: 'mastra',
810
810
  exporters: [
811
- new DefaultExporter(), // Persists traces to storage for Mastra Studio
812
- new CloudExporter(), // Sends observability data to hosted Mastra Studio (if MASTRA_CLOUD_ACCESS_TOKEN is set)
811
+ new MastraStorageExporter(), // Persists observability events to Mastra Storage
812
+ new MastraPlatformExporter(), // Sends observability events to Mastra Platform (if MASTRA_CLOUD_ACCESS_TOKEN is set)
813
813
  ],
814
814
  spanOutputProcessors: [
815
815
  new SensitiveDataFilter(), // Redacts sensitive data like passwords, tokens, keys
@@ -1520,17 +1520,17 @@ var PosthogAnalytics = class {
1520
1520
  }
1521
1521
  }
1522
1522
  // Ensure PostHog client is shutdown properly
1523
- async shutdown() {
1523
+ async shutdown(timeoutMs) {
1524
1524
  if (!this.client) {
1525
1525
  return;
1526
1526
  }
1527
1527
  try {
1528
- await this.client.shutdown();
1528
+ await this.client.shutdown(timeoutMs);
1529
1529
  } catch {
1530
1530
  }
1531
1531
  }
1532
1532
  };
1533
1533
 
1534
1534
  export { COMPONENTS, DepsService, FileService, LLMProvider, LLM_PROVIDERS, PosthogAnalytics, checkAndInstallCoreDeps, checkForPkgJson, createComponentsDir, createMastraDir, getAPIKey, getAnalytics, getModelIdentifier, getPackageManager, getPackageManagerAddCommand, getVersionTag, gitInit, installMastraDocsMCPServer, interactivePrompt, isGitInitialized, parseComponents, parseLlmProvider, parseMcp, parseSkills, setAnalytics, shouldSkipDotenvLoading, writeAPIKey, writeAgentsMarkdown, writeClaudeMarkdown, writeCodeSample, writeIndexFile };
1535
- //# sourceMappingURL=chunk-SDL4FTWG.js.map
1536
- //# sourceMappingURL=chunk-SDL4FTWG.js.map
1535
+ //# sourceMappingURL=chunk-SRICB6YH.js.map
1536
+ //# sourceMappingURL=chunk-SRICB6YH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/init/mcp-docs-server-install.ts","../src/utils/package-manager.ts","../src/services/service.deps.ts","../src/services/service.env.ts","../src/services/service.fileEnv.ts","../src/services/service.file.ts","../src/commands/init/utils.ts","../src/commands/utils.ts","../src/analytics/index.ts"],"names":["hasMastraMCP","fs","path","fsPromises","fs2","__filename","__dirname","fsExtra","p","confirm","fileURLToPath","execa","existsSync","os"],"mappings":";;;;;;;;;;;;;;;;;;;;AAKA,IAAM,UAAA,GAAa,CAAC,UAAA,KAAwB;AAC1C,EAAA,MAAM,WAAA,GAAc,UAAA,GAAa,CAAA,wBAAA,EAA2B,UAAU,CAAA,CAAA,GAAK,yBAAA;AAC3E,EAAA,OAAO,CAAC,MAAM,WAAW,CAAA;AAC3B,CAAA;AAEA,IAAM,eAAA,GAAkB,CAAC,MAAA,EAAgB,UAAA,KAAwB;AAC/D,EAAA,MAAM,IAAA,GAAO,WAAW,UAAU,CAAA;AAClC,EAAA,IAAI,WAAW,QAAA,EAAU;AACvB,IAAA,OAAO;AAAA,MACL,OAAA,EAAS;AAAA,QACP,MAAA,EACE,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KAAA,EAAO;AACd,MAAA,MAAM,UAAA,GAAa,IAAA,CAAK,aAAA,CAAc,SAAS,CAAA;AAC/C,MAAA,IAAA,CAAK,YAAA,CAAa;AAAA,QAChB,OAAA;AAAA,QACA,IAAA;AAAA,QACA,UAAA;AAAA,QACA,MAAA,EAAQ,OAAA;AAAA,QACR,OAAO,KAAA,YAAiB,KAAA,GAAQ,KAAA,CAAM,OAAA,GAAU,OAAO,KAAK,CAAA;AAAA,QAC5D;AAAA,OACD,CAAA;AAED,MAAA,MAAM,KAAA;AAAA,IACR;AAAA,EACF;AAAA;AAAA,EAGA,MAAM,SAAS,SAAA,EAAmC;AAChD,IAAA,IAAI,CAAC,KAAK,MAAA,EAAQ;AAChB,MAAA;AAAA,IACF;AACA,IAAA,IAAI;AACF,MAAA,MAAM,IAAA,CAAK,MAAA,CAAO,QAAA,CAAS,SAAS,CAAA;AAAA,IACtC,CAAA,CAAA,MAAQ;AAAA,IAER;AAAA,EACF;AACF","file":"chunk-SRICB6YH.js","sourcesContent":["import { existsSync } from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { ensureFile, readJSON, writeJSON } from 'fs-extra/esm';\n\nconst createArgs = (versionTag?: string) => {\n const packageName = versionTag ? `@mastra/mcp-docs-server@${versionTag}` : '@mastra/mcp-docs-server';\n return ['-y', packageName];\n};\n\nconst createMcpConfig = (editor: Editor, versionTag?: string) => {\n const args = createArgs(versionTag);\n if (editor === 'vscode') {\n return {\n servers: {\n mastra:\n process.platform === `win32`\n ? {\n command: 'cmd',\n args: ['/c', 'npx', ...args],\n type: 'stdio',\n }\n : {\n command: 'npx',\n args,\n type: 'stdio',\n },\n },\n };\n }\n return {\n mcpServers: {\n mastra: {\n command: 'npx',\n args,\n },\n },\n };\n};\n\nfunction makeConfig(\n original: { mcpServers?: Record<string, unknown>; servers?: Record<string, unknown> },\n editor: Editor,\n versionTag?: string,\n) {\n if (editor === 'vscode') {\n return {\n ...original,\n servers: {\n ...(original?.servers || {}),\n ...createMcpConfig(editor, versionTag).servers,\n },\n };\n }\n return {\n ...original,\n mcpServers: {\n ...(original?.mcpServers || {}),\n ...createMcpConfig(editor, versionTag).mcpServers,\n },\n };\n}\n\nasync function writeMergedConfig(configPath: string, editor: Editor, versionTag?: string) {\n const configExists = existsSync(configPath);\n const config = makeConfig(configExists ? await readJSON(configPath) : {}, editor, versionTag);\n await ensureFile(configPath);\n await writeJSON(configPath, config, {\n spaces: 2,\n });\n}\n\nexport const windsurfGlobalMCPConfigPath = path.join(os.homedir(), '.codeium', 'windsurf', 'mcp_config.json');\nexport const antigravityGlobalMCPConfigPath = path.join(os.homedir(), '.gemini', 'antigravity', 'mcp_config.json');\nexport const cursorGlobalMCPConfigPath = path.join(os.homedir(), '.cursor', 'mcp.json');\nexport const vscodeMCPConfigPath = path.join(process.cwd(), '.vscode', 'mcp.json');\nexport const vscodeGlobalMCPConfigPath = path.join(\n os.homedir(),\n process.platform === 'win32'\n ? path.join('AppData', 'Roaming', 'Code', 'User', 'settings.json')\n : process.platform === 'darwin'\n ? path.join('Library', 'Application Support', 'Code', 'User', 'settings.json')\n : path.join('.config', 'Code', 'User', 'settings.json'),\n);\n\nexport const EDITOR = ['cursor', 'cursor-global', 'windsurf', 'vscode', 'antigravity'] as const;\nexport type Editor = (typeof EDITOR)[number];\n\nexport const MCP_SERVER = ['cursor', 'cursor-global', 'windsurf', 'antigravity'] as const;\nexport type MCPServer = (typeof MCP_SERVER)[number];\n\n/**\n * Type-guard to check if a string is a valid MCPServer\n */\nexport function isValidMCPServer(value: string): value is MCPServer {\n return MCP_SERVER.includes(value as MCPServer);\n}\n\n/**\n * Type-guard to check if a string is a valid Editor\n */\nexport function isValidEditor(value: string): value is Editor {\n return EDITOR.includes(value as Editor);\n}\n\nexport async function installMastraDocsMCPServer({\n editor,\n directory,\n versionTag,\n}: {\n editor?: Editor;\n directory: string;\n versionTag?: string;\n}) {\n if (editor === `cursor`) {\n await writeMergedConfig(path.join(directory, '.cursor', 'mcp.json'), 'cursor', versionTag);\n }\n if (editor === `vscode`) {\n await writeMergedConfig(path.join(directory, '.vscode', 'mcp.json'), 'vscode', versionTag);\n }\n if (editor === `cursor-global`) {\n const alreadyInstalled = await globalMCPIsAlreadyInstalled(editor, versionTag);\n if (alreadyInstalled) {\n return;\n }\n await writeMergedConfig(cursorGlobalMCPConfigPath, 'cursor-global', versionTag);\n }\n\n if (editor === `windsurf`) {\n const alreadyInstalled = await globalMCPIsAlreadyInstalled(editor, versionTag);\n if (alreadyInstalled) {\n return;\n }\n await writeMergedConfig(windsurfGlobalMCPConfigPath, editor, versionTag);\n }\n\n if (editor === `antigravity`) {\n const alreadyInstalled = await globalMCPIsAlreadyInstalled(editor, versionTag);\n if (alreadyInstalled) {\n return;\n }\n await writeMergedConfig(antigravityGlobalMCPConfigPath, editor, versionTag);\n }\n}\n\nexport async function globalMCPIsAlreadyInstalled(editor: Editor, versionTag?: string) {\n let configPath: string = ``;\n\n if (editor === 'windsurf') {\n configPath = windsurfGlobalMCPConfigPath;\n } else if (editor === 'antigravity') {\n configPath = antigravityGlobalMCPConfigPath;\n } else if (editor === 'cursor-global') {\n configPath = cursorGlobalMCPConfigPath;\n } else if (editor === 'vscode') {\n configPath = vscodeGlobalMCPConfigPath;\n }\n\n if (!configPath || !existsSync(configPath)) {\n return false;\n }\n\n try {\n const configContents = await readJSON(configPath);\n\n if (!configContents) return false;\n\n // Construct the expected package string based on versionTag\n const expectedPackage = versionTag ? `@mastra/mcp-docs-server@${versionTag}` : '@mastra/mcp-docs-server';\n\n if (editor === 'vscode') {\n if (!configContents.servers) return false;\n const hasMastraMCP = Object.values(configContents.servers).some((server?: any) =>\n server?.args?.find((arg?: string) => arg === expectedPackage),\n );\n return hasMastraMCP;\n }\n\n if (!configContents?.mcpServers) return false;\n const hasMastraMCP = Object.values(configContents.mcpServers).some((server?: any) =>\n server?.args?.find((arg?: string) => arg === expectedPackage),\n );\n\n return hasMastraMCP;\n } catch {\n return false;\n }\n}\n","export type PackageManager = 'npm' | 'yarn' | 'pnpm' | 'bun';\n\nexport function getPackageManagerAddCommand(pm: PackageManager): string {\n switch (pm) {\n case 'npm':\n return 'install --audit=false --fund=false --loglevel=error --progress=false --update-notifier=false';\n case 'yarn':\n return 'add';\n case 'pnpm':\n return 'add --loglevel=error';\n case 'bun':\n return 'add';\n default:\n return 'add';\n }\n}\n","import fs from 'node:fs';\nimport fsPromises from 'node:fs/promises';\nimport path from 'node:path';\nimport { execa } from 'execa';\nimport { getPackageManagerAddCommand } from '../utils/package-manager';\nimport type { PackageManager } from '../utils/package-manager';\n\nexport class DepsService {\n readonly packageManager: PackageManager;\n\n constructor() {\n this.packageManager = this.getPackageManager();\n }\n\n private findLockFile(dir: string): string | null {\n const lockFiles = ['pnpm-lock.yaml', 'package-lock.json', 'yarn.lock', 'bun.lock', 'bun.lockb'];\n for (const file of lockFiles) {\n if (fs.existsSync(path.join(dir, file))) {\n return file;\n }\n }\n const parentDir = path.resolve(dir, '..');\n if (parentDir !== dir) {\n return this.findLockFile(parentDir);\n }\n return null;\n }\n\n private getPackageManager(): PackageManager {\n const lockFile = this.findLockFile(process.cwd());\n switch (lockFile) {\n case 'pnpm-lock.yaml':\n return 'pnpm';\n case 'package-lock.json':\n return 'npm';\n case 'yarn.lock':\n return 'yarn';\n case 'bun.lock':\n case 'bun.lockb':\n return 'bun';\n default:\n return 'npm';\n }\n }\n\n public async installPackages(packages: string[]) {\n const pm = this.packageManager;\n const installCommand = getPackageManagerAddCommand(pm);\n\n const packageList = packages.join(' ');\n return execa(`${pm} ${installCommand} ${packageList}`, {\n all: true,\n shell: true,\n stdio: 'pipe',\n });\n }\n\n public async checkDependencies(dependencies: string[]): Promise<string> {\n try {\n const packageJsonPath = path.join(process.cwd(), 'package.json');\n\n try {\n await fsPromises.access(packageJsonPath);\n } catch {\n return 'No package.json file found in the current directory';\n }\n\n const packageJson = JSON.parse(await fsPromises.readFile(packageJsonPath, 'utf-8'));\n for (const dependency of dependencies) {\n if (!packageJson.dependencies || !packageJson.dependencies[dependency]) {\n return `Please install ${dependency} before running this command (${this.packageManager} install ${dependency})`;\n }\n }\n\n return 'ok';\n } catch (err) {\n console.error(err);\n return 'Could not check dependencies';\n }\n }\n\n public async getProjectName() {\n try {\n const packageJsonPath = path.join(process.cwd(), 'package.json');\n const packageJson = await fsPromises.readFile(packageJsonPath, 'utf-8');\n const pkg = JSON.parse(packageJson);\n return pkg.name;\n } catch (err) {\n throw err;\n }\n }\n\n public async addScriptsToPackageJson(scripts: Record<string, string>) {\n const packageJson = JSON.parse(await fsPromises.readFile('package.json', 'utf-8'));\n packageJson.scripts = {\n ...packageJson.scripts,\n ...scripts,\n };\n await fsPromises.writeFile('package.json', JSON.stringify(packageJson, null, 2));\n }\n}\n","export abstract class EnvService {\n abstract getEnvValue(key: string): Promise<string | null>;\n abstract setEnvValue(key: string, value: string): Promise<void>;\n}\n","import * as fs from 'node:fs';\n\nimport { EnvService } from './service.env';\n\n// TODO: Refactor (copied from admin)\nexport class FileEnvService extends EnvService {\n private filePath: string;\n\n constructor(filePath: string) {\n super();\n this.filePath = filePath;\n }\n\n private readFile(filePath: string): Promise<string> {\n return new Promise((resolve, reject) => {\n fs.readFile(filePath, 'utf8', (err: NodeJS.ErrnoException | null, data: string) => {\n if (err) reject(err);\n else resolve(data);\n });\n });\n }\n\n private writeFile({ filePath, data }: { filePath: string; data: string }): Promise<void> {\n return new Promise((resolve, reject) => {\n fs.writeFile(filePath, data, 'utf8', (err: NodeJS.ErrnoException | null) => {\n if (err) reject(err);\n else resolve();\n });\n });\n }\n\n private async updateEnvData({\n key,\n value,\n filePath = this.filePath,\n data,\n }: {\n key: string;\n value: string;\n filePath?: string;\n data: string;\n }): Promise<string> {\n const regex = new RegExp(`^${key}=.*$`, 'm');\n if (data.match(regex)) {\n data = data.replace(regex, `${key}=${value}`);\n } else {\n data += `\\n${key}=${value}`;\n }\n await this.writeFile({ filePath, data });\n console.info(`${key} set to ${value} in ENV file.`);\n return data;\n }\n\n async getEnvValue(key: string): Promise<string | null> {\n try {\n const data = await this.readFile(this.filePath);\n const regex = new RegExp(`^${key}=(.*)$`, 'm');\n const match = data.match(regex);\n return match?.[1] || null;\n } catch (err) {\n console.error(`Error reading ENV value: ${err}`);\n return null;\n }\n }\n\n async setEnvValue(key: string, value: string): Promise<void> {\n try {\n const data = await this.readFile(this.filePath);\n await this.updateEnvData({ key, value, data });\n } catch (err) {\n console.error(`Error writing ENV value: ${err}`);\n }\n }\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport fsExtra from 'fs-extra/esm';\n\nimport { FileEnvService } from './service.fileEnv';\n\nexport class FileService {\n /**\n *\n * @param inputFile the file in the starter files directory to copy\n * @param outputFilePath the destination path\n * @param replaceIfExists flag to replace if it exists\n * @returns\n */\n public async copyStarterFile(inputFile: string, outputFilePath: string, replaceIfExists?: boolean) {\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = path.dirname(__filename);\n const filePath = path.resolve(__dirname, 'starter-files', inputFile);\n const fileString = fs.readFileSync(filePath, 'utf8');\n\n if (fs.existsSync(outputFilePath) && !replaceIfExists) {\n console.info(`${outputFilePath} already exists`);\n return false;\n }\n\n await fsExtra.outputFile(outputFilePath, fileString);\n\n return true;\n }\n\n public async setupEnvFile({ dbUrl }: { dbUrl: string }) {\n const envPath = path.join(process.cwd(), '.env.development');\n\n await fsExtra.ensureFile(envPath);\n\n const fileEnvService = new FileEnvService(envPath);\n await fileEnvService.setEnvValue('DB_URL', dbUrl);\n }\n\n public getFirstExistingFile(files: string[]): string {\n for (const f of files) {\n if (fs.existsSync(f)) {\n return f;\n }\n }\n\n throw new Error('Missing required file, checked the following paths: ' + files.join(', '));\n }\n\n public replaceValuesInFile({\n filePath,\n replacements,\n }: {\n filePath: string;\n replacements: { search: string; replace: string }[];\n }) {\n let fileContent = fs.readFileSync(filePath, 'utf8');\n replacements.forEach(({ search, replace }) => {\n fileContent = fileContent.replaceAll(search, replace);\n });\n\n fs.writeFileSync(filePath, fileContent);\n }\n}\n","import child_process from 'node:child_process';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\nimport util from 'node:util';\nimport * as p from '@clack/prompts';\nimport type { ModelRouterModelId } from '@mastra/core/llm';\nimport fsExtra from 'fs-extra/esm';\nimport color from 'picocolors';\nimport shellQuote from 'shell-quote';\nimport yoctoSpinner from 'yocto-spinner';\n\nimport { DepsService } from '../../services/service.deps';\nimport { FileService } from '../../services/service.file';\nimport {\n cursorGlobalMCPConfigPath,\n windsurfGlobalMCPConfigPath,\n antigravityGlobalMCPConfigPath,\n} from './mcp-docs-server-install';\nimport type { Editor } from './mcp-docs-server-install';\n\nconst exec = util.promisify(child_process.exec);\n\nexport const LLMProvider = ['openai', 'anthropic', 'groq', 'google', 'cerebras', 'mistral'] as const;\nexport const COMPONENTS = ['agents', 'workflows', 'tools', 'scorers'] as const;\n\nexport type LLMProvider = (typeof LLMProvider)[number];\nexport type Component = (typeof COMPONENTS)[number];\n\n/**\n * Type-guard to check if a value is a valid LLMProvider\n */\nexport function isValidLLMProvider(value: string): value is LLMProvider {\n return LLMProvider.includes(value as LLMProvider);\n}\n\n/**\n * Type-guard to check if a value contains only valid Components\n */\nexport function areValidComponents(values: string[]): values is Component[] {\n return values.every(value => COMPONENTS.includes(value as Component));\n}\n\nexport const getModelIdentifier = (llmProvider: LLMProvider): ModelRouterModelId => {\n let model: ModelRouterModelId = 'openai/gpt-5-mini';\n\n if (llmProvider === 'anthropic') {\n model = 'anthropic/claude-sonnet-4-5';\n } else if (llmProvider === 'groq') {\n model = 'groq/llama-3.3-70b-versatile';\n } else if (llmProvider === 'google') {\n model = 'google/gemini-2.5-pro';\n } else if (llmProvider === 'cerebras') {\n model = 'cerebras/llama-3.3-70b';\n } else if (llmProvider === 'mistral') {\n model = 'mistral/mistral-medium-2508';\n }\n\n return model;\n};\n\nexport async function writeAgentSample(\n llmProvider: LLMProvider,\n destPath: string,\n addExampleTool: boolean,\n addScorers: boolean,\n) {\n const modelString = getModelIdentifier(llmProvider);\n\n const instructions = `You are a helpful weather assistant that provides accurate weather information and can help planning activities based on the weather.\n\nYour primary function is to help users get weather details for specific locations. When responding:\n- Always ask for a location if none is provided\n- If the location name isn't in English, please translate it\n- If giving a location with multiple parts (e.g. \"New York, NY\"), use the most relevant part (e.g. \"New York\")\n- Include relevant details like humidity, wind conditions, and precipitation\n- Keep responses concise but informative\n- If the user asks for activities and provides the weather forecast, suggest activities based on the weather forecast.\n- If the user asks for activities, respond in the format they request.${addExampleTool ? '\\n\\nUse the weatherTool to fetch current weather data.' : ''}`;\n const imports = [\n `import { Agent } from '@mastra/core/agent';`,\n `import { Memory } from '@mastra/memory';`,\n addExampleTool ? `import { weatherTool } from '../tools/weather-tool';` : undefined,\n addScorers ? `import { scorers } from '../scorers/weather-scorer';` : undefined,\n ]\n .filter(Boolean)\n .join('\\n');\n const toolsConfig = addExampleTool ? ` tools: { weatherTool },\\n` : '';\n const scorersConfig = addScorers\n ? ` scorers: {\n toolCallAppropriateness: {\n scorer: scorers.toolCallAppropriatenessScorer,\n sampling: {\n type: 'ratio',\n rate: 1,\n },\n },\n completeness: {\n scorer: scorers.completenessScorer,\n sampling: {\n type: 'ratio',\n rate: 1,\n },\n },\n translation: {\n scorer: scorers.translationScorer,\n sampling: {\n type: 'ratio',\n rate: 1,\n },\n },\n },\n`\n : '';\n const content = `${imports}\n\nexport const weatherAgent = new Agent({\n id: 'weather-agent',\n name: 'Weather Agent',\n instructions: \\`${instructions}\\`,\n model: '${modelString}',\n${toolsConfig}${scorersConfig} memory: new Memory(),\n});\n`;\n\n await fs.writeFile(destPath, content);\n}\n\nexport async function writeWorkflowSample(destPath: string) {\n const content = `import { createStep, createWorkflow } from '@mastra/core/workflows';\nimport { z } from 'zod';\n\nconst forecastSchema = z.object({\n date: z.string(),\n maxTemp: z.number(),\n minTemp: z.number(),\n precipitationChance: z.number(),\n condition: z.string(),\n location: z.string(),\n})\n\nfunction getWeatherCondition(code: number): string {\n const conditions: Record<number, string> = {\n 0: 'Clear sky',\n 1: 'Mainly clear',\n 2: 'Partly cloudy',\n 3: 'Overcast',\n 45: 'Foggy',\n 48: 'Depositing rime fog',\n 51: 'Light drizzle',\n 53: 'Moderate drizzle',\n 55: 'Dense drizzle',\n 61: 'Slight rain',\n 63: 'Moderate rain',\n 65: 'Heavy rain',\n 71: 'Slight snow fall',\n 73: 'Moderate snow fall',\n 75: 'Heavy snow fall',\n 95: 'Thunderstorm',\n }\n return conditions[code] || 'Unknown'\n}\n\nconst fetchWeather = createStep({\n id: 'fetch-weather',\n description: 'Fetches weather forecast for a given city',\n inputSchema: z.object({\n city: z.string().describe('The city to get the weather for'),\n }),\n outputSchema: forecastSchema,\n execute: async ({ inputData }) => {\n if (!inputData) {\n throw new Error('Input data not found');\n }\n\n const geocodingUrl = \\`https://geocoding-api.open-meteo.com/v1/search?name=\\${encodeURIComponent(inputData.city)}&count=1\\`;\n const geocodingResponse = await fetch(geocodingUrl);\n const geocodingData = (await geocodingResponse.json()) as {\n results: { latitude: number; longitude: number; name: string }[];\n };\n\n if (!geocodingData.results?.[0]) {\n throw new Error(\\`Location '\\${inputData.city}' not found\\`);\n }\n\n const { latitude, longitude, name } = geocodingData.results[0];\n\n const weatherUrl = \\`https://api.open-meteo.com/v1/forecast?latitude=\\${latitude}&longitude=\\${longitude}&current=precipitation,weathercode&timezone=auto,&hourly=precipitation_probability,temperature_2m\\`;\n const response = await fetch(weatherUrl);\n const data = (await response.json()) as {\n current: {\n time: string\n precipitation: number\n weathercode: number\n }\n hourly: {\n precipitation_probability: number[]\n temperature_2m: number[]\n }\n }\n\n const forecast = {\n date: new Date().toISOString(),\n maxTemp: Math.max(...data.hourly.temperature_2m),\n minTemp: Math.min(...data.hourly.temperature_2m),\n condition: getWeatherCondition(data.current.weathercode),\n precipitationChance: data.hourly.precipitation_probability.reduce(\n (acc, curr) => Math.max(acc, curr),\n 0\n ),\n location: name\n }\n\n return forecast;\n },\n});\n\n\nconst planActivities = createStep({\n id: 'plan-activities',\n description: 'Suggests activities based on weather conditions',\n inputSchema: forecastSchema,\n outputSchema: z.object({\n activities: z.string(),\n }),\n execute: async ({ inputData, mastra }) => {\n const forecast = inputData\n\n if (!forecast) {\n throw new Error('Forecast data not found')\n }\n\n const agent = mastra?.getAgent('weatherAgent');\n if (!agent) {\n throw new Error('Weather agent not found');\n }\n\n const prompt = \\`Based on the following weather forecast for \\${forecast.location}, suggest appropriate activities:\n \\${JSON.stringify(forecast, null, 2)}\n For each day in the forecast, structure your response exactly as follows:\n\n 📅 [Day, Month Date, Year]\n ═══════════════════════════\n\n 🌡️ WEATHER SUMMARY\n • Conditions: [brief description]\n • Temperature: [X°C/Y°F to A°C/B°F]\n • Precipitation: [X% chance]\n\n 🌅 MORNING ACTIVITIES\n Outdoor:\n • [Activity Name] - [Brief description including specific location/route]\n Best timing: [specific time range]\n Note: [relevant weather consideration]\n\n 🌞 AFTERNOON ACTIVITIES\n Outdoor:\n • [Activity Name] - [Brief description including specific location/route]\n Best timing: [specific time range]\n Note: [relevant weather consideration]\n\n 🏠 INDOOR ALTERNATIVES\n • [Activity Name] - [Brief description including specific venue]\n Ideal for: [weather condition that would trigger this alternative]\n\n ⚠️ SPECIAL CONSIDERATIONS\n • [Any relevant weather warnings, UV index, wind conditions, etc.]\n\n Guidelines:\n - Suggest 2-3 time-specific outdoor activities per day\n - Include 1-2 indoor backup options\n - For precipitation >50%, lead with indoor activities\n - All activities must be specific to the location\n - Include specific venues, trails, or locations\n - Consider activity intensity based on temperature\n - Keep descriptions concise but informative\n\n Maintain this exact formatting for consistency, using the emoji and section headers as shown.\\`;\n\n const response = await agent.stream([\n {\n role: 'user',\n content: prompt,\n },\n ]);\n\n let activitiesText = '';\n\n for await (const chunk of response.textStream) {\n process.stdout.write(chunk);\n activitiesText += chunk;\n }\n\n return {\n activities: activitiesText,\n };\n },\n});\n\nconst weatherWorkflow = createWorkflow({\n id: 'weather-workflow',\n inputSchema: z.object({\n city: z.string().describe('The city to get the weather for'),\n }),\n outputSchema: z.object({\n activities: z.string(),\n })\n})\n .then(fetchWeather)\n .then(planActivities);\n\nweatherWorkflow.commit();\n\nexport { weatherWorkflow };`;\n\n await fs.writeFile(destPath, content);\n}\n\nexport async function writeToolSample(destPath: string) {\n const fileService = new FileService();\n await fileService.copyStarterFile('tools.ts', destPath);\n}\n\nexport async function writeScorersSample(llmProvider: LLMProvider, destPath: string) {\n const modelString = getModelIdentifier(llmProvider);\n const content = `import { z } from 'zod';\nimport { createToolCallAccuracyScorerCode } from '@mastra/evals/scorers/prebuilt';\nimport { createCompletenessScorer } from '@mastra/evals/scorers/prebuilt';\nimport { getAssistantMessageFromRunOutput, getUserMessageFromRunInput } from '@mastra/evals/scorers/utils';\nimport { createScorer } from '@mastra/core/evals';\n\nexport const toolCallAppropriatenessScorer = createToolCallAccuracyScorerCode({\n expectedTool: 'weatherTool',\n strictMode: false,\n});\n\nexport const completenessScorer = createCompletenessScorer();\n\n// Custom LLM-judged scorer: evaluates if non-English locations are translated appropriately\nexport const translationScorer = createScorer({\n id: 'translation-quality-scorer',\n name: 'Translation Quality',\n description: 'Checks that non-English location names are translated and used correctly',\n type: 'agent',\n judge: {\n model: '${modelString}',\n instructions:\n 'You are an expert evaluator of translation quality for geographic locations. ' +\n 'Determine whether the user text mentions a non-English location and whether the assistant correctly uses an English translation of that location. ' +\n 'Be lenient with transliteration differences and diacritics. ' +\n 'Return only the structured JSON matching the provided schema.',\n },\n})\n .preprocess(({ run }) => {\n const userText = getUserMessageFromRunInput(run.input) || '';\n const assistantText = getAssistantMessageFromRunOutput(run.output) || '';\n return { userText, assistantText };\n })\n .analyze({\n description: 'Extract location names and detect language/translation adequacy',\n outputSchema: z.object({\n nonEnglish: z.boolean(),\n translated: z.boolean(),\n confidence: z.number().min(0).max(1).default(1),\n explanation: z.string().default(''),\n }),\n createPrompt: ({ results }) => \\`\n You are evaluating if a weather assistant correctly handled translation of a non-English location.\n User text:\n \"\"\"\n \\${results.preprocessStepResult.userText}\n \"\"\"\n Assistant response:\n \"\"\"\n \\${results.preprocessStepResult.assistantText}\n \"\"\"\n Tasks:\n 1) Identify if the user mentioned a location that appears non-English.\n 2) If non-English, check whether the assistant used a correct English translation of that location in its response.\n 3) Be lenient with transliteration differences (e.g., accents/diacritics).\n Return JSON with fields:\n {\n \"nonEnglish\": boolean,\n \"translated\": boolean,\n \"confidence\": number, // 0-1\n \"explanation\": string\n }\n \\`,\n })\n .generateScore(({ results }) => {\n const r = (results as any)?.analyzeStepResult || {};\n if (!r.nonEnglish) return 1; // If not applicable, full credit\n if (r.translated) return Math.max(0, Math.min(1, 0.7 + 0.3 * (r.confidence ?? 1)));\n return 0; // Non-English but not translated\n })\n .generateReason(({ results, score }) => {\n const r = (results as any)?.analyzeStepResult || {};\n return \\`Translation scoring: nonEnglish=\\${r.nonEnglish ?? false}, translated=\\${r.translated ?? false}, confidence=\\${r.confidence ?? 0}. Score=\\${score}. \\${r.explanation ?? ''}\\`;\n });\n\nexport const scorers = {\n toolCallAppropriatenessScorer,\n completenessScorer,\n translationScorer,\n};`;\n\n await fs.writeFile(destPath, content);\n}\n\nexport async function writeCodeSampleForComponents(\n llmprovider: LLMProvider,\n component: Component,\n destPath: string,\n importComponents: Component[],\n) {\n switch (component) {\n case 'agents':\n return writeAgentSample(\n llmprovider,\n destPath,\n importComponents.includes('tools'),\n importComponents.includes('scorers'),\n );\n case 'tools':\n return writeToolSample(destPath);\n case 'workflows':\n return writeWorkflowSample(destPath);\n case 'scorers':\n return writeScorersSample(llmprovider, destPath);\n default:\n return '';\n }\n}\n\nexport const createComponentsDir = async (dirPath: string, component: string) => {\n const componentPath = dirPath + `/${component}`;\n\n await fsExtra.ensureDir(componentPath);\n};\n\nexport const writeIndexFile = async ({\n dirPath,\n addAgent,\n addExample,\n addWorkflow,\n addScorers,\n}: {\n dirPath: string;\n addExample: boolean;\n addWorkflow: boolean;\n addAgent: boolean;\n addScorers: boolean;\n}) => {\n const indexPath = dirPath + '/index.ts';\n const destPath = path.join(indexPath);\n try {\n await fs.writeFile(destPath, '');\n const filteredExports = [\n addWorkflow ? `workflows: { weatherWorkflow },` : '',\n addAgent ? `agents: { weatherAgent },` : '',\n addScorers ? `scorers: { toolCallAppropriatenessScorer, completenessScorer, translationScorer },` : '',\n ].filter(Boolean);\n if (!addExample) {\n await fs.writeFile(\n destPath,\n `\nimport { Mastra } from '@mastra/core/mastra';\n\nexport const mastra = new Mastra()\n `,\n );\n\n return;\n }\n await fs.writeFile(\n destPath,\n `\nimport { Mastra } from '@mastra/core/mastra';\nimport { PinoLogger } from '@mastra/loggers';\nimport { LibSQLStore } from '@mastra/libsql';\nimport { DuckDBStore } from \"@mastra/duckdb\";\nimport { MastraCompositeStore } from '@mastra/core/storage';\nimport { Observability, MastraStorageExporter, MastraPlatformExporter, SensitiveDataFilter } from '@mastra/observability';\n${addWorkflow ? `import { weatherWorkflow } from './workflows/weather-workflow';` : ''}\n${addAgent ? `import { weatherAgent } from './agents/weather-agent';` : ''}\n${addScorers ? `import { toolCallAppropriatenessScorer, completenessScorer, translationScorer } from './scorers/weather-scorer';` : ''}\n\nexport const mastra = new Mastra({\n ${filteredExports.join('\\n ')}\n storage: new MastraCompositeStore({\n id: 'composite-storage',\n default: new LibSQLStore({\n id: \"mastra-storage\",\n url: \"file:./mastra.db\",\n }),\n domains: {\n observability: await new DuckDBStore().getStore('observability'),\n }\n }),\n logger: new PinoLogger({\n name: 'Mastra',\n level: 'info',\n }),\n observability: new Observability({\n configs: {\n default: {\n serviceName: 'mastra',\n exporters: [\n new MastraStorageExporter(), // Persists observability events to Mastra Storage\n new MastraPlatformExporter(), // Sends observability events to Mastra Platform (if MASTRA_CLOUD_ACCESS_TOKEN is set)\n ],\n spanOutputProcessors: [\n new SensitiveDataFilter(), // Redacts sensitive data like passwords, tokens, keys\n ],\n },\n },\n }),\n});\n`,\n );\n } catch (err) {\n throw err;\n }\n};\n\nexport const checkInitialization = async (dirPath: string) => {\n try {\n await fs.access(dirPath);\n return true;\n } catch {\n return false;\n }\n};\n\nexport const checkAndInstallCoreDeps = async (addExample: boolean, versionTag?: string) => {\n const spinner = yoctoSpinner({ text: 'Installing Mastra core dependencies' });\n let packages: Array<{ name: string; version: string }> = [];\n const mastraVersionTag = versionTag || 'latest';\n\n try {\n const depService = new DepsService();\n\n spinner.start();\n\n const needsCore = (await depService.checkDependencies(['@mastra/core'])) !== `ok`;\n const needsCli = (await depService.checkDependencies(['mastra'])) !== `ok`;\n const needsZod = (await depService.checkDependencies(['zod'])) !== `ok`;\n\n if (needsCore) {\n packages.push({ name: '@mastra/core', version: mastraVersionTag });\n }\n\n if (needsCli) {\n packages.push({ name: 'mastra', version: mastraVersionTag });\n }\n\n if (needsZod) {\n packages.push({ name: 'zod', version: '^4' });\n }\n\n if (addExample) {\n const needsLibsql = (await depService.checkDependencies(['@mastra/libsql'])) !== `ok`;\n\n if (needsLibsql) {\n packages.push({ name: '@mastra/libsql', version: mastraVersionTag });\n }\n }\n\n if (packages.length > 0) {\n await depService.installPackages(packages.map(pkg => `${pkg.name}@${pkg.version}`));\n }\n\n spinner.success('Successfully installed Mastra core dependencies');\n } catch (err) {\n spinner.error(`Failed to install core dependencies: ${err instanceof Error ? err.message : 'Unknown error'}`);\n }\n};\n\nexport const getAPIKey = async (provider: LLMProvider) => {\n let key = 'OPENAI_API_KEY';\n switch (provider) {\n case 'anthropic':\n key = 'ANTHROPIC_API_KEY';\n return key;\n case 'groq':\n key = 'GROQ_API_KEY';\n return key;\n case 'google':\n key = 'GOOGLE_GENERATIVE_AI_API_KEY';\n return key;\n case 'cerebras':\n key = 'CEREBRAS_API_KEY';\n return key;\n case 'mistral':\n key = 'MISTRAL_API_KEY';\n return key;\n default:\n return key;\n }\n};\n\nexport const writeAPIKey = async ({ provider, apiKey }: { provider: LLMProvider; apiKey?: string }) => {\n /**\n * If people skip entering an API key (because they e.g. have it in their environment already), we write to .env.example instead of .env so that they can immediately run Mastra without having to delete an .env file with an invalid key.\n */\n const envFileName = apiKey ? '.env' : '.env.example';\n\n const key = await getAPIKey(provider);\n const escapedKey = shellQuote.quote([key]);\n const escapedApiKey = shellQuote.quote([apiKey ? apiKey : 'your-api-key']);\n await exec(`echo ${escapedKey}=${escapedApiKey} >> ${envFileName}`);\n};\nexport const createMastraDir = async (directory: string): Promise<{ ok: true; dirPath: string } | { ok: false }> => {\n let dir = directory\n .trim()\n .split('/')\n .filter(item => item !== '');\n\n const dirPath = path.join(process.cwd(), ...dir, 'mastra');\n\n try {\n await fs.access(dirPath);\n return { ok: false };\n } catch {\n await fsExtra.ensureDir(dirPath);\n return { ok: true, dirPath };\n }\n};\n\nexport const writeCodeSample = async (\n dirPath: string,\n component: Component,\n llmProvider: LLMProvider,\n importComponents: Component[],\n) => {\n const destPath = dirPath + `/${component}/weather-${component.slice(0, -1)}.ts`;\n\n try {\n await writeCodeSampleForComponents(llmProvider, component, destPath, importComponents);\n } catch (err) {\n throw err;\n }\n};\n\nexport const LLM_PROVIDERS: { value: LLMProvider; label: string; hint?: string }[] = [\n { value: 'openai', label: 'OpenAI', hint: 'recommended' },\n { value: 'anthropic', label: 'Anthropic' },\n { value: 'groq', label: 'Groq' },\n { value: 'google', label: 'Google' },\n { value: 'cerebras', label: 'Cerebras' },\n { value: 'mistral', label: 'Mistral' },\n];\n\ninterface InteractivePromptArgs {\n options?: {\n showBanner?: boolean;\n };\n skip?: {\n directory?: boolean;\n llmProvider?: boolean;\n llmApiKey?: boolean;\n gitInit?: boolean;\n skills?: boolean;\n mcpServer?: boolean;\n };\n}\n\nexport const interactivePrompt = async (args: InteractivePromptArgs = {}) => {\n const { skip = {}, options: { showBanner = true } = {} } = args;\n\n if (showBanner) {\n p.intro(color.inverse(' Mastra Init '));\n }\n const mastraProject = await p.group(\n {\n directory: () =>\n skip?.directory\n ? undefined\n : p.text({\n message: 'Where should we create the Mastra files? (default: src/)',\n placeholder: 'src/',\n defaultValue: 'src/',\n }),\n llmProvider: () =>\n skip?.llmProvider\n ? undefined\n : p.select({\n message: 'Select a default provider:',\n options: LLM_PROVIDERS,\n }),\n llmApiKey: async ({ results: { llmProvider } }) => {\n if (skip?.llmApiKey) return undefined;\n\n const llmName = LLM_PROVIDERS.find(p => p.value === llmProvider)?.label || 'provider';\n const keyChoice = await p.select({\n message: `Enter your ${llmName} API key?`,\n options: [\n { value: 'skip', label: 'Skip for now', hint: 'default' },\n { value: 'enter', label: 'Enter API key' },\n ],\n initialValue: 'skip',\n });\n\n if (keyChoice === 'enter') {\n return p.password({\n message: 'Enter your API key:',\n mask: '*',\n clearOnError: true,\n validate: value => {\n if (!value || value.length === 0) return 'API key cannot be empty';\n },\n });\n }\n return undefined;\n },\n configureMastraToolingForAgents: async () => {\n if (skip?.skills && skip?.mcpServer) return { skills: undefined, mcpServer: undefined };\n\n const choice = await p.select({\n message: `Configure Mastra tooling for agents?`,\n options: [\n { value: 'skills', label: 'Skills', hint: 'recommended' },\n { value: 'mcp', label: 'MCP Docs Server' },\n ],\n initialValue: 'skills',\n });\n\n if (p.isCancel(choice)) {\n return { skills: undefined, mcpServer: undefined };\n }\n\n if (choice === 'skills') {\n // Popular agents\n const POPULAR_AGENTS: { value: string; label: string }[] = [\n { value: 'universal', label: 'Universal (Codex, Cursor, Gemini, GitHub, OpenCode)' },\n { value: 'claude-code', label: 'Claude Code' },\n ];\n\n // All agents (alphabetically)\n const ALL_AGENTS: { value: string; label: string }[] = [\n ...POPULAR_AGENTS,\n { value: 'adal', label: 'AdaL' },\n { value: 'antigravity', label: 'Antigravity' },\n { value: 'augment', label: 'Augment' },\n { value: 'codebuddy', label: 'CodeBuddy' },\n { value: 'command-code', label: 'Command Code' },\n { value: 'crush', label: 'Crush' },\n { value: 'droid', label: 'Droid' },\n { value: 'goose', label: 'Goose' },\n { value: 'iflow-cli', label: 'iFlow CLI' },\n { value: 'junie', label: 'Junie' },\n { value: 'kilo', label: 'Kilo Code' },\n { value: 'kiro-cli', label: 'Kiro CLI' },\n { value: 'kode', label: 'Kode' },\n { value: 'mcpjam', label: 'MCPJam' },\n { value: 'mistral-vibe', label: 'Mistral Vibe' },\n { value: 'mux', label: 'Mux' },\n { value: 'neovate', label: 'Neovate' },\n { value: 'openclaude', label: 'OpenClaude IDE' },\n { value: 'openclaw', label: 'OpenClaw' },\n { value: 'openhands', label: 'OpenHands' },\n { value: 'pi', label: 'Pi' },\n { value: 'pochi', label: 'Pochi' },\n { value: 'qoder', label: 'Qoder' },\n { value: 'qwen-code', label: 'Qwen Code' },\n { value: 'replit', label: 'Replit' },\n { value: 'roo', label: 'Roo Code' },\n { value: 'trae', label: 'Trae' },\n { value: 'trae-cn', label: 'Trae CN' },\n { value: 'windsurf', label: 'Windsurf' },\n { value: 'zencoder', label: 'Zencoder' },\n ];\n\n // Show popular agents first with \"Show all\" option\n const initialSelection = await p.select({\n message: `Select your agent:`,\n options: [...POPULAR_AGENTS, { value: '__show_all__', label: '+ Show all agents' }],\n initialValue: 'universal',\n });\n\n if (p.isCancel(initialSelection)) {\n return { skills: undefined, mcpServer: undefined };\n }\n\n let selectedAgents = new Set<string>();\n\n // If user selected \"Show all\", show full list\n if (initialSelection === '__show_all__') {\n const followUpSelection = await p.select({\n message: `Select your agent:`,\n options: ALL_AGENTS,\n });\n\n if (p.isCancel(followUpSelection)) {\n return { skills: undefined, mcpServer: undefined };\n }\n\n selectedAgents.add(followUpSelection);\n } else {\n selectedAgents.add(initialSelection);\n }\n\n // Always add \"universal\" type so that the definition there gets symlinked to the proprietary agent folders\n selectedAgents.add('universal');\n\n return { skills: Array.from(selectedAgents), mcpServer: undefined };\n }\n\n // If MCP selected, show editor sub-selection\n if (choice === 'mcp') {\n const editor = await p.select({\n message: `Which editor?`,\n options: [\n {\n value: 'cursor',\n label: 'Cursor (project only)',\n },\n {\n value: 'cursor-global',\n label: 'Cursor (global, all projects)',\n },\n {\n value: 'windsurf',\n label: 'Windsurf',\n },\n {\n value: 'vscode',\n label: 'VSCode',\n },\n {\n value: 'antigravity',\n label: 'Antigravity',\n },\n ] satisfies { value: Editor; label: string }[],\n });\n\n if (p.isCancel(editor)) {\n return { skills: undefined, mcpServer: undefined };\n }\n\n // Handle MCP editor selections with confirmations\n if (editor === `cursor`) {\n p.log.message(\n `\\nNote: you will need to go into Cursor Settings -> MCP Settings and manually enable the installed Mastra MCP server.\\n`,\n );\n }\n\n if (editor === `cursor-global`) {\n const confirm = await p.select({\n message: `Global install will add/update ${cursorGlobalMCPConfigPath} and make the Mastra docs MCP server available in all your Cursor projects. Continue?`,\n options: [\n { value: 'yes', label: 'Yes, I understand' },\n { value: 'no', label: 'No, cancel' },\n ],\n });\n if (confirm !== `yes`) {\n return { skills: undefined, mcpServer: undefined };\n }\n }\n\n if (editor === `windsurf`) {\n const confirm = await p.select({\n message: `Windsurf only supports a global MCP config (at ${windsurfGlobalMCPConfigPath}) is it ok to add/update that global config?\\nThis means the Mastra docs MCP server will be available in all your Windsurf projects.`,\n options: [\n { value: 'yes', label: 'Yes, I understand' },\n { value: 'no', label: 'No, cancel' },\n ],\n });\n if (confirm !== `yes`) {\n return { skills: undefined, mcpServer: undefined };\n }\n }\n\n if (editor === `antigravity`) {\n const confirm = await p.select({\n message: `Antigravity only supports a global MCP config (at ${antigravityGlobalMCPConfigPath}). Is it ok to add/update that global config?\\nThis will make the Mastra docs MCP server available in all Antigravity projects.`,\n options: [\n { value: 'yes', label: 'Yes, I understand' },\n { value: 'no', label: 'No, cancel' },\n ],\n });\n\n if (confirm !== `yes`) {\n return { skills: undefined, mcpServer: undefined };\n }\n }\n return { skills: undefined, mcpServer: editor };\n }\n\n return { skills: undefined, mcpServer: undefined };\n },\n initGit: async () => {\n if (skip?.gitInit) return false;\n\n return p.confirm({\n message: 'Initialize a new git repository?',\n initialValue: true,\n });\n },\n },\n {\n onCancel: () => {\n p.cancel('Operation cancelled.');\n process.exit(0);\n },\n },\n );\n\n // Flatten the configureMastraToolingForAgents return value\n const { configureMastraToolingForAgents, ...rest } = mastraProject;\n return {\n ...rest,\n skills: configureMastraToolingForAgents?.skills as string[] | undefined,\n mcpServer: configureMastraToolingForAgents?.mcpServer as Editor | undefined,\n };\n};\n\n/**\n * Check if the current directory has a package.json file. If not, we should alert the user to create one or run \"mastra create\" to create a new project. The package.json file is required to install dependencies in the next steps.\n */\nexport const checkForPkgJson = async () => {\n const cwd = process.cwd();\n const pkgJsonPath = path.join(cwd, 'package.json');\n\n try {\n await fs.access(pkgJsonPath);\n\n // Do nothing\n } catch {\n p.log.error(\n 'No package.json file found in the current directory. Please run \"npm init -y\" to create one, or run \"npx create-mastra@latest\" to create a new Mastra project.',\n );\n\n process.exit(1);\n }\n};\n\n/**\n * Generate content for AGENTS.md file\n */\nexport function generateAgentsMarkdown({ skills, mcpServer }: { skills?: string[]; mcpServer?: Editor }): string {\n const hasSkills = skills && skills.length > 0;\n const hasMcp = !!mcpServer;\n\n let content = `# AGENTS.md\n\nYou are a TypeScript developer experienced with the Mastra framework. You build AI agents, tools, workflows, and scorers. You follow strict TypeScript practices and always consult up-to-date Mastra documentation before making changes.\n\n`;\n\n // Add critical Mastra skill section if skills were installed\n if (hasSkills) {\n content += `\n## CRITICAL: Load \\`mastra\\` skill\n\n**BEFORE doing ANYTHING with Mastra, load the \\`mastra\\` skill FIRST.** Never rely on cached knowledge as Mastra's APIs change frequently between versions. Use the skill to read up-to-date documentation from \\`node_modules\\`.\n`;\n }\n\n content += `\n## Project Overview\n\nThis is a **Mastra** project written in TypeScript. Mastra is a framework for building AI-powered applications and agents with a modern TypeScript stack. The Node.js runtime is \\`>=22.13.0\\`.\n\n## Commands\n\n\\`\\`\\`bash\nnpm run dev # Start Mastra Studio at localhost:4111 (long-running, use a separate terminal)\nnpm run build # Build a production-ready server\n\\`\\`\\`\n\n## Project Structure\n\n| Folder | Description |\n| ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |\n| \\`src/mastra\\` | Entry point for all Mastra-related code and configuration. |\n| \\`src/mastra/agents\\` | Define and configure your agents - their behavior, goals, and tools. |\n| \\`src/mastra/workflows\\` | Define multi-step workflows that orchestrate agents and tools together. |\n| \\`src/mastra/tools\\` | Create reusable tools that your agents can call |\n| \\`src/mastra/mcp\\` | (Optional) Implement custom MCP servers to share your tools with external agents |\n| \\`src/mastra/scorers\\` | (Optional) Define scorers for evaluating agent performance over time |\n| \\`src/mastra/public\\` | (Optional) Contents are copied into the \\`.build/output\\` directory during the build process, making them available for serving at runtime |\n\n### Top-level files\n\nTop-level files define how your Mastra project is configured, built, and connected to its environment.\n\n| File | Description |\n| --------------------- | ----------------------------------------------------------------------------------------------------------------- |\n| \\`src/mastra/index.ts\\` | Central entry point where you configure and initialize Mastra. |\n| \\`.env.example\\` | Template for environment variables - copy and rename to \\`.env\\` to add your secret [model provider](/models) keys. |\n| \\`package.json\\` | Defines project metadata, dependencies, and available npm scripts. |\n| \\`tsconfig.json\\` | Configures TypeScript options such as path aliases, compiler settings, and build output. |\n\n## Boundaries\n\n### Always do\n\n- Load the \\`mastra\\` skill before any Mastra-related work\n- Register new agents, tools, workflows, and scorers in \\`src/mastra/index.ts\\`\n- Use schemas for tool inputs and outputs\n- Run \\`npm run build\\` to verify changes compile\n\n### Never do\n\n- Never commit \\`.env\\` files or secrets\n- Never modify \\`node_modules\\` or Mastra's database files directly\n- Never hardcode API keys (always use environment variables)\n`;\n\n // Add MCP section if MCP server was configured\n if (hasMcp) {\n const editorName =\n mcpServer === 'cursor-global' ? 'Cursor (global)' : mcpServer!.charAt(0).toUpperCase() + mcpServer!.slice(1);\n\n content += `## MCP Docs Server\n\nThis project has the Mastra MCP Docs Server configured for ${editorName}.\n\n### Using MCP Docs\n\nThe MCP server provides embedded documentation access within your editor:\n\n1. The server was automatically configured during project creation\n2. Restart your editor to load the MCP server\n3. Use the Mastra docs tools in your editor to access:\n - API references\n - Code examples\n - Integration guides\n\nLearn more in the [MCP Documentation](https://mastra.ai/docs/mcp/overview).\n\n`;\n }\n\n // Add resources section\n content += `## Resources\n\n- [Mastra Documentation](https://mastra.ai/llms.txt)\n- [Mastra .well-known skills discovery](https://mastra.ai/.well-known/skills/index.json)\n`;\n\n return content;\n}\n\n/**\n * Write AGENTS.md file to project root\n */\nexport async function writeAgentsMarkdown(options: { skills?: string[]; mcpServer?: Editor }): Promise<void> {\n const content = generateAgentsMarkdown(options);\n const filePath = path.join(process.cwd(), 'AGENTS.md');\n await fs.writeFile(filePath, content);\n}\n\n/**\n * Write CLAUDE.md file to project root\n */\nexport async function writeClaudeMarkdown(): Promise<void> {\n const filePath = path.join(process.cwd(), 'CLAUDE.md');\n await fs.writeFile(filePath, '@AGENTS.md');\n}\n","import { fileURLToPath } from 'node:url';\nimport { InvalidArgumentError } from 'commander';\nimport { execa } from 'execa';\nimport fsExtra from 'fs-extra';\nimport type { PackageManager } from '../utils/package-manager';\nimport { EDITOR, isValidEditor } from './init/mcp-docs-server-install';\nimport { areValidComponents, COMPONENTS, isValidLLMProvider, LLMProvider } from './init/utils';\n\nexport function getPackageManager(): PackageManager {\n const userAgent = process.env.npm_config_user_agent || '';\n const execPath = process.env.npm_execpath || '';\n\n // Check user agent first\n if (userAgent.includes('bun')) {\n return 'bun';\n }\n if (userAgent.includes('yarn')) {\n return 'yarn';\n }\n if (userAgent.includes('pnpm')) {\n return 'pnpm';\n }\n if (userAgent.includes('npm')) {\n return 'npm';\n }\n\n // Fallback to execpath check\n if (execPath.includes('bun')) {\n return 'bun';\n }\n if (execPath.includes('yarn')) {\n return 'yarn';\n }\n if (execPath.includes('pnpm')) {\n return 'pnpm';\n }\n if (execPath.includes('npm')) {\n return 'npm';\n }\n\n return 'npm'; // Default fallback\n}\n\nexport function parseMcp(value: string) {\n if (!isValidEditor(value)) {\n throw new InvalidArgumentError(`Choose a valid value: ${EDITOR.join(', ')}`);\n }\n return value;\n}\n\nexport function parseSkills(value: string) {\n // Skills flag accepts comma-separated agent names\n return value\n .split(',')\n .map(s => s.trim())\n .filter(Boolean);\n}\n\nexport function parseComponents(value: string) {\n const parsedValue = value.split(',');\n\n if (!areValidComponents(parsedValue)) {\n throw new InvalidArgumentError(`Choose valid components: ${COMPONENTS.join(', ')}`);\n }\n\n return parsedValue;\n}\n\nexport function parseLlmProvider(value: string) {\n if (!isValidLLMProvider(value)) {\n throw new InvalidArgumentError(`Choose a valid provider: ${LLMProvider.join(', ')}`);\n }\n return value;\n}\n\nexport function shouldSkipDotenvLoading(): boolean {\n return process.env.MASTRA_SKIP_DOTENV === 'true' || process.env.MASTRA_SKIP_DOTENV === '1';\n}\n\n/**\n * Get the version tag (e.g., 'beta', 'latest') for the currently running mastra CLI.\n * This queries npm dist-tags to find which tag corresponds to the current version.\n */\nexport async function getVersionTag(): Promise<string | undefined> {\n try {\n const pkgPath = fileURLToPath(import.meta.resolve('mastra/package.json'));\n const json = await fsExtra.readJSON(pkgPath);\n const currentVersion = json.version;\n\n const { stdout } = await execa('npm', ['dist-tag', 'ls', 'mastra'], {\n cwd: import.meta.dirname,\n });\n const tagLine = stdout.split('\\n').find((distLine: string) => distLine.endsWith(`: ${currentVersion}`));\n const tag = tagLine ? tagLine.split(':')[0]?.trim() : undefined;\n\n return tag;\n } catch {\n // If we can't determine the tag, return undefined (will use default/latest)\n return undefined;\n }\n}\n\n/**\n * Check if the current directory already has git initialized.\n */\nexport async function isGitInitialized({ cwd }: { cwd: string }): Promise<boolean> {\n try {\n await execa('git', ['rev-parse', '--is-inside-work-tree'], { cwd, stdio: 'ignore' });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Initialize a git repository in the specified directory.\n */\nexport async function gitInit({ cwd }: { cwd: string }) {\n await execa('git', ['init'], { cwd, stdio: 'ignore' });\n await execa('git', ['add', '-A'], { cwd, stdio: 'ignore' });\n await execa(\n 'git',\n [\n 'commit',\n '-m',\n '\"Initial commit from Mastra\"',\n '--author=\"dane-ai-mastra[bot] <dane-ai-mastra[bot]@users.noreply.github.com>\"',\n ],\n { cwd, stdio: 'ignore' },\n );\n}\n","import { randomUUID } from 'node:crypto';\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { PostHog } from 'posthog-node';\nimport { getPackageManager } from '../commands/utils.js';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\ninterface CommandData {\n command: string;\n args?: Record<string, unknown>;\n durationMs?: number;\n status: 'success' | 'error';\n error?: string;\n}\n\nexport type CLI_ORIGIN = 'mastra-cloud' | 'oss';\n\nlet analyticsInstance: PosthogAnalytics | null = null;\n\nexport function getAnalytics(): PosthogAnalytics | null {\n return analyticsInstance;\n}\n\nexport function setAnalytics(instance: PosthogAnalytics): void {\n analyticsInstance = instance;\n}\n\nexport class PosthogAnalytics {\n private sessionId: string;\n private client?: PostHog;\n private distinctId: string;\n private version: string;\n private packageManager: string;\n\n constructor({\n version,\n apiKey,\n host = 'https://app.posthog.com',\n }: {\n version: string;\n apiKey: string;\n host: string;\n }) {\n this.version = version;\n this.packageManager = getPackageManager();\n const cliConfigPath = path.join(__dirname, 'mastra-cli.json');\n if (existsSync(cliConfigPath)) {\n try {\n const { distinctId, sessionId } = JSON.parse(readFileSync(cliConfigPath, 'utf-8'));\n this.distinctId = distinctId;\n this.sessionId = sessionId;\n } catch {\n this.sessionId = randomUUID();\n this.distinctId = this.getDistinctId();\n }\n\n this.writeCliConfig({\n distinctId: this.distinctId,\n sessionId: this.sessionId,\n });\n } else {\n this.sessionId = randomUUID();\n this.distinctId = this.getDistinctId();\n this.writeCliConfig({\n distinctId: this.distinctId,\n sessionId: this.sessionId,\n });\n }\n\n if (this.isTelemetryEnabled()) {\n this.initializePostHog(apiKey, host);\n }\n }\n\n private writeCliConfig({ distinctId, sessionId }: { distinctId: string; sessionId: string }): void {\n try {\n writeFileSync(path.join(__dirname, 'mastra-cli.json'), JSON.stringify({ distinctId, sessionId }));\n } catch {\n //swallow\n }\n }\n\n private initializePostHog(apiKey: string, host: string): void {\n this.client = new PostHog(apiKey, {\n host,\n flushAt: 1,\n flushInterval: 0,\n disableGeoip: false,\n });\n\n this.captureSessionStart();\n\n process.on('exit', () => {\n this.client?.flush().catch(() => {});\n });\n }\n\n private isTelemetryEnabled(): boolean {\n // Check environment variable first\n if (process.env.MASTRA_TELEMETRY_DISABLED) {\n return false;\n }\n // Default to enabled\n return true;\n }\n\n private getDistinctId(): string {\n // Use machine-id or generate a persistent ID\n // This helps track unique CLI installations\n const machineId = os.hostname();\n return `mastra-${machineId}`;\n }\n\n private getSystemProperties(): Record<string, any> {\n return {\n os: process.platform,\n os_version: os.release(),\n node_version: process.version,\n platform: process.arch,\n session_id: this.sessionId,\n cli_version: this.version || 'unknown',\n machine_id: os.hostname(),\n package_manager: this.packageManager,\n };\n }\n private getDurationMs(startTime: [number, number]): number {\n const [seconds, nanoseconds] = process.hrtime(startTime);\n return seconds * 1000 + nanoseconds / 1_000_000;\n }\n\n private captureSessionStart(): void {\n if (!this.client) {\n return;\n }\n\n this.client.capture({\n distinctId: this.distinctId,\n event: 'cli_session_start',\n properties: {\n ...this.getSystemProperties(),\n },\n });\n }\n\n trackEvent(eventName: string, properties?: Record<string, any>): void {\n try {\n if (!this.client) {\n return;\n }\n\n this.client.capture({\n distinctId: this.distinctId,\n event: eventName,\n properties: {\n ...this.getSystemProperties(),\n ...properties,\n },\n });\n } catch {\n //swallow\n }\n }\n\n trackCommand(options: {\n command: string;\n args?: Record<string, unknown>;\n durationMs?: number;\n status?: 'success' | 'error';\n error?: string;\n origin?: CLI_ORIGIN;\n }): void {\n try {\n if (!this.client) {\n return;\n }\n\n const commandData: CommandData = {\n command: options.command,\n status: options.status || 'success',\n };\n\n if (options.args) {\n commandData.args = options.args;\n }\n\n if (options.durationMs) {\n commandData.durationMs = options.durationMs;\n }\n\n if (options.error) {\n commandData.error = options.error;\n }\n\n this.client.capture({\n distinctId: this.distinctId,\n event: 'cli_command',\n properties: {\n ...this.getSystemProperties(),\n ...commandData,\n origin: options?.origin || 'oss',\n },\n });\n } catch {\n //swallow\n }\n }\n\n // Helper method to wrap command execution with timing\n async trackCommandExecution<T>({\n command,\n args,\n execution,\n origin,\n }: {\n command: string;\n args: Record<string, unknown>;\n execution: () => Promise<T>;\n origin?: CLI_ORIGIN;\n }): Promise<T> {\n const startTime = process.hrtime();\n\n try {\n const result = await execution();\n const durationMs = this.getDurationMs(startTime);\n this.trackCommand({\n command,\n args,\n durationMs,\n status: 'success',\n origin,\n });\n\n return result;\n } catch (error) {\n const durationMs = this.getDurationMs(startTime);\n this.trackCommand({\n command,\n args,\n durationMs,\n status: 'error',\n error: error instanceof Error ? error.message : String(error),\n origin,\n });\n\n throw error;\n }\n }\n\n // Ensure PostHog client is shutdown properly\n async shutdown(timeoutMs?: number): Promise<void> {\n if (!this.client) {\n return;\n }\n try {\n await this.client.shutdown(timeoutMs);\n } catch {\n //swallow\n }\n }\n}\n"]}