aider-ce 0.87.2.dev9__py3-none-any.whl

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.

Potentially problematic release.


This version of aider-ce might be problematic. Click here for more details.

Files changed (264) hide show
  1. aider/__init__.py +20 -0
  2. aider/__main__.py +4 -0
  3. aider/_version.py +34 -0
  4. aider/analytics.py +258 -0
  5. aider/args.py +1014 -0
  6. aider/args_formatter.py +228 -0
  7. aider/change_tracker.py +133 -0
  8. aider/coders/__init__.py +36 -0
  9. aider/coders/architect_coder.py +48 -0
  10. aider/coders/architect_prompts.py +40 -0
  11. aider/coders/ask_coder.py +9 -0
  12. aider/coders/ask_prompts.py +35 -0
  13. aider/coders/base_coder.py +3013 -0
  14. aider/coders/base_prompts.py +87 -0
  15. aider/coders/chat_chunks.py +64 -0
  16. aider/coders/context_coder.py +53 -0
  17. aider/coders/context_prompts.py +75 -0
  18. aider/coders/editblock_coder.py +657 -0
  19. aider/coders/editblock_fenced_coder.py +10 -0
  20. aider/coders/editblock_fenced_prompts.py +143 -0
  21. aider/coders/editblock_func_coder.py +141 -0
  22. aider/coders/editblock_func_prompts.py +27 -0
  23. aider/coders/editblock_prompts.py +177 -0
  24. aider/coders/editor_diff_fenced_coder.py +9 -0
  25. aider/coders/editor_diff_fenced_prompts.py +11 -0
  26. aider/coders/editor_editblock_coder.py +9 -0
  27. aider/coders/editor_editblock_prompts.py +21 -0
  28. aider/coders/editor_whole_coder.py +9 -0
  29. aider/coders/editor_whole_prompts.py +12 -0
  30. aider/coders/help_coder.py +16 -0
  31. aider/coders/help_prompts.py +46 -0
  32. aider/coders/navigator_coder.py +2711 -0
  33. aider/coders/navigator_legacy_prompts.py +338 -0
  34. aider/coders/navigator_prompts.py +530 -0
  35. aider/coders/patch_coder.py +706 -0
  36. aider/coders/patch_prompts.py +161 -0
  37. aider/coders/search_replace.py +757 -0
  38. aider/coders/shell.py +37 -0
  39. aider/coders/single_wholefile_func_coder.py +102 -0
  40. aider/coders/single_wholefile_func_prompts.py +27 -0
  41. aider/coders/udiff_coder.py +429 -0
  42. aider/coders/udiff_prompts.py +117 -0
  43. aider/coders/udiff_simple.py +14 -0
  44. aider/coders/udiff_simple_prompts.py +25 -0
  45. aider/coders/wholefile_coder.py +144 -0
  46. aider/coders/wholefile_func_coder.py +134 -0
  47. aider/coders/wholefile_func_prompts.py +27 -0
  48. aider/coders/wholefile_prompts.py +70 -0
  49. aider/commands.py +1946 -0
  50. aider/copypaste.py +72 -0
  51. aider/deprecated.py +126 -0
  52. aider/diffs.py +128 -0
  53. aider/dump.py +29 -0
  54. aider/editor.py +147 -0
  55. aider/exceptions.py +107 -0
  56. aider/format_settings.py +26 -0
  57. aider/gui.py +545 -0
  58. aider/help.py +163 -0
  59. aider/help_pats.py +19 -0
  60. aider/history.py +178 -0
  61. aider/io.py +1257 -0
  62. aider/linter.py +304 -0
  63. aider/llm.py +47 -0
  64. aider/main.py +1297 -0
  65. aider/mcp/__init__.py +94 -0
  66. aider/mcp/server.py +119 -0
  67. aider/mdstream.py +243 -0
  68. aider/models.py +1344 -0
  69. aider/onboarding.py +428 -0
  70. aider/openrouter.py +129 -0
  71. aider/prompts.py +56 -0
  72. aider/queries/tree-sitter-language-pack/README.md +7 -0
  73. aider/queries/tree-sitter-language-pack/arduino-tags.scm +5 -0
  74. aider/queries/tree-sitter-language-pack/c-tags.scm +9 -0
  75. aider/queries/tree-sitter-language-pack/chatito-tags.scm +16 -0
  76. aider/queries/tree-sitter-language-pack/clojure-tags.scm +7 -0
  77. aider/queries/tree-sitter-language-pack/commonlisp-tags.scm +122 -0
  78. aider/queries/tree-sitter-language-pack/cpp-tags.scm +15 -0
  79. aider/queries/tree-sitter-language-pack/csharp-tags.scm +26 -0
  80. aider/queries/tree-sitter-language-pack/d-tags.scm +26 -0
  81. aider/queries/tree-sitter-language-pack/dart-tags.scm +92 -0
  82. aider/queries/tree-sitter-language-pack/elisp-tags.scm +5 -0
  83. aider/queries/tree-sitter-language-pack/elixir-tags.scm +54 -0
  84. aider/queries/tree-sitter-language-pack/elm-tags.scm +19 -0
  85. aider/queries/tree-sitter-language-pack/gleam-tags.scm +41 -0
  86. aider/queries/tree-sitter-language-pack/go-tags.scm +42 -0
  87. aider/queries/tree-sitter-language-pack/java-tags.scm +20 -0
  88. aider/queries/tree-sitter-language-pack/javascript-tags.scm +88 -0
  89. aider/queries/tree-sitter-language-pack/lua-tags.scm +34 -0
  90. aider/queries/tree-sitter-language-pack/matlab-tags.scm +10 -0
  91. aider/queries/tree-sitter-language-pack/ocaml-tags.scm +115 -0
  92. aider/queries/tree-sitter-language-pack/ocaml_interface-tags.scm +98 -0
  93. aider/queries/tree-sitter-language-pack/pony-tags.scm +39 -0
  94. aider/queries/tree-sitter-language-pack/properties-tags.scm +5 -0
  95. aider/queries/tree-sitter-language-pack/python-tags.scm +14 -0
  96. aider/queries/tree-sitter-language-pack/r-tags.scm +21 -0
  97. aider/queries/tree-sitter-language-pack/racket-tags.scm +12 -0
  98. aider/queries/tree-sitter-language-pack/ruby-tags.scm +64 -0
  99. aider/queries/tree-sitter-language-pack/rust-tags.scm +60 -0
  100. aider/queries/tree-sitter-language-pack/solidity-tags.scm +43 -0
  101. aider/queries/tree-sitter-language-pack/swift-tags.scm +51 -0
  102. aider/queries/tree-sitter-language-pack/udev-tags.scm +20 -0
  103. aider/queries/tree-sitter-languages/README.md +23 -0
  104. aider/queries/tree-sitter-languages/c-tags.scm +9 -0
  105. aider/queries/tree-sitter-languages/c_sharp-tags.scm +46 -0
  106. aider/queries/tree-sitter-languages/cpp-tags.scm +15 -0
  107. aider/queries/tree-sitter-languages/dart-tags.scm +91 -0
  108. aider/queries/tree-sitter-languages/elisp-tags.scm +8 -0
  109. aider/queries/tree-sitter-languages/elixir-tags.scm +54 -0
  110. aider/queries/tree-sitter-languages/elm-tags.scm +19 -0
  111. aider/queries/tree-sitter-languages/go-tags.scm +30 -0
  112. aider/queries/tree-sitter-languages/hcl-tags.scm +77 -0
  113. aider/queries/tree-sitter-languages/java-tags.scm +20 -0
  114. aider/queries/tree-sitter-languages/javascript-tags.scm +88 -0
  115. aider/queries/tree-sitter-languages/kotlin-tags.scm +27 -0
  116. aider/queries/tree-sitter-languages/matlab-tags.scm +10 -0
  117. aider/queries/tree-sitter-languages/ocaml-tags.scm +115 -0
  118. aider/queries/tree-sitter-languages/ocaml_interface-tags.scm +98 -0
  119. aider/queries/tree-sitter-languages/php-tags.scm +26 -0
  120. aider/queries/tree-sitter-languages/python-tags.scm +12 -0
  121. aider/queries/tree-sitter-languages/ql-tags.scm +26 -0
  122. aider/queries/tree-sitter-languages/ruby-tags.scm +64 -0
  123. aider/queries/tree-sitter-languages/rust-tags.scm +60 -0
  124. aider/queries/tree-sitter-languages/scala-tags.scm +65 -0
  125. aider/queries/tree-sitter-languages/typescript-tags.scm +41 -0
  126. aider/reasoning_tags.py +82 -0
  127. aider/repo.py +621 -0
  128. aider/repomap.py +988 -0
  129. aider/report.py +200 -0
  130. aider/resources/__init__.py +3 -0
  131. aider/resources/model-metadata.json +699 -0
  132. aider/resources/model-settings.yml +2046 -0
  133. aider/run_cmd.py +132 -0
  134. aider/scrape.py +284 -0
  135. aider/sendchat.py +61 -0
  136. aider/special.py +203 -0
  137. aider/tools/__init__.py +26 -0
  138. aider/tools/command.py +58 -0
  139. aider/tools/command_interactive.py +53 -0
  140. aider/tools/delete_block.py +120 -0
  141. aider/tools/delete_line.py +112 -0
  142. aider/tools/delete_lines.py +137 -0
  143. aider/tools/extract_lines.py +276 -0
  144. aider/tools/grep.py +171 -0
  145. aider/tools/indent_lines.py +155 -0
  146. aider/tools/insert_block.py +211 -0
  147. aider/tools/list_changes.py +51 -0
  148. aider/tools/ls.py +49 -0
  149. aider/tools/make_editable.py +46 -0
  150. aider/tools/make_readonly.py +29 -0
  151. aider/tools/remove.py +48 -0
  152. aider/tools/replace_all.py +77 -0
  153. aider/tools/replace_line.py +125 -0
  154. aider/tools/replace_lines.py +160 -0
  155. aider/tools/replace_text.py +125 -0
  156. aider/tools/show_numbered_context.py +101 -0
  157. aider/tools/tool_utils.py +313 -0
  158. aider/tools/undo_change.py +60 -0
  159. aider/tools/view.py +13 -0
  160. aider/tools/view_files_at_glob.py +65 -0
  161. aider/tools/view_files_matching.py +103 -0
  162. aider/tools/view_files_with_symbol.py +121 -0
  163. aider/urls.py +17 -0
  164. aider/utils.py +454 -0
  165. aider/versioncheck.py +113 -0
  166. aider/voice.py +187 -0
  167. aider/waiting.py +221 -0
  168. aider/watch.py +318 -0
  169. aider/watch_prompts.py +12 -0
  170. aider/website/Gemfile +8 -0
  171. aider/website/_includes/blame.md +162 -0
  172. aider/website/_includes/get-started.md +22 -0
  173. aider/website/_includes/help-tip.md +5 -0
  174. aider/website/_includes/help.md +24 -0
  175. aider/website/_includes/install.md +5 -0
  176. aider/website/_includes/keys.md +4 -0
  177. aider/website/_includes/model-warnings.md +67 -0
  178. aider/website/_includes/multi-line.md +22 -0
  179. aider/website/_includes/python-m-aider.md +5 -0
  180. aider/website/_includes/recording.css +228 -0
  181. aider/website/_includes/recording.md +34 -0
  182. aider/website/_includes/replit-pipx.md +9 -0
  183. aider/website/_includes/works-best.md +1 -0
  184. aider/website/_sass/custom/custom.scss +103 -0
  185. aider/website/docs/config/adv-model-settings.md +2260 -0
  186. aider/website/docs/config/aider_conf.md +548 -0
  187. aider/website/docs/config/api-keys.md +90 -0
  188. aider/website/docs/config/dotenv.md +493 -0
  189. aider/website/docs/config/editor.md +127 -0
  190. aider/website/docs/config/mcp.md +95 -0
  191. aider/website/docs/config/model-aliases.md +104 -0
  192. aider/website/docs/config/options.md +890 -0
  193. aider/website/docs/config/reasoning.md +210 -0
  194. aider/website/docs/config.md +44 -0
  195. aider/website/docs/faq.md +384 -0
  196. aider/website/docs/git.md +76 -0
  197. aider/website/docs/index.md +47 -0
  198. aider/website/docs/install/codespaces.md +39 -0
  199. aider/website/docs/install/docker.md +57 -0
  200. aider/website/docs/install/optional.md +100 -0
  201. aider/website/docs/install/replit.md +8 -0
  202. aider/website/docs/install.md +115 -0
  203. aider/website/docs/languages.md +264 -0
  204. aider/website/docs/legal/contributor-agreement.md +111 -0
  205. aider/website/docs/legal/privacy.md +104 -0
  206. aider/website/docs/llms/anthropic.md +77 -0
  207. aider/website/docs/llms/azure.md +48 -0
  208. aider/website/docs/llms/bedrock.md +132 -0
  209. aider/website/docs/llms/cohere.md +34 -0
  210. aider/website/docs/llms/deepseek.md +32 -0
  211. aider/website/docs/llms/gemini.md +49 -0
  212. aider/website/docs/llms/github.md +111 -0
  213. aider/website/docs/llms/groq.md +36 -0
  214. aider/website/docs/llms/lm-studio.md +39 -0
  215. aider/website/docs/llms/ollama.md +75 -0
  216. aider/website/docs/llms/openai-compat.md +39 -0
  217. aider/website/docs/llms/openai.md +58 -0
  218. aider/website/docs/llms/openrouter.md +78 -0
  219. aider/website/docs/llms/other.md +111 -0
  220. aider/website/docs/llms/vertex.md +50 -0
  221. aider/website/docs/llms/warnings.md +10 -0
  222. aider/website/docs/llms/xai.md +53 -0
  223. aider/website/docs/llms.md +54 -0
  224. aider/website/docs/more/analytics.md +127 -0
  225. aider/website/docs/more/edit-formats.md +116 -0
  226. aider/website/docs/more/infinite-output.md +159 -0
  227. aider/website/docs/more-info.md +8 -0
  228. aider/website/docs/recordings/auto-accept-architect.md +31 -0
  229. aider/website/docs/recordings/dont-drop-original-read-files.md +35 -0
  230. aider/website/docs/recordings/index.md +21 -0
  231. aider/website/docs/recordings/model-accepts-settings.md +69 -0
  232. aider/website/docs/recordings/tree-sitter-language-pack.md +80 -0
  233. aider/website/docs/repomap.md +112 -0
  234. aider/website/docs/scripting.md +100 -0
  235. aider/website/docs/troubleshooting/aider-not-found.md +24 -0
  236. aider/website/docs/troubleshooting/edit-errors.md +76 -0
  237. aider/website/docs/troubleshooting/imports.md +62 -0
  238. aider/website/docs/troubleshooting/models-and-keys.md +54 -0
  239. aider/website/docs/troubleshooting/support.md +79 -0
  240. aider/website/docs/troubleshooting/token-limits.md +96 -0
  241. aider/website/docs/troubleshooting/warnings.md +12 -0
  242. aider/website/docs/troubleshooting.md +11 -0
  243. aider/website/docs/usage/browser.md +57 -0
  244. aider/website/docs/usage/caching.md +49 -0
  245. aider/website/docs/usage/commands.md +133 -0
  246. aider/website/docs/usage/conventions.md +119 -0
  247. aider/website/docs/usage/copypaste.md +121 -0
  248. aider/website/docs/usage/images-urls.md +48 -0
  249. aider/website/docs/usage/lint-test.md +118 -0
  250. aider/website/docs/usage/modes.md +211 -0
  251. aider/website/docs/usage/not-code.md +179 -0
  252. aider/website/docs/usage/notifications.md +87 -0
  253. aider/website/docs/usage/tips.md +79 -0
  254. aider/website/docs/usage/tutorials.md +30 -0
  255. aider/website/docs/usage/voice.md +121 -0
  256. aider/website/docs/usage/watch.md +294 -0
  257. aider/website/docs/usage.md +102 -0
  258. aider/website/share/index.md +101 -0
  259. aider_ce-0.87.2.dev9.dist-info/METADATA +543 -0
  260. aider_ce-0.87.2.dev9.dist-info/RECORD +264 -0
  261. aider_ce-0.87.2.dev9.dist-info/WHEEL +5 -0
  262. aider_ce-0.87.2.dev9.dist-info/entry_points.txt +3 -0
  263. aider_ce-0.87.2.dev9.dist-info/licenses/LICENSE.txt +202 -0
  264. aider_ce-0.87.2.dev9.dist-info/top_level.txt +1 -0
