Something went wrong. Try again.
MCP based ACP agent
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627"""crow-cli init - Interactive configuration setup wizard.
Builds config.yaml and .env in ~/.agents/crow (or --config-dir), then clonesthe source checkout into <config-dir>/src, installs the crow-cli skillglobally, and writes the default `agent_servers` entry pointing at thecheckout — bare `crow-cli` launches the TOP entry, so there is always one.See crow_cli.cli.source.
Configuration priority (highest to lowest):1. LLM_*_API_KEY / LLM_*_BASE_URL env vars2. config.yaml in config_dir (if exists)3. .env in current directory (loaded via load_dotenv)4. Interactive prompts
"""
import base64import getpassimport osimport secretsfrom pathlib import Pathfrom typing import Any
import httpximport yamlfrom dotenv import load_dotenvfrom rich.console import Consolefrom rich.panel import Panelfrom rich.prompt import Confirm, Promptfrom rich.table import Table
from crow_cli.cli.source import ( bootstrap as source_bootstrap, default_agent_server_entry, global_checkout, is_checkout,)from crow_cli.config.default import ( COMPOSE_YAML, SEARXNG_SETTINGS_YML, SYSTEM_PROMPT,)
load_dotenv() # Load .env from current directory if present
console = Console()
# DashScope detectionDASHSCOPE_URL = "https://coding-intl.dashscope.aliyuncs.com/v1"
# Default models to use when DashScope is detectedDASHSCOPE_MODELS = { "qwen3.6-plus": {"provider": "dashscope", "model": "qwen3.6-plus"}, "glm-5": {"provider": "dashscope", "model": "glm-5"},}
def fetch_models(base_url: str, api_key: str) -> list[dict]: """Fetch available models from an OpenAI-compatible /models endpoint.""" try: base_url = base_url.rstrip("/") url = f"{base_url}/models"
response = httpx.get( url, headers={"Authorization": f"Bearer {api_key}"}, timeout=30.0, ) response.raise_for_status() data = response.json()
models = [] for model in data.get("data", []): models.append( { "id": model.get("id", "unknown"), "owned_by": model.get("owned_by", "unknown"), } ) return sorted(models, key=lambda m: m["id"]) except Exception as e: console.print( f"[yellow]Warning: Could not fetch models from {base_url}: {e}[/yellow]" ) return []
def select_models(models: list[dict]) -> list[tuple[str, str]]: """Let user select models interactively. Returns list of (friendly_name, model_id).""" if not models: console.print( "[yellow]No models available. You can add them manually later.[/yellow]" ) return []
console.print( f"\n[cyan]Found {len(models)} models. Select which ones to add:[/cyan]" )
table = Table(show_header=True, header_style="bold cyan") table.add_column("#", style="dim", width=4) table.add_column("Model ID", style="green") table.add_column("Owner", style="dim")
for i, model in enumerate(models, 1): table.add_row(str(i), model["id"], model["owned_by"])
console.print(table)
console.print( "\n[dim]Enter model numbers to add (comma-separated, e.g., 1,3,5) or 'all' or 'none':[/dim]" ) selection = Prompt.ask("Models", default="all")
if selection.lower() == "none": return []
if selection.lower() == "all": indices = list(range(len(models))) else: try: indices = [int(x.strip()) - 1 for x in selection.split(",") if x.strip()] except ValueError: console.print("[red]Invalid selection[/red]") return []
indices = [i for i in indices if 0 <= i < len(models)]
selected = [] for idx in indices: model_id = models[idx]["id"] default_name = model_id.split("/")[-1] if "/" in model_id else model_id friendly_name = Prompt.ask( f" Friendly name for [green]{model_id}[/]", default=default_name ) selected.append((friendly_name, model_id))
return selected
def is_dashscope_url(base_url: str) -> bool: """Detect if base_url points to DashScope's coding-intl endpoint.""" return "coding-intl.dashscope.aliyuncs.com" in base_url
def add_default_agent_server(config_dir: Path) -> bool: """Write the default ``crow-cli`` agent_servers entry into config.yaml.
Bare `crow-cli` launches the TOP agent_servers entry, so init leaves one pointing at the source checkout — the explicit route for what used to be an implicit override. Never steps on an existing ``crow-cli`` entry, and writes nothing when there is no checkout (a dangling entry would break the bare launch). Returns True when the file gained the entry. """ checkout = global_checkout(config_dir) if not is_checkout(checkout): return False
config_file = config_dir / "config.yaml" config: dict[str, Any] = yaml.safe_load(config_file.read_text()) or {} servers = config.get("agent_servers") or {} if "crow-cli" in servers: return False servers["crow-cli"] = default_agent_server_entry(config_dir) config["agent_servers"] = servers with open(config_file, "w") as f: yaml.dump( config, f, default_flow_style=False, sort_keys=False, allow_unicode=True, ) return True
def run_init(config_dir: Path, yes: bool = False, source: bool = True): """Run the interactive initialization wizard.
``source=False`` skips the source checkout clone (Step 5) — the escape hatch for offline installs and for tests that must not touch the network. """ config_dir = Path(os.path.expanduser(str(config_dir)))
console.print( Panel.fit( "[bold]🪶 Crow CLI Setup[/bold]\n\n" f"This will create your configuration in [cyan]{config_dir}[/cyan]", border_style="magenta", ) )
config_file = config_dir / "config.yaml" env_file = config_dir / ".env" if config_file.exists() and not yes: if not Confirm.ask( f"\n[yellow]{config_file} already exists. Overwrite?[/]", default=False ): console.print("[red]Aborted.[/red]") return
# Data structures providers: dict[str, dict] = {} models: dict[str, dict] = {} env_vars: dict[str, str] = {} dashscope_api_key = None
# ========================================================================= # STEP 1: Add providers # ========================================================================= console.print("\n[bold cyan]═══ Step 1: LLM Providers ═══[/bold cyan]\n")
if yes: console.print("[dim]→ --yes mode: checking env vars for providers...[/dim]") for key, value in os.environ.items(): if key.startswith("LLM_") and key.endswith("_API_KEY"): provider = key[len("LLM_") : -len("_API_KEY")].lower() base_url_key = f"LLM_{provider.upper()}_BASE_URL" base_url = os.environ.get(base_url_key, "") if base_url and value:
console.print( f" [cyan]✓[/cyan] Found provider: [green]{provider}[/green] " f"from env vars" ) providers[provider] = { "base_url": base_url, "api_key": f"${{{key}}}", } env_vars[key] = value try: available_models = fetch_models(base_url, value) for model in available_models[:5]: models[model["id"]] = { "provider": provider, "model": model["id"], } except Exception: pass if not providers: console.print( "[yellow] No providers found in env vars. " "Add LLM_<PROVIDER>_API_KEY + LLM_<PROVIDER>_BASE_URL.[/yellow]" ) console.print() else: while True: console.print("[dim]--- Add a provider ---[/dim]")
provider_name = ( Prompt.ask("Provider name (e.g., openai, anthropic, openrouter)") .strip() .lower() ) if not provider_name: console.print("[red]Provider name required[/red]") continue
base_url = Prompt.ask("Base URL (e.g., https://api.openai.com/v1)").strip() if not base_url: console.print("[red]Base URL required[/red]") continue
api_key = getpass.getpass("API key (hidden): ").strip() if not api_key: console.print( "[yellow]Warning: No API key provided. " "You'll need to set it manually.[/yellow]" )
providers[provider_name] = { "base_url": base_url, "api_key": f"${{{provider_name.upper()}_API_KEY}}", } env_vars[f"{provider_name.upper()}_API_KEY"] = api_key
if api_key and base_url: console.print(f"\n[cyan]Fetching models from {provider_name}...[/cyan]") available_models = fetch_models(base_url, api_key) selected = select_models(available_models)
for friendly_name, model_id in selected: models[friendly_name] = { "provider": provider_name, "model": model_id, } else: console.print( "[yellow]Skipping model fetch (no API key or base URL)[/yellow]" )
if not Confirm.ask("\nAdd another provider?", default=False): break
# ========================================================================= # STEP 2: SearXNG # ========================================================================= console.print("\n[bold cyan]═══ Step 2: SearXNG (Local Search) ═══[/bold cyan]\n")
setup_searxng = None if yes: setup_searxng = True searxng_port = os.environ.get("SEARXNG_PORT", "2946") env_vars["SEARXNG_PORT"] = searxng_port console.print("[dim]→ --yes mode: defaulting to SearXNG install[/dim]") elif os.environ.get("YES_INSTALL_SEARXNG", "").lower() in ("1", "true", "yes"): setup_searxng = True console.print("[dim]→ YES_INSTALL_SEARXNG=1 detected, skipping prompt[/dim]") searxng_port = os.environ.get("SEARXNG_PORT", "2946") env_vars["SEARXNG_PORT"] = searxng_port else: setup_searxng = Confirm.ask( "Set up local SearXNG search instance? (Requires Docker)", default=True, )
if setup_searxng: searxng_port = Prompt.ask("SearXNG port", default="2946") env_vars["SEARXNG_PORT"] = searxng_port else: searxng_port = None
# ========================================================================= # STEP 2b: RustFS (S3 object store for images) # ========================================================================= console.print( "\n[bold cyan]═══ Step 2b: RustFS (S3 image store) ═══[/bold cyan]\n" )
setup_rustfs = None if yes: setup_rustfs = True console.print("[dim]→ --yes mode: defaulting to RustFS install[/dim]") elif os.environ.get("YES_INSTALL_RUSTFS", "").lower() in ("1", "true", "yes"): setup_rustfs = True console.print("[dim]→ YES_INSTALL_RUSTFS=1 detected, skipping prompt[/dim]") else: setup_rustfs = Confirm.ask( "Set up RustFS S3 object store for images? (Requires Docker; " "falls back to filesystem when down)", default=True, )
if setup_rustfs: env_vars["RUSTFS_PORT"] = os.environ.get("RUSTFS_PORT", "9000") env_vars["RUSTFS_CONSOLE_PORT"] = os.environ.get("RUSTFS_CONSOLE_PORT", "9001") env_vars["RUSTFS_ACCESS_KEY"] = os.environ.get("RUSTFS_ACCESS_KEY", "rustfsadmin") env_vars["RUSTFS_SECRET_KEY"] = os.environ.get("RUSTFS_SECRET_KEY", "rustfsadmin") if not yes: env_vars["RUSTFS_ACCESS_KEY"] = Prompt.ask( "RustFS access key", default=env_vars["RUSTFS_ACCESS_KEY"] ) env_vars["RUSTFS_SECRET_KEY"] = Prompt.ask( "RustFS secret key", default=env_vars["RUSTFS_SECRET_KEY"] )
# ========================================================================= # STEP 2c: PostgreSQL (shared memory database) # ========================================================================= console.print( "\n[bold cyan]═══ Step 2c: PostgreSQL (shared memory DB) ═══[/bold cyan]\n" )
setup_postgres = None if yes: setup_postgres = True console.print("[dim]→ --yes mode: defaulting to PostgreSQL install[/dim]") elif os.environ.get("YES_INSTALL_POSTGRES", "").lower() in ("1", "true", "yes"): setup_postgres = True console.print("[dim]→ YES_INSTALL_POSTGRES=1 detected, skipping prompt[/dim]") else: setup_postgres = Confirm.ask( "Set up PostgreSQL for shared memory? (Requires Docker; " "sqlite is used when skipped)", default=True, )
if setup_postgres: env_vars["POSTGRES_PORT"] = os.environ.get("POSTGRES_PORT", "5432") env_vars["POSTGRES_USER"] = os.environ.get("POSTGRES_USER", "crow") env_vars["POSTGRES_DB"] = os.environ.get("POSTGRES_DB", "crow") env_vars["POSTGRES_PASSWORD"] = os.environ.get( "POSTGRES_PASSWORD", secrets.token_hex(16) ) if not yes: env_vars["POSTGRES_USER"] = Prompt.ask( "PostgreSQL user", default=env_vars["POSTGRES_USER"] ) env_vars["POSTGRES_DB"] = Prompt.ask( "PostgreSQL database", default=env_vars["POSTGRES_DB"] ) env_vars["POSTGRES_PASSWORD"] = Prompt.ask( "PostgreSQL password", default=env_vars["POSTGRES_PASSWORD"] )
# ========================================================================= # STEP 3: Review # ========================================================================= console.print("\n[bold cyan]═══ Step 3: Review ═══[/bold cyan]\n")
if setup_postgres: db_uri = ( "postgresql+psycopg://${POSTGRES_USER}:${POSTGRES_PASSWORD}" "@localhost:${POSTGRES_PORT}/${POSTGRES_DB}" ) else: db_uri = f"sqlite:///{config_dir / 'crow.db'}" console.print(f"[dim]Memory store: {db_uri}[/dim]")
if providers: p_table = Table(title="Providers", show_header=True) p_table.add_column("Name", style="cyan") p_table.add_column("Base URL", style="dim") for name, data in providers.items(): p_table.add_row(name, data["base_url"]) console.print(p_table)
if models: m_table = Table(title="Models", show_header=True) m_table.add_column("Friendly Name", style="green") m_table.add_column("Provider", style="cyan") m_table.add_column("Model ID", style="dim") for name, data in models.items(): m_table.add_row(name, data["provider"], data["model"]) console.print(m_table)
s_table = Table(title="Services", show_header=True) s_table.add_column("Service", style="cyan") s_table.add_column("Status", style="green") s_table.add_row("SearXNG", "✓ Docker" if setup_searxng else "✗ Skip") s_table.add_row("RustFS", "✓ Docker" if setup_rustfs else "✗ Skip") s_table.add_row("PostgreSQL", "✓ Docker" if setup_postgres else "✗ Skip") s_table.add_row( "Memory", "PostgreSQL (shared, docker)" if setup_postgres else "sqlite (crow.db, in-process)", ) s_table.add_row("MCP", "crow-cli mcp over stdio") console.print(s_table)
console.print(f"\n[dim]Config directory: {config_dir}[/dim]") console.print(f"[dim]Memory store: {db_uri}[/dim]")
if not yes and not Confirm.ask("\nLooks good?", default=True): console.print("[red]Aborted. No files were written.[/red]") return
# ========================================================================= # STEP 4: Write files # ========================================================================= console.print("\n[bold cyan]═══ Step 4: Writing Configuration ═══[/bold cyan]\n")
config_dir.mkdir(parents=True, exist_ok=True)
# System prompt template dest_prompts = config_dir / "prompts" dest_prompts.mkdir(parents=True, exist_ok=True) prompt_file = dest_prompts / "system_prompt.jinja2" if not prompt_file.exists(): prompt_file.write_text(SYSTEM_PROMPT) console.print(f"[green]✓[/green] Wrote prompt template to {prompt_file}") else: console.print(f"[yellow]⊘[/yellow] Prompt template already exists, skipping")
# config.yaml — single source of truth for crow-cli config config_data: dict[str, Any] = { "mcpServers": { "crow-mcp": { "transport": "stdio", "command": "crow-cli", "args": ["mcp"], } }, "db_uri": db_uri, "providers": providers, "models": models, "MAX_COMPACT_TOKENS": 190000, "max_retries_per_step": 3, }
if setup_rustfs: # S3 image store — the agent probes this endpoint at init and falls # back to filesystem images when unreachable. Secrets via .env refs. config_data["image_store"] = { "s3": { "endpoint": f"http://localhost:{env_vars['RUSTFS_PORT']}", "bucket": "crow-images", "access_key": "${RUSTFS_ACCESS_KEY}", "secret_key": "${RUSTFS_SECRET_KEY}", } }
with open(config_file, "w") as f: yaml.dump( config_data, f, default_flow_style=False, sort_keys=False, allow_unicode=True, ) console.print(f"[green]✓[/green] Written {config_file}")
# .env — secrets live here, not in config.yaml; keep them owner-only env_lines = [f"{k}={v}" for k, v in env_vars.items()] with open(env_file, "w") as f: f.write("\n".join(env_lines) + "\n") os.chmod(env_file, 0o600) console.print(f"[green]✓[/green] Written {env_file}")
# SearXNG compose + settings (written but NOT started) if setup_searxng: searxng_dir = config_dir / "searxng" searxng_dir.mkdir(exist_ok=True)
with open(searxng_dir / "settings.yml", "w") as f: f.write(SEARXNG_SETTINGS_YML) console.print(f"[green]✓[/green] Wrote SearXNG settings.yml")
# Build compose.yaml from defaults — selectively include services compose_template = yaml.safe_load(COMPOSE_YAML) available_services = compose_template.get("services", {}) active_services: dict[str, Any] = {}
if setup_searxng and "searxng" in available_services: active_services["searxng"] = available_services["searxng"] if setup_rustfs: for svc in ("rustfs", "volume-permission-helper"): if svc in available_services: active_services[svc] = available_services[svc] if setup_postgres and "postgres" in available_services: active_services["postgres"] = available_services["postgres"]
compose_file = config_dir / "compose.yaml" if active_services: compose_data: dict[str, Any] = { "services": active_services, "volumes": compose_template.get("volumes", {}), } # rustfs declares its own network; carry it only when rustfs is in if setup_rustfs and compose_template.get("networks"): compose_data["networks"] = compose_template["networks"] with open(compose_file, "w") as f: yaml.dump(compose_data, f, default_flow_style=False, sort_keys=False) console.print(f"[green]✓[/green] Written {compose_file}")
# Logs directory (config_dir / "logs").mkdir(exist_ok=True)
# ========================================================================= # STEP 5: Source checkout + the crow-cli skill # ========================================================================= # Crow is source-first: there is no non-source distribution. The installed # tool is the bootloader; the checkout at <config_dir>/src/crow-cli is the # program a source-first spawn actually runs (`uv --project ... run crow-cli acp`), so # a `git pull` there is an upgrade and pure-Python changes are live with no # reinstall. The skill is installed GLOBALLY because it is the BIOS — when # a project-level spawn is broken, the agent that fixes it cannot fetch the # skill from the broken thing it is repairing. source_report: dict[str, Any] = {"checkouts": {}, "errors": [], "skill": None} if source: console.print("\n[bold cyan]═══ Step 5: Source & Skills ═══[/bold cyan]\n") source_report = source_bootstrap(config_dir, log=console.print) for error in source_report["errors"]: # type: ignore[index] console.print(f"[yellow]Retry:[/yellow] [dim]{error}[/dim]") else: console.print( "\n[dim]--no-source: skipping the source checkout; a spawn will run " "the installed crow-cli.[/dim]" )
# The default agent server, written down: bare `crow-cli` launches the TOP # agent_servers entry, so init leaves one pointing at the checkout — the # explicit route for what used to be implicit. Only when the checkout # exists; an entry pointing at nothing would break the launch. if add_default_agent_server(config_dir): console.print( f"[green]✓[/green] agent_servers crow-cli → " f"[cyan]{global_checkout(config_dir)}[/cyan]" ) elif not source: console.print( "[dim]--no-source: no checkout, so no agent_servers entry — bare " "`crow-cli` runs the installed crow-cli.[/dim]" )
# ========================================================================= # Done # ========================================================================= config_logs = config_dir / "logs" system_prompt_dir = config_dir / "prompts"
console.print() memory_line = ( f"Memory: [cyan]postgresql → localhost:{env_vars['POSTGRES_PORT']}" f"/{env_vars['POSTGRES_DB']} (docker)[/cyan]" if setup_postgres else f"Memory: [cyan]sqlite → {config_dir / 'crow.db'}[/cyan]" ) done_lines = [ "[bold green]✓ Configuration complete![/bold green]\n", f"Config: [cyan]{config_file}[/cyan]", memory_line, f"Logs: [cyan]{config_logs}[/cyan]", f"Prompt: [cyan]{system_prompt_dir}/system_prompt.jinja2[/cyan]", f"Secrets: [cyan]{env_file}[/cyan]", ] if active_services: done_lines.append(f"Compose: [cyan]{compose_file}[/cyan]") if checkout := source_report["checkouts"].get("crow-cli"): # type: ignore[union-attr] done_lines.append(f"Source: [cyan]{checkout}[/cyan] [dim](git pull = upgrade)[/dim]") if skill := source_report["skill"]: done_lines.append(f"Skill: [cyan]{Path(str(skill)).parent}[/cyan]") done_lines.append(f'[dim]Test:[/dim] [bold white]crow-cli run "hey"[/bold white]') console.print(Panel.fit("\n".join(done_lines), border_style="green"))
# For typer integrationdef init_command(config_dir: Path = None, yes: bool = False, source: bool = True): """Initialize Crow configuration interactively.""" if config_dir is None: config_dir = Path(os.path.expanduser("~/.agents/crow")) run_init(config_dir=config_dir, yes=yes, source=source)