mastracode 0.46.0-alpha.8 → 0.46.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.
- package/CHANGELOG.md +106 -0
- package/dist/cli.cjs +62 -9
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +62 -9
- package/dist/cli.js.map +1 -1
- package/dist/docs/SKILL.md +1 -1
- package/dist/docs/assets/SOURCE_MAP.json +1 -1
- package/dist/initial-prompt.d.ts +16 -0
- package/dist/initial-prompt.d.ts.map +1 -1
- package/dist/tui/mastra-tui.d.ts.map +1 -1
- package/dist/tui/model-packs/apply.d.ts +2 -16
- package/dist/tui/model-packs/apply.d.ts.map +1 -1
- package/dist/tui/state.d.ts +5 -0
- package/dist/tui/state.d.ts.map +1 -1
- package/dist/{tui-BqcIy2hd.js → tui-Cvs2FMoN.js} +17 -50
- package/dist/tui-Cvs2FMoN.js.map +1 -0
- package/dist/{tui-BEov2a70.cjs → tui-cSDF1a2H.cjs} +24 -57
- package/dist/tui-cSDF1a2H.cjs.map +1 -0
- package/dist/tui.cjs +1 -1
- package/dist/tui.js +1 -1
- package/package.json +14 -14
- package/dist/tui-BEov2a70.cjs.map +0 -1
- package/dist/tui-BqcIy2hd.js.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,111 @@
|
|
|
1
1
|
# mastracode
|
|
2
2
|
|
|
3
|
+
## 0.46.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- Refreshed the Mastra Code terminal UI. ([#25937](https://github.com/mastra-ai/mastra/pull/25937))
|
|
8
|
+
|
|
9
|
+
- **Header:** the Mastra logo in Braille next to the project info, replacing the block-letter banner.
|
|
10
|
+
- **Prompt and messages:** a borderless shaded prompt that fades into the terminal background, with a steady → marker. Sent messages sit on a panel sized to their text, and the prompt no longer jumps when a run starts or ends.
|
|
11
|
+
- **Status line:** one row (mode · model · context · location) that stays put while the agent works. Long paths shorten like zsh (`~/…/parent/dir`); on narrow terminals the location moves to a second row. A Working row above the prompt shows a pulsing dot, elapsed time and throughput, and reads "thinking" while the model reasons.
|
|
12
|
+
- **Tool calls:** a small • status row; when a call has output, the row and its output sit on a two-tone grey card. Long shell output is capped to 8 lines with a ctrl+e hint. Subagents, `!` shell commands and observational memory use the same blocks. Skill and command messages show a collapsed `skill /name` or `command /name` header (ctrl+e expands them), and quiet-mode shell groups keep their bordered box. Notifications render in soft grey; errors, notifications, goal checks and system reminders are left-bar cards.
|
|
13
|
+
- **Prompts:** questions, plan approval and tool approval appear inline in the chat as cards. Tool approval is now one row under the tool call instead of a pop-up, and answered questions keep their options in place with a ✓ on the choice, so the prompt below doesn't jump.
|
|
14
|
+
- **Setup:** /setup and first-run onboarding fill the terminal with the logo and a step indicator.
|
|
15
|
+
- **Colors:** a lighter mint accent on dark backgrounds, softer text for tool output and the status line, and panels shaded from your terminal's own background, keeping its tint (Solarized, Gruvbox and the like) and staying visible on pure-black backgrounds. Light terminals get one consistent green and readable code colors, and 256-color terminals get neutral grey panels.
|
|
16
|
+
- **Fixes:** file previews no longer drop a leading number from lines like `1. Step`, and a failed shell command's dot turns red.
|
|
17
|
+
|
|
18
|
+
- Compact rendering is now the only display mode in Mastra Code. The quiet mode toggle in `/settings` and the first-run "Try compact quiet mode?" prompt are gone. Tool calls, notifications and background completions always render as compact rows. Press Ctrl+E to expand them. ([#26576](https://github.com/mastra-ai/mastra/pull/26576))
|
|
19
|
+
|
|
20
|
+
The "Quiet mode tool preview lines" setting is now called **Preview lines** and is always shown in `/settings`. Your existing value carries over automatically. The old settings keys stay in your existing `settings.json`, so Mastra Code instances that are still running an older version when you upgrade keep their current display settings.
|
|
21
|
+
|
|
22
|
+
- Added a `--pack <id>` startup flag to the interactive TUI. It accepts a builtin pack id (`anthropic`, `openai`, `github-copilot`) or a saved custom pack by `custom:<name>` or bare name. Unknown ids fail fast with the list of valid packs. Startup uses the pack's models for the session and saves the pack as the global default. `--pack` takes precedence over `MASTRACODE_MODEL_ID`. ([#26691](https://github.com/mastra-ai/mastra/pull/26691))
|
|
23
|
+
|
|
24
|
+
**Example**
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
mastracode --pack anthropic
|
|
28
|
+
mastracode --pack custom:Kimi
|
|
29
|
+
mastracode --pack Kimi
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
### Patch Changes
|
|
33
|
+
|
|
34
|
+
- Fixed the update check treating a prerelease, such as `1.2.0-alpha.1`, as already up to date when its stable release (`1.2.0`) is out. `/update`, `mastracode update`, and the startup update notice now offer the stable release. ([#26455](https://github.com/mastra-ai/mastra/pull/26455))
|
|
35
|
+
|
|
36
|
+
- Use a consistent background for subagent-style tool blocks, including plugin questions, while preserving ordinary tool styling. ([#26503](https://github.com/mastra-ai/mastra/pull/26503))
|
|
37
|
+
|
|
38
|
+
- Fixed messages queued during an active agent run being dropped when that run is aborted. Queued messages now start their own run after the abort instead of inheriting the aborted run's cancellation. ([#26280](https://github.com/mastra-ai/mastra/pull/26280))
|
|
39
|
+
|
|
40
|
+
- `/think` and the Agent Client Protocol (ACP) reasoning option now offer only the thinking levels the selected model runs. Claude Haiku 4.5 no longer offers Max, which sent the same thinking budget as Extra high. Models that cannot think, such as Claude 3.5 Haiku, Gemini 2.0 Flash or GPT-4o, offer only Off. Models that can only turn thinking on or off, such as GLM-4.6, offer Off and High. `/think` marks the level your saved setting runs at as current. ([#26229](https://github.com/mastra-ai/mastra/pull/26229))
|
|
41
|
+
|
|
42
|
+
Switching models in ACP keeps your saved level. The reasoning option shows the level the new model runs, and switching back restores the saved level: Extra high on Claude Opus 4.7 runs as High on Claude Sonnet 4.6, and is Extra high again when you switch back.
|
|
43
|
+
|
|
44
|
+
- Fixed `mastracode update` and `mastracode upgrade` starting a chat with that word as the prompt. They now install the latest version of Mastra Code and exit, printing the command to run manually if the update fails or doesn't change the running install. Added `/upgrade` as an alias for `/update` in the TUI. ([#26455](https://github.com/mastra-ai/mastra/pull/26455))
|
|
45
|
+
|
|
46
|
+
```sh
|
|
47
|
+
mastracode update
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Refreshed how updates look, in the shell and in `/update`:
|
|
51
|
+
|
|
52
|
+
- A spinner with elapsed time while checking and installing, instead of a static "Updating…" line.
|
|
53
|
+
- A short header with the version change, then a single ✓, ✗ or ! result line.
|
|
54
|
+
- Failures show the package manager's error in muted text and the exact command to run yourself, instead of one red error block.
|
|
55
|
+
|
|
56
|
+
- Fixed Ctrl+C discarding slash commands queued with Ctrl+F. Queued slash commands now still run after you interrupt the current response (#25748). ([#26280](https://github.com/mastra-ai/mastra/pull/26280))
|
|
57
|
+
|
|
58
|
+
- Defaulted Observer and Reflector models to Auto so they follow the active main model's provider unless explicitly pinned. Observer and Reflector choices you already saved stay pinned after upgrading, unless the active model pack sets its own memory model; choose Auto in `/om` to switch a role back. Added effective-model display and independent reset controls, and removed the observational-memory model choice from onboarding. Signing in with `mastracode login` no longer pins memory models. ([#24508](https://github.com/mastra-ai/mastra/pull/24508))
|
|
59
|
+
|
|
60
|
+
A model pack's memory model now has three states in `/models`: not set (uses your `/om` settings), Auto, or a specific model. A pack's memory model applies to both roles while the pack is active, including roles pinned in `/om`, and `/om` and the status line show the model it selects.
|
|
61
|
+
|
|
62
|
+
- Fixed missing file paths in quiet tool errors when a tool's input finishes streaming before the next render. ([#26113](https://github.com/mastra-ai/mastra/pull/26113))
|
|
63
|
+
|
|
64
|
+
- Fixed restarted Mastra Code sessions staying unreachable to other agents for up to about 13 seconds. A session that was shutting down kept its threads claimed until it fully exited, and the restarted session waited up to 5 seconds between attempts to claim them. Shutdown in the TUI, headless mode and ACP now releases thread claims first, so a restarted session is reachable again within about a second. Retries are also capped at 1 second. ([#26292](https://github.com/mastra-ai/mastra/pull/26292))
|
|
65
|
+
|
|
66
|
+
Embedders that shut down a `createMastraCode()` result themselves can call the new `releaseThreadClaims()` at the start of their teardown:
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
const mastraCode = await createMastraCode(config);
|
|
70
|
+
|
|
71
|
+
// On shutdown, before stopping workers and closing storage:
|
|
72
|
+
mastraCode.releaseThreadClaims();
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
- Rearchitected an experimental memory feature. ([#26024](https://github.com/mastra-ai/mastra/pull/26024))
|
|
76
|
+
|
|
77
|
+
- Removed the "Starting on <account>" notice that was emitted at the start of each turn when using subscription accounts. Preferred-account routing is unchanged. ([#25937](https://github.com/mastra-ai/mastra/pull/25937))
|
|
78
|
+
|
|
79
|
+
- Updated dependencies [[`908f923`](https://github.com/mastra-ai/mastra/commit/908f92340e14f776d7a69edab244d0ae3cefe057), [`b196f30`](https://github.com/mastra-ai/mastra/commit/b196f30602005325e95bde29a9b7676aeea14c42), [`b801545`](https://github.com/mastra-ai/mastra/commit/b80154540bf557de296bcb6f068b5117b5d84ef9), [`a65d0c7`](https://github.com/mastra-ai/mastra/commit/a65d0c788824081f36ccd95078a8d1214ff687c4), [`4b8f1d7`](https://github.com/mastra-ai/mastra/commit/4b8f1d74adb2b1742fd10ebb1d24e863329075aa), [`9a511a4`](https://github.com/mastra-ai/mastra/commit/9a511a4ff5ac8349f4d4b64b0f432576fa3c8656), [`2233844`](https://github.com/mastra-ai/mastra/commit/223384452984718e16fc660d29f0d5d93a1ebaf2), [`eec3388`](https://github.com/mastra-ai/mastra/commit/eec3388f29248ecb71724e8ca0a9afef7a522629), [`a22fc0d`](https://github.com/mastra-ai/mastra/commit/a22fc0d1029860531282aec80d17ac0b76c5884e), [`eec3388`](https://github.com/mastra-ai/mastra/commit/eec3388f29248ecb71724e8ca0a9afef7a522629), [`cca0f8a`](https://github.com/mastra-ai/mastra/commit/cca0f8a543eca15c24be21c8ee43dc46fb7aefae), [`20f7f87`](https://github.com/mastra-ai/mastra/commit/20f7f878953cb0965962d1e83a463be5e4ba2c26), [`65b62c0`](https://github.com/mastra-ai/mastra/commit/65b62c04c28267ab81f7d6b92ed29ce0ef46671b), [`d4e6c7f`](https://github.com/mastra-ai/mastra/commit/d4e6c7fffdef836fc44276509596e78d7d785729), [`b801545`](https://github.com/mastra-ai/mastra/commit/b80154540bf557de296bcb6f068b5117b5d84ef9), [`ed0e355`](https://github.com/mastra-ai/mastra/commit/ed0e355205da51bac4d11b7a9553c95ef1f505f4), [`b93ce2e`](https://github.com/mastra-ai/mastra/commit/b93ce2ee034c6a0be511b717e1e043e875dca677), [`ddb53f2`](https://github.com/mastra-ai/mastra/commit/ddb53f26142ccf6177dec5392b6dc867ce177d15), [`72d9bcf`](https://github.com/mastra-ai/mastra/commit/72d9bcf404d08ed991221b1d53d6d327ee47f58b), [`8f51bae`](https://github.com/mastra-ai/mastra/commit/8f51bae55307c62f18d2b69da27270ebdf1f728f), [`6df693a`](https://github.com/mastra-ai/mastra/commit/6df693aa926482422ef447d8db058adef36a594b), [`42a3c74`](https://github.com/mastra-ai/mastra/commit/42a3c748085fee95d4e38e42a4ccbce891ce3e3f), [`918704f`](https://github.com/mastra-ai/mastra/commit/918704fd4608aa4d9d90d4d92c0a3429de2b880a), [`21eaa20`](https://github.com/mastra-ai/mastra/commit/21eaa208834ae36721324700023f88cec7cf5c01), [`4580309`](https://github.com/mastra-ai/mastra/commit/45803095e2aed7bf58d878eb206a767b9b0e2489), [`06e428d`](https://github.com/mastra-ai/mastra/commit/06e428d80ccbc54bb74eb6bd6f01a7fd4eddc45f), [`d0db35e`](https://github.com/mastra-ai/mastra/commit/d0db35e00be93f1339525188c102f73dea5867d8), [`b48ddcc`](https://github.com/mastra-ai/mastra/commit/b48ddcc7768c76f02d1dd4ed0f21d417a8b21418), [`578d2c4`](https://github.com/mastra-ai/mastra/commit/578d2c41fc83b13efd88165ff0105904434a6db4), [`b875985`](https://github.com/mastra-ai/mastra/commit/b87598584f0f2b008242ed1f458b7f72ba6d42d1), [`cf6446c`](https://github.com/mastra-ai/mastra/commit/cf6446cae036784bd6802e4bcca8f3cf34a9ca9f), [`a8f39b6`](https://github.com/mastra-ai/mastra/commit/a8f39b629d8bcd6659b61bf71bd5a5dd2f38ed12), [`34844fc`](https://github.com/mastra-ai/mastra/commit/34844fcc7aeff1ae867c0aeedcd990caa520c418), [`04a2433`](https://github.com/mastra-ai/mastra/commit/04a2433d8e533010e23c3af84421d52bd0b3a908), [`85cfc88`](https://github.com/mastra-ai/mastra/commit/85cfc88fc5f196ef97cd2334441cd30cac99bce1), [`f2073f6`](https://github.com/mastra-ai/mastra/commit/f2073f6f2fff59ffca7eeac67579093454a0e761), [`46bb6b2`](https://github.com/mastra-ai/mastra/commit/46bb6b29dd83cabb09cf720dd8a3655860bf5858), [`2bf5b78`](https://github.com/mastra-ai/mastra/commit/2bf5b78761af6606b42ae2e085722eb50cdbc839), [`dc28dbd`](https://github.com/mastra-ai/mastra/commit/dc28dbd89f7afa455a1985c7909adf42ddd6bd48), [`25b8b60`](https://github.com/mastra-ai/mastra/commit/25b8b6074cbb5f0c744e4edb4ce0c5ee1f3771d6), [`41bf075`](https://github.com/mastra-ai/mastra/commit/41bf0759e486ff7eb078ff9d83d532e086a16039), [`73e6b7c`](https://github.com/mastra-ai/mastra/commit/73e6b7c18ee19fbb31c6f9bad4ce23c16212876b), [`68fa51c`](https://github.com/mastra-ai/mastra/commit/68fa51cf57ee7a3b0914d5381870b60e81f0647e), [`faf79ea`](https://github.com/mastra-ai/mastra/commit/faf79ea0d1aa7b2265b070f5323339fa275ebb49), [`b801545`](https://github.com/mastra-ai/mastra/commit/b80154540bf557de296bcb6f068b5117b5d84ef9), [`fdd4587`](https://github.com/mastra-ai/mastra/commit/fdd458784211bc89f5da4837a7ba4a1a7485e3e5), [`a1793d7`](https://github.com/mastra-ai/mastra/commit/a1793d7d077ed450125628ede812897ecbf08c4c), [`3645c3d`](https://github.com/mastra-ai/mastra/commit/3645c3d67e0c1f40005035911103deba381d246a), [`a9c8af5`](https://github.com/mastra-ai/mastra/commit/a9c8af5b6b2449e4127ab30b662e79ac025cc4f0), [`028dc61`](https://github.com/mastra-ai/mastra/commit/028dc61f4802fad472603df1538c4ca126f8680f), [`f83023e`](https://github.com/mastra-ai/mastra/commit/f83023e66dc6cf50ffd3fe4007bb8945ec9b2826), [`e5688d2`](https://github.com/mastra-ai/mastra/commit/e5688d2945aff1e867eb8b9fc5f25393d6579216), [`1211fcf`](https://github.com/mastra-ai/mastra/commit/1211fcf499acbda22ca8d399ae820789c69609f2), [`6d1307a`](https://github.com/mastra-ai/mastra/commit/6d1307af4c33c9a2ac99c424b2adc9c153f6ba37), [`e2d49cd`](https://github.com/mastra-ai/mastra/commit/e2d49cd482b1eb3d3e5fb9828dac457ce8b02232), [`a1c0020`](https://github.com/mastra-ai/mastra/commit/a1c002066736e54a4b07c03968b0df19cf1afb03), [`c0540d2`](https://github.com/mastra-ai/mastra/commit/c0540d2dfccec3470eed3cab539221557abd1fc5), [`297e55e`](https://github.com/mastra-ai/mastra/commit/297e55ea3d0eef280c3776bec401584ce3c2bff2), [`e995603`](https://github.com/mastra-ai/mastra/commit/e995603f64d4f03d234e7f53cc3ab03d9dfea502), [`2f0c604`](https://github.com/mastra-ai/mastra/commit/2f0c604b802068a063689fec4d0db91daa80d7c9), [`85636a2`](https://github.com/mastra-ai/mastra/commit/85636a2341aca229feb83c72b730a0d50f2f1753), [`eec3388`](https://github.com/mastra-ai/mastra/commit/eec3388f29248ecb71724e8ca0a9afef7a522629), [`2ef4283`](https://github.com/mastra-ai/mastra/commit/2ef428340d1eda6c6c8cfba4b90a43b88739f098), [`d45b854`](https://github.com/mastra-ai/mastra/commit/d45b854640e9b3d7fe7434061be988359ac2f470), [`b801545`](https://github.com/mastra-ai/mastra/commit/b80154540bf557de296bcb6f068b5117b5d84ef9), [`a7404f9`](https://github.com/mastra-ai/mastra/commit/a7404f965b811a0eef35d41a5e69c91187eb0cf6), [`eec3388`](https://github.com/mastra-ai/mastra/commit/eec3388f29248ecb71724e8ca0a9afef7a522629), [`ef231f2`](https://github.com/mastra-ai/mastra/commit/ef231f27f1d1507f1d3cd6717aa1489263b2e10b), [`4324cd3`](https://github.com/mastra-ai/mastra/commit/4324cd38ee744eb46b85ce0a9d3f2e4a0657ca87), [`4324cd3`](https://github.com/mastra-ai/mastra/commit/4324cd38ee744eb46b85ce0a9d3f2e4a0657ca87), [`5068168`](https://github.com/mastra-ai/mastra/commit/50681683948fd55928d029a63f0de7e56976e1f4), [`956901a`](https://github.com/mastra-ai/mastra/commit/956901a36b84a85f3985d9e5956494749b7ea72c), [`92004fd`](https://github.com/mastra-ai/mastra/commit/92004fd001edd2a0647f2531e0daf76a5825fc00), [`b389368`](https://github.com/mastra-ai/mastra/commit/b389368b0574a6a575a5835a11fc41437b78b842), [`38643be`](https://github.com/mastra-ai/mastra/commit/38643beb41ab0d1f67b8754f057781022448a618), [`38643be`](https://github.com/mastra-ai/mastra/commit/38643beb41ab0d1f67b8754f057781022448a618), [`6c9ad80`](https://github.com/mastra-ai/mastra/commit/6c9ad808c8503e812a72a48827ce425b9e78970f), [`eec3388`](https://github.com/mastra-ai/mastra/commit/eec3388f29248ecb71724e8ca0a9afef7a522629), [`eda5b00`](https://github.com/mastra-ai/mastra/commit/eda5b0081bdc49cc17ac8fc1267fccabb5e7a33f), [`38643be`](https://github.com/mastra-ai/mastra/commit/38643beb41ab0d1f67b8754f057781022448a618), [`4324cd3`](https://github.com/mastra-ai/mastra/commit/4324cd38ee744eb46b85ce0a9d3f2e4a0657ca87), [`838fd4b`](https://github.com/mastra-ai/mastra/commit/838fd4b1526c5385424d8e147d3d1d37137f6a13), [`f9659a2`](https://github.com/mastra-ai/mastra/commit/f9659a2b6612cbecadac9533af64bae6267272b8), [`fdd4587`](https://github.com/mastra-ai/mastra/commit/fdd458784211bc89f5da4837a7ba4a1a7485e3e5), [`b801545`](https://github.com/mastra-ai/mastra/commit/b80154540bf557de296bcb6f068b5117b5d84ef9), [`eec3388`](https://github.com/mastra-ai/mastra/commit/eec3388f29248ecb71724e8ca0a9afef7a522629), [`85636a2`](https://github.com/mastra-ai/mastra/commit/85636a2341aca229feb83c72b730a0d50f2f1753), [`835e2cd`](https://github.com/mastra-ai/mastra/commit/835e2cdba8dbef6848f18bb73bbb8aa9dad6dddf), [`65b62c0`](https://github.com/mastra-ai/mastra/commit/65b62c04c28267ab81f7d6b92ed29ce0ef46671b), [`71f003a`](https://github.com/mastra-ai/mastra/commit/71f003afd305a6e81b1649e6e857a6b72486089f), [`0fca057`](https://github.com/mastra-ai/mastra/commit/0fca05756ac8409494d54c70106db2ef7dfc81fc), [`40fe078`](https://github.com/mastra-ai/mastra/commit/40fe078b30e4df383d65c9e0887236f900059d2f), [`57c3117`](https://github.com/mastra-ai/mastra/commit/57c3117dd4d0dd0ad0835edb1bf410b6ec76fba0), [`9db8229`](https://github.com/mastra-ai/mastra/commit/9db8229bc7c30133fb1c085f710f1fbf94e5d335), [`7a96951`](https://github.com/mastra-ai/mastra/commit/7a96951771a6aab850ceafefc73afe684ef24b21), [`3278e85`](https://github.com/mastra-ai/mastra/commit/3278e857ba50b6f29c53bf80069d15b2d3accd60), [`6c9ad80`](https://github.com/mastra-ai/mastra/commit/6c9ad808c8503e812a72a48827ce425b9e78970f), [`a3f884c`](https://github.com/mastra-ai/mastra/commit/a3f884c6fa230f9c75049f7105df5f1429fa406e), [`e89310a`](https://github.com/mastra-ai/mastra/commit/e89310a8db29a663a85c6a31a8c376cc8f59c129), [`7c0cf99`](https://github.com/mastra-ai/mastra/commit/7c0cf997ab2306a176aa84fe6f611574721120c3), [`46bb6b2`](https://github.com/mastra-ai/mastra/commit/46bb6b29dd83cabb09cf720dd8a3655860bf5858), [`a3269cd`](https://github.com/mastra-ai/mastra/commit/a3269cd4b92683780591ca782be491834787b861), [`152679c`](https://github.com/mastra-ai/mastra/commit/152679c4b74de8be29e5d932f6c4b35e79397516), [`18afca3`](https://github.com/mastra-ai/mastra/commit/18afca34ba6ab013152da61b2017dc443c2aa08b), [`9acbfa0`](https://github.com/mastra-ai/mastra/commit/9acbfa05394be0d21bb3dc6230f5be62c8e47de2), [`b6b3f49`](https://github.com/mastra-ai/mastra/commit/b6b3f49d35ce62b584d9753361a7db7c15045801), [`a2d52e1`](https://github.com/mastra-ai/mastra/commit/a2d52e1d6a1542e3eb994853145ffd113fd02c2f), [`3a7e3d0`](https://github.com/mastra-ai/mastra/commit/3a7e3d01211a7ad5696b242f033cd1a30b06912e), [`436ea9d`](https://github.com/mastra-ai/mastra/commit/436ea9d4fb8146250bb106fd0f0200ea1cfd47d5), [`aa95d15`](https://github.com/mastra-ai/mastra/commit/aa95d15913925da141d1b7f707c2fa4f45f7b317), [`a7a34bf`](https://github.com/mastra-ai/mastra/commit/a7a34bfcc2235daa6229d6783b3ad1a2eaa25c56), [`65b62c0`](https://github.com/mastra-ai/mastra/commit/65b62c04c28267ab81f7d6b92ed29ce0ef46671b), [`eec3388`](https://github.com/mastra-ai/mastra/commit/eec3388f29248ecb71724e8ca0a9afef7a522629), [`4416137`](https://github.com/mastra-ai/mastra/commit/4416137e6b9368c11fcb31edba3d1937cfe61a40), [`678e1c3`](https://github.com/mastra-ai/mastra/commit/678e1c36f9118165c3315c2fd739334d9138eff4), [`f2243ae`](https://github.com/mastra-ai/mastra/commit/f2243ae5e0d183fdbb8c8f3ff81fa86d32036a6c), [`70d59a9`](https://github.com/mastra-ai/mastra/commit/70d59a97fb2a5953c5853bf5f5fdfdc02d2337e7), [`ce79b99`](https://github.com/mastra-ai/mastra/commit/ce79b99663d2e59421412acbb647d57f81d1da66), [`eec3388`](https://github.com/mastra-ai/mastra/commit/eec3388f29248ecb71724e8ca0a9afef7a522629), [`005161a`](https://github.com/mastra-ai/mastra/commit/005161a90ac9a8d25a4f9b1edc95c139e5d295d9), [`14f9341`](https://github.com/mastra-ai/mastra/commit/14f934145150a2531abfc1c36d03909fd05b5c56), [`b329f0d`](https://github.com/mastra-ai/mastra/commit/b329f0d45ce719acdd8926263269de6c91e31305), [`539d0e6`](https://github.com/mastra-ai/mastra/commit/539d0e638c9eaa3b71d99df067061af4ddbb2045), [`46bb6b2`](https://github.com/mastra-ai/mastra/commit/46bb6b29dd83cabb09cf720dd8a3655860bf5858), [`38643be`](https://github.com/mastra-ai/mastra/commit/38643beb41ab0d1f67b8754f057781022448a618), [`956901a`](https://github.com/mastra-ai/mastra/commit/956901a36b84a85f3985d9e5956494749b7ea72c), [`c7283d7`](https://github.com/mastra-ai/mastra/commit/c7283d715d9c8a7f3d3afd904f402ea0d4d843c4), [`7cb014d`](https://github.com/mastra-ai/mastra/commit/7cb014d3bdd96739c4bd7ad968af34c6a88ced7e), [`fe99f41`](https://github.com/mastra-ai/mastra/commit/fe99f41ea293a172da840c89a782d13a7c7a7709), [`eec3388`](https://github.com/mastra-ai/mastra/commit/eec3388f29248ecb71724e8ca0a9afef7a522629), [`9f4ab32`](https://github.com/mastra-ai/mastra/commit/9f4ab3242bd686ff43c871fedeede1ed21260dbf), [`2558c00`](https://github.com/mastra-ai/mastra/commit/2558c00b338025de29f778ca72b6bd05e5726349), [`2f14b26`](https://github.com/mastra-ai/mastra/commit/2f14b267b06da7255ef7c131f1138993c39bd733), [`590d6ca`](https://github.com/mastra-ai/mastra/commit/590d6ca9fa6ccf8b55dcf2e98da080ee1a348f67), [`918704f`](https://github.com/mastra-ai/mastra/commit/918704fd4608aa4d9d90d4d92c0a3429de2b880a), [`1511a1d`](https://github.com/mastra-ai/mastra/commit/1511a1d65d9e2ccc08b4d6746f8e8053fc48549e), [`1511a1d`](https://github.com/mastra-ai/mastra/commit/1511a1d65d9e2ccc08b4d6746f8e8053fc48549e), [`1511a1d`](https://github.com/mastra-ai/mastra/commit/1511a1d65d9e2ccc08b4d6746f8e8053fc48549e), [`f431c23`](https://github.com/mastra-ai/mastra/commit/f431c2321cf186f09565c42ddba33ee40cb96b6d), [`ea7ca75`](https://github.com/mastra-ai/mastra/commit/ea7ca755a470f026606949567da32e69969ef16c), [`a831a8b`](https://github.com/mastra-ai/mastra/commit/a831a8be6b92cf7a549e7b9d851f3c4295d4431b), [`436ea9d`](https://github.com/mastra-ai/mastra/commit/436ea9d4fb8146250bb106fd0f0200ea1cfd47d5), [`cfaeff3`](https://github.com/mastra-ai/mastra/commit/cfaeff3e03d6743682a8db0c1c30c2dab11b3171), [`180bdc5`](https://github.com/mastra-ai/mastra/commit/180bdc5398e253ffae7eaff6330409d7f5254f8b), [`45a1ab7`](https://github.com/mastra-ai/mastra/commit/45a1ab7f300637be9d5b953d82b58f77b64c1b56), [`70d59a9`](https://github.com/mastra-ai/mastra/commit/70d59a97fb2a5953c5853bf5f5fdfdc02d2337e7), [`33a206d`](https://github.com/mastra-ai/mastra/commit/33a206d7d0a52d17ebab8db5224c5091c086c86d), [`38643be`](https://github.com/mastra-ai/mastra/commit/38643beb41ab0d1f67b8754f057781022448a618), [`7c34315`](https://github.com/mastra-ai/mastra/commit/7c343153b26755a4cdcdd7897d2b4bd2758c29d4)]:
|
|
80
|
+
- @mastra/core@1.76.0
|
|
81
|
+
- @mastra/code-sdk@1.12.0
|
|
82
|
+
- @mastra/memory@1.37.0
|
|
83
|
+
- @mastra/pg@1.31.0
|
|
84
|
+
- @mastra/observability@1.19.0
|
|
85
|
+
- @mastra/libsql@1.26.0
|
|
86
|
+
- @mastra/duckdb@1.14.0
|
|
87
|
+
- @mastra/mcp@2.3.0
|
|
88
|
+
|
|
89
|
+
## 0.46.0-alpha.9
|
|
90
|
+
|
|
91
|
+
### Minor Changes
|
|
92
|
+
|
|
93
|
+
- Added a `--pack <id>` startup flag to the interactive TUI. It accepts a builtin pack id (`anthropic`, `openai`, `github-copilot`) or a saved custom pack by `custom:<name>` or bare name. Unknown ids fail fast with the list of valid packs. Startup uses the pack's models for the session and saves the pack as the global default. `--pack` takes precedence over `MASTRACODE_MODEL_ID`. ([#26691](https://github.com/mastra-ai/mastra/pull/26691))
|
|
94
|
+
|
|
95
|
+
**Example**
|
|
96
|
+
|
|
97
|
+
```bash
|
|
98
|
+
mastracode --pack anthropic
|
|
99
|
+
mastracode --pack custom:Kimi
|
|
100
|
+
mastracode --pack Kimi
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
### Patch Changes
|
|
104
|
+
|
|
105
|
+
- Updated dependencies [[`a65d0c7`](https://github.com/mastra-ai/mastra/commit/a65d0c788824081f36ccd95078a8d1214ff687c4), [`fdd4587`](https://github.com/mastra-ai/mastra/commit/fdd458784211bc89f5da4837a7ba4a1a7485e3e5), [`fdd4587`](https://github.com/mastra-ai/mastra/commit/fdd458784211bc89f5da4837a7ba4a1a7485e3e5), [`e89310a`](https://github.com/mastra-ai/mastra/commit/e89310a8db29a663a85c6a31a8c376cc8f59c129), [`590d6ca`](https://github.com/mastra-ai/mastra/commit/590d6ca9fa6ccf8b55dcf2e98da080ee1a348f67)]:
|
|
106
|
+
- @mastra/core@1.76.0-alpha.9
|
|
107
|
+
- @mastra/code-sdk@1.12.0-alpha.9
|
|
108
|
+
|
|
3
109
|
## 0.46.0-alpha.8
|
|
4
110
|
|
|
5
111
|
### Patch Changes
|
package/dist/cli.cjs
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
const require_tui = require("./tui-
|
|
2
|
+
const require_tui = require("./tui-cSDF1a2H.cjs");
|
|
3
3
|
let _mastra_code_sdk = require("@mastra/code-sdk");
|
|
4
4
|
let fs = require("fs");
|
|
5
5
|
fs = require_tui.__toESM(fs, 1);
|
|
6
6
|
let _mastra_code_sdk_analytics = require("@mastra/code-sdk/analytics");
|
|
7
7
|
let _mastra_code_sdk_error_classification = require("@mastra/code-sdk/error-classification");
|
|
8
8
|
let _mastra_code_sdk_headless_index = require("@mastra/code-sdk/headless/index");
|
|
9
|
+
let _mastra_code_sdk_onboarding_pack_activation = require("@mastra/code-sdk/onboarding/pack-activation");
|
|
9
10
|
let _mastra_code_sdk_onboarding_settings = require("@mastra/code-sdk/onboarding/settings");
|
|
10
11
|
let _mastra_code_sdk_plugins_scaffold = require("@mastra/code-sdk/plugins/scaffold");
|
|
11
12
|
let _mastra_code_sdk_process_memory_diagnostics = require("@mastra/code-sdk/process-memory-diagnostics");
|
|
@@ -79,6 +80,41 @@ function initialMessageOptions(args, pipedInput) {
|
|
|
79
80
|
resumeSkipNotice: `Resumed the existing conversation for this directory, so ${pipedInput ? "the initial prompt and piped input were" : "the initial prompt was"} not sent. Use ${TUI_PROMPT_FLAG} to send ${pipedInput ? "them" : "it"} anyway.`
|
|
80
81
|
};
|
|
81
82
|
}
|
|
83
|
+
const PACK_FLAG = "--pack";
|
|
84
|
+
/**
|
|
85
|
+
* Extracts `--pack <id>` (or `--pack=<id>`) from argv. The pack id is validated
|
|
86
|
+
* later against the packs in settings (built-in ids, `custom:<name>`, or a bare
|
|
87
|
+
* custom-pack name); here we only strip the flag so other argv consumers never
|
|
88
|
+
* mistake the id for a positional prompt.
|
|
89
|
+
*/
|
|
90
|
+
function takePackFlag(argv) {
|
|
91
|
+
const rest = [];
|
|
92
|
+
let value;
|
|
93
|
+
let error;
|
|
94
|
+
for (let i = 0; i < argv.length; i++) {
|
|
95
|
+
const arg = argv[i];
|
|
96
|
+
if (arg === "--pack") {
|
|
97
|
+
const next = argv[++i];
|
|
98
|
+
if (next === void 0 || next.startsWith("-")) {
|
|
99
|
+
error = `${PACK_FLAG} needs a value`;
|
|
100
|
+
break;
|
|
101
|
+
}
|
|
102
|
+
value = next;
|
|
103
|
+
} else if (arg.startsWith(`--pack=`)) {
|
|
104
|
+
const inline = arg.slice(7);
|
|
105
|
+
if (inline === "" || inline.startsWith("-")) {
|
|
106
|
+
error = `${PACK_FLAG} needs a value`;
|
|
107
|
+
break;
|
|
108
|
+
}
|
|
109
|
+
value = inline;
|
|
110
|
+
} else rest.push(arg);
|
|
111
|
+
}
|
|
112
|
+
return {
|
|
113
|
+
argv: rest,
|
|
114
|
+
...value !== void 0 ? { value } : {},
|
|
115
|
+
...error ? { error } : {}
|
|
116
|
+
};
|
|
117
|
+
}
|
|
82
118
|
//#endregion
|
|
83
119
|
//#region src/process-memory-diagnostics-lifecycle.ts
|
|
84
120
|
async function startTuiProcessMemoryDiagnostics(env, warn, createSetup = _mastra_code_sdk_process_memory_diagnostics.createProcessMemoryDiagnosticsFromEnvironment) {
|
|
@@ -234,7 +270,7 @@ async function runUpdateCommand({ args = [], output = process.stdout, errorOutpu
|
|
|
234
270
|
//#endregion
|
|
235
271
|
//#region src/version.ts
|
|
236
272
|
function getCurrentVersion() {
|
|
237
|
-
return "0.46.0
|
|
273
|
+
return "0.46.0";
|
|
238
274
|
}
|
|
239
275
|
//#endregion
|
|
240
276
|
//#region src/main.ts
|
|
@@ -266,8 +302,8 @@ function isTruthyEnv(name) {
|
|
|
266
302
|
"on"
|
|
267
303
|
].includes(process.env[name]?.trim().toLowerCase() ?? "");
|
|
268
304
|
}
|
|
269
|
-
function resolveInitialStateFromEnv() {
|
|
270
|
-
const currentModelId = process.env.MASTRACODE_MODEL_ID?.trim();
|
|
305
|
+
function resolveInitialStateFromEnv(options = {}) {
|
|
306
|
+
const currentModelId = options.ignoreModelEnv ? void 0 : process.env.MASTRACODE_MODEL_ID?.trim();
|
|
271
307
|
const initialState = {};
|
|
272
308
|
if (currentModelId) initialState.currentModelId = currentModelId;
|
|
273
309
|
if (isTruthyEnv("MASTRACODE_YOLO")) initialState.yolo = true;
|
|
@@ -281,7 +317,7 @@ process.on("unhandledRejection", (reason) => {
|
|
|
281
317
|
if ((0, _mastra_code_sdk_error_classification.isStreamDestroyedError)(reason)) return;
|
|
282
318
|
handleFatalError(reason instanceof Error ? reason : new Error(String(reason)));
|
|
283
319
|
});
|
|
284
|
-
async function tuiMain(startupMessage = {}, resumeThreadId) {
|
|
320
|
+
async function tuiMain(startupMessage = {}, resumeThreadId, startupPackId) {
|
|
285
321
|
const settings = (0, _mastra_code_sdk_onboarding_settings.loadSettings)();
|
|
286
322
|
processMemoryDiagnostics = await startTuiProcessMemoryDiagnostics(process.env, (warning) => {
|
|
287
323
|
console.info(`⚠ ${warning}`);
|
|
@@ -291,7 +327,7 @@ async function tuiMain(startupMessage = {}, resumeThreadId) {
|
|
|
291
327
|
browserPromise ??= (0, _mastra_code_sdk_onboarding_settings.createBrowserFromSettings)(settings.browser, { chatModelId });
|
|
292
328
|
return browserPromise;
|
|
293
329
|
};
|
|
294
|
-
const initialState = resolveInitialStateFromEnv();
|
|
330
|
+
const initialState = resolveInitialStateFromEnv({ ignoreModelEnv: startupPackId !== void 0 });
|
|
295
331
|
const result = await (0, _mastra_code_sdk.createMastraCode)({
|
|
296
332
|
createInitialThread: false,
|
|
297
333
|
coAuthor: require_tui.TUI_CO_AUTHOR,
|
|
@@ -356,6 +392,7 @@ async function tuiMain(startupMessage = {}, resumeThreadId) {
|
|
|
356
392
|
version: getCurrentVersion(),
|
|
357
393
|
inlineQuestions: true,
|
|
358
394
|
initialModelOverride: Boolean(initialState?.currentModelId),
|
|
395
|
+
...startupPackId ? { initialPackId: startupPackId } : {},
|
|
359
396
|
...resumeThreadId ? { resumeThreadId } : {},
|
|
360
397
|
githubSignals: result.githubSignals,
|
|
361
398
|
backgroundToolsEnabled: result.backgroundToolsEnabled,
|
|
@@ -516,12 +553,18 @@ async function main() {
|
|
|
516
553
|
await new Promise((resolve) => process.stdout.write("", resolve));
|
|
517
554
|
return process.exit(code);
|
|
518
555
|
}
|
|
519
|
-
const
|
|
556
|
+
const packFlag = takePackFlag(process.argv);
|
|
557
|
+
if (packFlag.error) {
|
|
558
|
+
process.stderr.write(`${packFlag.error}\n`);
|
|
559
|
+
process.exit(1);
|
|
560
|
+
}
|
|
561
|
+
const initialPrompt = takeInitialPrompt(packFlag.argv, process.env);
|
|
520
562
|
if (initialPrompt.error) {
|
|
521
563
|
process.stderr.write(`${initialPrompt.error}\n`);
|
|
522
564
|
process.exit(1);
|
|
523
565
|
}
|
|
524
566
|
if (initialPrompt.flag) process.argv = initialPrompt.argv;
|
|
567
|
+
const tuiArgv = initialPrompt.flag ? initialPrompt.argv : packFlag.argv;
|
|
525
568
|
const rejectInitialPromptFlag = (reason) => {
|
|
526
569
|
if (!initialPrompt.flag) return;
|
|
527
570
|
process.stderr.write(`${initialPrompt.flag} starts the interactive TUI; ${reason}\n`);
|
|
@@ -529,7 +572,7 @@ async function main() {
|
|
|
529
572
|
};
|
|
530
573
|
let resumeThreadId;
|
|
531
574
|
try {
|
|
532
|
-
resumeThreadId = parseResumeThreadId(
|
|
575
|
+
resumeThreadId = parseResumeThreadId(tuiArgv.slice(2));
|
|
533
576
|
} catch (error) {
|
|
534
577
|
process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
|
|
535
578
|
process.exitCode = 1;
|
|
@@ -548,6 +591,16 @@ async function main() {
|
|
|
548
591
|
coAuthor: require_tui.TUI_CO_AUTHOR
|
|
549
592
|
});
|
|
550
593
|
}
|
|
594
|
+
let startupPackId;
|
|
595
|
+
if (packFlag.value !== void 0) {
|
|
596
|
+
const resolved = (0, _mastra_code_sdk_onboarding_pack_activation.resolveModePackArg)((0, _mastra_code_sdk_onboarding_settings.loadSettings)(), packFlag.value);
|
|
597
|
+
if ("error" in resolved) {
|
|
598
|
+
process.stderr.write(`Error: ${resolved.error}\n`);
|
|
599
|
+
process.exit(1);
|
|
600
|
+
}
|
|
601
|
+
startupPackId = resolved.packId;
|
|
602
|
+
if (process.env.MASTRACODE_MODEL_ID?.trim()) process.stderr.write("Note: --pack takes precedence over MASTRACODE_MODEL_ID for this session.\n");
|
|
603
|
+
}
|
|
551
604
|
if (shouldRejectResumeWithoutTTY(resumeThreadId, Boolean(process.stdin.isTTY))) {
|
|
552
605
|
process.stderr.write("mastracode resume requires an interactive terminal.\n");
|
|
553
606
|
process.exitCode = 1;
|
|
@@ -568,7 +621,7 @@ async function main() {
|
|
|
568
621
|
process.stderr.write(`${conflict}\n`);
|
|
569
622
|
process.exit(1);
|
|
570
623
|
}
|
|
571
|
-
return tuiMain(initialMessageOptions(initialPrompt, pipedInput), resumeThreadId);
|
|
624
|
+
return tuiMain(initialMessageOptions(initialPrompt, pipedInput), resumeThreadId, startupPackId);
|
|
572
625
|
}
|
|
573
626
|
main().catch((error) => {
|
|
574
627
|
handleFatalError(error);
|
package/dist/cli.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.cjs","names":["createProcessMemoryDiagnosticsFromEnvironment","chalk","Chalk","formatUpdateHeader","formatRegistryError","formatUpToDate","formatUpdateOutcome","formatInstallingLabel","TUI_CO_AUTHOR","detectTerminalTheme","MastraTUI"],"sources":["../src/initial-prompt.ts","../src/process-memory-diagnostics-lifecycle.ts","../src/resume-command.ts","../src/subagent-settings.ts","../src/update-command.ts","../src/version.ts","../src/main.ts"],"sourcesContent":["export const INITIAL_PROMPT_FLAG = '--tui-initial-prompt' as const;\nexport const INITIAL_PROMPT_ENV = 'MASTRACODE_TUI_INITIAL_PROMPT';\n\nexport const TUI_PROMPT_FLAG = '--tui-prompt' as const;\n\nexport type InitialPromptArgs = {\n /** argv with the flag and its value removed, so headless detection never mistakes the value for a prompt. */\n argv: string[];\n prompt?: string;\n /** Set when a flag was passed without a value, or both flags were passed. */\n error?: string;\n /** The flag the prompt came from; undefined when it came from the environment. */\n flag?: typeof INITIAL_PROMPT_FLAG | typeof TUI_PROMPT_FLAG;\n /**\n * `--tui-prompt` sends even when startup resumes an existing conversation;\n * `--tui-initial-prompt` and the environment variable only start a new one.\n */\n sendOnResume: boolean;\n};\n\n/**\n * Takes the interactive startup prompt from `--tui-initial-prompt <text>` or\n * `--tui-prompt <text>` (also `--flag=<text>`), falling back to\n * `MASTRACODE_TUI_INITIAL_PROMPT`.\n *\n * The environment variable is always removed from `env`: everything this\n * process spawns inherits its environment, and a nested Mastra Code (or any\n * shell the agent starts) must not send the same prompt again.\n */\nexport function takeInitialPrompt(argv: string[], env: NodeJS.ProcessEnv): InitialPromptArgs {\n const fromEnv = env[INITIAL_PROMPT_ENV];\n delete env[INITIAL_PROMPT_ENV];\n\n const rest: string[] = [];\n const found = new Map<NonNullable<InitialPromptArgs['flag']>, string>();\n let error: string | undefined;\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i]!;\n const flag = [INITIAL_PROMPT_FLAG, TUI_PROMPT_FLAG].find(f => arg === f || arg.startsWith(`${f}=`));\n if (!flag) {\n rest.push(arg);\n } else if (arg !== flag) {\n found.set(flag, arg.slice(flag.length + 1));\n } else if (argv[i + 1] === undefined) {\n error = `${flag} needs a value`;\n } else {\n found.set(flag, argv[++i]!);\n }\n }\n if (found.size > 1) error = `Use either ${INITIAL_PROMPT_FLAG} or ${TUI_PROMPT_FLAG}, not both`;\n\n const [flag, flagValue] = [...found][0] ?? [];\n const prompt = (flag ? flagValue : fromEnv)?.trim() || undefined;\n return { argv: rest, prompt, error, flag, sendOnResume: flag === TUI_PROMPT_FLAG };\n}\n\n/** The first message the TUI sends: the initial prompt, followed by any piped stdin. */\nexport function composeInitialMessage(prompt: string | undefined, pipedInput: string | null | undefined) {\n const piped = pipedInput ? `The following was piped via stdin:\\n\\n${pipedInput}` : undefined;\n if (prompt && piped) return `${prompt}\\n\\n${piped}`;\n return prompt ?? piped;\n}\n\n/**\n * Why a startup prompt can't be combined with piped stdin, if it can't.\n *\n * The first message is submitted like typed input, so a prompt starting with\n * `/` or `!` is dispatched as a command. Folding piped text into it would make\n * that text part of the command — skill arguments, or a shell script for `!`.\n */\nexport function pipedInputConflict(\n args: Pick<InitialPromptArgs, 'prompt' | 'flag'>,\n pipedInput: string | null | undefined,\n): string | undefined {\n if (!args.prompt || !pipedInput) return undefined;\n if (!args.prompt.startsWith('/') && !args.prompt.startsWith('!')) return undefined;\n const source = args.flag ?? INITIAL_PROMPT_ENV;\n return `${source} can't be combined with piped stdin when it is a slash command or starts with !`;\n}\n\n/** The TUI options for a startup prompt and/or piped stdin. */\nexport function initialMessageOptions(\n args: Pick<InitialPromptArgs, 'prompt' | 'sendOnResume'>,\n pipedInput?: string | null,\n): { initialMessage?: string; resumeSkipNotice?: string } {\n const initialMessage = composeInitialMessage(args.prompt, pipedInput);\n if (!initialMessage) return {};\n // Piped stdin on its own is always sent, as before.\n if (!args.prompt || args.sendOnResume) return { initialMessage };\n const skipped = pipedInput ? 'the initial prompt and piped input were' : 'the initial prompt was';\n return {\n initialMessage,\n resumeSkipNotice: `Resumed the existing conversation for this directory, so ${skipped} not sent. Use ${TUI_PROMPT_FLAG} to send ${pipedInput ? 'them' : 'it'} anyway.`,\n };\n}\n","import {\n createProcessMemoryDiagnosticsFromEnvironment,\n startConfiguredProcessMemoryDiagnostics,\n type ProcessMemoryDiagnostics,\n type ProcessMemoryDiagnosticsEnvironment,\n type ProcessMemoryDiagnosticsSetup,\n} from '@mastra/code-sdk/process-memory-diagnostics';\n\nexport async function startTuiProcessMemoryDiagnostics(\n env: ProcessMemoryDiagnosticsEnvironment,\n warn: (message: string) => void,\n createSetup: (\n env: ProcessMemoryDiagnosticsEnvironment,\n ) => ProcessMemoryDiagnosticsSetup = createProcessMemoryDiagnosticsFromEnvironment,\n): Promise<ProcessMemoryDiagnostics> {\n return startConfiguredProcessMemoryDiagnostics(createSetup(env), warn);\n}\n\nexport function createOneShotFatalErrorHandler(handle: (error: unknown) => void): (error: unknown) => void {\n let handlingFatalError = false;\n return error => {\n if (handlingFatalError) return;\n handlingFatalError = true;\n handle(error);\n };\n}\n\nexport function createShutdownCoordinator(\n cleanup: () => Promise<void>,\n exit: (exitCode: number) => never,\n timeoutMs = 5_000,\n): (exitCode: number) => Promise<void> {\n let shutdownPromise: Promise<void> | null = null;\n return exitCode => {\n shutdownPromise ??= (async () => {\n let timeout: ReturnType<typeof setTimeout> | undefined;\n await Promise.race([\n cleanup().catch(() => undefined),\n new Promise<void>(resolve => {\n timeout = setTimeout(resolve, timeoutMs);\n }),\n ]);\n if (timeout) clearTimeout(timeout);\n exit(exitCode);\n })();\n return shutdownPromise;\n };\n}\n","export function parseResumeThreadId(args: string[]): string | undefined {\n if (args[0] !== 'resume') return undefined;\n\n const threadId = args[1]?.trim();\n if (!threadId || args.length !== 2) {\n throw new Error('Usage: mastracode resume <thread-id>');\n }\n return threadId;\n}\n\nexport function shouldRunHeadless(\n argv: string[],\n resumeThreadId: string | undefined,\n hasHeadlessFlag: boolean,\n): boolean {\n return !resumeThreadId && (hasHeadlessFlag || argv.includes('--help') || argv.includes('-h'));\n}\n\nexport function shouldRejectResumeWithoutTTY(resumeThreadId: string | undefined, isTTY: boolean): boolean {\n return Boolean(resumeThreadId) && !isTTY;\n}\n\nexport function formatResumeHint(threadId: string): string {\n const hasControlCharacters = [...threadId].some(character => {\n const codePoint = character.codePointAt(0)!;\n return codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f);\n });\n const argument = /^[a-zA-Z0-9_-]+$/.test(threadId)\n ? threadId\n : hasControlCharacters\n ? `$'${[...threadId]\n .map(character => {\n const codePoint = character.codePointAt(0)!;\n if (character === \"'\") return \"\\\\'\";\n if (character === '\\\\') return '\\\\\\\\';\n if (codePoint <= 0x1f || codePoint === 0x7f) return `\\\\x${codePoint.toString(16).padStart(2, '0')}`;\n if (codePoint >= 0x80 && codePoint <= 0x9f) {\n return `\\\\u${codePoint.toString(16).padStart(4, '0')}`;\n }\n return character;\n })\n .join('')}'`\n : `'${threadId.replaceAll(\"'\", \"'\\\\''\")}'`;\n return `To continue this session, run mastracode resume ${argument}`;\n}\n","export function resolveTuiSubagents(enabled: boolean): undefined | [] {\n return enabled ? undefined : [];\n}\n","import {\n detectPackageManager,\n fetchLatestVersion,\n isNewerVersion,\n performUpdate,\n planUpdate,\n} from '@mastra/code-sdk/utils/update-check';\nimport { Chalk } from 'chalk';\nimport {\n formatInstallingLabel,\n formatRegistryError,\n formatUpdateHeader,\n formatUpdateOutcome,\n formatUpToDate,\n} from './update-output.js';\nimport type { UpdateStyle } from './update-output.js';\n\nconst UPDATE_COMMANDS = new Set(['update', 'upgrade']);\nconst USAGE =\n 'Usage: mastracode update\\n\\nInstall the latest version of Mastra Code. `mastracode upgrade` is an alias.';\nconst SPINNER_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];\n\ntype OutputStream = NodeJS.WritableStream & { isTTY?: boolean };\n\n/** Arguments after `mastracode update`/`mastracode upgrade`, or undefined for any other invocation. */\nexport function getUpdateCommandArgs(argv: string[]): string[] | undefined {\n return UPDATE_COMMANDS.has(argv[2] ?? '') ? argv.slice(3) : undefined;\n}\n\n/** Terminal colors, so the output reads well on light and dark terminals; none when the stream isn't a terminal. */\nfunction styleFor(stream: OutputStream): UpdateStyle {\n const chalk = new Chalk(stream.isTTY && !process.env.NO_COLOR ? {} : { level: 0 });\n return { accent: chalk.green, muted: chalk.gray, error: chalk.red, warning: chalk.yellow, bold: chalk.bold };\n}\n\n/** Spin `label` on a terminal until stopped; elsewhere print it once (or not at all when `quiet`). */\nfunction startSpinner(stream: OutputStream, style: UpdateStyle, label: string, { quiet = false } = {}): () => void {\n if (!stream.isTTY) {\n if (!quiet) stream.write(`${label}\\n`);\n return () => {};\n }\n const started = Date.now();\n let frame = 0;\n const draw = () => {\n const seconds = Math.floor((Date.now() - started) / 1000);\n stream.write(`\\r\\x1b[2K${style.accent(SPINNER_FRAMES[frame]!)} ${label} ${style.muted(`${seconds}s`)}`);\n frame = (frame + 1) % SPINNER_FRAMES.length;\n };\n draw();\n const timer = setInterval(draw, 80);\n return () => {\n clearInterval(timer);\n stream.write('\\r\\x1b[2K');\n };\n}\n\ninterface UpdateCommandOptions {\n args?: string[];\n output?: OutputStream;\n /** Failures go here, so `mastracode update >/dev/null` still shows them. */\n errorOutput?: OutputStream;\n currentVersion: string;\n}\n\n/**\n * Update Mastra Code from the shell. Unlike `/update`, there's no confirmation:\n * running the command is the request. Exits 1 unless the running install is on\n * the latest version afterwards.\n */\nexport async function runUpdateCommand({\n args = [],\n output = process.stdout,\n errorOutput = process.stderr,\n currentVersion,\n}: UpdateCommandOptions): Promise<number> {\n const style = styleFor(output);\n const errorStyle = styleFor(errorOutput);\n const say = (line: string) => output.write(`${line}\\n`);\n const fail = (...lines: string[]) => {\n errorOutput.write(`${lines.join('\\n')}\\n`);\n return 1;\n };\n\n if (args.includes('--help') || args.includes('-h')) {\n say(USAGE);\n return 0;\n }\n if (args.length > 0) {\n return fail(`${errorStyle.error('✗')} Unexpected argument: ${errorStyle.bold(args[0]!)}`, '', USAGE);\n }\n\n const stopChecking = startSpinner(output, style, 'Checking for updates', { quiet: true });\n const latestVersion = await fetchLatestVersion();\n if (!latestVersion || !isNewerVersion(currentVersion, latestVersion)) {\n stopChecking();\n say(formatUpdateHeader(style, currentVersion));\n if (!latestVersion) return fail(formatRegistryError(errorStyle));\n say(formatUpToDate(style));\n return 0;\n }\n const pm = await detectPackageManager();\n const plan = await planUpdate(pm, latestVersion);\n stopChecking();\n\n say(formatUpdateHeader(style, currentVersion, latestVersion));\n // Nothing to install for the user (e.g. Homebrew owns it): show the command to run instead.\n if (!plan.willInstall) return fail(...formatUpdateOutcome(errorStyle, plan.outcome, latestVersion));\n\n const stopInstalling = startSpinner(output, style, formatInstallingLabel(style, plan));\n const outcome = await performUpdate(pm, latestVersion, plan);\n stopInstalling();\n if (outcome.status === 'updated') {\n say(formatUpdateOutcome(style, outcome, latestVersion).join('\\n'));\n return 0;\n }\n return fail(...formatUpdateOutcome(errorStyle, outcome, latestVersion));\n}\n","import { readFileSync } from 'node:fs';\n\ndeclare const MASTRACODE_VERSION: string | undefined;\n\nexport function getCurrentVersion(): string {\n if (typeof MASTRACODE_VERSION !== 'undefined') {\n return MASTRACODE_VERSION;\n }\n\n const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as { version: string };\n return pkg.version;\n}\n","#!/usr/bin/env node\n/**\n * Main entry point for Mastra Code TUI.\n */\nimport fs from 'node:fs';\n\nimport { createMastraCode } from '@mastra/code-sdk';\nimport { createMastraCodeAnalytics } from '@mastra/code-sdk/analytics';\nimport { isStreamDestroyedError } from '@mastra/code-sdk/error-classification';\nimport { hasHeadlessFlag, runMCCli } from '@mastra/code-sdk/headless/index';\nimport {\n createBrowserFromSettings,\n loadSettings,\n resolveStagehandModel,\n toActiveBrowserSettings,\n} from '@mastra/code-sdk/onboarding/settings';\nimport { formatScaffoldSuccess, scaffoldPlugin } from '@mastra/code-sdk/plugins/scaffold';\nimport {\n stopProcessMemoryDiagnosticsWithTimeout,\n type ProcessMemoryDiagnostics,\n} from '@mastra/code-sdk/process-memory-diagnostics';\nimport { setupDebugLogging, truncateLogFile } from '@mastra/code-sdk/utils/debug-log';\nimport { drainPipedStdin, reopenStdinFromTTY } from '@mastra/code-sdk/utils/stdin-pipe';\nimport { releaseAllThreadLocks } from '@mastra/code-sdk/utils/thread-lock';\nimport { TUI_CO_AUTHOR } from './commit-attribution.js';\nimport { initialMessageOptions, pipedInputConflict, takeInitialPrompt } from './initial-prompt.js';\nimport {\n createOneShotFatalErrorHandler,\n createShutdownCoordinator,\n startTuiProcessMemoryDiagnostics,\n} from './process-memory-diagnostics-lifecycle.js';\nimport {\n formatResumeHint,\n parseResumeThreadId,\n shouldRejectResumeWithoutTTY,\n shouldRunHeadless,\n} from './resume-command.js';\nimport { resolveTuiSubagents } from './subagent-settings.js';\nimport { detectTerminalTheme } from './tui/detect-theme.js';\nimport { MastraTUI } from './tui/index.js';\nimport { applyThemeMode, restoreTerminalForeground } from './tui/theme.js';\nimport { getUpdateCommandArgs, runUpdateCommand } from './update-command.js';\nimport { getCurrentVersion } from './version.js';\n\nlet controller: Awaited<ReturnType<typeof createMastraCode>>['controller'];\nlet mcpManager: Awaited<ReturnType<typeof createMastraCode>>['mcpManager'];\nlet hookManager: Awaited<ReturnType<typeof createMastraCode>>['hookManager'];\nlet authStorage: Awaited<ReturnType<typeof createMastraCode>>['authStorage'];\nlet signalsPubSub: Awaited<ReturnType<typeof createMastraCode>>['signalsPubSub'];\nlet storageMaintenance: Awaited<ReturnType<typeof createMastraCode>>['storageMaintenance'];\nlet stopPluginSignalProviders: Awaited<ReturnType<typeof createMastraCode>>['stopPluginSignalProviders'] | undefined;\nlet threadScheduler: Awaited<ReturnType<typeof createMastraCode>>['threadScheduler'] | undefined;\nlet stopNotificationDispatch: Awaited<ReturnType<typeof createMastraCode>>['stopNotificationDispatch'] | undefined;\nlet releaseThreadClaims: Awaited<ReturnType<typeof createMastraCode>>['releaseThreadClaims'] | undefined;\nlet analytics: ReturnType<typeof createMastraCodeAnalytics> | undefined;\nlet tui: MastraTUI | undefined;\nlet processMemoryDiagnostics: ProcessMemoryDiagnostics | undefined;\nlet storageClosed = false;\nlet cleanupPromise: Promise<void> | null = null;\nlet getResumeThreadId: (() => string | null) | undefined;\n\nconst CRASH_LOG_PATH = '/tmp/mastra-crash.log';\n\nfunction isTruthyEnv(name: string): boolean {\n return ['1', 'true', 'yes', 'on'].includes(process.env[name]?.trim().toLowerCase() ?? '');\n}\n\nfunction resolveInitialStateFromEnv() {\n const currentModelId = process.env.MASTRACODE_MODEL_ID?.trim();\n const initialState: Record<string, unknown> = {};\n if (currentModelId) initialState.currentModelId = currentModelId;\n if (isTruthyEnv('MASTRACODE_YOLO')) initialState.yolo = true;\n return Object.keys(initialState).length > 0 ? initialState : undefined;\n}\n\n// Global safety nets — catch any uncaught errors from storage init, etc.\nprocess.on('uncaughtException', error => {\n // ERR_STREAM_DESTROYED is non-fatal — happens routinely when streams close\n // during shutdown, cancelled LLM requests, or LSP/subprocess exits (#13548, #13549)\n if (isStreamDestroyedError(error)) return;\n handleFatalError(error);\n});\nprocess.on('unhandledRejection', reason => {\n if (isStreamDestroyedError(reason)) return;\n handleFatalError(reason instanceof Error ? reason : new Error(String(reason)));\n});\n\nasync function tuiMain(startupMessage: ReturnType<typeof initialMessageOptions> = {}, resumeThreadId?: string) {\n const settings = loadSettings();\n processMemoryDiagnostics = await startTuiProcessMemoryDiagnostics(process.env, warning => {\n console.info(`⚠ ${warning}`);\n });\n let browserPromise: ReturnType<typeof createBrowserFromSettings> | undefined;\n const loadBrowser = (chatModelId: string | undefined) => {\n browserPromise ??= createBrowserFromSettings(settings.browser, { chatModelId });\n return browserPromise;\n };\n\n const initialState = resolveInitialStateFromEnv();\n const result = await createMastraCode({\n createInitialThread: false,\n coAuthor: TUI_CO_AUTHOR,\n unixSocketPubSub: !isTruthyEnv('MASTRACODE_DISABLE_UNIX_SOCKET_PUBSUB'),\n disableMcp: isTruthyEnv('MASTRACODE_DISABLE_MCP'),\n disableHooks: isTruthyEnv('MASTRACODE_DISABLE_HOOKS'),\n subagents: resolveTuiSubagents(settings.preferences.subagentsEnabled),\n ...(isTruthyEnv('MASTRACODE_DISABLE_MEMORY') ? { memory: false as never } : {}),\n ...(initialState ? { initialState: initialState as never } : {}),\n });\n controller = result.controller;\n mcpManager = result.mcpManager;\n hookManager = result.hookManager;\n authStorage = result.authStorage;\n signalsPubSub = result.signalsPubSub;\n storageMaintenance = result.storageMaintenance;\n stopPluginSignalProviders = result.stopPluginSignalProviders;\n threadScheduler = result.threadScheduler;\n stopNotificationDispatch = result.stopNotificationDispatch;\n releaseThreadClaims = result.releaseThreadClaims;\n\n if (result.storageWarning) {\n console.info(`⚠ ${result.storageWarning}`);\n }\n if (result.observabilityWarning) {\n console.info(`⚠ ${result.observabilityWarning}`);\n }\n\n // MCP connection is deferred to TUI.init() (after ui.start()) so that\n // status messages use showInfo() instead of console.info(), which would\n // corrupt the terminal. Headless mode still inits from headless/cli.ts.\n\n setupDebugLogging();\n\n // Detect and apply terminal theme\n // MASTRA_THEME env var is the highest-priority override\n const envTheme = process.env.MASTRA_THEME?.toLowerCase();\n let themeMode: 'dark' | 'light';\n let detectedBgHex: string | undefined;\n if (envTheme === 'dark' || envTheme === 'light') {\n themeMode = envTheme;\n } else {\n const settings = loadSettings();\n const themePref = settings.preferences.theme;\n if (themePref === 'dark' || themePref === 'light') {\n themeMode = themePref;\n } else {\n const detection = await detectTerminalTheme();\n themeMode = detection.mode;\n detectedBgHex = detection.detectedBgHex;\n }\n }\n applyThemeMode(themeMode, detectedBgHex);\n\n // createMastraCode() brought up shared resources and minted the single\n // session that all work runs through. The AgentController owns no session of its own.\n const session = result.session;\n getResumeThreadId = () => (tui ? tui.getResumeThreadId() : session.thread.getId());\n\n analytics = createMastraCodeAnalytics({ version: getCurrentVersion() });\n analytics.capture('mastracode_session_started', {\n mode: session.mode.get(),\n resourceId: session.identity.getResourceId(),\n hasAuthStorage: Boolean(authStorage),\n hasMcp: Boolean(mcpManager),\n theme: themeMode,\n });\n\n tui = new MastraTUI({\n controller: controller,\n session,\n hookManager,\n analytics,\n authStorage,\n mcpManager,\n pluginManager: result.pluginManager,\n storageMaintenance: result.storageMaintenance,\n processMemoryDiagnostics,\n knowledgeInspector: result.knowledgeInspector,\n knowledgeInspectorUnavailableReason: result.knowledgeInspectorUnavailableReason,\n threadScheduler: result.threadScheduler,\n appName: 'Mastra Code',\n version: getCurrentVersion(),\n inlineQuestions: true,\n initialModelOverride: Boolean(initialState?.currentModelId),\n ...(resumeThreadId ? { resumeThreadId } : {}),\n githubSignals: result.githubSignals,\n backgroundToolsEnabled: result.backgroundToolsEnabled,\n backgroundCompletionEvents: result.backgroundCompletionEvents,\n exit: exitCode => void shutdownAndExit(exitCode),\n ...startupMessage,\n });\n tui.run().catch(error => {\n handleFatalError(error);\n });\n\n if (settings.browser.enabled) {\n // Captured once: the Stagehand instance is fixed at launch and shared by every thread.\n const chatModelId = session.model.get();\n void loadBrowser(chatModelId)\n .then(browser => {\n if (!browser) return;\n controller.setBrowser(browser);\n void session.state\n .set({\n activeBrowserSettings: toActiveBrowserSettings(settings.browser),\n activeBrowserModel: resolveStagehandModel(settings.browser, { chatModelId }),\n } as any)\n .catch(() => {});\n })\n .catch(() => {});\n }\n}\n\nconst asyncCleanup = (): Promise<void> => {\n cleanupPromise ??= (async () => {\n releaseAllThreadLocks();\n // Release thread claims before the slow teardown below, so a restarted\n // session can claim its thread (and peers can reach it) right away.\n try {\n releaseThreadClaims?.();\n } catch {\n // Best-effort — the process is exiting.\n }\n // Stop plugin-contributed signal providers (and the plugin reload listener)\n // before quiescing workers: a provider that keeps polling past this point\n // could dispatch into a controller that is shutting down.\n try {\n stopPluginSignalProviders?.();\n } catch {\n // Best-effort — the process is exiting.\n }\n const diagnosticsShutdown = processMemoryDiagnostics\n ? stopProcessMemoryDiagnosticsWithTimeout(processMemoryDiagnostics, message => console.warn(message))\n : undefined;\n // Schedules live only in this process; stop their timers so none fires mid-shutdown.\n threadScheduler?.stop();\n // Release this process's notification dispatch leases before the pubsub that holds them closes.\n await stopNotificationDispatch?.().catch(() => {});\n await Promise.allSettled([mcpManager?.disconnect(), controller?.stopIntervals()]);\n // Mastra owns the workspaces and must destroy them to stop retained language\n // servers before storage is closed.\n await Promise.allSettled([controller?.getMastra()?.shutdown(), analytics?.shutdown()]);\n // The signals pubsub is Mastra's event bus: in-flight runs and background\n // tasks drain through it during shutdown, so close it only afterwards. Call\n // close() on the object; a detached method loses `this` and rejects silently.\n const pubsubToClose = signalsPubSub as { close?: () => Promise<void> | void } | undefined;\n await Promise.allSettled([pubsubToClose?.close?.()]);\n // Checkpoint WAL and close the local storage connection after all producers\n // and timers are quiesced. Idempotent — repeated signals (SIGINT then SIGHUP)\n // close only once. LibSQLStore.close()/LibSQLVector.close() truncate the WAL\n // and switch back to DELETE journal mode for a clean shutdown.\n if (!storageClosed) {\n storageClosed = true;\n await storageMaintenance?.closeStorage?.().catch(() => {\n // Swallow — best-effort cleanup during shutdown. The process is exiting.\n });\n }\n await diagnosticsShutdown;\n })();\n return cleanupPromise;\n};\n\nconst shutdownAndExit = createShutdownCoordinator(asyncCleanup, exitCode => process.exit(exitCode));\n\nprocess.on('beforeExit', () => {\n void asyncCleanup();\n});\nprocess.on('exit', () => {\n // Ensure terminal protocols (kitty keyboard, modifyOtherKeys, bracketed paste,\n // raw mode) are disabled on ANY exit path. Without this, killing the process\n // via SIGINT/SIGTERM leaves the terminal in a corrupted state where keypresses\n // produce escape sequences like \"5;99~\" instead of normal characters.\n try {\n tui?.stop();\n } catch {\n // Failsafe: even if MastraTUI.stop() throws, write raw terminal reset\n // sequences to disable Kitty keyboard protocol, bracketed paste, and\n // modifyOtherKeys. These are the exact sequences pi-tui's terminal.stop()\n // would write.\n }\n // Belt-and-suspenders: always write terminal reset sequences directly,\n // regardless of whether tui.stop() succeeded. Writing them twice is harmless\n // but missing them leaves the terminal in a corrupted state.\n try {\n process.stdout.write(\n '\\x1b[?2004l' + // disable bracketed paste\n '\\x1b[<u' + // pop kitty keyboard protocol\n '\\x1b[>4;0m' + // disable modifyOtherKeys\n '\\x1b[?25h', // show cursor\n );\n if (process.stdin.setRawMode) {\n process.stdin.setRawMode(false);\n }\n } catch {\n // stdout may already be closed during exit\n }\n restoreTerminalForeground();\n releaseAllThreadLocks();\n try {\n const threadId = getResumeThreadId?.();\n if (threadId) {\n process.stdout.write(`\\n${formatResumeHint(threadId)}\\n`);\n }\n } catch {\n // session state or stdout may already be closed during exit\n }\n});\n\n// Start durable diagnostics shutdown before synchronous TUI teardown so a stalled\n// terminal cleanup cannot prevent the final profile capture. The exit handler still\n// provides a failsafe terminal reset if teardown throws.\nconst handleTermSignal = () => {\n void asyncCleanup();\n try {\n tui?.stop();\n } catch {\n // ignored — exit handler has failsafe reset\n }\n void shutdownAndExit(0);\n};\nprocess.on('SIGINT', handleTermSignal);\nprocess.on('SIGTERM', handleTermSignal);\nprocess.on('SIGHUP', handleTermSignal);\n\nfunction hasEconnrefused(err: unknown, depth = 0): boolean {\n if (!err || depth > 5) return false;\n const e = err as any;\n if (e.code === 'ECONNREFUSED') return true;\n if (e.cause) return hasEconnrefused(e.cause, depth + 1);\n // AggregateError has .errors array\n if (Array.isArray(e.errors)) return e.errors.some((inner: unknown) => hasEconnrefused(inner, depth + 1));\n return false;\n}\n\nfunction pluginMain(args: string[]): void {\n if (args[0] !== 'scaffold') {\n process.stderr.write('Usage: mastracode plugin scaffold <dir> [--id acme.foo] [--name \"Foo Tools\"]\\n');\n process.exit(1);\n }\n\n const dir = args[1];\n if (!dir) {\n process.stderr.write('Usage: mastracode plugin scaffold <dir> [--id acme.foo] [--name \"Foo Tools\"]\\n');\n process.exit(1);\n }\n\n const id = readFlag(args, '--id');\n const name = readFlag(args, '--name');\n const targetDir = scaffoldPlugin(dir, { ...(id ? { id } : {}), ...(name ? { name } : {}) });\n process.stdout.write(`${formatScaffoldSuccess(targetDir)}\\n`);\n}\n\nfunction readFlag(args: string[], flag: string): string | undefined {\n const index = args.indexOf(flag);\n if (index === -1) return undefined;\n const value = args[index + 1];\n if (!value || value.startsWith('--')) {\n throw new Error(`Missing value for ${flag}`);\n }\n return value;\n}\n\nconst handleFatalError = createOneShotFatalErrorHandler((error: unknown): void => {\n // Always write to real stderr, even if console.error was overridden\n const write = (msg: string) => {\n try {\n process.stderr.write(msg + '\\n');\n } catch {}\n };\n\n if (hasEconnrefused(error)) {\n const settings = loadSettings();\n const connStr = settings.storage?.pg?.connectionString;\n const target = connStr ?? 'localhost:5432';\n write(\n `\\nFailed to connect to PostgreSQL at ${target}.` +\n `\\nMake sure the database is running and accessible.` +\n `\\n\\nTo switch back to LibSQL:` +\n `\\n Set MASTRA_STORAGE_BACKEND=libsql or change the backend in /settings\\n`,\n );\n void asyncCleanup();\n try {\n tui?.stop();\n } catch {}\n void shutdownAndExit(1);\n return;\n }\n\n const msg = `Fatal error: ${error instanceof Error ? error.message : String(error)}`;\n write(msg);\n // Write crash log to file so it persists even if terminal closes\n try {\n const crashLog = `[${new Date().toISOString()}] ${msg}\\n${error instanceof Error && error.stack ? error.stack + '\\n' : ''}`;\n truncateLogFile(CRASH_LOG_PATH);\n fs.appendFileSync(CRASH_LOG_PATH, crashLog);\n truncateLogFile(CRASH_LOG_PATH);\n } catch {}\n if (error instanceof Error && error.stack) {\n write(error.stack);\n }\n void asyncCleanup();\n try {\n tui?.stop();\n } catch {}\n void shutdownAndExit(1);\n});\n\nasync function main() {\n if (process.argv[2] === 'plugin') {\n return pluginMain(process.argv.slice(3));\n }\n\n // Storage maintenance without the TUI, so a database can still be pruned and\n // compacted when the interactive session won't start. Checked before the\n // headless branch below, which would otherwise claim `prune --help`.\n if (process.argv[2] === 'prune') {\n const { runPruneCommand } = await import('@mastra/code-sdk/utils/prune-cli');\n return process.exit(await runPruneCommand(process.argv.slice(3)));\n }\n\n // Also checked before the headless branch, which would send the bare word as a prompt.\n const updateArgs = getUpdateCommandArgs(process.argv);\n if (updateArgs) {\n const code = await runUpdateCommand({ args: updateArgs, currentVersion: getCurrentVersion() });\n await Promise.all(\n [process.stdout, process.stderr].map(stream => new Promise(resolve => stream.write('', resolve))),\n );\n return process.exit(code);\n }\n\n const loginIndex = process.argv.findIndex(\n (arg, index) => index >= 2 && arg !== '--acp' && arg !== '--dangerous-auto-approve',\n );\n if (process.argv[loginIndex] === 'login') {\n const { runLoginCommand } = await import('./login-command.js');\n const code = await runLoginCommand({ args: process.argv.slice(loginIndex + 1) });\n await new Promise(resolve => process.stdout.write('', resolve));\n return process.exit(code);\n }\n\n const initialPrompt = takeInitialPrompt(process.argv, process.env);\n if (initialPrompt.error) {\n process.stderr.write(`${initialPrompt.error}\\n`);\n process.exit(1);\n }\n if (initialPrompt.flag) process.argv = initialPrompt.argv;\n // The flag only means something to the interactive TUI. Paths that can't run\n // it reject the flag instead of dropping the prompt; an env var prompt is\n // just ignored there.\n const rejectInitialPromptFlag = (reason: string) => {\n if (!initialPrompt.flag) return;\n process.stderr.write(`${initialPrompt.flag} starts the interactive TUI; ${reason}\\n`);\n process.exit(1);\n };\n\n let resumeThreadId: string | undefined;\n try {\n resumeThreadId = parseResumeThreadId(process.argv.slice(2));\n } catch (error) {\n process.stderr.write(`${error instanceof Error ? error.message : String(error)}\\n`);\n process.exitCode = 1;\n return;\n }\n\n const headless = hasHeadlessFlag(process.argv);\n if (shouldRunHeadless(process.argv, resumeThreadId, headless)) {\n if (headless) rejectInitialPromptFlag('use --prompt for headless runs');\n return runMCCli(undefined, { coAuthor: TUI_CO_AUTHOR });\n }\n\n if (process.argv.includes('--acp')) {\n rejectInitialPromptFlag('it cannot be combined with --acp');\n const { acpMain } = await import('@mastra/code-sdk/acp/index');\n return acpMain({\n dangerousAutoApprove: process.argv.includes('--dangerous-auto-approve'),\n coAuthor: TUI_CO_AUTHOR,\n });\n }\n\n if (shouldRejectResumeWithoutTTY(resumeThreadId, Boolean(process.stdin.isTTY))) {\n process.stderr.write('mastracode resume requires an interactive terminal.\\n');\n process.exitCode = 1;\n return;\n }\n\n // When stdin is piped (e.g. `cat foo | mastracode`), drain the pipe fully\n // before starting the TUI. The drain blocks until the sender process exits\n // and closes its stdout, so we never see partial output.\n let pipedInput: string | null = null;\n if (!process.stdin.isTTY) {\n process.stderr.write('Reading piped input...\\n');\n pipedInput = await drainPipedStdin();\n\n // Always reopen a real TTY — even if the pipe was empty, the original\n // stdin is consumed/closed and the TUI needs a live TTY for keyboard input.\n const reopenedStdin = reopenStdinFromTTY();\n if (!reopenedStdin) {\n rejectInitialPromptFlag('no TTY is available, so use --prompt for headless runs');\n process.stderr.write('No TTY available — falling back to headless mode.\\n');\n return runMCCli(pipedInput, { coAuthor: TUI_CO_AUTHOR });\n }\n }\n\n const conflict = pipedInputConflict(initialPrompt, pipedInput);\n if (conflict) {\n process.stderr.write(`${conflict}\\n`);\n process.exit(1);\n }\n\n return tuiMain(initialMessageOptions(initialPrompt, pipedInput), resumeThreadId);\n}\n\nmain().catch(error => {\n handleFatalError(error);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;AAAA,MAAa,sBAAsB;AACnC,MAAa,qBAAqB;AAElC,MAAa,kBAAkB;;;;;;;;;;AA0B/B,SAAgB,kBAAkB,MAAgB,KAA2C;CAC3F,MAAM,UAAU,IAAI;CACpB,OAAO,IAAI;CAEX,MAAM,OAAiB,CAAC;CACxB,MAAM,wBAAQ,IAAI,IAAoD;CACtE,IAAI;CACJ,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;EACpC,MAAM,MAAM,KAAK;EACjB,MAAM,OAAO,CAAC,qBAAqB,eAAe,CAAC,CAAC,MAAK,MAAK,QAAQ,KAAK,IAAI,WAAW,GAAG,EAAE,EAAE,CAAC;EAClG,IAAI,CAAC,MACH,KAAK,KAAK,GAAG;OACR,IAAI,QAAQ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AAa,OAAA,GAAA,kCAAA,gBAAA,CAAsB;EAKnC,IAAI,EAAA,GAAA,kCAAA,mBAAA,CAAa,GAAG;GAClB,wBAAwB,wDAAwD;GAChF,QAAQ,OAAO,MAAM,qDAAqD;GAC1E,QAAA,GAAA,gCAAA,SAAA,CAAgB,YAAY,EAAE,UAAUA,YAAAA,cAAc,CAAC;EACzD;CACF;CAEA,MAAM,WAAW,mBAAmB,eAAe,UAAU;CAC7D,IAAI,UAAU;EACZ,QAAQ,OAAO,MAAM,GAAG,SAAS,GAAG;EACpC,QAAQ,KAAK,CAAC;CAChB;CAEA,OAAO,QAAQ,sBAAsB,eAAe,UAAU,GAAG,cAAc;AACjF;AAEA,KAAK,CAAC,CAAC,OAAM,UAAS;CACpB,iBAAiB,KAAK;AACxB,CAAC"}
|
|
1
|
+
{"version":3,"file":"cli.cjs","names":["createProcessMemoryDiagnosticsFromEnvironment","chalk","Chalk","formatUpdateHeader","formatRegistryError","formatUpToDate","formatUpdateOutcome","formatInstallingLabel","TUI_CO_AUTHOR","detectTerminalTheme","MastraTUI"],"sources":["../src/initial-prompt.ts","../src/process-memory-diagnostics-lifecycle.ts","../src/resume-command.ts","../src/subagent-settings.ts","../src/update-command.ts","../src/version.ts","../src/main.ts"],"sourcesContent":["export const INITIAL_PROMPT_FLAG = '--tui-initial-prompt' as const;\nexport const INITIAL_PROMPT_ENV = 'MASTRACODE_TUI_INITIAL_PROMPT';\n\nexport const TUI_PROMPT_FLAG = '--tui-prompt' as const;\n\nexport type InitialPromptArgs = {\n /** argv with the flag and its value removed, so headless detection never mistakes the value for a prompt. */\n argv: string[];\n prompt?: string;\n /** Set when a flag was passed without a value, or both flags were passed. */\n error?: string;\n /** The flag the prompt came from; undefined when it came from the environment. */\n flag?: typeof INITIAL_PROMPT_FLAG | typeof TUI_PROMPT_FLAG;\n /**\n * `--tui-prompt` sends even when startup resumes an existing conversation;\n * `--tui-initial-prompt` and the environment variable only start a new one.\n */\n sendOnResume: boolean;\n};\n\n/**\n * Takes the interactive startup prompt from `--tui-initial-prompt <text>` or\n * `--tui-prompt <text>` (also `--flag=<text>`), falling back to\n * `MASTRACODE_TUI_INITIAL_PROMPT`.\n *\n * The environment variable is always removed from `env`: everything this\n * process spawns inherits its environment, and a nested Mastra Code (or any\n * shell the agent starts) must not send the same prompt again.\n */\nexport function takeInitialPrompt(argv: string[], env: NodeJS.ProcessEnv): InitialPromptArgs {\n const fromEnv = env[INITIAL_PROMPT_ENV];\n delete env[INITIAL_PROMPT_ENV];\n\n const rest: string[] = [];\n const found = new Map<NonNullable<InitialPromptArgs['flag']>, string>();\n let error: string | undefined;\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i]!;\n const flag = [INITIAL_PROMPT_FLAG, TUI_PROMPT_FLAG].find(f => arg === f || arg.startsWith(`${f}=`));\n if (!flag) {\n rest.push(arg);\n } else if (arg !== flag) {\n found.set(flag, arg.slice(flag.length + 1));\n } else if (argv[i + 1] === undefined) {\n error = `${flag} needs a value`;\n } else {\n found.set(flag, argv[++i]!);\n }\n }\n if (found.size > 1) error = `Use either ${INITIAL_PROMPT_FLAG} or ${TUI_PROMPT_FLAG}, not both`;\n\n const [flag, flagValue] = [...found][0] ?? [];\n const prompt = (flag ? flagValue : fromEnv)?.trim() || undefined;\n return { argv: rest, prompt, error, flag, sendOnResume: flag === TUI_PROMPT_FLAG };\n}\n\n/** The first message the TUI sends: the initial prompt, followed by any piped stdin. */\nexport function composeInitialMessage(prompt: string | undefined, pipedInput: string | null | undefined) {\n const piped = pipedInput ? `The following was piped via stdin:\\n\\n${pipedInput}` : undefined;\n if (prompt && piped) return `${prompt}\\n\\n${piped}`;\n return prompt ?? piped;\n}\n\n/**\n * Why a startup prompt can't be combined with piped stdin, if it can't.\n *\n * The first message is submitted like typed input, so a prompt starting with\n * `/` or `!` is dispatched as a command. Folding piped text into it would make\n * that text part of the command — skill arguments, or a shell script for `!`.\n */\nexport function pipedInputConflict(\n args: Pick<InitialPromptArgs, 'prompt' | 'flag'>,\n pipedInput: string | null | undefined,\n): string | undefined {\n if (!args.prompt || !pipedInput) return undefined;\n if (!args.prompt.startsWith('/') && !args.prompt.startsWith('!')) return undefined;\n const source = args.flag ?? INITIAL_PROMPT_ENV;\n return `${source} can't be combined with piped stdin when it is a slash command or starts with !`;\n}\n\n/** The TUI options for a startup prompt and/or piped stdin. */\nexport function initialMessageOptions(\n args: Pick<InitialPromptArgs, 'prompt' | 'sendOnResume'>,\n pipedInput?: string | null,\n): { initialMessage?: string; resumeSkipNotice?: string } {\n const initialMessage = composeInitialMessage(args.prompt, pipedInput);\n if (!initialMessage) return {};\n // Piped stdin on its own is always sent, as before.\n if (!args.prompt || args.sendOnResume) return { initialMessage };\n const skipped = pipedInput ? 'the initial prompt and piped input were' : 'the initial prompt was';\n return {\n initialMessage,\n resumeSkipNotice: `Resumed the existing conversation for this directory, so ${skipped} not sent. Use ${TUI_PROMPT_FLAG} to send ${pipedInput ? 'them' : 'it'} anyway.`,\n };\n}\n\nexport const PACK_FLAG = '--pack' as const;\n\nexport type PackFlagArgs = {\n /** argv with `--pack` and its value removed. */\n argv: string[];\n /** The raw pack id argument, when `--pack` was passed. */\n value?: string;\n /** Set when the flag was passed without a value. */\n error?: string;\n};\n\n/**\n * Extracts `--pack <id>` (or `--pack=<id>`) from argv. The pack id is validated\n * later against the packs in settings (built-in ids, `custom:<name>`, or a bare\n * custom-pack name); here we only strip the flag so other argv consumers never\n * mistake the id for a positional prompt.\n */\nexport function takePackFlag(argv: string[]): PackFlagArgs {\n const rest: string[] = [];\n let value: string | undefined;\n let error: string | undefined;\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i]!;\n if (arg === PACK_FLAG) {\n const next = argv[++i];\n if (next === undefined || next.startsWith('-')) {\n error = `${PACK_FLAG} needs a value`;\n break;\n }\n value = next;\n } else if (arg.startsWith(`${PACK_FLAG}=`)) {\n const inline = arg.slice(PACK_FLAG.length + 1);\n if (inline === '' || inline.startsWith('-')) {\n error = `${PACK_FLAG} needs a value`;\n break;\n }\n value = inline;\n } else {\n rest.push(arg);\n }\n }\n return { argv: rest, ...(value !== undefined ? { value } : {}), ...(error ? { error } : {}) };\n}\n","import {\n createProcessMemoryDiagnosticsFromEnvironment,\n startConfiguredProcessMemoryDiagnostics,\n type ProcessMemoryDiagnostics,\n type ProcessMemoryDiagnosticsEnvironment,\n type ProcessMemoryDiagnosticsSetup,\n} from '@mastra/code-sdk/process-memory-diagnostics';\n\nexport async function startTuiProcessMemoryDiagnostics(\n env: ProcessMemoryDiagnosticsEnvironment,\n warn: (message: string) => void,\n createSetup: (\n env: ProcessMemoryDiagnosticsEnvironment,\n ) => ProcessMemoryDiagnosticsSetup = createProcessMemoryDiagnosticsFromEnvironment,\n): Promise<ProcessMemoryDiagnostics> {\n return startConfiguredProcessMemoryDiagnostics(createSetup(env), warn);\n}\n\nexport function createOneShotFatalErrorHandler(handle: (error: unknown) => void): (error: unknown) => void {\n let handlingFatalError = false;\n return error => {\n if (handlingFatalError) return;\n handlingFatalError = true;\n handle(error);\n };\n}\n\nexport function createShutdownCoordinator(\n cleanup: () => Promise<void>,\n exit: (exitCode: number) => never,\n timeoutMs = 5_000,\n): (exitCode: number) => Promise<void> {\n let shutdownPromise: Promise<void> | null = null;\n return exitCode => {\n shutdownPromise ??= (async () => {\n let timeout: ReturnType<typeof setTimeout> | undefined;\n await Promise.race([\n cleanup().catch(() => undefined),\n new Promise<void>(resolve => {\n timeout = setTimeout(resolve, timeoutMs);\n }),\n ]);\n if (timeout) clearTimeout(timeout);\n exit(exitCode);\n })();\n return shutdownPromise;\n };\n}\n","export function parseResumeThreadId(args: string[]): string | undefined {\n if (args[0] !== 'resume') return undefined;\n\n const threadId = args[1]?.trim();\n if (!threadId || args.length !== 2) {\n throw new Error('Usage: mastracode resume <thread-id>');\n }\n return threadId;\n}\n\nexport function shouldRunHeadless(\n argv: string[],\n resumeThreadId: string | undefined,\n hasHeadlessFlag: boolean,\n): boolean {\n return !resumeThreadId && (hasHeadlessFlag || argv.includes('--help') || argv.includes('-h'));\n}\n\nexport function shouldRejectResumeWithoutTTY(resumeThreadId: string | undefined, isTTY: boolean): boolean {\n return Boolean(resumeThreadId) && !isTTY;\n}\n\nexport function formatResumeHint(threadId: string): string {\n const hasControlCharacters = [...threadId].some(character => {\n const codePoint = character.codePointAt(0)!;\n return codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f);\n });\n const argument = /^[a-zA-Z0-9_-]+$/.test(threadId)\n ? threadId\n : hasControlCharacters\n ? `$'${[...threadId]\n .map(character => {\n const codePoint = character.codePointAt(0)!;\n if (character === \"'\") return \"\\\\'\";\n if (character === '\\\\') return '\\\\\\\\';\n if (codePoint <= 0x1f || codePoint === 0x7f) return `\\\\x${codePoint.toString(16).padStart(2, '0')}`;\n if (codePoint >= 0x80 && codePoint <= 0x9f) {\n return `\\\\u${codePoint.toString(16).padStart(4, '0')}`;\n }\n return character;\n })\n .join('')}'`\n : `'${threadId.replaceAll(\"'\", \"'\\\\''\")}'`;\n return `To continue this session, run mastracode resume ${argument}`;\n}\n","export function resolveTuiSubagents(enabled: boolean): undefined | [] {\n return enabled ? undefined : [];\n}\n","import {\n detectPackageManager,\n fetchLatestVersion,\n isNewerVersion,\n performUpdate,\n planUpdate,\n} from '@mastra/code-sdk/utils/update-check';\nimport { Chalk } from 'chalk';\nimport {\n formatInstallingLabel,\n formatRegistryError,\n formatUpdateHeader,\n formatUpdateOutcome,\n formatUpToDate,\n} from './update-output.js';\nimport type { UpdateStyle } from './update-output.js';\n\nconst UPDATE_COMMANDS = new Set(['update', 'upgrade']);\nconst USAGE =\n 'Usage: mastracode update\\n\\nInstall the latest version of Mastra Code. `mastracode upgrade` is an alias.';\nconst SPINNER_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];\n\ntype OutputStream = NodeJS.WritableStream & { isTTY?: boolean };\n\n/** Arguments after `mastracode update`/`mastracode upgrade`, or undefined for any other invocation. */\nexport function getUpdateCommandArgs(argv: string[]): string[] | undefined {\n return UPDATE_COMMANDS.has(argv[2] ?? '') ? argv.slice(3) : undefined;\n}\n\n/** Terminal colors, so the output reads well on light and dark terminals; none when the stream isn't a terminal. */\nfunction styleFor(stream: OutputStream): UpdateStyle {\n const chalk = new Chalk(stream.isTTY && !process.env.NO_COLOR ? {} : { level: 0 });\n return { accent: chalk.green, muted: chalk.gray, error: chalk.red, warning: chalk.yellow, bold: chalk.bold };\n}\n\n/** Spin `label` on a terminal until stopped; elsewhere print it once (or not at all when `quiet`). */\nfunction startSpinner(stream: OutputStream, style: UpdateStyle, label: string, { quiet = false } = {}): () => void {\n if (!stream.isTTY) {\n if (!quiet) stream.write(`${label}\\n`);\n return () => {};\n }\n const started = Date.now();\n let frame = 0;\n const draw = () => {\n const seconds = Math.floor((Date.now() - started) / 1000);\n stream.write(`\\r\\x1b[2K${style.accent(SPINNER_FRAMES[frame]!)} ${label} ${style.muted(`${seconds}s`)}`);\n frame = (frame + 1) % SPINNER_FRAMES.length;\n };\n draw();\n const timer = setInterval(draw, 80);\n return () => {\n clearInterval(timer);\n stream.write('\\r\\x1b[2K');\n };\n}\n\ninterface UpdateCommandOptions {\n args?: string[];\n output?: OutputStream;\n /** Failures go here, so `mastracode update >/dev/null` still shows them. */\n errorOutput?: OutputStream;\n currentVersion: string;\n}\n\n/**\n * Update Mastra Code from the shell. Unlike `/update`, there's no confirmation:\n * running the command is the request. Exits 1 unless the running install is on\n * the latest version afterwards.\n */\nexport async function runUpdateCommand({\n args = [],\n output = process.stdout,\n errorOutput = process.stderr,\n currentVersion,\n}: UpdateCommandOptions): Promise<number> {\n const style = styleFor(output);\n const errorStyle = styleFor(errorOutput);\n const say = (line: string) => output.write(`${line}\\n`);\n const fail = (...lines: string[]) => {\n errorOutput.write(`${lines.join('\\n')}\\n`);\n return 1;\n };\n\n if (args.includes('--help') || args.includes('-h')) {\n say(USAGE);\n return 0;\n }\n if (args.length > 0) {\n return fail(`${errorStyle.error('✗')} Unexpected argument: ${errorStyle.bold(args[0]!)}`, '', USAGE);\n }\n\n const stopChecking = startSpinner(output, style, 'Checking for updates', { quiet: true });\n const latestVersion = await fetchLatestVersion();\n if (!latestVersion || !isNewerVersion(currentVersion, latestVersion)) {\n stopChecking();\n say(formatUpdateHeader(style, currentVersion));\n if (!latestVersion) return fail(formatRegistryError(errorStyle));\n say(formatUpToDate(style));\n return 0;\n }\n const pm = await detectPackageManager();\n const plan = await planUpdate(pm, latestVersion);\n stopChecking();\n\n say(formatUpdateHeader(style, currentVersion, latestVersion));\n // Nothing to install for the user (e.g. Homebrew owns it): show the command to run instead.\n if (!plan.willInstall) return fail(...formatUpdateOutcome(errorStyle, plan.outcome, latestVersion));\n\n const stopInstalling = startSpinner(output, style, formatInstallingLabel(style, plan));\n const outcome = await performUpdate(pm, latestVersion, plan);\n stopInstalling();\n if (outcome.status === 'updated') {\n say(formatUpdateOutcome(style, outcome, latestVersion).join('\\n'));\n return 0;\n }\n return fail(...formatUpdateOutcome(errorStyle, outcome, latestVersion));\n}\n","import { readFileSync } from 'node:fs';\n\ndeclare const MASTRACODE_VERSION: string | undefined;\n\nexport function getCurrentVersion(): string {\n if (typeof MASTRACODE_VERSION !== 'undefined') {\n return MASTRACODE_VERSION;\n }\n\n const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as { version: string };\n return pkg.version;\n}\n","#!/usr/bin/env node\n/**\n * Main entry point for Mastra Code TUI.\n */\nimport fs from 'node:fs';\n\nimport { createMastraCode } from '@mastra/code-sdk';\nimport { createMastraCodeAnalytics } from '@mastra/code-sdk/analytics';\nimport { isStreamDestroyedError } from '@mastra/code-sdk/error-classification';\nimport { hasHeadlessFlag, runMCCli } from '@mastra/code-sdk/headless/index';\nimport { resolveModePackArg } from '@mastra/code-sdk/onboarding/pack-activation';\nimport {\n createBrowserFromSettings,\n loadSettings,\n resolveStagehandModel,\n toActiveBrowserSettings,\n} from '@mastra/code-sdk/onboarding/settings';\nimport { formatScaffoldSuccess, scaffoldPlugin } from '@mastra/code-sdk/plugins/scaffold';\nimport {\n stopProcessMemoryDiagnosticsWithTimeout,\n type ProcessMemoryDiagnostics,\n} from '@mastra/code-sdk/process-memory-diagnostics';\nimport { setupDebugLogging, truncateLogFile } from '@mastra/code-sdk/utils/debug-log';\nimport { drainPipedStdin, reopenStdinFromTTY } from '@mastra/code-sdk/utils/stdin-pipe';\nimport { releaseAllThreadLocks } from '@mastra/code-sdk/utils/thread-lock';\nimport { TUI_CO_AUTHOR } from './commit-attribution.js';\nimport { initialMessageOptions, pipedInputConflict, takeInitialPrompt, takePackFlag } from './initial-prompt.js';\nimport {\n createOneShotFatalErrorHandler,\n createShutdownCoordinator,\n startTuiProcessMemoryDiagnostics,\n} from './process-memory-diagnostics-lifecycle.js';\nimport {\n formatResumeHint,\n parseResumeThreadId,\n shouldRejectResumeWithoutTTY,\n shouldRunHeadless,\n} from './resume-command.js';\nimport { resolveTuiSubagents } from './subagent-settings.js';\nimport { detectTerminalTheme } from './tui/detect-theme.js';\nimport { MastraTUI } from './tui/index.js';\nimport { applyThemeMode, restoreTerminalForeground } from './tui/theme.js';\nimport { getUpdateCommandArgs, runUpdateCommand } from './update-command.js';\nimport { getCurrentVersion } from './version.js';\n\nlet controller: Awaited<ReturnType<typeof createMastraCode>>['controller'];\nlet mcpManager: Awaited<ReturnType<typeof createMastraCode>>['mcpManager'];\nlet hookManager: Awaited<ReturnType<typeof createMastraCode>>['hookManager'];\nlet authStorage: Awaited<ReturnType<typeof createMastraCode>>['authStorage'];\nlet signalsPubSub: Awaited<ReturnType<typeof createMastraCode>>['signalsPubSub'];\nlet storageMaintenance: Awaited<ReturnType<typeof createMastraCode>>['storageMaintenance'];\nlet stopPluginSignalProviders: Awaited<ReturnType<typeof createMastraCode>>['stopPluginSignalProviders'] | undefined;\nlet threadScheduler: Awaited<ReturnType<typeof createMastraCode>>['threadScheduler'] | undefined;\nlet stopNotificationDispatch: Awaited<ReturnType<typeof createMastraCode>>['stopNotificationDispatch'] | undefined;\nlet releaseThreadClaims: Awaited<ReturnType<typeof createMastraCode>>['releaseThreadClaims'] | undefined;\nlet analytics: ReturnType<typeof createMastraCodeAnalytics> | undefined;\nlet tui: MastraTUI | undefined;\nlet processMemoryDiagnostics: ProcessMemoryDiagnostics | undefined;\nlet storageClosed = false;\nlet cleanupPromise: Promise<void> | null = null;\nlet getResumeThreadId: (() => string | null) | undefined;\n\nconst CRASH_LOG_PATH = '/tmp/mastra-crash.log';\n\nfunction isTruthyEnv(name: string): boolean {\n return ['1', 'true', 'yes', 'on'].includes(process.env[name]?.trim().toLowerCase() ?? '');\n}\n\nfunction resolveInitialStateFromEnv(options: { ignoreModelEnv?: boolean } = {}) {\n const currentModelId = options.ignoreModelEnv ? undefined : process.env.MASTRACODE_MODEL_ID?.trim();\n const initialState: Record<string, unknown> = {};\n if (currentModelId) initialState.currentModelId = currentModelId;\n if (isTruthyEnv('MASTRACODE_YOLO')) initialState.yolo = true;\n return Object.keys(initialState).length > 0 ? initialState : undefined;\n}\n\n// Global safety nets — catch any uncaught errors from storage init, etc.\nprocess.on('uncaughtException', error => {\n // ERR_STREAM_DESTROYED is non-fatal — happens routinely when streams close\n // during shutdown, cancelled LLM requests, or LSP/subprocess exits (#13548, #13549)\n if (isStreamDestroyedError(error)) return;\n handleFatalError(error);\n});\nprocess.on('unhandledRejection', reason => {\n if (isStreamDestroyedError(reason)) return;\n handleFatalError(reason instanceof Error ? reason : new Error(String(reason)));\n});\n\nasync function tuiMain(\n startupMessage: ReturnType<typeof initialMessageOptions> = {},\n resumeThreadId?: string,\n startupPackId?: string,\n) {\n const settings = loadSettings();\n processMemoryDiagnostics = await startTuiProcessMemoryDiagnostics(process.env, warning => {\n console.info(`⚠ ${warning}`);\n });\n let browserPromise: ReturnType<typeof createBrowserFromSettings> | undefined;\n const loadBrowser = (chatModelId: string | undefined) => {\n browserPromise ??= createBrowserFromSettings(settings.browser, { chatModelId });\n return browserPromise;\n };\n\n const initialState = resolveInitialStateFromEnv({ ignoreModelEnv: startupPackId !== undefined });\n const result = await createMastraCode({\n createInitialThread: false,\n coAuthor: TUI_CO_AUTHOR,\n unixSocketPubSub: !isTruthyEnv('MASTRACODE_DISABLE_UNIX_SOCKET_PUBSUB'),\n disableMcp: isTruthyEnv('MASTRACODE_DISABLE_MCP'),\n disableHooks: isTruthyEnv('MASTRACODE_DISABLE_HOOKS'),\n subagents: resolveTuiSubagents(settings.preferences.subagentsEnabled),\n ...(isTruthyEnv('MASTRACODE_DISABLE_MEMORY') ? { memory: false as never } : {}),\n ...(initialState ? { initialState: initialState as never } : {}),\n });\n controller = result.controller;\n mcpManager = result.mcpManager;\n hookManager = result.hookManager;\n authStorage = result.authStorage;\n signalsPubSub = result.signalsPubSub;\n storageMaintenance = result.storageMaintenance;\n stopPluginSignalProviders = result.stopPluginSignalProviders;\n threadScheduler = result.threadScheduler;\n stopNotificationDispatch = result.stopNotificationDispatch;\n releaseThreadClaims = result.releaseThreadClaims;\n\n if (result.storageWarning) {\n console.info(`⚠ ${result.storageWarning}`);\n }\n if (result.observabilityWarning) {\n console.info(`⚠ ${result.observabilityWarning}`);\n }\n\n // MCP connection is deferred to TUI.init() (after ui.start()) so that\n // status messages use showInfo() instead of console.info(), which would\n // corrupt the terminal. Headless mode still inits from headless/cli.ts.\n\n setupDebugLogging();\n\n // Detect and apply terminal theme\n // MASTRA_THEME env var is the highest-priority override\n const envTheme = process.env.MASTRA_THEME?.toLowerCase();\n let themeMode: 'dark' | 'light';\n let detectedBgHex: string | undefined;\n if (envTheme === 'dark' || envTheme === 'light') {\n themeMode = envTheme;\n } else {\n const settings = loadSettings();\n const themePref = settings.preferences.theme;\n if (themePref === 'dark' || themePref === 'light') {\n themeMode = themePref;\n } else {\n const detection = await detectTerminalTheme();\n themeMode = detection.mode;\n detectedBgHex = detection.detectedBgHex;\n }\n }\n applyThemeMode(themeMode, detectedBgHex);\n\n // createMastraCode() brought up shared resources and minted the single\n // session that all work runs through. The AgentController owns no session of its own.\n const session = result.session;\n getResumeThreadId = () => (tui ? tui.getResumeThreadId() : session.thread.getId());\n\n analytics = createMastraCodeAnalytics({ version: getCurrentVersion() });\n analytics.capture('mastracode_session_started', {\n mode: session.mode.get(),\n resourceId: session.identity.getResourceId(),\n hasAuthStorage: Boolean(authStorage),\n hasMcp: Boolean(mcpManager),\n theme: themeMode,\n });\n\n tui = new MastraTUI({\n controller: controller,\n session,\n hookManager,\n analytics,\n authStorage,\n mcpManager,\n pluginManager: result.pluginManager,\n storageMaintenance: result.storageMaintenance,\n processMemoryDiagnostics,\n knowledgeInspector: result.knowledgeInspector,\n knowledgeInspectorUnavailableReason: result.knowledgeInspectorUnavailableReason,\n threadScheduler: result.threadScheduler,\n appName: 'Mastra Code',\n version: getCurrentVersion(),\n inlineQuestions: true,\n initialModelOverride: Boolean(initialState?.currentModelId),\n ...(startupPackId ? { initialPackId: startupPackId } : {}),\n ...(resumeThreadId ? { resumeThreadId } : {}),\n githubSignals: result.githubSignals,\n backgroundToolsEnabled: result.backgroundToolsEnabled,\n backgroundCompletionEvents: result.backgroundCompletionEvents,\n exit: exitCode => void shutdownAndExit(exitCode),\n ...startupMessage,\n });\n tui.run().catch(error => {\n handleFatalError(error);\n });\n\n if (settings.browser.enabled) {\n // Captured once: the Stagehand instance is fixed at launch and shared by every thread.\n const chatModelId = session.model.get();\n void loadBrowser(chatModelId)\n .then(browser => {\n if (!browser) return;\n controller.setBrowser(browser);\n void session.state\n .set({\n activeBrowserSettings: toActiveBrowserSettings(settings.browser),\n activeBrowserModel: resolveStagehandModel(settings.browser, { chatModelId }),\n } as any)\n .catch(() => {});\n })\n .catch(() => {});\n }\n}\n\nconst asyncCleanup = (): Promise<void> => {\n cleanupPromise ??= (async () => {\n releaseAllThreadLocks();\n // Release thread claims before the slow teardown below, so a restarted\n // session can claim its thread (and peers can reach it) right away.\n try {\n releaseThreadClaims?.();\n } catch {\n // Best-effort — the process is exiting.\n }\n // Stop plugin-contributed signal providers (and the plugin reload listener)\n // before quiescing workers: a provider that keeps polling past this point\n // could dispatch into a controller that is shutting down.\n try {\n stopPluginSignalProviders?.();\n } catch {\n // Best-effort — the process is exiting.\n }\n const diagnosticsShutdown = processMemoryDiagnostics\n ? stopProcessMemoryDiagnosticsWithTimeout(processMemoryDiagnostics, message => console.warn(message))\n : undefined;\n // Schedules live only in this process; stop their timers so none fires mid-shutdown.\n threadScheduler?.stop();\n // Release this process's notification dispatch leases before the pubsub that holds them closes.\n await stopNotificationDispatch?.().catch(() => {});\n await Promise.allSettled([mcpManager?.disconnect(), controller?.stopIntervals()]);\n // Mastra owns the workspaces and must destroy them to stop retained language\n // servers before storage is closed.\n await Promise.allSettled([controller?.getMastra()?.shutdown(), analytics?.shutdown()]);\n // The signals pubsub is Mastra's event bus: in-flight runs and background\n // tasks drain through it during shutdown, so close it only afterwards. Call\n // close() on the object; a detached method loses `this` and rejects silently.\n const pubsubToClose = signalsPubSub as { close?: () => Promise<void> | void } | undefined;\n await Promise.allSettled([pubsubToClose?.close?.()]);\n // Checkpoint WAL and close the local storage connection after all producers\n // and timers are quiesced. Idempotent — repeated signals (SIGINT then SIGHUP)\n // close only once. LibSQLStore.close()/LibSQLVector.close() truncate the WAL\n // and switch back to DELETE journal mode for a clean shutdown.\n if (!storageClosed) {\n storageClosed = true;\n await storageMaintenance?.closeStorage?.().catch(() => {\n // Swallow — best-effort cleanup during shutdown. The process is exiting.\n });\n }\n await diagnosticsShutdown;\n })();\n return cleanupPromise;\n};\n\nconst shutdownAndExit = createShutdownCoordinator(asyncCleanup, exitCode => process.exit(exitCode));\n\nprocess.on('beforeExit', () => {\n void asyncCleanup();\n});\nprocess.on('exit', () => {\n // Ensure terminal protocols (kitty keyboard, modifyOtherKeys, bracketed paste,\n // raw mode) are disabled on ANY exit path. Without this, killing the process\n // via SIGINT/SIGTERM leaves the terminal in a corrupted state where keypresses\n // produce escape sequences like \"5;99~\" instead of normal characters.\n try {\n tui?.stop();\n } catch {\n // Failsafe: even if MastraTUI.stop() throws, write raw terminal reset\n // sequences to disable Kitty keyboard protocol, bracketed paste, and\n // modifyOtherKeys. These are the exact sequences pi-tui's terminal.stop()\n // would write.\n }\n // Belt-and-suspenders: always write terminal reset sequences directly,\n // regardless of whether tui.stop() succeeded. Writing them twice is harmless\n // but missing them leaves the terminal in a corrupted state.\n try {\n process.stdout.write(\n '\\x1b[?2004l' + // disable bracketed paste\n '\\x1b[<u' + // pop kitty keyboard protocol\n '\\x1b[>4;0m' + // disable modifyOtherKeys\n '\\x1b[?25h', // show cursor\n );\n if (process.stdin.setRawMode) {\n process.stdin.setRawMode(false);\n }\n } catch {\n // stdout may already be closed during exit\n }\n restoreTerminalForeground();\n releaseAllThreadLocks();\n try {\n const threadId = getResumeThreadId?.();\n if (threadId) {\n process.stdout.write(`\\n${formatResumeHint(threadId)}\\n`);\n }\n } catch {\n // session state or stdout may already be closed during exit\n }\n});\n\n// Start durable diagnostics shutdown before synchronous TUI teardown so a stalled\n// terminal cleanup cannot prevent the final profile capture. The exit handler still\n// provides a failsafe terminal reset if teardown throws.\nconst handleTermSignal = () => {\n void asyncCleanup();\n try {\n tui?.stop();\n } catch {\n // ignored — exit handler has failsafe reset\n }\n void shutdownAndExit(0);\n};\nprocess.on('SIGINT', handleTermSignal);\nprocess.on('SIGTERM', handleTermSignal);\nprocess.on('SIGHUP', handleTermSignal);\n\nfunction hasEconnrefused(err: unknown, depth = 0): boolean {\n if (!err || depth > 5) return false;\n const e = err as any;\n if (e.code === 'ECONNREFUSED') return true;\n if (e.cause) return hasEconnrefused(e.cause, depth + 1);\n // AggregateError has .errors array\n if (Array.isArray(e.errors)) return e.errors.some((inner: unknown) => hasEconnrefused(inner, depth + 1));\n return false;\n}\n\nfunction pluginMain(args: string[]): void {\n if (args[0] !== 'scaffold') {\n process.stderr.write('Usage: mastracode plugin scaffold <dir> [--id acme.foo] [--name \"Foo Tools\"]\\n');\n process.exit(1);\n }\n\n const dir = args[1];\n if (!dir) {\n process.stderr.write('Usage: mastracode plugin scaffold <dir> [--id acme.foo] [--name \"Foo Tools\"]\\n');\n process.exit(1);\n }\n\n const id = readFlag(args, '--id');\n const name = readFlag(args, '--name');\n const targetDir = scaffoldPlugin(dir, { ...(id ? { id } : {}), ...(name ? { name } : {}) });\n process.stdout.write(`${formatScaffoldSuccess(targetDir)}\\n`);\n}\n\nfunction readFlag(args: string[], flag: string): string | undefined {\n const index = args.indexOf(flag);\n if (index === -1) return undefined;\n const value = args[index + 1];\n if (!value || value.startsWith('--')) {\n throw new Error(`Missing value for ${flag}`);\n }\n return value;\n}\n\nconst handleFatalError = createOneShotFatalErrorHandler((error: unknown): void => {\n // Always write to real stderr, even if console.error was overridden\n const write = (msg: string) => {\n try {\n process.stderr.write(msg + '\\n');\n } catch {}\n };\n\n if (hasEconnrefused(error)) {\n const settings = loadSettings();\n const connStr = settings.storage?.pg?.connectionString;\n const target = connStr ?? 'localhost:5432';\n write(\n `\\nFailed to connect to PostgreSQL at ${target}.` +\n `\\nMake sure the database is running and accessible.` +\n `\\n\\nTo switch back to LibSQL:` +\n `\\n Set MASTRA_STORAGE_BACKEND=libsql or change the backend in /settings\\n`,\n );\n void asyncCleanup();\n try {\n tui?.stop();\n } catch {}\n void shutdownAndExit(1);\n return;\n }\n\n const msg = `Fatal error: ${error instanceof Error ? error.message : String(error)}`;\n write(msg);\n // Write crash log to file so it persists even if terminal closes\n try {\n const crashLog = `[${new Date().toISOString()}] ${msg}\\n${error instanceof Error && error.stack ? error.stack + '\\n' : ''}`;\n truncateLogFile(CRASH_LOG_PATH);\n fs.appendFileSync(CRASH_LOG_PATH, crashLog);\n truncateLogFile(CRASH_LOG_PATH);\n } catch {}\n if (error instanceof Error && error.stack) {\n write(error.stack);\n }\n void asyncCleanup();\n try {\n tui?.stop();\n } catch {}\n void shutdownAndExit(1);\n});\n\nasync function main() {\n if (process.argv[2] === 'plugin') {\n return pluginMain(process.argv.slice(3));\n }\n\n // Storage maintenance without the TUI, so a database can still be pruned and\n // compacted when the interactive session won't start. Checked before the\n // headless branch below, which would otherwise claim `prune --help`.\n if (process.argv[2] === 'prune') {\n const { runPruneCommand } = await import('@mastra/code-sdk/utils/prune-cli');\n return process.exit(await runPruneCommand(process.argv.slice(3)));\n }\n\n // Also checked before the headless branch, which would send the bare word as a prompt.\n const updateArgs = getUpdateCommandArgs(process.argv);\n if (updateArgs) {\n const code = await runUpdateCommand({ args: updateArgs, currentVersion: getCurrentVersion() });\n await Promise.all(\n [process.stdout, process.stderr].map(stream => new Promise(resolve => stream.write('', resolve))),\n );\n return process.exit(code);\n }\n\n const loginIndex = process.argv.findIndex(\n (arg, index) => index >= 2 && arg !== '--acp' && arg !== '--dangerous-auto-approve',\n );\n if (process.argv[loginIndex] === 'login') {\n const { runLoginCommand } = await import('./login-command.js');\n const code = await runLoginCommand({ args: process.argv.slice(loginIndex + 1) });\n await new Promise(resolve => process.stdout.write('', resolve));\n return process.exit(code);\n }\n\n // --pack is shared with headless mode, which re-parses it from process.argv\n // in runMCCli. Strip it here only for the interactive path's other argv\n // consumers (initial prompt, resume) so the pack id is never mistaken for a\n // positional prompt.\n const packFlag = takePackFlag(process.argv);\n if (packFlag.error) {\n process.stderr.write(`${packFlag.error}\\n`);\n process.exit(1);\n }\n\n const initialPrompt = takeInitialPrompt(packFlag.argv, process.env);\n if (initialPrompt.error) {\n process.stderr.write(`${initialPrompt.error}\\n`);\n process.exit(1);\n }\n if (initialPrompt.flag) process.argv = initialPrompt.argv;\n const tuiArgv = initialPrompt.flag ? initialPrompt.argv : packFlag.argv;\n // The flag only means something to the interactive TUI. Paths that can't run\n // it reject the flag instead of dropping the prompt; an env var prompt is\n // just ignored there.\n const rejectInitialPromptFlag = (reason: string) => {\n if (!initialPrompt.flag) return;\n process.stderr.write(`${initialPrompt.flag} starts the interactive TUI; ${reason}\\n`);\n process.exit(1);\n };\n\n let resumeThreadId: string | undefined;\n try {\n resumeThreadId = parseResumeThreadId(tuiArgv.slice(2));\n } catch (error) {\n process.stderr.write(`${error instanceof Error ? error.message : String(error)}\\n`);\n process.exitCode = 1;\n return;\n }\n\n const headless = hasHeadlessFlag(process.argv);\n if (shouldRunHeadless(process.argv, resumeThreadId, headless)) {\n if (headless) rejectInitialPromptFlag('use --prompt for headless runs');\n return runMCCli(undefined, { coAuthor: TUI_CO_AUTHOR });\n }\n\n if (process.argv.includes('--acp')) {\n rejectInitialPromptFlag('it cannot be combined with --acp');\n const { acpMain } = await import('@mastra/code-sdk/acp/index');\n return acpMain({\n dangerousAutoApprove: process.argv.includes('--dangerous-auto-approve'),\n coAuthor: TUI_CO_AUTHOR,\n });\n }\n\n // Interactive --pack: fail fast on an unknown pack. Validation and\n // activation (which mirrors /models → Activate and becomes the global\n // default in settings) happen in MastraTUI.init after thread resume, once\n // the resumed session mode is known and the pack is confirmed to have a\n // model for it; the TUI then applies it to the session (and any resumed\n // thread) at startup.\n let startupPackId: string | undefined;\n if (packFlag.value !== undefined) {\n const settings = loadSettings();\n const resolved = resolveModePackArg(settings, packFlag.value);\n if ('error' in resolved) {\n process.stderr.write(`Error: ${resolved.error}\\n`);\n process.exit(1);\n }\n startupPackId = resolved.packId;\n if (process.env.MASTRACODE_MODEL_ID?.trim()) {\n process.stderr.write('Note: --pack takes precedence over MASTRACODE_MODEL_ID for this session.\\n');\n }\n }\n\n if (shouldRejectResumeWithoutTTY(resumeThreadId, Boolean(process.stdin.isTTY))) {\n process.stderr.write('mastracode resume requires an interactive terminal.\\n');\n process.exitCode = 1;\n return;\n }\n\n // When stdin is piped (e.g. `cat foo | mastracode`), drain the pipe fully\n // before starting the TUI. The drain blocks until the sender process exits\n // and closes its stdout, so we never see partial output.\n let pipedInput: string | null = null;\n if (!process.stdin.isTTY) {\n process.stderr.write('Reading piped input...\\n');\n pipedInput = await drainPipedStdin();\n\n // Always reopen a real TTY — even if the pipe was empty, the original\n // stdin is consumed/closed and the TUI needs a live TTY for keyboard input.\n const reopenedStdin = reopenStdinFromTTY();\n if (!reopenedStdin) {\n rejectInitialPromptFlag('no TTY is available, so use --prompt for headless runs');\n process.stderr.write('No TTY available — falling back to headless mode.\\n');\n return runMCCli(pipedInput, { coAuthor: TUI_CO_AUTHOR });\n }\n }\n\n const conflict = pipedInputConflict(initialPrompt, pipedInput);\n if (conflict) {\n process.stderr.write(`${conflict}\\n`);\n process.exit(1);\n }\n\n return tuiMain(initialMessageOptions(initialPrompt, pipedInput), resumeThreadId, startupPackId);\n}\n\nmain().catch(error => {\n handleFatalError(error);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA,MAAa,sBAAsB;AACnC,MAAa,qBAAqB;AAElC,MAAa,kBAAkB;;;;;;;;;;AA0B/B,SAAgB,kBAAkB,MAAgB,KAA2C;CAC3F,MAAM,UAAU,IAAI;CACpB,OAAO,IAAI;CAEX,MAAM,OAAiB,CAAC;CACxB,MAAM,wBAAQ,IAAI,IAAoD;CACtE,IAAI;CACJ,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;EACpC,MAAM,MAAM,KAAK;EACjB,MAAM,OAAO,CAAC,qBAAqB,eAAe,CAAC,CAAC,MAAK,MAAK,QAAQ,KAAK,IAAI,WAAW,GAAG,EAAE,EAAE,CAAC;EAClG,IAAI,CAAC,MACH,KAAK,KAAK,GAAG;OACR,IAAI,QAAQ,MACjB,MAAM,IAAI,MAAM,IAAI,MAAM,KAAK,SAAS,CAAC,CAAC;OACrC,IAAI,KAAK,IAAI,OAAO,KAAA,GACzB,QAAQ,GAAG,KAAK;OAEhB,MAAM,IAAI,MAAM,KAAK,EAAE,EAAG;CAE9B;CACA,IAAI,MAAM,OAAO,GAAG,QAAQ,cAAc,oBAAoB,MAAM,gBAAgB;CAEpF,MAAM,CAAC,MAAM,aAAa,CAAC,GAAG,KAAK,CAAC,CAAC,MAAM,CAAC;CAE5C,OAAO;EAAE,MAAM;EAAM,SADL,OAAO,YAAY,QAAA,EAAU,KAAK,KAAK,KAAA;EAC1B;EAAO;EAAM,cAAc,SAAS;CAAgB;AACnF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