koder 0.2.0__tar.gz → 0.3.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {koder-0.2.0 → koder-0.3.0}/PKG-INFO +2 -5
- {koder-0.2.0 → koder-0.3.0}/README.md +1 -4
- {koder-0.2.0 → koder-0.3.0}/koder_agent/__init__.py +1 -1
- {koder-0.2.0 → koder-0.3.0}/koder_agent/agentic/agent.py +0 -14
- {koder-0.2.0 → koder-0.3.0}/koder_agent/cli.py +6 -13
- {koder-0.2.0 → koder-0.3.0}/koder_agent/core/commands.py +2 -2
- {koder-0.2.0 → koder-0.3.0}/koder_agent/core/interactive.py +24 -19
- koder-0.3.0/koder_agent/core/scheduler.py +355 -0
- koder-0.3.0/koder_agent/core/streaming_display.py +491 -0
- {koder-0.2.0 → koder-0.3.0}/koder_agent/mcp/cli_handler.py +2 -2
- {koder-0.2.0 → koder-0.3.0}/koder_agent/tools/engine.py +1 -1
- {koder-0.2.0 → koder-0.3.0}/koder_agent/tools/task_ops.py +1 -0
- {koder-0.2.0 → koder-0.3.0}/koder_agent/utils/client.py +3 -3
- {koder-0.2.0 → koder-0.3.0}/pyproject.toml +1 -1
- {koder-0.2.0 → koder-0.3.0}/uv.lock +1 -1
- koder-0.2.0/koder_agent/core/scheduler.py +0 -349
- {koder-0.2.0 → koder-0.3.0}/.claude/settings.local.json +0 -0
- {koder-0.2.0 → koder-0.3.0}/.github/dependabot.yml +0 -0
- {koder-0.2.0 → koder-0.3.0}/.gitignore +0 -0
- {koder-0.2.0 → koder-0.3.0}/CLAUDE.md +0 -0
- {koder-0.2.0 → koder-0.3.0}/KODER.md +0 -0
- {koder-0.2.0 → koder-0.3.0}/LICENSE +0 -0
- {koder-0.2.0 → koder-0.3.0}/koder_agent/agentic/__init__.py +0 -0
- {koder-0.2.0 → koder-0.3.0}/koder_agent/agentic/hooks.py +0 -0
- {koder-0.2.0 → koder-0.3.0}/koder_agent/core/__init__.py +0 -0
- {koder-0.2.0 → koder-0.3.0}/koder_agent/core/context.py +0 -0
- {koder-0.2.0 → koder-0.3.0}/koder_agent/core/security.py +0 -0
- {koder-0.2.0 → koder-0.3.0}/koder_agent/mcp/__init__.py +0 -0
- {koder-0.2.0 → koder-0.3.0}/koder_agent/mcp/server_config.py +0 -0
- {koder-0.2.0 → koder-0.3.0}/koder_agent/mcp/server_factory.py +0 -0
- {koder-0.2.0 → koder-0.3.0}/koder_agent/mcp/server_manager.py +0 -0
- {koder-0.2.0 → koder-0.3.0}/koder_agent/tools/__init__.py +0 -0
- {koder-0.2.0 → koder-0.3.0}/koder_agent/tools/file_ops.py +0 -0
- {koder-0.2.0 → koder-0.3.0}/koder_agent/tools/search_ops.py +0 -0
- {koder-0.2.0 → koder-0.3.0}/koder_agent/tools/shell_ops.py +0 -0
- {koder-0.2.0 → koder-0.3.0}/koder_agent/tools/todo_ops.py +0 -0
- {koder-0.2.0 → koder-0.3.0}/koder_agent/tools/web_ops.py +0 -0
- {koder-0.2.0 → koder-0.3.0}/koder_agent/utils/__init__.py +0 -0
- {koder-0.2.0 → koder-0.3.0}/koder_agent/utils/prompts.py +0 -0
- {koder-0.2.0 → koder-0.3.0}/koder_agent/utils/queue.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: koder
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
4
|
Summary: An intuitive AI coding assistant and interactive CLI tool that boosts developer productivity with intelligent automation and context-aware support.
|
|
5
5
|
Author: Pengfei Ni
|
|
6
6
|
License-File: LICENSE
|
|
@@ -21,10 +21,7 @@ Description-Content-Type: text/markdown
|
|
|
21
21
|
|
|
22
22
|
# Koder
|
|
23
23
|
|
|
24
|
-
[](https://www.python.org/downloads/)
|
|
25
|
-
[](LICENSE)
|
|
26
|
-
[](https://github.com/psf/black)
|
|
27
|
-
[](https://github.com/astral-sh/ruff)
|
|
24
|
+
[](https://www.python.org/downloads/) [](LICENSE) [](https://github.com/psf/black) [](https://github.com/astral-sh/ruff) [](https://pepy.tech/projects/koder)
|
|
28
25
|
|
|
29
26
|
An intuitive AI coding assistant and interactive CLI tool that boosts developer productivity with intelligent automation and context-aware support.
|
|
30
27
|
|
|
@@ -1,9 +1,6 @@
|
|
|
1
1
|
# Koder
|
|
2
2
|
|
|
3
|
-
[](https://www.python.org/downloads/)
|
|
4
|
-
[](LICENSE)
|
|
5
|
-
[](https://github.com/psf/black)
|
|
6
|
-
[](https://github.com/astral-sh/ruff)
|
|
3
|
+
[](https://www.python.org/downloads/) [](LICENSE) [](https://github.com/psf/black) [](https://github.com/astral-sh/ruff) [](https://pepy.tech/projects/koder)
|
|
7
4
|
|
|
8
5
|
An intuitive AI coding assistant and interactive CLI tool that boosts developer productivity with intelligent automation and context-aware support.
|
|
9
6
|
|
|
@@ -14,31 +14,17 @@ console = Console()
|
|
|
14
14
|
logger = logging.getLogger(__name__)
|
|
15
15
|
|
|
16
16
|
|
|
17
|
-
# def create_planner_agent(model, tools, mcp_servers) -> Agent:
|
|
18
|
-
# """Create the planner agent."""
|
|
19
|
-
# return Agent(
|
|
20
|
-
# name="Planner",
|
|
21
|
-
# instructions=f"{KODER_SYSTEM_PROMPT}\nReturn numbered list or 'no planning needed'.",
|
|
22
|
-
# tools=tools,
|
|
23
|
-
# mcp_servers=mcp_servers,
|
|
24
|
-
# model=model,
|
|
25
|
-
# handoffs=[],
|
|
26
|
-
# )
|
|
27
|
-
|
|
28
|
-
|
|
29
17
|
async def create_dev_agent(tools) -> Agent:
|
|
30
18
|
"""Create the main development agent with MCP servers."""
|
|
31
19
|
# Get the appropriate model based on environment
|
|
32
20
|
model = get_model_name()
|
|
33
21
|
mcp_servers = await load_mcp_servers()
|
|
34
|
-
# planner = create_planner_agent(model, tools, mcp_servers)
|
|
35
22
|
|
|
36
23
|
dev_agent = Agent(
|
|
37
24
|
name="Koder",
|
|
38
25
|
model=model,
|
|
39
26
|
instructions=KODER_SYSTEM_PROMPT,
|
|
40
27
|
tools=tools,
|
|
41
|
-
# handoffs=[planner],
|
|
42
28
|
mcp_servers=mcp_servers,
|
|
43
29
|
)
|
|
44
30
|
|
|
@@ -51,9 +51,7 @@ async def main():
|
|
|
51
51
|
|
|
52
52
|
# Add root-level options (from old chat command)
|
|
53
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
|
-
)
|
|
54
|
+
parser.add_argument("--no-stream", action="store_true", help="Disable streaming mode")
|
|
57
55
|
|
|
58
56
|
# Create subparsers for specific commands
|
|
59
57
|
subparsers = parser.add_subparsers(dest="command", help="Available commands")
|
|
@@ -133,18 +131,13 @@ async def main():
|
|
|
133
131
|
|
|
134
132
|
# Load context for chat mode
|
|
135
133
|
context = await load_context()
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
"[dim]Type 'exit' or 'quit' to stop, Ctrl+C to interrupt[/dim]",
|
|
141
|
-
title="Koder",
|
|
142
|
-
border_style="cyan",
|
|
143
|
-
)
|
|
144
|
-
)
|
|
134
|
+
# Simple startup message
|
|
135
|
+
console.print(f"[dim]koder session: {args.session}[/dim]")
|
|
136
|
+
console.print(f"[dim]working in: {os.getcwd()}[/dim]")
|
|
137
|
+
print()
|
|
145
138
|
|
|
146
139
|
# Create scheduler
|
|
147
|
-
scheduler = AgentScheduler(session_id=args.session, streaming=args.
|
|
140
|
+
scheduler = AgentScheduler(session_id=args.session, streaming=not args.no_stream)
|
|
148
141
|
|
|
149
142
|
try:
|
|
150
143
|
# Create interactive prompt with slash commands
|
|
@@ -94,7 +94,7 @@ class StatusCommand(SlashCommand):
|
|
|
94
94
|
tool_count = len(tools)
|
|
95
95
|
|
|
96
96
|
# Create status table
|
|
97
|
-
table = Table(title="
|
|
97
|
+
table = Table(title="Koder Status", show_header=True, header_style="bold cyan")
|
|
98
98
|
table.add_column("Setting", style="cyan", width=20)
|
|
99
99
|
table.add_column("Value", style="green")
|
|
100
100
|
|
|
@@ -150,7 +150,7 @@ class McpCommand(SlashCommand):
|
|
|
150
150
|
return "No MCP servers configured. Use 'koder mcp add' to add servers."
|
|
151
151
|
|
|
152
152
|
# Create simple table for display
|
|
153
|
-
table = Table(title="
|
|
153
|
+
table = Table(title="MCP Servers", show_header=True, header_style="bold cyan")
|
|
154
154
|
table.add_column("Name", style="cyan", width=20)
|
|
155
155
|
table.add_column("Type", style="green", width=10)
|
|
156
156
|
table.add_column("Configuration", style="white")
|
|
@@ -109,17 +109,18 @@ class InteractivePrompt:
|
|
|
109
109
|
input_processors=[BeforeInput("> ")],
|
|
110
110
|
)
|
|
111
111
|
|
|
112
|
-
# Create input window
|
|
112
|
+
# Create input window with dynamic height
|
|
113
113
|
input_window = Window(
|
|
114
114
|
content=buffer_control,
|
|
115
|
-
height=1,
|
|
116
|
-
wrap_lines=False,
|
|
115
|
+
height=Dimension(min=1, max=10), # Allow 1-10 lines, auto-expand
|
|
116
|
+
wrap_lines=False, # Keep single line behavior, expand vertically instead
|
|
117
|
+
dont_extend_height=True,
|
|
117
118
|
)
|
|
118
119
|
|
|
119
|
-
# Create frame
|
|
120
|
+
# Create simple frame without heavy styling
|
|
120
121
|
framed_input = Frame(
|
|
121
122
|
body=input_window,
|
|
122
|
-
title=f"
|
|
123
|
+
title=f"{prompt_text}",
|
|
123
124
|
)
|
|
124
125
|
|
|
125
126
|
# Key bindings
|
|
@@ -127,19 +128,23 @@ class InteractivePrompt:
|
|
|
127
128
|
|
|
128
129
|
@kb.add("enter")
|
|
129
130
|
def accept_input(event):
|
|
131
|
+
# Submit the input
|
|
130
132
|
event.app.exit(result=buffer.text)
|
|
131
133
|
|
|
134
|
+
@kb.add("c-j") # For Ctrl+Enter in many terminals
|
|
135
|
+
@kb.add("escape", "enter") # For Alt+Enter as a more compatible option
|
|
136
|
+
def insert_newline(event):
|
|
137
|
+
# Insert a newline for multi-line input
|
|
138
|
+
event.app.current_buffer.insert_text("\n")
|
|
139
|
+
|
|
132
140
|
@kb.add("c-c")
|
|
133
141
|
def cancel_input(event):
|
|
134
142
|
event.app.exit(exception=KeyboardInterrupt())
|
|
135
143
|
|
|
136
144
|
@kb.add("c-d")
|
|
137
|
-
def
|
|
138
|
-
#
|
|
139
|
-
|
|
140
|
-
event.app.exit(exception=EOFError())
|
|
141
|
-
else:
|
|
142
|
-
event.app.exit(result=buffer.text)
|
|
145
|
+
def clear_input(event):
|
|
146
|
+
# Clear the input content
|
|
147
|
+
event.app.current_buffer.text = ""
|
|
143
148
|
|
|
144
149
|
# Add Tab key for completion navigation
|
|
145
150
|
@kb.add("tab")
|
|
@@ -200,16 +205,16 @@ class InteractivePrompt:
|
|
|
200
205
|
)
|
|
201
206
|
)
|
|
202
207
|
|
|
203
|
-
#
|
|
208
|
+
# Minimal style for clean terminal look
|
|
204
209
|
style = Style.from_dict(
|
|
205
210
|
{
|
|
206
|
-
"frame.border": "#
|
|
207
|
-
"frame.title": "#
|
|
208
|
-
"": "#
|
|
209
|
-
"completion-menu.completion": "#ffffff bg:#
|
|
210
|
-
"completion-menu.completion.current": "#ffffff bg:#
|
|
211
|
-
"completion-menu.meta.completion": "#aaaaaa bg:#
|
|
212
|
-
"completion-menu.meta.completion.current": "#ffffff bg:#
|
|
211
|
+
"frame.border": "#555555", # Subtle gray border
|
|
212
|
+
"frame.title": "#888888", # Muted title
|
|
213
|
+
"": "#ffffff", # Normal white text for input
|
|
214
|
+
"completion-menu.completion": "#ffffff bg:#333333", # Clean completion items
|
|
215
|
+
"completion-menu.completion.current": "#ffffff bg:#555555", # Selected completion
|
|
216
|
+
"completion-menu.meta.completion": "#aaaaaa bg:#222222", # Muted description
|
|
217
|
+
"completion-menu.meta.completion.current": "#ffffff bg:#444444", # Selected desc
|
|
213
218
|
}
|
|
214
219
|
)
|
|
215
220
|
|
|
@@ -0,0 +1,355 @@
|
|
|
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.types.responses import ResponseFunctionToolCall
|
|
15
|
+
from openai.types.responses.response_text_delta_event import ResponseTextDeltaEvent
|
|
16
|
+
from rich.console import Console, Group
|
|
17
|
+
from rich.live import Live
|
|
18
|
+
from rich.text import Text
|
|
19
|
+
|
|
20
|
+
from ..agentic import create_dev_agent, get_display_hooks
|
|
21
|
+
from ..core.context import ContextManager
|
|
22
|
+
from ..core.streaming_display import StreamingDisplayManager
|
|
23
|
+
from ..tools import get_all_tools
|
|
24
|
+
|
|
25
|
+
console = Console()
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class AgentScheduler:
|
|
29
|
+
"""Scheduler for managing agent execution with context and security."""
|
|
30
|
+
|
|
31
|
+
def __init__(self, session_id: str = "default", streaming: bool = False):
|
|
32
|
+
self.semaphore = asyncio.Semaphore(10)
|
|
33
|
+
self.context_manager = ContextManager(session_id)
|
|
34
|
+
self.tools = get_all_tools()
|
|
35
|
+
self.dev_agent = None # Will be initialized in async method
|
|
36
|
+
self.streaming = streaming
|
|
37
|
+
self.hooks = get_display_hooks(streaming_mode=streaming)
|
|
38
|
+
self._agent_initialized = False
|
|
39
|
+
self._mcp_servers = [] # Track MCP servers for cleanup
|
|
40
|
+
|
|
41
|
+
def _has_content(self, content) -> bool:
|
|
42
|
+
"""Check if Rich or string content has any content."""
|
|
43
|
+
if isinstance(content, str):
|
|
44
|
+
return bool(content.strip())
|
|
45
|
+
elif isinstance(content, Text):
|
|
46
|
+
return bool(str(content).strip())
|
|
47
|
+
elif isinstance(content, Group):
|
|
48
|
+
return bool(content.renderables)
|
|
49
|
+
else:
|
|
50
|
+
return content is not None
|
|
51
|
+
|
|
52
|
+
def _get_line_count(self, content) -> int:
|
|
53
|
+
"""Get line count for Rich or string content."""
|
|
54
|
+
if isinstance(content, str):
|
|
55
|
+
return content.count("\n") + 1
|
|
56
|
+
elif isinstance(content, Text):
|
|
57
|
+
return str(content).count("\n") + 1
|
|
58
|
+
elif isinstance(content, Group):
|
|
59
|
+
return len(content.renderables) * 2
|
|
60
|
+
else:
|
|
61
|
+
return 50 # Conservative estimate
|
|
62
|
+
|
|
63
|
+
async def _ensure_agent_initialized(self):
|
|
64
|
+
"""Ensure the dev agent is initialized."""
|
|
65
|
+
if not self._agent_initialized:
|
|
66
|
+
self.dev_agent = await create_dev_agent(self.tools)
|
|
67
|
+
# Track MCP servers for cleanup
|
|
68
|
+
if hasattr(self.dev_agent, "mcp_servers") and self.dev_agent.mcp_servers:
|
|
69
|
+
self._mcp_servers = self.dev_agent.mcp_servers
|
|
70
|
+
self._agent_initialized = True
|
|
71
|
+
|
|
72
|
+
async def handle(self, user_input: str) -> str:
|
|
73
|
+
"""Handle user input and execute agent."""
|
|
74
|
+
# Ensure agent is initialized with MCP servers
|
|
75
|
+
await self._ensure_agent_initialized()
|
|
76
|
+
|
|
77
|
+
if self.dev_agent is None:
|
|
78
|
+
console.print("[dim red]Agent not initialized[/dim red]")
|
|
79
|
+
return "Agent not initialized"
|
|
80
|
+
|
|
81
|
+
# Note: Input panel is now displayed in InteractivePrompt, so we skip showing it here
|
|
82
|
+
|
|
83
|
+
# Load conversation history
|
|
84
|
+
history = await self.context_manager.load()
|
|
85
|
+
|
|
86
|
+
console.print("[dim]thinking...[/dim]")
|
|
87
|
+
|
|
88
|
+
# Build context from history
|
|
89
|
+
context_str = ""
|
|
90
|
+
if history:
|
|
91
|
+
context_str = "Previous conversation:\n"
|
|
92
|
+
for msg in history:
|
|
93
|
+
role = msg["role"].capitalize()
|
|
94
|
+
content = msg["content"]
|
|
95
|
+
context_str += f"{role}: {content}\n"
|
|
96
|
+
context_str += "\nCurrent request:\n"
|
|
97
|
+
|
|
98
|
+
# Combine context with current user input
|
|
99
|
+
full_input = context_str + user_input if context_str else user_input
|
|
100
|
+
|
|
101
|
+
# Run the agent
|
|
102
|
+
async with self.semaphore:
|
|
103
|
+
if self.streaming:
|
|
104
|
+
response = await self._handle_streaming(full_input)
|
|
105
|
+
else:
|
|
106
|
+
result = await Runner.run(
|
|
107
|
+
self.dev_agent,
|
|
108
|
+
full_input,
|
|
109
|
+
run_config=RunConfig(),
|
|
110
|
+
hooks=self.hooks,
|
|
111
|
+
max_turns=50,
|
|
112
|
+
)
|
|
113
|
+
# Filter output for security
|
|
114
|
+
response = self._filter_output(result.final_output)
|
|
115
|
+
|
|
116
|
+
# Clean response output without heavy panels
|
|
117
|
+
print() # Add space before response
|
|
118
|
+
console.print(response)
|
|
119
|
+
print() # Add space after response
|
|
120
|
+
|
|
121
|
+
# Save conversation to context
|
|
122
|
+
await self.context_manager.save(
|
|
123
|
+
history
|
|
124
|
+
+ [
|
|
125
|
+
{"role": "user", "content": user_input},
|
|
126
|
+
{"role": "assistant", "content": response},
|
|
127
|
+
]
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
return response
|
|
131
|
+
|
|
132
|
+
async def _handle_streaming(self, full_input: str) -> str:
|
|
133
|
+
"""Handle streaming execution with Rich Live and smart cleanup."""
|
|
134
|
+
import os
|
|
135
|
+
import sys
|
|
136
|
+
|
|
137
|
+
# Create the streaming display manager
|
|
138
|
+
display_manager = StreamingDisplayManager(console)
|
|
139
|
+
|
|
140
|
+
# Detect terminal capabilities
|
|
141
|
+
terminal_type = os.environ.get("TERM_PROGRAM", "unknown")
|
|
142
|
+
supports_advanced_clearing = terminal_type in ["iTerm.app", "Apple_Terminal", "vscode"]
|
|
143
|
+
|
|
144
|
+
# Add space before streaming starts
|
|
145
|
+
print()
|
|
146
|
+
|
|
147
|
+
# Capture cursor position before Rich Live starts (if supported)
|
|
148
|
+
if supports_advanced_clearing:
|
|
149
|
+
sys.stdout.write("\033[6n") # Request cursor position
|
|
150
|
+
sys.stdout.flush()
|
|
151
|
+
|
|
152
|
+
# Run the agent in streaming mode
|
|
153
|
+
if self.dev_agent is None:
|
|
154
|
+
console.print("[dim red]Agent not initialized[/dim red]")
|
|
155
|
+
return "Agent not initialized"
|
|
156
|
+
|
|
157
|
+
result = Runner.run_streamed(
|
|
158
|
+
self.dev_agent,
|
|
159
|
+
full_input,
|
|
160
|
+
run_config=RunConfig(),
|
|
161
|
+
hooks=self.hooks,
|
|
162
|
+
max_turns=50,
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
# Track if we displayed content during streaming
|
|
166
|
+
content_displayed = False
|
|
167
|
+
|
|
168
|
+
# Use Rich Live for proper formatting during streaming
|
|
169
|
+
with Live(
|
|
170
|
+
"",
|
|
171
|
+
console=console,
|
|
172
|
+
refresh_per_second=8, # Reasonable refresh rate
|
|
173
|
+
transient=False, # Keep content visible during streaming
|
|
174
|
+
vertical_overflow="visible", # Show all content even if it exceeds screen height
|
|
175
|
+
) as live:
|
|
176
|
+
try:
|
|
177
|
+
# Process streaming events
|
|
178
|
+
async for event in result.stream_events():
|
|
179
|
+
try:
|
|
180
|
+
should_update = False
|
|
181
|
+
|
|
182
|
+
# Handle raw response events (token-by-token streaming)
|
|
183
|
+
if isinstance(event, RawResponsesStreamEvent):
|
|
184
|
+
if isinstance(event.data, ResponseTextDeltaEvent):
|
|
185
|
+
delta_text = event.data.delta
|
|
186
|
+
output_index = event.data.output_index
|
|
187
|
+
|
|
188
|
+
if delta_text:
|
|
189
|
+
should_update = display_manager.handle_text_delta(
|
|
190
|
+
output_index, delta_text
|
|
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
|
+
should_update = display_manager.handle_tool_called(event.item)
|
|
202
|
+
|
|
203
|
+
elif event.name == "tool_output":
|
|
204
|
+
if hasattr(event, "item") and isinstance(
|
|
205
|
+
event.item, ToolCallOutputItem
|
|
206
|
+
):
|
|
207
|
+
should_update = display_manager.handle_tool_output(event.item)
|
|
208
|
+
|
|
209
|
+
elif event.name == "message_output_created":
|
|
210
|
+
pass
|
|
211
|
+
elif event.name == "handoff_requested":
|
|
212
|
+
# Handle agent handoff as a special tool call
|
|
213
|
+
should_update = display_manager.handle_tool_called(
|
|
214
|
+
type(
|
|
215
|
+
"HandoffItem",
|
|
216
|
+
(),
|
|
217
|
+
{
|
|
218
|
+
"raw_item": type(
|
|
219
|
+
"RawItem",
|
|
220
|
+
(),
|
|
221
|
+
{
|
|
222
|
+
"name": "agent_handoff",
|
|
223
|
+
"arguments": "{}",
|
|
224
|
+
"id": "handoff",
|
|
225
|
+
},
|
|
226
|
+
)()
|
|
227
|
+
},
|
|
228
|
+
)()
|
|
229
|
+
)
|
|
230
|
+
elif event.name == "handoff_occured":
|
|
231
|
+
# Handle as tool output
|
|
232
|
+
should_update = display_manager.handle_tool_output(
|
|
233
|
+
type(
|
|
234
|
+
"HandoffOutput",
|
|
235
|
+
(),
|
|
236
|
+
{"output": "Agent switched", "tool_call_id": "handoff"},
|
|
237
|
+
)()
|
|
238
|
+
)
|
|
239
|
+
elif event.name == "reasoning_item_created":
|
|
240
|
+
# Don't show reasoning steps in display
|
|
241
|
+
pass
|
|
242
|
+
|
|
243
|
+
# Handle agent updates (handoffs, etc.)
|
|
244
|
+
elif isinstance(event, AgentUpdatedStreamEvent):
|
|
245
|
+
# This is handled by handoff events above
|
|
246
|
+
pass
|
|
247
|
+
|
|
248
|
+
# Update Rich Live display
|
|
249
|
+
if should_update:
|
|
250
|
+
current_content = display_manager.get_display_content()
|
|
251
|
+
# Handle both string and renderable objects
|
|
252
|
+
if isinstance(current_content, str):
|
|
253
|
+
if current_content.strip():
|
|
254
|
+
live.update(current_content)
|
|
255
|
+
content_displayed = True
|
|
256
|
+
elif current_content: # For renderables like Group
|
|
257
|
+
live.update(current_content)
|
|
258
|
+
content_displayed = True
|
|
259
|
+
|
|
260
|
+
except Exception as e:
|
|
261
|
+
# Log event processing errors but continue streaming
|
|
262
|
+
console.print(f"[dim red]Event processing error: {e}[/dim red]")
|
|
263
|
+
continue
|
|
264
|
+
|
|
265
|
+
except Exception as e:
|
|
266
|
+
# Handle streaming errors
|
|
267
|
+
console.print(f"[dim red]Streaming error: {e}[/dim red]")
|
|
268
|
+
|
|
269
|
+
# After Rich Live context ends, perform intelligent cleanup
|
|
270
|
+
display_manager.finalize_text_sections()
|
|
271
|
+
|
|
272
|
+
# Get final content for permanent display
|
|
273
|
+
final_content = display_manager.get_display_content()
|
|
274
|
+
|
|
275
|
+
# Clear the Rich Live region and show final content cleanly
|
|
276
|
+
# Check if we have content to display
|
|
277
|
+
has_content = self._has_content(final_content)
|
|
278
|
+
|
|
279
|
+
if has_content:
|
|
280
|
+
# Strategy 1: For advanced terminals, clear the scroll buffer region
|
|
281
|
+
if supports_advanced_clearing:
|
|
282
|
+
try:
|
|
283
|
+
# Clear recent lines from scroll buffer (terminal-specific)
|
|
284
|
+
if terminal_type == "iTerm.app":
|
|
285
|
+
# iTerm2 specific: Clear last N lines from scrollback
|
|
286
|
+
lines_count = self._get_line_count(final_content)
|
|
287
|
+
sys.stdout.write(f"\033]1337;ClearScrollback=lines:{lines_count * 3}\007")
|
|
288
|
+
elif terminal_type == "Apple_Terminal":
|
|
289
|
+
# Terminal.app: Use scrollback clearing if available
|
|
290
|
+
sys.stdout.write("\033[3J") # Clear scrollback
|
|
291
|
+
|
|
292
|
+
sys.stdout.flush()
|
|
293
|
+
except Exception:
|
|
294
|
+
pass # Fallback to simple approach
|
|
295
|
+
|
|
296
|
+
# Strategy 2: Print final clean content only if not already displayed
|
|
297
|
+
# Skip if we already showed content during streaming
|
|
298
|
+
if not content_displayed:
|
|
299
|
+
# No content was displayed during streaming, show it now
|
|
300
|
+
print() # Add spacing
|
|
301
|
+
console.print(final_content)
|
|
302
|
+
print() # Add spacing after
|
|
303
|
+
|
|
304
|
+
# Get final text response for context saving
|
|
305
|
+
final_response = display_manager.get_final_text()
|
|
306
|
+
if not final_response:
|
|
307
|
+
# Fallback to result.final_output if no text was captured
|
|
308
|
+
final_response = self._filter_output(result.final_output)
|
|
309
|
+
else:
|
|
310
|
+
final_response = self._filter_output(final_response)
|
|
311
|
+
|
|
312
|
+
return final_response
|
|
313
|
+
|
|
314
|
+
def _get_display_input(self, user_input: str) -> str:
|
|
315
|
+
"""Get a filtered version of user input for display purposes."""
|
|
316
|
+
# Check if input contains KODER.md content
|
|
317
|
+
if "KODER.md content:" in user_input:
|
|
318
|
+
lines = user_input.split("\n")
|
|
319
|
+
filtered_lines = []
|
|
320
|
+
skip_koder_content = False
|
|
321
|
+
|
|
322
|
+
for line in lines:
|
|
323
|
+
if "KODER.md content:" in line:
|
|
324
|
+
skip_koder_content = True
|
|
325
|
+
continue
|
|
326
|
+
elif skip_koder_content and line.startswith("User request:"):
|
|
327
|
+
skip_koder_content = False
|
|
328
|
+
filtered_lines.append(line)
|
|
329
|
+
elif not skip_koder_content:
|
|
330
|
+
filtered_lines.append(line)
|
|
331
|
+
|
|
332
|
+
return "\n".join(filtered_lines)
|
|
333
|
+
|
|
334
|
+
return user_input
|
|
335
|
+
|
|
336
|
+
def _filter_output(self, text: str) -> str:
|
|
337
|
+
"""Filter sensitive information from output."""
|
|
338
|
+
import re
|
|
339
|
+
|
|
340
|
+
# Filter API keys and tokens
|
|
341
|
+
text = re.sub(r"sk-\w{10,}", "[TOKEN]", text)
|
|
342
|
+
text = re.sub(
|
|
343
|
+
r"(api[_-]?key|token|secret)[\s:=]+[\w-]{10,}", "[REDACTED]", text, flags=re.IGNORECASE
|
|
344
|
+
)
|
|
345
|
+
return text
|
|
346
|
+
|
|
347
|
+
async def cleanup(self):
|
|
348
|
+
"""Clean up resources, including MCP servers."""
|
|
349
|
+
if self._mcp_servers:
|
|
350
|
+
for server in self._mcp_servers:
|
|
351
|
+
try:
|
|
352
|
+
await server.cleanup()
|
|
353
|
+
except Exception as e:
|
|
354
|
+
console.print(f"[dim red]Error disconnecting MCP server: {e}[/dim red]")
|
|
355
|
+
self._mcp_servers.clear()
|