@shareai-lab/kode 1.0.69 → 1.0.71

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 (253) hide show
  1. package/README.md +205 -72
  2. package/README.zh-CN.md +246 -0
  3. package/cli.js +62 -0
  4. package/package.json +45 -25
  5. package/scripts/postinstall.js +56 -0
  6. package/src/ProjectOnboarding.tsx +180 -0
  7. package/src/Tool.ts +53 -0
  8. package/src/commands/approvedTools.ts +53 -0
  9. package/src/commands/bug.tsx +20 -0
  10. package/src/commands/clear.ts +43 -0
  11. package/src/commands/compact.ts +120 -0
  12. package/src/commands/config.tsx +19 -0
  13. package/src/commands/cost.ts +18 -0
  14. package/src/commands/ctx_viz.ts +209 -0
  15. package/src/commands/doctor.ts +24 -0
  16. package/src/commands/help.tsx +19 -0
  17. package/src/commands/init.ts +37 -0
  18. package/src/commands/listen.ts +42 -0
  19. package/src/commands/login.tsx +51 -0
  20. package/src/commands/logout.tsx +40 -0
  21. package/src/commands/mcp.ts +41 -0
  22. package/src/commands/model.tsx +40 -0
  23. package/src/commands/modelstatus.tsx +20 -0
  24. package/src/commands/onboarding.tsx +34 -0
  25. package/src/commands/pr_comments.ts +59 -0
  26. package/src/commands/refreshCommands.ts +54 -0
  27. package/src/commands/release-notes.ts +34 -0
  28. package/src/commands/resume.tsx +30 -0
  29. package/src/commands/review.ts +49 -0
  30. package/src/commands/terminalSetup.ts +221 -0
  31. package/src/commands.ts +136 -0
  32. package/src/components/ApproveApiKey.tsx +93 -0
  33. package/src/components/AsciiLogo.tsx +13 -0
  34. package/src/components/AutoUpdater.tsx +148 -0
  35. package/src/components/Bug.tsx +367 -0
  36. package/src/components/Config.tsx +289 -0
  37. package/src/components/ConsoleOAuthFlow.tsx +326 -0
  38. package/src/components/Cost.tsx +23 -0
  39. package/src/components/CostThresholdDialog.tsx +46 -0
  40. package/src/components/CustomSelect/option-map.ts +42 -0
  41. package/src/components/CustomSelect/select-option.tsx +52 -0
  42. package/src/components/CustomSelect/select.tsx +143 -0
  43. package/src/components/CustomSelect/use-select-state.ts +414 -0
  44. package/src/components/CustomSelect/use-select.ts +35 -0
  45. package/src/components/FallbackToolUseRejectedMessage.tsx +15 -0
  46. package/src/components/FileEditToolUpdatedMessage.tsx +66 -0
  47. package/src/components/Help.tsx +215 -0
  48. package/src/components/HighlightedCode.tsx +33 -0
  49. package/src/components/InvalidConfigDialog.tsx +113 -0
  50. package/src/components/Link.tsx +32 -0
  51. package/src/components/LogSelector.tsx +86 -0
  52. package/src/components/Logo.tsx +145 -0
  53. package/src/components/MCPServerApprovalDialog.tsx +100 -0
  54. package/src/components/MCPServerDialogCopy.tsx +25 -0
  55. package/src/components/MCPServerMultiselectDialog.tsx +109 -0
  56. package/src/components/Message.tsx +219 -0
  57. package/src/components/MessageResponse.tsx +15 -0
  58. package/src/components/MessageSelector.tsx +211 -0
  59. package/src/components/ModeIndicator.tsx +88 -0
  60. package/src/components/ModelConfig.tsx +301 -0
  61. package/src/components/ModelListManager.tsx +223 -0
  62. package/src/components/ModelSelector.tsx +3208 -0
  63. package/src/components/ModelStatusDisplay.tsx +228 -0
  64. package/src/components/Onboarding.tsx +274 -0
  65. package/src/components/PressEnterToContinue.tsx +11 -0
  66. package/src/components/PromptInput.tsx +710 -0
  67. package/src/components/SentryErrorBoundary.ts +33 -0
  68. package/src/components/Spinner.tsx +129 -0
  69. package/src/components/StructuredDiff.tsx +184 -0
  70. package/src/components/TextInput.tsx +246 -0
  71. package/src/components/TokenWarning.tsx +31 -0
  72. package/src/components/ToolUseLoader.tsx +40 -0
  73. package/src/components/TrustDialog.tsx +106 -0
  74. package/src/components/binary-feedback/BinaryFeedback.tsx +63 -0
  75. package/src/components/binary-feedback/BinaryFeedbackOption.tsx +111 -0
  76. package/src/components/binary-feedback/BinaryFeedbackView.tsx +172 -0
  77. package/src/components/binary-feedback/utils.ts +220 -0
  78. package/src/components/messages/AssistantBashOutputMessage.tsx +22 -0
  79. package/src/components/messages/AssistantLocalCommandOutputMessage.tsx +45 -0
  80. package/src/components/messages/AssistantRedactedThinkingMessage.tsx +19 -0
  81. package/src/components/messages/AssistantTextMessage.tsx +144 -0
  82. package/src/components/messages/AssistantThinkingMessage.tsx +40 -0
  83. package/src/components/messages/AssistantToolUseMessage.tsx +123 -0
  84. package/src/components/messages/UserBashInputMessage.tsx +28 -0
  85. package/src/components/messages/UserCommandMessage.tsx +30 -0
  86. package/src/components/messages/UserKodingInputMessage.tsx +28 -0
  87. package/src/components/messages/UserPromptMessage.tsx +35 -0
  88. package/src/components/messages/UserTextMessage.tsx +39 -0
  89. package/src/components/messages/UserToolResultMessage/UserToolCanceledMessage.tsx +12 -0
  90. package/src/components/messages/UserToolResultMessage/UserToolErrorMessage.tsx +36 -0
  91. package/src/components/messages/UserToolResultMessage/UserToolRejectMessage.tsx +31 -0
  92. package/src/components/messages/UserToolResultMessage/UserToolResultMessage.tsx +57 -0
  93. package/src/components/messages/UserToolResultMessage/UserToolSuccessMessage.tsx +35 -0
  94. package/src/components/messages/UserToolResultMessage/utils.tsx +56 -0
  95. package/src/components/permissions/BashPermissionRequest/BashPermissionRequest.tsx +121 -0
  96. package/src/components/permissions/FallbackPermissionRequest.tsx +155 -0
  97. package/src/components/permissions/FileEditPermissionRequest/FileEditPermissionRequest.tsx +182 -0
  98. package/src/components/permissions/FileEditPermissionRequest/FileEditToolDiff.tsx +75 -0
  99. package/src/components/permissions/FileWritePermissionRequest/FileWritePermissionRequest.tsx +164 -0
  100. package/src/components/permissions/FileWritePermissionRequest/FileWriteToolDiff.tsx +81 -0
  101. package/src/components/permissions/FilesystemPermissionRequest/FilesystemPermissionRequest.tsx +242 -0
  102. package/src/components/permissions/PermissionRequest.tsx +103 -0
  103. package/src/components/permissions/PermissionRequestTitle.tsx +69 -0
  104. package/src/components/permissions/hooks.ts +44 -0
  105. package/src/components/permissions/toolUseOptions.ts +59 -0
  106. package/src/components/permissions/utils.ts +23 -0
  107. package/src/constants/betas.ts +5 -0
  108. package/src/constants/claude-asterisk-ascii-art.tsx +238 -0
  109. package/src/constants/figures.ts +4 -0
  110. package/src/constants/keys.ts +3 -0
  111. package/src/constants/macros.ts +6 -0
  112. package/src/constants/models.ts +935 -0
  113. package/src/constants/oauth.ts +18 -0
  114. package/src/constants/product.ts +17 -0
  115. package/src/constants/prompts.ts +177 -0
  116. package/src/constants/releaseNotes.ts +7 -0
  117. package/src/context/PermissionContext.tsx +149 -0
  118. package/src/context.ts +278 -0
  119. package/src/cost-tracker.ts +84 -0
  120. package/src/entrypoints/cli.tsx +1498 -0
  121. package/src/entrypoints/mcp.ts +176 -0
  122. package/src/history.ts +25 -0
  123. package/src/hooks/useApiKeyVerification.ts +59 -0
  124. package/src/hooks/useArrowKeyHistory.ts +55 -0
  125. package/src/hooks/useCanUseTool.ts +138 -0
  126. package/src/hooks/useCancelRequest.ts +39 -0
  127. package/src/hooks/useDoublePress.ts +42 -0
  128. package/src/hooks/useExitOnCtrlCD.ts +31 -0
  129. package/src/hooks/useInterval.ts +25 -0
  130. package/src/hooks/useLogMessages.ts +16 -0
  131. package/src/hooks/useLogStartupTime.ts +12 -0
  132. package/src/hooks/useNotifyAfterTimeout.ts +65 -0
  133. package/src/hooks/usePermissionRequestLogging.ts +44 -0
  134. package/src/hooks/useSlashCommandTypeahead.ts +137 -0
  135. package/src/hooks/useTerminalSize.ts +49 -0
  136. package/src/hooks/useTextInput.ts +315 -0
  137. package/src/messages.ts +37 -0
  138. package/src/permissions.ts +268 -0
  139. package/src/query.ts +704 -0
  140. package/src/screens/ConfigureNpmPrefix.tsx +197 -0
  141. package/src/screens/Doctor.tsx +219 -0
  142. package/src/screens/LogList.tsx +68 -0
  143. package/src/screens/REPL.tsx +792 -0
  144. package/src/screens/ResumeConversation.tsx +68 -0
  145. package/src/services/browserMocks.ts +66 -0
  146. package/src/services/claude.ts +1947 -0
  147. package/src/services/customCommands.ts +683 -0
  148. package/src/services/fileFreshness.ts +377 -0
  149. package/src/services/mcpClient.ts +564 -0
  150. package/src/services/mcpServerApproval.tsx +50 -0
  151. package/src/services/notifier.ts +40 -0
  152. package/src/services/oauth.ts +357 -0
  153. package/src/services/openai.ts +796 -0
  154. package/src/services/sentry.ts +3 -0
  155. package/src/services/statsig.ts +171 -0
  156. package/src/services/statsigStorage.ts +86 -0
  157. package/src/services/systemReminder.ts +406 -0
  158. package/src/services/vcr.ts +161 -0
  159. package/src/tools/ArchitectTool/ArchitectTool.tsx +122 -0
  160. package/src/tools/ArchitectTool/prompt.ts +15 -0
  161. package/src/tools/AskExpertModelTool/AskExpertModelTool.tsx +505 -0
  162. package/src/tools/BashTool/BashTool.tsx +270 -0
  163. package/src/tools/BashTool/BashToolResultMessage.tsx +38 -0
  164. package/src/tools/BashTool/OutputLine.tsx +48 -0
  165. package/src/tools/BashTool/prompt.ts +174 -0
  166. package/src/tools/BashTool/utils.ts +56 -0
  167. package/src/tools/FileEditTool/FileEditTool.tsx +316 -0
  168. package/src/tools/FileEditTool/prompt.ts +51 -0
  169. package/src/tools/FileEditTool/utils.ts +58 -0
  170. package/src/tools/FileReadTool/FileReadTool.tsx +371 -0
  171. package/src/tools/FileReadTool/prompt.ts +7 -0
  172. package/src/tools/FileWriteTool/FileWriteTool.tsx +297 -0
  173. package/src/tools/FileWriteTool/prompt.ts +10 -0
  174. package/src/tools/GlobTool/GlobTool.tsx +119 -0
  175. package/src/tools/GlobTool/prompt.ts +8 -0
  176. package/src/tools/GrepTool/GrepTool.tsx +147 -0
  177. package/src/tools/GrepTool/prompt.ts +11 -0
  178. package/src/tools/MCPTool/MCPTool.tsx +106 -0
  179. package/src/tools/MCPTool/prompt.ts +3 -0
  180. package/src/tools/MemoryReadTool/MemoryReadTool.tsx +127 -0
  181. package/src/tools/MemoryReadTool/prompt.ts +3 -0
  182. package/src/tools/MemoryWriteTool/MemoryWriteTool.tsx +89 -0
  183. package/src/tools/MemoryWriteTool/prompt.ts +3 -0
  184. package/src/tools/MultiEditTool/MultiEditTool.tsx +366 -0
  185. package/src/tools/MultiEditTool/prompt.ts +45 -0
  186. package/src/tools/NotebookEditTool/NotebookEditTool.tsx +298 -0
  187. package/src/tools/NotebookEditTool/prompt.ts +3 -0
  188. package/src/tools/NotebookReadTool/NotebookReadTool.tsx +266 -0
  189. package/src/tools/NotebookReadTool/prompt.ts +3 -0
  190. package/src/tools/StickerRequestTool/StickerRequestTool.tsx +93 -0
  191. package/src/tools/StickerRequestTool/prompt.ts +19 -0
  192. package/src/tools/TaskTool/TaskTool.tsx +382 -0
  193. package/src/tools/TaskTool/constants.ts +1 -0
  194. package/src/tools/TaskTool/prompt.ts +56 -0
  195. package/src/tools/ThinkTool/ThinkTool.tsx +56 -0
  196. package/src/tools/ThinkTool/prompt.ts +12 -0
  197. package/src/tools/TodoWriteTool/TodoWriteTool.tsx +289 -0
  198. package/src/tools/TodoWriteTool/prompt.ts +63 -0
  199. package/src/tools/lsTool/lsTool.tsx +269 -0
  200. package/src/tools/lsTool/prompt.ts +2 -0
  201. package/src/tools.ts +63 -0
  202. package/src/types/PermissionMode.ts +120 -0
  203. package/src/types/RequestContext.ts +72 -0
  204. package/src/utils/Cursor.ts +436 -0
  205. package/src/utils/PersistentShell.ts +373 -0
  206. package/src/utils/agentStorage.ts +97 -0
  207. package/src/utils/array.ts +3 -0
  208. package/src/utils/ask.tsx +98 -0
  209. package/src/utils/auth.ts +13 -0
  210. package/src/utils/autoCompactCore.ts +223 -0
  211. package/src/utils/autoUpdater.ts +318 -0
  212. package/src/utils/betas.ts +20 -0
  213. package/src/utils/browser.ts +14 -0
  214. package/src/utils/cleanup.ts +72 -0
  215. package/src/utils/commands.ts +261 -0
  216. package/src/utils/config.ts +771 -0
  217. package/src/utils/conversationRecovery.ts +54 -0
  218. package/src/utils/debugLogger.ts +1123 -0
  219. package/src/utils/diff.ts +42 -0
  220. package/src/utils/env.ts +57 -0
  221. package/src/utils/errors.ts +21 -0
  222. package/src/utils/exampleCommands.ts +108 -0
  223. package/src/utils/execFileNoThrow.ts +51 -0
  224. package/src/utils/expertChatStorage.ts +136 -0
  225. package/src/utils/file.ts +402 -0
  226. package/src/utils/fileRecoveryCore.ts +71 -0
  227. package/src/utils/format.tsx +44 -0
  228. package/src/utils/generators.ts +62 -0
  229. package/src/utils/git.ts +92 -0
  230. package/src/utils/globalLogger.ts +77 -0
  231. package/src/utils/http.ts +10 -0
  232. package/src/utils/imagePaste.ts +38 -0
  233. package/src/utils/json.ts +13 -0
  234. package/src/utils/log.ts +382 -0
  235. package/src/utils/markdown.ts +213 -0
  236. package/src/utils/messageContextManager.ts +289 -0
  237. package/src/utils/messages.tsx +938 -0
  238. package/src/utils/model.ts +836 -0
  239. package/src/utils/permissions/filesystem.ts +118 -0
  240. package/src/utils/ripgrep.ts +167 -0
  241. package/src/utils/sessionState.ts +49 -0
  242. package/src/utils/state.ts +25 -0
  243. package/src/utils/style.ts +29 -0
  244. package/src/utils/terminal.ts +49 -0
  245. package/src/utils/theme.ts +122 -0
  246. package/src/utils/thinking.ts +144 -0
  247. package/src/utils/todoStorage.ts +431 -0
  248. package/src/utils/tokens.ts +43 -0
  249. package/src/utils/toolExecutionController.ts +163 -0
  250. package/src/utils/unaryLogging.ts +26 -0
  251. package/src/utils/user.ts +37 -0
  252. package/src/utils/validate.ts +165 -0
  253. package/cli.mjs +0 -1803
