repl-toolkit 2.2.0__tar.gz → 2.3.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.
- {repl_toolkit-2.2.0/repl_toolkit.egg-info → repl_toolkit-2.3.0}/PKG-INFO +55 -4
- {repl_toolkit-2.2.0 → repl_toolkit-2.3.0}/README.md +54 -3
- {repl_toolkit-2.2.0 → repl_toolkit-2.3.0}/pyproject.toml +1 -1
- {repl_toolkit-2.2.0 → repl_toolkit-2.3.0}/repl_toolkit/__init__.py +1 -1
- {repl_toolkit-2.2.0 → repl_toolkit-2.3.0}/repl_toolkit/async_repl.py +56 -40
- {repl_toolkit-2.2.0 → repl_toolkit-2.3.0}/repl_toolkit/ptypes.py +33 -15
- {repl_toolkit-2.2.0 → repl_toolkit-2.3.0/repl_toolkit.egg-info}/PKG-INFO +55 -4
- {repl_toolkit-2.2.0 → repl_toolkit-2.3.0}/LICENSE +0 -0
- {repl_toolkit-2.2.0 → repl_toolkit-2.3.0}/repl_toolkit/actions/__init__.py +0 -0
- {repl_toolkit-2.2.0 → repl_toolkit-2.3.0}/repl_toolkit/actions/action.py +0 -0
- {repl_toolkit-2.2.0 → repl_toolkit-2.3.0}/repl_toolkit/actions/registry.py +0 -0
- {repl_toolkit-2.2.0 → repl_toolkit-2.3.0}/repl_toolkit/completion/__init__.py +0 -0
- {repl_toolkit-2.2.0 → repl_toolkit-2.3.0}/repl_toolkit/completion/prefix.py +0 -0
- {repl_toolkit-2.2.0 → repl_toolkit-2.3.0}/repl_toolkit/completion/shell_expansion.py +0 -0
- {repl_toolkit-2.2.0 → repl_toolkit-2.3.0}/repl_toolkit/formatting.py +0 -0
- {repl_toolkit-2.2.0 → repl_toolkit-2.3.0}/repl_toolkit/headless_repl.py +0 -0
- {repl_toolkit-2.2.0 → repl_toolkit-2.3.0}/repl_toolkit/images.py +0 -0
- {repl_toolkit-2.2.0 → repl_toolkit-2.3.0}/repl_toolkit/tests/__init__.py +0 -0
- {repl_toolkit-2.2.0 → repl_toolkit-2.3.0}/repl_toolkit/tests/conftest.py +0 -0
- {repl_toolkit-2.2.0 → repl_toolkit-2.3.0}/repl_toolkit/tests/test_actions.py +0 -0
- {repl_toolkit-2.2.0 → repl_toolkit-2.3.0}/repl_toolkit/tests/test_async_repl.py +0 -0
- {repl_toolkit-2.2.0 → repl_toolkit-2.3.0}/repl_toolkit/tests/test_cancellation.py +0 -0
- {repl_toolkit-2.2.0 → repl_toolkit-2.3.0}/repl_toolkit/tests/test_completion.py +0 -0
- {repl_toolkit-2.2.0 → repl_toolkit-2.3.0}/repl_toolkit/tests/test_ctrl_c_cancel.py +0 -0
- {repl_toolkit-2.2.0 → repl_toolkit-2.3.0}/repl_toolkit/tests/test_formatting.py +0 -0
- {repl_toolkit-2.2.0 → repl_toolkit-2.3.0}/repl_toolkit/tests/test_headless.py +0 -0
- {repl_toolkit-2.2.0 → repl_toolkit-2.3.0}/repl_toolkit/tests/test_image_utils.py +0 -0
- {repl_toolkit-2.2.0 → repl_toolkit-2.3.0}/repl_toolkit/tests/test_images.py +0 -0
- {repl_toolkit-2.2.0 → repl_toolkit-2.3.0}/repl_toolkit/tests/test_output_handling.py +0 -0
- {repl_toolkit-2.2.0 → repl_toolkit-2.3.0}/repl_toolkit/tests/test_types.py +0 -0
- {repl_toolkit-2.2.0 → repl_toolkit-2.3.0}/repl_toolkit.egg-info/SOURCES.txt +0 -0
- {repl_toolkit-2.2.0 → repl_toolkit-2.3.0}/repl_toolkit.egg-info/dependency_links.txt +0 -0
- {repl_toolkit-2.2.0 → repl_toolkit-2.3.0}/repl_toolkit.egg-info/requires.txt +0 -0
- {repl_toolkit-2.2.0 → repl_toolkit-2.3.0}/repl_toolkit.egg-info/top_level.txt +0 -0
- {repl_toolkit-2.2.0 → repl_toolkit-2.3.0}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: repl-toolkit
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.3.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
|
|
@@ -637,8 +637,15 @@ class CancellableBackend:
|
|
|
637
637
|
def __init__(self):
|
|
638
638
|
self._cancel_requested = False
|
|
639
639
|
|
|
640
|
-
def cancel(self, message: Optional[str] = None) ->
|
|
641
|
-
"""
|
|
640
|
+
def cancel(self, message: Optional[str] = None) -> Optional[bool]:
|
|
641
|
+
"""
|
|
642
|
+
Optional method to support cooperative cancellation.
|
|
643
|
+
|
|
644
|
+
Returns:
|
|
645
|
+
Optional[bool]:
|
|
646
|
+
- True or None (default): REPL force-cancels the asyncio task
|
|
647
|
+
- False: REPL lets handle_input() complete gracefully
|
|
648
|
+
"""
|
|
642
649
|
self._cancel_requested = True
|
|
643
650
|
if message:
|
|
644
651
|
print(f"Cancellation: {message}")
|
|
@@ -661,6 +668,49 @@ class CancellableBackend:
|
|
|
661
668
|
return True
|
|
662
669
|
```
|
|
663
670
|
|
|
671
|
+
### Cancellation Behavior Control (v2.3.0)
|
|
672
|
+
|
|
673
|
+
The `cancel()` method can return a boolean to control how the REPL handles cancellation:
|
|
674
|
+
|
|
675
|
+
```python
|
|
676
|
+
class ForceCancel Backend:
|
|
677
|
+
"""Traditional behavior - REPL cancels the asyncio task."""
|
|
678
|
+
|
|
679
|
+
def cancel(self, message: Optional[str] = None) -> bool:
|
|
680
|
+
self._cancelled = True
|
|
681
|
+
return True # or None - REPL force-cancels task
|
|
682
|
+
```
|
|
683
|
+
|
|
684
|
+
```python
|
|
685
|
+
class GracefulBackend:
|
|
686
|
+
"""New behavior - let handle_input() complete gracefully."""
|
|
687
|
+
|
|
688
|
+
def cancel(self, message: Optional[str] = None) -> bool:
|
|
689
|
+
self._cancelled = True
|
|
690
|
+
return False # REPL waits for handle_input() to finish
|
|
691
|
+
|
|
692
|
+
async def handle_input(self, user_input: str, **kwargs) -> bool:
|
|
693
|
+
self._cancelled = False
|
|
694
|
+
|
|
695
|
+
# Your processing with checkpoints
|
|
696
|
+
for step in steps:
|
|
697
|
+
if self._cancelled:
|
|
698
|
+
await self.cleanup() # Cleanup hooks fire!
|
|
699
|
+
return False
|
|
700
|
+
await process(step)
|
|
701
|
+
return True
|
|
702
|
+
```
|
|
703
|
+
|
|
704
|
+
**When to return False:**
|
|
705
|
+
- Backend uses cleanup hooks that need to fire
|
|
706
|
+
- Using agent frameworks with cleanup/finalization logic
|
|
707
|
+
- Need to save state or close connections gracefully
|
|
708
|
+
|
|
709
|
+
**When to return True/None:**
|
|
710
|
+
- Quick cancellation is preferred
|
|
711
|
+
- No cleanup needed
|
|
712
|
+
- Traditional async task cancellation is sufficient
|
|
713
|
+
|
|
664
714
|
### When cancel() is Called
|
|
665
715
|
|
|
666
716
|
The REPL automatically calls `backend.cancel()` (if implemented) when:
|
|
@@ -682,11 +732,12 @@ class SubprocessBackend:
|
|
|
682
732
|
self._cancel_requested = False
|
|
683
733
|
self._current_process = None
|
|
684
734
|
|
|
685
|
-
def cancel(self, message: Optional[str] = None) ->
|
|
735
|
+
def cancel(self, message: Optional[str] = None) -> bool:
|
|
686
736
|
"""Cancel current subprocess."""
|
|
687
737
|
self._cancel_requested = True
|
|
688
738
|
if self._current_process:
|
|
689
739
|
self._current_process.terminate() # Stop the subprocess
|
|
740
|
+
return True # Force cancel the asyncio task
|
|
690
741
|
|
|
691
742
|
async def handle_input(self, user_input: str, **kwargs) -> bool:
|
|
692
743
|
"""Run command with cancellation support."""
|
|
@@ -592,8 +592,15 @@ class CancellableBackend:
|
|
|
592
592
|
def __init__(self):
|
|
593
593
|
self._cancel_requested = False
|
|
594
594
|
|
|
595
|
-
def cancel(self, message: Optional[str] = None) ->
|
|
596
|
-
"""
|
|
595
|
+
def cancel(self, message: Optional[str] = None) -> Optional[bool]:
|
|
596
|
+
"""
|
|
597
|
+
Optional method to support cooperative cancellation.
|
|
598
|
+
|
|
599
|
+
Returns:
|
|
600
|
+
Optional[bool]:
|
|
601
|
+
- True or None (default): REPL force-cancels the asyncio task
|
|
602
|
+
- False: REPL lets handle_input() complete gracefully
|
|
603
|
+
"""
|
|
597
604
|
self._cancel_requested = True
|
|
598
605
|
if message:
|
|
599
606
|
print(f"Cancellation: {message}")
|
|
@@ -616,6 +623,49 @@ class CancellableBackend:
|
|
|
616
623
|
return True
|
|
617
624
|
```
|
|
618
625
|
|
|
626
|
+
### Cancellation Behavior Control (v2.3.0)
|
|
627
|
+
|
|
628
|
+
The `cancel()` method can return a boolean to control how the REPL handles cancellation:
|
|
629
|
+
|
|
630
|
+
```python
|
|
631
|
+
class ForceCancel Backend:
|
|
632
|
+
"""Traditional behavior - REPL cancels the asyncio task."""
|
|
633
|
+
|
|
634
|
+
def cancel(self, message: Optional[str] = None) -> bool:
|
|
635
|
+
self._cancelled = True
|
|
636
|
+
return True # or None - REPL force-cancels task
|
|
637
|
+
```
|
|
638
|
+
|
|
639
|
+
```python
|
|
640
|
+
class GracefulBackend:
|
|
641
|
+
"""New behavior - let handle_input() complete gracefully."""
|
|
642
|
+
|
|
643
|
+
def cancel(self, message: Optional[str] = None) -> bool:
|
|
644
|
+
self._cancelled = True
|
|
645
|
+
return False # REPL waits for handle_input() to finish
|
|
646
|
+
|
|
647
|
+
async def handle_input(self, user_input: str, **kwargs) -> bool:
|
|
648
|
+
self._cancelled = False
|
|
649
|
+
|
|
650
|
+
# Your processing with checkpoints
|
|
651
|
+
for step in steps:
|
|
652
|
+
if self._cancelled:
|
|
653
|
+
await self.cleanup() # Cleanup hooks fire!
|
|
654
|
+
return False
|
|
655
|
+
await process(step)
|
|
656
|
+
return True
|
|
657
|
+
```
|
|
658
|
+
|
|
659
|
+
**When to return False:**
|
|
660
|
+
- Backend uses cleanup hooks that need to fire
|
|
661
|
+
- Using agent frameworks with cleanup/finalization logic
|
|
662
|
+
- Need to save state or close connections gracefully
|
|
663
|
+
|
|
664
|
+
**When to return True/None:**
|
|
665
|
+
- Quick cancellation is preferred
|
|
666
|
+
- No cleanup needed
|
|
667
|
+
- Traditional async task cancellation is sufficient
|
|
668
|
+
|
|
619
669
|
### When cancel() is Called
|
|
620
670
|
|
|
621
671
|
The REPL automatically calls `backend.cancel()` (if implemented) when:
|
|
@@ -637,11 +687,12 @@ class SubprocessBackend:
|
|
|
637
687
|
self._cancel_requested = False
|
|
638
688
|
self._current_process = None
|
|
639
689
|
|
|
640
|
-
def cancel(self, message: Optional[str] = None) ->
|
|
690
|
+
def cancel(self, message: Optional[str] = None) -> bool:
|
|
641
691
|
"""Cancel current subprocess."""
|
|
642
692
|
self._cancel_requested = True
|
|
643
693
|
if self._current_process:
|
|
644
694
|
self._current_process.terminate() # Stop the subprocess
|
|
695
|
+
return True # Force cancel the asyncio task
|
|
645
696
|
|
|
646
697
|
async def handle_input(self, user_input: str, **kwargs) -> bool:
|
|
647
698
|
"""Run command with cancellation support."""
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "repl-toolkit"
|
|
7
|
-
version = "2.
|
|
7
|
+
version = "2.3.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"
|
|
@@ -37,7 +37,7 @@ import logging
|
|
|
37
37
|
# Add NullHandler to prevent "No handler found" warnings
|
|
38
38
|
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
|
39
39
|
|
|
40
|
-
__version__ = "2.
|
|
40
|
+
__version__ = "2.3.0"
|
|
41
41
|
|
|
42
42
|
from .actions import Action, ActionContext, ActionRegistry
|
|
43
43
|
from .async_repl import AsyncREPL, run_async_repl
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
"""
|
|
2
2
|
Async REPL interface with action support for repl_toolkit.
|
|
3
3
|
|
|
4
|
-
Provides an interactive chat interface with
|
|
5
|
-
|
|
6
|
-
|
|
4
|
+
Provides an interactive chat interface with:
|
|
5
|
+
- Command history and multi-line editing
|
|
6
|
+
- Action handling (commands and keyboard shortcuts)
|
|
7
|
+
- Image paste support
|
|
8
|
+
- Cancellation of long-running operations via Ctrl+C or Alt+C
|
|
7
9
|
"""
|
|
8
10
|
|
|
9
11
|
import asyncio
|
|
@@ -35,14 +37,10 @@ THINKING_MESSAGE = HTML("<i><grey>Thinking... (Press Ctrl+C or Alt+C to cancel)<
|
|
|
35
37
|
|
|
36
38
|
class AsyncREPL:
|
|
37
39
|
"""
|
|
38
|
-
|
|
40
|
+
Async REPL with action support and cancellation handling.
|
|
39
41
|
|
|
40
|
-
Provides user input handling, action processing
|
|
41
|
-
|
|
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.
|
|
42
|
+
Provides user input handling, action processing, and robust cancellation
|
|
43
|
+
of long-running backend operations.
|
|
46
44
|
"""
|
|
47
45
|
|
|
48
46
|
def __init__(
|
|
@@ -68,12 +66,10 @@ class AsyncREPL:
|
|
|
68
66
|
self._image_buffer: Dict[str, ImageData] = {}
|
|
69
67
|
self._image_counter = 0
|
|
70
68
|
|
|
71
|
-
# Create ActionRegistry with prompt_toolkit printer
|
|
72
69
|
if action_registry is None:
|
|
73
70
|
action_registry = ActionRegistry(printer=lambda msg: print_formatted_text(msg))
|
|
74
71
|
self.action_registry = action_registry
|
|
75
72
|
|
|
76
|
-
# Register image paste action if enabled
|
|
77
73
|
if enable_image_paste:
|
|
78
74
|
self._register_image_paste_action()
|
|
79
75
|
|
|
@@ -106,7 +102,6 @@ class AsyncREPL:
|
|
|
106
102
|
self._image_buffer[image_id] = ImageData(
|
|
107
103
|
data=img_bytes, media_type=media_type, timestamp=time.time()
|
|
108
104
|
)
|
|
109
|
-
logger.debug(f"Added image {image_id} ({media_type}, {len(img_bytes)} bytes)")
|
|
110
105
|
return image_id
|
|
111
106
|
|
|
112
107
|
def clear_images(self) -> None:
|
|
@@ -134,7 +129,6 @@ class AsyncREPL:
|
|
|
134
129
|
|
|
135
130
|
@bindings.add("enter")
|
|
136
131
|
def handle_enter(event):
|
|
137
|
-
"""Execute command or add new line."""
|
|
138
132
|
buffer_text = event.app.current_buffer.text
|
|
139
133
|
if self.action_registry.is_registered_command(buffer_text):
|
|
140
134
|
event.app.current_buffer.validate_and_handle()
|
|
@@ -143,13 +137,11 @@ class AsyncREPL:
|
|
|
143
137
|
|
|
144
138
|
@bindings.add(Keys.Escape, "enter")
|
|
145
139
|
def handle_alt_enter(event):
|
|
146
|
-
"""Send message with Alt+Enter."""
|
|
147
140
|
event.app.current_buffer.validate_and_handle()
|
|
148
141
|
|
|
149
142
|
@bindings.add(Keys.F7)
|
|
150
143
|
@bindings.add(Keys.Escape, Keys.Escape)
|
|
151
144
|
def handle_clear(event):
|
|
152
|
-
"""Clear buffer with F7 or Escape Escape."""
|
|
153
145
|
event.app.current_buffer.reset()
|
|
154
146
|
|
|
155
147
|
self._register_action_shortcuts(bindings)
|
|
@@ -190,11 +182,9 @@ class AsyncREPL:
|
|
|
190
182
|
"""Parse key combination string into prompt_toolkit format."""
|
|
191
183
|
key_combo = key_combo.lower().strip()
|
|
192
184
|
|
|
193
|
-
# Function keys (F1, F2, etc.)
|
|
194
185
|
if key_combo.startswith("f") and key_combo[1:].isdigit():
|
|
195
186
|
return (key_combo,)
|
|
196
187
|
|
|
197
|
-
# Modifier combinations
|
|
198
188
|
if "-" in key_combo:
|
|
199
189
|
parts = key_combo.split("-")
|
|
200
190
|
if len(parts) == 3:
|
|
@@ -241,7 +231,7 @@ class AsyncREPL:
|
|
|
241
231
|
continue
|
|
242
232
|
if user_input.strip().startswith("/"):
|
|
243
233
|
self.action_registry.handle_command(user_input.strip())
|
|
244
|
-
await asyncio.sleep(0)
|
|
234
|
+
await asyncio.sleep(0)
|
|
245
235
|
continue
|
|
246
236
|
|
|
247
237
|
await self._process_input(user_input, backend)
|
|
@@ -264,8 +254,8 @@ class AsyncREPL:
|
|
|
264
254
|
"""
|
|
265
255
|
Process user input with cancellation support.
|
|
266
256
|
|
|
267
|
-
Runs the backend
|
|
268
|
-
|
|
257
|
+
Runs the backend task concurrently with a cancellation listener,
|
|
258
|
+
allowing users to cancel via Ctrl+C or Alt+C.
|
|
269
259
|
"""
|
|
270
260
|
async with self._cancellation_context() as ctx:
|
|
271
261
|
kwargs = self._build_backend_kwargs(ctx["trigger_cancel"])
|
|
@@ -295,7 +285,7 @@ class AsyncREPL:
|
|
|
295
285
|
"""
|
|
296
286
|
Context manager for cancellation support.
|
|
297
287
|
|
|
298
|
-
Sets up the cancel future
|
|
288
|
+
Sets up the cancel future and cancellation key listener.
|
|
299
289
|
Yields a dict with cancel_future and trigger_cancel callback.
|
|
300
290
|
"""
|
|
301
291
|
loop = asyncio.get_event_loop()
|
|
@@ -304,7 +294,7 @@ class AsyncREPL:
|
|
|
304
294
|
listener_task: Optional[asyncio.Task] = None
|
|
305
295
|
|
|
306
296
|
def trigger_cancel():
|
|
307
|
-
"""Thread-safe callback
|
|
297
|
+
"""Thread-safe callback to trigger cancellation."""
|
|
308
298
|
|
|
309
299
|
def _set_cancel():
|
|
310
300
|
if not cancel_future.done():
|
|
@@ -322,7 +312,6 @@ class AsyncREPL:
|
|
|
322
312
|
}
|
|
323
313
|
|
|
324
314
|
except KeyboardInterrupt:
|
|
325
|
-
logger.debug("KeyboardInterrupt during input processing")
|
|
326
315
|
if not cancel_future.done():
|
|
327
316
|
cancel_future.set_result(None)
|
|
328
317
|
|
|
@@ -335,7 +324,7 @@ class AsyncREPL:
|
|
|
335
324
|
self._reset_ui()
|
|
336
325
|
|
|
337
326
|
def _create_cancel_app(self, cancel_future: asyncio.Future) -> Application:
|
|
338
|
-
"""Create
|
|
327
|
+
"""Create application that listens for Ctrl+C and Alt+C."""
|
|
339
328
|
kb = KeyBindings()
|
|
340
329
|
|
|
341
330
|
@kb.add("escape", "c")
|
|
@@ -349,7 +338,8 @@ class AsyncREPL:
|
|
|
349
338
|
def handle_ctrl_c(event):
|
|
350
339
|
if not cancel_future.done():
|
|
351
340
|
cancel_future.set_result(None)
|
|
352
|
-
event.app.
|
|
341
|
+
if not event.app.is_done:
|
|
342
|
+
event.app.exit()
|
|
353
343
|
|
|
354
344
|
return Application(key_bindings=kb, output=DummyOutput(), input=create_input())
|
|
355
345
|
|
|
@@ -361,23 +351,48 @@ class AsyncREPL:
|
|
|
361
351
|
return kwargs
|
|
362
352
|
|
|
363
353
|
async def _handle_cancellation(self, backend_task: asyncio.Task, backend: AsyncBackend) -> None:
|
|
364
|
-
"""
|
|
354
|
+
"""
|
|
355
|
+
Handle cancellation of the backend task.
|
|
356
|
+
|
|
357
|
+
Calls backend.cancel() if supported and respects its return value:
|
|
358
|
+
- True or None: Force-cancel the asyncio task (backward compatible default)
|
|
359
|
+
- False: Wait for task to complete gracefully (allows cleanup hooks to fire)
|
|
360
|
+
"""
|
|
365
361
|
print("\nOperation cancelled by user.")
|
|
366
362
|
|
|
367
|
-
#
|
|
363
|
+
# Default: force cancel (backward compatible with old backends)
|
|
364
|
+
should_force_cancel = True
|
|
365
|
+
|
|
366
|
+
# Signal cancellation to backend if it supports the protocol
|
|
368
367
|
if isinstance(backend, CancellableBackend):
|
|
369
368
|
try:
|
|
370
|
-
backend.cancel("Operation cancelled by user")
|
|
369
|
+
result = backend.cancel("Operation cancelled by user")
|
|
370
|
+
# Only False means "let me complete gracefully"
|
|
371
|
+
# True or None (legacy) means "force cancel"
|
|
372
|
+
if result is False:
|
|
373
|
+
should_force_cancel = False
|
|
371
374
|
except Exception as e:
|
|
372
|
-
logger.error(f"Error signaling cancellation
|
|
375
|
+
logger.error(f"Error signaling cancellation: {e}")
|
|
373
376
|
|
|
374
|
-
|
|
375
|
-
|
|
377
|
+
if backend_task.done():
|
|
378
|
+
return
|
|
379
|
+
|
|
380
|
+
if should_force_cancel:
|
|
381
|
+
# Force cancel - backward compatible behavior
|
|
376
382
|
backend_task.cancel()
|
|
377
383
|
try:
|
|
378
384
|
await backend_task
|
|
379
385
|
except asyncio.CancelledError:
|
|
380
386
|
pass
|
|
387
|
+
else:
|
|
388
|
+
# Graceful completion - wait for task to finish naturally
|
|
389
|
+
# This allows cleanup hooks to fire in the backend
|
|
390
|
+
try:
|
|
391
|
+
await backend_task
|
|
392
|
+
except asyncio.CancelledError:
|
|
393
|
+
pass
|
|
394
|
+
except Exception:
|
|
395
|
+
logger.exception("Backend task raised exception during cancellation")
|
|
381
396
|
|
|
382
397
|
async def _cleanup_cancel_context(
|
|
383
398
|
self, cancel_app: Optional[Application], listener_task: Optional[asyncio.Task]
|
|
@@ -387,22 +402,23 @@ class AsyncREPL:
|
|
|
387
402
|
if cancel_app and not cancel_app.is_done:
|
|
388
403
|
cancel_app.exit()
|
|
389
404
|
|
|
390
|
-
if listener_task
|
|
391
|
-
listener_task.
|
|
405
|
+
if listener_task:
|
|
406
|
+
if not listener_task.done():
|
|
407
|
+
listener_task.cancel()
|
|
392
408
|
try:
|
|
393
409
|
await listener_task
|
|
394
|
-
except asyncio.CancelledError:
|
|
410
|
+
except (asyncio.CancelledError, KeyboardInterrupt, Exception):
|
|
395
411
|
pass
|
|
396
|
-
except Exception
|
|
397
|
-
|
|
412
|
+
except Exception:
|
|
413
|
+
pass
|
|
398
414
|
|
|
399
415
|
def _reset_ui(self) -> None:
|
|
400
416
|
"""Reset the UI after processing."""
|
|
401
417
|
try:
|
|
402
418
|
self.main_app.renderer.reset()
|
|
403
419
|
self.main_app.invalidate()
|
|
404
|
-
except Exception
|
|
405
|
-
|
|
420
|
+
except Exception:
|
|
421
|
+
pass
|
|
406
422
|
|
|
407
423
|
|
|
408
424
|
# ─────────────────────────────────────────────────────────────────────────────
|
|
@@ -420,7 +436,7 @@ async def run_async_repl(
|
|
|
420
436
|
**kwargs,
|
|
421
437
|
):
|
|
422
438
|
"""
|
|
423
|
-
Convenience function to create and run an AsyncREPL
|
|
439
|
+
Convenience function to create and run an AsyncREPL.
|
|
424
440
|
|
|
425
441
|
Args:
|
|
426
442
|
backend: Backend for processing input
|
|
@@ -46,30 +46,41 @@ class CancellableBackend(AsyncBackend, Protocol):
|
|
|
46
46
|
Protocol for async backends that support cooperative cancellation.
|
|
47
47
|
|
|
48
48
|
Extends AsyncBackend with a cancel() method that allows the REPL to
|
|
49
|
-
signal cancellation to the backend. The backend
|
|
50
|
-
|
|
49
|
+
signal cancellation to the backend. The backend can control whether
|
|
50
|
+
the REPL should force-cancel the asyncio task or let it complete gracefully.
|
|
51
51
|
|
|
52
52
|
Implementation Guidelines:
|
|
53
53
|
1. cancel() MUST be non-blocking (return immediately)
|
|
54
54
|
2. Set an internal cancellation token/flag
|
|
55
|
-
3.
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
55
|
+
3. Return value controls REPL behavior:
|
|
56
|
+
- True or None: Force cancel the asyncio task (default, backward compatible)
|
|
57
|
+
- False: Let handle_input() complete gracefully
|
|
58
|
+
4. handle_input() should check the cancellation flag at safe checkpoints
|
|
59
|
+
5. Reset the flag at the start of each new operation
|
|
60
|
+
|
|
61
|
+
Backward Compatibility:
|
|
62
|
+
- Backends without cancel() → task is force-cancelled
|
|
63
|
+
- Backends with cancel() returning None → task is force-cancelled
|
|
64
|
+
- This maintains behavior expected by existing implementations
|
|
65
|
+
|
|
66
|
+
Example (force cancellation - default/legacy behavior):
|
|
67
|
+
class LegacyBackend:
|
|
64
68
|
def cancel(self, message: Optional[str] = None) -> None:
|
|
65
|
-
self.
|
|
69
|
+
self._cancelled = True
|
|
70
|
+
# Returns None → REPL force-cancels the task
|
|
71
|
+
|
|
72
|
+
Example (graceful completion - new behavior):
|
|
73
|
+
class GracefulBackend:
|
|
74
|
+
def cancel(self, message: Optional[str] = None) -> bool:
|
|
75
|
+
self._token.cancel(message)
|
|
76
|
+
return False # Let handle_input() complete, hooks will fire
|
|
66
77
|
|
|
67
78
|
async def handle_input(self, user_input: str, **kwargs) -> bool:
|
|
68
|
-
|
|
69
|
-
|
|
79
|
+
# Process with agent - hooks handle cleanup on cancellation
|
|
80
|
+
return await self.agent.process(user_input)
|
|
70
81
|
"""
|
|
71
82
|
|
|
72
|
-
def cancel(self, message: Optional[str] = None) ->
|
|
83
|
+
def cancel(self, message: Optional[str] = None) -> Optional[bool]:
|
|
73
84
|
"""
|
|
74
85
|
Signal cancellation to the backend.
|
|
75
86
|
|
|
@@ -79,6 +90,13 @@ class CancellableBackend(AsyncBackend, Protocol):
|
|
|
79
90
|
Args:
|
|
80
91
|
message: Optional message describing the cancellation reason.
|
|
81
92
|
Typically "Operation cancelled by user".
|
|
93
|
+
|
|
94
|
+
Returns:
|
|
95
|
+
Optional[bool]:
|
|
96
|
+
True or None: REPL should force-cancel the asyncio task
|
|
97
|
+
(handle_input receives CancelledError)
|
|
98
|
+
False: REPL should let handle_input() complete gracefully
|
|
99
|
+
(allows cleanup hooks to fire)
|
|
82
100
|
"""
|
|
83
101
|
...
|
|
84
102
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: repl-toolkit
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.3.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
|
|
@@ -637,8 +637,15 @@ class CancellableBackend:
|
|
|
637
637
|
def __init__(self):
|
|
638
638
|
self._cancel_requested = False
|
|
639
639
|
|
|
640
|
-
def cancel(self, message: Optional[str] = None) ->
|
|
641
|
-
"""
|
|
640
|
+
def cancel(self, message: Optional[str] = None) -> Optional[bool]:
|
|
641
|
+
"""
|
|
642
|
+
Optional method to support cooperative cancellation.
|
|
643
|
+
|
|
644
|
+
Returns:
|
|
645
|
+
Optional[bool]:
|
|
646
|
+
- True or None (default): REPL force-cancels the asyncio task
|
|
647
|
+
- False: REPL lets handle_input() complete gracefully
|
|
648
|
+
"""
|
|
642
649
|
self._cancel_requested = True
|
|
643
650
|
if message:
|
|
644
651
|
print(f"Cancellation: {message}")
|
|
@@ -661,6 +668,49 @@ class CancellableBackend:
|
|
|
661
668
|
return True
|
|
662
669
|
```
|
|
663
670
|
|
|
671
|
+
### Cancellation Behavior Control (v2.3.0)
|
|
672
|
+
|
|
673
|
+
The `cancel()` method can return a boolean to control how the REPL handles cancellation:
|
|
674
|
+
|
|
675
|
+
```python
|
|
676
|
+
class ForceCancel Backend:
|
|
677
|
+
"""Traditional behavior - REPL cancels the asyncio task."""
|
|
678
|
+
|
|
679
|
+
def cancel(self, message: Optional[str] = None) -> bool:
|
|
680
|
+
self._cancelled = True
|
|
681
|
+
return True # or None - REPL force-cancels task
|
|
682
|
+
```
|
|
683
|
+
|
|
684
|
+
```python
|
|
685
|
+
class GracefulBackend:
|
|
686
|
+
"""New behavior - let handle_input() complete gracefully."""
|
|
687
|
+
|
|
688
|
+
def cancel(self, message: Optional[str] = None) -> bool:
|
|
689
|
+
self._cancelled = True
|
|
690
|
+
return False # REPL waits for handle_input() to finish
|
|
691
|
+
|
|
692
|
+
async def handle_input(self, user_input: str, **kwargs) -> bool:
|
|
693
|
+
self._cancelled = False
|
|
694
|
+
|
|
695
|
+
# Your processing with checkpoints
|
|
696
|
+
for step in steps:
|
|
697
|
+
if self._cancelled:
|
|
698
|
+
await self.cleanup() # Cleanup hooks fire!
|
|
699
|
+
return False
|
|
700
|
+
await process(step)
|
|
701
|
+
return True
|
|
702
|
+
```
|
|
703
|
+
|
|
704
|
+
**When to return False:**
|
|
705
|
+
- Backend uses cleanup hooks that need to fire
|
|
706
|
+
- Using agent frameworks with cleanup/finalization logic
|
|
707
|
+
- Need to save state or close connections gracefully
|
|
708
|
+
|
|
709
|
+
**When to return True/None:**
|
|
710
|
+
- Quick cancellation is preferred
|
|
711
|
+
- No cleanup needed
|
|
712
|
+
- Traditional async task cancellation is sufficient
|
|
713
|
+
|
|
664
714
|
### When cancel() is Called
|
|
665
715
|
|
|
666
716
|
The REPL automatically calls `backend.cancel()` (if implemented) when:
|
|
@@ -682,11 +732,12 @@ class SubprocessBackend:
|
|
|
682
732
|
self._cancel_requested = False
|
|
683
733
|
self._current_process = None
|
|
684
734
|
|
|
685
|
-
def cancel(self, message: Optional[str] = None) ->
|
|
735
|
+
def cancel(self, message: Optional[str] = None) -> bool:
|
|
686
736
|
"""Cancel current subprocess."""
|
|
687
737
|
self._cancel_requested = True
|
|
688
738
|
if self._current_process:
|
|
689
739
|
self._current_process.terminate() # Stop the subprocess
|
|
740
|
+
return True # Force cancel the asyncio task
|
|
690
741
|
|
|
691
742
|
async def handle_input(self, user_input: str, **kwargs) -> bool:
|
|
692
743
|
"""Run command with cancellation support."""
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|