@mastra/code-sdk 0.1.0-alpha.6 → 0.1.0-alpha.8

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.
@@ -46,9 +46,13 @@ export interface StorageSettings {
46
46
  /** PostgreSQL-specific config (used when backend is 'pg'). */
47
47
  pg: PgStorageSettings;
48
48
  }
49
- /** Memory gateway provider key used in AuthStorage. */
50
- export declare const MEMORY_GATEWAY_PROVIDER = "mastra-gateway";
49
+ /** Gateway provider key used in AuthStorage. */
50
+ export declare const MASTRA_GATEWAY_PROVIDER = "mastra-gateway";
51
51
  /** Default gateway URL. */
52
+ export declare const MASTRA_GATEWAY_DEFAULT_URL = "https://gateway-api.mastra.ai";
53
+ /** @deprecated Renamed to {@link MASTRA_GATEWAY_PROVIDER}. */
54
+ export declare const MEMORY_GATEWAY_PROVIDER = "mastra-gateway";
55
+ /** @deprecated Renamed to {@link MASTRA_GATEWAY_DEFAULT_URL}. */
52
56
  export declare const MEMORY_GATEWAY_DEFAULT_URL = "https://gateway-api.mastra.ai";
53
57
  /** Valid persisted thinking level values. */
54
58
  export type ThinkingLevelSetting = 'off' | 'low' | 'medium' | 'high' | 'xhigh';
