Skip to content

The platform for continuously improving AI agents.

54.2 KB
Raw Blame
import json
import logging
import time
import uuid
from concurrent.futures import ThreadPoolExecutor
from contextlib import suppress
from contextvars import copy_context
from copy import deepcopy
from datetime import datetime, timedelta

from django.core.exceptions import ValidationError as MalformedValue
from django.db import close_old_connections, transaction
from django.db.models import Count, Exists, F, IntegerField, OuterRef, Q, Subquery
from django.db.models.functions import Cast, Coalesce
from django.utils import timezone
from pydantic import ValidationError
from rest_framework.exceptions import ValidationError as RequestValidationError

from agent_runtime.observations import compact, observation
from agent_runtime.tool_contract import ToolError, ToolResponse
from overbae.core.errors import InputValidationError
from overbae.core.llms import call_llm_tools, completion_failure, effective_max_tokens
from overbae.models import (
    BillingService,
    ProjectMembership,
    ResearchAction,
    ResearchAgent,
    ResearchAssignment,
    ResearchEvent,
)
from overbae.services import (
    billing_ledger,
    context_graph,
    execution_mandates,
    experiment_conversation,
    experiment_native,
    experiment_operator,
    experiment_stages,
    experiment_training,
    model_catalog,
    model_meter,
    research,
    research_benchmarks,
    research_context_authorship,
    research_continuity,
    research_evidence,
    research_experiments,
    research_identifiers,
    research_memory,
    research_notes,
    research_prompt,
    research_requests,
    research_serving,
    research_team,
    research_telemetry,
    research_tools,
    research_workshop,
    research_workspace,
    training_campaigns,
)
from overbae.services.research_catalogue import definitions
from overbae.services.research_contract import TOOLS, WORKSPACE_RUNS

logger = logging.getLogger(__name__)

# Campaign states in which training or its evaluation is still producing measurements.
CAMPAIGN_PROGRESS_STATES = {"running"}


class StoppedError(Exception):
    """The run was stopped while its lead's reply was arriving."""


def system(agent):
    return research_prompt.build(agent)


def evidence(agent):
    # Agent-authored runs enter the same engine used by the Console.
    from overbae.services import experiment_dispatch

    assignment = agent.assignment
    campaigns = [
        {"id": str(c.pk), "state": c.state, "observations": training_evidence(c)}
        for c in research_evidence.campaigns(assignment, observe=True)
    ]
    helpers = [
        {
            "id": str(child.pk),
            "state": child.state if child.state in research.TERMINAL else "active",
            "result": research_evidence.helper_result(assignment, child.result),
        }
        for child in agent.children.order_by("pk")
    ]
    executions = list(
        agent.actions.filter(tool="workspace", arguments__operation__in=WORKSPACE_RUNS)
        .order_by("-created_at", "pk")
        .values("id", "result")
    )
    outputs = [
        {
            "receipt": str(item["id"]),
            **{
                key: item["result"][key]
                for key in ("state", "exit_code", "error", "total_output_chars")
                if key in item["result"]
            },
        }
        for item in executions
    ]
    return research_evidence.visible(
        assignment,
        {
            "flow_runs": experiment_dispatch.observations(assignment),
            **(
                {
                    "supervision": {"autonomy": experiment_operator.autonomy(assignment)},
                    "supervised_runs": experiment_operator.observations(assignment),
                }
                if experiment_operator.is_operator(assignment)
                else {}
            ),
            # A lead that works alone has no team to be told about.
            **(
                {}
                if research_requests.flow_bound(assignment)
                else {
                    "team": [
                        {
                            **research_team.record(member),
                            "state": member.state
                            if member.state in research.TERMINAL
                            else "active",
                        }
                        for member in assignment.agents.order_by("pk")
                    ],
                    "helpers": helpers,
                }
            ),
            "inbox": research_team.inbox(agent),
            "inbox_version": agent.assignment.events.filter(
                kind="agent_message", payload__recipient=str(agent.pk)
            )
            .order_by("-pk")
            .values_list("pk", flat=True)
            .first(),
            "notes_identity": context_graph.fingerprint(agent.notes),
            "acceptance_reviews": review_observations(agent),
            "unresolved_actions": list(
                agent.actions.filter(state="unknown").exclude(tool="model").values("id", "tool")
            ),
            "automation_evidence": list(
                assignment.events.filter(kind="trigger_evidence")
                .order_by("pk")
                .values("id", "payload")
            ),
            "campaigns": campaigns,
            "benchmarks": research_benchmarks.observations(assignment),
            "serving": research_serving.describe(assignment),
            "executions": outputs,
            "data_work": research_tools.work_evidence(assignment),
            "retained_artifacts": [
                research.artifact_record(a)
                for a in research_evidence.artifacts(assignment).order_by("-created_at")[:20]
            ],
        },
    )


def review_observations(agent):
    retained, seen = [], set()
    for action in (
        agent.actions.filter(tool="review")
        .only("id", "result")
        .order_by("-created_at")
        .iterator(chunk_size=50)
    ):
        result = action.result
        subject = result.get("subject")
        if not subject or "accepted" not in result:
            continue
        identity = context_graph.fingerprint(
            {
                "subject": subject,
                "criteria": sorted(result.get("criteria", {})),
                "scope": result.get("scope"),
            }
        )
        if identity in seen:
            continue
        seen.add(identity)
        retained.append(
            {"receipt": str(action.pk)}
            | {
                key: result[key]
                for key in (
                    "subject",
                    "source",
                    "state",
                    "accepted",
                    "criteria",
                    "scope",
                    "checked_records",
                    "first_mismatched_indices",
                    "error",
                )
                if key in result
            }
        )
        if len(retained) == 20:
            break
    return retained


