Skip to content

"Vibe-Trading: Your Personal Trading Agent"

39.8 KB
Raw Blame
"""Scheduled research HTTP routes.

Mounted by ``agent/api_server.py`` via ``register_scheduled_routes(app, ...)``.
"""

from __future__ import annotations

import logging
import sys as _sys
import time
import uuid
from typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict, List, Literal, Optional

from fastapi import Depends, FastAPI, HTTPException, Query, status
from pydantic import BaseModel, Field
from starlette.responses import Response

from src.config.accessor import get_env_config
from src.scheduled_research.models import contains_pdf_password

if TYPE_CHECKING:
    from src.scheduled_research.models import ScheduledResearchJob

logger = logging.getLogger(__name__)


# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------

_SCHEDULED_RESEARCH_SCHEDULER_ENV = "VIBE_TRADING_ENABLE_SCHEDULER"
_SCHEDULED_RESEARCH_TRUE_VALUES = {"1", "true", "yes", "on"}


# ---------------------------------------------------------------------------
# Module-level state
# ---------------------------------------------------------------------------

_scheduled_research_store: Any = None
_scheduled_research_executor: Any = None


def _scheduled_research_scheduler_enabled() -> bool:
    """Return whether scheduled research execution is enabled."""
    return get_env_config().agent_tuning.vibe_trading_enable_scheduler


def _get_scheduled_research_store():
    """Return the singleton ScheduledResearchJobStore, creating it on first call."""
    global _scheduled_research_store
    if _scheduled_research_store is None:
        from src.scheduled_research.store import ScheduledResearchJobStore

        _scheduled_research_store = ScheduledResearchJobStore()
    return _scheduled_research_store


async def _dispatch_scheduled_research_job(job) -> Optional[str]:
    """Enqueue one scheduled research job through the session runtime.

    ``send_message`` queues the agent attempt and returns once accepted; it
    does not wait for that agent run to reach a terminal status. The executor's
    ``COMPLETED`` state for this dispatch path means "successfully enqueued."

    Returns:
        The session id the attempt was enqueued into, which is what lets the
        delivery outbox find the briefing once the run actually finishes.
    """
    host = _sys.modules.get("api_server") or _sys.modules.get("agent.api_server")
    svc = host._get_session_service()
    if not svc:
        raise RuntimeError("Session runtime not enabled")
    # Pass a copy so the session runtime's internal config writes (e.g.
    # include_shell_tools) do not mutate the persisted scheduled-run config.
    session = svc.create_session(
        title=f"scheduled-research:{job.id}", config=dict(job.config)
    )
    logger.info(
        "dispatching scheduled research job %s via session %s",
        job.id,
        session.session_id,
    )
    await svc.send_message(session.session_id, job.prompt)
    return session.session_id


def _read_scheduled_briefing(session_id: str) -> Optional[tuple[str, str]]:
    """Return ``(terminal status, briefing text)`` once a run has finished.

    The assistant reply carries the attempt's terminal status in its metadata,
    and it is the same text the user sees in the session — delivering anything
    else would mean the channel and the app disagree about what the run said.

    Args:
        session_id: Session the scheduled run was dispatched into.

    Returns:
        The status and text, or ``None`` while the run is still in flight.
    """
    host = _sys.modules.get("api_server") or _sys.modules.get("agent.api_server")
    svc = host._get_session_service() if host else None
    if not svc:
        return None
    for message in reversed(svc.get_messages(session_id, limit=50)):
        if message.role != "assistant":
            continue
        status = (message.metadata or {}).get("status")
        if isinstance(status, str) and status:
            return status, message.content or ""
    return None


async def _send_scheduled_briefing(
    channel: str,
    target: Optional[str],
    text: str,
    delivery_format: Optional[str] = None,
    protect_pdf: bool = False,
):
    """Deliver one briefing through the configured IM channel.

    Args:
        channel: Channel id as configured in the channel runtime.
        target: Explicit destination within that channel; missing targets fail.
        text: The briefing to deliver.
        delivery_format: Optional presentation hint for channels that support it.
        protect_pdf: Whether the generated PDF must be password protected.

    Raises:
        RuntimeError: If the channel runtime is unavailable or has no such
            channel, so the outbox records a retryable failure rather than
            reporting a delivery that never happened.
    """
    from src.channels.bus.events import OutboundMessage

    host = _sys.modules.get("api_server") or _sys.modules.get("agent.api_server")
    manager = getattr(host, "_channel_manager", None) if host else None
    if manager is None:
        raise RuntimeError("channel runtime is not running")
    adapter = manager.get_channel(channel)
    if adapter is None:
        raise RuntimeError(f"channel {channel!r} is not configured")
    if not target:
        raise RuntimeError(f"channel {channel!r} has no delivery target configured")
    metadata = {"force_send": True}
    if delivery_format:
        metadata["delivery_format"] = delivery_format
    if protect_pdf:
        metadata["protect_pdf"] = True
    return await adapter.send_with_receipt(
        OutboundMessage(channel=channel, chat_id=target, content=text, metadata=metadata)
    )


