-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
346 lines (274 loc) · 11 KB
/
Copy pathcli.py
File metadata and controls
346 lines (274 loc) · 11 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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
"""
CodePipe CLI — multi-language deterministic pipeline coding agent.
Commands:
run Gate → Locator → Orchestrator (one-shot)
repl Interactive REPL loop with /commands
chat Single prompt to LLM
providers List configured LLM providers
init-config Write a starter config.yaml
"""
import os
import sys
from pathlib import Path
import typer
DEFAULT_CONFIG = """# CodePipe configuration.
# API keys are read from environment variables by default.
active: deepseek # deepseek | ollama
providers:
deepseek:
base_url: "https://api.deepseek.com/v1"
api_key: "${DEEPSEEK_API_KEY}"
model: "deepseek-chat"
description: "DeepSeek API (cloud, OpenAI-compatible)"
ollama:
base_url: "http://localhost:11434/v1"
api_key: "ollama"
model: "qwen3:8b"
description: "Local Ollama (open-source models, OpenAI-compatible)"
generation:
temperature: 0.0
max_tokens: 2048
stream: false
safety:
max_retries: 3
fuzzy_match_threshold: 0.85
"""
app = typer.Typer(
name="codepipe",
help="CodePipe — multi-language deterministic pipeline coding agent",
add_completion=False,
)
# ── Pipeline runner (shared by `run` and `repl`) ────────────
def _run_pipeline(task: str, project_root: str, client, verbose: bool = False) -> dict:
"""Execute Gate → Locator → Orchestrator. Returns result dict."""
from core.gate import Gate
from core.locator.locator import Locator
from core.orchestrator import Orchestrator
# Step 1: Gate
typer.echo(" [1/3] Gate...", nl=False)
gate = Gate(client)
gate_result = gate.classify(task)
typer.echo(f" {gate_result.expert_type} | {' → '.join(gate_result.pipeline)}")
if gate_result.expert_type == "chat":
messages = [{"role": "user", "content": task}]
response = client.generate(messages)
typer.echo(f"\n{response}")
return {"success": True, "mode": "chat", "output": response, "retries": 0}
# Step 2: Locator
typer.echo(" [2/3] Locator...", nl=False)
locator = Locator()
try:
locator_result = locator.locate(project_root, task)
except Exception as e:
typer.echo(f" warn: {e}")
locator_result = {"files": [], "context": {}, "edit_locations": []}
files = locator_result.get("files", [])
typer.echo(f" {len(files)} files" if files else " no files found")
if verbose and files:
for loc in locator_result.get("edit_locations", [])[:3]:
typer.echo(f" → {loc}")
target_file = files[0] if files else "output.py"
# Step 3: Orchestrator
typer.echo(f" [3/3] Orchestrator → {target_file} ...", nl=False)
orch = Orchestrator(project_root)
orch.llm_client = client
result = orch.run(
user_request=task,
target_file=target_file,
locator_context=locator_result,
)
return result
def _show_result(result: dict, verbose: bool = False):
"""Display pipeline result."""
if result["success"]:
typer.echo(f" [OK] mode={result.get('mode', '?')} retries={result.get('retries', 0)}")
if verbose and result.get("output"):
typer.echo(f"\n{result['output'][:1000]}")
else:
typer.echo(f" [FAIL] {result.get('error', 'unknown')[:120]}")
if result.get("rollback"):
typer.echo(" [ROLLBACK] git reset --hard")
def _config_missing_error(path: str = "config.yaml") -> None:
typer.echo(f"[ERROR] {path} not found", err=True)
typer.echo("Run `codepipe init-config` in your project, then edit config.yaml.", err=True)
# ── Commands ─────────────────────────────────────────────────
@app.command()
def run(
task: str = typer.Argument(..., help="Task description in natural language"),
project: str = typer.Option(".", "--project", "-p", help="Project root directory"),
verbose: bool = typer.Option(False, "--verbose", "-v", help="Show detailed output"),
):
"""Run the full pipeline once: Gate → Locator → Orchestrator."""
from core.llm_client import LLMClient
project_root = str(Path(project).resolve())
try:
client = LLMClient.from_config()
except FileNotFoundError:
_config_missing_error()
raise typer.Exit(code=1)
typer.echo(f"provider={client.config.provider_name} model={client.model} project={project_root}")
typer.echo("")
result = _run_pipeline(task, project_root, client, verbose)
typer.echo("")
_show_result(result, verbose)
@app.command()
def repl(
project: str = typer.Option(".", "--project", "-p", help="Project root directory"),
):
"""Start interactive REPL loop with /commands."""
from core.llm_client import LLMClient
project_root = str(Path(project).resolve())
try:
client = LLMClient.from_config()
except FileNotFoundError:
_config_missing_error()
raise typer.Exit(code=1)
typer.echo(f"CodePipe REPL — provider={client.config.provider_name} model={client.model}")
typer.echo(f"project={project_root}")
typer.echo("Type /help for commands, /quit to exit.\n")
_repl_loop(client, project_root)
def _repl_loop(client, project_root: str):
"""Interactive read-eval-print loop."""
while True:
try:
user_input = typer.prompt("> ", prompt_suffix="").strip()
except (KeyboardInterrupt, EOFError):
typer.echo("\n/quit")
break
if not user_input:
continue
# ── Slash commands ──
if user_input.startswith("/"):
handled = _handle_slash_cmd(user_input, client, project_root)
if handled == "quit":
break
continue
# ── Natural language → pipeline ──
typer.echo("")
result = _run_pipeline(user_input, project_root, client, verbose=False)
typer.echo("")
_show_result(result, verbose=False)
typer.echo("")
def _handle_slash_cmd(cmd: str, client, project_root: str) -> str:
"""Handle a slash command. Returns 'quit' to exit REPL."""
parts = cmd.split(maxsplit=1)
name = parts[0].lower()
arg = parts[1] if len(parts) > 1 else ""
if name in ("/quit", "/exit", "/q"):
typer.echo("Goodbye.")
return "quit"
elif name == "/help":
typer.echo("""
Commands:
<task> Run the full pipeline on a natural language task
/plan <task> Preview Gate classification + Locator results (no changes)
/model <name> Switch active model (e.g. /model qwen3:14b)
/api Show current API configuration
/cd <path> Change project directory
/experts List available expert types and pipelines
/help Show this help
/quit, /exit Exit REPL
""")
elif name == "/plan":
if not arg:
typer.echo("[ERROR] /plan requires a task description")
else:
from core.gate import Gate
from core.locator.locator import Locator
typer.echo("")
gate = Gate(client)
gr = gate.classify(arg)
typer.echo(f" Gate: {gr.expert_type} | difficulty={gr.difficulty}")
typer.echo(f" Pipeline: {' → '.join(gr.pipeline)}")
if gr.expert_type != "chat":
locator = Locator()
lr = locator.locate(project_root, arg)
files = lr.get("files", [])
typer.echo(f" Locator: {len(files)} files")
for loc in lr.get("edit_locations", [])[:5]:
typer.echo(f" → {loc}")
typer.echo("")
elif name == "/model":
if not arg:
from core.llm_client import LLMConfig
typer.echo(f" current model: {client.model}")
else:
client._model = arg
client.config.model = arg
typer.echo(f" switched to: {arg}")
elif name == "/api":
cfg = client.config
typer.echo(f" provider: {cfg.provider_name}")
typer.echo(f" base_url: {cfg.base_url}")
typer.echo(f" model: {cfg.model}")
elif name == "/cd":
if not arg:
typer.echo(f" current: {project_root}")
else:
new_root = str(Path(arg).resolve())
if os.path.isdir(new_root):
project_root = new_root
typer.echo(f" switched to: {project_root}")
else:
typer.echo(f" [ERROR] directory not found: {arg}")
elif name == "/experts":
from core.gate import EXPERT_PIPELINES
typer.echo("")
for et, pl in EXPERT_PIPELINES.items():
typer.echo(f" {et:12s} → {' → '.join(pl)}")
typer.echo("")
else:
typer.echo(f" Unknown command: {name}. Type /help for available commands.")
return ""
@app.command()
def chat(prompt: str = typer.Argument(..., help="Message to send to the LLM")):
"""Send a single prompt to the configured LLM and print the response."""
from core.llm_client import LLMClient
try:
client = LLMClient.from_config()
except FileNotFoundError:
_config_missing_error()
raise typer.Exit(code=1)
except Exception as e:
typer.echo(f"[ERROR] Config error: {e}", err=True)
raise typer.Exit(code=1)
typer.echo(f"[LLM] provider={client.config.provider_name} model={client.model}")
try:
messages = [{"role": "user", "content": prompt}]
response = client.generate(messages)
typer.echo(response)
except Exception as e:
typer.echo(f"[ERROR] LLM call failed: {e}", err=True)
raise typer.Exit(code=1)
@app.command()
def providers():
"""List available providers from config.yaml."""
import yaml
config_path = Path("config.yaml")
if not config_path.exists():
_config_missing_error()
raise typer.Exit(code=1)
with open(config_path) as f:
data = yaml.safe_load(f)
active = data.get("active", "?")
providers_data = data.get("providers", {})
typer.echo(f"Active: {active}")
typer.echo("Available providers:")
for name, cfg in providers_data.items():
marker = " (active)" if name == active else ""
typer.echo(f" {name}: {cfg.get('model', '?')} @ {cfg.get('base_url', '?')}{marker}")
@app.command("init-config")
def init_config(
path: str = typer.Option("config.yaml", "--path", "-p", help="Config file path to write"),
force: bool = typer.Option(False, "--force", "-f", help="Overwrite an existing config file"),
):
"""Write a starter config.yaml for the current project."""
config_path = Path(path)
if config_path.exists() and not force:
typer.echo(f"[ERROR] {config_path} already exists. Use --force to overwrite.", err=True)
raise typer.Exit(code=1)
config_path.write_text(DEFAULT_CONFIG, encoding="utf-8")
typer.echo(f"Wrote {config_path}")
typer.echo("Set DEEPSEEK_API_KEY or switch active provider to ollama before running CodePipe.")
if __name__ == "__main__":
app()