koder 0.1.0__py3-none-any.whl
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.1.0.dist-info/METADATA +213 -0
- koder-0.1.0.dist-info/RECORD +33 -0
- koder-0.1.0.dist-info/WHEEL +4 -0
- koder-0.1.0.dist-info/entry_points.txt +2 -0
- koder-0.1.0.dist-info/licenses/LICENSE +21 -0
- koder_agent/__init__.py +7 -0
- koder_agent/agentic/__init__.py +16 -0
- koder_agent/agentic/agent.py +44 -0
- koder_agent/agentic/hooks.py +73 -0
- koder_agent/cli.py +231 -0
- koder_agent/core/__init__.py +7 -0
- koder_agent/core/commands.py +253 -0
- koder_agent/core/context.py +154 -0
- koder_agent/core/interactive.py +242 -0
- koder_agent/core/scheduler.py +349 -0
- koder_agent/core/security.py +67 -0
- koder_agent/mcp/__init__.py +36 -0
- koder_agent/mcp/cli_handler.py +292 -0
- koder_agent/mcp/server_config.py +134 -0
- koder_agent/mcp/server_factory.py +148 -0
- koder_agent/mcp/server_manager.py +141 -0
- koder_agent/tools/__init__.py +98 -0
- koder_agent/tools/engine.py +134 -0
- koder_agent/tools/file_ops.py +109 -0
- koder_agent/tools/search_ops.py +141 -0
- koder_agent/tools/shell_ops.py +92 -0
- koder_agent/tools/task_ops.py +90 -0
- koder_agent/tools/todo_ops.py +81 -0
- koder_agent/tools/web_ops.py +128 -0
- koder_agent/utils/__init__.py +7 -0
- koder_agent/utils/client.py +82 -0
- koder_agent/utils/prompts.py +97 -0
- koder_agent/utils/queue.py +59 -0
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
"""Agent scheduler for managing agent execution."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
|
|
5
|
+
from agents import (
|
|
6
|
+
AgentUpdatedStreamEvent,
|
|
7
|
+
RawResponsesStreamEvent,
|
|
8
|
+
RunConfig,
|
|
9
|
+
RunItemStreamEvent,
|
|
10
|
+
Runner,
|
|
11
|
+
ToolCallItem,
|
|
12
|
+
ToolCallOutputItem,
|
|
13
|
+
)
|
|
14
|
+
from openai._utils import is_dict
|
|
15
|
+
from openai.types.responses import ResponseFunctionToolCall
|
|
16
|
+
from openai.types.responses.response_text_delta_event import ResponseTextDeltaEvent
|
|
17
|
+
from rich.console import Console
|
|
18
|
+
from rich.live import Live
|
|
19
|
+
from rich.panel import Panel
|
|
20
|
+
from rich.text import Text
|
|
21
|
+
|
|
22
|
+
from ..agentic import create_dev_agent, get_display_hooks
|
|
23
|
+
from ..core.context import ContextManager
|
|
24
|
+
from ..tools import get_all_tools
|
|
25
|
+
|
|
26
|
+
console = Console()
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class AgentScheduler:
|
|
30
|
+
"""Scheduler for managing agent execution with context and security."""
|
|
31
|
+
|
|
32
|
+
def __init__(self, session_id: str = "default", streaming: bool = False):
|
|
33
|
+
self.semaphore = asyncio.Semaphore(10)
|
|
34
|
+
self.context_manager = ContextManager(session_id)
|
|
35
|
+
self.tools = get_all_tools()
|
|
36
|
+
self.dev_agent = None # Will be initialized in async method
|
|
37
|
+
self.streaming = streaming
|
|
38
|
+
self.hooks = get_display_hooks(streaming_mode=streaming)
|
|
39
|
+
self._agent_initialized = False
|
|
40
|
+
self._mcp_servers = [] # Track MCP servers for cleanup
|
|
41
|
+
|
|
42
|
+
async def _ensure_agent_initialized(self):
|
|
43
|
+
"""Ensure the dev agent is initialized."""
|
|
44
|
+
if not self._agent_initialized:
|
|
45
|
+
self.dev_agent = await create_dev_agent(self.tools)
|
|
46
|
+
# Track MCP servers for cleanup
|
|
47
|
+
if hasattr(self.dev_agent, "mcp_servers") and self.dev_agent.mcp_servers:
|
|
48
|
+
self._mcp_servers = self.dev_agent.mcp_servers
|
|
49
|
+
self._agent_initialized = True
|
|
50
|
+
|
|
51
|
+
async def handle(self, user_input: str) -> str:
|
|
52
|
+
"""Handle user input and execute agent."""
|
|
53
|
+
# Ensure agent is initialized with MCP servers
|
|
54
|
+
await self._ensure_agent_initialized()
|
|
55
|
+
|
|
56
|
+
if self.dev_agent is None:
|
|
57
|
+
console.print("[dim red]Agent not initialized[/dim red]")
|
|
58
|
+
return "Agent not initialized"
|
|
59
|
+
|
|
60
|
+
# Note: Input panel is now displayed in InteractivePrompt, so we skip showing it here
|
|
61
|
+
|
|
62
|
+
# Load conversation history
|
|
63
|
+
history = await self.context_manager.load()
|
|
64
|
+
|
|
65
|
+
console.print("[yellow]🤖 Agent is thinking...[/yellow]")
|
|
66
|
+
|
|
67
|
+
# Build context from history
|
|
68
|
+
context_str = ""
|
|
69
|
+
if history:
|
|
70
|
+
context_str = "Previous conversation:\n"
|
|
71
|
+
for msg in history:
|
|
72
|
+
role = msg["role"].capitalize()
|
|
73
|
+
content = msg["content"]
|
|
74
|
+
context_str += f"{role}: {content}\n"
|
|
75
|
+
context_str += "\nCurrent request:\n"
|
|
76
|
+
|
|
77
|
+
# Combine context with current user input
|
|
78
|
+
full_input = context_str + user_input if context_str else user_input
|
|
79
|
+
|
|
80
|
+
# Run the agent
|
|
81
|
+
async with self.semaphore:
|
|
82
|
+
if self.streaming:
|
|
83
|
+
response = await self._handle_streaming(full_input)
|
|
84
|
+
else:
|
|
85
|
+
result = await Runner.run(
|
|
86
|
+
self.dev_agent,
|
|
87
|
+
full_input,
|
|
88
|
+
run_config=RunConfig(),
|
|
89
|
+
hooks=self.hooks,
|
|
90
|
+
)
|
|
91
|
+
# Filter output for security
|
|
92
|
+
response = self._filter_output(result.final_output)
|
|
93
|
+
|
|
94
|
+
console.print(
|
|
95
|
+
Panel(
|
|
96
|
+
f"[dark_cyan]{response}[/dark_cyan]",
|
|
97
|
+
title="🤖 Agent Response",
|
|
98
|
+
border_style="dark_cyan",
|
|
99
|
+
)
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
# Save conversation to context
|
|
103
|
+
await self.context_manager.save(
|
|
104
|
+
history
|
|
105
|
+
+ [
|
|
106
|
+
{"role": "user", "content": user_input},
|
|
107
|
+
{"role": "assistant", "content": response},
|
|
108
|
+
]
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
return response
|
|
112
|
+
|
|
113
|
+
async def _handle_streaming(self, full_input: str) -> str:
|
|
114
|
+
"""Handle streaming execution with real-time output."""
|
|
115
|
+
# TODO: upstream issue https://github.com/openai/openai-agents-python/issues/1016
|
|
116
|
+
# TODO: upstream issue https://github.com/openai/openai-agents-python/issues/824
|
|
117
|
+
# Create initial display content
|
|
118
|
+
streaming_text = Text()
|
|
119
|
+
current_response = ""
|
|
120
|
+
# Track text content by output_index to avoid duplication
|
|
121
|
+
output_texts = {}
|
|
122
|
+
# Track non-text indicators (tool calls, status messages, etc.)
|
|
123
|
+
indicators = []
|
|
124
|
+
|
|
125
|
+
def rebuild_display():
|
|
126
|
+
"""Rebuild the complete display with indicators and text content."""
|
|
127
|
+
display_text = Text()
|
|
128
|
+
|
|
129
|
+
# Add all indicators first
|
|
130
|
+
for indicator in indicators:
|
|
131
|
+
display_text.append(indicator)
|
|
132
|
+
|
|
133
|
+
# Add text content from all outputs
|
|
134
|
+
for idx in sorted(output_texts.keys()):
|
|
135
|
+
filtered_text = self._filter_output(output_texts[idx])
|
|
136
|
+
display_text.append(filtered_text)
|
|
137
|
+
|
|
138
|
+
return display_text
|
|
139
|
+
|
|
140
|
+
# Use Rich Live to update the display in real-time
|
|
141
|
+
with Live(
|
|
142
|
+
Panel(
|
|
143
|
+
streaming_text,
|
|
144
|
+
title="🤖 Agent Response",
|
|
145
|
+
border_style="dark_cyan",
|
|
146
|
+
style="dark_cyan",
|
|
147
|
+
),
|
|
148
|
+
refresh_per_second=10,
|
|
149
|
+
console=console,
|
|
150
|
+
) as live:
|
|
151
|
+
# Run the agent in streaming mode
|
|
152
|
+
if self.dev_agent is None:
|
|
153
|
+
console.print("[dim red]Agent not initialized[/dim red]")
|
|
154
|
+
return "Agent not initialized"
|
|
155
|
+
|
|
156
|
+
result = Runner.run_streamed(
|
|
157
|
+
self.dev_agent,
|
|
158
|
+
full_input,
|
|
159
|
+
run_config=RunConfig(),
|
|
160
|
+
hooks=self.hooks,
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
try:
|
|
164
|
+
# Process streaming events
|
|
165
|
+
async for event in result.stream_events():
|
|
166
|
+
try:
|
|
167
|
+
# Handle raw response events (token-by-token streaming)
|
|
168
|
+
if isinstance(event, RawResponsesStreamEvent):
|
|
169
|
+
if isinstance(event.data, ResponseTextDeltaEvent):
|
|
170
|
+
delta_text = event.data.delta
|
|
171
|
+
output_index = event.data.output_index
|
|
172
|
+
|
|
173
|
+
if delta_text:
|
|
174
|
+
# Initialize output text for this index if not exists
|
|
175
|
+
if output_index not in output_texts:
|
|
176
|
+
output_texts[output_index] = ""
|
|
177
|
+
|
|
178
|
+
# Append delta to the specific output stream
|
|
179
|
+
output_texts[output_index] += delta_text
|
|
180
|
+
|
|
181
|
+
# Update current_response for final result
|
|
182
|
+
current_response = "".join(output_texts.values())
|
|
183
|
+
|
|
184
|
+
# Rebuild and update display
|
|
185
|
+
live.update(
|
|
186
|
+
Panel(
|
|
187
|
+
rebuild_display(),
|
|
188
|
+
title="🤖 Agent Response",
|
|
189
|
+
border_style="dark_cyan",
|
|
190
|
+
)
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
# Handle run item events (tool calls, outputs, etc.)
|
|
194
|
+
elif isinstance(event, RunItemStreamEvent):
|
|
195
|
+
if event.name == "tool_called":
|
|
196
|
+
if (
|
|
197
|
+
hasattr(event, "item")
|
|
198
|
+
and isinstance(event.item, ToolCallItem)
|
|
199
|
+
and isinstance(event.item.raw_item, ResponseFunctionToolCall)
|
|
200
|
+
):
|
|
201
|
+
tool_name = event.item.raw_item.name
|
|
202
|
+
tool_id = event.item.raw_item.call_id
|
|
203
|
+
tool_args = event.item.raw_item.arguments
|
|
204
|
+
tool_indicator = Text(
|
|
205
|
+
f"\n[🔧 Tool {tool_name} called (ID: {tool_id}): {tool_args}]\n",
|
|
206
|
+
style="dim yellow",
|
|
207
|
+
)
|
|
208
|
+
indicators.append(tool_indicator)
|
|
209
|
+
live.update(
|
|
210
|
+
Panel(
|
|
211
|
+
rebuild_display(),
|
|
212
|
+
title="🤖 Agent Response",
|
|
213
|
+
border_style="dark_cyan",
|
|
214
|
+
)
|
|
215
|
+
)
|
|
216
|
+
elif event.name == "tool_output":
|
|
217
|
+
if hasattr(event, "item") and isinstance(
|
|
218
|
+
event.item, ToolCallOutputItem
|
|
219
|
+
):
|
|
220
|
+
if (
|
|
221
|
+
is_dict(event.item.raw_item)
|
|
222
|
+
and "call_id" in event.item.raw_item
|
|
223
|
+
and "output" in event.item.raw_item
|
|
224
|
+
):
|
|
225
|
+
tool_id = event.item.raw_item.get("call_id", "unknown")
|
|
226
|
+
tool_result = event.item.raw_item.get("output", "unknown")
|
|
227
|
+
tool_result = str(tool_result)[:150]
|
|
228
|
+
tool_indicator = Text(
|
|
229
|
+
f"\n[📤 Tool {tool_id} output:\n{tool_result}]\n",
|
|
230
|
+
style="dim green",
|
|
231
|
+
)
|
|
232
|
+
indicators.append(tool_indicator)
|
|
233
|
+
live.update(
|
|
234
|
+
Panel(
|
|
235
|
+
rebuild_display(),
|
|
236
|
+
title="🤖 Agent Response",
|
|
237
|
+
border_style="dark_cyan",
|
|
238
|
+
)
|
|
239
|
+
)
|
|
240
|
+
elif event.name == "message_output_created":
|
|
241
|
+
pass
|
|
242
|
+
elif event.name == "handoff_requested":
|
|
243
|
+
handoff_indicator = Text(
|
|
244
|
+
"\n[🤝 Handoff requested]", style="dim magenta"
|
|
245
|
+
)
|
|
246
|
+
indicators.append(handoff_indicator)
|
|
247
|
+
live.update(
|
|
248
|
+
Panel(
|
|
249
|
+
rebuild_display(),
|
|
250
|
+
title="🤖 Agent Response",
|
|
251
|
+
border_style="dark_cyan",
|
|
252
|
+
)
|
|
253
|
+
)
|
|
254
|
+
elif event.name == "handoff_occured":
|
|
255
|
+
handoff_indicator = Text(
|
|
256
|
+
"\n[✋ Handoff occurred]", style="dim magenta"
|
|
257
|
+
)
|
|
258
|
+
indicators.append(handoff_indicator)
|
|
259
|
+
live.update(
|
|
260
|
+
Panel(
|
|
261
|
+
rebuild_display(),
|
|
262
|
+
title="🤖 Agent Response",
|
|
263
|
+
border_style="dark_cyan",
|
|
264
|
+
)
|
|
265
|
+
)
|
|
266
|
+
elif event.name == "reasoning_item_created":
|
|
267
|
+
reasoning_indicator = Text(
|
|
268
|
+
"\n[🧠 Reasoning step]", style="dim purple"
|
|
269
|
+
)
|
|
270
|
+
indicators.append(reasoning_indicator)
|
|
271
|
+
live.update(
|
|
272
|
+
Panel(
|
|
273
|
+
rebuild_display(),
|
|
274
|
+
title="🤖 Agent Response",
|
|
275
|
+
border_style="dark_cyan",
|
|
276
|
+
)
|
|
277
|
+
)
|
|
278
|
+
|
|
279
|
+
# Handle agent updates (handoffs, etc.)
|
|
280
|
+
elif isinstance(event, AgentUpdatedStreamEvent):
|
|
281
|
+
agent_indicator = Text(
|
|
282
|
+
f"\n[🤖 Entering Agent {event.new_agent.name}]\n", style="dim cyan"
|
|
283
|
+
)
|
|
284
|
+
indicators.append(agent_indicator)
|
|
285
|
+
live.update(
|
|
286
|
+
Panel(
|
|
287
|
+
rebuild_display(),
|
|
288
|
+
title="🤖 Agent Response",
|
|
289
|
+
border_style="dark_cyan",
|
|
290
|
+
)
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
except Exception as e:
|
|
294
|
+
# Log event processing errors but continue streaming
|
|
295
|
+
console.print(f"[dim red]Event processing error: {e}[/dim red]")
|
|
296
|
+
continue
|
|
297
|
+
except Exception as e:
|
|
298
|
+
# Handle streaming errors
|
|
299
|
+
console.print(f"[dim red]Streaming error: {e}[/dim red]")
|
|
300
|
+
|
|
301
|
+
# Get final result and filter it
|
|
302
|
+
if current_response:
|
|
303
|
+
final_response = self._filter_output(current_response)
|
|
304
|
+
else:
|
|
305
|
+
final_response = self._filter_output(result.final_output)
|
|
306
|
+
return final_response
|
|
307
|
+
|
|
308
|
+
def _get_display_input(self, user_input: str) -> str:
|
|
309
|
+
"""Get a filtered version of user input for display purposes."""
|
|
310
|
+
# Check if input contains KODER.md content
|
|
311
|
+
if "KODER.md content:" in user_input:
|
|
312
|
+
lines = user_input.split("\n")
|
|
313
|
+
filtered_lines = []
|
|
314
|
+
skip_koder_content = False
|
|
315
|
+
|
|
316
|
+
for line in lines:
|
|
317
|
+
if "KODER.md content:" in line:
|
|
318
|
+
skip_koder_content = True
|
|
319
|
+
continue
|
|
320
|
+
elif skip_koder_content and line.startswith("User request:"):
|
|
321
|
+
skip_koder_content = False
|
|
322
|
+
filtered_lines.append(line)
|
|
323
|
+
elif not skip_koder_content:
|
|
324
|
+
filtered_lines.append(line)
|
|
325
|
+
|
|
326
|
+
return "\n".join(filtered_lines)
|
|
327
|
+
|
|
328
|
+
return user_input
|
|
329
|
+
|
|
330
|
+
def _filter_output(self, text: str) -> str:
|
|
331
|
+
"""Filter sensitive information from output."""
|
|
332
|
+
import re
|
|
333
|
+
|
|
334
|
+
# Filter API keys and tokens
|
|
335
|
+
text = re.sub(r"sk-\w{10,}", "[TOKEN]", text)
|
|
336
|
+
text = re.sub(
|
|
337
|
+
r"(api[_-]?key|token|secret)[\s:=]+[\w-]{10,}", "[REDACTED]", text, flags=re.IGNORECASE
|
|
338
|
+
)
|
|
339
|
+
return text
|
|
340
|
+
|
|
341
|
+
async def cleanup(self):
|
|
342
|
+
"""Clean up resources, including MCP servers."""
|
|
343
|
+
if self._mcp_servers:
|
|
344
|
+
for server in self._mcp_servers:
|
|
345
|
+
try:
|
|
346
|
+
await server.cleanup()
|
|
347
|
+
except Exception as e:
|
|
348
|
+
console.print(f"[dim red]Error disconnecting MCP server: {e}[/dim red]")
|
|
349
|
+
self._mcp_servers.clear()
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Security guards for the Koder Agent."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Optional
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class SecurityGuard:
|
|
9
|
+
"""Security guard to validate paths and inputs."""
|
|
10
|
+
|
|
11
|
+
UI_PATTERN = re.compile(r"^[\s\S]{1,2000}$")
|
|
12
|
+
FORBIDDEN_WORDS = {"rm -rf", "shutdown", "reboot"}
|
|
13
|
+
|
|
14
|
+
@staticmethod
|
|
15
|
+
def validate_command(command: str) -> Optional[str]:
|
|
16
|
+
"""Validate a shell command for safety."""
|
|
17
|
+
command_lower = command.lower()
|
|
18
|
+
|
|
19
|
+
# Check for forbidden commands
|
|
20
|
+
for forbidden in SecurityGuard.FORBIDDEN_WORDS:
|
|
21
|
+
if forbidden in command_lower:
|
|
22
|
+
return f"Forbidden command pattern detected: {forbidden}"
|
|
23
|
+
|
|
24
|
+
# Check for dangerous patterns
|
|
25
|
+
dangerous_patterns = [
|
|
26
|
+
r">\s*/dev/", # Writing to device files
|
|
27
|
+
r"dd\s+if=", # Disk destroyer
|
|
28
|
+
r"mkfs", # Format filesystem
|
|
29
|
+
r":(){ :|:& };:", # Fork bomb
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
for pattern in dangerous_patterns:
|
|
33
|
+
if re.search(pattern, command_lower):
|
|
34
|
+
return "Dangerous command pattern detected"
|
|
35
|
+
|
|
36
|
+
return None # Valid command
|
|
37
|
+
|
|
38
|
+
@staticmethod
|
|
39
|
+
def sanitize_path(path: str) -> str:
|
|
40
|
+
"""Sanitize a path for safe usage."""
|
|
41
|
+
# Remove any null bytes
|
|
42
|
+
path = path.replace("\0", "")
|
|
43
|
+
|
|
44
|
+
# Normalize path separators
|
|
45
|
+
path = path.replace("\\", "/")
|
|
46
|
+
|
|
47
|
+
# Remove redundant separators
|
|
48
|
+
while "//" in path:
|
|
49
|
+
path = path.replace("//", "/")
|
|
50
|
+
|
|
51
|
+
# Remove trailing separators
|
|
52
|
+
path = path.rstrip("/")
|
|
53
|
+
|
|
54
|
+
return path
|
|
55
|
+
|
|
56
|
+
@staticmethod
|
|
57
|
+
def check_file_size(path: str, max_size_mb: int = 50) -> Optional[str]:
|
|
58
|
+
"""Check if file size is within limits."""
|
|
59
|
+
try:
|
|
60
|
+
path_obj = Path(path)
|
|
61
|
+
if path_obj.is_file():
|
|
62
|
+
size_mb = path_obj.stat().st_size / (1024 * 1024)
|
|
63
|
+
if size_mb > max_size_mb:
|
|
64
|
+
return f"File too large: {size_mb:.2f}MB (max: {max_size_mb}MB)"
|
|
65
|
+
return None
|
|
66
|
+
except Exception as e:
|
|
67
|
+
return f"Error checking file size: {str(e)}"
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""MCP (Model Context Protocol) support for Koder."""
|
|
2
|
+
|
|
3
|
+
from typing import List
|
|
4
|
+
|
|
5
|
+
from agents.mcp import MCPServer
|
|
6
|
+
|
|
7
|
+
from .server_config import MCPServerConfig, MCPServerType
|
|
8
|
+
from .server_factory import MCPServerFactory
|
|
9
|
+
from .server_manager import MCPServerManager
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
async def load_mcp_servers() -> List[MCPServer]:
|
|
13
|
+
"""Load and create MCP server instances from configuration."""
|
|
14
|
+
try:
|
|
15
|
+
manager = MCPServerManager()
|
|
16
|
+
configs = await manager.list_servers()
|
|
17
|
+
|
|
18
|
+
if not configs:
|
|
19
|
+
return []
|
|
20
|
+
|
|
21
|
+
# Create server instances
|
|
22
|
+
servers = await MCPServerFactory.create_servers_from_configs(configs)
|
|
23
|
+
|
|
24
|
+
return servers
|
|
25
|
+
|
|
26
|
+
except Exception as e:
|
|
27
|
+
raise RuntimeError(f"Failed to load MCP servers: {e}") from e
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"load_mcp_servers",
|
|
32
|
+
"MCPServerConfig",
|
|
33
|
+
"MCPServerType",
|
|
34
|
+
"MCPServerManager",
|
|
35
|
+
"MCPServerFactory",
|
|
36
|
+
]
|