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