@within-7/minto 0.3.5 → 0.3.9

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 (153) hide show
  1. package/{cli.js → cli.cjs} +25 -23
  2. package/dist/commands/language.js +137 -0
  3. package/dist/commands/language.js.map +7 -0
  4. package/dist/commands/new.js +56 -0
  5. package/dist/commands/new.js.map +7 -0
  6. package/dist/commands/resume.js +251 -16
  7. package/dist/commands/resume.js.map +2 -2
  8. package/dist/commands/sessions.js +224 -0
  9. package/dist/commands/sessions.js.map +7 -0
  10. package/dist/commands/setup.js +3 -2
  11. package/dist/commands/setup.js.map +2 -2
  12. package/dist/commands/stats.js +235 -0
  13. package/dist/commands/stats.js.map +7 -0
  14. package/dist/commands/status.js +11 -5
  15. package/dist/commands/status.js.map +2 -2
  16. package/dist/commands/undo.js +26 -16
  17. package/dist/commands/undo.js.map +2 -2
  18. package/dist/commands.js +6 -0
  19. package/dist/commands.js.map +2 -2
  20. package/dist/components/AskUserQuestionDialog/AskUserQuestionDialog.js +3 -2
  21. package/dist/components/AskUserQuestionDialog/AskUserQuestionDialog.js.map +2 -2
  22. package/dist/components/Config.js +9 -8
  23. package/dist/components/Config.js.map +2 -2
  24. package/dist/components/HeaderBar.js +2 -1
  25. package/dist/components/HeaderBar.js.map +2 -2
  26. package/dist/components/Help.js +2 -1
  27. package/dist/components/Help.js.map +2 -2
  28. package/dist/components/HotkeyHelpPanel.js +46 -44
  29. package/dist/components/HotkeyHelpPanel.js.map +2 -2
  30. package/dist/components/Logo.js +5 -2
  31. package/dist/components/Logo.js.map +2 -2
  32. package/dist/components/MCPServerApprovalDialog.js +6 -5
  33. package/dist/components/MCPServerApprovalDialog.js.map +2 -2
  34. package/dist/components/MCPServerMultiselectDialog.js +5 -4
  35. package/dist/components/MCPServerMultiselectDialog.js.map +2 -2
  36. package/dist/components/MessageSelector.js +4 -3
  37. package/dist/components/MessageSelector.js.map +2 -2
  38. package/dist/components/ModelConfig.js +13 -12
  39. package/dist/components/ModelConfig.js.map +2 -2
  40. package/dist/components/ModelListManager.js +4 -3
  41. package/dist/components/ModelListManager.js.map +2 -2
  42. package/dist/components/PromptInput.js +72 -39
  43. package/dist/components/PromptInput.js.map +2 -2
  44. package/dist/components/SensitiveFileWarning.js +12 -8
  45. package/dist/components/SensitiveFileWarning.js.map +2 -2
  46. package/dist/components/TabbedListView/ScrollableList.js +91 -0
  47. package/dist/components/TabbedListView/ScrollableList.js.map +7 -0
  48. package/dist/components/TabbedListView/SearchInput.js +23 -0
  49. package/dist/components/TabbedListView/SearchInput.js.map +7 -0
  50. package/dist/components/TabbedListView/TabBar.js +20 -0
  51. package/dist/components/TabbedListView/TabBar.js.map +7 -0
  52. package/dist/components/TabbedListView/TabbedListView.js +171 -0
  53. package/dist/components/TabbedListView/TabbedListView.js.map +7 -0
  54. package/dist/components/TabbedListView/index.js +11 -0
  55. package/dist/components/TabbedListView/index.js.map +7 -0
  56. package/dist/components/TabbedListView/types.js +1 -0
  57. package/dist/components/TabbedListView/types.js.map +7 -0
  58. package/dist/components/TodoChangeBlock.js +6 -5
  59. package/dist/components/TodoChangeBlock.js.map +3 -3
  60. package/dist/components/TodoPanel.js +6 -3
  61. package/dist/components/TodoPanel.js.map +3 -3
  62. package/dist/components/TrustDialog.js +6 -5
  63. package/dist/components/TrustDialog.js.map +2 -2
  64. package/dist/components/messages/UserToolResultMessage/UserToolCanceledMessage.js +2 -1
  65. package/dist/components/messages/UserToolResultMessage/UserToolCanceledMessage.js.map +2 -2
  66. package/dist/constants/macros.js +1 -1
  67. package/dist/constants/macros.js.map +1 -1
  68. package/dist/constants/product.js +2 -2
  69. package/dist/constants/product.js.map +1 -1
  70. package/dist/constants/prompts.js +17 -0
  71. package/dist/constants/prompts.js.map +2 -2
  72. package/dist/constants/toolInputExamples.js +5 -1
  73. package/dist/constants/toolInputExamples.js.map +2 -2
  74. package/dist/core/tokenStatsManager.js +5 -0
  75. package/dist/core/tokenStatsManager.js.map +2 -2
  76. package/dist/entrypoints/bootstrap.js +54 -0
  77. package/dist/entrypoints/bootstrap.js.map +7 -0
  78. package/dist/entrypoints/cli.js +132 -23
  79. package/dist/entrypoints/cli.js.map +3 -3
  80. package/dist/history.js +75 -15
  81. package/dist/history.js.map +2 -2
  82. package/dist/i18n/index.js +2 -2
  83. package/dist/i18n/index.js.map +2 -2
  84. package/dist/i18n/locales/en.js +283 -1
  85. package/dist/i18n/locales/en.js.map +2 -2
  86. package/dist/i18n/locales/zh-CN.js +283 -1
  87. package/dist/i18n/locales/zh-CN.js.map +2 -2
  88. package/dist/i18n/types.js.map +1 -1
  89. package/dist/index.js +1 -1
  90. package/dist/index.js.map +2 -2
  91. package/dist/messages.js +11 -0
  92. package/dist/messages.js.map +2 -2
  93. package/dist/permissions.js.map +2 -2
  94. package/dist/query.js +9 -0
  95. package/dist/query.js.map +2 -2
  96. package/dist/screens/REPL.js +45 -7
  97. package/dist/screens/REPL.js.map +2 -2
  98. package/dist/services/customCommands.js +14 -8
  99. package/dist/services/customCommands.js.map +2 -2
  100. package/dist/tools/TaskTool/TaskTool.js +176 -1
  101. package/dist/tools/TaskTool/TaskTool.js.map +2 -2
  102. package/dist/tools/TodoWriteTool/prompt.js +21 -0
  103. package/dist/tools/TodoWriteTool/prompt.js.map +2 -2
  104. package/dist/tools/URLFetcherTool/prompt.js +14 -9
  105. package/dist/tools/URLFetcherTool/prompt.js.map +2 -2
  106. package/dist/tools/WebSearchTool/prompt.js +12 -6
  107. package/dist/tools/WebSearchTool/prompt.js.map +2 -2
  108. package/dist/types/PermissionMode.js +30 -1
  109. package/dist/types/PermissionMode.js.map +2 -2
  110. package/dist/types/plugin.js.map +2 -2
  111. package/dist/utils/agentHookExecutor.js +106 -0
  112. package/dist/utils/agentHookExecutor.js.map +7 -0
  113. package/dist/utils/agentLoader.js +212 -26
  114. package/dist/utils/agentLoader.js.map +2 -2
  115. package/dist/utils/agentMemory.js +134 -0
  116. package/dist/utils/agentMemory.js.map +7 -0
  117. package/dist/utils/config.js +51 -1
  118. package/dist/utils/config.js.map +2 -2
  119. package/dist/utils/configPaths.js +199 -0
  120. package/dist/utils/configPaths.js.map +7 -0
  121. package/dist/utils/historyManager.js +234 -0
  122. package/dist/utils/historyManager.js.map +7 -0
  123. package/dist/utils/messages.js +13 -8
  124. package/dist/utils/messages.js.map +2 -2
  125. package/dist/utils/migration/index.js +37 -0
  126. package/dist/utils/migration/index.js.map +7 -0
  127. package/dist/utils/migration/migrateHistory.js +273 -0
  128. package/dist/utils/migration/migrateHistory.js.map +7 -0
  129. package/dist/utils/migration/migrateTodos.js +323 -0
  130. package/dist/utils/migration/migrateTodos.js.map +7 -0
  131. package/dist/utils/pasteCache.js +309 -0
  132. package/dist/utils/pasteCache.js.map +7 -0
  133. package/dist/utils/pluginLoader.js +6 -3
  134. package/dist/utils/pluginLoader.js.map +2 -2
  135. package/dist/utils/sessionIndex.js +192 -0
  136. package/dist/utils/sessionIndex.js.map +7 -0
  137. package/dist/utils/sessionTracker.js +170 -0
  138. package/dist/utils/sessionTracker.js.map +7 -0
  139. package/dist/utils/skillLoader.js +91 -5
  140. package/dist/utils/skillLoader.js.map +2 -2
  141. package/dist/utils/stats.js +417 -0
  142. package/dist/utils/stats.js.map +7 -0
  143. package/dist/utils/stringSubstitution.js +107 -0
  144. package/dist/utils/stringSubstitution.js.map +7 -0
  145. package/dist/utils/teamConfig.js +3 -1
  146. package/dist/utils/teamConfig.js.map +2 -2
  147. package/dist/utils/todoStorage.js +51 -19
  148. package/dist/utils/todoStorage.js.map +2 -2
  149. package/dist/utils/tooling/safeRender.js.map +2 -2
  150. package/dist/version.js +2 -2
  151. package/dist/version.js.map +1 -1
  152. package/package.json +71 -28
  153. package/scripts/{postinstall.js → postinstall.cjs} +1 -1