@@ -0,0 +1,1498 @@
1
+ #!/usr/bin/env -S node --no-warnings=ExperimentalWarning --enable-source-maps
2
+ import { initSentry } from '../services/sentry'
3
+ import { PRODUCT_COMMAND, PRODUCT_NAME } from '../constants/product'
4
+ initSentry() // Initialize Sentry as early as possible
5
+
6
+ // XXX: Without this line (and the Object.keys, even though it seems like it does nothing!),
7
+ // there is a bug in Bun only on Win32 that causes this import to be removed, even though
8
+ // its use is solely because of its side-effects.
9
+ import * as dontcare from '@anthropic-ai/sdk/shims/node'
10
+ Object.keys(dontcare)
11
+
12
+ import React from 'react'
13
+ import { ReadStream } from 'tty'
14
+ import { openSync, existsSync } from 'fs'
15
+ import { render, RenderOptions } from 'ink'
16
+ import { REPL } from '../screens/REPL'
17
+ import { addToHistory } from '../history'
18
+ import { getContext, setContext, removeContext } from '../context'
19
+ import { Command } from '@commander-js/extra-typings'
20
+ import { ask } from '../utils/ask'
21
+ import { hasPermissionsToUseTool } from '../permissions'
22
+ import { getTools } from '../tools'
23
+ import {
24
+ getGlobalConfig,
25
+ getCurrentProjectConfig,
26
+ saveGlobalConfig,
27
+ saveCurrentProjectConfig,
28
+ getCustomApiKeyStatus,
29
+ normalizeApiKeyForConfig,
30
+ setConfigForCLI,
31
+ deleteConfigForCLI,
32
+ getConfigForCLI,
33
+ listConfigForCLI,
34
+ enableConfigs,
35
+ } from '../utils/config'
36
+ import { cwd } from 'process'
37
+ import { dateToFilename, logError, parseLogFilename } from '../utils/log'
38
+ import { initDebugLogger } from '../utils/debugLogger'
39
+ import { Onboarding } from '../components/Onboarding'
40
+ import { Doctor } from '../screens/Doctor'
41
+ import { ApproveApiKey } from '../components/ApproveApiKey'
42
+ import { TrustDialog } from '../components/TrustDialog'
43
+ import { checkHasTrustDialogAccepted } from '../utils/config'
44
+ import { isDefaultSlowAndCapableModel } from '../utils/model'
45
+ import { LogList } from '../screens/LogList'
46
+ import { ResumeConversation } from '../screens/ResumeConversation'
47
+ import { startMCPServer } from './mcp'
48
+ import { env } from '../utils/env'
49
+ import { getCwd, setCwd, setOriginalCwd } from '../utils/state'
50
+ import { omit } from 'lodash-es'
51
+ import { getCommands } from '../commands'
52
+ import { getNextAvailableLogForkNumber, loadLogList } from '../utils/log'
53
+ import { loadMessagesFromLog } from '../utils/conversationRecovery'
54
+ import { cleanupOldMessageFilesInBackground } from '../utils/cleanup'
55
+ import {
56
+ handleListApprovedTools,
57
+ handleRemoveApprovedTool,
58
+ } from '../commands/approvedTools'
59
+ import {
60
+ addMcpServer,
61
+ getMcpServer,
62
+ listMCPServers,
63
+ parseEnvVars,
64
+ removeMcpServer,
65
+ getClients,
66
+ ensureConfigScope,
67
+ } from '../services/mcpClient'
68
+ import { handleMcprcServerApprovals } from '../services/mcpServerApproval'
69
+ import { checkGate, initializeStatsig, logEvent } from '../services/statsig'
70
+ import { getExampleCommands } from '../utils/exampleCommands'
71
+ import { cursorShow } from 'ansi-escapes'
72
+ import {
73
+ getLatestVersion,
74
+ installGlobalPackage,
75
+ assertMinVersion,
76
+ } from '../utils/autoUpdater'
77
+ import { CACHE_PATHS } from '../utils/log'
78
+ import { PersistentShell } from '../utils/PersistentShell'
79
+ import { GATE_USE_EXTERNAL_UPDATER } from '../constants/betas'
80
+ import { clearTerminal } from '../utils/terminal'
81
+ import { showInvalidConfigDialog } from '../components/InvalidConfigDialog'
82
+ import { ConfigParseError } from '../utils/errors'
83
+ import { grantReadPermissionForOriginalDir } from '../utils/permissions/filesystem'
84
+ import { MACRO } from '../constants/macros'
85
+ export function completeOnboarding(): void {
86
+ const config = getGlobalConfig()
87
+ saveGlobalConfig({
88
+ ...config,
89
+ hasCompletedOnboarding: true,
90
+ lastOnboardingVersion: MACRO.VERSION,
91
+ })
92
+ }
93
+
94
+ async function showSetupScreens(
95
+ safeMode?: boolean,
96
+ print?: boolean,
97
+ ): Promise<void> {
98
+ if (process.env.NODE_ENV === 'test') {
99
+ return
100
+ }
101
+
102
+ const config = getGlobalConfig()
103
+ if (
104
+ !config.theme ||
105
+ !config.hasCompletedOnboarding // always show onboarding at least once
106
+ ) {
107
+ await clearTerminal()
108
+ await new Promise<void>(resolve => {
109
+ render(
110
+ <Onboarding
111
+ onDone={async () => {
112
+ completeOnboarding()
113
+ await clearTerminal()
114
+ resolve()
115
+ }}
116
+ />,
117
+ {
118
+ exitOnCtrlC: false,
119
+ },
120
+ )
121
+ })
122
+ }
123
+
124
+ // // Check for custom API key (only allowed for ants)
125
+ // if (process.env.ANTHROPIC_API_KEY && process.env.USER_TYPE === 'ant') {
126
+ // const customApiKeyTruncated = normalizeApiKeyForConfig(
127
+ // process.env.ANTHROPIC_API_KEY!,
128
+ // )
129
+ // const keyStatus = getCustomApiKeyStatus(customApiKeyTruncated)
130
+ // if (keyStatus === 'new') {
131
+ // await new Promise<void>(resolve => {
132
+ // render(
133
+ // <ApproveApiKey
134
+ // customApiKeyTruncated={customApiKeyTruncated}
135
+ // onDone={async () => {
136
+ // await clearTerminal()
137
+ // resolve()
138
+ // }}
139
+ // />,
140
+ // {
141
+ // exitOnCtrlC: false,
142
+ // },
143
+ // )
144
+ // })
145
+ // }
146
+ // }
147
+
148
+ // In non-interactive mode, only show trust dialog in safe mode
149
+ if (!print && safeMode) {
150
+ if (!checkHasTrustDialogAccepted()) {
151
+ await new Promise<void>(resolve => {
152
+ const onDone = () => {
153
+ // Grant read permission to the current working directory
154
+ grantReadPermissionForOriginalDir()
155
+ resolve()
156
+ }
157
+ render(<TrustDialog onDone={onDone} />, {
158
+ exitOnCtrlC: false,
159
+ })
160
+ })
161
+ }
162
+
163
+ // After trust dialog, check for any mcprc servers that need approval
164
+ if (process.env.USER_TYPE === 'ant') {
165
+ await handleMcprcServerApprovals()
166
+ }
167
+ }
168
+ }
169
+
170
+ function logStartup(): void {
171
+ const config = getGlobalConfig()
172
+ saveGlobalConfig({
173
+ ...config,
174
+ numStartups: (config.numStartups ?? 0) + 1,
175
+ })
176
+ }
177
+
178
+ async function setup(cwd: string, safeMode?: boolean): Promise<void> {
179
+ // Set both current and original working directory if --cwd was provided
180
+ if (cwd !== process.cwd()) {
181
+ setOriginalCwd(cwd)
182
+ }
183
+ await setCwd(cwd)
184
+
185
+ // Always grant read permissions for original working dir
186
+ grantReadPermissionForOriginalDir()
187
+
188
+ // If --safe mode is enabled, prevent root/sudo usage for security
189
+ if (safeMode) {
190
+ // Check if running as root/sudo on Unix-like systems
191
+ if (
192
+ process.platform !== 'win32' &&
193
+ typeof process.getuid === 'function' &&
194
+ process.getuid() === 0
195
+ ) {
196
+ console.error(
197
+ `--safe mode cannot be used with root/sudo privileges for security reasons`,
198
+ )
199
+ process.exit(1)
200
+ }
201
+ }
202
+
203
+ if (process.env.NODE_ENV === 'test') {
204
+ return
205
+ }
206
+
207
+ cleanupOldMessageFilesInBackground()
208
+ // getExampleCommands() // Pre-fetch example commands
209
+ getContext() // Pre-fetch all context data at once
210
+ // initializeStatsig() // Kick off statsig initialization
211
+
212
+ // Migrate old iterm2KeyBindingInstalled config to new shiftEnterKeyBindingInstalled
213
+ const globalConfig = getGlobalConfig()
214
+ if (
215
+ globalConfig.iterm2KeyBindingInstalled === true &&
216
+ globalConfig.shiftEnterKeyBindingInstalled !== true
217
+ ) {
218
+ const updatedConfig = {
219
+ ...globalConfig,
220
+ shiftEnterKeyBindingInstalled: true,
221
+ }
222
+ // Remove the old config property
223
+ delete updatedConfig.iterm2KeyBindingInstalled
224
+ saveGlobalConfig(updatedConfig)
225
+ }
226
+
227
+ // Check for last session's cost and duration
228
+ const projectConfig = getCurrentProjectConfig()
229
+ if (
230
+ projectConfig.lastCost !== undefined &&
231
+ projectConfig.lastDuration !== undefined
232
+ ) {
233
+ logEvent('tengu_exit', {
234
+ last_session_cost: String(projectConfig.lastCost),
235
+ last_session_api_duration: String(projectConfig.lastAPIDuration),
236
+ last_session_duration: String(projectConfig.lastDuration),
237
+ last_session_id: projectConfig.lastSessionId,
238
+ })
239
+ // Clear the values after logging
240
+ // saveCurrentProjectConfig({
241
+ // ...projectConfig,
242
+ // lastCost: undefined,
243
+ // lastAPIDuration: undefined,
244
+ // lastDuration: undefined,
245
+ // lastSessionId: undefined,
246
+ // })
247
+ }
248
+
249
+ // Check auto-updater permissions
250
+ const autoUpdaterStatus = globalConfig.autoUpdaterStatus ?? 'not_configured'
251
+ if (autoUpdaterStatus === 'not_configured') {
252
+ logEvent('tengu_setup_auto_updater_not_configured', {})
253
+ await new Promise<void>(resolve => {
254
+ render(<Doctor onDone={() => resolve()} />)
255
+ })
256
+ }
257
+ }
258
+
259
+ async function main() {
260
+ // 初始化调试日志系统
261
+ initDebugLogger()
262
+
263
+ // Validate configs are valid and enable configuration system
264
+ try {
265
+ enableConfigs()
266
+ } catch (error: unknown) {
267
+ if (error instanceof ConfigParseError) {
268
+ // Show the invalid config dialog with the error object
269
+ await showInvalidConfigDialog({ error })
270
+ return // Exit after handling the config error
271
+ }
272
+ }
273
+
274
+ let inputPrompt = ''
275
+ let renderContext: RenderOptions | undefined = {
276
+ exitOnCtrlC: false,
277
+ onFlicker() {
278
+ logEvent('tengu_flicker', {})
279
+ },
280
+ }
281
+
282
+ if (
283
+ !process.stdin.isTTY &&
284
+ !process.env.CI &&
285
+ // Input hijacking breaks MCP.
286
+ !process.argv.includes('mcp')
287
+ ) {
288
+ inputPrompt = await stdin()
289
+ if (process.platform !== 'win32') {
290
+ try {
291
+ const ttyFd = openSync('/dev/tty', 'r')
292
+ renderContext = { ...renderContext, stdin: new ReadStream(ttyFd) }
293
+ } catch (err) {
294
+ logError(`Could not open /dev/tty: ${err}`)
295
+ }
296
+ }
297
+ }
298
+ await parseArgs(inputPrompt, renderContext)
299
+ }
300
+
301
+ async function parseArgs(
302
+ stdinContent: string,
303
+ renderContext: RenderOptions | undefined,
304
+ ): Promise<Command> {
305
+ const program = new Command()
306
+
307
+ const renderContextWithExitOnCtrlC = {
308
+ ...renderContext,
309
+ exitOnCtrlC: true,
310
+ }
311
+
312
+ // Get the initial list of commands filtering based on user type
313
+ const commands = await getCommands()
314
+
315
+ // Format command list for help text (using same filter as in help.ts)
316
+ const commandList = commands
317
+ .filter(cmd => !cmd.isHidden)
318
+ .map(cmd => `/${cmd.name} - ${cmd.description}`)
319
+ .join('\n')
320
+
321
+ program
322
+ .name(PRODUCT_COMMAND)
323
+ .description(
324
+ `${PRODUCT_NAME} - starts an interactive session by default, use -p/--print for non-interactive output
325
+
326
+ Slash commands available during an interactive session:
327
+ ${commandList}`,
328
+ )
329
+ .argument('[prompt]', 'Your prompt', String)
330
+ .option('-c, --cwd <cwd>', 'The current working directory', String, cwd())
331
+ .option('-d, --debug', 'Enable debug mode', () => true)
332
+ .option(
333
+ '--debug-verbose',
334
+ 'Enable verbose debug terminal output',
335
+ () => true,
336
+ )
337
+ .option(
338
+ '--verbose',
339
+ 'Override verbose mode setting from config',
340
+ () => true,
341
+ )
342
+ .option('-e, --enable-architect', 'Enable the Architect tool', () => true)
343
+ .option(
344
+ '-p, --print',
345
+ 'Print response and exit (useful for pipes)',
346
+ () => true,
347
+ )
348
+ .option(
349
+ '--safe',
350
+ 'Enable strict permission checking mode (default is permissive)',
351
+ () => true,
352
+ )
353
+ .action(
354
+ async (prompt, { cwd, debug, verbose, enableArchitect, print, safe }) => {
355
+ await showSetupScreens(safe, print)
356
+ logEvent('tengu_init', {
357
+ entrypoint: PRODUCT_COMMAND,
358
+ hasInitialPrompt: Boolean(prompt).toString(),
359
+ hasStdin: Boolean(stdinContent).toString(),
360
+ enableArchitect: enableArchitect?.toString() ?? 'false',
361
+ verbose: verbose?.toString() ?? 'false',
362
+ debug: debug?.toString() ?? 'false',
363
+ print: print?.toString() ?? 'false',
364
+ })
365
+ await setup(cwd, safe)
366
+
367
+ assertMinVersion()
368
+
369
+ const [tools, mcpClients] = await Promise.all([
370
+ getTools(
371
+ enableArchitect ?? getCurrentProjectConfig().enableArchitectTool,
372
+ ),
373
+ getClients(),
374
+ ])
375
+ // logStartup()
376
+ const inputPrompt = [prompt, stdinContent].filter(Boolean).join('\n')
377
+ if (print) {
378
+ if (!inputPrompt) {
379
+ console.error(
380
+ 'Error: Input must be provided either through stdin or as a prompt argument when using --print',
381
+ )
382
+ process.exit(1)
383
+ }
384
+
385
+ addToHistory(inputPrompt)
386
+ const { resultText: response } = await ask({
387
+ commands,
388
+ hasPermissionsToUseTool,
389
+ messageLogName: dateToFilename(new Date()),
390
+ prompt: inputPrompt,
391
+ cwd,
392
+ tools,
393
+ safeMode: safe,
394
+ })
395
+ console.log(response)
396
+ process.exit(0)
397
+ } else {
398
+ const isDefaultModel = await isDefaultSlowAndCapableModel()
399
+
400
+ render(
401
+ <REPL
402
+ commands={commands}
403
+ debug={debug}
404
+ initialPrompt={inputPrompt}
405
+ messageLogName={dateToFilename(new Date())}
406
+ shouldShowPromptInput={true}
407
+ verbose={verbose}
408
+ tools={tools}
409
+ safeMode={safe}
410
+ mcpClients={mcpClients}
411
+ isDefaultModel={isDefaultModel}
412
+ />,
413
+ renderContext,
414
+ )
415
+ }
416
+ },
417
+ )
418
+ .version(MACRO.VERSION, '-v, --version')
419
+
420
+ // Enable melon mode for ants if --melon is passed
421
+ // For bun tree shaking to work, this has to be a top level --define, not inside MACRO
422
+ // if (process.env.USER_TYPE === 'ant') {
423
+ // program
424
+ // .option('--melon', 'Enable melon mode')
425
+ // .hook('preAction', async () => {
426
+ // if ((program.opts() as { melon?: boolean }).melon) {
427
+ // const { runMelonWrapper } = await import('../utils/melonWrapper')
428
+ // const melonArgs = process.argv.slice(
429
+ // process.argv.indexOf('--melon') + 1,
430
+ // )
431
+ // const exitCode = runMelonWrapper(melonArgs)
432
+ // process.exit(exitCode)
433
+ // }
434
+ // })
435
+ // }
436
+
437
+ // claude config
438
+ const config = program
439
+ .command('config')
440
+ .description(
441
+ `Manage configuration (eg. ${PRODUCT_COMMAND} config set -g theme dark)`,
442
+ )
443
+
444
+ config
445
+ .command('get <key>')
446
+ .description('Get a config value')
447
+ .option('-c, --cwd <cwd>', 'The current working directory', String, cwd())
448
+ .option('-g, --global', 'Use global config')
449
+ .action(async (key, { cwd, global }) => {
450
+ await setup(cwd, false)
451
+ console.log(getConfigForCLI(key, global ?? false))
452
+ process.exit(0)
453
+ })
454
+
455
+ config
456
+ .command('set <key> <value>')
457
+ .description('Set a config value')
458
+ .option('-c, --cwd <cwd>', 'The current working directory', String, cwd())
459
+ .option('-g, --global', 'Use global config')
460
+ .action(async (key, value, { cwd, global }) => {
461
+ await setup(cwd, false)
462
+ setConfigForCLI(key, value, global ?? false)
463
+ console.log(`Set ${key} to ${value}`)
464
+ process.exit(0)
465
+ })
466
+
467
+ config
468
+ .command('remove <key>')
469
+ .description('Remove a config value')
470
+ .option('-c, --cwd <cwd>', 'The current working directory', String, cwd())
471
+ .option('-g, --global', 'Use global config')
472
+ .action(async (key, { cwd, global }) => {
473
+ await setup(cwd, false)
474
+ deleteConfigForCLI(key, global ?? false)
475
+ console.log(`Removed ${key}`)
476
+ process.exit(0)
477
+ })
478
+
479
+ config
480
+ .command('list')
481
+ .description('List all config values')
482
+ .option('-c, --cwd <cwd>', 'The current working directory', String, cwd())
483
+ .option('-g, --global', 'Use global config', false)
484
+ .action(async ({ cwd, global }) => {
485
+ await setup(cwd, false)
486
+ console.log(
487
+ JSON.stringify(listConfigForCLI((global as true) ?? false), null, 2),
488
+ )
489
+ process.exit(0)
490
+ })
491
+
492
+ // claude approved-tools
493
+
494
+ const allowedTools = program
495
+ .command('approved-tools')
496
+ .description('Manage approved tools')
497
+
498
+ allowedTools
499
+ .command('list')
500
+ .description('List all approved tools')
501
+ .action(async () => {
502
+ const result = handleListApprovedTools(getCwd())
503
+ console.log(result)
504
+ process.exit(0)
505
+ })
506
+
507
+ allowedTools
508
+ .command('remove <tool>')
509
+ .description('Remove a tool from the list of approved tools')
510
+ .action(async (tool: string) => {
511
+ const result = handleRemoveApprovedTool(tool)
512
+ logEvent('tengu_approved_tool_remove', {
513
+ tool,
514
+ success: String(result.success),
515
+ })
516
+ console.log(result.message)
517
+ process.exit(result.success ? 0 : 1)
518
+ })
519
+
520
+ // claude mcp
521
+
522
+ const mcp = program
523
+ .command('mcp')
524
+ .description('Configure and manage MCP servers')
525
+
526
+ mcp
527
+ .command('serve')
528
+ .description(`Start the ${PRODUCT_NAME} MCP server`)
529
+ .action(async () => {
530
+ const providedCwd = (program.opts() as { cwd?: string }).cwd ?? cwd()
531
+ logEvent('tengu_mcp_start', { providedCwd })
532
+
533
+ // Verify the directory exists
534
+ if (!existsSync(providedCwd)) {
535
+ console.error(`Error: Directory ${providedCwd} does not exist`)
536
+ process.exit(1)
537
+ }
538
+
539
+ try {
540
+ await setup(providedCwd, false)
541
+ await startMCPServer(providedCwd)
542
+ } catch (error) {
543
+ console.error('Error: Failed to start MCP server:', error)
544
+ process.exit(1)
545
+ }
546
+ })
547
+
548
+ mcp
549
+ .command('add-sse <name> <url>')
550
+ .description('Add an SSE server')
551
+ .option(
552
+ '-s, --scope <scope>',
553
+ 'Configuration scope (project or global)',
554
+ 'project',
555
+ )
556
+ .action(async (name, url, options) => {
557
+ try {
558
+ const scope = ensureConfigScope(options.scope)
559
+ logEvent('tengu_mcp_add', { name, type: 'sse', scope })
560
+
561
+ addMcpServer(name, { type: 'sse', url }, scope)
562
+ console.log(
563
+ `Added SSE MCP server ${name} with URL ${url} to ${scope} config`,
564
+ )
565
+ process.exit(0)
566
+ } catch (error) {
567
+ console.error((error as Error).message)
568
+ process.exit(1)
569
+ }
570
+ })
571
+
572
+ mcp
573
+ .command('add [name] [commandOrUrl] [args...]')
574
+ .description('Add a server (run without arguments for interactive wizard)')
575
+ .option(
576
+ '-s, --scope <scope>',
577
+ 'Configuration scope (project or global)',
578
+ 'project',
579
+ )
580
+ .option(
581
+ '-e, --env <env...>',
582
+ 'Set environment variables (e.g. -e KEY=value)',
583
+ )
584
+ .action(async (name, commandOrUrl, args, options) => {
585
+ try {
586
+ // If name is not provided, start interactive wizard
587
+ if (!name) {
588
+ console.log('Interactive wizard mode: Enter the server details')
589
+ const { createInterface } = await import('readline')
590
+ const rl = createInterface({
591
+ input: process.stdin,
592
+ output: process.stdout,
593
+ })
594
+
595
+ const question = (query: string) =>
596
+ new Promise<string>(resolve => rl.question(query, resolve))
597
+
598
+ // Get server name
599
+ const serverName = await question('Server name: ')
600
+ if (!serverName) {
601
+ console.error('Error: Server name is required')
602
+ rl.close()
603
+ process.exit(1)
604
+ }
605
+
606
+ // Get server type
607
+ const serverType = await question(
608
+ 'Server type (stdio or sse) [stdio]: ',
609
+ )
610
+ const type =
611
+ serverType && ['stdio', 'sse'].includes(serverType)
612
+ ? serverType
613
+ : 'stdio'
614
+
615
+ // Get command or URL
616
+ const prompt = type === 'stdio' ? 'Command: ' : 'URL: '
617
+ const commandOrUrlValue = await question(prompt)
618
+ if (!commandOrUrlValue) {
619
+ console.error(
620
+ `Error: ${type === 'stdio' ? 'Command' : 'URL'} is required`,
621
+ )
622
+ rl.close()
623
+ process.exit(1)
624
+ }
625
+
626
+ // Get args and env if stdio
627
+ let serverArgs: string[] = []
628
+ let serverEnv: Record<string, string> = {}
629
+
630
+ if (type === 'stdio') {
631
+ const argsStr = await question(
632
+ 'Command arguments (space-separated): ',
633
+ )
634
+ serverArgs = argsStr ? argsStr.split(' ').filter(Boolean) : []
635
+
636
+ const envStr = await question(
637
+ 'Environment variables (format: KEY1=value1,KEY2=value2): ',
638
+ )
639
+ if (envStr) {
640
+ const envPairs = envStr.split(',').map(pair => pair.trim())
641
+ serverEnv = parseEnvVars(envPairs.map(pair => pair))
642
+ }
643
+ }
644
+
645
+ // Get scope
646
+ const scopeStr = await question(
647
+ 'Configuration scope (project or global) [project]: ',
648
+ )
649
+ const serverScope = ensureConfigScope(scopeStr || 'project')
650
+
651
+ rl.close()
652
+
653
+ // Add the server
654
+ if (type === 'sse') {
655
+ logEvent('tengu_mcp_add', {
656
+ name: serverName,
657
+ type: 'sse',
658
+ scope: serverScope,
659
+ })
660
+ addMcpServer(
661
+ serverName,
662
+ { type: 'sse', url: commandOrUrlValue },
663
+ serverScope,
664
+ )
665
+ console.log(
666
+ `Added SSE MCP server ${serverName} with URL ${commandOrUrlValue} to ${serverScope} config`,
667
+ )
668
+ } else {
669
+ logEvent('tengu_mcp_add', {
670
+ name: serverName,
671
+ type: 'stdio',
672
+ scope: serverScope,
673
+ })
674
+ addMcpServer(
675
+ serverName,
676
+ {
677
+ type: 'stdio',
678
+ command: commandOrUrlValue,
679
+ args: serverArgs,
680
+ env: serverEnv,
681
+ },
682
+ serverScope,
683
+ )
684
+
685
+ console.log(
686
+ `Added stdio MCP server ${serverName} with command: ${commandOrUrlValue} ${serverArgs.join(' ')} to ${serverScope} config`,
687
+ )
688
+ }
689
+ } else if (name && commandOrUrl) {
690
+ // Regular non-interactive flow
691
+ const scope = ensureConfigScope(options.scope)
692
+
693
+ // Check if it's an SSE URL (starts with http:// or https://)
694
+ if (commandOrUrl.match(/^https?:\/\//)) {
695
+ logEvent('tengu_mcp_add', { name, type: 'sse', scope })
696
+ addMcpServer(name, { type: 'sse', url: commandOrUrl }, scope)
697
+ console.log(
698
+ `Added SSE MCP server ${name} with URL ${commandOrUrl} to ${scope} config`,
699
+ )
700
+ } else {
701
+ logEvent('tengu_mcp_add', { name, type: 'stdio', scope })
702
+ const env = parseEnvVars(options.env)
703
+ addMcpServer(
704
+ name,
705
+ { type: 'stdio', command: commandOrUrl, args: args || [], env },
706
+ scope,
707
+ )
708
+
709
+ console.log(
710
+ `Added stdio MCP server ${name} with command: ${commandOrUrl} ${(args || []).join(' ')} to ${scope} config`,
711
+ )
712
+ }
713
+ } else {
714
+ console.error(
715
+ 'Error: Missing required arguments. Either provide no arguments for interactive mode or specify name and command/URL.',
716
+ )
717
+ process.exit(1)
718
+ }
719
+
720
+ process.exit(0)
721
+ } catch (error) {
722
+ console.error((error as Error).message)
723
+ process.exit(1)
724
+ }
725
+ })
726
+ mcp
727
+ .command('remove <name>')
728
+ .description('Remove an MCP server')
729
+ .option(
730
+ '-s, --scope <scope>',
731
+ 'Configuration scope (project, global, or mcprc)',
732
+ 'project',
733
+ )
734
+ .action(async (name: string, options: { scope?: string }) => {
735
+ try {
736
+ const scope = ensureConfigScope(options.scope)
737
+ logEvent('tengu_mcp_delete', { name, scope })
738
+
739
+ removeMcpServer(name, scope)
740
+ console.log(`Removed MCP server ${name} from ${scope} config`)
741
+ process.exit(0)
742
+ } catch (error) {
743
+ console.error((error as Error).message)
744
+ process.exit(1)
745
+ }
746
+ })
747
+
748
+ mcp
749
+ .command('list')
750
+ .description('List configured MCP servers')
751
+ .action(() => {
752
+ logEvent('tengu_mcp_list', {})
753
+ const servers = listMCPServers()
754
+ if (Object.keys(servers).length === 0) {
755
+ console.log(
756
+ `No MCP servers configured. Use \`${PRODUCT_COMMAND} mcp add\` to add a server.`,
757
+ )
758
+ } else {
759
+ for (const [name, server] of Object.entries(servers)) {
760
+ if (server.type === 'sse') {
761
+ console.log(`${name}: ${server.url} (SSE)`)
762
+ } else {
763
+ console.log(`${name}: ${server.command} ${server.args.join(' ')}`)
764
+ }
765
+ }
766
+ }
767
+ process.exit(0)
768
+ })
769
+
770
+ mcp
771
+ .command('add-json <name> <json>')
772
+ .description('Add an MCP server (stdio or SSE) with a JSON string')
773
+ .option(
774
+ '-s, --scope <scope>',
775
+ 'Configuration scope (project or global)',
776
+ 'project',
777
+ )
778
+ .action(async (name, jsonStr, options) => {
779
+ try {
780
+ const scope = ensureConfigScope(options.scope)
781
+
782
+ // Parse JSON string
783
+ let serverConfig
784
+ try {
785
+ serverConfig = JSON.parse(jsonStr)
786
+ } catch (e) {
787
+ console.error('Error: Invalid JSON string')
788
+ process.exit(1)
789
+ }
790
+
791
+ // Validate the server config
792
+ if (
793
+ !serverConfig.type ||
794
+ !['stdio', 'sse'].includes(serverConfig.type)
795
+ ) {
796
+ console.error('Error: Server type must be "stdio" or "sse"')
797
+ process.exit(1)
798
+ }
799
+
800
+ if (serverConfig.type === 'sse' && !serverConfig.url) {
801
+ console.error('Error: SSE server must have a URL')
802
+ process.exit(1)
803
+ }
804
+
805
+ if (serverConfig.type === 'stdio' && !serverConfig.command) {
806
+ console.error('Error: stdio server must have a command')
807
+ process.exit(1)
808
+ }
809
+
810
+ // Add server with the provided config
811
+ logEvent('tengu_mcp_add_json', { name, type: serverConfig.type, scope })
812
+ addMcpServer(name, serverConfig, scope)
813
+
814
+ if (serverConfig.type === 'sse') {
815
+ console.log(
816
+ `Added SSE MCP server ${name} with URL ${serverConfig.url} to ${scope} config`,
817
+ )
818
+ } else {
819
+ console.log(
820
+ `Added stdio MCP server ${name} with command: ${serverConfig.command} ${(
821
+ serverConfig.args || []
822
+ ).join(' ')} to ${scope} config`,
823
+ )
824
+ }
825
+
826
+ process.exit(0)
827
+ } catch (error) {
828
+ console.error((error as Error).message)
829
+ process.exit(1)
830
+ }
831
+ })
832
+
833
+ mcp
834
+ .command('get <name>')
835
+ .description('Get details about an MCP server')
836
+ .action((name: string) => {
837
+ logEvent('tengu_mcp_get', { name })
838
+ const server = getMcpServer(name)
839
+ if (!server) {
840
+ console.error(`No MCP server found with name: ${name}`)
841
+ process.exit(1)
842
+ }
843
+ console.log(`${name}:`)
844
+ console.log(` Scope: ${server.scope}`)
845
+ if (server.type === 'sse') {
846
+ console.log(` Type: sse`)
847
+ console.log(` URL: ${server.url}`)
848
+ } else {
849
+ console.log(` Type: stdio`)
850
+ console.log(` Command: ${server.command}`)
851
+ console.log(` Args: ${server.args.join(' ')}`)
852
+ if (server.env) {
853
+ console.log(' Environment:')
854
+ for (const [key, value] of Object.entries(server.env)) {
855
+ console.log(` ${key}=${value}`)
856
+ }
857
+ }
858
+ }
859
+ process.exit(0)
860
+ })
861
+
862
+ // Import servers from Claude Desktop
863
+ mcp
864
+ .command('add-from-claude-desktop')
865
+ .description(
866
+ 'Import MCP servers from Claude Desktop (Mac, Windows and WSL)',
867
+ )
868
+ .option(
869
+ '-s, --scope <scope>',
870
+ 'Configuration scope (project or global)',
871
+ 'project',
872
+ )
873
+ .action(async options => {
874
+ try {
875
+ const scope = ensureConfigScope(options.scope)
876
+ const platform = process.platform
877
+
878
+ // Import fs and path modules
879
+ const { existsSync, readFileSync } = await import('fs')
880
+ const { join } = await import('path')
881
+ const { exec } = await import('child_process')
882
+
883
+ // Determine if running in WSL
884
+ const isWSL =
885
+ platform === 'linux' &&
886
+ existsSync('/proc/version') &&
887
+ readFileSync('/proc/version', 'utf-8')
888
+ .toLowerCase()
889
+ .includes('microsoft')
890
+
891
+ if (platform !== 'darwin' && platform !== 'win32' && !isWSL) {
892
+ console.error(
893
+ 'Error: This command is only supported on macOS, Windows, and WSL',
894
+ )
895
+ process.exit(1)
896
+ }
897
+
898
+ // Get Claude Desktop config path
899
+ let configPath
900
+ if (platform === 'darwin') {
901
+ configPath = join(
902
+ process.env.HOME || '~',
903
+ 'Library/Application Support/Claude/claude_desktop_config.json',
904
+ )
905
+ } else if (platform === 'win32') {
906
+ configPath = join(
907
+ process.env.APPDATA || '',
908
+ 'Claude/claude_desktop_config.json',
909
+ )
910
+ } else if (isWSL) {
911
+ // Get Windows username
912
+ const whoamiCommand = await new Promise<string>((resolve, reject) => {
913
+ exec(
914
+ 'powershell.exe -Command "whoami"',
915
+ (err: Error, stdout: string) => {
916
+ if (err) reject(err)
917
+ else resolve(stdout.trim().split('\\').pop() || '')
918
+ },
919
+ )
920
+ })
921
+
922
+ configPath = `/mnt/c/Users/${whoamiCommand}/AppData/Roaming/Claude/claude_desktop_config.json`
923
+ }
924
+
925
+ // Check if config file exists
926
+ if (!existsSync(configPath)) {
927
+ console.error(
928
+ `Error: Claude Desktop config file not found at ${configPath}`,
929
+ )
930
+ process.exit(1)
931
+ }
932
+
933
+ // Read config file
934
+ let config
935
+ try {
936
+ const configContent = readFileSync(configPath, 'utf-8')
937
+ config = JSON.parse(configContent)
938
+ } catch (err) {
939
+ console.error(`Error reading config file: ${err}`)
940
+ process.exit(1)
941
+ }
942
+
943
+ // Extract MCP servers
944
+ const mcpServers = config.mcpServers || {}
945
+ const serverNames = Object.keys(mcpServers)
946
+ const numServers = serverNames.length
947
+
948
+ if (numServers === 0) {
949
+ console.log('No MCP servers found in Claude Desktop config')
950
+ process.exit(0)
951
+ }
952
+
953
+ // Create server information for display
954
+ const serversInfo = serverNames.map(name => {
955
+ const server = mcpServers[name]
956
+ let description = ''
957
+
958
+ if (server.type === 'sse') {
959
+ description = `SSE: ${server.url}`
960
+ } else {
961
+ description = `stdio: ${server.command} ${(server.args || []).join(' ')}`
962
+ }
963
+
964
+ return { name, description, server }
965
+ })
966
+
967
+ // First import all required modules outside the component
968
+ // Import modules separately to avoid any issues
969
+ const ink = await import('ink')
970
+ const reactModule = await import('react')
971
+ const inkjsui = await import('@inkjs/ui')
972
+ const utilsTheme = await import('../utils/theme')
973
+
974
+ const { render } = ink
975
+ const React = reactModule // React is already the default export when imported this way
976
+ const { MultiSelect } = inkjsui
977
+ const { Box, Text } = ink
978
+ const { getTheme } = utilsTheme
979
+
980
+ // Use Ink to render a nice UI for selection
981
+ await new Promise<void>(resolve => {
982
+ // Create a component for the server selection
983
+ function ClaudeDesktopImport() {
984
+ const { useState } = reactModule
985
+ const [isFinished, setIsFinished] = useState(false)
986
+ const [importResults, setImportResults] = useState<
987
+ { name: string; success: boolean }[]
988
+ >([])
989
+ const [isImporting, setIsImporting] = useState(false)
990
+ const theme = getTheme()
991
+
992
+ // Function to import selected servers
993
+ const importServers = async (selectedServers: string[]) => {
994
+ setIsImporting(true)
995
+ const results = []
996
+
997
+ for (const name of selectedServers) {
998
+ try {
999
+ const server = mcpServers[name]
1000
+
1001
+ // Check if server already exists
1002
+ const existingServer = getMcpServer(name)
1003
+ if (existingServer) {
1004
+ // Skip duplicates - we'll handle them in the confirmation step
1005
+ continue
1006
+ }
1007
+
1008
+ addMcpServer(name, server as McpServerConfig, scope)
1009
+ results.push({ name, success: true })
1010
+ } catch (err) {
1011
+ results.push({ name, success: false })
1012
+ }
1013
+ }
1014
+
1015
+ setImportResults(results)
1016
+ setIsImporting(false)
1017
+ setIsFinished(true)
1018
+
1019
+ // Give time to show results
1020
+ setTimeout(() => {
1021
+ resolve()
1022
+ }, 1000)
1023
+ }
1024
+
1025
+ // Handle confirmation of selections
1026
+ const handleConfirm = async (selectedServers: string[]) => {
1027
+ // Check for existing servers and confirm overwrite
1028
+ const existingServers = selectedServers.filter(name =>
1029
+ getMcpServer(name),
1030
+ )
1031
+
1032
+ if (existingServers.length > 0) {
1033
+ // We'll just handle it directly since we have a simple UI
1034
+ const results = []
1035
+
1036
+ // Process non-existing servers first
1037
+ const newServers = selectedServers.filter(
1038
+ name => !getMcpServer(name),
1039
+ )
1040
+ for (const name of newServers) {
1041
+ try {
1042
+ const server = mcpServers[name]
1043
+ addMcpServer(name, server as McpServerConfig, scope)
1044
+ results.push({ name, success: true })
1045
+ } catch (err) {
1046
+ results.push({ name, success: false })
1047
+ }
1048
+ }
1049
+
1050
+ // Now handle existing servers by prompting for each one
1051
+ for (const name of existingServers) {
1052
+ try {
1053
+ const server = mcpServers[name]
1054
+ // Overwrite existing server - in a real interactive UI you'd prompt here
1055
+ addMcpServer(name, server as McpServerConfig, scope)
1056
+ results.push({ name, success: true })
1057
+ } catch (err) {
1058
+ results.push({ name, success: false })
1059
+ }
1060
+ }
1061
+
1062
+ setImportResults(results)
1063
+ setIsImporting(false)
1064
+ setIsFinished(true)
1065
+
1066
+ // Give time to show results before resolving
1067
+ setTimeout(() => {
1068
+ resolve()
1069
+ }, 1000)
1070
+ } else {
1071
+ // No existing servers, proceed with import
1072
+ await importServers(selectedServers)
1073
+ }
1074
+ }
1075
+
1076
+ return (
1077
+ <Box flexDirection="column" padding={1}>
1078
+ <Box
1079
+ flexDirection="column"
1080
+ borderStyle="round"
1081
+ borderColor={theme.claude}
1082
+ padding={1}
1083
+ width={'100%'}
1084
+ >
1085
+ <Text bold color={theme.claude}>
1086
+ Import MCP Servers from Claude Desktop
1087
+ </Text>
1088
+
1089
+ <Box marginY={1}>
1090
+ <Text>
1091
+ Found {numServers} MCP servers in Claude Desktop.
1092
+ </Text>
1093
+ </Box>
1094
+
1095
+ <Text>Please select the servers you want to import:</Text>
1096
+
1097
+ <Box marginTop={1}>
1098
+ <MultiSelect
1099
+ options={serverNames.map(name => ({
1100
+ label: name,
1101
+ value: name,
1102
+ }))}
1103
+ defaultValue={serverNames}
1104
+ onSubmit={handleConfirm}
1105
+ />
1106
+ </Box>
1107
+ </Box>
1108
+
1109
+ <Box marginTop={0} marginLeft={3}>
1110
+ <Text dimColor>
1111
+ Space to select · Enter to confirm · Esc to cancel
1112
+ </Text>
1113
+ </Box>
1114
+
1115
+ {isFinished && (
1116
+ <Box marginTop={1}>
1117
+ <Text color={theme.success}>
1118
+ Successfully imported{' '}
1119
+ {importResults.filter(r => r.success).length} MCP server
1120
+ to local config.
1121
+ </Text>
1122
+ </Box>
1123
+ )}
1124
+ </Box>
1125
+ )
1126
+ }
1127
+
1128
+ // Render the component
1129
+ const { unmount } = render(<ClaudeDesktopImport />)
1130
+
1131
+ // Clean up when done
1132
+ setTimeout(() => {
1133
+ unmount()
1134
+ resolve()
1135
+ }, 30000) // Timeout after 30 seconds as a fallback
1136
+ })
1137
+
1138
+ process.exit(0)
1139
+ } catch (error) {
1140
+ console.error(`Error: ${(error as Error).message}`)
1141
+ process.exit(1)
1142
+ }
1143
+ })
1144
+
1145
+ // Function to reset MCP server choices
1146
+ const resetMcpChoices = () => {
1147
+ const config = getCurrentProjectConfig()
1148
+ saveCurrentProjectConfig({
1149
+ ...config,
1150
+ approvedMcprcServers: [],
1151
+ rejectedMcprcServers: [],
1152
+ })
1153
+ console.log('All .mcprc server approvals and rejections have been reset.')
1154
+ console.log(
1155
+ `You will be prompted for approval next time you start ${PRODUCT_NAME}.`,
1156
+ )
1157
+ process.exit(0)
1158
+ }
1159
+
1160
+ // New command name to match Kode
1161
+ mcp
1162
+ .command('reset-project-choices')
1163
+ .description(
1164
+ 'Reset all approved and rejected project-scoped (.mcp.json) servers within this project',
1165
+ )
1166
+ .action(() => {
1167
+ logEvent('tengu_mcp_reset_project_choices', {})
1168
+ resetMcpChoices()
1169
+ })
1170
+
1171
+ // Keep old command for backward compatibility (visible only to ants)
1172
+ if (process.env.USER_TYPE === 'ant') {
1173
+ mcp
1174
+ .command('reset-mcprc-choices')
1175
+ .description(
1176
+ 'Reset all approved and rejected .mcprc servers for this project',
1177
+ )
1178
+ .action(() => {
1179
+ logEvent('tengu_mcp_reset_mcprc_choices', {})
1180
+ resetMcpChoices()
1181
+ })
1182
+ }
1183
+
1184
+ // Doctor command - check installation health
1185
+ program
1186
+ .command('doctor')
1187
+ .description(`Check the health of your ${PRODUCT_NAME} auto-updater`)
1188
+ .action(async () => {
1189
+ logEvent('tengu_doctor_command', {})
1190
+
1191
+ await new Promise<void>(resolve => {
1192
+ render(<Doctor onDone={() => resolve()} doctorMode={true} />)
1193
+ })
1194
+ process.exit(0)
1195
+ })
1196
+
1197
+ // ant-only commands
1198
+
1199
+ // claude update
1200
+ program
1201
+ .command('update')
1202
+ .description('Check for updates and install if available')
1203
+ .action(async () => {
1204
+ const useExternalUpdater = await checkGate(GATE_USE_EXTERNAL_UPDATER)
1205
+ if (useExternalUpdater) {
1206
+ // The external updater intercepts calls to "claude update", which means if we have received
1207
+ // this command at all, the extenral updater isn't installed on this machine.
1208
+ console.log(`This version of ${PRODUCT_NAME} is no longer supported.`)
1209
+ process.exit(0)
1210
+ }
1211
+
1212
+ logEvent('tengu_update_check', {})
1213
+ console.log(`Current version: ${MACRO.VERSION}`)
1214
+ console.log('Checking for updates...')
1215
+
1216
+ const latestVersion = await getLatestVersion()
1217
+
1218
+ if (!latestVersion) {
1219
+ console.error('Failed to check for updates')
1220
+ process.exit(1)
1221
+ }
1222
+
1223
+ if (latestVersion === MACRO.VERSION) {
1224
+ console.log(`${PRODUCT_NAME} is up to date`)
1225
+ process.exit(0)
1226
+ }
1227
+
1228
+ console.log(`New version available: ${latestVersion}`)
1229
+ console.log('Installing update...')
1230
+
1231
+ const status = await installGlobalPackage()
1232
+
1233
+ switch (status) {
1234
+ case 'success':
1235
+ console.log(`Successfully updated to version ${latestVersion}`)
1236
+ break
1237
+ case 'no_permissions':
1238
+ console.error('Error: Insufficient permissions to install update')
1239
+ console.error('Try running with sudo or fix npm permissions')
1240
+ process.exit(1)
1241
+ break
1242
+ case 'install_failed':
1243
+ console.error('Error: Failed to install update')
1244
+ process.exit(1)
1245
+ break
1246
+ case 'in_progress':
1247
+ console.error(
1248
+ 'Error: Another instance is currently performing an update',
1249
+ )
1250
+ console.error('Please wait and try again later')
1251
+ process.exit(1)
1252
+ break
1253
+ }
1254
+ process.exit(0)
1255
+ })
1256
+
1257
+ // claude log
1258
+ program
1259
+ .command('log')
1260
+ .description('Manage conversation logs.')
1261
+ .argument(
1262
+ '[number]',
1263
+ 'A number (0, 1, 2, etc.) to display a specific log',
1264
+ parseInt,
1265
+ )
1266
+ .option('-c, --cwd <cwd>', 'The current working directory', String, cwd())
1267
+ .action(async (number, { cwd }) => {
1268
+ await setup(cwd, false)
1269
+ logEvent('tengu_view_logs', { number: number?.toString() ?? '' })
1270
+ const context: { unmount?: () => void } = {}
1271
+ const { unmount } = render(
1272
+ <LogList context={context} type="messages" logNumber={number} />,
1273
+ renderContextWithExitOnCtrlC,
1274
+ )
1275
+ context.unmount = unmount
1276
+ })
1277
+
1278
+ // claude resume
1279
+ program
1280
+ .command('resume')
1281
+ .description(
1282
+ 'Resume a previous conversation. Optionally provide a number (0, 1, 2, etc.) or file path to resume a specific conversation.',
1283
+ )
1284
+ .argument(
1285
+ '[identifier]',
1286
+ 'A number (0, 1, 2, etc.) or file path to resume a specific conversation',
1287
+ )
1288
+ .option('-c, --cwd <cwd>', 'The current working directory', String, cwd())
1289
+ .option('-e, --enable-architect', 'Enable the Architect tool', () => true)
1290
+ .option('-v, --verbose', 'Do not truncate message output', () => true)
1291
+ .option(
1292
+ '--safe',
1293
+ 'Enable strict permission checking mode (default is permissive)',
1294
+ () => true,
1295
+ )
1296
+ .action(async (identifier, { cwd, enableArchitect, safe, verbose }) => {
1297
+ await setup(cwd, safe)
1298
+ assertMinVersion()
1299
+
1300
+ const [tools, commands, logs, mcpClients] = await Promise.all([
1301
+ getTools(
1302
+ enableArchitect ?? getCurrentProjectConfig().enableArchitectTool,
1303
+ ),
1304
+ getCommands(),
1305
+ loadLogList(CACHE_PATHS.messages()),
1306
+ getClients(),
1307
+ ])
1308
+ // logStartup()
1309
+
1310
+ // If a specific conversation is requested, load and resume it directly
1311
+ if (identifier !== undefined) {
1312
+ // Check if identifier is a number or a file path
1313
+ const number = Math.abs(parseInt(identifier))
1314
+ const isNumber = !isNaN(number)
1315
+ let messages, date, forkNumber
1316
+ try {
1317
+ if (isNumber) {
1318
+ logEvent('tengu_resume', { number: number.toString() })
1319
+ const log = logs[number]
1320
+ if (!log) {
1321
+ console.error('No conversation found at index', number)
1322
+ process.exit(1)
1323
+ }
1324
+ messages = await loadMessagesFromLog(log.fullPath, tools)
1325
+ ;({ date, forkNumber } = log)
1326
+ } else {
1327
+ // Handle file path case
1328
+ logEvent('tengu_resume', { filePath: identifier })
1329
+ if (!existsSync(identifier)) {
1330
+ console.error('File does not exist:', identifier)
1331
+ process.exit(1)
1332
+ }
1333
+ messages = await loadMessagesFromLog(identifier, tools)
1334
+ const pathSegments = identifier.split('/')
1335
+ const filename = pathSegments[pathSegments.length - 1] ?? 'unknown'
1336
+ ;({ date, forkNumber } = parseLogFilename(filename))
1337
+ }
1338
+ const fork = getNextAvailableLogForkNumber(date, forkNumber ?? 1, 0)
1339
+ const isDefaultModel = await isDefaultSlowAndCapableModel()
1340
+ render(
1341
+ <REPL
1342
+ initialPrompt=""
1343
+ messageLogName={date}
1344
+ initialForkNumber={fork}
1345
+ shouldShowPromptInput={true}
1346
+ verbose={verbose}
1347
+ commands={commands}
1348
+ tools={tools}
1349
+ safeMode={safe}
1350
+ initialMessages={messages}
1351
+ mcpClients={mcpClients}
1352
+ isDefaultModel={isDefaultModel}
1353
+ />,
1354
+ { exitOnCtrlC: false },
1355
+ )
1356
+ } catch (error) {
1357
+ logError(`Failed to load conversation: ${error}`)
1358
+ process.exit(1)
1359
+ }
1360
+ } else {
1361
+ // Show the conversation selector UI
1362
+ const context: { unmount?: () => void } = {}
1363
+ const { unmount } = render(
1364
+ <ResumeConversation
1365
+ context={context}
1366
+ commands={commands}
1367
+ logs={logs}
1368
+ tools={tools}
1369
+ verbose={verbose}
1370
+ />,
1371
+ renderContextWithExitOnCtrlC,
1372
+ )
1373
+ context.unmount = unmount
1374
+ }
1375
+ })
1376
+
1377
+ // claude error
1378
+ program
1379
+ .command('error')
1380
+ .description(
1381
+ 'View error logs. Optionally provide a number (0, -1, -2, etc.) to display a specific log.',
1382
+ )
1383
+ .argument(
1384
+ '[number]',
1385
+ 'A number (0, 1, 2, etc.) to display a specific log',
1386
+ parseInt,
1387
+ )
1388
+ .option('-c, --cwd <cwd>', 'The current working directory', String, cwd())
1389
+ .action(async (number, { cwd }) => {
1390
+ await setup(cwd, false)
1391
+ logEvent('tengu_view_errors', { number: number?.toString() ?? '' })
1392
+ const context: { unmount?: () => void } = {}
1393
+ const { unmount } = render(
1394
+ <LogList context={context} type="errors" logNumber={number} />,
1395
+ renderContextWithExitOnCtrlC,
1396
+ )
1397
+ context.unmount = unmount
1398
+ })
1399
+
1400
+ // claude context (TODO: deprecate)
1401
+ const context = program
1402
+ .command('context')
1403
+ .description(
1404
+ `Set static context (eg. ${PRODUCT_COMMAND} context add-file ./src/*.py)`,
1405
+ )
1406
+
1407
+ context
1408
+ .command('get <key>')
1409
+ .option('-c, --cwd <cwd>', 'The current working directory', String, cwd())
1410
+ .description('Get a value from context')
1411
+ .action(async (key, { cwd }) => {
1412
+ await setup(cwd, false)
1413
+ logEvent('tengu_context_get', { key })
1414
+ const context = omit(
1415
+ await getContext(),
1416
+ 'codeStyle',
1417
+ 'directoryStructure',
1418
+ )
1419
+ console.log(context[key])
1420
+ process.exit(0)
1421
+ })
1422
+
1423
+ context
1424
+ .command('set <key> <value>')
1425
+ .description('Set a value in context')
1426
+ .option('-c, --cwd <cwd>', 'The current working directory', String, cwd())
1427
+ .action(async (key, value, { cwd }) => {
1428
+ await setup(cwd, false)
1429
+ logEvent('tengu_context_set', { key })
1430
+ setContext(key, value)
1431
+ console.log(`Set context.${key} to "${value}"`)
1432
+ process.exit(0)
1433
+ })
1434
+
1435
+ context
1436
+ .command('list')
1437
+ .description('List all context values')
1438
+ .option('-c, --cwd <cwd>', 'The current working directory', String, cwd())
1439
+ .action(async ({ cwd }) => {
1440
+ await setup(cwd, false)
1441
+ logEvent('tengu_context_list', {})
1442
+ const context = omit(
1443
+ await getContext(),
1444
+ 'codeStyle',
1445
+ 'directoryStructure',
1446
+ 'gitStatus',
1447
+ )
1448
+ console.log(JSON.stringify(context, null, 2))
1449
+ process.exit(0)
1450
+ })
1451
+
1452
+ context
1453
+ .command('remove <key>')
1454
+ .description('Remove a value from context')
1455
+ .option('-c, --cwd <cwd>', 'The current working directory', String, cwd())
1456
+ .action(async (key, { cwd }) => {
1457
+ await setup(cwd, false)
1458
+ logEvent('tengu_context_delete', { key })
1459
+ removeContext(key)
1460
+ console.log(`Removed context.${key}`)
1461
+ process.exit(0)
1462
+ })
1463
+
1464
+ await program.parseAsync(process.argv)
1465
+ return program
1466
+ }
1467
+
1468
+ // TODO: stream?
1469
+ async function stdin() {
1470
+ if (process.stdin.isTTY) {
1471
+ return ''
1472
+ }
1473
+
1474
+ let data = ''
1475
+ for await (const chunk of process.stdin) data += chunk
1476
+ return data
1477
+ }
1478
+
1479
+ process.on('exit', () => {
1480
+ resetCursor()
1481
+ PersistentShell.getInstance().close()
1482
+ })
1483
+
1484
+ process.on('SIGINT', () => {
1485
+ console.log('SIGINT')
1486
+ process.exit(0)
1487
+ })
1488
+
1489
+ function resetCursor() {
1490
+ const terminal = process.stderr.isTTY
1491
+ ? process.stderr
1492
+ : process.stdout.isTTY
1493
+ ? process.stdout
1494
+ : undefined
1495
+ terminal?.write(`\u001B[?25h${cursorShow}`)
1496
+ }
1497
+
1498
+ main()