@shareai-lab/kode 1.0.69 → 1.0.71

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (253) hide show
  1. package/README.md +205 -72
  2. package/README.zh-CN.md +246 -0
  3. package/cli.js +62 -0
  4. package/package.json +45 -25
  5. package/scripts/postinstall.js +56 -0
  6. package/src/ProjectOnboarding.tsx +180 -0
  7. package/src/Tool.ts +53 -0
  8. package/src/commands/approvedTools.ts +53 -0
  9. package/src/commands/bug.tsx +20 -0
  10. package/src/commands/clear.ts +43 -0
  11. package/src/commands/compact.ts +120 -0
  12. package/src/commands/config.tsx +19 -0
  13. package/src/commands/cost.ts +18 -0
  14. package/src/commands/ctx_viz.ts +209 -0
  15. package/src/commands/doctor.ts +24 -0
  16. package/src/commands/help.tsx +19 -0
  17. package/src/commands/init.ts +37 -0
  18. package/src/commands/listen.ts +42 -0
  19. package/src/commands/login.tsx +51 -0
  20. package/src/commands/logout.tsx +40 -0
  21. package/src/commands/mcp.ts +41 -0
  22. package/src/commands/model.tsx +40 -0
  23. package/src/commands/modelstatus.tsx +20 -0
  24. package/src/commands/onboarding.tsx +34 -0
  25. package/src/commands/pr_comments.ts +59 -0
  26. package/src/commands/refreshCommands.ts +54 -0
  27. package/src/commands/release-notes.ts +34 -0
  28. package/src/commands/resume.tsx +30 -0
  29. package/src/commands/review.ts +49 -0
  30. package/src/commands/terminalSetup.ts +221 -0
  31. package/src/commands.ts +136 -0
  32. package/src/components/ApproveApiKey.tsx +93 -0
  33. package/src/components/AsciiLogo.tsx +13 -0
  34. package/src/components/AutoUpdater.tsx +148 -0
  35. package/src/components/Bug.tsx +367 -0
  36. package/src/components/Config.tsx +289 -0
  37. package/src/components/ConsoleOAuthFlow.tsx +326 -0
  38. package/src/components/Cost.tsx +23 -0
  39. package/src/components/CostThresholdDialog.tsx +46 -0
  40. package/src/components/CustomSelect/option-map.ts +42 -0
  41. package/src/components/CustomSelect/select-option.tsx +52 -0
  42. package/src/components/CustomSelect/select.tsx +143 -0
  43. package/src/components/CustomSelect/use-select-state.ts +414 -0
  44. package/src/components/CustomSelect/use-select.ts +35 -0
  45. package/src/components/FallbackToolUseRejectedMessage.tsx +15 -0
  46. package/src/components/FileEditToolUpdatedMessage.tsx +66 -0
  47. package/src/components/Help.tsx +215 -0
  48. package/src/components/HighlightedCode.tsx +33 -0
  49. package/src/components/InvalidConfigDialog.tsx +113 -0
  50. package/src/components/Link.tsx +32 -0
  51. package/src/components/LogSelector.tsx +86 -0
  52. package/src/components/Logo.tsx +145 -0
  53. package/src/components/MCPServerApprovalDialog.tsx +100 -0
  54. package/src/components/MCPServerDialogCopy.tsx +25 -0
  55. package/src/components/MCPServerMultiselectDialog.tsx +109 -0
  56. package/src/components/Message.tsx +219 -0
  57. package/src/components/MessageResponse.tsx +15 -0
  58. package/src/components/MessageSelector.tsx +211 -0
  59. package/src/components/ModeIndicator.tsx +88 -0
  60. package/src/components/ModelConfig.tsx +301 -0
  61. package/src/components/ModelListManager.tsx +223 -0
  62. package/src/components/ModelSelector.tsx +3208 -0
  63. package/src/components/ModelStatusDisplay.tsx +228 -0
  64. package/src/components/Onboarding.tsx +274 -0
  65. package/src/components/PressEnterToContinue.tsx +11 -0
  66. package/src/components/PromptInput.tsx +710 -0
  67. package/src/components/SentryErrorBoundary.ts +33 -0
  68. package/src/components/Spinner.tsx +129 -0
  69. package/src/components/StructuredDiff.tsx +184 -0
  70. package/src/components/TextInput.tsx +246 -0
  71. package/src/components/TokenWarning.tsx +31 -0
  72. package/src/components/ToolUseLoader.tsx +40 -0
  73. package/src/components/TrustDialog.tsx +106 -0
  74. package/src/components/binary-feedback/BinaryFeedback.tsx +63 -0
  75. package/src/components/binary-feedback/BinaryFeedbackOption.tsx +111 -0
  76. package/src/components/binary-feedback/BinaryFeedbackView.tsx +172 -0
  77. package/src/components/binary-feedback/utils.ts +220 -0
  78. package/src/components/messages/AssistantBashOutputMessage.tsx +22 -0
  79. package/src/components/messages/AssistantLocalCommandOutputMessage.tsx +45 -0
  80. package/src/components/messages/AssistantRedactedThinkingMessage.tsx +19 -0
  81. package/src/components/messages/AssistantTextMessage.tsx +144 -0
  82. package/src/components/messages/AssistantThinkingMessage.tsx +40 -0
  83. package/src/components/messages/AssistantToolUseMessage.tsx +123 -0
  84. package/src/components/messages/UserBashInputMessage.tsx +28 -0
  85. package/src/components/messages/UserCommandMessage.tsx +30 -0
  86. package/src/components/messages/UserKodingInputMessage.tsx +28 -0
  87. package/src/components/messages/UserPromptMessage.tsx +35 -0
  88. package/src/components/messages/UserTextMessage.tsx +39 -0
  89. package/src/components/messages/UserToolResultMessage/UserToolCanceledMessage.tsx +12 -0
  90. package/src/components/messages/UserToolResultMessage/UserToolErrorMessage.tsx +36 -0
  91. package/src/components/messages/UserToolResultMessage/UserToolRejectMessage.tsx +31 -0
  92. package/src/components/messages/UserToolResultMessage/UserToolResultMessage.tsx +57 -0
  93. package/src/components/messages/UserToolResultMessage/UserToolSuccessMessage.tsx +35 -0
  94. package/src/components/messages/UserToolResultMessage/utils.tsx +56 -0
  95. package/src/components/permissions/BashPermissionRequest/BashPermissionRequest.tsx +121 -0
  96. package/src/components/permissions/FallbackPermissionRequest.tsx +155 -0
  97. package/src/components/permissions/FileEditPermissionRequest/FileEditPermissionRequest.tsx +182 -0
  98. package/src/components/permissions/FileEditPermissionRequest/FileEditToolDiff.tsx +75 -0
  99. package/src/components/permissions/FileWritePermissionRequest/FileWritePermissionRequest.tsx +164 -0
  100. package/src/components/permissions/FileWritePermissionRequest/FileWriteToolDiff.tsx +81 -0
  101. package/src/components/permissions/FilesystemPermissionRequest/FilesystemPermissionRequest.tsx +242 -0
  102. package/src/components/permissions/PermissionRequest.tsx +103 -0
  103. package/src/components/permissions/PermissionRequestTitle.tsx +69 -0
  104. package/src/components/permissions/hooks.ts +44 -0
  105. package/src/components/permissions/toolUseOptions.ts +59 -0
  106. package/src/components/permissions/utils.ts +23 -0
  107. package/src/constants/betas.ts +5 -0
  108. package/src/constants/claude-asterisk-ascii-art.tsx +238 -0
  109. package/src/constants/figures.ts +4 -0
  110. package/src/constants/keys.ts +3 -0
  111. package/src/constants/macros.ts +6 -0
  112. package/src/constants/models.ts +935 -0
  113. package/src/constants/oauth.ts +18 -0
  114. package/src/constants/product.ts +17 -0
  115. package/src/constants/prompts.ts +177 -0
  116. package/src/constants/releaseNotes.ts +7 -0
  117. package/src/context/PermissionContext.tsx +149 -0
  118. package/src/context.ts +278 -0
  119. package/src/cost-tracker.ts +84 -0
  120. package/src/entrypoints/cli.tsx +1498 -0
  121. package/src/entrypoints/mcp.ts +176 -0
  122. package/src/history.ts +25 -0
  123. package/src/hooks/useApiKeyVerification.ts +59 -0
  124. package/src/hooks/useArrowKeyHistory.ts +55 -0
  125. package/src/hooks/useCanUseTool.ts +138 -0
  126. package/src/hooks/useCancelRequest.ts +39 -0
  127. package/src/hooks/useDoublePress.ts +42 -0
  128. package/src/hooks/useExitOnCtrlCD.ts +31 -0
  129. package/src/hooks/useInterval.ts +25 -0
  130. package/src/hooks/useLogMessages.ts +16 -0
  131. package/src/hooks/useLogStartupTime.ts +12 -0
  132. package/src/hooks/useNotifyAfterTimeout.ts +65 -0
  133. package/src/hooks/usePermissionRequestLogging.ts +44 -0
  134. package/src/hooks/useSlashCommandTypeahead.ts +137 -0
  135. package/src/hooks/useTerminalSize.ts +49 -0
  136. package/src/hooks/useTextInput.ts +315 -0
  137. package/src/messages.ts +37 -0
  138. package/src/permissions.ts +268 -0
  139. package/src/query.ts +704 -0
  140. package/src/screens/ConfigureNpmPrefix.tsx +197 -0
  141. package/src/screens/Doctor.tsx +219 -0
  142. package/src/screens/LogList.tsx +68 -0
  143. package/src/screens/REPL.tsx +792 -0
  144. package/src/screens/ResumeConversation.tsx +68 -0
  145. package/src/services/browserMocks.ts +66 -0
  146. package/src/services/claude.ts +1947 -0
  147. package/src/services/customCommands.ts +683 -0
  148. package/src/services/fileFreshness.ts +377 -0
  149. package/src/services/mcpClient.ts +564 -0
  150. package/src/services/mcpServerApproval.tsx +50 -0
  151. package/src/services/notifier.ts +40 -0
  152. package/src/services/oauth.ts +357 -0
  153. package/src/services/openai.ts +796 -0
  154. package/src/services/sentry.ts +3 -0
  155. package/src/services/statsig.ts +171 -0
  156. package/src/services/statsigStorage.ts +86 -0
  157. package/src/services/systemReminder.ts +406 -0
  158. package/src/services/vcr.ts +161 -0
  159. package/src/tools/ArchitectTool/ArchitectTool.tsx +122 -0
  160. package/src/tools/ArchitectTool/prompt.ts +15 -0
  161. package/src/tools/AskExpertModelTool/AskExpertModelTool.tsx +505 -0
  162. package/src/tools/BashTool/BashTool.tsx +270 -0
  163. package/src/tools/BashTool/BashToolResultMessage.tsx +38 -0
  164. package/src/tools/BashTool/OutputLine.tsx +48 -0
  165. package/src/tools/BashTool/prompt.ts +174 -0
  166. package/src/tools/BashTool/utils.ts +56 -0
  167. package/src/tools/FileEditTool/FileEditTool.tsx +316 -0
  168. package/src/tools/FileEditTool/prompt.ts +51 -0
  169. package/src/tools/FileEditTool/utils.ts +58 -0
  170. package/src/tools/FileReadTool/FileReadTool.tsx +371 -0
  171. package/src/tools/FileReadTool/prompt.ts +7 -0
  172. package/src/tools/FileWriteTool/FileWriteTool.tsx +297 -0
  173. package/src/tools/FileWriteTool/prompt.ts +10 -0
  174. package/src/tools/GlobTool/GlobTool.tsx +119 -0
  175. package/src/tools/GlobTool/prompt.ts +8 -0
  176. package/src/tools/GrepTool/GrepTool.tsx +147 -0
  177. package/src/tools/GrepTool/prompt.ts +11 -0
  178. package/src/tools/MCPTool/MCPTool.tsx +106 -0
  179. package/src/tools/MCPTool/prompt.ts +3 -0
  180. package/src/tools/MemoryReadTool/MemoryReadTool.tsx +127 -0
  181. package/src/tools/MemoryReadTool/prompt.ts +3 -0
  182. package/src/tools/MemoryWriteTool/MemoryWriteTool.tsx +89 -0
  183. package/src/tools/MemoryWriteTool/prompt.ts +3 -0
  184. package/src/tools/MultiEditTool/MultiEditTool.tsx +366 -0
  185. package/src/tools/MultiEditTool/prompt.ts +45 -0
  186. package/src/tools/NotebookEditTool/NotebookEditTool.tsx +298 -0
  187. package/src/tools/NotebookEditTool/prompt.ts +3 -0
  188. package/src/tools/NotebookReadTool/NotebookReadTool.tsx +266 -0
  189. package/src/tools/NotebookReadTool/prompt.ts +3 -0
  190. package/src/tools/StickerRequestTool/StickerRequestTool.tsx +93 -0
  191. package/src/tools/StickerRequestTool/prompt.ts +19 -0
  192. package/src/tools/TaskTool/TaskTool.tsx +382 -0
  193. package/src/tools/TaskTool/constants.ts +1 -0
  194. package/src/tools/TaskTool/prompt.ts +56 -0
  195. package/src/tools/ThinkTool/ThinkTool.tsx +56 -0
  196. package/src/tools/ThinkTool/prompt.ts +12 -0
  197. package/src/tools/TodoWriteTool/TodoWriteTool.tsx +289 -0
  198. package/src/tools/TodoWriteTool/prompt.ts +63 -0
  199. package/src/tools/lsTool/lsTool.tsx +269 -0
  200. package/src/tools/lsTool/prompt.ts +2 -0
  201. package/src/tools.ts +63 -0
  202. package/src/types/PermissionMode.ts +120 -0
  203. package/src/types/RequestContext.ts +72 -0
  204. package/src/utils/Cursor.ts +436 -0
  205. package/src/utils/PersistentShell.ts +373 -0
  206. package/src/utils/agentStorage.ts +97 -0
  207. package/src/utils/array.ts +3 -0
  208. package/src/utils/ask.tsx +98 -0
  209. package/src/utils/auth.ts +13 -0
  210. package/src/utils/autoCompactCore.ts +223 -0
  211. package/src/utils/autoUpdater.ts +318 -0
  212. package/src/utils/betas.ts +20 -0
  213. package/src/utils/browser.ts +14 -0
  214. package/src/utils/cleanup.ts +72 -0
  215. package/src/utils/commands.ts +261 -0
  216. package/src/utils/config.ts +771 -0
  217. package/src/utils/conversationRecovery.ts +54 -0
  218. package/src/utils/debugLogger.ts +1123 -0
  219. package/src/utils/diff.ts +42 -0
  220. package/src/utils/env.ts +57 -0
  221. package/src/utils/errors.ts +21 -0
  222. package/src/utils/exampleCommands.ts +108 -0
  223. package/src/utils/execFileNoThrow.ts +51 -0
  224. package/src/utils/expertChatStorage.ts +136 -0
  225. package/src/utils/file.ts +402 -0
  226. package/src/utils/fileRecoveryCore.ts +71 -0
  227. package/src/utils/format.tsx +44 -0
  228. package/src/utils/generators.ts +62 -0
  229. package/src/utils/git.ts +92 -0
  230. package/src/utils/globalLogger.ts +77 -0
  231. package/src/utils/http.ts +10 -0
  232. package/src/utils/imagePaste.ts +38 -0
  233. package/src/utils/json.ts +13 -0
  234. package/src/utils/log.ts +382 -0
  235. package/src/utils/markdown.ts +213 -0
  236. package/src/utils/messageContextManager.ts +289 -0
  237. package/src/utils/messages.tsx +938 -0
  238. package/src/utils/model.ts +836 -0
  239. package/src/utils/permissions/filesystem.ts +118 -0
  240. package/src/utils/ripgrep.ts +167 -0
  241. package/src/utils/sessionState.ts +49 -0
  242. package/src/utils/state.ts +25 -0
  243. package/src/utils/style.ts +29 -0
  244. package/src/utils/terminal.ts +49 -0
  245. package/src/utils/theme.ts +122 -0
  246. package/src/utils/thinking.ts +144 -0
  247. package/src/utils/todoStorage.ts +431 -0
  248. package/src/utils/tokens.ts +43 -0
  249. package/src/utils/toolExecutionController.ts +163 -0
  250. package/src/utils/unaryLogging.ts +26 -0
  251. package/src/utils/user.ts +37 -0
  252. package/src/utils/validate.ts +165 -0
  253. package/cli.mjs +0 -1803