@@ -0,0 +1,134 @@
1
+ import {
2
+ existsSync,
3
+ readFileSync,
4
+ writeFileSync,
5
+ mkdirSync,
6
+ unlinkSync
7
+ } from "fs";
8
+ import { join, dirname } from "path";
9
+ import { homedir } from "os";
10
+ import { getCwd } from "./state.js";
11
+ function getMemoryBasePath(scope) {
12
+ const cwd = getCwd();
13
+ switch (scope) {
14
+ case "user":
15
+ return join(homedir(), ".minto", "memory");
16
+ case "project":
17
+ return join(cwd, ".minto", "memory");
18
+ case "local":
19
+ return join(cwd, ".minto", ".memory");
20
+ // Gitignored by convention
21
+ default:
22
+ return join(cwd, ".minto", "memory");
23
+ }
24
+ }
25
+ function getMemoryFilePath(agentType, memory) {
26
+ const basePath = getMemoryBasePath(memory.scope);
27
+ const key = memory.key || agentType;
28
+ const sanitizedKey = key.replace(/[^a-zA-Z0-9_-]/g, "_");
29
+ return join(basePath, `${sanitizedKey}.json`);
30
+ }
31
+ async function loadAgentMemory(agentType, memory) {
32
+ const filePath = getMemoryFilePath(agentType, memory);
33
+ if (!existsSync(filePath)) {
34
+ return null;
35
+ }
36
+ try {
37
+ const data = JSON.parse(readFileSync(filePath, "utf-8"));
38
+ return data.content;
39
+ } catch (error) {
40
+ console.warn(`Failed to load agent memory from ${filePath}:`, error);
41
+ return null;
42
+ }
43
+ }
44
+ async function saveAgentMemory(agentType, memory, content) {
45
+ const filePath = getMemoryFilePath(agentType, memory);
46
+ const dirPath = dirname(filePath);
47
+ try {
48
+ if (!existsSync(dirPath)) {
49
+ mkdirSync(dirPath, { recursive: true });
50
+ }
51
+ let version = 1;
52
+ if (existsSync(filePath)) {
53
+ try {
54
+ const existing = JSON.parse(
55
+ readFileSync(filePath, "utf-8")
56
+ );
57
+ version = (existing.version || 0) + 1;
58
+ } catch {
59
+ }
60
+ }
61
+ const entry = {
62
+ content,
63
+ updatedAt: Date.now(),
64
+ agentType,
65
+ version
66
+ };
67
+ writeFileSync(filePath, JSON.stringify(entry, null, 2), "utf-8");
68
+ } catch (error) {
69
+ console.error(`Failed to save agent memory to ${filePath}:`, error);
70
+ throw error;
71
+ }
72
+ }
73
+ async function deleteAgentMemory(agentType, memory) {
74
+ const filePath = getMemoryFilePath(agentType, memory);
75
+ if (existsSync(filePath)) {
76
+ try {
77
+ unlinkSync(filePath);
78
+ } catch (error) {
79
+ console.warn(`Failed to delete agent memory at ${filePath}:`, error);
80
+ }
81
+ }
82
+ }
83
+ function hasAgentMemory(agentType, memory) {
84
+ const filePath = getMemoryFilePath(agentType, memory);
85
+ return existsSync(filePath);
86
+ }
87
+ async function getAgentMemoryMetadata(agentType, memory) {
88
+ const filePath = getMemoryFilePath(agentType, memory);
89
+ if (!existsSync(filePath)) {
90
+ return null;
91
+ }
92
+ try {
93
+ const data = JSON.parse(readFileSync(filePath, "utf-8"));
94
+ return {
95
+ updatedAt: data.updatedAt,
96
+ version: data.version
97
+ };
98
+ } catch {
99
+ return null;
100
+ }
101
+ }
102
+ function formatMemoryForPrompt(content, agentType) {
103
+ return `
104
+ <agent-memory agent="${agentType}">
105
+ ${content}
106
+ </agent-memory>
107
+ `;
108
+ }
109
+ function ensureLocalMemoryGitignored() {
110
+ const cwd = getCwd();
111
+ const gitignorePath = join(cwd, ".gitignore");
112
+ const memoryPattern = ".minto/.memory";
113
+ try {
114
+ if (existsSync(gitignorePath)) {
115
+ const content = readFileSync(gitignorePath, "utf-8");
116
+ if (!content.includes(memoryPattern)) {
117
+ console.debug(
118
+ `Consider adding '${memoryPattern}' to .gitignore for local agent memory`
119
+ );
120
+ }
121
+ }
122
+ } catch {
123
+ }
124
+ }
125
+ export {
126
+ deleteAgentMemory,
127
+ ensureLocalMemoryGitignored,
128
+ formatMemoryForPrompt,
129
+ getAgentMemoryMetadata,
130
+ hasAgentMemory,
131
+ loadAgentMemory,
132
+ saveAgentMemory
133
+ };
134
+ //# sourceMappingURL=agentMemory.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/utils/agentMemory.ts"],
4
+ "sourcesContent": ["/**\n * Agent Memory Persistence\n *\n * Implements Claude Code specification for agent memory persistence.\n * Supports three scopes:\n * - user: ~/.minto/memory/ (persists across all projects)\n * - project: ./.minto/memory/ (persists within project, tracked in git)\n * - local: ./.minto/.memory/ (persists within project, gitignored)\n */\n\nimport {\n existsSync,\n readFileSync,\n writeFileSync,\n mkdirSync,\n unlinkSync,\n} from 'fs'\nimport { join, dirname } from 'path'\nimport { homedir } from 'os'\nimport { getCwd } from './state'\nimport type { AgentMemory } from './agentLoader'\n\n/**\n * Memory entry structure\n */\ninterface MemoryEntry {\n content: string\n updatedAt: number\n agentType: string\n version: number\n}\n\n/**\n * Get the base path for memory storage based on scope\n */\nfunction getMemoryBasePath(scope: AgentMemory['scope']): string {\n const cwd = getCwd()\n\n switch (scope) {\n case 'user':\n return join(homedir(), '.minto', 'memory')\n case 'project':\n return join(cwd, '.minto', 'memory')\n case 'local':\n return join(cwd, '.minto', '.memory') // Gitignored by convention\n default:\n return join(cwd, '.minto', 'memory')\n }\n}\n\n/**\n * Get the full path for a memory file\n */\nfunction getMemoryFilePath(\n agentType: string,\n memory: AgentMemory,\n): string {\n const basePath = getMemoryBasePath(memory.scope)\n const key = memory.key || agentType\n // Sanitize key to be a valid filename\n const sanitizedKey = key.replace(/[^a-zA-Z0-9_-]/g, '_')\n return join(basePath, `${sanitizedKey}.json`)\n}\n\n/**\n * Load agent memory from persistent storage\n *\n * @param agentType - The agent type identifier\n * @param memory - Memory configuration\n * @returns Memory content if found, null otherwise\n */\nexport async function loadAgentMemory(\n agentType: string,\n memory: AgentMemory,\n): Promise<string | null> {\n const filePath = getMemoryFilePath(agentType, memory)\n\n if (!existsSync(filePath)) {\n return null\n }\n\n try {\n const data = JSON.parse(readFileSync(filePath, 'utf-8')) as MemoryEntry\n return data.content\n } catch (error) {\n console.warn(`Failed to load agent memory from ${filePath}:`, error)\n return null\n }\n}\n\n/**\n * Save agent memory to persistent storage\n *\n * @param agentType - The agent type identifier\n * @param memory - Memory configuration\n * @param content - Content to save\n */\nexport async function saveAgentMemory(\n agentType: string,\n memory: AgentMemory,\n content: string,\n): Promise<void> {\n const filePath = getMemoryFilePath(agentType, memory)\n const dirPath = dirname(filePath)\n\n try {\n // Ensure directory exists\n if (!existsSync(dirPath)) {\n mkdirSync(dirPath, { recursive: true })\n }\n\n // Load existing entry to preserve version\n let version = 1\n if (existsSync(filePath)) {\n try {\n const existing = JSON.parse(\n readFileSync(filePath, 'utf-8'),\n ) as MemoryEntry\n version = (existing.version || 0) + 1\n } catch {\n // Ignore parse errors, start fresh\n }\n }\n\n const entry: MemoryEntry = {\n content,\n updatedAt: Date.now(),\n agentType,\n version,\n }\n\n writeFileSync(filePath, JSON.stringify(entry, null, 2), 'utf-8')\n } catch (error) {\n console.error(`Failed to save agent memory to ${filePath}:`, error)\n throw error\n }\n}\n\n/**\n * Delete agent memory from persistent storage\n *\n * @param agentType - The agent type identifier\n * @param memory - Memory configuration\n */\nexport async function deleteAgentMemory(\n agentType: string,\n memory: AgentMemory,\n): Promise<void> {\n const filePath = getMemoryFilePath(agentType, memory)\n\n if (existsSync(filePath)) {\n try {\n unlinkSync(filePath)\n } catch (error) {\n console.warn(`Failed to delete agent memory at ${filePath}:`, error)\n }\n }\n}\n\n/**\n * Check if agent memory exists\n *\n * @param agentType - The agent type identifier\n * @param memory - Memory configuration\n * @returns True if memory exists\n */\nexport function hasAgentMemory(\n agentType: string,\n memory: AgentMemory,\n): boolean {\n const filePath = getMemoryFilePath(agentType, memory)\n return existsSync(filePath)\n}\n\n/**\n * Get memory metadata without loading content\n *\n * @param agentType - The agent type identifier\n * @param memory - Memory configuration\n * @returns Metadata if found, null otherwise\n */\nexport async function getAgentMemoryMetadata(\n agentType: string,\n memory: AgentMemory,\n): Promise<{ updatedAt: number; version: number } | null> {\n const filePath = getMemoryFilePath(agentType, memory)\n\n if (!existsSync(filePath)) {\n return null\n }\n\n try {\n const data = JSON.parse(readFileSync(filePath, 'utf-8')) as MemoryEntry\n return {\n updatedAt: data.updatedAt,\n version: data.version,\n }\n } catch {\n return null\n }\n}\n\n/**\n * Format memory content for injection into system prompt\n *\n * @param content - Memory content\n * @param agentType - Agent type for context\n * @returns Formatted memory section for system prompt\n */\nexport function formatMemoryForPrompt(\n content: string,\n agentType: string,\n): string {\n return `\n<agent-memory agent=\"${agentType}\">\n${content}\n</agent-memory>\n`\n}\n\n/**\n * Ensure the .memory directory is gitignored for 'local' scope\n * This should be called once during initialization\n */\nexport function ensureLocalMemoryGitignored(): void {\n const cwd = getCwd()\n const gitignorePath = join(cwd, '.gitignore')\n const memoryPattern = '.minto/.memory'\n\n try {\n if (existsSync(gitignorePath)) {\n const content = readFileSync(gitignorePath, 'utf-8')\n if (!content.includes(memoryPattern)) {\n // Could optionally append to .gitignore, but for now just warn\n console.debug(\n `Consider adding '${memoryPattern}' to .gitignore for local agent memory`,\n )\n }\n }\n } catch {\n // Ignore errors reading .gitignore\n }\n}\n"],
5
+ "mappings": "AAUA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,MAAM,eAAe;AAC9B,SAAS,eAAe;AACxB,SAAS,cAAc;AAgBvB,SAAS,kBAAkB,OAAqC;AAC9D,QAAM,MAAM,OAAO;AAEnB,UAAQ,OAAO;AAAA,IACb,KAAK;AACH,aAAO,KAAK,QAAQ,GAAG,UAAU,QAAQ;AAAA,IAC3C,KAAK;AACH,aAAO,KAAK,KAAK,UAAU,QAAQ;AAAA,IACrC,KAAK;AACH,aAAO,KAAK,KAAK,UAAU,SAAS;AAAA;AAAA,IACtC;AACE,aAAO,KAAK,KAAK,UAAU,QAAQ;AAAA,EACvC;AACF;AAKA,SAAS,kBACP,WACA,QACQ;AACR,QAAM,WAAW,kBAAkB,OAAO,KAAK;AAC/C,QAAM,MAAM,OAAO,OAAO;AAE1B,QAAM,eAAe,IAAI,QAAQ,mBAAmB,GAAG;AACvD,SAAO,KAAK,UAAU,GAAG,YAAY,OAAO;AAC9C;AASA,eAAsB,gBACpB,WACA,QACwB;AACxB,QAAM,WAAW,kBAAkB,WAAW,MAAM;AAEpD,MAAI,CAAC,WAAW,QAAQ,GAAG;AACzB,WAAO;AAAA,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;AAEpD,MAAI,CAAC,WAAW,QAAQ,GAAG;AACzB,WAAO;AAAA,EACT;AAEA,MAAI;AACF,UAAM,OAAO,KAAK,MAAM,aAAa,UAAU,OAAO,CAAC;AACvD,WAAO;AAAA,MACL,WAAW,KAAK;AAAA,MAChB,SAAS,KAAK;AAAA,IAChB;AAAA,EACF,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AASO,SAAS,sBACd,SACA,WACQ;AACR,SAAO;AAAA,uBACc,SAAS;AAAA,EAC9B,OAAO;AAAA;AAAA;AAGT;AAMO,SAAS,8BAAoC;AAClD,QAAM,MAAM,OAAO;AACnB,QAAM,gBAAgB,KAAK,KAAK,YAAY;AAC5C,QAAM,gBAAgB;AAEtB,MAAI;AACF,QAAI,WAAW,aAAa,GAAG;AAC7B,YAAM,UAAU,aAAa,eAAe,OAAO;AACnD,UAAI,CAAC,QAAQ,SAAS,aAAa,GAAG;AAEpC,gBAAQ;AAAA,UACN,oBAAoB,aAAa;AAAA,QACnC;AAAA,MACF;AAAA,IACF;AAAA,EACF,QAAQ;AAAA,EAER;AACF;",
6
+ "names": []
7
+ }
@@ -181,7 +181,39 @@ function getGlobalConfig() {
181
181
  }