@@ -1 +1 @@
1
- {"version":3,"file":"settings.d.ts","sourceRoot":"","sources":["../../src/onboarding/settings.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAMxD,yEAAyE;AACzE,MAAM,WAAW,UAAU;IACzB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC/B,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,+DAA+D;AAC/D,MAAM,WAAW,qBAAqB;IACpC,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,EAAE,MAAM,CAAC;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cAAc,EAAE,KAAK,CAAC;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC,GACrD,MAAM,GAAG,IAAI,CAEf;AAqBD,wBAAgB,YAAY,CAAC,QAAQ,EAAE,cAAc,EAAE,QAAQ,GAAE,MAA0B,GAAG,IAAI,CASjG;AAKD;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,WAAW,EAAE,MAAM,GAAG,eAAe,GAAG,SAAS,CAcnF;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,WAAW,EAAE,MAAM,EAAE,QAAQ,EAAE,eAAe,GAAG,IAAI,CAMvF;AAED;;;GAGG;AACH,wBAAgB,4BAA4B,CAC1C,WAAW,EAAE,MAAM,GAAG,SAAS,EAC/B,cAAc,EAAE,eAAe,GAC9B,eAAe,GAAG,SAAS,CAS7B;AAMD;;;;GAIG;AACH,wBAAsB,yBAAyB,CAAC,QAAQ,EAAE,eAAe,GAAG,OAAO,CAAC,aAAa,GAAG,SAAS,CAAC,CAqE7G"}
@@ -4,8 +4,10 @@ import { AuthStorage } from "../auth/storage.js";
4
4
  import { buildCodexStagehandFetch, createCodexMiddleware } from "../providers/openai-codex.js";
5
5
  import { getAppDataDir } from "../utils/project.js";
6
6
  import { DEFAULT_STT_PROVIDER, resolveSTTModel } from "../voice/stt-registry.js";
7
- const MEMORY_GATEWAY_PROVIDER = "mastra-gateway";
8
- const MEMORY_GATEWAY_DEFAULT_URL = "https://gateway-api.mastra.ai";
7
+ const MASTRA_GATEWAY_PROVIDER = "mastra-gateway";
8
+ const MASTRA_GATEWAY_DEFAULT_URL = "https://gateway-api.mastra.ai";
9
+ const MEMORY_GATEWAY_PROVIDER = MASTRA_GATEWAY_PROVIDER;
10
+ const MEMORY_GATEWAY_DEFAULT_URL = MASTRA_GATEWAY_DEFAULT_URL;
9
11
  const OBSERVABILITY_AUTH_PREFIX = "observability:";
10
12
  const STORAGE_DEFAULTS = {
11
13
  backend: "libsql",
@@ -568,6 +570,8 @@ async function createBrowserFromSettings(settings) {
568
570
  throw new Error(`Unsupported browser provider: ${provider}`);
569
571
  }
570
572
  export {
573
+ MASTRA_GATEWAY_DEFAULT_URL,
574
+ MASTRA_GATEWAY_PROVIDER,
571
575
  MEMORY_GATEWAY_DEFAULT_URL,
572
576
  MEMORY_GATEWAY_PROVIDER,
573
577
  OBSERVABILITY_AUTH_PREFIX,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/onboarding/settings.ts"],"sourcesContent":["/**\n * Persistent global settings stored in the app data directory as settings.json.\n * This file persists onboarding state AND user preferences (model choices, yolo, etc.)\n * so they carry across threads and restarts.\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport type { MastraBrowser } from '@mastra/core/browser';\nimport type { LSPConfig } from '@mastra/core/workspace';\nimport { AuthStorage } from '../auth/storage.js';\nimport { buildCodexStagehandFetch, createCodexMiddleware } from '../providers/openai-codex.js';\nimport { getAppDataDir } from '../utils/project.js';\nimport { DEFAULT_STT_PROVIDER, resolveSTTModel } from '../voice/stt-registry.js';\n\n/** A saved custom pack — user-defined model selections for each mode. */\nexport interface CustomPack {\n name: string;\n models: Record<string, string>;\n createdAt: string;\n}\n\n/** A saved custom provider for OpenAI-compatible endpoints. */\nexport interface CustomProviderSetting {\n name: string;\n url: string;\n apiKey?: string;\n models: string[];\n}\n\n/** Storage backend type. */\nexport type StorageBackend = 'libsql' | 'pg';\n\n/** LibSQL-specific storage settings. */\nexport interface LibSQLStorageSettings {\n url?: string;\n authToken?: string;\n}\n\n/** PostgreSQL-specific storage settings. */\nexport interface PgStorageSettings {\n connectionString?: string;\n host?: string;\n port?: number;\n database?: string;\n user?: string;\n password?: string;\n schemaName?: string;\n disableInit?: boolean;\n skipDefaultIndexes?: boolean;\n}\n\n/** Storage configuration persisted in global settings. */\nexport interface StorageSettings {\n /** Which backend to use. Default: 'libsql'. */\n backend: StorageBackend;\n /** LibSQL-specific config (used when backend is 'libsql'). */\n libsql: LibSQLStorageSettings;\n /** PostgreSQL-specific config (used when backend is 'pg'). */\n pg: PgStorageSettings;\n}\n\n/** Memory gateway provider key used in AuthStorage. */\nexport const MEMORY_GATEWAY_PROVIDER = 'mastra-gateway';\n\n/** Default gateway URL. */\nexport const MEMORY_GATEWAY_DEFAULT_URL = 'https://gateway-api.mastra.ai';\n\n/** Valid persisted thinking level values. */\nexport type ThinkingLevelSetting = 'off' | 'low' | 'medium' | 'high' | 'xhigh';\n\n/** Browser provider type. */\nexport type BrowserProvider = 'stagehand' | 'agent-browser';\n\n/** Direct TUI `!` shell passthrough mode. */\nexport type ShellPassthroughSettingsMode = 'default' | 'path' | 'login';\n\n/** Direct TUI `!` shell command language. */\nexport type ShellPassthroughSettingsFamily = 'posix' | 'cmd' | 'powershell';\n\n/** Direct TUI `!` shell passthrough configuration. */\nexport interface ShellPassthroughSettings {\n mode?: ShellPassthroughSettingsMode | string;\n executable?: string;\n family?: ShellPassthroughSettingsFamily | string;\n}\n\n/** STT engine: on-device macOS recognizer or a cloud provider. */\nexport type VoiceEngine = 'macos-native' | 'cloud';\n\n/** Voice (hold-space dictation) configuration persisted in global settings. */\nexport interface VoiceSettings {\n /** Whether hold-space voice input is enabled. */\n enabled: boolean;\n /** Which STT engine to use. Defaults to macOS native on darwin, else cloud. */\n engine: VoiceEngine;\n /** Cloud provider id (matches an STT registry entry). Cloud engine only. */\n provider: string;\n /** Cloud model id; defaults to the provider's first registry model. */\n model?: string;\n}\n\n/** Stagehand environment type. */\nexport type StagehandEnv = 'LOCAL' | 'BROWSERBASE';\n\n/** Stagehand-specific browser settings. */\nexport interface StagehandSettings {\n env: StagehandEnv;\n apiKey?: string;\n projectId?: string;\n /** Whether to preserve the user data directory after the browser closes. */\n preserveUserDataDir?: boolean;\n}\n\n/** AgentBrowser-specific browser settings. */\nexport interface AgentBrowserSettings {\n /** Path to a Playwright storage state file (JSON) containing cookies and localStorage. */\n storageState?: string;\n}\n\n/** Browser configuration persisted in global settings. */\nexport interface BrowserSettings {\n /** Whether browser automation is enabled. */\n enabled: boolean;\n /** Which browser provider to use. */\n provider: BrowserProvider;\n /** Whether to run headless (no visible browser window). */\n headless: boolean;\n /** Browser viewport dimensions. */\n viewport?: { width: number; height: number };\n /** CDP URL for connecting to an existing browser. */\n cdpUrl?: string;\n /** Path to a Chrome/Chromium user data directory (profile). */\n profile?: string;\n /** Path to the browser executable to use. */\n executablePath?: string;\n /** Browser scope — 'shared' (all threads share one browser) or 'thread' (each thread gets its own). */\n scope?: 'shared' | 'thread';\n /** Stagehand-specific settings. */\n stagehand?: StagehandSettings;\n /** AgentBrowser-specific settings. */\n agentBrowser?: AgentBrowserSettings;\n}\n\nexport interface GlobalSettings {\n // Onboarding tracking\n onboarding: {\n completedAt: string | null;\n skippedAt: string | null;\n version: number;\n modePackId: string | null;\n omPackId: string | null;\n quietModePreferenceSelected: boolean;\n };\n // Global model preferences (applied to new threads)\n models: {\n /**\n * Active model pack ID. Built-in packs use their id directly (\"anthropic\",\n * \"openai\"). Custom packs use \"custom:<name>\".\n * When set, models are resolved from the pack at startup so pack updates\n * (e.g. new model versions) apply automatically.\n * Cleared when the user manually overrides via /models (falls back to modeDefaults).\n */\n activeModelPackId: string | null;\n /** Explicit per-mode overrides — used when no activeModelPackId is set. */\n modeDefaults: Record<string, string>;\n /**\n * Active OM pack ID (e.g. \"gemini\", \"anthropic\", \"custom\").\n * When set, the OM model is resolved from the pack at startup so pack\n * updates (e.g. new model versions) apply automatically.\n * Cleared when the user manually overrides via /om (falls back to omModelOverride).\n */\n activeOmPackId: string | null;\n /**\n * Shared OM model override — used for both observer and reflector when a\n * role-specific override is not set. Kept for back-compat with older settings\n * files and set by onboarding when the user picks a custom OM pack.\n */\n omModelOverride: string | null;\n /**\n * Explicit Observer model override — takes precedence over `omModelOverride`\n * when set. Written by `/om` when the observer model is changed independently.\n */\n observerModelOverride: string | null;\n /**\n * Explicit Reflector model override — takes precedence over `omModelOverride`\n * when set. Written by `/om` when the reflector model is changed independently.\n */\n reflectorModelOverride: string | null;\n /** Default OM observation threshold used for new threads unless overridden per-thread. */\n omObservationThreshold: number | null;\n /** Default OM reflection threshold used for new threads unless overridden per-thread. */\n omReflectionThreshold: number | null;\n /**\n * Whether observations and reflections use the terse caveman-style instruction.\n * `null` means inherit the built-in default (currently `false` — caveman is\n * opt-in via `/om` settings). Used as the default for new threads unless\n * overridden per-thread.\n */\n omCavemanObservations: boolean | null;\n /**\n * Whether Observational Memory forwards image/file attachment parts to the\n * Observer LLM. `null` ⇒ inherit built-in default ('auto'). 'auto' checks\n * model capabilities; true/false forces the setting.\n */\n omObserveAttachments: 'auto' | boolean | null;\n /** Per-agent-type subagent model overrides (e.g. { explore: \"openai/gpt-5.1-codex-mini\" }) */\n subagentModels: Record<string, string>;\n /** Default judge model for /goal. */\n goalJudgeModel: string | null;\n /** Default max attempts for /goal. */\n goalMaxTurns: number | null;\n };\n // Global behavior preferences\n preferences: {\n yolo: boolean | null;\n theme: 'auto' | 'dark' | 'light';\n /** Default reasoning effort level used for all threads/models unless overridden in-session. */\n thinkingLevel: ThinkingLevelSetting;\n /** When true, components like subagent output collapse to compact summaries on completion. */\n quietMode: boolean;\n /** Maximum quiet-mode detail preview lines for compact tool calls. Set to 0 to hide previews. */\n quietModeMaxToolPreviewLines: number;\n };\n // Storage backend configuration\n storage: StorageSettings;\n // User-created custom model packs\n customModelPacks: CustomPack[];\n // User-created custom providers with custom models\n customProviders: CustomProviderSetting[];\n // Model usage counts for ranking in the selector\n modelUseCounts: Record<string, number>;\n // Version the user dismissed the update prompt for (skip until they manually update past this)\n updateDismissedVersion: string | null;\n // Memory gateway configuration\n memoryGateway: { baseUrl?: string };\n // LSP configuration forwarded to the workspace\n lsp?: LSPConfig;\n // Browser automation configuration\n browser: BrowserSettings;\n // Direct TUI `!` shell passthrough configuration\n shellPassthrough: ShellPassthroughSettings;\n // Hold-space voice input configuration\n voice: VoiceSettings;\n // Signal routing configuration\n signals: SignalSettings;\n // Cloud observability configuration (per-resource project IDs; tokens stored in auth.json)\n observability: ObservabilitySettings;\n}\n\nexport interface SignalSettings {\n /** Opt into local Unix socket PubSub for cross-process signal routing. */\n unixSocketPubSub: boolean;\n /** Experimental: enable GitHub PR subscription signals backed by gitcrawl. */\n experimentalGithubSignals: boolean;\n}\n\nexport interface ObservabilityResourceConfig {\n /** Cloud project ID for this resource */\n projectId: string;\n /** When this config was created */\n configuredAt: string;\n}\n\nexport interface ObservabilitySettings {\n /** Per-resource cloud project configs, keyed by resourceId */\n resources: Record<string, ObservabilityResourceConfig>;\n /** Whether to store traces locally in DuckDB. Off by default to avoid disk usage. */\n localTracing: boolean;\n}\n\n/** Auth key prefix for observability tokens stored per-resource in auth.json */\nexport const OBSERVABILITY_AUTH_PREFIX = 'observability:';\n\nexport const STORAGE_DEFAULTS: StorageSettings = {\n backend: 'libsql',\n libsql: {},\n pg: {},\n};\n\n/** Default STT engine: on-device macOS recognizer where available, else cloud. */\nexport function defaultVoiceEngine(): VoiceEngine {\n return process.platform === 'darwin' ? 'macos-native' : 'cloud';\n}\n\nconst DEFAULTS: GlobalSettings = {\n onboarding: {\n completedAt: null,\n skippedAt: null,\n version: 0,\n modePackId: null,\n omPackId: null,\n quietModePreferenceSelected: true,\n },\n models: {\n activeModelPackId: null,\n modeDefaults: {},\n activeOmPackId: null,\n omModelOverride: null,\n observerModelOverride: null,\n reflectorModelOverride: null,\n omObservationThreshold: null,\n omReflectionThreshold: null,\n omCavemanObservations: null,\n omObserveAttachments: null,\n subagentModels: {},\n goalJudgeModel: null,\n goalMaxTurns: null,\n },\n preferences: {\n yolo: null,\n theme: 'auto',\n thinkingLevel: 'off',\n quietMode: false,\n quietModeMaxToolPreviewLines: 2,\n },\n storage: { ...STORAGE_DEFAULTS },\n customModelPacks: [],\n customProviders: [],\n modelUseCounts: {},\n updateDismissedVersion: null,\n memoryGateway: {},\n lsp: {},\n browser: {\n enabled: false,\n provider: 'stagehand',\n headless: false,\n viewport: { width: 1280, height: 720 },\n stagehand: { env: 'LOCAL' },\n },\n shellPassthrough: { mode: 'default' },\n voice: { enabled: false, engine: defaultVoiceEngine(), provider: DEFAULT_STT_PROVIDER },\n signals: { unixSocketPubSub: false, experimentalGithubSignals: false },\n observability: { resources: {}, localTracing: false },\n};\n\nconst THINKING_LEVEL_VALUES: ThinkingLevelSetting[] = ['off', 'low', 'medium', 'high', 'xhigh'];\nconst QUIET_MODE_MAX_TOOL_PREVIEW_LINES_MAX = 8;\nconst loadedSignalSettings = new WeakMap<GlobalSettings, SignalSettings>();\n\nfunction cloneSignalSettings(signals: SignalSettings): SignalSettings {\n return { ...signals };\n}\n\nfunction rememberLoadedSettings(settings: GlobalSettings): GlobalSettings {\n loadedSignalSettings.set(settings, cloneSignalSettings(settings.signals));\n return settings;\n}\n\nfunction signalSettingsEqual(left: SignalSettings, right: SignalSettings): boolean {\n return (\n left.unixSocketPubSub === right.unixSocketPubSub &&\n left.experimentalGithubSignals === right.experimentalGithubSignals\n );\n}\n\nfunction parseThinkingLevel(value: unknown): ThinkingLevelSetting {\n return typeof value === 'string' && THINKING_LEVEL_VALUES.includes(value as ThinkingLevelSetting)\n ? (value as ThinkingLevelSetting)\n : DEFAULTS.preferences.thinkingLevel;\n}\n\nfunction parseQuietModeMaxToolPreviewLines(value: unknown): number {\n const rawValue =\n typeof value === 'number' && Number.isFinite(value) ? value : DEFAULTS.preferences.quietModeMaxToolPreviewLines;\n return Math.min(QUIET_MODE_MAX_TOOL_PREVIEW_LINES_MAX, Math.max(0, Math.floor(rawValue)));\n}\n\nfunction parsePreferences(rawPreferences: unknown): GlobalSettings['preferences'] {\n const raw = rawPreferences && typeof rawPreferences === 'object' ? (rawPreferences as Record<string, unknown>) : {};\n\n return {\n ...DEFAULTS.preferences,\n ...raw,\n thinkingLevel: parseThinkingLevel(raw.thinkingLevel),\n quietModeMaxToolPreviewLines: parseQuietModeMaxToolPreviewLines(raw.quietModeMaxToolPreviewLines),\n };\n}\n\nfunction parseSignalSettings(rawSignals: unknown): SignalSettings {\n const raw = rawSignals && typeof rawSignals === 'object' ? (rawSignals as Record<string, unknown>) : {};\n return {\n unixSocketPubSub:\n typeof raw.unixSocketPubSub === 'boolean' ? raw.unixSocketPubSub : DEFAULTS.signals.unixSocketPubSub,\n experimentalGithubSignals:\n typeof raw.experimentalGithubSignals === 'boolean'\n ? raw.experimentalGithubSignals\n : DEFAULTS.signals.experimentalGithubSignals,\n };\n}\n\nfunction hasQuietModePreferenceSelected(rawOnboarding: unknown): boolean {\n return Boolean(\n rawOnboarding &&\n typeof rawOnboarding === 'object' &&\n Object.prototype.hasOwnProperty.call(rawOnboarding, 'quietModePreferenceSelected'),\n );\n}\n\nfunction applyQuietModePreferenceRollout(settings: GlobalSettings, rawOnboarding: unknown): void {\n if (hasQuietModePreferenceSelected(rawOnboarding)) return;\n settings.onboarding.quietModePreferenceSelected = settings.preferences.quietMode === true;\n}\n\nfunction getNewInstallDefaults(): GlobalSettings {\n const settings = structuredClone(DEFAULTS);\n settings.preferences.quietMode = true;\n settings.onboarding.quietModePreferenceSelected = true;\n return settings;\n}\n\nexport function getSettingsPath(): string {\n return join(getAppDataDir(), 'settings.json');\n}\n\nexport function getCustomProviderId(name: string): string {\n const slug = name\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '');\n return slug || 'provider';\n}\n\nexport function toCustomProviderModelId(providerName: string, modelName: string): string {\n const providerId = getCustomProviderId(providerName);\n const trimmedModelName = modelName.trim();\n const providerPrefix = `${providerId}/`;\n if (trimmedModelName.startsWith(providerPrefix)) {\n return trimmedModelName;\n }\n return `${providerId}/${trimmedModelName}`;\n}\n\nexport function parseCustomProviders(rawProviders: unknown): CustomProviderSetting[] {\n if (!Array.isArray(rawProviders)) return [];\n\n const parsedProviders: CustomProviderSetting[] = [];\n for (const rawProvider of rawProviders) {\n if (!rawProvider || typeof rawProvider !== 'object') continue;\n\n const candidate = rawProvider as Record<string, unknown>;\n const name = typeof candidate.name === 'string' ? candidate.name.trim() : '';\n const url = typeof candidate.url === 'string' ? candidate.url.trim() : '';\n if (!name || !url) continue;\n\n const providerId = getCustomProviderId(name);\n const models = Array.isArray(candidate.models)\n ? [\n ...new Set(\n candidate.models\n .filter((model): model is string => typeof model === 'string')\n .map(model => model.trim())\n .map(model => {\n const providerPrefix = `${providerId}/`;\n if (model.startsWith(providerPrefix)) {\n return model.slice(providerPrefix.length);\n }\n return model;\n }),\n ),\n ].filter(model => model.length > 0)\n : [];\n\n const apiKey =\n typeof candidate.apiKey === 'string' && candidate.apiKey.trim().length > 0 ? candidate.apiKey.trim() : undefined;\n\n parsedProviders.push({\n name,\n url,\n ...(apiKey ? { apiKey } : {}),\n models,\n });\n }\n\n return parsedProviders;\n}\n\nconst BROWSER_PROVIDERS = new Set<BrowserProvider>(['stagehand', 'agent-browser']);\nconst STAGEHAND_ENVS = new Set<StagehandEnv>(['LOCAL', 'BROWSERBASE']);\n\n/**\n * Deep-merge and validate browser settings from JSON.\n * Explicitly validates types to handle malformed settings.json gracefully.\n */\nfunction parseBrowserSettings(rawBrowser: unknown): BrowserSettings {\n const raw = rawBrowser && typeof rawBrowser === 'object' ? (rawBrowser as Record<string, unknown>) : {};\n const rawViewport = raw.viewport && typeof raw.viewport === 'object' ? (raw.viewport as Record<string, unknown>) : {};\n const rawStagehand =\n raw.stagehand && typeof raw.stagehand === 'object' ? (raw.stagehand as Record<string, unknown>) : {};\n const rawAgentBrowser =\n raw.agentBrowser && typeof raw.agentBrowser === 'object' ? (raw.agentBrowser as Record<string, unknown>) : {};\n\n return {\n enabled: typeof raw.enabled === 'boolean' ? raw.enabled : DEFAULTS.browser.enabled,\n provider:\n typeof raw.provider === 'string' && BROWSER_PROVIDERS.has(raw.provider as BrowserProvider)\n ? (raw.provider as BrowserProvider)\n : DEFAULTS.browser.provider,\n headless: typeof raw.headless === 'boolean' ? raw.headless : DEFAULTS.browser.headless,\n cdpUrl: typeof raw.cdpUrl === 'string' && raw.cdpUrl.trim() ? raw.cdpUrl.trim() : undefined,\n profile: typeof raw.profile === 'string' && raw.profile.trim() ? raw.profile.trim() : undefined,\n executablePath:\n typeof raw.executablePath === 'string' && raw.executablePath.trim() ? raw.executablePath.trim() : undefined,\n viewport: {\n width: typeof rawViewport.width === 'number' ? rawViewport.width : DEFAULTS.browser.viewport!.width,\n height: typeof rawViewport.height === 'number' ? rawViewport.height : DEFAULTS.browser.viewport!.height,\n },\n scope: typeof raw.scope === 'string' && (raw.scope === 'shared' || raw.scope === 'thread') ? raw.scope : undefined,\n stagehand: {\n env:\n typeof rawStagehand.env === 'string' && STAGEHAND_ENVS.has(rawStagehand.env as StagehandEnv)\n ? (rawStagehand.env as StagehandEnv)\n : DEFAULTS.browser.stagehand!.env,\n ...(typeof rawStagehand.apiKey === 'string' && rawStagehand.apiKey.trim()\n ? { apiKey: rawStagehand.apiKey.trim() }\n : {}),\n ...(typeof rawStagehand.projectId === 'string' && rawStagehand.projectId.trim()\n ? { projectId: rawStagehand.projectId.trim() }\n : {}),\n ...(typeof rawStagehand.preserveUserDataDir === 'boolean'\n ? { preserveUserDataDir: rawStagehand.preserveUserDataDir }\n : {}),\n },\n agentBrowser:\n typeof rawAgentBrowser.storageState === 'string' && rawAgentBrowser.storageState.trim()\n ? { storageState: rawAgentBrowser.storageState.trim() }\n : undefined,\n };\n}\n\nfunction parseShellPassthroughSettings(rawShellPassthrough: unknown): ShellPassthroughSettings {\n const raw =\n rawShellPassthrough && typeof rawShellPassthrough === 'object'\n ? (rawShellPassthrough as Record<string, unknown>)\n : {};\n const executable = typeof raw.executable === 'string' && raw.executable.trim() ? raw.executable.trim() : undefined;\n const family = typeof raw.family === 'string' && raw.family.trim() ? raw.family.trim() : undefined;\n const mode = typeof raw.mode === 'string' && raw.mode.trim() ? raw.mode.trim() : undefined;\n const defaultMode = executable ? undefined : DEFAULTS.shellPassthrough.mode;\n\n return {\n ...((mode ?? defaultMode) ? { mode: mode ?? defaultMode } : {}),\n ...(executable ? { executable } : {}),\n ...(family ? { family } : {}),\n };\n}\n\nfunction parseVoiceSettings(rawVoice: unknown): VoiceSettings {\n const raw = rawVoice && typeof rawVoice === 'object' ? (rawVoice as Record<string, unknown>) : {};\n const enabled = typeof raw.enabled === 'boolean' ? raw.enabled : DEFAULTS.voice.enabled;\n const engine: VoiceEngine =\n raw.engine === 'macos-native' || raw.engine === 'cloud' ? raw.engine : defaultVoiceEngine();\n // Validate provider/model against the registry, falling back to a usable entry\n // so old `{ enabled }`-only files and unknown values still resolve cleanly.\n const provider = typeof raw.provider === 'string' ? raw.provider : DEFAULTS.voice.provider;\n const model = typeof raw.model === 'string' ? raw.model : undefined;\n const resolved = resolveSTTModel(provider, model);\n return {\n enabled,\n engine,\n provider: resolved.provider,\n model: resolved.model,\n };\n}\n\nconst VALID_PROJECT_ID = /^[a-zA-Z0-9_-]+$/;\n\nfunction parseObservabilitySettings(raw: unknown): ObservabilitySettings {\n if (!raw || typeof raw !== 'object') return { resources: {}, localTracing: false };\n const obj = raw as Record<string, unknown>;\n const localTracing = obj.localTracing === true;\n const rawResources = obj.resources;\n if (!rawResources || typeof rawResources !== 'object') return { resources: {}, localTracing };\n const resources: Record<string, ObservabilityResourceConfig> = {};\n for (const [key, val] of Object.entries(rawResources as Record<string, unknown>)) {\n if (val && typeof val === 'object') {\n const v = val as Record<string, unknown>;\n if (typeof v.projectId === 'string' && VALID_PROJECT_ID.test(v.projectId)) {\n resources[key] = {\n projectId: v.projectId,\n configuredAt: typeof v.configuredAt === 'string' ? v.configuredAt : new Date().toISOString(),\n };\n }\n }\n }\n return { resources, localTracing };\n}\n\n/**\n * One-time migration: move model-related data from auth.json to settings.json.\n * Reads `_modelRanks`, `_modeModelId_*`, `_subagentModelId*` from auth.json,\n * merges them into settings, removes them from auth.json, and writes both files.\n * No-ops if auth.json has no _ prefixed model data.\n */\nfunction migrateFromAuth(settingsPath: string): boolean {\n const authPath = join(getAppDataDir(), 'auth.json');\n if (!existsSync(authPath)) return false;\n\n let authData: Record<string, any>;\n try {\n authData = JSON.parse(readFileSync(authPath, 'utf-8'));\n } catch {\n return false;\n }\n\n const modelKeys = Object.keys(authData).filter(k => k.startsWith('_'));\n if (modelKeys.length === 0) return false;\n\n // Load existing settings (or defaults) and merge auth data into it\n let settings: GlobalSettings;\n if (existsSync(settingsPath)) {\n try {\n const raw = JSON.parse(readFileSync(settingsPath, 'utf-8'));\n settings = {\n onboarding: { ...DEFAULTS.onboarding, ...raw.onboarding },\n models: { ...DEFAULTS.models, ...raw.models },\n preferences: parsePreferences(raw.preferences),\n storage: {\n ...STORAGE_DEFAULTS,\n ...raw.storage,\n libsql: { ...STORAGE_DEFAULTS.libsql, ...raw.storage?.libsql },\n pg: { ...STORAGE_DEFAULTS.pg, ...raw.storage?.pg },\n },\n customModelPacks: Array.isArray(raw.customModelPacks) ? raw.customModelPacks : [],\n customProviders: parseCustomProviders(raw.customProviders),\n modelUseCounts: raw.modelUseCounts && typeof raw.modelUseCounts === 'object' ? raw.modelUseCounts : {},\n updateDismissedVersion: typeof raw.updateDismissedVersion === 'string' ? raw.updateDismissedVersion : null,\n memoryGateway: raw.memoryGateway && typeof raw.memoryGateway === 'object' ? raw.memoryGateway : {},\n lsp: raw.lsp && typeof raw.lsp === 'object' ? (raw.lsp as LSPConfig) : undefined,\n browser: parseBrowserSettings(raw.browser),\n shellPassthrough: parseShellPassthroughSettings(raw.shellPassthrough),\n voice: parseVoiceSettings(raw.voice),\n signals: parseSignalSettings(raw.signals),\n observability: parseObservabilitySettings(raw.observability),\n };\n applyQuietModePreferenceRollout(settings, raw.onboarding);\n } catch {\n settings = structuredClone(DEFAULTS);\n }\n } else {\n settings = structuredClone(DEFAULTS);\n }\n\n // Migrate model use counts (only if settings doesn't already have them)\n if (authData._modelRanks && typeof authData._modelRanks === 'object') {\n settings.modelUseCounts = { ...authData._modelRanks, ...settings.modelUseCounts };\n }\n\n // Migrate per-mode model defaults (don't overwrite existing settings)\n for (const key of modelKeys) {\n const modeMatch = key.match(/^_modeModelId_(.+)$/);\n if (modeMatch?.[1] && typeof authData[key] === 'string' && !settings.models.modeDefaults[modeMatch[1]]) {\n settings.models.modeDefaults[modeMatch[1]] = authData[key];\n }\n }\n\n // Migrate subagent models (don't overwrite existing settings)\n for (const key of modelKeys) {\n if (key === '_subagentModelId' && typeof authData[key] === 'string' && !settings.models.subagentModels['default']) {\n settings.models.subagentModels['default'] = authData[key];\n }\n const saMatch = key.match(/^_subagentModelId_(.+)$/);\n if (saMatch?.[1] && typeof authData[key] === 'string' && !settings.models.subagentModels[saMatch[1]]) {\n settings.models.subagentModels[saMatch[1]] = authData[key];\n }\n }\n\n // Write migrated settings\n saveSettings(settings, settingsPath);\n\n // Clean up auth.json — remove _ prefixed keys\n for (const key of modelKeys) {\n delete authData[key];\n }\n try {\n writeFileSync(authPath, JSON.stringify(authData, null, 2), 'utf-8');\n } catch {\n // Non-fatal — settings are saved, auth cleanup can fail\n }\n\n return true;\n}\n\nconst LEGACY_VARIED_MODELS: Record<string, string> = {\n plan: 'openai/gpt-5.4',\n build: 'anthropic/claude-sonnet-4-5',\n fast: 'anthropic/claude-haiku-4-5',\n};\n\nexport function migrateLegacyVariedPack(settings: GlobalSettings): boolean {\n const legacyPackId = 'varied';\n const customPackId = 'custom:varied';\n const hasLegacyReference =\n settings.models.activeModelPackId === legacyPackId || settings.onboarding.modePackId === legacyPackId;\n\n if (!hasLegacyReference) return false;\n\n const existingIdx = settings.customModelPacks.findIndex(p => p.name === 'varied');\n if (existingIdx >= 0) {\n const existing = settings.customModelPacks[existingIdx]!;\n const modelsMatch = Object.entries(LEGACY_VARIED_MODELS).every(([k, v]) => existing.models[k] === v);\n if (!modelsMatch) {\n existing.models = { ...LEGACY_VARIED_MODELS };\n }\n } else {\n settings.customModelPacks.push({\n name: 'varied',\n models: { ...LEGACY_VARIED_MODELS },\n createdAt: new Date().toISOString(),\n });\n }\n\n if (settings.models.activeModelPackId === legacyPackId) {\n settings.models.activeModelPackId = customPackId;\n if (Object.keys(settings.models.modeDefaults).length === 0) {\n settings.models.modeDefaults = { ...LEGACY_VARIED_MODELS };\n }\n }\n\n if (settings.onboarding.modePackId === legacyPackId) {\n settings.onboarding.modePackId = customPackId;\n }\n\n return true;\n}\n\nexport function loadSettings(filePath: string = getSettingsPath()): GlobalSettings {\n // One-time migration: move model data from auth.json into settings.json\n migrateFromAuth(filePath);\n\n if (!existsSync(filePath)) return rememberLoadedSettings(getNewInstallDefaults());\n try {\n const raw = JSON.parse(readFileSync(filePath, 'utf-8'));\n // Spread raw first to preserve unknown top-level keys (forward-compatibility),\n // then overlay with parsed/typed fields so known keys are always correct.\n const settings: GlobalSettings = {\n ...raw,\n onboarding: { ...DEFAULTS.onboarding, ...raw.onboarding },\n models: { ...DEFAULTS.models, ...raw.models },\n preferences: parsePreferences(raw.preferences),\n storage: {\n ...STORAGE_DEFAULTS,\n ...raw.storage,\n libsql: { ...STORAGE_DEFAULTS.libsql, ...raw.storage?.libsql },\n pg: { ...STORAGE_DEFAULTS.pg, ...raw.storage?.pg },\n },\n customModelPacks: Array.isArray(raw.customModelPacks) ? raw.customModelPacks : [],\n customProviders: parseCustomProviders(raw.customProviders),\n modelUseCounts: raw.modelUseCounts && typeof raw.modelUseCounts === 'object' ? raw.modelUseCounts : {},\n updateDismissedVersion: typeof raw.updateDismissedVersion === 'string' ? raw.updateDismissedVersion : null,\n memoryGateway: raw.memoryGateway && typeof raw.memoryGateway === 'object' ? raw.memoryGateway : {},\n lsp: raw.lsp && typeof raw.lsp === 'object' ? (raw.lsp as LSPConfig) : undefined,\n browser: parseBrowserSettings(raw.browser),\n shellPassthrough: parseShellPassthroughSettings(raw.shellPassthrough),\n voice: parseVoiceSettings(raw.voice),\n signals: parseSignalSettings(raw.signals),\n observability: parseObservabilitySettings(raw.observability),\n };\n\n // Migrate legacy omModelId → omModelOverride\n let settingsChanged = false;\n if (!hasQuietModePreferenceSelected(raw.onboarding)) {\n applyQuietModePreferenceRollout(settings, raw.onboarding);\n settingsChanged = true;\n }\n if (raw.models?.omModelId && !settings.models.omModelOverride) {\n settings.models.omModelOverride = raw.models.omModelId;\n settingsChanged = true;\n }\n\n if (migrateLegacyVariedPack(settings)) {\n settingsChanged = true;\n }\n\n if (settingsChanged) {\n saveSettings(settings, filePath);\n }\n\n return rememberLoadedSettings(settings);\n } catch {\n return rememberLoadedSettings(structuredClone(DEFAULTS));\n }\n}\n\nexport const THREAD_ACTIVE_MODEL_PACK_ID_KEY = 'activeModelPackId';\n\nexport interface ThreadSettings {\n activeModelPackId: string | null;\n modeModelIds: Record<string, string>;\n}\n\nexport function parseThreadSettings(metadata: Record<string, unknown> | undefined): ThreadSettings {\n const modeModelIds: Record<string, string> = {};\n for (const [key, value] of Object.entries(metadata ?? {})) {\n const modeMatch = key.match(/^modeModelId_(.+)$/);\n if (modeMatch?.[1] && typeof value === 'string' && value.length > 0) {\n modeModelIds[modeMatch[1]] = value;\n }\n }\n\n const rawPackId = metadata?.[THREAD_ACTIVE_MODEL_PACK_ID_KEY];\n const activeModelPackId = typeof rawPackId === 'string' && rawPackId.length > 0 ? rawPackId : null;\n\n return {\n activeModelPackId,\n modeModelIds,\n };\n}\n\n/**\n * Resolve active model pack id for the current thread.\n *\n * Priority:\n * 1) explicit thread metadata activeModelPackId\n * 2) inferred from thread modeModelId_* values\n * 3) global settings.models.activeModelPackId\n */\nexport function resolveThreadActiveModelPackId(\n settings: GlobalSettings,\n builtinPacks: Array<{ id: string; models: Record<string, string> }>,\n metadata: Record<string, unknown> | undefined,\n): string | null {\n const threadSettings = parseThreadSettings(metadata);\n\n const isKnownPack = (packId: string): boolean => {\n if (packId.startsWith('custom:')) {\n const name = packId.slice('custom:'.length);\n return settings.customModelPacks.some(p => p.name === name);\n }\n return builtinPacks.some(p => p.id === packId);\n };\n\n if (threadSettings.activeModelPackId && isKnownPack(threadSettings.activeModelPackId)) {\n return threadSettings.activeModelPackId;\n }\n\n const allPacks: Array<{ id: string; models: Record<string, string> }> = [\n ...builtinPacks,\n ...settings.customModelPacks.map(p => ({ id: `custom:${p.name}`, models: p.models })),\n ];\n\n for (const pack of allPacks) {\n const packEntries = Object.entries(pack.models);\n const threadEntries = Object.keys(threadSettings.modeModelIds);\n const matches =\n packEntries.length === threadEntries.length &&\n packEntries.every(([modeId, modelId]) => threadSettings.modeModelIds[modeId] === modelId);\n if (matches) return pack.id;\n }\n\n if (settings.models.activeModelPackId && isKnownPack(settings.models.activeModelPackId)) {\n return settings.models.activeModelPackId;\n }\n\n return null;\n}\n\n/**\n * Resolve effective per-mode model defaults.\n *\n * If `activeModelPackId` is set, looks up the pack (built-in or custom) and\n * returns its models. Falls back to the explicit `modeDefaults` map.\n *\n * @param settings The loaded global settings.\n * @param builtinPacks Built-in packs for the current provider access\n * (from `getAvailableModePacks`). Pass `[]` if unavailable.\n */\nexport function resolveModelDefaults(\n settings: GlobalSettings,\n builtinPacks: Array<{ id: string; models: Record<string, string> }>,\n): Record<string, string> {\n const { activeModelPackId, modeDefaults } = settings.models;\n if (!activeModelPackId) return modeDefaults;\n\n // Custom pack: \"custom:<name>\"\n if (activeModelPackId.startsWith('custom:')) {\n const name = activeModelPackId.slice('custom:'.length);\n const pack = settings.customModelPacks.find(p => p.name === name);\n if (pack) return pack.models;\n // Custom pack was deleted — fall through to modeDefaults\n return modeDefaults;\n }\n\n // Built-in pack\n const builtin = builtinPacks.find(p => p.id === activeModelPackId);\n if (builtin) return builtin.models;\n\n // Unknown pack id — fall through\n return modeDefaults;\n}\n\n/**\n * Resolve the effective model ID for one of the two OM roles.\n *\n * Lookup order:\n * 1. The role-specific override (`observerModelOverride` /\n * `reflectorModelOverride`) if set.\n * 2. If `activeOmPackId` points at a built-in pack, that pack's model.\n * 3. The shared `omModelOverride` fallback.\n *\n * @param settings The loaded global settings.\n * @param role Which OM role to resolve (`'observer'` or `'reflector'`).\n * @param builtinOmPacks Built-in OM packs for the current provider access\n * (from `getAvailableOmPacks`). Pass `[]` if unavailable.\n */\nexport function resolveOmRoleModel(\n settings: GlobalSettings,\n role: 'observer' | 'reflector',\n builtinOmPacks: Array<{ id: string; modelId: string }>,\n): string | null {\n const { activeOmPackId, omModelOverride, observerModelOverride, reflectorModelOverride } = settings.models;\n const roleOverride = role === 'observer' ? observerModelOverride : reflectorModelOverride;\n if (roleOverride) return roleOverride;\n\n if (!activeOmPackId) return omModelOverride;\n if (activeOmPackId === 'custom') return omModelOverride;\n\n const pack = builtinOmPacks.find(p => p.id === activeOmPackId);\n if (pack) return pack.modelId;\n\n return omModelOverride;\n}\n\n/**\n * @deprecated Use `resolveOmRoleModel(settings, 'observer' | 'reflector', ...)`.\n * Equivalent to resolving the observer role (existing callers set both observer\n * and reflector to the same value).\n */\nexport function resolveOmModel(\n settings: GlobalSettings,\n builtinOmPacks: Array<{ id: string; modelId: string }>,\n): string | null {\n return resolveOmRoleModel(settings, 'observer', builtinOmPacks);\n}\n\nfunction getSignalSettingsForSave(settings: GlobalSettings, filePath: string): SignalSettings {\n const loadedSignals = loadedSignalSettings.get(settings);\n if (!loadedSignals || !signalSettingsEqual(settings.signals, loadedSignals) || !existsSync(filePath)) {\n return settings.signals;\n }\n\n try {\n const currentRaw = JSON.parse(readFileSync(filePath, 'utf-8')) as Record<string, unknown>;\n const currentSignals = parseSignalSettings(currentRaw.signals);\n if (!signalSettingsEqual(currentSignals, loadedSignals)) {\n return currentSignals;\n }\n } catch {\n // If the current file is unreadable, fall back to the caller's settings.\n }\n\n return settings.signals;\n}\n\nexport function saveSettings(settings: GlobalSettings, filePath: string = getSettingsPath()): void {\n const dir = dirname(filePath);\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n const signals = getSignalSettingsForSave(settings, filePath);\n settings.signals = signals;\n loadedSignalSettings.set(settings, cloneSignalSettings(signals));\n writeFileSync(filePath, JSON.stringify(settings, null, 2), 'utf-8');\n}\n\n/** Marker file name to track which provider last used a profile. */\nconst PROFILE_PROVIDER_MARKER = '.mastra-provider';\n\n/**\n * Check which provider last used a profile directory.\n * Returns the provider name if the marker exists, undefined otherwise.\n */\nexport function getProfileProvider(profilePath: string): BrowserProvider | undefined {\n const markerPath = join(profilePath, PROFILE_PROVIDER_MARKER);\n if (!existsSync(markerPath)) {\n return undefined;\n }\n try {\n const content = readFileSync(markerPath, 'utf-8').trim();\n if (content === 'stagehand' || content === 'agent-browser') {\n return content;\n }\n return undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Write the provider marker to a profile directory.\n * Creates the directory if it doesn't exist.\n */\nexport function setProfileProvider(profilePath: string, provider: BrowserProvider): void {\n const markerPath = join(profilePath, PROFILE_PROVIDER_MARKER);\n if (!existsSync(profilePath)) {\n mkdirSync(profilePath, { recursive: true });\n }\n writeFileSync(markerPath, provider, 'utf-8');\n}\n\n/**\n * Check if a profile has a provider mismatch.\n * Returns the existing provider if there's a mismatch, undefined otherwise.\n */\nexport function checkProfileProviderMismatch(\n profilePath: string | undefined,\n targetProvider: BrowserProvider,\n): BrowserProvider | undefined {\n if (!profilePath) {\n return undefined;\n }\n const existingProvider = getProfileProvider(profilePath);\n if (existingProvider && existingProvider !== targetProvider) {\n return existingProvider;\n }\n return undefined;\n}\n\nfunction browserRecordingOptions() {\n return { outputDir: join(getAppDataDir(), 'browser-recordings') };\n}\n\n/**\n * Create a browser instance from settings.\n * Shared by startup (main.ts) and live reconfiguration (/browser command).\n * Returns undefined if browser is disabled.\n */\nexport async function createBrowserFromSettings(settings: BrowserSettings): Promise<MastraBrowser | undefined> {\n if (!settings.enabled) {\n return undefined;\n }\n\n const { provider, headless, viewport, cdpUrl, profile, executablePath, stagehand, agentBrowser } = settings;\n\n // Chrome only allows one process per profile directory, so force 'shared' scope\n // when a profile is set. Otherwise use the user's setting (or provider default).\n const scope = profile ? ('shared' as const) : settings.scope;\n\n // Common launch options (no CDP)\n const launchConfig = { headless, viewport, profile, executablePath, scope } as const;\n\n if (provider === 'stagehand') {\n const { StagehandBrowser } = await import('@mastra/stagehand');\n const stagehandOpts: Record<string, unknown> = {\n env: stagehand?.env ?? 'LOCAL',\n apiKey: stagehand?.apiKey ?? process.env.BROWSERBASE_API_KEY,\n projectId: stagehand?.projectId ?? process.env.BROWSERBASE_PROJECT_ID,\n preserveUserDataDir: stagehand?.preserveUserDataDir,\n recording: browserRecordingOptions(),\n };\n\n // When the user has an active OpenAI Codex (ChatGPT) subscription, route\n // Stagehand through the Codex endpoint. We use the AI SDK provider's\n // standard hooks (baseURL, headers, fetch, and middleware) instead of a\n // URL-rewriting fetch:\n // - baseURL: target Codex's Responses API directly (no URL rewriting).\n // - headers: static Codex identifiers (originator, UA, account id).\n // - fetch: a tiny refresher that injects the live OAuth bearer per call,\n // since AI SDK takes `apiKey` as a static string.\n // - middleware: createCodexMiddleware() sets `store: false`, which Codex\n // requires on every request.\n // Model is `gpt-5.4-mini`, the current ChatGPT-sign-in Codex whitelist\n // pick suited to Stagehand's vision + structured-output workload.\n const authStorage = new AuthStorage();\n const cred = authStorage.get('openai-codex');\n if (cred?.type === 'oauth') {\n const accountId = (cred as any).accountId as string | undefined;\n stagehandOpts.model = {\n modelName: 'openai/gpt-5.4-mini',\n apiKey: 'codex-oauth',\n baseURL: 'https://chatgpt.com/backend-api/codex',\n headers: {\n originator: 'mastracode',\n 'User-Agent': 'mastracode',\n ...(accountId ? { 'ChatGPT-Account-ID': accountId } : {}),\n },\n fetch: buildCodexStagehandFetch(authStorage),\n middleware: createCodexMiddleware(),\n } as any;\n }\n\n return cdpUrl\n ? new StagehandBrowser({ ...launchConfig, cdpUrl, scope: 'shared', ...stagehandOpts })\n : new StagehandBrowser({ ...launchConfig, ...stagehandOpts });\n } else if (provider === 'agent-browser') {\n const { AgentBrowser } = await import('@mastra/agent-browser');\n const agentBrowserOpts = {\n storageState: agentBrowser?.storageState,\n recording: browserRecordingOptions(),\n };\n return cdpUrl\n ? new AgentBrowser({ ...launchConfig, cdpUrl, scope: 'shared', ...agentBrowserOpts })\n : new AgentBrowser({ ...launchConfig, ...agentBrowserOpts, scope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,UAAM,EAAE,aAAa,IAAI,MAAM,OAAO,uBAAuB;AAC7D,UAAM,mBAAmB;AAAA,MACvB,cAAc,cAAc;AAAA,MAC5B,WAAW,wBAAwB;AAAA,IACrC;AACA,WAAO,SACH,IAAI,aAAa,EAAE,GAAG,cAAc,QAAQ,OAAO,UAAU,GAAG,iBAAiB,CAAC,IAClF,IAAI,aAAa,EAAE,GAAG,cAAc,GAAG,kBAAkB,MAAM,CAAC;AAAA,EACtE;AAEA,QAAM,IAAI,MAAM,iCAAiC,QAAQ,EAAE;AAC7D;","names":[]}
1
+ {"version":3,"sources":["../../src/onboarding/settings.ts"],"sourcesContent":["/**\n * Persistent global settings stored in the app data directory as settings.json.\n * This file persists onboarding state AND user preferences (model choices, yolo, etc.)\n * so they carry across threads and restarts.\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport type { MastraBrowser } from '@mastra/core/browser';\nimport type { LSPConfig } from '@mastra/core/workspace';\nimport { AuthStorage } from '../auth/storage.js';\nimport { buildCodexStagehandFetch, createCodexMiddleware } from '../providers/openai-codex.js';\nimport { getAppDataDir } from '../utils/project.js';\nimport { DEFAULT_STT_PROVIDER, resolveSTTModel } from '../voice/stt-registry.js';\n\n/** A saved custom pack — user-defined model selections for each mode. */\nexport interface CustomPack {\n name: string;\n models: Record<string, string>;\n createdAt: string;\n}\n\n/** A saved custom provider for OpenAI-compatible endpoints. */\nexport interface CustomProviderSetting {\n name: string;\n url: string;\n apiKey?: string;\n models: string[];\n}\n\n/** Storage backend type. */\nexport type StorageBackend = 'libsql' | 'pg';\n\n/** LibSQL-specific storage settings. */\nexport interface LibSQLStorageSettings {\n url?: string;\n authToken?: string;\n}\n\n/** PostgreSQL-specific storage settings. */\nexport interface PgStorageSettings {\n connectionString?: string;\n host?: string;\n port?: number;\n database?: string;\n user?: string;\n password?: string;\n schemaName?: string;\n disableInit?: boolean;\n skipDefaultIndexes?: boolean;\n}\n\n/** Storage configuration persisted in global settings. */\nexport interface StorageSettings {\n /** Which backend to use. Default: 'libsql'. */\n backend: StorageBackend;\n /** LibSQL-specific config (used when backend is 'libsql'). */\n libsql: LibSQLStorageSettings;\n /** PostgreSQL-specific config (used when backend is 'pg'). */\n pg: PgStorageSettings;\n}\n\n/** Gateway provider key used in AuthStorage. */\nexport const MASTRA_GATEWAY_PROVIDER = 'mastra-gateway';\n\n/** Default gateway URL. */\nexport const MASTRA_GATEWAY_DEFAULT_URL = 'https://gateway-api.mastra.ai';\n\n/** @deprecated Renamed to {@link MASTRA_GATEWAY_PROVIDER}. */\nexport const MEMORY_GATEWAY_PROVIDER = MASTRA_GATEWAY_PROVIDER;\n\n/** @deprecated Renamed to {@link MASTRA_GATEWAY_DEFAULT_URL}. */\nexport const MEMORY_GATEWAY_DEFAULT_URL = MASTRA_GATEWAY_DEFAULT_URL;\n\n/** Valid persisted thinking level values. */\nexport type ThinkingLevelSetting = 'off' | 'low' | 'medium' | 'high' | 'xhigh';\n\n/** Browser provider type. */\nexport type BrowserProvider = 'stagehand' | 'agent-browser';\n\n/** Direct TUI `!` shell passthrough mode. */\nexport type ShellPassthroughSettingsMode = 'default' | 'path' | 'login';\n\n/** Direct TUI `!` shell command language. */\nexport type ShellPassthroughSettingsFamily = 'posix' | 'cmd' | 'powershell';\n\n/** Direct TUI `!` shell passthrough configuration. */\nexport interface ShellPassthroughSettings {\n mode?: ShellPassthroughSettingsMode | string;\n executable?: string;\n family?: ShellPassthroughSettingsFamily | string;\n}\n\n/** STT engine: on-device macOS recognizer or a cloud provider. */\nexport type VoiceEngine = 'macos-native' | 'cloud';\n\n/** Voice (hold-space dictation) configuration persisted in global settings. */\nexport interface VoiceSettings {\n /** Whether hold-space voice input is enabled. */\n enabled: boolean;\n /** Which STT engine to use. Defaults to macOS native on darwin, else cloud. */\n engine: VoiceEngine;\n /** Cloud provider id (matches an STT registry entry). Cloud engine only. */\n provider: string;\n /** Cloud model id; defaults to the provider's first registry model. */\n model?: string;\n}\n\n/** Stagehand environment type. */\nexport type StagehandEnv = 'LOCAL' | 'BROWSERBASE';\n\n/** Stagehand-specific browser settings. */\nexport interface StagehandSettings {\n env: StagehandEnv;\n apiKey?: string;\n projectId?: string;\n /** Whether to preserve the user data directory after the browser closes. */\n preserveUserDataDir?: boolean;\n}\n\n/** AgentBrowser-specific browser settings. */\nexport interface AgentBrowserSettings {\n /** Path to a Playwright storage state file (JSON) containing cookies and localStorage. */\n storageState?: string;\n}\n\n/** Browser configuration persisted in global settings. */\nexport interface BrowserSettings {\n /** Whether browser automation is enabled. */\n enabled: boolean;\n /** Which browser provider to use. */\n provider: BrowserProvider;\n /** Whether to run headless (no visible browser window). */\n headless: boolean;\n /** Browser viewport dimensions. */\n viewport?: { width: number; height: number };\n /** CDP URL for connecting to an existing browser. */\n cdpUrl?: string;\n /** Path to a Chrome/Chromium user data directory (profile). */\n profile?: string;\n /** Path to the browser executable to use. */\n executablePath?: string;\n /** Browser scope — 'shared' (all threads share one browser) or 'thread' (each thread gets its own). */\n scope?: 'shared' | 'thread';\n /** Stagehand-specific settings. */\n stagehand?: StagehandSettings;\n /** AgentBrowser-specific settings. */\n agentBrowser?: AgentBrowserSettings;\n}\n\nexport interface GlobalSettings {\n // Onboarding tracking\n onboarding: {\n completedAt: string | null;\n skippedAt: string | null;\n version: number;\n modePackId: string | null;\n omPackId: string | null;\n quietModePreferenceSelected: boolean;\n };\n // Global model preferences (applied to new threads)\n models: {\n /**\n * Active model pack ID. Built-in packs use their id directly (\"anthropic\",\n * \"openai\"). Custom packs use \"custom:<name>\".\n * When set, models are resolved from the pack at startup so pack updates\n * (e.g. new model versions) apply automatically.\n * Cleared when the user manually overrides via /models (falls back to modeDefaults).\n */\n activeModelPackId: string | null;\n /** Explicit per-mode overrides — used when no activeModelPackId is set. */\n modeDefaults: Record<string, string>;\n /**\n * Active OM pack ID (e.g. \"gemini\", \"anthropic\", \"custom\").\n * When set, the OM model is resolved from the pack at startup so pack\n * updates (e.g. new model versions) apply automatically.\n * Cleared when the user manually overrides via /om (falls back to omModelOverride).\n */\n activeOmPackId: string | null;\n /**\n * Shared OM model override — used for both observer and reflector when a\n * role-specific override is not set. Kept for back-compat with older settings\n * files and set by onboarding when the user picks a custom OM pack.\n */\n omModelOverride: string | null;\n /**\n * Explicit Observer model override — takes precedence over `omModelOverride`\n * when set. Written by `/om` when the observer model is changed independently.\n */\n observerModelOverride: string | null;\n /**\n * Explicit Reflector model override — takes precedence over `omModelOverride`\n * when set. Written by `/om` when the reflector model is changed independently.\n */\n reflectorModelOverride: string | null;\n /** Default OM observation threshold used for new threads unless overridden per-thread. */\n omObservationThreshold: number | null;\n /** Default OM reflection threshold used for new threads unless overridden per-thread. */\n omReflectionThreshold: number | null;\n /**\n * Whether observations and reflections use the terse caveman-style instruction.\n * `null` means inherit the built-in default (currently `false` — caveman is\n * opt-in via `/om` settings). Used as the default for new threads unless\n * overridden per-thread.\n */\n omCavemanObservations: boolean | null;\n /**\n * Whether Observational Memory forwards image/file attachment parts to the\n * Observer LLM. `null` ⇒ inherit built-in default ('auto'). 'auto' checks\n * model capabilities; true/false forces the setting.\n */\n omObserveAttachments: 'auto' | boolean | null;\n /** Per-agent-type subagent model overrides (e.g. { explore: \"openai/gpt-5.1-codex-mini\" }) */\n subagentModels: Record<string, string>;\n /** Default judge model for /goal. */\n goalJudgeModel: string | null;\n /** Default max attempts for /goal. */\n goalMaxTurns: number | null;\n };\n // Global behavior preferences\n preferences: {\n yolo: boolean | null;\n theme: 'auto' | 'dark' | 'light';\n /** Default reasoning effort level used for all threads/models unless overridden in-session. */\n thinkingLevel: ThinkingLevelSetting;\n /** When true, components like subagent output collapse to compact summaries on completion. */\n quietMode: boolean;\n /** Maximum quiet-mode detail preview lines for compact tool calls. Set to 0 to hide previews. */\n quietModeMaxToolPreviewLines: number;\n };\n // Storage backend configuration\n storage: StorageSettings;\n // User-created custom model packs\n customModelPacks: CustomPack[];\n // User-created custom providers with custom models\n customProviders: CustomProviderSetting[];\n // Model usage counts for ranking in the selector\n modelUseCounts: Record<string, number>;\n // Version the user dismissed the update prompt for (skip until they manually update past this)\n updateDismissedVersion: string | null;\n // Mastra gateway configuration\n memoryGateway: { baseUrl?: string };\n // LSP configuration forwarded to the workspace\n lsp?: LSPConfig;\n // Browser automation configuration\n browser: BrowserSettings;\n // Direct TUI `!` shell passthrough configuration\n shellPassthrough: ShellPassthroughSettings;\n // Hold-space voice input configuration\n voice: VoiceSettings;\n // Signal routing configuration\n signals: SignalSettings;\n // Cloud observability configuration (per-resource project IDs; tokens stored in auth.json)\n observability: ObservabilitySettings;\n}\n\nexport interface SignalSettings {\n /** Opt into local Unix socket PubSub for cross-process signal routing. */\n unixSocketPubSub: boolean;\n /** Experimental: enable GitHub PR subscription signals backed by gitcrawl. */\n experimentalGithubSignals: boolean;\n}\n\nexport interface ObservabilityResourceConfig {\n /** Cloud project ID for this resource */\n projectId: string;\n /** When this config was created */\n configuredAt: string;\n}\n\nexport interface ObservabilitySettings {\n /** Per-resource cloud project configs, keyed by resourceId */\n resources: Record<string, ObservabilityResourceConfig>;\n /** Whether to store traces locally in DuckDB. Off by default to avoid disk usage. */\n localTracing: boolean;\n}\n\n/** Auth key prefix for observability tokens stored per-resource in auth.json */\nexport const OBSERVABILITY_AUTH_PREFIX = 'observability:';\n\nexport const STORAGE_DEFAULTS: StorageSettings = {\n backend: 'libsql',\n libsql: {},\n pg: {},\n};\n\n/** Default STT engine: on-device macOS recognizer where available, else cloud. */\nexport function defaultVoiceEngine(): VoiceEngine {\n return process.platform === 'darwin' ? 'macos-native' : 'cloud';\n}\n\nconst DEFAULTS: GlobalSettings = {\n onboarding: {\n completedAt: null,\n skippedAt: null,\n version: 0,\n modePackId: null,\n omPackId: null,\n quietModePreferenceSelected: true,\n },\n models: {\n activeModelPackId: null,\n modeDefaults: {},\n activeOmPackId: null,\n omModelOverride: null,\n observerModelOverride: null,\n reflectorModelOverride: null,\n omObservationThreshold: null,\n omReflectionThreshold: null,\n omCavemanObservations: null,\n omObserveAttachments: null,\n subagentModels: {},\n goalJudgeModel: null,\n goalMaxTurns: null,\n },\n preferences: {\n yolo: null,\n theme: 'auto',\n thinkingLevel: 'off',\n quietMode: false,\n quietModeMaxToolPreviewLines: 2,\n },\n storage: { ...STORAGE_DEFAULTS },\n customModelPacks: [],\n customProviders: [],\n modelUseCounts: {},\n updateDismissedVersion: null,\n memoryGateway: {},\n lsp: {},\n browser: {\n enabled: false,\n provider: 'stagehand',\n headless: false,\n viewport: { width: 1280, height: 720 },\n stagehand: { env: 'LOCAL' },\n },\n shellPassthrough: { mode: 'default' },\n voice: { enabled: false, engine: defaultVoiceEngine(), provider: DEFAULT_STT_PROVIDER },\n signals: { unixSocketPubSub: false, experimentalGithubSignals: false },\n observability: { resources: {}, localTracing: false },\n};\n\nconst THINKING_LEVEL_VALUES: ThinkingLevelSetting[] = ['off', 'low', 'medium', 'high', 'xhigh'];\nconst QUIET_MODE_MAX_TOOL_PREVIEW_LINES_MAX = 8;\nconst loadedSignalSettings = new WeakMap<GlobalSettings, SignalSettings>();\n\nfunction cloneSignalSettings(signals: SignalSettings): SignalSettings {\n return { ...signals };\n}\n\nfunction rememberLoadedSettings(settings: GlobalSettings): GlobalSettings {\n loadedSignalSettings.set(settings, cloneSignalSettings(settings.signals));\n return settings;\n}\n\nfunction signalSettingsEqual(left: SignalSettings, right: SignalSettings): boolean {\n return (\n left.unixSocketPubSub === right.unixSocketPubSub &&\n left.experimentalGithubSignals === right.experimentalGithubSignals\n );\n}\n\nfunction parseThinkingLevel(value: unknown): ThinkingLevelSetting {\n return typeof value === 'string' && THINKING_LEVEL_VALUES.includes(value as ThinkingLevelSetting)\n ? (value as ThinkingLevelSetting)\n : DEFAULTS.preferences.thinkingLevel;\n}\n\nfunction parseQuietModeMaxToolPreviewLines(value: unknown): number {\n const rawValue =\n typeof value === 'number' && Number.isFinite(value) ? value : DEFAULTS.preferences.quietModeMaxToolPreviewLines;\n return Math.min(QUIET_MODE_MAX_TOOL_PREVIEW_LINES_MAX, Math.max(0, Math.floor(rawValue)));\n}\n\nfunction parsePreferences(rawPreferences: unknown): GlobalSettings['preferences'] {\n const raw = rawPreferences && typeof rawPreferences === 'object' ? (rawPreferences as Record<string, unknown>) : {};\n\n return {\n ...DEFAULTS.preferences,\n ...raw,\n thinkingLevel: parseThinkingLevel(raw.thinkingLevel),\n quietModeMaxToolPreviewLines: parseQuietModeMaxToolPreviewLines(raw.quietModeMaxToolPreviewLines),\n };\n}\n\nfunction parseSignalSettings(rawSignals: unknown): SignalSettings {\n const raw = rawSignals && typeof rawSignals === 'object' ? (rawSignals as Record<string, unknown>) : {};\n return {\n unixSocketPubSub:\n typeof raw.unixSocketPubSub === 'boolean' ? raw.unixSocketPubSub : DEFAULTS.signals.unixSocketPubSub,\n experimentalGithubSignals:\n typeof raw.experimentalGithubSignals === 'boolean'\n ? raw.experimentalGithubSignals\n : DEFAULTS.signals.experimentalGithubSignals,\n };\n}\n\nfunction hasQuietModePreferenceSelected(rawOnboarding: unknown): boolean {\n return Boolean(\n rawOnboarding &&\n typeof rawOnboarding === 'object' &&\n Object.prototype.hasOwnProperty.call(rawOnboarding, 'quietModePreferenceSelected'),\n );\n}\n\nfunction applyQuietModePreferenceRollout(settings: GlobalSettings, rawOnboarding: unknown): void {\n if (hasQuietModePreferenceSelected(rawOnboarding)) return;\n settings.onboarding.quietModePreferenceSelected = settings.preferences.quietMode === true;\n}\n\nfunction getNewInstallDefaults(): GlobalSettings {\n const settings = structuredClone(DEFAULTS);\n settings.preferences.quietMode = true;\n settings.onboarding.quietModePreferenceSelected = true;\n return settings;\n}\n\nexport function getSettingsPath(): string {\n return join(getAppDataDir(), 'settings.json');\n}\n\nexport function getCustomProviderId(name: string): string {\n const slug = name\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '');\n return slug || 'provider';\n}\n\nexport function toCustomProviderModelId(providerName: string, modelName: string): string {\n const providerId = getCustomProviderId(providerName);\n const trimmedModelName = modelName.trim();\n const providerPrefix = `${providerId}/`;\n if (trimmedModelName.startsWith(providerPrefix)) {\n return trimmedModelName;\n }\n return `${providerId}/${trimmedModelName}`;\n}\n\nexport function parseCustomProviders(rawProviders: unknown): CustomProviderSetting[] {\n if (!Array.isArray(rawProviders)) return [];\n\n const parsedProviders: CustomProviderSetting[] = [];\n for (const rawProvider of rawProviders) {\n if (!rawProvider || typeof rawProvider !== 'object') continue;\n\n const candidate = rawProvider as Record<string, unknown>;\n const name = typeof candidate.name === 'string' ? candidate.name.trim() : '';\n const url = typeof candidate.url === 'string' ? candidate.url.trim() : '';\n if (!name || !url) continue;\n\n const providerId = getCustomProviderId(name);\n const models = Array.isArray(candidate.models)\n ? [\n ...new Set(\n candidate.models\n .filter((model): model is string => typeof model === 'string')\n .map(model => model.trim())\n .map(model => {\n const providerPrefix = `${providerId}/`;\n if (model.startsWith(providerPrefix)) {\n return model.slice(providerPrefix.length);\n }\n return model;\n }),\n ),\n ].filter(model => model.length > 0)\n : [];\n\n const apiKey =\n typeof candidate.apiKey === 'string' && candidate.apiKey.trim().length > 0 ? candidate.apiKey.trim() : undefined;\n\n parsedProviders.push({\n name,\n url,\n ...(apiKey ? { apiKey } : {}),\n models,\n });\n }\n\n return parsedProviders;\n}\n\nconst BROWSER_PROVIDERS = new Set<BrowserProvider>(['stagehand', 'agent-browser']);\nconst STAGEHAND_ENVS = new Set<StagehandEnv>(['LOCAL', 'BROWSERBASE']);\n\n/**\n * Deep-merge and validate browser settings from JSON.\n * Explicitly validates types to handle malformed settings.json gracefully.\n */\nfunction parseBrowserSettings(rawBrowser: unknown): BrowserSettings {\n const raw = rawBrowser && typeof rawBrowser === 'object' ? (rawBrowser as Record<string, unknown>) : {};\n const rawViewport = raw.viewport && typeof raw.viewport === 'object' ? (raw.viewport as Record<string, unknown>) : {};\n const rawStagehand =\n raw.stagehand && typeof raw.stagehand === 'object' ? (raw.stagehand as Record<string, unknown>) : {};\n const rawAgentBrowser =\n raw.agentBrowser && typeof raw.agentBrowser === 'object' ? (raw.agentBrowser as Record<string, unknown>) : {};\n\n return {\n enabled: typeof raw.enabled === 'boolean' ? raw.enabled : DEFAULTS.browser.enabled,\n provider:\n typeof raw.provider === 'string' && BROWSER_PROVIDERS.has(raw.provider as BrowserProvider)\n ? (raw.provider as BrowserProvider)\n : DEFAULTS.browser.provider,\n headless: typeof raw.headless === 'boolean' ? raw.headless : DEFAULTS.browser.headless,\n cdpUrl: typeof raw.cdpUrl === 'string' && raw.cdpUrl.trim() ? raw.cdpUrl.trim() : undefined,\n profile: typeof raw.profile === 'string' && raw.profile.trim() ? raw.profile.trim() : undefined,\n executablePath:\n typeof raw.executablePath === 'string' && raw.executablePath.trim() ? raw.executablePath.trim() : undefined,\n viewport: {\n width: typeof rawViewport.width === 'number' ? rawViewport.width : DEFAULTS.browser.viewport!.width,\n height: typeof rawViewport.height === 'number' ? rawViewport.height : DEFAULTS.browser.viewport!.height,\n },\n scope: typeof raw.scope === 'string' && (raw.scope === 'shared' || raw.scope === 'thread') ? raw.scope : undefined,\n stagehand: {\n env:\n typeof rawStagehand.env === 'string' && STAGEHAND_ENVS.has(rawStagehand.env as StagehandEnv)\n ? (rawStagehand.env as StagehandEnv)\n : DEFAULTS.browser.stagehand!.env,\n ...(typeof rawStagehand.apiKey === 'string' && rawStagehand.apiKey.trim()\n ? { apiKey: rawStagehand.apiKey.trim() }\n : {}),\n ...(typeof rawStagehand.projectId === 'string' && rawStagehand.projectId.trim()\n ? { projectId: rawStagehand.projectId.trim() }\n : {}),\n ...(typeof rawStagehand.preserveUserDataDir === 'boolean'\n ? { preserveUserDataDir: rawStagehand.preserveUserDataDir }\n : {}),\n },\n agentBrowser:\n typeof rawAgentBrowser.storageState === 'string' && rawAgentBrowser.storageState.trim()\n ? { storageState: rawAgentBrowser.storageState.trim() }\n : undefined,\n };\n}\n\nfunction parseShellPassthroughSettings(rawShellPassthrough: unknown): ShellPassthroughSettings {\n const raw =\n rawShellPassthrough && typeof rawShellPassthrough === 'object'\n ? (rawShellPassthrough as Record<string, unknown>)\n : {};\n const executable = typeof raw.executable === 'string' && raw.executable.trim() ? raw.executable.trim() : undefined;\n const family = typeof raw.family === 'string' && raw.family.trim() ? raw.family.trim() : undefined;\n const mode = typeof raw.mode === 'string' && raw.mode.trim() ? raw.mode.trim() : undefined;\n const defaultMode = executable ? undefined : DEFAULTS.shellPassthrough.mode;\n\n return {\n ...((mode ?? defaultMode) ? { mode: mode ?? defaultMode } : {}),\n ...(executable ? { executable } : {}),\n ...(family ? { family } : {}),\n };\n}\n\nfunction parseVoiceSettings(rawVoice: unknown): VoiceSettings {\n const raw = rawVoice && typeof rawVoice === 'object' ? (rawVoice as Record<string, unknown>) : {};\n const enabled = typeof raw.enabled === 'boolean' ? raw.enabled : DEFAULTS.voice.enabled;\n const engine: VoiceEngine =\n raw.engine === 'macos-native' || raw.engine === 'cloud' ? raw.engine : defaultVoiceEngine();\n // Validate provider/model against the registry, falling back to a usable entry\n // so old `{ enabled }`-only files and unknown values still resolve cleanly.\n const provider = typeof raw.provider === 'string' ? raw.provider : DEFAULTS.voice.provider;\n const model = typeof raw.model === 'string' ? raw.model : undefined;\n const resolved = resolveSTTModel(provider, model);\n return {\n enabled,\n engine,\n provider: resolved.provider,\n model: resolved.model,\n };\n}\n\nconst VALID_PROJECT_ID = /^[a-zA-Z0-9_-]+$/;\n\nfunction parseObservabilitySettings(raw: unknown): ObservabilitySettings {\n if (!raw || typeof raw !== 'object') return { resources: {}, localTracing: false };\n const obj = raw as Record<string, unknown>;\n const localTracing = obj.localTracing === true;\n const rawResources = obj.resources;\n if (!rawResources || typeof rawResources !== 'object') return { resources: {}, localTracing };\n const resources: Record<string, ObservabilityResourceConfig> = {};\n for (const [key, val] of Object.entries(rawResources as Record<string, unknown>)) {\n if (val && typeof val === 'object') {\n const v = val as Record<string, unknown>;\n if (typeof v.projectId === 'string' && VALID_PROJECT_ID.test(v.projectId)) {\n resources[key] = {\n projectId: v.projectId,\n configuredAt: typeof v.configuredAt === 'string' ? v.configuredAt : new Date().toISOString(),\n };\n }\n }\n }\n return { resources, localTracing };\n}\n\n/**\n * One-time migration: move model-related data from auth.json to settings.json.\n * Reads `_modelRanks`, `_modeModelId_*`, `_subagentModelId*` from auth.json,\n * merges them into settings, removes them from auth.json, and writes both files.\n * No-ops if auth.json has no _ prefixed model data.\n */\nfunction migrateFromAuth(settingsPath: string): boolean {\n const authPath = join(getAppDataDir(), 'auth.json');\n if (!existsSync(authPath)) return false;\n\n let authData: Record<string, any>;\n try {\n authData = JSON.parse(readFileSync(authPath, 'utf-8'));\n } catch {\n return false;\n }\n\n const modelKeys = Object.keys(authData).filter(k => k.startsWith('_'));\n if (modelKeys.length === 0) return false;\n\n // Load existing settings (or defaults) and merge auth data into it\n let settings: GlobalSettings;\n if (existsSync(settingsPath)) {\n try {\n const raw = JSON.parse(readFileSync(settingsPath, 'utf-8'));\n settings = {\n onboarding: { ...DEFAULTS.onboarding, ...raw.onboarding },\n models: { ...DEFAULTS.models, ...raw.models },\n preferences: parsePreferences(raw.preferences),\n storage: {\n ...STORAGE_DEFAULTS,\n ...raw.storage,\n libsql: { ...STORAGE_DEFAULTS.libsql, ...raw.storage?.libsql },\n pg: { ...STORAGE_DEFAULTS.pg, ...raw.storage?.pg },\n },\n customModelPacks: Array.isArray(raw.customModelPacks) ? raw.customModelPacks : [],\n customProviders: parseCustomProviders(raw.customProviders),\n modelUseCounts: raw.modelUseCounts && typeof raw.modelUseCounts === 'object' ? raw.modelUseCounts : {},\n updateDismissedVersion: typeof raw.updateDismissedVersion === 'string' ? raw.updateDismissedVersion : null,\n memoryGateway: raw.memoryGateway && typeof raw.memoryGateway === 'object' ? raw.memoryGateway : {},\n lsp: raw.lsp && typeof raw.lsp === 'object' ? (raw.lsp as LSPConfig) : undefined,\n browser: parseBrowserSettings(raw.browser),\n shellPassthrough: parseShellPassthroughSettings(raw.shellPassthrough),\n voice: parseVoiceSettings(raw.voice),\n signals: parseSignalSettings(raw.signals),\n observability: parseObservabilitySettings(raw.observability),\n };\n applyQuietModePreferenceRollout(settings, raw.onboarding);\n } catch {\n settings = structuredClone(DEFAULTS);\n }\n } else {\n settings = structuredClone(DEFAULTS);\n }\n\n // Migrate model use counts (only if settings doesn't already have them)\n if (authData._modelRanks && typeof authData._modelRanks === 'object') {\n settings.modelUseCounts = { ...authData._modelRanks, ...settings.modelUseCounts };\n }\n\n // Migrate per-mode model defaults (don't overwrite existing settings)\n for (const key of modelKeys) {\n const modeMatch = key.match(/^_modeModelId_(.+)$/);\n if (modeMatch?.[1] && typeof authData[key] === 'string' && !settings.models.modeDefaults[modeMatch[1]]) {\n settings.models.modeDefaults[modeMatch[1]] = authData[key];\n }\n }\n\n // Migrate subagent models (don't overwrite existing settings)\n for (const key of modelKeys) {\n if (key === '_subagentModelId' && typeof authData[key] === 'string' && !settings.models.subagentModels['default']) {\n settings.models.subagentModels['default'] = authData[key];\n }\n const saMatch = key.match(/^_subagentModelId_(.+)$/);\n if (saMatch?.[1] && typeof authData[key] === 'string' && !settings.models.subagentModels[saMatch[1]]) {\n settings.models.subagentModels[saMatch[1]] = authData[key];\n }\n }\n\n // Write migrated settings\n saveSettings(settings, settingsPath);\n\n // Clean up auth.json — remove _ prefixed keys\n for (const key of modelKeys) {\n delete authData[key];\n }\n try {\n writeFileSync(authPath, JSON.stringify(authData, null, 2), 'utf-8');\n } catch {\n // Non-fatal — settings are saved, auth cleanup can fail\n }\n\n return true;\n}\n\nconst LEGACY_VARIED_MODELS: Record<string, string> = {\n plan: 'openai/gpt-5.4',\n build: 'anthropic/claude-sonnet-4-5',\n fast: 'anthropic/claude-haiku-4-5',\n};\n\nexport function migrateLegacyVariedPack(settings: GlobalSettings): boolean {\n const legacyPackId = 'varied';\n const customPackId = 'custom:varied';\n const hasLegacyReference =\n settings.models.activeModelPackId === legacyPackId || settings.onboarding.modePackId === legacyPackId;\n\n if (!hasLegacyReference) return false;\n\n const existingIdx = settings.customModelPacks.findIndex(p => p.name === 'varied');\n if (existingIdx >= 0) {\n const existing = settings.customModelPacks[existingIdx]!;\n const modelsMatch = Object.entries(LEGACY_VARIED_MODELS).every(([k, v]) => existing.models[k] === v);\n if (!modelsMatch) {\n existing.models = { ...LEGACY_VARIED_MODELS };\n }\n } else {\n settings.customModelPacks.push({\n name: 'varied',\n models: { ...LEGACY_VARIED_MODELS },\n createdAt: new Date().toISOString(),\n });\n }\n\n if (settings.models.activeModelPackId === legacyPackId) {\n settings.models.activeModelPackId = customPackId;\n if (Object.keys(settings.models.modeDefaults).length === 0) {\n settings.models.modeDefaults = { ...LEGACY_VARIED_MODELS };\n }\n }\n\n if (settings.onboarding.modePackId === legacyPackId) {\n settings.onboarding.modePackId = customPackId;\n }\n\n return true;\n}\n\nexport function loadSettings(filePath: string = getSettingsPath()): GlobalSettings {\n // One-time migration: move model data from auth.json into settings.json\n migrateFromAuth(filePath);\n\n if (!existsSync(filePath)) return rememberLoadedSettings(getNewInstallDefaults());\n try {\n const raw = JSON.parse(readFileSync(filePath, 'utf-8'));\n // Spread raw first to preserve unknown top-level keys (forward-compatibility),\n // then overlay with parsed/typed fields so known keys are always correct.\n const settings: GlobalSettings = {\n ...raw,\n onboarding: { ...DEFAULTS.onboarding, ...raw.onboarding },\n models: { ...DEFAULTS.models, ...raw.models },\n preferences: parsePreferences(raw.preferences),\n storage: {\n ...STORAGE_DEFAULTS,\n ...raw.storage,\n libsql: { ...STORAGE_DEFAULTS.libsql, ...raw.storage?.libsql },\n pg: { ...STORAGE_DEFAULTS.pg, ...raw.storage?.pg },\n },\n customModelPacks: Array.isArray(raw.customModelPacks) ? raw.customModelPacks : [],\n customProviders: parseCustomProviders(raw.customProviders),\n modelUseCounts: raw.modelUseCounts && typeof raw.modelUseCounts === 'object' ? raw.modelUseCounts : {},\n updateDismissedVersion: typeof raw.updateDismissedVersion === 'string' ? raw.updateDismissedVersion : null,\n memoryGateway: raw.memoryGateway && typeof raw.memoryGateway === 'object' ? raw.memoryGateway : {},\n lsp: raw.lsp && typeof raw.lsp === 'object' ? (raw.lsp as LSPConfig) : undefined,\n browser: parseBrowserSettings(raw.browser),\n shellPassthrough: parseShellPassthroughSettings(raw.shellPassthrough),\n voice: parseVoiceSettings(raw.voice),\n signals: parseSignalSettings(raw.signals),\n observability: parseObservabilitySettings(raw.observability),\n };\n\n // Migrate legacy omModelId → omModelOverride\n let settingsChanged = false;\n if (!hasQuietModePreferenceSelected(raw.onboarding)) {\n applyQuietModePreferenceRollout(settings, raw.onboarding);\n settingsChanged = true;\n }\n if (raw.models?.omModelId && !settings.models.omModelOverride) {\n settings.models.omModelOverride = raw.models.omModelId;\n settingsChanged = true;\n }\n\n if (migrateLegacyVariedPack(settings)) {\n settingsChanged = true;\n }\n\n if (settingsChanged) {\n saveSettings(settings, filePath);\n }\n\n return rememberLoadedSettings(settings);\n } catch {\n return rememberLoadedSettings(structuredClone(DEFAULTS));\n }\n}\n\nexport const THREAD_ACTIVE_MODEL_PACK_ID_KEY = 'activeModelPackId';\n\nexport interface ThreadSettings {\n activeModelPackId: string | null;\n modeModelIds: Record<string, string>;\n}\n\nexport function parseThreadSettings(metadata: Record<string, unknown> | undefined): ThreadSettings {\n const modeModelIds: Record<string, string> = {};\n for (const [key, value] of Object.entries(metadata ?? {})) {\n const modeMatch = key.match(/^modeModelId_(.+)$/);\n if (modeMatch?.[1] && typeof value === 'string' && value.length > 0) {\n modeModelIds[modeMatch[1]] = value;\n }\n }\n\n const rawPackId = metadata?.[THREAD_ACTIVE_MODEL_PACK_ID_KEY];\n const activeModelPackId = typeof rawPackId === 'string' && rawPackId.length > 0 ? rawPackId : null;\n\n return {\n activeModelPackId,\n modeModelIds,\n };\n}\n\n/**\n * Resolve active model pack id for the current thread.\n *\n * Priority:\n * 1) explicit thread metadata activeModelPackId\n * 2) inferred from thread modeModelId_* values\n * 3) global settings.models.activeModelPackId\n */\nexport function resolveThreadActiveModelPackId(\n settings: GlobalSettings,\n builtinPacks: Array<{ id: string; models: Record<string, string> }>,\n metadata: Record<string, unknown> | undefined,\n): string | null {\n const threadSettings = parseThreadSettings(metadata);\n\n const isKnownPack = (packId: string): boolean => {\n if (packId.startsWith('custom:')) {\n const name = packId.slice('custom:'.length);\n return settings.customModelPacks.some(p => p.name === name);\n }\n return builtinPacks.some(p => p.id === packId);\n };\n\n if (threadSettings.activeModelPackId && isKnownPack(threadSettings.activeModelPackId)) {\n return threadSettings.activeModelPackId;\n }\n\n const allPacks: Array<{ id: string; models: Record<string, string> }> = [\n ...builtinPacks,\n ...settings.customModelPacks.map(p => ({ id: `custom:${p.name}`, models: p.models })),\n ];\n\n for (const pack of allPacks) {\n const packEntries = Object.entries(pack.models);\n const threadEntries = Object.keys(threadSettings.modeModelIds);\n const matches =\n packEntries.length === threadEntries.length &&\n packEntries.every(([modeId, modelId]) => threadSettings.modeModelIds[modeId] === modelId);\n if (matches) return pack.id;\n }\n\n if (settings.models.activeModelPackId && isKnownPack(settings.models.activeModelPackId)) {\n return settings.models.activeModelPackId;\n }\n\n return null;\n}\n\n/**\n * Resolve effective per-mode model defaults.\n *\n * If `activeModelPackId` is set, looks up the pack (built-in or custom) and\n * returns its models. Falls back to the explicit `modeDefaults` map.\n *\n * @param settings The loaded global settings.\n * @param builtinPacks Built-in packs for the current provider access\n * (from `getAvailableModePacks`). Pass `[]` if unavailable.\n */\nexport function resolveModelDefaults(\n settings: GlobalSettings,\n builtinPacks: Array<{ id: string; models: Record<string, string> }>,\n): Record<string, string> {\n const { activeModelPackId, modeDefaults } = settings.models;\n if (!activeModelPackId) return modeDefaults;\n\n // Custom pack: \"custom:<name>\"\n if (activeModelPackId.startsWith('custom:')) {\n const name = activeModelPackId.slice('custom:'.length);\n const pack = settings.customModelPacks.find(p => p.name === name);\n if (pack) return pack.models;\n // Custom pack was deleted — fall through to modeDefaults\n return modeDefaults;\n }\n\n // Built-in pack\n const builtin = builtinPacks.find(p => p.id === activeModelPackId);\n if (builtin) return builtin.models;\n\n // Unknown pack id — fall through\n return modeDefaults;\n}\n\n/**\n * Resolve the effective model ID for one of the two OM roles.\n *\n * Lookup order:\n * 1. The role-specific override (`observerModelOverride` /\n * `reflectorModelOverride`) if set.\n * 2. If `activeOmPackId` points at a built-in pack, that pack's model.\n * 3. The shared `omModelOverride` fallback.\n *\n * @param settings The loaded global settings.\n * @param role Which OM role to resolve (`'observer'` or `'reflector'`).\n * @param builtinOmPacks Built-in OM packs for the current provider access\n * (from `getAvailableOmPacks`). Pass `[]` if unavailable.\n */\nexport function resolveOmRoleModel(\n settings: GlobalSettings,\n role: 'observer' | 'reflector',\n builtinOmPacks: Array<{ id: string; modelId: string }>,\n): string | null {\n const { activeOmPackId, omModelOverride, observerModelOverride, reflectorModelOverride } = settings.models;\n const roleOverride = role === 'observer' ? observerModelOverride : reflectorModelOverride;\n if (roleOverride) return roleOverride;\n\n if (!activeOmPackId) return omModelOverride;\n if (activeOmPackId === 'custom') return omModelOverride;\n\n const pack = builtinOmPacks.find(p => p.id === activeOmPackId);\n if (pack) return pack.modelId;\n\n return omModelOverride;\n}\n\n/**\n * @deprecated Use `resolveOmRoleModel(settings, 'observer' | 'reflector', ...)`.\n * Equivalent to resolving the observer role (existing callers set both observer\n * and reflector to the same value).\n */\nexport function resolveOmModel(\n settings: GlobalSettings,\n builtinOmPacks: Array<{ id: string; modelId: string }>,\n): string | null {\n return resolveOmRoleModel(settings, 'observer', builtinOmPacks);\n}\n\nfunction getSignalSettingsForSave(settings: GlobalSettings, filePath: string): SignalSettings {\n const loadedSignals = loadedSignalSettings.get(settings);\n if (!loadedSignals || !signalSettingsEqual(settings.signals, loadedSignals) || !existsSync(filePath)) {\n return settings.signals;\n }\n\n try {\n const currentRaw = JSON.parse(readFileSync(filePath, 'utf-8')) as Record<string, unknown>;\n const currentSignals = parseSignalSettings(currentRaw.signals);\n if (!signalSettingsEqual(currentSignals, loadedSignals)) {\n return currentSignals;\n }\n } catch {\n // If the current file is unreadable, fall back to the caller's settings.\n }\n\n return settings.signals;\n}\n\nexport function saveSettings(settings: GlobalSettings, filePath: string = getSettingsPath()): void {\n const dir = dirname(filePath);\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n const signals = getSignalSettingsForSave(settings, filePath);\n settings.signals = signals;\n loadedSignalSettings.set(settings, cloneSignalSettings(signals));\n writeFileSync(filePath, JSON.stringify(settings, null, 2), 'utf-8');\n}\n\n/** Marker file name to track which provider last used a profile. */\nconst PROFILE_PROVIDER_MARKER = '.mastra-provider';\n\n/**\n * Check which provider last used a profile directory.\n * Returns the provider name if the marker exists, undefined otherwise.\n */\nexport function getProfileProvider(profilePath: string): BrowserProvider | undefined {\n const markerPath = join(profilePath, PROFILE_PROVIDER_MARKER);\n if (!existsSync(markerPath)) {\n return undefined;\n }\n try {\n const content = readFileSync(markerPath, 'utf-8').trim();\n if (content === 'stagehand' || content === 'agent-browser') {\n return content;\n }\n return undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Write the provider marker to a profile directory.\n * Creates the directory if it doesn't exist.\n */\nexport function setProfileProvider(profilePath: string, provider: BrowserProvider): void {\n const markerPath = join(profilePath, PROFILE_PROVIDER_MARKER);\n if (!existsSync(profilePath)) {\n mkdirSync(profilePath, { recursive: true });\n }\n writeFileSync(markerPath, provider, 'utf-8');\n}\n\n/**\n * Check if a profile has a provider mismatch.\n * Returns the existing provider if there's a mismatch, undefined otherwise.\n */\nexport function checkProfileProviderMismatch(\n profilePath: string | undefined,\n targetProvider: BrowserProvider,\n): BrowserProvider | undefined {\n if (!profilePath) {\n return undefined;\n }\n const existingProvider = getProfileProvider(profilePath);\n if (existingProvider && existingProvider !== targetProvider) {\n return existingProvider;\n }\n return undefined;\n}\n\nfunction browserRecordingOptions() {\n return { outputDir: join(getAppDataDir(), 'browser-recordings') };\n}\n\n/**\n * Create a browser instance from settings.\n * Shared by startup (main.ts) and live reconfiguration (/browser command).\n * Returns undefined if browser is disabled.\n */\nexport async function createBrowserFromSettings(settings: BrowserSettings): Promise<MastraBrowser | undefined> {\n if (!settings.enabled) {\n return undefined;\n }\n\n const { provider, headless, viewport, cdpUrl, profile, executablePath, stagehand, agentBrowser } = settings;\n\n // Chrome only allows one process per profile directory, so force 'shared' scope\n // when a profile is set. Otherwise use the user's setting (or provider default).\n const scope = profile ? ('shared' as const) : settings.scope;\n\n // Common launch options (no CDP)\n const launchConfig = { headless, viewport, profile, executablePath, scope } as const;\n\n if (provider === 'stagehand') {\n const { StagehandBrowser } = await import('@mastra/stagehand');\n const stagehandOpts: Record<string, unknown> = {\n env: stagehand?.env ?? 'LOCAL',\n apiKey: stagehand?.apiKey ?? process.env.BROWSERBASE_API_KEY,\n projectId: stagehand?.projectId ?? process.env.BROWSERBASE_PROJECT_ID,\n preserveUserDataDir: stagehand?.preserveUserDataDir,\n recording: browserRecordingOptions(),\n };\n\n // When the user has an active OpenAI Codex (ChatGPT) subscription, route\n // Stagehand through the Codex endpoint. We use the AI SDK provider's\n // standard hooks (baseURL, headers, fetch, and middleware) instead of a\n // URL-rewriting fetch:\n // - baseURL: target Codex's Responses API directly (no URL rewriting).\n // - headers: static Codex identifiers (originator, UA, account id).\n // - fetch: a tiny refresher that injects the live OAuth bearer per call,\n // since AI SDK takes `apiKey` as a static string.\n // - middleware: createCodexMiddleware() sets `store: false`, which Codex\n // requires on every request.\n // Model is `gpt-5.4-mini`, the current ChatGPT-sign-in Codex whitelist\n // pick suited to Stagehand's vision + structured-output workload.\n const authStorage = new AuthStorage();\n const cred = authStorage.get('openai-codex');\n if (cred?.type === 'oauth') {\n const accountId = (cred as any).accountId as string | undefined;\n stagehandOpts.model = {\n modelName: 'openai/gpt-5.4-mini',\n apiKey: 'codex-oauth',\n baseURL: 'https://chatgpt.com/backend-api/codex',\n headers: {\n originator: 'mastracode',\n 'User-Agent': 'mastracode',\n ...(accountId ? { 'ChatGPT-Account-ID': accountId } : {}),\n },\n fetch: buildCodexStagehandFetch(authStorage),\n middleware: createCodexMiddleware(),\n } as any;\n }\n\n return cdpUrl\n ? new StagehandBrowser({ ...launchConfig, cdpUrl, scope: 'shared', ...stagehandOpts })\n : new StagehandBrowser({ ...launchConfig, ...stagehandOpts });\n } else if (provider === 'agent-browser') {\n const { AgentBrowser } = await import('@mastra/agent-browser');\n const agentBrowserOpts = {\n storageState: agentBrowser?.storageState,\n recording: browserRecordingOptions(),\n };\n return cdpUrl\n ? new AgentBrowser({ ...launchConfig, cdpUrl, scope: 'shared', ...agentBrowserOpts })\n : new AgentBrowser({ ...launchConfig, ...agentBrowserOpts, scope });\n }\n\n throw new Error(`Unsupported browser provider: ${provider}`);\n}\n"],"mappings":"AAMA,SAAS,YAAY,WAAW,cAAc,qBAAqB;AACnE,SAAS,SAAS,YAAY;AAG9B,SAAS,mBAAmB;AAC5B,SAAS,0BAA0B,6BAA6B;AAChE,SAAS,qBAAqB;AAC9B,SAAS,sBAAsB,uBAAuB;AAkD/C,MAAM,0BAA0B;AAGhC,MAAM,6BAA6B;AAGnC,MAAM,0BAA0B;AAGhC,MAAM,6BAA6B;AA8MnC,MAAM,4BAA4B;AAElC,MAAM,mBAAoC;AAAA,EAC/C,SAAS;AAAA,EACT,QAAQ,CAAC;AAAA,EACT,IAAI,CAAC;AACP;AAGO,SAAS,qBAAkC;AAChD,SAAO,QAAQ,aAAa,WAAW,iBAAiB;AAC1D;AAEA,MAAM,WAA2B;AAAA,EAC/B,YAAY;AAAA,IACV,aAAa;AAAA,IACb,WAAW;AAAA,IACX,SAAS;AAAA,IACT,YAAY;AAAA,IACZ,UAAU;AAAA,IACV,6BAA6B;AAAA,EAC/B;AAAA,EACA,QAAQ;AAAA,IACN,mBAAmB;AAAA,IACnB,cAAc,CAAC;AAAA,IACf,gBAAgB;AAAA,IAChB,iBAAiB;AAAA,IACjB,uBAAuB;AAAA,IACvB,wBAAwB;AAAA,IACxB,wBAAwB;AAAA,IACxB,uBAAuB;AAAA,IACvB,uBAAuB;AAAA,IACvB,sBAAsB;AAAA,IACtB,gBAAgB,CAAC;AAAA,IACjB,gBAAgB;AAAA,IAChB,cAAc;AAAA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C,UAAU,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CAOpF;AAED,wBAAgB,mBAAmB,CAAC,UAAU,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAE7E"}
1
+ {"version":3,"file":"dependencies.d.ts","sourceRoot":"","sources":["../../src/plugins/dependencies.ts"],"names":[],"mappings":"AAUA,MAAM,MAAM,6BAA6B,GAAG;IAC1C,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,KAAK,IAAI,CAAC;IAC5C,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB,CAAC;AAEF,wBAAsB,yBAAyB,CAC7C,UAAU,EAAE,MAAM,EAClB,WAAW,SAAa,EACxB,OAAO,GAAE,6BAAkC,GAC1C,OAAO,CAAC,OAAO,CAAC,CAqClB;AAED,wBAAsB,iCAAiC,CACrD,UAAU,EAAE,MAAM,EAClB,KAAK,EAAE,MAAM,EACb,OAAO,GAAE,6BAAkC,GAC1C,OAAO,CAAC,IAAI,CAAC,CAIf;AAED,wBAAgB,wBAAwB,CAAC,UAAU,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CAOpF;AAED,wBAAgB,mBAAmB,CAAC,UAAU,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAE7E"}
@@ -1,7 +1,6 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { execa } from "execa";
4
- const NON_INTERACTIVE_INSTALL_ENV = { ...process.env, GIT_TERMINAL_PROMPT: "0" };
5
4
  async function installPluginDependencies(pluginRoot, commandRoot = pluginRoot, options = {}) {
6
5
  const packageJsonPath = path.join(pluginRoot, "package.json");
7
6
  if (!fs.existsSync(packageJsonPath)) {
@@ -9,15 +8,12 @@ async function installPluginDependencies(pluginRoot, commandRoot = pluginRoot, o
9
8
  }
10
9
  const packageJson = readPackageJson(pluginRoot);
11
10
  const commandPackageJson = commandRoot === pluginRoot ? packageJson : readPackageJson(commandRoot);
12
- const installCommand2 = getInstallCommand(
13
- pluginRoot,
14
- typeof packageJson.packageManager === "string" ? packageJson.packageManager : void 0,
15
- commandRoot,
16
- typeof commandPackageJson.packageManager === "string" ? commandPackageJson.packageManager : void 0
17
- );
18
- const child = execa(installCommand2.command, installCommand2.args, {
11
+ const packageManager = Object.hasOwn(packageJson, "packageManager") ? packageJson.packageManager : commandPackageJson.packageManager;
12
+ const pnpmVersion = getPnpmVersion(pluginRoot, packageManager);
13
+ const installCommand = getInstallCommand(pluginRoot, pnpmVersion);
14
+ const child = execa(installCommand.command, installCommand.args, {
19
15
  cwd: pluginRoot,
20
- env: NON_INTERACTIVE_INSTALL_ENV,
16
+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
21
17
  stdout: options.onOutput ? "pipe" : "ignore",
22
18
  stderr: options.onOutput ? "pipe" : "ignore",
23
19
  cancelSignal: options.signal
@@ -31,7 +27,7 @@ async function installPluginDependencies(pluginRoot, commandRoot = pluginRoot, o
31
27
  } catch (error) {
32
28
  if (isCommandNotFoundError(error)) {
33
29
  throw new Error(
34
- `This plugin uses ${installCommand2.command}, but ${installCommand2.command} is not installed. Install ${installCommand2.command} and try again. Plugin path: ${pluginRoot}`,
30
+ 'Mastra Code requires Corepack to install GitHub plugin dependencies. Install it with "npm install --global corepack" and try again.',
35
31
  { cause: error }
36
32
  );
37
33
  }
@@ -72,63 +68,37 @@ function isInsideDirectory(targetPath, root) {
72
68
  const resolvedRoot = path.resolve(root);
73
69
  return resolvedTarget === resolvedRoot || resolvedTarget.startsWith(resolvedRoot + path.sep);
74
70
  }
75
- function getInstallCommand(pluginRoot, packageManager, commandRoot = pluginRoot, commandPackageManager) {
76
- const manager = packageManager ?? commandPackageManager;
77
- if (manager?.startsWith("pnpm@")) {
78
- return hasFile(pluginRoot, "pnpm-lock.yaml") ? installCommand("pnpm", ["install", "--ignore-workspace", "--frozen-lockfile", "--pm-on-fail=ignore"]) : installCommand("pnpm", ["install", "--ignore-workspace", "--pm-on-fail=ignore"]);
79
- }
80
- if (manager?.startsWith("npm@")) {
81
- return hasNpmLockfile(pluginRoot) ? installCommand("npm", ["ci"]) : installCommand("npm", ["install"]);
82
- }
83
- if (manager?.startsWith("yarn@")) {
84
- return hasFile(pluginRoot, "yarn.lock") ? installCommand("yarn", ["install", "--frozen-lockfile"]) : installCommand("yarn", ["install"]);
85
- }
86
- if (manager?.startsWith("bun@")) {
87
- return hasFile(pluginRoot, "bun.lock") || hasFile(pluginRoot, "bun.lockb") ? installCommand("bun", ["install", "--frozen-lockfile"]) : installCommand("bun", ["install"]);
88
- }
89
- if (manager) {
90
- return installCommand(manager.split("@")[0] ?? manager, ["install"]);
91
- }
92
- if (hasFile(pluginRoot, "pnpm-lock.yaml")) {
93
- return installCommand("pnpm", ["install", "--ignore-workspace", "--frozen-lockfile", "--pm-on-fail=ignore"]);
94
- }
95
- if (hasFile(commandRoot, "pnpm-lock.yaml")) {
96
- return installCommand("pnpm", ["install", "--ignore-workspace", "--pm-on-fail=ignore"]);
97
- }
98
- if (hasNpmLockfile(pluginRoot)) {
99
- return installCommand("npm", ["ci"]);
100
- }
101
- if (hasNpmLockfile(commandRoot)) {
102
- return installCommand("npm", ["install"]);
103
- }
104
- if (hasFile(pluginRoot, "yarn.lock")) {
105
- return installCommand("yarn", ["install", "--frozen-lockfile"]);
106
- }
107
- if (hasFile(commandRoot, "yarn.lock")) {
108
- return installCommand("yarn", ["install"]);
109
- }
110
- if (hasFile(pluginRoot, "bun.lock") || hasFile(pluginRoot, "bun.lockb")) {
111
- return installCommand("bun", ["install", "--frozen-lockfile"]);
112
- }
113
- if (hasFile(commandRoot, "bun.lock") || hasFile(commandRoot, "bun.lockb")) {
114
- return installCommand("bun", ["install"]);
115
- }
116
- return installCommand("npm", ["install"]);
71
+ function getPnpmVersion(pluginRoot, packageManager) {
72
+ if (typeof packageManager !== "string") {
73
+ throw new Error(
74
+ `Plugin at ${pluginRoot} must declare an exact pnpm version in package.json using "packageManager": "pnpm@x.y.z".`
75
+ );
76
+ }
77
+ const match = /^pnpm@(\d+\.\d+\.\d+)$/.exec(packageManager);
78
+ if (!match?.[1]) {
79
+ throw new Error(
80
+ `Plugin at ${pluginRoot} must declare an exact pnpm version in package.json using "packageManager": "pnpm@x.y.z".`
81
+ );
82
+ }
83
+ return match[1];
117
84
  }
118
- function installCommand(command, args) {
119
- return { command, args: [...args, "--ignore-scripts"] };
85
+ function getInstallCommand(pluginRoot, pnpmVersion) {
86
+ const installArgs = ["install", "--ignore-workspace"];
87
+ if (hasFile(pluginRoot, "pnpm-lock.yaml")) installArgs.push("--frozen-lockfile");
88
+ installArgs.push("--ignore-scripts");
89
+ return {
90
+ command: "corepack",
91
+ args: [`pnpm@${pnpmVersion}`, ...installArgs]
92
+ };
120
93
  }
121
94
  function isCommandNotFoundError(error) {
122
- return typeof error === "object" && error !== null && error.code === "ENOENT";
95
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
123
96
  }
124
97
  function readPackageJson(pluginRoot) {
125
98
  const packageJsonPath = path.join(pluginRoot, "package.json");
126
99
  if (!fs.existsSync(packageJsonPath)) return {};
127
100
  return JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
128
101
  }
129
- function hasNpmLockfile(pluginRoot) {
130
- return hasFile(pluginRoot, "package-lock.json") || hasFile(pluginRoot, "npm-shrinkwrap.json");
131
- }
132
102
  function hasFile(pluginRoot, fileName) {
133
103
  return fs.existsSync(path.join(pluginRoot, fileName));
134
104
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/plugins/dependencies.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { execa } from 'execa';\n\nconst NON_INTERACTIVE_INSTALL_ENV = { ...process.env, GIT_TERMINAL_PROMPT: '0' };\n\ntype InstallCommand = {\n command: string;\n args: string[];\n};\n\nexport type PluginInstallExecutionOptions = {\n onOutput?: (chunk: Buffer | string) => void;\n signal?: AbortSignal;\n};\n\nexport async function installPluginDependencies(\n pluginRoot: string,\n commandRoot = pluginRoot,\n options: PluginInstallExecutionOptions = {},\n): Promise<boolean> {\n const packageJsonPath = path.join(pluginRoot, 'package.json');\n if (!fs.existsSync(packageJsonPath)) {\n return false;\n }\n\n const packageJson = readPackageJson(pluginRoot);\n const commandPackageJson = commandRoot === pluginRoot ? packageJson : readPackageJson(commandRoot);\n const installCommand = getInstallCommand(\n pluginRoot,\n typeof packageJson.packageManager === 'string' ? packageJson.packageManager : undefined,\n commandRoot,\n typeof commandPackageJson.packageManager === 'string' ? commandPackageJson.packageManager : undefined,\n );\n\n const child = execa(installCommand.command, installCommand.args, {\n cwd: pluginRoot,\n env: NON_INTERACTIVE_INSTALL_ENV,\n stdout: options.onOutput ? 'pipe' : 'ignore',\n stderr: options.onOutput ? 'pipe' : 'ignore',\n cancelSignal: options.signal,\n });\n if (options.onOutput) {\n child.stdout?.on('data', options.onOutput);\n child.stderr?.on('data', options.onOutput);\n }\n try {\n await child;\n } catch (error) {\n if (isCommandNotFoundError(error)) {\n throw new Error(\n `This plugin uses ${installCommand.command}, but ${installCommand.command} is not installed. Install ${installCommand.command} and try again. Plugin path: ${pluginRoot}`,\n { cause: error },\n );\n }\n throw error;\n }\n return true;\n}\n\nexport async function installPluginDependenciesForEntry(\n pluginRoot: string,\n entry: string,\n options: PluginInstallExecutionOptions = {},\n): Promise<void> {\n for (const dependencyRoot of getPluginDependencyRoots(pluginRoot, entry)) {\n await installPluginDependencies(dependencyRoot, pluginRoot, options);\n }\n}\n\nexport function getPluginDependencyRoots(pluginRoot: string, entry: string): string[] {\n const roots = fs.existsSync(path.join(pluginRoot, 'package.json')) ? [pluginRoot] : [];\n const entryPackageRoot = findEntryPackageRoot(pluginRoot, entry);\n if (entryPackageRoot && entryPackageRoot !== pluginRoot) {\n roots.push(entryPackageRoot);\n }\n return roots;\n}\n\nexport function getEntryPackageRoot(pluginRoot: string, entry: string): string {\n return findEntryPackageRoot(pluginRoot, entry) ?? pluginRoot;\n}\n\nfunction findEntryPackageRoot(pluginRoot: string, entry: string): string | undefined {\n const root = path.resolve(pluginRoot);\n let current = path.dirname(path.resolve(pluginRoot, entry));\n\n while (isInsideDirectory(current, root)) {\n if (fs.existsSync(path.join(current, 'package.json'))) {\n return current;\n }\n if (current === root) break;\n current = path.dirname(current);\n }\n\n return undefined;\n}\n\nfunction isInsideDirectory(targetPath: string, root: string): boolean {\n const resolvedTarget = path.resolve(targetPath);\n const resolvedRoot = path.resolve(root);\n return resolvedTarget === resolvedRoot || resolvedTarget.startsWith(resolvedRoot + path.sep);\n}\n\nfunction getInstallCommand(\n pluginRoot: string,\n packageManager?: string,\n commandRoot = pluginRoot,\n commandPackageManager?: string,\n): InstallCommand {\n const manager = packageManager ?? commandPackageManager;\n\n if (manager?.startsWith('pnpm@')) {\n return hasFile(pluginRoot, 'pnpm-lock.yaml')\n ? installCommand('pnpm', ['install', '--ignore-workspace', '--frozen-lockfile', '--pm-on-fail=ignore'])\n : installCommand('pnpm', ['install', '--ignore-workspace', '--pm-on-fail=ignore']);\n }\n\n if (manager?.startsWith('npm@')) {\n return hasNpmLockfile(pluginRoot) ? installCommand('npm', ['ci']) : installCommand('npm', ['install']);\n }\n\n if (manager?.startsWith('yarn@')) {\n return hasFile(pluginRoot, 'yarn.lock')\n ? installCommand('yarn', ['install', '--frozen-lockfile'])\n : installCommand('yarn', ['install']);\n }\n\n if (manager?.startsWith('bun@')) {\n return hasFile(pluginRoot, 'bun.lock') || hasFile(pluginRoot, 'bun.lockb')\n ? installCommand('bun', ['install', '--frozen-lockfile'])\n : installCommand('bun', ['install']);\n }\n\n if (manager) {\n return installCommand(manager.split('@')[0] ?? manager, ['install']);\n }\n\n if (hasFile(pluginRoot, 'pnpm-lock.yaml')) {\n return installCommand('pnpm', ['install', '--ignore-workspace', '--frozen-lockfile', '--pm-on-fail=ignore']);\n }\n\n if (hasFile(commandRoot, 'pnpm-lock.yaml')) {\n return installCommand('pnpm', ['install', '--ignore-workspace', '--pm-on-fail=ignore']);\n }\n\n if (hasNpmLockfile(pluginRoot)) {\n return installCommand('npm', ['ci']);\n }\n\n if (hasNpmLockfile(commandRoot)) {\n return installCommand('npm', ['install']);\n }\n\n if (hasFile(pluginRoot, 'yarn.lock')) {\n return installCommand('yarn', ['install', '--frozen-lockfile']);\n }\n\n if (hasFile(commandRoot, 'yarn.lock')) {\n return installCommand('yarn', ['install']);\n }\n\n if (hasFile(pluginRoot, 'bun.lock') || hasFile(pluginRoot, 'bun.lockb')) {\n return installCommand('bun', ['install', '--frozen-lockfile']);\n }\n\n if (hasFile(commandRoot, 'bun.lock') || hasFile(commandRoot, 'bun.lockb')) {\n return installCommand('bun', ['install']);\n }\n\n return installCommand('npm', ['install']);\n}\n\nfunction installCommand(command: string, args: string[]): InstallCommand {\n return { command, args: [...args, '--ignore-scripts'] };\n}\n\nfunction isCommandNotFoundError(error: unknown): boolean {\n return typeof error === 'object' && error !== null && (error as { code?: unknown }).code === 'ENOENT';\n}\n\nfunction readPackageJson(pluginRoot: string): { packageManager?: unknown } {\n const packageJsonPath = path.join(pluginRoot, 'package.json');\n if (!fs.existsSync(packageJsonPath)) return {};\n return JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')) as { packageManager?: unknown };\n}\n\nfunction hasNpmLockfile(pluginRoot: string): boolean {\n return hasFile(pluginRoot, 'package-lock.json') || hasFile(pluginRoot, 'npm-shrinkwrap.json');\n}\n\nfunction hasFile(pluginRoot: string, fileName: string): boolean {\n return fs.existsSync(path.join(pluginRoot, fileName));\n}\n"],"mappings":"AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AAEjB,SAAS,aAAa;AAEtB,MAAM,8BAA8B,EAAE,GAAG,QAAQ,KAAK,qBAAqB,IAAI;AAY/E,eAAsB,0BACpB,YACA,cAAc,YACd,UAAyC,CAAC,GACxB;AAClB,QAAM,kBAAkB,KAAK,KAAK,YAAY,cAAc;AAC5D,MAAI,CAAC,GAAG,WAAW,eAAe,GAAG;A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AiB,MAAgC;AACvE,SAAO,EAAE,SAAS,MAAM,CAAC,GAAG,MAAM,kBAAkB,EAAE;AACxD;AAEA,SAAS,uBAAuB,OAAyB;AACvD,SAAO,OAAO,UAAU,YAAY,UAAU,QAAS,MAA6B,SAAS;AAC/F;AAEA,SAAS,gBAAgB,YAAkD;AACzE,QAAM,kBAAkB,KAAK,KAAK,YAAY,cAAc;AAC5D,MAAI,CAAC,GAAG,WAAW,eAAe,EAAG,QAAO,CAAC;AAC7C,SAAO,KAAK,MAAM,GAAG,aAAa,iBAAiB,MAAM,CAAC;AAC5D;AAEA,SAAS,eAAe,YAA6B;AACnD,SAAO,QAAQ,YAAY,mBAAmB,KAAK,QAAQ,YAAY,qBAAqB;AAC9F;AAEA,SAAS,QAAQ,YAAoB,UAA2B;AAC9D,SAAO,GAAG,WAAW,KAAK,KAAK,YAAY,QAAQ,CAAC;AACtD;","names":["installCommand"]}
1
+ {"version":3,"sources":["../../src/plugins/dependencies.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { execa } from 'execa';\n\ntype InstallCommand = {\n command: string;\n args: string[];\n};\n\nexport type PluginInstallExecutionOptions = {\n onOutput?: (chunk: Buffer | string) => void;\n signal?: AbortSignal;\n};\n\nexport async function installPluginDependencies(\n pluginRoot: string,\n commandRoot = pluginRoot,\n options: PluginInstallExecutionOptions = {},\n): Promise<boolean> {\n const packageJsonPath = path.join(pluginRoot, 'package.json');\n if (!fs.existsSync(packageJsonPath)) {\n return false;\n }\n\n const packageJson = readPackageJson(pluginRoot);\n const commandPackageJson = commandRoot === pluginRoot ? packageJson : readPackageJson(commandRoot);\n const packageManager = Object.hasOwn(packageJson, 'packageManager')\n ? packageJson.packageManager\n : commandPackageJson.packageManager;\n const pnpmVersion = getPnpmVersion(pluginRoot, packageManager);\n const installCommand = getInstallCommand(pluginRoot, pnpmVersion);\n\n const child = execa(installCommand.command, installCommand.args, {\n cwd: pluginRoot,\n env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },\n stdout: options.onOutput ? 'pipe' : 'ignore',\n stderr: options.onOutput ? 'pipe' : 'ignore',\n cancelSignal: options.signal,\n });\n if (options.onOutput) {\n child.stdout?.on('data', options.onOutput);\n child.stderr?.on('data', options.onOutput);\n }\n try {\n await child;\n } catch (error) {\n if (isCommandNotFoundError(error)) {\n throw new Error(\n 'Mastra Code requires Corepack to install GitHub plugin dependencies. Install it with \"npm install --global corepack\" and try again.',\n { cause: error },\n );\n }\n throw error;\n }\n return true;\n}\n\nexport async function installPluginDependenciesForEntry(\n pluginRoot: string,\n entry: string,\n options: PluginInstallExecutionOptions = {},\n): Promise<void> {\n for (const dependencyRoot of getPluginDependencyRoots(pluginRoot, entry)) {\n await installPluginDependencies(dependencyRoot, pluginRoot, options);\n }\n}\n\nexport function getPluginDependencyRoots(pluginRoot: string, entry: string): string[] {\n const roots = fs.existsSync(path.join(pluginRoot, 'package.json')) ? [pluginRoot] : [];\n const entryPackageRoot = findEntryPackageRoot(pluginRoot, entry);\n if (entryPackageRoot && entryPackageRoot !== pluginRoot) {\n roots.push(entryPackageRoot);\n }\n return roots;\n}\n\nexport function getEntryPackageRoot(pluginRoot: string, entry: string): string {\n return findEntryPackageRoot(pluginRoot, entry) ?? pluginRoot;\n}\n\nfunction findEntryPackageRoot(pluginRoot: string, entry: string): string | undefined {\n const root = path.resolve(pluginRoot);\n let current = path.dirname(path.resolve(pluginRoot, entry));\n\n while (isInsideDirectory(current, root)) {\n if (fs.existsSync(path.join(current, 'package.json'))) {\n return current;\n }\n if (current === root) break;\n current = path.dirname(current);\n }\n\n return undefined;\n}\n\nfunction isInsideDirectory(targetPath: string, root: string): boolean {\n const resolvedTarget = path.resolve(targetPath);\n const resolvedRoot = path.resolve(root);\n return resolvedTarget === resolvedRoot || resolvedTarget.startsWith(resolvedRoot + path.sep);\n}\n\nfunction getPnpmVersion(pluginRoot: string, packageManager: unknown): string {\n if (typeof packageManager !== 'string') {\n throw new Error(\n `Plugin at ${pluginRoot} must declare an exact pnpm version in package.json using \"packageManager\": \"pnpm@x.y.z\".`,\n );\n }\n\n const match = /^pnpm@(\\d+\\.\\d+\\.\\d+)$/.exec(packageManager);\n if (!match?.[1]) {\n throw new Error(\n `Plugin at ${pluginRoot} must declare an exact pnpm version in package.json using \"packageManager\": \"pnpm@x.y.z\".`,\n );\n }\n return match[1];\n}\n\nfunction getInstallCommand(pluginRoot: string, pnpmVersion: string): InstallCommand {\n const installArgs = ['install', '--ignore-workspace'];\n if (hasFile(pluginRoot, 'pnpm-lock.yaml')) installArgs.push('--frozen-lockfile');\n installArgs.push('--ignore-scripts');\n\n return {\n command: 'corepack',\n args: [`pnpm@${pnpmVersion}`, ...installArgs],\n };\n}\n\nfunction isCommandNotFoundError(error: unknown): boolean {\n return typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT';\n}\n\nfunction readPackageJson(pluginRoot: string): { packageManager?: unknown } {\n const packageJsonPath = path.join(pluginRoot, 'package.json');\n if (!fs.existsSync(packageJsonPath)) return {};\n return JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')) as { packageManager?: unknown };\n}\n\nfunction hasFile(pluginRoot: string, fileName: string): boolean {\n return fs.existsSync(path.join(pluginRoot, fileName));\n}\n"],"mappings":"AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AAEjB,SAAS,aAAa;AAYtB,eAAsB,0BACpB,YACA,cAAc,YACd,UAAyC,CAAC,GACxB;AAClB,QAAM,kBAAkB,KAAK,KAAK,YAAY,cAAc;AAC5D,MAAI,CAAC,GAAG,WAAW,eAAe,GAAG;AACnC,WAAO;AAAA,EACT;AAEA,QAAM,cAAc,gBAAgB,UAAU;AAC9C,QAAM,qBAAqB,gBAAgB,aAAa,cAAc,gBAAgB,WAAW;AACjG,QAAM,iBAAiB,OAAO,OAAO,aAAa,gBAAgB,IAC9D,YAAY,iBACZ,mBAAmB;AACvB,QAAM,cAAc,eAAe,YAAY,cAAc;AAC7D,QAAM,iBAAiB,kBAAkB,YAAY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AAQ,YAAoB,UAA2B;AAC9D,SAAO,GAAG,WAAW,KAAK,KAAK,YAAY,QAAQ,CAAC;AACtD;","names":[]}
@@ -0,0 +1,2 @@
1
+ export declare function isPathWithinRoot(candidatePath: string, rootPath: string): boolean;
2
+ //# sourceMappingURL=path-security.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"path-security.d.ts","sourceRoot":"","sources":["../../src/utils/path-security.ts"],"names":[],"mappings":"AAEA,wBAAgB,gBAAgB,CAAC,aAAa,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAMjF"}
@@ -0,0 +1,9 @@
1
+ import path from "node:path";
2
+ function isPathWithinRoot(candidatePath, rootPath) {
3
+ const relativePath = path.relative(rootPath, candidatePath);
4
+ return relativePath === "" || !relativePath.startsWith(`..${path.sep}`) && relativePath !== ".." && !path.isAbsolute(relativePath);
5
+ }
6
+ export {
7
+ isPathWithinRoot
8
+ };
9
+ //# sourceMappingURL=path-security.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/utils/path-security.ts"],"sourcesContent":["import path from 'node:path';\n\nexport function isPathWithinRoot(candidatePath: string, rootPath: string): boolean {\n const relativePath = path.relative(rootPath, candidatePath);\n return (\n relativePath === '' ||\n (!relativePath.startsWith(`..${path.sep}`) && relativePath !== '..' && !path.isAbsolute(relativePath))\n );\n}\n"],"mappings":"AAAA,OAAO,UAAU;AAEV,SAAS,iBAAiB,eAAuB,UAA2B;AACjF,QAAM,eAAe,KAAK,SAAS,UAAU,aAAa;AAC1D,SACE,iBAAiB,MAChB,CAAC,aAAa,WAAW,KAAK,KAAK,GAAG,EAAE,KAAK,iBAAiB,QAAQ,CAAC,KAAK,WAAW,YAAY;AAExG;","names":[]}
@@ -31,7 +31,11 @@ export declare function extractCommandName(filePath: string, baseDir: string): s
31
31
  * @param rootDir - Original root commands directory (used for namespace derivation).
32
32
  * When omitted the first call sets it to dirPath.
33
33
  */
34
- export declare function scanCommandDirectory(dirPath: string, rootDir?: string): Promise<SlashCommandMetadata[]>;
34
+ export interface ScanCommandDirectoryOptions {
35
+ allowedRoot?: string;
36
+ visitedDirectories?: Set<string>;
37
+ }
38
+ export declare function scanCommandDirectory(dirPath: string, rootDir?: string, options?: ScanCommandDirectoryOptions): Promise<SlashCommandMetadata[]>;
35
39
  /**
36
40
  * Load custom slash commands from all configured directories
37
41
  * Priority: mastra project > claude project > opencode project > mastra user > claude user > opencode user
@@ -1 +1 @@
1
- {"version":3,"file":"slash-command-loader.d.ts","sourceRoot":"","sources":["../../src/utils/slash-command-loader.ts"],"names":[],"mappings":"AAKA;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACnC,wCAAwC;IACxC,IAAI,EAAE,MAAM,CAAC;IACb,iCAAiC;IACjC,WAAW,EAAE,MAAM,CAAC;IACpB,0CAA0C;IAC1C,QAAQ,EAAE,MAAM,CAAC;IACjB,uBAAuB;IACvB,UAAU,EAAE,MAAM,CAAC;IACnB,iDAAiD;IACjD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,kEAAkE;IAClE,IAAI,CAAC,EAAE,OAAO,CAAC;CAChB;AAED;;;GAGG;AACH,wBAAsB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,oBAAoB,GAAG,IAAI,CAAC,CAqD/G;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAY5E;AAED;;;;;GAKG;AACH,wBAAsB,oBAAoB,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,oBAAoB,EAAE,CAAC,CA2B7G;AACD;;;GAGG;AACH,wBAAsB,kBAAkB,CACtC,UAAU,CAAC,EAAE,MAAM,EACnB,aAAa,SAAqB,EAClC,gBAAgB,GAAE,MAAM,EAAO,GAC9B,OAAO,CAAC,oBAAoB,EAAE,CAAC,CA4DjC;AAED;;GAEG;AACH,wBAAgB,qBAAqB,CAAC,UAAU,EAAE,MAAM,EAAE,aAAa,SAAqB,GAAG,MAAM,CAEpG;AAED;;GAEG;AACH,wBAAsB,qBAAqB,CAAC,UAAU,EAAE,MAAM,EAAE,aAAa,SAAqB,GAAG,OAAO,CAAC,IAAI,CAAC,CA4BjH"}
1
+ {"version":3,"file":"slash-command-loader.d.ts","sourceRoot":"","sources":["../../src/utils/slash-command-loader.ts"],"names":[],"mappings":"AAMA;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACnC,wCAAwC;IACxC,IAAI,EAAE,MAAM,CAAC;IACb,iCAAiC;IACjC,WAAW,EAAE,MAAM,CAAC;IACpB,0CAA0C;IAC1C,QAAQ,EAAE,MAAM,CAAC;IACjB,uBAAuB;IACvB,UAAU,EAAE,MAAM,CAAC;IACnB,iDAAiD;IACjD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,kEAAkE;IAClE,IAAI,CAAC,EAAE,OAAO,CAAC;CAChB;AAED;;;GAGG;AACH,wBAAsB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,oBAAoB,GAAG,IAAI,CAAC,CAqD/G;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAY5E;AAED;;;;;GAKG;AACH,MAAM,WAAW,2BAA2B;IAC1C,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,kBAAkB,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;CAClC;AAED,wBAAsB,oBAAoB,CACxC,OAAO,EAAE,MAAM,EACf,OAAO,CAAC,EAAE,MAAM,EAChB,OAAO,GAAE,2BAAgC,GACxC,OAAO,CAAC,oBAAoB,EAAE,CAAC,CA4CjC;AACD;;;GAGG;AACH,wBAAsB,kBAAkB,CACtC,UAAU,CAAC,EA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