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