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/io.py ADDED
@@ -0,0 +1,1209 @@
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 = 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.line_endings = line_endings
331
+ self.newline = (
332
+ None if line_endings == "platform" else "\n" if line_endings == "lf" else "\r\n"
333
+ )
334
+ self.dry_run = dry_run
335
+
336
+ current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
337
+ self.append_chat_history(f"\n# patch chat started at {current_time}\n\n")
338
+
339
+ self.prompt_session = None
340
+ self.is_dumb_terminal = is_dumb_terminal()
341
+
342
+ if self.is_dumb_terminal:
343
+ self.pretty = False
344
+ fancy_input = False
345
+
346
+ if fancy_input:
347
+ # Initialize PromptSession only if we have a capable terminal
348
+ session_kwargs = {
349
+ "input": self.input,
350
+ "output": self.output,
351
+ "lexer": PygmentsLexer(MarkdownLexer),
352
+ "editing_mode": self.editingmode,
353
+ }
354
+ if self.editingmode == EditingMode.VI:
355
+ session_kwargs["cursor"] = ModalCursorShapeConfig()
356
+ if self.input_history_file is not None:
357
+ session_kwargs["history"] = FileHistory(self.input_history_file)
358
+ try:
359
+ self.prompt_session = PromptSession(**session_kwargs)
360
+ self.console = Console() # pretty console
361
+ except Exception as err:
362
+ self.console = Console(force_terminal=False, no_color=True)
363
+ self.tool_error(f"Can't initialize prompt toolkit: {err}") # non-pretty
364
+ else:
365
+ self.console = Console(force_terminal=False, no_color=True) # non-pretty
366
+ if self.is_dumb_terminal:
367
+ self.tool_output("Detected dumb terminal, disabling fancy input and pretty output.")
368
+
369
+ self.file_watcher = file_watcher
370
+ self.root = root
371
+
372
+ # Validate color settings after console is initialized
373
+ self._validate_color_settings()
374
+
375
+ def _validate_color_settings(self):
376
+ """Validate configured color strings and reset invalid ones."""
377
+ color_attributes = [
378
+ "user_input_color",
379
+ "tool_output_color",
380
+ "tool_error_color",
381
+ "tool_warning_color",
382
+ "assistant_output_color",
383
+ "completion_menu_color",
384
+ "completion_menu_bg_color",
385
+ "completion_menu_current_color",
386
+ "completion_menu_current_bg_color",
387
+ ]
388
+ for attr_name in color_attributes:
389
+ color_value = getattr(self, attr_name, None)
390
+ if color_value:
391
+ try:
392
+ # Try creating a style to validate the color
393
+ RichStyle(color=color_value)
394
+ except ColorParseError as e:
395
+ self.console.print(
396
+ "[bold red]Warning:[/bold red] Invalid configuration for"
397
+ f" {attr_name}: '{color_value}'. {e}. Disabling this color."
398
+ )
399
+ setattr(self, attr_name, None) # Reset invalid color to None
400
+
401
+ def _get_style(self):
402
+ style_dict = {}
403
+ if not self.pretty:
404
+ return Style.from_dict(style_dict)
405
+
406
+ if self.user_input_color:
407
+ style_dict.setdefault("", self.user_input_color)
408
+ style_dict.update(
409
+ {
410
+ "pygments.literal.string": f"bold italic {self.user_input_color}",
411
+ }
412
+ )
413
+
414
+ # Conditionally add 'completion-menu' style
415
+ completion_menu_style = []
416
+ if self.completion_menu_bg_color:
417
+ completion_menu_style.append(f"bg:{self.completion_menu_bg_color}")
418
+ if self.completion_menu_color:
419
+ completion_menu_style.append(self.completion_menu_color)
420
+ if completion_menu_style:
421
+ style_dict["completion-menu"] = " ".join(completion_menu_style)
422
+
423
+ # Conditionally add 'completion-menu.completion.current' style
424
+ completion_menu_current_style = []
425
+ if self.completion_menu_current_bg_color:
426
+ completion_menu_current_style.append(self.completion_menu_current_bg_color)
427
+ if self.completion_menu_current_color:
428
+ completion_menu_current_style.append(f"bg:{self.completion_menu_current_color}")
429
+ if completion_menu_current_style:
430
+ style_dict["completion-menu.completion.current"] = " ".join(
431
+ completion_menu_current_style
432
+ )
433
+
434
+ return Style.from_dict(style_dict)
435
+
436
+ def read_image(self, filename: str | os.PathLike[str]) -> str | None:
437
+ try:
438
+ with open(str(filename), "rb") as image_file:
439
+ encoded_string = base64.b64encode(image_file.read())
440
+ return encoded_string.decode("utf-8")
441
+ except OSError as err:
442
+ self.tool_error(f"{filename}: unable to read: {err}")
443
+ return None
444
+ except FileNotFoundError:
445
+ self.tool_error(f"{filename}: file not found error")
446
+ return None
447
+ except IsADirectoryError:
448
+ self.tool_error(f"{filename}: is a directory")
449
+ return None
450
+ except Exception as e:
451
+ self.tool_error(f"{filename}: {e}")
452
+ return None
453
+
454
+ def read_text(self, filename: str | os.PathLike[str], silent: bool = False) -> str | None:
455
+ if is_image_file(filename):
456
+ return self.read_image(filename)
457
+
458
+ try:
459
+ with open(str(filename), "r", encoding=self.encoding) as f:
460
+ return f.read()
461
+ except FileNotFoundError:
462
+ if not silent:
463
+ self.tool_error(f"{filename}: file not found error")
464
+ return None
465
+ except IsADirectoryError:
466
+ if not silent:
467
+ self.tool_error(f"{filename}: is a directory")
468
+ return None
469
+ except OSError as err:
470
+ if not silent:
471
+ self.tool_error(f"{filename}: unable to read: {err}")
472
+ return None
473
+ except UnicodeError as e:
474
+ if not silent:
475
+ self.tool_error(f"{filename}: {e}")
476
+ self.tool_error("Use --encoding to set the unicode encoding.")
477
+ return None
478
+
479
+ def write_text(
480
+ self,
481
+ filename: str | os.PathLike[str],
482
+ content: str,
483
+ max_retries: int = 5,
484
+ initial_delay: float = 0.1,
485
+ ) -> None:
486
+ """
487
+ Writes content to a file, retrying with progressive backoff if the file is locked.
488
+
489
+ :param filename: Path to the file to write.
490
+ :param content: Content to write to the file.
491
+ :param max_retries: Maximum number of retries if a file lock is encountered.
492
+ :param initial_delay: Initial delay (in seconds) before the first retry.
493
+ """
494
+ if self.dry_run:
495
+ return
496
+
497
+ delay = initial_delay
498
+ for attempt in range(max_retries):
499
+ try:
500
+ newline = self.newline
501
+ if self.line_endings == "platform":
502
+ try:
503
+ existing = Path(filename).read_bytes()
504
+ crlf_count = existing.count(b"\r\n")
505
+ lf_count = existing.count(b"\n") - crlf_count
506
+ if crlf_count or lf_count:
507
+ newline = "\r\n" if crlf_count > lf_count else "\n"
508
+ except OSError:
509
+ pass
510
+
511
+ with open(str(filename), "w", encoding=self.encoding, newline=newline) as f:
512
+ f.write(content)
513
+ return # Successfully wrote the file
514
+ except PermissionError as err:
515
+ if attempt < max_retries - 1:
516
+ time.sleep(delay)
517
+ delay *= 2 # Exponential backoff
518
+ else:
519
+ self.tool_error(
520
+ f"Unable to write file {filename} after {max_retries} attempts: {err}"
521
+ )
522
+ raise
523
+ except OSError as err:
524
+ self.tool_error(f"Unable to write file {filename}: {err}")
525
+ raise
526
+
527
+ def rule(self):
528
+ if self.pretty:
529
+ style = dict(style=self.user_input_color) if self.user_input_color else dict()
530
+ self.console.rule(**style)
531
+ else:
532
+ print()
533
+
534
+ def interrupt_input(self):
535
+ if self.prompt_session and self.prompt_session.app:
536
+ # Store any partial input before interrupting
537
+ self.placeholder = self.prompt_session.app.current_buffer.text
538
+ self.interrupted = True
539
+ self.prompt_session.app.exit()
540
+
541
+ def get_input(
542
+ self,
543
+ root,
544
+ rel_fnames,
545
+ addable_rel_fnames,
546
+ commands,
547
+ abs_read_only_fnames=None,
548
+ edit_format=None,
549
+ ):
550
+ self.rule()
551
+
552
+ # Ring the bell if needed
553
+ self.ring_bell()
554
+
555
+ rel_fnames = list(rel_fnames)
556
+ show = ""
557
+ if rel_fnames:
558
+ rel_read_only_fnames = [
559
+ get_rel_fname(fname, root) for fname in (abs_read_only_fnames or [])
560
+ ]
561
+ show = self.format_files_for_input(rel_fnames, rel_read_only_fnames)
562
+
563
+ prompt_prefix = ""
564
+ if edit_format:
565
+ prompt_prefix += edit_format
566
+ if self.multiline_mode:
567
+ prompt_prefix += (" " if edit_format else "") + "multi"
568
+ prompt_prefix += "> "
569
+
570
+ show += prompt_prefix
571
+ self.prompt_prefix = prompt_prefix
572
+
573
+ inp = ""
574
+ multiline_input = False
575
+
576
+ style = self._get_style()
577
+
578
+ completer_instance = ThreadedCompleter(
579
+ AutoCompleter(
580
+ root,
581
+ rel_fnames,
582
+ addable_rel_fnames,
583
+ commands,
584
+ self.encoding,
585
+ abs_read_only_fnames=abs_read_only_fnames,
586
+ )
587
+ )
588
+
589
+ def suspend_to_bg(event):
590
+ """Suspend currently running application."""
591
+ event.app.suspend_to_background()
592
+
593
+ kb = KeyBindings()
594
+
595
+ @kb.add(Keys.ControlZ, filter=Condition(lambda: hasattr(signal, "SIGTSTP")))
596
+ def _(event):
597
+ "Suspend to background with ctrl-z"
598
+ suspend_to_bg(event)
599
+
600
+ @kb.add("c-space")
601
+ def _(event):
602
+ "Ignore Ctrl when pressing space bar"
603
+ event.current_buffer.insert_text(" ")
604
+
605
+ @kb.add("c-up")
606
+ def _(event):
607
+ "Navigate backward through history"
608
+ event.current_buffer.history_backward()
609
+
610
+ @kb.add("c-down")
611
+ def _(event):
612
+ "Navigate forward through history"
613
+ event.current_buffer.history_forward()
614
+
615
+ @kb.add("c-x", "c-e")
616
+ def _(event):
617
+ "Edit current input in external editor (like Bash)"
618
+ buffer = event.current_buffer
619
+ current_text = buffer.text
620
+
621
+ # Open the editor with the current text
622
+ edited_text = pipe_editor(input_data=current_text, suffix="md")
623
+
624
+ # Replace the buffer with the edited text, strip any trailing newlines
625
+ buffer.text = edited_text.rstrip("\n")
626
+
627
+ # Move cursor to the end of the text
628
+ buffer.cursor_position = len(buffer.text)
629
+
630
+ @kb.add("enter", eager=True, filter=~is_searching)
631
+ def _(event):
632
+ "Handle Enter key press"
633
+ if self.multiline_mode and not (
634
+ self.editingmode == EditingMode.VI
635
+ and event.app.vi_state.input_mode == InputMode.NAVIGATION
636
+ ):
637
+ # In multiline mode and if not in vi-mode or vi navigation/normal mode,
638
+ # Enter adds a newline
639
+ event.current_buffer.insert_text("\n")
640
+ else:
641
+ # In normal mode, Enter submits
642
+ event.current_buffer.validate_and_handle()
643
+
644
+ @kb.add("escape", "enter", eager=True, filter=~is_searching) # This is Alt+Enter
645
+ def _(event):
646
+ "Handle Alt+Enter key press"
647
+ if self.multiline_mode:
648
+ # In multiline mode, Alt+Enter submits
649
+ event.current_buffer.validate_and_handle()
650
+ else:
651
+ # In normal mode, Alt+Enter adds a newline
652
+ event.current_buffer.insert_text("\n")
653
+
654
+ while True:
655
+ if multiline_input:
656
+ show = self.prompt_prefix
657
+
658
+ try:
659
+ if self.prompt_session:
660
+ # Use placeholder if set, then clear it
661
+ default = self.placeholder or ""
662
+ self.placeholder = None
663
+
664
+ self.interrupted = False
665
+ if not multiline_input:
666
+ if self.file_watcher:
667
+ self.file_watcher.start()
668
+ if self.clipboard_watcher:
669
+ self.clipboard_watcher.start()
670
+
671
+ def get_continuation(width, line_number, is_soft_wrap):
672
+ return self.prompt_prefix
673
+
674
+ line = self.prompt_session.prompt(
675
+ show,
676
+ default=default,
677
+ completer=completer_instance,
678
+ reserve_space_for_menu=4,
679
+ complete_style=CompleteStyle.MULTI_COLUMN,
680
+ style=style,
681
+ key_bindings=kb,
682
+ complete_while_typing=True,
683
+ prompt_continuation=get_continuation,
684
+ )
685
+ else:
686
+ line = input(show)
687
+
688
+ # Check if we were interrupted by a file change
689
+ if self.interrupted:
690
+ line = line or ""
691
+ if self.file_watcher:
692
+ cmd = self.file_watcher.process_changes()
693
+ return cmd
694
+
695
+ except EOFError:
696
+ raise
697
+ except Exception as err:
698
+ import traceback
699
+
700
+ self.tool_error(str(err))
701
+ self.tool_error(traceback.format_exc())
702
+ return ""
703
+ except UnicodeEncodeError as err:
704
+ self.tool_error(str(err))
705
+ return ""
706
+ finally:
707
+ if self.file_watcher:
708
+ self.file_watcher.stop()
709
+ if self.clipboard_watcher:
710
+ self.clipboard_watcher.stop()
711
+
712
+ if line.strip("\r\n") and not multiline_input:
713
+ stripped = line.strip("\r\n")
714
+ if stripped == "{":
715
+ multiline_input = True
716
+ multiline_tag = None
717
+ inp += ""
718
+ elif stripped[0] == "{":
719
+ # Extract tag if it exists (only alphanumeric chars)
720
+ tag = "".join(c for c in stripped[1:] if c.isalnum())
721
+ if stripped == "{" + tag:
722
+ multiline_input = True
723
+ multiline_tag = tag
724
+ inp += ""
725
+ else:
726
+ inp = line
727
+ break
728
+ else:
729
+ inp = line
730
+ break
731
+ continue
732
+ elif multiline_input and line.strip():
733
+ if multiline_tag:
734
+ # Check if line is exactly "tag}"
735
+ if line.strip("\r\n") == f"{multiline_tag}}}":
736
+ break
737
+ else:
738
+ inp += line + "\n"
739
+ # Check if line is exactly "}"
740
+ elif line.strip("\r\n") == "}":
741
+ break
742
+ else:
743
+ inp += line + "\n"
744
+ elif multiline_input:
745
+ inp += line + "\n"
746
+ else:
747
+ inp = line
748
+ break
749
+
750
+ print()
751
+ self.user_input(inp)
752
+ return inp
753
+
754
+ def add_to_input_history(self, inp):
755
+ if not self.input_history_file:
756
+ return
757
+ try:
758
+ FileHistory(self.input_history_file).append_string(inp)
759
+ # Also add to the in-memory history if it exists
760
+ if self.prompt_session and self.prompt_session.history:
761
+ self.prompt_session.history.append_string(inp)
762
+ except OSError as err:
763
+ self.tool_warning(f"Unable to write to input history file: {err}")
764
+
765
+ def get_input_history(self):
766
+ if not self.input_history_file:
767
+ return []
768
+
769
+ fh = FileHistory(self.input_history_file)
770
+ return fh.load_history_strings()
771
+
772
+ def log_llm_history(self, role, content):
773
+ if not self.llm_history_file:
774
+ return
775
+ timestamp = datetime.now().isoformat(timespec="seconds")
776
+ try:
777
+ Path(self.llm_history_file).parent.mkdir(parents=True, exist_ok=True)
778
+ with open(self.llm_history_file, "a", encoding="utf-8") as log_file:
779
+ log_file.write(f"{role.upper()} {timestamp}\n")
780
+ log_file.write(content + "\n")
781
+ except (PermissionError, OSError) as err:
782
+ self.tool_warning(f"Unable to write to llm history file {self.llm_history_file}: {err}")
783
+ self.llm_history_file = None
784
+
785
+ def display_user_input(self, inp):
786
+ if self.pretty and self.user_input_color:
787
+ style = dict(style=self.user_input_color)
788
+ else:
789
+ style = dict()
790
+
791
+ self.console.print(Text(inp), **style)
792
+
793
+ def user_input(self, inp, log_only=True):
794
+ if not log_only:
795
+ self.display_user_input(inp)
796
+
797
+ prefix = "####"
798
+ if inp:
799
+ hist = inp.splitlines()
800
+ else:
801
+ hist = ["<blank>"]
802
+
803
+ hist = f" \n{prefix} ".join(hist)
804
+
805
+ hist = f"""
806
+ {prefix} {hist}"""
807
+ self.append_chat_history(hist, linebreak=True)
808
+
809
+ # OUTPUT
810
+
811
+ def ai_output(self, content):
812
+ hist = "\n" + content.strip() + "\n\n"
813
+ self.append_chat_history(hist)
814
+
815
+ def offer_url(self, url, prompt="Open URL for more info?", allow_never=True):
816
+ """Offer to open a URL in the browser, returns True if opened."""
817
+ if url in self.never_prompts:
818
+ return False
819
+ if self.confirm_ask(prompt, subject=url, allow_never=allow_never):
820
+ webbrowser.open(url)
821
+ return True
822
+ return False
823
+
824
+ @restore_multiline
825
+ def confirm_ask(
826
+ self,
827
+ question,
828
+ default="y",
829
+ subject=None,
830
+ explicit_yes_required=False,
831
+ group=None,
832
+ allow_never=False,
833
+ ):
834
+ self.num_user_asks += 1
835
+
836
+ # Ring the bell if needed
837
+ self.ring_bell()
838
+
839
+ question_id = (question, subject)
840
+
841
+ if question_id in self.never_prompts:
842
+ return False
843
+
844
+ if group and not group.show_group:
845
+ group = None
846
+ if group:
847
+ allow_never = True
848
+
849
+ valid_responses = ["yes", "no", "skip", "all"]
850
+ options = " (Y)es/(N)o"
851
+ if group:
852
+ if not explicit_yes_required:
853
+ options += "/(A)ll"
854
+ options += "/(S)kip all"
855
+ if allow_never:
856
+ options += "/(D)on't ask again"
857
+ valid_responses.append("don't")
858
+
859
+ if default.lower().startswith("y"):
860
+ question += options + " [Yes]: "
861
+ elif default.lower().startswith("n"):
862
+ question += options + " [No]: "
863
+ else:
864
+ question += options + f" [{default}]: "
865
+
866
+ if subject:
867
+ self.tool_output()
868
+ if "\n" in subject:
869
+ lines = subject.splitlines()
870
+ max_length = max(len(line) for line in lines)
871
+ padded_lines = [line.ljust(max_length) for line in lines]
872
+ padded_subject = "\n".join(padded_lines)
873
+ self.tool_output(padded_subject, bold=True)
874
+ else:
875
+ self.tool_output(subject, bold=True)
876
+
877
+ style = self._get_style()
878
+
879
+ def is_valid_response(text):
880
+ if not text:
881
+ return True
882
+ return text.lower() in valid_responses
883
+
884
+ if self.yes is True:
885
+ res = "n" if explicit_yes_required else "y"
886
+ elif self.yes is False:
887
+ res = "n"
888
+ elif group and group.preference:
889
+ res = group.preference
890
+ self.user_input(f"{question}{res}", log_only=False)
891
+ else:
892
+ while True:
893
+ try:
894
+ if self.prompt_session:
895
+ res = self.prompt_session.prompt(
896
+ question,
897
+ style=style,
898
+ complete_while_typing=False,
899
+ )
900
+ else:
901
+ res = input(question)
902
+ except EOFError:
903
+ # Treat EOF (Ctrl+D) as if the user pressed Enter
904
+ res = default
905
+ break
906
+
907
+ if not res:
908
+ res = default
909
+ break
910
+ res = res.lower()
911
+ good = any(valid_response.startswith(res) for valid_response in valid_responses)
912
+ if good:
913
+ break
914
+
915
+ error_message = f"Please answer with one of: {', '.join(valid_responses)}"
916
+ self.tool_error(error_message)
917
+
918
+ res = res.lower()[0]
919
+
920
+ if res == "d" and allow_never:
921
+ self.never_prompts.add(question_id)
922
+ hist = f"{question.strip()} {res}"
923
+ self.append_chat_history(hist, linebreak=True, blockquote=True)
924
+ return False
925
+
926
+ if explicit_yes_required:
927
+ is_yes = res == "y"
928
+ else:
929
+ is_yes = res in ("y", "a")
930
+
931
+ is_all = res == "a" and group is not None and not explicit_yes_required
932
+ is_skip = res == "s" and group is not None
933
+
934
+ if group:
935
+ if is_all and not explicit_yes_required:
936
+ group.preference = "all"
937
+ elif is_skip:
938
+ group.preference = "skip"
939
+
940
+ hist = f"{question.strip()} {res}"
941
+ self.append_chat_history(hist, linebreak=True, blockquote=True)
942
+
943
+ return is_yes
944
+
945
+ @restore_multiline
946
+ def prompt_ask(self, question, default="", subject=None):
947
+ self.num_user_asks += 1
948
+
949
+ # Ring the bell if needed
950
+ self.ring_bell()
951
+
952
+ if subject:
953
+ self.tool_output()
954
+ self.tool_output(subject, bold=True)
955
+
956
+ style = self._get_style()
957
+
958
+ if self.yes is True:
959
+ res = "yes"
960
+ elif self.yes is False:
961
+ res = "no"
962
+ else:
963
+ try:
964
+ if self.prompt_session:
965
+ res = self.prompt_session.prompt(
966
+ question + " ",
967
+ default=default,
968
+ style=style,
969
+ complete_while_typing=True,
970
+ )
971
+ else:
972
+ res = input(question + " ")
973
+ except EOFError:
974
+ # Treat EOF (Ctrl+D) as if the user pressed Enter
975
+ res = default
976
+
977
+ hist = f"{question.strip()} {res.strip()}"
978
+ self.append_chat_history(hist, linebreak=True, blockquote=True)
979
+ if self.yes in (True, False):
980
+ self.tool_output(hist)
981
+
982
+ return res
983
+
984
+ def _tool_message(self, message="", strip=True, color=None):
985
+ if message.strip():
986
+ if "\n" in message:
987
+ for line in message.splitlines():
988
+ self.append_chat_history(line, linebreak=True, blockquote=True, strip=strip)
989
+ else:
990
+ hist = message.strip() if strip else message
991
+ self.append_chat_history(hist, linebreak=True, blockquote=True)
992
+
993
+ if not isinstance(message, Text):
994
+ message = Text(message)
995
+ color = ensure_hash_prefix(color) if color else None
996
+ style = dict(style=color) if self.pretty and color else dict()
997
+ try:
998
+ self.console.print(message, **style)
999
+ except UnicodeEncodeError:
1000
+ # Fallback to ASCII-safe output
1001
+ if isinstance(message, Text):
1002
+ message = message.plain
1003
+ message = str(message).encode("ascii", errors="replace").decode("ascii")
1004
+ self.console.print(message, **style)
1005
+
1006
+ def tool_error(self, message="", strip=True):
1007
+ self.num_error_outputs += 1
1008
+ self._tool_message(message, strip, self.tool_error_color)
1009
+
1010
+ def tool_warning(self, message="", strip=True):
1011
+ self._tool_message(message, strip, self.tool_warning_color)
1012
+
1013
+ def tool_output(self, *messages, log_only=False, bold=False):
1014
+ if messages:
1015
+ hist = " ".join(messages)
1016
+ hist = f"{hist.strip()}"
1017
+ self.append_chat_history(hist, linebreak=True, blockquote=True)
1018
+
1019
+ if log_only:
1020
+ return
1021
+
1022
+ messages = list(map(Text, messages))
1023
+ style = dict()
1024
+ if self.pretty:
1025
+ if self.tool_output_color:
1026
+ style["color"] = ensure_hash_prefix(self.tool_output_color)
1027
+ style["reverse"] = bold
1028
+
1029
+ style = RichStyle(**style)
1030
+ self.console.print(*messages, style=style)
1031
+
1032
+ def get_assistant_mdstream(self):
1033
+ mdargs = dict(
1034
+ style=self.assistant_output_color,
1035
+ code_theme=self.code_theme,
1036
+ inline_code_lexer="text",
1037
+ )
1038
+ mdStream = MarkdownStream(mdargs=mdargs)
1039
+ return mdStream
1040
+
1041
+ def assistant_output(self, message, pretty=None):
1042
+ if not message:
1043
+ self.tool_warning("Empty response received from LLM. Check your provider account?")
1044
+ return
1045
+
1046
+ show_resp = message
1047
+
1048
+ # Coder will force pretty off if fence is not triple-backticks
1049
+ if pretty is None:
1050
+ pretty = self.pretty
1051
+
1052
+ if pretty:
1053
+ show_resp = Markdown(
1054
+ message, style=self.assistant_output_color, code_theme=self.code_theme
1055
+ )
1056
+ else:
1057
+ show_resp = Text(message or "(empty response)")
1058
+
1059
+ self.console.print(show_resp)
1060
+
1061
+ def set_placeholder(self, placeholder):
1062
+ """Set a one-time placeholder text for the next input prompt."""
1063
+ self.placeholder = placeholder
1064
+
1065
+ def print(self, message=""):
1066
+ print(message)
1067
+
1068
+ def llm_started(self):
1069
+ """Mark that the LLM has started processing, so we should ring the bell on next input"""
1070
+ self.bell_on_next_input = True
1071
+
1072
+ def get_default_notification_command(self):
1073
+ """Return a default notification command based on the operating system."""
1074
+ import platform
1075
+
1076
+ system = platform.system()
1077
+
1078
+ if system == "Darwin": # macOS
1079
+ # Check for terminal-notifier first
1080
+ if shutil.which("terminal-notifier"):
1081
+ return f"terminal-notifier -title 'Patch' -message '{NOTIFICATION_MESSAGE}'"
1082
+ # Fall back to osascript
1083
+ return (
1084
+ f'osascript -e \'display notification "{NOTIFICATION_MESSAGE}" with title "Patch"\''
1085
+ )
1086
+ elif system == "Linux":
1087
+ # Check for common Linux notification tools
1088
+ for cmd in ["notify-send", "zenity"]:
1089
+ if shutil.which(cmd):
1090
+ if cmd == "notify-send":
1091
+ return f"notify-send 'Patch' '{NOTIFICATION_MESSAGE}'"
1092
+ elif cmd == "zenity":
1093
+ return f"zenity --notification --text='{NOTIFICATION_MESSAGE}'"
1094
+ return None # No known notification tool found
1095
+ elif system == "Windows":
1096
+ # PowerShell notification
1097
+ return (
1098
+ "powershell -command"
1099
+ " \"[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms');"
1100
+ f" [System.Windows.Forms.MessageBox]::Show('{NOTIFICATION_MESSAGE}',"
1101
+ " 'Patch')\""
1102
+ )
1103
+
1104
+ return None # Unknown system
1105
+
1106
+ def ring_bell(self):
1107
+ """Ring the terminal bell if needed and clear the flag"""
1108
+ if self.bell_on_next_input and self.notifications:
1109
+ if self.notifications_command:
1110
+ try:
1111
+ result = subprocess.run(
1112
+ self.notifications_command, shell=True, capture_output=True
1113
+ )
1114
+ if result.returncode != 0 and result.stderr:
1115
+ error_msg = result.stderr.decode("utf-8", errors="replace")
1116
+ self.tool_warning(f"Failed to run notifications command: {error_msg}")
1117
+ except Exception as e:
1118
+ self.tool_warning(f"Failed to run notifications command: {e}")
1119
+ else:
1120
+ print("\a", end="", flush=True) # Ring the bell
1121
+ self.bell_on_next_input = False # Clear the flag
1122
+
1123
+ def toggle_multiline_mode(self):
1124
+ """Toggle between normal and multiline input modes"""
1125
+ self.multiline_mode = not self.multiline_mode
1126
+ if self.multiline_mode:
1127
+ self.tool_output(
1128
+ "Multiline mode: Enabled. Enter inserts newline, Alt-Enter submits text"
1129
+ )
1130
+ else:
1131
+ self.tool_output(
1132
+ "Multiline mode: Disabled. Alt-Enter inserts newline, Enter submits text"
1133
+ )
1134
+
1135
+ def append_chat_history(self, text, linebreak=False, blockquote=False, strip=True):
1136
+ if blockquote:
1137
+ if strip:
1138
+ text = text.strip()
1139
+ text = "> " + text
1140
+ if linebreak:
1141
+ if strip:
1142
+ text = text.rstrip()
1143
+ text = text + " \n"
1144
+ if not text.endswith("\n"):
1145
+ text += "\n"
1146
+ if self.chat_history_file is not None:
1147
+ try:
1148
+ self.chat_history_file.parent.mkdir(parents=True, exist_ok=True)
1149
+ with self.chat_history_file.open("a", encoding=self.encoding, errors="ignore") as f:
1150
+ f.write(text)
1151
+ except (PermissionError, OSError) as err:
1152
+ print(f"Warning: Unable to write to chat history file {self.chat_history_file}.")
1153
+ print(err)
1154
+ self.chat_history_file = None # Disable further attempts to write
1155
+
1156
+ def format_files_for_input(self, rel_fnames, rel_read_only_fnames):
1157
+ if not self.pretty:
1158
+ read_only_files = []
1159
+ for full_path in sorted(rel_read_only_fnames or []):
1160
+ read_only_files.append(f"{full_path} (read only)")
1161
+
1162
+ editable_files = []
1163
+ for full_path in sorted(rel_fnames):
1164
+ if full_path in rel_read_only_fnames:
1165
+ continue
1166
+ editable_files.append(f"{full_path}")
1167
+
1168
+ return "\n".join(read_only_files + editable_files) + "\n"
1169
+
1170
+ output = StringIO()
1171
+ console = Console(file=output, force_terminal=False)
1172
+
1173
+ read_only_files = sorted(rel_read_only_fnames or [])
1174
+ editable_files = [f for f in sorted(rel_fnames) if f not in rel_read_only_fnames]
1175
+
1176
+ if read_only_files:
1177
+ # Use shorter of abs/rel paths for readonly files
1178
+ ro_paths = []
1179
+ for rel_path in read_only_files:
1180
+ abs_path = os.path.abspath(os.path.join(self.root, rel_path))
1181
+ ro_paths.append(Text(abs_path if len(abs_path) < len(rel_path) else rel_path))
1182
+
1183
+ files_with_label = [Text("Readonly:")] + ro_paths
1184
+ read_only_output = StringIO()
1185
+ Console(file=read_only_output, force_terminal=False).print(Columns(files_with_label))
1186
+ read_only_lines = read_only_output.getvalue().splitlines()
1187
+ console.print(Columns(files_with_label))
1188
+
1189
+ if editable_files:
1190
+ text_editable_files = [Text(f) for f in editable_files]
1191
+ files_with_label = text_editable_files
1192
+ if read_only_files:
1193
+ files_with_label = [Text("Editable:")] + text_editable_files
1194
+ editable_output = StringIO()
1195
+ Console(file=editable_output, force_terminal=False).print(Columns(files_with_label))
1196
+ editable_lines = editable_output.getvalue().splitlines()
1197
+
1198
+ if len(read_only_lines) > 1 or len(editable_lines) > 1:
1199
+ console.print()
1200
+ console.print(Columns(files_with_label))
1201
+
1202
+ return output.getvalue()
1203
+
1204
+
1205
+ def get_rel_fname(fname, root):
1206
+ try:
1207
+ return os.path.relpath(fname, root)
1208
+ except ValueError:
1209
+ return fname