def training_evidence(campaign):
    """What a campaign's runs measured, as the agent sees it at a wake."""
    return {
        "selected_job": str(campaign.selected_id) if campaign.selected_id else None,
        "summary": campaign.summary,
        "trials": [
            {
                "trial": str(trial.pk),
                "index": trial.index,
                "job": str(trial.job_id),
                "status": trial.job.status,
                "best_development_loss": training_campaigns.outcome(trial.job),
                "checks": trial.job.validation_runs.filter(state="completed").count(),
                "checkpoint": (experiment_training.checkpoint(trial.job) or {}).get("identity"),
            }
            for trial in campaign.trials.select_related("job").order_by("index")
        ],
        "preparation_recovery": [
            {
                "trial": str(trial.pk),
                "preparation": str(trial.job.preparation_id),
                "state": trial.job.preparation.state,
                "error": trial.job.preparation.error,
            }
            for trial in campaign.trials.filter(
                job__status="failed", job__preparation__isnull=False
            )
            .select_related("job__preparation")
            .order_by("created_at", "pk")
        ],
    }


def training_wake_evidence(observed):
    observed = deepcopy(observed)
    for preparation in observed.get("preparation_recovery", []):
        if preparation["state"] in {"queued", "starting", "running"}:
            preparation["state"] = "active"
    for trial in observed.get("trials", []):
        if trial["status"] in {"queued", "preparing", "running"}:
            trial["status"] = "active"
    return observed


def tool_content(action):
    value = research_evidence.action_result(action.agent.assignment, action)
    if action.tool == "explore_context":
        return value
    if action.tool == "review" and action.arguments.get("operation") == "facts":
        summary = dict(value)
        summary["campaigns"] = []
        for campaign in value.get("campaigns", []):
            record = dict(campaign)
            record["trials"] = [
                {
                    **trial,
                    "requested_training": {
                        key: item
                        for key, item in trial.get("requested_training", {}).items()
                        if not isinstance(item, (dict, list))
                    },
                    "training_trajectory": [
                        {
                            **check,
                            "metrics": {
                                key: item
                                for key, item in check.get("metrics", {}).items()
                                if not isinstance(item, (dict, list))
                            },
                        }
                        for check in trial.get("training_trajectory", [])
                    ],
                }
                for trial in campaign.get("trials", [])
            ]
            if campaign.get("selected"):
                record["selected"] = {
                    key: item
                    for key, item in campaign["selected"].items()
                    if key not in {"executions", "requested_training", "training_trajectory"}
                }
            summary["campaigns"].append(record)
        summary["transformations"] = [
            {
                **{
                    key: item
                    for key, item in record.items()
                    if key not in {"package", "specification", "entrypoints"}
                },
                "package": {
                    key: item
                    for key, item in (record.get("package") or {}).items()
                    if key in {"id", "sha256"}
                },
                "entrypoints": record.get("entrypoints", [])
                if record["state"] == "completed"
                else [],
            }
            for record in value.get("transformations", [])
        ]
        summary["cost_snapshots"] = value.get("cost_snapshots", [])[:3]
        return compact(summary, text_limit=3000, items=12) | {
            "full_receipt": str(action.pk),
            "compacted": True,
            "omitted_details": "Full training configuration, nested metric diagnostics, failed transformation code and older cost snapshots remain in the receipt.",
        }
    nested = (
        action.tool == "experiment"
        and isinstance(value, dict)
        and isinstance(value.get("result"), dict)
    )
    packet = value["result"] if nested else value
    campaign = packet.get("campaign", packet) if isinstance(packet, dict) else None
    if (
        action.tool in {"training", "experiment"}
        and isinstance(campaign, dict)
        and "trials" in campaign
    ):
        summary = {key: packet[key] for key in ("campaign", "selection") if key in packet} | {
            "full_receipt": str(action.pk),
            "compacted": True,
            "fields": list(packet),
        }
        value = {**value, "result": summary} if nested else summary
        return compact(value, text_limit=3000, items=12) | {"compacted": True}
    tool = (
        "python"
        if action.tool == "workspace" and action.arguments.get("operation") in WORKSPACE_RUNS
        else "read"
        if action.arguments.get("describe")
        or action.tool == "workspace"
        and action.arguments.get("operation") == "read"
        else action.tool
    )
    if action.tool in {
        "inspect_action",
        "history",
        "explore_context",
        "inspect_source",
        "inbox",
    } or (action.tool == "platform" and action.arguments.get("name") == "get_model_catalog"):
        tool = "read"
    if isinstance(value, dict) and {"next_offset", "next_cursor", "continuation"} & value.keys():
        tool = "read"
    return observation(value, str(action.pk), tool=tool)


def tool_observation(action):
    content = dict(tool_content(action))
    content.pop("full_receipt", None)
    compacted = content.pop("compacted", False)
    error = None
    if action.state in {"failed", "denied", "unknown"}:
        raw = research_evidence.action_result(action.agent.assignment, action)
        unknown = action.state == "unknown"
        invalid = raw.get("type") in {"ValidationError", "ToolArgumentsError"}
        error = ToolError(
            code="outcome_unknown" if unknown else "invalid_arguments" if invalid else "rejected",
            message=str(raw.get("error", "Tool did not complete")),
            details=raw.get("details", []) if isinstance(raw.get("details"), list) else [],
            recovery=(
                "Inspect this receipt and the saved native operation identity before retrying; execution may already have started."
                if unknown
                else raw.get(
                    "recovery",
                    "Resolve the reported prerequisite before retrying; unchanged arguments will not resolve it.",
                )
            ),
        )
    return ToolResponse(
        tool=action.tool,
        operation=action.arguments.get("operation", action.arguments.get("name")),
        status=action.state,
        data=content,
        error=error,
        receipt=str(action.pk),
        compacted=compacted,
    ).model_dump(mode="json")


