Skip to content

The platform for continuously improving AI agents.

14.5 KB
Raw Blame
import logging

from django.db import transaction
from django.db.models import F, Prefetch, Q
from django.utils import timezone

from overbae.core.errors import InputValidationError
from overbae.models import (
    ResearchAction,
    ResearchAgent,
    ResearchAssignment,
    ResearchEvent,
    ResearchExperiment,
)
from overbae.services import execution_mandates, research, research_evidence, research_wakes

logger = logging.getLogger(__name__)

AUTONOMY = ("suggest", "remediate")
# Settled history retained alongside every active run.
RECENT = 5
BUDGET = {"max_seconds": 604800}
EVENTS = ("flow_started", "flow_node", "flow_retry", "flow_finished", "stop_requested")
JOURNAL = ("operator_note", "operator_action")
MUTATIONS = {"define", "stage", "remove", "run", "save_source"}

OBJECTIVE = (
    "Supervise the flow runs of this experiment. You are woken when a supervised run starts, "
    "when one of its stages fails and when it settles; nobody is waiting on a reply. On each "
    "wake read supervised_runs, inspect what changed with supervise(operation=inspect), and "
    "record what you find with supervise(operation=note): a mistake in the flow or its data, "
    "the cause of a failure, or a suggested amendment with the exact stage and setting. "
    "supervision.autonomy says what else you may do. Under suggest you change nothing. Under "
    "remediate you may retry a run whose failure an unchanged retry can clear, or save a "
    "corrected stage and run it; record the action you took and why. Never repeat an action "
    "that already failed for the same reason. When nothing more can be done until the next "
    "event, call wait. Do not finish: supervision ends when the experiment does."
)


def is_operator(assignment):
    return assignment.specification.get("task", {}).get("operator") is True


def experiment(assignment):
    return ResearchExperiment.objects.filter(
        pk=assignment.specification["task"]["experiment"], project_id=assignment.project_id
    ).first()


def operators(target):
    return ResearchAssignment.objects.filter(
        project_id=target.project_id,
        specification__task__operator=True,
        specification__task__experiment=str(target.pk),
    )


def current(target):
    for assignment in operators(target).filter(state="running").order_by("-created_at"):
        if assignment.deadline > timezone.now() and research.authorized(assignment):
            return assignment
    return None


def create(target, user):
    document = target.revisions.order_by("-number").first().document
    roots = list(
        dict.fromkeys(
            f"cell:{node['config']['cell']}"
            for node in document["nodes"]
            if node["kind"] == "data" and isinstance(node["config"].get("cell"), str)
        )
    )[:30]
    mandate = execution_mandates.admission(
        roots=roots,
        sources=execution_mandates.flow_sources(target.project, document, allow_unbound=True),
        experiment=target.pk,
        explicit={"local_platform_data_only": True},
    )
    if target.scientific_lock:
        mandate = execution_mandates.normalize(
            {**mandate, "authority": "observe", "families": ["read", "author"]}
        )
    return research.initialize(
        target.project,
        user=user,
        request_key=f"operator:{target.pk}:{operators(target).count()}",
        objective=OBJECTIVE,
        task={"experiment": str(target.pk), "operator": True},
        context_roots=roots,
        constraints={"local_platform_data_only": True},
        budget=BUDGET,
        execution_mandate=mandate,
    )


def attach(run):
    """Give a supervised run its experiment's operator. A new operator starts ready, and one
    that stands by is woken: either way its next turn reads the run that just started."""
    target = run.execution.revision.experiment
    operator = current(target) or create(target, run.created_by)
    research_wakes.request(operator.pk)
    return operator


def notify(run):
    task = run.specification.get("task", {})
    if "supervision" not in task:
        return
    for identifier in (
        ResearchAssignment.objects.filter(
            project_id=run.project_id,
            state="running",
            specification__task__operator=True,
            specification__task__experiment=task["experiment"],
        )
        .order_by("-created_at")
        .values_list("pk", flat=True)[:1]
    ):
        research_wakes.request(identifier)


def runs(assignment):
    return ResearchAssignment.objects.filter(
        project_id=assignment.project_id,
        execution__isnull=False,
        specification__task__experiment=assignment.specification["task"]["experiment"],
        specification__task__has_key="supervision",
    ).select_related("execution__revision")


