repl-toolkit 2.3.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.3.0/repl_toolkit.egg-info → repl_toolkit-2.4.0}/PKG-INFO +36 -7
  2. {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/README.md +32 -2
  3. {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/pyproject.toml +5 -6
  4. {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/__init__.py +3 -2
  5. {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/actions/__init__.py +14 -1
  6. {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/actions/action.py +48 -1
  7. {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/actions/registry.py +33 -10
  8. {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/async_repl.py +21 -6
  9. {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/headless_repl.py +25 -6
  10. {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/ptypes.py +13 -3
  11. {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/test_actions.py +167 -0
  12. {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/test_async_repl.py +296 -1
  13. {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/test_headless.py +158 -1
  14. {repl_toolkit-2.3.0 → repl_toolkit-2.4.0/repl_toolkit.egg-info}/PKG-INFO +36 -7
  15. {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/LICENSE +0 -0
  16. {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/completion/__init__.py +0 -0
  17. {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/completion/prefix.py +0 -0
  18. {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/completion/shell_expansion.py +0 -0
  19. {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/formatting.py +0 -0
  20. {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/images.py +0 -0
  21. {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/__init__.py +0 -0
  22. {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/conftest.py +0 -0
  23. {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/test_cancellation.py +0 -0
  24. {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/test_completion.py +0 -0
  25. {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/test_ctrl_c_cancel.py +0 -0
  26. {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/test_formatting.py +0 -0
  27. {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/test_image_utils.py +0 -0
  28. {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/test_images.py +0 -0
  29. {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/test_output_handling.py +0 -0
  30. {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/test_types.py +0 -0
  31. {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit.egg-info/SOURCES.txt +0 -0
  32. {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit.egg-info/dependency_links.txt +0 -0
  33. {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit.egg-info/requires.txt +0 -0
  34. {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit.egg-info/top_level.txt +0 -0
  35. {repl_toolkit-2.3.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.3.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
  )
@@ -905,7 +933,8 @@ print(HTML("<red>Error!</red>"))
905
933
 
906
934
  ## Requirements
907
935
 
908
- - 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.
909
938
  - prompt-toolkit 3.0+
910
939
  - pyclip 0.7+ (optional, for image paste support)
911
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
  )
@@ -860,7 +889,8 @@ print(HTML("<red>Error!</red>"))
860
889
 
861
890
  ## Requirements
862
891
 
863
- - 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.
864
894
  - prompt-toolkit 3.0+
865
895
  - pyclip 0.7+ (optional, for image paste support)
866
896
 
@@ -4,10 +4,10 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "repl-toolkit"
7
- version = "2.3.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.3.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}")
@@ -26,7 +26,7 @@ from prompt_toolkit.output import DummyOutput
26
26
  from prompt_toolkit.patch_stdout import patch_stdout
27
27
  from prompt_toolkit.shortcuts import print_formatted_text
28
28
 
29
- from .actions import ActionContext, ActionRegistry
29
+ from .actions import ActionContext, ActionRegistry, SendToBackend, filter_reserved_backend_kwargs
30
30
  from .images import ImageData, create_paste_action
31
31
  from .ptypes import AsyncBackend, CancellableBackend
32
32
 
@@ -171,7 +171,9 @@ class AsyncREPL:
171
171
  event=event,
172
172
  triggered_by="shortcut",
173
173
  )
174
- self.action_registry.execute_action(action, context)
174
+ result = self.action_registry.execute_action(action, context)
175
+ if isinstance(result, SendToBackend):
176
+ logger.debug(f"Ignoring SendToBackend returned by shortcut '{key_combo}'")
175
177
  except Exception:
176
178
  logger.exception(f"Error executing shortcut '{key_combo}'")
177
179
 
@@ -230,8 +232,14 @@ class AsyncREPL:
230
232
  if not user_input.strip():
231
233
  continue
232
234
  if user_input.strip().startswith("/"):
233
- self.action_registry.handle_command(user_input.strip())
234
- await asyncio.sleep(0)
235
+ result = self.action_registry.handle_command(user_input.strip())
236
+ if isinstance(result, SendToBackend):
237
+ if result.text.strip():
238
+ await self._process_input(result.text, backend, **result.backend_kwargs)
239
+ else:
240
+ logger.debug("Ignoring SendToBackend with empty text")
241
+ else:
242
+ await asyncio.sleep(0)
235
243
  continue
236
244
 
237
245
  await self._process_input(user_input, backend)
@@ -250,15 +258,22 @@ class AsyncREPL:
250
258
  # Input Processing with Cancellation
251
259
  # ─────────────────────────────────────────────────────────────────────────
252
260
 
253
- async def _process_input(self, user_input: str, backend: AsyncBackend):
261
+ async def _process_input(self, user_input: str, backend: AsyncBackend, **extra_kwargs: Any):
254
262
  """
255
263
  Process user input with cancellation support.
256
264
 
257
265
  Runs the backend task concurrently with a cancellation listener,
258
266
  allowing users to cancel via Ctrl+C or Alt+C.
267
+
268
+ Args:
269
+ user_input: Text to send to the backend
270
+ backend: Backend processing the input
271
+ **extra_kwargs: Extra keyword arguments for backend.handle_input(),
272
+ e.g. from SendToBackend. Reserved keys are dropped with a warning.
259
273
  """
274
+ extra = filter_reserved_backend_kwargs(extra_kwargs)
260
275
  async with self._cancellation_context() as ctx:
261
- kwargs = self._build_backend_kwargs(ctx["trigger_cancel"])
276
+ kwargs = {**extra, **self._build_backend_kwargs(ctx["trigger_cancel"])}
262
277
  backend_task = asyncio.create_task(backend.handle_input(user_input, **kwargs))
263
278
 
264
279
  print(THINKING_MESSAGE)
@@ -1,10 +1,11 @@
1
1
  import asyncio
2
2
  import logging
3
3
  import sys
4
- from typing import Optional
4
+ from typing import Any, Optional
5
5
 
6
6
  logger = logging.getLogger(__name__)
7
7
 
8
+ from .actions.action import SendToBackend, filter_reserved_backend_kwargs
8
9
  from .actions.registry import ActionRegistry
9
10
  from .ptypes import ActionHandler, AsyncBackend, CancellableBackend
10
11
 
@@ -116,7 +117,13 @@ class HeadlessREPL:
116
117
  await self._execute_send(backend, f"line {line_num}")
117
118
  else:
118
119
  # Synchronous command processing
119
- self._execute_command(line)
120
+ result = self._execute_command(line)
121
+ if isinstance(result, SendToBackend):
122
+ if result.text:
123
+ self._add_to_buffer(result.text)
124
+ await self._execute_send(
125
+ backend, f"line {line_num}", **result.backend_kwargs
126
+ )
120
127
  # Yield to event loop to ensure any pending async work completes
121
128
  # before processing the next line. This prevents race conditions
122
129
  # where commands modify backend state and the next line
@@ -145,16 +152,20 @@ class HeadlessREPL:
145
152
  logger.debug(f"Added line to buffer, total length: {len(self.buffer)}")
146
153
  logger.debug("HeadlessREPL._add_to_buffer() exit")
147
154
 
148
- async def _execute_send(self, backend: AsyncBackend, context_info: str):
155
+ async def _execute_send(self, backend: AsyncBackend, context_info: str, **extra_kwargs: Any):
149
156
  """
150
157
  Execute /send command - send buffer to backend and wait.
151
158
 
152
159
  Args:
153
160
  backend: Backend to send buffer content to
154
161
  context_info: Context information for logging (e.g., "line 5", "EOF")
162
+ **extra_kwargs: Extra keyword arguments for backend.handle_input(),
163
+ e.g. from SendToBackend. Reserved keys are dropped with a warning.
155
164
  """
156
165
  logger.debug("HeadlessREPL._execute_send() entry")
157
166
 
167
+ extra = filter_reserved_backend_kwargs(extra_kwargs)
168
+
158
169
  buffer_content = self.buffer.strip()
159
170
 
160
171
  if not buffer_content:
@@ -169,7 +180,7 @@ class HeadlessREPL:
169
180
 
170
181
  try:
171
182
  # Send to backend and wait for completion
172
- success = await backend.handle_input(buffer_content)
183
+ success = await backend.handle_input(buffer_content, **extra)
173
184
 
174
185
  if success:
175
186
  logger.info(f"Send #{self.send_count} completed successfully")
@@ -188,23 +199,31 @@ class HeadlessREPL:
188
199
 
189
200
  logger.debug("HeadlessREPL._execute_send() exit")
190
201
 
191
- def _execute_command(self, command: str):
202
+ def _execute_command(self, command: str) -> Optional[SendToBackend]:
192
203
  """
193
204
  Execute a command through the action system.
194
205
 
195
206
  Args:
196
207
  command: Command string to execute (e.g., "/help", "/shortcuts")
208
+
209
+ Returns:
210
+ The registry's handle_command result, or None if the command raised
197
211
  """
198
212
  logger.debug("HeadlessREPL._execute_command() entry")
199
213
 
200
214
  try:
201
- self.action_registry.handle_command(command, headless_mode=True, buffer=self.buffer)
215
+ result = self.action_registry.handle_command(
216
+ command, headless_mode=True, buffer=self.buffer
217
+ )
218
+ logger.debug("HeadlessREPL._execute_command() exit")
219
+ return result
202
220
 
203
221
  except Exception as e:
204
222
  logger.error(f"Error executing command '{command}': {e}")
205
223
  # Don't fail entire process for command errors
206
224
 
207
225
  logger.debug("HeadlessREPL._execute_command() exit")
226
+ return None
208
227
 
209
228
  async def _handle_eof(self, backend: AsyncBackend):
210
229
  """
@@ -8,7 +8,7 @@ for compatibility with the REPL toolkit.
8
8
  from typing import TYPE_CHECKING, Dict, List, Optional, Protocol, runtime_checkable
9
9
 
10
10
  if TYPE_CHECKING:
11
- from .actions.action import ActionContext
11
+ from .actions.action import ActionContext, SendToBackend
12
12
  from .images import ImageData
13
13
 
14
14
 
@@ -110,7 +110,9 @@ class ActionHandler(Protocol):
110
110
  and keyboard shortcut-based actions in a coherent manner.
111
111
  """
112
112
 
113
- def execute_action(self, action_name: str, context: "ActionContext") -> None:
113
+ def execute_action(
114
+ self, action_name: str, context: "ActionContext"
115
+ ) -> Optional["SendToBackend"]:
114
116
  """
115
117
  Execute an action by name.
116
118
 
@@ -118,18 +120,26 @@ class ActionHandler(Protocol):
118
120
  action_name: Name of the action to execute
119
121
  context: Action context containing relevant information
120
122
 
123
+ Returns:
124
+ A SendToBackend if the handler asked for input to be submitted to
125
+ the backend, None otherwise.
126
+
121
127
  Raises:
122
128
  ActionError: If action execution fails
123
129
  """
124
130
  ...
125
131
 
126
- def handle_command(self, command_string: str, **kwargs) -> None:
132
+ def handle_command(self, command_string: str, **kwargs) -> Optional["SendToBackend"]:
127
133
  """
128
134
  Handle a command string by mapping to appropriate action.
129
135
 
130
136
  Args:
131
137
  command_string: Full command string (e.g., '/help arg1 arg2')
132
138
  **kwargs: Additional context parameters
139
+
140
+ Returns:
141
+ A SendToBackend if the command's handler asked for input to be
142
+ submitted to the backend, None otherwise.
133
143
  """
134
144
  ...
135
145