@within-7/minto 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (254) hide show
  1. package/dist/commands/agents/AgentsCommand.js +22 -24
  2. package/dist/commands/agents/AgentsCommand.js.map +2 -2
  3. package/dist/commands/context.js +2 -1
  4. package/dist/commands/context.js.map +2 -2
  5. package/dist/commands/export.js +2 -1
  6. package/dist/commands/export.js.map +2 -2
  7. package/dist/commands/mcp-interactive.js +7 -6
  8. package/dist/commands/mcp-interactive.js.map +2 -2
  9. package/dist/commands/model.js +3 -2
  10. package/dist/commands/model.js.map +2 -2
  11. package/dist/commands/permissions.js +4 -3
  12. package/dist/commands/permissions.js.map +2 -2
  13. package/dist/commands/plugin/AddMarketplaceForm.js +3 -2
  14. package/dist/commands/plugin/AddMarketplaceForm.js.map +2 -2
  15. package/dist/commands/plugin/ConfirmDialog.js +2 -1
  16. package/dist/commands/plugin/ConfirmDialog.js.map +2 -2
  17. package/dist/commands/plugin/ErrorView.js +2 -1
  18. package/dist/commands/plugin/ErrorView.js.map +2 -2
  19. package/dist/commands/plugin/InstalledPluginsByMarketplace.js +5 -4
  20. package/dist/commands/plugin/InstalledPluginsByMarketplace.js.map +2 -2
  21. package/dist/commands/plugin/InstalledPluginsManager.js +5 -4
  22. package/dist/commands/plugin/InstalledPluginsManager.js.map +2 -2
  23. package/dist/commands/plugin/MainMenu.js +2 -1
  24. package/dist/commands/plugin/MainMenu.js.map +2 -2
  25. package/dist/commands/plugin/MarketplaceManager.js +5 -4
  26. package/dist/commands/plugin/MarketplaceManager.js.map +2 -2
  27. package/dist/commands/plugin/MarketplaceSelector.js +4 -3
  28. package/dist/commands/plugin/MarketplaceSelector.js.map +2 -2
  29. package/dist/commands/plugin/PlaceholderScreen.js +3 -2
  30. package/dist/commands/plugin/PlaceholderScreen.js.map +2 -2
  31. package/dist/commands/plugin/PluginBrowser.js +6 -5
  32. package/dist/commands/plugin/PluginBrowser.js.map +2 -2
  33. package/dist/commands/plugin/PluginDetailsInstall.js +5 -4
  34. package/dist/commands/plugin/PluginDetailsInstall.js.map +2 -2
  35. package/dist/commands/plugin/PluginDetailsManage.js +4 -3
  36. package/dist/commands/plugin/PluginDetailsManage.js.map +2 -2
  37. package/dist/commands/plugin.js +16 -15
  38. package/dist/commands/plugin.js.map +2 -2
  39. package/dist/commands/sandbox.js +4 -3
  40. package/dist/commands/sandbox.js.map +2 -2
  41. package/dist/commands/setup.js +2 -1
  42. package/dist/commands/setup.js.map +2 -2
  43. package/dist/commands/status.js +2 -1
  44. package/dist/commands/status.js.map +2 -2
  45. package/dist/commands/undo.js +245 -0
  46. package/dist/commands/undo.js.map +7 -0
  47. package/dist/commands.js +2 -0
  48. package/dist/commands.js.map +2 -2
  49. package/dist/components/AgentThinkingBlock.js +1 -1
  50. package/dist/components/AgentThinkingBlock.js.map +2 -2
  51. package/dist/components/AsciiLogo.js +7 -8
  52. package/dist/components/AsciiLogo.js.map +2 -2
  53. package/dist/components/AskUserQuestionDialog/AskUserQuestionDialog.js +3 -2
  54. package/dist/components/AskUserQuestionDialog/AskUserQuestionDialog.js.map +2 -2
  55. package/dist/components/AskUserQuestionDialog/QuestionView.js +2 -1
  56. package/dist/components/AskUserQuestionDialog/QuestionView.js.map +2 -2
  57. package/dist/components/CollapsibleHint.js +2 -1
  58. package/dist/components/CollapsibleHint.js.map +2 -2
  59. package/dist/components/Config.js +3 -2
  60. package/dist/components/Config.js.map +2 -2
  61. package/dist/components/ConsoleOAuthFlow.js +2 -1
  62. package/dist/components/ConsoleOAuthFlow.js.map +2 -2
  63. package/dist/components/Cost.js +2 -1
  64. package/dist/components/Cost.js.map +2 -2
  65. package/dist/components/HeaderBar.js +13 -8
  66. package/dist/components/HeaderBar.js.map +2 -2
  67. package/dist/components/HistorySearchOverlay.js +4 -3
  68. package/dist/components/HistorySearchOverlay.js.map +2 -2
  69. package/dist/components/HotkeyHelpPanel.js +8 -11
  70. package/dist/components/HotkeyHelpPanel.js.map +2 -2
  71. package/dist/components/InvalidConfigDialog.js +2 -1
  72. package/dist/components/InvalidConfigDialog.js.map +2 -2
  73. package/dist/components/Logo.js +23 -67
  74. package/dist/components/Logo.js.map +2 -2
  75. package/dist/components/MCPServerApprovalDialog.js +2 -1
  76. package/dist/components/MCPServerApprovalDialog.js.map +2 -2
  77. package/dist/components/MCPServerDialogCopy.js +2 -1
  78. package/dist/components/MCPServerDialogCopy.js.map +2 -2
  79. package/dist/components/MCPServerMultiselectDialog.js +2 -1
  80. package/dist/components/MCPServerMultiselectDialog.js.map +2 -2
  81. package/dist/components/MessageSelector.js +4 -3
  82. package/dist/components/MessageSelector.js.map +2 -2
  83. package/dist/components/ModeIndicator.js +2 -1
  84. package/dist/components/ModeIndicator.js.map +2 -2
  85. package/dist/components/ModelConfig.js +4 -3
  86. package/dist/components/ModelConfig.js.map +2 -2
  87. package/dist/components/ModelListManager.js +4 -3
  88. package/dist/components/ModelListManager.js.map +2 -2
  89. package/dist/components/ModelSelector/ModelSelector.js +26 -13
  90. package/dist/components/ModelSelector/ModelSelector.js.map +2 -2
  91. package/dist/components/Onboarding.js +3 -2
  92. package/dist/components/Onboarding.js.map +2 -2
  93. package/dist/components/OperationSummary.js +130 -0
  94. package/dist/components/OperationSummary.js.map +7 -0
  95. package/dist/components/PromptInput.js +88 -75
  96. package/dist/components/PromptInput.js.map +2 -2
  97. package/dist/components/SensitiveFileWarning.js +31 -0
  98. package/dist/components/SensitiveFileWarning.js.map +7 -0
  99. package/dist/components/Spinner.js +71 -22
  100. package/dist/components/Spinner.js.map +2 -2
  101. package/dist/components/StructuredDiff.js +6 -8
  102. package/dist/components/StructuredDiff.js.map +2 -2
  103. package/dist/components/SubagentBlock.js +4 -2
  104. package/dist/components/SubagentBlock.js.map +2 -2
  105. package/dist/components/SubagentProgress.js +7 -4
  106. package/dist/components/SubagentProgress.js.map +2 -2
  107. package/dist/components/TaskCard.js +14 -11
  108. package/dist/components/TaskCard.js.map +2 -2
  109. package/dist/components/TextInput.js +9 -1
  110. package/dist/components/TextInput.js.map +2 -2
  111. package/dist/components/TodoPanel.js +44 -26
  112. package/dist/components/TodoPanel.js.map +2 -2
  113. package/dist/components/ToolUseLoader.js +2 -2
  114. package/dist/components/ToolUseLoader.js.map +2 -2
  115. package/dist/components/TreeConnector.js +4 -3
  116. package/dist/components/TreeConnector.js.map +2 -2
  117. package/dist/components/TrustDialog.js +2 -1
  118. package/dist/components/TrustDialog.js.map +2 -2
  119. package/dist/components/binary-feedback/BinaryFeedbackView.js +2 -1
  120. package/dist/components/binary-feedback/BinaryFeedbackView.js.map +2 -2
  121. package/dist/components/messages/AssistantTextMessage.js +17 -9
  122. package/dist/components/messages/AssistantTextMessage.js.map +2 -2
  123. package/dist/components/messages/AssistantToolUseMessage.js +8 -4
  124. package/dist/components/messages/AssistantToolUseMessage.js.map +2 -2
  125. package/dist/components/messages/GroupRenderer.js +2 -1
  126. package/dist/components/messages/GroupRenderer.js.map +2 -2
  127. package/dist/components/messages/NestedTasksPreview.js +13 -1
  128. package/dist/components/messages/NestedTasksPreview.js.map +2 -2
  129. package/dist/components/messages/ParallelTasksGroupView.js +4 -3
  130. package/dist/components/messages/ParallelTasksGroupView.js.map +2 -2
  131. package/dist/components/messages/TaskInModuleView.js +35 -15
  132. package/dist/components/messages/TaskInModuleView.js.map +2 -2
  133. package/dist/components/messages/TaskOutputContent.js +9 -6
  134. package/dist/components/messages/TaskOutputContent.js.map +2 -2
  135. package/dist/components/messages/UserPromptMessage.js +2 -2
  136. package/dist/components/messages/UserPromptMessage.js.map +2 -2
  137. package/dist/constants/colors.js +90 -72
  138. package/dist/constants/colors.js.map +2 -2
  139. package/dist/constants/toolInputExamples.js +84 -0
  140. package/dist/constants/toolInputExamples.js.map +7 -0
  141. package/dist/core/backupManager.js +321 -0
  142. package/dist/core/backupManager.js.map +7 -0
  143. package/dist/core/costTracker.js +9 -18
  144. package/dist/core/costTracker.js.map +2 -2
  145. package/dist/core/gitAutoCommit.js +287 -0
  146. package/dist/core/gitAutoCommit.js.map +7 -0
  147. package/dist/core/index.js +3 -0
  148. package/dist/core/index.js.map +2 -2
  149. package/dist/core/operationTracker.js +212 -0
  150. package/dist/core/operationTracker.js.map +7 -0
  151. package/dist/core/permissions/rules/allowedToolsRule.js +1 -1
  152. package/dist/core/permissions/rules/allowedToolsRule.js.map +2 -2
  153. package/dist/core/permissions/rules/autoEscalationRule.js +5 -0
  154. package/dist/core/permissions/rules/autoEscalationRule.js.map +2 -2
  155. package/dist/core/permissions/rules/projectBoundaryRule.js +5 -0
  156. package/dist/core/permissions/rules/projectBoundaryRule.js.map +2 -2
  157. package/dist/core/permissions/rules/sensitivePathsRule.js +5 -0
  158. package/dist/core/permissions/rules/sensitivePathsRule.js.map +2 -2
  159. package/dist/core/tokenStats.js +9 -0
  160. package/dist/core/tokenStats.js.map +7 -0
  161. package/dist/core/tokenStatsManager.js +331 -0
  162. package/dist/core/tokenStatsManager.js.map +7 -0
  163. package/dist/entrypoints/cli.js +115 -87
  164. package/dist/entrypoints/cli.js.map +2 -2
  165. package/dist/hooks/useAgentTokenStats.js +72 -0
  166. package/dist/hooks/useAgentTokenStats.js.map +7 -0
  167. package/dist/hooks/useAgentTranscripts.js +30 -6
  168. package/dist/hooks/useAgentTranscripts.js.map +2 -2
  169. package/dist/hooks/useLogMessages.js +12 -1
  170. package/dist/hooks/useLogMessages.js.map +2 -2
  171. package/dist/i18n/locales/en.js +6 -5
  172. package/dist/i18n/locales/en.js.map +2 -2
  173. package/dist/i18n/locales/zh-CN.js +6 -5
  174. package/dist/i18n/locales/zh-CN.js.map +2 -2
  175. package/dist/i18n/types.js.map +1 -1
  176. package/dist/permissions.js +28 -1
  177. package/dist/permissions.js.map +2 -2
  178. package/dist/query.js +78 -4
  179. package/dist/query.js.map +3 -3
  180. package/dist/screens/REPL.js +23 -3
  181. package/dist/screens/REPL.js.map +2 -2
  182. package/dist/services/claude.js +54 -3
  183. package/dist/services/claude.js.map +2 -2
  184. package/dist/services/intelligentCompactor.js +1 -1
  185. package/dist/services/intelligentCompactor.js.map +2 -2
  186. package/dist/services/mcpClient.js +81 -25
  187. package/dist/services/mcpClient.js.map +2 -2
  188. package/dist/services/sandbox/filesystemBoundary.js +58 -17
  189. package/dist/services/sandbox/filesystemBoundary.js.map +2 -2
  190. package/dist/tools/AskExpertModelTool/AskExpertModelTool.js +3 -2
  191. package/dist/tools/AskExpertModelTool/AskExpertModelTool.js.map +2 -2
  192. package/dist/tools/AskUserQuestionTool/AskUserQuestionTool.js +2 -1
  193. package/dist/tools/AskUserQuestionTool/AskUserQuestionTool.js.map +2 -2
  194. package/dist/tools/BashTool/BashTool.js +22 -3
  195. package/dist/tools/BashTool/BashTool.js.map +2 -2
  196. package/dist/tools/BashTool/prompt.js +178 -34
  197. package/dist/tools/BashTool/prompt.js.map +2 -2
  198. package/dist/tools/FileEditTool/prompt.js +6 -3
  199. package/dist/tools/FileEditTool/prompt.js.map +2 -2
  200. package/dist/tools/FileWriteTool/prompt.js +4 -2
  201. package/dist/tools/FileWriteTool/prompt.js.map +2 -2
  202. package/dist/tools/MultiEditTool/prompt.js +5 -3
  203. package/dist/tools/MultiEditTool/prompt.js.map +2 -2
  204. package/dist/tools/NotebookEditTool/NotebookEditTool.js +2 -1
  205. package/dist/tools/NotebookEditTool/NotebookEditTool.js.map +2 -2
  206. package/dist/tools/PlanModeTool/EnterPlanModeTool.js +3 -2
  207. package/dist/tools/PlanModeTool/EnterPlanModeTool.js.map +2 -2
  208. package/dist/tools/PlanModeTool/ExitPlanModeTool.js +3 -2
  209. package/dist/tools/PlanModeTool/ExitPlanModeTool.js.map +2 -2
  210. package/dist/tools/PlanModeTool/prompt.js +1 -1
  211. package/dist/tools/PlanModeTool/prompt.js.map +1 -1
  212. package/dist/tools/SkillTool/SkillTool.js +4 -3
  213. package/dist/tools/SkillTool/SkillTool.js.map +2 -2
  214. package/dist/tools/SkillTool/prompt.js +1 -1
  215. package/dist/tools/SkillTool/prompt.js.map +1 -1
  216. package/dist/tools/TaskOutputTool/TaskOutputTool.js +3 -2
  217. package/dist/tools/TaskOutputTool/TaskOutputTool.js.map +2 -2
  218. package/dist/tools/TaskTool/TaskTool.js +8 -0
  219. package/dist/tools/TaskTool/TaskTool.js.map +2 -2
  220. package/dist/utils/CircuitBreaker.js +242 -0
  221. package/dist/utils/CircuitBreaker.js.map +7 -0
  222. package/dist/utils/ask.js +2 -0
  223. package/dist/utils/ask.js.map +2 -2
  224. package/dist/utils/config.js +47 -5
  225. package/dist/utils/config.js.map +2 -2
  226. package/dist/utils/credentials/CredentialStore.js +1 -0
  227. package/dist/utils/credentials/CredentialStore.js.map +7 -0
  228. package/dist/utils/credentials/EncryptedFileStore.js +157 -0
  229. package/dist/utils/credentials/EncryptedFileStore.js.map +7 -0
  230. package/dist/utils/credentials/index.js +37 -0
  231. package/dist/utils/credentials/index.js.map +7 -0
  232. package/dist/utils/credentials/migration.js +82 -0
  233. package/dist/utils/credentials/migration.js.map +7 -0
  234. package/dist/utils/markdown.js +13 -1
  235. package/dist/utils/markdown.js.map +2 -2
  236. package/dist/utils/permissions/filesystem.js +5 -1
  237. package/dist/utils/permissions/filesystem.js.map +2 -2
  238. package/dist/utils/safePath.js +132 -0
  239. package/dist/utils/safePath.js.map +7 -0
  240. package/dist/utils/sensitiveFiles.js +125 -0
  241. package/dist/utils/sensitiveFiles.js.map +7 -0
  242. package/dist/utils/taskDisplayUtils.js +9 -9
  243. package/dist/utils/taskDisplayUtils.js.map +2 -2
  244. package/dist/utils/theme.js +6 -6
  245. package/dist/utils/theme.js.map +1 -1
  246. package/dist/utils/toolRiskClassification.js +207 -0
  247. package/dist/utils/toolRiskClassification.js.map +7 -0
  248. package/dist/utils/tooling/safeRender.js +5 -4
  249. package/dist/utils/tooling/safeRender.js.map +2 -2
  250. package/dist/version.js +2 -2
  251. package/dist/version.js.map +1 -1
  252. package/package.json +9 -7
  253. package/dist/hooks/useCancelRequest.js +0 -31
  254. package/dist/hooks/useCancelRequest.js.map +0 -7
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/utils/config.ts"],
4
- "sourcesContent": ["import { existsSync, readFileSync, writeFileSync } from 'fs'\nimport { resolve, join } from 'path'\nimport { cloneDeep, memoize, pick } from 'lodash-es'\nimport { homedir } from 'os'\nimport { GLOBAL_CONFIG_FILE } from './env'\nimport { getCwd } from './state'\nimport { randomBytes } from 'crypto'\nimport { safeParseJSON } from './json'\nimport { ConfigParseError } from './errors'\nimport type { ThemeNames } from './theme'\nimport { debug as debugLogger } from './debugLogger'\nimport { getSessionState, setSessionState } from './sessionState'\nimport type { CompressionMode } from '@constants/compressionPrompts'\n\nexport type McpStdioServerConfig = {\n type?: 'stdio' // Optional for backwards compatibility\n command: string\n args: string[]\n env?: Record<string, string>\n enabled?: boolean\n}\n\nexport type McpSSEServerConfig = {\n type: 'sse'\n url: string\n enabled?: boolean\n}\n\nexport type McpServerConfig = McpStdioServerConfig | McpSSEServerConfig\n\n/**\n * Sandbox configuration for project-level security settings\n */\nexport type SandboxConfigData = {\n /** Whether sandboxing is enabled */\n enabled: boolean\n /** Filesystem access policy */\n filesystem?: {\n writeAllowed?: string[]\n readAllowed?: string[]\n denied?: string[]\n }\n /** Network access policy */\n network?: {\n allowedDomains?: string[]\n promptForNewDomains?: boolean\n blockAll?: boolean\n }\n /** Process isolation policy */\n process?: {\n excludedCommands?: string[]\n maxExecutionTime?: number\n }\n}\n\nexport type ProjectConfig = {\n allowedTools: string[]\n context: Record<string, string>\n contextFiles?: string[]\n history: string[]\n dontCrawlDirectory?: boolean\n enableArchitectTool?: boolean\n mcpContextUris: string[]\n mcpServers?: Record<string, McpServerConfig>\n approvedMcprcServers?: string[]\n rejectedMcprcServers?: string[]\n lastAPIDuration?: number\n lastCost?: number\n lastDuration?: number\n lastSessionId?: string\n exampleFiles?: string[]\n exampleFilesGeneratedAt?: number\n hasTrustDialogAccepted?: boolean\n hasCompletedProjectOnboarding?: boolean\n /** Sandbox configuration for command execution isolation */\n sandbox?: SandboxConfigData\n}\n\nconst DEFAULT_PROJECT_CONFIG: ProjectConfig = {\n allowedTools: [],\n context: {},\n history: [],\n dontCrawlDirectory: false,\n enableArchitectTool: false,\n mcpContextUris: [],\n mcpServers: {},\n approvedMcprcServers: [],\n rejectedMcprcServers: [],\n hasTrustDialogAccepted: false,\n}\n\nfunction defaultConfigForProject(projectPath: string): ProjectConfig {\n const config = { ...DEFAULT_PROJECT_CONFIG }\n if (projectPath === homedir()) {\n config.dontCrawlDirectory = true\n }\n return config\n}\n\nexport type AutoUpdaterStatus =\n | 'disabled'\n | 'enabled'\n | 'no_permissions'\n | 'not_configured'\n\nexport function isAutoUpdaterStatus(value: string): value is AutoUpdaterStatus {\n return ['disabled', 'enabled', 'no_permissions', 'not_configured'].includes(\n value as AutoUpdaterStatus,\n )\n}\n\nexport type NotificationChannel =\n | 'iterm2'\n | 'terminal_bell'\n | 'iterm2_with_bell'\n | 'notifications_disabled'\n\n/**\n * @deprecated Use verbose boolean instead. Kept for backward compatibility migration.\n */\nexport type DisplayMode = 'minimal' | 'compact' | 'detailed'\n\n/**\n * Supported UI languages\n */\nexport type UILanguage = 'en' | 'zh-CN'\n\n/**\n * Get verbose mode label (uses i18n)\n * Import dynamically to avoid circular dependency\n */\nexport function getVerboseLabel(verbose: boolean): string {\n // Dynamic import to avoid circular dependency at module load time\n try {\n const { t } = require('../i18n')\n return verbose ? t('ui.verbose.on') : t('ui.verbose.off')\n } catch {\n // Fallback if i18n not loaded yet\n return verbose ? 'Verbose: On' : 'Verbose: Off'\n }\n}\n\n/**\n * @deprecated Use getVerboseLabel() instead\n */\nexport function getDisplayModeLabel(mode: DisplayMode): string {\n return mode === 'detailed' ? 'Verbose: On' : 'Verbose: Off'\n}\n\n/**\n * @deprecated No longer needed - use verbose boolean directly\n */\nexport const DISPLAY_MODE_LABELS: Record<DisplayMode, string> = {\n minimal: 'Verbose: Off',\n compact: 'Verbose: Off',\n detailed: 'Verbose: On',\n}\n\n/**\n * @deprecated Use !verbose instead\n */\nexport function getNextDisplayMode(current: DisplayMode): DisplayMode {\n // Simply toggle between compact (off) and detailed (on)\n return current === 'detailed' ? 'compact' : 'detailed'\n}\n\n/**\n * Convert displayMode to verbose boolean for backward compatibility\n * @deprecated Components should use verbose directly\n */\nexport function displayModeToVerbose(mode: DisplayMode): boolean {\n return mode === 'detailed'\n}\n\n/**\n * Convert verbose boolean to displayMode for backward compatibility\n */\nexport function verboseToDisplayMode(verbose: boolean): DisplayMode {\n return verbose ? 'detailed' : 'compact'\n}\n\nexport type ProviderType =\n | 'anthropic'\n | 'openai'\n | 'mistral'\n | 'deepseek'\n | 'kimi'\n | 'qwen'\n | 'glm'\n | 'minimax'\n | 'baidu-qianfan'\n | 'siliconflow'\n | 'bigdream'\n | 'opendev'\n | 'xai'\n | 'groq'\n | 'gemini'\n | 'ollama'\n | 'azure'\n | 'custom'\n | 'custom-openai'\n\n// New model system types\nexport type ModelProfile = {\n name: string // User-friendly name\n provider: ProviderType // Provider type\n modelName: string // Primary key - actual model identifier\n baseURL?: string // Custom endpoint\n apiKey: string\n maxTokens: number // Output token limit (for GPT-5, this maps to max_completion_tokens)\n contextLength: number // Context window size\n reasoningEffort?: 'low' | 'medium' | 'high' | 'minimal' | 'medium'\n isActive: boolean // Whether profile is enabled\n createdAt: number // Creation timestamp\n lastUsed?: number // Last usage timestamp\n // \uD83D\uDD25 GPT-5 specific metadata\n isGPT5?: boolean // Auto-detected GPT-5 model flag\n validationStatus?: 'valid' | 'needs_repair' | 'auto_repaired' // Configuration status\n lastValidation?: number // Last validation timestamp\n}\n\n// Legacy type for config migration - includes deprecated 'id' field\ntype LegacyModelProfile = ModelProfile & {\n id?: string\n}\n\n// Legacy global config fields for migration\ntype LegacyGlobalConfigFields = {\n defaultModelId?: string\n defaultModelName?: string\n currentSelectedModelId?: string\n mainAgentModelId?: string\n taskToolModelId?: string\n}\n\nexport type ModelPointerType =\n | 'main'\n | 'task'\n | 'reasoning'\n | 'quick'\n | 'compact'\n\nexport type ModelPointers = {\n main: string // Main dialog model ID\n task: string // Task tool model ID\n reasoning: string // Reasoning model ID\n quick: string // Quick model ID\n compact: string // Compact/summary model ID (for context compression)\n}\n\nexport type AccountInfo = {\n accountUuid: string\n emailAddress: string\n organizationUuid?: string\n}\n\nexport type GlobalConfig = {\n projects?: Record<string, ProjectConfig>\n numStartups: number\n autoUpdaterStatus?: AutoUpdaterStatus\n userID?: string\n theme: ThemeNames\n hasCompletedOnboarding?: boolean\n // Tracks the last version that reset onboarding, used with MIN_VERSION_REQUIRING_ONBOARDING_RESET\n lastOnboardingVersion?: string\n // Tracks the last version for which release notes were seen, used for managing release notes\n lastReleaseNotesSeen?: string\n mcpServers?: Record<string, McpServerConfig>\n preferredNotifChannel: NotificationChannel\n /**\n * Verbose mode: shows full parameters and complete outputs when enabled\n * - false: Concise output (default)\n * - true: Detailed/verbose output\n */\n verbose: boolean\n /**\n * @deprecated Use verbose boolean instead. Kept for backward compatibility migration.\n */\n displayMode?: DisplayMode\n customApiKeyResponses?: {\n approved?: string[]\n rejected?: string[]\n }\n primaryProvider?: ProviderType\n maxTokens?: number\n hasAcknowledgedCostThreshold?: boolean\n oauthAccount?: AccountInfo\n iterm2KeyBindingInstalled?: boolean // Legacy - keeping for backward compatibility\n shiftEnterKeyBindingInstalled?: boolean\n proxy?: string\n stream?: boolean\n\n // New model system\n modelProfiles?: ModelProfile[] // Model configuration list\n modelPointers?: ModelPointers // Model pointer system\n defaultModelName?: string // Default model\n // Update notifications\n lastDismissedUpdateVersion?: string\n // Compression mode\n compressionMode?: CompressionMode // Compression algorithm mode ('business' or 'code')\n // Thinking mode (Phase 4.2)\n thinking?: boolean // Whether thinking/extended reasoning mode is enabled\n // UI Language\n language?: UILanguage // UI language ('en' or 'zh-CN')\n}\n\nexport const DEFAULT_GLOBAL_CONFIG: GlobalConfig = {\n numStartups: 0,\n autoUpdaterStatus: 'not_configured',\n theme: 'dark' as ThemeNames,\n preferredNotifChannel: 'iterm2',\n verbose: false,\n primaryProvider: 'anthropic' as ProviderType,\n customApiKeyResponses: {\n approved: [],\n rejected: [],\n },\n stream: true,\n\n // New model system defaults\n modelProfiles: [],\n modelPointers: {\n main: '',\n task: '',\n reasoning: '',\n quick: '',\n compact: '',\n },\n lastDismissedUpdateVersion: undefined,\n compressionMode: 'business', // Default to business consulting compression\n thinking: false, // Default to thinking mode off (Phase 4.2)\n language: 'en', // Default to English\n}\n\nexport const GLOBAL_CONFIG_KEYS = [\n 'autoUpdaterStatus',\n 'theme',\n 'hasCompletedOnboarding',\n 'lastOnboardingVersion',\n 'lastReleaseNotesSeen',\n 'verbose',\n 'customApiKeyResponses',\n 'primaryProvider',\n 'preferredNotifChannel',\n 'shiftEnterKeyBindingInstalled',\n 'maxTokens',\n 'compressionMode',\n 'language',\n] as const\n\nexport type GlobalConfigKey = (typeof GLOBAL_CONFIG_KEYS)[number]\n\nexport function isGlobalConfigKey(key: string): key is GlobalConfigKey {\n return GLOBAL_CONFIG_KEYS.includes(key as GlobalConfigKey)\n}\n\nexport const PROJECT_CONFIG_KEYS = [\n 'dontCrawlDirectory',\n 'enableArchitectTool',\n 'hasTrustDialogAccepted',\n 'hasCompletedProjectOnboarding',\n] as const\n\nexport type ProjectConfigKey = (typeof PROJECT_CONFIG_KEYS)[number]\n\nexport function checkHasTrustDialogAccepted(): boolean {\n let currentPath = getCwd()\n const config = getConfig(GLOBAL_CONFIG_FILE, DEFAULT_GLOBAL_CONFIG)\n\n while (true) {\n const projectConfig = config.projects?.[currentPath]\n if (projectConfig?.hasTrustDialogAccepted) {\n return true\n }\n const parentPath = resolve(currentPath, '..')\n // Stop if we've reached the root (when parent is same as current)\n if (parentPath === currentPath) {\n break\n }\n currentPath = parentPath\n }\n\n return false\n}\n\n// We have to put this test code here because Jest doesn't support mocking ES modules :O\nconst TEST_GLOBAL_CONFIG_FOR_TESTING: GlobalConfig = {\n ...DEFAULT_GLOBAL_CONFIG,\n autoUpdaterStatus: 'disabled',\n}\nconst TEST_PROJECT_CONFIG_FOR_TESTING: ProjectConfig = {\n ...DEFAULT_PROJECT_CONFIG,\n}\n\nexport function isProjectConfigKey(key: string): key is ProjectConfigKey {\n return PROJECT_CONFIG_KEYS.includes(key as ProjectConfigKey)\n}\n\nexport function saveGlobalConfig(config: GlobalConfig): void {\n if (process.env.NODE_ENV === 'test') {\n for (const key in config) {\n TEST_GLOBAL_CONFIG_FOR_TESTING[key] = config[key]\n }\n return\n }\n\n // \u76F4\u63A5\u4FDD\u5B58\u914D\u7F6E\uFF08\u65E0\u9700\u6E05\u9664\u7F13\u5B58\uFF0C\u56E0\u4E3A\u5DF2\u79FB\u9664\u7F13\u5B58\uFF09\n saveConfig(\n GLOBAL_CONFIG_FILE,\n {\n ...config,\n projects: getConfig(GLOBAL_CONFIG_FILE, DEFAULT_GLOBAL_CONFIG).projects,\n },\n DEFAULT_GLOBAL_CONFIG,\n )\n}\n\n/**\n * Migrate legacy displayMode to verbose boolean\n */\nfunction migrateDisplayModeToVerbose(config: GlobalConfig): GlobalConfig {\n // If verbose is already set, no migration needed\n if (config.verbose !== undefined) {\n return config\n }\n\n // Check for legacy displayMode field\n const legacyConfig = config as GlobalConfig & { displayMode?: DisplayMode }\n if (legacyConfig.displayMode !== undefined) {\n const migratedConfig: GlobalConfig = {\n ...config,\n verbose: legacyConfig.displayMode === 'detailed',\n }\n // Remove legacy field\n delete (migratedConfig as any).displayMode\n return migratedConfig\n }\n\n // Default to false if no verbose or displayMode\n return {\n ...config,\n verbose: false,\n }\n}\n\n// \u4E34\u65F6\u79FB\u9664\u7F13\u5B58\uFF0C\u786E\u4FDD\u603B\u662F\u83B7\u53D6\u6700\u65B0\u914D\u7F6E\nexport function getGlobalConfig(): GlobalConfig {\n if (process.env.NODE_ENV === 'test') {\n return TEST_GLOBAL_CONFIG_FOR_TESTING\n }\n const config = getConfig(GLOBAL_CONFIG_FILE, DEFAULT_GLOBAL_CONFIG)\n const migratedConfig = migrateModelProfilesRemoveId(config)\n return migrateDisplayModeToVerbose(migratedConfig)\n}\n\nexport function getAnthropicApiKey(): null | string {\n return process.env.ANTHROPIC_API_KEY || null\n}\n\nexport function normalizeApiKeyForConfig(apiKey: string): string {\n return apiKey?.slice(-20) ?? ''\n}\n\nexport function getCustomApiKeyStatus(\n truncatedApiKey: string,\n): 'approved' | 'rejected' | 'new' {\n const config = getGlobalConfig()\n if (config.customApiKeyResponses?.approved?.includes(truncatedApiKey)) {\n return 'approved'\n }\n if (config.customApiKeyResponses?.rejected?.includes(truncatedApiKey)) {\n return 'rejected'\n }\n return 'new'\n}\n\nfunction saveConfig<A extends object>(\n file: string,\n config: A,\n defaultConfig: A,\n): void {\n // Filter out any values that match the defaults\n const filteredConfig = Object.fromEntries(\n Object.entries(config).filter(\n ([key, value]) =>\n JSON.stringify(value) !== JSON.stringify(defaultConfig[key as keyof A]),\n ),\n )\n try {\n writeFileSync(file, JSON.stringify(filteredConfig, null, 2), 'utf-8')\n } catch (error) {\n const err = error as NodeJS.ErrnoException\n if (\n err?.code === 'EACCES' ||\n err?.code === 'EPERM' ||\n err?.code === 'EROFS'\n ) {\n debugLogger.state('CONFIG_SAVE_SKIPPED', {\n file,\n reason: String(err.code),\n })\n return\n }\n throw error\n }\n}\n\n// Flag to track if config reading is allowed\nlet configReadingAllowed = false\n\nexport function enableConfigs(): void {\n // Any reads to configuration before this flag is set show an console warning\n // to prevent us from adding config reading during module initialization\n configReadingAllowed = true\n // We only check the global config because currently all the configs share a file\n getConfig(\n GLOBAL_CONFIG_FILE,\n DEFAULT_GLOBAL_CONFIG,\n true /* throw on invalid */,\n )\n}\n\nfunction getConfig<A>(\n file: string,\n defaultConfig: A,\n throwOnInvalid?: boolean,\n): A {\n // \u7B80\u5316\u914D\u7F6E\u8BBF\u95EE\u903B\u8F91\uFF0C\u79FB\u9664\u590D\u6742\u7684\u65F6\u5E8F\u68C0\u67E5\n\n debugLogger.state('CONFIG_LOAD_START', {\n file,\n fileExists: String(existsSync(file)),\n throwOnInvalid: String(!!throwOnInvalid),\n })\n\n if (!existsSync(file)) {\n debugLogger.state('CONFIG_LOAD_DEFAULT', {\n file,\n reason: 'file_not_exists',\n defaultConfigKeys: Object.keys(defaultConfig as object).join(', '),\n })\n return cloneDeep(defaultConfig)\n }\n\n try {\n const fileContent = readFileSync(file, 'utf-8')\n debugLogger.state('CONFIG_FILE_READ', {\n file,\n contentLength: String(fileContent.length),\n contentPreview:\n fileContent.substring(0, 100) + (fileContent.length > 100 ? '...' : ''),\n })\n\n try {\n const parsedConfig = JSON.parse(fileContent)\n debugLogger.state('CONFIG_JSON_PARSED', {\n file,\n parsedKeys: Object.keys(parsedConfig).join(', '),\n })\n\n // Handle backward compatibility - remove logic for deleted fields\n const finalConfig = {\n ...cloneDeep(defaultConfig),\n ...parsedConfig,\n }\n\n debugLogger.state('CONFIG_LOAD_SUCCESS', {\n file,\n finalConfigKeys: Object.keys(finalConfig as object).join(', '),\n })\n\n return finalConfig\n } catch (error) {\n // Throw a ConfigParseError with the file path and default config\n const errorMessage =\n error instanceof Error ? error.message : String(error)\n\n debugLogger.error('CONFIG_JSON_PARSE_ERROR', {\n file,\n errorMessage,\n errorType:\n error instanceof Error ? error.constructor.name : typeof error,\n contentLength: String(fileContent.length),\n })\n\n throw new ConfigParseError(errorMessage, file, defaultConfig)\n }\n } catch (error: unknown) {\n // Re-throw ConfigParseError if throwOnInvalid is true\n if (error instanceof ConfigParseError && throwOnInvalid) {\n debugLogger.error('CONFIG_PARSE_ERROR_RETHROWN', {\n file,\n throwOnInvalid: String(throwOnInvalid),\n errorMessage: error.message,\n })\n throw error\n }\n\n debugLogger.warn('CONFIG_FALLBACK_TO_DEFAULT', {\n file,\n errorType: error instanceof Error ? error.constructor.name : typeof error,\n errorMessage: error instanceof Error ? error.message : String(error),\n action: 'using_default_config',\n })\n\n return cloneDeep(defaultConfig)\n }\n}\n\nexport function getCurrentProjectConfig(): ProjectConfig {\n if (process.env.NODE_ENV === 'test') {\n return TEST_PROJECT_CONFIG_FOR_TESTING\n }\n\n const absolutePath = resolve(getCwd())\n const config = getConfig(GLOBAL_CONFIG_FILE, DEFAULT_GLOBAL_CONFIG)\n\n if (!config.projects) {\n return defaultConfigForProject(absolutePath)\n }\n\n const projectConfig =\n config.projects[absolutePath] ?? defaultConfigForProject(absolutePath)\n // Not sure how this became a string\n // TODO: Fix upstream\n if (typeof projectConfig.allowedTools === 'string') {\n projectConfig.allowedTools =\n (safeParseJSON(projectConfig.allowedTools) as string[]) ?? []\n }\n return projectConfig\n}\n\nexport function saveCurrentProjectConfig(projectConfig: ProjectConfig): void {\n if (process.env.NODE_ENV === 'test') {\n for (const key in projectConfig) {\n TEST_PROJECT_CONFIG_FOR_TESTING[key] = projectConfig[key]\n }\n return\n }\n const config = getConfig(GLOBAL_CONFIG_FILE, DEFAULT_GLOBAL_CONFIG)\n saveConfig(\n GLOBAL_CONFIG_FILE,\n {\n ...config,\n projects: {\n ...config.projects,\n [resolve(getCwd())]: projectConfig,\n },\n },\n DEFAULT_GLOBAL_CONFIG,\n )\n}\n\nexport async function isAutoUpdaterDisabled(): Promise<boolean> {\n return getGlobalConfig().autoUpdaterStatus === 'disabled'\n}\n\nexport const TEST_MCPRC_CONFIG_FOR_TESTING: Record<string, McpServerConfig> = {}\n\nexport function clearMcprcConfigForTesting(): void {\n if (process.env.NODE_ENV === 'test') {\n Object.keys(TEST_MCPRC_CONFIG_FOR_TESTING).forEach(key => {\n delete TEST_MCPRC_CONFIG_FOR_TESTING[key]\n })\n }\n}\n\nexport function addMcprcServerForTesting(\n name: string,\n server: McpServerConfig,\n): void {\n if (process.env.NODE_ENV === 'test') {\n TEST_MCPRC_CONFIG_FOR_TESTING[name] = server\n }\n}\n\nexport function removeMcprcServerForTesting(name: string): void {\n if (process.env.NODE_ENV === 'test') {\n if (!TEST_MCPRC_CONFIG_FOR_TESTING[name]) {\n throw new Error(`No MCP server found with name: ${name} in .mcprc`)\n }\n delete TEST_MCPRC_CONFIG_FOR_TESTING[name]\n }\n}\n\nexport const getMcprcConfig = memoize(\n (): Record<string, McpServerConfig> => {\n if (process.env.NODE_ENV === 'test') {\n return TEST_MCPRC_CONFIG_FOR_TESTING\n }\n\n const mcprcPath = join(getCwd(), '.mcprc')\n if (!existsSync(mcprcPath)) {\n return {}\n }\n\n try {\n const mcprcContent = readFileSync(mcprcPath, 'utf-8')\n const config = safeParseJSON(mcprcContent)\n if (config && typeof config === 'object') {\n // Logging removed\n return config as Record<string, McpServerConfig>\n }\n } catch {\n // Ignore errors reading/parsing .mcprc (they're logged in safeParseJSON)\n }\n return {}\n },\n // This function returns the same value as long as the cwd and mcprc file content remain the same\n () => {\n const cwd = getCwd()\n const mcprcPath = join(cwd, '.mcprc')\n if (existsSync(mcprcPath)) {\n try {\n const stat = readFileSync(mcprcPath, 'utf-8')\n return `${cwd}:${stat}`\n } catch {\n return cwd\n }\n }\n return cwd\n },\n)\n\nexport function getOrCreateUserID(): string {\n const config = getGlobalConfig()\n if (config.userID) {\n return config.userID\n }\n\n const userID = randomBytes(32).toString('hex')\n saveGlobalConfig({ ...config, userID })\n return userID\n}\n\nexport function getConfigForCLI(key: string, global: boolean): unknown {\n if (global) {\n if (!isGlobalConfigKey(key)) {\n console.error(\n `Error: '${key}' is not a valid config key. Valid keys are: ${GLOBAL_CONFIG_KEYS.join(', ')}`,\n )\n process.exit(1)\n }\n return getGlobalConfig()[key]\n } else {\n if (!isProjectConfigKey(key)) {\n console.error(\n `Error: '${key}' is not a valid config key. Valid keys are: ${PROJECT_CONFIG_KEYS.join(', ')}`,\n )\n process.exit(1)\n }\n return getCurrentProjectConfig()[key]\n }\n}\n\nexport function setConfigForCLI(\n key: string,\n value: unknown,\n global: boolean,\n): void {\n if (global) {\n if (!isGlobalConfigKey(key)) {\n console.error(\n `Error: Cannot set '${key}'. Only these keys can be modified: ${GLOBAL_CONFIG_KEYS.join(', ')}`,\n )\n process.exit(1)\n }\n\n if (key === 'autoUpdaterStatus' && !isAutoUpdaterStatus(value as string)) {\n console.error(\n `Error: Invalid value for autoUpdaterStatus. Must be one of: disabled, enabled, no_permissions, not_configured`,\n )\n process.exit(1)\n }\n\n const currentConfig = getGlobalConfig()\n saveGlobalConfig({\n ...currentConfig,\n [key]: value,\n })\n } else {\n if (!isProjectConfigKey(key)) {\n console.error(\n `Error: Cannot set '${key}'. Only these keys can be modified: ${PROJECT_CONFIG_KEYS.join(', ')}. Did you mean --global?`,\n )\n process.exit(1)\n }\n const currentConfig = getCurrentProjectConfig()\n saveCurrentProjectConfig({\n ...currentConfig,\n [key]: value,\n })\n }\n // Wait for the output to be flushed, to avoid clearing the screen.\n setTimeout(() => {\n // Without this we hang indefinitely.\n process.exit(0)\n }, 100)\n}\n\nexport function deleteConfigForCLI(key: string, global: boolean): void {\n if (global) {\n if (!isGlobalConfigKey(key)) {\n console.error(\n `Error: Cannot delete '${key}'. Only these keys can be modified: ${GLOBAL_CONFIG_KEYS.join(', ')}`,\n )\n process.exit(1)\n }\n const currentConfig = getGlobalConfig()\n delete currentConfig[key]\n saveGlobalConfig(currentConfig)\n } else {\n if (!isProjectConfigKey(key)) {\n console.error(\n `Error: Cannot delete '${key}'. Only these keys can be modified: ${PROJECT_CONFIG_KEYS.join(', ')}. Did you mean --global?`,\n )\n process.exit(1)\n }\n const currentConfig = getCurrentProjectConfig()\n delete currentConfig[key]\n saveCurrentProjectConfig(currentConfig)\n }\n}\n\nexport function listConfigForCLI(global: true): GlobalConfig\nexport function listConfigForCLI(global: false): ProjectConfig\nexport function listConfigForCLI(global: boolean): object {\n if (global) {\n const currentConfig = pick(getGlobalConfig(), GLOBAL_CONFIG_KEYS)\n return currentConfig\n } else {\n return pick(getCurrentProjectConfig(), PROJECT_CONFIG_KEYS)\n }\n}\n\nexport function getOpenAIApiKey(): string | undefined {\n return process.env.OPENAI_API_KEY\n}\n\n// Configuration migration utility functions\nfunction migrateModelProfilesRemoveId(config: GlobalConfig): GlobalConfig {\n if (!config.modelProfiles) return config\n\n // Cast to legacy type for migration - config may have old fields\n const legacyConfig = config as GlobalConfig & LegacyGlobalConfigFields\n\n // 1. Remove id field from ModelProfile objects and build ID to modelName mapping\n const idToModelNameMap = new Map<string, string>()\n const migratedProfiles = config.modelProfiles.map(profile => {\n // Cast to legacy type that includes optional id field\n const legacyProfile = profile as LegacyModelProfile\n // Build mapping before removing id field\n if (legacyProfile.id && profile.modelName) {\n idToModelNameMap.set(legacyProfile.id, profile.modelName)\n }\n\n // Remove id field, keep everything else\n const { id, ...profileWithoutId } = legacyProfile\n return profileWithoutId as ModelProfile\n })\n\n // 2. Migrate ModelPointers from IDs to modelNames\n const migratedPointers: ModelPointers = {\n main: '',\n task: '',\n reasoning: '',\n quick: '',\n compact: '',\n }\n\n if (config.modelPointers) {\n Object.entries(config.modelPointers).forEach(([pointer, value]) => {\n if (value) {\n // If value looks like an old ID (model_xxx), map it to modelName\n const modelName = idToModelNameMap.get(value) || value\n migratedPointers[pointer as ModelPointerType] = modelName\n }\n })\n }\n\n // 3. Migrate legacy config fields\n let defaultModelName: string | undefined\n if (legacyConfig.defaultModelId) {\n defaultModelName =\n idToModelNameMap.get(legacyConfig.defaultModelId) ||\n legacyConfig.defaultModelId\n } else if (legacyConfig.defaultModelName) {\n defaultModelName = legacyConfig.defaultModelName\n }\n\n // 4. Remove legacy fields and return migrated config\n const migratedConfig: GlobalConfig & Partial<LegacyGlobalConfigFields> = {\n ...config,\n }\n delete migratedConfig.defaultModelId\n delete migratedConfig.currentSelectedModelId\n delete migratedConfig.mainAgentModelId\n delete migratedConfig.taskToolModelId\n\n return {\n ...migratedConfig,\n modelProfiles: migratedProfiles,\n modelPointers: migratedPointers,\n defaultModelName,\n }\n}\n\n// New model system utility functions\n\nexport function setAllPointersToModel(modelName: string): void {\n const config = getGlobalConfig()\n const updatedConfig = {\n ...config,\n modelPointers: {\n main: modelName,\n task: modelName,\n reasoning: modelName,\n quick: modelName,\n compact: modelName,\n },\n defaultModelName: modelName,\n }\n saveGlobalConfig(updatedConfig)\n}\n\nexport function setModelPointer(\n pointer: ModelPointerType,\n modelName: string,\n): void {\n const config = getGlobalConfig()\n const updatedConfig = {\n ...config,\n modelPointers: {\n ...config.modelPointers,\n [pointer]: modelName,\n },\n }\n saveGlobalConfig(updatedConfig)\n\n // \uD83D\uDD27 Fix: Force ModelManager reload after config change\n // Import here to avoid circular dependency\n import('./model').then(({ reloadModelManager }) => {\n reloadModelManager()\n })\n}\n\n// \uD83D\uDD25 GPT-5 Configuration Validation and Auto-Repair Functions\n\n/**\n * Check if a model name represents a GPT-5 model\n */\nexport function isGPT5ModelName(modelName: string): boolean {\n if (!modelName || typeof modelName !== 'string') return false\n const lowerName = modelName.toLowerCase()\n return lowerName.startsWith('gpt-5') || lowerName.includes('gpt-5')\n}\n\n/**\n * Validate and auto-repair GPT-5 model configuration\n */\nexport function validateAndRepairGPT5Profile(\n profile: ModelProfile,\n): ModelProfile {\n const isGPT5 = isGPT5ModelName(profile.modelName)\n const now = Date.now()\n\n // Create a working copy\n const repairedProfile: ModelProfile = { ...profile }\n let wasRepaired = false\n\n // \uD83D\uDD27 Set GPT-5 detection flag\n if (isGPT5 !== profile.isGPT5) {\n repairedProfile.isGPT5 = isGPT5\n wasRepaired = true\n }\n\n if (isGPT5) {\n // \uD83D\uDD27 GPT-5 Parameter Validation and Repair\n\n // 1. Reasoning effort validation\n const validReasoningEfforts = ['minimal', 'low', 'medium', 'high']\n if (\n !profile.reasoningEffort ||\n !validReasoningEfforts.includes(profile.reasoningEffort)\n ) {\n repairedProfile.reasoningEffort = 'medium' // Default for coding tasks\n wasRepaired = true\n console.log(\n `\uD83D\uDD27 GPT-5 Config: Set reasoning effort to 'medium' for ${profile.modelName}`,\n )\n }\n\n // 2. Context length validation (GPT-5 models typically have 128k context)\n if (profile.contextLength < 128000) {\n repairedProfile.contextLength = 128000\n wasRepaired = true\n console.log(\n `\uD83D\uDD27 GPT-5 Config: Updated context length to 128k for ${profile.modelName}`,\n )\n }\n\n // 3. Output tokens validation (reasonable defaults for GPT-5)\n if (profile.maxTokens < 4000) {\n repairedProfile.maxTokens = 8192 // Good default for coding tasks\n wasRepaired = true\n console.log(\n `\uD83D\uDD27 GPT-5 Config: Updated max tokens to 8192 for ${profile.modelName}`,\n )\n }\n\n // 4. Provider validation\n if (\n profile.provider !== 'openai' &&\n profile.provider !== 'custom-openai' &&\n profile.provider !== 'azure'\n ) {\n console.warn(\n `\u26A0\uFE0F GPT-5 Config: Unexpected provider '${profile.provider}' for GPT-5 model ${profile.modelName}. Consider using 'openai' or 'custom-openai'.`,\n )\n }\n\n // 5. Base URL validation for official models\n if (profile.modelName.includes('gpt-5') && !profile.baseURL) {\n repairedProfile.baseURL = 'https://api.openai.com/v1'\n wasRepaired = true\n console.log(\n `\uD83D\uDD27 GPT-5 Config: Set default base URL for ${profile.modelName}`,\n )\n }\n }\n\n // Update validation metadata\n repairedProfile.validationStatus = wasRepaired ? 'auto_repaired' : 'valid'\n repairedProfile.lastValidation = now\n\n if (wasRepaired) {\n console.log(\n `\u2705 GPT-5 Config: Auto-repaired configuration for ${profile.modelName}`,\n )\n }\n\n return repairedProfile\n}\n\n/**\n * Validate and repair all GPT-5 profiles in the global configuration\n */\nexport function validateAndRepairAllGPT5Profiles(): {\n repaired: number\n total: number\n} {\n const config = getGlobalConfig()\n if (!config.modelProfiles) {\n return { repaired: 0, total: 0 }\n }\n\n let repairCount = 0\n const repairedProfiles = config.modelProfiles.map(profile => {\n const repairedProfile = validateAndRepairGPT5Profile(profile)\n if (repairedProfile.validationStatus === 'auto_repaired') {\n repairCount++\n }\n return repairedProfile\n })\n\n // Save the repaired configuration\n if (repairCount > 0) {\n const updatedConfig = {\n ...config,\n modelProfiles: repairedProfiles,\n }\n saveGlobalConfig(updatedConfig)\n console.log(`\uD83D\uDD27 GPT-5 Config: Auto-repaired ${repairCount} model profiles`)\n }\n\n return { repaired: repairCount, total: config.modelProfiles.length }\n}\n\n/**\n * Get GPT-5 configuration recommendations for a specific model\n */\nexport function getGPT5ConfigRecommendations(\n modelName: string,\n): Partial<ModelProfile> {\n if (!isGPT5ModelName(modelName)) {\n return {}\n }\n\n const recommendations: Partial<ModelProfile> = {\n contextLength: 128000, // GPT-5 standard context length\n maxTokens: 8192, // Good default for coding tasks\n reasoningEffort: 'medium', // Balanced for most coding tasks\n isGPT5: true,\n }\n\n // Model-specific optimizations\n if (modelName.includes('gpt-5-mini')) {\n recommendations.maxTokens = 4096 // Smaller default for mini\n recommendations.reasoningEffort = 'low' // Faster for simple tasks\n } else if (modelName.includes('gpt-5-nano')) {\n recommendations.maxTokens = 2048 // Even smaller for nano\n recommendations.reasoningEffort = 'minimal' // Fastest option\n }\n\n return recommendations\n}\n\n/**\n * Create a properly configured GPT-5 model profile\n */\nexport function createGPT5ModelProfile(\n name: string,\n modelName: string,\n apiKey: string,\n baseURL?: string,\n provider: ProviderType = 'openai',\n): ModelProfile {\n const recommendations = getGPT5ConfigRecommendations(modelName)\n\n const profile: ModelProfile = {\n name,\n provider,\n modelName,\n baseURL: baseURL || 'https://api.openai.com/v1',\n apiKey,\n maxTokens: recommendations.maxTokens || 8192,\n contextLength: recommendations.contextLength || 128000,\n reasoningEffort: recommendations.reasoningEffort || 'medium',\n isActive: true,\n createdAt: Date.now(),\n isGPT5: true,\n validationStatus: 'valid',\n lastValidation: Date.now(),\n }\n\n console.log(`\u2705 Created GPT-5 model profile: ${name} (${modelName})`)\n return profile\n}\n"],
5
- "mappings": "AAAA,SAAS,YAAY,cAAc,qBAAqB;AACxD,SAAS,SAAS,YAAY;AAC9B,SAAS,WAAW,SAAS,YAAY;AACzC,SAAS,eAAe;AACxB,SAAS,0BAA0B;AACnC,SAAS,cAAc;AACvB,SAAS,mBAAmB;AAC5B,SAAS,qBAAqB;AAC9B,SAAS,wBAAwB;AAEjC,SAAS,SAAS,mBAAmB;AAoErC,MAAM,yBAAwC;AAAA,EAC5C,cAAc,CAAC;AAAA,EACf,SAAS,CAAC;AAAA,EACV,SAAS,CAAC;AAAA,EACV,oBAAoB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AO,cAAc,OAAO;AACrE;AAKO,SAAS,6BACd,WACuB;AACvB,MAAI,CAAC,gBAAgB,SAAS,GAAG;AAC/B,WAAO,CAAC;AAAA,EACV;AAEA,QAAM,kBAAyC;AAAA,IAC7C,eAAe;AAAA;AAAA,IACf,WAAW;AAAA;AAAA,IACX,iBAAiB;AAAA;AAAA,IACjB,QAAQ;AAAA,EACV;AAGA,MAAI,UAAU,SAAS,YAAY,GAAG;AACpC,oBAAgB,YAAY;AAC5B,oBAAgB,kBAAkB;AAAA,EACpC,WAAW,UAAU,SAAS,YAAY,GAAG;AAC3C,oBAAgB,YAAY;AAC5B,oBAAgB,kBAAkB;AAAA,EACpC;AAEA,SAAO;AACT;AAKO,SAAS,uBACd,MACA,WACA,QACA,SACA,WAAyB,UACX;AACd,QAAM,kBAAkB,6BAA6B,SAAS;AAE9D,QAAM,UAAwB;AAAA,IAC5B;AAAA,IACA;AAAA,IACA;AAAA,IACA,SAAS,WAAW;AAAA,IACpB;AAAA,IACA,WAAW,gBAAgB,aAAa;AAAA,IACxC,eAAe,gBAAgB,iBAAiB;AAAA,IAChD,iBAAiB,gBAAgB,mBAAmB;AAAA,IACpD,UAAU;AAAA,IACV,WAAW,KAAK,IAAI;AAAA,IACpB,QAAQ;AAAA,IACR,kBAAkB;AAAA,IAClB,gBAAgB,KAAK,IAAI;AAAA,EAC3B;AAEA,UAAQ,IAAI,uCAAkC,IAAI,KAAK,SAAS,GAAG;AACnE,SAAO;AACT;",
4
+ "sourcesContent": ["import { existsSync, readFileSync, writeFileSync, renameSync, rmSync } from 'fs'\nimport { resolve, join, dirname } from 'path'\nimport { cloneDeep, memoize, pick } from 'lodash-es'\nimport { homedir } from 'os'\nimport { GLOBAL_CONFIG_FILE } from './env'\nimport { getCwd } from './state'\nimport { randomBytes } from 'crypto'\nimport { safeParseJSON } from './json'\nimport { ConfigParseError } from './errors'\nimport type { ThemeNames } from './theme'\nimport { debug as debugLogger } from './debugLogger'\nimport { getSessionState, setSessionState } from './sessionState'\nimport type { CompressionMode } from '@constants/compressionPrompts'\n\nexport type McpStdioServerConfig = {\n type?: 'stdio' // Optional for backwards compatibility\n command: string\n args: string[]\n env?: Record<string, string>\n enabled?: boolean\n}\n\nexport type McpSSEServerConfig = {\n type: 'sse'\n url: string\n enabled?: boolean\n}\n\nexport type McpServerConfig = McpStdioServerConfig | McpSSEServerConfig\n\n/**\n * Sandbox configuration for project-level security settings\n */\nexport type SandboxConfigData = {\n /** Whether sandboxing is enabled */\n enabled: boolean\n /** Filesystem access policy */\n filesystem?: {\n writeAllowed?: string[]\n readAllowed?: string[]\n denied?: string[]\n }\n /** Network access policy */\n network?: {\n allowedDomains?: string[]\n promptForNewDomains?: boolean\n blockAll?: boolean\n }\n /** Process isolation policy */\n process?: {\n excludedCommands?: string[]\n maxExecutionTime?: number\n }\n}\n\nexport type ProjectConfig = {\n allowedTools: string[]\n context: Record<string, string>\n contextFiles?: string[]\n history: string[]\n dontCrawlDirectory?: boolean\n enableArchitectTool?: boolean\n mcpContextUris: string[]\n mcpServers?: Record<string, McpServerConfig>\n approvedMcprcServers?: string[]\n rejectedMcprcServers?: string[]\n lastAPIDuration?: number\n lastCost?: number\n lastDuration?: number\n lastSessionId?: string\n exampleFiles?: string[]\n exampleFilesGeneratedAt?: number\n hasTrustDialogAccepted?: boolean\n hasCompletedProjectOnboarding?: boolean\n /** Sandbox configuration for command execution isolation */\n sandbox?: SandboxConfigData\n}\n\nconst DEFAULT_PROJECT_CONFIG: ProjectConfig = {\n allowedTools: [],\n context: {},\n history: [],\n dontCrawlDirectory: false,\n enableArchitectTool: false,\n mcpContextUris: [],\n mcpServers: {},\n approvedMcprcServers: [],\n rejectedMcprcServers: [],\n hasTrustDialogAccepted: false,\n}\n\nfunction defaultConfigForProject(projectPath: string): ProjectConfig {\n const config = { ...DEFAULT_PROJECT_CONFIG }\n if (projectPath === homedir()) {\n config.dontCrawlDirectory = true\n }\n return config\n}\n\nexport type AutoUpdaterStatus =\n | 'disabled'\n | 'enabled'\n | 'no_permissions'\n | 'not_configured'\n\nexport function isAutoUpdaterStatus(value: string): value is AutoUpdaterStatus {\n return ['disabled', 'enabled', 'no_permissions', 'not_configured'].includes(\n value as AutoUpdaterStatus,\n )\n}\n\nexport type NotificationChannel =\n | 'iterm2'\n | 'terminal_bell'\n | 'iterm2_with_bell'\n | 'notifications_disabled'\n\n/**\n * @deprecated Use verbose boolean instead. Kept for backward compatibility migration.\n */\nexport type DisplayMode = 'minimal' | 'compact' | 'detailed'\n\n/**\n * Supported UI languages\n */\nexport type UILanguage = 'en' | 'zh-CN'\n\n/**\n * Safety mode for tool execution\n * - 'yolo': All tools allowed without confirmation (default for non-technical users)\n * - 'smart': Safe/monitored tools auto-allowed, dangerous tools need confirmation\n * - 'strict': Only safe tools auto-allowed, all others need confirmation\n */\nexport type SafetyMode = 'yolo' | 'smart' | 'strict'\n\n/**\n * Get verbose mode label (uses i18n)\n * Import dynamically to avoid circular dependency\n */\nexport function getVerboseLabel(verbose: boolean): string {\n // Dynamic import to avoid circular dependency at module load time\n try {\n const { t } = require('../i18n')\n return verbose ? t('ui.verbose.on') : t('ui.verbose.off')\n } catch {\n // Fallback if i18n not loaded yet\n return verbose ? 'Verbose: On' : 'Verbose: Off'\n }\n}\n\n/**\n * @deprecated Use getVerboseLabel() instead\n */\nexport function getDisplayModeLabel(mode: DisplayMode): string {\n return mode === 'detailed' ? 'Verbose: On' : 'Verbose: Off'\n}\n\n/**\n * @deprecated No longer needed - use verbose boolean directly\n */\nexport const DISPLAY_MODE_LABELS: Record<DisplayMode, string> = {\n minimal: 'Verbose: Off',\n compact: 'Verbose: Off',\n detailed: 'Verbose: On',\n}\n\n/**\n * @deprecated Use !verbose instead\n */\nexport function getNextDisplayMode(current: DisplayMode): DisplayMode {\n // Simply toggle between compact (off) and detailed (on)\n return current === 'detailed' ? 'compact' : 'detailed'\n}\n\n/**\n * Convert displayMode to verbose boolean for backward compatibility\n * @deprecated Components should use verbose directly\n */\nexport function displayModeToVerbose(mode: DisplayMode): boolean {\n return mode === 'detailed'\n}\n\n/**\n * Convert verbose boolean to displayMode for backward compatibility\n */\nexport function verboseToDisplayMode(verbose: boolean): DisplayMode {\n return verbose ? 'detailed' : 'compact'\n}\n\nexport type ProviderType =\n | 'anthropic'\n | 'openai'\n | 'mistral'\n | 'deepseek'\n | 'kimi'\n | 'qwen'\n | 'glm'\n | 'minimax'\n | 'baidu-qianfan'\n | 'siliconflow'\n | 'bigdream'\n | 'opendev'\n | 'xai'\n | 'groq'\n | 'gemini'\n | 'ollama'\n | 'azure'\n | 'custom'\n | 'custom-openai'\n\n// New model system types\nexport type ModelProfile = {\n name: string // User-friendly name\n provider: ProviderType // Provider type\n modelName: string // Primary key - actual model identifier\n baseURL?: string // Custom endpoint\n apiKey: string\n maxTokens: number // Output token limit (for GPT-5, this maps to max_completion_tokens)\n contextLength: number // Context window size\n reasoningEffort?: 'low' | 'medium' | 'high' | 'minimal' | 'medium'\n isActive: boolean // Whether profile is enabled\n createdAt: number // Creation timestamp\n lastUsed?: number // Last usage timestamp\n // \uD83D\uDD25 GPT-5 specific metadata\n isGPT5?: boolean // Auto-detected GPT-5 model flag\n validationStatus?: 'valid' | 'needs_repair' | 'auto_repaired' // Configuration status\n lastValidation?: number // Last validation timestamp\n}\n\n// Legacy type for config migration - includes deprecated 'id' field\ntype LegacyModelProfile = ModelProfile & {\n id?: string\n}\n\n// Legacy global config fields for migration\ntype LegacyGlobalConfigFields = {\n defaultModelId?: string\n defaultModelName?: string\n currentSelectedModelId?: string\n mainAgentModelId?: string\n taskToolModelId?: string\n}\n\nexport type ModelPointerType =\n | 'main'\n | 'task'\n | 'reasoning'\n | 'quick'\n | 'compact'\n\nexport type ModelPointers = {\n main: string // Main dialog model ID\n task: string // Task tool model ID\n reasoning: string // Reasoning model ID\n quick: string // Quick model ID\n compact: string // Compact/summary model ID (for context compression)\n}\n\nexport type AccountInfo = {\n accountUuid: string\n emailAddress: string\n organizationUuid?: string\n}\n\nexport type GlobalConfig = {\n projects?: Record<string, ProjectConfig>\n numStartups: number\n autoUpdaterStatus?: AutoUpdaterStatus\n userID?: string\n theme: ThemeNames\n hasCompletedOnboarding?: boolean\n // Tracks the last version that reset onboarding, used with MIN_VERSION_REQUIRING_ONBOARDING_RESET\n lastOnboardingVersion?: string\n // Tracks the last version for which release notes were seen, used for managing release notes\n lastReleaseNotesSeen?: string\n mcpServers?: Record<string, McpServerConfig>\n preferredNotifChannel: NotificationChannel\n /**\n * Verbose mode: shows full parameters and complete outputs when enabled\n * - false: Concise output (default)\n * - true: Detailed/verbose output\n */\n verbose: boolean\n /**\n * @deprecated Use verbose boolean instead. Kept for backward compatibility migration.\n */\n displayMode?: DisplayMode\n customApiKeyResponses?: {\n approved?: string[]\n rejected?: string[]\n }\n primaryProvider?: ProviderType\n maxTokens?: number\n hasAcknowledgedCostThreshold?: boolean\n oauthAccount?: AccountInfo\n iterm2KeyBindingInstalled?: boolean // Legacy - keeping for backward compatibility\n shiftEnterKeyBindingInstalled?: boolean\n proxy?: string\n stream?: boolean\n\n // New model system\n modelProfiles?: ModelProfile[] // Model configuration list\n modelPointers?: ModelPointers // Model pointer system\n defaultModelName?: string // Default model\n // Update notifications\n lastDismissedUpdateVersion?: string\n // Compression mode\n compressionMode?: CompressionMode // Compression algorithm mode ('business' or 'code')\n // Thinking mode (Phase 4.2)\n thinking?: boolean // Whether thinking/extended reasoning mode is enabled\n // UI Language\n language?: UILanguage // UI language ('en' or 'zh-CN')\n /**\n * @deprecated Use safetyMode instead. Kept for backward compatibility.\n * Safe mode: when enabled, requires user confirmation for all tool executions\n */\n safeMode?: boolean\n /**\n * Safety mode for tool execution (new 3-tier system):\n * - 'yolo': All tools allowed without confirmation (default for non-technical users)\n * - 'smart': Safe/monitored tools auto-allowed, dangerous tools need confirmation\n * - 'strict': Only safe tools auto-allowed, all others need confirmation\n */\n safetyMode?: SafetyMode\n}\n\nexport const DEFAULT_GLOBAL_CONFIG: GlobalConfig = {\n numStartups: 0,\n autoUpdaterStatus: 'not_configured',\n theme: 'dark' as ThemeNames,\n preferredNotifChannel: 'iterm2',\n verbose: false,\n primaryProvider: 'anthropic' as ProviderType,\n customApiKeyResponses: {\n approved: [],\n rejected: [],\n },\n stream: true,\n\n // New model system defaults\n modelProfiles: [],\n modelPointers: {\n main: '',\n task: '',\n reasoning: '',\n quick: '',\n compact: '',\n },\n lastDismissedUpdateVersion: undefined,\n compressionMode: 'business', // Default to business consulting compression\n thinking: false, // Default to thinking mode off (Phase 4.2)\n language: 'en', // Default to English\n safeMode: false, // Deprecated: use safetyMode instead\n safetyMode: 'yolo', // Default to YOLO mode for non-technical users (zero interruption)\n}\n\nexport const GLOBAL_CONFIG_KEYS = [\n 'autoUpdaterStatus',\n 'theme',\n 'hasCompletedOnboarding',\n 'lastOnboardingVersion',\n 'lastReleaseNotesSeen',\n 'verbose',\n 'customApiKeyResponses',\n 'primaryProvider',\n 'preferredNotifChannel',\n 'shiftEnterKeyBindingInstalled',\n 'maxTokens',\n 'compressionMode',\n 'language',\n 'safetyMode',\n] as const\n\nexport type GlobalConfigKey = (typeof GLOBAL_CONFIG_KEYS)[number]\n\nexport function isGlobalConfigKey(key: string): key is GlobalConfigKey {\n return GLOBAL_CONFIG_KEYS.includes(key as GlobalConfigKey)\n}\n\nexport const PROJECT_CONFIG_KEYS = [\n 'dontCrawlDirectory',\n 'enableArchitectTool',\n 'hasTrustDialogAccepted',\n 'hasCompletedProjectOnboarding',\n] as const\n\nexport type ProjectConfigKey = (typeof PROJECT_CONFIG_KEYS)[number]\n\nexport function checkHasTrustDialogAccepted(): boolean {\n let currentPath = getCwd()\n const config = getConfig(GLOBAL_CONFIG_FILE, DEFAULT_GLOBAL_CONFIG)\n\n while (true) {\n const projectConfig = config.projects?.[currentPath]\n if (projectConfig?.hasTrustDialogAccepted) {\n return true\n }\n const parentPath = resolve(currentPath, '..')\n // Stop if we've reached the root (when parent is same as current)\n if (parentPath === currentPath) {\n break\n }\n currentPath = parentPath\n }\n\n return false\n}\n\n// We have to put this test code here because Jest doesn't support mocking ES modules :O\nconst TEST_GLOBAL_CONFIG_FOR_TESTING: GlobalConfig = {\n ...DEFAULT_GLOBAL_CONFIG,\n autoUpdaterStatus: 'disabled',\n}\nconst TEST_PROJECT_CONFIG_FOR_TESTING: ProjectConfig = {\n ...DEFAULT_PROJECT_CONFIG,\n}\n\nexport function isProjectConfigKey(key: string): key is ProjectConfigKey {\n return PROJECT_CONFIG_KEYS.includes(key as ProjectConfigKey)\n}\n\nexport function saveGlobalConfig(config: GlobalConfig): void {\n if (process.env.NODE_ENV === 'test') {\n for (const key in config) {\n TEST_GLOBAL_CONFIG_FOR_TESTING[key] = config[key]\n }\n return\n }\n\n // \u76F4\u63A5\u4FDD\u5B58\u914D\u7F6E\uFF08\u65E0\u9700\u6E05\u9664\u7F13\u5B58\uFF0C\u56E0\u4E3A\u5DF2\u79FB\u9664\u7F13\u5B58\uFF09\n saveConfig(\n GLOBAL_CONFIG_FILE,\n {\n ...config,\n projects: getConfig(GLOBAL_CONFIG_FILE, DEFAULT_GLOBAL_CONFIG).projects,\n },\n DEFAULT_GLOBAL_CONFIG,\n )\n}\n\n/**\n * Migrate legacy displayMode to verbose boolean\n */\nfunction migrateDisplayModeToVerbose(config: GlobalConfig): GlobalConfig {\n // If verbose is already set, no migration needed\n if (config.verbose !== undefined) {\n return config\n }\n\n // Check for legacy displayMode field\n const legacyConfig = config as GlobalConfig & { displayMode?: DisplayMode }\n if (legacyConfig.displayMode !== undefined) {\n const migratedConfig: GlobalConfig = {\n ...config,\n verbose: legacyConfig.displayMode === 'detailed',\n }\n // Remove legacy field\n delete (migratedConfig as any).displayMode\n return migratedConfig\n }\n\n // Default to false if no verbose or displayMode\n return {\n ...config,\n verbose: false,\n }\n}\n\n// \u4E34\u65F6\u79FB\u9664\u7F13\u5B58\uFF0C\u786E\u4FDD\u603B\u662F\u83B7\u53D6\u6700\u65B0\u914D\u7F6E\nexport function getGlobalConfig(): GlobalConfig {\n if (process.env.NODE_ENV === 'test') {\n return TEST_GLOBAL_CONFIG_FOR_TESTING\n }\n const config = getConfig(GLOBAL_CONFIG_FILE, DEFAULT_GLOBAL_CONFIG)\n const migratedConfig = migrateModelProfilesRemoveId(config)\n return migrateDisplayModeToVerbose(migratedConfig)\n}\n\nexport function getAnthropicApiKey(): null | string {\n return process.env.ANTHROPIC_API_KEY || null\n}\n\nexport function normalizeApiKeyForConfig(apiKey: string): string {\n return apiKey?.slice(-20) ?? ''\n}\n\nexport function getCustomApiKeyStatus(\n truncatedApiKey: string,\n): 'approved' | 'rejected' | 'new' {\n const config = getGlobalConfig()\n if (config.customApiKeyResponses?.approved?.includes(truncatedApiKey)) {\n return 'approved'\n }\n if (config.customApiKeyResponses?.rejected?.includes(truncatedApiKey)) {\n return 'rejected'\n }\n return 'new'\n}\n\n/**\n * Atomically write content to a file using temp file + rename pattern.\n * This prevents data corruption if writes are interrupted or multiple processes\n * attempt to write concurrently.\n *\n * @param filePath - The target file path to write to\n * @param content - The content to write\n * @throws {Error} If write or rename operation fails\n */\nfunction atomicWriteFileSync(filePath: string, content: string): void {\n const dir = dirname(filePath)\n const tempPath = join(\n dir,\n `.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`,\n )\n\n try {\n // Write to temporary file\n writeFileSync(tempPath, content, 'utf-8')\n // Atomically rename temp to target (atomic on most filesystems)\n renameSync(tempPath, filePath)\n } catch (error) {\n // Clean up temporary file on failure\n try {\n rmSync(tempPath, { force: true })\n } catch {\n // Ignore cleanup errors\n }\n throw error\n }\n}\n\nfunction saveConfig<A extends object>(\n file: string,\n config: A,\n defaultConfig: A,\n): void {\n // Filter out any values that match the defaults\n const filteredConfig = Object.fromEntries(\n Object.entries(config).filter(\n ([key, value]) =>\n JSON.stringify(value) !== JSON.stringify(defaultConfig[key as keyof A]),\n ),\n )\n try {\n atomicWriteFileSync(file, JSON.stringify(filteredConfig, null, 2))\n } catch (error) {\n const err = error as NodeJS.ErrnoException\n if (\n err?.code === 'EACCES' ||\n err?.code === 'EPERM' ||\n err?.code === 'EROFS'\n ) {\n debugLogger.state('CONFIG_SAVE_SKIPPED', {\n file,\n reason: String(err.code),\n })\n return\n }\n throw error\n }\n}\n\n// Flag to track if config reading is allowed\nlet configReadingAllowed = false\n\nexport function enableConfigs(): void {\n // Any reads to configuration before this flag is set show an console warning\n // to prevent us from adding config reading during module initialization\n configReadingAllowed = true\n // We only check the global config because currently all the configs share a file\n getConfig(\n GLOBAL_CONFIG_FILE,\n DEFAULT_GLOBAL_CONFIG,\n true /* throw on invalid */,\n )\n}\n\nfunction getConfig<A>(\n file: string,\n defaultConfig: A,\n throwOnInvalid?: boolean,\n): A {\n // \u7B80\u5316\u914D\u7F6E\u8BBF\u95EE\u903B\u8F91\uFF0C\u79FB\u9664\u590D\u6742\u7684\u65F6\u5E8F\u68C0\u67E5\n\n debugLogger.state('CONFIG_LOAD_START', {\n file,\n fileExists: String(existsSync(file)),\n throwOnInvalid: String(!!throwOnInvalid),\n })\n\n if (!existsSync(file)) {\n debugLogger.state('CONFIG_LOAD_DEFAULT', {\n file,\n reason: 'file_not_exists',\n defaultConfigKeys: Object.keys(defaultConfig as object).join(', '),\n })\n return cloneDeep(defaultConfig)\n }\n\n try {\n const fileContent = readFileSync(file, 'utf-8')\n debugLogger.state('CONFIG_FILE_READ', {\n file,\n contentLength: String(fileContent.length),\n contentPreview:\n fileContent.substring(0, 100) + (fileContent.length > 100 ? '...' : ''),\n })\n\n try {\n const parsedConfig = JSON.parse(fileContent)\n debugLogger.state('CONFIG_JSON_PARSED', {\n file,\n parsedKeys: Object.keys(parsedConfig).join(', '),\n })\n\n // Handle backward compatibility - remove logic for deleted fields\n const finalConfig = {\n ...cloneDeep(defaultConfig),\n ...parsedConfig,\n }\n\n debugLogger.state('CONFIG_LOAD_SUCCESS', {\n file,\n finalConfigKeys: Object.keys(finalConfig as object).join(', '),\n })\n\n return finalConfig\n } catch (error) {\n // Throw a ConfigParseError with the file path and default config\n const errorMessage =\n error instanceof Error ? error.message : String(error)\n\n debugLogger.error('CONFIG_JSON_PARSE_ERROR', {\n file,\n errorMessage,\n errorType:\n error instanceof Error ? error.constructor.name : typeof error,\n contentLength: String(fileContent.length),\n })\n\n throw new ConfigParseError(errorMessage, file, defaultConfig)\n }\n } catch (error: unknown) {\n // Re-throw ConfigParseError if throwOnInvalid is true\n if (error instanceof ConfigParseError && throwOnInvalid) {\n debugLogger.error('CONFIG_PARSE_ERROR_RETHROWN', {\n file,\n throwOnInvalid: String(throwOnInvalid),\n errorMessage: error.message,\n })\n throw error\n }\n\n debugLogger.warn('CONFIG_FALLBACK_TO_DEFAULT', {\n file,\n errorType: error instanceof Error ? error.constructor.name : typeof error,\n errorMessage: error instanceof Error ? error.message : String(error),\n action: 'using_default_config',\n })\n\n return cloneDeep(defaultConfig)\n }\n}\n\nexport function getCurrentProjectConfig(): ProjectConfig {\n if (process.env.NODE_ENV === 'test') {\n return TEST_PROJECT_CONFIG_FOR_TESTING\n }\n\n const absolutePath = resolve(getCwd())\n const config = getConfig(GLOBAL_CONFIG_FILE, DEFAULT_GLOBAL_CONFIG)\n\n if (!config.projects) {\n return defaultConfigForProject(absolutePath)\n }\n\n const projectConfig =\n config.projects[absolutePath] ?? defaultConfigForProject(absolutePath)\n // Not sure how this became a string\n // TODO: Fix upstream\n if (typeof projectConfig.allowedTools === 'string') {\n projectConfig.allowedTools =\n (safeParseJSON(projectConfig.allowedTools) as string[]) ?? []\n }\n return projectConfig\n}\n\nexport function saveCurrentProjectConfig(projectConfig: ProjectConfig): void {\n if (process.env.NODE_ENV === 'test') {\n for (const key in projectConfig) {\n TEST_PROJECT_CONFIG_FOR_TESTING[key] = projectConfig[key]\n }\n return\n }\n const config = getConfig(GLOBAL_CONFIG_FILE, DEFAULT_GLOBAL_CONFIG)\n saveConfig(\n GLOBAL_CONFIG_FILE,\n {\n ...config,\n projects: {\n ...config.projects,\n [resolve(getCwd())]: projectConfig,\n },\n },\n DEFAULT_GLOBAL_CONFIG,\n )\n}\n\nexport async function isAutoUpdaterDisabled(): Promise<boolean> {\n return getGlobalConfig().autoUpdaterStatus === 'disabled'\n}\n\nexport const TEST_MCPRC_CONFIG_FOR_TESTING: Record<string, McpServerConfig> = {}\n\nexport function clearMcprcConfigForTesting(): void {\n if (process.env.NODE_ENV === 'test') {\n Object.keys(TEST_MCPRC_CONFIG_FOR_TESTING).forEach(key => {\n delete TEST_MCPRC_CONFIG_FOR_TESTING[key]\n })\n }\n}\n\nexport function addMcprcServerForTesting(\n name: string,\n server: McpServerConfig,\n): void {\n if (process.env.NODE_ENV === 'test') {\n TEST_MCPRC_CONFIG_FOR_TESTING[name] = server\n }\n}\n\nexport function removeMcprcServerForTesting(name: string): void {\n if (process.env.NODE_ENV === 'test') {\n if (!TEST_MCPRC_CONFIG_FOR_TESTING[name]) {\n throw new Error(`No MCP server found with name: ${name} in .mcprc`)\n }\n delete TEST_MCPRC_CONFIG_FOR_TESTING[name]\n }\n}\n\nexport const getMcprcConfig = memoize(\n (): Record<string, McpServerConfig> => {\n if (process.env.NODE_ENV === 'test') {\n return TEST_MCPRC_CONFIG_FOR_TESTING\n }\n\n const mcprcPath = join(getCwd(), '.mcprc')\n if (!existsSync(mcprcPath)) {\n return {}\n }\n\n try {\n const mcprcContent = readFileSync(mcprcPath, 'utf-8')\n const config = safeParseJSON(mcprcContent)\n if (config && typeof config === 'object') {\n // Logging removed\n return config as Record<string, McpServerConfig>\n }\n } catch {\n // Ignore errors reading/parsing .mcprc (they're logged in safeParseJSON)\n }\n return {}\n },\n // This function returns the same value as long as the cwd and mcprc file content remain the same\n () => {\n const cwd = getCwd()\n const mcprcPath = join(cwd, '.mcprc')\n if (existsSync(mcprcPath)) {\n try {\n const stat = readFileSync(mcprcPath, 'utf-8')\n return `${cwd}:${stat}`\n } catch {\n return cwd\n }\n }\n return cwd\n },\n)\n\nexport function getOrCreateUserID(): string {\n const config = getGlobalConfig()\n if (config.userID) {\n return config.userID\n }\n\n const userID = randomBytes(32).toString('hex')\n saveGlobalConfig({ ...config, userID })\n return userID\n}\n\nexport function getConfigForCLI(key: string, global: boolean): unknown {\n if (global) {\n if (!isGlobalConfigKey(key)) {\n console.error(\n `Error: '${key}' is not a valid config key. Valid keys are: ${GLOBAL_CONFIG_KEYS.join(', ')}`,\n )\n process.exit(1)\n }\n return getGlobalConfig()[key]\n } else {\n if (!isProjectConfigKey(key)) {\n console.error(\n `Error: '${key}' is not a valid config key. Valid keys are: ${PROJECT_CONFIG_KEYS.join(', ')}`,\n )\n process.exit(1)\n }\n return getCurrentProjectConfig()[key]\n }\n}\n\nexport function setConfigForCLI(\n key: string,\n value: unknown,\n global: boolean,\n): void {\n if (global) {\n if (!isGlobalConfigKey(key)) {\n console.error(\n `Error: Cannot set '${key}'. Only these keys can be modified: ${GLOBAL_CONFIG_KEYS.join(', ')}`,\n )\n process.exit(1)\n }\n\n if (key === 'autoUpdaterStatus' && !isAutoUpdaterStatus(value as string)) {\n console.error(\n `Error: Invalid value for autoUpdaterStatus. Must be one of: disabled, enabled, no_permissions, not_configured`,\n )\n process.exit(1)\n }\n\n const currentConfig = getGlobalConfig()\n saveGlobalConfig({\n ...currentConfig,\n [key]: value,\n })\n } else {\n if (!isProjectConfigKey(key)) {\n console.error(\n `Error: Cannot set '${key}'. Only these keys can be modified: ${PROJECT_CONFIG_KEYS.join(', ')}. Did you mean --global?`,\n )\n process.exit(1)\n }\n const currentConfig = getCurrentProjectConfig()\n saveCurrentProjectConfig({\n ...currentConfig,\n [key]: value,\n })\n }\n // Wait for the output to be flushed, to avoid clearing the screen.\n setTimeout(() => {\n // Without this we hang indefinitely.\n process.exit(0)\n }, 100)\n}\n\nexport function deleteConfigForCLI(key: string, global: boolean): void {\n if (global) {\n if (!isGlobalConfigKey(key)) {\n console.error(\n `Error: Cannot delete '${key}'. Only these keys can be modified: ${GLOBAL_CONFIG_KEYS.join(', ')}`,\n )\n process.exit(1)\n }\n const currentConfig = getGlobalConfig()\n delete currentConfig[key]\n saveGlobalConfig(currentConfig)\n } else {\n if (!isProjectConfigKey(key)) {\n console.error(\n `Error: Cannot delete '${key}'. Only these keys can be modified: ${PROJECT_CONFIG_KEYS.join(', ')}. Did you mean --global?`,\n )\n process.exit(1)\n }\n const currentConfig = getCurrentProjectConfig()\n delete currentConfig[key]\n saveCurrentProjectConfig(currentConfig)\n }\n}\n\nexport function listConfigForCLI(global: true): GlobalConfig\nexport function listConfigForCLI(global: false): ProjectConfig\nexport function listConfigForCLI(global: boolean): object {\n if (global) {\n const currentConfig = pick(getGlobalConfig(), GLOBAL_CONFIG_KEYS)\n return currentConfig\n } else {\n return pick(getCurrentProjectConfig(), PROJECT_CONFIG_KEYS)\n }\n}\n\nexport function getOpenAIApiKey(): string | undefined {\n return process.env.OPENAI_API_KEY\n}\n\n// Configuration migration utility functions\nfunction migrateModelProfilesRemoveId(config: GlobalConfig): GlobalConfig {\n if (!config.modelProfiles) return config\n\n // Cast to legacy type for migration - config may have old fields\n const legacyConfig = config as GlobalConfig & LegacyGlobalConfigFields\n\n // 1. Remove id field from ModelProfile objects and build ID to modelName mapping\n const idToModelNameMap = new Map<string, string>()\n const migratedProfiles = config.modelProfiles.map(profile => {\n // Cast to legacy type that includes optional id field\n const legacyProfile = profile as LegacyModelProfile\n // Build mapping before removing id field\n if (legacyProfile.id && profile.modelName) {\n idToModelNameMap.set(legacyProfile.id, profile.modelName)\n }\n\n // Remove id field, keep everything else\n const { id, ...profileWithoutId } = legacyProfile\n return profileWithoutId as ModelProfile\n })\n\n // 2. Migrate ModelPointers from IDs to modelNames\n const migratedPointers: ModelPointers = {\n main: '',\n task: '',\n reasoning: '',\n quick: '',\n compact: '',\n }\n\n if (config.modelPointers) {\n Object.entries(config.modelPointers).forEach(([pointer, value]) => {\n if (value) {\n // If value looks like an old ID (model_xxx), map it to modelName\n const modelName = idToModelNameMap.get(value) || value\n migratedPointers[pointer as ModelPointerType] = modelName\n }\n })\n }\n\n // 3. Migrate legacy config fields\n let defaultModelName: string | undefined\n if (legacyConfig.defaultModelId) {\n defaultModelName =\n idToModelNameMap.get(legacyConfig.defaultModelId) ||\n legacyConfig.defaultModelId\n } else if (legacyConfig.defaultModelName) {\n defaultModelName = legacyConfig.defaultModelName\n }\n\n // 4. Remove legacy fields and return migrated config\n const migratedConfig: GlobalConfig & Partial<LegacyGlobalConfigFields> = {\n ...config,\n }\n delete migratedConfig.defaultModelId\n delete migratedConfig.currentSelectedModelId\n delete migratedConfig.mainAgentModelId\n delete migratedConfig.taskToolModelId\n\n return {\n ...migratedConfig,\n modelProfiles: migratedProfiles,\n modelPointers: migratedPointers,\n defaultModelName,\n }\n}\n\n// New model system utility functions\n\nexport function setAllPointersToModel(modelName: string): void {\n const config = getGlobalConfig()\n const updatedConfig = {\n ...config,\n modelPointers: {\n main: modelName,\n task: modelName,\n reasoning: modelName,\n quick: modelName,\n compact: modelName,\n },\n defaultModelName: modelName,\n }\n saveGlobalConfig(updatedConfig)\n}\n\nexport function setModelPointer(\n pointer: ModelPointerType,\n modelName: string,\n): void {\n const config = getGlobalConfig()\n const updatedConfig = {\n ...config,\n modelPointers: {\n ...config.modelPointers,\n [pointer]: modelName,\n },\n }\n saveGlobalConfig(updatedConfig)\n\n // \uD83D\uDD27 Fix: Force ModelManager reload after config change\n // Import here to avoid circular dependency\n import('./model').then(({ reloadModelManager }) => {\n reloadModelManager()\n })\n}\n\n// Credential resolution functions for secure API key management\n\n/**\n * Resolve an API key for a ModelProfile.\n * Supports both plaintext keys (backward compatibility) and encrypted references.\n *\n * For plaintext keys (legacy):\n * Returns the key directly from the profile\n *\n * For encrypted references (encrypted:modelName):\n * Retrieves the key from the encrypted credential store\n *\n * @param profile The model profile to resolve the API key for\n * @returns The resolved API key, or null if not found\n * @throws Error if credential store access fails\n */\nexport async function resolveApiKey(\n profile: ModelProfile,\n): Promise<string | null> {\n if (!profile.apiKey) {\n return null\n }\n\n // Check if this is an encrypted reference\n if (profile.apiKey.startsWith('encrypted:')) {\n // Extract model name from the encrypted reference\n const modelName = profile.apiKey.slice('encrypted:'.length)\n\n // Import dynamically to avoid circular dependencies\n try {\n const { getApiKey } = await import('./credentials')\n return getApiKey(modelName)\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : String(error)\n console.warn(\n `Failed to resolve encrypted API key for ${modelName}: ${errorMsg}`,\n )\n return null\n }\n }\n\n // Return plaintext key for backward compatibility\n return profile.apiKey\n}\n\n// \uD83D\uDD25 GPT-5 Configuration Validation and Auto-Repair Functions\n\n/**\n * Check if a model name represents a GPT-5 model\n */\nexport function isGPT5ModelName(modelName: string): boolean {\n if (!modelName || typeof modelName !== 'string') return false\n const lowerName = modelName.toLowerCase()\n return lowerName.startsWith('gpt-5') || lowerName.includes('gpt-5')\n}\n\n/**\n * Validate and auto-repair GPT-5 model configuration\n */\nexport function validateAndRepairGPT5Profile(\n profile: ModelProfile,\n): ModelProfile {\n const isGPT5 = isGPT5ModelName(profile.modelName)\n const now = Date.now()\n\n // Create a working copy\n const repairedProfile: ModelProfile = { ...profile }\n let wasRepaired = false\n\n // \uD83D\uDD27 Set GPT-5 detection flag\n if (isGPT5 !== profile.isGPT5) {\n repairedProfile.isGPT5 = isGPT5\n wasRepaired = true\n }\n\n if (isGPT5) {\n // \uD83D\uDD27 GPT-5 Parameter Validation and Repair\n\n // 1. Reasoning effort validation\n const validReasoningEfforts = ['minimal', 'low', 'medium', 'high']\n if (\n !profile.reasoningEffort ||\n !validReasoningEfforts.includes(profile.reasoningEffort)\n ) {\n repairedProfile.reasoningEffort = 'medium' // Default for coding tasks\n wasRepaired = true\n console.log(\n `\uD83D\uDD27 GPT-5 Config: Set reasoning effort to 'medium' for ${profile.modelName}`,\n )\n }\n\n // 2. Context length validation (GPT-5 models typically have 128k context)\n if (profile.contextLength < 128000) {\n repairedProfile.contextLength = 128000\n wasRepaired = true\n console.log(\n `\uD83D\uDD27 GPT-5 Config: Updated context length to 128k for ${profile.modelName}`,\n )\n }\n\n // 3. Output tokens validation (reasonable defaults for GPT-5)\n if (profile.maxTokens < 4000) {\n repairedProfile.maxTokens = 8192 // Good default for coding tasks\n wasRepaired = true\n console.log(\n `\uD83D\uDD27 GPT-5 Config: Updated max tokens to 8192 for ${profile.modelName}`,\n )\n }\n\n // 4. Provider validation\n if (\n profile.provider !== 'openai' &&\n profile.provider !== 'custom-openai' &&\n profile.provider !== 'azure'\n ) {\n console.warn(\n `\u26A0\uFE0F GPT-5 Config: Unexpected provider '${profile.provider}' for GPT-5 model ${profile.modelName}. Consider using 'openai' or 'custom-openai'.`,\n )\n }\n\n // 5. Base URL validation for official models\n if (profile.modelName.includes('gpt-5') && !profile.baseURL) {\n repairedProfile.baseURL = 'https://api.openai.com/v1'\n wasRepaired = true\n console.log(\n `\uD83D\uDD27 GPT-5 Config: Set default base URL for ${profile.modelName}`,\n )\n }\n }\n\n // Update validation metadata\n repairedProfile.validationStatus = wasRepaired ? 'auto_repaired' : 'valid'\n repairedProfile.lastValidation = now\n\n if (wasRepaired) {\n console.log(\n `\u2705 GPT-5 Config: Auto-repaired configuration for ${profile.modelName}`,\n )\n }\n\n return repairedProfile\n}\n\n/**\n * Validate and repair all GPT-5 profiles in the global configuration\n */\nexport function validateAndRepairAllGPT5Profiles(): {\n repaired: number\n total: number\n} {\n const config = getGlobalConfig()\n if (!config.modelProfiles) {\n return { repaired: 0, total: 0 }\n }\n\n let repairCount = 0\n const repairedProfiles = config.modelProfiles.map(profile => {\n const repairedProfile = validateAndRepairGPT5Profile(profile)\n if (repairedProfile.validationStatus === 'auto_repaired') {\n repairCount++\n }\n return repairedProfile\n })\n\n // Save the repaired configuration\n if (repairCount > 0) {\n const updatedConfig = {\n ...config,\n modelProfiles: repairedProfiles,\n }\n saveGlobalConfig(updatedConfig)\n console.log(`\uD83D\uDD27 GPT-5 Config: Auto-repaired ${repairCount} model profiles`)\n }\n\n return { repaired: repairCount, total: config.modelProfiles.length }\n}\n\n/**\n * Get GPT-5 configuration recommendations for a specific model\n */\nexport function getGPT5ConfigRecommendations(\n modelName: string,\n): Partial<ModelProfile> {\n if (!isGPT5ModelName(modelName)) {\n return {}\n }\n\n const recommendations: Partial<ModelProfile> = {\n contextLength: 128000, // GPT-5 standard context length\n maxTokens: 8192, // Good default for coding tasks\n reasoningEffort: 'medium', // Balanced for most coding tasks\n isGPT5: true,\n }\n\n // Model-specific optimizations\n if (modelName.includes('gpt-5-mini')) {\n recommendations.maxTokens = 4096 // Smaller default for mini\n recommendations.reasoningEffort = 'low' // Faster for simple tasks\n } else if (modelName.includes('gpt-5-nano')) {\n recommendations.maxTokens = 2048 // Even smaller for nano\n recommendations.reasoningEffort = 'minimal' // Fastest option\n }\n\n return recommendations\n}\n\n/**\n * Create a properly configured GPT-5 model profile\n */\nexport function createGPT5ModelProfile(\n name: string,\n modelName: string,\n apiKey: string,\n baseURL?: string,\n provider: ProviderType = 'openai',\n): ModelProfile {\n const recommendations = getGPT5ConfigRecommendations(modelName)\n\n const profile: ModelProfile = {\n name,\n provider,\n modelName,\n baseURL: baseURL || 'https://api.openai.com/v1',\n apiKey,\n maxTokens: recommendations.maxTokens || 8192,\n contextLength: recommendations.contextLength || 128000,\n reasoningEffort: recommendations.reasoningEffort || 'medium',\n isActive: true,\n createdAt: Date.now(),\n isGPT5: true,\n validationStatus: 'valid',\n lastValidation: Date.now(),\n }\n\n console.log(`\u2705 Created GPT-5 model profile: ${name} (${modelName})`)\n return profile\n}\n"],
5
+ "mappings": "AAAA,SAAS,YAAY,cAAc,eAAe,YAAY,cAAc;AAC5E,SAAS,SAAS,MAAM,eAAe;AACvC,SAAS,WAAW,SAAS,YAAY;AACzC,SAAS,eAAe;AACxB,SAAS,0BAA0B;AACnC,SAAS,cAAc;AACvB,SAAS,mBAAmB;AAC5B,SAAS,qBAAqB;AAC9B,SAAS,wBAAwB;AAEjC,SAAS,SAAS,mBAAmB;AAoErC,MAAM,yBAAwC;AAAA,EAC5C,cAAc,CAAC;AAAA,EACf,SAAS,CAAC;AAAA,EACV,SAAS,CAAC;AAAA,EACV,oBAAoB;AAAA,EACpB,qB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ACpC,WAAW,UAAU,SAAS,YAAY,GAAG;AAC3C,oBAAgB,YAAY;AAC5B,oBAAgB,kBAAkB;AAAA,EACpC;AAEA,SAAO;AACT;AAKO,SAAS,uBACd,MACA,WACA,QACA,SACA,WAAyB,UACX;AACd,QAAM,kBAAkB,6BAA6B,SAAS;AAE9D,QAAM,UAAwB;AAAA,IAC5B;AAAA,IACA;AAAA,IACA;AAAA,IACA,SAAS,WAAW;AAAA,IACpB;AAAA,IACA,WAAW,gBAAgB,aAAa;AAAA,IACxC,eAAe,gBAAgB,iBAAiB;AAAA,IAChD,iBAAiB,gBAAgB,mBAAmB;AAAA,IACpD,UAAU;AAAA,IACV,WAAW,KAAK,IAAI;AAAA,IACpB,QAAQ;AAAA,IACR,kBAAkB;AAAA,IAClB,gBAAgB,KAAK,IAAI;AAAA,EAC3B;AAEA,UAAQ,IAAI,uCAAkC,IAAI,KAAK,SAAS,GAAG;AACnE,SAAO;AACT;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=CredentialStore.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": [],
4
+ "sourcesContent": [],
5
+ "mappings": "",
6
+ "names": []
7
+ }
@@ -0,0 +1,157 @@
1
+ import {
2
+ createCipheriv,
3
+ createDecipheriv,
4
+ randomBytes,
5
+ scryptSync
6
+ } from "crypto";
7
+ import {
8
+ readFileSync,
9
+ writeFileSync,
10
+ existsSync,
11
+ chmodSync,
12
+ mkdirSync
13
+ } from "fs";
14
+ import { join } from "path";
15
+ import { homedir, hostname } from "os";
16
+ import { debug as debugLogger } from "../debugLogger.js";
17
+ const ALGORITHM = "aes-256-gcm";
18
+ const SALT = "minto-credentials-salt-v1";
19
+ const CREDENTIALS_DIR = join(homedir(), ".minto");
20
+ const CREDENTIALS_FILE = join(CREDENTIALS_DIR, "credentials.enc");
21
+ function getMachineId() {
22
+ const username = process.env.USER || process.env.USERNAME || "unknown";
23
+ const machineHostname = hostname();
24
+ const homeDir = homedir();
25
+ return `${machineHostname}:${username}:${homeDir}`;
26
+ }
27
+ class EncryptedFileStore {
28
+ /**
29
+ * Derive a consistent encryption key from the machine ID using scrypt KDF
30
+ */
31
+ getEncryptionKey() {
32
+ const machineId = getMachineId();
33
+ return scryptSync(machineId, SALT, 32);
34
+ }
35
+ /**
36
+ * Ensure credentials directory exists with proper permissions
37
+ */
38
+ ensureCredentialsDir() {
39
+ if (!existsSync(CREDENTIALS_DIR)) {
40
+ mkdirSync(CREDENTIALS_DIR, { mode: 448, recursive: true });
41
+ }
42
+ }
43
+ /**
44
+ * Load and decrypt credentials from disk
45
+ */
46
+ loadCredentials() {
47
+ if (!existsSync(CREDENTIALS_FILE)) {
48
+ debugLogger.state("CREDENTIALS_FILE_NOT_FOUND", {
49
+ path: CREDENTIALS_FILE
50
+ });
51
+ return {};
52
+ }
53
+ try {
54
+ const encryptedData = readFileSync(CREDENTIALS_FILE);
55
+ if (encryptedData.length < 32) {
56
+ debugLogger.warn("CREDENTIALS_FILE_TOO_SHORT", {
57
+ path: CREDENTIALS_FILE,
58
+ size: encryptedData.length
59
+ });
60
+ return {};
61
+ }
62
+ const iv = encryptedData.subarray(0, 16);
63
+ const authTag = encryptedData.subarray(16, 32);
64
+ const encrypted = encryptedData.subarray(32);
65
+ const key = this.getEncryptionKey();
66
+ const decipher = createDecipheriv(ALGORITHM, key, iv);
67
+ decipher.setAuthTag(authTag);
68
+ const decrypted = Buffer.concat([
69
+ decipher.update(encrypted),
70
+ decipher.final()
71
+ ]);
72
+ const credentials = JSON.parse(decrypted.toString("utf-8"));
73
+ debugLogger.state("CREDENTIALS_LOADED", {
74
+ path: CREDENTIALS_FILE,
75
+ count: Object.keys(credentials).length
76
+ });
77
+ return credentials;
78
+ } catch (error) {
79
+ const errorMsg = error instanceof Error ? error.message : String(error);
80
+ debugLogger.error("CREDENTIALS_LOAD_ERROR", {
81
+ path: CREDENTIALS_FILE,
82
+ error: errorMsg,
83
+ errorType: error instanceof Error ? error.constructor.name : typeof error
84
+ });
85
+ return {};
86
+ }
87
+ }
88
+ /**
89
+ * Encrypt and save credentials to disk
90
+ */
91
+ saveCredentials(credentials) {
92
+ try {
93
+ this.ensureCredentialsDir();
94
+ const key = this.getEncryptionKey();
95
+ const iv = randomBytes(16);
96
+ const cipher = createCipheriv(ALGORITHM, key, iv);
97
+ const plaintext = JSON.stringify(credentials);
98
+ const encrypted = Buffer.concat([
99
+ cipher.update(plaintext, "utf-8"),
100
+ cipher.final()
101
+ ]);
102
+ const authTag = cipher.getAuthTag();
103
+ const combined = Buffer.concat([iv, authTag, encrypted]);
104
+ writeFileSync(CREDENTIALS_FILE, combined);
105
+ chmodSync(CREDENTIALS_FILE, 384);
106
+ debugLogger.state("CREDENTIALS_SAVED", {
107
+ path: CREDENTIALS_FILE,
108
+ size: combined.length
109
+ });
110
+ } catch (error) {
111
+ const errorMsg = error instanceof Error ? error.message : String(error);
112
+ debugLogger.error("CREDENTIALS_SAVE_ERROR", {
113
+ path: CREDENTIALS_FILE,
114
+ error: errorMsg
115
+ });
116
+ throw error;
117
+ }
118
+ }
119
+ /**
120
+ * Generate a composite key for storing credentials
121
+ */
122
+ makeKey(service, account) {
123
+ return `${service}:${account}`;
124
+ }
125
+ async get(service, account) {
126
+ const credentials = this.loadCredentials();
127
+ const key = this.makeKey(service, account);
128
+ return credentials[key] ?? null;
129
+ }
130
+ async set(service, account, password) {
131
+ const credentials = this.loadCredentials();
132
+ credentials[this.makeKey(service, account)] = password;
133
+ this.saveCredentials(credentials);
134
+ }
135
+ async delete(service, account) {
136
+ const credentials = this.loadCredentials();
137
+ const key = this.makeKey(service, account);
138
+ delete credentials[key];
139
+ this.saveCredentials(credentials);
140
+ }
141
+ async findCredentials(service) {
142
+ const credentials = this.loadCredentials();
143
+ const prefix = `${service}:`;
144
+ const results = [];
145
+ for (const [key, password] of Object.entries(credentials)) {
146
+ if (key.startsWith(prefix)) {
147
+ const account = key.slice(prefix.length);
148
+ results.push({ account, password });
149
+ }
150
+ }
151
+ return results;
152
+ }
153
+ }
154
+ export {
155
+ EncryptedFileStore
156
+ };
157
+ //# sourceMappingURL=EncryptedFileStore.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/utils/credentials/EncryptedFileStore.ts"],
4
+ "sourcesContent": ["import {\n createCipheriv,\n createDecipheriv,\n randomBytes,\n scryptSync,\n} from 'crypto'\nimport {\n readFileSync,\n writeFileSync,\n existsSync,\n chmodSync,\n mkdirSync,\n} from 'fs'\nimport { join, dirname } from 'path'\nimport { homedir, hostname } from 'os'\nimport type { CredentialStore } from './CredentialStore'\nimport { debug as debugLogger } from '../debugLogger'\n\nconst ALGORITHM = 'aes-256-gcm'\nconst SALT = 'minto-credentials-salt-v1'\nconst CREDENTIALS_DIR = join(homedir(), '.minto')\nconst CREDENTIALS_FILE = join(CREDENTIALS_DIR, 'credentials.enc')\n\n/**\n * Get a machine identifier for deterministic key derivation.\n * Uses hostname + username + homedir to create a stable machine-specific identifier.\n */\nfunction getMachineId(): string {\n const username = process.env.USER || process.env.USERNAME || 'unknown'\n const machineHostname = hostname()\n const homeDir = homedir()\n return `${machineHostname}:${username}:${homeDir}`\n}\n\n/**\n * Encrypted file-based credential store using AES-256-GCM encryption.\n * Credentials are stored in ~/.minto/credentials.enc with machine-specific encryption.\n */\nexport class EncryptedFileStore implements CredentialStore {\n /**\n * Derive a consistent encryption key from the machine ID using scrypt KDF\n */\n private getEncryptionKey(): Buffer {\n const machineId = getMachineId()\n // scrypt(password, salt, keylen, options)\n return scryptSync(machineId, SALT, 32)\n }\n\n /**\n * Ensure credentials directory exists with proper permissions\n */\n private ensureCredentialsDir(): void {\n if (!existsSync(CREDENTIALS_DIR)) {\n mkdirSync(CREDENTIALS_DIR, { mode: 0o700, recursive: true })\n }\n }\n\n /**\n * Load and decrypt credentials from disk\n */\n private loadCredentials(): Record<string, string> {\n if (!existsSync(CREDENTIALS_FILE)) {\n debugLogger.state('CREDENTIALS_FILE_NOT_FOUND', {\n path: CREDENTIALS_FILE,\n })\n return {}\n }\n\n try {\n const encryptedData = readFileSync(CREDENTIALS_FILE)\n\n // Format: iv (16) + authTag (16) + encryptedContent\n if (encryptedData.length < 32) {\n debugLogger.warn('CREDENTIALS_FILE_TOO_SHORT', {\n path: CREDENTIALS_FILE,\n size: encryptedData.length,\n })\n return {}\n }\n\n const iv = encryptedData.subarray(0, 16)\n const authTag = encryptedData.subarray(16, 32)\n const encrypted = encryptedData.subarray(32)\n\n const key = this.getEncryptionKey()\n const decipher = createDecipheriv(ALGORITHM, key, iv)\n decipher.setAuthTag(authTag)\n\n const decrypted = Buffer.concat([\n decipher.update(encrypted),\n decipher.final(),\n ])\n\n const credentials = JSON.parse(decrypted.toString('utf-8'))\n debugLogger.state('CREDENTIALS_LOADED', {\n path: CREDENTIALS_FILE,\n count: Object.keys(credentials).length,\n })\n\n return credentials as Record<string, string>\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : String(error)\n debugLogger.error('CREDENTIALS_LOAD_ERROR', {\n path: CREDENTIALS_FILE,\n error: errorMsg,\n errorType:\n error instanceof Error ? error.constructor.name : typeof error,\n })\n return {}\n }\n }\n\n /**\n * Encrypt and save credentials to disk\n */\n private saveCredentials(credentials: Record<string, string>): void {\n try {\n this.ensureCredentialsDir()\n\n const key = this.getEncryptionKey()\n const iv = randomBytes(16)\n const cipher = createCipheriv(ALGORITHM, key, iv)\n\n const plaintext = JSON.stringify(credentials)\n const encrypted = Buffer.concat([\n cipher.update(plaintext, 'utf-8'),\n cipher.final(),\n ])\n const authTag = cipher.getAuthTag()\n\n // Format: iv (16) + authTag (16) + encryptedContent\n const combined = Buffer.concat([iv, authTag, encrypted])\n\n writeFileSync(CREDENTIALS_FILE, combined)\n // Set strict permissions: readable/writable only by owner\n chmodSync(CREDENTIALS_FILE, 0o600)\n\n debugLogger.state('CREDENTIALS_SAVED', {\n path: CREDENTIALS_FILE,\n size: combined.length,\n })\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : String(error)\n debugLogger.error('CREDENTIALS_SAVE_ERROR', {\n path: CREDENTIALS_FILE,\n error: errorMsg,\n })\n throw error\n }\n }\n\n /**\n * Generate a composite key for storing credentials\n */\n private makeKey(service: string, account: string): string {\n return `${service}:${account}`\n }\n\n async get(service: string, account: string): Promise<string | null> {\n const credentials = this.loadCredentials()\n const key = this.makeKey(service, account)\n return credentials[key] ?? null\n }\n\n async set(service: string, account: string, password: string): Promise<void> {\n const credentials = this.loadCredentials()\n credentials[this.makeKey(service, account)] = password\n this.saveCredentials(credentials)\n }\n\n async delete(service: string, account: string): Promise<void> {\n const credentials = this.loadCredentials()\n const key = this.makeKey(service, account)\n delete credentials[key]\n this.saveCredentials(credentials)\n }\n\n async findCredentials(\n service: string,\n ): Promise<{ account: string; password: string }[]> {\n const credentials = this.loadCredentials()\n const prefix = `${service}:`\n const results: { account: string; password: string }[] = []\n\n for (const [key, password] of Object.entries(credentials)) {\n if (key.startsWith(prefix)) {\n const account = key.slice(prefix.length)\n results.push({ account, password })\n }\n }\n\n return results\n }\n}\n"],
5
+ "mappings": "AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,YAAqB;AAC9B,SAAS,SAAS,gBAAgB;AAElC,SAAS,SAAS,mBAAmB;AAErC,MAAM,YAAY;AAClB,MAAM,OAAO;AACb,MAAM,kBAAkB,KAAK,QAAQ,GAAG,QAAQ;AAChD,MAAM,mBAAmB,KAAK,iBAAiB,iBAAiB;AAMhE,SAAS,eAAuB;AAC9B,QAAM,WAAW,QAAQ,IAAI,QAAQ,QAAQ,IAAI,YAAY;AAC7D,QAAM,kBAAkB,SAAS;AACjC,QAAM,UAAU,QAAQ;AACxB,SAAO,GAAG,eAAe,IAAI,QAAQ,IAAI,OAAO;AAClD;AAMO,MAAM,mBAA8C;AAAA;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c,KAAK,gBAAgB;AACzC,gBAAY,KAAK,QAAQ,SAAS,OAAO,CAAC,IAAI;AAC9C,SAAK,gBAAgB,WAAW;AAAA,EAClC;AAAA,EAEA,MAAM,OAAO,SAAiB,SAAgC;AAC5D,UAAM,cAAc,KAAK,gBAAgB;AACzC,UAAM,MAAM,KAAK,QAAQ,SAAS,OAAO;AACzC,WAAO,YAAY,GAAG;AACtB,SAAK,gBAAgB,WAAW;AAAA,EAClC;AAAA,EAEA,MAAM,gBACJ,SACkD;AAClD,UAAM,cAAc,KAAK,gBAAgB;AACzC,UAAM,SAAS,GAAG,OAAO;AACzB,UAAM,UAAmD,CAAC;AAE1D,eAAW,CAAC,KAAK,QAAQ,KAAK,OAAO,QAAQ,WAAW,GAAG;AACzD,UAAI,IAAI,WAAW,MAAM,GAAG;AAC1B,cAAM,UAAU,IAAI,MAAM,OAAO,MAAM;AACvC,gBAAQ,KAAK,EAAE,SAAS,SAAS,CAAC;AAAA,MACpC;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AACF;",
6
+ "names": []
7
+ }
@@ -0,0 +1,37 @@
1
+ import { EncryptedFileStore } from "./EncryptedFileStore.js";
2
+ let store = null;
3
+ const SERVICE_NAME = "minto-api";
4
+ function getCredentialStore() {
5
+ if (!store) {
6
+ store = new EncryptedFileStore();
7
+ }
8
+ return store;
9
+ }
10
+ function resetCredentialStore() {
11
+ store = null;
12
+ }
13
+ async function getApiKey(modelName) {
14
+ return getCredentialStore().get(SERVICE_NAME, modelName);
15
+ }
16
+ async function setApiKey(modelName, apiKey) {
17
+ return getCredentialStore().set(SERVICE_NAME, modelName, apiKey);
18
+ }
19
+ async function deleteApiKey(modelName) {
20
+ return getCredentialStore().delete(SERVICE_NAME, modelName);
21
+ }
22
+ async function findAllApiKeys() {
23
+ const credentials = await getCredentialStore().findCredentials(SERVICE_NAME);
24
+ return credentials.map(({ account, password }) => ({
25
+ modelName: account,
26
+ apiKey: password
27
+ }));
28
+ }
29
+ export {
30
+ deleteApiKey,
31
+ findAllApiKeys,
32
+ getApiKey,
33
+ getCredentialStore,
34
+ resetCredentialStore,
35
+ setApiKey
36
+ };
37
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/utils/credentials/index.ts"],
4
+ "sourcesContent": ["import { EncryptedFileStore } from './EncryptedFileStore'\nimport type { CredentialStore } from './CredentialStore'\n\n// Current credential store implementation (using encrypted files)\n// In Phase 2, this can be extended to support keytar for native OS keychains\nlet store: CredentialStore | null = null\n\nconst SERVICE_NAME = 'minto-api'\n\n/**\n * Get the current credential store instance\n * Currently uses encrypted file storage; will be extended to support keytar in Phase 2\n */\nexport function getCredentialStore(): CredentialStore {\n if (!store) {\n store = new EncryptedFileStore()\n }\n return store\n}\n\n/**\n * Reset the credential store (primarily for testing)\n */\nexport function resetCredentialStore(): void {\n store = null\n}\n\n/**\n * Retrieve an API key for a specific model from the credential store.\n * Returns null if the key is not found.\n *\n * @param modelName The name of the model to retrieve the API key for\n * @returns The API key or null if not stored in credential store\n */\nexport async function getApiKey(modelName: string): Promise<string | null> {\n return getCredentialStore().get(SERVICE_NAME, modelName)\n}\n\n/**\n * Store an API key for a specific model in the credential store.\n * This stores the key securely in encrypted storage.\n *\n * @param modelName The name of the model\n * @param apiKey The API key to store\n */\nexport async function setApiKey(\n modelName: string,\n apiKey: string,\n): Promise<void> {\n return getCredentialStore().set(SERVICE_NAME, modelName, apiKey)\n}\n\n/**\n * Delete an API key for a specific model from the credential store.\n *\n * @param modelName The name of the model\n */\nexport async function deleteApiKey(modelName: string): Promise<void> {\n return getCredentialStore().delete(SERVICE_NAME, modelName)\n}\n\n/**\n * Find all stored API keys for the service\n *\n * @returns Array of model names and their API keys\n */\nexport async function findAllApiKeys(): Promise<\n { modelName: string; apiKey: string }[]\n> {\n const credentials = await getCredentialStore().findCredentials(SERVICE_NAME)\n return credentials.map(({ account, password }) => ({\n modelName: account,\n apiKey: password,\n }))\n}\n"],
5
+ "mappings": "AAAA,SAAS,0BAA0B;AAKnC,IAAI,QAAgC;AAEpC,MAAM,eAAe;AAMd,SAAS,qBAAsC;AACpD,MAAI,CAAC,OAAO;AACV,YAAQ,IAAI,mBAAmB;AAAA,EACjC;AACA,SAAO;AACT;AAKO,SAAS,uBAA6B;AAC3C,UAAQ;AACV;AASA,eAAsB,UAAU,WAA2C;AACzE,SAAO,mBAAmB,EAAE,IAAI,cAAc,SAAS;AACzD;AASA,eAAsB,UACpB,WACA,QACe;AACf,SAAO,mBAAmB,EAAE,IAAI,cAAc,WAAW,MAAM;AACjE;AAOA,eAAsB,aAAa,WAAkC;AACnE,SAAO,mBAAmB,EAAE,OAAO,cAAc,SAAS;AAC5D;AAOA,eAAsB,iBAEpB;AACA,QAAM,cAAc,MAAM,mBAAmB,EAAE,gBAAgB,YAAY;AAC3E,SAAO,YAAY,IAAI,CAAC,EAAE,SAAS,SAAS,OAAO;AAAA,IACjD,WAAW;AAAA,IACX,QAAQ;AAAA,EACV,EAAE;AACJ;",
6
+ "names": []
7
+ }
@@ -0,0 +1,82 @@
1
+ import { getGlobalConfig, saveGlobalConfig } from "../config.js";
2
+ import { setApiKey } from "./index.js";
3
+ import { debug as debugLogger } from "../debugLogger.js";
4
+ async function migrateApiKeysToEncrypted() {
5
+ const config = getGlobalConfig();
6
+ let migrated = 0;
7
+ let skipped = 0;
8
+ const errors = [];
9
+ if (!config.modelProfiles || config.modelProfiles.length === 0) {
10
+ debugLogger.state("MIGRATION_NO_PROFILES", {});
11
+ return { migrated: 0, errors: [], skipped: 0 };
12
+ }
13
+ try {
14
+ debugLogger.state("MIGRATION_START", {
15
+ profileCount: config.modelProfiles.length
16
+ });
17
+ const migratedProfiles = await Promise.all(
18
+ config.modelProfiles.map(async (profile) => {
19
+ if (!profile.apiKey) {
20
+ skipped++;
21
+ return profile;
22
+ }
23
+ if (profile.apiKey.startsWith("encrypted:")) {
24
+ debugLogger.state("MIGRATION_SKIP_ALREADY_ENCRYPTED", {
25
+ modelName: profile.modelName
26
+ });
27
+ skipped++;
28
+ return profile;
29
+ }
30
+ try {
31
+ await setApiKey(profile.modelName, profile.apiKey);
32
+ const migratedProfile = {
33
+ ...profile,
34
+ apiKey: `encrypted:${profile.modelName}`
35
+ };
36
+ debugLogger.state("MIGRATION_SUCCESS", {
37
+ modelName: profile.modelName,
38
+ provider: profile.provider
39
+ });
40
+ migrated++;
41
+ return migratedProfile;
42
+ } catch (error) {
43
+ const errorMsg = error instanceof Error ? error.message : String(error);
44
+ const errorText = `Failed to migrate ${profile.modelName}: ${errorMsg}`;
45
+ errors.push(errorText);
46
+ debugLogger.error("MIGRATION_PROFILE_ERROR", {
47
+ modelName: profile.modelName,
48
+ error: errorMsg
49
+ });
50
+ return profile;
51
+ }
52
+ })
53
+ );
54
+ if (migrated > 0) {
55
+ const updatedConfig = {
56
+ ...config,
57
+ modelProfiles: migratedProfiles
58
+ };
59
+ saveGlobalConfig(updatedConfig);
60
+ debugLogger.state("MIGRATION_CONFIG_SAVED", {
61
+ profilesMigrated: migrated,
62
+ profilesSkipped: skipped
63
+ });
64
+ }
65
+ debugLogger.state("MIGRATION_COMPLETE", {
66
+ migrated,
67
+ skipped,
68
+ errors: errors.length
69
+ });
70
+ } catch (error) {
71
+ const errorMsg = error instanceof Error ? error.message : String(error);
72
+ debugLogger.error("MIGRATION_FATAL_ERROR", {
73
+ error: errorMsg
74
+ });
75
+ errors.push(`Fatal migration error: ${errorMsg}`);
76
+ }
77
+ return { migrated, errors, skipped };
78
+ }
79
+ export {
80
+ migrateApiKeysToEncrypted
81
+ };
82
+ //# sourceMappingURL=migration.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/utils/credentials/migration.ts"],
4
+ "sourcesContent": ["import { getGlobalConfig, saveGlobalConfig, type GlobalConfig } from '../config'\nimport { setApiKey } from './index'\nimport { debug as debugLogger } from '../debugLogger'\n\nexport interface MigrationResult {\n migrated: number\n errors: string[]\n skipped: number\n}\n\n/**\n * Migrate API keys from plaintext config to encrypted credential store.\n * This function:\n * 1. Reads all model profiles from the global config\n * 2. For each profile with a plaintext apiKey (not already encrypted):\n * - Stores the key in the encrypted credential store\n * - Updates the config to use the `encrypted:modelName` reference\n * 3. Saves the updated config\n *\n * After migration, the actual API keys are removed from the config file and stored\n * securely in ~/.minto/credentials.enc\n *\n * @returns Migration result with counts of migrated, skipped, and error entries\n */\nexport async function migrateApiKeysToEncrypted(): Promise<MigrationResult> {\n const config = getGlobalConfig()\n let migrated = 0\n let skipped = 0\n const errors: string[] = []\n\n if (!config.modelProfiles || config.modelProfiles.length === 0) {\n debugLogger.state('MIGRATION_NO_PROFILES', {})\n return { migrated: 0, errors: [], skipped: 0 }\n }\n\n try {\n debugLogger.state('MIGRATION_START', {\n profileCount: config.modelProfiles.length,\n })\n\n // Process each model profile\n const migratedProfiles = await Promise.all(\n config.modelProfiles.map(async profile => {\n if (!profile.apiKey) {\n skipped++\n return profile\n }\n\n // Skip if already encrypted\n if (profile.apiKey.startsWith('encrypted:')) {\n debugLogger.state('MIGRATION_SKIP_ALREADY_ENCRYPTED', {\n modelName: profile.modelName,\n })\n skipped++\n return profile\n }\n\n try {\n // Store the plaintext key in encrypted credential store\n await setApiKey(profile.modelName, profile.apiKey)\n\n // Update the profile to reference the encrypted key\n const migratedProfile = {\n ...profile,\n apiKey: `encrypted:${profile.modelName}`,\n }\n\n debugLogger.state('MIGRATION_SUCCESS', {\n modelName: profile.modelName,\n provider: profile.provider,\n })\n\n migrated++\n return migratedProfile\n } catch (error) {\n const errorMsg =\n error instanceof Error ? error.message : String(error)\n const errorText = `Failed to migrate ${profile.modelName}: ${errorMsg}`\n errors.push(errorText)\n debugLogger.error('MIGRATION_PROFILE_ERROR', {\n modelName: profile.modelName,\n error: errorMsg,\n })\n // Return unchanged profile on error\n return profile\n }\n }),\n )\n\n // Save the migrated config only if something changed\n if (migrated > 0) {\n const updatedConfig: GlobalConfig = {\n ...config,\n modelProfiles: migratedProfiles,\n }\n saveGlobalConfig(updatedConfig)\n debugLogger.state('MIGRATION_CONFIG_SAVED', {\n profilesMigrated: migrated,\n profilesSkipped: skipped,\n })\n }\n\n debugLogger.state('MIGRATION_COMPLETE', {\n migrated,\n skipped,\n errors: errors.length,\n })\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : String(error)\n debugLogger.error('MIGRATION_FATAL_ERROR', {\n error: errorMsg,\n })\n errors.push(`Fatal migration error: ${errorMsg}`)\n }\n\n return { migrated, errors, skipped }\n}\n"],
5
+ "mappings": "AAAA,SAAS,iBAAiB,wBAA2C;AACrE,SAAS,iBAAiB;AAC1B,SAAS,SAAS,mBAAmB;AAsBrC,eAAsB,4BAAsD;AAC1E,QAAM,SAAS,gBAAgB;AAC/B,MAAI,WAAW;AACf,MAAI,UAAU;AACd,QAAM,SAAmB,CAAC;AAE1B,MAAI,CAAC,OAAO,iBAAiB,OAAO,cAAc,WAAW,GAAG;AAC9D,gBAAY,MAAM,yBAAyB,CAAC,CAAC;AAC7C,WAAO,EAAE,UAAU,GAAG,QAAQ,CAAC,GAAG,SAAS,EAAE;AAAA,EAC/C;AAEA,MAAI;AACF,gBAAY,MAAM,mBAAmB;AAAA,MACnC,cAAc,OAAO,cAAc;AAAA,IACrC,CAAC;AAGD,UAAM,mBAAmB,MAAM,QAAQ;AAAA,MACrC,OAAO,cAAc,IAAI,OAAM,YAAW;AACxC,YAAI,CAAC,QAAQ,QAAQ;AACnB;AACA,iBAAO;AAAA,QACT;AAGA,YAAI,QAAQ,OAAO,WAAW,YAAY,GAAG;AAC3C,sBAAY,MAAM,oCAAoC;AAAA,YACpD,WAAW,QAAQ;AAAA,UACrB,CAAC;AACD;AACA,iBAAO;AAAA,QACT;AAEA,YAAI;AAEF,gBAAM,UAAU,QAAQ,WAAW,QAAQ,MAAM;AAGjD,gBAAM,kBAAkB;AAAA,YACtB,GAAG;AAAA,YACH,QAAQ,aAAa,QAAQ,SAAS;AAAA,UACxC;AAEA,sBAAY,MAAM,qBAAqB;AAAA,YACrC,WAAW,QAAQ;AAAA,YACnB,UAAU,QAAQ;AAAA,UACpB,CAAC;AAED;AACA,iBAAO;AAAA,QACT,SAAS,OAAO;AACd,gBAAM,WACJ,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACvD,gBAAM,YAAY,qBAAqB,QAAQ,SAAS,KAAK,QAAQ;AACrE,iBAAO,KAAK,SAAS;AACrB,sBAAY,MAAM,2BAA2B;AAAA,YAC3C,WAAW,QAAQ;AAAA,YACnB,OAAO;AAAA,UACT,CAAC;AAED,iBAAO;AAAA,QACT;AAAA,MACF,CAAC;AAAA,IACH;AAGA,QAAI,WAAW,GAAG;AAChB,YAAM,gBAA8B;AAAA,QAClC,GAAG;AAAA,QACH,eAAe;AAAA,MACjB;AACA,uBAAiB,aAAa;AAC9B,kBAAY,MAAM,0BAA0B;AAAA,QAC1C,kBAAkB;AAAA,QAClB,iBAAiB;AAAA,MACnB,CAAC;AAAA,IACH;AAEA,gBAAY,MAAM,sBAAsB;AAAA,MACtC;AAAA,MACA;AAAA,MACA,QAAQ,OAAO;AAAA,IACjB,CAAC;AAAA,EACH,SAAS,OAAO;AACd,UAAM,WAAW,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACtE,gBAAY,MAAM,yBAAyB;AAAA,MACzC,OAAO;AAAA,IACT,CAAC;AACD,WAAO,KAAK,0BAA0B,QAAQ,EAAE;AAAA,EAClD;AAEA,SAAO,EAAE,UAAU,QAAQ,QAAQ;AACrC;",
6
+ "names": []
7
+ }
@@ -4,8 +4,20 @@ import chalk from "chalk";
4
4
  import { EOL } from "os";
5
5
  import { highlight, supportsLanguage } from "cli-highlight";
6
6
  import { logError } from "./log.js";
7
+ function stripMarkdownCodeBlockWrapper(content) {
8
+ const trimmed = content.trim();
9
+ const codeBlockRegex = /^```(?:markdown|md)?\s*\n([\s\S]*?)\n```$/;
10
+ const match = trimmed.match(codeBlockRegex);
11
+ if (match) {
12
+ return match[1] ?? trimmed;
13
+ }
14
+ return content;
15
+ }
7
16
  function applyMarkdown(content) {
8
- return marked.lexer(stripSystemMessages(content)).map((_) => format(_)).join("").trim();
17
+ const preprocessed = stripMarkdownCodeBlockWrapper(
18
+ stripSystemMessages(content)
19
+ );
20
+ return marked.lexer(preprocessed).map((_) => format(_)).join("").trim();
9
21
  }
10
22
  function format(token, listDepth = 0, orderedListNumber = null, parent = null) {
11
23
  switch (token.type) {