@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
package/src/query.ts ADDED
@@ -0,0 +1,704 @@
1
+ import {
2
+ Message as APIAssistantMessage,
3
+ MessageParam,
4
+ ToolUseBlock,
5
+ } from '@anthropic-ai/sdk/resources/index.mjs'
6
+ import { UUID } from 'crypto'
7
+ import type { Tool, ToolUseContext } from './Tool'
8
+ import {
9
+ messagePairValidForBinaryFeedback,
10
+ shouldUseBinaryFeedback,
11
+ } from './components/binary-feedback/utils.js'
12
+ import { CanUseToolFn } from './hooks/useCanUseTool'
13
+ import {
14
+ formatSystemPromptWithContext,
15
+ queryLLM,
16
+ queryModel,
17
+ } from './services/claude.js'
18
+ import { emitReminderEvent } from './services/systemReminder'
19
+ import { logEvent } from './services/statsig'
20
+ import { all } from './utils/generators'
21
+ import { logError } from './utils/log'
22
+ import {
23
+ debug as debugLogger,
24
+ markPhase,
25
+ getCurrentRequest,
26
+ logUserFriendly,
27
+ } from './utils/debugLogger'
28
+ import { getModelManager } from './utils/model.js'
29
+ import {
30
+ createAssistantMessage,
31
+ createProgressMessage,
32
+ createToolResultStopMessage,
33
+ createUserMessage,
34
+ FullToolUseResult,
35
+ INTERRUPT_MESSAGE,
36
+ INTERRUPT_MESSAGE_FOR_TOOL_USE,
37
+ NormalizedMessage,
38
+ normalizeMessagesForAPI,
39
+ } from './utils/messages.js'
40
+ import { createToolExecutionController } from './utils/toolExecutionController'
41
+ import { BashTool } from './tools/BashTool/BashTool'
42
+ import { getCwd } from './utils/state'
43
+ import { checkAutoCompact } from './utils/autoCompactCore'
44
+
45
+ // Extended ToolUseContext for query functions
46
+ interface ExtendedToolUseContext extends ToolUseContext {
47
+ abortController: AbortController
48
+ options: {
49
+ commands: any[]
50
+ forkNumber: number
51
+ messageLogName: string
52
+ tools: Tool[]
53
+ verbose: boolean
54
+ safeMode: boolean
55
+ maxThinkingTokens: number
56
+ isKodingRequest?: boolean
57
+ model?: string | import('./utils/config').ModelPointerType
58
+ }
59
+ readFileTimestamps: { [filename: string]: number }
60
+ setToolJSX: (jsx: any) => void
61
+ requestId?: string
62
+ }
63
+
64
+ export type Response = { costUSD: number; response: string }
65
+ export type UserMessage = {
66
+ message: MessageParam
67
+ type: 'user'
68
+ uuid: UUID
69
+ toolUseResult?: FullToolUseResult
70
+ options?: {
71
+ isKodingRequest?: boolean
72
+ kodingContext?: string
73
+ }
74
+ }
75
+
76
+ export type AssistantMessage = {
77
+ costUSD: number
78
+ durationMs: number
79
+ message: APIAssistantMessage
80
+ type: 'assistant'
81
+ uuid: UUID
82
+ isApiErrorMessage?: boolean
83
+ }
84
+
85
+ export type BinaryFeedbackResult =
86
+ | { message: AssistantMessage | null; shouldSkipPermissionCheck: false }
87
+ | { message: AssistantMessage; shouldSkipPermissionCheck: true }
88
+
89
+ export type ProgressMessage = {
90
+ content: AssistantMessage
91
+ normalizedMessages: NormalizedMessage[]
92
+ siblingToolUseIDs: Set<string>
93
+ tools: Tool[]
94
+ toolUseID: string
95
+ type: 'progress'
96
+ uuid: UUID
97
+ }
98
+
99
+ // Each array item is either a single message or a message-and-response pair
100
+ export type Message = UserMessage | AssistantMessage | ProgressMessage
101
+
102
+ const MAX_TOOL_USE_CONCURRENCY = 10
103
+
104
+ // Returns a message if we got one, or `null` if the user cancelled
105
+ async function queryWithBinaryFeedback(
106
+ toolUseContext: ExtendedToolUseContext,
107
+ getAssistantResponse: () => Promise<AssistantMessage>,
108
+ getBinaryFeedbackResponse?: (
109
+ m1: AssistantMessage,
110
+ m2: AssistantMessage,
111
+ ) => Promise<BinaryFeedbackResult>,
112
+ ): Promise<BinaryFeedbackResult> {
113
+ if (
114
+ process.env.USER_TYPE !== 'ant' ||
115
+ !getBinaryFeedbackResponse ||
116
+ !(await shouldUseBinaryFeedback())
117
+ ) {
118
+ const assistantMessage = await getAssistantResponse()
119
+ if (toolUseContext.abortController.signal.aborted) {
120
+ return { message: null, shouldSkipPermissionCheck: false }
121
+ }
122
+ return { message: assistantMessage, shouldSkipPermissionCheck: false }
123
+ }
124
+ const [m1, m2] = await Promise.all([
125
+ getAssistantResponse(),
126
+ getAssistantResponse(),
127
+ ])
128
+ if (toolUseContext.abortController.signal.aborted) {
129
+ return { message: null, shouldSkipPermissionCheck: false }
130
+ }
131
+ if (m2.isApiErrorMessage) {
132
+ // If m2 is an error, we might as well return m1, even if it's also an error --
133
+ // the UI will display it as an error as it would in the non-feedback path.
134
+ return { message: m1, shouldSkipPermissionCheck: false }
135
+ }
136
+ if (m1.isApiErrorMessage) {
137
+ return { message: m2, shouldSkipPermissionCheck: false }
138
+ }
139
+ if (!messagePairValidForBinaryFeedback(m1, m2)) {
140
+ return { message: m1, shouldSkipPermissionCheck: false }
141
+ }
142
+ return await getBinaryFeedbackResponse(m1, m2)
143
+ }
144
+
145
+ /**
146
+ * The rules of thinking are lengthy and fortuitous. They require plenty of thinking
147
+ * of most long duration and deep meditation for a wizard to wrap one's noggin around.
148
+ *
149
+ * The rules follow:
150
+ * 1. A message that contains a thinking or redacted_thinking block must be part of a query whose max_thinking_length > 0
151
+ * 2. A thinking block may not be the last message in a block
152
+ * 3. Thinking blocks must be preserved for the duration of an assistant trajectory (a single turn, or if that turn includes a tool_use block then also its subsequent tool_result and the following assistant message)
153
+ *
154
+ * Heed these rules well, young wizard. For they are the rules of thinking, and
155
+ * the rules of thinking are the rules of the universe. If ye does not heed these
156
+ * rules, ye will be punished with an entire day of debugging and hair pulling.
157
+ */
158
+ export async function* query(
159
+ messages: Message[],
160
+ systemPrompt: string[],
161
+ context: { [k: string]: string },
162
+ canUseTool: CanUseToolFn,
163
+ toolUseContext: ExtendedToolUseContext,
164
+ getBinaryFeedbackResponse?: (
165
+ m1: AssistantMessage,
166
+ m2: AssistantMessage,
167
+ ) => Promise<BinaryFeedbackResult>,
168
+ ): AsyncGenerator<Message, void> {
169
+ const currentRequest = getCurrentRequest()
170
+
171
+ markPhase('QUERY_INIT')
172
+
173
+ // Auto-compact check
174
+ const { messages: processedMessages, wasCompacted } = await checkAutoCompact(
175
+ messages,
176
+ toolUseContext,
177
+ )
178
+ if (wasCompacted) {
179
+ messages = processedMessages
180
+ }
181
+
182
+ markPhase('SYSTEM_PROMPT_BUILD')
183
+
184
+ const { systemPrompt: fullSystemPrompt, reminders } =
185
+ formatSystemPromptWithContext(systemPrompt, context, toolUseContext.agentId)
186
+
187
+ // Emit session startup event
188
+ emitReminderEvent('session:startup', {
189
+ agentId: toolUseContext.agentId,
190
+ messages: messages.length,
191
+ timestamp: Date.now(),
192
+ })
193
+
194
+ // Inject reminders into the latest user message
195
+ if (reminders && messages.length > 0) {
196
+ // Find the last user message
197
+ for (let i = messages.length - 1; i >= 0; i--) {
198
+ if (messages[i]?.type === 'user') {
199
+ const lastUserMessage = messages[i]
200
+ messages[i] = {
201
+ ...lastUserMessage,
202
+ message: {
203
+ ...lastUserMessage.message,
204
+ content:
205
+ typeof lastUserMessage.message.content === 'string'
206
+ ? reminders + lastUserMessage.message.content
207
+ : [
208
+ { type: 'text', text: reminders },
209
+ ...(Array.isArray(lastUserMessage.message.content)
210
+ ? lastUserMessage.message.content
211
+ : []),
212
+ ],
213
+ },
214
+ }
215
+ break
216
+ }
217
+ }
218
+ }
219
+
220
+ markPhase('LLM_PREPARATION')
221
+
222
+ function getAssistantResponse() {
223
+ return queryLLM(
224
+ normalizeMessagesForAPI(messages),
225
+ fullSystemPrompt,
226
+ toolUseContext.options.maxThinkingTokens,
227
+ toolUseContext.options.tools,
228
+ toolUseContext.abortController.signal,
229
+ {
230
+ safeMode: toolUseContext.options.safeMode ?? false,
231
+ model: toolUseContext.options.model || 'main',
232
+ prependCLISysprompt: true,
233
+ },
234
+ )
235
+ }
236
+
237
+ const result = await queryWithBinaryFeedback(
238
+ toolUseContext,
239
+ getAssistantResponse,
240
+ getBinaryFeedbackResponse,
241
+ )
242
+
243
+ // If request was cancelled, return immediately with interrupt message
244
+ if (toolUseContext.abortController.signal.aborted) {
245
+ yield createAssistantMessage(INTERRUPT_MESSAGE)
246
+ return
247
+ }
248
+
249
+ if (result.message === null) {
250
+ yield createAssistantMessage(INTERRUPT_MESSAGE)
251
+ return
252
+ }
253
+
254
+ const assistantMessage = result.message
255
+ const shouldSkipPermissionCheck = result.shouldSkipPermissionCheck
256
+
257
+ yield assistantMessage
258
+
259
+ // @see https://docs.anthropic.com/en/docs/build-with-claude/tool-use
260
+ // Note: stop_reason === 'tool_use' is unreliable -- it's not always set correctly
261
+ const toolUseMessages = assistantMessage.message.content.filter(
262
+ _ => _.type === 'tool_use',
263
+ )
264
+
265
+ // If there's no more tool use, we're done
266
+ if (!toolUseMessages.length) {
267
+ return
268
+ }
269
+
270
+ const toolResults: UserMessage[] = []
271
+
272
+ // Simple concurrency check like original system
273
+ const canRunConcurrently = toolUseMessages.every(msg =>
274
+ toolUseContext.options.tools.find(t => t.name === msg.name)?.isReadOnly(),
275
+ )
276
+
277
+ if (canRunConcurrently) {
278
+ for await (const message of runToolsConcurrently(
279
+ toolUseMessages,
280
+ assistantMessage,
281
+ canUseTool,
282
+ toolUseContext,
283
+ shouldSkipPermissionCheck,
284
+ )) {
285
+ yield message
286
+ // progress messages are not sent to the server, so don't need to be accumulated for the next turn
287
+ if (message.type === 'user') {
288
+ toolResults.push(message)
289
+ }
290
+ }
291
+ } else {
292
+ for await (const message of runToolsSerially(
293
+ toolUseMessages,
294
+ assistantMessage,
295
+ canUseTool,
296
+ toolUseContext,
297
+ shouldSkipPermissionCheck,
298
+ )) {
299
+ yield message
300
+ // progress messages are not sent to the server, so don't need to be accumulated for the next turn
301
+ if (message.type === 'user') {
302
+ toolResults.push(message)
303
+ }
304
+ }
305
+ }
306
+
307
+ if (toolUseContext.abortController.signal.aborted) {
308
+ yield createAssistantMessage(INTERRUPT_MESSAGE_FOR_TOOL_USE)
309
+ return
310
+ }
311
+
312
+ // Sort toolResults to match the order of toolUseMessages
313
+ const orderedToolResults = toolResults.sort((a, b) => {
314
+ const aIndex = toolUseMessages.findIndex(
315
+ tu => tu.id === (a.message.content[0] as ToolUseBlock).id,
316
+ )
317
+ const bIndex = toolUseMessages.findIndex(
318
+ tu => tu.id === (b.message.content[0] as ToolUseBlock).id,
319
+ )
320
+ return aIndex - bIndex
321
+ })
322
+
323
+ // Recursive query
324
+
325
+ try {
326
+ yield* await query(
327
+ [...messages, assistantMessage, ...orderedToolResults],
328
+ systemPrompt,
329
+ context,
330
+ canUseTool,
331
+ toolUseContext,
332
+ getBinaryFeedbackResponse,
333
+ )
334
+ } catch (error) {
335
+ // Re-throw the error to maintain the original behavior
336
+ throw error
337
+ }
338
+ }
339
+
340
+ async function* runToolsConcurrently(
341
+ toolUseMessages: ToolUseBlock[],
342
+ assistantMessage: AssistantMessage,
343
+ canUseTool: CanUseToolFn,
344
+ toolUseContext: ExtendedToolUseContext,
345
+ shouldSkipPermissionCheck?: boolean,
346
+ ): AsyncGenerator<Message, void> {
347
+ yield* all(
348
+ toolUseMessages.map(toolUse =>
349
+ runToolUse(
350
+ toolUse,
351
+ new Set(toolUseMessages.map(_ => _.id)),
352
+ assistantMessage,
353
+ canUseTool,
354
+ toolUseContext,
355
+ shouldSkipPermissionCheck,
356
+ ),
357
+ ),
358
+ MAX_TOOL_USE_CONCURRENCY,
359
+ )
360
+ }
361
+
362
+ async function* runToolsSerially(
363
+ toolUseMessages: ToolUseBlock[],
364
+ assistantMessage: AssistantMessage,
365
+ canUseTool: CanUseToolFn,
366
+ toolUseContext: ExtendedToolUseContext,
367
+ shouldSkipPermissionCheck?: boolean,
368
+ ): AsyncGenerator<Message, void> {
369
+ for (const toolUse of toolUseMessages) {
370
+ yield* runToolUse(
371
+ toolUse,
372
+ new Set(toolUseMessages.map(_ => _.id)),
373
+ assistantMessage,
374
+ canUseTool,
375
+ toolUseContext,
376
+ shouldSkipPermissionCheck,
377
+ )
378
+ }
379
+ }
380
+
381
+ export async function* runToolUse(
382
+ toolUse: ToolUseBlock,
383
+ siblingToolUseIDs: Set<string>,
384
+ assistantMessage: AssistantMessage,
385
+ canUseTool: CanUseToolFn,
386
+ toolUseContext: ExtendedToolUseContext,
387
+ shouldSkipPermissionCheck?: boolean,
388
+ ): AsyncGenerator<Message, void> {
389
+ const currentRequest = getCurrentRequest()
390
+
391
+ // 🔍 Debug: 工具调用开始
392
+ debugLogger.flow('TOOL_USE_START', {
393
+ toolName: toolUse.name,
394
+ toolUseID: toolUse.id,
395
+ inputSize: JSON.stringify(toolUse.input).length,
396
+ siblingToolCount: siblingToolUseIDs.size,
397
+ shouldSkipPermissionCheck: !!shouldSkipPermissionCheck,
398
+ requestId: currentRequest?.id,
399
+ })
400
+
401
+ logUserFriendly(
402
+ 'TOOL_EXECUTION',
403
+ {
404
+ toolName: toolUse.name,
405
+ action: 'Starting',
406
+ target: toolUse.input ? Object.keys(toolUse.input).join(', ') : '',
407
+ },
408
+ currentRequest?.id,
409
+ )
410
+
411
+ logEvent('tengu_tool_use_start', {
412
+ toolName: toolUse.name,
413
+ toolUseID: toolUse.id,
414
+ })
415
+
416
+ const toolName = toolUse.name
417
+ const tool = toolUseContext.options.tools.find(t => t.name === toolName)
418
+
419
+ // Check if the tool exists
420
+ if (!tool) {
421
+ debugLogger.error('TOOL_NOT_FOUND', {
422
+ requestedTool: toolName,
423
+ availableTools: toolUseContext.options.tools.map(t => t.name),
424
+ toolUseID: toolUse.id,
425
+ requestId: currentRequest?.id,
426
+ })
427
+
428
+ logEvent('tengu_tool_use_error', {
429
+ error: `No such tool available: ${toolName}`,
430
+ messageID: assistantMessage.message.id,
431
+ toolName,
432
+ toolUseID: toolUse.id,
433
+ })
434
+
435
+ yield createUserMessage([
436
+ {
437
+ type: 'tool_result',
438
+ content: `Error: No such tool available: ${toolName}`,
439
+ is_error: true,
440
+ tool_use_id: toolUse.id,
441
+ },
442
+ ])
443
+ return
444
+ }
445
+
446
+ const toolInput = toolUse.input as { [key: string]: string }
447
+
448
+ debugLogger.flow('TOOL_VALIDATION_START', {
449
+ toolName: tool.name,
450
+ toolUseID: toolUse.id,
451
+ inputKeys: Object.keys(toolInput),
452
+ requestId: currentRequest?.id,
453
+ })
454
+
455
+ try {
456
+ // 🔧 Check for cancellation before starting tool execution
457
+ if (toolUseContext.abortController.signal.aborted) {
458
+ debugLogger.flow('TOOL_USE_CANCELLED_BEFORE_START', {
459
+ toolName: tool.name,
460
+ toolUseID: toolUse.id,
461
+ abortReason: 'AbortController signal',
462
+ requestId: currentRequest?.id,
463
+ })
464
+
465
+ logEvent('tengu_tool_use_cancelled', {
466
+ toolName: tool.name,
467
+ toolUseID: toolUse.id,
468
+ })
469
+
470
+ const message = createUserMessage([
471
+ createToolResultStopMessage(toolUse.id),
472
+ ])
473
+ yield message
474
+ return
475
+ }
476
+
477
+ // Track if any progress messages were yielded
478
+ let hasProgressMessages = false
479
+
480
+ for await (const message of checkPermissionsAndCallTool(
481
+ tool,
482
+ toolUse.id,
483
+ siblingToolUseIDs,
484
+ toolInput,
485
+ toolUseContext,
486
+ canUseTool,
487
+ assistantMessage,
488
+ shouldSkipPermissionCheck,
489
+ )) {
490
+ // 🔧 Check for cancellation during tool execution
491
+ if (toolUseContext.abortController.signal.aborted) {
492
+ debugLogger.flow('TOOL_USE_CANCELLED_DURING_EXECUTION', {
493
+ toolName: tool.name,
494
+ toolUseID: toolUse.id,
495
+ hasProgressMessages,
496
+ abortReason: 'AbortController signal during execution',
497
+ requestId: currentRequest?.id,
498
+ })
499
+
500
+ // If we yielded progress messages but got cancelled, yield a cancellation result
501
+ if (hasProgressMessages && message.type === 'progress') {
502
+ yield message // yield the last progress message first
503
+ }
504
+
505
+ // Always yield a tool result message for cancellation to clear UI state
506
+ const cancelMessage = createUserMessage([
507
+ createToolResultStopMessage(toolUse.id),
508
+ ])
509
+ yield cancelMessage
510
+ return
511
+ }
512
+
513
+ if (message.type === 'progress') {
514
+ hasProgressMessages = true
515
+ }
516
+
517
+ yield message
518
+ }
519
+ } catch (e) {
520
+ logError(e)
521
+
522
+ // 🔧 Even on error, ensure we yield a tool result to clear UI state
523
+ const errorMessage = createUserMessage([
524
+ {
525
+ type: 'tool_result',
526
+ content: `Tool execution failed: ${e instanceof Error ? e.message : String(e)}`,
527
+ is_error: true,
528
+ tool_use_id: toolUse.id,
529
+ },
530
+ ])
531
+ yield errorMessage
532
+ }
533
+ }
534
+
535
+ // TODO: Generalize this to all tools
536
+ export function normalizeToolInput(
537
+ tool: Tool,
538
+ input: { [key: string]: boolean | string | number },
539
+ ): { [key: string]: boolean | string | number } {
540
+ switch (tool) {
541
+ case BashTool: {
542
+ const { command, timeout } = BashTool.inputSchema.parse(input) // already validated upstream, won't throw
543
+ return {
544
+ command: command.replace(`cd ${getCwd()} && `, ''),
545
+ ...(timeout ? { timeout } : {}),
546
+ }
547
+ }
548
+ default:
549
+ return input
550
+ }
551
+ }
552
+
553
+ async function* checkPermissionsAndCallTool(
554
+ tool: Tool,
555
+ toolUseID: string,
556
+ siblingToolUseIDs: Set<string>,
557
+ input: { [key: string]: boolean | string | number },
558
+ context: ToolUseContext,
559
+ canUseTool: CanUseToolFn,
560
+ assistantMessage: AssistantMessage,
561
+ shouldSkipPermissionCheck?: boolean,
562
+ ): AsyncGenerator<UserMessage | ProgressMessage, void> {
563
+ // Validate input types with zod
564
+ // (surprisingly, the model is not great at generating valid input)
565
+ const isValidInput = tool.inputSchema.safeParse(input)
566
+ if (!isValidInput.success) {
567
+ logEvent('tengu_tool_use_error', {
568
+ error: `InputValidationError: ${isValidInput.error.message}`,
569
+ messageID: assistantMessage.message.id,
570
+ toolName: tool.name,
571
+ toolInput: JSON.stringify(input).slice(0, 200),
572
+ })
573
+ yield createUserMessage([
574
+ {
575
+ type: 'tool_result',
576
+ content: `InputValidationError: ${isValidInput.error.message}`,
577
+ is_error: true,
578
+ tool_use_id: toolUseID,
579
+ },
580
+ ])
581
+ return
582
+ }
583
+
584
+ const normalizedInput = normalizeToolInput(tool, input)
585
+
586
+ // Validate input values. Each tool has its own validation logic
587
+ const isValidCall = await tool.validateInput?.(
588
+ normalizedInput as never,
589
+ context,
590
+ )
591
+ if (isValidCall?.result === false) {
592
+ logEvent('tengu_tool_use_error', {
593
+ error: isValidCall?.message.slice(0, 2000),
594
+ messageID: assistantMessage.message.id,
595
+ toolName: tool.name,
596
+ toolInput: JSON.stringify(input).slice(0, 200),
597
+ ...(isValidCall?.meta ?? {}),
598
+ })
599
+ yield createUserMessage([
600
+ {
601
+ type: 'tool_result',
602
+ content: isValidCall!.message,
603
+ is_error: true,
604
+ tool_use_id: toolUseID,
605
+ },
606
+ ])
607
+ return
608
+ }
609
+
610
+ // Check whether we have permission to use the tool,
611
+ // and ask the user for permission if we don't
612
+ const permissionResult = shouldSkipPermissionCheck
613
+ ? ({ result: true } as const)
614
+ : await canUseTool(tool, normalizedInput, context, assistantMessage)
615
+ if (permissionResult.result === false) {
616
+ yield createUserMessage([
617
+ {
618
+ type: 'tool_result',
619
+ content: permissionResult.message,
620
+ is_error: true,
621
+ tool_use_id: toolUseID,
622
+ },
623
+ ])
624
+ return
625
+ }
626
+
627
+ // Call the tool
628
+ try {
629
+ const generator = tool.call(normalizedInput as never, context, canUseTool)
630
+ for await (const result of generator) {
631
+ switch (result.type) {
632
+ case 'result':
633
+ logEvent('tengu_tool_use_success', {
634
+ messageID: assistantMessage.message.id,
635
+ toolName: tool.name,
636
+ })
637
+ yield createUserMessage(
638
+ [
639
+ {
640
+ type: 'tool_result',
641
+ content: result.resultForAssistant,
642
+ tool_use_id: toolUseID,
643
+ },
644
+ ],
645
+ {
646
+ data: result.data,
647
+ resultForAssistant: result.resultForAssistant,
648
+ },
649
+ )
650
+ return
651
+ case 'progress':
652
+ logEvent('tengu_tool_use_progress', {
653
+ messageID: assistantMessage.message.id,
654
+ toolName: tool.name,
655
+ })
656
+ yield createProgressMessage(
657
+ toolUseID,
658
+ siblingToolUseIDs,
659
+ result.content,
660
+ result.normalizedMessages,
661
+ result.tools,
662
+ )
663
+ }
664
+ }
665
+ } catch (error) {
666
+ const content = formatError(error)
667
+ logError(error)
668
+ logEvent('tengu_tool_use_error', {
669
+ error: content.slice(0, 2000),
670
+ messageID: assistantMessage.message.id,
671
+ toolName: tool.name,
672
+ toolInput: JSON.stringify(input).slice(0, 1000),
673
+ })
674
+ yield createUserMessage([
675
+ {
676
+ type: 'tool_result',
677
+ content,
678
+ is_error: true,
679
+ tool_use_id: toolUseID,
680
+ },
681
+ ])
682
+ }
683
+ }
684
+
685
+ function formatError(error: unknown): string {
686
+ if (!(error instanceof Error)) {
687
+ return String(error)
688
+ }
689
+ const parts = [error.message]
690
+ if ('stderr' in error && typeof error.stderr === 'string') {
691
+ parts.push(error.stderr)
692
+ }
693
+ if ('stdout' in error && typeof error.stdout === 'string') {
694
+ parts.push(error.stdout)
695
+ }
696
+ const fullMessage = parts.filter(Boolean).join('\n')
697
+ if (fullMessage.length <= 10000) {
698
+ return fullMessage
699
+ }
700
+ const halfLength = 5000
701
+ const start = fullMessage.slice(0, halfLength)
702
+ const end = fullMessage.slice(-halfLength)
703
+ return `${start}\n\n... [${fullMessage.length - 10000} characters truncated] ...\n\n${end}`
704
+ }