def evidence_identity(observed):
    # Reading messages and saving notes are not new execution evidence.
    meaningful = {
        key: value
        for key, value in observed.items()
        if key not in {"inbox", "notes_identity", "acceptance_reviews"}
    }
    # A Workshop task reports each step it takes; only its settling is news to a waiting agent.
    work = meaningful.get("data_work")
    if work:
        meaningful["data_work"] = work | {
            "workshop": [
                task
                if task["state"] in research_workshop.SETTLED
                else {"task": task["task"], "state": "active"}
                for task in work["workshop"]
            ]
        }
    if "supervised_runs" in meaningful:
        meaningful["supervised_runs"] = experiment_operator.wake_facts(
            meaningful["supervised_runs"]
        )
    meaningful["flow_runs"] = [
        flow
        if flow["state"] in research.TERMINAL
        else {"run": flow["run"], "state": "active", "failed_nodes": flow.get("failed_nodes", [])}
        for flow in meaningful.get("flow_runs", [])
    ]
    meaningful["campaigns"] = [
        {**campaign, "observations": training_wake_evidence(campaign["observations"])}
        if campaign["state"] not in CAMPAIGN_PROGRESS_STATES
        else {
            "id": campaign["id"],
            "state": campaign["state"],
            "failed": sorted(
                str(trial.get("trial"))
                for trial in campaign["observations"].get("trials", [])
                if trial.get("status") == "failed"
            ),
        }
        for campaign in meaningful.get("campaigns", [])
    ]
    meaningful["benchmarks"] = [
        benchmark
        if benchmark["state"] in {"completed", "failed", "cancelled", "paused"}
        else {
            "id": benchmark["id"],
            "state": "active",
            "error": benchmark.get("error"),
            "failed_stages": {
                key: stage.get("error")
                for key, stage in benchmark.get("stages", {}).items()
                if stage.get("error")
            },
        }
        for benchmark in meaningful.get("benchmarks", [])
    ]
    return context_graph.fingerprint(meaningful)


def wake_needed(agent):
    return agent.state == "ready" or (
        not agent.wake.get("question")
        and agent.wake.get("evidence") != evidence_identity(evidence(agent))
    )


STATE_SECTIONS = ("experiment", "working_brief", "input_artifacts", "inputs")


def state(agent):
    assignment = agent.assignment
    observed = evidence(agent)
    revision = (
        research_experiments.current_revision(assignment)
        if assignment.experiment_revision_id or experiment_operator.is_operator(assignment)
        else None
    )
    return {
        "inputs": research_tools.approved_inputs(assignment),
        "experiment": (
            {
                "id": str(revision.experiment_id),
                "revision": revision.number,
                **(
                    {
                        "chat_workflow": "Save the requested edits and finish with delivery=definition. "
                        "The user starts a ready flow with Run on the canvas. The background "
                        "agent monitors execution. For requested data processing, delegate "
                        "with workshop(operation=prepare), passing the pinned source_cell, "
                        "the request and downstream_context. Wait for verified publication, "
                        "then wire its exact cells and partition roles into the experiment. "
                        "Workshop preparation does not require running the experiment or "
                        "creating a temporary data-only revision."
                    }
                    if research_requests.construction_only(assignment)
                    else {}
                ),
                **experiment_stages.describe(
                    research_context_authorship.project_document(assignment, revision)
                ),
            }
            if revision
            else None
        ),
        "working_brief": research_continuity.brief(agent),
        "input_artifacts": list(
            dict.fromkeys(
                agent.work_order.get("artifacts", [])
                + agent.result.get("input_artifacts", [])
                + [
                    artifact
                    for dependency in research_team.dependencies(agent)
                    for artifact in dependency["artifacts"]
                ]
            )
        ),
        "execution_limits": research.allowance(assignment, agent),
        "costs": research.recorded_costs(assignment),
        "observations": compact(observed, text_limit=6000, items=20),
        "observation_identity": evidence_identity(observed),
    }


def packet(agent):
    assignment = agent.assignment
    authored = research_team.record(agent)
    return {
        "assignment": str(assignment.pk),
        "tool_catalogue": {"operation": "contracts", "kind": "tools"},
        "role": research_team.role(agent),
        "work_order": authored["work_order"],
        "delegation_provenance": authored["delegation_provenance"],
        "is_helper": bool(agent.parent_id),
        "context_roots": assignment.context.roots,
        "context_access": {"tool": "explore_context", "snapshot": str(assignment.context_id)},
        "project_memory": research_memory.recall(agent),
        **state(agent),
    }


def shown(history):
    """The latest value of every state section already sent to the model."""
    sections = {"observations": {}}
    for message in history:
        if message.get("role") != "user":
            continue
        try:
            value = json.loads(message["content"])
        except (ValueError, TypeError):
            continue
        if not isinstance(value, dict):
            continue
        update = value if "assignment" in value else value.get("state_update")
        if not isinstance(update, dict):
            continue
        for key, item in update.items():
            if key == "observations":
                sections["observations"].update(item)
            else:
                sections[key] = item
    return sections


def state_update(history, current):
    """Only the sections that changed since the model last saw them, or ``None``."""
    previous = shown(history)
    changed = {
        key: current[key]
        for key in STATE_SECTIONS
        if context_graph.canonical(current[key]) != context_graph.canonical(previous.get(key))
    }
    observations = {
        key: value
        for key, value in current["observations"].items()
        if context_graph.canonical(value)
        != context_graph.canonical(previous["observations"].get(key))
    }
    if observations:
        changed["observations"] = observations
    # Evidence can change inside detail the compact sections omit; the identity still advances
    # so a later wait anchors to what the model was actually told.
    if not changed and current["observation_identity"] == previous.get("observation_identity"):
        return None
    return {
        "state_update": {
            **changed,
            "execution_limits": current["execution_limits"],
            "costs": current["costs"],
            "observation_identity": current["observation_identity"],
        }
    }


