koder 0.4.0__tar.gz → 0.4.1__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.4.1/.claude/settings.local.json +10 -0
- koder-0.4.1/CLAUDE.md +98 -0
- {koder-0.4.0 → koder-0.4.1}/PKG-INFO +1 -29
- {koder-0.4.0 → koder-0.4.1}/README.md +0 -28
- {koder-0.4.0 → koder-0.4.1}/koder_agent/agentic/agent.py +18 -5
- koder-0.4.1/koder_agent/agentic/hooks.py +106 -0
- {koder-0.4.0 → koder-0.4.1}/koder_agent/cli.py +13 -5
- {koder-0.4.0 → koder-0.4.1}/koder_agent/core/context.py +21 -28
- {koder-0.4.0 → koder-0.4.1}/koder_agent/core/scheduler.py +7 -1
- {koder-0.4.0 → koder-0.4.1}/koder_agent/core/status_line.py +3 -1
- {koder-0.4.0 → koder-0.4.1}/koder_agent/core/streaming_display.py +41 -17
- koder-0.4.1/koder_agent/tools/todo.py +86 -0
- {koder-0.4.0 → koder-0.4.1}/koder_agent/utils/client.py +50 -1
- {koder-0.4.0 → koder-0.4.1}/pyproject.toml +1 -1
- {koder-0.4.0 → koder-0.4.1}/uv.lock +2967 -2984
- koder-0.4.0/koder_agent/agentic/hooks.py +0 -73
- koder-0.4.0/koder_agent/tools/todo.py +0 -76
- {koder-0.4.0 → koder-0.4.1}/.github/dependabot.yml +0 -0
- {koder-0.4.0 → koder-0.4.1}/.gitignore +0 -0
- {koder-0.4.0 → koder-0.4.1}/AGENTS.md +0 -0
- {koder-0.4.0 → koder-0.4.1}/CONTRIBUTING.md +0 -0
- {koder-0.4.0 → koder-0.4.1}/LICENSE +0 -0
- {koder-0.4.0 → koder-0.4.1}/koder_agent/__init__.py +0 -0
- {koder-0.4.0 → koder-0.4.1}/koder_agent/agentic/__init__.py +0 -0
- {koder-0.4.0 → koder-0.4.1}/koder_agent/agentic/approval_hooks.py +0 -0
- {koder-0.4.0 → koder-0.4.1}/koder_agent/config/__init__.py +0 -0
- {koder-0.4.0 → koder-0.4.1}/koder_agent/config/cli_handler.py +0 -0
- {koder-0.4.0 → koder-0.4.1}/koder_agent/config/manager.py +0 -0
- {koder-0.4.0 → koder-0.4.1}/koder_agent/config/models.py +0 -0
- {koder-0.4.0 → koder-0.4.1}/koder_agent/core/__init__.py +0 -0
- {koder-0.4.0 → koder-0.4.1}/koder_agent/core/commands.py +0 -0
- {koder-0.4.0 → koder-0.4.1}/koder_agent/core/interactive.py +0 -0
- {koder-0.4.0 → koder-0.4.1}/koder_agent/core/security.py +0 -0
- {koder-0.4.0 → koder-0.4.1}/koder_agent/core/usage_tracker.py +0 -0
- {koder-0.4.0 → koder-0.4.1}/koder_agent/mcp/__init__.py +0 -0
- {koder-0.4.0 → koder-0.4.1}/koder_agent/mcp/cli_handler.py +0 -0
- {koder-0.4.0 → koder-0.4.1}/koder_agent/mcp/server_config.py +0 -0
- {koder-0.4.0 → koder-0.4.1}/koder_agent/mcp/server_factory.py +0 -0
- {koder-0.4.0 → koder-0.4.1}/koder_agent/mcp/server_manager.py +0 -0
- {koder-0.4.0 → koder-0.4.1}/koder_agent/tools/__init__.py +0 -0
- {koder-0.4.0 → koder-0.4.1}/koder_agent/tools/engine.py +0 -0
- {koder-0.4.0 → koder-0.4.1}/koder_agent/tools/file.py +0 -0
- {koder-0.4.0 → koder-0.4.1}/koder_agent/tools/search.py +0 -0
- {koder-0.4.0 → koder-0.4.1}/koder_agent/tools/shell.py +0 -0
- {koder-0.4.0 → koder-0.4.1}/koder_agent/tools/task.py +0 -0
- {koder-0.4.0 → koder-0.4.1}/koder_agent/tools/web.py +0 -0
- {koder-0.4.0 → koder-0.4.1}/koder_agent/utils/__init__.py +0 -0
- {koder-0.4.0 → koder-0.4.1}/koder_agent/utils/model_info.py +0 -0
- {koder-0.4.0 → koder-0.4.1}/koder_agent/utils/prompts.py +0 -0
- {koder-0.4.0 → koder-0.4.1}/koder_agent/utils/queue.py +0 -0
- {koder-0.4.0 → koder-0.4.1}/koder_agent/utils/sessions.py +0 -0
- {koder-0.4.0 → koder-0.4.1}/koder_agent/utils/terminal_theme.py +0 -0
- {koder-0.4.0 → koder-0.4.1}/scripts/upgrade_dependency.py +0 -0
- {koder-0.4.0 → koder-0.4.1}/tests/test_file_tools.py +0 -0
- {koder-0.4.0 → koder-0.4.1}/tests/test_shell_background.py +0 -0
- {koder-0.4.0 → koder-0.4.1}/tests/test_web.py +0 -0
koder-0.4.1/CLAUDE.md
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
# CLAUDE.md
|
|
2
|
+
|
|
3
|
+
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
|
4
|
+
|
|
5
|
+
## Commands
|
|
6
|
+
|
|
7
|
+
### Development Setup
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
# Install dependencies
|
|
11
|
+
uv sync
|
|
12
|
+
|
|
13
|
+
# Run the CLI in development
|
|
14
|
+
uv run koder
|
|
15
|
+
|
|
16
|
+
# Run with a single prompt
|
|
17
|
+
uv run koder "Your prompt here"
|
|
18
|
+
|
|
19
|
+
# Run with specific session
|
|
20
|
+
uv run koder --session my-session "Your prompt"
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
### Code Quality
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
# Code formatting
|
|
27
|
+
black .
|
|
28
|
+
|
|
29
|
+
# Linting with auto-fix
|
|
30
|
+
ruff check --fix
|
|
31
|
+
|
|
32
|
+
# Error-only pylint check
|
|
33
|
+
pylint koder_agent/ --disable=C,R,W --errors-only
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
### Testing
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
# Run all tests
|
|
40
|
+
pytest
|
|
41
|
+
|
|
42
|
+
# Run a single test file
|
|
43
|
+
pytest tests/test_file_tools.py
|
|
44
|
+
|
|
45
|
+
# Run with verbose output
|
|
46
|
+
pytest -v
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Architecture
|
|
50
|
+
|
|
51
|
+
Koder is a terminal-based AI coding assistant built on the `openai-agents` library with multi-provider support via LiteLLM.
|
|
52
|
+
|
|
53
|
+
### Package Structure
|
|
54
|
+
|
|
55
|
+
```
|
|
56
|
+
koder_agent/
|
|
57
|
+
├── agentic/ # Agent creation, hooks, and approval system
|
|
58
|
+
├── cli.py # Main CLI entry point
|
|
59
|
+
├── config/ # Configuration management (YAML, env vars)
|
|
60
|
+
├── core/ # Scheduler, context, streaming, security, commands
|
|
61
|
+
├── mcp/ # Model Context Protocol server integration
|
|
62
|
+
├── tools/ # Tool implementations (file, search, shell, web, task, todo)
|
|
63
|
+
└── utils/ # Helpers (client setup, prompts, sessions, model info)
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### Core Flow
|
|
67
|
+
|
|
68
|
+
1. **CLI Entry** (`cli.py`) → parses args, initializes session
|
|
69
|
+
2. **AgentScheduler** (`core/scheduler.py`) → orchestrates agent execution with streaming
|
|
70
|
+
3. **Agent Creation** (`agentic/agent.py`) → builds agent with tools, MCP servers, model settings
|
|
71
|
+
4. **Tool Engine** (`tools/engine.py`) → registers tools, validates inputs, filters sensitive output
|
|
72
|
+
5. **Context Manager** (`core/context.py`) → persists conversations in SQLite with token-aware compression
|
|
73
|
+
|
|
74
|
+
### Key Design Patterns
|
|
75
|
+
|
|
76
|
+
- **Provider Abstraction**: `utils/client.py` detects providers from environment and configures either native OpenAI client or LiteLLM wrapper
|
|
77
|
+
- **Streaming Display**: `core/streaming_display.py` manages Rich Live displays for real-time output
|
|
78
|
+
- **Approval Hooks**: `agentic/approval_hooks.py` wraps tool execution with permission checks
|
|
79
|
+
- **Security Guard**: `core/security.py` validates shell commands before execution
|
|
80
|
+
|
|
81
|
+
### Configuration Priority
|
|
82
|
+
|
|
83
|
+
CLI Arguments > Environment Variables > Config File (`~/.koder/config.yaml`) > Defaults
|
|
84
|
+
|
|
85
|
+
Key environment variables:
|
|
86
|
+
- `KODER_MODEL` - Model name (e.g., `gpt-4o`, `claude-opus-4-20250514`)
|
|
87
|
+
- Provider API keys: `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, `GOOGLE_API_KEY`, etc.
|
|
88
|
+
|
|
89
|
+
### Database
|
|
90
|
+
|
|
91
|
+
SQLite at `~/.koder/koder.db` stores:
|
|
92
|
+
- Conversation history with token-aware compression (50k limit)
|
|
93
|
+
- Session metadata
|
|
94
|
+
- MCP server configurations
|
|
95
|
+
|
|
96
|
+
### Project Context
|
|
97
|
+
|
|
98
|
+
The CLI loads `AGENTS.md` from the working directory as project-specific context for the agent.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: koder
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.1
|
|
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
|
Project-URL: Homepage, https://github.com/feiskyer/koder
|
|
6
6
|
Project-URL: Repository, https://github.com/feiskyer/koder
|
|
@@ -118,27 +118,6 @@ koder
|
|
|
118
118
|
|
|
119
119
|
Koder uses a YAML config file at `~/.koder/config.yaml` for persistent settings.
|
|
120
120
|
|
|
121
|
-
#### Config CLI Commands
|
|
122
|
-
|
|
123
|
-
```bash
|
|
124
|
-
# Initialize config file with defaults
|
|
125
|
-
koder config init
|
|
126
|
-
|
|
127
|
-
# Show current configuration
|
|
128
|
-
koder config show
|
|
129
|
-
|
|
130
|
-
# Show config file path
|
|
131
|
-
koder config path
|
|
132
|
-
|
|
133
|
-
# Open config file in editor (respects $EDITOR)
|
|
134
|
-
koder config edit
|
|
135
|
-
|
|
136
|
-
# Set specific values (supports dot notation)
|
|
137
|
-
koder config set model.name gpt-4o
|
|
138
|
-
koder config set model.provider anthropic
|
|
139
|
-
koder config set cli.stream false
|
|
140
|
-
```
|
|
141
|
-
|
|
142
121
|
#### Config File Format
|
|
143
122
|
|
|
144
123
|
```yaml
|
|
@@ -151,13 +130,6 @@ model:
|
|
|
151
130
|
api_key: null # API key (prefer env vars for security)
|
|
152
131
|
base_url: null # Custom API endpoint (optional)
|
|
153
132
|
|
|
154
|
-
# Azure-specific settings
|
|
155
|
-
azure_api_version: null # e.g., "2025-04-01-preview"
|
|
156
|
-
|
|
157
|
-
# Vertex AI-specific settings
|
|
158
|
-
vertex_ai_location: null # e.g., "us-central1"
|
|
159
|
-
vertex_ai_credentials_path: null # Path to service account JSON
|
|
160
|
-
|
|
161
133
|
# Reasoning effort for OpenAI reasoning models (o1, o3, gpt-5.1, etc.)
|
|
162
134
|
reasoning_effort: "medium" # none, minimal, low, medium, high, or null
|
|
163
135
|
|
|
@@ -83,27 +83,6 @@ koder
|
|
|
83
83
|
|
|
84
84
|
Koder uses a YAML config file at `~/.koder/config.yaml` for persistent settings.
|
|
85
85
|
|
|
86
|
-
#### Config CLI Commands
|
|
87
|
-
|
|
88
|
-
```bash
|
|
89
|
-
# Initialize config file with defaults
|
|
90
|
-
koder config init
|
|
91
|
-
|
|
92
|
-
# Show current configuration
|
|
93
|
-
koder config show
|
|
94
|
-
|
|
95
|
-
# Show config file path
|
|
96
|
-
koder config path
|
|
97
|
-
|
|
98
|
-
# Open config file in editor (respects $EDITOR)
|
|
99
|
-
koder config edit
|
|
100
|
-
|
|
101
|
-
# Set specific values (supports dot notation)
|
|
102
|
-
koder config set model.name gpt-4o
|
|
103
|
-
koder config set model.provider anthropic
|
|
104
|
-
koder config set cli.stream false
|
|
105
|
-
```
|
|
106
|
-
|
|
107
86
|
#### Config File Format
|
|
108
87
|
|
|
109
88
|
```yaml
|
|
@@ -116,13 +95,6 @@ model:
|
|
|
116
95
|
api_key: null # API key (prefer env vars for security)
|
|
117
96
|
base_url: null # Custom API endpoint (optional)
|
|
118
97
|
|
|
119
|
-
# Azure-specific settings
|
|
120
|
-
azure_api_version: null # e.g., "2025-04-01-preview"
|
|
121
|
-
|
|
122
|
-
# Vertex AI-specific settings
|
|
123
|
-
vertex_ai_location: null # e.g., "us-central1"
|
|
124
|
-
vertex_ai_credentials_path: null # Path to service account JSON
|
|
125
|
-
|
|
126
98
|
# Reasoning effort for OpenAI reasoning models (o1, o3, gpt-5.1, etc.)
|
|
127
99
|
reasoning_effort: "medium" # none, minimal, low, medium, high, or null
|
|
128
100
|
|
|
@@ -4,12 +4,13 @@ import logging
|
|
|
4
4
|
import uuid
|
|
5
5
|
|
|
6
6
|
from agents import Agent, ModelSettings
|
|
7
|
+
from agents.extensions.models.litellm_model import LitellmModel
|
|
7
8
|
from openai.types.shared import Reasoning
|
|
8
9
|
from rich.console import Console
|
|
9
10
|
|
|
10
11
|
from ..config import get_config
|
|
11
12
|
from ..mcp import load_mcp_servers
|
|
12
|
-
from ..utils.client import get_model_name
|
|
13
|
+
from ..utils.client import get_litellm_model_kwargs, get_model_name, is_native_openai_provider
|
|
13
14
|
from ..utils.model_info import get_maximum_output_tokens
|
|
14
15
|
from ..utils.prompts import KODER_SYSTEM_PROMPT
|
|
15
16
|
|
|
@@ -19,13 +20,25 @@ logger = logging.getLogger(__name__)
|
|
|
19
20
|
|
|
20
21
|
async def create_dev_agent(tools) -> Agent:
|
|
21
22
|
"""Create the main development agent with MCP servers."""
|
|
22
|
-
# Get the appropriate model based on environment
|
|
23
|
-
model = get_model_name()
|
|
24
23
|
config = get_config()
|
|
25
24
|
mcp_servers = await load_mcp_servers()
|
|
26
25
|
|
|
26
|
+
# Determine the model to use: native OpenAI string or LitellmModel instance
|
|
27
|
+
if is_native_openai_provider():
|
|
28
|
+
# Use string model name for native OpenAI providers (handled by default client)
|
|
29
|
+
model = get_model_name()
|
|
30
|
+
else:
|
|
31
|
+
# Use LitellmModel with explicit base_url and api_key for all other providers
|
|
32
|
+
litellm_kwargs = get_litellm_model_kwargs()
|
|
33
|
+
model = LitellmModel(
|
|
34
|
+
model=litellm_kwargs["model"],
|
|
35
|
+
base_url=litellm_kwargs["base_url"],
|
|
36
|
+
api_key=litellm_kwargs["api_key"],
|
|
37
|
+
)
|
|
38
|
+
|
|
27
39
|
# Build model_settings with reasoning if configured
|
|
28
|
-
|
|
40
|
+
model_name_str = get_model_name() # Always get string name for max_tokens lookup
|
|
41
|
+
model_settings = ModelSettings(max_tokens=get_maximum_output_tokens(model_name_str))
|
|
29
42
|
if config.model.reasoning_effort is not None:
|
|
30
43
|
model_settings.reasoning = Reasoning(effort=config.model.reasoning_effort)
|
|
31
44
|
|
|
@@ -38,7 +51,7 @@ async def create_dev_agent(tools) -> Agent:
|
|
|
38
51
|
model_settings=model_settings,
|
|
39
52
|
)
|
|
40
53
|
|
|
41
|
-
if "github_copilot" in
|
|
54
|
+
if "github_copilot" in model_name_str:
|
|
42
55
|
dev_agent.model_settings.extra_headers = {
|
|
43
56
|
"copilot-integration-id": "vscode-chat",
|
|
44
57
|
"editor-version": "vscode/1.98.1",
|
|
@@ -0,0 +1,106 @@
|
|
|
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.text import Text
|
|
11
|
+
|
|
12
|
+
console = Console()
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _truncate_agent_name(name: str, max_len: int = 40) -> str:
|
|
16
|
+
"""Truncate agent name if it's too long."""
|
|
17
|
+
if len(name) <= max_len:
|
|
18
|
+
return name
|
|
19
|
+
return name[: max_len - 3] + "..."
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class ToolDisplayHooks(RunHooks):
|
|
23
|
+
"""RunHooks implementation to display tool input/output with rich formatting."""
|
|
24
|
+
|
|
25
|
+
def __init__(self, streaming_mode: bool = False):
|
|
26
|
+
self.streaming_mode = streaming_mode
|
|
27
|
+
|
|
28
|
+
async def on_agent_start(self, context: RunContextWrapper, agent: Agent) -> None:
|
|
29
|
+
"""Called before the agent is invoked. Called each time the current agent changes."""
|
|
30
|
+
if self.streaming_mode:
|
|
31
|
+
# In streaming mode, don't print to avoid conflicts
|
|
32
|
+
return
|
|
33
|
+
|
|
34
|
+
# Use simple bullet-point style consistent with streaming_display.py
|
|
35
|
+
agent_text = Text()
|
|
36
|
+
agent_text.append("● ", style="green")
|
|
37
|
+
agent_text.append("Agent: ", style="bold cyan")
|
|
38
|
+
agent_text.append(_truncate_agent_name(agent.name), style="cyan")
|
|
39
|
+
console.print(agent_text)
|
|
40
|
+
|
|
41
|
+
async def on_tool_start(self, context: RunContextWrapper, agent: Agent, tool: Tool) -> None:
|
|
42
|
+
"""Display tool execution start."""
|
|
43
|
+
# Don't print on tool start - wait for tool end to print both name and result together
|
|
44
|
+
# This ensures tool name and result are always paired even with parallel execution
|
|
45
|
+
pass
|
|
46
|
+
|
|
47
|
+
async def on_tool_end(
|
|
48
|
+
self, context: RunContextWrapper, agent: Agent, tool: Tool, result: str
|
|
49
|
+
) -> None:
|
|
50
|
+
"""Display tool execution result."""
|
|
51
|
+
if self.streaming_mode:
|
|
52
|
+
# In streaming mode, don't print to avoid conflicts
|
|
53
|
+
return
|
|
54
|
+
|
|
55
|
+
# Print tool name and result together to ensure they're always paired
|
|
56
|
+
tool_text = Text()
|
|
57
|
+
tool_text.append("● ", style="green")
|
|
58
|
+
tool_text.append(tool.name, style="bold cyan")
|
|
59
|
+
console.print(tool_text)
|
|
60
|
+
|
|
61
|
+
# Show tool output with arrow style consistent with streaming_display.py
|
|
62
|
+
display_result = str(result).strip()
|
|
63
|
+
if len(display_result) > 200:
|
|
64
|
+
display_result = display_result[:200] + "..."
|
|
65
|
+
|
|
66
|
+
# Determine if this is an error output
|
|
67
|
+
is_error = _is_error_output(display_result)
|
|
68
|
+
style = "red" if is_error else "dim green"
|
|
69
|
+
arrow_style = "red" if is_error else "dim green"
|
|
70
|
+
|
|
71
|
+
output_text = Text()
|
|
72
|
+
output_text.append(" ╰─ ", style=arrow_style)
|
|
73
|
+
output_text.append(display_result, style=style)
|
|
74
|
+
console.print(output_text)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _is_error_output(output: str) -> bool:
|
|
78
|
+
"""Check if the output indicates an error."""
|
|
79
|
+
if not output:
|
|
80
|
+
return False
|
|
81
|
+
|
|
82
|
+
error_indicators = [
|
|
83
|
+
"error:",
|
|
84
|
+
"Error:",
|
|
85
|
+
"ERROR:",
|
|
86
|
+
"failed:",
|
|
87
|
+
"Failed:",
|
|
88
|
+
"FAILED:",
|
|
89
|
+
"exception:",
|
|
90
|
+
"Exception:",
|
|
91
|
+
"traceback",
|
|
92
|
+
"Traceback",
|
|
93
|
+
"not found",
|
|
94
|
+
"Not found",
|
|
95
|
+
"permission denied",
|
|
96
|
+
"Permission denied",
|
|
97
|
+
"No such file",
|
|
98
|
+
"fatal:",
|
|
99
|
+
]
|
|
100
|
+
|
|
101
|
+
return any(indicator in output for indicator in error_indicators)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def get_display_hooks(streaming_mode: bool = False) -> RunHooks:
|
|
105
|
+
"""Get the display hooks instance."""
|
|
106
|
+
return ToolDisplayHooks(streaming_mode=streaming_mode)
|
|
@@ -346,7 +346,14 @@ async def main():
|
|
|
346
346
|
pass
|
|
347
347
|
scheduler._title_generation_task = None
|
|
348
348
|
finally:
|
|
349
|
-
|
|
349
|
+
try:
|
|
350
|
+
await scheduler.cleanup()
|
|
351
|
+
except (asyncio.CancelledError, KeyboardInterrupt, EOFError):
|
|
352
|
+
# Silently ignore interruption during cleanup
|
|
353
|
+
pass
|
|
354
|
+
except Exception:
|
|
355
|
+
# Ignore other cleanup errors on exit
|
|
356
|
+
pass
|
|
350
357
|
|
|
351
358
|
return 0
|
|
352
359
|
|
|
@@ -356,11 +363,12 @@ def run():
|
|
|
356
363
|
try:
|
|
357
364
|
exit_code = asyncio.run(main())
|
|
358
365
|
exit(exit_code)
|
|
359
|
-
except KeyboardInterrupt:
|
|
360
|
-
|
|
361
|
-
Panel("[yellow]Interrupted![/yellow]", title="Interruption", border_style="yellow")
|
|
362
|
-
)
|
|
366
|
+
except (KeyboardInterrupt, EOFError, asyncio.CancelledError):
|
|
367
|
+
# Silently exit on Ctrl+C, Ctrl+D, or task cancellation
|
|
363
368
|
exit(0)
|
|
369
|
+
except SystemExit:
|
|
370
|
+
# Re-raise SystemExit to allow normal exit
|
|
371
|
+
raise
|
|
364
372
|
except Exception as e:
|
|
365
373
|
console.print(
|
|
366
374
|
Panel(f"[red]Fatal error: {e}[/red]", title="Fatal Error", border_style="red")
|
|
@@ -20,7 +20,6 @@ class ContextManager:
|
|
|
20
20
|
db_path: Optional[str] = None,
|
|
21
21
|
):
|
|
22
22
|
self.session_id = session_id
|
|
23
|
-
self._cached_token_count = 0 # Cached token count for status line
|
|
24
23
|
if db_path is None:
|
|
25
24
|
# Use $HOME/.koder/koder.db as default
|
|
26
25
|
home_dir = os.path.expanduser("~")
|
|
@@ -45,10 +44,6 @@ class ContextManager:
|
|
|
45
44
|
|
|
46
45
|
self.encoder = _NaiveEncoder()
|
|
47
46
|
|
|
48
|
-
def get_cached_token_count(self) -> int:
|
|
49
|
-
"""Get the cached token count (updated after load/save operations)."""
|
|
50
|
-
return self._cached_token_count
|
|
51
|
-
|
|
52
47
|
async def _ensure_table(self, conn: aiosqlite.Connection) -> None:
|
|
53
48
|
"""Ensure the context table exists with all columns."""
|
|
54
49
|
await conn.execute(
|
|
@@ -132,32 +127,30 @@ class ContextManager:
|
|
|
132
127
|
)
|
|
133
128
|
row = await cursor.fetchone()
|
|
134
129
|
if row and row[0]:
|
|
135
|
-
|
|
136
|
-
# Update cached token count
|
|
137
|
-
self._cached_token_count = self._estimate_tokens(messages)
|
|
138
|
-
return messages
|
|
139
|
-
self._cached_token_count = 0
|
|
130
|
+
return json.loads(row[0])
|
|
140
131
|
return []
|
|
141
132
|
except Exception as e:
|
|
142
133
|
print(f"Error loading context: {e}")
|
|
143
|
-
self._cached_token_count = 0
|
|
144
134
|
return []
|
|
145
135
|
|
|
146
|
-
async def save(
|
|
147
|
-
|
|
136
|
+
async def save(
|
|
137
|
+
self, messages: List[Dict[str, str]], current_token_count: int | None = None
|
|
138
|
+
) -> None:
|
|
139
|
+
"""Save conversation history to database, with summarization if needed.
|
|
140
|
+
|
|
141
|
+
Args:
|
|
142
|
+
messages: List of message dictionaries to save
|
|
143
|
+
current_token_count: Actual token count from API response.
|
|
144
|
+
If None (first chat), skip summarization.
|
|
145
|
+
"""
|
|
148
146
|
try:
|
|
149
147
|
# Check token count and summarize if needed
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
# Recalculate tokens after summarization
|
|
157
|
-
total_tokens = self._estimate_tokens(messages)
|
|
158
|
-
|
|
159
|
-
# Update cached token count
|
|
160
|
-
self._cached_token_count = total_tokens
|
|
148
|
+
# Skip summarization if no token count provided (first chat)
|
|
149
|
+
if current_token_count is not None:
|
|
150
|
+
model = get_model_name()
|
|
151
|
+
threshold = get_summarization_threshold(model)
|
|
152
|
+
if current_token_count > threshold:
|
|
153
|
+
messages = await self._summarize_messages(messages, current_token_count, model)
|
|
161
154
|
|
|
162
155
|
async with aiosqlite.connect(self.db_path) as conn:
|
|
163
156
|
await self._ensure_table(conn)
|
|
@@ -172,7 +165,7 @@ class ContextManager:
|
|
|
172
165
|
print(f"Error saving context: {e}")
|
|
173
166
|
|
|
174
167
|
async def _summarize_messages(
|
|
175
|
-
self, messages: List[Dict[str, str]],
|
|
168
|
+
self, messages: List[Dict[str, str]], current_tokens: int, model: str
|
|
176
169
|
) -> List[Dict[str, str]]:
|
|
177
170
|
"""
|
|
178
171
|
Summarize message history using LLM when tokens exceed threshold.
|
|
@@ -184,7 +177,7 @@ class ContextManager:
|
|
|
184
177
|
|
|
185
178
|
Args:
|
|
186
179
|
messages: Original message list
|
|
187
|
-
|
|
180
|
+
current_tokens: Current token count (from API or estimated)
|
|
188
181
|
model: Model name for context window calculation
|
|
189
182
|
|
|
190
183
|
Returns:
|
|
@@ -194,7 +187,7 @@ class ContextManager:
|
|
|
194
187
|
context_window = get_context_window_size(model)
|
|
195
188
|
|
|
196
189
|
print(
|
|
197
|
-
f"\n[Context] Token
|
|
190
|
+
f"\n[Context] Token count: {current_tokens}/{context_window} (threshold: {threshold})"
|
|
198
191
|
)
|
|
199
192
|
print("[Context] Triggering message history summarization...")
|
|
200
193
|
|
|
@@ -241,7 +234,7 @@ class ContextManager:
|
|
|
241
234
|
|
|
242
235
|
# Calculate new token count
|
|
243
236
|
new_tokens = self._estimate_tokens(new_messages)
|
|
244
|
-
print(f"[Context] Summary completed: {
|
|
237
|
+
print(f"[Context] Summary completed: {current_tokens} -> {new_tokens} tokens")
|
|
245
238
|
print(
|
|
246
239
|
f"[Context] Structure: system + {len(user_indices)} user messages + {summary_count} summaries"
|
|
247
240
|
)
|
|
@@ -155,12 +155,15 @@ class AgentScheduler:
|
|
|
155
155
|
return response
|
|
156
156
|
|
|
157
157
|
# Save conversation to context
|
|
158
|
+
# Pass actual token count from API response (if available) instead of estimation
|
|
159
|
+
current_token_count = self.usage_tracker.session_usage.last_input_tokens or None
|
|
158
160
|
await self.context_manager.save(
|
|
159
161
|
history
|
|
160
162
|
+ [
|
|
161
163
|
{"role": "user", "content": user_input},
|
|
162
164
|
{"role": "assistant", "content": response},
|
|
163
|
-
]
|
|
165
|
+
],
|
|
166
|
+
current_token_count=current_token_count,
|
|
164
167
|
)
|
|
165
168
|
|
|
166
169
|
return response
|
|
@@ -412,6 +415,9 @@ class AgentScheduler:
|
|
|
412
415
|
usage = result.context_wrapper.usage
|
|
413
416
|
input_tokens = getattr(usage, "input_tokens", 0) or 0
|
|
414
417
|
output_tokens = getattr(usage, "output_tokens", 0) or 0
|
|
418
|
+
# console.print(
|
|
419
|
+
# f"[dim][Usage] input={input_tokens}, output={output_tokens}[/dim]"
|
|
420
|
+
# )
|
|
415
421
|
if input_tokens > 0 or output_tokens > 0:
|
|
416
422
|
self.usage_tracker.record_usage(input_tokens, output_tokens)
|
|
417
423
|
except Exception:
|
|
@@ -87,7 +87,9 @@ class StatusLine:
|
|
|
87
87
|
usage = self.usage_tracker.session_usage
|
|
88
88
|
cost_str = f"${usage.total_cost:.4f}"
|
|
89
89
|
|
|
90
|
-
# Context window usage:
|
|
90
|
+
# Context window usage: use last_input_tokens from the most recent Runner.run() call
|
|
91
|
+
# Since Koder sends full conversation history each time, last_input_tokens
|
|
92
|
+
# represents the current context size (not cumulative across calls)
|
|
91
93
|
current_tokens = usage.last_input_tokens
|
|
92
94
|
max_context = get_context_window_size(model)
|
|
93
95
|
context_pct = (current_tokens / max_context * 100) if max_context > 0 else 0
|
|
@@ -146,14 +146,13 @@ class StreamingDisplayManager:
|
|
|
146
146
|
actual_call_id = call_id
|
|
147
147
|
|
|
148
148
|
# Try multiple ways to extract output
|
|
149
|
-
if hasattr(tool_output_item, "output"):
|
|
149
|
+
if hasattr(tool_output_item, "output") and tool_output_item.output:
|
|
150
150
|
output = str(tool_output_item.output)
|
|
151
|
-
|
|
152
|
-
if hasattr(tool_output_item.raw_item, "output"):
|
|
151
|
+
if not output and hasattr(tool_output_item, "raw_item"):
|
|
152
|
+
if hasattr(tool_output_item.raw_item, "output") and tool_output_item.raw_item.output:
|
|
153
153
|
output = str(tool_output_item.raw_item.output)
|
|
154
|
-
elif (
|
|
155
|
-
|
|
156
|
-
and "output" in tool_output_item.raw_item
|
|
154
|
+
elif isinstance(tool_output_item.raw_item, dict) and tool_output_item.raw_item.get(
|
|
155
|
+
"output"
|
|
157
156
|
):
|
|
158
157
|
output = str(tool_output_item.raw_item["output"])
|
|
159
158
|
|
|
@@ -194,12 +193,12 @@ class StreamingDisplayManager:
|
|
|
194
193
|
tracker = t
|
|
195
194
|
break
|
|
196
195
|
|
|
196
|
+
# Find the position of the corresponding tool call section
|
|
197
|
+
tool_call_index = -1
|
|
197
198
|
if tracker:
|
|
198
199
|
tracker.output = output
|
|
199
200
|
tracker.completed = True
|
|
200
201
|
|
|
201
|
-
# Find the position of the corresponding tool call section
|
|
202
|
-
tool_call_index = -1
|
|
203
202
|
for i, section in enumerate(self.sections):
|
|
204
203
|
if (
|
|
205
204
|
section.type == OutputType.TOOL_CALL
|
|
@@ -210,7 +209,8 @@ class StreamingDisplayManager:
|
|
|
210
209
|
tool_call_index = i
|
|
211
210
|
break
|
|
212
211
|
|
|
213
|
-
|
|
212
|
+
# Create tool output section (even if tracker not found, still show output)
|
|
213
|
+
if output or tracker:
|
|
214
214
|
output_section = OutputSection(
|
|
215
215
|
type=OutputType.TOOL_OUTPUT, content=output, tool_tracker=tracker, complete=True
|
|
216
216
|
)
|
|
@@ -287,9 +287,10 @@ class StreamingDisplayManager:
|
|
|
287
287
|
renderables.append(tool_text)
|
|
288
288
|
|
|
289
289
|
elif section.type == OutputType.TOOL_OUTPUT:
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
290
|
+
# Get tool name for summary generation
|
|
291
|
+
tool_name = section.tool_tracker.tool_name if section.tool_tracker else "unknown"
|
|
292
|
+
|
|
293
|
+
if section.content:
|
|
293
294
|
summary = self._generate_smart_summary(tool_name, section.content)
|
|
294
295
|
is_error = self._is_error_output(section.content, tool_name)
|
|
295
296
|
|
|
@@ -301,6 +302,12 @@ class StreamingDisplayManager:
|
|
|
301
302
|
style = "dim green"
|
|
302
303
|
arrow_style = "dim green"
|
|
303
304
|
|
|
305
|
+
# Fallback to truncated content if no summary
|
|
306
|
+
if not summary:
|
|
307
|
+
summary = section.content.strip()[:80]
|
|
308
|
+
if len(section.content.strip()) > 80:
|
|
309
|
+
summary += "..."
|
|
310
|
+
|
|
304
311
|
if summary:
|
|
305
312
|
# Handle multi-line output with proper alignment
|
|
306
313
|
summary_lines = summary.split("\n")
|
|
@@ -320,11 +327,15 @@ class StreamingDisplayManager:
|
|
|
320
327
|
renderables.append(output_text)
|
|
321
328
|
|
|
322
329
|
# Show file diff if this is a file update
|
|
323
|
-
diff_content = self._extract_diff_content(
|
|
324
|
-
section.tool_tracker.tool_name, section.content
|
|
325
|
-
)
|
|
330
|
+
diff_content = self._extract_diff_content(tool_name, section.content)
|
|
326
331
|
if diff_content:
|
|
327
332
|
renderables.extend(diff_content)
|
|
333
|
+
else:
|
|
334
|
+
# Empty content - show a placeholder
|
|
335
|
+
output_text = Text()
|
|
336
|
+
output_text.append(" ╰─ ", style="dim green")
|
|
337
|
+
output_text.append("(no output)", style="dim")
|
|
338
|
+
renderables.append(output_text)
|
|
328
339
|
|
|
329
340
|
# Return a Group for proper rendering
|
|
330
341
|
if renderables:
|
|
@@ -711,13 +722,26 @@ class StreamingDisplayManager:
|
|
|
711
722
|
else:
|
|
712
723
|
return clean_output[:60] + ("..." if len(clean_output) > 60 else "")
|
|
713
724
|
|
|
714
|
-
# Handle todo_write
|
|
725
|
+
# Handle todo_write - show full todo list with emoji
|
|
715
726
|
elif tool_name == "todo_write":
|
|
716
|
-
if "
|
|
727
|
+
if "Todo list cleared" in clean_output:
|
|
728
|
+
return "Todo list cleared."
|
|
729
|
+
elif clean_output.strip():
|
|
730
|
+
# Return the full todo list for display (with emoji indicators)
|
|
717
731
|
return clean_output
|
|
718
732
|
else:
|
|
719
733
|
return "Todos updated"
|
|
720
734
|
|
|
735
|
+
# Handle todo_read - show all todos for visibility
|
|
736
|
+
elif tool_name == "todo_read":
|
|
737
|
+
if "No todos found" in clean_output:
|
|
738
|
+
return "No todos found. The list is empty."
|
|
739
|
+
elif clean_output.strip():
|
|
740
|
+
# Return the full todo list for display (with emoji indicators)
|
|
741
|
+
return clean_output
|
|
742
|
+
else:
|
|
743
|
+
return "No todos found."
|
|
744
|
+
|
|
721
745
|
# Default case
|
|
722
746
|
else:
|
|
723
747
|
if len(clean_output) <= 80:
|