def _get_scheduled_research_executor():
    """Return the singleton scheduled research executor."""
    global _scheduled_research_executor
    if _scheduled_research_executor is None:
        from src.scheduled_research.executor import ScheduledResearchExecutor
        from src.scheduled_research.internal_dispatch import resolve_scheduled_internal_callable

        _scheduled_research_executor = ScheduledResearchExecutor(
            _get_scheduled_research_store(),
            _dispatch_scheduled_research_job,
            enabled=_scheduled_research_scheduler_enabled(),
            briefing_reader=_read_scheduled_briefing,
            channel_sender=_send_scheduled_briefing,
            internal_dispatcher=resolve_scheduled_internal_callable,
        )
    return _scheduled_research_executor


def _start_scheduled_research_executor() -> None:
    """Start scheduled research execution when explicitly enabled.

    Single-writer invariant: the FastAPI lifespan is the SOLE owner of this
    call (``src/scheduled_research/store.py``); a duplicate ``start()`` is a
    no-op. ``ensure_system_jobs`` runs BEFORE ``start()`` (timing contract in
    :mod:`src.scheduling.system_jobs`); master flag off early-returns.
    """
    if not _scheduled_research_scheduler_enabled():
        return
    from src.scheduling.system_jobs import ensure_system_jobs

    ensure_system_jobs(_get_scheduled_research_store())
    _get_scheduled_research_executor().start()


async def _stop_scheduled_research_on_shutdown() -> None:
    """Stop live drivers, channels and research even if one service fails."""
    from src.api.channels_routes import _stop_channel_runtime
    from src.api.live_routes import _stop_live_runners

    host = _sys.modules.get("api_server")
    try:
        await getattr(host, "_stop_live_runners", _stop_live_runners)()
    finally:
        try:
            await getattr(host, "_stop_channel_runtime", _stop_channel_runtime)()
        finally:
            await getattr(host, "_stop_scheduled_research_executor", _stop_scheduled_research_executor)()


async def _stop_scheduled_research_executor() -> None:
    """Stop scheduled research execution if it was started."""
    executor = _scheduled_research_executor
    if executor is not None:
        await executor.stop()


# ---------------------------------------------------------------------------
# Pydantic models
# ---------------------------------------------------------------------------


class CreateScheduledRunRequest(BaseModel):
    """Request body for POST /scheduled-runs."""

    id: Optional[str] = Field(
        None,
        description=(
            "Job id; auto-generated UUID when omitted. Must match the id rule "
            "the delete route enforces: letters, digits, '_' and '-', 1-128 "
            "characters."
        ),
    )
    prompt: str = Field(
        ..., min_length=1, description="Research prompt or backtest description"
    )
    title: Optional[str] = Field(None, description="Human-readable monitor title")
    schedule: str = Field(
        ..., min_length=1, description="Interval-ms or 5-field cron expression"
    )
    next_run_at: Optional[int] = Field(
        None, description="Epoch-ms for next run; defaults to now"
    )
    config: Dict[str, Any] = Field(
        default_factory=dict, description="Optional backtest parameters"
    )
    timezone: Optional[str] = Field(
        None,
        description=(
            "IANA timezone key the cron schedule is evaluated in "
            "(e.g. 'Pacific/Auckland'); null = UTC, the pre-existing "
            "semantics. Ignored by interval schedules."
        ),
    )
    delivery_channel: Optional[str] = Field(
        None,
        description=(
            "Channel id a finished briefing is pushed to. Delivery is opt-in "
            "per job: omit this and results stay in the app, which is the "
            "behaviour every existing job keeps."
        ),
    )
    delivery_target: Optional[str] = Field(
        None,
        description="Address within that channel (chat / group / user id).",
    )
    delivery_target_ref: Optional[str] = Field(
        None, description="Opaque operator-configured target ref; preferred over raw target ids"
    )
    delivery_format: Optional[Literal["html", "pdf"]] = Field(
        None, description="Email report presentation: HTML body or PDF attachment"
    )
    protect_pdf: bool = Field(False, description="Password-protect the generated PDF")
    end_at: Optional[int] = Field(
        None, description="Epoch-ms boundary after which no further run is dispatched"
    )


