@shareai-lab/kode 1.0.70 → 1.0.73

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 (278) hide show
  1. package/README.md +342 -75
  2. package/README.zh-CN.md +292 -0
  3. package/cli.js +62 -0
  4. package/package.json +49 -25
  5. package/scripts/postinstall.js +56 -0
  6. package/src/ProjectOnboarding.tsx +198 -0
  7. package/src/Tool.ts +82 -0
  8. package/src/commands/agents.tsx +3401 -0
  9. package/src/commands/approvedTools.ts +53 -0
  10. package/src/commands/bug.tsx +20 -0
  11. package/src/commands/clear.ts +43 -0
  12. package/src/commands/compact.ts +120 -0
  13. package/src/commands/config.tsx +19 -0
  14. package/src/commands/cost.ts +18 -0
  15. package/src/commands/ctx_viz.ts +209 -0
  16. package/src/commands/doctor.ts +24 -0
  17. package/src/commands/help.tsx +19 -0
  18. package/src/commands/init.ts +37 -0
  19. package/src/commands/listen.ts +42 -0
  20. package/src/commands/login.tsx +51 -0
  21. package/src/commands/logout.tsx +40 -0
  22. package/src/commands/mcp.ts +41 -0
  23. package/src/commands/model.tsx +40 -0
  24. package/src/commands/modelstatus.tsx +20 -0
  25. package/src/commands/onboarding.tsx +34 -0
  26. package/src/commands/pr_comments.ts +59 -0
  27. package/src/commands/refreshCommands.ts +54 -0
  28. package/src/commands/release-notes.ts +34 -0
  29. package/src/commands/resume.tsx +31 -0
  30. package/src/commands/review.ts +49 -0
  31. package/src/commands/terminalSetup.ts +221 -0
  32. package/src/commands.ts +139 -0
  33. package/src/components/ApproveApiKey.tsx +93 -0
  34. package/src/components/AsciiLogo.tsx +13 -0
  35. package/src/components/AutoUpdater.tsx +148 -0
  36. package/src/components/Bug.tsx +367 -0
  37. package/src/components/Config.tsx +293 -0
  38. package/src/components/ConsoleOAuthFlow.tsx +327 -0
  39. package/src/components/Cost.tsx +23 -0
  40. package/src/components/CostThresholdDialog.tsx +46 -0
  41. package/src/components/CustomSelect/option-map.ts +42 -0
  42. package/src/components/CustomSelect/select-option.tsx +78 -0
  43. package/src/components/CustomSelect/select.tsx +152 -0
  44. package/src/components/CustomSelect/theme.ts +45 -0
  45. package/src/components/CustomSelect/use-select-state.ts +414 -0
  46. package/src/components/CustomSelect/use-select.ts +35 -0
  47. package/src/components/FallbackToolUseRejectedMessage.tsx +15 -0
  48. package/src/components/FileEditToolUpdatedMessage.tsx +66 -0
  49. package/src/components/Help.tsx +215 -0
  50. package/src/components/HighlightedCode.tsx +33 -0
  51. package/src/components/InvalidConfigDialog.tsx +113 -0
  52. package/src/components/Link.tsx +32 -0
  53. package/src/components/LogSelector.tsx +86 -0
  54. package/src/components/Logo.tsx +145 -0
  55. package/src/components/MCPServerApprovalDialog.tsx +100 -0
  56. package/src/components/MCPServerDialogCopy.tsx +25 -0
  57. package/src/components/MCPServerMultiselectDialog.tsx +109 -0
  58. package/src/components/Message.tsx +221 -0
  59. package/src/components/MessageResponse.tsx +15 -0
  60. package/src/components/MessageSelector.tsx +211 -0
  61. package/src/components/ModeIndicator.tsx +88 -0
  62. package/src/components/ModelConfig.tsx +301 -0
  63. package/src/components/ModelListManager.tsx +227 -0
  64. package/src/components/ModelSelector.tsx +3386 -0
  65. package/src/components/ModelStatusDisplay.tsx +230 -0
  66. package/src/components/Onboarding.tsx +274 -0
  67. package/src/components/PressEnterToContinue.tsx +11 -0
  68. package/src/components/PromptInput.tsx +740 -0
  69. package/src/components/SentryErrorBoundary.ts +33 -0
  70. package/src/components/Spinner.tsx +129 -0
  71. package/src/components/StickerRequestForm.tsx +16 -0
  72. package/src/components/StructuredDiff.tsx +191 -0
  73. package/src/components/TextInput.tsx +259 -0
  74. package/src/components/TodoItem.tsx +11 -0
  75. package/src/components/TokenWarning.tsx +31 -0
  76. package/src/components/ToolUseLoader.tsx +40 -0
  77. package/src/components/TrustDialog.tsx +106 -0
  78. package/src/components/binary-feedback/BinaryFeedback.tsx +63 -0
  79. package/src/components/binary-feedback/BinaryFeedbackOption.tsx +111 -0
  80. package/src/components/binary-feedback/BinaryFeedbackView.tsx +172 -0
  81. package/src/components/binary-feedback/utils.ts +220 -0
  82. package/src/components/messages/AssistantBashOutputMessage.tsx +22 -0
  83. package/src/components/messages/AssistantLocalCommandOutputMessage.tsx +49 -0
  84. package/src/components/messages/AssistantRedactedThinkingMessage.tsx +19 -0
  85. package/src/components/messages/AssistantTextMessage.tsx +144 -0
  86. package/src/components/messages/AssistantThinkingMessage.tsx +40 -0
  87. package/src/components/messages/AssistantToolUseMessage.tsx +133 -0
  88. package/src/components/messages/TaskProgressMessage.tsx +32 -0
  89. package/src/components/messages/TaskToolMessage.tsx +58 -0
  90. package/src/components/messages/UserBashInputMessage.tsx +28 -0
  91. package/src/components/messages/UserCommandMessage.tsx +30 -0
  92. package/src/components/messages/UserKodingInputMessage.tsx +28 -0
  93. package/src/components/messages/UserPromptMessage.tsx +35 -0
  94. package/src/components/messages/UserTextMessage.tsx +39 -0
  95. package/src/components/messages/UserToolResultMessage/UserToolCanceledMessage.tsx +12 -0
  96. package/src/components/messages/UserToolResultMessage/UserToolErrorMessage.tsx +36 -0
  97. package/src/components/messages/UserToolResultMessage/UserToolRejectMessage.tsx +31 -0
  98. package/src/components/messages/UserToolResultMessage/UserToolResultMessage.tsx +57 -0
  99. package/src/components/messages/UserToolResultMessage/UserToolSuccessMessage.tsx +35 -0
  100. package/src/components/messages/UserToolResultMessage/utils.tsx +56 -0
  101. package/src/components/permissions/BashPermissionRequest/BashPermissionRequest.tsx +121 -0
  102. package/src/components/permissions/FallbackPermissionRequest.tsx +153 -0
  103. package/src/components/permissions/FileEditPermissionRequest/FileEditPermissionRequest.tsx +182 -0
  104. package/src/components/permissions/FileEditPermissionRequest/FileEditToolDiff.tsx +77 -0
  105. package/src/components/permissions/FileWritePermissionRequest/FileWritePermissionRequest.tsx +164 -0
  106. package/src/components/permissions/FileWritePermissionRequest/FileWriteToolDiff.tsx +83 -0
  107. package/src/components/permissions/FilesystemPermissionRequest/FilesystemPermissionRequest.tsx +240 -0
  108. package/src/components/permissions/PermissionRequest.tsx +101 -0
  109. package/src/components/permissions/PermissionRequestTitle.tsx +69 -0
  110. package/src/components/permissions/hooks.ts +44 -0
  111. package/src/components/permissions/toolUseOptions.ts +59 -0
  112. package/src/components/permissions/utils.ts +23 -0
  113. package/src/constants/betas.ts +5 -0
  114. package/src/constants/claude-asterisk-ascii-art.tsx +238 -0
  115. package/src/constants/figures.ts +4 -0
  116. package/src/constants/keys.ts +3 -0
  117. package/src/constants/macros.ts +8 -0
  118. package/src/constants/modelCapabilities.ts +179 -0
  119. package/src/constants/models.ts +1025 -0
  120. package/src/constants/oauth.ts +18 -0
  121. package/src/constants/product.ts +17 -0
  122. package/src/constants/prompts.ts +177 -0
  123. package/src/constants/releaseNotes.ts +7 -0
  124. package/src/context/PermissionContext.tsx +149 -0
  125. package/src/context.ts +278 -0
  126. package/src/cost-tracker.ts +84 -0
  127. package/src/entrypoints/cli.tsx +1518 -0
  128. package/src/entrypoints/mcp.ts +176 -0
  129. package/src/history.ts +25 -0
  130. package/src/hooks/useApiKeyVerification.ts +59 -0
  131. package/src/hooks/useArrowKeyHistory.ts +55 -0
  132. package/src/hooks/useCanUseTool.ts +138 -0
  133. package/src/hooks/useCancelRequest.ts +39 -0
  134. package/src/hooks/useDoublePress.ts +42 -0
  135. package/src/hooks/useExitOnCtrlCD.ts +31 -0
  136. package/src/hooks/useInterval.ts +25 -0
  137. package/src/hooks/useLogMessages.ts +16 -0
  138. package/src/hooks/useLogStartupTime.ts +12 -0
  139. package/src/hooks/useNotifyAfterTimeout.ts +65 -0
  140. package/src/hooks/usePermissionRequestLogging.ts +44 -0
  141. package/src/hooks/useTerminalSize.ts +49 -0
  142. package/src/hooks/useTextInput.ts +318 -0
  143. package/src/hooks/useUnifiedCompletion.ts +1404 -0
  144. package/src/messages.ts +38 -0
  145. package/src/permissions.ts +268 -0
  146. package/src/query.ts +707 -0
  147. package/src/screens/ConfigureNpmPrefix.tsx +197 -0
  148. package/src/screens/Doctor.tsx +219 -0
  149. package/src/screens/LogList.tsx +68 -0
  150. package/src/screens/REPL.tsx +798 -0
  151. package/src/screens/ResumeConversation.tsx +68 -0
  152. package/src/services/adapters/base.ts +38 -0
  153. package/src/services/adapters/chatCompletions.ts +90 -0
  154. package/src/services/adapters/responsesAPI.ts +170 -0
  155. package/src/services/browserMocks.ts +66 -0
  156. package/src/services/claude.ts +2083 -0
  157. package/src/services/customCommands.ts +704 -0
  158. package/src/services/fileFreshness.ts +377 -0
  159. package/src/services/gpt5ConnectionTest.ts +340 -0
  160. package/src/services/mcpClient.ts +564 -0
  161. package/src/services/mcpServerApproval.tsx +50 -0
  162. package/src/services/mentionProcessor.ts +273 -0
  163. package/src/services/modelAdapterFactory.ts +69 -0
  164. package/src/services/notifier.ts +40 -0
  165. package/src/services/oauth.ts +357 -0
  166. package/src/services/openai.ts +1305 -0
  167. package/src/services/responseStateManager.ts +90 -0
  168. package/src/services/sentry.ts +3 -0
  169. package/src/services/statsig.ts +171 -0
  170. package/src/services/statsigStorage.ts +86 -0
  171. package/src/services/systemReminder.ts +507 -0
  172. package/src/services/vcr.ts +161 -0
  173. package/src/test/testAdapters.ts +96 -0
  174. package/src/tools/ArchitectTool/ArchitectTool.tsx +122 -0
  175. package/src/tools/ArchitectTool/prompt.ts +15 -0
  176. package/src/tools/AskExpertModelTool/AskExpertModelTool.tsx +569 -0
  177. package/src/tools/BashTool/BashTool.tsx +243 -0
  178. package/src/tools/BashTool/BashToolResultMessage.tsx +38 -0
  179. package/src/tools/BashTool/OutputLine.tsx +49 -0
  180. package/src/tools/BashTool/prompt.ts +174 -0
  181. package/src/tools/BashTool/utils.ts +56 -0
  182. package/src/tools/FileEditTool/FileEditTool.tsx +315 -0
  183. package/src/tools/FileEditTool/prompt.ts +51 -0
  184. package/src/tools/FileEditTool/utils.ts +58 -0
  185. package/src/tools/FileReadTool/FileReadTool.tsx +404 -0
  186. package/src/tools/FileReadTool/prompt.ts +7 -0
  187. package/src/tools/FileWriteTool/FileWriteTool.tsx +297 -0
  188. package/src/tools/FileWriteTool/prompt.ts +10 -0
  189. package/src/tools/GlobTool/GlobTool.tsx +119 -0
  190. package/src/tools/GlobTool/prompt.ts +8 -0
  191. package/src/tools/GrepTool/GrepTool.tsx +147 -0
  192. package/src/tools/GrepTool/prompt.ts +11 -0
  193. package/src/tools/MCPTool/MCPTool.tsx +107 -0
  194. package/src/tools/MCPTool/prompt.ts +3 -0
  195. package/src/tools/MemoryReadTool/MemoryReadTool.tsx +127 -0
  196. package/src/tools/MemoryReadTool/prompt.ts +3 -0
  197. package/src/tools/MemoryWriteTool/MemoryWriteTool.tsx +89 -0
  198. package/src/tools/MemoryWriteTool/prompt.ts +3 -0
  199. package/src/tools/MultiEditTool/MultiEditTool.tsx +366 -0
  200. package/src/tools/MultiEditTool/prompt.ts +45 -0
  201. package/src/tools/NotebookEditTool/NotebookEditTool.tsx +298 -0
  202. package/src/tools/NotebookEditTool/prompt.ts +3 -0
  203. package/src/tools/NotebookReadTool/NotebookReadTool.tsx +258 -0
  204. package/src/tools/NotebookReadTool/prompt.ts +3 -0
  205. package/src/tools/StickerRequestTool/StickerRequestTool.tsx +93 -0
  206. package/src/tools/StickerRequestTool/prompt.ts +19 -0
  207. package/src/tools/TaskTool/TaskTool.tsx +466 -0
  208. package/src/tools/TaskTool/constants.ts +1 -0
  209. package/src/tools/TaskTool/prompt.ts +92 -0
  210. package/src/tools/ThinkTool/ThinkTool.tsx +54 -0
  211. package/src/tools/ThinkTool/prompt.ts +12 -0
  212. package/src/tools/TodoWriteTool/TodoWriteTool.tsx +290 -0
  213. package/src/tools/TodoWriteTool/prompt.ts +63 -0
  214. package/src/tools/lsTool/lsTool.tsx +272 -0
  215. package/src/tools/lsTool/prompt.ts +2 -0
  216. package/src/tools.ts +63 -0
  217. package/src/types/PermissionMode.ts +120 -0
  218. package/src/types/RequestContext.ts +72 -0
  219. package/src/types/conversation.ts +51 -0
  220. package/src/types/logs.ts +58 -0
  221. package/src/types/modelCapabilities.ts +64 -0
  222. package/src/types/notebook.ts +87 -0
  223. package/src/utils/Cursor.ts +436 -0
  224. package/src/utils/PersistentShell.ts +373 -0
  225. package/src/utils/advancedFuzzyMatcher.ts +290 -0
  226. package/src/utils/agentLoader.ts +284 -0
  227. package/src/utils/agentStorage.ts +97 -0
  228. package/src/utils/array.ts +3 -0
  229. package/src/utils/ask.tsx +99 -0
  230. package/src/utils/auth.ts +13 -0
  231. package/src/utils/autoCompactCore.ts +223 -0
  232. package/src/utils/autoUpdater.ts +318 -0
  233. package/src/utils/betas.ts +20 -0
  234. package/src/utils/browser.ts +14 -0
  235. package/src/utils/cleanup.ts +72 -0
  236. package/src/utils/commands.ts +261 -0
  237. package/src/utils/commonUnixCommands.ts +161 -0
  238. package/src/utils/config.ts +942 -0
  239. package/src/utils/conversationRecovery.ts +55 -0
  240. package/src/utils/debugLogger.ts +1123 -0
  241. package/src/utils/diff.ts +42 -0
  242. package/src/utils/env.ts +57 -0
  243. package/src/utils/errors.ts +21 -0
  244. package/src/utils/exampleCommands.ts +109 -0
  245. package/src/utils/execFileNoThrow.ts +51 -0
  246. package/src/utils/expertChatStorage.ts +136 -0
  247. package/src/utils/file.ts +402 -0
  248. package/src/utils/fileRecoveryCore.ts +71 -0
  249. package/src/utils/format.tsx +44 -0
  250. package/src/utils/fuzzyMatcher.ts +328 -0
  251. package/src/utils/generators.ts +62 -0
  252. package/src/utils/git.ts +92 -0
  253. package/src/utils/globalLogger.ts +77 -0
  254. package/src/utils/http.ts +10 -0
  255. package/src/utils/imagePaste.ts +38 -0
  256. package/src/utils/json.ts +13 -0
  257. package/src/utils/log.ts +382 -0
  258. package/src/utils/markdown.ts +213 -0
  259. package/src/utils/messageContextManager.ts +289 -0
  260. package/src/utils/messages.tsx +939 -0
  261. package/src/utils/model.ts +836 -0
  262. package/src/utils/permissions/filesystem.ts +118 -0
  263. package/src/utils/responseState.ts +23 -0
  264. package/src/utils/ripgrep.ts +167 -0
  265. package/src/utils/secureFile.ts +559 -0
  266. package/src/utils/sessionState.ts +49 -0
  267. package/src/utils/state.ts +25 -0
  268. package/src/utils/style.ts +29 -0
  269. package/src/utils/terminal.ts +50 -0
  270. package/src/utils/theme.ts +133 -0
  271. package/src/utils/thinking.ts +144 -0
  272. package/src/utils/todoStorage.ts +431 -0
  273. package/src/utils/tokens.ts +43 -0
  274. package/src/utils/toolExecutionController.ts +163 -0
  275. package/src/utils/unaryLogging.ts +26 -0
  276. package/src/utils/user.ts +37 -0
  277. package/src/utils/validate.ts +165 -0
  278. package/cli.mjs +0 -1803
