mastracode 0.45.0-alpha.3 → 0.45.0-alpha.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- const require_tui = require("./tui-CPJv6T_R.cjs");
2
+ const require_tui = require("./tui-DGvjBiNg.cjs");
3
3
  let _mastra_code_sdk = require("@mastra/code-sdk");
4
4
  let fs = require("fs");
5
5
  fs = require_tui.__toESM(fs, 1);
@@ -140,7 +140,7 @@ function resolveTuiSubagents(enabled) {
140
140
  //#endregion
141
141
  //#region src/version.ts
142
142
  function getCurrentVersion() {
143
- return "0.45.0-alpha.3";
143
+ return "0.45.0-alpha.4";
144
144
  }
145
145
  //#endregion
146
146
  //#region src/main.ts
@@ -399,6 +399,13 @@ async function main() {
399
399
  const { runPruneCommand } = await import("@mastra/code-sdk/utils/prune-cli");
400
400
  return process.exit(await runPruneCommand(process.argv.slice(3)));
401
401
  }
402
+ const loginIndex = process.argv.findIndex((arg, index) => index >= 2 && arg !== "--acp" && arg !== "--dangerous-auto-approve");
403
+ if (process.argv[loginIndex] === "login") {
404
+ const { runLoginCommand } = await Promise.resolve().then(() => require("./login-command-BSpvG0ws.cjs"));
405
+ const code = await runLoginCommand({ args: process.argv.slice(loginIndex + 1) });
406
+ await new Promise((resolve) => process.stdout.write("", resolve));
407
+ return process.exit(code);
408
+ }
402
409
  const initialPrompt = takeInitialPrompt(process.argv, process.env);
403
410
  if (initialPrompt.error) {
404
411
  process.stderr.write(`${initialPrompt.error}\n`);
package/dist/cli.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.cjs","names":["createProcessMemoryDiagnosticsFromEnvironment","TUI_CO_AUTHOR","detectTerminalTheme","MastraTUI"],"sources":["../src/initial-prompt.ts","../src/process-memory-diagnostics-lifecycle.ts","../src/resume-command.ts","../src/subagent-settings.ts","../src/version.ts","../src/main.ts"],"sourcesContent":["export const INITIAL_PROMPT_FLAG = '--tui-initial-prompt' as const;\nexport const INITIAL_PROMPT_ENV = 'MASTRACODE_TUI_INITIAL_PROMPT';\n\nexport const TUI_PROMPT_FLAG = '--tui-prompt' as const;\n\nexport type InitialPromptArgs = {\n /** argv with the flag and its value removed, so headless detection never mistakes the value for a prompt. */\n argv: string[];\n prompt?: string;\n /** Set when a flag was passed without a value, or both flags were passed. */\n error?: string;\n /** The flag the prompt came from; undefined when it came from the environment. */\n flag?: typeof INITIAL_PROMPT_FLAG | typeof TUI_PROMPT_FLAG;\n /**\n * `--tui-prompt` sends even when startup resumes an existing conversation;\n * `--tui-initial-prompt` and the environment variable only start a new one.\n */\n sendOnResume: boolean;\n};\n\n/**\n * Takes the interactive startup prompt from `--tui-initial-prompt <text>` or\n * `--tui-prompt <text>` (also `--flag=<text>`), falling back to\n * `MASTRACODE_TUI_INITIAL_PROMPT`.\n *\n * The environment variable is always removed from `env`: everything this\n * process spawns inherits its environment, and a nested Mastra Code (or any\n * shell the agent starts) must not send the same prompt again.\n */\nexport function takeInitialPrompt(argv: string[], env: NodeJS.ProcessEnv): InitialPromptArgs {\n const fromEnv = env[INITIAL_PROMPT_ENV];\n delete env[INITIAL_PROMPT_ENV];\n\n const rest: string[] = [];\n const found = new Map<NonNullable<InitialPromptArgs['flag']>, string>();\n let error: string | undefined;\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i]!;\n const flag = [INITIAL_PROMPT_FLAG, TUI_PROMPT_FLAG].find(f => arg === f || arg.startsWith(`${f}=`));\n if (!flag) {\n rest.push(arg);\n } else if (arg !== flag) {\n found.set(flag, arg.slice(flag.length + 1));\n } else if (argv[i + 1] === undefined) {\n error = `${flag} needs a value`;\n } else {\n found.set(flag, argv[++i]!);\n }\n }\n if (found.size > 1) error = `Use either ${INITIAL_PROMPT_FLAG} or ${TUI_PROMPT_FLAG}, not both`;\n\n const [flag, flagValue] = [...found][0] ?? [];\n const prompt = (flag ? flagValue : fromEnv)?.trim() || undefined;\n return { argv: rest, prompt, error, flag, sendOnResume: flag === TUI_PROMPT_FLAG };\n}\n\n/** The first message the TUI sends: the initial prompt, followed by any piped stdin. */\nexport function composeInitialMessage(prompt: string | undefined, pipedInput: string | null | undefined) {\n const piped = pipedInput ? `The following was piped via stdin:\\n\\n${pipedInput}` : undefined;\n if (prompt && piped) return `${prompt}\\n\\n${piped}`;\n return prompt ?? piped;\n}\n\n/**\n * Why a startup prompt can't be combined with piped stdin, if it can't.\n *\n * The first message is submitted like typed input, so a prompt starting with\n * `/` or `!` is dispatched as a command. Folding piped text into it would make\n * that text part of the command — skill arguments, or a shell script for `!`.\n */\nexport function pipedInputConflict(\n args: Pick<InitialPromptArgs, 'prompt' | 'flag'>,\n pipedInput: string | null | undefined,\n): string | undefined {\n if (!args.prompt || !pipedInput) return undefined;\n if (!args.prompt.startsWith('/') && !args.prompt.startsWith('!')) return undefined;\n const source = args.flag ?? INITIAL_PROMPT_ENV;\n return `${source} can't be combined with piped stdin when it is a slash command or starts with !`;\n}\n\n/** The TUI options for a startup prompt and/or piped stdin. */\nexport function initialMessageOptions(\n args: Pick<InitialPromptArgs, 'prompt' | 'sendOnResume'>,\n pipedInput?: string | null,\n): { initialMessage?: string; resumeSkipNotice?: string } {\n const initialMessage = composeInitialMessage(args.prompt, pipedInput);\n if (!initialMessage) return {};\n // Piped stdin on its own is always sent, as before.\n if (!args.prompt || args.sendOnResume) return { initialMessage };\n const skipped = pipedInput ? 'the initial prompt and piped input were' : 'the initial prompt was';\n return {\n initialMessage,\n resumeSkipNotice: `Resumed the existing conversation for this directory, so ${skipped} not sent. Use ${TUI_PROMPT_FLAG} to send ${pipedInput ? 'them' : 'it'} anyway.`,\n };\n}\n","import {\n createProcessMemoryDiagnosticsFromEnvironment,\n startConfiguredProcessMemoryDiagnostics,\n type ProcessMemoryDiagnostics,\n type ProcessMemoryDiagnosticsEnvironment,\n type ProcessMemoryDiagnosticsSetup,\n} from '@mastra/code-sdk/process-memory-diagnostics';\n\nexport async function startTuiProcessMemoryDiagnostics(\n env: ProcessMemoryDiagnosticsEnvironment,\n warn: (message: string) => void,\n createSetup: (\n env: ProcessMemoryDiagnosticsEnvironment,\n ) => ProcessMemoryDiagnosticsSetup = createProcessMemoryDiagnosticsFromEnvironment,\n): Promise<ProcessMemoryDiagnostics> {\n return startConfiguredProcessMemoryDiagnostics(createSetup(env), warn);\n}\n\nexport function createOneShotFatalErrorHandler(handle: (error: unknown) => void): (error: unknown) => void {\n let handlingFatalError = false;\n return error => {\n if (handlingFatalError) return;\n handlingFatalError = true;\n handle(error);\n };\n}\n\nexport function createShutdownCoordinator(\n cleanup: () => Promise<void>,\n exit: (exitCode: number) => never,\n timeoutMs = 5_000,\n): (exitCode: number) => Promise<void> {\n let shutdownPromise: Promise<void> | null = null;\n return exitCode => {\n shutdownPromise ??= (async () => {\n let timeout: ReturnType<typeof setTimeout> | undefined;\n await Promise.race([\n cleanup().catch(() => undefined),\n new Promise<void>(resolve => {\n timeout = setTimeout(resolve, timeoutMs);\n }),\n ]);\n if (timeout) clearTimeout(timeout);\n exit(exitCode);\n })();\n return shutdownPromise;\n };\n}\n","export function parseResumeThreadId(args: string[]): string | undefined {\n if (args[0] !== 'resume') return undefined;\n\n const threadId = args[1]?.trim();\n if (!threadId || args.length !== 2) {\n throw new Error('Usage: mastracode resume <thread-id>');\n }\n return threadId;\n}\n\nexport function shouldRunHeadless(\n argv: string[],\n resumeThreadId: string | undefined,\n hasHeadlessFlag: boolean,\n): boolean {\n return !resumeThreadId && (hasHeadlessFlag || argv.includes('--help') || argv.includes('-h'));\n}\n\nexport function shouldRejectResumeWithoutTTY(resumeThreadId: string | undefined, isTTY: boolean): boolean {\n return Boolean(resumeThreadId) && !isTTY;\n}\n\nexport function formatResumeHint(threadId: string): string {\n const hasControlCharacters = [...threadId].some(character => {\n const codePoint = character.codePointAt(0)!;\n return codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f);\n });\n const argument = /^[a-zA-Z0-9_-]+$/.test(threadId)\n ? threadId\n : hasControlCharacters\n ? `$'${[...threadId]\n .map(character => {\n const codePoint = character.codePointAt(0)!;\n if (character === \"'\") return \"\\\\'\";\n if (character === '\\\\') return '\\\\\\\\';\n if (codePoint <= 0x1f || codePoint === 0x7f) return `\\\\x${codePoint.toString(16).padStart(2, '0')}`;\n if (codePoint >= 0x80 && codePoint <= 0x9f) {\n return `\\\\u${codePoint.toString(16).padStart(4, '0')}`;\n }\n return character;\n })\n .join('')}'`\n : `'${threadId.replaceAll(\"'\", \"'\\\\''\")}'`;\n return `To continue this session, run mastracode resume ${argument}`;\n}\n","export function resolveTuiSubagents(enabled: boolean): undefined | [] {\n return enabled ? undefined : [];\n}\n","import { readFileSync } from 'node:fs';\n\ndeclare const MASTRACODE_VERSION: string | undefined;\n\nexport function getCurrentVersion(): string {\n if (typeof MASTRACODE_VERSION !== 'undefined') {\n return MASTRACODE_VERSION;\n }\n\n const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as { version: string };\n return pkg.version;\n}\n","#!/usr/bin/env node\n/**\n * Main entry point for Mastra Code TUI.\n */\nimport fs from 'node:fs';\n\nimport { createMastraCode } from '@mastra/code-sdk';\nimport { createMastraCodeAnalytics } from '@mastra/code-sdk/analytics';\nimport { isStreamDestroyedError } from '@mastra/code-sdk/error-classification';\nimport { hasHeadlessFlag, runMCCli } from '@mastra/code-sdk/headless/index';\nimport {\n createBrowserFromSettings,\n loadSettings,\n resolveStagehandModel,\n toActiveBrowserSettings,\n} from '@mastra/code-sdk/onboarding/settings';\nimport { formatScaffoldSuccess, scaffoldPlugin } from '@mastra/code-sdk/plugins/scaffold';\nimport {\n stopProcessMemoryDiagnosticsWithTimeout,\n type ProcessMemoryDiagnostics,\n} from '@mastra/code-sdk/process-memory-diagnostics';\nimport { setupDebugLogging, truncateLogFile } from '@mastra/code-sdk/utils/debug-log';\nimport { drainPipedStdin, reopenStdinFromTTY } from '@mastra/code-sdk/utils/stdin-pipe';\nimport { releaseAllThreadLocks } from '@mastra/code-sdk/utils/thread-lock';\nimport { TUI_CO_AUTHOR } from './commit-attribution.js';\nimport { initialMessageOptions, pipedInputConflict, takeInitialPrompt } from './initial-prompt.js';\nimport {\n createOneShotFatalErrorHandler,\n createShutdownCoordinator,\n startTuiProcessMemoryDiagnostics,\n} from './process-memory-diagnostics-lifecycle.js';\nimport {\n formatResumeHint,\n parseResumeThreadId,\n shouldRejectResumeWithoutTTY,\n shouldRunHeadless,\n} from './resume-command.js';\nimport { resolveTuiSubagents } from './subagent-settings.js';\nimport { detectTerminalTheme } from './tui/detect-theme.js';\nimport { MastraTUI } from './tui/index.js';\nimport { applyThemeMode, restoreTerminalForeground } from './tui/theme.js';\nimport { 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 analytics: ReturnType<typeof createMastraCodeAnalytics> | undefined;\nlet tui: MastraTUI | undefined;\nlet processMemoryDiagnostics: ProcessMemoryDiagnostics | undefined;\nlet storageClosed = false;\nlet cleanupPromise: Promise<void> | null = null;\nlet getResumeThreadId: (() => string | null) | undefined;\n\nconst CRASH_LOG_PATH = '/tmp/mastra-crash.log';\n\nfunction isTruthyEnv(name: string): boolean {\n return ['1', 'true', 'yes', 'on'].includes(process.env[name]?.trim().toLowerCase() ?? '');\n}\n\nfunction resolveInitialStateFromEnv() {\n const currentModelId = process.env.MASTRACODE_MODEL_ID?.trim();\n const initialState: Record<string, unknown> = {};\n if (currentModelId) initialState.currentModelId = currentModelId;\n if (isTruthyEnv('MASTRACODE_YOLO')) initialState.yolo = true;\n return Object.keys(initialState).length > 0 ? initialState : undefined;\n}\n\n// Global safety nets — catch any uncaught errors from storage init, etc.\nprocess.on('uncaughtException', error => {\n // ERR_STREAM_DESTROYED is non-fatal — happens routinely when streams close\n // during shutdown, cancelled LLM requests, or LSP/subprocess exits (#13548, #13549)\n if (isStreamDestroyedError(error)) return;\n handleFatalError(error);\n});\nprocess.on('unhandledRejection', reason => {\n if (isStreamDestroyedError(reason)) return;\n handleFatalError(reason instanceof Error ? reason : new Error(String(reason)));\n});\n\nasync function tuiMain(startupMessage: ReturnType<typeof initialMessageOptions> = {}, resumeThreadId?: string) {\n const settings = loadSettings();\n processMemoryDiagnostics = await startTuiProcessMemoryDiagnostics(process.env, warning => {\n console.info(`⚠ ${warning}`);\n });\n let browserPromise: ReturnType<typeof createBrowserFromSettings> | undefined;\n const loadBrowser = (chatModelId: string | undefined) => {\n browserPromise ??= createBrowserFromSettings(settings.browser, { chatModelId });\n return browserPromise;\n };\n\n const initialState = resolveInitialStateFromEnv();\n const result = await createMastraCode({\n createInitialThread: false,\n coAuthor: TUI_CO_AUTHOR,\n unixSocketPubSub: !isTruthyEnv('MASTRACODE_DISABLE_UNIX_SOCKET_PUBSUB'),\n disableMcp: isTruthyEnv('MASTRACODE_DISABLE_MCP'),\n disableHooks: isTruthyEnv('MASTRACODE_DISABLE_HOOKS'),\n subagents: resolveTuiSubagents(settings.preferences.subagentsEnabled),\n ...(isTruthyEnv('MASTRACODE_DISABLE_MEMORY') ? { memory: false as never } : {}),\n ...(initialState ? { initialState: initialState as never } : {}),\n });\n controller = result.controller;\n mcpManager = result.mcpManager;\n hookManager = result.hookManager;\n authStorage = result.authStorage;\n signalsPubSub = result.signalsPubSub;\n storageMaintenance = result.storageMaintenance;\n stopPluginSignalProviders = result.stopPluginSignalProviders;\n threadScheduler = result.threadScheduler;\n stopNotificationDispatch = result.stopNotificationDispatch;\n\n if (result.storageWarning) {\n console.info(`⚠ ${result.storageWarning}`);\n }\n if (result.observabilityWarning) {\n console.info(`⚠ ${result.observabilityWarning}`);\n }\n\n // MCP connection is deferred to TUI.init() (after ui.start()) so that\n // status messages use showInfo() instead of console.info(), which would\n // corrupt the terminal. Headless mode still inits from headless/cli.ts.\n\n setupDebugLogging();\n\n // Detect and apply terminal theme\n // MASTRA_THEME env var is the highest-priority override\n const envTheme = process.env.MASTRA_THEME?.toLowerCase();\n let themeMode: 'dark' | 'light';\n let detectedBgHex: string | undefined;\n if (envTheme === 'dark' || envTheme === 'light') {\n themeMode = envTheme;\n } else {\n const settings = loadSettings();\n const themePref = settings.preferences.theme;\n if (themePref === 'dark' || themePref === 'light') {\n themeMode = themePref;\n } else {\n const detection = await detectTerminalTheme();\n themeMode = detection.mode;\n detectedBgHex = detection.detectedBgHex;\n }\n }\n applyThemeMode(themeMode, detectedBgHex);\n\n // createMastraCode() brought up shared resources and minted the single\n // session that all work runs through. The AgentController owns no session of its own.\n const session = result.session;\n getResumeThreadId = () => (tui ? tui.getResumeThreadId() : session.thread.getId());\n\n analytics = createMastraCodeAnalytics({ version: getCurrentVersion() });\n analytics.capture('mastracode_session_started', {\n mode: session.mode.get(),\n resourceId: session.identity.getResourceId(),\n hasAuthStorage: Boolean(authStorage),\n hasMcp: Boolean(mcpManager),\n theme: themeMode,\n });\n\n tui = new MastraTUI({\n controller: controller,\n session,\n hookManager,\n analytics,\n authStorage,\n mcpManager,\n pluginManager: result.pluginManager,\n storageMaintenance: result.storageMaintenance,\n processMemoryDiagnostics,\n knowledgeInspector: result.knowledgeInspector,\n threadScheduler: result.threadScheduler,\n appName: 'Mastra Code',\n version: getCurrentVersion(),\n inlineQuestions: true,\n ...(resumeThreadId ? { resumeThreadId } : {}),\n githubSignals: result.githubSignals,\n backgroundToolsEnabled: result.backgroundToolsEnabled,\n backgroundCompletionEvents: result.backgroundCompletionEvents,\n exit: exitCode => void shutdownAndExit(exitCode),\n ...startupMessage,\n });\n tui.run().catch(error => {\n handleFatalError(error);\n });\n\n if (settings.browser.enabled) {\n // Captured once: the Stagehand instance is fixed at launch and shared by every thread.\n const chatModelId = session.model.get();\n void loadBrowser(chatModelId)\n .then(browser => {\n if (!browser) return;\n controller.setBrowser(browser);\n void session.state\n .set({\n activeBrowserSettings: toActiveBrowserSettings(settings.browser),\n activeBrowserModel: resolveStagehandModel(settings.browser, { chatModelId }),\n } as any)\n .catch(() => {});\n })\n .catch(() => {});\n }\n}\n\nconst asyncCleanup = (): Promise<void> => {\n cleanupPromise ??= (async () => {\n releaseAllThreadLocks();\n // Stop plugin-contributed signal providers (and the plugin reload listener)\n // before quiescing workers: a provider that keeps polling past this point\n // could dispatch into a controller that is shutting down.\n try {\n stopPluginSignalProviders?.();\n } catch {\n // Best-effort — the process is exiting.\n }\n const diagnosticsShutdown = processMemoryDiagnostics\n ? stopProcessMemoryDiagnosticsWithTimeout(processMemoryDiagnostics, message => console.warn(message))\n : undefined;\n // Schedules live only in this process; stop their timers so none fires mid-shutdown.\n threadScheduler?.stop();\n // Release this process's notification dispatch leases before the pubsub that holds them closes.\n await stopNotificationDispatch?.().catch(() => {});\n await Promise.allSettled([mcpManager?.disconnect(), controller?.stopIntervals()]);\n // Mastra owns the workspaces and must destroy them to stop retained language\n // servers before storage is closed.\n await Promise.allSettled([controller?.getMastra()?.shutdown(), analytics?.shutdown()]);\n // The signals pubsub is Mastra's event bus: in-flight runs and background\n // tasks drain through it during shutdown, so close it only afterwards. Call\n // close() on the object; a detached method loses `this` and rejects silently.\n const pubsubToClose = signalsPubSub as { close?: () => Promise<void> | void } | undefined;\n await Promise.allSettled([pubsubToClose?.close?.()]);\n // Checkpoint WAL and close the local storage connection after all producers\n // and timers are quiesced. Idempotent — repeated signals (SIGINT then SIGHUP)\n // close only once. LibSQLStore.close()/LibSQLVector.close() truncate the WAL\n // and switch back to DELETE journal mode for a clean shutdown.\n if (!storageClosed) {\n storageClosed = true;\n await storageMaintenance?.closeStorage?.().catch(() => {\n // Swallow — best-effort cleanup during shutdown. The process is exiting.\n });\n }\n await diagnosticsShutdown;\n })();\n return cleanupPromise;\n};\n\nconst shutdownAndExit = createShutdownCoordinator(asyncCleanup, exitCode => process.exit(exitCode));\n\nprocess.on('beforeExit', () => {\n void asyncCleanup();\n});\nprocess.on('exit', () => {\n // Ensure terminal protocols (kitty keyboard, modifyOtherKeys, bracketed paste,\n // raw mode) are disabled on ANY exit path. Without this, killing the process\n // via SIGINT/SIGTERM leaves the terminal in a corrupted state where keypresses\n // produce escape sequences like \"5;99~\" instead of normal characters.\n try {\n tui?.stop();\n } catch {\n // Failsafe: even if MastraTUI.stop() throws, write raw terminal reset\n // sequences to disable Kitty keyboard protocol, bracketed paste, and\n // modifyOtherKeys. These are the exact sequences pi-tui's terminal.stop()\n // would write.\n }\n // Belt-and-suspenders: always write terminal reset sequences directly,\n // regardless of whether tui.stop() succeeded. Writing them twice is harmless\n // but missing them leaves the terminal in a corrupted state.\n try {\n process.stdout.write(\n '\\x1b[?2004l' + // disable bracketed paste\n '\\x1b[<u' + // pop kitty keyboard protocol\n '\\x1b[>4;0m' + // disable modifyOtherKeys\n '\\x1b[?25h', // show cursor\n );\n if (process.stdin.setRawMode) {\n process.stdin.setRawMode(false);\n }\n } catch {\n // stdout may already be closed during exit\n }\n restoreTerminalForeground();\n releaseAllThreadLocks();\n try {\n const threadId = getResumeThreadId?.();\n if (threadId) {\n process.stdout.write(`\\n${formatResumeHint(threadId)}\\n`);\n }\n } catch {\n // session state or stdout may already be closed during exit\n }\n});\n\n// Start durable diagnostics shutdown before synchronous TUI teardown so a stalled\n// terminal cleanup cannot prevent the final profile capture. The exit handler still\n// provides a failsafe terminal reset if teardown throws.\nconst handleTermSignal = () => {\n void asyncCleanup();\n try {\n tui?.stop();\n } catch {\n // ignored — exit handler has failsafe reset\n }\n void shutdownAndExit(0);\n};\nprocess.on('SIGINT', handleTermSignal);\nprocess.on('SIGTERM', handleTermSignal);\nprocess.on('SIGHUP', handleTermSignal);\n\nfunction hasEconnrefused(err: unknown, depth = 0): boolean {\n if (!err || depth > 5) return false;\n const e = err as any;\n if (e.code === 'ECONNREFUSED') return true;\n if (e.cause) return hasEconnrefused(e.cause, depth + 1);\n // AggregateError has .errors array\n if (Array.isArray(e.errors)) return e.errors.some((inner: unknown) => hasEconnrefused(inner, depth + 1));\n return false;\n}\n\nfunction pluginMain(args: string[]): void {\n if (args[0] !== 'scaffold') {\n process.stderr.write('Usage: mastracode plugin scaffold <dir> [--id acme.foo] [--name \"Foo Tools\"]\\n');\n process.exit(1);\n }\n\n const dir = args[1];\n if (!dir) {\n process.stderr.write('Usage: mastracode plugin scaffold <dir> [--id acme.foo] [--name \"Foo Tools\"]\\n');\n process.exit(1);\n }\n\n const id = readFlag(args, '--id');\n const name = readFlag(args, '--name');\n const targetDir = scaffoldPlugin(dir, { ...(id ? { id } : {}), ...(name ? { name } : {}) });\n process.stdout.write(`${formatScaffoldSuccess(targetDir)}\\n`);\n}\n\nfunction readFlag(args: string[], flag: string): string | undefined {\n const index = args.indexOf(flag);\n if (index === -1) return undefined;\n const value = args[index + 1];\n if (!value || value.startsWith('--')) {\n throw new Error(`Missing value for ${flag}`);\n }\n return value;\n}\n\nconst handleFatalError = createOneShotFatalErrorHandler((error: unknown): void => {\n // Always write to real stderr, even if console.error was overridden\n const write = (msg: string) => {\n try {\n process.stderr.write(msg + '\\n');\n } catch {}\n };\n\n if (hasEconnrefused(error)) {\n const settings = loadSettings();\n const connStr = settings.storage?.pg?.connectionString;\n const target = connStr ?? 'localhost:5432';\n write(\n `\\nFailed to connect to PostgreSQL at ${target}.` +\n `\\nMake sure the database is running and accessible.` +\n `\\n\\nTo switch back to LibSQL:` +\n `\\n Set MASTRA_STORAGE_BACKEND=libsql or change the backend in /settings\\n`,\n );\n void asyncCleanup();\n try {\n tui?.stop();\n } catch {}\n void shutdownAndExit(1);\n return;\n }\n\n const msg = `Fatal error: ${error instanceof Error ? error.message : String(error)}`;\n write(msg);\n // Write crash log to file so it persists even if terminal closes\n try {\n const crashLog = `[${new Date().toISOString()}] ${msg}\\n${error instanceof Error && error.stack ? error.stack + '\\n' : ''}`;\n truncateLogFile(CRASH_LOG_PATH);\n fs.appendFileSync(CRASH_LOG_PATH, crashLog);\n truncateLogFile(CRASH_LOG_PATH);\n } catch {}\n if (error instanceof Error && error.stack) {\n write(error.stack);\n }\n void asyncCleanup();\n try {\n tui?.stop();\n } catch {}\n void shutdownAndExit(1);\n});\n\nasync function main() {\n if (process.argv[2] === 'plugin') {\n return pluginMain(process.argv.slice(3));\n }\n\n // Storage maintenance without the TUI, so a database can still be pruned and\n // compacted when the interactive session won't start. Checked before the\n // headless branch below, which would otherwise claim `prune --help`.\n if (process.argv[2] === 'prune') {\n const { runPruneCommand } = await import('@mastra/code-sdk/utils/prune-cli');\n return process.exit(await runPruneCommand(process.argv.slice(3)));\n }\n\n const initialPrompt = takeInitialPrompt(process.argv, process.env);\n if (initialPrompt.error) {\n process.stderr.write(`${initialPrompt.error}\\n`);\n process.exit(1);\n }\n if (initialPrompt.flag) process.argv = initialPrompt.argv;\n // The flag only means something to the interactive TUI. Paths that can't run\n // it reject the flag instead of dropping the prompt; an env var prompt is\n // just ignored there.\n const rejectInitialPromptFlag = (reason: string) => {\n if (!initialPrompt.flag) return;\n process.stderr.write(`${initialPrompt.flag} starts the interactive TUI; ${reason}\\n`);\n process.exit(1);\n };\n\n let resumeThreadId: string | undefined;\n try {\n resumeThreadId = parseResumeThreadId(process.argv.slice(2));\n } catch (error) {\n process.stderr.write(`${error instanceof Error ? error.message : String(error)}\\n`);\n process.exitCode = 1;\n return;\n }\n\n const headless = hasHeadlessFlag(process.argv);\n if (shouldRunHeadless(process.argv, resumeThreadId, headless)) {\n if (headless) rejectInitialPromptFlag('use --prompt for headless runs');\n return runMCCli(undefined, { coAuthor: TUI_CO_AUTHOR });\n }\n\n if (process.argv.includes('--acp')) {\n rejectInitialPromptFlag('it cannot be combined with --acp');\n const { acpMain } = await import('@mastra/code-sdk/acp/index');\n return acpMain({\n dangerousAutoApprove: process.argv.includes('--dangerous-auto-approve'),\n coAuthor: TUI_CO_AUTHOR,\n });\n }\n\n if (shouldRejectResumeWithoutTTY(resumeThreadId, Boolean(process.stdin.isTTY))) {\n process.stderr.write('mastracode resume requires an interactive terminal.\\n');\n process.exitCode = 1;\n return;\n }\n\n // When stdin is piped (e.g. `cat foo | mastracode`), drain the pipe fully\n // before starting the TUI. The drain blocks until the sender process exits\n // and closes its stdout, so we never see partial output.\n let pipedInput: string | null = null;\n if (!process.stdin.isTTY) {\n process.stderr.write('Reading piped input...\\n');\n pipedInput = await drainPipedStdin();\n\n // Always reopen a real TTY — even if the pipe was empty, the original\n // stdin is consumed/closed and the TUI needs a live TTY for keyboard input.\n const reopenedStdin = reopenStdinFromTTY();\n if (!reopenedStdin) {\n rejectInitialPromptFlag('no TTY is available, so use --prompt for headless runs');\n process.stderr.write('No TTY available — falling back to headless mode.\\n');\n return runMCCli(pipedInput, { coAuthor: TUI_CO_AUTHOR });\n }\n }\n\n const conflict = pipedInputConflict(initialPrompt, pipedInput);\n if (conflict) {\n process.stderr.write(`${conflict}\\n`);\n process.exit(1);\n }\n\n return tuiMain(initialMessageOptions(initialPrompt, pipedInput), resumeThreadId);\n}\n\nmain().catch(error => {\n handleFatalError(error);\n});\n"],"mappings":";;;;;;;;;;;;;;;AAAA,MAAa,sBAAsB;AACnC,MAAa,qBAAqB;AAElC,MAAa,kBAAkB;;;;;;;;;;AA0B/B,SAAgB,kBAAkB,MAAgB,KAA2C;CAC3F,MAAM,UAAU,IAAI;CACpB,OAAO,IAAI;CAEX,MAAM,OAAiB,CAAC;CACxB,MAAM,wBAAQ,IAAI,IAAoD;CACtE,IAAI;CACJ,KAAK,IAAI,IAAI,GAAG,IAAI,KA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AClC,wBAAwB,kCAAkC;EAC1D,MAAM,EAAE,YAAY,MAAM,OAAO;EACjC,OAAO,QAAQ;GACb,sBAAsB,QAAQ,KAAK,SAAS,0BAA0B;GACtE,UAAUA,YAAAA;EACZ,CAAC;CACH;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,GAAA,kCAAA,gBAAA,CAAsB;EAKnC,IAAI,EAAA,GAAA,kCAAA,mBAAA,CAAa,GAAG;GAClB,wBAAwB,wDAAwD;GAChF,QAAQ,OAAO,MAAM,qDAAqD;GAC1E,QAAA,GAAA,gCAAA,SAAA,CAAgB,YAAY,EAAE,UAAUA,YAAAA,cAAc,CAAC;EACzD;CACF;CAEA,MAAM,WAAW,mBAAmB,eAAe,UAAU;CAC7D,IAAI,UAAU;EACZ,QAAQ,OAAO,MAAM,GAAG,SAAS,GAAG;EACpC,QAAQ,KAAK,CAAC;CAChB;CAEA,OAAO,QAAQ,sBAAsB,eAAe,UAAU,GAAG,cAAc;AACjF;AAEA,KAAK,CAAC,CAAC,OAAM,UAAS;CACpB,iBAAiB,KAAK;AACxB,CAAC"}
1
+ {"version":3,"file":"cli.cjs","names":["createProcessMemoryDiagnosticsFromEnvironment","TUI_CO_AUTHOR","detectTerminalTheme","MastraTUI"],"sources":["../src/initial-prompt.ts","../src/process-memory-diagnostics-lifecycle.ts","../src/resume-command.ts","../src/subagent-settings.ts","../src/version.ts","../src/main.ts"],"sourcesContent":["export const INITIAL_PROMPT_FLAG = '--tui-initial-prompt' as const;\nexport const INITIAL_PROMPT_ENV = 'MASTRACODE_TUI_INITIAL_PROMPT';\n\nexport const TUI_PROMPT_FLAG = '--tui-prompt' as const;\n\nexport type InitialPromptArgs = {\n /** argv with the flag and its value removed, so headless detection never mistakes the value for a prompt. */\n argv: string[];\n prompt?: string;\n /** Set when a flag was passed without a value, or both flags were passed. */\n error?: string;\n /** The flag the prompt came from; undefined when it came from the environment. */\n flag?: typeof INITIAL_PROMPT_FLAG | typeof TUI_PROMPT_FLAG;\n /**\n * `--tui-prompt` sends even when startup resumes an existing conversation;\n * `--tui-initial-prompt` and the environment variable only start a new one.\n */\n sendOnResume: boolean;\n};\n\n/**\n * Takes the interactive startup prompt from `--tui-initial-prompt <text>` or\n * `--tui-prompt <text>` (also `--flag=<text>`), falling back to\n * `MASTRACODE_TUI_INITIAL_PROMPT`.\n *\n * The environment variable is always removed from `env`: everything this\n * process spawns inherits its environment, and a nested Mastra Code (or any\n * shell the agent starts) must not send the same prompt again.\n */\nexport function takeInitialPrompt(argv: string[], env: NodeJS.ProcessEnv): InitialPromptArgs {\n const fromEnv = env[INITIAL_PROMPT_ENV];\n delete env[INITIAL_PROMPT_ENV];\n\n const rest: string[] = [];\n const found = new Map<NonNullable<InitialPromptArgs['flag']>, string>();\n let error: string | undefined;\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i]!;\n const flag = [INITIAL_PROMPT_FLAG, TUI_PROMPT_FLAG].find(f => arg === f || arg.startsWith(`${f}=`));\n if (!flag) {\n rest.push(arg);\n } else if (arg !== flag) {\n found.set(flag, arg.slice(flag.length + 1));\n } else if (argv[i + 1] === undefined) {\n error = `${flag} needs a value`;\n } else {\n found.set(flag, argv[++i]!);\n }\n }\n if (found.size > 1) error = `Use either ${INITIAL_PROMPT_FLAG} or ${TUI_PROMPT_FLAG}, not both`;\n\n const [flag, flagValue] = [...found][0] ?? [];\n const prompt = (flag ? flagValue : fromEnv)?.trim() || undefined;\n return { argv: rest, prompt, error, flag, sendOnResume: flag === TUI_PROMPT_FLAG };\n}\n\n/** The first message the TUI sends: the initial prompt, followed by any piped stdin. */\nexport function composeInitialMessage(prompt: string | undefined, pipedInput: string | null | undefined) {\n const piped = pipedInput ? `The following was piped via stdin:\\n\\n${pipedInput}` : undefined;\n if (prompt && piped) return `${prompt}\\n\\n${piped}`;\n return prompt ?? piped;\n}\n\n/**\n * Why a startup prompt can't be combined with piped stdin, if it can't.\n *\n * The first message is submitted like typed input, so a prompt starting with\n * `/` or `!` is dispatched as a command. Folding piped text into it would make\n * that text part of the command — skill arguments, or a shell script for `!`.\n */\nexport function pipedInputConflict(\n args: Pick<InitialPromptArgs, 'prompt' | 'flag'>,\n pipedInput: string | null | undefined,\n): string | undefined {\n if (!args.prompt || !pipedInput) return undefined;\n if (!args.prompt.startsWith('/') && !args.prompt.startsWith('!')) return undefined;\n const source = args.flag ?? INITIAL_PROMPT_ENV;\n return `${source} can't be combined with piped stdin when it is a slash command or starts with !`;\n}\n\n/** The TUI options for a startup prompt and/or piped stdin. */\nexport function initialMessageOptions(\n args: Pick<InitialPromptArgs, 'prompt' | 'sendOnResume'>,\n pipedInput?: string | null,\n): { initialMessage?: string; resumeSkipNotice?: string } {\n const initialMessage = composeInitialMessage(args.prompt, pipedInput);\n if (!initialMessage) return {};\n // Piped stdin on its own is always sent, as before.\n if (!args.prompt || args.sendOnResume) return { initialMessage };\n const skipped = pipedInput ? 'the initial prompt and piped input were' : 'the initial prompt was';\n return {\n initialMessage,\n resumeSkipNotice: `Resumed the existing conversation for this directory, so ${skipped} not sent. Use ${TUI_PROMPT_FLAG} to send ${pipedInput ? 'them' : 'it'} anyway.`,\n };\n}\n","import {\n createProcessMemoryDiagnosticsFromEnvironment,\n startConfiguredProcessMemoryDiagnostics,\n type ProcessMemoryDiagnostics,\n type ProcessMemoryDiagnosticsEnvironment,\n type ProcessMemoryDiagnosticsSetup,\n} from '@mastra/code-sdk/process-memory-diagnostics';\n\nexport async function startTuiProcessMemoryDiagnostics(\n env: ProcessMemoryDiagnosticsEnvironment,\n warn: (message: string) => void,\n createSetup: (\n env: ProcessMemoryDiagnosticsEnvironment,\n ) => ProcessMemoryDiagnosticsSetup = createProcessMemoryDiagnosticsFromEnvironment,\n): Promise<ProcessMemoryDiagnostics> {\n return startConfiguredProcessMemoryDiagnostics(createSetup(env), warn);\n}\n\nexport function createOneShotFatalErrorHandler(handle: (error: unknown) => void): (error: unknown) => void {\n let handlingFatalError = false;\n return error => {\n if (handlingFatalError) return;\n handlingFatalError = true;\n handle(error);\n };\n}\n\nexport function createShutdownCoordinator(\n cleanup: () => Promise<void>,\n exit: (exitCode: number) => never,\n timeoutMs = 5_000,\n): (exitCode: number) => Promise<void> {\n let shutdownPromise: Promise<void> | null = null;\n return exitCode => {\n shutdownPromise ??= (async () => {\n let timeout: ReturnType<typeof setTimeout> | undefined;\n await Promise.race([\n cleanup().catch(() => undefined),\n new Promise<void>(resolve => {\n timeout = setTimeout(resolve, timeoutMs);\n }),\n ]);\n if (timeout) clearTimeout(timeout);\n exit(exitCode);\n })();\n return shutdownPromise;\n };\n}\n","export function parseResumeThreadId(args: string[]): string | undefined {\n if (args[0] !== 'resume') return undefined;\n\n const threadId = args[1]?.trim();\n if (!threadId || args.length !== 2) {\n throw new Error('Usage: mastracode resume <thread-id>');\n }\n return threadId;\n}\n\nexport function shouldRunHeadless(\n argv: string[],\n resumeThreadId: string | undefined,\n hasHeadlessFlag: boolean,\n): boolean {\n return !resumeThreadId && (hasHeadlessFlag || argv.includes('--help') || argv.includes('-h'));\n}\n\nexport function shouldRejectResumeWithoutTTY(resumeThreadId: string | undefined, isTTY: boolean): boolean {\n return Boolean(resumeThreadId) && !isTTY;\n}\n\nexport function formatResumeHint(threadId: string): string {\n const hasControlCharacters = [...threadId].some(character => {\n const codePoint = character.codePointAt(0)!;\n return codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f);\n });\n const argument = /^[a-zA-Z0-9_-]+$/.test(threadId)\n ? threadId\n : hasControlCharacters\n ? `$'${[...threadId]\n .map(character => {\n const codePoint = character.codePointAt(0)!;\n if (character === \"'\") return \"\\\\'\";\n if (character === '\\\\') return '\\\\\\\\';\n if (codePoint <= 0x1f || codePoint === 0x7f) return `\\\\x${codePoint.toString(16).padStart(2, '0')}`;\n if (codePoint >= 0x80 && codePoint <= 0x9f) {\n return `\\\\u${codePoint.toString(16).padStart(4, '0')}`;\n }\n return character;\n })\n .join('')}'`\n : `'${threadId.replaceAll(\"'\", \"'\\\\''\")}'`;\n return `To continue this session, run mastracode resume ${argument}`;\n}\n","export function resolveTuiSubagents(enabled: boolean): undefined | [] {\n return enabled ? undefined : [];\n}\n","import { readFileSync } from 'node:fs';\n\ndeclare const MASTRACODE_VERSION: string | undefined;\n\nexport function getCurrentVersion(): string {\n if (typeof MASTRACODE_VERSION !== 'undefined') {\n return MASTRACODE_VERSION;\n }\n\n const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as { version: string };\n return pkg.version;\n}\n","#!/usr/bin/env node\n/**\n * Main entry point for Mastra Code TUI.\n */\nimport fs from 'node:fs';\n\nimport { createMastraCode } from '@mastra/code-sdk';\nimport { createMastraCodeAnalytics } from '@mastra/code-sdk/analytics';\nimport { isStreamDestroyedError } from '@mastra/code-sdk/error-classification';\nimport { hasHeadlessFlag, runMCCli } from '@mastra/code-sdk/headless/index';\nimport {\n createBrowserFromSettings,\n loadSettings,\n resolveStagehandModel,\n toActiveBrowserSettings,\n} from '@mastra/code-sdk/onboarding/settings';\nimport { formatScaffoldSuccess, scaffoldPlugin } from '@mastra/code-sdk/plugins/scaffold';\nimport {\n stopProcessMemoryDiagnosticsWithTimeout,\n type ProcessMemoryDiagnostics,\n} from '@mastra/code-sdk/process-memory-diagnostics';\nimport { setupDebugLogging, truncateLogFile } from '@mastra/code-sdk/utils/debug-log';\nimport { drainPipedStdin, reopenStdinFromTTY } from '@mastra/code-sdk/utils/stdin-pipe';\nimport { releaseAllThreadLocks } from '@mastra/code-sdk/utils/thread-lock';\nimport { TUI_CO_AUTHOR } from './commit-attribution.js';\nimport { initialMessageOptions, pipedInputConflict, takeInitialPrompt } from './initial-prompt.js';\nimport {\n createOneShotFatalErrorHandler,\n createShutdownCoordinator,\n startTuiProcessMemoryDiagnostics,\n} from './process-memory-diagnostics-lifecycle.js';\nimport {\n formatResumeHint,\n parseResumeThreadId,\n shouldRejectResumeWithoutTTY,\n shouldRunHeadless,\n} from './resume-command.js';\nimport { resolveTuiSubagents } from './subagent-settings.js';\nimport { detectTerminalTheme } from './tui/detect-theme.js';\nimport { MastraTUI } from './tui/index.js';\nimport { applyThemeMode, restoreTerminalForeground } from './tui/theme.js';\nimport { 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 analytics: ReturnType<typeof createMastraCodeAnalytics> | undefined;\nlet tui: MastraTUI | undefined;\nlet processMemoryDiagnostics: ProcessMemoryDiagnostics | undefined;\nlet storageClosed = false;\nlet cleanupPromise: Promise<void> | null = null;\nlet getResumeThreadId: (() => string | null) | undefined;\n\nconst CRASH_LOG_PATH = '/tmp/mastra-crash.log';\n\nfunction isTruthyEnv(name: string): boolean {\n return ['1', 'true', 'yes', 'on'].includes(process.env[name]?.trim().toLowerCase() ?? '');\n}\n\nfunction resolveInitialStateFromEnv() {\n const currentModelId = process.env.MASTRACODE_MODEL_ID?.trim();\n const initialState: Record<string, unknown> = {};\n if (currentModelId) initialState.currentModelId = currentModelId;\n if (isTruthyEnv('MASTRACODE_YOLO')) initialState.yolo = true;\n return Object.keys(initialState).length > 0 ? initialState : undefined;\n}\n\n// Global safety nets — catch any uncaught errors from storage init, etc.\nprocess.on('uncaughtException', error => {\n // ERR_STREAM_DESTROYED is non-fatal — happens routinely when streams close\n // during shutdown, cancelled LLM requests, or LSP/subprocess exits (#13548, #13549)\n if (isStreamDestroyedError(error)) return;\n handleFatalError(error);\n});\nprocess.on('unhandledRejection', reason => {\n if (isStreamDestroyedError(reason)) return;\n handleFatalError(reason instanceof Error ? reason : new Error(String(reason)));\n});\n\nasync function tuiMain(startupMessage: ReturnType<typeof initialMessageOptions> = {}, resumeThreadId?: string) {\n const settings = loadSettings();\n processMemoryDiagnostics = await startTuiProcessMemoryDiagnostics(process.env, warning => {\n console.info(`⚠ ${warning}`);\n });\n let browserPromise: ReturnType<typeof createBrowserFromSettings> | undefined;\n const loadBrowser = (chatModelId: string | undefined) => {\n browserPromise ??= createBrowserFromSettings(settings.browser, { chatModelId });\n return browserPromise;\n };\n\n const initialState = resolveInitialStateFromEnv();\n const result = await createMastraCode({\n createInitialThread: false,\n coAuthor: TUI_CO_AUTHOR,\n unixSocketPubSub: !isTruthyEnv('MASTRACODE_DISABLE_UNIX_SOCKET_PUBSUB'),\n disableMcp: isTruthyEnv('MASTRACODE_DISABLE_MCP'),\n disableHooks: isTruthyEnv('MASTRACODE_DISABLE_HOOKS'),\n subagents: resolveTuiSubagents(settings.preferences.subagentsEnabled),\n ...(isTruthyEnv('MASTRACODE_DISABLE_MEMORY') ? { memory: false as never } : {}),\n ...(initialState ? { initialState: initialState as never } : {}),\n });\n controller = result.controller;\n mcpManager = result.mcpManager;\n hookManager = result.hookManager;\n authStorage = result.authStorage;\n signalsPubSub = result.signalsPubSub;\n storageMaintenance = result.storageMaintenance;\n stopPluginSignalProviders = result.stopPluginSignalProviders;\n threadScheduler = result.threadScheduler;\n stopNotificationDispatch = result.stopNotificationDispatch;\n\n if (result.storageWarning) {\n console.info(`⚠ ${result.storageWarning}`);\n }\n if (result.observabilityWarning) {\n console.info(`⚠ ${result.observabilityWarning}`);\n }\n\n // MCP connection is deferred to TUI.init() (after ui.start()) so that\n // status messages use showInfo() instead of console.info(), which would\n // corrupt the terminal. Headless mode still inits from headless/cli.ts.\n\n setupDebugLogging();\n\n // Detect and apply terminal theme\n // MASTRA_THEME env var is the highest-priority override\n const envTheme = process.env.MASTRA_THEME?.toLowerCase();\n let themeMode: 'dark' | 'light';\n let detectedBgHex: string | undefined;\n if (envTheme === 'dark' || envTheme === 'light') {\n themeMode = envTheme;\n } else {\n const settings = loadSettings();\n const themePref = settings.preferences.theme;\n if (themePref === 'dark' || themePref === 'light') {\n themeMode = themePref;\n } else {\n const detection = await detectTerminalTheme();\n themeMode = detection.mode;\n detectedBgHex = detection.detectedBgHex;\n }\n }\n applyThemeMode(themeMode, detectedBgHex);\n\n // createMastraCode() brought up shared resources and minted the single\n // session that all work runs through. The AgentController owns no session of its own.\n const session = result.session;\n getResumeThreadId = () => (tui ? tui.getResumeThreadId() : session.thread.getId());\n\n analytics = createMastraCodeAnalytics({ version: getCurrentVersion() });\n analytics.capture('mastracode_session_started', {\n mode: session.mode.get(),\n resourceId: session.identity.getResourceId(),\n hasAuthStorage: Boolean(authStorage),\n hasMcp: Boolean(mcpManager),\n theme: themeMode,\n });\n\n tui = new MastraTUI({\n controller: controller,\n session,\n hookManager,\n analytics,\n authStorage,\n mcpManager,\n pluginManager: result.pluginManager,\n storageMaintenance: result.storageMaintenance,\n processMemoryDiagnostics,\n knowledgeInspector: result.knowledgeInspector,\n threadScheduler: result.threadScheduler,\n appName: 'Mastra Code',\n version: getCurrentVersion(),\n inlineQuestions: true,\n ...(resumeThreadId ? { resumeThreadId } : {}),\n githubSignals: result.githubSignals,\n backgroundToolsEnabled: result.backgroundToolsEnabled,\n backgroundCompletionEvents: result.backgroundCompletionEvents,\n exit: exitCode => void shutdownAndExit(exitCode),\n ...startupMessage,\n });\n tui.run().catch(error => {\n handleFatalError(error);\n });\n\n if (settings.browser.enabled) {\n // Captured once: the Stagehand instance is fixed at launch and shared by every thread.\n const chatModelId = session.model.get();\n void loadBrowser(chatModelId)\n .then(browser => {\n if (!browser) return;\n controller.setBrowser(browser);\n void session.state\n .set({\n activeBrowserSettings: toActiveBrowserSettings(settings.browser),\n activeBrowserModel: resolveStagehandModel(settings.browser, { chatModelId }),\n } as any)\n .catch(() => {});\n })\n .catch(() => {});\n }\n}\n\nconst asyncCleanup = (): Promise<void> => {\n cleanupPromise ??= (async () => {\n releaseAllThreadLocks();\n // Stop plugin-contributed signal providers (and the plugin reload listener)\n // before quiescing workers: a provider that keeps polling past this point\n // could dispatch into a controller that is shutting down.\n try {\n stopPluginSignalProviders?.();\n } catch {\n // Best-effort — the process is exiting.\n }\n const diagnosticsShutdown = processMemoryDiagnostics\n ? stopProcessMemoryDiagnosticsWithTimeout(processMemoryDiagnostics, message => console.warn(message))\n : undefined;\n // Schedules live only in this process; stop their timers so none fires mid-shutdown.\n threadScheduler?.stop();\n // Release this process's notification dispatch leases before the pubsub that holds them closes.\n await stopNotificationDispatch?.().catch(() => {});\n await Promise.allSettled([mcpManager?.disconnect(), controller?.stopIntervals()]);\n // Mastra owns the workspaces and must destroy them to stop retained language\n // servers before storage is closed.\n await Promise.allSettled([controller?.getMastra()?.shutdown(), analytics?.shutdown()]);\n // The signals pubsub is Mastra's event bus: in-flight runs and background\n // tasks drain through it during shutdown, so close it only afterwards. Call\n // close() on the object; a detached method loses `this` and rejects silently.\n const pubsubToClose = signalsPubSub as { close?: () => Promise<void> | void } | undefined;\n await Promise.allSettled([pubsubToClose?.close?.()]);\n // Checkpoint WAL and close the local storage connection after all producers\n // and timers are quiesced. Idempotent — repeated signals (SIGINT then SIGHUP)\n // close only once. LibSQLStore.close()/LibSQLVector.close() truncate the WAL\n // and switch back to DELETE journal mode for a clean shutdown.\n if (!storageClosed) {\n storageClosed = true;\n await storageMaintenance?.closeStorage?.().catch(() => {\n // Swallow — best-effort cleanup during shutdown. The process is exiting.\n });\n }\n await diagnosticsShutdown;\n })();\n return cleanupPromise;\n};\n\nconst shutdownAndExit = createShutdownCoordinator(asyncCleanup, exitCode => process.exit(exitCode));\n\nprocess.on('beforeExit', () => {\n void asyncCleanup();\n});\nprocess.on('exit', () => {\n // Ensure terminal protocols (kitty keyboard, modifyOtherKeys, bracketed paste,\n // raw mode) are disabled on ANY exit path. Without this, killing the process\n // via SIGINT/SIGTERM leaves the terminal in a corrupted state where keypresses\n // produce escape sequences like \"5;99~\" instead of normal characters.\n try {\n tui?.stop();\n } catch {\n // Failsafe: even if MastraTUI.stop() throws, write raw terminal reset\n // sequences to disable Kitty keyboard protocol, bracketed paste, and\n // modifyOtherKeys. These are the exact sequences pi-tui's terminal.stop()\n // would write.\n }\n // Belt-and-suspenders: always write terminal reset sequences directly,\n // regardless of whether tui.stop() succeeded. Writing them twice is harmless\n // but missing them leaves the terminal in a corrupted state.\n try {\n process.stdout.write(\n '\\x1b[?2004l' + // disable bracketed paste\n '\\x1b[<u' + // pop kitty keyboard protocol\n '\\x1b[>4;0m' + // disable modifyOtherKeys\n '\\x1b[?25h', // show cursor\n );\n if (process.stdin.setRawMode) {\n process.stdin.setRawMode(false);\n }\n } catch {\n // stdout may already be closed during exit\n }\n restoreTerminalForeground();\n releaseAllThreadLocks();\n try {\n const threadId = getResumeThreadId?.();\n if (threadId) {\n process.stdout.write(`\\n${formatResumeHint(threadId)}\\n`);\n }\n } catch {\n // session state or stdout may already be closed during exit\n }\n});\n\n// Start durable diagnostics shutdown before synchronous TUI teardown so a stalled\n// terminal cleanup cannot prevent the final profile capture. The exit handler still\n// provides a failsafe terminal reset if teardown throws.\nconst handleTermSignal = () => {\n void asyncCleanup();\n try {\n tui?.stop();\n } catch {\n // ignored — exit handler has failsafe reset\n }\n void shutdownAndExit(0);\n};\nprocess.on('SIGINT', handleTermSignal);\nprocess.on('SIGTERM', handleTermSignal);\nprocess.on('SIGHUP', handleTermSignal);\n\nfunction hasEconnrefused(err: unknown, depth = 0): boolean {\n if (!err || depth > 5) return false;\n const e = err as any;\n if (e.code === 'ECONNREFUSED') return true;\n if (e.cause) return hasEconnrefused(e.cause, depth + 1);\n // AggregateError has .errors array\n if (Array.isArray(e.errors)) return e.errors.some((inner: unknown) => hasEconnrefused(inner, depth + 1));\n return false;\n}\n\nfunction pluginMain(args: string[]): void {\n if (args[0] !== 'scaffold') {\n process.stderr.write('Usage: mastracode plugin scaffold <dir> [--id acme.foo] [--name \"Foo Tools\"]\\n');\n process.exit(1);\n }\n\n const dir = args[1];\n if (!dir) {\n process.stderr.write('Usage: mastracode plugin scaffold <dir> [--id acme.foo] [--name \"Foo Tools\"]\\n');\n process.exit(1);\n }\n\n const id = readFlag(args, '--id');\n const name = readFlag(args, '--name');\n const targetDir = scaffoldPlugin(dir, { ...(id ? { id } : {}), ...(name ? { name } : {}) });\n process.stdout.write(`${formatScaffoldSuccess(targetDir)}\\n`);\n}\n\nfunction readFlag(args: string[], flag: string): string | undefined {\n const index = args.indexOf(flag);\n if (index === -1) return undefined;\n const value = args[index + 1];\n if (!value || value.startsWith('--')) {\n throw new Error(`Missing value for ${flag}`);\n }\n return value;\n}\n\nconst handleFatalError = createOneShotFatalErrorHandler((error: unknown): void => {\n // Always write to real stderr, even if console.error was overridden\n const write = (msg: string) => {\n try {\n process.stderr.write(msg + '\\n');\n } catch {}\n };\n\n if (hasEconnrefused(error)) {\n const settings = loadSettings();\n const connStr = settings.storage?.pg?.connectionString;\n const target = connStr ?? 'localhost:5432';\n write(\n `\\nFailed to connect to PostgreSQL at ${target}.` +\n `\\nMake sure the database is running and accessible.` +\n `\\n\\nTo switch back to LibSQL:` +\n `\\n Set MASTRA_STORAGE_BACKEND=libsql or change the backend in /settings\\n`,\n );\n void asyncCleanup();\n try {\n tui?.stop();\n } catch {}\n void shutdownAndExit(1);\n return;\n }\n\n const msg = `Fatal error: ${error instanceof Error ? error.message : String(error)}`;\n write(msg);\n // Write crash log to file so it persists even if terminal closes\n try {\n const crashLog = `[${new Date().toISOString()}] ${msg}\\n${error instanceof Error && error.stack ? error.stack + '\\n' : ''}`;\n truncateLogFile(CRASH_LOG_PATH);\n fs.appendFileSync(CRASH_LOG_PATH, crashLog);\n truncateLogFile(CRASH_LOG_PATH);\n } catch {}\n if (error instanceof Error && error.stack) {\n write(error.stack);\n }\n void asyncCleanup();\n try {\n tui?.stop();\n } catch {}\n void shutdownAndExit(1);\n});\n\nasync function main() {\n if (process.argv[2] === 'plugin') {\n return pluginMain(process.argv.slice(3));\n }\n\n // Storage maintenance without the TUI, so a database can still be pruned and\n // compacted when the interactive session won't start. Checked before the\n // headless branch below, which would otherwise claim `prune --help`.\n if (process.argv[2] === 'prune') {\n const { runPruneCommand } = await import('@mastra/code-sdk/utils/prune-cli');\n return process.exit(await runPruneCommand(process.argv.slice(3)));\n }\n\n const loginIndex = process.argv.findIndex(\n (arg, index) => index >= 2 && arg !== '--acp' && arg !== '--dangerous-auto-approve',\n );\n if (process.argv[loginIndex] === 'login') {\n const { runLoginCommand } = await import('./login-command.js');\n const code = await runLoginCommand({ args: process.argv.slice(loginIndex + 1) });\n await new Promise(resolve => process.stdout.write('', resolve));\n return process.exit(code);\n }\n\n const initialPrompt = takeInitialPrompt(process.argv, process.env);\n if (initialPrompt.error) {\n process.stderr.write(`${initialPrompt.error}\\n`);\n process.exit(1);\n }\n if (initialPrompt.flag) process.argv = initialPrompt.argv;\n // The flag only means something to the interactive TUI. Paths that can't run\n // it reject the flag instead of dropping the prompt; an env var prompt is\n // just ignored there.\n const rejectInitialPromptFlag = (reason: string) => {\n if (!initialPrompt.flag) return;\n process.stderr.write(`${initialPrompt.flag} starts the interactive TUI; ${reason}\\n`);\n process.exit(1);\n };\n\n let resumeThreadId: string | undefined;\n try {\n resumeThreadId = parseResumeThreadId(process.argv.slice(2));\n } catch (error) {\n process.stderr.write(`${error instanceof Error ? error.message : String(error)}\\n`);\n process.exitCode = 1;\n return;\n }\n\n const headless = hasHeadlessFlag(process.argv);\n if (shouldRunHeadless(process.argv, resumeThreadId, headless)) {\n if (headless) rejectInitialPromptFlag('use --prompt for headless runs');\n return runMCCli(undefined, { coAuthor: TUI_CO_AUTHOR });\n }\n\n if (process.argv.includes('--acp')) {\n rejectInitialPromptFlag('it cannot be combined with --acp');\n const { acpMain } = await import('@mastra/code-sdk/acp/index');\n return acpMain({\n dangerousAutoApprove: process.argv.includes('--dangerous-auto-approve'),\n coAuthor: TUI_CO_AUTHOR,\n });\n }\n\n if (shouldRejectResumeWithoutTTY(resumeThreadId, Boolean(process.stdin.isTTY))) {\n process.stderr.write('mastracode resume requires an interactive terminal.\\n');\n process.exitCode = 1;\n return;\n }\n\n // When stdin is piped (e.g. `cat foo | mastracode`), drain the pipe fully\n // before starting the TUI. The drain blocks until the sender process exits\n // and closes its stdout, so we never see partial output.\n let pipedInput: string | null = null;\n if (!process.stdin.isTTY) {\n process.stderr.write('Reading piped input...\\n');\n pipedInput = await drainPipedStdin();\n\n // Always reopen a real TTY — even if the pipe was empty, the original\n // stdin is consumed/closed and the TUI needs a live TTY for keyboard input.\n const reopenedStdin = reopenStdinFromTTY();\n if (!reopenedStdin) {\n rejectInitialPromptFlag('no TTY is available, so use --prompt for headless runs');\n process.stderr.write('No TTY available — falling back to headless mode.\\n');\n return runMCCli(pipedInput, { coAuthor: TUI_CO_AUTHOR });\n }\n }\n\n const conflict = pipedInputConflict(initialPrompt, pipedInput);\n if (conflict) {\n process.stderr.write(`${conflict}\\n`);\n process.exit(1);\n }\n\n return tuiMain(initialMessageOptions(initialPrompt, pipedInput), resumeThreadId);\n}\n\nmain().catch(error => {\n handleFatalError(error);\n});\n"],"mappings":";;;;;;;;;;;;;;;AAAA,MAAa,sBAAsB;AACnC,MAAa,qBAAqB;AAElC,MAAa,kBAAkB;;;;;;;;;;AA0B/B,SAAgB,kBAAkB,MAAgB,KAA2C;CAC3F,MAAM,UAAU,IAAI;CACpB,OAAO,IAAI;CAEX,MAAM,OAAiB,CAAC;CACxB,MAAM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;CAChB;CAEA,OAAO,QAAQ,sBAAsB,eAAe,UAAU,GAAG,cAAc;AACjF;AAEA,KAAK,CAAC,CAAC,OAAM,UAAS;CACpB,iBAAiB,KAAK;AACxB,CAAC"}
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { b as TUI_CO_AUTHOR, d as detectTerminalTheme, f as applyThemeMode, t as MastraTUI, v as restoreTerminalForeground } from "./tui-CUNuxs-4.js";
2
+ import { b as TUI_CO_AUTHOR, d as detectTerminalTheme, f as applyThemeMode, t as MastraTUI, v as restoreTerminalForeground } from "./tui-Boav6A4H.js";
3
3
  import { createMastraCode } from "@mastra/code-sdk";
4
4
  import fs from "fs";
5
5
  import { createMastraCodeAnalytics } from "@mastra/code-sdk/analytics";
@@ -139,7 +139,7 @@ function resolveTuiSubagents(enabled) {
139
139
  //#endregion
140
140
  //#region src/version.ts
141
141
  function getCurrentVersion() {
142
- return "0.45.0-alpha.3";
142
+ return "0.45.0-alpha.4";
143
143
  }
144
144
  //#endregion
145
145
  //#region src/main.ts
@@ -398,6 +398,13 @@ async function main() {
398
398
  const { runPruneCommand } = await import("@mastra/code-sdk/utils/prune-cli");
399
399
  return process.exit(await runPruneCommand(process.argv.slice(3)));
400
400
  }
401
+ const loginIndex = process.argv.findIndex((arg, index) => index >= 2 && arg !== "--acp" && arg !== "--dangerous-auto-approve");
402
+ if (process.argv[loginIndex] === "login") {
403
+ const { runLoginCommand } = await import("./login-command-C0Ro4glG.js");
404
+ const code = await runLoginCommand({ args: process.argv.slice(loginIndex + 1) });
405
+ await new Promise((resolve) => process.stdout.write("", resolve));
406
+ return process.exit(code);
407
+ }
401
408
  const initialPrompt = takeInitialPrompt(process.argv, process.env);
402
409
  if (initialPrompt.error) {
403
410
  process.stderr.write(`${initialPrompt.error}\n`);
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","names":[],"sources":["../src/initial-prompt.ts","../src/process-memory-diagnostics-lifecycle.ts","../src/resume-command.ts","../src/subagent-settings.ts","../src/version.ts","../src/main.ts"],"sourcesContent":["export const INITIAL_PROMPT_FLAG = '--tui-initial-prompt' as const;\nexport const INITIAL_PROMPT_ENV = 'MASTRACODE_TUI_INITIAL_PROMPT';\n\nexport const TUI_PROMPT_FLAG = '--tui-prompt' as const;\n\nexport type InitialPromptArgs = {\n /** argv with the flag and its value removed, so headless detection never mistakes the value for a prompt. */\n argv: string[];\n prompt?: string;\n /** Set when a flag was passed without a value, or both flags were passed. */\n error?: string;\n /** The flag the prompt came from; undefined when it came from the environment. */\n flag?: typeof INITIAL_PROMPT_FLAG | typeof TUI_PROMPT_FLAG;\n /**\n * `--tui-prompt` sends even when startup resumes an existing conversation;\n * `--tui-initial-prompt` and the environment variable only start a new one.\n */\n sendOnResume: boolean;\n};\n\n/**\n * Takes the interactive startup prompt from `--tui-initial-prompt <text>` or\n * `--tui-prompt <text>` (also `--flag=<text>`), falling back to\n * `MASTRACODE_TUI_INITIAL_PROMPT`.\n *\n * The environment variable is always removed from `env`: everything this\n * process spawns inherits its environment, and a nested Mastra Code (or any\n * shell the agent starts) must not send the same prompt again.\n */\nexport function takeInitialPrompt(argv: string[], env: NodeJS.ProcessEnv): InitialPromptArgs {\n const fromEnv = env[INITIAL_PROMPT_ENV];\n delete env[INITIAL_PROMPT_ENV];\n\n const rest: string[] = [];\n const found = new Map<NonNullable<InitialPromptArgs['flag']>, string>();\n let error: string | undefined;\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i]!;\n const flag = [INITIAL_PROMPT_FLAG, TUI_PROMPT_FLAG].find(f => arg === f || arg.startsWith(`${f}=`));\n if (!flag) {\n rest.push(arg);\n } else if (arg !== flag) {\n found.set(flag, arg.slice(flag.length + 1));\n } else if (argv[i + 1] === undefined) {\n error = `${flag} needs a value`;\n } else {\n found.set(flag, argv[++i]!);\n }\n }\n if (found.size > 1) error = `Use either ${INITIAL_PROMPT_FLAG} or ${TUI_PROMPT_FLAG}, not both`;\n\n const [flag, flagValue] = [...found][0] ?? [];\n const prompt = (flag ? flagValue : fromEnv)?.trim() || undefined;\n return { argv: rest, prompt, error, flag, sendOnResume: flag === TUI_PROMPT_FLAG };\n}\n\n/** The first message the TUI sends: the initial prompt, followed by any piped stdin. */\nexport function composeInitialMessage(prompt: string | undefined, pipedInput: string | null | undefined) {\n const piped = pipedInput ? `The following was piped via stdin:\\n\\n${pipedInput}` : undefined;\n if (prompt && piped) return `${prompt}\\n\\n${piped}`;\n return prompt ?? piped;\n}\n\n/**\n * Why a startup prompt can't be combined with piped stdin, if it can't.\n *\n * The first message is submitted like typed input, so a prompt starting with\n * `/` or `!` is dispatched as a command. Folding piped text into it would make\n * that text part of the command — skill arguments, or a shell script for `!`.\n */\nexport function pipedInputConflict(\n args: Pick<InitialPromptArgs, 'prompt' | 'flag'>,\n pipedInput: string | null | undefined,\n): string | undefined {\n if (!args.prompt || !pipedInput) return undefined;\n if (!args.prompt.startsWith('/') && !args.prompt.startsWith('!')) return undefined;\n const source = args.flag ?? INITIAL_PROMPT_ENV;\n return `${source} can't be combined with piped stdin when it is a slash command or starts with !`;\n}\n\n/** The TUI options for a startup prompt and/or piped stdin. */\nexport function initialMessageOptions(\n args: Pick<InitialPromptArgs, 'prompt' | 'sendOnResume'>,\n pipedInput?: string | null,\n): { initialMessage?: string; resumeSkipNotice?: string } {\n const initialMessage = composeInitialMessage(args.prompt, pipedInput);\n if (!initialMessage) return {};\n // Piped stdin on its own is always sent, as before.\n if (!args.prompt || args.sendOnResume) return { initialMessage };\n const skipped = pipedInput ? 'the initial prompt and piped input were' : 'the initial prompt was';\n return {\n initialMessage,\n resumeSkipNotice: `Resumed the existing conversation for this directory, so ${skipped} not sent. Use ${TUI_PROMPT_FLAG} to send ${pipedInput ? 'them' : 'it'} anyway.`,\n };\n}\n","import {\n createProcessMemoryDiagnosticsFromEnvironment,\n startConfiguredProcessMemoryDiagnostics,\n type ProcessMemoryDiagnostics,\n type ProcessMemoryDiagnosticsEnvironment,\n type ProcessMemoryDiagnosticsSetup,\n} from '@mastra/code-sdk/process-memory-diagnostics';\n\nexport async function startTuiProcessMemoryDiagnostics(\n env: ProcessMemoryDiagnosticsEnvironment,\n warn: (message: string) => void,\n createSetup: (\n env: ProcessMemoryDiagnosticsEnvironment,\n ) => ProcessMemoryDiagnosticsSetup = createProcessMemoryDiagnosticsFromEnvironment,\n): Promise<ProcessMemoryDiagnostics> {\n return startConfiguredProcessMemoryDiagnostics(createSetup(env), warn);\n}\n\nexport function createOneShotFatalErrorHandler(handle: (error: unknown) => void): (error: unknown) => void {\n let handlingFatalError = false;\n return error => {\n if (handlingFatalError) return;\n handlingFatalError = true;\n handle(error);\n };\n}\n\nexport function createShutdownCoordinator(\n cleanup: () => Promise<void>,\n exit: (exitCode: number) => never,\n timeoutMs = 5_000,\n): (exitCode: number) => Promise<void> {\n let shutdownPromise: Promise<void> | null = null;\n return exitCode => {\n shutdownPromise ??= (async () => {\n let timeout: ReturnType<typeof setTimeout> | undefined;\n await Promise.race([\n cleanup().catch(() => undefined),\n new Promise<void>(resolve => {\n timeout = setTimeout(resolve, timeoutMs);\n }),\n ]);\n if (timeout) clearTimeout(timeout);\n exit(exitCode);\n })();\n return shutdownPromise;\n };\n}\n","export function parseResumeThreadId(args: string[]): string | undefined {\n if (args[0] !== 'resume') return undefined;\n\n const threadId = args[1]?.trim();\n if (!threadId || args.length !== 2) {\n throw new Error('Usage: mastracode resume <thread-id>');\n }\n return threadId;\n}\n\nexport function shouldRunHeadless(\n argv: string[],\n resumeThreadId: string | undefined,\n hasHeadlessFlag: boolean,\n): boolean {\n return !resumeThreadId && (hasHeadlessFlag || argv.includes('--help') || argv.includes('-h'));\n}\n\nexport function shouldRejectResumeWithoutTTY(resumeThreadId: string | undefined, isTTY: boolean): boolean {\n return Boolean(resumeThreadId) && !isTTY;\n}\n\nexport function formatResumeHint(threadId: string): string {\n const hasControlCharacters = [...threadId].some(character => {\n const codePoint = character.codePointAt(0)!;\n return codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f);\n });\n const argument = /^[a-zA-Z0-9_-]+$/.test(threadId)\n ? threadId\n : hasControlCharacters\n ? `$'${[...threadId]\n .map(character => {\n const codePoint = character.codePointAt(0)!;\n if (character === \"'\") return \"\\\\'\";\n if (character === '\\\\') return '\\\\\\\\';\n if (codePoint <= 0x1f || codePoint === 0x7f) return `\\\\x${codePoint.toString(16).padStart(2, '0')}`;\n if (codePoint >= 0x80 && codePoint <= 0x9f) {\n return `\\\\u${codePoint.toString(16).padStart(4, '0')}`;\n }\n return character;\n })\n .join('')}'`\n : `'${threadId.replaceAll(\"'\", \"'\\\\''\")}'`;\n return `To continue this session, run mastracode resume ${argument}`;\n}\n","export function resolveTuiSubagents(enabled: boolean): undefined | [] {\n return enabled ? undefined : [];\n}\n","import { readFileSync } from 'node:fs';\n\ndeclare const MASTRACODE_VERSION: string | undefined;\n\nexport function getCurrentVersion(): string {\n if (typeof MASTRACODE_VERSION !== 'undefined') {\n return MASTRACODE_VERSION;\n }\n\n const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as { version: string };\n return pkg.version;\n}\n","#!/usr/bin/env node\n/**\n * Main entry point for Mastra Code TUI.\n */\nimport fs from 'node:fs';\n\nimport { createMastraCode } from '@mastra/code-sdk';\nimport { createMastraCodeAnalytics } from '@mastra/code-sdk/analytics';\nimport { isStreamDestroyedError } from '@mastra/code-sdk/error-classification';\nimport { hasHeadlessFlag, runMCCli } from '@mastra/code-sdk/headless/index';\nimport {\n createBrowserFromSettings,\n loadSettings,\n resolveStagehandModel,\n toActiveBrowserSettings,\n} from '@mastra/code-sdk/onboarding/settings';\nimport { formatScaffoldSuccess, scaffoldPlugin } from '@mastra/code-sdk/plugins/scaffold';\nimport {\n stopProcessMemoryDiagnosticsWithTimeout,\n type ProcessMemoryDiagnostics,\n} from '@mastra/code-sdk/process-memory-diagnostics';\nimport { setupDebugLogging, truncateLogFile } from '@mastra/code-sdk/utils/debug-log';\nimport { drainPipedStdin, reopenStdinFromTTY } from '@mastra/code-sdk/utils/stdin-pipe';\nimport { releaseAllThreadLocks } from '@mastra/code-sdk/utils/thread-lock';\nimport { TUI_CO_AUTHOR } from './commit-attribution.js';\nimport { initialMessageOptions, pipedInputConflict, takeInitialPrompt } from './initial-prompt.js';\nimport {\n createOneShotFatalErrorHandler,\n createShutdownCoordinator,\n startTuiProcessMemoryDiagnostics,\n} from './process-memory-diagnostics-lifecycle.js';\nimport {\n formatResumeHint,\n parseResumeThreadId,\n shouldRejectResumeWithoutTTY,\n shouldRunHeadless,\n} from './resume-command.js';\nimport { resolveTuiSubagents } from './subagent-settings.js';\nimport { detectTerminalTheme } from './tui/detect-theme.js';\nimport { MastraTUI } from './tui/index.js';\nimport { applyThemeMode, restoreTerminalForeground } from './tui/theme.js';\nimport { 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 analytics: ReturnType<typeof createMastraCodeAnalytics> | undefined;\nlet tui: MastraTUI | undefined;\nlet processMemoryDiagnostics: ProcessMemoryDiagnostics | undefined;\nlet storageClosed = false;\nlet cleanupPromise: Promise<void> | null = null;\nlet getResumeThreadId: (() => string | null) | undefined;\n\nconst CRASH_LOG_PATH = '/tmp/mastra-crash.log';\n\nfunction isTruthyEnv(name: string): boolean {\n return ['1', 'true', 'yes', 'on'].includes(process.env[name]?.trim().toLowerCase() ?? '');\n}\n\nfunction resolveInitialStateFromEnv() {\n const currentModelId = process.env.MASTRACODE_MODEL_ID?.trim();\n const initialState: Record<string, unknown> = {};\n if (currentModelId) initialState.currentModelId = currentModelId;\n if (isTruthyEnv('MASTRACODE_YOLO')) initialState.yolo = true;\n return Object.keys(initialState).length > 0 ? initialState : undefined;\n}\n\n// Global safety nets — catch any uncaught errors from storage init, etc.\nprocess.on('uncaughtException', error => {\n // ERR_STREAM_DESTROYED is non-fatal — happens routinely when streams close\n // during shutdown, cancelled LLM requests, or LSP/subprocess exits (#13548, #13549)\n if (isStreamDestroyedError(error)) return;\n handleFatalError(error);\n});\nprocess.on('unhandledRejection', reason => {\n if (isStreamDestroyedError(reason)) return;\n handleFatalError(reason instanceof Error ? reason : new Error(String(reason)));\n});\n\nasync function tuiMain(startupMessage: ReturnType<typeof initialMessageOptions> = {}, resumeThreadId?: string) {\n const settings = loadSettings();\n processMemoryDiagnostics = await startTuiProcessMemoryDiagnostics(process.env, warning => {\n console.info(`⚠ ${warning}`);\n });\n let browserPromise: ReturnType<typeof createBrowserFromSettings> | undefined;\n const loadBrowser = (chatModelId: string | undefined) => {\n browserPromise ??= createBrowserFromSettings(settings.browser, { chatModelId });\n return browserPromise;\n };\n\n const initialState = resolveInitialStateFromEnv();\n const result = await createMastraCode({\n createInitialThread: false,\n coAuthor: TUI_CO_AUTHOR,\n unixSocketPubSub: !isTruthyEnv('MASTRACODE_DISABLE_UNIX_SOCKET_PUBSUB'),\n disableMcp: isTruthyEnv('MASTRACODE_DISABLE_MCP'),\n disableHooks: isTruthyEnv('MASTRACODE_DISABLE_HOOKS'),\n subagents: resolveTuiSubagents(settings.preferences.subagentsEnabled),\n ...(isTruthyEnv('MASTRACODE_DISABLE_MEMORY') ? { memory: false as never } : {}),\n ...(initialState ? { initialState: initialState as never } : {}),\n });\n controller = result.controller;\n mcpManager = result.mcpManager;\n hookManager = result.hookManager;\n authStorage = result.authStorage;\n signalsPubSub = result.signalsPubSub;\n storageMaintenance = result.storageMaintenance;\n stopPluginSignalProviders = result.stopPluginSignalProviders;\n threadScheduler = result.threadScheduler;\n stopNotificationDispatch = result.stopNotificationDispatch;\n\n if (result.storageWarning) {\n console.info(`⚠ ${result.storageWarning}`);\n }\n if (result.observabilityWarning) {\n console.info(`⚠ ${result.observabilityWarning}`);\n }\n\n // MCP connection is deferred to TUI.init() (after ui.start()) so that\n // status messages use showInfo() instead of console.info(), which would\n // corrupt the terminal. Headless mode still inits from headless/cli.ts.\n\n setupDebugLogging();\n\n // Detect and apply terminal theme\n // MASTRA_THEME env var is the highest-priority override\n const envTheme = process.env.MASTRA_THEME?.toLowerCase();\n let themeMode: 'dark' | 'light';\n let detectedBgHex: string | undefined;\n if (envTheme === 'dark' || envTheme === 'light') {\n themeMode = envTheme;\n } else {\n const settings = loadSettings();\n const themePref = settings.preferences.theme;\n if (themePref === 'dark' || themePref === 'light') {\n themeMode = themePref;\n } else {\n const detection = await detectTerminalTheme();\n themeMode = detection.mode;\n detectedBgHex = detection.detectedBgHex;\n }\n }\n applyThemeMode(themeMode, detectedBgHex);\n\n // createMastraCode() brought up shared resources and minted the single\n // session that all work runs through. The AgentController owns no session of its own.\n const session = result.session;\n getResumeThreadId = () => (tui ? tui.getResumeThreadId() : session.thread.getId());\n\n analytics = createMastraCodeAnalytics({ version: getCurrentVersion() });\n analytics.capture('mastracode_session_started', {\n mode: session.mode.get(),\n resourceId: session.identity.getResourceId(),\n hasAuthStorage: Boolean(authStorage),\n hasMcp: Boolean(mcpManager),\n theme: themeMode,\n });\n\n tui = new MastraTUI({\n controller: controller,\n session,\n hookManager,\n analytics,\n authStorage,\n mcpManager,\n pluginManager: result.pluginManager,\n storageMaintenance: result.storageMaintenance,\n processMemoryDiagnostics,\n knowledgeInspector: result.knowledgeInspector,\n threadScheduler: result.threadScheduler,\n appName: 'Mastra Code',\n version: getCurrentVersion(),\n inlineQuestions: true,\n ...(resumeThreadId ? { resumeThreadId } : {}),\n githubSignals: result.githubSignals,\n backgroundToolsEnabled: result.backgroundToolsEnabled,\n backgroundCompletionEvents: result.backgroundCompletionEvents,\n exit: exitCode => void shutdownAndExit(exitCode),\n ...startupMessage,\n });\n tui.run().catch(error => {\n handleFatalError(error);\n });\n\n if (settings.browser.enabled) {\n // Captured once: the Stagehand instance is fixed at launch and shared by every thread.\n const chatModelId = session.model.get();\n void loadBrowser(chatModelId)\n .then(browser => {\n if (!browser) return;\n controller.setBrowser(browser);\n void session.state\n .set({\n activeBrowserSettings: toActiveBrowserSettings(settings.browser),\n activeBrowserModel: resolveStagehandModel(settings.browser, { chatModelId }),\n } as any)\n .catch(() => {});\n })\n .catch(() => {});\n }\n}\n\nconst asyncCleanup = (): Promise<void> => {\n cleanupPromise ??= (async () => {\n releaseAllThreadLocks();\n // Stop plugin-contributed signal providers (and the plugin reload listener)\n // before quiescing workers: a provider that keeps polling past this point\n // could dispatch into a controller that is shutting down.\n try {\n stopPluginSignalProviders?.();\n } catch {\n // Best-effort — the process is exiting.\n }\n const diagnosticsShutdown = processMemoryDiagnostics\n ? stopProcessMemoryDiagnosticsWithTimeout(processMemoryDiagnostics, message => console.warn(message))\n : undefined;\n // Schedules live only in this process; stop their timers so none fires mid-shutdown.\n threadScheduler?.stop();\n // Release this process's notification dispatch leases before the pubsub that holds them closes.\n await stopNotificationDispatch?.().catch(() => {});\n await Promise.allSettled([mcpManager?.disconnect(), controller?.stopIntervals()]);\n // Mastra owns the workspaces and must destroy them to stop retained language\n // servers before storage is closed.\n await Promise.allSettled([controller?.getMastra()?.shutdown(), analytics?.shutdown()]);\n // The signals pubsub is Mastra's event bus: in-flight runs and background\n // tasks drain through it during shutdown, so close it only afterwards. Call\n // close() on the object; a detached method loses `this` and rejects silently.\n const pubsubToClose = signalsPubSub as { close?: () => Promise<void> | void } | undefined;\n await Promise.allSettled([pubsubToClose?.close?.()]);\n // Checkpoint WAL and close the local storage connection after all producers\n // and timers are quiesced. Idempotent — repeated signals (SIGINT then SIGHUP)\n // close only once. LibSQLStore.close()/LibSQLVector.close() truncate the WAL\n // and switch back to DELETE journal mode for a clean shutdown.\n if (!storageClosed) {\n storageClosed = true;\n await storageMaintenance?.closeStorage?.().catch(() => {\n // Swallow — best-effort cleanup during shutdown. The process is exiting.\n });\n }\n await diagnosticsShutdown;\n })();\n return cleanupPromise;\n};\n\nconst shutdownAndExit = createShutdownCoordinator(asyncCleanup, exitCode => process.exit(exitCode));\n\nprocess.on('beforeExit', () => {\n void asyncCleanup();\n});\nprocess.on('exit', () => {\n // Ensure terminal protocols (kitty keyboard, modifyOtherKeys, bracketed paste,\n // raw mode) are disabled on ANY exit path. Without this, killing the process\n // via SIGINT/SIGTERM leaves the terminal in a corrupted state where keypresses\n // produce escape sequences like \"5;99~\" instead of normal characters.\n try {\n tui?.stop();\n } catch {\n // Failsafe: even if MastraTUI.stop() throws, write raw terminal reset\n // sequences to disable Kitty keyboard protocol, bracketed paste, and\n // modifyOtherKeys. These are the exact sequences pi-tui's terminal.stop()\n // would write.\n }\n // Belt-and-suspenders: always write terminal reset sequences directly,\n // regardless of whether tui.stop() succeeded. Writing them twice is harmless\n // but missing them leaves the terminal in a corrupted state.\n try {\n process.stdout.write(\n '\\x1b[?2004l' + // disable bracketed paste\n '\\x1b[<u' + // pop kitty keyboard protocol\n '\\x1b[>4;0m' + // disable modifyOtherKeys\n '\\x1b[?25h', // show cursor\n );\n if (process.stdin.setRawMode) {\n process.stdin.setRawMode(false);\n }\n } catch {\n // stdout may already be closed during exit\n }\n restoreTerminalForeground();\n releaseAllThreadLocks();\n try {\n const threadId = getResumeThreadId?.();\n if (threadId) {\n process.stdout.write(`\\n${formatResumeHint(threadId)}\\n`);\n }\n } catch {\n // session state or stdout may already be closed during exit\n }\n});\n\n// Start durable diagnostics shutdown before synchronous TUI teardown so a stalled\n// terminal cleanup cannot prevent the final profile capture. The exit handler still\n// provides a failsafe terminal reset if teardown throws.\nconst handleTermSignal = () => {\n void asyncCleanup();\n try {\n tui?.stop();\n } catch {\n // ignored — exit handler has failsafe reset\n }\n void shutdownAndExit(0);\n};\nprocess.on('SIGINT', handleTermSignal);\nprocess.on('SIGTERM', handleTermSignal);\nprocess.on('SIGHUP', handleTermSignal);\n\nfunction hasEconnrefused(err: unknown, depth = 0): boolean {\n if (!err || depth > 5) return false;\n const e = err as any;\n if (e.code === 'ECONNREFUSED') return true;\n if (e.cause) return hasEconnrefused(e.cause, depth + 1);\n // AggregateError has .errors array\n if (Array.isArray(e.errors)) return e.errors.some((inner: unknown) => hasEconnrefused(inner, depth + 1));\n return false;\n}\n\nfunction pluginMain(args: string[]): void {\n if (args[0] !== 'scaffold') {\n process.stderr.write('Usage: mastracode plugin scaffold <dir> [--id acme.foo] [--name \"Foo Tools\"]\\n');\n process.exit(1);\n }\n\n const dir = args[1];\n if (!dir) {\n process.stderr.write('Usage: mastracode plugin scaffold <dir> [--id acme.foo] [--name \"Foo Tools\"]\\n');\n process.exit(1);\n }\n\n const id = readFlag(args, '--id');\n const name = readFlag(args, '--name');\n const targetDir = scaffoldPlugin(dir, { ...(id ? { id } : {}), ...(name ? { name } : {}) });\n process.stdout.write(`${formatScaffoldSuccess(targetDir)}\\n`);\n}\n\nfunction readFlag(args: string[], flag: string): string | undefined {\n const index = args.indexOf(flag);\n if (index === -1) return undefined;\n const value = args[index + 1];\n if (!value || value.startsWith('--')) {\n throw new Error(`Missing value for ${flag}`);\n }\n return value;\n}\n\nconst handleFatalError = createOneShotFatalErrorHandler((error: unknown): void => {\n // Always write to real stderr, even if console.error was overridden\n const write = (msg: string) => {\n try {\n process.stderr.write(msg + '\\n');\n } catch {}\n };\n\n if (hasEconnrefused(error)) {\n const settings = loadSettings();\n const connStr = settings.storage?.pg?.connectionString;\n const target = connStr ?? 'localhost:5432';\n write(\n `\\nFailed to connect to PostgreSQL at ${target}.` +\n `\\nMake sure the database is running and accessible.` +\n `\\n\\nTo switch back to LibSQL:` +\n `\\n Set MASTRA_STORAGE_BACKEND=libsql or change the backend in /settings\\n`,\n );\n void asyncCleanup();\n try {\n tui?.stop();\n } catch {}\n void shutdownAndExit(1);\n return;\n }\n\n const msg = `Fatal error: ${error instanceof Error ? error.message : String(error)}`;\n write(msg);\n // Write crash log to file so it persists even if terminal closes\n try {\n const crashLog = `[${new Date().toISOString()}] ${msg}\\n${error instanceof Error && error.stack ? error.stack + '\\n' : ''}`;\n truncateLogFile(CRASH_LOG_PATH);\n fs.appendFileSync(CRASH_LOG_PATH, crashLog);\n truncateLogFile(CRASH_LOG_PATH);\n } catch {}\n if (error instanceof Error && error.stack) {\n write(error.stack);\n }\n void asyncCleanup();\n try {\n tui?.stop();\n } catch {}\n void shutdownAndExit(1);\n});\n\nasync function main() {\n if (process.argv[2] === 'plugin') {\n return pluginMain(process.argv.slice(3));\n }\n\n // Storage maintenance without the TUI, so a database can still be pruned and\n // compacted when the interactive session won't start. Checked before the\n // headless branch below, which would otherwise claim `prune --help`.\n if (process.argv[2] === 'prune') {\n const { runPruneCommand } = await import('@mastra/code-sdk/utils/prune-cli');\n return process.exit(await runPruneCommand(process.argv.slice(3)));\n }\n\n const initialPrompt = takeInitialPrompt(process.argv, process.env);\n if (initialPrompt.error) {\n process.stderr.write(`${initialPrompt.error}\\n`);\n process.exit(1);\n }\n if (initialPrompt.flag) process.argv = initialPrompt.argv;\n // The flag only means something to the interactive TUI. Paths that can't run\n // it reject the flag instead of dropping the prompt; an env var prompt is\n // just ignored there.\n const rejectInitialPromptFlag = (reason: string) => {\n if (!initialPrompt.flag) return;\n process.stderr.write(`${initialPrompt.flag} starts the interactive TUI; ${reason}\\n`);\n process.exit(1);\n };\n\n let resumeThreadId: string | undefined;\n try {\n resumeThreadId = parseResumeThreadId(process.argv.slice(2));\n } catch (error) {\n process.stderr.write(`${error instanceof Error ? error.message : String(error)}\\n`);\n process.exitCode = 1;\n return;\n }\n\n const headless = hasHeadlessFlag(process.argv);\n if (shouldRunHeadless(process.argv, resumeThreadId, headless)) {\n if (headless) rejectInitialPromptFlag('use --prompt for headless runs');\n return runMCCli(undefined, { coAuthor: TUI_CO_AUTHOR });\n }\n\n if (process.argv.includes('--acp')) {\n rejectInitialPromptFlag('it cannot be combined with --acp');\n const { acpMain } = await import('@mastra/code-sdk/acp/index');\n return acpMain({\n dangerousAutoApprove: process.argv.includes('--dangerous-auto-approve'),\n coAuthor: TUI_CO_AUTHOR,\n });\n }\n\n if (shouldRejectResumeWithoutTTY(resumeThreadId, Boolean(process.stdin.isTTY))) {\n process.stderr.write('mastracode resume requires an interactive terminal.\\n');\n process.exitCode = 1;\n return;\n }\n\n // When stdin is piped (e.g. `cat foo | mastracode`), drain the pipe fully\n // before starting the TUI. The drain blocks until the sender process exits\n // and closes its stdout, so we never see partial output.\n let pipedInput: string | null = null;\n if (!process.stdin.isTTY) {\n process.stderr.write('Reading piped input...\\n');\n pipedInput = await drainPipedStdin();\n\n // Always reopen a real TTY — even if the pipe was empty, the original\n // stdin is consumed/closed and the TUI needs a live TTY for keyboard input.\n const reopenedStdin = reopenStdinFromTTY();\n if (!reopenedStdin) {\n rejectInitialPromptFlag('no TTY is available, so use --prompt for headless runs');\n process.stderr.write('No TTY available — falling back to headless mode.\\n');\n return runMCCli(pipedInput, { coAuthor: TUI_CO_AUTHOR });\n }\n }\n\n const conflict = pipedInputConflict(initialPrompt, pipedInput);\n if (conflict) {\n process.stderr.write(`${conflict}\\n`);\n process.exit(1);\n }\n\n return tuiMain(initialMessageOptions(initialPrompt, pipedInput), resumeThreadId);\n}\n\nmain().catch(error => {\n handleFatalError(error);\n});\n"],"mappings":";;;;;;;;;;;;;;AAAA,MAAa,sBAAsB;AACnC,MAAa,qBAAqB;AAElC,MAAa,kBAAkB;;;;;;;;;;AA0B/B,SAAgB,kBAAkB,MAAgB,KAA2C;CAC3F,MAAM,UAAU,IAAI;CACpB,OAAO,IAAI;CAEX,MAAM,OAAiB,CAAC;CACxB,MAAM,wBAAQ,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,wBAAwB,wDAAwD;GAChF,QAAQ,OAAO,MAAM,qDAAqD;GAC1E,OAAO,SAAS,YAAY,EAAE,UAAU,cAAc,CAAC;EACzD;CACF;CAEA,MAAM,WAAW,mBAAmB,eAAe,UAAU;CAC7D,IAAI,UAAU;EACZ,QAAQ,OAAO,MAAM,GAAG,SAAS,GAAG;EACpC,QAAQ,KAAK,CAAC;CAChB;CAEA,OAAO,QAAQ,sBAAsB,eAAe,UAAU,GAAG,cAAc;AACjF;AAEA,KAAK,CAAC,CAAC,OAAM,UAAS;CACpB,iBAAiB,KAAK;AACxB,CAAC"}
1
+ {"version":3,"file":"cli.js","names":[],"sources":["../src/initial-prompt.ts","../src/process-memory-diagnostics-lifecycle.ts","../src/resume-command.ts","../src/subagent-settings.ts","../src/version.ts","../src/main.ts"],"sourcesContent":["export const INITIAL_PROMPT_FLAG = '--tui-initial-prompt' as const;\nexport const INITIAL_PROMPT_ENV = 'MASTRACODE_TUI_INITIAL_PROMPT';\n\nexport const TUI_PROMPT_FLAG = '--tui-prompt' as const;\n\nexport type InitialPromptArgs = {\n /** argv with the flag and its value removed, so headless detection never mistakes the value for a prompt. */\n argv: string[];\n prompt?: string;\n /** Set when a flag was passed without a value, or both flags were passed. */\n error?: string;\n /** The flag the prompt came from; undefined when it came from the environment. */\n flag?: typeof INITIAL_PROMPT_FLAG | typeof TUI_PROMPT_FLAG;\n /**\n * `--tui-prompt` sends even when startup resumes an existing conversation;\n * `--tui-initial-prompt` and the environment variable only start a new one.\n */\n sendOnResume: boolean;\n};\n\n/**\n * Takes the interactive startup prompt from `--tui-initial-prompt <text>` or\n * `--tui-prompt <text>` (also `--flag=<text>`), falling back to\n * `MASTRACODE_TUI_INITIAL_PROMPT`.\n *\n * The environment variable is always removed from `env`: everything this\n * process spawns inherits its environment, and a nested Mastra Code (or any\n * shell the agent starts) must not send the same prompt again.\n */\nexport function takeInitialPrompt(argv: string[], env: NodeJS.ProcessEnv): InitialPromptArgs {\n const fromEnv = env[INITIAL_PROMPT_ENV];\n delete env[INITIAL_PROMPT_ENV];\n\n const rest: string[] = [];\n const found = new Map<NonNullable<InitialPromptArgs['flag']>, string>();\n let error: string | undefined;\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i]!;\n const flag = [INITIAL_PROMPT_FLAG, TUI_PROMPT_FLAG].find(f => arg === f || arg.startsWith(`${f}=`));\n if (!flag) {\n rest.push(arg);\n } else if (arg !== flag) {\n found.set(flag, arg.slice(flag.length + 1));\n } else if (argv[i + 1] === undefined) {\n error = `${flag} needs a value`;\n } else {\n found.set(flag, argv[++i]!);\n }\n }\n if (found.size > 1) error = `Use either ${INITIAL_PROMPT_FLAG} or ${TUI_PROMPT_FLAG}, not both`;\n\n const [flag, flagValue] = [...found][0] ?? [];\n const prompt = (flag ? flagValue : fromEnv)?.trim() || undefined;\n return { argv: rest, prompt, error, flag, sendOnResume: flag === TUI_PROMPT_FLAG };\n}\n\n/** The first message the TUI sends: the initial prompt, followed by any piped stdin. */\nexport function composeInitialMessage(prompt: string | undefined, pipedInput: string | null | undefined) {\n const piped = pipedInput ? `The following was piped via stdin:\\n\\n${pipedInput}` : undefined;\n if (prompt && piped) return `${prompt}\\n\\n${piped}`;\n return prompt ?? piped;\n}\n\n/**\n * Why a startup prompt can't be combined with piped stdin, if it can't.\n *\n * The first message is submitted like typed input, so a prompt starting with\n * `/` or `!` is dispatched as a command. Folding piped text into it would make\n * that text part of the command — skill arguments, or a shell script for `!`.\n */\nexport function pipedInputConflict(\n args: Pick<InitialPromptArgs, 'prompt' | 'flag'>,\n pipedInput: string | null | undefined,\n): string | undefined {\n if (!args.prompt || !pipedInput) return undefined;\n if (!args.prompt.startsWith('/') && !args.prompt.startsWith('!')) return undefined;\n const source = args.flag ?? INITIAL_PROMPT_ENV;\n return `${source} can't be combined with piped stdin when it is a slash command or starts with !`;\n}\n\n/** The TUI options for a startup prompt and/or piped stdin. */\nexport function initialMessageOptions(\n args: Pick<InitialPromptArgs, 'prompt' | 'sendOnResume'>,\n pipedInput?: string | null,\n): { initialMessage?: string; resumeSkipNotice?: string } {\n const initialMessage = composeInitialMessage(args.prompt, pipedInput);\n if (!initialMessage) return {};\n // Piped stdin on its own is always sent, as before.\n if (!args.prompt || args.sendOnResume) return { initialMessage };\n const skipped = pipedInput ? 'the initial prompt and piped input were' : 'the initial prompt was';\n return {\n initialMessage,\n resumeSkipNotice: `Resumed the existing conversation for this directory, so ${skipped} not sent. Use ${TUI_PROMPT_FLAG} to send ${pipedInput ? 'them' : 'it'} anyway.`,\n };\n}\n","import {\n createProcessMemoryDiagnosticsFromEnvironment,\n startConfiguredProcessMemoryDiagnostics,\n type ProcessMemoryDiagnostics,\n type ProcessMemoryDiagnosticsEnvironment,\n type ProcessMemoryDiagnosticsSetup,\n} from '@mastra/code-sdk/process-memory-diagnostics';\n\nexport async function startTuiProcessMemoryDiagnostics(\n env: ProcessMemoryDiagnosticsEnvironment,\n warn: (message: string) => void,\n createSetup: (\n env: ProcessMemoryDiagnosticsEnvironment,\n ) => ProcessMemoryDiagnosticsSetup = createProcessMemoryDiagnosticsFromEnvironment,\n): Promise<ProcessMemoryDiagnostics> {\n return startConfiguredProcessMemoryDiagnostics(createSetup(env), warn);\n}\n\nexport function createOneShotFatalErrorHandler(handle: (error: unknown) => void): (error: unknown) => void {\n let handlingFatalError = false;\n return error => {\n if (handlingFatalError) return;\n handlingFatalError = true;\n handle(error);\n };\n}\n\nexport function createShutdownCoordinator(\n cleanup: () => Promise<void>,\n exit: (exitCode: number) => never,\n timeoutMs = 5_000,\n): (exitCode: number) => Promise<void> {\n let shutdownPromise: Promise<void> | null = null;\n return exitCode => {\n shutdownPromise ??= (async () => {\n let timeout: ReturnType<typeof setTimeout> | undefined;\n await Promise.race([\n cleanup().catch(() => undefined),\n new Promise<void>(resolve => {\n timeout = setTimeout(resolve, timeoutMs);\n }),\n ]);\n if (timeout) clearTimeout(timeout);\n exit(exitCode);\n })();\n return shutdownPromise;\n };\n}\n","export function parseResumeThreadId(args: string[]): string | undefined {\n if (args[0] !== 'resume') return undefined;\n\n const threadId = args[1]?.trim();\n if (!threadId || args.length !== 2) {\n throw new Error('Usage: mastracode resume <thread-id>');\n }\n return threadId;\n}\n\nexport function shouldRunHeadless(\n argv: string[],\n resumeThreadId: string | undefined,\n hasHeadlessFlag: boolean,\n): boolean {\n return !resumeThreadId && (hasHeadlessFlag || argv.includes('--help') || argv.includes('-h'));\n}\n\nexport function shouldRejectResumeWithoutTTY(resumeThreadId: string | undefined, isTTY: boolean): boolean {\n return Boolean(resumeThreadId) && !isTTY;\n}\n\nexport function formatResumeHint(threadId: string): string {\n const hasControlCharacters = [...threadId].some(character => {\n const codePoint = character.codePointAt(0)!;\n return codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f);\n });\n const argument = /^[a-zA-Z0-9_-]+$/.test(threadId)\n ? threadId\n : hasControlCharacters\n ? `$'${[...threadId]\n .map(character => {\n const codePoint = character.codePointAt(0)!;\n if (character === \"'\") return \"\\\\'\";\n if (character === '\\\\') return '\\\\\\\\';\n if (codePoint <= 0x1f || codePoint === 0x7f) return `\\\\x${codePoint.toString(16).padStart(2, '0')}`;\n if (codePoint >= 0x80 && codePoint <= 0x9f) {\n return `\\\\u${codePoint.toString(16).padStart(4, '0')}`;\n }\n return character;\n })\n .join('')}'`\n : `'${threadId.replaceAll(\"'\", \"'\\\\''\")}'`;\n return `To continue this session, run mastracode resume ${argument}`;\n}\n","export function resolveTuiSubagents(enabled: boolean): undefined | [] {\n return enabled ? undefined : [];\n}\n","import { readFileSync } from 'node:fs';\n\ndeclare const MASTRACODE_VERSION: string | undefined;\n\nexport function getCurrentVersion(): string {\n if (typeof MASTRACODE_VERSION !== 'undefined') {\n return MASTRACODE_VERSION;\n }\n\n const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as { version: string };\n return pkg.version;\n}\n","#!/usr/bin/env node\n/**\n * Main entry point for Mastra Code TUI.\n */\nimport fs from 'node:fs';\n\nimport { createMastraCode } from '@mastra/code-sdk';\nimport { createMastraCodeAnalytics } from '@mastra/code-sdk/analytics';\nimport { isStreamDestroyedError } from '@mastra/code-sdk/error-classification';\nimport { hasHeadlessFlag, runMCCli } from '@mastra/code-sdk/headless/index';\nimport {\n createBrowserFromSettings,\n loadSettings,\n resolveStagehandModel,\n toActiveBrowserSettings,\n} from '@mastra/code-sdk/onboarding/settings';\nimport { formatScaffoldSuccess, scaffoldPlugin } from '@mastra/code-sdk/plugins/scaffold';\nimport {\n stopProcessMemoryDiagnosticsWithTimeout,\n type ProcessMemoryDiagnostics,\n} from '@mastra/code-sdk/process-memory-diagnostics';\nimport { setupDebugLogging, truncateLogFile } from '@mastra/code-sdk/utils/debug-log';\nimport { drainPipedStdin, reopenStdinFromTTY } from '@mastra/code-sdk/utils/stdin-pipe';\nimport { releaseAllThreadLocks } from '@mastra/code-sdk/utils/thread-lock';\nimport { TUI_CO_AUTHOR } from './commit-attribution.js';\nimport { initialMessageOptions, pipedInputConflict, takeInitialPrompt } from './initial-prompt.js';\nimport {\n createOneShotFatalErrorHandler,\n createShutdownCoordinator,\n startTuiProcessMemoryDiagnostics,\n} from './process-memory-diagnostics-lifecycle.js';\nimport {\n formatResumeHint,\n parseResumeThreadId,\n shouldRejectResumeWithoutTTY,\n shouldRunHeadless,\n} from './resume-command.js';\nimport { resolveTuiSubagents } from './subagent-settings.js';\nimport { detectTerminalTheme } from './tui/detect-theme.js';\nimport { MastraTUI } from './tui/index.js';\nimport { applyThemeMode, restoreTerminalForeground } from './tui/theme.js';\nimport { 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 analytics: ReturnType<typeof createMastraCodeAnalytics> | undefined;\nlet tui: MastraTUI | undefined;\nlet processMemoryDiagnostics: ProcessMemoryDiagnostics | undefined;\nlet storageClosed = false;\nlet cleanupPromise: Promise<void> | null = null;\nlet getResumeThreadId: (() => string | null) | undefined;\n\nconst CRASH_LOG_PATH = '/tmp/mastra-crash.log';\n\nfunction isTruthyEnv(name: string): boolean {\n return ['1', 'true', 'yes', 'on'].includes(process.env[name]?.trim().toLowerCase() ?? '');\n}\n\nfunction resolveInitialStateFromEnv() {\n const currentModelId = process.env.MASTRACODE_MODEL_ID?.trim();\n const initialState: Record<string, unknown> = {};\n if (currentModelId) initialState.currentModelId = currentModelId;\n if (isTruthyEnv('MASTRACODE_YOLO')) initialState.yolo = true;\n return Object.keys(initialState).length > 0 ? initialState : undefined;\n}\n\n// Global safety nets — catch any uncaught errors from storage init, etc.\nprocess.on('uncaughtException', error => {\n // ERR_STREAM_DESTROYED is non-fatal — happens routinely when streams close\n // during shutdown, cancelled LLM requests, or LSP/subprocess exits (#13548, #13549)\n if (isStreamDestroyedError(error)) return;\n handleFatalError(error);\n});\nprocess.on('unhandledRejection', reason => {\n if (isStreamDestroyedError(reason)) return;\n handleFatalError(reason instanceof Error ? reason : new Error(String(reason)));\n});\n\nasync function tuiMain(startupMessage: ReturnType<typeof initialMessageOptions> = {}, resumeThreadId?: string) {\n const settings = loadSettings();\n processMemoryDiagnostics = await startTuiProcessMemoryDiagnostics(process.env, warning => {\n console.info(`⚠ ${warning}`);\n });\n let browserPromise: ReturnType<typeof createBrowserFromSettings> | undefined;\n const loadBrowser = (chatModelId: string | undefined) => {\n browserPromise ??= createBrowserFromSettings(settings.browser, { chatModelId });\n return browserPromise;\n };\n\n const initialState = resolveInitialStateFromEnv();\n const result = await createMastraCode({\n createInitialThread: false,\n coAuthor: TUI_CO_AUTHOR,\n unixSocketPubSub: !isTruthyEnv('MASTRACODE_DISABLE_UNIX_SOCKET_PUBSUB'),\n disableMcp: isTruthyEnv('MASTRACODE_DISABLE_MCP'),\n disableHooks: isTruthyEnv('MASTRACODE_DISABLE_HOOKS'),\n subagents: resolveTuiSubagents(settings.preferences.subagentsEnabled),\n ...(isTruthyEnv('MASTRACODE_DISABLE_MEMORY') ? { memory: false as never } : {}),\n ...(initialState ? { initialState: initialState as never } : {}),\n });\n controller = result.controller;\n mcpManager = result.mcpManager;\n hookManager = result.hookManager;\n authStorage = result.authStorage;\n signalsPubSub = result.signalsPubSub;\n storageMaintenance = result.storageMaintenance;\n stopPluginSignalProviders = result.stopPluginSignalProviders;\n threadScheduler = result.threadScheduler;\n stopNotificationDispatch = result.stopNotificationDispatch;\n\n if (result.storageWarning) {\n console.info(`⚠ ${result.storageWarning}`);\n }\n if (result.observabilityWarning) {\n console.info(`⚠ ${result.observabilityWarning}`);\n }\n\n // MCP connection is deferred to TUI.init() (after ui.start()) so that\n // status messages use showInfo() instead of console.info(), which would\n // corrupt the terminal. Headless mode still inits from headless/cli.ts.\n\n setupDebugLogging();\n\n // Detect and apply terminal theme\n // MASTRA_THEME env var is the highest-priority override\n const envTheme = process.env.MASTRA_THEME?.toLowerCase();\n let themeMode: 'dark' | 'light';\n let detectedBgHex: string | undefined;\n if (envTheme === 'dark' || envTheme === 'light') {\n themeMode = envTheme;\n } else {\n const settings = loadSettings();\n const themePref = settings.preferences.theme;\n if (themePref === 'dark' || themePref === 'light') {\n themeMode = themePref;\n } else {\n const detection = await detectTerminalTheme();\n themeMode = detection.mode;\n detectedBgHex = detection.detectedBgHex;\n }\n }\n applyThemeMode(themeMode, detectedBgHex);\n\n // createMastraCode() brought up shared resources and minted the single\n // session that all work runs through. The AgentController owns no session of its own.\n const session = result.session;\n getResumeThreadId = () => (tui ? tui.getResumeThreadId() : session.thread.getId());\n\n analytics = createMastraCodeAnalytics({ version: getCurrentVersion() });\n analytics.capture('mastracode_session_started', {\n mode: session.mode.get(),\n resourceId: session.identity.getResourceId(),\n hasAuthStorage: Boolean(authStorage),\n hasMcp: Boolean(mcpManager),\n theme: themeMode,\n });\n\n tui = new MastraTUI({\n controller: controller,\n session,\n hookManager,\n analytics,\n authStorage,\n mcpManager,\n pluginManager: result.pluginManager,\n storageMaintenance: result.storageMaintenance,\n processMemoryDiagnostics,\n knowledgeInspector: result.knowledgeInspector,\n threadScheduler: result.threadScheduler,\n appName: 'Mastra Code',\n version: getCurrentVersion(),\n inlineQuestions: true,\n ...(resumeThreadId ? { resumeThreadId } : {}),\n githubSignals: result.githubSignals,\n backgroundToolsEnabled: result.backgroundToolsEnabled,\n backgroundCompletionEvents: result.backgroundCompletionEvents,\n exit: exitCode => void shutdownAndExit(exitCode),\n ...startupMessage,\n });\n tui.run().catch(error => {\n handleFatalError(error);\n });\n\n if (settings.browser.enabled) {\n // Captured once: the Stagehand instance is fixed at launch and shared by every thread.\n const chatModelId = session.model.get();\n void loadBrowser(chatModelId)\n .then(browser => {\n if (!browser) return;\n controller.setBrowser(browser);\n void session.state\n .set({\n activeBrowserSettings: toActiveBrowserSettings(settings.browser),\n activeBrowserModel: resolveStagehandModel(settings.browser, { chatModelId }),\n } as any)\n .catch(() => {});\n })\n .catch(() => {});\n }\n}\n\nconst asyncCleanup = (): Promise<void> => {\n cleanupPromise ??= (async () => {\n releaseAllThreadLocks();\n // Stop plugin-contributed signal providers (and the plugin reload listener)\n // before quiescing workers: a provider that keeps polling past this point\n // could dispatch into a controller that is shutting down.\n try {\n stopPluginSignalProviders?.();\n } catch {\n // Best-effort — the process is exiting.\n }\n const diagnosticsShutdown = processMemoryDiagnostics\n ? stopProcessMemoryDiagnosticsWithTimeout(processMemoryDiagnostics, message => console.warn(message))\n : undefined;\n // Schedules live only in this process; stop their timers so none fires mid-shutdown.\n threadScheduler?.stop();\n // Release this process's notification dispatch leases before the pubsub that holds them closes.\n await stopNotificationDispatch?.().catch(() => {});\n await Promise.allSettled([mcpManager?.disconnect(), controller?.stopIntervals()]);\n // Mastra owns the workspaces and must destroy them to stop retained language\n // servers before storage is closed.\n await Promise.allSettled([controller?.getMastra()?.shutdown(), analytics?.shutdown()]);\n // The signals pubsub is Mastra's event bus: in-flight runs and background\n // tasks drain through it during shutdown, so close it only afterwards. Call\n // close() on the object; a detached method loses `this` and rejects silently.\n const pubsubToClose = signalsPubSub as { close?: () => Promise<void> | void } | undefined;\n await Promise.allSettled([pubsubToClose?.close?.()]);\n // Checkpoint WAL and close the local storage connection after all producers\n // and timers are quiesced. Idempotent — repeated signals (SIGINT then SIGHUP)\n // close only once. LibSQLStore.close()/LibSQLVector.close() truncate the WAL\n // and switch back to DELETE journal mode for a clean shutdown.\n if (!storageClosed) {\n storageClosed = true;\n await storageMaintenance?.closeStorage?.().catch(() => {\n // Swallow — best-effort cleanup during shutdown. The process is exiting.\n });\n }\n await diagnosticsShutdown;\n })();\n return cleanupPromise;\n};\n\nconst shutdownAndExit = createShutdownCoordinator(asyncCleanup, exitCode => process.exit(exitCode));\n\nprocess.on('beforeExit', () => {\n void asyncCleanup();\n});\nprocess.on('exit', () => {\n // Ensure terminal protocols (kitty keyboard, modifyOtherKeys, bracketed paste,\n // raw mode) are disabled on ANY exit path. Without this, killing the process\n // via SIGINT/SIGTERM leaves the terminal in a corrupted state where keypresses\n // produce escape sequences like \"5;99~\" instead of normal characters.\n try {\n tui?.stop();\n } catch {\n // Failsafe: even if MastraTUI.stop() throws, write raw terminal reset\n // sequences to disable Kitty keyboard protocol, bracketed paste, and\n // modifyOtherKeys. These are the exact sequences pi-tui's terminal.stop()\n // would write.\n }\n // Belt-and-suspenders: always write terminal reset sequences directly,\n // regardless of whether tui.stop() succeeded. Writing them twice is harmless\n // but missing them leaves the terminal in a corrupted state.\n try {\n process.stdout.write(\n '\\x1b[?2004l' + // disable bracketed paste\n '\\x1b[<u' + // pop kitty keyboard protocol\n '\\x1b[>4;0m' + // disable modifyOtherKeys\n '\\x1b[?25h', // show cursor\n );\n if (process.stdin.setRawMode) {\n process.stdin.setRawMode(false);\n }\n } catch {\n // stdout may already be closed during exit\n }\n restoreTerminalForeground();\n releaseAllThreadLocks();\n try {\n const threadId = getResumeThreadId?.();\n if (threadId) {\n process.stdout.write(`\\n${formatResumeHint(threadId)}\\n`);\n }\n } catch {\n // session state or stdout may already be closed during exit\n }\n});\n\n// Start durable diagnostics shutdown before synchronous TUI teardown so a stalled\n// terminal cleanup cannot prevent the final profile capture. The exit handler still\n// provides a failsafe terminal reset if teardown throws.\nconst handleTermSignal = () => {\n void asyncCleanup();\n try {\n tui?.stop();\n } catch {\n // ignored — exit handler has failsafe reset\n }\n void shutdownAndExit(0);\n};\nprocess.on('SIGINT', handleTermSignal);\nprocess.on('SIGTERM', handleTermSignal);\nprocess.on('SIGHUP', handleTermSignal);\n\nfunction hasEconnrefused(err: unknown, depth = 0): boolean {\n if (!err || depth > 5) return false;\n const e = err as any;\n if (e.code === 'ECONNREFUSED') return true;\n if (e.cause) return hasEconnrefused(e.cause, depth + 1);\n // AggregateError has .errors array\n if (Array.isArray(e.errors)) return e.errors.some((inner: unknown) => hasEconnrefused(inner, depth + 1));\n return false;\n}\n\nfunction pluginMain(args: string[]): void {\n if (args[0] !== 'scaffold') {\n process.stderr.write('Usage: mastracode plugin scaffold <dir> [--id acme.foo] [--name \"Foo Tools\"]\\n');\n process.exit(1);\n }\n\n const dir = args[1];\n if (!dir) {\n process.stderr.write('Usage: mastracode plugin scaffold <dir> [--id acme.foo] [--name \"Foo Tools\"]\\n');\n process.exit(1);\n }\n\n const id = readFlag(args, '--id');\n const name = readFlag(args, '--name');\n const targetDir = scaffoldPlugin(dir, { ...(id ? { id } : {}), ...(name ? { name } : {}) });\n process.stdout.write(`${formatScaffoldSuccess(targetDir)}\\n`);\n}\n\nfunction readFlag(args: string[], flag: string): string | undefined {\n const index = args.indexOf(flag);\n if (index === -1) return undefined;\n const value = args[index + 1];\n if (!value || value.startsWith('--')) {\n throw new Error(`Missing value for ${flag}`);\n }\n return value;\n}\n\nconst handleFatalError = createOneShotFatalErrorHandler((error: unknown): void => {\n // Always write to real stderr, even if console.error was overridden\n const write = (msg: string) => {\n try {\n process.stderr.write(msg + '\\n');\n } catch {}\n };\n\n if (hasEconnrefused(error)) {\n const settings = loadSettings();\n const connStr = settings.storage?.pg?.connectionString;\n const target = connStr ?? 'localhost:5432';\n write(\n `\\nFailed to connect to PostgreSQL at ${target}.` +\n `\\nMake sure the database is running and accessible.` +\n `\\n\\nTo switch back to LibSQL:` +\n `\\n Set MASTRA_STORAGE_BACKEND=libsql or change the backend in /settings\\n`,\n );\n void asyncCleanup();\n try {\n tui?.stop();\n } catch {}\n void shutdownAndExit(1);\n return;\n }\n\n const msg = `Fatal error: ${error instanceof Error ? error.message : String(error)}`;\n write(msg);\n // Write crash log to file so it persists even if terminal closes\n try {\n const crashLog = `[${new Date().toISOString()}] ${msg}\\n${error instanceof Error && error.stack ? error.stack + '\\n' : ''}`;\n truncateLogFile(CRASH_LOG_PATH);\n fs.appendFileSync(CRASH_LOG_PATH, crashLog);\n truncateLogFile(CRASH_LOG_PATH);\n } catch {}\n if (error instanceof Error && error.stack) {\n write(error.stack);\n }\n void asyncCleanup();\n try {\n tui?.stop();\n } catch {}\n void shutdownAndExit(1);\n});\n\nasync function main() {\n if (process.argv[2] === 'plugin') {\n return pluginMain(process.argv.slice(3));\n }\n\n // Storage maintenance without the TUI, so a database can still be pruned and\n // compacted when the interactive session won't start. Checked before the\n // headless branch below, which would otherwise claim `prune --help`.\n if (process.argv[2] === 'prune') {\n const { runPruneCommand } = await import('@mastra/code-sdk/utils/prune-cli');\n return process.exit(await runPruneCommand(process.argv.slice(3)));\n }\n\n const loginIndex = process.argv.findIndex(\n (arg, index) => index >= 2 && arg !== '--acp' && arg !== '--dangerous-auto-approve',\n );\n if (process.argv[loginIndex] === 'login') {\n const { runLoginCommand } = await import('./login-command.js');\n const code = await runLoginCommand({ args: process.argv.slice(loginIndex + 1) });\n await new Promise(resolve => process.stdout.write('', resolve));\n return process.exit(code);\n }\n\n const initialPrompt = takeInitialPrompt(process.argv, process.env);\n if (initialPrompt.error) {\n process.stderr.write(`${initialPrompt.error}\\n`);\n process.exit(1);\n }\n if (initialPrompt.flag) process.argv = initialPrompt.argv;\n // The flag only means something to the interactive TUI. Paths that can't run\n // it reject the flag instead of dropping the prompt; an env var prompt is\n // just ignored there.\n const rejectInitialPromptFlag = (reason: string) => {\n if (!initialPrompt.flag) return;\n process.stderr.write(`${initialPrompt.flag} starts the interactive TUI; ${reason}\\n`);\n process.exit(1);\n };\n\n let resumeThreadId: string | undefined;\n try {\n resumeThreadId = parseResumeThreadId(process.argv.slice(2));\n } catch (error) {\n process.stderr.write(`${error instanceof Error ? error.message : String(error)}\\n`);\n process.exitCode = 1;\n return;\n }\n\n const headless = hasHeadlessFlag(process.argv);\n if (shouldRunHeadless(process.argv, resumeThreadId, headless)) {\n if (headless) rejectInitialPromptFlag('use --prompt for headless runs');\n return runMCCli(undefined, { coAuthor: TUI_CO_AUTHOR });\n }\n\n if (process.argv.includes('--acp')) {\n rejectInitialPromptFlag('it cannot be combined with --acp');\n const { acpMain } = await import('@mastra/code-sdk/acp/index');\n return acpMain({\n dangerousAutoApprove: process.argv.includes('--dangerous-auto-approve'),\n coAuthor: TUI_CO_AUTHOR,\n });\n }\n\n if (shouldRejectResumeWithoutTTY(resumeThreadId, Boolean(process.stdin.isTTY))) {\n process.stderr.write('mastracode resume requires an interactive terminal.\\n');\n process.exitCode = 1;\n return;\n }\n\n // When stdin is piped (e.g. `cat foo | mastracode`), drain the pipe fully\n // before starting the TUI. The drain blocks until the sender process exits\n // and closes its stdout, so we never see partial output.\n let pipedInput: string | null = null;\n if (!process.stdin.isTTY) {\n process.stderr.write('Reading piped input...\\n');\n pipedInput = await drainPipedStdin();\n\n // Always reopen a real TTY — even if the pipe was empty, the original\n // stdin is consumed/closed and the TUI needs a live TTY for keyboard input.\n const reopenedStdin = reopenStdinFromTTY();\n if (!reopenedStdin) {\n rejectInitialPromptFlag('no TTY is available, so use --prompt for headless runs');\n process.stderr.write('No TTY available — falling back to headless mode.\\n');\n return runMCCli(pipedInput, { coAuthor: TUI_CO_AUTHOR });\n }\n }\n\n const conflict = pipedInputConflict(initialPrompt, pipedInput);\n if (conflict) {\n process.stderr.write(`${conflict}\\n`);\n process.exit(1);\n }\n\n return tuiMain(initialMessageOptions(initialPrompt, pipedInput), resumeThreadId);\n}\n\nmain().catch(error => {\n handleFatalError(error);\n});\n"],"mappings":";;;;;;;;;;;;;;AAAA,MAAa,sBAAsB;AACnC,MAAa,qBAAqB;AAElC,MAAa,kBAAkB;;;;;;;;;;AA0B/B,SAAgB,kBAAkB,MAAgB,KAA2C;CAC3F,MAAM,UAAU,IAAI;CACpB,OAAO,IAAI;CAEX,MAAM,OAAiB,CAAC;CACxB,MAAM,wBAAQ,IAAI,IAAoD;CACtE,IAAI;CACJ,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;EACpC,MAAM,MAAM,KAAK;EACjB,MAAM,OAAO,CAAC,qBAAqB,eAAe,CAAC,CAAC,MAAK,MAAK,QAAQ,KAAK,IAAI,WAAW,GAAG,EAAE,EAAE,CAAC;EAClG,IAAI,CAAC,MACH,KAAK,KAAK,GAAG;OACR,IAAI,QAAQ,MACjB,MAAM,IAAI,MAAM,IAAI,MAAM,KAAK,SAAS,CAAC,CAAC;OACrC,IAAI,KAAK,IAAI,OAAO,KAAA,GACzB,QAAQ,GAAG,KAAK;OAEhB,MAAM,IAAI,MAAM,KAAK,EAAE,EAAG;CAE9B;CACA,IAAI,MAAM,OAAO,GAAG,QAAQ,cAAc,oBAAoB,MAAM,gBAAgB;CAEpF,MAAM,CAAC,MAAM,aAAa,CAAC,GAAG,KAAK,CAAC,CAA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,GAAG;EACpC,QAAQ,KAAK,CAAC;CAChB;CAEA,OAAO,QAAQ,sBAAsB,eAAe,UAAU,GAAG,cAAc;AACjF;AAEA,KAAK,CAAC,CAAC,OAAM,UAAS;CACpB,iBAAiB,KAAK;AACxB,CAAC"}
@@ -3,7 +3,7 @@ name: mastracode
3
3
  description: Documentation for mastracode. Use when working with mastracode APIs, configuration, or implementation.
4
4
  metadata:
5
5
  package: "mastracode"
6
- version: "0.45.0-alpha.3"
6
+ version: "0.45.0-alpha.4"
7
7
  ---
8
8
 
9
9
  ## When to use
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.45.0-alpha.3",
2
+ "version": "0.45.0-alpha.4",
3
3
  "package": "mastracode",
4
4
  "exports": {},
5
5
  "modules": {}
@@ -25,10 +25,27 @@ A client that accepts command and argument fields can use:
25
25
  }
26
26
  ```
27
27
 
28
- Configure provider authentication in Mastra Code before starting the client, or supply API keys in the server process's environment. ACP sessions don't load project `.env` files into the shared process environment. The server doesn't offer interactive ACP authentication.
29
-
30
28
  After initialization, the client calls `session/new` with an absolute `cwd` and an `mcpServers` array. The response includes the session ID and configuration choices. Send that ID with subsequent prompts and configuration requests.
31
29
 
30
+ ## Authentication
31
+
32
+ `session/new` returns an `auth_required` error when no model provider is configured, so clients can offer the methods from the `initialize` response:
33
+
34
+ | Method ID | Type | Behavior |
35
+ | ------------------ | -------- | ---------------------------------------------------------------------------------------------- |
36
+ | `openai-codex` | Agent | Opens the browser to sign in with a ChatGPT Plus or Pro subscription. |
37
+ | `kimi-for-coding` | Agent | Opens the browser to approve a Kimi For Coding device sign-in. |
38
+ | `xai` | Agent | Opens the browser to approve an xAI device sign-in. |
39
+ | `anthropic` | Terminal | Runs `mastracode login --provider anthropic` to sign in with a Claude Pro or Max subscription. |
40
+ | `github-copilot` | Terminal | Runs `mastracode login --provider github-copilot` to sign in with GitHub Copilot. |
41
+ | `mastracode-login` | Terminal | Runs `mastracode login` to choose any provider or save an API key. |
42
+
43
+ Terminal methods are offered only to clients that advertise terminal authentication.
44
+
45
+ For agent methods, `authenticate` runs the sign-in inside the server process and returns after the credentials are saved. If a provider needs typed input, such as a code to paste, the request fails and asks you to run `mastracode login` in a terminal.
46
+
47
+ API keys in the server process's environment also count as a configured provider. ACP sessions don't load project `.env` files into the shared process environment. New sessions pick up saved credentials without restarting the server. When the default model's provider isn't configured, a new session starts on the default model of a provider that is, such as `anthropic/claude-fable-5` after an Anthropic sign-in.
48
+
32
49
  ## `acpMain(options?)`
33
50
 
34
51
  To start the same server from an SDK entry point:
@@ -0,0 +1,100 @@
1
+ let _mastra_code_sdk_auth_storage = require("@mastra/code-sdk/auth/storage");
2
+ let stream = require("stream");
3
+ let _mastra_code_sdk_utils_open_url = require("@mastra/code-sdk/utils/open-url");
4
+ let util = require("util");
5
+ let _mastra_code_sdk_onboarding_om_settings = require("@mastra/code-sdk/onboarding/om-settings");
6
+ let _mastra_core_llm = require("@mastra/core/llm");
7
+ let readline = require("readline");
8
+ //#region src/login-command.ts
9
+ async function choose(ask, labels, say) {
10
+ labels.forEach((label, index) => say(` ${index + 1}. ${label}`));
11
+ const index = Number((await ask("Choose an option: ")).trim()) - 1;
12
+ return Number.isInteger(index) && index >= 0 && index < labels.length ? index : void 0;
13
+ }
14
+ async function signIn(ask, provider, authStorage, openUrl, say) {
15
+ const modes = provider.authModes ?? [];
16
+ let authMode;
17
+ if (modes.length > 1) {
18
+ const index = await choose(ask, modes.map((mode) => mode.name), say);
19
+ if (index === void 0) throw new Error("No sign-in method selected");
20
+ authMode = modes[index].id;
21
+ }
22
+ await authStorage.login(provider.id, {
23
+ authMode,
24
+ onAuth: ({ url, instructions }) => {
25
+ say(`Open ${url} to sign in`);
26
+ if (instructions) say(instructions);
27
+ openUrl(url);
28
+ },
29
+ onPrompt: ({ message, placeholder }) => ask(`${message}${placeholder ? ` (${placeholder})` : ""} `),
30
+ onProgress: say
31
+ });
32
+ (0, _mastra_code_sdk_onboarding_om_settings.seedProviderOMDefault)(provider.id);
33
+ say(`Signed in to ${provider.name}`);
34
+ }
35
+ async function addApiKey(ask, authStorage, say) {
36
+ const providerId = (await ask("Provider (for example anthropic, openai, google): ")).trim();
37
+ if (!(providerId in _mastra_core_llm.PROVIDER_REGISTRY)) throw new Error(`Unknown provider: ${providerId}`);
38
+ const key = (await ask("API key: ", { secret: true })).trim();
39
+ say("");
40
+ if (!key) throw new Error("No API key entered");
41
+ authStorage.setStoredApiKey(providerId, key);
42
+ say(`Saved the ${providerId} API key`);
43
+ }
44
+ async function runLoginCommand({ args = [], input = process.stdin, output = process.stdout, authStorage = new _mastra_code_sdk_auth_storage.AuthStorage(), openUrl = _mastra_code_sdk_utils_open_url.openUrlInBrowser } = {}) {
45
+ let echo = false;
46
+ const rl = (0, readline.createInterface)({
47
+ input,
48
+ output: new stream.Writable({ write(chunk, encoding, callback) {
49
+ if (echo) output.write(chunk, encoding);
50
+ callback();
51
+ } }),
52
+ prompt: "",
53
+ terminal: Boolean(input.isTTY)
54
+ });
55
+ rl.on("line", () => {
56
+ echo = false;
57
+ });
58
+ const lines = rl[Symbol.asyncIterator]();
59
+ const say = (line) => output.write(`${line}\n`);
60
+ const ask = async (prompt, { secret = false } = {}) => {
61
+ output.write(prompt);
62
+ echo = !secret;
63
+ const line = await lines.next();
64
+ echo = false;
65
+ if (line.done) throw new Error("Input ended before sign-in finished");
66
+ return line.value;
67
+ };
68
+ try {
69
+ const providers = (0, _mastra_code_sdk_auth_storage.getOAuthProviders)();
70
+ const { values } = (0, util.parseArgs)({
71
+ args,
72
+ options: { provider: { type: "string" } }
73
+ });
74
+ if (values.provider !== void 0) {
75
+ const provider = providers.find(({ id }) => id === values.provider);
76
+ if (!provider) {
77
+ const ids = providers.map(({ id }) => id).join(", ");
78
+ throw new Error(`Unknown provider: ${values.provider}. Use one of: ${ids}`);
79
+ }
80
+ await signIn(ask, provider, authStorage, openUrl, say);
81
+ return 0;
82
+ }
83
+ say("Sign in to Mastra Code");
84
+ const index = await choose(ask, [...providers.map((provider) => provider.name), "Add an API key"], say);
85
+ if (index === void 0) throw new Error("No option selected");
86
+ const provider = providers[index];
87
+ if (provider) await signIn(ask, provider, authStorage, openUrl, say);
88
+ else await addApiKey(ask, authStorage, say);
89
+ return 0;
90
+ } catch (error) {
91
+ say(`Sign-in failed: ${error instanceof Error ? error.message : String(error)}`);
92
+ return 1;
93
+ } finally {
94
+ rl.close();
95
+ }
96
+ }
97
+ //#endregion
98
+ exports.runLoginCommand = runLoginCommand;
99
+
100
+ //# sourceMappingURL=login-command-BSpvG0ws.cjs.map