aider/commands.py ADDED
@@ -0,0 +1,1946 @@
1
+ import glob
2
+ import os
3
+ import re
4
+ import subprocess
5
+ import sys
6
+ import tempfile
7
+ from collections import OrderedDict
8
+ from os.path import expanduser
9
+ from pathlib import Path
10
+
11
+ import pyperclip
12
+ from PIL import Image, ImageGrab
13
+ from prompt_toolkit.completion import Completion, PathCompleter
14
+ from prompt_toolkit.document import Document
15
+
16
+ from aider import models, prompts, voice
17
+ from aider.editor import pipe_editor
18
+ from aider.format_settings import format_settings
19
+ from aider.help import Help, install_help_extra
20
+ from aider.io import CommandCompletionException
21
+ from aider.llm import litellm
22
+ from aider.repo import ANY_GIT_ERROR
23
+ from aider.run_cmd import run_cmd
24
+ from aider.scrape import Scraper, install_playwright
25
+ from aider.utils import is_image_file, run_fzf
26
+
27
+ from .dump import dump # noqa: F401
28
+
29
+
30
+ class SwitchCoder(Exception):
31
+ def __init__(self, placeholder=None, **kwargs):
32
+ self.kwargs = kwargs
33
+ self.placeholder = placeholder
34
+
35
+
36
+ class Commands:
37
+ voice = None
38
+ scraper = None
39
+
40
+ def clone(self):
41
+ return Commands(
42
+ self.io,
43
+ None,
44
+ voice_language=self.voice_language,
45
+ verify_ssl=self.verify_ssl,
46
+ args=self.args,
47
+ parser=self.parser,
48
+ verbose=self.verbose,
49
+ editor=self.editor,
50
+ original_read_only_fnames=self.original_read_only_fnames,
51
+ )
52
+
53
+ def __init__(
54
+ self,
55
+ io,
56
+ coder,
57
+ voice_language=None,
58
+ voice_input_device=None,
59
+ voice_format=None,
60
+ verify_ssl=True,
61
+ args=None,
62
+ parser=None,
63
+ verbose=False,
64
+ editor=None,
65
+ original_read_only_fnames=None,
66
+ ):
67
+ self.io = io
68
+ self.coder = coder
69
+ self.parser = parser
70
+ self.args = args
71
+ self.verbose = verbose
72
+
73
+ self.verify_ssl = verify_ssl
74
+ if voice_language == "auto":
75
+ voice_language = None
76
+
77
+ self.voice_language = voice_language
78
+ self.voice_format = voice_format
79
+ self.voice_input_device = voice_input_device
80
+
81
+ self.help = None
82
+ self.editor = editor
83
+
84
+ # Store the original read-only filenames provided via args.read
85
+ self.original_read_only_fnames = set(original_read_only_fnames or [])
86
+
87
+ def cmd_model(self, args):
88
+ "Switch the Main Model to a new LLM"
89
+
90
+ model_name = args.strip()
91
+ if not model_name:
92
+ announcements = "\n".join(self.coder.get_announcements())
93
+ self.io.tool_output(announcements)
94
+ return
95
+
96
+ model = models.Model(
97
+ model_name,
98
+ editor_model=self.coder.main_model.editor_model.name,
99
+ weak_model=self.coder.main_model.weak_model.name,
100
+ )
101
+ models.sanity_check_models(self.io, model)
102
+
103
+ # Check if the current edit format is the default for the old model
104
+ old_model_edit_format = self.coder.main_model.edit_format
105
+ current_edit_format = self.coder.edit_format
106
+
107
+ new_edit_format = current_edit_format
108
+ if current_edit_format == old_model_edit_format:
109
+ # If the user was using the old model's default, switch to the new model's default
110
+ new_edit_format = model.edit_format
111
+
112
+ raise SwitchCoder(main_model=model, edit_format=new_edit_format)
113
+
114
+ def cmd_editor_model(self, args):
115
+ "Switch the Editor Model to a new LLM"
116
+
117
+ model_name = args.strip()
118
+ model = models.Model(
119
+ self.coder.main_model.name,
120
+ editor_model=model_name,
121
+ weak_model=self.coder.main_model.weak_model.name,
122
+ )
123
+ models.sanity_check_models(self.io, model)
124
+ raise SwitchCoder(main_model=model)
125
+
126
+ def cmd_weak_model(self, args):
127
+ "Switch the Weak Model to a new LLM"
128
+
129
+ model_name = args.strip()
130
+ model = models.Model(
131
+ self.coder.main_model.name,
132
+ editor_model=self.coder.main_model.editor_model.name,
133
+ weak_model=model_name,
134
+ )
135
+ models.sanity_check_models(self.io, model)
136
+ raise SwitchCoder(main_model=model)
137
+
138
+ def cmd_chat_mode(self, args):
139
+ "Switch to a new chat mode"
140
+
141
+ from aider import coders
142
+
143
+ ef = args.strip()
144
+ valid_formats = OrderedDict(
145
+ sorted(
146
+ (
147
+ coder.edit_format,
148
+ coder.__doc__.strip().split("\n")[0] if coder.__doc__ else "No description",
149
+ )
150
+ for coder in coders.__all__
151
+ if getattr(coder, "edit_format", None)
152
+ )
153
+ )
154
+
155
+ show_formats = OrderedDict(
156
+ [
157
+ ("help", "Get help about using aider (usage, config, troubleshoot)."),
158
+ ("ask", "Ask questions about your code without making any changes."),
159
+ ("code", "Ask for changes to your code (using the best edit format)."),
160
+ (
161
+ "architect",
162
+ (
163
+ "Work with an architect model to design code changes, and an editor to make"
164
+ " them."
165
+ ),
166
+ ),
167
+ (
168
+ "context",
169
+ "Automatically identify which files will need to be edited.",
170
+ ),
171
+ ]
172
+ )
173
+
174
+ if ef not in valid_formats and ef not in show_formats:
175
+ if ef:
176
+ self.io.tool_error(f'Chat mode "{ef}" should be one of these:\n')
177
+ else:
178
+ self.io.tool_output("Chat mode should be one of these:\n")
179
+
180
+ max_format_length = max(len(format) for format in valid_formats.keys())
181
+ for format, description in show_formats.items():
182
+ self.io.tool_output(f"- {format:<{max_format_length}} : {description}")
183
+
184
+ self.io.tool_output("\nOr a valid edit format:\n")
185
+ for format, description in valid_formats.items():
186
+ if format not in show_formats:
187
+ self.io.tool_output(f"- {format:<{max_format_length}} : {description}")
188
+
189
+ return
190
+
191
+ summarize_from_coder = True
192
+ edit_format = ef
193
+
194
+ if ef == "code":
195
+ edit_format = self.coder.main_model.edit_format
196
+ summarize_from_coder = False
197
+ elif ef == "ask":
198
+ summarize_from_coder = False
199
+
200
+ raise SwitchCoder(
201
+ edit_format=edit_format,
202
+ summarize_from_coder=summarize_from_coder,
203
+ )
204
+
205
+ def completions_model(self):
206
+ models = litellm.model_cost.keys()
207
+ return models
208
+
209
+ def cmd_models(self, args):
210
+ "Search the list of available models"
211
+
212
+ args = args.strip()
213
+
214
+ if args:
215
+ models.print_matching_models(self.io, args)
216
+ else:
217
+ self.io.tool_output("Please provide a partial model name to search for.")
218
+
219
+ def cmd_web(self, args, return_content=False):
220
+ "Scrape a webpage, convert to markdown and send in a message"
221
+
222
+ url = args.strip()
223
+ if not url:
224
+ self.io.tool_error("Please provide a URL to scrape.")
225
+ return
226
+
227
+ self.io.tool_output(f"Scraping {url}...")
228
+ if not self.scraper:
229
+ disable_playwright = getattr(self.args, "disable_playwright", False)
230
+ if disable_playwright:
231
+ res = False
232
+ else:
233
+ res = install_playwright(self.io)
234
+ if not res:
235
+ self.io.tool_warning("Unable to initialize playwright.")
236
+
237
+ self.scraper = Scraper(
238
+ print_error=self.io.tool_error,
239
+ playwright_available=res,
240
+ verify_ssl=self.verify_ssl,
241
+ )
242
+
243
+ content = self.scraper.scrape(url) or ""
244
+ content = f"Here is the content of {url}:\n\n" + content
245
+ if return_content:
246
+ return content
247
+
248
+ self.io.tool_output("... added to chat.")
249
+
250
+ self.coder.cur_messages += [
251
+ dict(role="user", content=content),
252
+ dict(role="assistant", content="Ok."),
253
+ ]
254
+
255
+ def is_command(self, inp):
256
+ return inp[0] in "/!"
257
+
258
+ def get_raw_completions(self, cmd):
259
+ assert cmd.startswith("/")
260
+ cmd = cmd[1:]
261
+ cmd = cmd.replace("-", "_")
262
+
263
+ raw_completer = getattr(self, f"completions_raw_{cmd}", None)
264
+ return raw_completer
265
+
266
+ def get_completions(self, cmd):
267
+ assert cmd.startswith("/")
268
+ cmd = cmd[1:]
269
+
270
+ cmd = cmd.replace("-", "_")
271
+ fun = getattr(self, f"completions_{cmd}", None)
272
+ if not fun:
273
+ return
274
+ return sorted(fun())
275
+
276
+ def get_commands(self):
277
+ commands = []
278
+ for attr in dir(self):
279
+ if not attr.startswith("cmd_"):
280
+ continue
281
+ cmd = attr[4:]
282
+ cmd = cmd.replace("_", "-")
283
+ commands.append("/" + cmd)
284
+
285
+ return commands
286
+
287
+ def do_run(self, cmd_name, args):
288
+ cmd_name = cmd_name.replace("-", "_")
289
+ cmd_method_name = f"cmd_{cmd_name}"
290
+ cmd_method = getattr(self, cmd_method_name, None)
291
+ if not cmd_method:
292
+ self.io.tool_output(f"Error: Command {cmd_name} not found.")
293
+ return
294
+
295
+ try:
296
+ return cmd_method(args)
297
+ except ANY_GIT_ERROR as err:
298
+ self.io.tool_error(f"Unable to complete {cmd_name}: {err}")
299
+
300
+ def matching_commands(self, inp):
301
+ words = inp.strip().split()
302
+ if not words:
303
+ return
304
+
305
+ first_word = words[0]
306
+ rest_inp = inp[len(words[0]) :].strip()
307
+
308
+ all_commands = self.get_commands()
309
+ matching_commands = [cmd for cmd in all_commands if cmd.startswith(first_word)]
310
+ return matching_commands, first_word, rest_inp
311
+
312
+ def run(self, inp):
313
+ if inp.startswith("!"):
314
+ self.coder.event("command_run")
315
+ return self.do_run("run", inp[1:])
316
+
317
+ res = self.matching_commands(inp)
318
+ if res is None:
319
+ return
320
+ matching_commands, first_word, rest_inp = res
321
+ if len(matching_commands) == 1:
322
+ command = matching_commands[0][1:]
323
+ self.coder.event(f"command_{command}")
324
+ return self.do_run(command, rest_inp)
325
+ elif first_word in matching_commands:
326
+ command = first_word[1:]
327
+ self.coder.event(f"command_{command}")
328
+ return self.do_run(command, rest_inp)
329
+ elif len(matching_commands) > 1:
330
+ self.io.tool_error(f"Ambiguous command: {', '.join(matching_commands)}")
331
+ else:
332
+ self.io.tool_error(f"Invalid command: {first_word}")
333
+
334
+ # any method called cmd_xxx becomes a command automatically.
335
+ # each one must take an args param.
336
+
337
+ def cmd_commit(self, args=None):
338
+ "Commit edits to the repo made outside the chat (commit message optional)"
339
+ try:
340
+ self.raw_cmd_commit(args)
341
+ except ANY_GIT_ERROR as err:
342
+ self.io.tool_error(f"Unable to complete commit: {err}")
343
+
344
+ def raw_cmd_commit(self, args=None):
345
+ if not self.coder.repo:
346
+ self.io.tool_error("No git repository found.")
347
+ return
348
+
349
+ if not self.coder.repo.is_dirty():
350
+ self.io.tool_warning("No more changes to commit.")
351
+ return
352
+
353
+ commit_message = args.strip() if args else None
354
+ self.coder.repo.commit(message=commit_message, coder=self.coder)
355
+
356
+ def cmd_lint(self, args="", fnames=None):
357
+ "Lint and fix in-chat files or all dirty files if none in chat"
358
+
359
+ if not self.coder.repo:
360
+ self.io.tool_error("No git repository found.")
361
+ return
362
+
363
+ if not fnames:
364
+ fnames = self.coder.get_inchat_relative_files()
365
+
366
+ # If still no files, get all dirty files in the repo
367
+ if not fnames and self.coder.repo:
368
+ fnames = self.coder.repo.get_dirty_files()
369
+
370
+ if not fnames:
371
+ self.io.tool_warning("No dirty files to lint.")
372
+ return
373
+
374
+ fnames = [self.coder.abs_root_path(fname) for fname in fnames]
375
+
376
+ lint_coder = None
377
+ for fname in fnames:
378
+ try:
379
+ errors = self.coder.linter.lint(fname)
380
+ except FileNotFoundError as err:
381
+ self.io.tool_error(f"Unable to lint {fname}")
382
+ self.io.tool_output(str(err))
383
+ continue
384
+
385
+ if not errors:
386
+ continue
387
+
388
+ self.io.tool_output(errors)
389
+ if not self.io.confirm_ask(f"Fix lint errors in {fname}?", default="y"):
390
+ continue
391
+
392
+ # Commit everything before we start fixing lint errors
393
+ if self.coder.repo.is_dirty() and self.coder.dirty_commits:
394
+ self.cmd_commit("")
395
+
396
+ if not lint_coder:
397
+ lint_coder = self.coder.clone(
398
+ # Clear the chat history, fnames
399
+ cur_messages=[],
400
+ done_messages=[],
401
+ fnames=None,
402
+ )
403
+
404
+ lint_coder.add_rel_fname(fname)
405
+ lint_coder.run(errors)
406
+ lint_coder.abs_fnames = set()
407
+
408
+ if lint_coder and self.coder.repo.is_dirty() and self.coder.auto_commits:
409
+ self.cmd_commit("")
410
+
411
+ def cmd_clear(self, args):
412
+ "Clear the chat history"
413
+
414
+ self._clear_chat_history()
415
+ self.io.tool_output("All chat history cleared.")
416
+
417
+ def _drop_all_files(self):
418
+ self.coder.abs_fnames = set()
419
+
420
+ # When dropping all files, keep those that were originally provided via args.read
421
+ if self.original_read_only_fnames:
422
+ # Keep only the original read-only files
423
+ to_keep = set()
424
+ for abs_fname in self.coder.abs_read_only_fnames:
425
+ rel_fname = self.coder.get_rel_fname(abs_fname)
426
+ if (
427
+ abs_fname in self.original_read_only_fnames
428
+ or rel_fname in self.original_read_only_fnames
429
+ ):
430
+ to_keep.add(abs_fname)
431
+ self.coder.abs_read_only_fnames = to_keep
432
+ else:
433
+ self.coder.abs_read_only_fnames = set()
434
+
435
+ def _clear_chat_history(self):
436
+ self.coder.done_messages = []
437
+ self.coder.cur_messages = []
438
+
439
+ def cmd_reset(self, args):
440
+ "Drop all files and clear the chat history"
441
+ self._drop_all_files()
442
+ self._clear_chat_history()
443
+ self.io.tool_output("All files dropped and chat history cleared.")
444
+
445
+ def cmd_tokens(self, args):
446
+ "Report on the number of tokens used by the current chat context"
447
+
448
+ res = []
449
+
450
+ self.coder.choose_fence()
451
+
452
+ # Show progress indicator
453
+ total_files = len(self.coder.abs_fnames) + len(self.coder.abs_read_only_fnames)
454
+ if total_files > 20:
455
+ self.io.tool_output(f"Calculating tokens for {total_files} files...")
456
+
457
+ # system messages
458
+ main_sys = self.coder.fmt_system_prompt(self.coder.gpt_prompts.main_system)
459
+ main_sys += "\n" + self.coder.fmt_system_prompt(self.coder.gpt_prompts.system_reminder)
460
+ msgs = [
461
+ dict(role="system", content=main_sys),
462
+ dict(
463
+ role="system",
464
+ content=self.coder.fmt_system_prompt(self.coder.gpt_prompts.system_reminder),
465
+ ),
466
+ ]
467
+
468
+ tokens = self.coder.main_model.token_count(msgs)
469
+ res.append((tokens, "system messages", ""))
470
+
471
+ # chat history
472
+ msgs = self.coder.done_messages + self.coder.cur_messages
473
+ if msgs:
474
+ tokens = self.coder.main_model.token_count(msgs)
475
+ res.append((tokens, "chat history", "use /clear to clear"))
476
+
477
+ # repo map
478
+ other_files = set(self.coder.get_all_abs_files()) - set(self.coder.abs_fnames)
479
+ if self.coder.repo_map:
480
+ repo_content = self.coder.repo_map.get_repo_map(self.coder.abs_fnames, other_files)
481
+ if repo_content:
482
+ tokens = self.coder.main_model.token_count(repo_content)
483
+ res.append((tokens, "repository map", "use --map-tokens to resize"))
484
+
485
+ # Enhanced context blocks (only for navigator mode)
486
+ if hasattr(self.coder, "use_enhanced_context") and self.coder.use_enhanced_context:
487
+ # Force token calculation if it hasn't been done yet
488
+ if hasattr(self.coder, "_calculate_context_block_tokens"):
489
+ if not hasattr(self.coder, "tokens_calculated") or not self.coder.tokens_calculated:
490
+ self.coder._calculate_context_block_tokens()
491
+
492
+ # Add enhanced context blocks to the display
493
+ if hasattr(self.coder, "context_block_tokens") and self.coder.context_block_tokens:
494
+ for block_name, tokens in self.coder.context_block_tokens.items():
495
+ # Format the block name more nicely
496
+ display_name = block_name.replace("_", " ").title()
497
+ res.append(
498
+ (tokens, f"{display_name} context block", "/context-blocks to toggle")
499
+ )
500
+
501
+ fence = "`" * 3
502
+
503
+ file_res = []
504
+ # Process files with progress indication
505
+ total_editable_files = len(self.coder.abs_fnames)
506
+ total_readonly_files = len(self.coder.abs_read_only_fnames)
507
+
508
+ # Display progress for editable files
509
+ if total_editable_files > 0:
510
+ if total_editable_files > 20:
511
+ self.io.tool_output(
512
+ f"Calculating tokens for {total_editable_files} editable files..."
513
+ )
514
+
515
+ # Calculate tokens for editable files
516
+ for i, fname in enumerate(self.coder.abs_fnames):
517
+ if i > 0 and i % 20 == 0 and total_editable_files > 20:
518
+ self.io.tool_output(f"Processed {i}/{total_editable_files} editable files...")
519
+
520
+ relative_fname = self.coder.get_rel_fname(fname)
521
+ content = self.io.read_text(fname)
522
+ if is_image_file(relative_fname):
523
+ tokens = self.coder.main_model.token_count_for_image(fname)
524
+ else:
525
+ # approximate
526
+ content = f"{relative_fname}\n{fence}\n" + content + "{fence}\n"
527
+ tokens = self.coder.main_model.token_count(content)
528
+ file_res.append((tokens, f"{relative_fname}", "/drop to remove"))
529
+
530
+ # Display progress for read-only files
531
+ if total_readonly_files > 0:
532
+ if total_readonly_files > 20:
533
+ self.io.tool_output(
534
+ f"Calculating tokens for {total_readonly_files} read-only files..."
535
+ )
536
+
537
+ # Calculate tokens for read-only files
538
+ for i, fname in enumerate(self.coder.abs_read_only_fnames):
539
+ if i > 0 and i % 20 == 0 and total_readonly_files > 20:
540
+ self.io.tool_output(f"Processed {i}/{total_readonly_files} read-only files...")
541
+
542
+ relative_fname = self.coder.get_rel_fname(fname)
543
+ content = self.io.read_text(fname)
544
+ if content is not None and not is_image_file(relative_fname):
545
+ # approximate
546
+ content = f"{relative_fname}\n{fence}\n" + content + "{fence}\n"
547
+ tokens = self.coder.main_model.token_count(content)
548
+ file_res.append((tokens, f"{relative_fname} (read-only)", "/drop to remove"))
549
+
550
+ if total_files > 20:
551
+ self.io.tool_output("Token calculation complete. Generating report...")
552
+
553
+ file_res.sort()
554
+ res.extend(file_res)
555
+
556
+ self.io.tool_output(
557
+ f"Approximate context window usage for {self.coder.main_model.name}, in tokens:"
558
+ )
559
+ self.io.tool_output()
560
+
561
+ width = 8
562
+ cost_width = 9
563
+
564
+ def fmt(v):
565
+ return format(int(v), ",").rjust(width)
566
+
567
+ col_width = max(len(row[1]) for row in res) if res else 0
568
+
569
+ cost_pad = " " * cost_width
570
+ total = 0
571
+ total_cost = 0.0
572
+ for tk, msg, tip in res:
573
+ total += tk
574
+ cost = tk * (self.coder.main_model.info.get("input_cost_per_token") or 0)
575
+ total_cost += cost
576
+ msg = msg.ljust(col_width)
577
+ self.io.tool_output(f"${cost:7.4f} {fmt(tk)} {msg} {tip}") # noqa: E231
578
+
579
+ self.io.tool_output("=" * (width + cost_width + 1))
580
+ self.io.tool_output(f"${total_cost:7.4f} {fmt(total)} tokens total") # noqa: E231
581
+
582
+ limit = self.coder.main_model.info.get("max_input_tokens") or 0
583
+ if not limit:
584
+ return
585
+
586
+ remaining = limit - total
587
+ if remaining > 1024:
588
+ self.io.tool_output(f"{cost_pad}{fmt(remaining)} tokens remaining in context window")
589
+ elif remaining > 0:
590
+ self.io.tool_error(
591
+ f"{cost_pad}{fmt(remaining)} tokens remaining in context window (use /drop or"
592
+ " /clear to make space)"
593
+ )
594
+ else:
595
+ self.io.tool_error(
596
+ f"{cost_pad}{fmt(remaining)} tokens remaining, window exhausted (use /drop or"
597
+ " /clear to make space)"
598
+ )
599
+ self.io.tool_output(f"{cost_pad}{fmt(limit)} tokens max context window size")
600
+
601
+ def cmd_undo(self, args):
602
+ "Undo the last git commit if it was done by aider"
603
+ try:
604
+ self.raw_cmd_undo(args)
605
+ except ANY_GIT_ERROR as err:
606
+ self.io.tool_error(f"Unable to complete undo: {err}")
607
+
608
+ def raw_cmd_undo(self, args):
609
+ if not self.coder.repo:
610
+ self.io.tool_error("No git repository found.")
611
+ return
612
+
613
+ last_commit = self.coder.repo.get_head_commit()
614
+ if not last_commit or not last_commit.parents:
615
+ self.io.tool_error("This is the first commit in the repository. Cannot undo.")
616
+ return
617
+
618
+ last_commit_hash = self.coder.repo.get_head_commit_sha(short=True)
619
+ last_commit_message = self.coder.repo.get_head_commit_message("(unknown)").strip()
620
+ last_commit_message = (last_commit_message.splitlines() or [""])[0]
621
+ if last_commit_hash not in self.coder.aider_commit_hashes:
622
+ self.io.tool_error("The last commit was not made by aider in this chat session.")
623
+ self.io.tool_output(
624
+ "You could try `/git reset --hard HEAD^` but be aware that this is a destructive"
625
+ " command!"
626
+ )
627
+ return
628
+
629
+ if len(last_commit.parents) > 1:
630
+ self.io.tool_error(
631
+ f"The last commit {last_commit.hexsha} has more than 1 parent, can't undo."
632
+ )
633
+ return
634
+
635
+ prev_commit = last_commit.parents[0]
636
+ changed_files_last_commit = [item.a_path for item in last_commit.diff(prev_commit)]
637
+
638
+ for fname in changed_files_last_commit:
639
+ if self.coder.repo.repo.is_dirty(path=fname):
640
+ self.io.tool_error(
641
+ f"The file {fname} has uncommitted changes. Please stash them before undoing."
642
+ )
643
+ return
644
+
645
+ # Check if the file was in the repo in the previous commit
646
+ try:
647
+ prev_commit.tree[fname]
648
+ except KeyError:
649
+ self.io.tool_error(
650
+ f"The file {fname} was not in the repository in the previous commit. Cannot"
651
+ " undo safely."
652
+ )
653
+ return
654
+
655
+ local_head = self.coder.repo.repo.git.rev_parse("HEAD")
656
+ current_branch = self.coder.repo.repo.active_branch.name
657
+ try:
658
+ remote_head = self.coder.repo.repo.git.rev_parse(f"origin/{current_branch}")
659
+ has_origin = True
660
+ except ANY_GIT_ERROR:
661
+ has_origin = False
662
+
663
+ if has_origin:
664
+ if local_head == remote_head:
665
+ self.io.tool_error(
666
+ "The last commit has already been pushed to the origin. Undoing is not"
667
+ " possible."
668
+ )
669
+ return
670
+
671
+ # Reset only the files which are part of `last_commit`
672
+ restored = set()
673
+ unrestored = set()
674
+ for file_path in changed_files_last_commit:
675
+ try:
676
+ self.coder.repo.repo.git.checkout("HEAD~1", file_path)
677
+ restored.add(file_path)
678
+ except ANY_GIT_ERROR:
679
+ unrestored.add(file_path)
680
+
681
+ if unrestored:
682
+ self.io.tool_error(f"Error restoring {file_path}, aborting undo.")
683
+ self.io.tool_output("Restored files:")
684
+ for file in restored:
685
+ self.io.tool_output(f" {file}")
686
+ self.io.tool_output("Unable to restore files:")
687
+ for file in unrestored:
688
+ self.io.tool_output(f" {file}")
689
+ return
690
+
691
+ # Move the HEAD back before the latest commit
692
+ self.coder.repo.repo.git.reset("--soft", "HEAD~1")
693
+
694
+ self.io.tool_output(f"Removed: {last_commit_hash} {last_commit_message}")
695
+
696
+ # Get the current HEAD after undo
697
+ current_head_hash = self.coder.repo.get_head_commit_sha(short=True)
698
+ current_head_message = self.coder.repo.get_head_commit_message("(unknown)").strip()
699
+ current_head_message = (current_head_message.splitlines() or [""])[0]
700
+ self.io.tool_output(f"Now at: {current_head_hash} {current_head_message}")
701
+
702
+ if self.coder.main_model.send_undo_reply:
703
+ return prompts.undo_command_reply
704
+
705
+ def cmd_diff(self, args=""):
706
+ "Display the diff of changes since the last message"
707
+ try:
708
+ self.raw_cmd_diff(args)
709
+ except ANY_GIT_ERROR as err:
710
+ self.io.tool_error(f"Unable to complete diff: {err}")
711
+
712
+ def raw_cmd_diff(self, args=""):
713
+ if not self.coder.repo:
714
+ self.io.tool_error("No git repository found.")
715
+ return
716
+
717
+ current_head = self.coder.repo.get_head_commit_sha()
718
+ if current_head is None:
719
+ self.io.tool_error("Unable to get current commit. The repository might be empty.")
720
+ return
721
+
722
+ if len(self.coder.commit_before_message) < 2:
723
+ commit_before_message = current_head + "^"
724
+ else:
725
+ commit_before_message = self.coder.commit_before_message[-2]
726
+
727
+ if not commit_before_message or commit_before_message == current_head:
728
+ self.io.tool_warning("No changes to display since the last message.")
729
+ return
730
+
731
+ self.io.tool_output(f"Diff since {commit_before_message[:7]}...")
732
+
733
+ if self.coder.pretty:
734
+ run_cmd(f"git diff {commit_before_message}")
735
+ return
736
+
737
+ diff = self.coder.repo.diff_commits(
738
+ self.coder.pretty,
739
+ commit_before_message,
740
+ "HEAD",
741
+ )
742
+
743
+ self.io.print(diff)
744
+
745
+ def quote_fname(self, fname):
746
+ if " " in fname and '"' not in fname:
747
+ fname = f'"{fname}"'
748
+ return fname
749
+
750
+ def completions_raw_read_only(self, document, complete_event):
751
+ # Get the text before the cursor
752
+ text = document.text_before_cursor
753
+
754
+ # Skip the first word and the space after it
755
+ after_command = text.split()[-1]
756
+
757
+ # Create a new Document object with the text after the command
758
+ new_document = Document(after_command, cursor_position=len(after_command))
759
+
760
+ def get_paths():
761
+ return [self.coder.root] if self.coder.root else None
762
+
763
+ path_completer = PathCompleter(
764
+ get_paths=get_paths,
765
+ only_directories=False,
766
+ expanduser=True,
767
+ )
768
+
769
+ # Adjust the start_position to replace all of 'after_command'
770
+ adjusted_start_position = -len(after_command)
771
+
772
+ # Collect all completions
773
+ all_completions = []
774
+
775
+ # Iterate over the completions and modify them
776
+ for completion in path_completer.get_completions(new_document, complete_event):
777
+ quoted_text = self.quote_fname(after_command + completion.text)
778
+ all_completions.append(
779
+ Completion(
780
+ text=quoted_text,
781
+ start_position=adjusted_start_position,
782
+ display=completion.display,
783
+ style=completion.style,
784
+ selected_style=completion.selected_style,
785
+ )
786
+ )
787
+
788
+ # Add completions from the 'add' command
789
+ add_completions = self.completions_add()
790
+ for completion in add_completions:
791
+ if after_command in completion:
792
+ all_completions.append(
793
+ Completion(
794
+ text=completion,
795
+ start_position=adjusted_start_position,
796
+ display=completion,
797
+ )
798
+ )
799
+
800
+ # Sort all completions based on their text
801
+ sorted_completions = sorted(all_completions, key=lambda c: c.text)
802
+
803
+ # Yield the sorted completions
804
+ for completion in sorted_completions:
805
+ yield completion
806
+
807
+ def completions_add(self):
808
+ files = set(self.coder.get_all_relative_files())
809
+ files = files - set(self.coder.get_inchat_relative_files())
810
+ files = [self.quote_fname(fn) for fn in files]
811
+ return files
812
+
813
+ def glob_filtered_to_repo(self, pattern):
814
+ if not pattern.strip():
815
+ return []
816
+ try:
817
+ if os.path.isabs(pattern):
818
+ # Handle absolute paths
819
+ raw_matched_files = [Path(pattern)]
820
+ else:
821
+ try:
822
+ raw_matched_files = list(Path(self.coder.root).glob(pattern))
823
+ except (IndexError, AttributeError):
824
+ raw_matched_files = []
825
+ except ValueError as err:
826
+ self.io.tool_error(f"Error matching {pattern}: {err}")
827
+ raw_matched_files = []
828
+
829
+ matched_files = []
830
+ for fn in raw_matched_files:
831
+ matched_files += expand_subdir(fn)
832
+
833
+ matched_files = [
834
+ fn.relative_to(self.coder.root)
835
+ for fn in matched_files
836
+ if fn.is_relative_to(self.coder.root)
837
+ ]
838
+
839
+ # if repo, filter against it
840
+ if self.coder.repo:
841
+ git_files = self.coder.repo.get_tracked_files()
842
+ matched_files = [fn for fn in matched_files if str(fn) in git_files]
843
+
844
+ res = list(map(str, matched_files))
845
+ return res
846
+
847
+ def cmd_add(self, args):
848
+ "Add files to the chat so aider can edit them or review them in detail"
849
+
850
+ if not args.strip():
851
+ all_files = self.coder.get_all_relative_files()
852
+ files_in_chat = self.coder.get_inchat_relative_files()
853
+ addable_files = sorted(set(all_files) - set(files_in_chat))
854
+ if not addable_files:
855
+ self.io.tool_output("No files available to add.")
856
+ return
857
+ selected_files = run_fzf(addable_files, multi=True)
858
+ if not selected_files:
859
+ return
860
+ args = " ".join([self.quote_fname(f) for f in selected_files])
861
+
862
+ all_matched_files = set()
863
+
864
+ filenames = parse_quoted_filenames(args)
865
+ for word in filenames:
866
+ if Path(word).is_absolute():
867
+ fname = Path(word)
868
+ else:
869
+ fname = Path(self.coder.root) / word
870
+
871
+ if self.coder.repo and self.coder.repo.ignored_file(fname):
872
+ self.io.tool_warning(f"Skipping {fname} due to aiderignore or --subtree-only.")
873
+ continue
874
+
875
+ if fname.exists():
876
+ if fname.is_file():
877
+ all_matched_files.add(str(fname))
878
+ continue
879
+ # an existing dir, escape any special chars so they won't be globs
880
+ word = re.sub(r"([\*\?\[\]])", r"[\1]", word)
881
+
882
+ matched_files = self.glob_filtered_to_repo(word)
883
+ if matched_files:
884
+ all_matched_files.update(matched_files)
885
+ continue
886
+
887
+ if "*" in str(fname) or "?" in str(fname):
888
+ self.io.tool_error(
889
+ f"No match, and cannot create file with wildcard characters: {fname}"
890
+ )
891
+ continue
892
+
893
+ if fname.exists() and fname.is_dir() and self.coder.repo:
894
+ self.io.tool_error(f"Directory {fname} is not in git.")
895
+ self.io.tool_output(f"You can add to git with: /git add {fname}")
896
+ continue
897
+
898
+ if self.io.confirm_ask(f"No files matched '{word}'. Do you want to create {fname}?"):
899
+ try:
900
+ fname.parent.mkdir(parents=True, exist_ok=True)
901
+ fname.touch()
902
+ all_matched_files.add(str(fname))
903
+ except OSError as e:
904
+ self.io.tool_error(f"Error creating file {fname}: {e}")
905
+
906
+ for matched_file in sorted(all_matched_files):
907
+ abs_file_path = self.coder.abs_root_path(matched_file)
908
+
909
+ if not abs_file_path.startswith(self.coder.root) and not is_image_file(matched_file):
910
+ self.io.tool_error(
911
+ f"Can not add {abs_file_path}, which is not within {self.coder.root}"
912
+ )
913
+ continue
914
+
915
+ if (
916
+ self.coder.repo
917
+ and self.coder.repo.git_ignored_file(matched_file)
918
+ and not self.coder.add_gitignore_files
919
+ ):
920
+ self.io.tool_error(f"Can't add {matched_file} which is in gitignore")
921
+ continue
922
+
923
+ if abs_file_path in self.coder.abs_fnames:
924
+ self.io.tool_error(f"{matched_file} is already in the chat as an editable file")
925
+ continue
926
+ elif abs_file_path in self.coder.abs_read_only_fnames:
927
+ if self.coder.repo and self.coder.repo.path_in_repo(matched_file):
928
+ self.coder.abs_read_only_fnames.remove(abs_file_path)
929
+ self.coder.abs_fnames.add(abs_file_path)
930
+ self.io.tool_output(
931
+ f"Moved {matched_file} from read-only to editable files in the chat"
932
+ )
933
+ else:
934
+ self.io.tool_error(
935
+ f"Cannot add {matched_file} as it's not part of the repository"
936
+ )
937
+ else:
938
+ if is_image_file(matched_file) and not self.coder.main_model.info.get(
939
+ "supports_vision"
940
+ ):
941
+ self.io.tool_error(
942
+ f"Cannot add image file {matched_file} as the"
943
+ f" {self.coder.main_model.name} does not support images."
944
+ )
945
+ continue
946
+ content = self.io.read_text(abs_file_path)
947
+ if content is None:
948
+ self.io.tool_error(f"Unable to read {matched_file}")
949
+ else:
950
+ self.coder.abs_fnames.add(abs_file_path)
951
+ fname = self.coder.get_rel_fname(abs_file_path)
952
+ self.io.tool_output(f"Added {fname} to the chat")
953
+ self.coder.check_added_files()
954
+
955
+ # Recalculate context block tokens if using navigator mode
956
+ if (
957
+ hasattr(self.coder, "use_enhanced_context")
958
+ and self.coder.use_enhanced_context
959
+ ):
960
+ if hasattr(self.coder, "_calculate_context_block_tokens"):
961
+ self.coder._calculate_context_block_tokens()
962
+
963
+ def completions_drop(self):
964
+ files = self.coder.get_inchat_relative_files()
965
+ read_only_files = [self.coder.get_rel_fname(fn) for fn in self.coder.abs_read_only_fnames]
966
+ all_files = files + read_only_files
967
+ all_files = [self.quote_fname(fn) for fn in all_files]
968
+ return all_files
969
+
970
+ def completions_context_blocks(self):
971
+ """Return available context block names for auto-completion."""
972
+ if not hasattr(self.coder, "use_enhanced_context") or not self.coder.use_enhanced_context:
973
+ return []
974
+
975
+ # If the coder has context blocks available
976
+ if hasattr(self.coder, "context_block_tokens") and self.coder.context_block_tokens:
977
+ # Get all block names from the tokens dictionary
978
+ block_names = list(self.coder.context_block_tokens.keys())
979
+ # Format them for display (convert snake_case to Title Case)
980
+ formatted_blocks = [name.replace("_", " ").title() for name in block_names]
981
+ return formatted_blocks
982
+
983
+ # Standard blocks that are typically available
984
+ return [
985
+ "Context Summary",
986
+ "Directory Structure",
987
+ "Environment Info",
988
+ "Git Status",
989
+ "Symbol Outline",
990
+ ]
991
+
992
+ def cmd_drop(self, args=""):
993
+ "Remove files from the chat session to free up context space"
994
+
995
+ if not args.strip():
996
+ if self.original_read_only_fnames:
997
+ self.io.tool_output(
998
+ "Dropping all files from the chat session except originally read-only files."
999
+ )
1000
+ else:
1001
+ self.io.tool_output("Dropping all files from the chat session.")
1002
+ self._drop_all_files()
1003
+
1004
+ # Recalculate context block tokens after dropping all files
1005
+ if hasattr(self.coder, "use_enhanced_context") and self.coder.use_enhanced_context:
1006
+ if hasattr(self.coder, "_calculate_context_block_tokens"):
1007
+ self.coder._calculate_context_block_tokens()
1008
+ return
1009
+
1010
+ filenames = parse_quoted_filenames(args)
1011
+ files_changed = False
1012
+
1013
+ for word in filenames:
1014
+ # Expand tilde in the path
1015
+ expanded_word = os.path.expanduser(word)
1016
+
1017
+ # Handle read-only files with substring matching and samefile check
1018
+ read_only_matched = []
1019
+ for f in self.coder.abs_read_only_fnames:
1020
+ if expanded_word in f:
1021
+ read_only_matched.append(f)
1022
+ continue
1023
+
1024
+ # Try samefile comparison for relative paths
1025
+ try:
1026
+ abs_word = os.path.abspath(expanded_word)
1027
+ if os.path.samefile(abs_word, f):
1028
+ read_only_matched.append(f)
1029
+ except (FileNotFoundError, OSError):
1030
+ continue
1031
+
1032
+ for matched_file in read_only_matched:
1033
+ self.coder.abs_read_only_fnames.remove(matched_file)
1034
+ self.io.tool_output(f"Removed read-only file {matched_file} from the chat")
1035
+ files_changed = True
1036
+
1037
+ # For editable files, use glob if word contains glob chars, otherwise use substring
1038
+ if any(c in expanded_word for c in "*?[]"):
1039
+ matched_files = self.glob_filtered_to_repo(expanded_word)
1040
+ else:
1041
+ # Use substring matching like we do for read-only files
1042
+ matched_files = [
1043
+ self.coder.get_rel_fname(f) for f in self.coder.abs_fnames if expanded_word in f
1044
+ ]
1045
+
1046
+ if not matched_files:
1047
+ matched_files.append(expanded_word)
1048
+
1049
+ for matched_file in matched_files:
1050
+ abs_fname = self.coder.abs_root_path(matched_file)
1051
+ if abs_fname in self.coder.abs_fnames:
1052
+ self.coder.abs_fnames.remove(abs_fname)
1053
+ self.io.tool_output(f"Removed {matched_file} from the chat")
1054
+ files_changed = True
1055
+
1056
+ # Recalculate context block tokens if any files were changed and using navigator mode
1057
+ if (
1058
+ files_changed
1059
+ and hasattr(self.coder, "use_enhanced_context")
1060
+ and self.coder.use_enhanced_context
1061
+ ):
1062
+ if hasattr(self.coder, "_calculate_context_block_tokens"):
1063
+ self.coder._calculate_context_block_tokens()
1064
+
1065
+ def cmd_git(self, args):
1066
+ "Run a git command (output excluded from chat)"
1067
+ combined_output = None
1068
+ try:
1069
+ args = "git " + args
1070
+ env = dict(subprocess.os.environ)
1071
+ env["GIT_EDITOR"] = "true"
1072
+ result = subprocess.run(
1073
+ args,
1074
+ stdout=subprocess.PIPE,
1075
+ stderr=subprocess.STDOUT,
1076
+ text=True,
1077
+ env=env,
1078
+ shell=True,
1079
+ encoding=self.io.encoding,
1080
+ errors="replace",
1081
+ )
1082
+ combined_output = result.stdout
1083
+ except Exception as e:
1084
+ self.io.tool_error(f"Error running /git command: {e}")
1085
+
1086
+ if combined_output is None:
1087
+ return
1088
+
1089
+ self.io.tool_output(combined_output)
1090
+
1091
+ def cmd_test(self, args):
1092
+ "Run a shell command and add the output to the chat on non-zero exit code"
1093
+ if not args and self.coder.test_cmd:
1094
+ args = self.coder.test_cmd
1095
+
1096
+ if not args:
1097
+ return
1098
+
1099
+ if not callable(args):
1100
+ if type(args) is not str:
1101
+ raise ValueError(repr(args))
1102
+ return self.cmd_run(args, True)
1103
+
1104
+ errors = args()
1105
+ if not errors:
1106
+ return
1107
+
1108
+ self.io.tool_output(errors)
1109
+ return errors
1110
+
1111
+ def cmd_run(self, args, add_on_nonzero_exit=False):
1112
+ "Run a shell command and optionally add the output to the chat (alias: !)"
1113
+ exit_status, combined_output = run_cmd(
1114
+ args, verbose=self.verbose, error_print=self.io.tool_error, cwd=self.coder.root
1115
+ )
1116
+
1117
+ if combined_output is None:
1118
+ return
1119
+
1120
+ # Calculate token count of output
1121
+ token_count = self.coder.main_model.token_count(combined_output)
1122
+ k_tokens = token_count / 1000
1123
+
1124
+ if add_on_nonzero_exit:
1125
+ add = exit_status != 0
1126
+ else:
1127
+ add = self.io.confirm_ask(f"Add {k_tokens:.1f}k tokens of command output to the chat?")
1128
+
1129
+ if add:
1130
+ num_lines = len(combined_output.strip().splitlines())
1131
+ line_plural = "line" if num_lines == 1 else "lines"
1132
+ self.io.tool_output(f"Added {num_lines} {line_plural} of output to the chat.")
1133
+
1134
+ msg = prompts.run_output.format(
1135
+ command=args,
1136
+ output=combined_output,
1137
+ )
1138
+
1139
+ self.coder.cur_messages += [
1140
+ dict(role="user", content=msg),
1141
+ dict(role="assistant", content="Ok."),
1142
+ ]
1143
+
1144
+ if add_on_nonzero_exit and exit_status != 0:
1145
+ # Return the formatted output message for test failures
1146
+ return msg
1147
+ elif add and exit_status != 0:
1148
+ self.io.placeholder = "What's wrong? Fix"
1149
+
1150
+ # Return None if output wasn't added or command succeeded
1151
+ return None
1152
+
1153
+ def cmd_exit(self, args):
1154
+ "Exit the application"
1155
+ self.coder.event("exit", reason="/exit")
1156
+ sys.exit()
1157
+
1158
+ def cmd_quit(self, args):
1159
+ "Exit the application"
1160
+ self.cmd_exit(args)
1161
+
1162
+ def cmd_context_management(self, args=""):
1163
+ "Toggle context management for large files"
1164
+ if not hasattr(self.coder, "context_management_enabled"):
1165
+ self.io.tool_error("Context management is only available in navigator mode.")
1166
+ return
1167
+
1168
+ # Toggle the setting
1169
+ self.coder.context_management_enabled = not self.coder.context_management_enabled
1170
+
1171
+ # Report the new state
1172
+ if self.coder.context_management_enabled:
1173
+ self.io.tool_output("Context management is now ON - large files may be truncated.")
1174
+ else:
1175
+ self.io.tool_output("Context management is now OFF - files will not be truncated.")
1176
+
1177
+ def cmd_context_blocks(self, args=""):
1178
+ "Toggle enhanced context blocks or print a specific block"
1179
+ if not hasattr(self.coder, "use_enhanced_context"):
1180
+ self.io.tool_error("Enhanced context blocks are only available in navigator mode.")
1181
+ return
1182
+
1183
+ # If an argument is provided, try to print that specific context block
1184
+ if args.strip():
1185
+ # Format block name to match internal naming conventions
1186
+ block_name = args.strip().lower().replace(" ", "_")
1187
+
1188
+ # Check if the coder has the necessary method to get context blocks
1189
+ if hasattr(self.coder, "_generate_context_block"):
1190
+ # Force token recalculation to ensure blocks are fresh
1191
+ if hasattr(self.coder, "_calculate_context_block_tokens"):
1192
+ self.coder._calculate_context_block_tokens(force=True)
1193
+
1194
+ # Try to get the requested block
1195
+ block_content = self.coder._generate_context_block(block_name)
1196
+
1197
+ if block_content:
1198
+ # Calculate token count
1199
+ tokens = self.coder.main_model.token_count(block_content)
1200
+ self.io.tool_output(f"Context block '{args.strip()}' ({tokens} tokens):")
1201
+ self.io.tool_output(block_content)
1202
+ return
1203
+ else:
1204
+ # List available blocks if the requested one wasn't found
1205
+ self.io.tool_error(f"Context block '{args.strip()}' not found or empty.")
1206
+ if hasattr(self.coder, "context_block_tokens"):
1207
+ available_blocks = list(self.coder.context_block_tokens.keys())
1208
+ formatted_blocks = [
1209
+ name.replace("_", " ").title() for name in available_blocks
1210
+ ]
1211
+ self.io.tool_output(f"Available blocks: {', '.join(formatted_blocks)}")
1212
+ return
1213
+ else:
1214
+ self.io.tool_error("This coder doesn't support generating context blocks.")
1215
+ return
1216
+
1217
+ # If no argument, toggle the enhanced context setting
1218
+ self.coder.use_enhanced_context = not self.coder.use_enhanced_context
1219
+
1220
+ # Report the new state
1221
+ if self.coder.use_enhanced_context:
1222
+ self.io.tool_output(
1223
+ "Enhanced context blocks are now ON - directory structure and git status will be"
1224
+ " included."
1225
+ )
1226
+ if hasattr(self.coder, "context_block_tokens"):
1227
+ available_blocks = list(self.coder.context_block_tokens.keys())
1228
+ formatted_blocks = [name.replace("_", " ").title() for name in available_blocks]
1229
+ self.io.tool_output(f"Available blocks: {', '.join(formatted_blocks)}")
1230
+ self.io.tool_output("Use '/context-blocks [block name]' to view a specific block.")
1231
+ else:
1232
+ self.io.tool_output(
1233
+ "Enhanced context blocks are now OFF - directory structure and git status will not"
1234
+ " be included."
1235
+ )
1236
+
1237
+ def cmd_granular_editing(self, args=""):
1238
+ "Toggle granular editing tools in navigator mode"
1239
+ if not hasattr(self.coder, "use_granular_editing"):
1240
+ self.io.tool_error("Granular editing toggle is only available in navigator mode.")
1241
+ return
1242
+
1243
+ # Toggle the setting using the navigator's method if available
1244
+ new_state = not self.coder.use_granular_editing
1245
+
1246
+ if hasattr(self.coder, "set_granular_editing"):
1247
+ self.coder.set_granular_editing(new_state)
1248
+ else:
1249
+ # Fallback if method doesn't exist
1250
+ self.coder.use_granular_editing = new_state
1251
+
1252
+ # Report the new state
1253
+ if self.coder.use_granular_editing:
1254
+ self.io.tool_output(
1255
+ "Granular editing tools are now ON - navigator will use specific editing tools"
1256
+ " instead of search/replace."
1257
+ )
1258
+ else:
1259
+ self.io.tool_output(
1260
+ "Granular editing tools are now OFF - navigator will use search/replace blocks for"
1261
+ " editing."
1262
+ )
1263
+
1264
+ def cmd_ls(self, args):
1265
+ "List all known files and indicate which are included in the chat session"
1266
+
1267
+ files = self.coder.get_all_relative_files()
1268
+
1269
+ other_files = []
1270
+ chat_files = []
1271
+ read_only_files = []
1272
+ for file in files:
1273
+ abs_file_path = self.coder.abs_root_path(file)
1274
+ if abs_file_path in self.coder.abs_fnames:
1275
+ chat_files.append(file)
1276
+ else:
1277
+ other_files.append(file)
1278
+
1279
+ # Add read-only files
1280
+ for abs_file_path in self.coder.abs_read_only_fnames:
1281
+ rel_file_path = self.coder.get_rel_fname(abs_file_path)
1282
+ read_only_files.append(rel_file_path)
1283
+
1284
+ if not chat_files and not other_files and not read_only_files:
1285
+ self.io.tool_output("\nNo files in chat, git repo, or read-only list.")
1286
+ return
1287
+
1288
+ if other_files:
1289
+ self.io.tool_output("Repo files not in the chat:\n")
1290
+ for file in other_files:
1291
+ self.io.tool_output(f" {file}")
1292
+
1293
+ if read_only_files:
1294
+ self.io.tool_output("\nRead-only files:\n")
1295
+ for file in read_only_files:
1296
+ self.io.tool_output(f" {file}")
1297
+
1298
+ if chat_files:
1299
+ self.io.tool_output("\nFiles in chat:\n")
1300
+ for file in chat_files:
1301
+ self.io.tool_output(f" {file}")
1302
+
1303
+ def basic_help(self):
1304
+ commands = sorted(self.get_commands())
1305
+ pad = max(len(cmd) for cmd in commands)
1306
+ pad = "{cmd:" + str(pad) + "}"
1307
+ for cmd in commands:
1308
+ cmd_method_name = f"cmd_{cmd[1:]}".replace("-", "_")
1309
+ cmd_method = getattr(self, cmd_method_name, None)
1310
+ cmd = pad.format(cmd=cmd)
1311
+ if cmd_method:
1312
+ description = cmd_method.__doc__
1313
+ self.io.tool_output(f"{cmd} {description}")
1314
+ else:
1315
+ self.io.tool_output(f"{cmd} No description available.")
1316
+ self.io.tool_output()
1317
+ self.io.tool_output("Use `/help <question>` to ask questions about how to use aider.")
1318
+
1319
+ def cmd_help(self, args):
1320
+ "Ask questions about aider"
1321
+
1322
+ if not args.strip():
1323
+ self.basic_help()
1324
+ return
1325
+
1326
+ self.coder.event("interactive help")
1327
+ from aider.coders.base_coder import Coder
1328
+
1329
+ if not self.help:
1330
+ res = install_help_extra(self.io)
1331
+ if not res:
1332
+ self.io.tool_error("Unable to initialize interactive help.")
1333
+ return
1334
+
1335
+ self.help = Help()
1336
+
1337
+ coder = Coder.create(
1338
+ io=self.io,
1339
+ from_coder=self.coder,
1340
+ edit_format="help",
1341
+ summarize_from_coder=False,
1342
+ map_tokens=512,
1343
+ map_mul_no_files=1,
1344
+ )
1345
+ user_msg = self.help.ask(args)
1346
+ user_msg += """
1347
+ # Announcement lines from when this session of aider was launched:
1348
+
1349
+ """
1350
+ user_msg += "\n".join(self.coder.get_announcements()) + "\n"
1351
+
1352
+ coder.run(user_msg, preproc=False)
1353
+
1354
+ if self.coder.repo_map:
1355
+ map_tokens = self.coder.repo_map.max_map_tokens
1356
+ map_mul_no_files = self.coder.repo_map.map_mul_no_files
1357
+ else:
1358
+ map_tokens = 0
1359
+ map_mul_no_files = 1
1360
+
1361
+ raise SwitchCoder(
1362
+ edit_format=self.coder.edit_format,
1363
+ summarize_from_coder=False,
1364
+ from_coder=coder,
1365
+ map_tokens=map_tokens,
1366
+ map_mul_no_files=map_mul_no_files,
1367
+ show_announcements=False,
1368
+ )
1369
+
1370
+ def completions_ask(self):
1371
+ raise CommandCompletionException()
1372
+
1373
+ def completions_code(self):
1374
+ raise CommandCompletionException()
1375
+
1376
+ def completions_architect(self):
1377
+ raise CommandCompletionException()
1378
+
1379
+ def completions_context(self):
1380
+ raise CommandCompletionException()
1381
+
1382
+ def completions_navigator(self):
1383
+ raise CommandCompletionException()
1384
+
1385
+ def cmd_ask(self, args):
1386
+ """Ask questions about the code base without editing any files. If no prompt provided, switches to ask mode.""" # noqa
1387
+ return self._generic_chat_command(args, "ask")
1388
+
1389
+ def cmd_code(self, args):
1390
+ """Ask for changes to your code. If no prompt provided, switches to code mode.""" # noqa
1391
+ return self._generic_chat_command(args, self.coder.main_model.edit_format)
1392
+
1393
+ def cmd_architect(self, args):
1394
+ """Enter architect/editor mode using 2 different models. If no prompt provided, switches to architect/editor mode.""" # noqa
1395
+ return self._generic_chat_command(args, "architect")
1396
+
1397
+ def cmd_context(self, args):
1398
+ """Enter context mode to see surrounding code context. If no prompt provided, switches to context mode.""" # noqa
1399
+ return self._generic_chat_command(args, "context", placeholder=args.strip() or None)
1400
+
1401
+ def cmd_navigator(self, args):
1402
+ """Enter navigator mode to autonomously discover and manage relevant files. If no prompt provided, switches to navigator mode.""" # noqa
1403
+ # Enable context management when entering navigator mode
1404
+ if hasattr(self.coder, "context_management_enabled"):
1405
+ self.coder.context_management_enabled = True
1406
+ self.io.tool_output("Context management enabled for large files")
1407
+
1408
+ return self._generic_chat_command(args, "navigator", placeholder=args.strip() or None)
1409
+
1410
+ def _generic_chat_command(self, args, edit_format, placeholder=None):
1411
+ if not args.strip():
1412
+ # Switch to the corresponding chat mode if no args provided
1413
+ return self.cmd_chat_mode(edit_format)
1414
+
1415
+ from aider.coders.base_coder import Coder
1416
+
1417
+ coder = Coder.create(
1418
+ io=self.io,
1419
+ from_coder=self.coder,
1420
+ edit_format=edit_format,
1421
+ summarize_from_coder=False,
1422
+ num_cache_warming_pings=0,
1423
+ )
1424
+
1425
+ user_msg = args
1426
+ coder.run(user_msg)
1427
+
1428
+ # Use the provided placeholder if any
1429
+ raise SwitchCoder(
1430
+ edit_format=self.coder.edit_format,
1431
+ summarize_from_coder=False,
1432
+ from_coder=coder,
1433
+ show_announcements=False,
1434
+ placeholder=placeholder,
1435
+ )
1436
+
1437
+ def get_help_md(self):
1438
+ "Show help about all commands in markdown"
1439
+
1440
+ res = """
1441
+ |Command|Description|
1442
+ |:------|:----------|
1443
+ """
1444
+ commands = sorted(self.get_commands())
1445
+ for cmd in commands:
1446
+ cmd_method_name = f"cmd_{cmd[1:]}".replace("-", "_")
1447
+ cmd_method = getattr(self, cmd_method_name, None)
1448
+ if cmd_method:
1449
+ description = cmd_method.__doc__
1450
+ res += f"| **{cmd}** | {description} |\n"
1451
+ else:
1452
+ res += f"| **{cmd}** | |\n"
1453
+
1454
+ res += "\n"
1455
+ return res
1456
+
1457
+ def cmd_voice(self, args):
1458
+ "Record and transcribe voice input"
1459
+
1460
+ if not self.voice:
1461
+ if "OPENAI_API_KEY" not in os.environ:
1462
+ self.io.tool_error("To use /voice you must provide an OpenAI API key.")
1463
+ return
1464
+ try:
1465
+ self.voice = voice.Voice(
1466
+ audio_format=self.voice_format or "wav", device_name=self.voice_input_device
1467
+ )
1468
+ except voice.SoundDeviceError:
1469
+ self.io.tool_error(
1470
+ "Unable to import `sounddevice` and/or `soundfile`, is portaudio installed?"
1471
+ )
1472
+ return
1473
+
1474
+ try:
1475
+ text = self.voice.record_and_transcribe(None, language=self.voice_language)
1476
+ except litellm.OpenAIError as err:
1477
+ self.io.tool_error(f"Unable to use OpenAI whisper model: {err}")
1478
+ return
1479
+
1480
+ if text:
1481
+ self.io.placeholder = text
1482
+
1483
+ def cmd_paste(self, args):
1484
+ """Paste image/text from the clipboard into the chat.\
1485
+ Optionally provide a name for the image."""
1486
+ try:
1487
+ # Check for image first
1488
+ image = ImageGrab.grabclipboard()
1489
+ if isinstance(image, Image.Image):
1490
+ if args.strip():
1491
+ filename = args.strip()
1492
+ ext = os.path.splitext(filename)[1].lower()
1493
+ if ext in (".jpg", ".jpeg", ".png"):
1494
+ basename = filename
1495
+ else:
1496
+ basename = f"{filename}.png"
1497
+ else:
1498
+ basename = "clipboard_image.png"
1499
+
1500
+ temp_dir = tempfile.mkdtemp()
1501
+ temp_file_path = os.path.join(temp_dir, basename)
1502
+ image_format = "PNG" if basename.lower().endswith(".png") else "JPEG"
1503
+ image.save(temp_file_path, image_format)
1504
+
1505
+ abs_file_path = Path(temp_file_path).resolve()
1506
+
1507
+ # Check if a file with the same name already exists in the chat
1508
+ existing_file = next(
1509
+ (f for f in self.coder.abs_fnames if Path(f).name == abs_file_path.name), None
1510
+ )
1511
+ if existing_file:
1512
+ self.coder.abs_fnames.remove(existing_file)
1513
+ self.io.tool_output(f"Replaced existing image in the chat: {existing_file}")
1514
+
1515
+ self.coder.abs_fnames.add(str(abs_file_path))
1516
+ self.io.tool_output(f"Added clipboard image to the chat: {abs_file_path}")
1517
+ self.coder.check_added_files()
1518
+
1519
+ return
1520
+
1521
+ # If not an image, try to get text
1522
+ text = pyperclip.paste()
1523
+ if text:
1524
+ self.io.tool_output(text)
1525
+ return text
1526
+
1527
+ self.io.tool_error("No image or text content found in clipboard.")
1528
+ return
1529
+
1530
+ except Exception as e:
1531
+ self.io.tool_error(f"Error processing clipboard content: {e}")
1532
+
1533
+ def cmd_read_only(self, args):
1534
+ """Add files to the chat that are for reference only, or turn added files to read-only.
1535
+ With no args, opens a fuzzy finder to select files from the repo.
1536
+ If no files are selected, converts all editable files in chat to read-only.
1537
+ """
1538
+ if not args.strip():
1539
+ if self.coder.repo:
1540
+ all_files = self.coder.repo.get_tracked_files()
1541
+ else:
1542
+ all_files = self.coder.get_all_relative_files()
1543
+
1544
+ if not all_files and not self.coder.abs_fnames:
1545
+ self.io.tool_output("No files in the repo or chat to make read-only.")
1546
+ return
1547
+
1548
+ selected_files = []
1549
+ if all_files:
1550
+ selected_files = run_fzf(all_files, multi=True)
1551
+
1552
+ if not selected_files:
1553
+ # Fallback behavior: convert all editable files to read-only
1554
+ if self.coder.abs_fnames:
1555
+ for fname in list(self.coder.abs_fnames):
1556
+ self.coder.abs_fnames.remove(fname)
1557
+ self.coder.abs_read_only_fnames.add(fname)
1558
+ rel_fname = self.coder.get_rel_fname(fname)
1559
+ self.io.tool_output(f"Converted {rel_fname} to read-only")
1560
+ else:
1561
+ self.io.tool_output("No files selected.")
1562
+ return
1563
+
1564
+ args = " ".join([self.quote_fname(f) for f in selected_files])
1565
+
1566
+ filenames = parse_quoted_filenames(args)
1567
+ all_paths = []
1568
+
1569
+ # First collect all expanded paths
1570
+ for pattern in filenames:
1571
+ expanded_pattern = expanduser(pattern)
1572
+ path_obj = Path(expanded_pattern)
1573
+ is_abs = path_obj.is_absolute()
1574
+ if not is_abs:
1575
+ path_obj = Path(self.coder.root) / path_obj
1576
+
1577
+ matches = []
1578
+ # Check for literal path existence first
1579
+ if path_obj.exists():
1580
+ matches = [path_obj]
1581
+ else:
1582
+ # If literal path doesn't exist, try globbing
1583
+ if is_abs:
1584
+ # For absolute paths, glob it
1585
+ matches = [Path(p) for p in glob.glob(expanded_pattern)]
1586
+ else:
1587
+ # For relative paths and globs, use glob from the root directory
1588
+ matches = list(Path(self.coder.root).glob(expanded_pattern))
1589
+
1590
+ if not matches:
1591
+ self.io.tool_error(f"No matches found for: {pattern}")
1592
+ else:
1593
+ all_paths.extend(matches)
1594
+
1595
+ # Then process them in sorted order
1596
+ for path in sorted(all_paths):
1597
+ abs_path = self.coder.abs_root_path(path)
1598
+ if os.path.isfile(abs_path):
1599
+ self._add_read_only_file(abs_path, path)
1600
+ elif os.path.isdir(abs_path):
1601
+ self._add_read_only_directory(abs_path, path)
1602
+ else:
1603
+ self.io.tool_error(f"Not a file or directory: {abs_path}")
1604
+
1605
+ def _add_read_only_file(self, abs_path, original_name):
1606
+ if is_image_file(original_name) and not self.coder.main_model.info.get("supports_vision"):
1607
+ self.io.tool_error(
1608
+ f"Cannot add image file {original_name} as the"
1609
+ f" {self.coder.main_model.name} does not support images."
1610
+ )
1611
+ return
1612
+
1613
+ if abs_path in self.coder.abs_read_only_fnames:
1614
+ self.io.tool_error(f"{original_name} is already in the chat as a read-only file")
1615
+ return
1616
+ elif abs_path in self.coder.abs_fnames:
1617
+ self.coder.abs_fnames.remove(abs_path)
1618
+ self.coder.abs_read_only_fnames.add(abs_path)
1619
+ self.io.tool_output(
1620
+ f"Moved {original_name} from editable to read-only files in the chat"
1621
+ )
1622
+ else:
1623
+ self.coder.abs_read_only_fnames.add(abs_path)
1624
+ self.io.tool_output(f"Added {original_name} to read-only files.")
1625
+
1626
+ def _add_read_only_directory(self, abs_path, original_name):
1627
+ added_files = 0
1628
+ for root, _, files in os.walk(abs_path):
1629
+ for file in files:
1630
+ file_path = os.path.join(root, file)
1631
+ if (
1632
+ file_path not in self.coder.abs_fnames
1633
+ and file_path not in self.coder.abs_read_only_fnames
1634
+ ):
1635
+ self.coder.abs_read_only_fnames.add(file_path)
1636
+ added_files += 1
1637
+
1638
+ if added_files > 0:
1639
+ self.io.tool_output(
1640
+ f"Added {added_files} files from directory {original_name} to read-only files."
1641
+ )
1642
+ else:
1643
+ self.io.tool_output(f"No new files added from directory {original_name}.")
1644
+
1645
+ def cmd_map(self, args):
1646
+ "Print out the current repository map"
1647
+ repo_map = self.coder.get_repo_map()
1648
+ if repo_map:
1649
+ self.io.tool_output(repo_map)
1650
+ else:
1651
+ self.io.tool_output("No repository map available.")
1652
+
1653
+ def cmd_map_refresh(self, args):
1654
+ "Force a refresh of the repository map"
1655
+ repo_map = self.coder.get_repo_map(force_refresh=True)
1656
+ if repo_map:
1657
+ self.io.tool_output("The repo map has been refreshed, use /map to view it.")
1658
+
1659
+ def cmd_settings(self, args):
1660
+ "Print out the current settings"
1661
+ settings = format_settings(self.parser, self.args)
1662
+ announcements = "\n".join(self.coder.get_announcements())
1663
+
1664
+ # Build metadata for the active models (main, editor, weak)
1665
+ model_sections = []
1666
+ active_models = [
1667
+ ("Main model", self.coder.main_model),
1668
+ ("Editor model", getattr(self.coder.main_model, "editor_model", None)),
1669
+ ("Weak model", getattr(self.coder.main_model, "weak_model", None)),
1670
+ ]
1671
+ for label, model in active_models:
1672
+ if not model:
1673
+ continue
1674
+ info = getattr(model, "info", {}) or {}
1675
+ if not info:
1676
+ continue
1677
+ model_sections.append(f"{label} ({model.name}):")
1678
+ for k, v in sorted(info.items()):
1679
+ model_sections.append(f" {k}: {v}")
1680
+ model_sections.append("") # blank line between models
1681
+
1682
+ model_metadata = "\n".join(model_sections)
1683
+
1684
+ output = f"{announcements}\n{settings}"
1685
+ if model_metadata:
1686
+ output += "\n" + model_metadata
1687
+ self.io.tool_output(output)
1688
+
1689
+ def completions_raw_load(self, document, complete_event):
1690
+ return self.completions_raw_read_only(document, complete_event)
1691
+
1692
+ def cmd_load(self, args):
1693
+ "Load and execute commands from a file"
1694
+ if not args.strip():
1695
+ self.io.tool_error("Please provide a filename containing commands to load.")
1696
+ return
1697
+
1698
+ try:
1699
+ with open(args.strip(), "r", encoding=self.io.encoding, errors="replace") as f:
1700
+ commands = f.readlines()
1701
+ except FileNotFoundError:
1702
+ self.io.tool_error(f"File not found: {args}")
1703
+ return
1704
+ except Exception as e:
1705
+ self.io.tool_error(f"Error reading file: {e}")
1706
+ return
1707
+
1708
+ for cmd in commands:
1709
+ cmd = cmd.strip()
1710
+ if not cmd or cmd.startswith("#"):
1711
+ continue
1712
+
1713
+ self.io.tool_output(f"\nExecuting: {cmd}")
1714
+ try:
1715
+ self.run(cmd)
1716
+ except SwitchCoder:
1717
+ self.io.tool_error(
1718
+ f"Command '{cmd}' is only supported in interactive mode, skipping."
1719
+ )
1720
+
1721
+ def completions_raw_save(self, document, complete_event):
1722
+ return self.completions_raw_read_only(document, complete_event)
1723
+
1724
+ def cmd_save(self, args):
1725
+ "Save commands to a file that can reconstruct the current chat session's files"
1726
+ if not args.strip():
1727
+ self.io.tool_error("Please provide a filename to save the commands to.")
1728
+ return
1729
+
1730
+ try:
1731
+ with open(args.strip(), "w", encoding=self.io.encoding) as f:
1732
+ f.write("/drop\n")
1733
+ # Write commands to add editable files
1734
+ for fname in sorted(self.coder.abs_fnames):
1735
+ rel_fname = self.coder.get_rel_fname(fname)
1736
+ f.write(f"/add {rel_fname}\n")
1737
+
1738
+ # Write commands to add read-only files
1739
+ for fname in sorted(self.coder.abs_read_only_fnames):
1740
+ # Use absolute path for files outside repo root, relative path for files inside
1741
+ if Path(fname).is_relative_to(self.coder.root):
1742
+ rel_fname = self.coder.get_rel_fname(fname)
1743
+ f.write(f"/read-only {rel_fname}\n")
1744
+ else:
1745
+ f.write(f"/read-only {fname}\n")
1746
+
1747
+ self.io.tool_output(f"Saved commands to {args.strip()}")
1748
+ except Exception as e:
1749
+ self.io.tool_error(f"Error saving commands to file: {e}")
1750
+
1751
+ def cmd_multiline_mode(self, args):
1752
+ "Toggle multiline mode (swaps behavior of Enter and Meta+Enter)"
1753
+ self.io.toggle_multiline_mode()
1754
+
1755
+ def cmd_copy(self, args):
1756
+ "Copy the last assistant message to the clipboard"
1757
+ all_messages = self.coder.done_messages + self.coder.cur_messages
1758
+ assistant_messages = [msg for msg in reversed(all_messages) if msg["role"] == "assistant"]
1759
+
1760
+ if not assistant_messages:
1761
+ self.io.tool_error("No assistant messages found to copy.")
1762
+ return
1763
+
1764
+ last_assistant_message = assistant_messages[0]["content"]
1765
+
1766
+ try:
1767
+ pyperclip.copy(last_assistant_message)
1768
+ preview = (
1769
+ last_assistant_message[:50] + "..."
1770
+ if len(last_assistant_message) > 50
1771
+ else last_assistant_message
1772
+ )
1773
+ self.io.tool_output(f"Copied last assistant message to clipboard. Preview: {preview}")
1774
+ except pyperclip.PyperclipException as e:
1775
+ self.io.tool_error(f"Failed to copy to clipboard: {str(e)}")
1776
+ self.io.tool_output(
1777
+ "You may need to install xclip or xsel on Linux, or pbcopy on macOS."
1778
+ )
1779
+ except Exception as e:
1780
+ self.io.tool_error(f"An unexpected error occurred while copying to clipboard: {str(e)}")
1781
+
1782
+ def cmd_report(self, args):
1783
+ "Report a problem by opening a GitHub Issue"
1784
+ from aider.report import report_github_issue
1785
+
1786
+ announcements = "\n".join(self.coder.get_announcements())
1787
+ issue_text = announcements
1788
+
1789
+ if args.strip():
1790
+ title = args.strip()
1791
+ else:
1792
+ title = None
1793
+
1794
+ report_github_issue(issue_text, title=title, confirm=False)
1795
+
1796
+ def cmd_editor(self, initial_content=""):
1797
+ "Open an editor to write a prompt"
1798
+
1799
+ user_input = pipe_editor(initial_content, suffix="md", editor=self.editor)
1800
+ if user_input.strip():
1801
+ self.io.set_placeholder(user_input.rstrip())
1802
+
1803
+ def cmd_edit(self, args=""):
1804
+ "Alias for /editor: Open an editor to write a prompt"
1805
+ return self.cmd_editor(args)
1806
+
1807
+ def cmd_history_search(self, args):
1808
+ "Fuzzy search in history and paste it in the prompt"
1809
+ history_lines = self.io.get_input_history()
1810
+ selected_lines = run_fzf(history_lines)
1811
+ if selected_lines:
1812
+ self.io.set_placeholder("".join(selected_lines))
1813
+
1814
+ def cmd_think_tokens(self, args):
1815
+ """Set the thinking token budget, eg: 8096, 8k, 10.5k, 0.5M, or 0 to disable."""
1816
+ model = self.coder.main_model
1817
+
1818
+ if not args.strip():
1819
+ # Display current value if no args are provided
1820
+ formatted_budget = model.get_thinking_tokens()
1821
+ if formatted_budget is None:
1822
+ self.io.tool_output("Thinking tokens are not currently set.")
1823
+ else:
1824
+ budget = model.get_raw_thinking_tokens()
1825
+ self.io.tool_output(
1826
+ f"Current thinking token budget: {budget:,} tokens ({formatted_budget})."
1827
+ )
1828
+ return
1829
+
1830
+ value = args.strip()
1831
+ model.set_thinking_tokens(value)
1832
+
1833
+ # Handle the special case of 0 to disable thinking tokens
1834
+ if value == "0":
1835
+ self.io.tool_output("Thinking tokens disabled.")
1836
+ else:
1837
+ formatted_budget = model.get_thinking_tokens()
1838
+ budget = model.get_raw_thinking_tokens()
1839
+ self.io.tool_output(
1840
+ f"Set thinking token budget to {budget:,} tokens ({formatted_budget})."
1841
+ )
1842
+
1843
+ self.io.tool_output()
1844
+
1845
+ # Output announcements
1846
+ announcements = "\n".join(self.coder.get_announcements())
1847
+ self.io.tool_output(announcements)
1848
+
1849
+ def cmd_reasoning_effort(self, args):
1850
+ "Set the reasoning effort level (values: number or low/medium/high depending on model)"
1851
+ model = self.coder.main_model
1852
+
1853
+ if not args.strip():
1854
+ # Display current value if no args are provided
1855
+ reasoning_value = model.get_reasoning_effort()
1856
+ if reasoning_value is None:
1857
+ self.io.tool_output("Reasoning effort is not currently set.")
1858
+ else:
1859
+ self.io.tool_output(f"Current reasoning effort: {reasoning_value}")
1860
+ return
1861
+
1862
+ value = args.strip()
1863
+ model.set_reasoning_effort(value)
1864
+ reasoning_value = model.get_reasoning_effort()
1865
+ self.io.tool_output(f"Set reasoning effort to {reasoning_value}")
1866
+ self.io.tool_output()
1867
+
1868
+ # Output announcements
1869
+ announcements = "\n".join(self.coder.get_announcements())
1870
+ self.io.tool_output(announcements)
1871
+
1872
+ def cmd_copy_context(self, args=None):
1873
+ """Copy the current chat context as markdown, suitable to paste into a web UI"""
1874
+
1875
+ chunks = self.coder.format_chat_chunks()
1876
+
1877
+ markdown = ""
1878
+
1879
+ # Only include specified chunks in order
1880
+ for messages in [chunks.repo, chunks.readonly_files, chunks.chat_files]:
1881
+ for msg in messages:
1882
+ # Only include user messages
1883
+ if msg["role"] != "user":
1884
+ continue
1885
+
1886
+ content = msg["content"]
1887
+
1888
+ # Handle image/multipart content
1889
+ if isinstance(content, list):
1890
+ for part in content:
1891
+ if part.get("type") == "text":
1892
+ markdown += part["text"] + "\n\n"
1893
+ else:
1894
+ markdown += content + "\n\n"
1895
+
1896
+ args = args or ""
1897
+ markdown += f"""
1898
+ Just tell me how to edit the files to make the changes.
1899
+ Don't give me back entire files.
1900
+ Just show me the edits I need to make.
1901
+
1902
+ {args}
1903
+ """
1904
+
1905
+ try:
1906
+ pyperclip.copy(markdown)
1907
+ self.io.tool_output("Copied code context to clipboard.")
1908
+ except pyperclip.PyperclipException as e:
1909
+ self.io.tool_error(f"Failed to copy to clipboard: {str(e)}")
1910
+ self.io.tool_output(
1911
+ "You may need to install xclip or xsel on Linux, or pbcopy on macOS."
1912
+ )
1913
+ except Exception as e:
1914
+ self.io.tool_error(f"An unexpected error occurred while copying to clipboard: {str(e)}")
1915
+
1916
+
1917
+ def expand_subdir(file_path):
1918
+ if file_path.is_file():
1919
+ yield file_path
1920
+ return
1921
+
1922
+ if file_path.is_dir():
1923
+ for file in file_path.rglob("*"):
1924
+ if file.is_file():
1925
+ yield file
1926
+
1927
+
1928
+ def parse_quoted_filenames(args):
1929
+ filenames = re.findall(r"\"(.+?)\"|(\S+)", args)
1930
+ filenames = [name for sublist in filenames for name in sublist if name]
1931
+ return filenames
1932
+
1933
+
1934
+ def get_help_md():
1935
+ md = Commands(None, None).get_help_md()
1936
+ return md
1937
+
1938
+
1939
+ def main():
1940
+ md = get_help_md()
1941
+ print(md)
1942
+
1943
+
1944
+ if __name__ == "__main__":
1945
+ status = main()
1946
+ sys.exit(status)