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