class UpdateScheduledRunRequest(BaseModel):
    """Mutable authored fields for an existing scheduled research job.

    Omitted fields are preserved. Explicit null clears nullable fields such as
    timezone, end_at, and delivery. Runtime/history fields are never client
    writable.
    """

    prompt: Optional[str] = Field(
        None, min_length=1, description="Replacement research prompt"
    )
    title: Optional[str] = Field(None, description="Human-readable monitor title")
    schedule: Optional[str] = Field(
        None, min_length=1, description="Replacement interval-ms or 5-field cron"
    )
    config: Optional[Dict[str, Any]] = Field(
        None, description="Replacement session/backtest config"
    )
    timezone: Optional[str] = Field(
        None, description="Replacement IANA timezone; null means UTC"
    )
    delivery_channel: Optional[str] = Field(
        None, description="Replacement delivery channel; null disables delivery"
    )
    delivery_target: Optional[str] = Field(
        None, description="Replacement address within the delivery channel"
    )
    delivery_target_ref: Optional[str] = Field(
        None, description="Replacement opaque configured target ref"
    )
    delivery_format: Optional[Literal["html", "pdf"]] = Field(
        None, description="Email presentation; null restores plain text"
    )
    protect_pdf: Optional[bool] = Field(None, description="Replace the PDF protection choice")
    end_at: Optional[int] = Field(
        None, description="Replacement epoch-ms end boundary; null removes it"
    )


class PlaybookResponse(BaseModel):
    """Catalogue record for one research playbook template.

    ``body`` is the raw instruction text with ``{{placeholders}}`` unresolved.
    It is populated only by the single-template endpoint; the list endpoint
    leaves it null so a catalogue response stays small.
    """

    slug: str
    name: str
    description: str
    suggested_schedule: str
    suggested_timezone: Optional[str] = None
    markets: List[str] = Field(default_factory=list)
    data_capabilities: List[str] = Field(default_factory=list)
    variables: Dict[str, str] = Field(default_factory=dict)
    body: Optional[str] = None


class CreateRunFromPlaybookRequest(BaseModel):
    """Request body for POST /scheduled-runs/playbooks/{slug}.

    Every field is optional: posting ``{}`` schedules the template on its own
    suggested cadence with its declared variable defaults.
    """

    id: Optional[str] = Field(
        None, description="Job id; defaults to a slug-prefixed generated id"
    )
    schedule: Optional[str] = Field(
        None,
        min_length=1,
        description=(
            "Schedule override (interval-ms or 5-field cron); defaults to the "
            "template's suggested_schedule"
        ),
    )
    timezone: Optional[str] = Field(
        None,
        description=(
            "IANA timezone override. Omit the field to keep the template's "
            "suggested_timezone; send null explicitly to force UTC."
        ),
    )
    variables: Dict[str, str] = Field(
        default_factory=dict,
        description=(
            "Overrides for the template's declared variables. An undeclared "
            "name is rejected rather than silently ignored."
        ),
    )
    config: Dict[str, Any] = Field(
        default_factory=dict, description="Session config forwarded to the agent run"
    )
    next_run_at: Optional[int] = Field(
        None, description="Explicit first-fire epoch-ms, bypassing the default rule"
    )
    title: Optional[str] = None
    end_at: Optional[int] = None
    delivery_target_ref: Optional[str] = None
    delivery_format: Optional[Literal["html", "pdf"]] = None
    protect_pdf: bool = False


class ScheduledRunResponse(BaseModel):
    """API response for a single scheduled job."""

    id: str
    prompt: str
    title: str = ""
    source_type: str = "prompt"
    playbook_slug: Optional[str] = None
    end_at: Optional[int] = None
    schedule: str
    next_run_at: int
    status: str
    created_at: int
    last_run_at: Optional[int] = None
    consecutive_failures: int = 0
    last_error: Optional[str] = None
    failure_kind: Optional[str] = None
    config: Dict[str, Any] = Field(default_factory=dict)
    timezone: Optional[str] = None
    delivery_channel: Optional[str] = None
    delivery_target: Optional[str] = None
    delivery_target_ref: Optional[str] = None
    delivery_target_label: Optional[str] = None
    delivery_format: Optional[str] = None
    protect_pdf: bool = False
    delivery_status: str = "none"
    delivery_error: Optional[str] = None
    delivery_updated_at: Optional[int] = None
    delivery_attempts: int = 0
    delivery_provider_message_id: Optional[str] = None
    last_verdict: Optional[Dict[str, Any]] = None


