|
| 1 | +"""Headless one-shot fleet dispatch command.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import json |
| 6 | +import os |
| 7 | +from pathlib import Path |
| 8 | +from typing import TYPE_CHECKING, Annotated, NoReturn |
| 9 | + |
| 10 | +from cyclopts import Parameter |
| 11 | + |
| 12 | +from autoskillit.core import get_logger, is_feature_enabled |
| 13 | + |
| 14 | +if TYPE_CHECKING: |
| 15 | + from autoskillit.config import AutomationConfig |
| 16 | + from autoskillit.core import CodingAgentBackend |
| 17 | + from autoskillit.fleet import DispatchResult |
| 18 | + |
| 19 | +logger = get_logger(__name__) |
| 20 | + |
| 21 | + |
| 22 | +def _fleet_run_error(error: str, message: str, exit_code: int = 1) -> NoReturn: |
| 23 | + envelope = {"success": False, "error": error, "user_visible_message": message} |
| 24 | + print(json.dumps(envelope)) |
| 25 | + raise SystemExit(exit_code) |
| 26 | + |
| 27 | + |
| 28 | +async def _execute_fleet_run( |
| 29 | + cfg: AutomationConfig, |
| 30 | + recipe: str, |
| 31 | + task: str, |
| 32 | + ingredients: dict[str, str] | None, |
| 33 | + timeout_sec: int | None, |
| 34 | + dispatch_backend: CodingAgentBackend | None, |
| 35 | + resume_session_id: str | None, |
| 36 | + prior_dispatch_id: str | None, |
| 37 | + disable_quota_guard: bool, |
| 38 | +) -> DispatchResult: |
| 39 | + import functools |
| 40 | + |
| 41 | + from autoskillit.core import detect_autoskillit_mcp_prefix |
| 42 | + from autoskillit.fleet import _build_food_truck_prompt, execute_dispatch |
| 43 | + from autoskillit.server import make_context |
| 44 | + |
| 45 | + ctx = make_context(cfg, project_dir=Path.cwd()) |
| 46 | + |
| 47 | + effective_backend = dispatch_backend or ctx.backend |
| 48 | + has_ufa = ( |
| 49 | + effective_backend.capabilities.has_unguarded_filesystem_access |
| 50 | + if effective_backend |
| 51 | + else False |
| 52 | + ) |
| 53 | + prompt_builder = functools.partial( |
| 54 | + _build_food_truck_prompt, |
| 55 | + mcp_prefix=detect_autoskillit_mcp_prefix(), |
| 56 | + has_unguarded_filesystem_access=has_ufa, |
| 57 | + ) |
| 58 | + |
| 59 | + if disable_quota_guard: |
| 60 | + |
| 61 | + async def quota_checker(_cfg: object) -> dict[str, object]: |
| 62 | + return {"should_sleep": False} |
| 63 | + else: |
| 64 | + from autoskillit.execution import check_and_sleep_if_needed |
| 65 | + |
| 66 | + _supports_quota = ( |
| 67 | + effective_backend.capabilities.anthropic_provider_capable |
| 68 | + if effective_backend |
| 69 | + else True |
| 70 | + ) |
| 71 | + |
| 72 | + async def quota_checker(_cfg: object) -> dict[str, object]: |
| 73 | + return await check_and_sleep_if_needed( |
| 74 | + _cfg, provider="anthropic" if _supports_quota else "" |
| 75 | + ) |
| 76 | + |
| 77 | + async def quota_refresher(_cfg: object) -> None: |
| 78 | + pass |
| 79 | + |
| 80 | + return await execute_dispatch( |
| 81 | + tool_ctx=ctx, |
| 82 | + recipe=recipe, |
| 83 | + task=task, |
| 84 | + ingredients=ingredients, |
| 85 | + dispatch_name=None, |
| 86 | + timeout_sec=timeout_sec, |
| 87 | + prompt_builder=prompt_builder, |
| 88 | + quota_checker=quota_checker, |
| 89 | + quota_refresher=quota_refresher, |
| 90 | + cache_invalidator=None, |
| 91 | + resume_session_id=resume_session_id, |
| 92 | + prior_dispatch_id=prior_dispatch_id, |
| 93 | + dispatch_backend=dispatch_backend, |
| 94 | + ) |
| 95 | + |
| 96 | + |
| 97 | +def fleet_run( |
| 98 | + recipe: str, |
| 99 | + *, |
| 100 | + task: Annotated[str, Parameter(name=["--task", "-t"])] = "", |
| 101 | + ingredient: Annotated[tuple[str, ...], Parameter(name=["--ingredient", "-i"])] = (), |
| 102 | + backend: Annotated[str | None, Parameter(name=["--backend"])] = None, |
| 103 | + timeout_sec: Annotated[int | None, Parameter(name=["--timeout-sec"])] = None, |
| 104 | + resume_session_id: Annotated[str | None, Parameter(name=["--resume-session-id"])] = None, |
| 105 | + prior_dispatch_id: Annotated[str | None, Parameter(name=["--prior-dispatch-id"])] = None, |
| 106 | + disable_quota_guard: Annotated[bool, Parameter(name=["--disable-quota-guard"])] = False, |
| 107 | +) -> None: |
| 108 | + """One-shot headless recipe dispatch (experimental). |
| 109 | +
|
| 110 | + Dispatches a single recipe run non-interactively. Prints the dispatch |
| 111 | + result envelope as JSON on stdout. Exit 0 on SUCCESS, nonzero otherwise. |
| 112 | + """ |
| 113 | + # --- Session-type guard (retained for headless — prevents recursive dispatch) --- |
| 114 | + if os.environ.get("AUTOSKILLIT_SESSION_TYPE") in ("skill", "leaf"): |
| 115 | + _fleet_run_error( |
| 116 | + "FLEET_SESSION_TYPE_BLOCKED", |
| 117 | + "'fleet run' cannot run inside a skill or leaf session.", |
| 118 | + ) |
| 119 | + # NOTE: CLAUDECODE guard intentionally NOT applied — REQ-HFD-006 |
| 120 | + |
| 121 | + # --- Config + feature gates --- |
| 122 | + from autoskillit.config import load_config |
| 123 | + |
| 124 | + try: |
| 125 | + cfg = load_config(Path.cwd()) |
| 126 | + except Exception as exc: |
| 127 | + logger.error("fleet run: failed to load config", exc_info=True) |
| 128 | + _fleet_run_error("FLEET_CONFIG_ERROR", f"Failed to load config: {exc}") |
| 129 | + |
| 130 | + # Fleet base feature check (equivalent to _require_fleet but with JSON output) |
| 131 | + if not is_feature_enabled( |
| 132 | + "fleet", cfg.features, experimental_enabled=cfg.experimental_enabled |
| 133 | + ): |
| 134 | + _fleet_run_error( |
| 135 | + "FLEET_FEATURE_DISABLED", |
| 136 | + "The 'fleet' feature is not enabled.\n" |
| 137 | + "Enable with: features.experimental_enabled: true in your config\n" |
| 138 | + "Or set: AUTOSKILLIT_FEATURES__FLEET=true", |
| 139 | + ) |
| 140 | + |
| 141 | + # Headless run feature check |
| 142 | + if not is_feature_enabled( |
| 143 | + "fleet_headless_run", |
| 144 | + cfg.features, |
| 145 | + experimental_enabled=cfg.experimental_enabled, |
| 146 | + ): |
| 147 | + _fleet_run_error( |
| 148 | + "FLEET_FEATURE_DISABLED", |
| 149 | + "The 'fleet_headless_run' feature is not enabled.\n" |
| 150 | + "Enable with: features.experimental_enabled: true\n" |
| 151 | + "Or: features.fleet_headless_run: true\n" |
| 152 | + "Or: AUTOSKILLIT_FEATURES__FLEET_HEADLESS_RUN=true", |
| 153 | + ) |
| 154 | + |
| 155 | + # --- Parse ingredients --- |
| 156 | + ingredients: dict[str, str] | None = None |
| 157 | + if ingredient: |
| 158 | + ingredients = {} |
| 159 | + for item in ingredient: |
| 160 | + if "=" not in item: |
| 161 | + _fleet_run_error( |
| 162 | + "FLEET_INVALID_ARGUMENT", |
| 163 | + f"Ingredient must be key=value, got: {item!r}", |
| 164 | + ) |
| 165 | + k, v = item.split("=", 1) |
| 166 | + ingredients[k] = v |
| 167 | + |
| 168 | + # --- Resolve backend --- |
| 169 | + dispatch_backend = None |
| 170 | + if backend is not None: |
| 171 | + from autoskillit.server import resolve_backend_override |
| 172 | + |
| 173 | + try: |
| 174 | + dispatch_backend = resolve_backend_override(backend) |
| 175 | + except ValueError as exc: |
| 176 | + _fleet_run_error("FLEET_INVALID_BACKEND", str(exc)) |
| 177 | + |
| 178 | + # --- Run dispatch --- |
| 179 | + import asyncio |
| 180 | + |
| 181 | + from autoskillit.fleet import DispatchRejected, DispatchStatus |
| 182 | + |
| 183 | + try: |
| 184 | + result = asyncio.run( |
| 185 | + _execute_fleet_run( |
| 186 | + cfg=cfg, |
| 187 | + recipe=recipe, |
| 188 | + task=task, |
| 189 | + ingredients=ingredients, |
| 190 | + timeout_sec=timeout_sec, |
| 191 | + dispatch_backend=dispatch_backend, |
| 192 | + resume_session_id=resume_session_id, |
| 193 | + prior_dispatch_id=prior_dispatch_id, |
| 194 | + disable_quota_guard=disable_quota_guard, |
| 195 | + ) |
| 196 | + ) |
| 197 | + except KeyboardInterrupt as exc: |
| 198 | + logger.error("fleet run: dispatch interrupted: %s", exc) |
| 199 | + _fleet_run_error( |
| 200 | + "FLEET_DISPATCH_INTERRUPTED", "Dispatch interrupted by signal.", exit_code=1 |
| 201 | + ) |
| 202 | + except Exception as exc: |
| 203 | + logger.error("fleet run: dispatch crashed", exc_info=True) |
| 204 | + _fleet_run_error("FLEET_L3_STARTUP_OR_CRASH", str(exc)) |
| 205 | + |
| 206 | + # --- Output result envelope --- |
| 207 | + print(result.outcome.to_envelope()) |
| 208 | + |
| 209 | + # --- Exit code (DispatchRejected has no .success/.dispatch_status — check it first) --- |
| 210 | + if isinstance(result.outcome, DispatchRejected): |
| 211 | + raise SystemExit(3) |
| 212 | + if result.outcome.success: |
| 213 | + raise SystemExit(0) |
| 214 | + if result.outcome.dispatch_status == DispatchStatus.RESUMABLE: |
| 215 | + raise SystemExit(2) |
| 216 | + raise SystemExit(1) |
0 commit comments