mastracode 0.48.1-alpha.3 → 0.48.1-alpha.5
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 +77 -0
- package/dist/cli.cjs +10 -21
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +11 -22
- 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/{login-command-DmwsIJrs.cjs → login-command-COPViada.cjs} +2 -3
- package/dist/{login-command-DmwsIJrs.cjs.map → login-command-COPViada.cjs.map} +1 -1
- package/dist/{login-command-yRvnvSo-.js → login-command-EvJk2jIW.js} +2 -3
- package/dist/{login-command-yRvnvSo-.js.map → login-command-EvJk2jIW.js.map} +1 -1
- package/dist/tui/commands/login.d.ts.map +1 -1
- package/dist/tui/commands/workflows.d.ts.map +1 -1
- package/dist/tui/detect-theme.d.ts.map +1 -1
- package/dist/tui/display.d.ts.map +1 -1
- package/dist/tui/onboarding-inline.d.ts.map +1 -1
- package/dist/tui/setup.d.ts.map +1 -1
- package/dist/{tui-NWh1Dtvz.js → tui-BMD4bPSG.js} +178 -356
- package/dist/tui-BMD4bPSG.js.map +1 -0
- package/dist/{tui-cKViKRi_.cjs → tui-Bj6tHGMd.cjs} +179 -358
- package/dist/tui-Bj6tHGMd.cjs.map +1 -0
- package/dist/tui.cjs +1 -1
- package/dist/tui.js +1 -1
- package/package.json +32 -32
- package/dist/subagent-settings.d.ts +0 -2
- package/dist/subagent-settings.d.ts.map +0 -1
- package/dist/tui-NWh1Dtvz.js.map +0 -1
- package/dist/tui-cKViKRi_.cjs.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,82 @@
|
|
|
1
1
|
# mastracode
|
|
2
2
|
|
|
3
|
+
## 0.48.1-alpha.5
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Fixed tool calls on Amazon Bedrock models failing with `AI_TypeValidationError` when zod 4.4 or newer is installed. Bedrock streams the start of a tool call without its input, which the old `@ai-sdk/amazon-bedrock` 3.x schema rejected. The Bedrock provider is now `@ai-sdk/amazon-bedrock` v5, which accepts these events. ([#28515](https://github.com/mastra-ai/mastra/pull/28515))
|
|
8
|
+
|
|
9
|
+
- An exhausted provider quota now shows its own error and a hint to check the account's billing or usage allowance, instead of being reported as a rate limit with "Wait a moment and try again". ([#28496](https://github.com/mastra-ai/mastra/pull/28496))
|
|
10
|
+
|
|
11
|
+
Account rotation and transient server error detection now read failures through the shared provider error reader in `@mastra/core/error`. A credential, usage or rate-limit failure named only in a provider's response body or stream frame now rotates to the next account, and an overloaded stream frame is retried as a server error.
|
|
12
|
+
|
|
13
|
+
- Mastra Code no longer registers subagents unless you turn them on. `createMastraCode()` and `mountAgentControllerOnMastra()` now default `subagents` to an empty list. ([#28600](https://github.com/mastra-ai/mastra/pull/28600))
|
|
14
|
+
|
|
15
|
+
Before, omitting `subagents` registered the explore, plan and execute subagents:
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
await createMastraCode();
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
After, pass `builtinSubagents` to keep them:
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
import { builtinSubagents, createMastraCode } from '@mastra/code-sdk';
|
|
25
|
+
|
|
26
|
+
await createMastraCode({ subagents: [...builtinSubagents] });
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
The same applies to `mountAgentControllerOnMastra()`.
|
|
30
|
+
|
|
31
|
+
The TUI, headless `mastracode --prompt` runs and ACP sessions all read the `subagentsEnabled` setting (toggled with `/subagents`, off by default), so subagents only run when a user opts in.
|
|
32
|
+
|
|
33
|
+
- Updated dependencies [[`4cfae01`](https://github.com/mastra-ai/mastra/commit/4cfae01571df81b9ca31d859c317e269e45d8b92), [`24a821b`](https://github.com/mastra-ai/mastra/commit/24a821b0ff29f527787c0645a7bf7bbe50d27f57), [`1fc075a`](https://github.com/mastra-ai/mastra/commit/1fc075ab7f7eddca854512d21149db8212f422eb), [`38ff787`](https://github.com/mastra-ai/mastra/commit/38ff787998d56210cfd938439af0fea68703a196), [`1fc075a`](https://github.com/mastra-ai/mastra/commit/1fc075ab7f7eddca854512d21149db8212f422eb), [`1fc075a`](https://github.com/mastra-ai/mastra/commit/1fc075ab7f7eddca854512d21149db8212f422eb), [`38ff787`](https://github.com/mastra-ai/mastra/commit/38ff787998d56210cfd938439af0fea68703a196), [`4ad204d`](https://github.com/mastra-ai/mastra/commit/4ad204dc5bdde76dca26cb7d87c48dd11f97316d), [`9ffb79b`](https://github.com/mastra-ai/mastra/commit/9ffb79b17e6ed0f0ec6bd1640218ef2a5fb7c058), [`155e3ac`](https://github.com/mastra-ai/mastra/commit/155e3aca3e57114ce3393bd88f6848c29f37c82b), [`7c20f00`](https://github.com/mastra-ai/mastra/commit/7c20f008c84db8f4f49e6e95d6dc965482bb2039), [`4ad204d`](https://github.com/mastra-ai/mastra/commit/4ad204dc5bdde76dca26cb7d87c48dd11f97316d), [`680b01a`](https://github.com/mastra-ai/mastra/commit/680b01acd54b1af3f18d20d8deb9c42d35258902), [`e56f88e`](https://github.com/mastra-ai/mastra/commit/e56f88e18d906635b033173abcae637cf361ce8a), [`cd4722a`](https://github.com/mastra-ai/mastra/commit/cd4722a583a0eb75022b1da6a6f8210f8126e486), [`5e88354`](https://github.com/mastra-ai/mastra/commit/5e883545edd6082e741cdce1d192e0e83fa5dc2e), [`2499c00`](https://github.com/mastra-ai/mastra/commit/2499c00181520cf7cda756729dc0e0085b85454f), [`c9445e0`](https://github.com/mastra-ai/mastra/commit/c9445e008d8036cad08bca9dd61b698d72fa96bf), [`d580530`](https://github.com/mastra-ai/mastra/commit/d580530ff36d43e752b1f838b3f8e16017e8f92b), [`4fc17c6`](https://github.com/mastra-ai/mastra/commit/4fc17c65e85628a71201bf7490fca1db8376cf71), [`682ebf6`](https://github.com/mastra-ai/mastra/commit/682ebf6b6f867224acbcb021fc142b902738ad07), [`dd6205e`](https://github.com/mastra-ai/mastra/commit/dd6205e985e5fd76b59d000076ab199143c989eb), [`97ade4e`](https://github.com/mastra-ai/mastra/commit/97ade4e8621a9afd01a1f38b921519ddc3086568), [`c8b8e27`](https://github.com/mastra-ai/mastra/commit/c8b8e27e9b26d9a08bc61d2e663804f25ae4fa2d), [`1fc075a`](https://github.com/mastra-ai/mastra/commit/1fc075ab7f7eddca854512d21149db8212f422eb), [`d1aee64`](https://github.com/mastra-ai/mastra/commit/d1aee64e65968744c118440d2d01eb4fba3616d6), [`0b7e619`](https://github.com/mastra-ai/mastra/commit/0b7e61996ede043dc4b134fc35b1fff51d638a46), [`9a9085e`](https://github.com/mastra-ai/mastra/commit/9a9085ef3481c31093152ea9976759c72dc3fd89), [`9a83d42`](https://github.com/mastra-ai/mastra/commit/9a83d42b2461dd1629021d05704939b641330d5b), [`2447071`](https://github.com/mastra-ai/mastra/commit/2447071b11d7a5f159e6dc726eb5df0aa0db69da), [`709a1da`](https://github.com/mastra-ai/mastra/commit/709a1daa64843cc92ac0b817c4dc05b2efdc92ac), [`ab1727d`](https://github.com/mastra-ai/mastra/commit/ab1727d5cafb64e36b04fad9f8871dc6640d2420), [`ab1727d`](https://github.com/mastra-ai/mastra/commit/ab1727d5cafb64e36b04fad9f8871dc6640d2420), [`ab1727d`](https://github.com/mastra-ai/mastra/commit/ab1727d5cafb64e36b04fad9f8871dc6640d2420), [`ab1727d`](https://github.com/mastra-ai/mastra/commit/ab1727d5cafb64e36b04fad9f8871dc6640d2420), [`4fc17c6`](https://github.com/mastra-ai/mastra/commit/4fc17c65e85628a71201bf7490fca1db8376cf71), [`ddb7721`](https://github.com/mastra-ai/mastra/commit/ddb77211bc797c45fe434baac5c44c4193c1381e), [`d1aee64`](https://github.com/mastra-ai/mastra/commit/d1aee64e65968744c118440d2d01eb4fba3616d6), [`852110d`](https://github.com/mastra-ai/mastra/commit/852110d4eeaf5ab74ea94747343501700033a1e8), [`5e88354`](https://github.com/mastra-ai/mastra/commit/5e883545edd6082e741cdce1d192e0e83fa5dc2e), [`5bb592a`](https://github.com/mastra-ai/mastra/commit/5bb592a862869d529d8d6ca48772cd0e1863f224), [`4278b9d`](https://github.com/mastra-ai/mastra/commit/4278b9dfb8aef7f274e4dfb102597cc0400475ee), [`45c1d16`](https://github.com/mastra-ai/mastra/commit/45c1d16c4f0cd3e5b18d2a788fb998c70b45b7c0), [`a9f392e`](https://github.com/mastra-ai/mastra/commit/a9f392e60e5bc1fab66280314bab5f697e8d7c09), [`0811cda`](https://github.com/mastra-ai/mastra/commit/0811cda8d22476cf1393b429a63aaefa5292048c), [`3cdaaa8`](https://github.com/mastra-ai/mastra/commit/3cdaaa86f48812bdae1077e55be1d58dd5e85fc5), [`852110d`](https://github.com/mastra-ai/mastra/commit/852110d4eeaf5ab74ea94747343501700033a1e8), [`b63456b`](https://github.com/mastra-ai/mastra/commit/b63456befb5f51d1a2b1288225f02c30738b6099), [`580452a`](https://github.com/mastra-ai/mastra/commit/580452acbbb9812eae1b31d4f3ded716c348a78b)]:
|
|
34
|
+
- @mastra/code-sdk@1.16.0-alpha.6
|
|
35
|
+
- @mastra/core@1.80.0-alpha.5
|
|
36
|
+
- @mastra/observability@1.22.0-alpha.3
|
|
37
|
+
- @mastra/fastembed@1.3.5-alpha.3
|
|
38
|
+
- @mastra/libsql@1.27.1-alpha.1
|
|
39
|
+
- @mastra/pg@1.33.0-alpha.3
|
|
40
|
+
- @mastra/mcp@2.6.0-alpha.2
|
|
41
|
+
- @mastra/memory@1.39.1-alpha.3
|
|
42
|
+
- @mastra/duckdb@1.16.0-alpha.2
|
|
43
|
+
|
|
44
|
+
## 0.48.1-alpha.4
|
|
45
|
+
|
|
46
|
+
### Patch Changes
|
|
47
|
+
|
|
48
|
+
- dependencies updates: ([#28417](https://github.com/mastra-ai/mastra/pull/28417))
|
|
49
|
+
- Updated dependency [`@agentclientprotocol/sdk@^0.21.1` ↗︎](https://www.npmjs.com/package/@agentclientprotocol/sdk/v/0.21.1) (from `^0.21.0`, in `dependencies`)
|
|
50
|
+
- Updated dependency [`@ai-sdk/amazon-bedrock@^3.0.141` ↗︎](https://www.npmjs.com/package/@ai-sdk/amazon-bedrock/v/3.0.141) (from `^3.0.140`, in `dependencies`)
|
|
51
|
+
- Updated dependency [`@ai-sdk/anthropic@^3.0.135` ↗︎](https://www.npmjs.com/package/@ai-sdk/anthropic/v/3.0.135) (from `^3.0.133`, in `dependencies`)
|
|
52
|
+
- Updated dependency [`@ai-sdk/openai@^3.0.131` ↗︎](https://www.npmjs.com/package/@ai-sdk/openai/v/3.0.131) (from `^3.0.130`, in `dependencies`)
|
|
53
|
+
- Updated dependency [`@ai-sdk/openai-compatible@^2.0.87` ↗︎](https://www.npmjs.com/package/@ai-sdk/openai-compatible/v/2.0.87) (from `^2.0.85`, in `dependencies`)
|
|
54
|
+
- Updated dependency [`@ast-grep/napi@^0.42.3` ↗︎](https://www.npmjs.com/package/@ast-grep/napi/v/0.42.3) (from `^0.42.0`, in `dependencies`)
|
|
55
|
+
- Updated dependency [`@aws-sdk/credential-providers@^3.1156.0` ↗︎](https://www.npmjs.com/package/@aws-sdk/credential-providers/v/3.1156.0) (from `^3.1095.0`, in `dependencies`)
|
|
56
|
+
- Updated dependency [`ai@^6.0.315` ↗︎](https://www.npmjs.com/package/ai/v/6.0.315) (from `^6.0.309`, in `dependencies`)
|
|
57
|
+
- Updated dependency [`chalk@^5.6.2` ↗︎](https://www.npmjs.com/package/chalk/v/5.6.2) (from `^5.5.0`, in `dependencies`)
|
|
58
|
+
- Updated dependency [`posthog-node@^5.57.1` ↗︎](https://www.npmjs.com/package/posthog-node/v/5.57.1) (from `^5.46.1`, in `dependencies`)
|
|
59
|
+
- Updated dependency [`tokenx@^1.6.0` ↗︎](https://www.npmjs.com/package/tokenx/v/1.6.0) (from `^1.3.0`, in `dependencies`)
|
|
60
|
+
- Updated dependency [`vscode-languageserver-protocol@^3.18.5` ↗︎](https://www.npmjs.com/package/vscode-languageserver-protocol/v/3.18.5) (from `^3.18.4`, in `dependencies`)
|
|
61
|
+
- Updated dependency [`yaml@^2.9.1` ↗︎](https://www.npmjs.com/package/yaml/v/2.9.1) (from `^2.7.1`, in `dependencies`)
|
|
62
|
+
- Updated dependency [`@copilotkit/aimock@^1.46.0` ↗︎](https://www.npmjs.com/package/@copilotkit/aimock/v/1.46.0) (from `^1.29.0`, in `devDependencies`)
|
|
63
|
+
- Updated dependency [`@types/node@22.19.15` ↗︎](https://www.npmjs.com/package/@types/node/v/22.19.15) (from `22.20.5`, in `devDependencies`)
|
|
64
|
+
- Updated dependencies [[`ce5d473`](https://github.com/mastra-ai/mastra/commit/ce5d4731eeeb44779748852618b95c5cb6485bed), [`ce5d473`](https://github.com/mastra-ai/mastra/commit/ce5d4731eeeb44779748852618b95c5cb6485bed), [`ce5d473`](https://github.com/mastra-ai/mastra/commit/ce5d4731eeeb44779748852618b95c5cb6485bed), [`ce5d473`](https://github.com/mastra-ai/mastra/commit/ce5d4731eeeb44779748852618b95c5cb6485bed), [`ce5d473`](https://github.com/mastra-ai/mastra/commit/ce5d4731eeeb44779748852618b95c5cb6485bed), [`ce5d473`](https://github.com/mastra-ai/mastra/commit/ce5d4731eeeb44779748852618b95c5cb6485bed), [`ce5d473`](https://github.com/mastra-ai/mastra/commit/ce5d4731eeeb44779748852618b95c5cb6485bed), [`ce5d473`](https://github.com/mastra-ai/mastra/commit/ce5d4731eeeb44779748852618b95c5cb6485bed), [`ce5d473`](https://github.com/mastra-ai/mastra/commit/ce5d4731eeeb44779748852618b95c5cb6485bed), [`ce5d473`](https://github.com/mastra-ai/mastra/commit/ce5d4731eeeb44779748852618b95c5cb6485bed), [`ce5d473`](https://github.com/mastra-ai/mastra/commit/ce5d4731eeeb44779748852618b95c5cb6485bed), [`ce5d473`](https://github.com/mastra-ai/mastra/commit/ce5d4731eeeb44779748852618b95c5cb6485bed), [`ce5d473`](https://github.com/mastra-ai/mastra/commit/ce5d4731eeeb44779748852618b95c5cb6485bed), [`ce5d473`](https://github.com/mastra-ai/mastra/commit/ce5d4731eeeb44779748852618b95c5cb6485bed), [`0a913e0`](https://github.com/mastra-ai/mastra/commit/0a913e096cb569aea396fa3d9f286cc874179ce8), [`3dfe2eb`](https://github.com/mastra-ai/mastra/commit/3dfe2eb8c3ef3b18d2395a3618b6214488963d05), [`152e380`](https://github.com/mastra-ai/mastra/commit/152e380aca6fcf74f598a158c710c0e755ceb325), [`99e4867`](https://github.com/mastra-ai/mastra/commit/99e486723d3f0063ae70a39c9840daf92a98fa23), [`929a728`](https://github.com/mastra-ai/mastra/commit/929a7281d411ac515e0befb53a5383741b06d484), [`52db47c`](https://github.com/mastra-ai/mastra/commit/52db47cd0d66f891d41a2dbfa36e55b640a30a37), [`14f209c`](https://github.com/mastra-ai/mastra/commit/14f209ceefc27d0ee75773fd4aa3e8160cdccab5), [`7adffbb`](https://github.com/mastra-ai/mastra/commit/7adffbb3df2f734b59648dcf8d461e7af8d1f914), [`f51a29e`](https://github.com/mastra-ai/mastra/commit/f51a29e82b6e2371b5c6aed46141ce20f099c9a9), [`3dfe2eb`](https://github.com/mastra-ai/mastra/commit/3dfe2eb8c3ef3b18d2395a3618b6214488963d05), [`063b292`](https://github.com/mastra-ai/mastra/commit/063b292e15d0c09b7c77d9c0d162792ccf5985d8), [`0f2c708`](https://github.com/mastra-ai/mastra/commit/0f2c70879a336fd00ae55a1474651fe418563dd3), [`c73d201`](https://github.com/mastra-ai/mastra/commit/c73d201c620760d9699901b2460f728a8ca19c1e), [`1bc29c2`](https://github.com/mastra-ai/mastra/commit/1bc29c2406dcba63e310e7c7691425b0257f11d0), [`279e890`](https://github.com/mastra-ai/mastra/commit/279e89061cd6327d4870b864e8d90fe0b873a72e), [`5c0a994`](https://github.com/mastra-ai/mastra/commit/5c0a99438ef82cf5584218f250a023371bab3373), [`7adffbb`](https://github.com/mastra-ai/mastra/commit/7adffbb3df2f734b59648dcf8d461e7af8d1f914), [`ffc663d`](https://github.com/mastra-ai/mastra/commit/ffc663d2ba4f9c301cbc03ca17c12e351f27330f), [`823a389`](https://github.com/mastra-ai/mastra/commit/823a3890deb5cf14484fd655c8360df4c41c4aed), [`ff35b8c`](https://github.com/mastra-ai/mastra/commit/ff35b8c3d86136509d31b87fed7f789a572dc1af), [`501b207`](https://github.com/mastra-ai/mastra/commit/501b207b1b6300af44b5b8f40ff33adfe7a9d195), [`d9245dd`](https://github.com/mastra-ai/mastra/commit/d9245dd486349163bfc6468ab45e5600abc6a59e), [`358c711`](https://github.com/mastra-ai/mastra/commit/358c71145d677394ce03a019156bc464afe6cc76), [`dbdfaee`](https://github.com/mastra-ai/mastra/commit/dbdfaee279dab2a5dca31134ca1967eb582e639c), [`52db47c`](https://github.com/mastra-ai/mastra/commit/52db47cd0d66f891d41a2dbfa36e55b640a30a37), [`87e9194`](https://github.com/mastra-ai/mastra/commit/87e91941fffd04b20a7416437a80fcd522b2a9b6), [`fdd2201`](https://github.com/mastra-ai/mastra/commit/fdd22014f6fbfa115eba53cff42063544af2ff41), [`501b207`](https://github.com/mastra-ai/mastra/commit/501b207b1b6300af44b5b8f40ff33adfe7a9d195), [`68f311e`](https://github.com/mastra-ai/mastra/commit/68f311e0dac06b2ff337727d8e72892f1d8d337f), [`4303017`](https://github.com/mastra-ai/mastra/commit/4303017f393b9c09f692837d8e9e7a19f6539cf4)]:
|
|
65
|
+
- @mastra/agent-browser@0.5.5-alpha.0
|
|
66
|
+
- @mastra/code-sdk@1.15.1-alpha.5
|
|
67
|
+
- @mastra/core@1.80.0-alpha.4
|
|
68
|
+
- @mastra/duckdb@1.16.0-alpha.1
|
|
69
|
+
- @mastra/fastembed@1.3.5-alpha.2
|
|
70
|
+
- @mastra/libsql@1.27.1-alpha.0
|
|
71
|
+
- @mastra/mcp@2.6.0-alpha.1
|
|
72
|
+
- @mastra/memory@1.39.1-alpha.2
|
|
73
|
+
- @mastra/observability@1.21.1-alpha.2
|
|
74
|
+
- @mastra/pg@1.33.0-alpha.2
|
|
75
|
+
- @mastra/schema-compat@1.3.17-alpha.0
|
|
76
|
+
- @mastra/stagehand@0.3.7-alpha.1
|
|
77
|
+
- @mastra/voice-deepgram@0.13.3-alpha.0
|
|
78
|
+
- @mastra/voice-openai@0.13.4-alpha.0
|
|
79
|
+
|
|
3
80
|
## 0.48.1-alpha.3
|
|
4
81
|
|
|
5
82
|
### Patch Changes
|
package/dist/cli.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
const require_tui = require("./tui-
|
|
2
|
+
const require_tui = require("./tui-Bj6tHGMd.cjs");
|
|
3
3
|
let _mastra_code_sdk = require("@mastra/code-sdk");
|
|
4
4
|
let child_process = require("child_process");
|
|
5
5
|
let fs = require("fs");
|
|
@@ -19,7 +19,7 @@ let _mastra_code_sdk_utils_stdin_pipe = require("@mastra/code-sdk/utils/stdin-pi
|
|
|
19
19
|
let _mastra_code_sdk_utils_thread_lock = require("@mastra/code-sdk/utils/thread-lock");
|
|
20
20
|
let chalk = require("chalk");
|
|
21
21
|
let _mastra_code_sdk_utils_update_check = require("@mastra/code-sdk/utils/update-check");
|
|
22
|
-
|
|
22
|
+
// src/initial-prompt.ts
|
|
23
23
|
const INITIAL_PROMPT_FLAG = "--tui-initial-prompt";
|
|
24
24
|
const INITIAL_PROMPT_ENV = "MASTRACODE_TUI_INITIAL_PROMPT";
|
|
25
25
|
const TUI_PROMPT_FLAG = "--tui-prompt";
|
|
@@ -119,8 +119,7 @@ function takePackFlag(argv) {
|
|
|
119
119
|
...error ? { error } : {}
|
|
120
120
|
};
|
|
121
121
|
}
|
|
122
|
-
|
|
123
|
-
//#region src/process-memory-diagnostics-lifecycle.ts
|
|
122
|
+
// src/process-memory-diagnostics-lifecycle.ts
|
|
124
123
|
async function startTuiProcessMemoryDiagnostics(env, warn, createSetup = _mastra_code_sdk_process_memory_diagnostics.createProcessMemoryDiagnosticsFromEnvironment) {
|
|
125
124
|
return (0, _mastra_code_sdk_process_memory_diagnostics.startConfiguredProcessMemoryDiagnostics)(createSetup(env), warn);
|
|
126
125
|
}
|
|
@@ -146,8 +145,7 @@ function createShutdownCoordinator(cleanup, exit, timeoutMs = 5e3) {
|
|
|
146
145
|
return shutdownPromise;
|
|
147
146
|
};
|
|
148
147
|
}
|
|
149
|
-
|
|
150
|
-
//#region src/resume-command.ts
|
|
148
|
+
// src/resume-command.ts
|
|
151
149
|
function parseResumeThreadId(args) {
|
|
152
150
|
if (args[0] !== "resume") return void 0;
|
|
153
151
|
const threadId = args[1]?.trim();
|
|
@@ -174,13 +172,7 @@ function formatResumeHint(threadId) {
|
|
|
174
172
|
return character;
|
|
175
173
|
}).join("")}'` : `'${threadId.replaceAll("'", "'\\''")}'`}`;
|
|
176
174
|
}
|
|
177
|
-
|
|
178
|
-
//#region src/subagent-settings.ts
|
|
179
|
-
function resolveTuiSubagents(enabled) {
|
|
180
|
-
return enabled ? void 0 : [];
|
|
181
|
-
}
|
|
182
|
-
//#endregion
|
|
183
|
-
//#region src/update-command.ts
|
|
175
|
+
// src/update-command.ts
|
|
184
176
|
const UPDATE_COMMANDS = /* @__PURE__ */ new Set(["update", "upgrade"]);
|
|
185
177
|
const USAGE = "Usage: mastracode update\n\nInstall the latest version of Mastra Code. `mastracode upgrade` is an alias.";
|
|
186
178
|
const SPINNER_FRAMES = [
|
|
@@ -271,13 +263,11 @@ async function runUpdateCommand({ args = [], output = process.stdout, errorOutpu
|
|
|
271
263
|
}
|
|
272
264
|
return fail(...require_tui.formatUpdateOutcome(errorStyle, outcome, latestVersion));
|
|
273
265
|
}
|
|
274
|
-
|
|
275
|
-
//#region src/version.ts
|
|
266
|
+
// src/version.ts
|
|
276
267
|
function getCurrentVersion() {
|
|
277
|
-
return "0.48.1-alpha.
|
|
268
|
+
return "0.48.1-alpha.5";
|
|
278
269
|
}
|
|
279
|
-
|
|
280
|
-
//#region src/main.ts
|
|
270
|
+
// src/main.ts
|
|
281
271
|
/**
|
|
282
272
|
* Main entry point for Mastra Code TUI.
|
|
283
273
|
*/
|
|
@@ -409,7 +399,7 @@ async function bootLocal(settings, themeMode, startupMessage, resumeThreadId, st
|
|
|
409
399
|
unixSocketPubSub: !isTruthyEnv("MASTRACODE_DISABLE_UNIX_SOCKET_PUBSUB"),
|
|
410
400
|
disableMcp: isTruthyEnv("MASTRACODE_DISABLE_MCP"),
|
|
411
401
|
disableHooks: isTruthyEnv("MASTRACODE_DISABLE_HOOKS"),
|
|
412
|
-
subagents:
|
|
402
|
+
subagents: (0, _mastra_code_sdk.resolveSubagentsSetting)(settings.preferences.subagentsEnabled),
|
|
413
403
|
...isTruthyEnv("MASTRACODE_DISABLE_MEMORY") ? { memory: false } : {},
|
|
414
404
|
...initialState ? { initialState } : {}
|
|
415
405
|
});
|
|
@@ -641,7 +631,7 @@ async function main() {
|
|
|
641
631
|
}
|
|
642
632
|
const loginIndex = process.argv.findIndex((arg, index) => index >= 2 && arg !== "--acp" && arg !== "--dangerous-auto-approve");
|
|
643
633
|
if (process.argv[loginIndex] === "login") {
|
|
644
|
-
const { runLoginCommand } = await Promise.resolve().then(() => require("./login-command-
|
|
634
|
+
const { runLoginCommand } = await Promise.resolve().then(() => require("./login-command-COPViada.cjs"));
|
|
645
635
|
const code = await runLoginCommand({ args: process.argv.slice(loginIndex + 1) });
|
|
646
636
|
await new Promise((resolve) => process.stdout.write("", resolve));
|
|
647
637
|
return process.exit(code);
|
|
@@ -720,6 +710,5 @@ async function main() {
|
|
|
720
710
|
main().catch((error) => {
|
|
721
711
|
handleFatalError(error);
|
|
722
712
|
});
|
|
723
|
-
//#endregion
|
|
724
713
|
|
|
725
714
|
//# sourceMappingURL=cli.cjs.map
|
package/dist/cli.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.cjs","names":["createProcessMemoryDiagnosticsFromEnvironment","startConfiguredProcessMemoryDiagnostics","chalk","Chalk","fetchLatestVersion","isNewerVersion","formatUpdateHeader","formatRegistryError","formatUpToDate","detectPackageManager","planUpdate","formatUpdateOutcome","formatInstallingLabel","performUpdate","isStreamDestroyedError","loadSettings","normalizeThemePreference","applyThemePreference","createMastraCodeAnalytics","getPlatformSession","RemoteSession","RemoteController","MastraTUI","createBrowserFromSettings","createMastraCode","TUI_CO_AUTHOR","toActiveBrowserSettings","resolveStagehandModel","stopProcessMemoryDiagnosticsWithTimeout","spawn","scaffoldPlugin","formatScaffoldSuccess","hasHeadlessFlag","runMCCli","resolveModePackArg","drainPipedStdin","reopenStdinFromTTY"],"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} from '@mastra/code-sdk/process-memory-diagnostics';\nimport type {\n ProcessMemoryDiagnostics,\n ProcessMemoryDiagnosticsEnvironment,\n 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 { spawn } from 'node:child_process';\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 { RemoteController } from '@mastra/code-sdk/factory/remote-controller';\nimport { RemoteSession } from '@mastra/code-sdk/factory/remote-session';\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 type { FactoryConnectionSettings } from '@mastra/code-sdk/onboarding/settings';\nimport { getPlatformSession } from '@mastra/code-sdk/platform/index';\nimport { formatScaffoldSuccess, scaffoldPlugin } from '@mastra/code-sdk/plugins/scaffold';\nimport { stopProcessMemoryDiagnosticsWithTimeout } from '@mastra/code-sdk/process-memory-diagnostics';\nimport type { ProcessMemoryDiagnostics } 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 { applyThemePreference, normalizeThemePreference } from './tui/commands/theme.js';\nimport { MastraTUI } from './tui/index.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;\nlet remoteSession: RemoteSession | 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\ntype StartupMessage = ReturnType<typeof initialMessageOptions>;\n\nasync function tuiMain(startupMessage: StartupMessage = {}, resumeThreadId?: string, startupPackId?: string) {\n const settings = loadSettings();\n processMemoryDiagnostics = await startTuiProcessMemoryDiagnostics(process.env, warning => {\n console.info(`⚠ ${warning}`);\n });\n\n setupDebugLogging();\n\n // Detect and apply terminal theme\n // MASTRA_THEME env var is the highest-priority override (mode name or custom theme name)\n const envTheme = normalizeThemePreference(process.env.MASTRA_THEME ?? '');\n const themeMode = envTheme || settings.preferences.theme || 'auto';\n await applyThemePreference(themeMode);\n\n analytics = createMastraCodeAnalytics({ version: getCurrentVersion() });\n if (settings.factory && settings.factory.active !== false && !isTruthyEnv('MASTRACODE_LOCAL')) {\n const ignored = [resumeThreadId && 'thread resume', startupPackId && 'model pack'].filter(Boolean);\n if (ignored.length > 0) console.info(`⚠ Factory mode ignores the requested ${ignored.join(' and ')}.`);\n try {\n return await bootFactory(settings.factory, themeMode, startupMessage);\n } catch (error) {\n // Never lock the user out of the TUI: they need it running to reconnect or disconnect.\n console.info(\n `⚠ Could not reach Factory ${settings.factory.factoryProjectName} (${(error as Error).message}). ` +\n 'Running locally — use /factory to retry or /factory disconnect to forget it.',\n );\n }\n }\n return bootLocal(settings, themeMode, startupMessage, resumeThreadId, startupPackId);\n}\n\n/**\n * Factory client: the agent, tools, storage, and model auth live in the Factory.\n * Nothing local is constructed; the TUI only renders and forwards input.\n */\nasync function bootFactory(factory: FactoryConnectionSettings, themeMode: string, startupMessage: StartupMessage) {\n const platform = await getPlatformSession();\n if (!platform) throw new Error('Mastra Platform login expired');\n const address = { url: factory.url, session: { token: platform.token, orgId: factory.orgId } };\n const session = new RemoteSession(address, factory.sessionId);\n const remoteController = new RemoteController(address);\n try {\n await Promise.all([session.connect(), remoteController.connect()]);\n } catch (error) {\n session.disconnect();\n throw error;\n }\n remoteSession = session;\n session.setModes(remoteController.listModes());\n getResumeThreadId = () => (tui ? tui.getResumeThreadId() : session.thread.getId());\n\n analytics?.capture('mastracode_session_started', {\n mode: session.mode.get(),\n resourceId: session.identity.getResourceId(),\n runtime: 'factory',\n theme: themeMode,\n });\n\n tui = new MastraTUI({\n runtime: 'factory',\n controller: remoteController,\n session,\n factory: {\n projectName: factory.factoryProjectName,\n repositorySlug: factory.repositorySlug,\n branch: factory.branch,\n url: factory.url,\n },\n analytics,\n processMemoryDiagnostics,\n appName: 'Mastra Code',\n version: getCurrentVersion(),\n inlineQuestions: true,\n exit: exitCode => void shutdownAndExit(exitCode),\n relaunch,\n ...startupMessage,\n });\n tui.run().catch(error => {\n handleFatalError(error);\n });\n}\n\nasync function bootLocal(\n settings: ReturnType<typeof loadSettings>,\n themeMode: string,\n startupMessage: StartupMessage,\n resumeThreadId?: string,\n startupPackId?: string,\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 // 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?.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 runtime: 'local',\n });\n\n tui = new MastraTUI({\n 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 relaunch,\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 remoteSession?.disconnect();\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\n/**\n * Restart Mastra Code so it boots in whichever mode settings now select. The\n * startup prompt and resume flags are dropped: they were for the previous run.\n */\nasync function relaunch(): Promise<void> {\n await asyncCleanup();\n tui?.stop();\n const env = { ...process.env };\n delete env.MASTRACODE_LOCAL;\n const args = [...process.execArgv, process.argv[1]!];\n const execve = (process as { execve?: (file: string, args: string[], env: NodeJS.ProcessEnv) => never }).execve;\n if (execve) execve(process.execPath, [process.execPath, ...args], env);\n // No in-place exec (Windows, older Node): hand the terminal to a child and mirror its exit.\n // The child shares the terminal's process group and handles Ctrl+C itself.\n for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP'] as const) {\n process.removeAllListeners(signal);\n process.on(signal, () => {});\n }\n // Release stdin so the child is the only reader of terminal input.\n process.stdin.removeAllListeners('data');\n process.stdin.pause();\n const child = spawn(process.execPath, args, { stdio: 'inherit', env });\n child.on('error', error => {\n console.error(`Failed to restart Mastra Code: ${error.message}`);\n process.exit(1);\n });\n child.on('exit', code => process.exit(code ?? 0));\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 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,KAA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AAI,EAAA,GADkBC,kCAAAA,mBAAAA,CACL,GAAG;GAClB,wBAAwB,wDAAwD;GAChF,QAAQ,OAAO,MAAM,qDAAqD;GAC1E,QAAA,GAAOH,gCAAAA,SAAAA,CAAS,YAAY,EAAE,UAAUR,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,gBAAgB,aAAa;AAChG;AAEA,KAAK,CAAC,CAAC,OAAM,UAAS;CACpB,iBAAiB,KAAK;AACxB,CAAC"}
|
|
1
|
+
{"version":3,"file":"cli.cjs","names":["createProcessMemoryDiagnosticsFromEnvironment","startConfiguredProcessMemoryDiagnostics","chalk","Chalk","fetchLatestVersion","isNewerVersion","formatUpdateHeader","formatRegistryError","formatUpToDate","detectPackageManager","planUpdate","formatUpdateOutcome","formatInstallingLabel","performUpdate","isStreamDestroyedError","loadSettings","normalizeThemePreference","applyThemePreference","createMastraCodeAnalytics","getPlatformSession","RemoteSession","RemoteController","MastraTUI","createBrowserFromSettings","createMastraCode","TUI_CO_AUTHOR","resolveSubagentsSetting","toActiveBrowserSettings","resolveStagehandModel","stopProcessMemoryDiagnosticsWithTimeout","spawn","scaffoldPlugin","formatScaffoldSuccess","hasHeadlessFlag","runMCCli","resolveModePackArg","drainPipedStdin","reopenStdinFromTTY"],"sources":["../src/initial-prompt.ts","../src/process-memory-diagnostics-lifecycle.ts","../src/resume-command.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} from '@mastra/code-sdk/process-memory-diagnostics';\nimport type {\n ProcessMemoryDiagnostics,\n ProcessMemoryDiagnosticsEnvironment,\n 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","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 { spawn } from 'node:child_process';\nimport fs from 'node:fs';\n\nimport { createMastraCode, resolveSubagentsSetting } from '@mastra/code-sdk';\nimport { createMastraCodeAnalytics } from '@mastra/code-sdk/analytics';\nimport { isStreamDestroyedError } from '@mastra/code-sdk/error-classification';\nimport { RemoteController } from '@mastra/code-sdk/factory/remote-controller';\nimport { RemoteSession } from '@mastra/code-sdk/factory/remote-session';\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 type { FactoryConnectionSettings } from '@mastra/code-sdk/onboarding/settings';\nimport { getPlatformSession } from '@mastra/code-sdk/platform/index';\nimport { formatScaffoldSuccess, scaffoldPlugin } from '@mastra/code-sdk/plugins/scaffold';\nimport { stopProcessMemoryDiagnosticsWithTimeout } from '@mastra/code-sdk/process-memory-diagnostics';\nimport type { ProcessMemoryDiagnostics } 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 { applyThemePreference, normalizeThemePreference } from './tui/commands/theme.js';\nimport { MastraTUI } from './tui/index.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;\nlet remoteSession: RemoteSession | 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\ntype StartupMessage = ReturnType<typeof initialMessageOptions>;\n\nasync function tuiMain(startupMessage: StartupMessage = {}, resumeThreadId?: string, startupPackId?: string) {\n const settings = loadSettings();\n processMemoryDiagnostics = await startTuiProcessMemoryDiagnostics(process.env, warning => {\n console.info(`⚠ ${warning}`);\n });\n\n setupDebugLogging();\n\n // Detect and apply terminal theme\n // MASTRA_THEME env var is the highest-priority override (mode name or custom theme name)\n const envTheme = normalizeThemePreference(process.env.MASTRA_THEME ?? '');\n const themeMode = envTheme || settings.preferences.theme || 'auto';\n await applyThemePreference(themeMode);\n\n analytics = createMastraCodeAnalytics({ version: getCurrentVersion() });\n if (settings.factory && settings.factory.active !== false && !isTruthyEnv('MASTRACODE_LOCAL')) {\n const ignored = [resumeThreadId && 'thread resume', startupPackId && 'model pack'].filter(Boolean);\n if (ignored.length > 0) console.info(`⚠ Factory mode ignores the requested ${ignored.join(' and ')}.`);\n try {\n return await bootFactory(settings.factory, themeMode, startupMessage);\n } catch (error) {\n // Never lock the user out of the TUI: they need it running to reconnect or disconnect.\n console.info(\n `⚠ Could not reach Factory ${settings.factory.factoryProjectName} (${(error as Error).message}). ` +\n 'Running locally — use /factory to retry or /factory disconnect to forget it.',\n );\n }\n }\n return bootLocal(settings, themeMode, startupMessage, resumeThreadId, startupPackId);\n}\n\n/**\n * Factory client: the agent, tools, storage, and model auth live in the Factory.\n * Nothing local is constructed; the TUI only renders and forwards input.\n */\nasync function bootFactory(factory: FactoryConnectionSettings, themeMode: string, startupMessage: StartupMessage) {\n const platform = await getPlatformSession();\n if (!platform) throw new Error('Mastra Platform login expired');\n const address = { url: factory.url, session: { token: platform.token, orgId: factory.orgId } };\n const session = new RemoteSession(address, factory.sessionId);\n const remoteController = new RemoteController(address);\n try {\n await Promise.all([session.connect(), remoteController.connect()]);\n } catch (error) {\n session.disconnect();\n throw error;\n }\n remoteSession = session;\n session.setModes(remoteController.listModes());\n getResumeThreadId = () => (tui ? tui.getResumeThreadId() : session.thread.getId());\n\n analytics?.capture('mastracode_session_started', {\n mode: session.mode.get(),\n resourceId: session.identity.getResourceId(),\n runtime: 'factory',\n theme: themeMode,\n });\n\n tui = new MastraTUI({\n runtime: 'factory',\n controller: remoteController,\n session,\n factory: {\n projectName: factory.factoryProjectName,\n repositorySlug: factory.repositorySlug,\n branch: factory.branch,\n url: factory.url,\n },\n analytics,\n processMemoryDiagnostics,\n appName: 'Mastra Code',\n version: getCurrentVersion(),\n inlineQuestions: true,\n exit: exitCode => void shutdownAndExit(exitCode),\n relaunch,\n ...startupMessage,\n });\n tui.run().catch(error => {\n handleFatalError(error);\n });\n}\n\nasync function bootLocal(\n settings: ReturnType<typeof loadSettings>,\n themeMode: string,\n startupMessage: StartupMessage,\n resumeThreadId?: string,\n startupPackId?: string,\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: resolveSubagentsSetting(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 // 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?.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 runtime: 'local',\n });\n\n tui = new MastraTUI({\n 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 relaunch,\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 remoteSession?.disconnect();\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\n/**\n * Restart Mastra Code so it boots in whichever mode settings now select. The\n * startup prompt and resume flags are dropped: they were for the previous run.\n */\nasync function relaunch(): Promise<void> {\n await asyncCleanup();\n tui?.stop();\n const env = { ...process.env };\n delete env.MASTRACODE_LOCAL;\n const args = [...process.execArgv, process.argv[1]!];\n const execve = (process as { execve?: (file: string, args: string[], env: NodeJS.ProcessEnv) => never }).execve;\n if (execve) execve(process.execPath, [process.execPath, ...args], env);\n // No in-place exec (Windows, older Node): hand the terminal to a child and mirror its exit.\n // The child shares the terminal's process group and handles Ctrl+C itself.\n for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP'] as const) {\n process.removeAllListeners(signal);\n process.on(signal, () => {});\n }\n // Release stdin so the child is the only reader of terminal input.\n process.stdin.removeAllListeners('data');\n process.stdin.pause();\n const child = spawn(process.execPath, args, { stdio: 'inherit', env });\n child.on('error', error => {\n console.error(`Failed to restart Mastra Code: ${error.message}`);\n process.exit(1);\n });\n child.on('exit', code => process.exit(code ?? 0));\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 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), resumeThre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AI,WAAW,UAAU;GACvB,QAAQ,OAAO,MAAM,UAAU,SAAS,MAAM,GAAG;GACjD,QAAQ,KAAK,CAAC;EAChB;EACA,gBAAgB,SAAS;EACzB,IAAI,QAAQ,IAAI,qBAAqB,KAAK,GACxC,QAAQ,OAAO,MAAM,4EAA4E;CAErG;CAEA,IAAI,6BAA6B,gBAAgB,QAAQ,QAAQ,MAAM,KAAK,CAAC,GAAG;EAC9E,QAAQ,OAAO,MAAM,uDAAuD;EAC5E,QAAQ,WAAW;EACnB;CACF;CAKA,IAAI,aAA4B;CAChC,IAAI,CAAC,QAAQ,MAAM,OAAO;EACxB,QAAQ,OAAO,MAAM,0BAA0B;EAC/C,aAAa,OAAA,GAAMC,kCAAAA,gBAAAA,CAAgB;EAKnC,IAAI,EAAA,GADkBC,kCAAAA,mBAAAA,CACL,GAAG;GAClB,wBAAwB,wDAAwD;GAChF,QAAQ,OAAO,MAAM,qDAAqD;GAC1E,QAAA,GAAOH,gCAAAA,SAAAA,CAAS,YAAY,EAAE,UAAUT,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,gBAAgB,aAAa;AAChG;AAEA,KAAK,CAAC,CAAC,OAAM,UAAS;CACpB,iBAAiB,KAAK;AACxB,CAAC"}
|
package/dist/cli.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { T as TUI_CO_AUTHOR, _ as normalizeThemePreference, a as formatUpdateHeader, g as applyThemePreference, i as formatUpToDate, n as formatInstallingLabel, o as formatUpdateOutcome, r as formatRegistryError, t as MastraTUI } from "./tui-
|
|
3
|
-
import { createMastraCode } from "@mastra/code-sdk";
|
|
2
|
+
import { T as TUI_CO_AUTHOR, _ as normalizeThemePreference, a as formatUpdateHeader, g as applyThemePreference, i as formatUpToDate, n as formatInstallingLabel, o as formatUpdateOutcome, r as formatRegistryError, t as MastraTUI } from "./tui-BMD4bPSG.js";
|
|
3
|
+
import { createMastraCode, resolveSubagentsSetting } from "@mastra/code-sdk";
|
|
4
4
|
import { spawn } from "child_process";
|
|
5
5
|
import fs from "fs";
|
|
6
6
|
import { createMastraCodeAnalytics } from "@mastra/code-sdk/analytics";
|
|
@@ -18,7 +18,7 @@ import { drainPipedStdin, reopenStdinFromTTY } from "@mastra/code-sdk/utils/stdi
|
|
|
18
18
|
import { releaseAllThreadLocks } from "@mastra/code-sdk/utils/thread-lock";
|
|
19
19
|
import { Chalk } from "chalk";
|
|
20
20
|
import { detectPackageManager, fetchLatestVersion, isNewerVersion, performUpdate, planUpdate } from "@mastra/code-sdk/utils/update-check";
|
|
21
|
-
|
|
21
|
+
// src/initial-prompt.ts
|
|
22
22
|
const INITIAL_PROMPT_FLAG = "--tui-initial-prompt";
|
|
23
23
|
const INITIAL_PROMPT_ENV = "MASTRACODE_TUI_INITIAL_PROMPT";
|
|
24
24
|
const TUI_PROMPT_FLAG = "--tui-prompt";
|
|
@@ -118,8 +118,7 @@ function takePackFlag(argv) {
|
|
|
118
118
|
...error ? { error } : {}
|
|
119
119
|
};
|
|
120
120
|
}
|
|
121
|
-
|
|
122
|
-
//#region src/process-memory-diagnostics-lifecycle.ts
|
|
121
|
+
// src/process-memory-diagnostics-lifecycle.ts
|
|
123
122
|
async function startTuiProcessMemoryDiagnostics(env, warn, createSetup = createProcessMemoryDiagnosticsFromEnvironment) {
|
|
124
123
|
return startConfiguredProcessMemoryDiagnostics(createSetup(env), warn);
|
|
125
124
|
}
|
|
@@ -145,8 +144,7 @@ function createShutdownCoordinator(cleanup, exit, timeoutMs = 5e3) {
|
|
|
145
144
|
return shutdownPromise;
|
|
146
145
|
};
|
|
147
146
|
}
|
|
148
|
-
|
|
149
|
-
//#region src/resume-command.ts
|
|
147
|
+
// src/resume-command.ts
|
|
150
148
|
function parseResumeThreadId(args) {
|
|
151
149
|
if (args[0] !== "resume") return void 0;
|
|
152
150
|
const threadId = args[1]?.trim();
|
|
@@ -173,13 +171,7 @@ function formatResumeHint(threadId) {
|
|
|
173
171
|
return character;
|
|
174
172
|
}).join("")}'` : `'${threadId.replaceAll("'", "'\\''")}'`}`;
|
|
175
173
|
}
|
|
176
|
-
|
|
177
|
-
//#region src/subagent-settings.ts
|
|
178
|
-
function resolveTuiSubagents(enabled) {
|
|
179
|
-
return enabled ? void 0 : [];
|
|
180
|
-
}
|
|
181
|
-
//#endregion
|
|
182
|
-
//#region src/update-command.ts
|
|
174
|
+
// src/update-command.ts
|
|
183
175
|
const UPDATE_COMMANDS = /* @__PURE__ */ new Set(["update", "upgrade"]);
|
|
184
176
|
const USAGE = "Usage: mastracode update\n\nInstall the latest version of Mastra Code. `mastracode upgrade` is an alias.";
|
|
185
177
|
const SPINNER_FRAMES = [
|
|
@@ -270,13 +262,11 @@ async function runUpdateCommand({ args = [], output = process.stdout, errorOutpu
|
|
|
270
262
|
}
|
|
271
263
|
return fail(...formatUpdateOutcome(errorStyle, outcome, latestVersion));
|
|
272
264
|
}
|
|
273
|
-
|
|
274
|
-
//#region src/version.ts
|
|
265
|
+
// src/version.ts
|
|
275
266
|
function getCurrentVersion() {
|
|
276
|
-
return "0.48.1-alpha.
|
|
267
|
+
return "0.48.1-alpha.5";
|
|
277
268
|
}
|
|
278
|
-
|
|
279
|
-
//#region src/main.ts
|
|
269
|
+
// src/main.ts
|
|
280
270
|
/**
|
|
281
271
|
* Main entry point for Mastra Code TUI.
|
|
282
272
|
*/
|
|
@@ -408,7 +398,7 @@ async function bootLocal(settings, themeMode, startupMessage, resumeThreadId, st
|
|
|
408
398
|
unixSocketPubSub: !isTruthyEnv("MASTRACODE_DISABLE_UNIX_SOCKET_PUBSUB"),
|
|
409
399
|
disableMcp: isTruthyEnv("MASTRACODE_DISABLE_MCP"),
|
|
410
400
|
disableHooks: isTruthyEnv("MASTRACODE_DISABLE_HOOKS"),
|
|
411
|
-
subagents:
|
|
401
|
+
subagents: resolveSubagentsSetting(settings.preferences.subagentsEnabled),
|
|
412
402
|
...isTruthyEnv("MASTRACODE_DISABLE_MEMORY") ? { memory: false } : {},
|
|
413
403
|
...initialState ? { initialState } : {}
|
|
414
404
|
});
|
|
@@ -640,7 +630,7 @@ async function main() {
|
|
|
640
630
|
}
|
|
641
631
|
const loginIndex = process.argv.findIndex((arg, index) => index >= 2 && arg !== "--acp" && arg !== "--dangerous-auto-approve");
|
|
642
632
|
if (process.argv[loginIndex] === "login") {
|
|
643
|
-
const { runLoginCommand } = await import("./login-command-
|
|
633
|
+
const { runLoginCommand } = await import("./login-command-EvJk2jIW.js");
|
|
644
634
|
const code = await runLoginCommand({ args: process.argv.slice(loginIndex + 1) });
|
|
645
635
|
await new Promise((resolve) => process.stdout.write("", resolve));
|
|
646
636
|
return process.exit(code);
|
|
@@ -719,7 +709,6 @@ async function main() {
|
|
|
719
709
|
main().catch((error) => {
|
|
720
710
|
handleFatalError(error);
|
|
721
711
|
});
|
|
722
|
-
//#endregion
|
|
723
712
|
export {};
|
|
724
713
|
|
|
725
714
|
//# sourceMappingURL=cli.js.map
|