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.
@@ -0,0 +1,213 @@
1
+ Metadata-Version: 2.4
2
+ Name: koder
3
+ Version: 0.1.0
4
+ Summary: An intuitive AI coding assistant and interactive CLI tool that boosts developer productivity with intelligent automation and context-aware support.
5
+ Author: Pengfei Ni
6
+ License-File: LICENSE
7
+ Keywords: agent,agentic,ai,copilot,litellm,openai,vibe coding
8
+ Requires-Python: >=3.9
9
+ Requires-Dist: aiosqlite>=0.19.0
10
+ Requires-Dist: beautifulsoup4>=4.12.0
11
+ Requires-Dist: google-cloud-aiplatform>=1.105.0
12
+ Requires-Dist: httpx[socks]>=0.25.0
13
+ Requires-Dist: openai-agents[litellm]>=0.1.0
14
+ Requires-Dist: openai==1.96.1
15
+ Requires-Dist: prompt-toolkit>=3.0.51
16
+ Requires-Dist: pydantic>=2.0.0
17
+ Requires-Dist: requests>=2.31.0
18
+ Requires-Dist: rich>=13.0.0
19
+ Requires-Dist: tiktoken>=0.5.0
20
+ Description-Content-Type: text/markdown
21
+
22
+ # Koder
23
+
24
+ [![Python](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/)
25
+ [![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
26
+ [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
27
+ [![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
28
+
29
+ An intuitive AI coding assistant and interactive CLI tool that boosts developer productivity with intelligent automation and context-aware support.
30
+
31
+ ## 🚀 Why this project
32
+
33
+ Yet another vibe coding assistant that aims to provide:
34
+
35
+ - Universal AI provider support - Works with OpenAI, Claude, Gemini, and 100+ providers through intelligent auto-detection.
36
+ - Persistent context - Remembers your conversations across sessions with smart token management.
37
+ - Rich toolset - File operations, search, shell commands, and web access in one unified interface.
38
+ - Zero-config start - Just set your API key and go, with automatic model selection and streaming support.
39
+ - Session management - Organize work by project with isolated conversation histories.
40
+
41
+ ## 📋 Requirements
42
+
43
+ - Python 3.9 or higher.
44
+ - API key and optional baseURL from OpenAI, Gemini, Anthropic or other AI providers.
45
+
46
+ ## 🛠️ Installation
47
+
48
+ ### Using uv (Recommended)
49
+
50
+ ```sh
51
+ uv tool install koder
52
+ ```
53
+
54
+ ### Using pip
55
+
56
+ ```bash
57
+ pip install koder
58
+ ```
59
+
60
+ ## 🤖 AI Provider Configuration
61
+
62
+ Koder automatically detects and uses the LLM provider from environment variables.
63
+
64
+ **Model Selection**
65
+
66
+ The `KODER_MODEL` environment variable controls which model to use:
67
+
68
+ ```bash
69
+ # OpenAI models
70
+ export KODER_MODEL="gpt-4.1"
71
+
72
+ # Claude models (via LiteLLM)
73
+ export KODER_MODEL="claude-opus-4-20250514"
74
+
75
+ # Google models (via LiteLLM)
76
+ export KODER_MODEL="gemini/gemini-2.5-pro"
77
+ ```
78
+
79
+ **AI Providers:**
80
+
81
+ <details>
82
+
83
+ <summary>OpenAI</summary>
84
+
85
+ ```bash
86
+ # Required
87
+ export OPENAI_API_KEY="your-openai-api-key"
88
+
89
+ # Optional: Custom OpenAI-compatible endpoint
90
+ export OPENAI_BASE_URL="https://api.openai.com/v1" # Default
91
+
92
+ # Optional: Specify model (default: gpt-4.1)
93
+ export KODER_MODEL="gpt-4o"
94
+ ```
95
+
96
+ </details>
97
+
98
+ <details>
99
+
100
+ <summary>Gemini</summary>
101
+
102
+ ```bash
103
+ # Required
104
+ export GEMINI_API_KEY="your-openai-api-key"
105
+
106
+ # Specify model (default: gemini/gemini-2.5-pro)
107
+ export KODER_MODEL="gemini/gemini-2.5-pro"
108
+ ```
109
+
110
+ </details>
111
+
112
+ <details>
113
+
114
+ <summary>Azure OpenAI</summary>
115
+
116
+ ```bash
117
+ # Required
118
+ export AZURE_OPENAI_API_KEY="your-azure-api-key"
119
+ export AZURE_OPENAI_ENDPOINT="https://your-resource.openai.azure.com"
120
+ export KODER_MODEL="gpt-4o" # Your Azure deployment model
121
+
122
+ # Optional
123
+ export AZURE_OPENAI_DEPLOYMENT="your-deployment-name" # Defaults to KODER_MODEL
124
+ export AZURE_OPENAI_API_VERSION="2025-04-01-preview" # Default version
125
+ ```
126
+
127
+ </details>
128
+
129
+ <details>
130
+
131
+ <summary>Other AI providers (via LiteLLM)</summary>
132
+
133
+ [LiteLLM](https://docs.litellm.ai/docs/providers) supports 100+ providers including Anthropic, Google, Cohere, Hugging Face, and more:
134
+
135
+ ```bash
136
+ # Anthropic Claude
137
+ export ANTHROPIC_API_KEY="your-anthropic-key"
138
+ export KODER_MODEL="claude-opus-4-20250514"
139
+
140
+ # Google Vertex AI
141
+ export GOOGLE_APPLICATION_CREDENTIALS="your-sa-path.json"
142
+ export VERTEXAI_LOCATION="<your-region>"
143
+ export KODER_MODEL="vertex_ai/claude-sonnet-4@20250514"
144
+
145
+ # Custom OpenAI-compatible endpoints
146
+ export OPENAI_API_KEY="your-key"
147
+ export OPENAI_BASE_URL="https://your-custom-endpoint.com/v1"
148
+ export KODER_MODEL="openai/<your-model-name>"
149
+ ```
150
+
151
+ </details>
152
+
153
+
154
+
155
+ ## ⚡ Quick Start
156
+
157
+ ### Basic Usage
158
+
159
+ ```bash
160
+ # Run in interactive mode
161
+ koder
162
+
163
+ # Execute a single prompt
164
+ koder -s my-project "Help me implement a new feature"
165
+
166
+ # Use a specific session
167
+ koder --session my-project "Your prompt here"
168
+
169
+ # Enable streaming mode
170
+ koder --stream "Your prompt here"
171
+ ```
172
+
173
+
174
+
175
+ ## 🧪 Development
176
+
177
+ ### Setup Development Environment
178
+
179
+ ```bash
180
+ # Clone and setup
181
+ git clone https://github.com/feiskyer/koder.git
182
+ cd koder
183
+ uv sync
184
+
185
+ uv run koder
186
+ ```
187
+
188
+ ### Code Quality
189
+
190
+ ```bash
191
+ # Format code
192
+ black .
193
+
194
+ # Lint code
195
+ ruff check .
196
+
197
+ # Type checking
198
+ mypy .
199
+ ```
200
+
201
+ ## 🤝 Contributing
202
+
203
+ 1. Fork the repository
204
+ 2. Create a feature branch: `git checkout -b feature/your-feature`
205
+ 3. Make your changes
206
+ 4. Run formating and linting: `black . && ruff check .`
207
+ 5. Commit your changes: `git commit -am 'Add your feature'`
208
+ 6. Push to the branch: `git push origin feature/your-feature`
209
+ 7. Submit a pull request
210
+
211
+ ## 📄 License
212
+
213
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
@@ -0,0 +1,33 @@
1
+ koder_agent/__init__.py,sha256=ylgGBwmmaKL_RGOHmEQ_kTOGqWTJbbhNL9Zwjf3AJek,171
2
+ koder_agent/cli.py,sha256=N7Bfxe_k02P5S_a8-pCgQ-VTnVh8sOz-EVPv6Qsra_k,8391
3
+ koder_agent/agentic/__init__.py,sha256=gq-1V6gHnuqyoBN_XWJ0Y2J4_4fKZP9lwhwTeQLGwrg,334
4
+ koder_agent/agentic/agent.py,sha256=E8NgzUskd7giT5BY8eeDFsdazaZmQrj4E819A8DBvbg,1220
5
+ koder_agent/agentic/hooks.py,sha256=EV4m6oCp-uwGZ8QGJDJEN_hZJpCoiLhJh8LeMfNR8bU,2336
6
+ koder_agent/core/__init__.py,sha256=Ez1Yq2tcj8_RjGCXXBcKfJa8QqFiTt4-sh82Kh5-l1I,215
7
+ koder_agent/core/commands.py,sha256=d2_lv2dKS0ZyspcC6uaHaFNR6yIeP8hAMO0kz1QKUZs,9131
8
+ koder_agent/core/context.py,sha256=tCjoki4LkZ37erPONwdG1ZS0fBMdQEJq0XKWtzglhdg,5725
9
+ koder_agent/core/interactive.py,sha256=j63pKTGQ22p8626Qn58D_t-34jmIIT0D2xvEZiZsYh8,8920
10
+ koder_agent/core/scheduler.py,sha256=9YPTKDQFMCccl-AsmtyLl7kIhzavaW1Q4VsMD6uc0_o,15402
11
+ koder_agent/core/security.py,sha256=ZLvROGGrbGpnW8UzhEPmH2Q-7IFlDqKZzn3ich2QS1I,2110
12
+ koder_agent/mcp/__init__.py,sha256=FWCGMUZNV_akYU0NkaQlMAPzTWu3f2Orofioyb-Bom8,887
13
+ koder_agent/mcp/cli_handler.py,sha256=2oJoyevSv14UhLhKXdAbJF5T_zASQFVdz1U0AjBgMvo,9792
14
+ koder_agent/mcp/server_config.py,sha256=7Uexds0yPObSNnliJ2U9YqqIkW7D_Mvr3BF96G1WUNw,5092
15
+ koder_agent/mcp/server_factory.py,sha256=otrxU-aLjtZdkljqEH4gSGS__lpaucNM-EhH34f9JX4,5300
16
+ koder_agent/mcp/server_manager.py,sha256=2QPPtl6I9TpWIJmTUR9OR1zDDHJEUvP9vrPOoee65GA,5786
17
+ koder_agent/tools/__init__.py,sha256=xhdmZj_1UTc3l2OUJQvbZDT0-iy-rJ6RQa1KQ3ZQ7xg,2434
18
+ koder_agent/tools/engine.py,sha256=39eNfqsgkhqx9xJcrYZyFbosgptutuwvwdICjM4jSX4,3931
19
+ koder_agent/tools/file_ops.py,sha256=5VLfuLBFloMGPHbDDs_C8wBqdVlr43QSdjbbyR9d2I8,2975
20
+ koder_agent/tools/search_ops.py,sha256=7IjC4vAXkdBMIXLRzschanjtKi7PeJBivs0sVqqASdM,4403
21
+ koder_agent/tools/shell_ops.py,sha256=st3RM6zcEpmfTZrh-waeY_RFaDjBCPf9xqsEEJxLOT0,2514
22
+ koder_agent/tools/task_ops.py,sha256=kKCsXeebG7D5KCDnwlHY_45J3d0FmB74t42yTUs6Ioc,3111
23
+ koder_agent/tools/todo_ops.py,sha256=nRwkQa3v_cP1MW5Z13GTLZCkal8R-1PjzQPX0iGY_oQ,1952
24
+ koder_agent/tools/web_ops.py,sha256=SaOA3wDx2IqDSeoKj4TaQICenjdioF9eLwnRDhWy16U,4098
25
+ koder_agent/utils/__init__.py,sha256=AV-Nq5QqOTAYbfaMECwBF1YflGUNNEdogr3PvVbNWMA,265
26
+ koder_agent/utils/client.py,sha256=90RUgx_yZRD_hyJeCEAMH3A0h2SzOuLQ5Sb2hB_MIFw,2728
27
+ koder_agent/utils/prompts.py,sha256=dZUTazx0Gn26HrFhRwGG49VsOT5Wsym7BlgKSgiu96U,10583
28
+ koder_agent/utils/queue.py,sha256=5SkAKAYV5kOLSONTTZ5iRNBfIlRu8RiHNX4x8mfK6Y8,1852
29
+ koder-0.1.0.dist-info/METADATA,sha256=OVsoUCchXiXfTDpqWasEZaZpGf5AFSz4shblMj_shkw,5296
30
+ koder-0.1.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
31
+ koder-0.1.0.dist-info/entry_points.txt,sha256=zSrvnNNCJxbTugC0hDOEp4nBaBIuZG1csOKheYnnk2k,46
32
+ koder-0.1.0.dist-info/licenses/LICENSE,sha256=CgdY9dqqgVOJjiXs9gZSRlFU4FpJdG9vbGyPAFug8PQ,1067
33
+ koder-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ koder = koder_agent.cli:run
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Pengfei Ni
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,7 @@
1
+ """Koder Agent - An advanced AI coding assistant and interactive CLI tool."""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ from .cli import main, run
6
+
7
+ __all__ = ["main", "run", "__version__"]
@@ -0,0 +1,16 @@
1
+ """Agent definitions and hooks for Koder."""
2
+
3
+ from .agent import (
4
+ create_dev_agent,
5
+ # create_planner_agent,
6
+ get_model_name,
7
+ )
8
+ from .hooks import ToolDisplayHooks, get_display_hooks
9
+
10
+ __all__ = [
11
+ "ToolDisplayHooks",
12
+ "get_display_hooks",
13
+ # "create_planner_agent",
14
+ "create_dev_agent",
15
+ "get_model_name",
16
+ ]
@@ -0,0 +1,44 @@
1
+ """Agent definitions and hooks for Koder."""
2
+
3
+ import logging
4
+
5
+ from agents import Agent
6
+ from rich.console import Console
7
+
8
+ from ..mcp import load_mcp_servers
9
+ from ..utils.client import get_model_name
10
+ from ..utils.prompts import KODER_SYSTEM_PROMPT
11
+
12
+ console = Console()
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ # def create_planner_agent(model, tools, mcp_servers) -> Agent:
17
+ # """Create the planner agent."""
18
+ # return Agent(
19
+ # name="Planner",
20
+ # instructions=f"{KODER_SYSTEM_PROMPT}\nReturn numbered list or 'no planning needed'.",
21
+ # tools=tools,
22
+ # mcp_servers=mcp_servers,
23
+ # model=model,
24
+ # handoffs=[],
25
+ # )
26
+
27
+
28
+ async def create_dev_agent(tools) -> Agent:
29
+ """Create the main development agent with MCP servers."""
30
+ # Get the appropriate model based on environment
31
+ model = get_model_name()
32
+ mcp_servers = await load_mcp_servers()
33
+ # planner = create_planner_agent(model, tools, mcp_servers)
34
+
35
+ dev_agent = Agent(
36
+ name="Koder",
37
+ model=model,
38
+ instructions=KODER_SYSTEM_PROMPT,
39
+ tools=tools,
40
+ # handoffs=[planner],
41
+ mcp_servers=mcp_servers,
42
+ )
43
+ # planner.handoffs.append(dev_agent)
44
+ return dev_agent
@@ -0,0 +1,73 @@
1
+ """Agent definitions and hooks for Koder."""
2
+
3
+ from agents import (
4
+ Agent,
5
+ RunContextWrapper,
6
+ RunHooks,
7
+ Tool,
8
+ )
9
+ from rich.console import Console
10
+ from rich.panel import Panel
11
+
12
+ console = Console()
13
+
14
+
15
+ class ToolDisplayHooks(RunHooks):
16
+ """RunHooks implementation to display tool input/output with rich formatting."""
17
+
18
+ def __init__(self, streaming_mode: bool = False):
19
+ self.streaming_mode = streaming_mode
20
+
21
+ async def on_agent_start(self, context: RunContextWrapper, agent: Agent) -> None:
22
+ """Called before the agent is invoked. Called each time the current agent changes."""
23
+ if self.streaming_mode:
24
+ # In streaming mode, don't print to avoid Panel conflicts
25
+ return
26
+
27
+ console.print(
28
+ Panel(
29
+ f"🚀 [dark_cyan]AGENT {agent.name} START[/dark_cyan]",
30
+ title="🚀 Agent START",
31
+ border_style="dark_cyan",
32
+ )
33
+ )
34
+
35
+ async def on_tool_start(self, context: RunContextWrapper, agent: Agent, tool: Tool) -> None:
36
+ """Display tool execution start."""
37
+ if self.streaming_mode:
38
+ # In streaming mode, don't print to avoid Panel conflicts
39
+ return
40
+
41
+ console.print(
42
+ Panel(
43
+ f"\nTOOL START: {agent.name} calling '{tool.name}'\n",
44
+ title=f"🔧{agent.name}: Tool {tool.name} START",
45
+ border_style="cyan",
46
+ )
47
+ )
48
+
49
+ async def on_tool_end(
50
+ self, context: RunContextWrapper, agent: Agent, tool: Tool, result: str
51
+ ) -> None:
52
+ """Display tool execution result."""
53
+ if self.streaming_mode:
54
+ # In streaming mode, don't print to avoid Panel conflicts
55
+ return
56
+
57
+ # Show tool output
58
+ display_result = str(result)
59
+ if len(display_result) > 200:
60
+ display_result = display_result[:200] + "..."
61
+
62
+ console.print(
63
+ Panel(
64
+ f"TOOL END: {agent.name} finished '{tool.name}' → {display_result}",
65
+ title=f"🔧{agent.name}: Tool {tool.name} END",
66
+ border_style="cyan",
67
+ )
68
+ )
69
+
70
+
71
+ def get_display_hooks(streaming_mode: bool = False) -> RunHooks:
72
+ """Get the display hooks instance."""
73
+ return ToolDisplayHooks(streaming_mode=streaming_mode)
koder_agent/cli.py ADDED
@@ -0,0 +1,231 @@
1
+ """Command-line interface for Koder Agent."""
2
+
3
+ import argparse
4
+ import asyncio
5
+ import os
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from rich.console import Console
10
+ from rich.panel import Panel
11
+
12
+ from .core.commands import slash_handler
13
+ from .core.interactive import InteractivePrompt
14
+ from .core.scheduler import AgentScheduler
15
+ from .utils import setup_openai_client
16
+
17
+ console = Console()
18
+
19
+
20
+ async def load_context() -> str:
21
+ """Load context information including current directory and KODER.md."""
22
+ context_info = []
23
+
24
+ # Add current directory
25
+ current_dir = os.getcwd()
26
+ context_info.append(f"Working directory: {current_dir}")
27
+
28
+ # Check for KODER.md
29
+ koder_md_path = Path(current_dir) / "KODER.md"
30
+ if koder_md_path.exists():
31
+ try:
32
+ koder_content = koder_md_path.read_text("utf-8", errors="ignore")
33
+ context_info.append(f"KODER.md content:\n{koder_content}")
34
+ except Exception as e:
35
+ context_info.append(f"Error reading KODER.md: {e}")
36
+
37
+ return "\n\n".join(context_info)
38
+
39
+
40
+ async def main():
41
+ """Main entry point for the CLI."""
42
+ # Set up OpenAI client
43
+ try:
44
+ setup_openai_client()
45
+ except ValueError as e:
46
+ console.print(Panel(f"[red]{e}[/red]", title="❌ Error", border_style="red"))
47
+ return 1
48
+
49
+ # Parse command line arguments
50
+ parser = argparse.ArgumentParser(description="Koder - AI Coding Assistant")
51
+
52
+ # Add root-level options (from old chat command)
53
+ parser.add_argument("--session", "-s", default="default", help="Session ID for context")
54
+ parser.add_argument(
55
+ "--stream", action="store_true", help="Enable streaming mode for real-time output"
56
+ )
57
+
58
+ # Create subparsers for specific commands
59
+ subparsers = parser.add_subparsers(dest="command", help="Available commands")
60
+
61
+ # MCP management commands
62
+ mcp_parser = subparsers.add_parser("mcp", help="Manage MCP servers")
63
+ mcp_subparsers = mcp_parser.add_subparsers(dest="mcp_action", help="MCP actions")
64
+
65
+ # MCP add command
66
+ add_parser = mcp_subparsers.add_parser("add", help="Add an MCP server")
67
+ add_parser.add_argument("name", help="Server name")
68
+ add_parser.add_argument("command_or_url", help="Command for stdio or URL for SSE/HTTP")
69
+ add_parser.add_argument("args", nargs="*", help="Arguments for stdio command")
70
+ add_parser.add_argument(
71
+ "--transport", choices=["stdio", "sse", "http"], default="stdio", help="Transport type"
72
+ )
73
+ add_parser.add_argument(
74
+ "-e", "--env", action="append", help="Environment variables (KEY=VALUE)"
75
+ )
76
+ add_parser.add_argument("--header", action="append", help="HTTP headers (Key: Value)")
77
+ add_parser.add_argument("--cache-tools", action="store_true", help="Cache tools list")
78
+ add_parser.add_argument("--allow-tool", action="append", help="Allowed tools")
79
+ add_parser.add_argument("--block-tool", action="append", help="Blocked tools")
80
+
81
+ # MCP list command
82
+ mcp_subparsers.add_parser("list", help="List all MCP servers")
83
+
84
+ # MCP get command
85
+ get_parser = mcp_subparsers.add_parser("get", help="Get details for a specific server")
86
+ get_parser.add_argument("name", help="Server name")
87
+
88
+ # MCP remove command
89
+ remove_parser = mcp_subparsers.add_parser("remove", help="Remove an MCP server")
90
+ remove_parser.add_argument("name", help="Server name")
91
+
92
+ # Try to parse arguments. If it fails due to unrecognized command,
93
+ # treat everything as a prompt for backward compatibility
94
+ try:
95
+ args = parser.parse_args()
96
+ except SystemExit:
97
+ # Check if the first non-flag argument is a known command
98
+ known_commands = {"mcp"}
99
+ non_flag_args = [arg for arg in sys.argv[1:] if not arg.startswith("-")]
100
+
101
+ # If it starts with a known command, re-raise the exception (it's a real parsing error)
102
+ if non_flag_args and non_flag_args[0] in known_commands:
103
+ raise
104
+
105
+ # Otherwise, treat everything as a prompt for backward compatibility
106
+ if non_flag_args:
107
+ # Parse only the flags
108
+ flag_args = [arg for arg in sys.argv[1:] if arg.startswith("-")]
109
+ # Add flag values
110
+ i = 0
111
+ while i < len(sys.argv[1:]):
112
+ arg = sys.argv[1:][i]
113
+ if (
114
+ arg.startswith("-")
115
+ and i + 1 < len(sys.argv[1:])
116
+ and not sys.argv[1:][i + 1].startswith("-")
117
+ ):
118
+ flag_args.append(sys.argv[1:][i + 1])
119
+ i += 1
120
+ i += 1
121
+
122
+ args = parser.parse_args(flag_args)
123
+ args.command = None
124
+ args.prompt = non_flag_args
125
+ else:
126
+ raise
127
+
128
+ # Handle MCP commands
129
+ if args.command == "mcp":
130
+ from .mcp.cli_handler import handle_mcp_command
131
+
132
+ return await handle_mcp_command(args)
133
+
134
+ # Load context for chat mode
135
+ context = await load_context()
136
+ console.print(
137
+ Panel(
138
+ f"[bold cyan]🚀 Koder Started[/bold cyan]\n"
139
+ f"[dim]Working in: {os.getcwd()}[/dim]\n"
140
+ "[dim]Type 'exit' or 'quit' to stop, Ctrl+C to interrupt[/dim]",
141
+ title="Koder",
142
+ border_style="cyan",
143
+ )
144
+ )
145
+
146
+ # Create scheduler
147
+ scheduler = AgentScheduler(session_id=args.session, streaming=args.stream)
148
+
149
+ try:
150
+ # Create interactive prompt with slash commands
151
+ command_list = slash_handler.get_command_list()
152
+ commands_dict = {name: desc for name, desc in command_list}
153
+ interactive_prompt = InteractivePrompt(commands_dict)
154
+
155
+ # Handle initial prompt if provided
156
+ prompt_text = getattr(args, "prompt", None)
157
+ if prompt_text:
158
+ prompt = " ".join(prompt_text)
159
+ if context:
160
+ prompt = f"Context:\n{context}\n\nUser request: {prompt}"
161
+ await scheduler.handle(prompt)
162
+ else:
163
+ # Interactive mode
164
+ while True:
165
+ try:
166
+ user_input = await interactive_prompt.get_input()
167
+ # If we get empty input, treat it as EOF for piped input
168
+ if not user_input and not sys.stdin.isatty():
169
+ break
170
+ except (EOFError, KeyboardInterrupt):
171
+ console.print(
172
+ Panel(
173
+ "[yellow]👋 Goodbye![/yellow]",
174
+ title="👋 Farewell",
175
+ border_style="yellow",
176
+ )
177
+ )
178
+ break
179
+
180
+ if user_input.lower() in {"exit", "quit"}:
181
+ console.print(
182
+ Panel(
183
+ "[yellow]👋 Goodbye![/yellow]",
184
+ title="👋 Farewell",
185
+ border_style="yellow",
186
+ )
187
+ )
188
+ break
189
+
190
+ if user_input:
191
+ # Check if it's a slash command
192
+ if slash_handler.is_slash_command(user_input):
193
+ slash_response = await slash_handler.handle_slash_input(
194
+ user_input, scheduler
195
+ )
196
+ if slash_response:
197
+ console.print(
198
+ Panel(
199
+ f"[bold green]{slash_response}[/bold green]",
200
+ title="⚡ Command Response",
201
+ border_style="green",
202
+ )
203
+ )
204
+ else:
205
+ await scheduler.handle(user_input)
206
+ finally:
207
+ # Always cleanup MCP servers, regardless of how we exit
208
+ await scheduler.cleanup()
209
+
210
+ return 0
211
+
212
+
213
+ def run():
214
+ """Run the CLI application."""
215
+ try:
216
+ exit_code = asyncio.run(main())
217
+ exit(exit_code)
218
+ except KeyboardInterrupt:
219
+ console.print(
220
+ Panel("[yellow]👋 Interrupted![/yellow]", title="⚠️ Interruption", border_style="yellow")
221
+ )
222
+ exit(0)
223
+ except Exception as e:
224
+ console.print(
225
+ Panel(f"[red]Fatal error: {e}[/red]", title="💥 Fatal Error", border_style="red")
226
+ )
227
+ exit(1)
228
+
229
+
230
+ if __name__ == "__main__":
231
+ run()
@@ -0,0 +1,7 @@
1
+ """Core components for Koder Agent."""
2
+
3
+ from .context import ContextManager
4
+ from .scheduler import AgentScheduler
5
+ from .security import SecurityGuard
6
+
7
+ __all__ = ["ContextManager", "AgentScheduler", "SecurityGuard"]