182
182
  const config = getConfig(GLOBAL_CONFIG_FILE, DEFAULT_GLOBAL_CONFIG);
183
183
  const migratedConfig = migrateModelProfilesRemoveId(config);
184
- return migrateDisplayModeToVerbose(migratedConfig);
184
+ const displayMigratedConfig = migrateDisplayModeToVerbose(migratedConfig);
185
+ if (displayMigratedConfig.modelProfiles && displayMigratedConfig.modelProfiles.length > 0) {
186
+ const originalCount = displayMigratedConfig.modelProfiles.length;
187
+ const deduplicatedProfiles = deduplicateModelProfiles(
188
+ displayMigratedConfig.modelProfiles
189
+ );
190
+ const deduplicatedCount = deduplicatedProfiles.length;
191
+ if (deduplicatedCount < originalCount) {
192
+ debugLogger.state("CONFIG_DEDUPLICATE_PROFILES", {
193
+ originalCount: String(originalCount),
194
+ deduplicatedCount: String(deduplicatedCount),
195
+ removedCount: String(originalCount - deduplicatedCount)
196
+ });
197
+ const configToSave = {
198
+ ...displayMigratedConfig,
199
+ modelProfiles: deduplicatedProfiles
200
+ };
201
+ saveConfig(
202
+ GLOBAL_CONFIG_FILE,
203
+ {
204
+ ...configToSave,
205
+ projects: config.projects
206
+ },
207
+ DEFAULT_GLOBAL_CONFIG
208
+ );
209
+ return configToSave;
210
+ }
211
+ return {
212
+ ...displayMigratedConfig,
213
+ modelProfiles: deduplicatedProfiles
214
+ };
215
+ }
216
+ return displayMigratedConfig;
185
217
  }
