-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcli.py
More file actions
243 lines (212 loc) · 8.56 KB
/
cli.py
File metadata and controls
243 lines (212 loc) · 8.56 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
"""Command-line interface for the caramba system.
The CLI is intentionally minimal: one entrypoint that runs a manifest.
"""
from __future__ import annotations
import click
from pathlib import Path
import uvicorn
from console import logger
from api.app import app
from experiment.runner import run_from_manifest_path
from codegraph.parser import parse_repo
from codegraph.sync import sync_files_to_falkordb
class CarambaCLI(click.Group):
"""A click Group that treats unknown commands as `run <manifest_path>`."""
def resolve_command(
self, ctx: click.Context, args: list[str]
) -> tuple[str | None, click.Command | None, list[str]]:
try:
return super().resolve_command(ctx, args)
except click.UsageError as e:
# If the first token isn't a known subcommand, interpret it as:
# `run <token> ...` so users can do: `caramba path/to/manifest.yml`.
if args:
cmd = super().get_command(ctx, "run")
if cmd is not None:
return "run", cmd, args
raise e
@click.group(cls=CarambaCLI, context_settings={"help_option_names": ["-h", "--help"]})
@click.option(
"--target",
type=str,
default=None,
help="Target to run (e.g. 'target:<name>' or a bare target name).",
)
@click.option(
"--dry-run",
is_flag=True,
default=False,
help="Validate/plan the manifest without executing.",
)
@click.pass_context
def cli(ctx: click.Context, target: str | None, dry_run: bool) -> None:
"""Run a manifest target, or use a subcommand."""
ctx.ensure_object(dict)
ctx.obj["target"] = target
ctx.obj["dry_run"] = bool(dry_run)
return
@cli.command("run")
@click.argument("manifest_path", type=click.Path(exists=True, path_type=Path))
@click.option(
"--target",
type=str,
default=None,
help="Target to run (e.g. 'target:<name>' or a bare target name). "
"If omitted, uses entrypoints.default or the first runnable target.",
)
@click.option(
"--dry-run",
is_flag=True,
default=False,
help="Validate/plan the manifest without executing.",
)
@click.pass_context
def run(ctx: click.Context, manifest_path: Path, target: str | None, dry_run: bool) -> None:
"""Run what a manifest declares (targets)."""
# Allow `caramba --dry-run MANIFEST.yml` by inheriting group options.
if ctx.parent is not None and ctx.parent.obj:
if target is None:
target = ctx.parent.obj.get("target")
if not dry_run:
dry_run = bool(ctx.parent.obj.get("dry_run", False))
try:
result = run_from_manifest_path(manifest_path, target=target, dry_run=dry_run)
if dry_run and result:
logger.inspect(result)
except Exception as e:
logger.error(f"Error: {e}")
raise click.Abort() from e
@cli.command("serve")
@click.option("--host", type=str, default="127.0.0.1", show_default=True)
@click.option("--port", type=int, default=8765, show_default=True)
def serve_cmd(host: str, port: int) -> None:
"""Start the local dev API server (UI control-plane).
This is a lightweight bridge for the frontend demos:
- POST /api/runs to spawn `caramba run ...`
- GET /api/runs/<id>/events to stream `train.jsonl` as SSE
"""
uvicorn.run(app, host=host, port=port, log_level="info")
@cli.command("tui")
@click.option("--url", type=str, default="http://localhost:9000", help="Root agent URL.")
@click.option("--log", type=click.Path(exists=False), default=None, help="Training log file path.")
@click.option("--steps", type=int, default=0, help="Total training steps.")
@click.option("-o", "--output", type=click.Path(), default="manifest.yml", help="Manifest output path.")
def tui_cmd(url: str, log: str | None, steps: int, output: str) -> None:
"""Launch the unified Caramba TUI.
A single interface with multiple views:
- Chat (Ctrl+1): Agent chat interface
- Training (Ctrl+2): Real-time training metrics dashboard
- Builder (Ctrl+3): Visual manifest/architecture builder
Example:
caramba tui --url http://localhost:9000 --log runs/train.jsonl
"""
from tui.unified import CarambaApp
app = CarambaApp(
root_agent_url=url,
log_path=log,
total_steps=steps,
manifest_output=output,
)
app.run()
@cli.command("agent")
@click.argument("persona", type=str)
@click.option("--host", type=str, default="0.0.0.0", show_default=True)
@click.option("--port", type=int, default=8001, show_default=True)
@click.option("--team-config", type=str, default="default", show_default=True, help="Team config name.")
@click.option("--root", is_flag=True, default=False, help="Run as root agent (port 9000 default).")
@click.option("--lead", is_flag=True, default=False, help="Run as team lead agent.")
def agent_cmd(persona: str, host: str, port: int, team_config: str, root: bool, lead: bool) -> None:
"""Start an AI agent server.
PERSONA is the persona type (e.g. 'root', 'research_lead', 'developer').
Examples:
caramba agent root --root # Root agent on port 9000
caramba agent research_lead --lead --port 8002 # Team lead
caramba agent developer --port 8003 # Regular agent
"""
from ai import run_root_server, run_lead_server, run_agent_server
if root or persona == "root":
actual_port = 9000 if port == 8001 else port
logger.info(f"Starting root agent on {host}:{actual_port}")
run_root_server(host=host, port=actual_port, team_config=team_config)
elif lead:
logger.info(f"Starting lead agent '{persona}' on {host}:{port}")
run_lead_server(persona, host=host, port=port, team_config=team_config)
else:
logger.info(f"Starting agent '{persona}' on {host}:{port}")
run_agent_server(persona, host=host, port=port)
@cli.command("codegraph-sync")
@click.argument("repo_root", type=click.Path(exists=True, file_okay=False, path_type=Path), default=".")
@click.option("--graph", type=str, default="caramba_code", show_default=True, help="FalkorDB graph name.")
@click.option(
"--falkordb-uri",
type=str,
default=None,
help="FalkorDB URI (e.g. redis://localhost:6379). Defaults to env FALKORDB_URI.",
)
@click.option("--falkordb-host", type=str, default=None, help="FalkorDB host (fallback if no URI).")
@click.option("--falkordb-port", type=int, default=None, help="FalkorDB port (fallback if no URI).")
@click.option("--falkordb-password", type=str, default=None, help="FalkorDB password.")
@click.option(
"--file",
"files",
multiple=True,
type=str,
help="Relative file path(s) to sync (repeatable). If omitted, scans all *.py under repo_root.",
)
@click.option("--reset", is_flag=True, default=False, help="Wipe the entire graph before ingesting.")
def codegraph_sync_cmd(
repo_root: Path,
graph: str,
falkordb_uri: str | None,
falkordb_host: str | None,
falkordb_port: int | None,
falkordb_password: str | None,
files: tuple[str, ...],
reset: bool,
) -> None:
"""Parse Python code and sync a structural graph into FalkorDB."""
# Allow users to disable this (useful for hooks).
try:
file_list = [str(x) for x in files if str(x).strip()] or None
nodes, edges = parse_repo(str(repo_root), files=file_list)
result = sync_files_to_falkordb(
repo_root=str(repo_root),
nodes=nodes,
edges=edges,
files=file_list,
graph=str(graph),
uri=falkordb_uri,
host=falkordb_host,
port=falkordb_port,
password=falkordb_password,
reset=bool(reset),
)
if result.get("ok"):
logger.success(
f"codegraph-sync ok • graph={result.get('graph')} nodes={result.get('nodes')} edges={result.get('edges')}"
)
else:
logger.error(f"codegraph-sync failed: {result.get('error')}")
except Exception as e:
logger.error(f"Error: {e}")
raise click.Abort() from e
def main(argv: list[str] | None = None) -> int:
"""Main entry point for the CLI.
Returns exit code (0 for success, non-zero for failure).
"""
try:
# click's main() expects sys.argv[1:] if args is None
# standalone_mode=False prevents it from calling sys.exit()
cli.main(args=argv, standalone_mode=False)
return 0
except click.Abort:
return 1
except click.ClickException as e:
e.show()
return 1
except Exception as e:
logger.error(f"Error: {e}")
return 1
if __name__ == "__main__":
import sys
sys.exit(main())