def autonomy(assignment):
    latest = runs(assignment).order_by("-created_at").first()
    return latest.specification["task"]["supervision"]["autonomy"] if latest else "suggest"


def require_remediation(assignment, *, run=None):
    permission = (
        run.specification["task"]["supervision"]["autonomy"] if run else autonomy(assignment)
    )
    if permission != "remediate":
        raise InputValidationError(
            "This run is supervised under suggest: nothing was changed. Record the change as "
            "supervise(operation=note, kind=suggestion) with the exact stage and setting."
        )


def node_record(receipt):
    definition = next(
        (item for item in receipt.scope.document["nodes"] if item["id"] == receipt.node), {}
    )
    return {
        "node": receipt.node,
        "kind": definition.get("kind"),
        "title": definition.get("title"),
        "state": receipt.state,
        "attempt": receipt.attempt,
        **({"scope": str(receipt.scope_id)} if receipt.scope.parent_id else {}),
        **({"error": receipt.error} if receipt.error else {}),
        **({"report": receipt.report} if receipt.report else {}),
    }


def run_record(run):
    task = run.specification["task"]
    return {
        "run": str(run.pk),
        "state": run.state,
        "revision": run.execution.revision.number,
        "autonomy": task["supervision"]["autonomy"],
        "started_by": task.get("controller_assignment") or "user",
        "created_at": run.created_at.isoformat(),
        "summary": run.result.get("summary"),
        "failed_nodes": run.result.get("failed_nodes", []),
        "outputs": sorted(run.result.get("outputs", {})),
        "nodes": [
            node_record(receipt)
            for receipt in run.execution.nodes.select_related("scope").order_by(
                "started_at", "node", "attempt"
            )
        ],
    }


def observations(assignment):
    supervised = runs(assignment)
    settled = supervised.filter(state__in=research.TERMINAL).order_by(
        "-completed_at", "-created_at"
    )[:RECENT]
    visible = supervised.filter(~Q(state__in=research.TERMINAL) | Q(pk__in=settled.values("pk")))
    return research_evidence.project_report(
        assignment, [run_record(run) for run in visible.order_by("-created_at")]
    )


def wake_facts(observed):
    """What wakes a standing operator: a run it has not seen, a stage that failed and a run
    that settled. A stage that completes or progresses does not."""
    return [
        {
            "run": run["run"],
            "state": run["state"] if run["state"] in research.TERMINAL else "active",
            "failed": sorted(
                f"{node.get('scope', '')}:{node['node']}:{node['attempt']}"
                for node in run.get("nodes", [])
                if node["state"] == "failed"
            ),
        }
        for run in observed
    ]


def standing(assignment, observed):
    return {
        "after": assignment.deadline.isoformat(),
        "reason": "Standing by for run events",
        "evidence": observed,
    }


def seen(agent):
    """The supervised state the operator last read in its current turn: its latest overview,
    or what the turn was launched with."""
    overview = (
        agent.actions.filter(
            tool="supervise",
            state="completed",
            result__epoch=agent.execution_epoch,
            result__has_key="observation_identity",
        )
        .order_by("-created_at")
        .values_list("result__observation_identity", flat=True)
        .first()
    )
    return overview or (agent.checkpoint_manifest.get("launch") or {}).get("evidence")


def inspect(assignment, *, run=None, node=None):
    target = runs(assignment).filter(pk=run).first() if run else None
    if target is None:
        raise InputValidationError("This run is not supervised by this operator")
    if node is None:
        value = {
            **run_record(target),
            "events": [
                {"id": event["id"], "kind": event["kind"], **event["payload"]}
                for event in target.events.filter(kind__in=EVENTS)
                .order_by("-pk")
                .values("id", "kind", "payload")[:200]
            ][::-1],
        }
        return research_evidence.project_report(assignment, value)
    receipt = (
        target.execution.nodes.filter(node=node)
        .select_related("scope", "action__agent__assignment")
        .order_by(F("scope__parent_id").asc(nulls_first=True), "-attempt")
        .first()
    )
    if receipt is None:
        raise InputValidationError("This run has no such stage")
    definition = next(item for item in receipt.scope.document["nodes"] if item["id"] == node)
    value = {
        "run": str(target.pk),
        **node_record(receipt),
        "definition": {
            key: definition.get(key) for key in ("config", "operation") if definition.get(key)
        },
        "inputs": receipt.inputs,
        "outputs": receipt.outputs,
        **(
            {"result": research_evidence.action_result(assignment, receipt.action)}
            if receipt.action_id
            else {}
        ),
    }
    return research_evidence.project_report(assignment, value)


