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,92 @@
|
|
|
1
|
+
"""Shell command execution tools."""
|
|
2
|
+
|
|
3
|
+
import shlex
|
|
4
|
+
import subprocess
|
|
5
|
+
|
|
6
|
+
from agents import function_tool
|
|
7
|
+
from pydantic import BaseModel
|
|
8
|
+
|
|
9
|
+
from ..core.security import SecurityGuard
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ShellModel(BaseModel):
|
|
13
|
+
command: str
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class GitModel(BaseModel):
|
|
17
|
+
command: str
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@function_tool
|
|
21
|
+
def run_shell(command: str) -> str:
|
|
22
|
+
"""Execute a shell command with security checks."""
|
|
23
|
+
try:
|
|
24
|
+
# Security validation
|
|
25
|
+
error = SecurityGuard.validate_command(command)
|
|
26
|
+
if error:
|
|
27
|
+
return error
|
|
28
|
+
|
|
29
|
+
# Additional check for allowed commands
|
|
30
|
+
parts = shlex.split(command)
|
|
31
|
+
if not parts:
|
|
32
|
+
return "Empty command"
|
|
33
|
+
|
|
34
|
+
# Execute command with timeout
|
|
35
|
+
result = subprocess.run(
|
|
36
|
+
command,
|
|
37
|
+
shell=True,
|
|
38
|
+
text=True,
|
|
39
|
+
capture_output=True,
|
|
40
|
+
timeout=30, # 30 second timeout
|
|
41
|
+
cwd=None, # Use current working directory
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
output = result.stdout.strip()
|
|
45
|
+
if result.stderr:
|
|
46
|
+
output += f"\n[stderr]: {result.stderr.strip()}"
|
|
47
|
+
|
|
48
|
+
if result.returncode != 0:
|
|
49
|
+
output += f"\n[exit code]: {result.returncode}"
|
|
50
|
+
|
|
51
|
+
return output or "(no output)"
|
|
52
|
+
|
|
53
|
+
except subprocess.TimeoutExpired:
|
|
54
|
+
return "Command timed out after 30 seconds"
|
|
55
|
+
except subprocess.CalledProcessError as e:
|
|
56
|
+
return f"Command failed: {str(e)}"
|
|
57
|
+
except Exception as e:
|
|
58
|
+
return f"Error executing command: {str(e)}"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@function_tool
|
|
62
|
+
def git_command(command: str) -> str:
|
|
63
|
+
"""Execute a git command."""
|
|
64
|
+
try:
|
|
65
|
+
# Ensure command starts with 'git'
|
|
66
|
+
if not command.strip().startswith("git"):
|
|
67
|
+
command = f"git {command}"
|
|
68
|
+
|
|
69
|
+
# Security validation
|
|
70
|
+
error = SecurityGuard.validate_command(command)
|
|
71
|
+
if error:
|
|
72
|
+
return error
|
|
73
|
+
|
|
74
|
+
# Execute git command
|
|
75
|
+
result = subprocess.run(
|
|
76
|
+
command, shell=True, text=True, capture_output=True, timeout=30, cwd=None
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
output = result.stdout.strip()
|
|
80
|
+
if result.stderr:
|
|
81
|
+
# Git often uses stderr for informational messages
|
|
82
|
+
output += f"\n{result.stderr.strip()}"
|
|
83
|
+
|
|
84
|
+
if result.returncode != 0 and not output:
|
|
85
|
+
output = f"Git command failed with exit code {result.returncode}"
|
|
86
|
+
|
|
87
|
+
return output or "(no output)"
|
|
88
|
+
|
|
89
|
+
except subprocess.TimeoutExpired:
|
|
90
|
+
return "Git command timed out after 30 seconds"
|
|
91
|
+
except Exception as e:
|
|
92
|
+
return f"Error executing git command: {str(e)}"
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Task delegation operations."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
from typing import List, Union
|
|
5
|
+
|
|
6
|
+
from agents import Agent, RunConfig, Runner, function_tool
|
|
7
|
+
from pydantic import BaseModel
|
|
8
|
+
|
|
9
|
+
from ..mcp import load_mcp_servers
|
|
10
|
+
from ..utils import get_model_name
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class TaskModel(BaseModel):
|
|
14
|
+
description: str
|
|
15
|
+
prompt: str
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class TaskDelegateModel(BaseModel):
|
|
19
|
+
tasks: Union[List[TaskModel], TaskModel]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@function_tool
|
|
23
|
+
async def task_delegate(tasks: Union[List[TaskModel], TaskModel]) -> str:
|
|
24
|
+
"""
|
|
25
|
+
Delegate one or more tasks to specialized agents and return the aggregated results.
|
|
26
|
+
If multiple tasks are provided, they will be run in parallel.
|
|
27
|
+
"""
|
|
28
|
+
try:
|
|
29
|
+
# Normalize input to always be a list
|
|
30
|
+
if isinstance(tasks, TaskModel):
|
|
31
|
+
task_list = [tasks]
|
|
32
|
+
else:
|
|
33
|
+
task_list = tasks
|
|
34
|
+
|
|
35
|
+
mcp_servers = await load_mcp_servers()
|
|
36
|
+
|
|
37
|
+
# Import tools dynamically to avoid circular imports
|
|
38
|
+
from ..agentic import get_display_hooks
|
|
39
|
+
from . import get_all_tools
|
|
40
|
+
|
|
41
|
+
async def run_single_task(task: TaskModel) -> tuple[str, str]:
|
|
42
|
+
"""Run a single task and return (description, result)."""
|
|
43
|
+
try:
|
|
44
|
+
tools = get_all_tools()
|
|
45
|
+
# remove task_delegate tool
|
|
46
|
+
tools = [tool for tool in tools if tool.name != "task_delegate"]
|
|
47
|
+
# Create agent for the delegated task
|
|
48
|
+
delegated_agent = Agent(
|
|
49
|
+
name=f"Delegated Agent - {task.description[:30]}...",
|
|
50
|
+
model=get_model_name(),
|
|
51
|
+
instructions=f"""You are a task agent handling this task: {task.description}
|
|
52
|
+
|
|
53
|
+
You have access to tools to help complete this task effectively.
|
|
54
|
+
Be concise and focused on the specific task at hand.
|
|
55
|
+
Return your findings or results directly without unnecessary explanation.""",
|
|
56
|
+
tools=tools,
|
|
57
|
+
mcp_servers=mcp_servers,
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
# Run the delegated agent
|
|
61
|
+
result = await Runner.run(
|
|
62
|
+
delegated_agent,
|
|
63
|
+
task.prompt,
|
|
64
|
+
run_config=RunConfig(),
|
|
65
|
+
hooks=get_display_hooks(),
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
return task.description, result.final_output
|
|
69
|
+
|
|
70
|
+
except Exception as e:
|
|
71
|
+
return task.description, f"Error: {e}"
|
|
72
|
+
|
|
73
|
+
# Run all tasks in parallel
|
|
74
|
+
results = await asyncio.gather(*[run_single_task(task) for task in task_list])
|
|
75
|
+
|
|
76
|
+
# Aggregate results
|
|
77
|
+
if len(results) == 1:
|
|
78
|
+
description, result = results[0]
|
|
79
|
+
return f"Delegated task '{description}' completed successfully:\n\n{result}"
|
|
80
|
+
else:
|
|
81
|
+
# Multiple tasks - format as aggregated report
|
|
82
|
+
aggregated_result = "# Delegated Tasks Results\n\n"
|
|
83
|
+
for i, (description, result) in enumerate(results, 1):
|
|
84
|
+
aggregated_result += f"## Task {i}: {description}\n\n{result}\n\n"
|
|
85
|
+
|
|
86
|
+
return aggregated_result
|
|
87
|
+
|
|
88
|
+
except Exception as e:
|
|
89
|
+
error_msg = f"Error delegating tasks: {e}"
|
|
90
|
+
return error_msg
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""Todo list management tools."""
|
|
2
|
+
|
|
3
|
+
from typing import List
|
|
4
|
+
|
|
5
|
+
from agents import function_tool
|
|
6
|
+
from pydantic import BaseModel
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class TodoModel(BaseModel):
|
|
10
|
+
pass
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class TodoItem(BaseModel):
|
|
14
|
+
content: str
|
|
15
|
+
status: str
|
|
16
|
+
priority: str
|
|
17
|
+
id: str
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class TodoWriteModel(BaseModel):
|
|
21
|
+
todos: List[TodoItem]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
# Global todo list storage (in production, this should be persistent)
|
|
25
|
+
_todos: List[dict] = []
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@function_tool
|
|
29
|
+
def todo_read() -> str:
|
|
30
|
+
"""Read all todos from the list."""
|
|
31
|
+
global _todos
|
|
32
|
+
|
|
33
|
+
if not _todos:
|
|
34
|
+
return "No todos found. The list is empty."
|
|
35
|
+
|
|
36
|
+
result = []
|
|
37
|
+
for i, todo in enumerate(_todos, 1):
|
|
38
|
+
status = todo.get("status", "pending")
|
|
39
|
+
priority = todo.get("priority", "medium")
|
|
40
|
+
content = todo.get("content", "")
|
|
41
|
+
todo_id = todo.get("id", str(i))
|
|
42
|
+
|
|
43
|
+
# Format with emojis for better readability
|
|
44
|
+
status_emoji = {
|
|
45
|
+
"pending": "⏳",
|
|
46
|
+
"in_progress": "🔄",
|
|
47
|
+
"completed": "✅",
|
|
48
|
+
"cancelled": "❌",
|
|
49
|
+
}.get(status, "❓")
|
|
50
|
+
|
|
51
|
+
priority_emoji = {"high": "🔴", "medium": "🟡", "low": "🟢"}.get(priority, "⚪")
|
|
52
|
+
|
|
53
|
+
result.append(
|
|
54
|
+
f"{i}. {status_emoji} [{priority_emoji} {priority}] {content} (id: {todo_id})"
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
return "\n".join(result)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@function_tool
|
|
61
|
+
def todo_write(todos: List[TodoItem]) -> str:
|
|
62
|
+
"""Write/update the todo list."""
|
|
63
|
+
global _todos
|
|
64
|
+
|
|
65
|
+
# Convert TodoItem objects to dictionaries
|
|
66
|
+
_todos = [todo.model_dump() for todo in todos]
|
|
67
|
+
|
|
68
|
+
# Count items by status
|
|
69
|
+
status_counts = {}
|
|
70
|
+
for todo in _todos:
|
|
71
|
+
status = todo.get("status", "pending")
|
|
72
|
+
status_counts[status] = status_counts.get(status, 0) + 1
|
|
73
|
+
|
|
74
|
+
# Create summary
|
|
75
|
+
summary_parts = []
|
|
76
|
+
for status, count in status_counts.items():
|
|
77
|
+
summary_parts.append(f"{count} {status}")
|
|
78
|
+
|
|
79
|
+
summary = f"Updated {len(todos)} todos: " + ", ".join(summary_parts)
|
|
80
|
+
|
|
81
|
+
return summary
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""Web-related operation tools."""
|
|
2
|
+
|
|
3
|
+
from urllib.parse import urlparse
|
|
4
|
+
|
|
5
|
+
import requests
|
|
6
|
+
from agents import function_tool
|
|
7
|
+
from bs4 import BeautifulSoup
|
|
8
|
+
from pydantic import BaseModel
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class SearchModel(BaseModel):
|
|
12
|
+
query: str
|
|
13
|
+
max_results: int = 3
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class WebFetchModel(BaseModel):
|
|
17
|
+
url: str
|
|
18
|
+
prompt: str
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@function_tool
|
|
22
|
+
def web_search(query: str, max_results: int = 3) -> str:
|
|
23
|
+
"""Search the web using DuckDuckGo."""
|
|
24
|
+
try:
|
|
25
|
+
# Validate query
|
|
26
|
+
if not query or len(query) > 200:
|
|
27
|
+
return "Invalid query: must be between 1 and 200 characters"
|
|
28
|
+
|
|
29
|
+
max_results = min(max_results, 10) # Cap at 10 results
|
|
30
|
+
|
|
31
|
+
response = requests.get(
|
|
32
|
+
"https://duckduckgo.com/html/",
|
|
33
|
+
params={"q": query},
|
|
34
|
+
timeout=10,
|
|
35
|
+
headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"},
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
if response.status_code != 200:
|
|
39
|
+
return f"Search failed with status code: {response.status_code}"
|
|
40
|
+
|
|
41
|
+
soup = BeautifulSoup(response.text, "html.parser")
|
|
42
|
+
|
|
43
|
+
results = []
|
|
44
|
+
for result in soup.select(".result")[:max_results]:
|
|
45
|
+
title_elem = result.select_one(".result__title")
|
|
46
|
+
snippet_elem = result.select_one(".result__snippet")
|
|
47
|
+
link_elem = result.select_one(".result__url")
|
|
48
|
+
|
|
49
|
+
if title_elem and snippet_elem:
|
|
50
|
+
title = title_elem.get_text(strip=True)
|
|
51
|
+
snippet = snippet_elem.get_text(" ", strip=True)
|
|
52
|
+
link = link_elem.get_text(strip=True) if link_elem else ""
|
|
53
|
+
|
|
54
|
+
results.append(f"**{title}**\n{snippet}\n{link}")
|
|
55
|
+
|
|
56
|
+
return "\n\n".join(results) if results else "No results found"
|
|
57
|
+
|
|
58
|
+
except requests.Timeout:
|
|
59
|
+
return "Search request timed out"
|
|
60
|
+
except requests.RequestException as e:
|
|
61
|
+
return f"Search request failed: {str(e)}"
|
|
62
|
+
except Exception as e:
|
|
63
|
+
return f"Search error: {str(e)}"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@function_tool
|
|
67
|
+
def web_fetch(url: str, prompt: str) -> str:
|
|
68
|
+
"""Fetch content from a URL and process with a prompt."""
|
|
69
|
+
try:
|
|
70
|
+
# Validate URL
|
|
71
|
+
parsed = urlparse(url)
|
|
72
|
+
if not parsed.scheme or not parsed.netloc:
|
|
73
|
+
return "Invalid URL format"
|
|
74
|
+
|
|
75
|
+
if parsed.scheme not in ["http", "https"]:
|
|
76
|
+
return "Only HTTP/HTTPS URLs are supported"
|
|
77
|
+
|
|
78
|
+
# Fetch content
|
|
79
|
+
response = requests.get(
|
|
80
|
+
url,
|
|
81
|
+
timeout=15,
|
|
82
|
+
headers={"User-Agent": "Mozilla/5.0 (compatible; KoderAgent/1.0)"},
|
|
83
|
+
allow_redirects=True,
|
|
84
|
+
verify=True,
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
if response.status_code != 200:
|
|
88
|
+
return f"Failed to fetch URL: HTTP {response.status_code}"
|
|
89
|
+
|
|
90
|
+
# Limit content size (10MB)
|
|
91
|
+
if len(response.content) > 10 * 1024 * 1024:
|
|
92
|
+
return "Content too large (>10MB)"
|
|
93
|
+
|
|
94
|
+
# Parse HTML content
|
|
95
|
+
content_type = response.headers.get("content-type", "").lower()
|
|
96
|
+
if "html" in content_type:
|
|
97
|
+
soup = BeautifulSoup(response.text, "html.parser")
|
|
98
|
+
|
|
99
|
+
# Remove script and style elements
|
|
100
|
+
for script in soup(["script", "style"]):
|
|
101
|
+
script.decompose()
|
|
102
|
+
|
|
103
|
+
# Extract text
|
|
104
|
+
text = soup.get_text(separator="\n", strip=True)
|
|
105
|
+
|
|
106
|
+
# Limit text length
|
|
107
|
+
if len(text) > 50000:
|
|
108
|
+
text = text[:50000] + "\n... (truncated)"
|
|
109
|
+
else:
|
|
110
|
+
# For non-HTML content, use raw text
|
|
111
|
+
text = response.text
|
|
112
|
+
if len(text) > 50000:
|
|
113
|
+
text = text[:50000] + "\n... (truncated)"
|
|
114
|
+
|
|
115
|
+
# Simple prompt processing (in real implementation, this would use an AI model)
|
|
116
|
+
result = f"URL: {url}\n\n"
|
|
117
|
+
result += f"Content Type: {content_type}\n\n"
|
|
118
|
+
result += f"Prompt: {prompt}\n\n"
|
|
119
|
+
result += f"Content Preview:\n{text[:1000]}..."
|
|
120
|
+
|
|
121
|
+
return result
|
|
122
|
+
|
|
123
|
+
except requests.Timeout:
|
|
124
|
+
return "Request timed out"
|
|
125
|
+
except requests.RequestException as e:
|
|
126
|
+
return f"Request failed: {str(e)}"
|
|
127
|
+
except Exception as e:
|
|
128
|
+
return f"Error fetching content: {str(e)}"
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""Utilities for Koder Agent."""
|
|
2
|
+
|
|
3
|
+
from .client import get_model_name, setup_openai_client
|
|
4
|
+
from .prompts import KODER_SYSTEM_PROMPT
|
|
5
|
+
from .queue import AsyncMessageQueue
|
|
6
|
+
|
|
7
|
+
__all__ = ["AsyncMessageQueue", "KODER_SYSTEM_PROMPT", "get_model_name", "setup_openai_client"]
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
from agents import (
|
|
4
|
+
set_default_openai_client,
|
|
5
|
+
set_tracing_disabled,
|
|
6
|
+
)
|
|
7
|
+
from openai import AsyncAzureOpenAI, AsyncOpenAI
|
|
8
|
+
from rich.console import Console
|
|
9
|
+
from rich.panel import Panel
|
|
10
|
+
|
|
11
|
+
console = Console()
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def get_model_name():
|
|
15
|
+
"""Get the appropriate model name based on the configured client type."""
|
|
16
|
+
model = os.environ.get("KODER_MODEL", "gpt-4.1")
|
|
17
|
+
# 1. OpenAI native
|
|
18
|
+
if os.environ.get("OPENAI_API_KEY"):
|
|
19
|
+
return model
|
|
20
|
+
|
|
21
|
+
# 2. Azure OpenAI - use deployment name
|
|
22
|
+
azure_vars = ["AZURE_OPENAI_API_KEY", "AZURE_OPENAI_ENDPOINT"]
|
|
23
|
+
if all(os.environ.get(var) for var in azure_vars):
|
|
24
|
+
return os.environ.get("AZURE_OPENAI_DEPLOYMENT", model)
|
|
25
|
+
|
|
26
|
+
# 3. LiteLLM - use litellm format like "litellm/gemini/gemini-2.5-pro"
|
|
27
|
+
if model == "gpt-4.1":
|
|
28
|
+
model = "gemini/gemini-2.5-pro"
|
|
29
|
+
if not model.startswith("litellm/"):
|
|
30
|
+
model = f"litellm/{model}"
|
|
31
|
+
return model
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def setup_openai_client():
|
|
35
|
+
"""Set up the OpenAI client with priority: OpenAI native > Azure > LiteLLM."""
|
|
36
|
+
set_tracing_disabled(True)
|
|
37
|
+
model = get_model_name()
|
|
38
|
+
# 1. Try OpenAI native integration first
|
|
39
|
+
if os.environ.get("OPENAI_API_KEY"):
|
|
40
|
+
client = AsyncOpenAI(
|
|
41
|
+
api_key=os.environ["OPENAI_API_KEY"],
|
|
42
|
+
base_url=os.environ.get("OPENAI_BASE_URL"), # Optional custom base URL
|
|
43
|
+
)
|
|
44
|
+
set_default_openai_client(client)
|
|
45
|
+
console.print(
|
|
46
|
+
Panel(
|
|
47
|
+
f"[green]✅ Using OpenAI {model}[/green]",
|
|
48
|
+
title="🔧 Model Configuration",
|
|
49
|
+
border_style="green",
|
|
50
|
+
)
|
|
51
|
+
)
|
|
52
|
+
return client
|
|
53
|
+
|
|
54
|
+
# 2. Try Azure OpenAI integration
|
|
55
|
+
azure_vars = ["AZURE_OPENAI_API_KEY", "AZURE_OPENAI_ENDPOINT"]
|
|
56
|
+
if all(os.environ.get(var) for var in azure_vars):
|
|
57
|
+
client = AsyncAzureOpenAI(
|
|
58
|
+
api_key=os.environ["AZURE_OPENAI_API_KEY"],
|
|
59
|
+
azure_deployment=os.environ.get("AZURE_OPENAI_DEPLOYMENT", model),
|
|
60
|
+
azure_endpoint=os.environ["AZURE_OPENAI_ENDPOINT"],
|
|
61
|
+
api_version=os.environ.get("AZURE_OPENAI_API_VERSION", "2025-04-01-preview"),
|
|
62
|
+
)
|
|
63
|
+
set_default_openai_client(client)
|
|
64
|
+
console.print(
|
|
65
|
+
Panel(
|
|
66
|
+
f"[green]✅ Using Azure OpenAI {model}[/green]",
|
|
67
|
+
title="🔧 Model Configuration",
|
|
68
|
+
border_style="green",
|
|
69
|
+
)
|
|
70
|
+
)
|
|
71
|
+
return client
|
|
72
|
+
|
|
73
|
+
# 3. Fall back to LiteLLM integration
|
|
74
|
+
# LiteLLM models use format: "litellm/provider/model-name"
|
|
75
|
+
console.print(
|
|
76
|
+
Panel(
|
|
77
|
+
f"[green]✅ Using LiteLLM {model}[/green]",
|
|
78
|
+
title="🔧 Model Configuration",
|
|
79
|
+
border_style="green",
|
|
80
|
+
)
|
|
81
|
+
)
|
|
82
|
+
return None
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""System prompts for Koder Agent."""
|
|
2
|
+
|
|
3
|
+
KODER_SYSTEM_PROMPT = """You are Koder, an advanced AI coding assistant and interactive CLI tool.
|
|
4
|
+
|
|
5
|
+
You are an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
|
|
6
|
+
|
|
7
|
+
IMPORTANT: Assist with defensive security tasks only. Refuse to create, modify, or improve code that may be used maliciously. Allow security analysis, detection rules, vulnerability explanations, defensive tools, and security documentation.
|
|
8
|
+
IMPORTANT: You must NEVER generate or guess URLs for the user unless you are confident that the URLs are for helping the user with programming. You may use URLs provided by the user in their messages or local files.
|
|
9
|
+
|
|
10
|
+
If the user asks for help or wants to give feedback inform them of the following:
|
|
11
|
+
- /help: Get help with using Koder
|
|
12
|
+
- To give feedback, users can create issues or contribute to the project
|
|
13
|
+
|
|
14
|
+
When the user directly asks about Koder (eg 'can Koder do...', 'does Koder have...') or asks in second person (eg 'are you able...', 'can you do...'), provide information about your capabilities as an AI coding assistant.
|
|
15
|
+
|
|
16
|
+
# Tone and style
|
|
17
|
+
You should be concise, direct, and to the point. When you run a non-trivial command, you should explain what the command does and why you are running it, to make sure the user understands what you are doing (this is especially important when you are running a command that will make changes to the user's system).
|
|
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
|
+
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
|
+
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: You should minimize output tokens as much as possible while maintaining helpfulness, quality, and accuracy. Only address the specific query or task at hand, avoiding tangential information unless absolutely critical for completing the request. If you can answer in 1-3 sentences or a short paragraph, please do.
|
|
22
|
+
IMPORTANT: You should NOT answer with unnecessary preamble or postamble (such as explaining your code or summarizing your action), unless the user asks you to.
|
|
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.
|
|
24
|
+
|
|
25
|
+
# Proactiveness
|
|
26
|
+
You are allowed to be proactive, but only when the user asks you to do something. You should strive to strike a balance between:
|
|
27
|
+
1. Doing the right thing when asked, including taking actions and follow-up actions
|
|
28
|
+
2. Not surprising the user with actions you take without asking
|
|
29
|
+
For example, if the user asks you how to approach something, you should do your best to answer their question first, and not immediately jump into taking actions.
|
|
30
|
+
3. Do not add additional code explanation summary unless requested by the user. After working on a file, just stop, rather than providing an explanation of what you did.
|
|
31
|
+
|
|
32
|
+
# Following conventions
|
|
33
|
+
When making changes to files, first understand the file's code conventions. Mimic code style, use existing libraries and utilities, and follow existing patterns.
|
|
34
|
+
- NEVER assume that a given library is available, even if it is well known. Whenever you write code that uses a library or framework, first check that this codebase already uses the given library. For example, you might look at neighboring files, or check the package.json (or cargo.toml, and so on depending on the language).
|
|
35
|
+
- When you create a new component, first look at existing components to see how they're written; then consider framework choice, naming conventions, typing, and other conventions.
|
|
36
|
+
- When you edit a piece of code, first look at the code's surrounding context (especially its imports) to understand the code's choice of frameworks and libraries. Then consider how to make the given change in a way that is most idiomatic.
|
|
37
|
+
- Always follow security best practices. Never introduce code that exposes or logs secrets and keys. Never commit secrets or keys to the repository.
|
|
38
|
+
|
|
39
|
+
# Code style
|
|
40
|
+
- IMPORTANT: DO NOT ADD ***ANY*** COMMENTS unless asked
|
|
41
|
+
|
|
42
|
+
# Tool availability
|
|
43
|
+
Available tools: read_file, write_file, append_file, run_shell, web_search, glob_search, grep_search, list_directory, todo_read, todo_write, web_fetch, task_delegate, git_command
|
|
44
|
+
|
|
45
|
+
# Task Management
|
|
46
|
+
Use the todo_read and todo_write tools proactively to plan and track tasks. Use these tools VERY frequently to ensure that you are tracking your tasks and giving the user visibility into your progress.
|
|
47
|
+
These tools are also EXTREMELY helpful for planning tasks, and for breaking down larger complex tasks into smaller steps. If you do not use this tool when planning, you may forget to do important tasks - and that is unacceptable.
|
|
48
|
+
|
|
49
|
+
It is critical that you mark todos as completed as soon as you are done with a task. Do not batch up multiple tasks before marking them as completed.
|
|
50
|
+
|
|
51
|
+
# Doing tasks
|
|
52
|
+
The user will primarily request you perform software engineering tasks. This includes solving bugs, adding new functionality, refactoring code, explaining code, and more. For these tasks the following steps are recommended:
|
|
53
|
+
- Use the todo_write tool to plan the task if required
|
|
54
|
+
- Use the available search tools to understand the codebase and the user's query. You are encouraged to use the search tools extensively both in parallel and sequentially.
|
|
55
|
+
- Implement the solution using all tools available to you
|
|
56
|
+
- Verify the solution if possible with tests. NEVER assume specific test framework or test script. Check the README or search codebase to determine the testing approach.
|
|
57
|
+
- VERY IMPORTANT: When you have completed a task, you MUST run the lint and typecheck commands (eg. npm run lint, npm run typecheck, ruff, etc.) with run_shell if they were provided to you to ensure your code is correct. If you are unable to find the correct command, ask the user for the command to run and if they supply it, proactively suggest writing it to KODER.md so that you will know to run it next time.
|
|
58
|
+
NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.
|
|
59
|
+
|
|
60
|
+
# Tool usage policy
|
|
61
|
+
- When doing file search, prefer to use the task_delegate tool in order to reduce context usage.
|
|
62
|
+
- 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.
|
|
63
|
+
|
|
64
|
+
You MUST answer concisely with fewer than 4 lines of text (not including tool use or code generation), unless user asks for detail.
|
|
65
|
+
|
|
66
|
+
# Committing changes with git
|
|
67
|
+
When the user asks you to create a new git commit, follow these steps carefully:
|
|
68
|
+
|
|
69
|
+
1. 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. ALWAYS run the following git commands in parallel, each using the git_command tool:
|
|
70
|
+
- Run a git status command to see all untracked files.
|
|
71
|
+
- Run a git diff command to see both staged and unstaged changes that will be committed.
|
|
72
|
+
- Run a git log command to see recent commit messages, so that you can follow this repository's commit message style.
|
|
73
|
+
2. Analyze all staged changes (both previously staged and newly added) and draft a commit message:
|
|
74
|
+
- Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.). Ensure the message accurately reflects the changes and their purpose (i.e. "add" means a wholly new feature, "update" means an enhancement to an existing feature, "fix" means a bug fix, etc.).
|
|
75
|
+
- Check for any sensitive information that shouldn't be committed
|
|
76
|
+
- Draft a concise (1-2 sentences) commit message that focuses on the "why" rather than the "what"
|
|
77
|
+
- Ensure it accurately reflects the changes and their purpose
|
|
78
|
+
3. 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. ALWAYS run the following commands in parallel:
|
|
79
|
+
- Add relevant untracked files to the staging area using git_command.
|
|
80
|
+
- Create the commit with a message ending with:
|
|
81
|
+
🤖 Generated with [Koder](https://github.com/your-repo/koder)
|
|
82
|
+
|
|
83
|
+
Co-Authored-By: Koder <noreply@koder.ai>
|
|
84
|
+
- Run git status to make sure the commit succeeded.
|
|
85
|
+
4. If the commit fails due to pre-commit hook changes, retry the commit ONCE to include these automated changes. If it fails again, it usually means a pre-commit hook is preventing the commit. If the commit succeeds but you notice that files were modified by the pre-commit hook, you MUST amend your commit to include them.
|
|
86
|
+
|
|
87
|
+
Important notes:
|
|
88
|
+
- NEVER update the git config
|
|
89
|
+
- NEVER run additional commands to read or explore code, besides git commands
|
|
90
|
+
- NEVER use the todo_write or task_delegate tools
|
|
91
|
+
- DO NOT push to the remote repository unless the user explicitly asks you to do so
|
|
92
|
+
- IMPORTANT: Never use git commands with the -i flag (like git rebase -i or git add -i) since they require interactive input which is not supported.
|
|
93
|
+
- If there are no changes to commit (i.e., no untracked files and no modifications), do not create an empty commit
|
|
94
|
+
|
|
95
|
+
# Code References
|
|
96
|
+
When referencing specific functions or pieces of code include the pattern `file_path:line_number` to allow the user to easily navigate to the source code location.
|
|
97
|
+
"""
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""Async message queue for inter-component communication."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
from collections import deque
|
|
5
|
+
from typing import Any, Deque, Optional
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class AsyncMessageQueue:
|
|
9
|
+
"""Async message queue for managing communication between components."""
|
|
10
|
+
|
|
11
|
+
def __init__(self, maxsize: int = 100):
|
|
12
|
+
self.queue: Deque[Any] = deque(maxlen=maxsize)
|
|
13
|
+
self.event = asyncio.Event()
|
|
14
|
+
self.lock = asyncio.Lock()
|
|
15
|
+
|
|
16
|
+
async def put(self, item: Any) -> None:
|
|
17
|
+
"""Put an item in the queue."""
|
|
18
|
+
async with self.lock:
|
|
19
|
+
self.queue.append(item)
|
|
20
|
+
self.event.set()
|
|
21
|
+
|
|
22
|
+
async def get(self) -> Any:
|
|
23
|
+
"""Get an item from the queue, waiting if necessary."""
|
|
24
|
+
while True:
|
|
25
|
+
async with self.lock:
|
|
26
|
+
if self.queue:
|
|
27
|
+
item = self.queue.popleft()
|
|
28
|
+
if not self.queue:
|
|
29
|
+
self.event.clear()
|
|
30
|
+
return item
|
|
31
|
+
await self.event.wait()
|
|
32
|
+
|
|
33
|
+
async def get_nowait(self) -> Optional[Any]:
|
|
34
|
+
"""Get an item from the queue without waiting."""
|
|
35
|
+
async with self.lock:
|
|
36
|
+
if self.queue:
|
|
37
|
+
item = self.queue.popleft()
|
|
38
|
+
if not self.queue:
|
|
39
|
+
self.event.clear()
|
|
40
|
+
return item
|
|
41
|
+
return None
|
|
42
|
+
|
|
43
|
+
def qsize(self) -> int:
|
|
44
|
+
"""Return the approximate size of the queue."""
|
|
45
|
+
return len(self.queue)
|
|
46
|
+
|
|
47
|
+
def empty(self) -> bool:
|
|
48
|
+
"""Return True if the queue is empty."""
|
|
49
|
+
return len(self.queue) == 0
|
|
50
|
+
|
|
51
|
+
def full(self) -> bool:
|
|
52
|
+
"""Return True if the queue is full."""
|
|
53
|
+
return len(self.queue) == self.queue.maxlen
|
|
54
|
+
|
|
55
|
+
async def clear(self) -> None:
|
|
56
|
+
"""Clear all items from the queue."""
|
|
57
|
+
async with self.lock:
|
|
58
|
+
self.queue.clear()
|
|
59
|
+
self.event.clear()
|