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,253 @@
|
|
|
1
|
+
"""Slash command system for Koder CLI."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Dict, List, Optional, Tuple
|
|
6
|
+
|
|
7
|
+
from rich.console import Console
|
|
8
|
+
from rich.panel import Panel
|
|
9
|
+
from rich.table import Table
|
|
10
|
+
|
|
11
|
+
from ..tools import get_all_tools
|
|
12
|
+
from ..utils.client import get_model_name
|
|
13
|
+
|
|
14
|
+
console = Console()
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class SlashCommand:
|
|
18
|
+
"""Base class for slash commands."""
|
|
19
|
+
|
|
20
|
+
def __init__(self, name: str, description: str):
|
|
21
|
+
self.name = name
|
|
22
|
+
self.description = description
|
|
23
|
+
|
|
24
|
+
async def execute(self, scheduler, *_args) -> str:
|
|
25
|
+
"""Execute the command."""
|
|
26
|
+
raise NotImplementedError
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class InitCommand(SlashCommand):
|
|
30
|
+
"""Initialize project by reading codebase and generating KODER.md."""
|
|
31
|
+
|
|
32
|
+
def __init__(self):
|
|
33
|
+
super().__init__("init", "Read through the project and generate KODER.md")
|
|
34
|
+
|
|
35
|
+
async def execute(self, scheduler, *_args) -> str:
|
|
36
|
+
"""Execute the /init command."""
|
|
37
|
+
koder_md_path = Path(os.getcwd()) / "KODER.md"
|
|
38
|
+
if koder_md_path.exists():
|
|
39
|
+
console.print("[yellow]⚠️ KODER.md already exists.[/yellow]")
|
|
40
|
+
return "⚠️ KODER.md already exists."
|
|
41
|
+
|
|
42
|
+
# Use the agent to analyze the project and generate KODER.md
|
|
43
|
+
prompt = """Please analyze this codebase and create a KODER.md file containing:
|
|
44
|
+
1. Build/lint/test commands - especially for running a single test
|
|
45
|
+
2. Code style guidelines including imports, formatting, types, naming conventions, error handling, etc.
|
|
46
|
+
|
|
47
|
+
Usage notes:
|
|
48
|
+
- The file you create will be given to agentic coding agents (such as yourself) that operate in this repository. Make it about 20 lines long.\
|
|
49
|
+
- If there's already a KODER.md, improve it.\
|
|
50
|
+
- If there are Cursor rules (in .cursor/rules/ or .cursorrules) or Copilot rules (in .github/copilot-instructions.md), make sure to include them.\
|
|
51
|
+
- Be sure to prefix the file with the following text:
|
|
52
|
+
|
|
53
|
+
# KODER.md
|
|
54
|
+
|
|
55
|
+
This file provides guidance to Koder when working with code in this repository.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
await scheduler.handle(prompt)
|
|
59
|
+
return "✅ KODER.md generated."
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class ClearCommand(SlashCommand):
|
|
63
|
+
"""Clear the current session context."""
|
|
64
|
+
|
|
65
|
+
def __init__(self):
|
|
66
|
+
super().__init__("clear", "Start a new session with clean context")
|
|
67
|
+
|
|
68
|
+
async def execute(self, scheduler, *_args) -> str:
|
|
69
|
+
"""Execute the /clear command."""
|
|
70
|
+
await scheduler.context_manager.clear()
|
|
71
|
+
return "🧹 Context Cleared"
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class StatusCommand(SlashCommand):
|
|
75
|
+
"""Show current model and configuration status."""
|
|
76
|
+
|
|
77
|
+
def __init__(self):
|
|
78
|
+
super().__init__("status", "Show model and configuration details")
|
|
79
|
+
|
|
80
|
+
async def execute(self, scheduler, *_args) -> str:
|
|
81
|
+
"""Execute the /status command."""
|
|
82
|
+
# Get current model
|
|
83
|
+
model = get_model_name()
|
|
84
|
+
|
|
85
|
+
# Get session info
|
|
86
|
+
session_id = scheduler.context_manager.session_id
|
|
87
|
+
streaming = scheduler.streaming
|
|
88
|
+
|
|
89
|
+
# Get available sessions
|
|
90
|
+
sessions = await scheduler.context_manager.list_sessions()
|
|
91
|
+
|
|
92
|
+
# Get tools count
|
|
93
|
+
tools = get_all_tools()
|
|
94
|
+
tool_count = len(tools)
|
|
95
|
+
|
|
96
|
+
# Create status table
|
|
97
|
+
table = Table(title="🔧 Koder Status", show_header=True, header_style="bold cyan")
|
|
98
|
+
table.add_column("Setting", style="cyan", width=20)
|
|
99
|
+
table.add_column("Value", style="green")
|
|
100
|
+
|
|
101
|
+
table.add_row("Model", model)
|
|
102
|
+
table.add_row("Current Session", session_id)
|
|
103
|
+
table.add_row("Streaming Mode", "✅ Enabled" if streaming else "❌ Disabled")
|
|
104
|
+
table.add_row("Available Tools", str(tool_count))
|
|
105
|
+
table.add_row("Total Sessions", str(len(sessions)))
|
|
106
|
+
table.add_row("Working Directory", os.getcwd())
|
|
107
|
+
|
|
108
|
+
# Show environment variables
|
|
109
|
+
env_vars = {
|
|
110
|
+
"OPENAI_API_KEY": "✅ Set" if os.environ.get("OPENAI_API_KEY") else "❌ Not set",
|
|
111
|
+
"AZURE_OPENAI_API_KEY": (
|
|
112
|
+
"✅ Set" if os.environ.get("AZURE_OPENAI_API_KEY") else "❌ Not set"
|
|
113
|
+
),
|
|
114
|
+
"KODER_MODEL": os.environ.get("KODER_MODEL", "Not set (using default)"),
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
table.add_section()
|
|
118
|
+
table.add_row("[bold]Environment[/bold]", "[bold]Status[/bold]")
|
|
119
|
+
for key, value in env_vars.items():
|
|
120
|
+
table.add_row(key, value)
|
|
121
|
+
|
|
122
|
+
if sessions:
|
|
123
|
+
table.add_section()
|
|
124
|
+
table.add_row("[bold]Available Sessions[/bold]", "[bold]ID[/bold]")
|
|
125
|
+
for session in sessions[:5]: # Show max 5 sessions
|
|
126
|
+
marker = "👉 " if session == session_id else " "
|
|
127
|
+
table.add_row("", f"{marker}{session}")
|
|
128
|
+
if len(sessions) > 5:
|
|
129
|
+
table.add_row("", f"... and {len(sessions) - 5} more")
|
|
130
|
+
|
|
131
|
+
console.print(table)
|
|
132
|
+
return "Status information displayed above."
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class McpCommand(SlashCommand):
|
|
136
|
+
"""Show MCP servers configuration."""
|
|
137
|
+
|
|
138
|
+
def __init__(self):
|
|
139
|
+
super().__init__("mcp", "Show configured MCP servers")
|
|
140
|
+
|
|
141
|
+
async def execute(self, scheduler, *_args) -> str:
|
|
142
|
+
"""Execute the /mcp command."""
|
|
143
|
+
from ..mcp.server_manager import MCPServerManager
|
|
144
|
+
|
|
145
|
+
try:
|
|
146
|
+
manager = MCPServerManager()
|
|
147
|
+
servers = await manager.list_servers()
|
|
148
|
+
|
|
149
|
+
if not servers:
|
|
150
|
+
return "No MCP servers configured. Use 'koder mcp add' to add servers."
|
|
151
|
+
|
|
152
|
+
# Create simple table for display
|
|
153
|
+
table = Table(title="🔧 MCP Servers", show_header=True, header_style="bold cyan")
|
|
154
|
+
table.add_column("Name", style="cyan", width=20)
|
|
155
|
+
table.add_column("Type", style="green", width=10)
|
|
156
|
+
table.add_column("Configuration", style="white")
|
|
157
|
+
|
|
158
|
+
for server in servers:
|
|
159
|
+
# Format configuration
|
|
160
|
+
if server.transport_type.value == "stdio":
|
|
161
|
+
config_str = f"{server.command} {' '.join(server.args or [])}"
|
|
162
|
+
else:
|
|
163
|
+
config_str = server.url or ""
|
|
164
|
+
|
|
165
|
+
table.add_row(
|
|
166
|
+
server.name,
|
|
167
|
+
server.transport_type.value.upper(),
|
|
168
|
+
config_str[:40] + "..." if len(config_str) > 40 else config_str,
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
console.print(table)
|
|
172
|
+
return f"Found {len(servers)} MCP server(s). Use 'koder mcp get <name>' for details."
|
|
173
|
+
|
|
174
|
+
except Exception as e:
|
|
175
|
+
return f"Error listing MCP servers: {e}"
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
class SlashCommandHandler:
|
|
179
|
+
"""Handles slash command detection and execution."""
|
|
180
|
+
|
|
181
|
+
def __init__(self):
|
|
182
|
+
self.commands: Dict[str, SlashCommand] = {
|
|
183
|
+
"init": InitCommand(),
|
|
184
|
+
"clear": ClearCommand(),
|
|
185
|
+
"status": StatusCommand(),
|
|
186
|
+
"mcp": McpCommand(),
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
def get_command_list(self) -> List[Tuple[str, str]]:
|
|
190
|
+
"""Get list of available commands with descriptions."""
|
|
191
|
+
return [(name, cmd.description) for name, cmd in self.commands.items()]
|
|
192
|
+
|
|
193
|
+
async def handle_slash_input(self, user_input: str, scheduler) -> Optional[str]:
|
|
194
|
+
"""Handle slash command input. Returns response if it's a slash command, None otherwise."""
|
|
195
|
+
if not user_input.startswith("/"):
|
|
196
|
+
return None
|
|
197
|
+
|
|
198
|
+
# Special case: just "/" shows command selection
|
|
199
|
+
if user_input.strip() == "/":
|
|
200
|
+
return await self._show_command_selection(scheduler)
|
|
201
|
+
|
|
202
|
+
# Parse command
|
|
203
|
+
parts = user_input[1:].split()
|
|
204
|
+
if not parts:
|
|
205
|
+
return await self._show_command_selection(scheduler)
|
|
206
|
+
|
|
207
|
+
command_name = parts[0].lower()
|
|
208
|
+
args = parts[1:] if len(parts) > 1 else []
|
|
209
|
+
|
|
210
|
+
if command_name not in self.commands:
|
|
211
|
+
available = ", ".join(self.commands.keys())
|
|
212
|
+
return f"❌ Unknown command '{command_name}'. Available commands: {available}"
|
|
213
|
+
|
|
214
|
+
try:
|
|
215
|
+
command = self.commands[command_name]
|
|
216
|
+
return await command.execute(scheduler, *args)
|
|
217
|
+
except Exception as e:
|
|
218
|
+
return f"❌ Error executing command '{command_name}': {str(e)}"
|
|
219
|
+
|
|
220
|
+
async def _show_command_selection(self, _scheduler) -> str:
|
|
221
|
+
"""Show interactive command selection menu."""
|
|
222
|
+
commands = self.get_command_list()
|
|
223
|
+
|
|
224
|
+
if not commands:
|
|
225
|
+
return "No slash commands available."
|
|
226
|
+
|
|
227
|
+
# Show available commands in a simple table
|
|
228
|
+
table = Table(
|
|
229
|
+
title="📋 Available Slash Commands", show_header=True, header_style="bold cyan"
|
|
230
|
+
)
|
|
231
|
+
table.add_column("Command", style="cyan", width=12)
|
|
232
|
+
table.add_column("Description", style="white")
|
|
233
|
+
|
|
234
|
+
for name, description in commands:
|
|
235
|
+
table.add_row(f"/{name}", description)
|
|
236
|
+
|
|
237
|
+
console.print(table)
|
|
238
|
+
console.print(
|
|
239
|
+
Panel(
|
|
240
|
+
"[dim]Commands are auto-completed when you type / - just start typing![/dim]",
|
|
241
|
+
border_style="dim",
|
|
242
|
+
)
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
return "Commands available with auto-completion. Type / and see the popup!"
|
|
246
|
+
|
|
247
|
+
def is_slash_command(self, user_input: str) -> bool:
|
|
248
|
+
"""Check if input is a slash command."""
|
|
249
|
+
return user_input.strip().startswith("/")
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
# Global instance
|
|
253
|
+
slash_handler = SlashCommandHandler()
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"""Context management for conversation history."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
from typing import Dict, List, Optional
|
|
6
|
+
|
|
7
|
+
import aiosqlite
|
|
8
|
+
import tiktoken
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class ContextManager:
|
|
12
|
+
"""Manages conversation context and history with token limits."""
|
|
13
|
+
|
|
14
|
+
def __init__(
|
|
15
|
+
self, session_id: str = "default", db_path: Optional[str] = None, max_tokens: int = 50000
|
|
16
|
+
):
|
|
17
|
+
self.session_id = session_id
|
|
18
|
+
if db_path is None:
|
|
19
|
+
# Use $HOME/.koder/koder.db as default
|
|
20
|
+
home_dir = os.path.expanduser("~")
|
|
21
|
+
koder_dir = os.path.join(home_dir, ".koder")
|
|
22
|
+
os.makedirs(koder_dir, exist_ok=True)
|
|
23
|
+
self.db_path = os.path.join(koder_dir, "koder.db")
|
|
24
|
+
else:
|
|
25
|
+
self.db_path = db_path
|
|
26
|
+
self.max_tokens = max_tokens
|
|
27
|
+
self.encoder = tiktoken.encoding_for_model("gpt-4o")
|
|
28
|
+
|
|
29
|
+
async def _ensure_table(self, conn: aiosqlite.Connection) -> None:
|
|
30
|
+
"""Ensure the context table exists."""
|
|
31
|
+
await conn.execute(
|
|
32
|
+
"""CREATE TABLE IF NOT EXISTS ctx (
|
|
33
|
+
sid TEXT PRIMARY KEY,
|
|
34
|
+
msgs TEXT
|
|
35
|
+
)"""
|
|
36
|
+
)
|
|
37
|
+
await conn.commit()
|
|
38
|
+
|
|
39
|
+
async def _ensure_mcp_table(self, conn: aiosqlite.Connection) -> None:
|
|
40
|
+
"""Ensure the MCP servers table exists."""
|
|
41
|
+
await conn.execute(
|
|
42
|
+
"""CREATE TABLE IF NOT EXISTS mcp_servers (
|
|
43
|
+
name TEXT PRIMARY KEY,
|
|
44
|
+
transport_type TEXT NOT NULL,
|
|
45
|
+
command TEXT,
|
|
46
|
+
args TEXT,
|
|
47
|
+
env_vars TEXT,
|
|
48
|
+
url TEXT,
|
|
49
|
+
headers TEXT,
|
|
50
|
+
cache_tools_list INTEGER DEFAULT 0,
|
|
51
|
+
allowed_tools TEXT,
|
|
52
|
+
blocked_tools TEXT,
|
|
53
|
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
54
|
+
)"""
|
|
55
|
+
)
|
|
56
|
+
await conn.commit()
|
|
57
|
+
|
|
58
|
+
async def load(self) -> List[Dict[str, str]]:
|
|
59
|
+
"""Load conversation history from database."""
|
|
60
|
+
try:
|
|
61
|
+
async with aiosqlite.connect(self.db_path) as conn:
|
|
62
|
+
await self._ensure_table(conn)
|
|
63
|
+
cursor = await conn.execute(
|
|
64
|
+
"SELECT msgs FROM ctx WHERE sid = ?", (self.session_id,)
|
|
65
|
+
)
|
|
66
|
+
row = await cursor.fetchone()
|
|
67
|
+
if row and row[0]:
|
|
68
|
+
return json.loads(row[0])
|
|
69
|
+
return []
|
|
70
|
+
except Exception as e:
|
|
71
|
+
print(f"Error loading context: {e}")
|
|
72
|
+
return []
|
|
73
|
+
|
|
74
|
+
async def save(self, messages: List[Dict[str, str]]) -> None:
|
|
75
|
+
"""Save conversation history to database."""
|
|
76
|
+
try:
|
|
77
|
+
# Check token count and compress if needed
|
|
78
|
+
total_tokens = sum(len(self.encoder.encode(msg["content"])) for msg in messages)
|
|
79
|
+
|
|
80
|
+
if total_tokens > self.max_tokens:
|
|
81
|
+
messages = self._compress_messages(messages)
|
|
82
|
+
|
|
83
|
+
async with aiosqlite.connect(self.db_path) as conn:
|
|
84
|
+
await self._ensure_table(conn)
|
|
85
|
+
await conn.execute(
|
|
86
|
+
"REPLACE INTO ctx VALUES(?, ?)",
|
|
87
|
+
(self.session_id, json.dumps(messages, ensure_ascii=False)),
|
|
88
|
+
)
|
|
89
|
+
await conn.commit()
|
|
90
|
+
except Exception as e:
|
|
91
|
+
print(f"Error saving context: {e}")
|
|
92
|
+
|
|
93
|
+
def _compress_messages(self, messages: List[Dict[str, str]]) -> List[Dict[str, str]]:
|
|
94
|
+
"""Compress messages to fit within token limit."""
|
|
95
|
+
if not messages:
|
|
96
|
+
return messages
|
|
97
|
+
|
|
98
|
+
# Keep first message (system) if it exists
|
|
99
|
+
result = []
|
|
100
|
+
system_msg = None
|
|
101
|
+
if messages and messages[0].get("role") == "system":
|
|
102
|
+
system_msg = messages[0]
|
|
103
|
+
result.append(system_msg)
|
|
104
|
+
remaining_messages = messages[1:]
|
|
105
|
+
else:
|
|
106
|
+
remaining_messages = messages
|
|
107
|
+
|
|
108
|
+
# Calculate tokens for system message
|
|
109
|
+
system_tokens = len(self.encoder.encode(system_msg["content"])) if system_msg else 0
|
|
110
|
+
available_tokens = self.max_tokens - system_tokens
|
|
111
|
+
|
|
112
|
+
# Work backwards from the end, adding messages until we hit token limit
|
|
113
|
+
current_tokens = 0
|
|
114
|
+
messages_to_keep = []
|
|
115
|
+
|
|
116
|
+
for msg in reversed(remaining_messages):
|
|
117
|
+
msg_tokens = len(self.encoder.encode(msg["content"]))
|
|
118
|
+
if current_tokens + msg_tokens > available_tokens:
|
|
119
|
+
break
|
|
120
|
+
messages_to_keep.insert(0, msg)
|
|
121
|
+
current_tokens += msg_tokens
|
|
122
|
+
|
|
123
|
+
# Add summary if we dropped messages
|
|
124
|
+
dropped_count = len(remaining_messages) - len(messages_to_keep)
|
|
125
|
+
if dropped_count > 0:
|
|
126
|
+
summary = {
|
|
127
|
+
"role": "system",
|
|
128
|
+
"content": f"[Note: {dropped_count} previous messages were truncated to stay within token limits]",
|
|
129
|
+
}
|
|
130
|
+
result.append(summary)
|
|
131
|
+
|
|
132
|
+
result.extend(messages_to_keep)
|
|
133
|
+
return result
|
|
134
|
+
|
|
135
|
+
async def clear(self) -> None:
|
|
136
|
+
"""Clear conversation history for the current session."""
|
|
137
|
+
try:
|
|
138
|
+
async with aiosqlite.connect(self.db_path) as conn:
|
|
139
|
+
await self._ensure_table(conn)
|
|
140
|
+
await conn.execute("DELETE FROM ctx WHERE sid = ?", (self.session_id,))
|
|
141
|
+
await conn.commit()
|
|
142
|
+
except Exception as e:
|
|
143
|
+
print(f"Error clearing context: {e}")
|
|
144
|
+
|
|
145
|
+
async def list_sessions(self) -> List[str]:
|
|
146
|
+
"""List all available sessions."""
|
|
147
|
+
try:
|
|
148
|
+
async with aiosqlite.connect(self.db_path) as conn:
|
|
149
|
+
await self._ensure_table(conn)
|
|
150
|
+
cursor = await conn.execute("SELECT sid FROM ctx")
|
|
151
|
+
rows = await cursor.fetchall()
|
|
152
|
+
return [row[0] for row in rows]
|
|
153
|
+
except Exception:
|
|
154
|
+
return []
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
"""Interactive prompt with slash command completion using prompt_toolkit."""
|
|
2
|
+
|
|
3
|
+
from typing import Dict
|
|
4
|
+
|
|
5
|
+
from prompt_toolkit.application import Application
|
|
6
|
+
from prompt_toolkit.buffer import Buffer
|
|
7
|
+
from prompt_toolkit.completion import CompleteEvent, Completer, Completion
|
|
8
|
+
from prompt_toolkit.document import Document
|
|
9
|
+
from prompt_toolkit.key_binding import KeyBindings
|
|
10
|
+
from prompt_toolkit.layout import Layout
|
|
11
|
+
from prompt_toolkit.layout.containers import HSplit, Window
|
|
12
|
+
from prompt_toolkit.layout.controls import BufferControl
|
|
13
|
+
from prompt_toolkit.layout.dimension import Dimension
|
|
14
|
+
from prompt_toolkit.layout.menus import CompletionsMenu
|
|
15
|
+
from prompt_toolkit.layout.processors import BeforeInput
|
|
16
|
+
from prompt_toolkit.shortcuts import PromptSession, confirm
|
|
17
|
+
from prompt_toolkit.styles import Style
|
|
18
|
+
from prompt_toolkit.widgets import Frame
|
|
19
|
+
from rich.console import Console
|
|
20
|
+
|
|
21
|
+
console = Console()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class DynamicCompletionsMenu(CompletionsMenu):
|
|
25
|
+
"""CompletionsMenu that adjusts height based on available completions."""
|
|
26
|
+
|
|
27
|
+
def __init__(self, scroll_offset: int = 1):
|
|
28
|
+
super().__init__(max_height=1, scroll_offset=scroll_offset)
|
|
29
|
+
|
|
30
|
+
def _get_completions(self, app):
|
|
31
|
+
"""Get current completions from the buffer."""
|
|
32
|
+
buffer = app.current_buffer
|
|
33
|
+
if buffer.complete_state:
|
|
34
|
+
return buffer.complete_state.completions
|
|
35
|
+
return []
|
|
36
|
+
|
|
37
|
+
def preferred_height(self, width, max_available_height):
|
|
38
|
+
"""Calculate preferred height based on number of completions."""
|
|
39
|
+
from prompt_toolkit.application import get_app
|
|
40
|
+
|
|
41
|
+
try:
|
|
42
|
+
app = get_app()
|
|
43
|
+
completions = self._get_completions(app)
|
|
44
|
+
completion_count = len(completions)
|
|
45
|
+
|
|
46
|
+
# Return height based on actual completion count, with minimum of 0
|
|
47
|
+
if completion_count == 0:
|
|
48
|
+
return Dimension.exact(0)
|
|
49
|
+
else:
|
|
50
|
+
# Cap at max_available_height to prevent overflow
|
|
51
|
+
height = min(completion_count, max_available_height)
|
|
52
|
+
return Dimension.exact(height)
|
|
53
|
+
except Exception:
|
|
54
|
+
# Fallback to no height if there's any error
|
|
55
|
+
return Dimension.exact(0)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class SlashCommandCompleter(Completer):
|
|
59
|
+
"""Custom completer for slash commands with descriptions."""
|
|
60
|
+
|
|
61
|
+
def __init__(self, commands: Dict[str, str]):
|
|
62
|
+
"""Initialize with command name -> description mapping."""
|
|
63
|
+
self.commands = commands
|
|
64
|
+
|
|
65
|
+
def get_completions(self, document: Document, complete_event: CompleteEvent):
|
|
66
|
+
"""Generate completions for slash commands."""
|
|
67
|
+
text = document.text_before_cursor
|
|
68
|
+
|
|
69
|
+
# Only show completions if we're at the start and typing a slash
|
|
70
|
+
if text == "/" or (text.startswith("/") and " " not in text):
|
|
71
|
+
# Remove the leading slash for matching
|
|
72
|
+
search_text = text[1:] if text.startswith("/") else text
|
|
73
|
+
|
|
74
|
+
for command, description in self.commands.items():
|
|
75
|
+
if command.startswith(search_text):
|
|
76
|
+
# Create completion with command name and description
|
|
77
|
+
yield Completion(
|
|
78
|
+
text=command,
|
|
79
|
+
start_position=-len(search_text),
|
|
80
|
+
display=f"/{command}",
|
|
81
|
+
display_meta=description,
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class InteractivePrompt:
|
|
86
|
+
"""Enhanced prompt with slash command support."""
|
|
87
|
+
|
|
88
|
+
def __init__(self, commands: Dict[str, str]):
|
|
89
|
+
"""Initialize with available slash commands."""
|
|
90
|
+
self.commands = commands
|
|
91
|
+
self.completer = SlashCommandCompleter(commands)
|
|
92
|
+
self.session = PromptSession(
|
|
93
|
+
completer=self.completer,
|
|
94
|
+
complete_while_typing=True,
|
|
95
|
+
mouse_support=True,
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
async def get_input(self, prompt_text: str = "user") -> str:
|
|
99
|
+
"""Get user input with Rich panel display and prompt_toolkit completion."""
|
|
100
|
+
# Create buffer
|
|
101
|
+
buffer = Buffer(
|
|
102
|
+
completer=self.completer,
|
|
103
|
+
complete_while_typing=True,
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
# Create buffer control with "> " prefix
|
|
107
|
+
buffer_control = BufferControl(
|
|
108
|
+
buffer=buffer,
|
|
109
|
+
input_processors=[BeforeInput("> ")],
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
# Create input window
|
|
113
|
+
input_window = Window(
|
|
114
|
+
content=buffer_control,
|
|
115
|
+
height=1,
|
|
116
|
+
wrap_lines=False,
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
# Create frame that mimics Rich panel
|
|
120
|
+
framed_input = Frame(
|
|
121
|
+
body=input_window,
|
|
122
|
+
title=f"💭 {prompt_text.title()} Input",
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
# Key bindings
|
|
126
|
+
kb = KeyBindings()
|
|
127
|
+
|
|
128
|
+
@kb.add("enter")
|
|
129
|
+
def accept_input(event):
|
|
130
|
+
event.app.exit(result=buffer.text)
|
|
131
|
+
|
|
132
|
+
@kb.add("c-c")
|
|
133
|
+
def cancel_input(event):
|
|
134
|
+
event.app.exit(exception=KeyboardInterrupt())
|
|
135
|
+
|
|
136
|
+
@kb.add("c-d")
|
|
137
|
+
def eof_input(event):
|
|
138
|
+
# Always exit immediately on Ctrl+D, raise EOFError if buffer is empty
|
|
139
|
+
if not buffer.text:
|
|
140
|
+
event.app.exit(exception=EOFError())
|
|
141
|
+
else:
|
|
142
|
+
event.app.exit(result=buffer.text)
|
|
143
|
+
|
|
144
|
+
# Add Tab key for completion navigation
|
|
145
|
+
@kb.add("tab")
|
|
146
|
+
def complete(event):
|
|
147
|
+
# Tab to navigate through completions
|
|
148
|
+
b = event.app.current_buffer
|
|
149
|
+
if b.complete_state:
|
|
150
|
+
b.complete_next()
|
|
151
|
+
else:
|
|
152
|
+
b.start_completion(select_first=True)
|
|
153
|
+
|
|
154
|
+
@kb.add("s-tab") # Shift+Tab
|
|
155
|
+
def complete_previous(event):
|
|
156
|
+
# Shift+Tab to navigate backwards through completions
|
|
157
|
+
b = event.app.current_buffer
|
|
158
|
+
if b.complete_state:
|
|
159
|
+
b.complete_previous()
|
|
160
|
+
|
|
161
|
+
@kb.add("backspace")
|
|
162
|
+
def handle_backspace(event):
|
|
163
|
+
# Handle backspace and retrigger completion if needed
|
|
164
|
+
b = event.app.current_buffer
|
|
165
|
+
# First perform the backspace
|
|
166
|
+
b.delete_before_cursor()
|
|
167
|
+
# If we're working with a slash command, retrigger completion
|
|
168
|
+
if b.text.startswith("/"):
|
|
169
|
+
# Cancel current completion state
|
|
170
|
+
b.cancel_completion()
|
|
171
|
+
# Start new completion
|
|
172
|
+
b.start_completion(select_first=False)
|
|
173
|
+
else:
|
|
174
|
+
# Cancel completion if we're no longer in slash mode
|
|
175
|
+
b.cancel_completion()
|
|
176
|
+
|
|
177
|
+
@kb.add("delete")
|
|
178
|
+
def handle_delete(event):
|
|
179
|
+
# Handle delete key and retrigger completion if needed
|
|
180
|
+
b = event.app.current_buffer
|
|
181
|
+
# First perform the delete
|
|
182
|
+
b.delete()
|
|
183
|
+
# If we're working with a slash command, retrigger completion
|
|
184
|
+
if b.text.startswith("/"):
|
|
185
|
+
# Cancel current completion state
|
|
186
|
+
b.cancel_completion()
|
|
187
|
+
# Start new completion
|
|
188
|
+
b.start_completion(select_first=False)
|
|
189
|
+
else:
|
|
190
|
+
# Cancel completion if we're no longer in slash mode
|
|
191
|
+
b.cancel_completion()
|
|
192
|
+
|
|
193
|
+
# Create layout with completion menu
|
|
194
|
+
layout = Layout(
|
|
195
|
+
HSplit(
|
|
196
|
+
[
|
|
197
|
+
framed_input,
|
|
198
|
+
DynamicCompletionsMenu(scroll_offset=1),
|
|
199
|
+
]
|
|
200
|
+
)
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
# Create style that matches Rich and supports completion
|
|
204
|
+
style = Style.from_dict(
|
|
205
|
+
{
|
|
206
|
+
"frame.border": "#7C7C78", # Blue border like Rich
|
|
207
|
+
"frame.title": "#7C7C78 bold", # White bold title
|
|
208
|
+
"": "#888888", # Gray color for user input text
|
|
209
|
+
"completion-menu.completion": "#ffffff bg:#444444", # Completion items
|
|
210
|
+
"completion-menu.completion.current": "#ffffff bg:#666666", # Selected completion
|
|
211
|
+
"completion-menu.meta.completion": "#aaaaaa bg:#333333", # Completion description
|
|
212
|
+
"completion-menu.meta.completion.current": "#ffffff bg:#555555", # Selected desc
|
|
213
|
+
}
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
# Create application
|
|
217
|
+
app = Application(
|
|
218
|
+
layout=layout,
|
|
219
|
+
key_bindings=kb,
|
|
220
|
+
style=style,
|
|
221
|
+
full_screen=False,
|
|
222
|
+
mouse_support=True,
|
|
223
|
+
)
|
|
224
|
+
|
|
225
|
+
result = await app.run_async()
|
|
226
|
+
if result is None:
|
|
227
|
+
raise EOFError("Empty input received")
|
|
228
|
+
return result.strip()
|
|
229
|
+
|
|
230
|
+
def confirm_action(self, message: str) -> bool:
|
|
231
|
+
"""Ask for confirmation with yes/no prompt."""
|
|
232
|
+
try:
|
|
233
|
+
return confirm(message)
|
|
234
|
+
except (EOFError, KeyboardInterrupt):
|
|
235
|
+
return False
|
|
236
|
+
|
|
237
|
+
def show_command_help(self) -> None:
|
|
238
|
+
"""Display available commands in a formatted way."""
|
|
239
|
+
console.print("\n[bold cyan]Available Slash Commands:[/bold cyan]")
|
|
240
|
+
for command, description in self.commands.items():
|
|
241
|
+
console.print(f" [cyan]/{command}[/cyan] - {description}")
|
|
242
|
+
console.print()
|