repl-toolkit 2.2.0__tar.gz → 2.4.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 (35) hide show
  1. {repl_toolkit-2.2.0/repl_toolkit.egg-info → repl_toolkit-2.4.0}/PKG-INFO +90 -10
  2. {repl_toolkit-2.2.0 → repl_toolkit-2.4.0}/README.md +86 -5
  3. {repl_toolkit-2.2.0 → repl_toolkit-2.4.0}/pyproject.toml +5 -6
  4. {repl_toolkit-2.2.0 → repl_toolkit-2.4.0}/repl_toolkit/__init__.py +3 -2
  5. {repl_toolkit-2.2.0 → repl_toolkit-2.4.0}/repl_toolkit/actions/__init__.py +14 -1
  6. {repl_toolkit-2.2.0 → repl_toolkit-2.4.0}/repl_toolkit/actions/action.py +48 -1
  7. {repl_toolkit-2.2.0 → repl_toolkit-2.4.0}/repl_toolkit/actions/registry.py +33 -10
  8. {repl_toolkit-2.2.0 → repl_toolkit-2.4.0}/repl_toolkit/async_repl.py +76 -45
  9. {repl_toolkit-2.2.0 → repl_toolkit-2.4.0}/repl_toolkit/headless_repl.py +25 -6
  10. {repl_toolkit-2.2.0 → repl_toolkit-2.4.0}/repl_toolkit/ptypes.py +46 -18
  11. {repl_toolkit-2.2.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/test_actions.py +167 -0
  12. {repl_toolkit-2.2.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/test_async_repl.py +296 -1
  13. {repl_toolkit-2.2.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/test_headless.py +158 -1
  14. {repl_toolkit-2.2.0 → repl_toolkit-2.4.0/repl_toolkit.egg-info}/PKG-INFO +90 -10
  15. {repl_toolkit-2.2.0 → repl_toolkit-2.4.0}/LICENSE +0 -0
  16. {repl_toolkit-2.2.0 → repl_toolkit-2.4.0}/repl_toolkit/completion/__init__.py +0 -0
  17. {repl_toolkit-2.2.0 → repl_toolkit-2.4.0}/repl_toolkit/completion/prefix.py +0 -0
  18. {repl_toolkit-2.2.0 → repl_toolkit-2.4.0}/repl_toolkit/completion/shell_expansion.py +0 -0
  19. {repl_toolkit-2.2.0 → repl_toolkit-2.4.0}/repl_toolkit/formatting.py +0 -0
  20. {repl_toolkit-2.2.0 → repl_toolkit-2.4.0}/repl_toolkit/images.py +0 -0
  21. {repl_toolkit-2.2.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/__init__.py +0 -0
  22. {repl_toolkit-2.2.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/conftest.py +0 -0
  23. {repl_toolkit-2.2.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/test_cancellation.py +0 -0
  24. {repl_toolkit-2.2.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/test_completion.py +0 -0
  25. {repl_toolkit-2.2.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/test_ctrl_c_cancel.py +0 -0
  26. {repl_toolkit-2.2.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/test_formatting.py +0 -0
  27. {repl_toolkit-2.2.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/test_image_utils.py +0 -0
  28. {repl_toolkit-2.2.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/test_images.py +0 -0
  29. {repl_toolkit-2.2.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/test_output_handling.py +0 -0
  30. {repl_toolkit-2.2.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/test_types.py +0 -0
  31. {repl_toolkit-2.2.0 → repl_toolkit-2.4.0}/repl_toolkit.egg-info/SOURCES.txt +0 -0
  32. {repl_toolkit-2.2.0 → repl_toolkit-2.4.0}/repl_toolkit.egg-info/dependency_links.txt +0 -0
  33. {repl_toolkit-2.2.0 → repl_toolkit-2.4.0}/repl_toolkit.egg-info/requires.txt +0 -0
  34. {repl_toolkit-2.2.0 → repl_toolkit-2.4.0}/repl_toolkit.egg-info/top_level.txt +0 -0
  35. {repl_toolkit-2.2.0 → repl_toolkit-2.4.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: repl-toolkit
3
- Version: 2.2.0
3
+ Version: 2.4.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
@@ -14,15 +14,14 @@ Classifier: Intended Audience :: Developers
14
14
  Classifier: License :: OSI Approved :: MIT License
15
15
  Classifier: Operating System :: OS Independent
16
16
  Classifier: Programming Language :: Python :: 3
17
- Classifier: Programming Language :: Python :: 3.8
18
- Classifier: Programming Language :: Python :: 3.9
19
- Classifier: Programming Language :: Python :: 3.10
20
17
  Classifier: Programming Language :: Python :: 3.11
21
18
  Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
22
21
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
23
22
  Classifier: Topic :: Software Development :: User Interfaces
24
23
  Classifier: Topic :: System :: Shells
25
- Requires-Python: >=3.8
24
+ Requires-Python: >=3.11
26
25
  Description-Content-Type: text/markdown
27
26
  License-File: LICENSE
28
27
  Requires-Dist: prompt-toolkit>=3.0.0
@@ -51,7 +50,7 @@ Build interactive command-line applications with async Python. Create REPLs (Rea
51
50
  [![Lint](https://github.com/bassmanitram/repl-toolkit/actions/workflows/lint.yml/badge.svg)](https://github.com/bassmanitram/repl-toolkit/actions/workflows/lint.yml)
52
51
  [![Code Quality](https://github.com/bassmanitram/repl-toolkit/actions/workflows/quality.yml/badge.svg)](https://github.com/bassmanitram/repl-toolkit/actions/workflows/quality.yml)
53
52
  [![Examples](https://github.com/bassmanitram/repl-toolkit/actions/workflows/examples.yml/badge.svg)](https://github.com/bassmanitram/repl-toolkit/actions/workflows/examples.yml)
54
- [![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)
53
+ [![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
55
54
  [![PyPI version](https://img.shields.io/pypi/v/repl-toolkit.svg)](https://pypi.org/project/repl-toolkit/)
56
55
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
57
56
 
@@ -440,6 +439,34 @@ def my_handler(context: ActionContext):
440
439
  context.backend # Your backend
441
440
  ```
442
441
 
442
+ ## Actions that send input
443
+
444
+ A command handler can submit text to the backend by returning a `SendToBackend`. The REPL then treats the text as if the user had typed and sent it. Handlers that return `None` behave as before.
445
+
446
+ ```python
447
+ from repl_toolkit import Action, SendToBackend
448
+
449
+ def handle_ask(ctx):
450
+ question = " ".join(ctx.args)
451
+ if not question:
452
+ ctx.printer("Usage: /ask <question>")
453
+ return None
454
+ return SendToBackend(f"Answer briefly: {question}", backend_kwargs={"mode": "brief"})
455
+
456
+ registry.register_action(Action(name="ask", command="/ask", handler=handle_ask,
457
+ description="Ask a brief question", category="General"))
458
+ ```
459
+
460
+ | REPL | Handler returns `SendToBackend(text, kwargs)` |
461
+ |---|---|
462
+ | AsyncREPL | `text` is processed as typed input (THINKING, cancellation); `kwargs` are passed to `handle_input`; empty `text` sends nothing |
463
+ | HeadlessREPL | `text` is appended to the buffer, which is sent immediately as with `/send`; `kwargs` are passed to `handle_input` |
464
+
465
+ Notes:
466
+
467
+ - `cancel_callback` and `images` are reserved for the REPL. If they appear in `backend_kwargs` they are dropped with a warning. Pasted images still reach the backend through the normal image buffer.
468
+ - Keyboard-shortcut handlers cannot send input: their return values are ignored.
469
+
443
470
  Add tab completion for commands, file paths, or custom values:
444
471
 
445
472
  ```python
@@ -548,6 +575,7 @@ from repl_toolkit import (
548
575
  ActionRegistry, # Manage commands and shortcuts
549
576
  Action, # Define a command/shortcut
550
577
  ActionContext, # Context passed to handlers
578
+ SendToBackend, # Returned by a handler to send input to the backend
551
579
  PrefixCompleter, # Tab completion
552
580
  ShellExpansionCompleter, # Advanced tab completion
553
581
  )
@@ -637,8 +665,15 @@ class CancellableBackend:
637
665
  def __init__(self):
638
666
  self._cancel_requested = False
639
667
 
640
- def cancel(self, message: Optional[str] = None) -> None:
641
- """Optional method to support cooperative cancellation."""
668
+ def cancel(self, message: Optional[str] = None) -> Optional[bool]:
669
+ """
670
+ Optional method to support cooperative cancellation.
671
+
672
+ Returns:
673
+ Optional[bool]:
674
+ - True or None (default): REPL force-cancels the asyncio task
675
+ - False: REPL lets handle_input() complete gracefully
676
+ """
642
677
  self._cancel_requested = True
643
678
  if message:
644
679
  print(f"Cancellation: {message}")
@@ -661,6 +696,49 @@ class CancellableBackend:
661
696
  return True
662
697
  ```
663
698
 
699
+ ### Cancellation Behavior Control (v2.3.0)
700
+
701
+ The `cancel()` method can return a boolean to control how the REPL handles cancellation:
702
+
703
+ ```python
704
+ class ForceCancel Backend:
705
+ """Traditional behavior - REPL cancels the asyncio task."""
706
+
707
+ def cancel(self, message: Optional[str] = None) -> bool:
708
+ self._cancelled = True
709
+ return True # or None - REPL force-cancels task
710
+ ```
711
+
712
+ ```python
713
+ class GracefulBackend:
714
+ """New behavior - let handle_input() complete gracefully."""
715
+
716
+ def cancel(self, message: Optional[str] = None) -> bool:
717
+ self._cancelled = True
718
+ return False # REPL waits for handle_input() to finish
719
+
720
+ async def handle_input(self, user_input: str, **kwargs) -> bool:
721
+ self._cancelled = False
722
+
723
+ # Your processing with checkpoints
724
+ for step in steps:
725
+ if self._cancelled:
726
+ await self.cleanup() # Cleanup hooks fire!
727
+ return False
728
+ await process(step)
729
+ return True
730
+ ```
731
+
732
+ **When to return False:**
733
+ - Backend uses cleanup hooks that need to fire
734
+ - Using agent frameworks with cleanup/finalization logic
735
+ - Need to save state or close connections gracefully
736
+
737
+ **When to return True/None:**
738
+ - Quick cancellation is preferred
739
+ - No cleanup needed
740
+ - Traditional async task cancellation is sufficient
741
+
664
742
  ### When cancel() is Called
665
743
 
666
744
  The REPL automatically calls `backend.cancel()` (if implemented) when:
@@ -682,11 +760,12 @@ class SubprocessBackend:
682
760
  self._cancel_requested = False
683
761
  self._current_process = None
684
762
 
685
- def cancel(self, message: Optional[str] = None) -> None:
763
+ def cancel(self, message: Optional[str] = None) -> bool:
686
764
  """Cancel current subprocess."""
687
765
  self._cancel_requested = True
688
766
  if self._current_process:
689
767
  self._current_process.terminate() # Stop the subprocess
768
+ return True # Force cancel the asyncio task
690
769
 
691
770
  async def handle_input(self, user_input: str, **kwargs) -> bool:
692
771
  """Run command with cancellation support."""
@@ -854,7 +933,8 @@ print(HTML("<red>Error!</red>"))
854
933
 
855
934
  ## Requirements
856
935
 
857
- - Python 3.8+
936
+ - Python 3.11+
937
+ - repl-toolkit supports CPython releases that have not reached end-of-life; support for a release is dropped in the first repl-toolkit release after its EOL date.
858
938
  - prompt-toolkit 3.0+
859
939
  - pyclip 0.7+ (optional, for image paste support)
860
940
 
@@ -6,7 +6,7 @@ Build interactive command-line applications with async Python. Create REPLs (Rea
6
6
  [![Lint](https://github.com/bassmanitram/repl-toolkit/actions/workflows/lint.yml/badge.svg)](https://github.com/bassmanitram/repl-toolkit/actions/workflows/lint.yml)
7
7
  [![Code Quality](https://github.com/bassmanitram/repl-toolkit/actions/workflows/quality.yml/badge.svg)](https://github.com/bassmanitram/repl-toolkit/actions/workflows/quality.yml)
8
8
  [![Examples](https://github.com/bassmanitram/repl-toolkit/actions/workflows/examples.yml/badge.svg)](https://github.com/bassmanitram/repl-toolkit/actions/workflows/examples.yml)
9
- [![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)
9
+ [![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
10
10
  [![PyPI version](https://img.shields.io/pypi/v/repl-toolkit.svg)](https://pypi.org/project/repl-toolkit/)
11
11
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
12
12
 
@@ -395,6 +395,34 @@ def my_handler(context: ActionContext):
395
395
  context.backend # Your backend
396
396
  ```
397
397
 
398
+ ## Actions that send input
399
+
400
+ A command handler can submit text to the backend by returning a `SendToBackend`. The REPL then treats the text as if the user had typed and sent it. Handlers that return `None` behave as before.
401
+
402
+ ```python
403
+ from repl_toolkit import Action, SendToBackend
404
+
405
+ def handle_ask(ctx):
406
+ question = " ".join(ctx.args)
407
+ if not question:
408
+ ctx.printer("Usage: /ask <question>")
409
+ return None
410
+ return SendToBackend(f"Answer briefly: {question}", backend_kwargs={"mode": "brief"})
411
+
412
+ registry.register_action(Action(name="ask", command="/ask", handler=handle_ask,
413
+ description="Ask a brief question", category="General"))
414
+ ```
415
+
416
+ | REPL | Handler returns `SendToBackend(text, kwargs)` |
417
+ |---|---|
418
+ | AsyncREPL | `text` is processed as typed input (THINKING, cancellation); `kwargs` are passed to `handle_input`; empty `text` sends nothing |
419
+ | HeadlessREPL | `text` is appended to the buffer, which is sent immediately as with `/send`; `kwargs` are passed to `handle_input` |
420
+
421
+ Notes:
422
+
423
+ - `cancel_callback` and `images` are reserved for the REPL. If they appear in `backend_kwargs` they are dropped with a warning. Pasted images still reach the backend through the normal image buffer.
424
+ - Keyboard-shortcut handlers cannot send input: their return values are ignored.
425
+
398
426
  Add tab completion for commands, file paths, or custom values:
399
427
 
400
428
  ```python
@@ -503,6 +531,7 @@ from repl_toolkit import (
503
531
  ActionRegistry, # Manage commands and shortcuts
504
532
  Action, # Define a command/shortcut
505
533
  ActionContext, # Context passed to handlers
534
+ SendToBackend, # Returned by a handler to send input to the backend
506
535
  PrefixCompleter, # Tab completion
507
536
  ShellExpansionCompleter, # Advanced tab completion
508
537
  )
@@ -592,8 +621,15 @@ class CancellableBackend:
592
621
  def __init__(self):
593
622
  self._cancel_requested = False
594
623
 
595
- def cancel(self, message: Optional[str] = None) -> None:
596
- """Optional method to support cooperative cancellation."""
624
+ def cancel(self, message: Optional[str] = None) -> Optional[bool]:
625
+ """
626
+ Optional method to support cooperative cancellation.
627
+
628
+ Returns:
629
+ Optional[bool]:
630
+ - True or None (default): REPL force-cancels the asyncio task
631
+ - False: REPL lets handle_input() complete gracefully
632
+ """
597
633
  self._cancel_requested = True
598
634
  if message:
599
635
  print(f"Cancellation: {message}")
@@ -616,6 +652,49 @@ class CancellableBackend:
616
652
  return True
617
653
  ```
618
654
 
655
+ ### Cancellation Behavior Control (v2.3.0)
656
+
657
+ The `cancel()` method can return a boolean to control how the REPL handles cancellation:
658
+
659
+ ```python
660
+ class ForceCancel Backend:
661
+ """Traditional behavior - REPL cancels the asyncio task."""
662
+
663
+ def cancel(self, message: Optional[str] = None) -> bool:
664
+ self._cancelled = True
665
+ return True # or None - REPL force-cancels task
666
+ ```
667
+
668
+ ```python
669
+ class GracefulBackend:
670
+ """New behavior - let handle_input() complete gracefully."""
671
+
672
+ def cancel(self, message: Optional[str] = None) -> bool:
673
+ self._cancelled = True
674
+ return False # REPL waits for handle_input() to finish
675
+
676
+ async def handle_input(self, user_input: str, **kwargs) -> bool:
677
+ self._cancelled = False
678
+
679
+ # Your processing with checkpoints
680
+ for step in steps:
681
+ if self._cancelled:
682
+ await self.cleanup() # Cleanup hooks fire!
683
+ return False
684
+ await process(step)
685
+ return True
686
+ ```
687
+
688
+ **When to return False:**
689
+ - Backend uses cleanup hooks that need to fire
690
+ - Using agent frameworks with cleanup/finalization logic
691
+ - Need to save state or close connections gracefully
692
+
693
+ **When to return True/None:**
694
+ - Quick cancellation is preferred
695
+ - No cleanup needed
696
+ - Traditional async task cancellation is sufficient
697
+
619
698
  ### When cancel() is Called
620
699
 
621
700
  The REPL automatically calls `backend.cancel()` (if implemented) when:
@@ -637,11 +716,12 @@ class SubprocessBackend:
637
716
  self._cancel_requested = False
638
717
  self._current_process = None
639
718
 
640
- def cancel(self, message: Optional[str] = None) -> None:
719
+ def cancel(self, message: Optional[str] = None) -> bool:
641
720
  """Cancel current subprocess."""
642
721
  self._cancel_requested = True
643
722
  if self._current_process:
644
723
  self._current_process.terminate() # Stop the subprocess
724
+ return True # Force cancel the asyncio task
645
725
 
646
726
  async def handle_input(self, user_input: str, **kwargs) -> bool:
647
727
  """Run command with cancellation support."""
@@ -809,7 +889,8 @@ print(HTML("<red>Error!</red>"))
809
889
 
810
890
  ## Requirements
811
891
 
812
- - Python 3.8+
892
+ - Python 3.11+
893
+ - repl-toolkit supports CPython releases that have not reached end-of-life; support for a release is dropped in the first repl-toolkit release after its EOL date.
813
894
  - prompt-toolkit 3.0+
814
895
  - pyclip 0.7+ (optional, for image paste support)
815
896
 
@@ -4,10 +4,10 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "repl-toolkit"
7
- version = "2.2.0"
7
+ version = "2.4.0"
8
8
  description = "A Python toolkit for building interactive REPL and headless interfaces with action support"
9
9
  readme = "README.md"
10
- requires-python = ">=3.8"
10
+ requires-python = ">=3.11"
11
11
  license = {text = "MIT"}
12
12
  authors = [
13
13
  {name = "REPL Toolkit Contributors", email = "martin.j.bartlett@gmail.com"}
@@ -19,11 +19,10 @@ classifiers = [
19
19
  "License :: OSI Approved :: MIT License",
20
20
  "Operating System :: OS Independent",
21
21
  "Programming Language :: Python :: 3",
22
- "Programming Language :: Python :: 3.8",
23
- "Programming Language :: Python :: 3.9",
24
- "Programming Language :: Python :: 3.10",
25
22
  "Programming Language :: Python :: 3.11",
26
23
  "Programming Language :: Python :: 3.12",
24
+ "Programming Language :: Python :: 3.13",
25
+ "Programming Language :: Python :: 3.14",
27
26
  "Topic :: Software Development :: Libraries :: Python Modules",
28
27
  "Topic :: Software Development :: User Interfaces",
29
28
  "Topic :: System :: Shells",
@@ -85,7 +84,7 @@ exclude_lines = [
85
84
 
86
85
  [tool.black]
87
86
  line-length = 100
88
- target-version = ['py38']
87
+ target-version = ['py311']
89
88
 
90
89
  [tool.isort]
91
90
  profile = "black"
@@ -37,9 +37,9 @@ 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.2.0"
40
+ __version__ = "2.4.0"
41
41
 
42
- from .actions import Action, ActionContext, ActionRegistry
42
+ from .actions import Action, ActionContext, ActionRegistry, SendToBackend
43
43
  from .async_repl import AsyncREPL, run_async_repl
44
44
  from .completion import PrefixCompleter, ShellExpansionCompleter
45
45
  from .formatting import (
@@ -70,6 +70,7 @@ __all__ = [
70
70
  "Action",
71
71
  "ActionContext",
72
72
  "ActionRegistry",
73
+ "SendToBackend",
73
74
  # Completion
74
75
  "PrefixCompleter",
75
76
  "ShellExpansionCompleter",
@@ -9,7 +9,16 @@ by either typed commands (e.g., /help) or keyboard shortcuts (e.g., F1),
9
9
  providing a consistent and discoverable interface for users.
10
10
  """
11
11
 
12
- from .action import Action, ActionContext, ActionError, ActionExecutionError, ActionValidationError
12
+ from .action import (
13
+ RESERVED_BACKEND_KWARGS,
14
+ Action,
15
+ ActionContext,
16
+ ActionError,
17
+ ActionExecutionError,
18
+ ActionValidationError,
19
+ SendToBackend,
20
+ filter_reserved_backend_kwargs,
21
+ )
13
22
  from .registry import ActionRegistry
14
23
 
15
24
  __all__ = [
@@ -19,6 +28,10 @@ __all__ = [
19
28
  "ActionError",
20
29
  "ActionValidationError",
21
30
  "ActionExecutionError",
31
+ # Backend submission
32
+ "SendToBackend",
33
+ "RESERVED_BACKEND_KWARGS",
34
+ "filter_reserved_backend_kwargs",
22
35
  # Registry
23
36
  "ActionRegistry",
24
37
  ]
@@ -7,7 +7,7 @@ foundation of the command and keyboard shortcut system.
7
7
 
8
8
  import logging
9
9
  from dataclasses import dataclass, field
10
- from typing import TYPE_CHECKING, Any, Callable, List, Optional, Union
10
+ from typing import TYPE_CHECKING, Any, Callable, Dict, List, Mapping, Optional, Union
11
11
 
12
12
  logger = logging.getLogger(__name__)
13
13
 
@@ -15,6 +15,53 @@ if TYPE_CHECKING:
15
15
  from .registry import ActionRegistry
16
16
 
17
17
 
18
+ # Backend keyword arguments owned by the REPL; action handlers cannot set them
19
+ RESERVED_BACKEND_KWARGS = frozenset({"cancel_callback", "images"})
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class SendToBackend:
24
+ """
25
+ Value returned by an action handler to submit input to the backend.
26
+
27
+ The REPL processes ``text`` as if the user had typed and sent it, passing
28
+ ``backend_kwargs`` on to ``backend.handle_input()``. Handlers that return
29
+ anything else (including ``None``) behave as before.
30
+
31
+ The keys ``cancel_callback`` and ``images`` are reserved for the REPL and
32
+ are dropped from ``backend_kwargs`` with a warning.
33
+
34
+ Instances are frozen but not hashable, because ``backend_kwargs`` is a dict.
35
+
36
+ Example:
37
+ def handle_ask(ctx):
38
+ return SendToBackend("Answer briefly: ...", backend_kwargs={"mode": "brief"})
39
+ """
40
+
41
+ text: str = ""
42
+ backend_kwargs: Mapping[str, Any] = field(default_factory=dict)
43
+
44
+
45
+ def filter_reserved_backend_kwargs(backend_kwargs: Mapping[str, Any]) -> Dict[str, Any]:
46
+ """
47
+ Remove REPL-owned keys from action-supplied backend kwargs.
48
+
49
+ Args:
50
+ backend_kwargs: Keyword arguments requested by an action handler
51
+
52
+ Returns:
53
+ A new dict without any key in RESERVED_BACKEND_KWARGS. A warning naming
54
+ each dropped key is logged.
55
+ """
56
+ filtered: Dict[str, Any] = {}
57
+ for key, value in backend_kwargs.items():
58
+ if key in RESERVED_BACKEND_KWARGS:
59
+ logger.warning(f"Ignoring reserved backend kwarg '{key}' from SendToBackend")
60
+ else:
61
+ filtered[key] = value
62
+ return filtered
63
+
64
+
18
65
  @dataclass
19
66
  class Action:
20
67
  """
@@ -12,7 +12,14 @@ from typing import Any, Callable, Dict, List, Optional
12
12
  logger = logging.getLogger(__name__)
13
13
 
14
14
  from ..ptypes import ActionHandler, AsyncBackend
15
- from .action import Action, ActionContext, ActionError, ActionExecutionError, ActionValidationError
15
+ from .action import (
16
+ Action,
17
+ ActionContext,
18
+ ActionError,
19
+ ActionExecutionError,
20
+ ActionValidationError,
21
+ SendToBackend,
22
+ )
16
23
 
17
24
 
18
25
  class ActionRegistry(ActionHandler):
@@ -274,7 +281,7 @@ class ActionRegistry(ActionHandler):
274
281
  f"Invalid handler type for action '{action.name}': {type(action.handler)}"
275
282
  ) # pragma: no cover
276
283
 
277
- def execute_action(self, action_name: str, context: ActionContext) -> None:
284
+ def execute_action(self, action_name: str, context: ActionContext) -> Optional[SendToBackend]:
278
285
  """
279
286
  Execute an action by name.
280
287
 
@@ -282,6 +289,10 @@ class ActionRegistry(ActionHandler):
282
289
  action_name: Name of action to execute
283
290
  context: Action context
284
291
 
292
+ Returns:
293
+ The handler's return value if it is a SendToBackend, None otherwise
294
+ (including disabled and main-loop actions).
295
+
285
296
  Raises:
286
297
  ActionError: If action is not found or execution fails
287
298
  """
@@ -294,7 +305,7 @@ class ActionRegistry(ActionHandler):
294
305
  if not action.enabled:
295
306
  logger.debug(f"Action '{action_name}' is disabled")
296
307
  logger.debug("ActionRegistry.execute_action() exit - disabled")
297
- return
308
+ return None
298
309
 
299
310
  # Resolve handler
300
311
  handler = self._resolve_handler(action)
@@ -302,15 +313,16 @@ class ActionRegistry(ActionHandler):
302
313
  # Main loop actions (like exit/quit) return without execution
303
314
  logger.debug(f"Action '{action_name}' handled by main loop")
304
315
  logger.debug("ActionRegistry.execute_action() exit - main loop")
305
- return
316
+ return None
306
317
 
307
318
  try:
308
319
  logger.debug(f"Executing action '{action_name}' via {context.triggered_by}")
309
320
 
310
321
  # Execute handler synchronously
311
322
  # If handler needs async operations, it can handle them internally
312
- handler(context)
323
+ result = handler(context)
313
324
  logger.debug("ActionRegistry.execute_action() exit - success")
325
+ return result if isinstance(result, SendToBackend) else None
314
326
 
315
327
  except Exception as e: # pragma: no cover
316
328
  logger.error(f"Error executing action '{action_name}': {e}") # pragma: no cover
@@ -319,12 +331,16 @@ class ActionRegistry(ActionHandler):
319
331
  f"Failed to execute action '{action_name}': {e}", action_name
320
332
  ) # pragma: no cover
321
333
 
322
- def handle_command(self, command_string: str, **kwargs: Any) -> None:
334
+ def handle_command(self, command_string: str, **kwargs: Any) -> Optional[SendToBackend]:
323
335
  """
324
336
  Handle a command string by mapping to appropriate action.
325
337
 
326
338
  Args:
327
339
  command_string: Full command string (e.g., '/help topic')
340
+
341
+ Returns:
342
+ The SendToBackend returned by the action's handler, or None if there
343
+ was none, the command was unknown, or execution failed.
328
344
  """
329
345
  logger.debug("ActionRegistry.handle_command() entry")
330
346
  logger.debug(f"Handling command: {command_string}")
@@ -333,7 +349,7 @@ class ActionRegistry(ActionHandler):
333
349
  parts = command_string.strip().split()
334
350
  if not parts:
335
351
  logger.debug("ActionRegistry.handle_command() exit - no parts")
336
- return
352
+ return None
337
353
 
338
354
  command = parts[0]
339
355
  args = parts[1:]
@@ -348,7 +364,7 @@ class ActionRegistry(ActionHandler):
348
364
  self.printer(f"Unknown command: {command}")
349
365
  self.printer("Use /help to see available commands.")
350
366
  logger.debug("ActionRegistry.handle_command() exit - unknown command")
351
- return
367
+ return None
352
368
 
353
369
  # Create context and execute
354
370
  context = ActionContext(
@@ -363,19 +379,24 @@ class ActionRegistry(ActionHandler):
363
379
  vars(context).update(kwargs)
364
380
 
365
381
  try:
366
- self.execute_action(action.name, context)
382
+ result = self.execute_action(action.name, context)
367
383
  logger.debug("ActionRegistry.handle_command() exit - success")
384
+ return result
368
385
  except ActionError as e: # pragma: no cover
369
386
  logger.warning(f"Action error in command '{command_string}': {e}")
370
387
  logger.debug("ActionRegistry.handle_command() exit - action error")
371
388
  except Exception: # pragma: no cover
372
389
  logger.exception(f"Unexpected error handling command '{command_string}'")
373
390
  logger.debug("ActionRegistry.handle_command() exit - unexpected error")
391
+ return None
374
392
 
375
393
  def handle_shortcut(self, key_combo: str, event: Any, **kwargs: Any) -> None:
376
394
  """
377
395
  Handle a keyboard shortcut by mapping to appropriate action.
378
396
 
397
+ Any SendToBackend returned by the handler is ignored: shortcuts cannot
398
+ submit input to the backend.
399
+
379
400
  Args:
380
401
  key_combo: Key combination string
381
402
  event: Key press event from prompt_toolkit
@@ -402,7 +423,9 @@ class ActionRegistry(ActionHandler):
402
423
  vars(context).update(kwargs)
403
424
 
404
425
  try:
405
- self.execute_action(action.name, context)
426
+ result = self.execute_action(action.name, context)
427
+ if isinstance(result, SendToBackend):
428
+ logger.debug(f"Ignoring SendToBackend returned by shortcut '{key_combo}'")
406
429
  logger.debug("ActionRegistry.handle_shortcut() exit - success")
407
430
  except ActionError as e: # pragma: no cover
408
431
  logger.warning(f"Action error in shortcut '{key_combo}': {e}")