agentcode-cli 1.0.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.
- agent.py +442 -0
- agentcode_cli-1.0.0.dist-info/METADATA +303 -0
- agentcode_cli-1.0.0.dist-info/RECORD +12 -0
- agentcode_cli-1.0.0.dist-info/WHEEL +5 -0
- agentcode_cli-1.0.0.dist-info/entry_points.txt +2 -0
- agentcode_cli-1.0.0.dist-info/licenses/LICENSE +21 -0
- agentcode_cli-1.0.0.dist-info/top_level.txt +6 -0
- cli.py +627 -0
- mcp_client.py +194 -0
- router.py +298 -0
- settings.py +185 -0
- tools.py +672 -0
cli.py
ADDED
|
@@ -0,0 +1,627 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
AgentCode — an open, multi-model agentic coding CLI.
|
|
4
|
+
|
|
5
|
+
Usage:
|
|
6
|
+
agentcode # Interactive REPL
|
|
7
|
+
agentcode "fix the bug" # One-shot mode
|
|
8
|
+
agentcode --model gpt-4o # Use a different model
|
|
9
|
+
agentcode --no-route # Disable cost-aware routing
|
|
10
|
+
|
|
11
|
+
Supported models (via LiteLLM):
|
|
12
|
+
claude-sonnet-4-6 # Anthropic Claude (default)
|
|
13
|
+
gpt-4o # OpenAI
|
|
14
|
+
gemini/gemini-2.5-pro # Google
|
|
15
|
+
... and 100+ more: https://docs.litellm.ai/docs/providers
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import os
|
|
19
|
+
import sys
|
|
20
|
+
import argparse
|
|
21
|
+
|
|
22
|
+
from dotenv import load_dotenv
|
|
23
|
+
load_dotenv()
|
|
24
|
+
|
|
25
|
+
from rich.console import Console
|
|
26
|
+
from rich.text import Text
|
|
27
|
+
from rich.theme import Theme
|
|
28
|
+
|
|
29
|
+
from agent import (
|
|
30
|
+
AgentConfig, Conversation, run_agent_loop,
|
|
31
|
+
load_project_config, build_system_prompt,
|
|
32
|
+
)
|
|
33
|
+
from router import ModelRouter
|
|
34
|
+
from mcp_client import create_mcp_manager
|
|
35
|
+
from settings import (
|
|
36
|
+
load_settings, generate_starter_settings, settings_sources, SETTINGS_HELP,
|
|
37
|
+
)
|
|
38
|
+
from tools import configure_limits
|
|
39
|
+
|
|
40
|
+
# ── Theme ─────────────────────────────────────────────────────────────────────
|
|
41
|
+
|
|
42
|
+
custom_theme = Theme({
|
|
43
|
+
"info": "cyan",
|
|
44
|
+
"warning": "yellow",
|
|
45
|
+
"error": "bold red",
|
|
46
|
+
"success": "bold green",
|
|
47
|
+
"prompt": "bold magenta",
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
console = Console(theme=custom_theme)
|
|
51
|
+
|
|
52
|
+
# ── Banner ────────────────────────────────────────────────────────────────────
|
|
53
|
+
|
|
54
|
+
BANNER = r"""
|
|
55
|
+
___ __ ______ __
|
|
56
|
+
/ _ | ___ ____ ___ ___/ /_/ ___/__ ___/ /__
|
|
57
|
+
/ __ |/ _ `/ -_) _ \/ __/ __/ /__/ _ \/ _ / -_)
|
|
58
|
+
/_/ |_|\_, /\__/_//_/\__/\__/\___/\___/\_,_/\__/
|
|
59
|
+
/___/
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def show_banner(config: AgentConfig, project_config: dict | None = None):
|
|
64
|
+
console.print(Text(BANNER, style="bold cyan"))
|
|
65
|
+
console.print(f" [dim]Model:[/dim] [bold]{config.model}[/bold]")
|
|
66
|
+
console.print(f" [dim]Dir:[/dim] [bold]{config.project_dir}[/bold]")
|
|
67
|
+
console.print(f" [dim]Safety:[/dim] [bold]{'auto-approve' if config.auto_approve else 'ask before write/exec'}[/bold]")
|
|
68
|
+
|
|
69
|
+
if config.router:
|
|
70
|
+
status = "[bold green]on[/bold green]" if config.router.enabled else "[dim]off[/dim]"
|
|
71
|
+
console.print(f" [dim]Routing:[/dim][bold] {status}[/bold] [dim](light/medium/heavy tiers)[/dim]")
|
|
72
|
+
else:
|
|
73
|
+
console.print(" [dim]Routing:[/dim] [dim]off[/dim]")
|
|
74
|
+
|
|
75
|
+
if config.mcp_manager:
|
|
76
|
+
servers = ", ".join(config.mcp_manager.server_names())
|
|
77
|
+
console.print(f" [dim]MCP:[/dim] [bold green]{servers}[/bold green]")
|
|
78
|
+
|
|
79
|
+
if project_config:
|
|
80
|
+
if project_config.get("project_path"):
|
|
81
|
+
console.print(f" [dim]Config:[/dim] [bold green]✓ {project_config['project_path']}[/bold green]")
|
|
82
|
+
if project_config.get("global_path"):
|
|
83
|
+
console.print(f" [dim]Global:[/dim] [bold green]✓ {project_config['global_path']}[/bold green]")
|
|
84
|
+
if not project_config.get("project_path") and not project_config.get("global_path"):
|
|
85
|
+
console.print(" [dim]Config:[/dim] [dim]no AGENTCODE.md found (optional)[/dim]")
|
|
86
|
+
|
|
87
|
+
sources = settings_sources(config.project_dir)
|
|
88
|
+
if sources["project"]:
|
|
89
|
+
console.print(f" [dim]Settings:[/dim][bold green] ✓ {sources['project']}[/bold green]")
|
|
90
|
+
elif sources["global"]:
|
|
91
|
+
console.print(f" [dim]Settings:[/dim][bold green] ✓ {sources['global']} (global)[/bold green]")
|
|
92
|
+
|
|
93
|
+
console.print()
|
|
94
|
+
console.print(" [dim]Type your request, or:[/dim]")
|
|
95
|
+
console.print(" [dim] /model <name> — switch model (disables routing)[/dim]")
|
|
96
|
+
console.print(" [dim] /route — show/toggle routing[/dim]")
|
|
97
|
+
console.print(" [dim] /cost — show session cost breakdown[/dim]")
|
|
98
|
+
console.print(" [dim] /mcp — manage MCP server connections[/dim]")
|
|
99
|
+
console.print(" [dim] /clear — reset conversation[/dim]")
|
|
100
|
+
console.print(" [dim] /compact — force context compaction[/dim]")
|
|
101
|
+
console.print(" [dim] /init — create AGENTCODE.md template[/dim]")
|
|
102
|
+
console.print(" [dim] /settings — show resolved settings[/dim]")
|
|
103
|
+
console.print(" [dim] /tokens — show token usage[/dim]")
|
|
104
|
+
console.print(" [dim] /help — show this help[/dim]")
|
|
105
|
+
console.print(" [dim] /exit — quit[/dim]")
|
|
106
|
+
console.print()
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
# ── Cost display ──────────────────────────────────────────────────────────────
|
|
110
|
+
|
|
111
|
+
def display_cost_line(config: AgentConfig):
|
|
112
|
+
"""Print per-turn and session cost after each response."""
|
|
113
|
+
if not config.router or not config.router.cost_tracker.requests:
|
|
114
|
+
return
|
|
115
|
+
tracker = config.router.cost_tracker
|
|
116
|
+
console.print(
|
|
117
|
+
f" [dim]💰 ${tracker.last_turn_cost:.4f} "
|
|
118
|
+
f"({tracker.last_turn_input:,} in / {tracker.last_turn_output:,} out)"
|
|
119
|
+
f" | session: ${tracker.total_cost:.4f}[/dim]"
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
# ── Slash Commands ────────────────────────────────────────────────────────────
|
|
124
|
+
|
|
125
|
+
def session_path(config: AgentConfig) -> Path:
|
|
126
|
+
from pathlib import Path
|
|
127
|
+
return Path(config.project_dir) / ".agentcode_session.json"
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def handle_slash_command(
|
|
131
|
+
cmd: str, config: AgentConfig, conversation: Conversation, project_config: dict | None = None
|
|
132
|
+
) -> bool:
|
|
133
|
+
"""Handle /commands. Returns True if the command was handled."""
|
|
134
|
+
parts = cmd.strip().split(maxsplit=1)
|
|
135
|
+
command = parts[0].lower()
|
|
136
|
+
arg = parts[1] if len(parts) > 1 else ""
|
|
137
|
+
|
|
138
|
+
if command in ("/exit", "/quit"):
|
|
139
|
+
console.print("[dim]Goodbye![/dim]")
|
|
140
|
+
sys.exit(0)
|
|
141
|
+
|
|
142
|
+
elif command == "/clear":
|
|
143
|
+
conversation.messages.clear()
|
|
144
|
+
session_path(config).unlink(missing_ok=True)
|
|
145
|
+
console.print("[success]✓ Conversation cleared[/success]")
|
|
146
|
+
return True
|
|
147
|
+
|
|
148
|
+
elif command == "/model":
|
|
149
|
+
if arg:
|
|
150
|
+
config.model = arg
|
|
151
|
+
if config.router:
|
|
152
|
+
config.router.enabled = False
|
|
153
|
+
console.print(f"[success]✓ Switched to model: {arg} (routing disabled)[/success]")
|
|
154
|
+
else:
|
|
155
|
+
console.print(f"[info]Current model: {config.model}[/info]")
|
|
156
|
+
console.print("[dim]Usage: /model <model_name>[/dim]")
|
|
157
|
+
console.print("[dim]Examples: claude-sonnet-4-6, gpt-4o, ollama/llama3[/dim]")
|
|
158
|
+
return True
|
|
159
|
+
|
|
160
|
+
elif command == "/route":
|
|
161
|
+
if not config.router:
|
|
162
|
+
console.print("[warning]Router not available.[/warning]")
|
|
163
|
+
return True
|
|
164
|
+
if arg in ("on", "off"):
|
|
165
|
+
config.router.enabled = arg == "on"
|
|
166
|
+
console.print(f"[success]✓ Routing {'enabled' if config.router.enabled else 'disabled'}[/success]")
|
|
167
|
+
else:
|
|
168
|
+
status = "[bold green]enabled[/bold green]" if config.router.enabled else "[dim]disabled[/dim]"
|
|
169
|
+
console.print(f" Routing: {status}")
|
|
170
|
+
console.print(f" Provider: [bold]{config.router.provider}[/bold]")
|
|
171
|
+
for tier in config.router.get_tiers():
|
|
172
|
+
console.print(
|
|
173
|
+
f" [dim]{tier.tier:6}[/dim] [bold]{tier.name}[/bold]"
|
|
174
|
+
f" [dim](${tier.input_cost_per_mtok:.2f}/${tier.output_cost_per_mtok:.2f} per 1M tok)[/dim]"
|
|
175
|
+
)
|
|
176
|
+
console.print("[dim] Usage: /route on | /route off[/dim]")
|
|
177
|
+
return True
|
|
178
|
+
|
|
179
|
+
elif command == "/cost":
|
|
180
|
+
if not config.router:
|
|
181
|
+
console.print("[warning]Cost tracking requires routing to be enabled.[/warning]")
|
|
182
|
+
return True
|
|
183
|
+
console.print(f"[info]{config.router.cost_tracker.summary()}[/info]")
|
|
184
|
+
return True
|
|
185
|
+
|
|
186
|
+
elif command == "/compact":
|
|
187
|
+
conversation.compact(max_tokens=0, model=config.model)
|
|
188
|
+
console.print("[success]✓ Context compacted[/success]")
|
|
189
|
+
return True
|
|
190
|
+
|
|
191
|
+
elif command == "/help":
|
|
192
|
+
show_banner(config, project_config)
|
|
193
|
+
return True
|
|
194
|
+
|
|
195
|
+
elif command == "/init":
|
|
196
|
+
_create_agentcode_template(config.project_dir)
|
|
197
|
+
return True
|
|
198
|
+
|
|
199
|
+
elif command == "/tokens":
|
|
200
|
+
est = conversation.token_estimate()
|
|
201
|
+
console.print(f"[info]Estimated tokens in context: ~{est:,}[/info]")
|
|
202
|
+
return True
|
|
203
|
+
|
|
204
|
+
elif command == "/mcp":
|
|
205
|
+
handle_mcp_command(arg.strip(), config)
|
|
206
|
+
return True
|
|
207
|
+
|
|
208
|
+
elif command == "/settings":
|
|
209
|
+
_show_settings(config)
|
|
210
|
+
return True
|
|
211
|
+
|
|
212
|
+
return False
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
# ── /settings display ────────────────────────────────────────────────────────
|
|
216
|
+
|
|
217
|
+
def _show_settings(config: AgentConfig) -> None:
|
|
218
|
+
"""Print the resolved settings and which files were loaded."""
|
|
219
|
+
sources = settings_sources(config.project_dir)
|
|
220
|
+
active = [v for v in sources.values() if v]
|
|
221
|
+
if active:
|
|
222
|
+
for path in active:
|
|
223
|
+
console.print(f" [dim]Loaded:[/dim] {path}")
|
|
224
|
+
else:
|
|
225
|
+
console.print(" [dim]No settings.json found — showing built-in defaults[/dim]")
|
|
226
|
+
console.print(f" [dim]Run with --init-settings to create one.[/dim]")
|
|
227
|
+
|
|
228
|
+
s = config.settings
|
|
229
|
+
if s is None:
|
|
230
|
+
return
|
|
231
|
+
|
|
232
|
+
console.print()
|
|
233
|
+
perms = s.permissions
|
|
234
|
+
auto_all = "[bold green]true[/bold green]" if perms.auto_approve_all else "[dim]false[/dim]"
|
|
235
|
+
console.print(f" [bold]permissions.auto_approve_all[/bold] {auto_all}")
|
|
236
|
+
console.print(f" [bold]permissions.auto_approve[/bold]")
|
|
237
|
+
for name in perms.auto_approve:
|
|
238
|
+
console.print(f" [dim]·[/dim] {name}")
|
|
239
|
+
deny_str = ", ".join(perms.deny) if perms.deny else "[dim](none)[/dim]"
|
|
240
|
+
console.print(f" [bold]permissions.deny[/bold] {deny_str}")
|
|
241
|
+
|
|
242
|
+
console.print()
|
|
243
|
+
m = s.model
|
|
244
|
+
console.print(f" [bold]model.default[/bold] {m.default}")
|
|
245
|
+
routing_str = "[bold green]true[/bold green]" if m.routing else "[dim]false[/dim]"
|
|
246
|
+
console.print(f" [bold]model.routing[/bold] {routing_str}")
|
|
247
|
+
for tier, val in [("light", m.light), ("medium", m.medium), ("heavy", m.heavy)]:
|
|
248
|
+
if val:
|
|
249
|
+
console.print(f" [bold]model.{tier}[/bold] {val}")
|
|
250
|
+
|
|
251
|
+
console.print()
|
|
252
|
+
lim = s.limits
|
|
253
|
+
console.print(f" [bold]limits.max_file_size[/bold] {lim.max_file_size:,} bytes")
|
|
254
|
+
console.print(f" [bold]limits.max_output[/bold] {lim.max_output:,} chars")
|
|
255
|
+
console.print(f" [bold]limits.max_search_results[/bold] {lim.max_search_results}")
|
|
256
|
+
console.print(f" [bold]limits.max_iterations[/bold] {lim.max_iterations}")
|
|
257
|
+
|
|
258
|
+
if s.hooks:
|
|
259
|
+
console.print()
|
|
260
|
+
console.print(" [bold]hooks:[/bold]")
|
|
261
|
+
for k, v in s.hooks.items():
|
|
262
|
+
console.print(f" [dim]{k}:[/dim] {v}")
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
# ── MCP command ───────────────────────────────────────────────────────────────
|
|
266
|
+
|
|
267
|
+
MCP_PRESETS = {
|
|
268
|
+
"github": {
|
|
269
|
+
"command": "npx",
|
|
270
|
+
"args": ["-y", "@modelcontextprotocol/server-github"],
|
|
271
|
+
"env_prompts": {"GITHUB_TOKEN": "GitHub personal access token (github.com/settings/tokens)"},
|
|
272
|
+
},
|
|
273
|
+
"filesystem": {
|
|
274
|
+
"command": "npx",
|
|
275
|
+
"args": ["-y", "@modelcontextprotocol/server-filesystem", "."],
|
|
276
|
+
"env_prompts": {},
|
|
277
|
+
},
|
|
278
|
+
"postgres": {
|
|
279
|
+
"command": "npx",
|
|
280
|
+
"args": ["-y", "@modelcontextprotocol/server-postgres"],
|
|
281
|
+
"env_prompts": {"POSTGRES_CONNECTION_STRING": "Postgres connection string (postgresql://user:pass@host/db)"},
|
|
282
|
+
},
|
|
283
|
+
"sqlite": {
|
|
284
|
+
"command": "npx",
|
|
285
|
+
"args": ["-y", "@modelcontextprotocol/server-sqlite"],
|
|
286
|
+
"env_prompts": {"SQLITE_DB_PATH": "Path to SQLite database file"},
|
|
287
|
+
},
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _load_mcp_config_file(project_dir: str) -> dict:
|
|
292
|
+
from pathlib import Path
|
|
293
|
+
path = Path(project_dir) / ".agentcode" / "mcp.json"
|
|
294
|
+
if path.exists():
|
|
295
|
+
try:
|
|
296
|
+
import json
|
|
297
|
+
return json.loads(path.read_text())
|
|
298
|
+
except Exception:
|
|
299
|
+
pass
|
|
300
|
+
return {"mcpServers": {}}
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _save_mcp_config_file(project_dir: str, data: dict) -> None:
|
|
304
|
+
from pathlib import Path
|
|
305
|
+
import json
|
|
306
|
+
path = Path(project_dir) / ".agentcode" / "mcp.json"
|
|
307
|
+
path.parent.mkdir(exist_ok=True)
|
|
308
|
+
path.write_text(json.dumps(data, indent=2))
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def handle_mcp_command(arg: str, config: AgentConfig) -> None:
|
|
312
|
+
parts = arg.split(maxsplit=1)
|
|
313
|
+
sub = parts[0].lower() if parts else ""
|
|
314
|
+
name = parts[1].strip() if len(parts) > 1 else ""
|
|
315
|
+
|
|
316
|
+
if sub == "list":
|
|
317
|
+
if config.mcp_manager and config.mcp_manager.server_names():
|
|
318
|
+
for server in config.mcp_manager.server_names():
|
|
319
|
+
tool_count = len([k for k in config.mcp_manager._tool_map if k.startswith(f"mcp__{server}__")])
|
|
320
|
+
console.print(f" [bold green]✓[/bold green] [bold]{server}[/bold] ({tool_count} tools)")
|
|
321
|
+
else:
|
|
322
|
+
console.print("[dim]No MCP servers connected. Use /mcp add <server> to connect one.[/dim]")
|
|
323
|
+
console.print(f"[dim]Available presets: {', '.join(MCP_PRESETS.keys())}[/dim]")
|
|
324
|
+
|
|
325
|
+
elif sub == "add":
|
|
326
|
+
if not name:
|
|
327
|
+
console.print(f"[warning]Usage: /mcp add <server>[/warning]")
|
|
328
|
+
console.print(f"[dim]Available presets: {', '.join(MCP_PRESETS.keys())}[/dim]")
|
|
329
|
+
return
|
|
330
|
+
|
|
331
|
+
if name not in MCP_PRESETS:
|
|
332
|
+
console.print(f"[warning]Unknown preset '{name}'. Available: {', '.join(MCP_PRESETS.keys())}[/warning]")
|
|
333
|
+
return
|
|
334
|
+
|
|
335
|
+
preset = MCP_PRESETS[name]
|
|
336
|
+
server_config = {"command": preset["command"], "args": preset["args"].copy()}
|
|
337
|
+
|
|
338
|
+
# Prompt for required env vars
|
|
339
|
+
if preset["env_prompts"]:
|
|
340
|
+
server_config["env"] = {}
|
|
341
|
+
for var, prompt in preset["env_prompts"].items():
|
|
342
|
+
try:
|
|
343
|
+
value = console.input(f" [bold]{prompt}:[/bold] ").strip()
|
|
344
|
+
except (EOFError, KeyboardInterrupt):
|
|
345
|
+
console.print("\n[warning]Cancelled.[/warning]")
|
|
346
|
+
return
|
|
347
|
+
if not value:
|
|
348
|
+
console.print("[warning]Cancelled — value required.[/warning]")
|
|
349
|
+
return
|
|
350
|
+
server_config["env"][var] = value
|
|
351
|
+
|
|
352
|
+
# Save to config file
|
|
353
|
+
data = _load_mcp_config_file(config.project_dir)
|
|
354
|
+
data["mcpServers"][name] = server_config
|
|
355
|
+
_save_mcp_config_file(config.project_dir, data)
|
|
356
|
+
|
|
357
|
+
# Hot-connect without restart
|
|
358
|
+
from mcp_client import MCPManager
|
|
359
|
+
if config.mcp_manager is None:
|
|
360
|
+
config.mcp_manager = MCPManager()
|
|
361
|
+
try:
|
|
362
|
+
config.mcp_manager.connect(name, server_config)
|
|
363
|
+
tool_count = len([k for k in config.mcp_manager._tool_map if k.startswith(f"mcp__{name}__")])
|
|
364
|
+
console.print(f"[success]✓ Connected to {name} ({tool_count} tools available)[/success]")
|
|
365
|
+
except Exception as e:
|
|
366
|
+
console.print(f"[error]Failed to connect to {name}: {e}[/error]")
|
|
367
|
+
# Roll back config
|
|
368
|
+
data["mcpServers"].pop(name, None)
|
|
369
|
+
_save_mcp_config_file(config.project_dir, data)
|
|
370
|
+
|
|
371
|
+
elif sub == "remove":
|
|
372
|
+
if not name:
|
|
373
|
+
console.print("[warning]Usage: /mcp remove <server>[/warning]")
|
|
374
|
+
return
|
|
375
|
+
|
|
376
|
+
data = _load_mcp_config_file(config.project_dir)
|
|
377
|
+
if name not in data.get("mcpServers", {}):
|
|
378
|
+
console.print(f"[warning]Server '{name}' not found in config.[/warning]")
|
|
379
|
+
return
|
|
380
|
+
|
|
381
|
+
data["mcpServers"].pop(name)
|
|
382
|
+
_save_mcp_config_file(config.project_dir, data)
|
|
383
|
+
|
|
384
|
+
# Remove from running manager
|
|
385
|
+
if config.mcp_manager:
|
|
386
|
+
keys_to_remove = [k for k in config.mcp_manager._tool_map if k.startswith(f"mcp__{name}__")]
|
|
387
|
+
for k in keys_to_remove:
|
|
388
|
+
config.mcp_manager._tool_map.pop(k)
|
|
389
|
+
config.mcp_manager._servers.pop(name, None)
|
|
390
|
+
|
|
391
|
+
console.print(f"[success]✓ Removed {name}[/success]")
|
|
392
|
+
|
|
393
|
+
else:
|
|
394
|
+
console.print(" [bold]/mcp list[/bold] — show connected servers")
|
|
395
|
+
console.print(" [bold]/mcp add <server>[/bold] — connect a server")
|
|
396
|
+
console.print(" [bold]/mcp remove <server>[/bold] — disconnect a server")
|
|
397
|
+
console.print(f" [dim]Available presets: {', '.join(MCP_PRESETS.keys())}[/dim]")
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
# ── AGENTCODE.md Template ─────────────────────────────────────────────────────
|
|
401
|
+
|
|
402
|
+
AGENTCODE_TEMPLATE = """\
|
|
403
|
+
# AGENTCODE.md — Project Configuration for AgentCode
|
|
404
|
+
|
|
405
|
+
## Project Overview
|
|
406
|
+
<!-- Brief description of what this project does -->
|
|
407
|
+
This is a [describe your project here].
|
|
408
|
+
|
|
409
|
+
## Tech Stack
|
|
410
|
+
<!-- Languages, frameworks, and key dependencies -->
|
|
411
|
+
- Language: Python 3.11+
|
|
412
|
+
- Framework: [your framework]
|
|
413
|
+
- Key dependencies: [list them]
|
|
414
|
+
|
|
415
|
+
## Coding Standards
|
|
416
|
+
<!-- Rules the agent should follow when writing code -->
|
|
417
|
+
- Use type hints for all function signatures
|
|
418
|
+
- Write docstrings for all public functions
|
|
419
|
+
- Follow PEP 8 style conventions
|
|
420
|
+
- Keep functions under 50 lines where possible
|
|
421
|
+
|
|
422
|
+
## File Structure
|
|
423
|
+
<!-- Help the agent understand your project layout -->
|
|
424
|
+
- `src/` — main source code
|
|
425
|
+
- `tests/` — test files (mirror src/ structure)
|
|
426
|
+
- `docs/` — documentation
|
|
427
|
+
|
|
428
|
+
## Testing
|
|
429
|
+
<!-- How to run tests and what framework you use -->
|
|
430
|
+
- Framework: pytest
|
|
431
|
+
- Run tests: `pytest tests/ -v`
|
|
432
|
+
- Always write tests for new functions
|
|
433
|
+
|
|
434
|
+
## Preferences
|
|
435
|
+
<!-- Your personal preferences for how the agent works -->
|
|
436
|
+
- Prefer descriptive variable names over abbreviations
|
|
437
|
+
- Use f-strings for string formatting
|
|
438
|
+
- Add comments for complex logic, skip obvious ones
|
|
439
|
+
- When in doubt, ask before making breaking changes
|
|
440
|
+
|
|
441
|
+
## Do NOT
|
|
442
|
+
<!-- Things the agent should avoid -->
|
|
443
|
+
- Do not modify configuration files without asking
|
|
444
|
+
- Do not install new dependencies without approval
|
|
445
|
+
- Do not delete files without confirmation
|
|
446
|
+
"""
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def _create_agentcode_template(project_dir: str):
|
|
450
|
+
"""Create an AGENTCODE.md template in the project directory."""
|
|
451
|
+
from pathlib import Path
|
|
452
|
+
target = Path(project_dir) / "AGENTCODE.md"
|
|
453
|
+
|
|
454
|
+
if target.exists():
|
|
455
|
+
console.print(f"[warning]⚠ AGENTCODE.md already exists at {target}[/warning]")
|
|
456
|
+
return
|
|
457
|
+
|
|
458
|
+
target.write_text(AGENTCODE_TEMPLATE)
|
|
459
|
+
console.print(f"[success]✓ Created AGENTCODE.md at {target}[/success]")
|
|
460
|
+
console.print("[dim] Edit it to define your project's coding standards and preferences.[/dim]")
|
|
461
|
+
console.print("[dim] Restart AgentCode to load the config.[/dim]")
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
# ── REPL ──────────────────────────────────────────────────────────────────────
|
|
465
|
+
|
|
466
|
+
def repl(config: AgentConfig):
|
|
467
|
+
"""Interactive read-eval-print loop."""
|
|
468
|
+
project_config = load_project_config(config.project_dir)
|
|
469
|
+
system_prompt = build_system_prompt(config.project_dir, project_config["combined"])
|
|
470
|
+
conversation = Conversation(system=system_prompt)
|
|
471
|
+
|
|
472
|
+
sess = session_path(config)
|
|
473
|
+
conversation.load(sess)
|
|
474
|
+
if conversation.messages:
|
|
475
|
+
console.print(f"[dim]Resumed session ({len(conversation.messages)} messages). Use /clear to start fresh.[/dim]\n")
|
|
476
|
+
|
|
477
|
+
show_banner(config, project_config)
|
|
478
|
+
|
|
479
|
+
while True:
|
|
480
|
+
try:
|
|
481
|
+
user_input = console.input("[prompt]❯[/prompt] ").strip()
|
|
482
|
+
except (EOFError, KeyboardInterrupt):
|
|
483
|
+
console.print("\n[dim]Goodbye![/dim]")
|
|
484
|
+
break
|
|
485
|
+
|
|
486
|
+
if not user_input:
|
|
487
|
+
continue
|
|
488
|
+
|
|
489
|
+
if user_input.startswith("/"):
|
|
490
|
+
if handle_slash_command(user_input, config, conversation, project_config):
|
|
491
|
+
continue
|
|
492
|
+
|
|
493
|
+
try:
|
|
494
|
+
run_agent_loop(user_input, conversation, config)
|
|
495
|
+
conversation.save(sess)
|
|
496
|
+
display_cost_line(config)
|
|
497
|
+
except KeyboardInterrupt:
|
|
498
|
+
console.print("\n[warning]⚠ Interrupted[/warning]")
|
|
499
|
+
continue
|
|
500
|
+
except Exception as e:
|
|
501
|
+
console.print(f"[error]Error: {e}[/error]")
|
|
502
|
+
continue
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
# ── One-Shot Mode ─────────────────────────────────────────────────────────────
|
|
506
|
+
|
|
507
|
+
def one_shot(prompt: str, config: AgentConfig):
|
|
508
|
+
"""Execute a single prompt and exit."""
|
|
509
|
+
project_config = load_project_config(config.project_dir)
|
|
510
|
+
system_prompt = build_system_prompt(config.project_dir, project_config["combined"])
|
|
511
|
+
conversation = Conversation(system=system_prompt)
|
|
512
|
+
run_agent_loop(prompt, conversation, config)
|
|
513
|
+
display_cost_line(config)
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
# ── Entry Point ───────────────────────────────────────────────────────────────
|
|
517
|
+
|
|
518
|
+
def main():
|
|
519
|
+
parser = argparse.ArgumentParser(
|
|
520
|
+
description="AgentCode — multi-model agentic coding CLI",
|
|
521
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
522
|
+
epilog=__doc__,
|
|
523
|
+
)
|
|
524
|
+
parser.add_argument(
|
|
525
|
+
"prompt",
|
|
526
|
+
nargs="?",
|
|
527
|
+
help="One-shot prompt (omit for interactive REPL)",
|
|
528
|
+
)
|
|
529
|
+
parser.add_argument(
|
|
530
|
+
"--model", "-m",
|
|
531
|
+
default=None,
|
|
532
|
+
help="LLM model to use (overrides settings.model.default)",
|
|
533
|
+
)
|
|
534
|
+
parser.add_argument(
|
|
535
|
+
"--no-route",
|
|
536
|
+
action="store_true",
|
|
537
|
+
help="Disable cost-aware model routing (always use --model)",
|
|
538
|
+
)
|
|
539
|
+
parser.add_argument(
|
|
540
|
+
"--auto-approve", "-y",
|
|
541
|
+
action="store_true",
|
|
542
|
+
help="Skip permission prompts for all tool calls (use with caution!)",
|
|
543
|
+
)
|
|
544
|
+
parser.add_argument(
|
|
545
|
+
"--dir", "-d",
|
|
546
|
+
default=os.getcwd(),
|
|
547
|
+
help="Project directory to operate in (default: current dir)",
|
|
548
|
+
)
|
|
549
|
+
parser.add_argument(
|
|
550
|
+
"--init-settings",
|
|
551
|
+
action="store_true",
|
|
552
|
+
help="Create a starter .agentcode/settings.json and exit",
|
|
553
|
+
)
|
|
554
|
+
|
|
555
|
+
args = parser.parse_args()
|
|
556
|
+
|
|
557
|
+
project_dir = os.path.abspath(args.dir)
|
|
558
|
+
os.chdir(project_dir)
|
|
559
|
+
|
|
560
|
+
# Handle --init-settings before anything else
|
|
561
|
+
if args.init_settings:
|
|
562
|
+
path, created = generate_starter_settings(project_dir)
|
|
563
|
+
if created:
|
|
564
|
+
console.print(f"[success]✓ Created {path}[/success]")
|
|
565
|
+
console.print()
|
|
566
|
+
console.print("[dim]Settings reference:[/dim]")
|
|
567
|
+
for line in SETTINGS_HELP.strip().splitlines():
|
|
568
|
+
console.print(f" [dim]{line}[/dim]")
|
|
569
|
+
else:
|
|
570
|
+
console.print(f"[warning]⚠ Settings already exist at {path}[/warning]")
|
|
571
|
+
console.print("[dim] Edit it directly or delete it and re-run --init-settings.[/dim]")
|
|
572
|
+
return
|
|
573
|
+
|
|
574
|
+
# Build CLI overrides dict so they take highest priority in merge
|
|
575
|
+
cli_overrides: dict = {}
|
|
576
|
+
if args.auto_approve:
|
|
577
|
+
cli_overrides.setdefault("permissions", {})["auto_approve_all"] = True
|
|
578
|
+
if args.no_route:
|
|
579
|
+
cli_overrides.setdefault("model", {})["routing"] = False
|
|
580
|
+
|
|
581
|
+
settings = load_settings(project_dir, cli_overrides or None)
|
|
582
|
+
|
|
583
|
+
# Apply configurable limits to tools module
|
|
584
|
+
configure_limits(settings.limits)
|
|
585
|
+
|
|
586
|
+
# Resolve model: CLI flag > env var > settings.model.default
|
|
587
|
+
model = (
|
|
588
|
+
args.model
|
|
589
|
+
or os.environ.get("AGENTCODE_MODEL")
|
|
590
|
+
or settings.model.default
|
|
591
|
+
)
|
|
592
|
+
|
|
593
|
+
# Resolve routing
|
|
594
|
+
routing_enabled = settings.model.routing # already patched by cli_overrides if --no-route
|
|
595
|
+
|
|
596
|
+
# Build router
|
|
597
|
+
temp_router = ModelRouter(default_model=model)
|
|
598
|
+
provider = temp_router.detect_provider(model)
|
|
599
|
+
router = ModelRouter(
|
|
600
|
+
provider=provider,
|
|
601
|
+
default_model=model,
|
|
602
|
+
enabled=routing_enabled,
|
|
603
|
+
)
|
|
604
|
+
|
|
605
|
+
# Resolve max_iterations: env var takes precedence for backward compat
|
|
606
|
+
max_iterations = int(
|
|
607
|
+
os.environ.get("AGENTCODE_MAX_ITERATIONS", settings.limits.max_iterations)
|
|
608
|
+
)
|
|
609
|
+
|
|
610
|
+
config = AgentConfig(
|
|
611
|
+
model=model,
|
|
612
|
+
auto_approve=settings.permissions.auto_approve_all,
|
|
613
|
+
project_dir=project_dir,
|
|
614
|
+
max_iterations=max_iterations,
|
|
615
|
+
router=router,
|
|
616
|
+
mcp_manager=create_mcp_manager(project_dir),
|
|
617
|
+
settings=settings,
|
|
618
|
+
)
|
|
619
|
+
|
|
620
|
+
if args.prompt:
|
|
621
|
+
one_shot(args.prompt, config)
|
|
622
|
+
else:
|
|
623
|
+
repl(config)
|
|
624
|
+
|
|
625
|
+
|
|
626
|
+
if __name__ == "__main__":
|
|
627
|
+
main()
|