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/io.py ADDED
@@ -0,0 +1,1191 @@
1
+ import base64
2
+ import functools
3
+ import os
4
+ import shutil
5
+ import signal
6
+ import subprocess
7
+ import time
8
+ import webbrowser
9
+ from collections import defaultdict
10
+ from dataclasses import dataclass
11
+ from datetime import datetime
12
+ from io import StringIO
13
+ from pathlib import Path
14
+
15
+ from prompt_toolkit.completion import Completer, Completion, ThreadedCompleter
16
+ from prompt_toolkit.cursor_shapes import ModalCursorShapeConfig
17
+ from prompt_toolkit.enums import EditingMode
18
+ from prompt_toolkit.filters import Condition, is_searching
19
+ from prompt_toolkit.history import FileHistory
20
+ from prompt_toolkit.key_binding import KeyBindings
21
+ from prompt_toolkit.key_binding.vi_state import InputMode
22
+ from prompt_toolkit.keys import Keys
23
+ from prompt_toolkit.lexers import PygmentsLexer
24
+ from prompt_toolkit.output.vt100 import is_dumb_terminal
25
+ from prompt_toolkit.shortcuts import CompleteStyle, PromptSession
26
+ from prompt_toolkit.styles import Style
27
+ from pygments.lexers import MarkdownLexer, guess_lexer_for_filename
28
+ from pygments.token import Token
29
+ from rich.color import ColorParseError
30
+ from rich.columns import Columns
31
+ from rich.console import Console
32
+ from rich.markdown import Markdown
33
+ from rich.style import Style as RichStyle
34
+ from rich.text import Text
35
+
36
+ from patch.mdstream import MarkdownStream
37
+
38
+ from .dump import dump # noqa: F401
39
+ from .editor import pipe_editor
40
+ from .utils import is_image_file
41
+
42
+ # Constants
43
+ NOTIFICATION_MESSAGE = "Patch is waiting for your input"
44
+
45
+
46
+ def ensure_hash_prefix(color):
47
+ """Ensure hex color values have a # prefix."""
48
+ if not color:
49
+ return color
50
+ if isinstance(color, str) and color.strip() and not color.startswith("#"):
51
+ # Check if it's a valid hex color (3 or 6 hex digits)
52
+ if all(c in "0123456789ABCDEFabcdef" for c in color) and len(color) in (3, 6):
53
+ return f"#{color}"
54
+ return color
55
+
56
+
57
+ def restore_multiline(func):
58
+ """Decorator to restore multiline mode after function execution"""
59
+
60
+ @functools.wraps(func)
61
+ def wrapper(self, *args, **kwargs):
62
+ orig_multiline = self.multiline_mode
63
+ self.multiline_mode = False
64
+ try:
65
+ return func(self, *args, **kwargs)
66
+ except Exception:
67
+ raise
68
+ finally:
69
+ self.multiline_mode = orig_multiline
70
+
71
+ return wrapper
72
+
73
+
74
+ class CommandCompletionException(Exception):
75
+ """Raised when a command should use the normal autocompleter instead of
76
+ command-specific completion."""
77
+
78
+ pass
79
+
80
+
81
+ @dataclass
82
+ class ConfirmGroup:
83
+ preference: str = None
84
+ show_group: bool = True
85
+
86
+ def __init__(self, items=None):
87
+ if items is not None:
88
+ self.show_group = len(items) > 1
89
+
90
+
91
+ class AutoCompleter(Completer):
92
+ def __init__(
93
+ self, root, rel_fnames, addable_rel_fnames, commands, encoding, abs_read_only_fnames=None
94
+ ):
95
+ self.addable_rel_fnames = addable_rel_fnames
96
+ self.rel_fnames = rel_fnames
97
+ self.encoding = encoding
98
+ self.abs_read_only_fnames = abs_read_only_fnames or []
99
+
100
+ fname_to_rel_fnames = defaultdict(list)
101
+ for rel_fname in addable_rel_fnames:
102
+ fname = os.path.basename(rel_fname)
103
+ if fname != rel_fname:
104
+ fname_to_rel_fnames[fname].append(rel_fname)
105
+ self.fname_to_rel_fnames = fname_to_rel_fnames
106
+
107
+ self.words = set()
108
+
109
+ self.commands = commands
110
+ self.command_completions = dict()
111
+ if commands:
112
+ self.command_names = self.commands.get_commands()
113
+
114
+ for rel_fname in addable_rel_fnames:
115
+ self.words.add(rel_fname)
116
+
117
+ for rel_fname in rel_fnames:
118
+ self.words.add(rel_fname)
119
+
120
+ all_fnames = [Path(root) / rel_fname for rel_fname in rel_fnames]
121
+ if abs_read_only_fnames:
122
+ all_fnames.extend(abs_read_only_fnames)
123
+
124
+ self.all_fnames = all_fnames
125
+ self.tokenized = False
126
+
127
+ def tokenize(self):
128
+ if self.tokenized:
129
+ return
130
+ self.tokenized = True
131
+
132
+ for fname in self.all_fnames:
133
+ try:
134
+ with open(fname, "r", encoding=self.encoding) as f:
135
+ content = f.read()
136
+ except (FileNotFoundError, UnicodeDecodeError, IsADirectoryError):
137
+ continue
138
+ try:
139
+ lexer = guess_lexer_for_filename(fname, content)
140
+ except Exception: # On Windows, bad ref to time.clock which is deprecated
141
+ continue
142
+
143
+ tokens = list(lexer.get_tokens(content))
144
+ self.words.update(
145
+ (token[1], f"`{token[1]}`") for token in tokens if token[0] in Token.Name
146
+ )
147
+
148
+ def get_command_completions(self, document, complete_event, text, words):
149
+ if len(words) == 1 and not text[-1].isspace():
150
+ partial = words[0].lower()
151
+ candidates = [cmd for cmd in self.command_names if cmd.startswith(partial)]
152
+ for candidate in sorted(candidates):
153
+ yield Completion(candidate, start_position=-len(words[-1]))
154
+ return
155
+
156
+ if len(words) <= 1 or text[-1].isspace():
157
+ return
158
+
159
+ cmd = words[0]
160
+ partial = words[-1].lower()
161
+
162
+ matches, _, _ = self.commands.matching_commands(cmd)
163
+ if len(matches) == 1:
164
+ cmd = matches[0]
165
+ elif cmd not in matches:
166
+ return
167
+
168
+ raw_completer = self.commands.get_raw_completions(cmd)
169
+ if raw_completer:
170
+ yield from raw_completer(document, complete_event)
171
+ return
172
+
173
+ if cmd not in self.command_completions:
174
+ candidates = self.commands.get_completions(cmd)
175
+ self.command_completions[cmd] = candidates
176
+ else:
177
+ candidates = self.command_completions[cmd]
178
+
179
+ if candidates is None:
180
+ return
181
+
182
+ candidates = [word for word in candidates if partial in word.lower()]
183
+ for candidate in sorted(candidates):
184
+ yield Completion(candidate, start_position=-len(words[-1]))
185
+
186
+ def get_completions(self, document, complete_event):
187
+ self.tokenize()
188
+
189
+ text = document.text_before_cursor
190
+ words = text.split()
191
+ if not words:
192
+ return
193
+
194
+ if text and text[-1].isspace():
195
+ # don't keep completing after a space
196
+ return
197
+
198
+ if text[0] == "/":
199
+ try:
200
+ yield from self.get_command_completions(document, complete_event, text, words)
201
+ return
202
+ except CommandCompletionException:
203
+ # Fall through to normal completion
204
+ pass
205
+
206
+ candidates = self.words
207
+ candidates.update(set(self.fname_to_rel_fnames))
208
+ candidates = [word if type(word) is tuple else (word, word) for word in candidates]
209
+
210
+ last_word = words[-1]
211
+
212
+ # Only provide completions if the user has typed at least 3 characters
213
+ if len(last_word) < 3:
214
+ return
215
+
216
+ completions = []
217
+ for word_match, word_insert in candidates:
218
+ if word_match.lower().startswith(last_word.lower()):
219
+ completions.append((word_insert, -len(last_word), word_match))
220
+
221
+ rel_fnames = self.fname_to_rel_fnames.get(word_match, [])
222
+ if rel_fnames:
223
+ for rel_fname in rel_fnames:
224
+ completions.append((rel_fname, -len(last_word), rel_fname))
225
+
226
+ for ins, pos, match in sorted(completions):
227
+ yield Completion(ins, start_position=pos, display=match)
228
+
229
+
230
+ class InputOutput:
231
+ num_error_outputs = 0
232
+ num_user_asks = 0
233
+ clipboard_watcher = None
234
+ bell_on_next_input = False
235
+ notifications_command = None
236
+
237
+ def __init__(
238
+ self,
239
+ pretty=True,
240
+ yes=None,
241
+ input_history_file=None,
242
+ chat_history_file=None,
243
+ input=None,
244
+ output=None,
245
+ user_input_color="blue",
246
+ tool_output_color=None,
247
+ tool_error_color="red",
248
+ tool_warning_color="#FFA500",
249
+ assistant_output_color="blue",
250
+ completion_menu_color=None,
251
+ completion_menu_bg_color=None,
252
+ completion_menu_current_color=None,
253
+ completion_menu_current_bg_color=None,
254
+ code_theme="default",
255
+ encoding="utf-8",
256
+ line_endings="platform",
257
+ dry_run=False,
258
+ llm_history_file=None,
259
+ editingmode=EditingMode.EMACS,
260
+ fancy_input=True,
261
+ file_watcher=None,
262
+ multiline_mode=False,
263
+ root=".",
264
+ notifications=False,
265
+ notifications_command=None,
266
+ ):
267
+ self.placeholder = None
268
+ self.interrupted = False
269
+ self.never_prompts = set()
270
+ self.editingmode = editingmode
271
+ self.multiline_mode = multiline_mode
272
+ self.bell_on_next_input = False
273
+ self.notifications = notifications
274
+ if notifications and notifications_command is None:
275
+ self.notifications_command = self.get_default_notification_command()
276
+ else:
277
+ self.notifications_command = notifications_command
278
+
279
+ no_color = os.environ.get("NO_COLOR")
280
+ if no_color is not None and no_color != "":
281
+ pretty = False
282
+
283
+ self.user_input_color = ensure_hash_prefix(user_input_color) if pretty else None
284
+ self.tool_output_color = ensure_hash_prefix(tool_output_color) if pretty else None
285
+ self.tool_error_color = ensure_hash_prefix(tool_error_color) if pretty else None
286
+ self.tool_warning_color = ensure_hash_prefix(tool_warning_color) if pretty else None
287
+ self.assistant_output_color = ensure_hash_prefix(assistant_output_color)
288
+ self.completion_menu_color = ensure_hash_prefix(completion_menu_color) if pretty else None
289
+ self.completion_menu_bg_color = (
290
+ ensure_hash_prefix(completion_menu_bg_color) if pretty else None
291
+ )
292
+ self.completion_menu_current_color = (
293
+ ensure_hash_prefix(completion_menu_current_color) if pretty else None
294
+ )
295
+ self.completion_menu_current_bg_color = (
296
+ ensure_hash_prefix(completion_menu_current_bg_color) if pretty else None
297
+ )
298
+
299
+ self.code_theme = code_theme
300
+
301
+ self.input = input
302
+ self.output = output
303
+
304
+ self.pretty = pretty
305
+ if self.output:
306
+ self.pretty = False
307
+
308
+ self.yes = yes
309
+
310
+ self.input_history_file = input_history_file
311
+ if self.input_history_file:
312
+ try:
313
+ Path(self.input_history_file).parent.mkdir(parents=True, exist_ok=True)
314
+ except (PermissionError, OSError) as e:
315
+ self.tool_warning(f"Could not create directory for input history: {e}")
316
+ self.input_history_file = None
317
+ self.llm_history_file = llm_history_file
318
+ if chat_history_file is not None:
319
+ self.chat_history_file = Path(chat_history_file)
320
+ else:
321
+ self.chat_history_file = None
322
+
323
+ self.encoding = encoding
324
+ valid_line_endings = {"platform", "lf", "crlf"}
325
+ if line_endings not in valid_line_endings:
326
+ raise ValueError(
327
+ f"Invalid line_endings value: {line_endings}. "
328
+ f"Must be one of: {', '.join(valid_line_endings)}"
329
+ )
330
+ self.newline = (
331
+ None if line_endings == "platform" else "\n" if line_endings == "lf" else "\r\n"
332
+ )
333
+ self.dry_run = dry_run
334
+
335
+ current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
336
+ self.append_chat_history(f"\n# patch chat started at {current_time}\n\n")
337
+
338
+ self.prompt_session = None
339
+ self.is_dumb_terminal = is_dumb_terminal()
340
+
341
+ if self.is_dumb_terminal:
342
+ self.pretty = False
343
+ fancy_input = False
344
+
345
+ if fancy_input:
346
+ # Initialize PromptSession only if we have a capable terminal
347
+ session_kwargs = {
348
+ "input": self.input,
349
+ "output": self.output,
350
+ "lexer": PygmentsLexer(MarkdownLexer),
351
+ "editing_mode": self.editingmode,
352
+ }
353
+ if self.editingmode == EditingMode.VI:
354
+ session_kwargs["cursor"] = ModalCursorShapeConfig()
355
+ if self.input_history_file is not None:
356
+ session_kwargs["history"] = FileHistory(self.input_history_file)
357
+ try:
358
+ self.prompt_session = PromptSession(**session_kwargs)
359
+ self.console = Console() # pretty console
360
+ except Exception as err:
361
+ self.console = Console(force_terminal=False, no_color=True)
362
+ self.tool_error(f"Can't initialize prompt toolkit: {err}") # non-pretty
363
+ else:
364
+ self.console = Console(force_terminal=False, no_color=True) # non-pretty
365
+ if self.is_dumb_terminal:
366
+ self.tool_output("Detected dumb terminal, disabling fancy input and pretty output.")
367
+
368
+ self.file_watcher = file_watcher
369
+ self.root = root
370
+
371
+ # Validate color settings after console is initialized
372
+ self._validate_color_settings()
373
+
374
+ def _validate_color_settings(self):
375
+ """Validate configured color strings and reset invalid ones."""
376
+ color_attributes = [
377
+ "user_input_color",
378
+ "tool_output_color",
379
+ "tool_error_color",
380
+ "tool_warning_color",
381
+ "assistant_output_color",
382
+ "completion_menu_color",
383
+ "completion_menu_bg_color",
384
+ "completion_menu_current_color",
385
+ "completion_menu_current_bg_color",
386
+ ]
387
+ for attr_name in color_attributes:
388
+ color_value = getattr(self, attr_name, None)
389
+ if color_value:
390
+ try:
391
+ # Try creating a style to validate the color
392
+ RichStyle(color=color_value)
393
+ except ColorParseError as e:
394
+ self.console.print(
395
+ "[bold red]Warning:[/bold red] Invalid configuration for"
396
+ f" {attr_name}: '{color_value}'. {e}. Disabling this color."
397
+ )
398
+ setattr(self, attr_name, None) # Reset invalid color to None
399
+
400
+ def _get_style(self):
401
+ style_dict = {}
402
+ if not self.pretty:
403
+ return Style.from_dict(style_dict)
404
+
405
+ if self.user_input_color:
406
+ style_dict.setdefault("", self.user_input_color)
407
+ style_dict.update(
408
+ {
409
+ "pygments.literal.string": f"bold italic {self.user_input_color}",
410
+ }
411
+ )
412
+
413
+ # Conditionally add 'completion-menu' style
414
+ completion_menu_style = []
415
+ if self.completion_menu_bg_color:
416
+ completion_menu_style.append(f"bg:{self.completion_menu_bg_color}")
417
+ if self.completion_menu_color:
418
+ completion_menu_style.append(self.completion_menu_color)
419
+ if completion_menu_style:
420
+ style_dict["completion-menu"] = " ".join(completion_menu_style)
421
+
422
+ # Conditionally add 'completion-menu.completion.current' style
423
+ completion_menu_current_style = []
424
+ if self.completion_menu_current_bg_color:
425
+ completion_menu_current_style.append(self.completion_menu_current_bg_color)
426
+ if self.completion_menu_current_color:
427
+ completion_menu_current_style.append(f"bg:{self.completion_menu_current_color}")
428
+ if completion_menu_current_style:
429
+ style_dict["completion-menu.completion.current"] = " ".join(
430
+ completion_menu_current_style
431
+ )
432
+
433
+ return Style.from_dict(style_dict)
434
+
435
+ def read_image(self, filename):
436
+ try:
437
+ with open(str(filename), "rb") as image_file:
438
+ encoded_string = base64.b64encode(image_file.read())
439
+ return encoded_string.decode("utf-8")
440
+ except OSError as err:
441
+ self.tool_error(f"{filename}: unable to read: {err}")
442
+ return
443
+ except FileNotFoundError:
444
+ self.tool_error(f"{filename}: file not found error")
445
+ return
446
+ except IsADirectoryError:
447
+ self.tool_error(f"{filename}: is a directory")
448
+ return
449
+ except Exception as e:
450
+ self.tool_error(f"{filename}: {e}")
451
+ return
452
+
453
+ def read_text(self, filename, silent=False):
454
+ if is_image_file(filename):
455
+ return self.read_image(filename)
456
+
457
+ try:
458
+ with open(str(filename), "r", encoding=self.encoding) as f:
459
+ return f.read()
460
+ except FileNotFoundError:
461
+ if not silent:
462
+ self.tool_error(f"{filename}: file not found error")
463
+ return
464
+ except IsADirectoryError:
465
+ if not silent:
466
+ self.tool_error(f"{filename}: is a directory")
467
+ return
468
+ except OSError as err:
469
+ if not silent:
470
+ self.tool_error(f"{filename}: unable to read: {err}")
471
+ return
472
+ except UnicodeError as e:
473
+ if not silent:
474
+ self.tool_error(f"{filename}: {e}")
475
+ self.tool_error("Use --encoding to set the unicode encoding.")
476
+ return
477
+
478
+ def write_text(self, filename, content, max_retries=5, initial_delay=0.1):
479
+ """
480
+ Writes content to a file, retrying with progressive backoff if the file is locked.
481
+
482
+ :param filename: Path to the file to write.
483
+ :param content: Content to write to the file.
484
+ :param max_retries: Maximum number of retries if a file lock is encountered.
485
+ :param initial_delay: Initial delay (in seconds) before the first retry.
486
+ """
487
+ if self.dry_run:
488
+ return
489
+
490
+ delay = initial_delay
491
+ for attempt in range(max_retries):
492
+ try:
493
+ with open(str(filename), "w", encoding=self.encoding, newline=self.newline) as f:
494
+ f.write(content)
495
+ return # Successfully wrote the file
496
+ except PermissionError as err:
497
+ if attempt < max_retries - 1:
498
+ time.sleep(delay)
499
+ delay *= 2 # Exponential backoff
500
+ else:
501
+ self.tool_error(
502
+ f"Unable to write file {filename} after {max_retries} attempts: {err}"
503
+ )
504
+ raise
505
+ except OSError as err:
506
+ self.tool_error(f"Unable to write file {filename}: {err}")
507
+ raise
508
+
509
+ def rule(self):
510
+ if self.pretty:
511
+ style = dict(style=self.user_input_color) if self.user_input_color else dict()
512
+ self.console.rule(**style)
513
+ else:
514
+ print()
515
+
516
+ def interrupt_input(self):
517
+ if self.prompt_session and self.prompt_session.app:
518
+ # Store any partial input before interrupting
519
+ self.placeholder = self.prompt_session.app.current_buffer.text
520
+ self.interrupted = True
521
+ self.prompt_session.app.exit()
522
+
523
+ def get_input(
524
+ self,
525
+ root,
526
+ rel_fnames,
527
+ addable_rel_fnames,
528
+ commands,
529
+ abs_read_only_fnames=None,
530
+ edit_format=None,
531
+ ):
532
+ self.rule()
533
+
534
+ # Ring the bell if needed
535
+ self.ring_bell()
536
+
537
+ rel_fnames = list(rel_fnames)
538
+ show = ""
539
+ if rel_fnames:
540
+ rel_read_only_fnames = [
541
+ get_rel_fname(fname, root) for fname in (abs_read_only_fnames or [])
542
+ ]
543
+ show = self.format_files_for_input(rel_fnames, rel_read_only_fnames)
544
+
545
+ prompt_prefix = ""
546
+ if edit_format:
547
+ prompt_prefix += edit_format
548
+ if self.multiline_mode:
549
+ prompt_prefix += (" " if edit_format else "") + "multi"
550
+ prompt_prefix += "> "
551
+
552
+ show += prompt_prefix
553
+ self.prompt_prefix = prompt_prefix
554
+
555
+ inp = ""
556
+ multiline_input = False
557
+
558
+ style = self._get_style()
559
+
560
+ completer_instance = ThreadedCompleter(
561
+ AutoCompleter(
562
+ root,
563
+ rel_fnames,
564
+ addable_rel_fnames,
565
+ commands,
566
+ self.encoding,
567
+ abs_read_only_fnames=abs_read_only_fnames,
568
+ )
569
+ )
570
+
571
+ def suspend_to_bg(event):
572
+ """Suspend currently running application."""
573
+ event.app.suspend_to_background()
574
+
575
+ kb = KeyBindings()
576
+
577
+ @kb.add(Keys.ControlZ, filter=Condition(lambda: hasattr(signal, "SIGTSTP")))
578
+ def _(event):
579
+ "Suspend to background with ctrl-z"
580
+ suspend_to_bg(event)
581
+
582
+ @kb.add("c-space")
583
+ def _(event):
584
+ "Ignore Ctrl when pressing space bar"
585
+ event.current_buffer.insert_text(" ")
586
+
587
+ @kb.add("c-up")
588
+ def _(event):
589
+ "Navigate backward through history"
590
+ event.current_buffer.history_backward()
591
+
592
+ @kb.add("c-down")
593
+ def _(event):
594
+ "Navigate forward through history"
595
+ event.current_buffer.history_forward()
596
+
597
+ @kb.add("c-x", "c-e")
598
+ def _(event):
599
+ "Edit current input in external editor (like Bash)"
600
+ buffer = event.current_buffer
601
+ current_text = buffer.text
602
+
603
+ # Open the editor with the current text
604
+ edited_text = pipe_editor(input_data=current_text, suffix="md")
605
+
606
+ # Replace the buffer with the edited text, strip any trailing newlines
607
+ buffer.text = edited_text.rstrip("\n")
608
+
609
+ # Move cursor to the end of the text
610
+ buffer.cursor_position = len(buffer.text)
611
+
612
+ @kb.add("enter", eager=True, filter=~is_searching)
613
+ def _(event):
614
+ "Handle Enter key press"
615
+ if self.multiline_mode and not (
616
+ self.editingmode == EditingMode.VI
617
+ and event.app.vi_state.input_mode == InputMode.NAVIGATION
618
+ ):
619
+ # In multiline mode and if not in vi-mode or vi navigation/normal mode,
620
+ # Enter adds a newline
621
+ event.current_buffer.insert_text("\n")
622
+ else:
623
+ # In normal mode, Enter submits
624
+ event.current_buffer.validate_and_handle()
625
+
626
+ @kb.add("escape", "enter", eager=True, filter=~is_searching) # This is Alt+Enter
627
+ def _(event):
628
+ "Handle Alt+Enter key press"
629
+ if self.multiline_mode:
630
+ # In multiline mode, Alt+Enter submits
631
+ event.current_buffer.validate_and_handle()
632
+ else:
633
+ # In normal mode, Alt+Enter adds a newline
634
+ event.current_buffer.insert_text("\n")
635
+
636
+ while True:
637
+ if multiline_input:
638
+ show = self.prompt_prefix
639
+
640
+ try:
641
+ if self.prompt_session:
642
+ # Use placeholder if set, then clear it
643
+ default = self.placeholder or ""
644
+ self.placeholder = None
645
+
646
+ self.interrupted = False
647
+ if not multiline_input:
648
+ if self.file_watcher:
649
+ self.file_watcher.start()
650
+ if self.clipboard_watcher:
651
+ self.clipboard_watcher.start()
652
+
653
+ def get_continuation(width, line_number, is_soft_wrap):
654
+ return self.prompt_prefix
655
+
656
+ line = self.prompt_session.prompt(
657
+ show,
658
+ default=default,
659
+ completer=completer_instance,
660
+ reserve_space_for_menu=4,
661
+ complete_style=CompleteStyle.MULTI_COLUMN,
662
+ style=style,
663
+ key_bindings=kb,
664
+ complete_while_typing=True,
665
+ prompt_continuation=get_continuation,
666
+ )
667
+ else:
668
+ line = input(show)
669
+
670
+ # Check if we were interrupted by a file change
671
+ if self.interrupted:
672
+ line = line or ""
673
+ if self.file_watcher:
674
+ cmd = self.file_watcher.process_changes()
675
+ return cmd
676
+
677
+ except EOFError:
678
+ raise
679
+ except Exception as err:
680
+ import traceback
681
+
682
+ self.tool_error(str(err))
683
+ self.tool_error(traceback.format_exc())
684
+ return ""
685
+ except UnicodeEncodeError as err:
686
+ self.tool_error(str(err))
687
+ return ""
688
+ finally:
689
+ if self.file_watcher:
690
+ self.file_watcher.stop()
691
+ if self.clipboard_watcher:
692
+ self.clipboard_watcher.stop()
693
+
694
+ if line.strip("\r\n") and not multiline_input:
695
+ stripped = line.strip("\r\n")
696
+ if stripped == "{":
697
+ multiline_input = True
698
+ multiline_tag = None
699
+ inp += ""
700
+ elif stripped[0] == "{":
701
+ # Extract tag if it exists (only alphanumeric chars)
702
+ tag = "".join(c for c in stripped[1:] if c.isalnum())
703
+ if stripped == "{" + tag:
704
+ multiline_input = True
705
+ multiline_tag = tag
706
+ inp += ""
707
+ else:
708
+ inp = line
709
+ break
710
+ else:
711
+ inp = line
712
+ break
713
+ continue
714
+ elif multiline_input and line.strip():
715
+ if multiline_tag:
716
+ # Check if line is exactly "tag}"
717
+ if line.strip("\r\n") == f"{multiline_tag}}}":
718
+ break
719
+ else:
720
+ inp += line + "\n"
721
+ # Check if line is exactly "}"
722
+ elif line.strip("\r\n") == "}":
723
+ break
724
+ else:
725
+ inp += line + "\n"
726
+ elif multiline_input:
727
+ inp += line + "\n"
728
+ else:
729
+ inp = line
730
+ break
731
+
732
+ print()
733
+ self.user_input(inp)
734
+ return inp
735
+
736
+ def add_to_input_history(self, inp):
737
+ if not self.input_history_file:
738
+ return
739
+ try:
740
+ FileHistory(self.input_history_file).append_string(inp)
741
+ # Also add to the in-memory history if it exists
742
+ if self.prompt_session and self.prompt_session.history:
743
+ self.prompt_session.history.append_string(inp)
744
+ except OSError as err:
745
+ self.tool_warning(f"Unable to write to input history file: {err}")
746
+
747
+ def get_input_history(self):
748
+ if not self.input_history_file:
749
+ return []
750
+
751
+ fh = FileHistory(self.input_history_file)
752
+ return fh.load_history_strings()
753
+
754
+ def log_llm_history(self, role, content):
755
+ if not self.llm_history_file:
756
+ return
757
+ timestamp = datetime.now().isoformat(timespec="seconds")
758
+ try:
759
+ Path(self.llm_history_file).parent.mkdir(parents=True, exist_ok=True)
760
+ with open(self.llm_history_file, "a", encoding="utf-8") as log_file:
761
+ log_file.write(f"{role.upper()} {timestamp}\n")
762
+ log_file.write(content + "\n")
763
+ except (PermissionError, OSError) as err:
764
+ self.tool_warning(f"Unable to write to llm history file {self.llm_history_file}: {err}")
765
+ self.llm_history_file = None
766
+
767
+ def display_user_input(self, inp):
768
+ if self.pretty and self.user_input_color:
769
+ style = dict(style=self.user_input_color)
770
+ else:
771
+ style = dict()
772
+
773
+ self.console.print(Text(inp), **style)
774
+
775
+ def user_input(self, inp, log_only=True):
776
+ if not log_only:
777
+ self.display_user_input(inp)
778
+
779
+ prefix = "####"
780
+ if inp:
781
+ hist = inp.splitlines()
782
+ else:
783
+ hist = ["<blank>"]
784
+
785
+ hist = f" \n{prefix} ".join(hist)
786
+
787
+ hist = f"""
788
+ {prefix} {hist}"""
789
+ self.append_chat_history(hist, linebreak=True)
790
+
791
+ # OUTPUT
792
+
793
+ def ai_output(self, content):
794
+ hist = "\n" + content.strip() + "\n\n"
795
+ self.append_chat_history(hist)
796
+
797
+ def offer_url(self, url, prompt="Open URL for more info?", allow_never=True):
798
+ """Offer to open a URL in the browser, returns True if opened."""
799
+ if url in self.never_prompts:
800
+ return False
801
+ if self.confirm_ask(prompt, subject=url, allow_never=allow_never):
802
+ webbrowser.open(url)
803
+ return True
804
+ return False
805
+
806
+ @restore_multiline
807
+ def confirm_ask(
808
+ self,
809
+ question,
810
+ default="y",
811
+ subject=None,
812
+ explicit_yes_required=False,
813
+ group=None,
814
+ allow_never=False,
815
+ ):
816
+ self.num_user_asks += 1
817
+
818
+ # Ring the bell if needed
819
+ self.ring_bell()
820
+
821
+ question_id = (question, subject)
822
+
823
+ if question_id in self.never_prompts:
824
+ return False
825
+
826
+ if group and not group.show_group:
827
+ group = None
828
+ if group:
829
+ allow_never = True
830
+
831
+ valid_responses = ["yes", "no", "skip", "all"]
832
+ options = " (Y)es/(N)o"
833
+ if group:
834
+ if not explicit_yes_required:
835
+ options += "/(A)ll"
836
+ options += "/(S)kip all"
837
+ if allow_never:
838
+ options += "/(D)on't ask again"
839
+ valid_responses.append("don't")
840
+
841
+ if default.lower().startswith("y"):
842
+ question += options + " [Yes]: "
843
+ elif default.lower().startswith("n"):
844
+ question += options + " [No]: "
845
+ else:
846
+ question += options + f" [{default}]: "
847
+
848
+ if subject:
849
+ self.tool_output()
850
+ if "\n" in subject:
851
+ lines = subject.splitlines()
852
+ max_length = max(len(line) for line in lines)
853
+ padded_lines = [line.ljust(max_length) for line in lines]
854
+ padded_subject = "\n".join(padded_lines)
855
+ self.tool_output(padded_subject, bold=True)
856
+ else:
857
+ self.tool_output(subject, bold=True)
858
+
859
+ style = self._get_style()
860
+
861
+ def is_valid_response(text):
862
+ if not text:
863
+ return True
864
+ return text.lower() in valid_responses
865
+
866
+ if self.yes is True:
867
+ res = "n" if explicit_yes_required else "y"
868
+ elif self.yes is False:
869
+ res = "n"
870
+ elif group and group.preference:
871
+ res = group.preference
872
+ self.user_input(f"{question}{res}", log_only=False)
873
+ else:
874
+ while True:
875
+ try:
876
+ if self.prompt_session:
877
+ res = self.prompt_session.prompt(
878
+ question,
879
+ style=style,
880
+ complete_while_typing=False,
881
+ )
882
+ else:
883
+ res = input(question)
884
+ except EOFError:
885
+ # Treat EOF (Ctrl+D) as if the user pressed Enter
886
+ res = default
887
+ break
888
+
889
+ if not res:
890
+ res = default
891
+ break
892
+ res = res.lower()
893
+ good = any(valid_response.startswith(res) for valid_response in valid_responses)
894
+ if good:
895
+ break
896
+
897
+ error_message = f"Please answer with one of: {', '.join(valid_responses)}"
898
+ self.tool_error(error_message)
899
+
900
+ res = res.lower()[0]
901
+
902
+ if res == "d" and allow_never:
903
+ self.never_prompts.add(question_id)
904
+ hist = f"{question.strip()} {res}"
905
+ self.append_chat_history(hist, linebreak=True, blockquote=True)
906
+ return False
907
+
908
+ if explicit_yes_required:
909
+ is_yes = res == "y"
910
+ else:
911
+ is_yes = res in ("y", "a")
912
+
913
+ is_all = res == "a" and group is not None and not explicit_yes_required
914
+ is_skip = res == "s" and group is not None
915
+
916
+ if group:
917
+ if is_all and not explicit_yes_required:
918
+ group.preference = "all"
919
+ elif is_skip:
920
+ group.preference = "skip"
921
+
922
+ hist = f"{question.strip()} {res}"
923
+ self.append_chat_history(hist, linebreak=True, blockquote=True)
924
+
925
+ return is_yes
926
+
927
+ @restore_multiline
928
+ def prompt_ask(self, question, default="", subject=None):
929
+ self.num_user_asks += 1
930
+
931
+ # Ring the bell if needed
932
+ self.ring_bell()
933
+
934
+ if subject:
935
+ self.tool_output()
936
+ self.tool_output(subject, bold=True)
937
+
938
+ style = self._get_style()
939
+
940
+ if self.yes is True:
941
+ res = "yes"
942
+ elif self.yes is False:
943
+ res = "no"
944
+ else:
945
+ try:
946
+ if self.prompt_session:
947
+ res = self.prompt_session.prompt(
948
+ question + " ",
949
+ default=default,
950
+ style=style,
951
+ complete_while_typing=True,
952
+ )
953
+ else:
954
+ res = input(question + " ")
955
+ except EOFError:
956
+ # Treat EOF (Ctrl+D) as if the user pressed Enter
957
+ res = default
958
+
959
+ hist = f"{question.strip()} {res.strip()}"
960
+ self.append_chat_history(hist, linebreak=True, blockquote=True)
961
+ if self.yes in (True, False):
962
+ self.tool_output(hist)
963
+
964
+ return res
965
+
966
+ def _tool_message(self, message="", strip=True, color=None):
967
+ if message.strip():
968
+ if "\n" in message:
969
+ for line in message.splitlines():
970
+ self.append_chat_history(line, linebreak=True, blockquote=True, strip=strip)
971
+ else:
972
+ hist = message.strip() if strip else message
973
+ self.append_chat_history(hist, linebreak=True, blockquote=True)
974
+
975
+ if not isinstance(message, Text):
976
+ message = Text(message)
977
+ color = ensure_hash_prefix(color) if color else None
978
+ style = dict(style=color) if self.pretty and color else dict()
979
+ try:
980
+ self.console.print(message, **style)
981
+ except UnicodeEncodeError:
982
+ # Fallback to ASCII-safe output
983
+ if isinstance(message, Text):
984
+ message = message.plain
985
+ message = str(message).encode("ascii", errors="replace").decode("ascii")
986
+ self.console.print(message, **style)
987
+
988
+ def tool_error(self, message="", strip=True):
989
+ self.num_error_outputs += 1
990
+ self._tool_message(message, strip, self.tool_error_color)
991
+
992
+ def tool_warning(self, message="", strip=True):
993
+ self._tool_message(message, strip, self.tool_warning_color)
994
+
995
+ def tool_output(self, *messages, log_only=False, bold=False):
996
+ if messages:
997
+ hist = " ".join(messages)
998
+ hist = f"{hist.strip()}"
999
+ self.append_chat_history(hist, linebreak=True, blockquote=True)
1000
+
1001
+ if log_only:
1002
+ return
1003
+
1004
+ messages = list(map(Text, messages))
1005
+ style = dict()
1006
+ if self.pretty:
1007
+ if self.tool_output_color:
1008
+ style["color"] = ensure_hash_prefix(self.tool_output_color)
1009
+ style["reverse"] = bold
1010
+
1011
+ style = RichStyle(**style)
1012
+ self.console.print(*messages, style=style)
1013
+
1014
+ def get_assistant_mdstream(self):
1015
+ mdargs = dict(
1016
+ style=self.assistant_output_color,
1017
+ code_theme=self.code_theme,
1018
+ inline_code_lexer="text",
1019
+ )
1020
+ mdStream = MarkdownStream(mdargs=mdargs)
1021
+ return mdStream
1022
+
1023
+ def assistant_output(self, message, pretty=None):
1024
+ if not message:
1025
+ self.tool_warning("Empty response received from LLM. Check your provider account?")
1026
+ return
1027
+
1028
+ show_resp = message
1029
+
1030
+ # Coder will force pretty off if fence is not triple-backticks
1031
+ if pretty is None:
1032
+ pretty = self.pretty
1033
+
1034
+ if pretty:
1035
+ show_resp = Markdown(
1036
+ message, style=self.assistant_output_color, code_theme=self.code_theme
1037
+ )
1038
+ else:
1039
+ show_resp = Text(message or "(empty response)")
1040
+
1041
+ self.console.print(show_resp)
1042
+
1043
+ def set_placeholder(self, placeholder):
1044
+ """Set a one-time placeholder text for the next input prompt."""
1045
+ self.placeholder = placeholder
1046
+
1047
+ def print(self, message=""):
1048
+ print(message)
1049
+
1050
+ def llm_started(self):
1051
+ """Mark that the LLM has started processing, so we should ring the bell on next input"""
1052
+ self.bell_on_next_input = True
1053
+
1054
+ def get_default_notification_command(self):
1055
+ """Return a default notification command based on the operating system."""
1056
+ import platform
1057
+
1058
+ system = platform.system()
1059
+
1060
+ if system == "Darwin": # macOS
1061
+ # Check for terminal-notifier first
1062
+ if shutil.which("terminal-notifier"):
1063
+ return f"terminal-notifier -title 'Patch' -message '{NOTIFICATION_MESSAGE}'"
1064
+ # Fall back to osascript
1065
+ return (
1066
+ f'osascript -e \'display notification "{NOTIFICATION_MESSAGE}" with title "Patch"\''
1067
+ )
1068
+ elif system == "Linux":
1069
+ # Check for common Linux notification tools
1070
+ for cmd in ["notify-send", "zenity"]:
1071
+ if shutil.which(cmd):
1072
+ if cmd == "notify-send":
1073
+ return f"notify-send 'Patch' '{NOTIFICATION_MESSAGE}'"
1074
+ elif cmd == "zenity":
1075
+ return f"zenity --notification --text='{NOTIFICATION_MESSAGE}'"
1076
+ return None # No known notification tool found
1077
+ elif system == "Windows":
1078
+ # PowerShell notification
1079
+ return (
1080
+ "powershell -command"
1081
+ " \"[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms');"
1082
+ f" [System.Windows.Forms.MessageBox]::Show('{NOTIFICATION_MESSAGE}',"
1083
+ " 'Patch')\""
1084
+ )
1085
+
1086
+ return None # Unknown system
1087
+
1088
+ def ring_bell(self):
1089
+ """Ring the terminal bell if needed and clear the flag"""
1090
+ if self.bell_on_next_input and self.notifications:
1091
+ if self.notifications_command:
1092
+ try:
1093
+ result = subprocess.run(
1094
+ self.notifications_command, shell=True, capture_output=True
1095
+ )
1096
+ if result.returncode != 0 and result.stderr:
1097
+ error_msg = result.stderr.decode("utf-8", errors="replace")
1098
+ self.tool_warning(f"Failed to run notifications command: {error_msg}")
1099
+ except Exception as e:
1100
+ self.tool_warning(f"Failed to run notifications command: {e}")
1101
+ else:
1102
+ print("\a", end="", flush=True) # Ring the bell
1103
+ self.bell_on_next_input = False # Clear the flag
1104
+
1105
+ def toggle_multiline_mode(self):
1106
+ """Toggle between normal and multiline input modes"""
1107
+ self.multiline_mode = not self.multiline_mode
1108
+ if self.multiline_mode:
1109
+ self.tool_output(
1110
+ "Multiline mode: Enabled. Enter inserts newline, Alt-Enter submits text"
1111
+ )
1112
+ else:
1113
+ self.tool_output(
1114
+ "Multiline mode: Disabled. Alt-Enter inserts newline, Enter submits text"
1115
+ )
1116
+
1117
+ def append_chat_history(self, text, linebreak=False, blockquote=False, strip=True):
1118
+ if blockquote:
1119
+ if strip:
1120
+ text = text.strip()
1121
+ text = "> " + text
1122
+ if linebreak:
1123
+ if strip:
1124
+ text = text.rstrip()
1125
+ text = text + " \n"
1126
+ if not text.endswith("\n"):
1127
+ text += "\n"
1128
+ if self.chat_history_file is not None:
1129
+ try:
1130
+ self.chat_history_file.parent.mkdir(parents=True, exist_ok=True)
1131
+ with self.chat_history_file.open("a", encoding=self.encoding, errors="ignore") as f:
1132
+ f.write(text)
1133
+ except (PermissionError, OSError) as err:
1134
+ print(f"Warning: Unable to write to chat history file {self.chat_history_file}.")
1135
+ print(err)
1136
+ self.chat_history_file = None # Disable further attempts to write
1137
+
1138
+ def format_files_for_input(self, rel_fnames, rel_read_only_fnames):
1139
+ if not self.pretty:
1140
+ read_only_files = []
1141
+ for full_path in sorted(rel_read_only_fnames or []):
1142
+ read_only_files.append(f"{full_path} (read only)")
1143
+
1144
+ editable_files = []
1145
+ for full_path in sorted(rel_fnames):
1146
+ if full_path in rel_read_only_fnames:
1147
+ continue
1148
+ editable_files.append(f"{full_path}")
1149
+
1150
+ return "\n".join(read_only_files + editable_files) + "\n"
1151
+
1152
+ output = StringIO()
1153
+ console = Console(file=output, force_terminal=False)
1154
+
1155
+ read_only_files = sorted(rel_read_only_fnames or [])
1156
+ editable_files = [f for f in sorted(rel_fnames) if f not in rel_read_only_fnames]
1157
+
1158
+ if read_only_files:
1159
+ # Use shorter of abs/rel paths for readonly files
1160
+ ro_paths = []
1161
+ for rel_path in read_only_files:
1162
+ abs_path = os.path.abspath(os.path.join(self.root, rel_path))
1163
+ ro_paths.append(Text(abs_path if len(abs_path) < len(rel_path) else rel_path))
1164
+
1165
+ files_with_label = [Text("Readonly:")] + ro_paths
1166
+ read_only_output = StringIO()
1167
+ Console(file=read_only_output, force_terminal=False).print(Columns(files_with_label))
1168
+ read_only_lines = read_only_output.getvalue().splitlines()
1169
+ console.print(Columns(files_with_label))
1170
+
1171
+ if editable_files:
1172
+ text_editable_files = [Text(f) for f in editable_files]
1173
+ files_with_label = text_editable_files
1174
+ if read_only_files:
1175
+ files_with_label = [Text("Editable:")] + text_editable_files
1176
+ editable_output = StringIO()
1177
+ Console(file=editable_output, force_terminal=False).print(Columns(files_with_label))
1178
+ editable_lines = editable_output.getvalue().splitlines()
1179
+
1180
+ if len(read_only_lines) > 1 or len(editable_lines) > 1:
1181
+ console.print()
1182
+ console.print(Columns(files_with_label))
1183
+
1184
+ return output.getvalue()
1185
+
1186
+
1187
+ def get_rel_fname(fname, root):
1188
+ try:
1189
+ return os.path.relpath(fname, root)
1190
+ except ValueError:
1191
+ return fname