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