@transaction.atomic
def lease(agent_id):
    assignment_id = ResearchAgent.objects.values_list("assignment_id", flat=True).get(pk=agent_id)
    ResearchAssignment.objects.select_for_update().get(pk=assignment_id)
    agent = (
        ResearchAgent.objects.select_for_update(of=("self",))
        .select_related("assignment__project", "assignment__created_by", "assignment__context")
        .get(pk=agent_id)
    )
    if agent.state in research.TERMINAL or agent.assignment.state != "running":
        return None
    if not research_team.ready(agent):
        return None
    if agent.lease_expires_at and agent.lease_expires_at > timezone.now():
        return None
    limit = agent.assignment.specification["budget"]["max_concurrent_agents"]
    if (
        agent.assignment.agents.exclude(pk=agent.pk)
        .filter(lease_expires_at__gt=timezone.now())
        .count()
        >= limit
    ):
        return None
    agent.lease = uuid.uuid4()
    agent.lease_expires_at = timezone.now() + timedelta(seconds=240)
    agent.save(update_fields=["lease", "lease_expires_at"])
    return agent


def observe(agent):
    for action in agent.actions.filter(
        tool="workspace",
        arguments__operation__in=WORKSPACE_RUNS,
        result__state__in=["accepted", "running"],
    ):
        sandbox = research_workspace.existing(agent)
        result = (
            research_workspace.checked_rpc(
                agent, sandbox, {"operation": "status", "execution": str(action.pk)}
            )
            if sandbox is not None
            else {"state": "unknown", "reason": "workspace_exited", "execution": str(action.pk)}
        )
        if result.get("state") not in {"accepted", "running"}:
            with transaction.atomic():
                research_team.current_turn(agent)
                action = ResearchAction.objects.select_for_update().get(pk=action.pk)
                action.result = result
                action.save(update_fields=["result"])
                research.event(
                    agent.assignment,
                    "execution_observed",
                    {
                        "action": str(action.pk),
                        "state": result.get("state"),
                        "exit_code": result.get("exit_code"),
                    },
                    agent,
                )
            if sandbox is not None:
                research_workspace.checkpoint(agent, sandbox, covered=str(action.pk))


def run_tools(agent):
    actions = research_team.next_tools(agent)
    if not actions:
        return False
    if len(actions) == 1:
        run_tool(agent, actions[0])
    else:
        with ThreadPoolExecutor(max_workers=len(actions)) as executor:
            futures = [
                executor.submit(copy_context().run, run_read_tool, action) for action in actions
            ]
            for future in futures:
                future.result()
    return True


def yield_turn(agent, reason, *, observed=None, flow=None, workshop=None):
    """Wait without consuming evidence that arrived after the model's observation."""
    observed = evidence(agent) if observed is None else observed
    captured = evidence_identity(observed)
    model = agent.actions.filter(tool="model", state="completed").order_by("-created_at").first()
    seen = model.arguments.get("observation_identity") if model else None
    if seen is None or seen == captured:
        # A launch acknowledges active work only; its later completion remains unobserved.
        if flow and not any(item["run"] == flow["run"] for item in observed["flow_runs"]):
            observed["flow_runs"].append({"run": flow["run"], "state": flow["state"]})
        if workshop and not any(
            item["task"] == workshop["task"] for item in observed["data_work"]["workshop"]
        ):
            observed["data_work"]["workshop"].append(
                {"task": workshop["task"], "state": workshop["state"]}
            )
        seen = evidence_identity(observed)
    retain_wait(agent, reason, seen)


@transaction.atomic
def retain_wait(agent, reason, observed):
    ResearchAssignment.objects.select_for_update().get(pk=agent.assignment_id)
    current = ResearchAgent.objects.select_for_update().get(pk=agent.pk)
    if current.wake.get("question"):
        return
    research_team.transition(
        agent,
        fence=agent.lease,
        state="waiting",
        wake={
            "after": (timezone.now() + timedelta(seconds=600)).isoformat(),
            "reason": reason,
            "evidence": observed,
        },
    )


def run_read_tool(action):
    close_old_connections()
    try:
        run_tool(action.agent, action)
    finally:
        close_old_connections()


@transaction.atomic
def settle_tool(agent, action, result, *, fence, state="completed"):
    ResearchAssignment.objects.select_for_update().get(pk=agent.assignment_id)
    current = ResearchAgent.objects.select_for_update().get(pk=agent.pk)
    if not research_team.lease_matches(current, fence):
        return False
    action = ResearchAction.objects.select_for_update().get(pk=action.pk, agent=current)
    if action.state not in {"pending", "running", "unknown"}:
        return False
    research.complete(action, result, state=state, cost=0 if state != "unknown" else None)
    return True