def _job_to_response(job: ScheduledResearchJob) -> "ScheduledRunResponse":
    """Flatten a job for the wire, delivery record included.

    ``to_dict`` nests the outbox row; the API keeps it flat because the list
    view reads it per row and a nested object would make every consumer reach
    through a key that means nothing to them.

    Args:
        job: The stored job.

    Returns:
        The response model for that job.
    """
    payload = job.to_dict()
    delivery = payload.pop("delivery", {}) or {}
    last_verdict = payload.pop("last_verdict", None)
    return ScheduledRunResponse(
        **payload,
        last_verdict=last_verdict,
        delivery_status=delivery.get("status", "none"),
        delivery_error=delivery.get("error"),
        delivery_updated_at=delivery.get("updated_at"),
        delivery_attempts=delivery.get("attempts", 0),
        delivery_provider_message_id=delivery.get("provider_message_id"),
    )


def _email_pdf_password_configured() -> bool:
    """Read only whether the private Email PDF password is configured."""
    from src.scheduled_research.service import email_pdf_password_configured

    return email_pdf_password_configured()


# ---------------------------------------------------------------------------
# Registration
# ---------------------------------------------------------------------------

AuthDep = Callable[..., Awaitable[Any] | Any]


def register_scheduled_routes(
    app: FastAPI,
    require_auth: AuthDep | None = None,
) -> None:
    """Mount the scheduled routes onto ``app``.

    Resolves ``require_auth`` from the host ``api_server`` module via
    ``sys.modules`` when not passed explicitly.
    """
    host = _sys.modules.get("api_server") or _sys.modules.get("agent.api_server")

    if host is None:
        raise RuntimeError(
            "register_scheduled_routes: api_server module not in sys.modules; "
            "ensure api_server is imported before calling this function"
        )

    if require_auth is None:
        require_auth = host.require_auth

    def _host_validate_path_param(value: str, kind: str) -> None:
        h = _sys.modules.get("api_server") or _sys.modules.get("agent.api_server")
        h._validate_path_param(value, kind)

    # --- Routes ---

    @app.post(
        "/scheduled-runs",
        response_model=ScheduledRunResponse,
        status_code=status.HTTP_201_CREATED,
        dependencies=[Depends(require_auth)],
    )
    async def create_scheduled_run(
        request: CreateScheduledRunRequest,
    ) -> ScheduledRunResponse:
        """Create (or replace) a scheduled research job.

        The job is persisted immediately. No execution is triggered.
        """
        from src.api.scheduled_guards import ensure_authorable_job_id
        from src.scheduled_research.executor import next_due
        from src.scheduled_research.models import (
            JobStatus,
            ScheduledResearchJob,
            is_interval_schedule,
            validate_schedule,
            validate_timezone,
            validate_timezone_shape,
        )

        ensure_authorable_job_id(request.id)
        if contains_pdf_password(request.config):
            raise HTTPException(status_code=422, detail="config must not include pdf_password")

        try:
            validate_schedule(request.schedule)
            # Interval schedules ignore the timezone, and the executor
            # deliberately skips resolving it for them so an interval job keeps
            # advancing on a host whose timezone database lacks the key. The
            # create path follows the same rule: only a cron schedule, whose
            # evaluation actually needs the zone, resolves it. Both forms still
            # reject a blank value.
            if is_interval_schedule(request.schedule):
                validate_timezone_shape(request.timezone)
            else:
                validate_timezone(request.timezone)
        except ValueError as exc:
            raise HTTPException(status_code=422, detail=str(exc)) from exc

        now_ms = int(time.time() * 1000)
        next_run_at = request.next_run_at
        if next_run_at is None:
            next_run_at = now_ms
            if request.timezone is not None and not is_interval_schedule(request.schedule):
                # A timezone-carrying cron job's contract is the authored wall
                # clock, so its first fire is the first authored occurrence —
                # not the creation moment. Interval jobs and timezone-less
                # jobs keep the pre-existing immediate-first-fire default.
                try:
                    next_run_at = next_due(request.schedule, now_ms, request.timezone)
                except ValueError as exc:
                    raise HTTPException(status_code=422, detail=str(exc)) from exc

        if request.end_at is not None:
            if request.end_at <= now_ms:
                raise HTTPException(status_code=422, detail="end_at must be in the future")
            if next_run_at > request.end_at:
                raise HTTPException(
                    status_code=422, detail="the first scheduled run occurs after end_at"
                )

        delivery_channel = request.delivery_channel
        delivery_target = request.delivery_target
        delivery_target_label = None
        if request.delivery_target_ref:
            from src.channels.targets import resolve_delivery_target

            try:
                resolved_target = resolve_delivery_target(request.delivery_target_ref)
            except ValueError as exc:
                raise HTTPException(status_code=422, detail=str(exc)) from exc
            delivery_channel = resolved_target.channel
            delivery_target = resolved_target.target
            delivery_target_label = resolved_target.label
        delivery_channel = (delivery_channel or "").strip() or None
        delivery_target = (delivery_target or "").strip() or None
        if delivery_channel is None:
            delivery_target = None
        elif delivery_target is None:
            raise HTTPException(
                status_code=422,
                detail="delivery_target is required when delivery_channel is set",
            )

        if request.delivery_format is not None and delivery_channel != "email":
            raise HTTPException(
                status_code=422,
                detail="delivery_format is supported only for email delivery",
            )
        if request.protect_pdf and request.delivery_format != "pdf":
            raise HTTPException(status_code=422, detail="protect_pdf requires PDF email delivery")
        if request.protect_pdf and delivery_channel != "email":
            raise HTTPException(status_code=422, detail="protect_pdf requires Email delivery")
        if request.protect_pdf and not _email_pdf_password_configured():
            raise HTTPException(
                status_code=422,
                detail="PDF protection requested but no PDF password is configured",
            )

        job = ScheduledResearchJob(
            id=request.id or str(uuid.uuid4()),
            title=request.title or "",
            prompt=request.prompt,
            schedule=request.schedule,
            next_run_at=next_run_at,
            status=JobStatus.PENDING,
            created_at=now_ms,
            config=request.config,
            timezone=request.timezone,
            end_at=request.end_at,
            delivery_channel=delivery_channel,
            delivery_target=delivery_target,
            delivery_target_ref=request.delivery_target_ref,
            delivery_target_label=delivery_target_label,
            delivery_format=request.delivery_format,
            protect_pdf=request.protect_pdf,
        )
        _get_scheduled_research_store().upsert(job)
        return _job_to_response(job)

    @app.get(
        "/scheduled-runs",
        response_model=List[ScheduledRunResponse],
        dependencies=[Depends(require_auth)],
    )
    async def list_scheduled_runs(
        status_filter: Optional[str] = Query(None, alias="status"),
        limit: int = Query(50, ge=1, le=200),
    ) -> List[ScheduledRunResponse]:
        """List scheduled research jobs, optionally filtered by status."""
        jobs = _get_scheduled_research_store().list_jobs(
            status=status_filter, limit=limit
        )
        return [_job_to_response(j) for j in jobs]

    @app.get(
        "/scheduled-runs/status",
        dependencies=[Depends(require_auth)],
    )
    async def get_scheduled_research_status() -> Dict[str, Any]:
        from src.channels.targets import list_delivery_targets
        from src.scheduled_research.service import scheduler_status

        payload = scheduler_status()
        payload["delivery_targets"] = [
            target.public_dict() for target in list_delivery_targets()
        ]
        return payload

    @app.post(
        "/scheduled-runs/proposals/{proposal_id}/commit",
        dependencies=[Depends(require_auth)],
    )
    async def commit_scheduled_research_proposal(proposal_id: str) -> Dict[str, Any]:
        from src.scheduled_research.proposals import ProposalError, commit_proposal

        try:
            return commit_proposal(proposal_id)
        except ProposalError as exc:
            raise HTTPException(status_code=409, detail=str(exc)) from exc

    @app.post(
        "/scheduled-runs/proposals/{proposal_id}/discard",
        dependencies=[Depends(require_auth)],
    )
    async def discard_scheduled_research_proposal(proposal_id: str) -> Dict[str, Any]:
        from src.scheduled_research.proposals import ProposalError, discard_proposal

        try:
            return discard_proposal(proposal_id)
        except ProposalError as exc:
            raise HTTPException(status_code=404, detail=str(exc)) from exc


    @app.patch(
        "/scheduled-runs/{job_id}",
        response_model=ScheduledRunResponse,
        dependencies=[Depends(require_auth)],
    )
    async def update_scheduled_run(
        job_id: str,
        request: UpdateScheduledRunRequest,
    ) -> ScheduledRunResponse:
        """Update future configuration without deleting the job or its history."""
        from src.api.scheduled_guards import guard_system_job_mutation
        from src.scheduled_research.executor import next_due
        from src.scheduled_research.models import (
            DeliveryRecord,
            DeliveryStatus,
            JobStatus,
            is_interval_schedule,
            validate_schedule,
            validate_timezone,
            validate_timezone_shape,
        )

        _host_validate_path_param(job_id, "job_id")
        store = _get_scheduled_research_store()
        job = store.get(job_id)
        if job is None:
            raise HTTPException(
                status_code=404, detail=f"scheduled run {job_id} not found"
            )
        guard_system_job_mutation(job.id, job.source_type)
        if job.status == JobStatus.RUNNING or job.delivery.status == DeliveryStatus.SENDING:
            raise HTTPException(
                status_code=409,
                detail="a running scheduled run or active delivery cannot be edited; retry after it finishes",
            )

        fields = request.model_fields_set
        if not fields:
            return _job_to_response(job)

        prompt = job.prompt
        if "prompt" in fields:
            if request.prompt is None or not request.prompt.strip():
                raise HTTPException(status_code=422, detail="prompt must not be blank")
            prompt = request.prompt

        title = job.title
        if "title" in fields:
            title = request.title or ""

        schedule = job.schedule
        if "schedule" in fields:
            if request.schedule is None:
                raise HTTPException(status_code=422, detail="schedule must not be null")
            schedule = request.schedule

        timezone = job.timezone if "timezone" not in fields else request.timezone
        config = job.config if "config" not in fields else (request.config or {})
        if contains_pdf_password(config):
            raise HTTPException(status_code=422, detail="config must not include pdf_password")
        end_at = job.end_at if "end_at" not in fields else request.end_at

        try:
            validate_schedule(schedule)
            if is_interval_schedule(schedule):
                validate_timezone_shape(timezone)
            else:
                validate_timezone(timezone)
        except ValueError as exc:
            raise HTTPException(status_code=422, detail=str(exc)) from exc

        now_ms = int(time.time() * 1000)
        if "end_at" in fields and end_at is not None and end_at <= now_ms:
            raise HTTPException(status_code=422, detail="end_at must be in the future")

        # Interval schedules are timezone-agnostic. A timezone-only edit must
        # not move their next fire time; only cron schedules use timezone as
        # part of their execution cadence.
        schedule_changed = schedule != job.schedule or (
            not is_interval_schedule(schedule) and timezone != job.timezone
        )
        next_run_at = job.next_run_at
        if schedule_changed:
            if is_interval_schedule(schedule):
                next_run_at = now_ms
            else:
                try:
                    next_run_at = next_due(schedule, now_ms, timezone)
                except ValueError as exc:
                    raise HTTPException(status_code=422, detail=str(exc)) from exc
        if end_at is not None and next_run_at > end_at:
            raise HTTPException(
                status_code=422, detail="the next scheduled run occurs after end_at"
            )

        delivery_fields = {
            "delivery_channel",
            "delivery_target",
            "delivery_target_ref",
            "protect_pdf",
        }
        delivery_requested = bool(delivery_fields & fields)
        delivery_channel = job.delivery_channel
        delivery_target = job.delivery_target
        delivery_target_ref = job.delivery_target_ref
        delivery_target_label = job.delivery_target_label

        if delivery_requested:
            if request.delivery_target_ref:
                from src.channels.targets import resolve_delivery_target

                try:
                    resolved = resolve_delivery_target(request.delivery_target_ref)
                except ValueError as exc:
                    raise HTTPException(status_code=422, detail=str(exc)) from exc
                delivery_channel = resolved.channel
                delivery_target = resolved.target
                delivery_target_ref = resolved.ref
                delivery_target_label = resolved.label
            else:
                if "delivery_channel" in fields:
                    new_channel = (request.delivery_channel or "").strip()
                    if (
                        new_channel != (job.delivery_channel or "")
                        and "delivery_target" not in fields
                    ):
                        delivery_target = None
                    delivery_channel = new_channel or None
                if "delivery_target" in fields:
                    new_target = (request.delivery_target or "").strip()
                    delivery_target = new_target or None
                # A raw channel/target edit supersedes any prior opaque ref.
                delivery_target_ref = None
                delivery_target_label = None
                if delivery_channel is None:
                    delivery_target = None
                elif delivery_target is None:
                    raise HTTPException(
                        status_code=422,
                        detail="delivery_target is required when delivery_channel is set",
                    )

        delivery_format = job.delivery_format
        protect_pdf = job.protect_pdf
        if "delivery_format" in fields:
            delivery_format = request.delivery_format
        if "protect_pdf" in fields:
            protect_pdf = request.protect_pdf is True
        if delivery_channel != "email" and "delivery_format" not in fields:
            delivery_format = None
        if delivery_format is not None and delivery_channel != "email":
            raise HTTPException(
                status_code=422, detail="delivery_format is supported only for email delivery"
            )
        if delivery_channel != "email":
            protect_pdf = False
        if protect_pdf and delivery_format != "pdf":
            raise HTTPException(status_code=422, detail="protect_pdf requires PDF email delivery")
        if protect_pdf and delivery_channel != "email":
            raise HTTPException(status_code=422, detail="protect_pdf requires Email delivery")
        if protect_pdf and not _email_pdf_password_configured():
            raise HTTPException(
                status_code=422,
                detail="PDF protection requested but no PDF password is configured",
            )

        delivery_changed = delivery_format != job.delivery_format or protect_pdf != job.protect_pdf or delivery_requested and (
            delivery_channel != job.delivery_channel
            or delivery_target != job.delivery_target
            or delivery_target_ref != job.delivery_target_ref
            or delivery_target_label != job.delivery_target_label
        )

        job.prompt = prompt
        job.title = title
        job.schedule = schedule
        job.config = config
        job.timezone = timezone
        job.end_at = end_at
        job.next_run_at = next_run_at
        if delivery_changed:
            job.delivery_format = delivery_format
            job.protect_pdf = protect_pdf
            job.delivery_channel = delivery_channel
            job.delivery_target = delivery_target
            job.delivery_target_ref = delivery_target_ref
            job.delivery_target_label = delivery_target_label
            # The previous outbox receipt describes the old destination. Clear
            # it rather than presenting that receipt as if it belonged to the
            # newly-authored delivery configuration.
            job.delivery = DeliveryRecord(session_id=job.delivery.session_id)

        store.upsert(job)
        return _job_to_response(job)

    @app.delete(
        "/scheduled-runs/{job_id}",
        status_code=status.HTTP_204_NO_CONTENT,
        dependencies=[Depends(require_auth)],
    )
    async def delete_scheduled_run(job_id: str) -> Response:
        """Cancel (delete) a scheduled research job by id."""
        from src.api.scheduled_guards import guard_system_job_deletion

        _host_validate_path_param(job_id, "job_id")
        guard_system_job_deletion(job_id)
        removed = _get_scheduled_research_store().delete(job_id)
        if not removed:
            raise HTTPException(
                status_code=404, detail=f"scheduled run {job_id} not found"
            )
        return Response(status_code=status.HTTP_204_NO_CONTENT)

    # --- Playbook templates ---
    #
    # Mounted under /scheduled-runs because a template is only useful as the
    # source of a scheduled run. ``{job_id}`` never matches across a "/", so
    # these paths cannot collide with the CRUD routes above. Every one carries
    # the same ``require_auth`` dependency: there is deliberately no unguarded
    # way to enumerate the catalogue or create a job from it.

    @app.get(
        "/scheduled-runs/playbooks",
        response_model=List[PlaybookResponse],
        dependencies=[Depends(require_auth)],
    )
    async def list_research_playbooks() -> List[PlaybookResponse]:
        """List the available research playbook templates, without bodies."""
        from src.scheduled_research.playbooks import PlaybookError, list_playbooks

        try:
            playbooks = list_playbooks()
        except (PlaybookError, OSError) as exc:
            # A malformed file is surfaced, not skipped: a user template the
            # loader refuses must be visible as a broken template rather than
            # vanish from the catalogue.
            raise HTTPException(
                status_code=500, detail=f"playbook catalogue is unreadable: {exc}"
            ) from exc
        return [PlaybookResponse(**pb.to_dict()) for pb in playbooks]

    @app.get(
        "/scheduled-runs/playbooks/{slug}",
        response_model=PlaybookResponse,
        dependencies=[Depends(require_auth)],
    )
    async def get_research_playbook(slug: str) -> PlaybookResponse:
        """Read one research playbook template, including its instruction body."""
        from src.scheduled_research.playbooks import (
            PlaybookError,
            PlaybookNotFoundError,
            get_playbook,
        )

        _host_validate_path_param(slug, "slug")
        try:
            playbook = get_playbook(slug)
        except PlaybookNotFoundError as exc:
            raise HTTPException(status_code=404, detail=str(exc)) from exc
        except (PlaybookError, OSError) as exc:
            raise HTTPException(status_code=422, detail=str(exc)) from exc
        return PlaybookResponse(**playbook.to_dict(include_body=True))

    @app.post(
        "/scheduled-runs/playbooks/{slug}",
        response_model=ScheduledRunResponse,
        status_code=status.HTTP_201_CREATED,
        dependencies=[Depends(require_auth)],
    )
    async def create_scheduled_run_from_playbook(
        slug: str,
        request: CreateRunFromPlaybookRequest,
    ) -> ScheduledRunResponse:
        """Create a scheduled research job from a template.

        The template body becomes ``job.prompt`` verbatim — the natural-language
        data requirements are never rewritten into tool calls here; routing
        stays the agent's job at run time.

        Schedule and timezone are validated by ``ResearchPlaybook.to_job``,
        which calls the same ``validate_schedule`` / ``validate_timezone`` the
        plain ``POST /scheduled-runs`` path uses, so the two entry points can
        never accept different schedule grammars.
        """
        from src.scheduled_research.playbooks import (
            PlaybookError,
            PlaybookNotFoundError,
            get_playbook,
        )

        _host_validate_path_param(slug, "slug")
        # Unlike POST /scheduled-runs this checks the caller-supplied id up
        # front: an id outside the safe pattern would persist fine but could
        # never be removed through DELETE /scheduled-runs/{job_id}, which
        # rejects it with 400.
        if request.id is not None:
            _host_validate_path_param(request.id, "id")

        try:
            playbook = get_playbook(slug)
        except PlaybookNotFoundError as exc:
            raise HTTPException(status_code=404, detail=str(exc)) from exc
        except (PlaybookError, OSError) as exc:
            raise HTTPException(status_code=422, detail=str(exc)) from exc

        kwargs: Dict[str, Any] = {}
        # An omitted timezone keeps the template's suggestion; an explicit null
        # means UTC. Pydantic collapses both to ``None``, so the distinction has
        # to come from the fields the caller actually sent.
        if "timezone" in request.model_fields_set:
            kwargs["timezone"] = request.timezone

        try:
            job = playbook.to_job(
                job_id=request.id,
                schedule=request.schedule,
                variables=request.variables,
                config=request.config,
                next_run_at=request.next_run_at,
                delivery_target_ref=request.delivery_target_ref,
                delivery_format=request.delivery_format,
                protect_pdf=request.protect_pdf,
                **kwargs,
            )
        except ValueError as exc:
            # Covers PlaybookError (undeclared/oversized variable) and the
            # schedule / timezone / cron-window failures, all ValueError.
            raise HTTPException(status_code=422, detail=str(exc)) from exc

        if job.protect_pdf and not _email_pdf_password_configured():
            raise HTTPException(
                status_code=422,
                detail="PDF protection requested but no PDF password is configured",
            )

        now_ms = int(time.time() * 1000)
        if request.end_at is not None:
            if request.end_at <= now_ms or job.next_run_at > request.end_at:
                raise HTTPException(
                    status_code=422,
                    detail="end_at must be in the future and after the first run",
                )
            job.end_at = request.end_at
        job.title = request.title or playbook.name
        job.source_type = "playbook"
        job.playbook_slug = playbook.slug
        _get_scheduled_research_store().upsert(job)
        return _job_to_response(job)

    # Registered after the static /playbooks routes so "playbooks" is never
    # consumed as a dynamic job id by Starlette's first-match routing.
    @app.get(
        "/scheduled-runs/{job_id}",
        response_model=ScheduledRunResponse,
        dependencies=[Depends(require_auth)],
    )
    async def get_scheduled_run(job_id: str) -> ScheduledRunResponse:
        _host_validate_path_param(job_id, "job_id")
        job = _get_scheduled_research_store().get(job_id)
        if job is None:
            raise HTTPException(status_code=404, detail=f"scheduled run {job_id} not found")
        return _job_to_response(job)