koder 0.4.2__tar.gz → 0.4.4__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.2 → koder-0.4.4}/.claude/settings.local.json +3 -1
- koder-0.4.4/GEMINI.md +1 -0
- {koder-0.4.2 → koder-0.4.4}/PKG-INFO +2 -1
- {koder-0.4.2 → koder-0.4.4}/koder_agent/agentic/agent.py +15 -17
- {koder-0.4.2 → koder-0.4.4}/koder_agent/cli.py +1 -29
- koder-0.4.4/koder_agent/core/keyboard_listener.py +202 -0
- {koder-0.4.2 → koder-0.4.4}/koder_agent/core/scheduler.py +152 -84
- {koder-0.4.2 → koder-0.4.4}/koder_agent/utils/client.py +100 -33
- {koder-0.4.2 → koder-0.4.4}/koder_agent/utils/prompts.py +2 -5
- {koder-0.4.2 → koder-0.4.4}/pyproject.toml +2 -1
- koder-0.4.4/tests/test_model_resolution.py +131 -0
- {koder-0.4.2 → koder-0.4.4}/uv.lock +3 -1
- {koder-0.4.2 → koder-0.4.4}/.github/dependabot.yml +0 -0
- {koder-0.4.2 → koder-0.4.4}/.gitignore +0 -0
- {koder-0.4.2 → koder-0.4.4}/AGENTS.md +0 -0
- {koder-0.4.2 → koder-0.4.4}/CLAUDE.md +0 -0
- {koder-0.4.2 → koder-0.4.4}/CONTRIBUTING.md +0 -0
- {koder-0.4.2 → koder-0.4.4}/LICENSE +0 -0
- {koder-0.4.2 → koder-0.4.4}/README.md +0 -0
- {koder-0.4.2 → koder-0.4.4}/koder_agent/__init__.py +0 -0
- {koder-0.4.2 → koder-0.4.4}/koder_agent/agentic/__init__.py +0 -0
- {koder-0.4.2 → koder-0.4.4}/koder_agent/agentic/approval_hooks.py +0 -0
- {koder-0.4.2 → koder-0.4.4}/koder_agent/agentic/hooks.py +0 -0
- {koder-0.4.2 → koder-0.4.4}/koder_agent/config/__init__.py +0 -0
- {koder-0.4.2 → koder-0.4.4}/koder_agent/config/cli_handler.py +0 -0
- {koder-0.4.2 → koder-0.4.4}/koder_agent/config/manager.py +0 -0
- {koder-0.4.2 → koder-0.4.4}/koder_agent/config/models.py +0 -0
- {koder-0.4.2 → koder-0.4.4}/koder_agent/core/__init__.py +0 -0
- {koder-0.4.2 → koder-0.4.4}/koder_agent/core/commands.py +0 -0
- {koder-0.4.2 → koder-0.4.4}/koder_agent/core/interactive.py +0 -0
- {koder-0.4.2 → koder-0.4.4}/koder_agent/core/security.py +0 -0
- {koder-0.4.2 → koder-0.4.4}/koder_agent/core/session.py +0 -0
- {koder-0.4.2 → koder-0.4.4}/koder_agent/core/status_line.py +0 -0
- {koder-0.4.2 → koder-0.4.4}/koder_agent/core/streaming_display.py +0 -0
- {koder-0.4.2 → koder-0.4.4}/koder_agent/core/usage_tracker.py +0 -0
- {koder-0.4.2 → koder-0.4.4}/koder_agent/mcp/__init__.py +0 -0
- {koder-0.4.2 → koder-0.4.4}/koder_agent/mcp/cli_handler.py +0 -0
- {koder-0.4.2 → koder-0.4.4}/koder_agent/mcp/server_config.py +0 -0
- {koder-0.4.2 → koder-0.4.4}/koder_agent/mcp/server_factory.py +0 -0
- {koder-0.4.2 → koder-0.4.4}/koder_agent/mcp/server_manager.py +0 -0
- {koder-0.4.2 → koder-0.4.4}/koder_agent/tools/__init__.py +0 -0
- {koder-0.4.2 → koder-0.4.4}/koder_agent/tools/engine.py +0 -0
- {koder-0.4.2 → koder-0.4.4}/koder_agent/tools/file.py +0 -0
- {koder-0.4.2 → koder-0.4.4}/koder_agent/tools/search.py +0 -0
- {koder-0.4.2 → koder-0.4.4}/koder_agent/tools/shell.py +0 -0
- {koder-0.4.2 → koder-0.4.4}/koder_agent/tools/task.py +0 -0
- {koder-0.4.2 → koder-0.4.4}/koder_agent/tools/todo.py +0 -0
- {koder-0.4.2 → koder-0.4.4}/koder_agent/tools/web.py +0 -0
- {koder-0.4.2 → koder-0.4.4}/koder_agent/utils/__init__.py +0 -0
- {koder-0.4.2 → koder-0.4.4}/koder_agent/utils/model_info.py +0 -0
- {koder-0.4.2 → koder-0.4.4}/koder_agent/utils/queue.py +0 -0
- {koder-0.4.2 → koder-0.4.4}/koder_agent/utils/sessions.py +0 -0
- {koder-0.4.2 → koder-0.4.4}/koder_agent/utils/terminal_theme.py +0 -0
- {koder-0.4.2 → koder-0.4.4}/scripts/upgrade_dependency.py +0 -0
- {koder-0.4.2 → koder-0.4.4}/tests/test_file_tools.py +0 -0
- {koder-0.4.2 → koder-0.4.4}/tests/test_shell_background.py +0 -0
- {koder-0.4.2 → koder-0.4.4}/tests/test_web.py +0 -0
koder-0.4.4/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.4
|
|
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
|
|
@@ -18,6 +18,7 @@ Requires-Dist: fastapi-sso>=0.18.0
|
|
|
18
18
|
Requires-Dist: fastapi>=0.122.0
|
|
19
19
|
Requires-Dist: google-cloud-aiplatform>=1.128.0
|
|
20
20
|
Requires-Dist: httpx[socks]>=0.28.1
|
|
21
|
+
Requires-Dist: litellm>=1.80.5
|
|
21
22
|
Requires-Dist: openai-agents[litellm]>=0.6.1
|
|
22
23
|
Requires-Dist: openai>=2.8.1
|
|
23
24
|
Requires-Dist: orjson>=3.11.4
|
|
@@ -23,15 +23,18 @@ logger = logging.getLogger(__name__)
|
|
|
23
23
|
class RetryingLitellmModel(LitellmModel):
|
|
24
24
|
"""LitellmModel with backoff retry logic."""
|
|
25
25
|
|
|
26
|
+
_EXC = getattr(litellm, "exceptions", litellm)
|
|
27
|
+
_EXC_TUPLE = (
|
|
28
|
+
getattr(_EXC, "ServiceUnavailableError", Exception),
|
|
29
|
+
getattr(_EXC, "RateLimitError", Exception),
|
|
30
|
+
getattr(_EXC, "APIConnectionError", Exception),
|
|
31
|
+
getattr(_EXC, "Timeout", Exception),
|
|
32
|
+
getattr(_EXC, "InternalServerError", Exception),
|
|
33
|
+
)
|
|
34
|
+
|
|
26
35
|
@backoff.on_exception(
|
|
27
36
|
backoff.expo,
|
|
28
|
-
|
|
29
|
-
litellm.exceptions.ServiceUnavailableError,
|
|
30
|
-
litellm.exceptions.RateLimitError,
|
|
31
|
-
litellm.exceptions.APIConnectionError,
|
|
32
|
-
litellm.exceptions.Timeout,
|
|
33
|
-
litellm.exceptions.InternalServerError,
|
|
34
|
-
),
|
|
37
|
+
_EXC_TUPLE,
|
|
35
38
|
max_tries=3,
|
|
36
39
|
jitter=backoff.full_jitter,
|
|
37
40
|
)
|
|
@@ -40,13 +43,7 @@ class RetryingLitellmModel(LitellmModel):
|
|
|
40
43
|
|
|
41
44
|
@backoff.on_exception(
|
|
42
45
|
backoff.expo,
|
|
43
|
-
|
|
44
|
-
litellm.exceptions.ServiceUnavailableError,
|
|
45
|
-
litellm.exceptions.RateLimitError,
|
|
46
|
-
litellm.exceptions.APIConnectionError,
|
|
47
|
-
litellm.exceptions.Timeout,
|
|
48
|
-
litellm.exceptions.InternalServerError,
|
|
49
|
-
),
|
|
46
|
+
_EXC_TUPLE,
|
|
50
47
|
max_tries=5,
|
|
51
48
|
jitter=backoff.full_jitter,
|
|
52
49
|
)
|
|
@@ -75,12 +72,13 @@ async def create_dev_agent(tools) -> Agent:
|
|
|
75
72
|
|
|
76
73
|
# Build model_settings with reasoning if configured
|
|
77
74
|
model_name_str = get_model_name() # Always get string name for max_tokens lookup
|
|
78
|
-
model_settings = ModelSettings(
|
|
75
|
+
model_settings = ModelSettings(
|
|
76
|
+
metadata={"source": "koder"},
|
|
77
|
+
max_tokens=get_maximum_output_tokens(model_name_str),
|
|
78
|
+
)
|
|
79
79
|
if config.model.reasoning_effort is not None:
|
|
80
80
|
effort = None if config.model.reasoning_effort == "none" else config.model.reasoning_effort
|
|
81
81
|
model_settings.reasoning = Reasoning(effort=effort, summary="detailed")
|
|
82
|
-
if "gpt-5" in model_name_str:
|
|
83
|
-
model_settings.verbosity = "high"
|
|
84
82
|
|
|
85
83
|
dev_agent = Agent(
|
|
86
84
|
name="Koder",
|
|
@@ -137,12 +137,6 @@ async def main():
|
|
|
137
137
|
"--stream", action="store_true", help="Force enable streaming mode"
|
|
138
138
|
)
|
|
139
139
|
stream_group.add_argument("--no-stream", action="store_true", help="Disable streaming mode")
|
|
140
|
-
parser.add_argument(
|
|
141
|
-
"--reasoning",
|
|
142
|
-
choices=["none", "minimal", "low", "medium", "high", "null"],
|
|
143
|
-
default=None,
|
|
144
|
-
help=("Reasoning effort for reasoning models (null to disable)"),
|
|
145
|
-
)
|
|
146
140
|
|
|
147
141
|
subparsers = parser.add_subparsers(dest="command", help="Available commands")
|
|
148
142
|
create_mcp_subparsers(subparsers)
|
|
@@ -159,12 +153,7 @@ async def main():
|
|
|
159
153
|
"--stream", action="store_true", help="Force enable streaming mode"
|
|
160
154
|
)
|
|
161
155
|
stream_group.add_argument("--no-stream", action="store_true", help="Disable streaming mode")
|
|
162
|
-
|
|
163
|
-
"--reasoning",
|
|
164
|
-
choices=["none", "minimal", "low", "medium", "high", "null"],
|
|
165
|
-
default=None,
|
|
166
|
-
help=("Reasoning effort for reasoning models (null to disable)"),
|
|
167
|
-
)
|
|
156
|
+
|
|
168
157
|
parser.add_argument(
|
|
169
158
|
"prompt", nargs="*", help="Prompt text (if not provided, starts interactive mode)"
|
|
170
159
|
)
|
|
@@ -181,23 +170,6 @@ async def main():
|
|
|
181
170
|
|
|
182
171
|
return await handle_config_command(args)
|
|
183
172
|
|
|
184
|
-
# Apply reasoning effort override from CLI or ENV (CLI > ENV > Config)
|
|
185
|
-
if config:
|
|
186
|
-
cli_reasoning = getattr(args, "reasoning", None)
|
|
187
|
-
if cli_reasoning is not None:
|
|
188
|
-
if cli_reasoning == "null":
|
|
189
|
-
config.model.reasoning_effort = None
|
|
190
|
-
else:
|
|
191
|
-
config.model.reasoning_effort = cli_reasoning
|
|
192
|
-
else:
|
|
193
|
-
env_reasoning = os.environ.get("KODER_REASONING_EFFORT")
|
|
194
|
-
if env_reasoning is not None:
|
|
195
|
-
env_reasoning_lower = env_reasoning.lower()
|
|
196
|
-
if env_reasoning_lower in ("null", "none", ""):
|
|
197
|
-
config.model.reasoning_effort = None
|
|
198
|
-
elif env_reasoning_lower in ("minimal", "low", "medium", "high"):
|
|
199
|
-
config.model.reasoning_effort = env_reasoning_lower
|
|
200
|
-
|
|
201
173
|
if getattr(args, "resume", False):
|
|
202
174
|
selected = await _prompt_select_session()
|
|
203
175
|
if selected:
|
|
@@ -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
|
|
@@ -18,6 +18,7 @@ from rich.live import Live
|
|
|
18
18
|
from rich.text import Text
|
|
19
19
|
|
|
20
20
|
from ..agentic import ApprovalHooks, create_dev_agent, get_display_hooks
|
|
21
|
+
from ..core.keyboard_listener import CancellationToken, escape_listener, iter_with_cancellation
|
|
21
22
|
from ..core.session import EnhancedSQLiteSession, migrate_legacy_sessions
|
|
22
23
|
from ..core.streaming_display import StreamingDisplayManager
|
|
23
24
|
from ..core.usage_tracker import UsageTracker
|
|
@@ -153,7 +154,7 @@ class AgentScheduler:
|
|
|
153
154
|
return response
|
|
154
155
|
|
|
155
156
|
async def _handle_streaming(self, user_input: str) -> str:
|
|
156
|
-
"""Handle streaming execution with Rich Live and
|
|
157
|
+
"""Handle streaming execution with Rich Live, smart cleanup, and ESC cancellation."""
|
|
157
158
|
import os
|
|
158
159
|
import sys
|
|
159
160
|
|
|
@@ -164,12 +165,12 @@ class AgentScheduler:
|
|
|
164
165
|
terminal_type = os.environ.get("TERM_PROGRAM", "unknown")
|
|
165
166
|
supports_advanced_clearing = terminal_type in ["iTerm.app", "Apple_Terminal", "vscode"]
|
|
166
167
|
|
|
168
|
+
# Check if ESC listener should be enabled (Unix TTY only)
|
|
169
|
+
esc_enabled = sys.platform != "win32" and sys.stdin.isatty()
|
|
170
|
+
|
|
167
171
|
# Add space before streaming starts
|
|
168
172
|
print()
|
|
169
173
|
|
|
170
|
-
# Skip cursor position capture - it causes escape sequence leaks
|
|
171
|
-
# The terminal clearing strategies below work without explicit position tracking
|
|
172
|
-
|
|
173
174
|
# Run the agent in streaming mode
|
|
174
175
|
if self.dev_agent is None:
|
|
175
176
|
console.print("[dim red]Agent not initialized[/dim red]")
|
|
@@ -187,6 +188,30 @@ class AgentScheduler:
|
|
|
187
188
|
# Track if we displayed content during streaming
|
|
188
189
|
content_displayed = False
|
|
189
190
|
|
|
191
|
+
# Track cancellation state with token for immediate response
|
|
192
|
+
cancel_token = CancellationToken()
|
|
193
|
+
cancelled = False
|
|
194
|
+
|
|
195
|
+
async def handle_escape():
|
|
196
|
+
"""Callback when ESC key is pressed."""
|
|
197
|
+
nonlocal cancelled
|
|
198
|
+
cancelled = True
|
|
199
|
+
cancel_token.cancel() # Signal to break out of iterator immediately
|
|
200
|
+
result.cancel(mode="immediate") # Also cancel the underlying stream
|
|
201
|
+
|
|
202
|
+
# Show ESC hint if enabled (will be cleared after streaming)
|
|
203
|
+
esc_hint_shown = False
|
|
204
|
+
if esc_enabled:
|
|
205
|
+
console.print("[dim]Press ESC to cancel[/dim]")
|
|
206
|
+
esc_hint_shown = True
|
|
207
|
+
|
|
208
|
+
def clear_esc_hint():
|
|
209
|
+
"""Clear the ESC hint line using ANSI escape sequences."""
|
|
210
|
+
if esc_hint_shown:
|
|
211
|
+
# Move cursor up one line and clear it
|
|
212
|
+
sys.stdout.write("\033[A\033[2K")
|
|
213
|
+
sys.stdout.flush()
|
|
214
|
+
|
|
190
215
|
# Use Rich Live for proper formatting during streaming
|
|
191
216
|
with Live(
|
|
192
217
|
"",
|
|
@@ -196,93 +221,107 @@ class AgentScheduler:
|
|
|
196
221
|
vertical_overflow="crop",
|
|
197
222
|
) as live:
|
|
198
223
|
try:
|
|
199
|
-
#
|
|
200
|
-
async
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
if
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
224
|
+
# Wrap event loop with ESC listener
|
|
225
|
+
async with escape_listener(on_escape=handle_escape, enabled=esc_enabled):
|
|
226
|
+
# Process streaming events with cancellation support
|
|
227
|
+
# iter_with_cancellation allows immediate break when ESC is pressed
|
|
228
|
+
stream_iter = result.stream_events()
|
|
229
|
+
async for event in iter_with_cancellation(stream_iter, cancel_token):
|
|
230
|
+
# Check if cancelled (redundant but explicit)
|
|
231
|
+
if cancelled:
|
|
232
|
+
break
|
|
233
|
+
|
|
234
|
+
try:
|
|
235
|
+
should_update = False
|
|
236
|
+
|
|
237
|
+
# Handle raw response events (token-by-token streaming)
|
|
238
|
+
if isinstance(event, RawResponsesStreamEvent):
|
|
239
|
+
if isinstance(event.data, ResponseTextDeltaEvent):
|
|
240
|
+
delta_text = event.data.delta
|
|
241
|
+
output_index = event.data.output_index
|
|
242
|
+
|
|
243
|
+
if delta_text:
|
|
244
|
+
should_update = display_manager.handle_text_delta(
|
|
245
|
+
output_index, delta_text
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
# Handle run item events (tool calls, outputs, etc.)
|
|
249
|
+
elif isinstance(event, RunItemStreamEvent):
|
|
250
|
+
if event.name == "tool_called":
|
|
251
|
+
if (
|
|
252
|
+
hasattr(event, "item")
|
|
253
|
+
and isinstance(event.item, ToolCallItem)
|
|
254
|
+
and isinstance(
|
|
255
|
+
event.item.raw_item, ResponseFunctionToolCall
|
|
256
|
+
)
|
|
257
|
+
):
|
|
258
|
+
should_update = display_manager.handle_tool_called(
|
|
259
|
+
event.item
|
|
260
|
+
)
|
|
261
|
+
|
|
262
|
+
elif event.name == "tool_output":
|
|
263
|
+
if hasattr(event, "item") and isinstance(
|
|
264
|
+
event.item, ToolCallOutputItem
|
|
265
|
+
):
|
|
266
|
+
should_update = display_manager.handle_tool_output(
|
|
267
|
+
event.item
|
|
268
|
+
)
|
|
269
|
+
|
|
270
|
+
elif event.name == "message_output_created":
|
|
271
|
+
pass
|
|
272
|
+
elif event.name == "handoff_requested":
|
|
273
|
+
# Handle agent handoff as a special tool call
|
|
274
|
+
should_update = display_manager.handle_tool_called(
|
|
275
|
+
type(
|
|
276
|
+
"HandoffItem",
|
|
277
|
+
(),
|
|
278
|
+
{
|
|
279
|
+
"raw_item": type(
|
|
280
|
+
"RawItem",
|
|
281
|
+
(),
|
|
282
|
+
{
|
|
283
|
+
"name": "agent_handoff",
|
|
284
|
+
"arguments": "{}",
|
|
285
|
+
"id": "handoff",
|
|
286
|
+
},
|
|
287
|
+
)()
|
|
288
|
+
},
|
|
289
|
+
)()
|
|
290
|
+
)
|
|
291
|
+
elif event.name == "handoff_occured":
|
|
292
|
+
# Handle as tool output
|
|
293
|
+
should_update = display_manager.handle_tool_output(
|
|
294
|
+
type(
|
|
295
|
+
"HandoffOutput",
|
|
296
|
+
(),
|
|
297
|
+
{"output": "Agent switched", "tool_call_id": "handoff"},
|
|
298
|
+
)()
|
|
213
299
|
)
|
|
300
|
+
elif event.name == "reasoning_item_created":
|
|
301
|
+
# Don't show reasoning steps in display
|
|
302
|
+
pass
|
|
214
303
|
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
if (
|
|
219
|
-
hasattr(event, "item")
|
|
220
|
-
and isinstance(event.item, ToolCallItem)
|
|
221
|
-
and isinstance(event.item.raw_item, ResponseFunctionToolCall)
|
|
222
|
-
):
|
|
223
|
-
should_update = display_manager.handle_tool_called(event.item)
|
|
224
|
-
|
|
225
|
-
elif event.name == "tool_output":
|
|
226
|
-
if hasattr(event, "item") and isinstance(
|
|
227
|
-
event.item, ToolCallOutputItem
|
|
228
|
-
):
|
|
229
|
-
should_update = display_manager.handle_tool_output(event.item)
|
|
230
|
-
|
|
231
|
-
elif event.name == "message_output_created":
|
|
232
|
-
pass
|
|
233
|
-
elif event.name == "handoff_requested":
|
|
234
|
-
# Handle agent handoff as a special tool call
|
|
235
|
-
should_update = display_manager.handle_tool_called(
|
|
236
|
-
type(
|
|
237
|
-
"HandoffItem",
|
|
238
|
-
(),
|
|
239
|
-
{
|
|
240
|
-
"raw_item": type(
|
|
241
|
-
"RawItem",
|
|
242
|
-
(),
|
|
243
|
-
{
|
|
244
|
-
"name": "agent_handoff",
|
|
245
|
-
"arguments": "{}",
|
|
246
|
-
"id": "handoff",
|
|
247
|
-
},
|
|
248
|
-
)()
|
|
249
|
-
},
|
|
250
|
-
)()
|
|
251
|
-
)
|
|
252
|
-
elif event.name == "handoff_occured":
|
|
253
|
-
# Handle as tool output
|
|
254
|
-
should_update = display_manager.handle_tool_output(
|
|
255
|
-
type(
|
|
256
|
-
"HandoffOutput",
|
|
257
|
-
(),
|
|
258
|
-
{"output": "Agent switched", "tool_call_id": "handoff"},
|
|
259
|
-
)()
|
|
260
|
-
)
|
|
261
|
-
elif event.name == "reasoning_item_created":
|
|
262
|
-
# Don't show reasoning steps in display
|
|
304
|
+
# Handle agent updates (handoffs, etc.)
|
|
305
|
+
elif isinstance(event, AgentUpdatedStreamEvent):
|
|
306
|
+
# This is handled by handoff events above
|
|
263
307
|
pass
|
|
264
308
|
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
if isinstance(current_content, str):
|
|
275
|
-
if current_content.strip():
|
|
309
|
+
# Update Rich Live display
|
|
310
|
+
if should_update:
|
|
311
|
+
current_content = display_manager.get_display_content()
|
|
312
|
+
# Handle both string and renderable objects
|
|
313
|
+
if isinstance(current_content, str):
|
|
314
|
+
if current_content.strip():
|
|
315
|
+
live.update(current_content)
|
|
316
|
+
content_displayed = True
|
|
317
|
+
elif current_content: # For renderables like Group
|
|
276
318
|
live.update(current_content)
|
|
277
319
|
content_displayed = True
|
|
278
|
-
elif current_content: # For renderables like Group
|
|
279
|
-
live.update(current_content)
|
|
280
|
-
content_displayed = True
|
|
281
320
|
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
321
|
+
except Exception as e:
|
|
322
|
+
# Log event processing errors but continue streaming
|
|
323
|
+
console.print(f"[dim red]Event processing error: {e}[/dim red]")
|
|
324
|
+
continue
|
|
286
325
|
|
|
287
326
|
except Exception as e:
|
|
288
327
|
# Handle execution errors in streaming mode
|
|
@@ -290,11 +329,40 @@ class AgentScheduler:
|
|
|
290
329
|
console.print(f"[red]{error_msg}[/red]")
|
|
291
330
|
# Clear the display manager and return early
|
|
292
331
|
display_manager.finalize_text_sections()
|
|
332
|
+
clear_esc_hint() # Clear ESC hint on error path too
|
|
293
333
|
return f"{error_msg}\n\nPlease provide new instructions."
|
|
294
334
|
|
|
295
335
|
# After Rich Live context ends, perform intelligent cleanup
|
|
296
336
|
display_manager.finalize_text_sections()
|
|
297
337
|
|
|
338
|
+
# Clear the ESC hint line
|
|
339
|
+
clear_esc_hint()
|
|
340
|
+
|
|
341
|
+
# Handle cancellation case
|
|
342
|
+
if cancelled:
|
|
343
|
+
# Rich Live with transient=True clears content on exit, so we need to re-print
|
|
344
|
+
# Get partial content that was accumulated during streaming
|
|
345
|
+
partial_display = display_manager.get_final_display()
|
|
346
|
+
partial_text = display_manager.get_final_text()
|
|
347
|
+
|
|
348
|
+
# Show the partial output (text + tool summaries)
|
|
349
|
+
if partial_display and partial_display.strip():
|
|
350
|
+
print() # Add spacing
|
|
351
|
+
console.print(partial_display)
|
|
352
|
+
elif partial_text and partial_text.strip():
|
|
353
|
+
print() # Add spacing
|
|
354
|
+
console.print(partial_text)
|
|
355
|
+
|
|
356
|
+
# Show cancellation message
|
|
357
|
+
console.print("\n[yellow]Operation cancelled by user[/yellow]")
|
|
358
|
+
console.print()
|
|
359
|
+
|
|
360
|
+
# Capture any usage data we can
|
|
361
|
+
self._capture_usage(result)
|
|
362
|
+
|
|
363
|
+
# Return partial text for session history
|
|
364
|
+
return partial_text or "Operation cancelled. You can provide additional instructions."
|
|
365
|
+
|
|
298
366
|
# Get final content for permanent display
|
|
299
367
|
final_content = display_manager.get_display_content()
|
|
300
368
|
|
|
@@ -17,6 +17,16 @@ from ..config import get_config, get_config_manager
|
|
|
17
17
|
litellm.suppress_debug_info = True
|
|
18
18
|
litellm.drop_params = True
|
|
19
19
|
|
|
20
|
+
# LiteLLM changed exception namespace in some versions; unify access.
|
|
21
|
+
_LITELLM_EXC = getattr(litellm, "exceptions", litellm)
|
|
22
|
+
_LITELLM_ERRORS = (
|
|
23
|
+
getattr(_LITELLM_EXC, "ServiceUnavailableError", Exception),
|
|
24
|
+
getattr(_LITELLM_EXC, "RateLimitError", Exception),
|
|
25
|
+
getattr(_LITELLM_EXC, "APIConnectionError", Exception),
|
|
26
|
+
getattr(_LITELLM_EXC, "Timeout", Exception),
|
|
27
|
+
getattr(_LITELLM_EXC, "InternalServerError", Exception),
|
|
28
|
+
)
|
|
29
|
+
|
|
20
30
|
# Configure global retry settings for LiteLLM
|
|
21
31
|
# num_retries will be applied to all litellm API calls unless overridden
|
|
22
32
|
litellm.num_retries = 3 # Default, will be updated with config values
|
|
@@ -93,18 +103,58 @@ def _split_model_identifier(model: str) -> tuple[Optional[str], str, bool]:
|
|
|
93
103
|
return provider_part.lower(), model_part, had_prefix
|
|
94
104
|
|
|
95
105
|
|
|
106
|
+
def _is_openai_native_model(raw_model: str) -> bool:
|
|
107
|
+
"""
|
|
108
|
+
Detect whether a model string refers to an OpenAI-native model.
|
|
109
|
+
|
|
110
|
+
Handles plain names ("gpt-4o") and provider-prefixed strings
|
|
111
|
+
("openai/gpt-4o", "litellm/openai/gpt-4o").
|
|
112
|
+
"""
|
|
113
|
+
if not raw_model:
|
|
114
|
+
return False
|
|
115
|
+
_, model_part, _ = _split_model_identifier(raw_model)
|
|
116
|
+
ml = model_part.lower()
|
|
117
|
+
return ml.startswith(("gpt-", "o1-", "o3-", "o4-", "chatgpt-"))
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _strip_matching_provider(raw_model: str, provider: str) -> str:
|
|
121
|
+
"""Strip provider prefix if it matches the resolved provider."""
|
|
122
|
+
explicit_provider, model_part, _ = _split_model_identifier(raw_model)
|
|
123
|
+
if explicit_provider and explicit_provider == provider.lower():
|
|
124
|
+
return model_part
|
|
125
|
+
return raw_model
|
|
126
|
+
|
|
127
|
+
|
|
96
128
|
def _resolve_model_settings():
|
|
97
|
-
"""Resolve the effective config, provider, and raw model string.
|
|
129
|
+
"""Resolve the effective config, provider, and raw model string.
|
|
130
|
+
|
|
131
|
+
When model comes from KODER_MODEL env var, it may use 'provider/model' format
|
|
132
|
+
(e.g., 'openrouter/x-ai/grok-4.1-fast:free'), so we extract the provider from it.
|
|
133
|
+
|
|
134
|
+
When model comes from config file, the provider is explicitly specified in
|
|
135
|
+
config.model.provider, so we use that directly without parsing the model name.
|
|
136
|
+
Model names can contain '/' (e.g., 'x-ai/grok-4.1-fast:free') which should not
|
|
137
|
+
be interpreted as a provider prefix.
|
|
138
|
+
"""
|
|
98
139
|
config = get_config()
|
|
99
140
|
config_manager = get_config_manager()
|
|
141
|
+
|
|
142
|
+
# Check if KODER_MODEL env var is set
|
|
143
|
+
env_model = os.environ.get("KODER_MODEL")
|
|
144
|
+
model_from_env = env_model is not None
|
|
145
|
+
|
|
100
146
|
raw_model = config_manager.get_effective_value(config.model.name, "KODER_MODEL")
|
|
101
147
|
provider = config.model.provider.lower()
|
|
102
148
|
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
149
|
+
# Only extract provider from model string if it came from environment variable
|
|
150
|
+
# Environment variable uses 'provider/model' format (e.g., 'openrouter/deepseek-r1')
|
|
151
|
+
# Config file has separate 'provider' field, so model name may contain '/' as part of name
|
|
152
|
+
if model_from_env:
|
|
153
|
+
explicit_provider, _, _ = _split_model_identifier(raw_model)
|
|
154
|
+
if explicit_provider:
|
|
155
|
+
provider = explicit_provider
|
|
106
156
|
|
|
107
|
-
return config, config_manager, provider, raw_model
|
|
157
|
+
return config, config_manager, provider, raw_model, model_from_env
|
|
108
158
|
|
|
109
159
|
|
|
110
160
|
def _get_provider_api_key(config, config_manager, provider: str):
|
|
@@ -143,48 +193,67 @@ def _setup_provider_env_vars(config, provider: str):
|
|
|
143
193
|
os.environ[env_var_name] = api_key
|
|
144
194
|
|
|
145
195
|
|
|
146
|
-
def _normalize_model_name(provider: str, raw_model: str) -> str:
|
|
147
|
-
"""Return a LiteLLM-compatible identifier, always using litellm/<provider>/<model>.
|
|
196
|
+
def _normalize_model_name(provider: str, raw_model: str, model_from_env: bool = False) -> str:
|
|
197
|
+
"""Return a LiteLLM-compatible identifier, always using litellm/<provider>/<model>.
|
|
198
|
+
|
|
199
|
+
Args:
|
|
200
|
+
provider: The resolved provider name
|
|
201
|
+
raw_model: The raw model string
|
|
202
|
+
model_from_env: If True, the model string came from KODER_MODEL env var and may
|
|
203
|
+
contain an explicit provider prefix (e.g., 'openrouter/model-name').
|
|
204
|
+
If False, the model name should be used as-is since provider comes
|
|
205
|
+
from config file.
|
|
206
|
+
"""
|
|
148
207
|
if not raw_model:
|
|
149
208
|
return raw_model
|
|
150
209
|
if raw_model.startswith("litellm/"):
|
|
151
210
|
return raw_model
|
|
152
211
|
|
|
153
|
-
|
|
154
|
-
if
|
|
155
|
-
|
|
212
|
+
# Only parse provider from model string if it came from environment variable
|
|
213
|
+
if model_from_env:
|
|
214
|
+
explicit_provider, remainder, _ = _split_model_identifier(raw_model)
|
|
215
|
+
if explicit_provider:
|
|
216
|
+
return f"litellm/{explicit_provider}/{remainder}"
|
|
156
217
|
|
|
157
218
|
provider = provider.lower()
|
|
158
219
|
return f"litellm/{provider}/{raw_model}"
|
|
159
220
|
|
|
160
221
|
|
|
161
|
-
def _compute_effective_model(config, config_manager, provider, raw_model):
|
|
222
|
+
def _compute_effective_model(config, config_manager, provider, raw_model, model_from_env=False):
|
|
162
223
|
"""Determine the model name and whether to use native OpenAI integration."""
|
|
163
224
|
api_key = _get_provider_api_key(config, config_manager, provider)
|
|
164
|
-
use_native =
|
|
225
|
+
use_native = (
|
|
226
|
+
provider in ("openai", "custom")
|
|
227
|
+
and api_key
|
|
228
|
+
and _is_openai_native_model(raw_model)
|
|
229
|
+
)
|
|
165
230
|
|
|
166
231
|
if use_native:
|
|
167
|
-
|
|
232
|
+
# If the raw model string included a provider prefix, strip it for native calls
|
|
233
|
+
normalized_raw = _strip_matching_provider(raw_model, provider)
|
|
234
|
+
return normalized_raw, True, api_key
|
|
168
235
|
|
|
169
|
-
return _normalize_model_name(provider, raw_model), False, api_key
|
|
236
|
+
return _normalize_model_name(provider, raw_model, model_from_env), False, api_key
|
|
170
237
|
|
|
171
238
|
|
|
172
239
|
def get_model_name():
|
|
173
240
|
"""Get the appropriate model name with priority: ENV > Config > Default."""
|
|
174
|
-
config, config_manager, provider, raw_model = _resolve_model_settings()
|
|
175
|
-
model, _, _ = _compute_effective_model(
|
|
241
|
+
config, config_manager, provider, raw_model, model_from_env = _resolve_model_settings()
|
|
242
|
+
model, _, _ = _compute_effective_model(
|
|
243
|
+
config, config_manager, provider, raw_model, model_from_env
|
|
244
|
+
)
|
|
176
245
|
return model
|
|
177
246
|
|
|
178
247
|
|
|
179
248
|
def get_api_key():
|
|
180
249
|
"""Get the API key for the current provider with priority: ENV > Config."""
|
|
181
|
-
config, config_manager, provider, _ = _resolve_model_settings()
|
|
250
|
+
config, config_manager, provider, _, _ = _resolve_model_settings()
|
|
182
251
|
return _get_provider_api_key(config, config_manager, provider)
|
|
183
252
|
|
|
184
253
|
|
|
185
254
|
def get_base_url():
|
|
186
255
|
"""Get the base URL for the current provider with priority: ENV > Config."""
|
|
187
|
-
config, config_manager, provider, _ = _resolve_model_settings()
|
|
256
|
+
config, config_manager, provider, _, _ = _resolve_model_settings()
|
|
188
257
|
# Get the provider-specific base_url env var, or fall back to a generic pattern
|
|
189
258
|
base_url_env_var = PROVIDER_ENV_VARS.get(provider, {}).get(
|
|
190
259
|
"base_url", f"{provider.upper()}_BASE_URL"
|
|
@@ -199,10 +268,10 @@ def get_litellm_model_kwargs() -> dict:
|
|
|
199
268
|
Returns a dict with 'model', 'api_key', 'base_url', and retry configuration
|
|
200
269
|
that can be passed directly to LitellmModel constructor.
|
|
201
270
|
"""
|
|
202
|
-
config, config_manager, provider, raw_model = _resolve_model_settings()
|
|
271
|
+
config, config_manager, provider, raw_model, model_from_env = _resolve_model_settings()
|
|
203
272
|
|
|
204
273
|
# Get normalized model name for LiteLLM
|
|
205
|
-
model = _normalize_model_name(provider, raw_model)
|
|
274
|
+
model = _normalize_model_name(provider, raw_model, model_from_env)
|
|
206
275
|
# Strip the 'litellm/' prefix since LitellmModel adds it internally
|
|
207
276
|
if model.startswith("litellm/"):
|
|
208
277
|
model = model[len("litellm/") :]
|
|
@@ -229,20 +298,15 @@ def get_litellm_model_kwargs() -> dict:
|
|
|
229
298
|
|
|
230
299
|
def is_native_openai_provider() -> bool:
|
|
231
300
|
"""Check if the current provider should use native OpenAI client."""
|
|
232
|
-
config, config_manager, provider, _ = _resolve_model_settings()
|
|
301
|
+
config, config_manager, provider, raw_model, _ = _resolve_model_settings()
|
|
233
302
|
api_key = _get_provider_api_key(config, config_manager, provider)
|
|
234
|
-
|
|
303
|
+
|
|
304
|
+
return provider in ("openai", "custom") and api_key is not None and _is_openai_native_model(raw_model)
|
|
235
305
|
|
|
236
306
|
|
|
237
307
|
@backoff.on_exception(
|
|
238
308
|
backoff.expo,
|
|
239
|
-
|
|
240
|
-
litellm.exceptions.ServiceUnavailableError,
|
|
241
|
-
litellm.exceptions.RateLimitError,
|
|
242
|
-
litellm.exceptions.APIConnectionError,
|
|
243
|
-
litellm.exceptions.Timeout,
|
|
244
|
-
litellm.exceptions.InternalServerError,
|
|
245
|
-
),
|
|
309
|
+
_LITELLM_ERRORS,
|
|
246
310
|
max_tries=3,
|
|
247
311
|
jitter=backoff.full_jitter,
|
|
248
312
|
)
|
|
@@ -261,14 +325,16 @@ async def llm_completion(messages: list, model: Optional[str] = None) -> str:
|
|
|
261
325
|
The completion response content as string
|
|
262
326
|
"""
|
|
263
327
|
|
|
264
|
-
config, config_manager, provider, raw_model = _resolve_model_settings()
|
|
328
|
+
config, config_manager, provider, raw_model, model_from_env = _resolve_model_settings()
|
|
265
329
|
|
|
266
330
|
# Ensure provider env vars are set (for litellm to pick up)
|
|
267
331
|
_setup_provider_env_vars(config, provider)
|
|
268
332
|
|
|
269
333
|
# Get model name and API key
|
|
270
334
|
if model is None:
|
|
271
|
-
model, _, api_key = _compute_effective_model(
|
|
335
|
+
model, _, api_key = _compute_effective_model(
|
|
336
|
+
config, config_manager, provider, raw_model, model_from_env
|
|
337
|
+
)
|
|
272
338
|
else:
|
|
273
339
|
api_key = _get_provider_api_key(config, config_manager, provider)
|
|
274
340
|
|
|
@@ -281,6 +347,7 @@ async def llm_completion(messages: list, model: Optional[str] = None) -> str:
|
|
|
281
347
|
kwargs = {
|
|
282
348
|
"model": model,
|
|
283
349
|
"messages": messages,
|
|
350
|
+
"metadata": {"source": "koder"},
|
|
284
351
|
}
|
|
285
352
|
if api_key:
|
|
286
353
|
kwargs["api_key"] = api_key
|
|
@@ -297,13 +364,13 @@ def setup_openai_client():
|
|
|
297
364
|
Also configures global LiteLLM retry settings for all providers.
|
|
298
365
|
"""
|
|
299
366
|
set_tracing_disabled(True)
|
|
300
|
-
config, config_manager, provider, raw_model = _resolve_model_settings()
|
|
367
|
+
config, config_manager, provider, raw_model, model_from_env = _resolve_model_settings()
|
|
301
368
|
|
|
302
369
|
# Setup provider environment variables for LiteLLM
|
|
303
370
|
_setup_provider_env_vars(config, provider)
|
|
304
371
|
|
|
305
372
|
model, use_native, api_key = _compute_effective_model(
|
|
306
|
-
config, config_manager, provider, raw_model
|
|
373
|
+
config, config_manager, provider, raw_model, model_from_env
|
|
307
374
|
)
|
|
308
375
|
|
|
309
376
|
# Get base URL with priority: ENV > Config
|
|
@@ -18,9 +18,8 @@ You should be concise, direct, and to the point. When you run a non-trivial comm
|
|
|
18
18
|
Remember that your output will be displayed on a command line interface. Your responses can use Github-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification.
|
|
19
19
|
Output text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like run_shell or code comments as means to communicate with the user during the session.
|
|
20
20
|
If you cannot or will not help the user with something, please do not say why or what it could lead to, since this comes across as preachy and annoying. Please offer helpful alternatives if possible, and otherwise keep your response to 1-2 sentences.
|
|
21
|
-
IMPORTANT:
|
|
22
|
-
IMPORTANT: You should NOT answer with unnecessary preamble or postamble (such as
|
|
23
|
-
IMPORTANT: Keep your responses short, since they will be displayed on a command line interface. You MUST answer concisely with fewer than 4 lines (not including tool use or code generation), unless user asks for detail. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response.
|
|
21
|
+
IMPORTANT: Stay focused on the specific query or task at hand, avoiding tangential information unless critical. Prefer clarity over brevity - provide enough context for the user to understand your response, but avoid unnecessary filler or repetition.
|
|
22
|
+
IMPORTANT: You should NOT answer with unnecessary preamble or postamble (such as "Sure, I can help with that!" or summarizing what you just did), unless the user asks you to.
|
|
24
23
|
|
|
25
24
|
# Proactiveness
|
|
26
25
|
You are allowed to be proactive, but only when the user asks you to do something. You should strive to strike a balance between:
|
|
@@ -69,8 +68,6 @@ NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTAN
|
|
|
69
68
|
- When doing file search, prefer to use the task_delegate tool in order to reduce context usage.
|
|
70
69
|
- You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. When making multiple run_shell tool calls, you MUST send a single message with multiple tools calls to run the calls in parallel. For example, if you need to run "git status" and "git diff", send a single message with two tool calls to run the calls in parallel.
|
|
71
70
|
|
|
72
|
-
You MUST answer concisely with fewer than 4 lines of text (not including tool use or code generation), unless user asks for detail.
|
|
73
|
-
|
|
74
71
|
# Committing changes with git
|
|
75
72
|
When the user asks you to create a new git commit, follow these steps carefully:
|
|
76
73
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "koder"
|
|
3
|
-
version = "0.4.
|
|
3
|
+
version = "0.4.4"
|
|
4
4
|
description = "An intuitive AI coding assistant and interactive CLI tool that boosts developer productivity with intelligent automation and context-aware support."
|
|
5
5
|
authors = [{ name = "Pengfei Ni" }]
|
|
6
6
|
readme = "README.md"
|
|
@@ -16,6 +16,7 @@ keywords = [
|
|
|
16
16
|
]
|
|
17
17
|
dependencies = [
|
|
18
18
|
"openai-agents[litellm]>=0.6.1",
|
|
19
|
+
"litellm>=1.80.5",
|
|
19
20
|
"tiktoken>=0.12.0",
|
|
20
21
|
"requests>=2.32.5",
|
|
21
22
|
"beautifulsoup4>=4.14.2",
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
import yaml
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
from koder_agent.config import reset_config_manager
|
|
6
|
+
from koder_agent.config.manager import ConfigManager
|
|
7
|
+
from koder_agent.utils.client import (
|
|
8
|
+
get_litellm_model_kwargs,
|
|
9
|
+
get_model_name,
|
|
10
|
+
is_native_openai_provider,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _write_config(tmp_path, data: dict) -> None:
|
|
15
|
+
"""Write a config file under the temp HOME used for tests."""
|
|
16
|
+
config_dir = tmp_path / ".koder"
|
|
17
|
+
config_dir.mkdir(parents=True, exist_ok=True)
|
|
18
|
+
(config_dir / "config.yaml").write_text(yaml.safe_dump(data), encoding="utf-8")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@pytest.fixture(autouse=True)
|
|
22
|
+
def isolate_config(monkeypatch, tmp_path):
|
|
23
|
+
"""
|
|
24
|
+
Isolate HOME and clear relevant env vars between tests.
|
|
25
|
+
|
|
26
|
+
The client code reads ~/.koder/config.yaml via Path.home(), so we
|
|
27
|
+
point HOME to a temp directory and reset the config manager cache.
|
|
28
|
+
"""
|
|
29
|
+
# Redirect config location to temp HOME
|
|
30
|
+
config_path = Path(tmp_path) / ".koder" / "config.yaml"
|
|
31
|
+
monkeypatch.setenv("HOME", str(tmp_path))
|
|
32
|
+
monkeypatch.setattr(ConfigManager, "DEFAULT_CONFIG_PATH", config_path)
|
|
33
|
+
|
|
34
|
+
for var in [
|
|
35
|
+
"KODER_MODEL",
|
|
36
|
+
"OPENAI_API_KEY",
|
|
37
|
+
"OPENAI_BASE_URL",
|
|
38
|
+
"AZURE_API_KEY",
|
|
39
|
+
"AZURE_API_BASE",
|
|
40
|
+
"AZURE_API_VERSION",
|
|
41
|
+
"OPENROUTER_API_KEY",
|
|
42
|
+
]:
|
|
43
|
+
monkeypatch.delenv(var, raising=False)
|
|
44
|
+
reset_config_manager()
|
|
45
|
+
yield
|
|
46
|
+
reset_config_manager()
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def test_env_model_provider_overrides_config(monkeypatch, tmp_path):
|
|
50
|
+
_write_config(
|
|
51
|
+
tmp_path,
|
|
52
|
+
{"model": {"name": "gpt-4.1", "provider": "openai"}},
|
|
53
|
+
)
|
|
54
|
+
monkeypatch.setenv("KODER_MODEL", "openrouter/x-ai/grok-4.1-fast:free")
|
|
55
|
+
monkeypatch.setenv("OPENROUTER_API_KEY", "sk-test")
|
|
56
|
+
|
|
57
|
+
# Env-supplied provider should be used and normalized for LiteLLM
|
|
58
|
+
assert (
|
|
59
|
+
get_model_name()
|
|
60
|
+
== "litellm/openrouter/x-ai/grok-4.1-fast:free"
|
|
61
|
+
)
|
|
62
|
+
kwargs = get_litellm_model_kwargs()
|
|
63
|
+
assert kwargs["model"] == "openrouter/x-ai/grok-4.1-fast:free"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def test_openai_native_model_uses_raw(monkeypatch, tmp_path):
|
|
67
|
+
_write_config(
|
|
68
|
+
tmp_path,
|
|
69
|
+
{"model": {"name": "gpt-4.1", "provider": "openai"}},
|
|
70
|
+
)
|
|
71
|
+
monkeypatch.setenv("OPENAI_API_KEY", "sk-test")
|
|
72
|
+
|
|
73
|
+
assert get_model_name() == "gpt-4.1"
|
|
74
|
+
assert is_native_openai_provider()
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def test_openai_provider_non_openai_model_uses_litellm(monkeypatch, tmp_path):
|
|
78
|
+
_write_config(
|
|
79
|
+
tmp_path,
|
|
80
|
+
{"model": {"name": "x-ai/grok-4.1-fast:free", "provider": "openai"}},
|
|
81
|
+
)
|
|
82
|
+
monkeypatch.setenv("OPENAI_API_KEY", "sk-test")
|
|
83
|
+
|
|
84
|
+
model = get_model_name()
|
|
85
|
+
assert model == "litellm/openai/x-ai/grok-4.1-fast:free"
|
|
86
|
+
assert not is_native_openai_provider()
|
|
87
|
+
kwargs = get_litellm_model_kwargs()
|
|
88
|
+
assert kwargs["model"] == "openai/x-ai/grok-4.1-fast:free"
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def test_azure_provider_uses_litellm_and_base_url(monkeypatch, tmp_path):
|
|
92
|
+
_write_config(
|
|
93
|
+
tmp_path,
|
|
94
|
+
{"model": {"name": "gpt-4o-mini", "provider": "azure"}},
|
|
95
|
+
)
|
|
96
|
+
monkeypatch.setenv("AZURE_API_KEY", "azure-key")
|
|
97
|
+
monkeypatch.setenv("AZURE_API_BASE", "https://example.azure.com")
|
|
98
|
+
monkeypatch.setenv("AZURE_API_VERSION", "2025-04-01-preview")
|
|
99
|
+
|
|
100
|
+
# Azure should always go through LiteLLM path
|
|
101
|
+
assert get_model_name() == "litellm/azure/gpt-4o-mini"
|
|
102
|
+
kwargs = get_litellm_model_kwargs()
|
|
103
|
+
assert kwargs["model"] == "azure/gpt-4o-mini"
|
|
104
|
+
assert kwargs["base_url"] == "https://example.azure.com"
|
|
105
|
+
assert kwargs["api_key"] == "azure-key"
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def test_openrouter_config_path(monkeypatch, tmp_path):
|
|
109
|
+
_write_config(
|
|
110
|
+
tmp_path,
|
|
111
|
+
{"model": {"name": "anthropic/claude-3-opus", "provider": "openrouter"}},
|
|
112
|
+
)
|
|
113
|
+
monkeypatch.setenv("OPENROUTER_API_KEY", "sk-openrouter")
|
|
114
|
+
|
|
115
|
+
assert get_model_name() == "litellm/openrouter/anthropic/claude-3-opus"
|
|
116
|
+
kwargs = get_litellm_model_kwargs()
|
|
117
|
+
assert kwargs["model"] == "openrouter/anthropic/claude-3-opus"
|
|
118
|
+
assert kwargs["api_key"] == "sk-openrouter"
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def test_env_openai_model_overrides_non_openai_config(monkeypatch, tmp_path):
|
|
122
|
+
# Config says azure, but KODER_MODEL supplies an OpenAI-native model with provider prefix
|
|
123
|
+
_write_config(
|
|
124
|
+
tmp_path,
|
|
125
|
+
{"model": {"name": "gpt-4o-mini", "provider": "azure"}},
|
|
126
|
+
)
|
|
127
|
+
monkeypatch.setenv("KODER_MODEL", "openai/gpt-4o")
|
|
128
|
+
monkeypatch.setenv("OPENAI_API_KEY", "sk-test")
|
|
129
|
+
|
|
130
|
+
assert get_model_name() == "gpt-4o"
|
|
131
|
+
assert is_native_openai_provider()
|
|
@@ -1839,7 +1839,7 @@ wheels = [
|
|
|
1839
1839
|
|
|
1840
1840
|
[[package]]
|
|
1841
1841
|
name = "koder"
|
|
1842
|
-
version = "0.4.
|
|
1842
|
+
version = "0.4.3"
|
|
1843
1843
|
source = { editable = "." }
|
|
1844
1844
|
dependencies = [
|
|
1845
1845
|
{ name = "aiosqlite" },
|
|
@@ -1853,6 +1853,7 @@ dependencies = [
|
|
|
1853
1853
|
{ name = "fastapi-sso" },
|
|
1854
1854
|
{ name = "google-cloud-aiplatform" },
|
|
1855
1855
|
{ name = "httpx", extra = ["socks"] },
|
|
1856
|
+
{ name = "litellm" },
|
|
1856
1857
|
{ name = "openai" },
|
|
1857
1858
|
{ name = "openai-agents", extra = ["litellm"] },
|
|
1858
1859
|
{ name = "orjson" },
|
|
@@ -1891,6 +1892,7 @@ requires-dist = [
|
|
|
1891
1892
|
{ name = "fastapi-sso", specifier = ">=0.18.0" },
|
|
1892
1893
|
{ name = "google-cloud-aiplatform", specifier = ">=1.128.0" },
|
|
1893
1894
|
{ name = "httpx", extras = ["socks"], specifier = ">=0.28.1" },
|
|
1895
|
+
{ name = "litellm", specifier = ">=1.80.5" },
|
|
1894
1896
|
{ name = "openai", specifier = ">=2.8.1" },
|
|
1895
1897
|
{ name = "openai-agents", extras = ["litellm"], specifier = ">=0.6.1" },
|
|
1896
1898
|
{ name = "orjson", specifier = ">=3.11.4" },
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|