def run_tool(agent, action):
    fence = research_team.turn_fence(agent)
    try:
        may_wait = (
            action.tool == "finish"
            or (
                action.tool == "experiment"
                and action.arguments.get("operation") in {"run", "define"}
            )
            or (action.tool == "workshop" and action.arguments.get("operation") == "prepare")
        )
        observed = evidence(agent) if may_wait else None
        result = research_tools.invoke(action)
        if (
            action.tool == "workshop"
            and action.arguments.get("operation") == "prepare"
            and result.get("state") not in research_workshop.SETTLED
        ):
            # The delegation stays open while the Workshop works. Each wake invokes it again,
            # and the agent's next turn receives the settled record as this call's result.
            yield_turn(
                agent, "Waiting for the Workshop to publish", observed=observed, workshop=result
            )
            return
        if not settle_tool(agent, action, result, fence=fence):
            return
        if research_team.pending_tools(agent).exists():
            return
        if (
            action.tool == "experiment"
            and action.arguments.get("operation") in {"run", "define"}
            and result.get("run")
            and result.get("state") not in research.TERMINAL
        ):
            yield_turn(agent, "Waiting for admitted flow outputs", observed=observed, flow=result)
        elif (
            action.tool == "finish"
            and result.get("accepted") is False
            and research_tools.pending_work(agent.assignment)
        ):
            yield_turn(agent, "Waiting for admitted work to settle", observed=observed)
    except research_team.SupersededTurnError:
        return
    # Django rejects a malformed identifier in a lookup with its own ValidationError.
    except (
        InputValidationError,
        ValidationError,
        RequestValidationError,
        MalformedValue,
        ValueError,
        KeyError,
    ) as exc:
        settle_tool(
            agent, action, research_tools.argument_failure(exc), fence=fence, state="failed"
        )
    except Exception:
        logger.exception(
            "Research action outcome requires reconciliation", extra={"action": str(action.pk)}
        )
        settle_tool(
            agent,
            action,
            {
                "error": "External action outcome is uncertain; inspect its saved identity before taking dependent action"
            },
            fence=fence,
            state="unknown",
        )


def messages(agent, tools=None):
    with research_tools.source_read_scope(agent.assignment):
        return projected_messages(agent, tools)


def projected_messages(agent, tools=None):
    """The next model request: the retained transcript plus what happened since.

    Source permissions are reapplied before sending retained tool replies. Unchanged
    messages retain their bytes for provider prefix caching.
    """
    if not agent.messages:
        return [
            {"role": "system", "content": system(agent)},
            {"role": "user", "content": context_graph.canonical(packet(agent))},
        ]
    history = [dict(message) for message in agent.messages]
    # A transcript retained under earlier instructions continues under the current ones.
    history[0] = {"role": "system", "content": system(agent)}
    recorded = {message.get("tool_call_id") for message in history if message.get("role") == "tool"}
    boundary = research_tools.source_boundary(agent.assignment)
    history = research_notes.project_calls(agent, history, boundary=boundary)
    retained = {
        action.request_key: action
        for action in agent.actions.filter(
            request_key__in=recorded, state__in=research.FINISHED_ACTIONS
        )
    }
    for message in history:
        if message.get("role") == "tool" and (action := retained.get(message.get("tool_call_id"))):
            if (
                research_evidence.action_result(agent.assignment, action, boundary=boundary)
                != action.result
            ):
                message["content"] = context_graph.canonical(tool_observation(action))
        elif message.get("role") == "user" and isinstance(message.get("content"), str):
            try:
                packet_value = json.loads(message["content"])
            except ValueError:
                continue
            if isinstance(packet_value, dict):
                if packet_value.get("assignment") == str(agent.assignment_id):
                    packet_value.setdefault(
                        "delegation_provenance", research_notes.delegation(agent)
                    )
                update = packet_value.get("state_update", packet_value)
                if isinstance(update, dict) and isinstance(update.get("working_brief"), dict):
                    update["working_brief"].setdefault(
                        "delegation_provenance", research_notes.delegation(agent)
                    )
            message["content"] = context_graph.canonical(
                research_evidence.visible(agent.assignment, packet_value, boundary=boundary)
            )
    calls = {call["id"] for message in history for call in message.get("tool_calls", [])}
    for action in agent.actions.filter(
        request_key__in=calls - recorded, state__in=research.FINISHED_ACTIONS
    ).order_by("created_at"):
        history.append(
            {
                "role": "tool",
                "tool_call_id": action.request_key,
                "content": context_graph.canonical(tool_observation(action)),
            }
        )
    history = research_continuity.fit(history, definitions(agent) if tools is None else tools)
    update = state_update(history, state(agent))
    if update is not None:
        history.append({"role": "user", "content": context_graph.canonical(update)})
    return history


@transaction.atomic
def accept_model_response(
    action, fence, history, text, calls, usage, *, sent=(), trace_inputs=None
):
    locked = model_owner(action.agent)
    action = ResearchAction.objects.select_for_update().get(pk=action.pk, agent=locked)
    action.agent = locked
    if action.state not in {"running", "unknown"} or action.result.get("accepted") is False:
        return action
    if not model_authorized(locked, fence):
        research.complete(
            action,
            {"text": text, "calls": calls, "accepted": False},
            usage=usage,
            cost=usage.get("response_cost"),
            trace_inputs=trace_inputs,
        )
        return action
    research.complete(
        action,
        {
            "text": text,
            "calls": calls,
            **({"thinking": usage["thinking"]} if usage.get("thinking") else {}),
        },
        usage=usage,
        cost=usage.get("response_cost"),
        trace_inputs=trace_inputs,
    )
    assistant = usage.get("assistant_message") or {
        "role": "assistant",
        "content": text,
        "tool_calls": calls,
    }
    locked.messages = history + [assistant]
    locked.state = "ready"
    locked.result.pop("provider_probe", None)
    locked.save(update_fields=["messages", "state", "result"])
    for call in calls:
        name = call["function"]["name"]
        try:
            arguments = research_team.own_arguments(
                locked,
                name,
                research_identifiers.repair(json.loads(call["function"]["arguments"]), sent),
            )
            if name not in TOOLS:
                raise ValueError("Unknown tool")
            TOOLS[name].parse(arguments)
            research.claim(locked, call["id"], name, arguments, authored_by=action)
        except (ValueError, ValidationError) as exc:
            invalid = research.claim(
                locked,
                call["id"],
                name,
                {"unparsed": call["function"]["arguments"]},
                authored_by=action,
            )
            research.complete(
                invalid,
                research_tools.argument_failure(exc),
                state="failed",
                cost=0,
            )