def note(action, request):
    assignment = action.agent.assignment
    if request.run and not runs(assignment).filter(pk=request.run).exists():
        raise InputValidationError("This run is not supervised by this operator")
    entry = {
        "action": str(action.pk),
        "kind": request.kind,
        "severity": request.severity,
        "run": str(request.run) if request.run else None,
        "node": request.node,
        "summary": request.summary,
        "proposal": request.proposal,
    }
    research.event(assignment, "operator_note", entry, action.agent)
    logger.info(
        "Experiment operator %s (%s) on run %s stage %s: %s",
        request.kind,
        request.severity,
        entry["run"],
        request.node,
        request.summary,
    )
    return {"recorded": True, "kind": request.kind}


def acted(action, operation, result):
    entry = {
        "action": str(action.pk),
        "operation": operation,
        **{
            key: result[key]
            for key in ("run", "state", "revision", "previous_revision", "started", "stage")
            if isinstance(result, dict) and key in result
        },
    }
    research.event(action.agent.assignment, "operator_action", entry, action.agent)
    logger.info(
        "Experiment operator action %s on experiment %s: run %s revision %s",
        operation,
        action.agent.assignment.specification["task"]["experiment"],
        entry.get("run"),
        entry.get("revision"),
    )
    return result


def journal(target, *, after=0, limit=100):
    """What the experiment's operators noted and did, oldest first."""
    entries = list(
        ResearchEvent.objects.filter(
            assignment__in=operators(target), kind__in=JOURNAL, pk__gt=after
        )
        .order_by("pk")
        .values("id", "kind", "payload", "created_at", "assignment_id")[: limit + 1]
    )
    page = entries[:limit]
    return {
        "entries": [
            {
                "id": entry["id"],
                "entry": entry["kind"].removeprefix("operator_"),
                "operator": str(entry["assignment_id"]),
                "at": entry["created_at"].isoformat(),
                **entry["payload"],
            }
            for entry in page
        ],
        "next_after": page[-1]["id"] if len(entries) > limit else None,
    }


def activity(target, *, before=None):
    owners = operators(target)
    agents = (
        ResearchAgent.objects.filter(assignment__in=owners)
        .select_related("assignment")
        .prefetch_related(
            Prefetch(
                "actions",
                queryset=ResearchAction.objects.order_by("-created_at")[:1],
                to_attr="latest_actions",
            )
        )
    )
    events = ResearchEvent.objects.filter(assignment__in=owners, kind__in=JOURNAL)
    if before is not None:
        events = events.filter(pk__lt=before)
    entries = list(
        events.order_by("-pk").values("id", "kind", "payload", "created_at", "assignment_id")[:51]
    )
    page = entries[:50]
    return {
        "agents": [
            {
                "id": str(agent.pk),
                "assignment": str(agent.assignment_id),
                "role": "operator" if agent.parent_id is None else agent.role,
                "state": agent.state,
                "active": agent.assignment.state == "running"
                and agent.assignment.deadline > timezone.now(),
                "activity": agent.latest_actions[0].arguments if agent.latest_actions else {},
                "tool": agent.latest_actions[0].tool if agent.latest_actions else "",
                "updated_at": agent.latest_actions[0].created_at
                if agent.latest_actions
                else agent.created_at,
            }
            for agent in agents.order_by("created_at")
        ],
        "entries": [
            {
                "id": entry["id"],
                "entry": entry["kind"].removeprefix("operator_"),
                "operator": str(entry["assignment_id"]),
                "at": entry["created_at"],
                **entry["payload"],
            }
            for entry in page
        ],
        "next_before": page[-1]["id"] if len(entries) > 50 else None,
    }


@transaction.atomic
def stand_by(agent, observed):
    """Park an operator whose turn ended without parking itself, against what that turn was
    shown: an event that arrived during the turn still wakes it."""
    current_agent = type(agent).objects.select_for_update().get(pk=agent.pk)
    if current_agent.state != "ready":
        return
    current_agent.state = "waiting"
    current_agent.wake = standing(agent.assignment, observed)
    current_agent.save(update_fields=["state", "wake"])