@@ -0,0 +1,942 @@
1
+ import { existsSync, readFileSync, writeFileSync } from 'fs'
2
+ import { resolve, join } from 'path'
3
+ import { cloneDeep, memoize, pick } from 'lodash-es'
4
+ import { homedir } from 'os'
5
+ import { GLOBAL_CLAUDE_FILE } from './env'
6
+ import { getCwd } from './state'
7
+ import { randomBytes } from 'crypto'
8
+ import { safeParseJSON } from './json'
9
+ import { checkGate, logEvent } from '../services/statsig'
10
+ import { GATE_USE_EXTERNAL_UPDATER } from '../constants/betas'
11
+ import { ConfigParseError } from './errors'
12
+ import type { ThemeNames } from './theme'
13
+ import { debug as debugLogger } from './debugLogger'
14
+ import { getSessionState, setSessionState } from './sessionState'
15
+
16
+ export type McpStdioServerConfig = {
17
+ type?: 'stdio' // Optional for backwards compatibility
18
+ command: string
19
+ args: string[]
20
+ env?: Record<string, string>
21
+ }
22
+
23
+ export type McpSSEServerConfig = {
24
+ type: 'sse'
25
+ url: string
26
+ }
27
+
28
+ export type McpServerConfig = McpStdioServerConfig | McpSSEServerConfig
29
+
30
+ export type ProjectConfig = {
31
+ allowedTools: string[]
32
+ context: Record<string, string>
33
+ contextFiles?: string[]
34
+ history: string[]
35
+ dontCrawlDirectory?: boolean
36
+ enableArchitectTool?: boolean
37
+ mcpContextUris: string[]
38
+ mcpServers?: Record<string, McpServerConfig>
39
+ approvedMcprcServers?: string[]
40
+ rejectedMcprcServers?: string[]
41
+ lastAPIDuration?: number
42
+ lastCost?: number
43
+ lastDuration?: number
44
+ lastSessionId?: string
45
+ exampleFiles?: string[]
46
+ exampleFilesGeneratedAt?: number
47
+ hasTrustDialogAccepted?: boolean
48
+ hasCompletedProjectOnboarding?: boolean
49
+ }
50
+
51
+ const DEFAULT_PROJECT_CONFIG: ProjectConfig = {
52
+ allowedTools: [],
53
+ context: {},
54
+ history: [],
55
+ dontCrawlDirectory: false,
56
+ enableArchitectTool: false,
57
+ mcpContextUris: [],
58
+ mcpServers: {},
59
+ approvedMcprcServers: [],
60
+ rejectedMcprcServers: [],
61
+ hasTrustDialogAccepted: false,
62
+ }
63
+
64
+ function defaultConfigForProject(projectPath: string): ProjectConfig {
65
+ const config = { ...DEFAULT_PROJECT_CONFIG }
66
+ if (projectPath === homedir()) {
67
+ config.dontCrawlDirectory = true
68
+ }
69
+ return config
70
+ }
71
+
72
+ export type AutoUpdaterStatus =
73
+ | 'disabled'
74
+ | 'enabled'
75
+ | 'no_permissions'
76
+ | 'not_configured'
77
+
78
+ export function isAutoUpdaterStatus(value: string): value is AutoUpdaterStatus {
79
+ return ['disabled', 'enabled', 'no_permissions', 'not_configured'].includes(
80
+ value as AutoUpdaterStatus,
81
+ )
82
+ }
83
+
84
+ export type NotificationChannel =
85
+ | 'iterm2'
86
+ | 'terminal_bell'
87
+ | 'iterm2_with_bell'
88
+ | 'notifications_disabled'
89
+
90
+ export type ProviderType =
91
+ | 'anthropic'
92
+ | 'openai'
93
+ | 'mistral'
94
+ | 'deepseek'
95
+ | 'kimi'
96
+ | 'qwen'
97
+ | 'glm'
98
+ | 'minimax'
99
+ | 'baidu-qianfan'
100
+ | 'siliconflow'
101
+ | 'bigdream'
102
+ | 'opendev'
103
+ | 'xai'
104
+ | 'groq'
105
+ | 'gemini'
106
+ | 'ollama'
107
+ | 'azure'
108
+ | 'custom'
109
+ | 'custom-openai'
110
+
111
+ // New model system types
112
+ export type ModelProfile = {
113
+ name: string // User-friendly name
114
+ provider: ProviderType // Provider type
115
+ modelName: string // Primary key - actual model identifier
116
+ baseURL?: string // Custom endpoint
117
+ apiKey: string
118
+ maxTokens: number // Output token limit (for GPT-5, this maps to max_completion_tokens)
119
+ contextLength: number // Context window size
120
+ reasoningEffort?: 'low' | 'medium' | 'high' | 'minimal' | 'medium'
121
+ isActive: boolean // Whether profile is enabled
122
+ createdAt: number // Creation timestamp
123
+ lastUsed?: number // Last usage timestamp
124
+ // 🔥 GPT-5 specific metadata
125
+ isGPT5?: boolean // Auto-detected GPT-5 model flag
126
+ validationStatus?: 'valid' | 'needs_repair' | 'auto_repaired' // Configuration status
127
+ lastValidation?: number // Last validation timestamp
128
+ }
129
+
130
+ export type ModelPointerType = 'main' | 'task' | 'reasoning' | 'quick'
131
+
132
+ export type ModelPointers = {
133
+ main: string // Main dialog model ID
134
+ task: string // Task tool model ID
135
+ reasoning: string // Reasoning model ID
136
+ quick: string // Quick model ID
137
+ }
138
+
139
+ export type AccountInfo = {
140
+ accountUuid: string
141
+ emailAddress: string
142
+ organizationUuid?: string
143
+ }
144
+
145
+ export type GlobalConfig = {
146
+ projects?: Record<string, ProjectConfig>
147
+ numStartups: number
148
+ autoUpdaterStatus?: AutoUpdaterStatus
149
+ userID?: string
150
+ theme: ThemeNames
151
+ hasCompletedOnboarding?: boolean
152
+ // Tracks the last version that reset onboarding, used with MIN_VERSION_REQUIRING_ONBOARDING_RESET
153
+ lastOnboardingVersion?: string
154
+ // Tracks the last version for which release notes were seen, used for managing release notes
155
+ lastReleaseNotesSeen?: string
156
+ mcpServers?: Record<string, McpServerConfig>
157
+ preferredNotifChannel: NotificationChannel
158
+ verbose: boolean
159
+ customApiKeyResponses?: {
160
+ approved?: string[]
161
+ rejected?: string[]
162
+ }
163
+ primaryProvider?: ProviderType
164
+ maxTokens?: number
165
+ hasAcknowledgedCostThreshold?: boolean
166
+ oauthAccount?: AccountInfo
167
+ iterm2KeyBindingInstalled?: boolean // Legacy - keeping for backward compatibility
168
+ shiftEnterKeyBindingInstalled?: boolean
169
+ proxy?: string
170
+ stream?: boolean
171
+
172
+ // New model system
173
+ modelProfiles?: ModelProfile[] // Model configuration list
174
+ modelPointers?: ModelPointers // Model pointer system
175
+ defaultModelName?: string // Default model
176
+ }
177
+
178
+ export const DEFAULT_GLOBAL_CONFIG: GlobalConfig = {
179
+ numStartups: 0,
180
+ autoUpdaterStatus: 'not_configured',
181
+ theme: 'dark' as ThemeNames,
182
+ preferredNotifChannel: 'iterm2',
183
+ verbose: false,
184
+ primaryProvider: 'anthropic' as ProviderType,
185
+ customApiKeyResponses: {
186
+ approved: [],
187
+ rejected: [],
188
+ },
189
+ stream: true,
190
+
191
+ // New model system defaults
192
+ modelProfiles: [],
193
+ modelPointers: {
194
+ main: '',
195
+ task: '',
196
+ reasoning: '',
197
+ quick: '',
198
+ },
199
+ }
200
+
201
+ export const GLOBAL_CONFIG_KEYS = [
202
+ 'autoUpdaterStatus',
203
+ 'theme',
204
+ 'hasCompletedOnboarding',
205
+ 'lastOnboardingVersion',
206
+ 'lastReleaseNotesSeen',
207
+ 'verbose',
208
+ 'customApiKeyResponses',
209
+ 'primaryProvider',
210
+ 'preferredNotifChannel',
211
+ 'shiftEnterKeyBindingInstalled',
212
+ 'maxTokens',
213
+ ] as const
214
+
215
+ export type GlobalConfigKey = (typeof GLOBAL_CONFIG_KEYS)[number]
216
+
217
+ export function isGlobalConfigKey(key: string): key is GlobalConfigKey {
218
+ return GLOBAL_CONFIG_KEYS.includes(key as GlobalConfigKey)
219
+ }
220
+
221
+ export const PROJECT_CONFIG_KEYS = [
222
+ 'dontCrawlDirectory',
223
+ 'enableArchitectTool',
224
+ 'hasTrustDialogAccepted',
225
+ 'hasCompletedProjectOnboarding',
226
+ ] as const
227
+
228
+ export type ProjectConfigKey = (typeof PROJECT_CONFIG_KEYS)[number]
229
+
230
+ export function checkHasTrustDialogAccepted(): boolean {
231
+ let currentPath = getCwd()
232
+ const config = getConfig(GLOBAL_CLAUDE_FILE, DEFAULT_GLOBAL_CONFIG)
233
+
234
+ while (true) {
235
+ const projectConfig = config.projects?.[currentPath]
236
+ if (projectConfig?.hasTrustDialogAccepted) {
237
+ return true
238
+ }
239
+ const parentPath = resolve(currentPath, '..')
240
+ // Stop if we've reached the root (when parent is same as current)
241
+ if (parentPath === currentPath) {
242
+ break
243
+ }
244
+ currentPath = parentPath
245
+ }
246
+
247
+ return false
248
+ }
249
+
250
+ // We have to put this test code here because Jest doesn't support mocking ES modules :O
251
+ const TEST_GLOBAL_CONFIG_FOR_TESTING: GlobalConfig = {
252
+ ...DEFAULT_GLOBAL_CONFIG,
253
+ autoUpdaterStatus: 'disabled',
254
+ }
255
+ const TEST_PROJECT_CONFIG_FOR_TESTING: ProjectConfig = {
256
+ ...DEFAULT_PROJECT_CONFIG,
257
+ }
258
+
259
+ export function isProjectConfigKey(key: string): key is ProjectConfigKey {
260
+ return PROJECT_CONFIG_KEYS.includes(key as ProjectConfigKey)
261
+ }
262
+
263
+ export function saveGlobalConfig(config: GlobalConfig): void {
264
+ if (process.env.NODE_ENV === 'test') {
265
+ for (const key in config) {
266
+ TEST_GLOBAL_CONFIG_FOR_TESTING[key] = config[key]
267
+ }
268
+ return
269
+ }
270
+
271
+ // 直接保存配置(无需清除缓存,因为已移除缓存)
272
+ saveConfig(
273
+ GLOBAL_CLAUDE_FILE,
274
+ {
275
+ ...config,
276
+ projects: getConfig(GLOBAL_CLAUDE_FILE, DEFAULT_GLOBAL_CONFIG).projects,
277
+ },
278
+ DEFAULT_GLOBAL_CONFIG,
279
+ )
280
+ }
281
+
282
+ // 临时移除缓存,确保总是获取最新配置
283
+ export function getGlobalConfig(): GlobalConfig {
284
+ if (process.env.NODE_ENV === 'test') {
285
+ return TEST_GLOBAL_CONFIG_FOR_TESTING
286
+ }
287
+ const config = getConfig(GLOBAL_CLAUDE_FILE, DEFAULT_GLOBAL_CONFIG)
288
+ return migrateModelProfilesRemoveId(config)
289
+ }
290
+
291
+ export function getAnthropicApiKey(): null | string {
292
+ return process.env.ANTHROPIC_API_KEY || null
293
+ }
294
+
295
+ export function normalizeApiKeyForConfig(apiKey: string): string {
296
+ return apiKey?.slice(-20) ?? ''
297
+ }
298
+
299
+ export function getCustomApiKeyStatus(
300
+ truncatedApiKey: string,
301
+ ): 'approved' | 'rejected' | 'new' {
302
+ const config = getGlobalConfig()
303
+ if (config.customApiKeyResponses?.approved?.includes(truncatedApiKey)) {
304
+ return 'approved'
305
+ }
306
+ if (config.customApiKeyResponses?.rejected?.includes(truncatedApiKey)) {
307
+ return 'rejected'
308
+ }
309
+ return 'new'
310
+ }
311
+
312
+ function saveConfig<A extends object>(
313
+ file: string,
314
+ config: A,
315
+ defaultConfig: A,
316
+ ): void {
317
+ // Filter out any values that match the defaults
318
+ const filteredConfig = Object.fromEntries(
319
+ Object.entries(config).filter(
320
+ ([key, value]) =>
321
+ JSON.stringify(value) !== JSON.stringify(defaultConfig[key as keyof A]),
322
+ ),
323
+ )
324
+ writeFileSync(file, JSON.stringify(filteredConfig, null, 2), 'utf-8')
325
+ }
326
+
327
+ // Flag to track if config reading is allowed
328
+ let configReadingAllowed = false
329
+
330
+ export function enableConfigs(): void {
331
+ // Any reads to configuration before this flag is set show an console warning
332
+ // to prevent us from adding config reading during module initialization
333
+ configReadingAllowed = true
334
+ // We only check the global config because currently all the configs share a file
335
+ getConfig(
336
+ GLOBAL_CLAUDE_FILE,
337
+ DEFAULT_GLOBAL_CONFIG,
338
+ true /* throw on invalid */,
339
+ )
340
+ }
341
+
342
+ function getConfig<A>(
343
+ file: string,
344
+ defaultConfig: A,
345
+ throwOnInvalid?: boolean,
346
+ ): A {
347
+ // 简化配置访问逻辑,移除复杂的时序检查
348
+
349
+ debugLogger.state('CONFIG_LOAD_START', {
350
+ file,
351
+ fileExists: String(existsSync(file)),
352
+ throwOnInvalid: String(!!throwOnInvalid),
353
+ })
354
+
355
+ if (!existsSync(file)) {
356
+ debugLogger.state('CONFIG_LOAD_DEFAULT', {
357
+ file,
358
+ reason: 'file_not_exists',
359
+ defaultConfigKeys: Object.keys(defaultConfig as object).join(', '),
360
+ })
361
+ return cloneDeep(defaultConfig)
362
+ }
363
+
364
+ try {
365
+ const fileContent = readFileSync(file, 'utf-8')
366
+ debugLogger.state('CONFIG_FILE_READ', {
367
+ file,
368
+ contentLength: String(fileContent.length),
369
+ contentPreview:
370
+ fileContent.substring(0, 100) + (fileContent.length > 100 ? '...' : ''),
371
+ })
372
+
373
+ try {
374
+ const parsedConfig = JSON.parse(fileContent)
375
+ debugLogger.state('CONFIG_JSON_PARSED', {
376
+ file,
377
+ parsedKeys: Object.keys(parsedConfig).join(', '),
378
+ })
379
+
380
+ // Handle backward compatibility - remove logic for deleted fields
381
+ const finalConfig = {
382
+ ...cloneDeep(defaultConfig),
383
+ ...parsedConfig,
384
+ }
385
+
386
+ debugLogger.state('CONFIG_LOAD_SUCCESS', {
387
+ file,
388
+ finalConfigKeys: Object.keys(finalConfig as object).join(', '),
389
+ })
390
+
391
+ return finalConfig
392
+ } catch (error) {
393
+ // Throw a ConfigParseError with the file path and default config
394
+ const errorMessage =
395
+ error instanceof Error ? error.message : String(error)
396
+
397
+ debugLogger.error('CONFIG_JSON_PARSE_ERROR', {
398
+ file,
399
+ errorMessage,
400
+ errorType:
401
+ error instanceof Error ? error.constructor.name : typeof error,
402
+ contentLength: String(fileContent.length),
403
+ })
404
+
405
+ throw new ConfigParseError(errorMessage, file, defaultConfig)
406
+ }
407
+ } catch (error: unknown) {
408
+ // Re-throw ConfigParseError if throwOnInvalid is true
409
+ if (error instanceof ConfigParseError && throwOnInvalid) {
410
+ debugLogger.error('CONFIG_PARSE_ERROR_RETHROWN', {
411
+ file,
412
+ throwOnInvalid: String(throwOnInvalid),
413
+ errorMessage: error.message,
414
+ })
415
+ throw error
416
+ }
417
+
418
+ debugLogger.warn('CONFIG_FALLBACK_TO_DEFAULT', {
419
+ file,
420
+ errorType: error instanceof Error ? error.constructor.name : typeof error,
421
+ errorMessage: error instanceof Error ? error.message : String(error),
422
+ action: 'using_default_config',
423
+ })
424
+
425
+ return cloneDeep(defaultConfig)
426
+ }
427
+ }
428
+
429
+ export function getCurrentProjectConfig(): ProjectConfig {
430
+ if (process.env.NODE_ENV === 'test') {
431
+ return TEST_PROJECT_CONFIG_FOR_TESTING
432
+ }
433
+
434
+ const absolutePath = resolve(getCwd())
435
+ const config = getConfig(GLOBAL_CLAUDE_FILE, DEFAULT_GLOBAL_CONFIG)
436
+
437
+ if (!config.projects) {
438
+ return defaultConfigForProject(absolutePath)
439
+ }
440
+
441
+ const projectConfig =
442
+ config.projects[absolutePath] ?? defaultConfigForProject(absolutePath)
443
+ // Not sure how this became a string
444
+ // TODO: Fix upstream
445
+ if (typeof projectConfig.allowedTools === 'string') {
446
+ projectConfig.allowedTools =
447
+ (safeParseJSON(projectConfig.allowedTools) as string[]) ?? []
448
+ }
449
+ return projectConfig
450
+ }
451
+
452
+ export function saveCurrentProjectConfig(projectConfig: ProjectConfig): void {
453
+ if (process.env.NODE_ENV === 'test') {
454
+ for (const key in projectConfig) {
455
+ TEST_PROJECT_CONFIG_FOR_TESTING[key] = projectConfig[key]
456
+ }
457
+ return
458
+ }
459
+ const config = getConfig(GLOBAL_CLAUDE_FILE, DEFAULT_GLOBAL_CONFIG)
460
+ saveConfig(
461
+ GLOBAL_CLAUDE_FILE,
462
+ {
463
+ ...config,
464
+ projects: {
465
+ ...config.projects,
466
+ [resolve(getCwd())]: projectConfig,
467
+ },
468
+ },
469
+ DEFAULT_GLOBAL_CONFIG,
470
+ )
471
+ }
472
+
473
+ export async function isAutoUpdaterDisabled(): Promise<boolean> {
474
+ const useExternalUpdater = await checkGate(GATE_USE_EXTERNAL_UPDATER)
475
+ return (
476
+ useExternalUpdater || getGlobalConfig().autoUpdaterStatus === 'disabled'
477
+ )
478
+ }
479
+
480
+ export const TEST_MCPRC_CONFIG_FOR_TESTING: Record<string, McpServerConfig> = {}
481
+
482
+ export function clearMcprcConfigForTesting(): void {
483
+ if (process.env.NODE_ENV === 'test') {
484
+ Object.keys(TEST_MCPRC_CONFIG_FOR_TESTING).forEach(key => {
485
+ delete TEST_MCPRC_CONFIG_FOR_TESTING[key]
486
+ })
487
+ }
488
+ }
489
+
490
+ export function addMcprcServerForTesting(
491
+ name: string,
492
+ server: McpServerConfig,
493
+ ): void {
494
+ if (process.env.NODE_ENV === 'test') {
495
+ TEST_MCPRC_CONFIG_FOR_TESTING[name] = server
496
+ }
497
+ }
498
+
499
+ export function removeMcprcServerForTesting(name: string): void {
500
+ if (process.env.NODE_ENV === 'test') {
501
+ if (!TEST_MCPRC_CONFIG_FOR_TESTING[name]) {
502
+ throw new Error(`No MCP server found with name: ${name} in .mcprc`)
503
+ }
504
+ delete TEST_MCPRC_CONFIG_FOR_TESTING[name]
505
+ }
506
+ }
507
+
508
+ export const getMcprcConfig = memoize(
509
+ (): Record<string, McpServerConfig> => {
510
+ if (process.env.NODE_ENV === 'test') {
511
+ return TEST_MCPRC_CONFIG_FOR_TESTING
512
+ }
513
+
514
+ const mcprcPath = join(getCwd(), '.mcprc')
515
+ if (!existsSync(mcprcPath)) {
516
+ return {}
517
+ }
518
+
519
+ try {
520
+ const mcprcContent = readFileSync(mcprcPath, 'utf-8')
521
+ const config = safeParseJSON(mcprcContent)
522
+ if (config && typeof config === 'object') {
523
+ logEvent('tengu_mcprc_found', {
524
+ numServers: Object.keys(config).length.toString(),
525
+ })
526
+ return config as Record<string, McpServerConfig>
527
+ }
528
+ } catch {
529
+ // Ignore errors reading/parsing .mcprc (they're logged in safeParseJSON)
530
+ }
531
+ return {}
532
+ },
533
+ // This function returns the same value as long as the cwd and mcprc file content remain the same
534
+ () => {
535
+ const cwd = getCwd()
536
+ const mcprcPath = join(cwd, '.mcprc')
537
+ if (existsSync(mcprcPath)) {
538
+ try {
539
+ const stat = readFileSync(mcprcPath, 'utf-8')
540
+ return `${cwd}:${stat}`
541
+ } catch {
542
+ return cwd
543
+ }
544
+ }
545
+ return cwd
546
+ },
547
+ )
548
+
549
+ export function getOrCreateUserID(): string {
550
+ const config = getGlobalConfig()
551
+ if (config.userID) {
552
+ return config.userID
553
+ }
554
+
555
+ const userID = randomBytes(32).toString('hex')
556
+ saveGlobalConfig({ ...config, userID })
557
+ return userID
558
+ }
559
+
560
+ export function getConfigForCLI(key: string, global: boolean): unknown {
561
+ logEvent('tengu_config_get', {
562
+ key,
563
+ global: global?.toString() ?? 'false',
564
+ })
565
+ if (global) {
566
+ if (!isGlobalConfigKey(key)) {
567
+ console.error(
568
+ `Error: '${key}' is not a valid config key. Valid keys are: ${GLOBAL_CONFIG_KEYS.join(', ')}`,
569
+ )
570
+ process.exit(1)
571
+ }
572
+ return getGlobalConfig()[key]
573
+ } else {
574
+ if (!isProjectConfigKey(key)) {
575
+ console.error(
576
+ `Error: '${key}' is not a valid config key. Valid keys are: ${PROJECT_CONFIG_KEYS.join(', ')}`,
577
+ )
578
+ process.exit(1)
579
+ }
580
+ return getCurrentProjectConfig()[key]
581
+ }
582
+ }
583
+
584
+ export function setConfigForCLI(
585
+ key: string,
586
+ value: unknown,
587
+ global: boolean,
588
+ ): void {
589
+ logEvent('tengu_config_set', {
590
+ key,
591
+ global: global?.toString() ?? 'false',
592
+ })
593
+ if (global) {
594
+ if (!isGlobalConfigKey(key)) {
595
+ console.error(
596
+ `Error: Cannot set '${key}'. Only these keys can be modified: ${GLOBAL_CONFIG_KEYS.join(', ')}`,
597
+ )
598
+ process.exit(1)
599
+ }
600
+
601
+ if (key === 'autoUpdaterStatus' && !isAutoUpdaterStatus(value as string)) {
602
+ console.error(
603
+ `Error: Invalid value for autoUpdaterStatus. Must be one of: disabled, enabled, no_permissions, not_configured`,
604
+ )
605
+ process.exit(1)
606
+ }
607
+
608
+ const currentConfig = getGlobalConfig()
609
+ saveGlobalConfig({
610
+ ...currentConfig,
611
+ [key]: value,
612
+ })
613
+ } else {
614
+ if (!isProjectConfigKey(key)) {
615
+ console.error(
616
+ `Error: Cannot set '${key}'. Only these keys can be modified: ${PROJECT_CONFIG_KEYS.join(', ')}. Did you mean --global?`,
617
+ )
618
+ process.exit(1)
619
+ }
620
+ const currentConfig = getCurrentProjectConfig()
621
+ saveCurrentProjectConfig({
622
+ ...currentConfig,
623
+ [key]: value,
624
+ })
625
+ }
626
+ // Wait for the output to be flushed, to avoid clearing the screen.
627
+ setTimeout(() => {
628
+ // Without this we hang indefinitely.
629
+ process.exit(0)
630
+ }, 100)
631
+ }
632
+
633
+ export function deleteConfigForCLI(key: string, global: boolean): void {
634
+ logEvent('tengu_config_delete', {
635
+ key,
636
+ global: global?.toString() ?? 'false',
637
+ })
638
+ if (global) {
639
+ if (!isGlobalConfigKey(key)) {
640
+ console.error(
641
+ `Error: Cannot delete '${key}'. Only these keys can be modified: ${GLOBAL_CONFIG_KEYS.join(', ')}`,
642
+ )
643
+ process.exit(1)
644
+ }
645
+ const currentConfig = getGlobalConfig()
646
+ delete currentConfig[key]
647
+ saveGlobalConfig(currentConfig)
648
+ } else {
649
+ if (!isProjectConfigKey(key)) {
650
+ console.error(
651
+ `Error: Cannot delete '${key}'. Only these keys can be modified: ${PROJECT_CONFIG_KEYS.join(', ')}. Did you mean --global?`,
652
+ )
653
+ process.exit(1)
654
+ }
655
+ const currentConfig = getCurrentProjectConfig()
656
+ delete currentConfig[key]
657
+ saveCurrentProjectConfig(currentConfig)
658
+ }
659
+ }
660
+
661
+ export function listConfigForCLI(global: true): GlobalConfig
662
+ export function listConfigForCLI(global: false): ProjectConfig
663
+ export function listConfigForCLI(global: boolean): object {
664
+ logEvent('tengu_config_list', {
665
+ global: global?.toString() ?? 'false',
666
+ })
667
+ if (global) {
668
+ const currentConfig = pick(getGlobalConfig(), GLOBAL_CONFIG_KEYS)
669
+ return currentConfig
670
+ } else {
671
+ return pick(getCurrentProjectConfig(), PROJECT_CONFIG_KEYS)
672
+ }
673
+ }
674
+
675
+ export function getOpenAIApiKey(): string | undefined {
676
+ return process.env.OPENAI_API_KEY
677
+ }
678
+
679
+ // Configuration migration utility functions
680
+ function migrateModelProfilesRemoveId(config: GlobalConfig): GlobalConfig {
681
+ if (!config.modelProfiles) return config
682
+
683
+ // 1. Remove id field from ModelProfile objects and build ID to modelName mapping
684
+ const idToModelNameMap = new Map<string, string>()
685
+ const migratedProfiles = config.modelProfiles.map(profile => {
686
+ // Build mapping before removing id field
687
+ if ((profile as any).id && profile.modelName) {
688
+ idToModelNameMap.set((profile as any).id, profile.modelName)
689
+ }
690
+
691
+ // Remove id field, keep everything else
692
+ const { id, ...profileWithoutId } = profile as any
693
+ return profileWithoutId as ModelProfile
694
+ })
695
+
696
+ // 2. Migrate ModelPointers from IDs to modelNames
697
+ const migratedPointers: ModelPointers = {
698
+ main: '',
699
+ task: '',
700
+ reasoning: '',
701
+ quick: '',
702
+ }
703
+
704
+ if (config.modelPointers) {
705
+ Object.entries(config.modelPointers).forEach(([pointer, value]) => {
706
+ if (value) {
707
+ // If value looks like an old ID (model_xxx), map it to modelName
708
+ const modelName = idToModelNameMap.get(value) || value
709
+ migratedPointers[pointer as ModelPointerType] = modelName
710
+ }
711
+ })
712
+ }
713
+
714
+ // 3. Migrate legacy config fields
715
+ let defaultModelName: string | undefined
716
+ if ((config as any).defaultModelId) {
717
+ defaultModelName =
718
+ idToModelNameMap.get((config as any).defaultModelId) ||
719
+ (config as any).defaultModelId
720
+ } else if ((config as any).defaultModelName) {
721
+ defaultModelName = (config as any).defaultModelName
722
+ }
723
+
724
+ // 4. Remove legacy fields and return migrated config
725
+ const migratedConfig = { ...config }
726
+ delete (migratedConfig as any).defaultModelId
727
+ delete (migratedConfig as any).currentSelectedModelId
728
+ delete (migratedConfig as any).mainAgentModelId
729
+ delete (migratedConfig as any).taskToolModelId
730
+
731
+ return {
732
+ ...migratedConfig,
733
+ modelProfiles: migratedProfiles,
734
+ modelPointers: migratedPointers,
735
+ defaultModelName,
736
+ }
737
+ }
738
+
739
+ // New model system utility functions
740
+
741
+ export function setAllPointersToModel(modelName: string): void {
742
+ const config = getGlobalConfig()
743
+ const updatedConfig = {
744
+ ...config,
745
+ modelPointers: {
746
+ main: modelName,
747
+ task: modelName,
748
+ reasoning: modelName,
749
+ quick: modelName,
750
+ },
751
+ defaultModelName: modelName,
752
+ }
753
+ saveGlobalConfig(updatedConfig)
754
+ }
755
+
756
+ export function setModelPointer(
757
+ pointer: ModelPointerType,
758
+ modelName: string,
759
+ ): void {
760
+ const config = getGlobalConfig()
761
+ const updatedConfig = {
762
+ ...config,
763
+ modelPointers: {
764
+ ...config.modelPointers,
765
+ [pointer]: modelName,
766
+ },
767
+ }
768
+ saveGlobalConfig(updatedConfig)
769
+
770
+ // 🔧 Fix: Force ModelManager reload after config change
771
+ // Import here to avoid circular dependency
772
+ import('./model').then(({ reloadModelManager }) => {
773
+ reloadModelManager()
774
+ })
775
+ }
776
+
777
+ // 🔥 GPT-5 Configuration Validation and Auto-Repair Functions
778
+
779
+ /**
780
+ * Check if a model name represents a GPT-5 model
781
+ */
782
+ export function isGPT5ModelName(modelName: string): boolean {
783
+ if (!modelName || typeof modelName !== 'string') return false
784
+ const lowerName = modelName.toLowerCase()
785
+ return lowerName.startsWith('gpt-5') || lowerName.includes('gpt-5')
786
+ }
787
+
788
+ /**
789
+ * Validate and auto-repair GPT-5 model configuration
790
+ */
791
+ export function validateAndRepairGPT5Profile(profile: ModelProfile): ModelProfile {
792
+ const isGPT5 = isGPT5ModelName(profile.modelName)
793
+ const now = Date.now()
794
+
795
+ // Create a working copy
796
+ const repairedProfile: ModelProfile = { ...profile }
797
+ let wasRepaired = false
798
+
799
+ // 🔧 Set GPT-5 detection flag
800
+ if (isGPT5 !== profile.isGPT5) {
801
+ repairedProfile.isGPT5 = isGPT5
802
+ wasRepaired = true
803
+ }
804
+
805
+ if (isGPT5) {
806
+ // 🔧 GPT-5 Parameter Validation and Repair
807
+
808
+ // 1. Reasoning effort validation
809
+ const validReasoningEfforts = ['minimal', 'low', 'medium', 'high']
810
+ if (!profile.reasoningEffort || !validReasoningEfforts.includes(profile.reasoningEffort)) {
811
+ repairedProfile.reasoningEffort = 'medium' // Default for coding tasks
812
+ wasRepaired = true
813
+ console.log(`🔧 GPT-5 Config: Set reasoning effort to 'medium' for ${profile.modelName}`)
814
+ }
815
+
816
+ // 2. Context length validation (GPT-5 models typically have 128k context)
817
+ if (profile.contextLength < 128000) {
818
+ repairedProfile.contextLength = 128000
819
+ wasRepaired = true
820
+ console.log(`🔧 GPT-5 Config: Updated context length to 128k for ${profile.modelName}`)
821
+ }
822
+
823
+ // 3. Output tokens validation (reasonable defaults for GPT-5)
824
+ if (profile.maxTokens < 4000) {
825
+ repairedProfile.maxTokens = 8192 // Good default for coding tasks
826
+ wasRepaired = true
827
+ console.log(`🔧 GPT-5 Config: Updated max tokens to 8192 for ${profile.modelName}`)
828
+ }
829
+
830
+ // 4. Provider validation
831
+ if (profile.provider !== 'openai' && profile.provider !== 'custom-openai' && profile.provider !== 'azure') {
832
+ console.warn(`⚠️ GPT-5 Config: Unexpected provider '${profile.provider}' for GPT-5 model ${profile.modelName}. Consider using 'openai' or 'custom-openai'.`)
833
+ }
834
+
835
+ // 5. Base URL validation for official models
836
+ if (profile.modelName.includes('gpt-5') && !profile.baseURL) {
837
+ repairedProfile.baseURL = 'https://api.openai.com/v1'
838
+ wasRepaired = true
839
+ console.log(`🔧 GPT-5 Config: Set default base URL for ${profile.modelName}`)
840
+ }
841
+ }
842
+
843
+ // Update validation metadata
844
+ repairedProfile.validationStatus = wasRepaired ? 'auto_repaired' : 'valid'
845
+ repairedProfile.lastValidation = now
846
+
847
+ if (wasRepaired) {
848
+ console.log(`✅ GPT-5 Config: Auto-repaired configuration for ${profile.modelName}`)
849
+ }
850
+
851
+ return repairedProfile
852
+ }
853
+
854
+ /**
855
+ * Validate and repair all GPT-5 profiles in the global configuration
856
+ */
857
+ export function validateAndRepairAllGPT5Profiles(): { repaired: number; total: number } {
858
+ const config = getGlobalConfig()
859
+ if (!config.modelProfiles) {
860
+ return { repaired: 0, total: 0 }
861
+ }
862
+
863
+ let repairCount = 0
864
+ const repairedProfiles = config.modelProfiles.map(profile => {
865
+ const repairedProfile = validateAndRepairGPT5Profile(profile)
866
+ if (repairedProfile.validationStatus === 'auto_repaired') {
867
+ repairCount++
868
+ }
869
+ return repairedProfile
870
+ })
871
+
872
+ // Save the repaired configuration
873
+ if (repairCount > 0) {
874
+ const updatedConfig = {
875
+ ...config,
876
+ modelProfiles: repairedProfiles,
877
+ }
878
+ saveGlobalConfig(updatedConfig)
879
+ console.log(`🔧 GPT-5 Config: Auto-repaired ${repairCount} model profiles`)
880
+ }
881
+
882
+ return { repaired: repairCount, total: config.modelProfiles.length }
883
+ }
884
+
885
+ /**
886
+ * Get GPT-5 configuration recommendations for a specific model
887
+ */
888
+ export function getGPT5ConfigRecommendations(modelName: string): Partial<ModelProfile> {
889
+ if (!isGPT5ModelName(modelName)) {
890
+ return {}
891
+ }
892
+
893
+ const recommendations: Partial<ModelProfile> = {
894
+ contextLength: 128000, // GPT-5 standard context length
895
+ maxTokens: 8192, // Good default for coding tasks
896
+ reasoningEffort: 'medium', // Balanced for most coding tasks
897
+ isGPT5: true,
898
+ }
899
+
900
+ // Model-specific optimizations
901
+ if (modelName.includes('gpt-5-mini')) {
902
+ recommendations.maxTokens = 4096 // Smaller default for mini
903
+ recommendations.reasoningEffort = 'low' // Faster for simple tasks
904
+ } else if (modelName.includes('gpt-5-nano')) {
905
+ recommendations.maxTokens = 2048 // Even smaller for nano
906
+ recommendations.reasoningEffort = 'minimal' // Fastest option
907
+ }
908
+
909
+ return recommendations
910
+ }
911
+
912
+ /**
913
+ * Create a properly configured GPT-5 model profile
914
+ */
915
+ export function createGPT5ModelProfile(
916
+ name: string,
917
+ modelName: string,
918
+ apiKey: string,
919
+ baseURL?: string,
920
+ provider: ProviderType = 'openai'
921
+ ): ModelProfile {
922
+ const recommendations = getGPT5ConfigRecommendations(modelName)
923
+
924
+ const profile: ModelProfile = {
925
+ name,
926
+ provider,
927
+ modelName,
928
+ baseURL: baseURL || 'https://api.openai.com/v1',
929
+ apiKey,
930
+ maxTokens: recommendations.maxTokens || 8192,
931
+ contextLength: recommendations.contextLength || 128000,
932
+ reasoningEffort: recommendations.reasoningEffort || 'medium',
933
+ isActive: true,
934
+ createdAt: Date.now(),
935
+ isGPT5: true,
936
+ validationStatus: 'valid',
937
+ lastValidation: Date.now(),
938
+ }
939
+
940
+ console.log(`✅ Created GPT-5 model profile: ${name} (${modelName})`)
941
+ return profile
942
+ }