@transaction.atomic
def accept_model_failure(action, fence, history, failure, usage, *, trace_inputs=None):
    agent = model_owner(action.agent)
    assignment = agent.assignment
    current = ResearchAction.objects.select_for_update().get(pk=action.pk, agent=agent)
    current.agent = agent
    if current.state not in {"running", "unknown"} or current.result.get("tools_executed") is False:
        return current
    # A replacement activity may mark this call unknown before its late usage arrives.
    research.complete(
        current,
        {**failure, "tools_executed": False},
        state="unknown",
        usage=usage,
        cost=usage.get("response_cost"),
        trace_inputs=trace_inputs,
    )
    if not model_authorized(agent, fence):
        return current
    agent.messages = history + [
        {
            "role": "user",
            "content": "The preceding model call did not yield a usable response. No tools from it executed; its cost remains reserved. Reassess the next action.",
        }
    ]
    agent.save(update_fields=["messages"])
    attempts = agent.actions.filter(tool="model")
    resumed = assignment.events.filter(kind="resumed").order_by("-id").first()
    if resumed:
        attempts = attempts.filter(created_at__gte=resumed.created_at)
    latest = list(attempts.order_by("-created_at")[:3])
    if not failure["retryable"] or (
        (len(latest) == 3 or agent.result.get("provider_probe"))
        and all(item.state == "unknown" for item in latest)
    ):
        recoveries = assignment.events.filter(kind="provider_recovery").count()
        assignment.state = "blocked"
        assignment.result = {
            **assignment.result,
            "provider_failure": failure,
            "retry_at": (
                (
                    timezone.now() + timedelta(seconds=min(900, 60 * 4 ** min(recoveries, 2)))
                ).isoformat()
                if failure["retryable"]
                else None
            ),
            "reason": "model_provider_unavailable"
            if failure["retryable"]
            else "model_provider_rejected",
            "error": (
                "Model provider unavailable. Recovery is retried with backoff within the original allowance. Unknown costs remain reserved."
                if failure["retryable"]
                else "Model request failed without a retryable response. Correct the request or provider configuration before resuming. Unknown costs remain reserved."
            ),
            "actions": [str(item.pk) for item in reversed(latest)],
        }
        assignment.save(update_fields=["state", "result"])
        research.event(assignment, "blocked", assignment.result, agent)
        agent.state = "blocked"
        agent.result = {**agent.result, "provider_probe": True}
        agent.save(update_fields=["state", "result"])
    return current


def prepare(agent):
    research_team.current_turn(agent)
    observe(agent)
    research_team.current_turn(agent)
    if not research.authorized(agent.assignment):
        reconcile(research.stop(agent.assignment))
        return False
    if agent.parent_id is None:
        try:
            research_workshop.record(agent)
        except InputValidationError:
            # The flow keeps its previous inputs; the publication itself is unaffected.
            logger.exception(
                "Prepared data was not recorded on the flow", extra={"agent": str(agent.pk)}
            )
    research_team.current_turn(agent)
    experiment_conversation.deliver(agent)
    current = research_team.current_turn(agent)
    agent.state, agent.wake = current.state, current.wake
    if agent.state == "waiting" and agent.wake.get("question"):
        if not agent.assignment.events.filter(
            kind="question_answered", payload__question=agent.wake["question"]
        ).exists():
            return False
        current = research_team.transition(
            agent, fence=research_team.turn_fence(agent), state="ready", wake={}
        )
        agent.state, agent.wake = current.state, current.wake
    if agent.state == "waiting":
        current = evidence_identity(evidence(agent))
        if agent.wake.get("evidence") == current and (
            datetime.fromisoformat(agent.wake["after"]) > timezone.now()
            or research_tools.pending_work(agent.assignment)
            or any(
                research_team.ready(member)
                for member in agent.assignment.agents.exclude(pk=agent.pk).filter(
                    state__in=["ready", "running"]
                )
            )
        ):
            return False
        agent.state = "ready"
    return True


def model_owner(agent):
    # Scientific admission imports Research's journal, so resolve its lock after import.
    from overbae.services import research_science

    research_science.experiment_for(agent.assignment, lock=True)
    # Invalid ancestry rejects admission below but must still retain a late response's usage.
    with suppress(InputValidationError):
        execution_mandates.lock_parents(agent.assignment)
    assignment = ResearchAssignment.objects.select_for_update().get(pk=agent.assignment_id)
    current = ResearchAgent.objects.select_for_update().get(pk=agent.pk)
    current.assignment = assignment
    return current


def model_authorized(agent, fence):
    if fence is None or not research_team.accepts_response(agent, fence):
        return False
    try:
        execution_mandates.check_authority(agent.assignment, "read", continuation=False)
    except InputValidationError:
        return False
    return True


@transaction.atomic
def prepare_model(agent, fence):
    agent = model_owner(agent)
    if not model_authorized(agent, fence):
        return None
    # Only the current activity can settle its predecessor's unretained response.
    for stale in agent.actions.select_for_update().filter(tool="model", state="running"):
        research.complete(
            stale,
            {
                "error": "Previous model response was not retained; no proposed tool from it was executed"
            },
            state="unknown",
        )
    if (
        research.model_calls(agent.assignment)
        >= agent.assignment.specification["budget"]["max_model_calls"]
    ):
        agent.state = "exhausted"
        agent.result = {"reason": "model_call_limit"}
        agent.save(update_fields=["state", "result"])
    return agent


def model_source_scope(assignment):
    return (
        research_tools.source_boundary(assignment),
        context_graph.fingerprint(
            {
                "mandate": assignment.execution_mandate,
                "roots": assignment.specification.get("context_roots", []),
            }
        ),
    )


