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