forked from he-yufeng/CoreCoder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
270 lines (234 loc) · 9.59 KB
/
Copy pathcli.py
File metadata and controls
270 lines (234 loc) · 9.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
"""Interactive REPL - the user-facing terminal interface."""
import sys
import os
import argparse
from rich.console import Console
from rich.markdown import Markdown
from rich.panel import Panel
from prompt_toolkit import prompt as pt_prompt
from prompt_toolkit.history import FileHistory
from prompt_toolkit.key_binding import KeyBindings
from .agent import Agent
from .llm import LLM, LiteLLM
from .config import Config
from .session import save_session, load_session, list_sessions
from . import __version__
console = Console()
def _parse_args():
p = argparse.ArgumentParser(
prog="corecoder",
description="Minimal AI coding agent. Works with any OpenAI-compatible LLM.",
)
p.add_argument("-m", "--model", help="Model name (default: $CORECODER_MODEL or gpt-5.5)")
p.add_argument("--base-url", help="API base URL (default: $OPENAI_BASE_URL)")
p.add_argument("--api-key", help="API key (default: $OPENAI_API_KEY)")
p.add_argument("-p", "--prompt", help="One-shot prompt (non-interactive mode)")
p.add_argument("-r", "--resume", metavar="ID", help="Resume a saved session")
p.add_argument("-v", "--version", action="version", version=f"%(prog)s {__version__}")
return p.parse_args()
def main():
args = _parse_args()
config = Config.from_env()
# CLI args override env vars
if args.model:
config.model = args.model
if args.base_url:
config.base_url = args.base_url
if args.api_key:
config.api_key = args.api_key
if not config.api_key:
console.print("[red bold]No API key found.[/]")
console.print(
"Set one of: OPENAI_API_KEY, DEEPSEEK_API_KEY, or CORECODER_API_KEY\n"
"\nExamples:\n"
" # OpenAI\n"
" export OPENAI_API_KEY=sk-...\n"
"\n"
" # DeepSeek\n"
" export OPENAI_API_KEY=sk-... OPENAI_BASE_URL=https://api.deepseek.com\n"
"\n"
" # Ollama (local)\n"
" export OPENAI_API_KEY=ollama OPENAI_BASE_URL=http://localhost:11434/v1 CORECODER_MODEL=qwen2.5-coder\n"
)
sys.exit(1)
llm_cls = LiteLLM if config.provider == "litellm" else LLM
llm = llm_cls(
model=config.model,
api_key=config.api_key,
base_url=config.base_url,
temperature=config.temperature,
max_tokens=config.max_tokens,
)
agent = Agent(llm=llm, max_context_tokens=config.max_context_tokens)
# resume saved session
if args.resume:
loaded = load_session(args.resume)
if loaded:
agent.messages, loaded_model = loaded
# restore the model from the saved session unless overridden by CLI
if not args.model:
agent.llm.model = loaded_model
config.model = loaded_model
console.print(f"[green]Resumed session: {args.resume} (model: {agent.llm.model})[/green]")
else:
console.print(f"[red]Session '{args.resume}' not found.[/red]")
sys.exit(1)
# one-shot mode
if args.prompt:
_run_once(agent, args.prompt)
return
# interactive REPL
_repl(agent, config)
def _run_once(agent: Agent, prompt: str):
"""Non-interactive: run one prompt and exit."""
def on_token(tok):
print(tok, end="", flush=True)
def on_tool(name, kwargs):
console.print(f"\n[dim]> {name}({_brief(kwargs)})[/dim]")
try:
agent.chat(prompt, on_token=on_token, on_tool=on_tool)
except KeyboardInterrupt:
console.print("\n[yellow]Interrupted.[/yellow]")
sys.exit(130)
except Exception as e:
console.print(f"\n[red]Error: {e}[/red]")
sys.exit(1)
print()
def _repl(agent: Agent, config: Config):
"""Interactive read-eval-print loop."""
console.print(Panel(
f"[bold]CoreCoder[/bold] v{__version__}\n"
f"Model: [cyan]{config.model}[/cyan]"
+ (f" Base: [dim]{config.base_url}[/dim]" if config.base_url else "")
+ "\nType [bold]/help[/bold] for commands, [bold]Ctrl+C[/bold] to cancel, [bold]quit[/bold] to exit.",
border_style="blue",
))
hist_path = os.path.expanduser("~/.corecoder_history")
history = FileHistory(hist_path)
# Enter submits, Escape+Enter inserts a newline (for pasting code blocks etc.)
kb = KeyBindings()
@kb.add("enter")
def _submit(event):
event.current_buffer.validate_and_handle()
@kb.add("escape", "enter")
def _newline(event):
event.current_buffer.insert_text("\n")
while True:
try:
user_input = pt_prompt(
"You > ",
history=history,
multiline=True,
key_bindings=kb,
prompt_continuation="... ",
).strip()
except (EOFError, KeyboardInterrupt):
console.print("\nBye!")
break
if not user_input:
continue
# built-in commands
if user_input.lower() in ("quit", "exit", "/quit", "/exit"):
break
if user_input == "/help":
_show_help()
continue
if user_input == "/reset":
agent.reset()
console.print("[yellow]Conversation reset.[/yellow]")
continue
if user_input == "/tokens":
p = agent.llm.total_prompt_tokens
c = agent.llm.total_completion_tokens
line = f"Tokens: [cyan]{p}[/cyan] prompt + [cyan]{c}[/cyan] completion = [bold]{p+c}[/bold] total"
cost = agent.llm.estimated_cost
if cost is not None:
line += f" (~${cost:.4f})"
console.print(line)
continue
if user_input == "/model" or user_input.startswith("/model "):
new_model = user_input[7:].strip() if user_input.startswith("/model ") else ""
if new_model:
agent.llm.model = new_model
config.model = new_model
console.print(f"Switched to [cyan]{new_model}[/cyan]")
else:
console.print(f"Current model: [cyan]{config.model}[/cyan]")
continue
if user_input == "/compact":
from .context import estimate_tokens
before = estimate_tokens(agent.messages)
compressed = agent.context.maybe_compress(agent.messages, agent.llm)
after = estimate_tokens(agent.messages)
if compressed:
console.print(f"[green]Compressed: {before} → {after} tokens ({len(agent.messages)} messages)[/green]")
else:
console.print(f"[dim]Nothing to compress ({before} tokens, {len(agent.messages)} messages)[/dim]")
continue
if user_input == "/save":
sid = save_session(agent.messages, config.model)
console.print(f"[green]Session saved: {sid}[/green]")
console.print(f"Resume with: corecoder -r {sid}")
continue
if user_input == "/diff":
from .tools.edit import _changed_files
if not _changed_files:
console.print("[dim]No files modified this session.[/dim]")
else:
console.print(f"[bold]Files modified this session ({len(_changed_files)}):[/bold]")
for f in sorted(_changed_files):
console.print(f" [cyan]{f}[/cyan]")
continue
if user_input == "/sessions":
sessions = list_sessions()
if not sessions:
console.print("[dim]No saved sessions.[/dim]")
else:
for s in sessions:
console.print(f" [cyan]{s['id']}[/cyan] ({s['model']}, {s['saved_at']}) {s['preview']}")
continue
# an unknown /command shouldn't be sent to the model as a prompt
if user_input.startswith("/"):
console.print(f"[yellow]Unknown command: {user_input.split()[0]} (try /help)[/yellow]")
continue
# call the agent
streamed: list[str] = []
def on_token(tok):
streamed.append(tok)
print(tok, end="", flush=True)
def on_tool(name, kwargs):
console.print(f"\n[dim]> {name}({_brief(kwargs)})[/dim]")
try:
response = agent.chat(user_input, on_token=on_token, on_tool=on_tool)
if streamed:
print() # newline after streamed tokens
else:
# response wasn't streamed (came after tool calls)
console.print(Markdown(response))
except KeyboardInterrupt:
console.print("\n[yellow]Interrupted.[/yellow]")
except Exception as e:
console.print(f"\n[red]Error: {e}[/red]")
def _show_help():
console.print(Panel(
"[bold]Commands:[/bold]\n"
" /help Show this help\n"
" /reset Clear conversation history\n"
" /model Show current model\n"
" /model <name> Switch model mid-conversation\n"
" /tokens Show token usage\n"
" /compact Compress conversation context\n"
" /diff Show files modified this session\n"
" /save Save session to disk\n"
" /sessions List saved sessions\n"
" quit Exit CoreCoder\n"
"\n"
"[bold]Input:[/bold]\n"
" Enter Submit message\n"
" Esc+Enter Insert newline (for pasting code)",
title="CoreCoder Help",
border_style="dim",
))
def _brief(kwargs: dict, maxlen: int = 80) -> str:
s = ", ".join(f"{k}={repr(v)[:40]}" for k, v in kwargs.items())
return s[:maxlen] + ("..." if len(s) > maxlen else "")