@transaction.atomic
def admit_model(agent, fence, key, arguments, reservation, *, source_scope):
    agent = model_owner(agent)
    if not model_authorized(agent, fence):
        return None
    # A changed projection is rebuilt by the next turn before any call is claimed.
    if model_source_scope(agent.assignment) != source_scope:
        return None
    action = research.claim(agent, key, "model", arguments, reservation)
    if action.state == "pending":
        action.state = "running"
        action.started_at = timezone.now()
        action.save(update_fields=["state", "started_at"])
    return action


def think(agent, turn):
    fence = research_team.turn_fence(agent)
    agent = prepare_model(agent, fence)
    if agent is None:
        return
    if agent.state == "exhausted":
        exhaust(agent)
        return
    tools = definitions(agent)
    with research_tools.source_read_scope(agent.assignment):
        source_scope = model_source_scope(agent.assignment)
        history = messages(agent, tools)
        source_cells = sorted(research_notes.sources_in_messages(agent.assignment, history))
    tokens = research_continuity.token_count(history, tools)
    output = 5000
    prompt_tokens = int(tokens * 1.25) + 1024
    # Research admission has no dollar ceiling: an unpriced model reserves nothing and its
    # cost stays unknown rather than stopping the investigation.
    quote = model_catalog.estimate_cost(
        agent.model, prompt_tokens, effective_max_tokens(agent.model, output)
    )
    observed = shown(history)
    retained = len(agent.messages)
    extends = retained > 0 and history[:retained] == agent.messages
    action = admit_model(
        agent,
        fence,
        f"model:{turn}",
        {
            "model": agent.model,
            "output_tokens": output,
            "context_estimated_tokens": tokens,
            "tool_schema_estimated_tokens": research_continuity.token_count([], tools),
            "cost_snapshot": observed.get("costs", {}),
            "observation_identity": observed.get("observation_identity"),
            "source_cells": source_cells,
            # Each request extends the retained transcript, so only its new tail is kept here.
            "request": {
                "messages": len(history),
                "fingerprint": context_graph.fingerprint(history),
                "tools": [tool["function"]["name"] for tool in tools],
                "tools_fingerprint": context_graph.fingerprint(tools),
                "extends_transcript": extends,
            },
            "appended": history[retained:] if extends else history,
        },
        quote * 1.1 if quote is not None else 0,
        source_scope=source_scope,
    )
    if action is None:
        return
    if action.state == "denied":
        with transaction.atomic():
            agent = model_owner(agent)
            if not model_authorized(agent, fence):
                return
            agent.state = "exhausted"
            agent.result = action.result
            agent.save(update_fields=["state", "result"])
        exhaust(agent)
        return
    trace_inputs = (
        {
            "model": agent.model,
            "messages": history,
            "tools": tools,
            "max_completion_tokens": output,
            "tool_choice": "required",
        }
        if research_telemetry.captures(agent.assignment.project_id)
        else None
    )
    written = {"at": 0.0}

    def progress(text, thinking):
        # What a lead writes is shown in its experiment's chat as it arrives.
        now = time.monotonic()
        if now - written["at"] >= 0.25 and (text or thinking):
            written["at"] = now
            ResearchAction.objects.filter(pk=action.pk, state="running").update(
                result={"text": text, "thinking": thinking, "streaming": True}
            )
            if not ResearchAssignment.objects.filter(
                pk=agent.assignment_id, state="running"
            ).exists():
                raise StoppedError

    try:
        with model_meter.billed(
            billing_ledger.cause(
                agent.assignment.project_id,
                BillingService.RESEARCH,
                "research_action",
                action.pk,
                actor=agent.assignment.created_by_id,
            )
        ):
            text, calls, usage = call_llm_tools(
                history,
                tools,
                model=agent.model,
                max_tokens=output,
                retry_deadline=150,
                max_attempts=1,
                tool_choice="required",
                on_progress=progress if agent.parent_id is None else None,
            )
    except StoppedError:
        # Its usage was never reported: the outcome is unknown, and what it wrote is kept.
        if ResearchAction.objects.filter(pk=action.pk, state="running").update(
            state="unknown", completed_at=timezone.now()
        ):
            research_telemetry.action_completed(action, inputs=trace_inputs)
        return
    except Exception as exc:
        accept_model_failure(
            action,
            fence,
            history,
            completion_failure(exc),
            getattr(exc, "stats", {}),
            trace_inputs=trace_inputs,
        )
        return
    accept_model_response(
        action, fence, history, text, calls, usage, sent=history, trace_inputs=trace_inputs
    )


def recovering_assignments(assignments):
    retries = (
        ResearchEvent.objects.filter(assignment_id=OuterRef("pk"), kind="provider_recovery")
        .order_by()
        .values("assignment_id")
        .annotate(total=Count("pk"))
        .values("total")
    )
    calls = (
        ResearchAction.objects.filter(agent__assignment_id=OuterRef("pk"), tool="model")
        .exclude(state="denied")
        .order_by()
        .values("agent__assignment_id")
        .annotate(total=Count("pk"))
        .values("total")
    )
    membership = ProjectMembership.objects.filter(
        project_id=OuterRef("project_id"), user_id=OuterRef("created_by_id")
    )
    return (
        assignments.filter(
            state="blocked",
            result__reason="model_provider_unavailable",
            result__retry_at__isnull=False,
            deadline__gt=timezone.now(),
            created_by__is_active=True,
            project__is_active=True,
        )
        .exclude(result__retry_at__in=["", None])
        .filter(
            Q(execution_mandate__constraints__historical_no_resume=False)
            | Q(execution_mandate__constraints__historical_no_resume__isnull=True)
        )
        .annotate(
            current_membership=Exists(membership),
            recovery_count=Coalesce(Subquery(retries), 0),
            recovery_calls=Coalesce(Subquery(calls), 0),
            recovery_call_limit=Cast("specification__budget__max_model_calls", IntegerField()),
        )
        .filter(
            current_membership=True,
            recovery_count__lt=3,
            recovery_calls__lt=F("recovery_call_limit"),
        )
    )


