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.
- {repl_toolkit-2.3.0/repl_toolkit.egg-info → repl_toolkit-2.4.0}/PKG-INFO +36 -7
- {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/README.md +32 -2
- {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/pyproject.toml +5 -6
- {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/__init__.py +3 -2
- {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/actions/__init__.py +14 -1
- {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/actions/action.py +48 -1
- {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/actions/registry.py +33 -10
- {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/async_repl.py +21 -6
- {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/headless_repl.py +25 -6
- {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/ptypes.py +13 -3
- {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/test_actions.py +167 -0
- {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/test_async_repl.py +296 -1
- {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/test_headless.py +158 -1
- {repl_toolkit-2.3.0 → repl_toolkit-2.4.0/repl_toolkit.egg-info}/PKG-INFO +36 -7
- {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/LICENSE +0 -0
- {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/completion/__init__.py +0 -0
- {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/completion/prefix.py +0 -0
- {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/completion/shell_expansion.py +0 -0
- {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/formatting.py +0 -0
- {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/images.py +0 -0
- {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/__init__.py +0 -0
- {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/conftest.py +0 -0
- {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/test_cancellation.py +0 -0
- {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/test_completion.py +0 -0
- {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/test_ctrl_c_cancel.py +0 -0
- {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/test_formatting.py +0 -0
- {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/test_image_utils.py +0 -0
- {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/test_images.py +0 -0
- {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/test_output_handling.py +0 -0
- {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit/tests/test_types.py +0 -0
- {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit.egg-info/SOURCES.txt +0 -0
- {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit.egg-info/dependency_links.txt +0 -0
- {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit.egg-info/requires.txt +0 -0
- {repl_toolkit-2.3.0 → repl_toolkit-2.4.0}/repl_toolkit.egg-info/top_level.txt +0 -0
- {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
|
+
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.
|
|
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
|
[](https://github.com/bassmanitram/repl-toolkit/actions/workflows/lint.yml)
|
|
52
51
|
[](https://github.com/bassmanitram/repl-toolkit/actions/workflows/quality.yml)
|
|
53
52
|
[](https://github.com/bassmanitram/repl-toolkit/actions/workflows/examples.yml)
|
|
54
|
-
[](https://www.python.org/downloads/)
|
|
55
54
|
[](https://pypi.org/project/repl-toolkit/)
|
|
56
55
|
[](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.
|
|
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
|
[](https://github.com/bassmanitram/repl-toolkit/actions/workflows/lint.yml)
|
|
7
7
|
[](https://github.com/bassmanitram/repl-toolkit/actions/workflows/quality.yml)
|
|
8
8
|
[](https://github.com/bassmanitram/repl-toolkit/actions/workflows/examples.yml)
|
|
9
|
-
[](https://www.python.org/downloads/)
|
|
10
10
|
[](https://pypi.org/project/repl-toolkit/)
|
|
11
11
|
[](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.
|
|
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.
|
|
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.
|
|
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 = ['
|
|
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.
|
|
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
|
|
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
|
|
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) ->
|
|
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) ->
|
|
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
|
-
|
|
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(
|
|
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(
|
|
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) ->
|
|
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
|
|