186
218
  function getAnthropicApiKey() {
187
219
  return process.env.ANTHROPIC_API_KEY || null;
@@ -547,6 +579,23 @@ function migrateModelProfilesRemoveId(config) {
547
579
  defaultModelName
548
580
  };
549
581
  }
582
+ function deduplicateModelProfiles(profiles) {
583
+ if (!profiles || profiles.length === 0) {
584
+ return [];
585
+ }
586
+ const profileMap = /* @__PURE__ */ new Map();
587
+ for (const profile of profiles) {
588
+ const existing = profileMap.get(profile.modelName);
589
+ if (!existing) {
590
+ profileMap.set(profile.modelName, profile);
591
+ } else {
592
+ if (profile.createdAt > existing.createdAt) {
593
+ profileMap.set(profile.modelName, profile);
594
+ }
595
+ }
596
+ }
597
+ return Array.from(profileMap.values());
598
+ }
550
599
  function setAllPointersToModel(modelName) {
551
600
  const config = getGlobalConfig();
552
601
  const updatedConfig = {
@@ -729,6 +778,7 @@ export {
729
778
  checkHasTrustDialogAccepted,
730
779
  clearMcprcConfigForTesting,
731
780
  createGPT5ModelProfile,
781
+ deduplicateModelProfiles,
732
782
  deleteConfigForCLI,
733
783
  displayModeToVerbose,
734
784
  enableConfigs,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/utils/config.ts"],
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 * - 'free': Project directory operations auto-allowed, outside requires confirmation\n */\nexport type SafetyMode = 'yolo' | 'smart' | 'strict' | 'free'\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 (4-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 * - 'free': Project directory operations auto-allowed, outside requires 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,0BAA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C/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 * - 'free': Project directory operations auto-allowed, outside requires confirmation\n */\nexport type SafetyMode = 'yolo' | 'smart' | 'strict' | 'free'\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 (4-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 * - 'free': Project directory operations auto-allowed, outside requires 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 const displayMigratedConfig = migrateDisplayModeToVerbose(migratedConfig)\n\n // Apply model profile deduplication\n if (\n displayMigratedConfig.modelProfiles &&\n displayMigratedConfig.modelProfiles.length > 0\n ) {\n const originalCount = displayMigratedConfig.modelProfiles.length\n const deduplicatedProfiles = deduplicateModelProfiles(\n displayMigratedConfig.modelProfiles,\n )\n const deduplicatedCount = deduplicatedProfiles.length\n\n // If duplicates were found and removed, auto-save the deduplicated config\n if (deduplicatedCount < originalCount) {\n debugLogger.state('CONFIG_DEDUPLICATE_PROFILES', {\n originalCount: String(originalCount),\n deduplicatedCount: String(deduplicatedCount),\n removedCount: String(originalCount - deduplicatedCount),\n })\n const configToSave = {\n ...displayMigratedConfig,\n modelProfiles: deduplicatedProfiles,\n }\n // Save the deduplicated config (avoid recursion by using saveConfig directly)\n saveConfig(\n GLOBAL_CONFIG_FILE,\n {\n ...configToSave,\n projects: config.projects,\n },\n DEFAULT_GLOBAL_CONFIG,\n )\n return configToSave\n }\n\n return {\n ...displayMigratedConfig,\n modelProfiles: deduplicatedProfiles,\n }\n }\n\n return displayMigratedConfig\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\n/**\n * Deduplicate model profiles by modelName, keeping the one with the latest createdAt timestamp.\n *\n * @param profiles - Array of model profiles to deduplicate\n * @returns Deduplicated array of model profiles\n */\nexport function deduplicateModelProfiles(\n profiles: ModelProfile[],\n): ModelProfile[] {\n if (!profiles || profiles.length === 0) {\n return []\n }\n\n // Use Map to track the latest profile for each modelName\n const profileMap = new Map<string, ModelProfile>()\n\n for (const profile of profiles) {\n const existing = profileMap.get(profile.modelName)\n\n if (!existing) {\n // First occurrence of this modelName\n profileMap.set(profile.modelName, profile)\n } else {\n // Keep the one with the latest createdAt timestamp\n if (profile.createdAt > existing.createdAt) {\n profileMap.set(profile.modelName, profile)\n }\n }\n }\n\n // Return as array, preserving insertion order (which follows original array order for first occurrences)\n return Array.from(profileMap.values())\n}\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,qBAAqB;AAAA,EACrB,gBAAgB,CAAC;AAAA,EACjB,YAAY,CAAC;AAAA,EACb,sBAAsB,CAAC;AAAA,EACvB,sBAAsB,CAAC;AAAA,E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