@@ -0,0 +1,316 @@
1
+ import { Hunk } from 'diff'
2
+ import { existsSync, mkdirSync, readFileSync, statSync } from 'fs'
3
+ import { Box, Text } from 'ink'
4
+ import { dirname, isAbsolute, relative, resolve, sep } from 'path'
5
+ import * as React from 'react'
6
+ import { z } from 'zod'
7
+ import { FileEditToolUpdatedMessage } from '../../components/FileEditToolUpdatedMessage'
8
+ import { StructuredDiff } from '../../components/StructuredDiff'
9
+ import { logEvent } from '../../services/statsig'
10
+ import { Tool, ValidationResult } from '../../Tool'
11
+ import { intersperse } from '../../utils/array'
12
+ import {
13
+ addLineNumbers,
14
+ detectFileEncoding,
15
+ detectLineEndings,
16
+ findSimilarFile,
17
+ writeTextContent,
18
+ } from '../../utils/file.js'
19
+ import { logError } from '../../utils/log'
20
+ import { getCwd } from '../../utils/state'
21
+ import { getTheme } from '../../utils/theme'
22
+ import { emitReminderEvent } from '../../services/systemReminder'
23
+ import { recordFileEdit } from '../../services/fileFreshness'
24
+ import { NotebookEditTool } from '../NotebookEditTool/NotebookEditTool'
25
+ import { DESCRIPTION } from './prompt'
26
+ import { applyEdit } from './utils'
27
+ import { hasWritePermission } from '../../utils/permissions/filesystem'
28
+ import { PROJECT_FILE } from '../../constants/product'
29
+
30
+ const inputSchema = z.strictObject({
31
+ file_path: z.string().describe('The absolute path to the file to modify'),
32
+ old_string: z.string().describe('The text to replace'),
33
+ new_string: z.string().describe('The text to replace it with'),
34
+ })
35
+
36
+ export type In = typeof inputSchema
37
+
38
+ // Number of lines of context to include before/after the change in our result message
39
+ const N_LINES_SNIPPET = 4
40
+
41
+ export const FileEditTool = {
42
+ name: 'Edit',
43
+ async description() {
44
+ return 'A tool for editing files'
45
+ },
46
+ async prompt() {
47
+ return DESCRIPTION
48
+ },
49
+ inputSchema,
50
+ userFacingName({ old_string, new_string }) {
51
+ if (old_string === '') return 'Create'
52
+ if (new_string === '') return 'Delete'
53
+ return 'Update'
54
+ },
55
+ async isEnabled() {
56
+ return true
57
+ },
58
+ isReadOnly() {
59
+ return false
60
+ },
61
+ isConcurrencySafe() {
62
+ return false // FileEdit modifies files, not safe for concurrent execution
63
+ },
64
+ needsPermissions({ file_path }) {
65
+ return !hasWritePermission(file_path)
66
+ },
67
+ renderToolUseMessage(input, { verbose }) {
68
+ return `file_path: ${verbose ? input.file_path : relative(getCwd(), input.file_path)}`
69
+ },
70
+ renderToolResultMessage({ filePath, structuredPatch }, { verbose }) {
71
+ return (
72
+ <FileEditToolUpdatedMessage
73
+ filePath={filePath}
74
+ structuredPatch={structuredPatch}
75
+ verbose={verbose}
76
+ />
77
+ )
78
+ },
79
+ renderToolUseRejectedMessage(
80
+ { file_path, old_string, new_string },
81
+ { columns, verbose },
82
+ ) {
83
+ try {
84
+ const { patch } = applyEdit(file_path, old_string, new_string)
85
+ return (
86
+ <Box flexDirection="column">
87
+ <Text>
88
+ {' '}⎿{' '}
89
+ <Text color={getTheme().error}>
90
+ User rejected {old_string === '' ? 'write' : 'update'} to{' '}
91
+ </Text>
92
+ <Text bold>
93
+ {verbose ? file_path : relative(getCwd(), file_path)}
94
+ </Text>
95
+ </Text>
96
+ {intersperse(
97
+ patch.map(patch => (
98
+ <Box flexDirection="column" paddingLeft={5} key={patch.newStart}>
99
+ <StructuredDiff patch={patch} dim={true} width={columns - 12} />
100
+ </Box>
101
+ )),
102
+ i => (
103
+ <Box paddingLeft={5} key={`ellipsis-${i}`}>
104
+ <Text color={getTheme().secondaryText}>...</Text>
105
+ </Box>
106
+ ),
107
+ )}
108
+ </Box>
109
+ )
110
+ } catch (e) {
111
+ // Handle the case where while we were showing the diff, the user manually made the change.
112
+ // TODO: Find a way to show the diff in this case
113
+ logError(e)
114
+ return (
115
+ <Box flexDirection="column">
116
+ <Text>{' '}⎿ (No changes)</Text>
117
+ </Box>
118
+ )
119
+ }
120
+ },
121
+ async validateInput(
122
+ { file_path, old_string, new_string },
123
+ { readFileTimestamps },
124
+ ) {
125
+ if (old_string === new_string) {
126
+ return {
127
+ result: false,
128
+ message:
129
+ 'No changes to make: old_string and new_string are exactly the same.',
130
+ meta: {
131
+ old_string,
132
+ },
133
+ } as ValidationResult
134
+ }
135
+
136
+ const fullFilePath = isAbsolute(file_path)
137
+ ? file_path
138
+ : resolve(getCwd(), file_path)
139
+
140
+ if (existsSync(fullFilePath) && old_string === '') {
141
+ return {
142
+ result: false,
143
+ message: 'Cannot create new file - file already exists.',
144
+ }
145
+ }
146
+
147
+ if (!existsSync(fullFilePath) && old_string === '') {
148
+ return {
149
+ result: true,
150
+ }
151
+ }
152
+
153
+ if (!existsSync(fullFilePath)) {
154
+ // Try to find a similar file with a different extension
155
+ const similarFilename = findSimilarFile(fullFilePath)
156
+ let message = 'File does not exist.'
157
+
158
+ // If we found a similar file, suggest it to the assistant
159
+ if (similarFilename) {
160
+ message += ` Did you mean ${similarFilename}?`
161
+ }
162
+
163
+ return {
164
+ result: false,
165
+ message,
166
+ }
167
+ }
168
+
169
+ if (fullFilePath.endsWith('.ipynb')) {
170
+ return {
171
+ result: false,
172
+ message: `File is a Jupyter Notebook. Use the ${NotebookEditTool.name} to edit this file.`,
173
+ }
174
+ }
175
+
176
+ const readTimestamp = readFileTimestamps[fullFilePath]
177
+ if (!readTimestamp) {
178
+ return {
179
+ result: false,
180
+ message:
181
+ 'File has not been read yet. Read it first before writing to it.',
182
+ meta: {
183
+ isFilePathAbsolute: String(isAbsolute(file_path)),
184
+ },
185
+ }
186
+ }
187
+
188
+ // Check if file exists and get its last modified time
189
+ const stats = statSync(fullFilePath)
190
+ const lastWriteTime = stats.mtimeMs
191
+ if (lastWriteTime > readTimestamp) {
192
+ return {
193
+ result: false,
194
+ message:
195
+ 'File has been modified since read, either by the user or by a linter. Read it again before attempting to write it.',
196
+ }
197
+ }
198
+
199
+ const enc = detectFileEncoding(fullFilePath)
200
+ const file = readFileSync(fullFilePath, enc)
201
+ if (!file.includes(old_string)) {
202
+ return {
203
+ result: false,
204
+ message: `String to replace not found in file.`,
205
+ meta: {
206
+ isFilePathAbsolute: String(isAbsolute(file_path)),
207
+ },
208
+ }
209
+ }
210
+
211
+ const matches = file.split(old_string).length - 1
212
+ if (matches > 1) {
213
+ return {
214
+ result: false,
215
+ message: `Found ${matches} matches of the string to replace. For safety, this tool only supports replacing exactly one occurrence at a time. Add more lines of context to your edit and try again.`,
216
+ meta: {
217
+ isFilePathAbsolute: String(isAbsolute(file_path)),
218
+ },
219
+ }
220
+ }
221
+
222
+ return { result: true }
223
+ },
224
+ async *call({ file_path, old_string, new_string }, { readFileTimestamps }) {
225
+ const { patch, updatedFile } = applyEdit(file_path, old_string, new_string)
226
+
227
+ const fullFilePath = isAbsolute(file_path)
228
+ ? file_path
229
+ : resolve(getCwd(), file_path)
230
+ const dir = dirname(fullFilePath)
231
+ mkdirSync(dir, { recursive: true })
232
+ const enc = existsSync(fullFilePath)
233
+ ? detectFileEncoding(fullFilePath)
234
+ : 'utf8'
235
+ const endings = existsSync(fullFilePath)
236
+ ? detectLineEndings(fullFilePath)
237
+ : 'LF'
238
+ const originalFile = existsSync(fullFilePath)
239
+ ? readFileSync(fullFilePath, enc)
240
+ : ''
241
+ writeTextContent(fullFilePath, updatedFile, enc, endings)
242
+
243
+ // Record Agent edit operation for file freshness tracking
244
+ recordFileEdit(fullFilePath, updatedFile)
245
+
246
+ // Update read timestamp, to invalidate stale writes
247
+ readFileTimestamps[fullFilePath] = statSync(fullFilePath).mtimeMs
248
+
249
+ // Log when editing CLAUDE.md
250
+ if (fullFilePath.endsWith(`${sep}${PROJECT_FILE}`)) {
251
+ logEvent('tengu_write_claudemd', {})
252
+ }
253
+
254
+ // Emit file edited event for system reminders
255
+ emitReminderEvent('file:edited', {
256
+ filePath: fullFilePath,
257
+ oldString: old_string,
258
+ newString: new_string,
259
+ timestamp: Date.now(),
260
+ operation:
261
+ old_string === '' ? 'create' : new_string === '' ? 'delete' : 'update',
262
+ })
263
+
264
+ const data = {
265
+ filePath: file_path,
266
+ oldString: old_string,
267
+ newString: new_string,
268
+ originalFile,
269
+ structuredPatch: patch,
270
+ }
271
+ yield {
272
+ type: 'result',
273
+ data,
274
+ resultForAssistant: this.renderResultForAssistant(data),
275
+ }
276
+ },
277
+ renderResultForAssistant({ filePath, originalFile, oldString, newString }) {
278
+ const { snippet, startLine } = getSnippet(
279
+ originalFile || '',
280
+ oldString,
281
+ newString,
282
+ )
283
+ return `The file ${filePath} has been updated. Here's the result of running \`cat -n\` on a snippet of the edited file:
284
+ ${addLineNumbers({
285
+ content: snippet,
286
+ startLine,
287
+ })}`
288
+ },
289
+ } satisfies Tool<
290
+ typeof inputSchema,
291
+ {
292
+ filePath: string
293
+ oldString: string
294
+ newString: string
295
+ originalFile: string
296
+ structuredPatch: Hunk[]
297
+ }
298
+ >
299
+
300
+ export function getSnippet(
301
+ initialText: string,
302
+ oldStr: string,
303
+ newStr: string,
304
+ ): { snippet: string; startLine: number } {
305
+ const before = initialText.split(oldStr)[0] ?? ''
306
+ const replacementLine = before.split(/\r?\n/).length - 1
307
+ const newFileLines = initialText.replace(oldStr, newStr).split(/\r?\n/)
308
+ // Calculate the start and end line numbers for the snippet
309
+ const startLine = Math.max(0, replacementLine - N_LINES_SNIPPET)
310
+ const endLine =
311
+ replacementLine + N_LINES_SNIPPET + newStr.split(/\r?\n/).length
312
+ // Get snippet
313
+ const snippetLines = newFileLines.slice(startLine, endLine + 1)
314
+ const snippet = snippetLines.join('\n')
315
+ return { snippet, startLine: startLine + 1 }
316
+ }
@@ -0,0 +1,51 @@
1
+ import { NotebookEditTool } from '../NotebookEditTool/NotebookEditTool'
2
+
3
+ export const DESCRIPTION = `This is a tool for editing files. For moving or renaming files, you should generally use the Bash tool with the 'mv' command instead. For larger edits, use the Write tool to overwrite files. For Jupyter notebooks (.ipynb files), use the ${NotebookEditTool.name} instead.
4
+
5
+ Before using this tool:
6
+
7
+ 1. Use the View tool to understand the file's contents and context
8
+
9
+ 2. Verify the directory path is correct (only applicable when creating new files):
10
+ - Use the LS tool to verify the parent directory exists and is the correct location
11
+
12
+ To make a file edit, provide the following:
13
+ 1. file_path: The absolute path to the file to modify (must be absolute, not relative)
14
+ 2. old_string: The text to replace (must be unique within the file, and must match the file contents exactly, including all whitespace and indentation)
15
+ 3. new_string: The edited text to replace the old_string
16
+
17
+ The tool will replace ONE occurrence of old_string with new_string in the specified file.
18
+
19
+ CRITICAL REQUIREMENTS FOR USING THIS TOOL:
20
+
21
+ 1. UNIQUENESS: The old_string MUST uniquely identify the specific instance you want to change. This means:
22
+ - Include AT LEAST 3-5 lines of context BEFORE the change point
23
+ - Include AT LEAST 3-5 lines of context AFTER the change point
24
+ - Include all whitespace, indentation, and surrounding code exactly as it appears in the file
25
+
26
+ 2. SINGLE INSTANCE: This tool can only change ONE instance at a time. If you need to change multiple instances:
27
+ - Make separate calls to this tool for each instance
28
+ - Each call must uniquely identify its specific instance using extensive context
29
+
30
+ 3. VERIFICATION: Before using this tool:
31
+ - Check how many instances of the target text exist in the file
32
+ - If multiple instances exist, gather enough context to uniquely identify each one
33
+ - Plan separate tool calls for each instance
34
+
35
+ WARNING: If you do not follow these requirements:
36
+ - The tool will fail if old_string matches multiple locations
37
+ - The tool will fail if old_string doesn't match exactly (including whitespace)
38
+ - You may change the wrong instance if you don't include enough context
39
+
40
+ When making edits:
41
+ - Ensure the edit results in idiomatic, correct code
42
+ - Do not leave the code in a broken state
43
+ - Always use absolute file paths (starting with /)
44
+
45
+ If you want to create a new file, use:
46
+ - A new file path, including dir name if needed
47
+ - An empty old_string
48
+ - The new file's contents as new_string
49
+
50
+ Remember: when making multiple file edits in a row to the same file, you should prefer to send all edits in a single message with multiple calls to this tool, rather than multiple messages with a single call each.
51
+ `
@@ -0,0 +1,58 @@
1
+ import { isAbsolute, resolve } from 'path'
2
+ import { getCwd } from '../../utils/state'
3
+ import { readFileSync } from 'fs'
4
+ import { detectFileEncoding } from '../../utils/file'
5
+ import { type Hunk } from 'diff'
6
+ import { getPatch } from '../../utils/diff'
7
+
8
+ /**
9
+ * Applies an edit to a file and returns the patch and updated file.
10
+ * Does not write the file to disk.
11
+ */
12
+ export function applyEdit(
13
+ file_path: string,
14
+ old_string: string,
15
+ new_string: string,
16
+ ): { patch: Hunk[]; updatedFile: string } {
17
+ const fullFilePath = isAbsolute(file_path)
18
+ ? file_path
19
+ : resolve(getCwd(), file_path)
20
+
21
+ let originalFile
22
+ let updatedFile
23
+ if (old_string === '') {
24
+ // Create new file
25
+ originalFile = ''
26
+ updatedFile = new_string
27
+ } else {
28
+ // Edit existing file
29
+ const enc = detectFileEncoding(fullFilePath)
30
+ originalFile = readFileSync(fullFilePath, enc)
31
+ if (new_string === '') {
32
+ if (
33
+ !old_string.endsWith('\n') &&
34
+ originalFile.includes(old_string + '\n')
35
+ ) {
36
+ updatedFile = originalFile.replace(old_string + '\n', () => new_string)
37
+ } else {
38
+ updatedFile = originalFile.replace(old_string, () => new_string)
39
+ }
40
+ } else {
41
+ updatedFile = originalFile.replace(old_string, () => new_string)
42
+ }
43
+ if (updatedFile === originalFile) {
44
+ throw new Error(
45
+ 'Original and edited file match exactly. Failed to apply edit.',
46
+ )
47
+ }
48
+ }
49
+
50
+ const patch = getPatch({
51
+ filePath: file_path,
52
+ fileContents: originalFile,
53
+ oldStr: originalFile,
54
+ newStr: updatedFile,
55
+ })
56
+
57
+ return { patch, updatedFile }
58
+ }