repl-toolkit 2.1.0__tar.gz → 2.2.0__tar.gz

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 (37) hide show
  1. {repl_toolkit-2.1.0/repl_toolkit.egg-info → repl_toolkit-2.2.0}/PKG-INFO +1 -1
  2. {repl_toolkit-2.1.0 → repl_toolkit-2.2.0}/pyproject.toml +1 -1
  3. {repl_toolkit-2.1.0 → repl_toolkit-2.2.0}/repl_toolkit/__init__.py +15 -11
  4. {repl_toolkit-2.1.0 → repl_toolkit-2.2.0}/repl_toolkit/actions/registry.py +14 -30
  5. repl_toolkit-2.2.0/repl_toolkit/async_repl.py +434 -0
  6. {repl_toolkit-2.1.0 → repl_toolkit-2.2.0}/repl_toolkit/headless_repl.py +2 -2
  7. {repl_toolkit-2.1.0 → repl_toolkit-2.2.0}/repl_toolkit/images.py +47 -1
  8. repl_toolkit-2.2.0/repl_toolkit/ptypes.py +160 -0
  9. {repl_toolkit-2.1.0 → repl_toolkit-2.2.0}/repl_toolkit/tests/test_async_repl.py +6 -6
  10. {repl_toolkit-2.1.0 → repl_toolkit-2.2.0}/repl_toolkit/tests/test_cancellation.py +2 -2
  11. {repl_toolkit-2.1.0 → repl_toolkit-2.2.0/repl_toolkit.egg-info}/PKG-INFO +1 -1
  12. repl_toolkit-2.1.0/repl_toolkit/async_repl.py +0 -536
  13. repl_toolkit-2.1.0/repl_toolkit/ptypes.py +0 -193
  14. {repl_toolkit-2.1.0 → repl_toolkit-2.2.0}/LICENSE +0 -0
  15. {repl_toolkit-2.1.0 → repl_toolkit-2.2.0}/README.md +0 -0
  16. {repl_toolkit-2.1.0 → repl_toolkit-2.2.0}/repl_toolkit/actions/__init__.py +0 -0
  17. {repl_toolkit-2.1.0 → repl_toolkit-2.2.0}/repl_toolkit/actions/action.py +0 -0
  18. {repl_toolkit-2.1.0 → repl_toolkit-2.2.0}/repl_toolkit/completion/__init__.py +0 -0
  19. {repl_toolkit-2.1.0 → repl_toolkit-2.2.0}/repl_toolkit/completion/prefix.py +0 -0
  20. {repl_toolkit-2.1.0 → repl_toolkit-2.2.0}/repl_toolkit/completion/shell_expansion.py +0 -0
  21. {repl_toolkit-2.1.0 → repl_toolkit-2.2.0}/repl_toolkit/formatting.py +0 -0
  22. {repl_toolkit-2.1.0 → repl_toolkit-2.2.0}/repl_toolkit/tests/__init__.py +0 -0
  23. {repl_toolkit-2.1.0 → repl_toolkit-2.2.0}/repl_toolkit/tests/conftest.py +0 -0
  24. {repl_toolkit-2.1.0 → repl_toolkit-2.2.0}/repl_toolkit/tests/test_actions.py +0 -0
  25. {repl_toolkit-2.1.0 → repl_toolkit-2.2.0}/repl_toolkit/tests/test_completion.py +0 -0
  26. {repl_toolkit-2.1.0 → repl_toolkit-2.2.0}/repl_toolkit/tests/test_ctrl_c_cancel.py +0 -0
  27. {repl_toolkit-2.1.0 → repl_toolkit-2.2.0}/repl_toolkit/tests/test_formatting.py +0 -0
  28. {repl_toolkit-2.1.0 → repl_toolkit-2.2.0}/repl_toolkit/tests/test_headless.py +0 -0
  29. {repl_toolkit-2.1.0 → repl_toolkit-2.2.0}/repl_toolkit/tests/test_image_utils.py +0 -0
  30. {repl_toolkit-2.1.0 → repl_toolkit-2.2.0}/repl_toolkit/tests/test_images.py +0 -0
  31. {repl_toolkit-2.1.0 → repl_toolkit-2.2.0}/repl_toolkit/tests/test_output_handling.py +0 -0
  32. {repl_toolkit-2.1.0 → repl_toolkit-2.2.0}/repl_toolkit/tests/test_types.py +0 -0
  33. {repl_toolkit-2.1.0 → repl_toolkit-2.2.0}/repl_toolkit.egg-info/SOURCES.txt +0 -0
  34. {repl_toolkit-2.1.0 → repl_toolkit-2.2.0}/repl_toolkit.egg-info/dependency_links.txt +0 -0
  35. {repl_toolkit-2.1.0 → repl_toolkit-2.2.0}/repl_toolkit.egg-info/requires.txt +0 -0
  36. {repl_toolkit-2.1.0 → repl_toolkit-2.2.0}/repl_toolkit.egg-info/top_level.txt +0 -0
  37. {repl_toolkit-2.1.0 → repl_toolkit-2.2.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: repl-toolkit
3
- Version: 2.1.0
3
+ Version: 2.2.0
4
4
  Summary: A Python toolkit for building interactive REPL and headless interfaces with action support
5
5
  Author-email: REPL Toolkit Contributors <martin.j.bartlett@gmail.com>
6
6
  License: MIT
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "repl-toolkit"
7
- version = "2.1.0"
7
+ version = "2.2.0"
8
8
  description = "A Python toolkit for building interactive REPL and headless interfaces with action support"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.8"
@@ -16,25 +16,28 @@ Basic usage:
16
16
  >>> repl = AsyncREPL()
17
17
  >>> await repl.run(MyBackend())
18
18
 
19
- With image support:
20
- >>> class ImageBackend:
21
- ... async def handle_input(self, user_input: str, images=None) -> bool:
22
- ... from repl_toolkit import parse_image_references
19
+ With cancellation support:
20
+ >>> from repl_toolkit import CancellableBackend
21
+ >>>
22
+ >>> class MyCancellableBackend:
23
+ ... def __init__(self):
24
+ ... self._cancelled = False
23
25
  ...
24
- ... parsed = parse_image_references(user_input)
25
- ... for img_id in parsed.image_ids:
26
- ... img_data = images[img_id]
27
- ... # Process image: img_data.data, img_data.media_type
26
+ ... async def handle_input(self, user_input: str, **kwargs) -> bool:
27
+ ... self._cancelled = False
28
+ ... # ... processing with cancellation checkpoints ...
28
29
  ... return True
30
+ ...
31
+ ... def cancel(self, message: str = None) -> None:
32
+ ... self._cancelled = True
29
33
  """
30
34
 
31
35
  import logging
32
36
 
33
37
  # Add NullHandler to prevent "No handler found" warnings
34
- # Applications using this library should configure their own handlers
35
38
  logging.getLogger(__name__).addHandler(logging.NullHandler())
36
39
 
37
- __version__ = "2.1.0"
40
+ __version__ = "2.2.0"
38
41
 
39
42
  from .actions import Action, ActionContext, ActionRegistry
40
43
  from .async_repl import AsyncREPL, run_async_repl
@@ -55,7 +58,7 @@ from .images import (
55
58
  parse_image_references,
56
59
  reconstruct_message,
57
60
  )
58
- from .ptypes import ActionHandler, AsyncBackend, Completer
61
+ from .ptypes import ActionHandler, AsyncBackend, CancellableBackend, Completer
59
62
 
60
63
  __all__ = [
61
64
  # Core REPL
@@ -86,5 +89,6 @@ __all__ = [
86
89
  # Protocols
87
90
  "ActionHandler",
88
91
  "AsyncBackend",
92
+ "CancellableBackend",
89
93
  "Completer",
90
94
  ]
@@ -79,7 +79,6 @@ class ActionRegistry(ActionHandler):
79
79
  @property
80
80
  def backend(self):
81
81
  """The backend property getter."""
82
- logger.debug("ActionRegistry.backend getter")
83
82
  return self._backend
84
83
 
85
84
  @backend.setter
@@ -320,7 +319,7 @@ class ActionRegistry(ActionHandler):
320
319
  f"Failed to execute action '{action_name}': {e}", action_name
321
320
  ) # pragma: no cover
322
321
 
323
- def handle_command(self, command_string: str, **kwargs) -> None:
322
+ def handle_command(self, command_string: str, **kwargs: Any) -> None:
324
323
  """
325
324
  Handle a command string by mapping to appropriate action.
326
325
 
@@ -373,7 +372,7 @@ class ActionRegistry(ActionHandler):
373
372
  logger.exception(f"Unexpected error handling command '{command_string}'")
374
373
  logger.debug("ActionRegistry.handle_command() exit - unexpected error")
375
374
 
376
- def handle_shortcut(self, key_combo: str, event: Any, **kwargs) -> None:
375
+ def handle_shortcut(self, key_combo: str, event: Any, **kwargs: Any) -> None:
377
376
  """
378
377
  Handle a keyboard shortcut by mapping to appropriate action.
379
378
 
@@ -415,22 +414,18 @@ class ActionRegistry(ActionHandler):
415
414
  # ActionHandler protocol implementation
416
415
  def validate_action(self, action_name: str) -> bool:
417
416
  """Validate if an action is supported."""
418
- logger.debug("ActionRegistry.validate_action() entry/exit")
419
417
  return action_name in self.actions
420
418
 
421
419
  def list_actions(self) -> List[str]:
422
420
  """Return a list of all available action names."""
423
- logger.debug("ActionRegistry.list_actions() entry/exit")
424
421
  return list(self.actions.keys())
425
422
 
426
423
  def list_commands(self) -> List[str]:
427
424
  """Return a list of all available commands."""
428
- logger.debug("ActionRegistry.list_commands() entry/exit")
429
425
  return list(self.command_map.keys())
430
426
 
431
427
  def list_shortcuts(self) -> List[str]:
432
428
  """Return a list of all available keyboard shortcuts."""
433
- logger.debug("ActionRegistry.list_shortcuts() entry/exit")
434
429
  return list(self.key_map.keys())
435
430
 
436
431
  def is_registered_command(self, text: str) -> bool:
@@ -509,7 +504,7 @@ class ActionRegistry(ActionHandler):
509
504
 
510
505
  if action:
511
506
  self._show_action_help(action, context)
512
- else: # pragma: no cover
507
+ else:
513
508
  context.printer(f"No help available for: {context.args[0]}")
514
509
  else:
515
510
  # Show general help
@@ -520,22 +515,19 @@ class ActionRegistry(ActionHandler):
520
515
  def _show_action_help(self, action: Action, context: ActionContext) -> None:
521
516
  """Show detailed help for a specific action."""
522
517
  logger.debug("ActionRegistry._show_action_help() entry")
523
- # pragma: no cover
524
- context.printer(f"\n{action.description}") # pragma: no cover
518
+ context.printer(f"\n{action.description}")
525
519
  context.printer(f"Category: {action.category}")
526
520
 
527
- if action.command: # pragma: no cover
521
+ if action.command:
528
522
  context.printer(f"Command: {action.command_usage or action.command}")
529
523
 
530
524
  if action.keys:
531
525
  keys_str = ", ".join(action.get_keys_list())
532
- desc = (
533
- f" - {action.keys_description}" if action.keys_description else ""
534
- ) # pragma: no cover
526
+ desc = f" - {action.keys_description}" if action.keys_description else ""
535
527
  context.printer(f"Shortcut: {keys_str}{desc}")
536
528
 
537
- if not action.enabled: # pragma: no cover
538
- context.printer("Status: Disabled") # pragma: no cover
529
+ if not action.enabled:
530
+ context.printer("Status: Disabled")
539
531
  context.printer("")
540
532
 
541
533
  logger.debug("ActionRegistry._show_action_help() exit")
@@ -543,13 +535,12 @@ class ActionRegistry(ActionHandler):
543
535
  def _show_general_help(self, context: ActionContext) -> None:
544
536
  """Show general help with all actions organized by category."""
545
537
  logger.debug("ActionRegistry._show_general_help() entry")
546
- # pragma: no cover
547
- context.printer("\nAvailable Actions:") # pragma: no cover
538
+ context.printer("\nAvailable Actions:")
548
539
  context.printer("=" * 50)
549
540
 
550
541
  categories = self.get_actions_by_category()
551
542
 
552
- for category, actions in sorted(categories.items()): # pragma: no cover
543
+ for category, actions in sorted(categories.items()):
553
544
  context.printer(f"\n{category}:")
554
545
  for action in sorted(actions, key=lambda a: a.name):
555
546
  # Format display line
@@ -567,13 +558,9 @@ class ActionRegistry(ActionHandler):
567
558
  parts.append(" " * 15)
568
559
 
569
560
  parts.append(action.description)
570
- # pragma: no cover
571
561
  context.printer(" " + "".join(parts))
572
- # pragma: no cover
573
- context.printer(
574
- "\nUse '/help <command>' for detailed information about a specific action."
575
- ) # pragma: no cover
576
- context.printer("Use '/shortcuts' to see only keyboard shortcuts.") # pragma: no cover
562
+ context.printer("\nUse '/help <command>' for detailed information about a specific action.")
563
+ context.printer("Use '/shortcuts' to see only keyboard shortcuts.")
577
564
  context.printer("")
578
565
 
579
566
  logger.debug("ActionRegistry._show_general_help() exit")
@@ -581,8 +568,7 @@ class ActionRegistry(ActionHandler):
581
568
  def _list_shortcuts(self, context: ActionContext) -> None:
582
569
  """List all keyboard shortcuts."""
583
570
  logger.debug("ActionRegistry._list_shortcuts() entry")
584
- # pragma: no cover
585
- context.printer("\nKeyboard Shortcuts:") # pragma: no cover
571
+ context.printer("\nKeyboard Shortcuts:")
586
572
  context.printer("=" * 50)
587
573
 
588
574
  categories = self.get_actions_by_category()
@@ -591,13 +577,11 @@ class ActionRegistry(ActionHandler):
591
577
  shortcuts_in_category = [a for a in actions if a.keys]
592
578
  if not shortcuts_in_category:
593
579
  continue
594
- # pragma: no cover
595
580
  context.printer(f"\n{category}:")
596
581
  for action in sorted(shortcuts_in_category, key=lambda a: a.name):
597
582
  keys_str = ", ".join(action.get_keys_list())
598
- desc = action.keys_description or action.description # pragma: no cover
583
+ desc = action.keys_description or action.description
599
584
  context.printer(f" {keys_str:<15} {desc}")
600
- # pragma: no cover
601
585
  context.printer("")
602
586
 
603
587
  logger.debug("ActionRegistry._list_shortcuts() exit")
@@ -0,0 +1,434 @@
1
+ """
2
+ Async REPL interface with action support for repl_toolkit.
3
+
4
+ Provides an interactive chat interface with full UI features including
5
+ history, action handling (commands + keyboard shortcuts), and
6
+ robust cancellation of long-running tasks.
7
+ """
8
+
9
+ import asyncio
10
+ import logging
11
+ import time
12
+ from contextlib import asynccontextmanager
13
+ from pathlib import Path
14
+ from typing import Any, Callable, Dict, Optional
15
+
16
+ from prompt_toolkit import HTML, PromptSession
17
+ from prompt_toolkit import print_formatted_text as print
18
+ from prompt_toolkit.application import Application
19
+ from prompt_toolkit.history import FileHistory
20
+ from prompt_toolkit.input import create_input
21
+ from prompt_toolkit.key_binding import KeyBindings
22
+ from prompt_toolkit.keys import Keys
23
+ from prompt_toolkit.output import DummyOutput
24
+ from prompt_toolkit.patch_stdout import patch_stdout
25
+ from prompt_toolkit.shortcuts import print_formatted_text
26
+
27
+ from .actions import ActionContext, ActionRegistry
28
+ from .images import ImageData, create_paste_action
29
+ from .ptypes import AsyncBackend, CancellableBackend
30
+
31
+ logger = logging.getLogger(__name__)
32
+
33
+ THINKING_MESSAGE = HTML("<i><grey>Thinking... (Press Ctrl+C or Alt+C to cancel)</grey></i>")
34
+
35
+
36
+ class AsyncREPL:
37
+ """
38
+ Manages an interactive async REPL session with action support.
39
+
40
+ Provides user input handling, action processing (commands and shortcuts),
41
+ and robust cancellation of long-running tasks.
42
+
43
+ The AsyncREPL supports late backend binding, allowing initialization without
44
+ a backend for scenarios where the backend is only available within a resource
45
+ context block.
46
+ """
47
+
48
+ def __init__(
49
+ self,
50
+ action_registry: Optional["ActionRegistry"] = None,
51
+ completer: Any = None,
52
+ prompt_string: Optional[str] = None,
53
+ history_path: Optional[Path] = None,
54
+ enable_image_paste: bool = True,
55
+ **kwargs,
56
+ ):
57
+ """
58
+ Initialize the async REPL interface.
59
+
60
+ Args:
61
+ action_registry: Action registry for commands and shortcuts
62
+ completer: Optional tab-completion provider
63
+ prompt_string: Custom prompt string (default: "User: ")
64
+ history_path: Optional path for command history storage
65
+ enable_image_paste: Enable image paste support (default: True)
66
+ """
67
+ self.prompt_string = HTML(prompt_string or "User: ")
68
+ self._image_buffer: Dict[str, ImageData] = {}
69
+ self._image_counter = 0
70
+
71
+ # Create ActionRegistry with prompt_toolkit printer
72
+ if action_registry is None:
73
+ action_registry = ActionRegistry(printer=lambda msg: print_formatted_text(msg))
74
+ self.action_registry = action_registry
75
+
76
+ # Register image paste action if enabled
77
+ if enable_image_paste:
78
+ self._register_image_paste_action()
79
+
80
+ self.session: PromptSession = PromptSession(
81
+ message=self.prompt_string,
82
+ history=self._create_history(history_path),
83
+ key_bindings=self._create_key_bindings(),
84
+ multiline=True,
85
+ completer=completer,
86
+ **kwargs,
87
+ )
88
+ self.main_app = self.session.app
89
+
90
+ def _register_image_paste_action(self) -> None:
91
+ """Register the image paste action if available."""
92
+ try:
93
+ paste_action = create_paste_action()
94
+ self.action_registry.register_action(paste_action)
95
+ except Exception as e:
96
+ logger.warning(f"Failed to register image paste action: {e}")
97
+
98
+ # ─────────────────────────────────────────────────────────────────────────
99
+ # Image Management
100
+ # ─────────────────────────────────────────────────────────────────────────
101
+
102
+ def add_image(self, img_bytes: bytes, media_type: str) -> str:
103
+ """Add image to buffer for next message send."""
104
+ self._image_counter += 1
105
+ image_id = f"img_{self._image_counter:03d}"
106
+ self._image_buffer[image_id] = ImageData(
107
+ data=img_bytes, media_type=media_type, timestamp=time.time()
108
+ )
109
+ logger.debug(f"Added image {image_id} ({media_type}, {len(img_bytes)} bytes)")
110
+ return image_id
111
+
112
+ def clear_images(self) -> None:
113
+ """Clear all images from the buffer."""
114
+ self._image_buffer.clear()
115
+
116
+ def get_images(self) -> Dict[str, ImageData]:
117
+ """Get current image buffer."""
118
+ return self._image_buffer.copy()
119
+
120
+ # ─────────────────────────────────────────────────────────────────────────
121
+ # Session Setup
122
+ # ─────────────────────────────────────────────────────────────────────────
123
+
124
+ def _create_history(self, path: Optional[Path]) -> Optional[FileHistory]:
125
+ """Create file history if path is provided."""
126
+ if path:
127
+ path.parent.mkdir(parents=True, exist_ok=True)
128
+ return FileHistory(str(path))
129
+ return None
130
+
131
+ def _create_key_bindings(self) -> KeyBindings:
132
+ """Create key bindings for the REPL session."""
133
+ bindings = KeyBindings()
134
+
135
+ @bindings.add("enter")
136
+ def handle_enter(event):
137
+ """Execute command or add new line."""
138
+ buffer_text = event.app.current_buffer.text
139
+ if self.action_registry.is_registered_command(buffer_text):
140
+ event.app.current_buffer.validate_and_handle()
141
+ else:
142
+ event.app.current_buffer.insert_text("\n")
143
+
144
+ @bindings.add(Keys.Escape, "enter")
145
+ def handle_alt_enter(event):
146
+ """Send message with Alt+Enter."""
147
+ event.app.current_buffer.validate_and_handle()
148
+
149
+ @bindings.add(Keys.F7)
150
+ @bindings.add(Keys.Escape, Keys.Escape)
151
+ def handle_clear(event):
152
+ """Clear buffer with F7 or Escape Escape."""
153
+ event.app.current_buffer.reset()
154
+
155
+ self._register_action_shortcuts(bindings)
156
+ return bindings
157
+
158
+ def _register_action_shortcuts(self, bindings: KeyBindings) -> None:
159
+ """Register keyboard shortcuts from the action registry."""
160
+ if not hasattr(self.action_registry, "key_map"):
161
+ return
162
+
163
+ for key_combo, action_name in self.action_registry.key_map.items():
164
+ self._register_shortcut(bindings, key_combo, action_name)
165
+
166
+ def _register_shortcut(self, bindings: KeyBindings, key_combo: str, action_name: str) -> None:
167
+ """Register a single keyboard shortcut."""
168
+ try:
169
+ keys = self._parse_key_combination(key_combo)
170
+
171
+ @bindings.add(*keys)
172
+ def handle_shortcut(event, action=action_name):
173
+ try:
174
+ context = ActionContext(
175
+ registry=self.action_registry,
176
+ repl=self,
177
+ buffer=event.current_buffer,
178
+ backend=getattr(self.action_registry, "backend", None),
179
+ event=event,
180
+ triggered_by="shortcut",
181
+ )
182
+ self.action_registry.execute_action(action, context)
183
+ except Exception:
184
+ logger.exception(f"Error executing shortcut '{key_combo}'")
185
+
186
+ except Exception as e:
187
+ logger.error(f"Failed to register shortcut '{key_combo}': {e}")
188
+
189
+ def _parse_key_combination(self, key_combo: str) -> tuple:
190
+ """Parse key combination string into prompt_toolkit format."""
191
+ key_combo = key_combo.lower().strip()
192
+
193
+ # Function keys (F1, F2, etc.)
194
+ if key_combo.startswith("f") and key_combo[1:].isdigit():
195
+ return (key_combo,)
196
+
197
+ # Modifier combinations
198
+ if "-" in key_combo:
199
+ parts = key_combo.split("-")
200
+ if len(parts) == 3:
201
+ return (key_combo,)
202
+ if len(parts) == 2:
203
+ modifier, key = parts
204
+ if modifier == "ctrl":
205
+ return ("c-" + key,)
206
+ elif modifier == "alt":
207
+ return (Keys.Escape, key)
208
+ elif modifier == "shift":
209
+ return ("s-" + key,)
210
+
211
+ return (key_combo,)
212
+
213
+ # ─────────────────────────────────────────────────────────────────────────
214
+ # Main REPL Loop
215
+ # ─────────────────────────────────────────────────────────────────────────
216
+
217
+ async def run(self, backend: AsyncBackend, initial_message: Optional[str] = None):
218
+ """
219
+ Run the async REPL session with the provided backend.
220
+
221
+ Args:
222
+ backend: Backend responsible for processing user input
223
+ initial_message: Optional message to process before starting loop
224
+ """
225
+ self.action_registry.backend = backend
226
+
227
+ if initial_message:
228
+ print(self.prompt_string, end="")
229
+ print(initial_message)
230
+ await self._process_input(initial_message, backend)
231
+ print()
232
+
233
+ while True:
234
+ try:
235
+ with patch_stdout():
236
+ user_input = await self.session.prompt_async()
237
+
238
+ if self._is_exit_command(user_input):
239
+ break
240
+ if not user_input.strip():
241
+ continue
242
+ if user_input.strip().startswith("/"):
243
+ self.action_registry.handle_command(user_input.strip())
244
+ await asyncio.sleep(0) # Yield for async cleanup
245
+ continue
246
+
247
+ await self._process_input(user_input, backend)
248
+
249
+ except (KeyboardInterrupt, EOFError):
250
+ print()
251
+ break
252
+ except Exception:
253
+ logger.exception("Error in REPL loop")
254
+
255
+ def _is_exit_command(self, user_input: str) -> bool:
256
+ """Check if input is an exit command."""
257
+ return user_input.strip().lower() in ["/exit", "/quit"]
258
+
259
+ # ─────────────────────────────────────────────────────────────────────────
260
+ # Input Processing with Cancellation
261
+ # ─────────────────────────────────────────────────────────────────────────
262
+
263
+ async def _process_input(self, user_input: str, backend: AsyncBackend):
264
+ """
265
+ Process user input with cancellation support.
266
+
267
+ Runs the backend processing task concurrently with a cancellation
268
+ listener, allowing users to cancel long-running operations.
269
+ """
270
+ async with self._cancellation_context() as ctx:
271
+ kwargs = self._build_backend_kwargs(ctx["trigger_cancel"])
272
+ backend_task = asyncio.create_task(backend.handle_input(user_input, **kwargs))
273
+
274
+ print(THINKING_MESSAGE)
275
+
276
+ done, _ = await asyncio.wait(
277
+ [backend_task, ctx["cancel_future"]],
278
+ return_when=asyncio.FIRST_COMPLETED,
279
+ )
280
+
281
+ if ctx["cancel_future"] in done:
282
+ await self._handle_cancellation(backend_task, backend)
283
+ elif backend_task in done:
284
+ try:
285
+ success = backend_task.result()
286
+ if not success:
287
+ print("Operation failed.")
288
+ except asyncio.CancelledError:
289
+ pass
290
+ except Exception:
291
+ logger.exception("Backend task raised exception")
292
+
293
+ @asynccontextmanager
294
+ async def _cancellation_context(self):
295
+ """
296
+ Context manager for cancellation support.
297
+
298
+ Sets up the cancel future, cancel app, and cleanup logic.
299
+ Yields a dict with cancel_future and trigger_cancel callback.
300
+ """
301
+ loop = asyncio.get_event_loop()
302
+ cancel_future: asyncio.Future = asyncio.Future()
303
+ cancel_app: Optional[Application] = None
304
+ listener_task: Optional[asyncio.Task] = None
305
+
306
+ def trigger_cancel():
307
+ """Thread-safe callback for tools to trigger cancellation."""
308
+
309
+ def _set_cancel():
310
+ if not cancel_future.done():
311
+ cancel_future.set_result(None)
312
+
313
+ loop.call_soon_threadsafe(_set_cancel)
314
+
315
+ try:
316
+ cancel_app = self._create_cancel_app(cancel_future)
317
+ listener_task = asyncio.create_task(cancel_app.run_async())
318
+
319
+ yield {
320
+ "cancel_future": cancel_future,
321
+ "trigger_cancel": trigger_cancel,
322
+ }
323
+
324
+ except KeyboardInterrupt:
325
+ logger.debug("KeyboardInterrupt during input processing")
326
+ if not cancel_future.done():
327
+ cancel_future.set_result(None)
328
+
329
+ except Exception:
330
+ logger.exception("Error during input processing")
331
+
332
+ finally:
333
+ self._image_buffer.clear()
334
+ await self._cleanup_cancel_context(cancel_app, listener_task)
335
+ self._reset_ui()
336
+
337
+ def _create_cancel_app(self, cancel_future: asyncio.Future) -> Application:
338
+ """Create the cancellation key bindings application."""
339
+ kb = KeyBindings()
340
+
341
+ @kb.add("escape", "c")
342
+ def handle_alt_c(event):
343
+ if not cancel_future.done():
344
+ cancel_future.set_result(None)
345
+ if not event.app.is_done:
346
+ event.app.exit()
347
+
348
+ @kb.add("c-c")
349
+ def handle_ctrl_c(event):
350
+ if not cancel_future.done():
351
+ cancel_future.set_result(None)
352
+ event.app.exit(exception=KeyboardInterrupt, style="class:aborting")
353
+
354
+ return Application(key_bindings=kb, output=DummyOutput(), input=create_input())
355
+
356
+ def _build_backend_kwargs(self, trigger_cancel: Callable[[], None]) -> Dict[str, Any]:
357
+ """Build kwargs dict for backend.handle_input()."""
358
+ kwargs: Dict[str, Any] = {"cancel_callback": trigger_cancel}
359
+ if self._image_buffer:
360
+ kwargs["images"] = self._image_buffer
361
+ return kwargs
362
+
363
+ async def _handle_cancellation(self, backend_task: asyncio.Task, backend: AsyncBackend) -> None:
364
+ """Handle cancellation of the backend task."""
365
+ print("\nOperation cancelled by user.")
366
+
367
+ # Signal cancellation to backend if it supports it
368
+ if isinstance(backend, CancellableBackend):
369
+ try:
370
+ backend.cancel("Operation cancelled by user")
371
+ except Exception as e:
372
+ logger.error(f"Error signaling cancellation to backend: {e}")
373
+
374
+ # Cancel the asyncio task
375
+ if backend_task and not backend_task.done():
376
+ backend_task.cancel()
377
+ try:
378
+ await backend_task
379
+ except asyncio.CancelledError:
380
+ pass
381
+
382
+ async def _cleanup_cancel_context(
383
+ self, cancel_app: Optional[Application], listener_task: Optional[asyncio.Task]
384
+ ) -> None:
385
+ """Cleanup the cancellation app and listener task."""
386
+ try:
387
+ if cancel_app and not cancel_app.is_done:
388
+ cancel_app.exit()
389
+
390
+ if listener_task and not listener_task.done():
391
+ listener_task.cancel()
392
+ try:
393
+ await listener_task
394
+ except asyncio.CancelledError:
395
+ pass
396
+ except Exception as e:
397
+ logger.debug(f"Cleanup exception (non-fatal): {e}")
398
+
399
+ def _reset_ui(self) -> None:
400
+ """Reset the UI after processing."""
401
+ try:
402
+ self.main_app.renderer.reset()
403
+ self.main_app.invalidate()
404
+ except Exception as e:
405
+ logger.debug(f"UI reset exception (non-fatal): {e}")
406
+
407
+
408
+ # ─────────────────────────────────────────────────────────────────────────────
409
+ # Convenience Function
410
+ # ─────────────────────────────────────────────────────────────────────────────
411
+
412
+
413
+ async def run_async_repl(
414
+ backend: AsyncBackend,
415
+ action_registry: Optional["ActionRegistry"] = None,
416
+ completer: Any = None,
417
+ initial_message: Optional[str] = None,
418
+ prompt_string: Optional[str] = None,
419
+ history_path: Optional[Path] = None,
420
+ **kwargs,
421
+ ):
422
+ """
423
+ Convenience function to create and run an AsyncREPL with action support.
424
+
425
+ Args:
426
+ backend: Backend for processing input
427
+ action_registry: Action registry for commands and shortcuts
428
+ completer: Optional completer
429
+ initial_message: Optional initial message
430
+ prompt_string: Optional custom prompt
431
+ history_path: Optional history file path
432
+ """
433
+ repl = AsyncREPL(action_registry, completer, prompt_string, history_path, **kwargs)
434
+ await repl.run(backend, initial_message)
@@ -6,7 +6,7 @@ from typing import Optional
6
6
  logger = logging.getLogger(__name__)
7
7
 
8
8
  from .actions.registry import ActionRegistry
9
- from .ptypes import ActionHandler, AsyncBackend
9
+ from .ptypes import ActionHandler, AsyncBackend, CancellableBackend
10
10
 
11
11
 
12
12
  class HeadlessREPL:
@@ -77,7 +77,7 @@ class HeadlessREPL:
77
77
  logger.info("Headless REPL interrupted by user (Ctrl+C)")
78
78
 
79
79
  # Signal cancellation to backend (if supported)
80
- if hasattr(backend, "cancel"):
80
+ if isinstance(backend, CancellableBackend):
81
81
  backend.cancel("Operation cancelled by user (Ctrl+C)")
82
82
  self.interrupted = True
83
83
  logger.debug("HeadlessREPL.run() exit - interrupted")