def provider_recovery_pending(assignment):
    return recovering_assignments(ResearchAssignment.objects.filter(pk=assignment.pk)).exists()


@transaction.atomic
def recover_provider(assignment):
    assignment = ResearchAssignment.objects.select_for_update().get(pk=assignment.pk)
    if not provider_recovery_pending(assignment) or (
        datetime.fromisoformat(assignment.result["retry_at"]) > timezone.now()
    ):
        return
    recovery = research.event(
        assignment, "provider_recovery", {"previous_result": assignment.result}
    )
    # A fresh model request cannot replay tools from an unreceived response.
    research.event(assignment, "resumed", {"automatic": True, "recovery": recovery.pk})
    assignment.agents.filter(state="blocked", result__provider_probe=True).update(state="ready")
    assignment.state = "running"
    assignment.result = {
        k: v
        for k, v in assignment.result.items()
        if k not in {"reason", "error", "retry_at", "actions", "provider_failure"}
    }
    assignment.save(update_fields=["state", "result"])


def reconcile(assignment):
    assignment.refresh_from_db()
    if assignment.state not in research.TERMINAL | {"stopping"}:
        _reconcile_current(assignment)
        return
    # Settlement may claim a flow receipt, which takes the experiment before its owner.
    from overbae.services import research_science  # Scientific admission imports this agent.

    # Resume takes this lock too; a retained terminal snapshot cannot cancel a new request.
    with transaction.atomic():
        research_science.experiment_for(assignment, lock=True)
        current = ResearchAssignment.objects.select_for_update().get(pk=assignment.pk)
        if current.state in research.TERMINAL | {"stopping"}:
            _reconcile_current(current)


def _reconcile_current(assignment):
    # Flow adapters also invoke the native research services.
    from overbae.services import (
        component_execution,
        experiment_dispatch,
        experiment_engine,
        experiment_predictions,
        experiment_research,
        experiment_scoring,
        research_qualification,
    )

    continuing = research.continues_admitted_work(assignment)
    if continuing and (
        assignment.deadline <= timezone.now() or not research.authorized(assignment)
    ):
        assignment = research.stop(assignment)
        continuing = False
    research_serving.reconcile(
        assignment,
        cancelling=assignment.state in {"stopping", "cancelled", "exhausted"} and not continuing,
    )
    research_benchmarks.reconcile(
        assignment,
        cancelling=assignment.state in {"stopping", "cancelled", "exhausted"} and not continuing,
    )
    component_execution.reconcile(assignment)
    experiment_predictions.reconcile(assignment)
    experiment_scoring.reconcile(assignment)
    experiment_dispatch.reconcile(assignment)
    if continuing and assignment.state in research.TERMINAL:
        if assignment.state == "blocked":
            recover_provider(assignment)
        return
    if assignment.state == "stopping" or assignment.state in research.TERMINAL:
        research_tools.stop_work(assignment)
        stopped = (
            not research_qualification.pending_actions([assignment.pk]).exists()
            and not experiment_native.pending(assignment)
            and not research_workshop.pending(assignment)
            and not research_serving.pending(assignment)
            and not research_benchmarks.pending(assignment)
        )
        stopped = experiment_research.stop_children(assignment) and stopped
        stopped = (
            experiment_dispatch.reconcile(assignment, stopping=assignment.state != "completed")
            and stopped
        )
        for agent in assignment.agents.all():
            stopped = research_workspace.stop(agent) and stopped
            if agent.state not in research.TERMINAL:
                agent.state = "cancelled"
                agent.completed_at = timezone.now()
                agent.save(update_fields=["state", "completed_at"])
            if assignment.state != "completed":
                research_team.abandon_tools(agent)
        # A stopped run cancels the campaigns it still trains; a cancelled job winds down on
        # its own record, so the run does not wait for the provider.
        for campaign in experiment_training.campaigns([assignment.pk]).filter(state="running"):
            experiment_training.stop(campaign)
        if stopped and assignment.state == "stopping":
            assignment.state = "cancelled"
            assignment.completed_at = timezone.now()
            assignment.save(update_fields=["state", "completed_at"])
            experiment_engine.settle_stop(assignment)


def settle_stop(identifier):
    """Settle a run that was asked to stop, and the campaigns it started, without waiting for
    the periodic pass. Runs it started are asked to stop here and settle themselves. True
    once the run is no longer stopping."""
    run = ResearchAssignment.objects.filter(pk=identifier).first()
    if run is None or run.state != "stopping":
        return True
    reconcile(run)
    run.refresh_from_db()
    return run.state != "stopping"


def exhaust(agent):
    fence = research_team.turn_fence(agent)
    with transaction.atomic():
        assignment = ResearchAssignment.objects.select_for_update().get(pk=agent.assignment_id)
        current = ResearchAgent.objects.select_for_update().get(pk=agent.pk)
        if not research_team.lease_matches(current, fence):
            return
        current.completed_at = timezone.now()
        current.save(update_fields=["completed_at"])
        if current.parent_id is None and assignment.state == "running":
            assignment.state = "exhausted"
            assignment.result = {**assignment.result, **current.result}
            research.event(assignment, "exhausted", assignment.result, current)
            assignment.completed_at = timezone.now()
            assignment.save(update_fields=["state", "result", "completed_at"])
    if current.parent_id:
        research_workspace.stop(current)
    else:
        reconcile(assignment)