koder 0.4.1__tar.gz → 0.4.3__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.
- koder-0.4.3/.claude/settings.local.json +13 -0
- koder-0.4.3/GEMINI.md +1 -0
- {koder-0.4.1 → koder-0.4.3}/PKG-INFO +1 -1
- {koder-0.4.1 → koder-0.4.3}/koder_agent/agentic/agent.py +45 -4
- {koder-0.4.1 → koder-0.4.3}/koder_agent/cli.py +6 -37
- {koder-0.4.1 → koder-0.4.3}/koder_agent/core/__init__.py +2 -2
- {koder-0.4.1 → koder-0.4.3}/koder_agent/core/commands.py +8 -4
- koder-0.4.3/koder_agent/core/keyboard_listener.py +202 -0
- {koder-0.4.1 → koder-0.4.3}/koder_agent/core/scheduler.py +187 -124
- koder-0.4.3/koder_agent/core/session.py +554 -0
- {koder-0.4.1 → koder-0.4.3}/koder_agent/core/status_line.py +9 -7
- {koder-0.4.1 → koder-0.4.3}/koder_agent/core/usage_tracker.py +15 -3
- {koder-0.4.1 → koder-0.4.3}/koder_agent/utils/client.py +48 -8
- {koder-0.4.1 → koder-0.4.3}/pyproject.toml +1 -1
- {koder-0.4.1 → koder-0.4.3}/uv.lock +1 -1
- koder-0.4.1/.claude/settings.local.json +0 -10
- koder-0.4.1/koder_agent/core/context.py +0 -433
- {koder-0.4.1 → koder-0.4.3}/.github/dependabot.yml +0 -0
- {koder-0.4.1 → koder-0.4.3}/.gitignore +0 -0
- {koder-0.4.1 → koder-0.4.3}/AGENTS.md +0 -0
- {koder-0.4.1 → koder-0.4.3}/CLAUDE.md +0 -0
- {koder-0.4.1 → koder-0.4.3}/CONTRIBUTING.md +0 -0
- {koder-0.4.1 → koder-0.4.3}/LICENSE +0 -0
- {koder-0.4.1 → koder-0.4.3}/README.md +0 -0
- {koder-0.4.1 → koder-0.4.3}/koder_agent/__init__.py +0 -0
- {koder-0.4.1 → koder-0.4.3}/koder_agent/agentic/__init__.py +0 -0
- {koder-0.4.1 → koder-0.4.3}/koder_agent/agentic/approval_hooks.py +0 -0
- {koder-0.4.1 → koder-0.4.3}/koder_agent/agentic/hooks.py +0 -0
- {koder-0.4.1 → koder-0.4.3}/koder_agent/config/__init__.py +0 -0
- {koder-0.4.1 → koder-0.4.3}/koder_agent/config/cli_handler.py +0 -0
- {koder-0.4.1 → koder-0.4.3}/koder_agent/config/manager.py +0 -0
- {koder-0.4.1 → koder-0.4.3}/koder_agent/config/models.py +0 -0
- {koder-0.4.1 → koder-0.4.3}/koder_agent/core/interactive.py +0 -0
- {koder-0.4.1 → koder-0.4.3}/koder_agent/core/security.py +0 -0
- {koder-0.4.1 → koder-0.4.3}/koder_agent/core/streaming_display.py +0 -0
- {koder-0.4.1 → koder-0.4.3}/koder_agent/mcp/__init__.py +0 -0
- {koder-0.4.1 → koder-0.4.3}/koder_agent/mcp/cli_handler.py +0 -0
- {koder-0.4.1 → koder-0.4.3}/koder_agent/mcp/server_config.py +0 -0
- {koder-0.4.1 → koder-0.4.3}/koder_agent/mcp/server_factory.py +0 -0
- {koder-0.4.1 → koder-0.4.3}/koder_agent/mcp/server_manager.py +0 -0
- {koder-0.4.1 → koder-0.4.3}/koder_agent/tools/__init__.py +0 -0
- {koder-0.4.1 → koder-0.4.3}/koder_agent/tools/engine.py +0 -0
- {koder-0.4.1 → koder-0.4.3}/koder_agent/tools/file.py +0 -0
- {koder-0.4.1 → koder-0.4.3}/koder_agent/tools/search.py +0 -0
- {koder-0.4.1 → koder-0.4.3}/koder_agent/tools/shell.py +0 -0
- {koder-0.4.1 → koder-0.4.3}/koder_agent/tools/task.py +0 -0
- {koder-0.4.1 → koder-0.4.3}/koder_agent/tools/todo.py +0 -0
- {koder-0.4.1 → koder-0.4.3}/koder_agent/tools/web.py +0 -0
- {koder-0.4.1 → koder-0.4.3}/koder_agent/utils/__init__.py +0 -0
- {koder-0.4.1 → koder-0.4.3}/koder_agent/utils/model_info.py +0 -0
- {koder-0.4.1 → koder-0.4.3}/koder_agent/utils/prompts.py +0 -0
- {koder-0.4.1 → koder-0.4.3}/koder_agent/utils/queue.py +0 -0
- {koder-0.4.1 → koder-0.4.3}/koder_agent/utils/sessions.py +0 -0
- {koder-0.4.1 → koder-0.4.3}/koder_agent/utils/terminal_theme.py +0 -0
- {koder-0.4.1 → koder-0.4.3}/scripts/upgrade_dependency.py +0 -0
- {koder-0.4.1 → koder-0.4.3}/tests/test_file_tools.py +0 -0
- {koder-0.4.1 → koder-0.4.3}/tests/test_shell_background.py +0 -0
- {koder-0.4.1 → koder-0.4.3}/tests/test_web.py +0 -0
koder-0.4.3/GEMINI.md
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
CLAUDE.md
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: koder
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.3
|
|
4
4
|
Summary: An intuitive AI coding assistant and interactive CLI tool that boosts developer productivity with intelligent automation and context-aware support.
|
|
5
5
|
Project-URL: Homepage, https://github.com/feiskyer/koder
|
|
6
6
|
Project-URL: Repository, https://github.com/feiskyer/koder
|
|
@@ -3,6 +3,8 @@
|
|
|
3
3
|
import logging
|
|
4
4
|
import uuid
|
|
5
5
|
|
|
6
|
+
import backoff
|
|
7
|
+
import litellm
|
|
6
8
|
from agents import Agent, ModelSettings
|
|
7
9
|
from agents.extensions.models.litellm_model import LitellmModel
|
|
8
10
|
from openai.types.shared import Reasoning
|
|
@@ -18,6 +20,41 @@ console = Console()
|
|
|
18
20
|
logger = logging.getLogger(__name__)
|
|
19
21
|
|
|
20
22
|
|
|
23
|
+
class RetryingLitellmModel(LitellmModel):
|
|
24
|
+
"""LitellmModel with backoff retry logic."""
|
|
25
|
+
|
|
26
|
+
@backoff.on_exception(
|
|
27
|
+
backoff.expo,
|
|
28
|
+
(
|
|
29
|
+
litellm.exceptions.ServiceUnavailableError,
|
|
30
|
+
litellm.exceptions.RateLimitError,
|
|
31
|
+
litellm.exceptions.APIConnectionError,
|
|
32
|
+
litellm.exceptions.Timeout,
|
|
33
|
+
litellm.exceptions.InternalServerError,
|
|
34
|
+
),
|
|
35
|
+
max_tries=3,
|
|
36
|
+
jitter=backoff.full_jitter,
|
|
37
|
+
)
|
|
38
|
+
async def get_response(self, *args, **kwargs):
|
|
39
|
+
return await super().get_response(*args, **kwargs)
|
|
40
|
+
|
|
41
|
+
@backoff.on_exception(
|
|
42
|
+
backoff.expo,
|
|
43
|
+
(
|
|
44
|
+
litellm.exceptions.ServiceUnavailableError,
|
|
45
|
+
litellm.exceptions.RateLimitError,
|
|
46
|
+
litellm.exceptions.APIConnectionError,
|
|
47
|
+
litellm.exceptions.Timeout,
|
|
48
|
+
litellm.exceptions.InternalServerError,
|
|
49
|
+
),
|
|
50
|
+
max_tries=5,
|
|
51
|
+
jitter=backoff.full_jitter,
|
|
52
|
+
)
|
|
53
|
+
async def stream_response(self, *args, **kwargs):
|
|
54
|
+
async for chunk in super().stream_response(*args, **kwargs):
|
|
55
|
+
yield chunk
|
|
56
|
+
|
|
57
|
+
|
|
21
58
|
async def create_dev_agent(tools) -> Agent:
|
|
22
59
|
"""Create the main development agent with MCP servers."""
|
|
23
60
|
config = get_config()
|
|
@@ -28,9 +65,9 @@ async def create_dev_agent(tools) -> Agent:
|
|
|
28
65
|
# Use string model name for native OpenAI providers (handled by default client)
|
|
29
66
|
model = get_model_name()
|
|
30
67
|
else:
|
|
31
|
-
# Use LitellmModel with explicit base_url and api_key
|
|
68
|
+
# Use LitellmModel with explicit base_url and api_key
|
|
32
69
|
litellm_kwargs = get_litellm_model_kwargs()
|
|
33
|
-
model =
|
|
70
|
+
model = RetryingLitellmModel(
|
|
34
71
|
model=litellm_kwargs["model"],
|
|
35
72
|
base_url=litellm_kwargs["base_url"],
|
|
36
73
|
api_key=litellm_kwargs["api_key"],
|
|
@@ -38,9 +75,13 @@ async def create_dev_agent(tools) -> Agent:
|
|
|
38
75
|
|
|
39
76
|
# Build model_settings with reasoning if configured
|
|
40
77
|
model_name_str = get_model_name() # Always get string name for max_tokens lookup
|
|
41
|
-
model_settings = ModelSettings(
|
|
78
|
+
model_settings = ModelSettings(
|
|
79
|
+
metadata={"source": "koder"},
|
|
80
|
+
max_tokens=get_maximum_output_tokens(model_name_str),
|
|
81
|
+
)
|
|
42
82
|
if config.model.reasoning_effort is not None:
|
|
43
|
-
|
|
83
|
+
effort = None if config.model.reasoning_effort == "none" else config.model.reasoning_effort
|
|
84
|
+
model_settings.reasoning = Reasoning(effort=effort, summary="detailed")
|
|
44
85
|
|
|
45
86
|
dev_agent = Agent(
|
|
46
87
|
name="Koder",
|
|
@@ -12,9 +12,9 @@ from rich.panel import Panel
|
|
|
12
12
|
|
|
13
13
|
from .config import get_config, get_config_manager
|
|
14
14
|
from .core.commands import slash_handler
|
|
15
|
-
from .core.context import ContextManager
|
|
16
15
|
from .core.interactive import InteractivePrompt
|
|
17
16
|
from .core.scheduler import AgentScheduler
|
|
17
|
+
from .core.session import EnhancedSQLiteSession
|
|
18
18
|
from .utils import (
|
|
19
19
|
default_session_local_ms,
|
|
20
20
|
parse_session_dt,
|
|
@@ -28,8 +28,7 @@ console = get_adaptive_console()
|
|
|
28
28
|
|
|
29
29
|
|
|
30
30
|
async def _prompt_select_session() -> Optional[str]:
|
|
31
|
-
|
|
32
|
-
sessions_with_titles = await ctx.list_sessions_with_titles()
|
|
31
|
+
sessions_with_titles = await EnhancedSQLiteSession.list_sessions_with_titles()
|
|
33
32
|
if not sessions_with_titles:
|
|
34
33
|
console.print(Panel("No sessions found.", title="Sessions", border_style="yellow"))
|
|
35
34
|
return None
|
|
@@ -138,12 +137,6 @@ async def main():
|
|
|
138
137
|
"--stream", action="store_true", help="Force enable streaming mode"
|
|
139
138
|
)
|
|
140
139
|
stream_group.add_argument("--no-stream", action="store_true", help="Disable streaming mode")
|
|
141
|
-
parser.add_argument(
|
|
142
|
-
"--reasoning",
|
|
143
|
-
choices=["none", "minimal", "low", "medium", "high", "null"],
|
|
144
|
-
default=None,
|
|
145
|
-
help=("Reasoning effort for reasoning models (null to disable)"),
|
|
146
|
-
)
|
|
147
140
|
|
|
148
141
|
subparsers = parser.add_subparsers(dest="command", help="Available commands")
|
|
149
142
|
create_mcp_subparsers(subparsers)
|
|
@@ -160,12 +153,7 @@ async def main():
|
|
|
160
153
|
"--stream", action="store_true", help="Force enable streaming mode"
|
|
161
154
|
)
|
|
162
155
|
stream_group.add_argument("--no-stream", action="store_true", help="Disable streaming mode")
|
|
163
|
-
|
|
164
|
-
"--reasoning",
|
|
165
|
-
choices=["none", "minimal", "low", "medium", "high", "null"],
|
|
166
|
-
default=None,
|
|
167
|
-
help=("Reasoning effort for reasoning models (null to disable)"),
|
|
168
|
-
)
|
|
156
|
+
|
|
169
157
|
parser.add_argument(
|
|
170
158
|
"prompt", nargs="*", help="Prompt text (if not provided, starts interactive mode)"
|
|
171
159
|
)
|
|
@@ -182,23 +170,6 @@ async def main():
|
|
|
182
170
|
|
|
183
171
|
return await handle_config_command(args)
|
|
184
172
|
|
|
185
|
-
# Apply reasoning effort override from CLI or ENV (CLI > ENV > Config)
|
|
186
|
-
if config:
|
|
187
|
-
cli_reasoning = getattr(args, "reasoning", None)
|
|
188
|
-
if cli_reasoning is not None:
|
|
189
|
-
if cli_reasoning == "null":
|
|
190
|
-
config.model.reasoning_effort = None
|
|
191
|
-
else:
|
|
192
|
-
config.model.reasoning_effort = cli_reasoning
|
|
193
|
-
else:
|
|
194
|
-
env_reasoning = os.environ.get("KODER_REASONING_EFFORT")
|
|
195
|
-
if env_reasoning is not None:
|
|
196
|
-
env_reasoning_lower = env_reasoning.lower()
|
|
197
|
-
if env_reasoning_lower in ("null", "none", ""):
|
|
198
|
-
config.model.reasoning_effort = None
|
|
199
|
-
elif env_reasoning_lower in ("minimal", "low", "medium", "high"):
|
|
200
|
-
config.model.reasoning_effort = env_reasoning_lower
|
|
201
|
-
|
|
202
173
|
if getattr(args, "resume", False):
|
|
203
174
|
selected = await _prompt_select_session()
|
|
204
175
|
if selected:
|
|
@@ -284,7 +255,7 @@ async def main():
|
|
|
284
255
|
# Check for completed title generation (might have finished while waiting for input)
|
|
285
256
|
if scheduler._title_generation_task and scheduler._title_generation_task.done():
|
|
286
257
|
try:
|
|
287
|
-
display_name = await scheduler.
|
|
258
|
+
display_name = await scheduler.session.get_display_name()
|
|
288
259
|
if interactive_prompt.status_line:
|
|
289
260
|
interactive_prompt.status_line.update_display_name(display_name)
|
|
290
261
|
except Exception:
|
|
@@ -313,9 +284,7 @@ async def main():
|
|
|
313
284
|
)
|
|
314
285
|
# Load existing title for the session if available
|
|
315
286
|
try:
|
|
316
|
-
display_name = (
|
|
317
|
-
await scheduler.context_manager.get_display_name()
|
|
318
|
-
)
|
|
287
|
+
display_name = await scheduler.session.get_display_name()
|
|
319
288
|
interactive_prompt.status_line.update_display_name(
|
|
320
289
|
display_name
|
|
321
290
|
)
|
|
@@ -339,7 +308,7 @@ async def main():
|
|
|
339
308
|
and scheduler._title_generation_task.done()
|
|
340
309
|
):
|
|
341
310
|
try:
|
|
342
|
-
display_name = await scheduler.
|
|
311
|
+
display_name = await scheduler.session.get_display_name()
|
|
343
312
|
if interactive_prompt.status_line:
|
|
344
313
|
interactive_prompt.status_line.update_display_name(display_name)
|
|
345
314
|
except Exception:
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"""Core components for Koder Agent."""
|
|
2
2
|
|
|
3
|
-
from .context import ContextManager
|
|
4
3
|
from .scheduler import AgentScheduler
|
|
5
4
|
from .security import SecurityGuard
|
|
5
|
+
from .session import EnhancedSQLiteSession
|
|
6
6
|
|
|
7
|
-
__all__ = ["
|
|
7
|
+
__all__ = ["EnhancedSQLiteSession", "AgentScheduler", "SecurityGuard"]
|
|
@@ -109,15 +109,17 @@ class StatusCommand(SlashCommand):
|
|
|
109
109
|
model = get_model_name()
|
|
110
110
|
|
|
111
111
|
# Get session info
|
|
112
|
-
session_id = scheduler.
|
|
112
|
+
session_id = scheduler.session.session_id
|
|
113
113
|
streaming = scheduler.streaming
|
|
114
114
|
|
|
115
115
|
# Get session title for current session
|
|
116
|
-
session_title = await scheduler.
|
|
116
|
+
session_title = await scheduler.session.get_title()
|
|
117
117
|
session_display = session_title or session_id
|
|
118
118
|
|
|
119
119
|
# Get available sessions with titles
|
|
120
|
-
|
|
120
|
+
from .session import EnhancedSQLiteSession
|
|
121
|
+
|
|
122
|
+
sessions_with_titles = await EnhancedSQLiteSession.list_sessions_with_titles()
|
|
121
123
|
|
|
122
124
|
# Get tools count
|
|
123
125
|
tools = get_all_tools()
|
|
@@ -322,7 +324,9 @@ class SlashCommandHandler:
|
|
|
322
324
|
scheduler._title_generation_task = None
|
|
323
325
|
|
|
324
326
|
# Get sessions with titles and prompt for selection
|
|
325
|
-
|
|
327
|
+
from .session import EnhancedSQLiteSession
|
|
328
|
+
|
|
329
|
+
sessions_with_titles = await EnhancedSQLiteSession.list_sessions_with_titles()
|
|
326
330
|
if not sessions_with_titles:
|
|
327
331
|
return "No sessions found."
|
|
328
332
|
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
"""Async keyboard listener for ESC key interruption.
|
|
2
|
+
|
|
3
|
+
This module provides non-blocking keyboard detection for cancelling
|
|
4
|
+
agent operations during streaming execution.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import asyncio
|
|
8
|
+
import sys
|
|
9
|
+
from contextlib import asynccontextmanager
|
|
10
|
+
from typing import AsyncIterator, Awaitable, Callable, Optional, TypeVar
|
|
11
|
+
|
|
12
|
+
# Platform-specific imports for Unix terminal control
|
|
13
|
+
if sys.platform != "win32":
|
|
14
|
+
import select
|
|
15
|
+
import termios
|
|
16
|
+
import tty
|
|
17
|
+
|
|
18
|
+
T = TypeVar("T")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class CancellationToken:
|
|
22
|
+
"""Token to signal cancellation across async operations."""
|
|
23
|
+
|
|
24
|
+
def __init__(self):
|
|
25
|
+
self._cancelled = False
|
|
26
|
+
self._event = asyncio.Event()
|
|
27
|
+
|
|
28
|
+
def cancel(self) -> None:
|
|
29
|
+
"""Signal cancellation."""
|
|
30
|
+
self._cancelled = True
|
|
31
|
+
self._event.set()
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def is_cancelled(self) -> bool:
|
|
35
|
+
"""Check if cancelled."""
|
|
36
|
+
return self._cancelled
|
|
37
|
+
|
|
38
|
+
async def wait(self) -> None:
|
|
39
|
+
"""Wait until cancelled."""
|
|
40
|
+
await self._event.wait()
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class KeyboardListener:
|
|
44
|
+
"""Non-blocking async keyboard listener for detecting ESC key.
|
|
45
|
+
|
|
46
|
+
Uses Unix termios/tty/select for character-by-character input detection
|
|
47
|
+
without blocking the event loop.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
ESC_KEY = 27 # ASCII code for ESC
|
|
51
|
+
|
|
52
|
+
def __init__(self):
|
|
53
|
+
self._original_settings: Optional[list] = None
|
|
54
|
+
self._listening = False
|
|
55
|
+
|
|
56
|
+
def _is_unix_tty(self) -> bool:
|
|
57
|
+
"""Check if running on Unix with a TTY stdin."""
|
|
58
|
+
return sys.platform != "win32" and sys.stdin.isatty()
|
|
59
|
+
|
|
60
|
+
def _setup_terminal(self) -> None:
|
|
61
|
+
"""Set terminal to cbreak mode for character-by-character input."""
|
|
62
|
+
if self._is_unix_tty():
|
|
63
|
+
self._original_settings = termios.tcgetattr(sys.stdin)
|
|
64
|
+
tty.setcbreak(sys.stdin.fileno())
|
|
65
|
+
|
|
66
|
+
def _restore_terminal(self) -> None:
|
|
67
|
+
"""Restore original terminal settings."""
|
|
68
|
+
if self._original_settings is not None:
|
|
69
|
+
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, self._original_settings)
|
|
70
|
+
self._original_settings = None
|
|
71
|
+
|
|
72
|
+
def _key_available(self) -> bool:
|
|
73
|
+
"""Check if a key is available without blocking."""
|
|
74
|
+
if not self._is_unix_tty():
|
|
75
|
+
return False
|
|
76
|
+
return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], [])
|
|
77
|
+
|
|
78
|
+
async def listen(
|
|
79
|
+
self,
|
|
80
|
+
on_escape: Callable[[], Awaitable[None]],
|
|
81
|
+
poll_interval: float = 0.05,
|
|
82
|
+
) -> None:
|
|
83
|
+
"""Listen for ESC key presses and invoke callback when detected.
|
|
84
|
+
|
|
85
|
+
Args:
|
|
86
|
+
on_escape: Async callback to invoke when ESC is pressed
|
|
87
|
+
poll_interval: How often to check for key presses (seconds)
|
|
88
|
+
"""
|
|
89
|
+
if not self._is_unix_tty():
|
|
90
|
+
# On non-TTY or Windows, ESC listening is disabled - return immediately
|
|
91
|
+
return
|
|
92
|
+
|
|
93
|
+
self._listening = True
|
|
94
|
+
try:
|
|
95
|
+
self._setup_terminal()
|
|
96
|
+
while self._listening:
|
|
97
|
+
if self._key_available():
|
|
98
|
+
char = sys.stdin.read(1)
|
|
99
|
+
if ord(char) == self.ESC_KEY:
|
|
100
|
+
self._listening = False
|
|
101
|
+
await on_escape()
|
|
102
|
+
break
|
|
103
|
+
await asyncio.sleep(poll_interval)
|
|
104
|
+
finally:
|
|
105
|
+
self._restore_terminal()
|
|
106
|
+
|
|
107
|
+
def stop(self) -> None:
|
|
108
|
+
"""Stop listening for key presses."""
|
|
109
|
+
self._listening = False
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
async def iter_with_cancellation(
|
|
113
|
+
async_iter: AsyncIterator[T],
|
|
114
|
+
token: CancellationToken,
|
|
115
|
+
) -> AsyncIterator[T]:
|
|
116
|
+
"""Wrap an async iterator to support cancellation.
|
|
117
|
+
|
|
118
|
+
This allows breaking out of an async for loop when cancellation is requested,
|
|
119
|
+
even if the underlying iterator is blocked waiting for the next item.
|
|
120
|
+
|
|
121
|
+
Args:
|
|
122
|
+
async_iter: The async iterator to wrap
|
|
123
|
+
token: Cancellation token to check
|
|
124
|
+
|
|
125
|
+
Yields:
|
|
126
|
+
Items from the underlying iterator until cancelled
|
|
127
|
+
"""
|
|
128
|
+
try:
|
|
129
|
+
while not token.is_cancelled:
|
|
130
|
+
# Create a task for getting the next item
|
|
131
|
+
try:
|
|
132
|
+
# Use anext with a wrapper that checks cancellation
|
|
133
|
+
next_task = asyncio.create_task(async_iter.__anext__())
|
|
134
|
+
cancel_task = asyncio.create_task(token.wait())
|
|
135
|
+
|
|
136
|
+
# Wait for either next item or cancellation
|
|
137
|
+
done, pending = await asyncio.wait(
|
|
138
|
+
[next_task, cancel_task],
|
|
139
|
+
return_when=asyncio.FIRST_COMPLETED,
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
# Cancel pending tasks
|
|
143
|
+
for task in pending:
|
|
144
|
+
task.cancel()
|
|
145
|
+
try:
|
|
146
|
+
await task
|
|
147
|
+
except asyncio.CancelledError:
|
|
148
|
+
pass
|
|
149
|
+
|
|
150
|
+
# Check what completed
|
|
151
|
+
if cancel_task in done:
|
|
152
|
+
# Cancellation requested
|
|
153
|
+
break
|
|
154
|
+
|
|
155
|
+
if next_task in done:
|
|
156
|
+
try:
|
|
157
|
+
item = next_task.result()
|
|
158
|
+
yield item
|
|
159
|
+
except StopAsyncIteration:
|
|
160
|
+
break
|
|
161
|
+
|
|
162
|
+
except asyncio.CancelledError:
|
|
163
|
+
break
|
|
164
|
+
except StopAsyncIteration:
|
|
165
|
+
pass
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
@asynccontextmanager
|
|
169
|
+
async def escape_listener(
|
|
170
|
+
on_escape: Callable[[], Awaitable[None]],
|
|
171
|
+
enabled: bool = True,
|
|
172
|
+
):
|
|
173
|
+
"""Context manager that runs an ESC key listener as a background task.
|
|
174
|
+
|
|
175
|
+
Usage:
|
|
176
|
+
async with escape_listener(on_escape=handle_cancel):
|
|
177
|
+
async for event in stream:
|
|
178
|
+
process(event)
|
|
179
|
+
|
|
180
|
+
Args:
|
|
181
|
+
on_escape: Async callback to invoke when ESC is pressed
|
|
182
|
+
enabled: Whether to enable the listener (disabled for non-TTY)
|
|
183
|
+
|
|
184
|
+
Yields:
|
|
185
|
+
KeyboardListener instance (or None if disabled)
|
|
186
|
+
"""
|
|
187
|
+
if not enabled:
|
|
188
|
+
yield None
|
|
189
|
+
return
|
|
190
|
+
|
|
191
|
+
listener = KeyboardListener()
|
|
192
|
+
task = asyncio.create_task(listener.listen(on_escape))
|
|
193
|
+
|
|
194
|
+
try:
|
|
195
|
+
yield listener
|
|
196
|
+
finally:
|
|
197
|
+
listener.stop()
|
|
198
|
+
task.cancel()
|
|
199
|
+
try:
|
|
200
|
+
await task
|
|
201
|
+
except asyncio.CancelledError:
|
|
202
|
+
pass
|