Skip to content

The platform for continuously improving AI agents.

31.4 KB
Raw Blame
import base64
import hashlib
import json
import logging
import os
import shutil
import time
from contextlib import suppress
from datetime import datetime, timedelta
from pathlib import Path
from uuid import UUID

import modal
from django.db import transaction
from django.utils import timezone

from overbae.core.errors import DatasetError, InputValidationError
from overbae.models import (
    Dataset,
    ResearchAction,
    ResearchAgent,
    ResearchArtifact,
    ResearchAssignment,
)
from overbae.services import (
    provider_pricing,
    research,
    research_evidence,
    research_notes,
    research_questions,
    research_team,
)
from overbae.services.datasets import dispatch, files
from overbae.services.research_contract import WORKSPACE_RUNS, Workspace

APP = "overmind-research-workspace"
ROOT = "/workspace"
MAX_FILE = 10 * 1024 * 1024
MAX_INPUT = 256 * 1024 * 1024
SETTLE_SECONDS = 45
# A directory snapshot takes seconds; routine writes share one instead of each paying for it.
CHECKPOINT_SECONDS = 120
REQUIREMENTS = Path(__file__).resolve().parents[2] / "docker/workshop/requirements.txt"
logger = logging.getLogger(__name__)


def image():
    return (
        modal.Image.debian_slim(python_version="3.13")
        .pip_install_from_requirements(str(REQUIREMENTS))
        .add_local_python_source("agent_runtime", copy=True)
    )


def environment():
    return os.environ.get("MODAL_ENVIRONMENT", "main")


def require_authority(agent, family, *, sandbox=None):
    # Native tools import this service, including deferred pinned-flow collection.
    from overbae.services import execution_mandates

    agent.refresh_from_db()
    research_team.require_turn(agent)
    if agent.state in research.TERMINAL:
        raise InputValidationError("This agent no longer has execution authority")
    execution_mandates.require(agent.assignment, family)
    if sandbox is not None:
        require_identity(agent, sandbox)


def require_identity(agent, sandbox):
    agent.refresh_from_db()
    if agent.workspace.get("sandbox") != sandbox.object_id or agent.workspace.get("stopped_at"):
        raise InputValidationError("This workspace lease is no longer current")


def save_lease(agent, saved, **updates):
    with transaction.atomic():
        current = ResearchAgent.objects.select_for_update().get(pk=agent.pk)
        if any(
            current.workspace.get(key) != saved.get(key)
            for key in ("lease", "generation", "name", "environment")
        ):
            raise InputValidationError("This workspace lease has been superseded")
        if updates.get("creation_started"):
            require_authority(current, "prepare")
            if current.workspace.get("stopped_at"):
                raise InputValidationError("This workspace lease is no longer current")
        current.workspace = {**current.workspace, **updates}
        current.save(update_fields=["workspace"])
        ResearchAction.objects.filter(pk=saved["lease"], agent=current).update(
            result=current.workspace,
            **({"state": "running"} if not current.workspace.get("stopped_at") else {}),
        )
        return current.workspace


def existing(agent):
    agent.refresh_from_db()
    saved = agent.workspace
    if not saved.get("sandbox") or saved.get("stopped_at"):
        return None
    sandbox = modal.Sandbox.from_id(saved["sandbox"])
    return sandbox if sandbox.poll() is None else None


def terminate(sandbox):
    code = sandbox.poll()
    if code is None:
        # A lease can expire between poll and terminate; its exit is still observable.
        with suppress(modal.exception.SandboxTimeoutError):
            sandbox.terminate(wait=True)
        code = sandbox.poll()
    return code


def rpc(sandbox, payload=None, *, operation="request"):
    arguments = ["python", "-m", "agent_runtime.session", "--root", ROOT, operation]
    if payload is not None:
        arguments += ["--payload", base64.b64encode(json.dumps(payload).encode()).decode()]
    process = sandbox.exec(*arguments, timeout=60)
    output = process.stdout.read()
    error = process.stderr.read()
    if process.wait() != 0:
        raise InputValidationError("Research workspace request failed: " + error[-1000:])
    return json.loads(output)


def checkpoint(agent, sandbox, *, covered, force=False):
    agent.refresh_from_db()
    saved = agent.workspace
    snapshot = saved.get("snapshot") or {}
    if (
        saved.get("sandbox") != sandbox.object_id
        or saved.get("initialization_pending")
        or snapshot.get("covered") == covered
    ):
        return
    if (
        not force
        and snapshot.get("created_at")
        and timezone.now() - datetime.fromisoformat(snapshot["created_at"])
        < timedelta(seconds=CHECKPOINT_SECONDS)
    ):
        return
    remaining = int((agent.assignment.deadline - timezone.now()).total_seconds())
    if remaining < 60:
        return
    try:
        require_authority(agent, "read", sandbox=sandbox)
    except (InputValidationError, research_team.SupersededTurnError):
        return
    try:
        if rpc(sandbox, {"operation": "health"}).get("active"):
            return
        size = sandbox.exec("du", "-sb", ROOT, timeout=30)
        size_text = size.stdout.read()
        if size.wait() or int(size_text.split()[0]) > 1024 * 1024 * 1024:
            raise InputValidationError("Workspace exceeds the 1 GiB persistence limit")
        if agent.assignment.events.filter(kind="workspace_checkpoint").count() >= 200:
            raise InputValidationError("Workspace checkpoint count is exhausted")
        require_authority(agent, "read", sandbox=sandbox)
        snapshot = sandbox.snapshot_directory(ROOT, timeout=55, ttl=remaining)
        record = {
            "image": snapshot.object_id,
            "covered": covered,
            "created_at": timezone.now().isoformat(),
            "expires_at": agent.assignment.deadline.isoformat(),
            "workspace_bytes": int(size_text.split()[0]),
            "python_state": "fresh kernel on restore",
        }
        with transaction.atomic():
            current = research_team.current_turn(agent)
            if current.workspace.get("sandbox") != sandbox.object_id:
                return
            current.workspace = {**current.workspace, "snapshot": record}
            current.save(update_fields=["workspace"])
            research.event(agent.assignment, "workspace_checkpoint", record, agent)
    except research_team.SupersededTurnError:
        return
    except Exception as exc:
        logger.warning("Research workspace persistence failed: %s", type(exc).__name__)
        try:
            with transaction.atomic():
                research_team.current_turn(agent)
                research.event(
                    agent.assignment,
                    "workspace_checkpoint_failed",
                    {
                        "covered": covered,
                        "error_type": type(exc).__name__,
                        "previous_snapshot_retained": bool(saved.get("snapshot")),
                    },
                    agent,
                )
        except research_team.SupersededTurnError:
            return


def network_access(agent):
    """The approved access request this agent's workspace runs under; helpers stay offline."""
    if agent.parent_id:
        return None
    return research_questions.granted_access(agent.assignment)


def network_secrets(agent, saved):
    if not saved.get("network"):
        return []
    return [modal.Secret.from_dict({"OVERMIND_NETWORK": "1"})]


def attach(agent, *, initialize=True):
    agent.refresh_from_db()
    sandbox = existing(agent)
    saved = agent.workspace
    access = network_access(agent)
    if (
        sandbox is not None
        and not saved.get("initialization_pending")
        and (saved.get("network") or {}).get("question") != (access or {}).get("question")
    ):
        # Network policy is fixed when a sandbox is created: a decision restarts it from its snapshot.
        if not stop(agent):
            raise InputValidationError("Workspace termination is still unconfirmed")
        agent.refresh_from_db()
        sandbox, saved = None, agent.workspace
    if sandbox is not None:
        if not saved.get("initialization_pending"):
            require_authority(agent, "prepare" if initialize else "read", sandbox=sandbox)
            if initialize:
                rpc(sandbox, operation="ensure")
                require_authority(agent, "prepare", sandbox=sandbox)
            return sandbox
        # No user operation was admitted before initialization completed.
        code = terminate(sandbox)
        if code is None:
            raise InputValidationError("Workspace termination is still unconfirmed")
        research.complete(
            agent.actions.get(pk=saved["lease"]),
            {**saved, "exit_code": code, "stopped_at": timezone.now().isoformat()},
        )
        research.event(
            agent.assignment,
            "workspace_init_restarted",
            {"sandbox": sandbox.object_id, "snapshot": saved.get("snapshot")},
            agent,
        )
    try:
        require_authority(agent, "prepare")
    except InputValidationError:
        stop(agent)
        raise
    # Scientific ownership imports the Workshop sandbox, which imports this module.
    from overbae.services import research_science

    with transaction.atomic():
        research_science.experiment_for(agent.assignment, lock=True)
        ResearchAssignment.objects.select_for_update(of=("self",)).get(pk=agent.assignment_id)
        agent = (
            ResearchAgent.objects.select_for_update(of=("self",))
            .select_related("assignment")
            .get(pk=agent.pk)
        )
        require_authority(agent, "prepare")
        saved = agent.workspace
        generation = saved.get("generation", 0)
        if not saved or saved.get("sandbox") or saved.get("stopped_at"):
            generation += 1
            policy = agent.assignment.specification["budget"]
            completion = not agent.parent_id and bool(
                agent.assignment.result.get("selection_locked")
            )
            seconds = min(
                policy["workspace_seconds"],
                research.allowance(agent.assignment)["remaining_seconds"],
                300 if completion else policy["workspace_seconds"],
            )
            if seconds < 60:
                raise InputValidationError(
                    "Insufficient time remains to start a research workspace"
                )
            card = provider_pricing.current_rates()
            rates = card["rates"]
            try:
                hourly = 2 * float(rates["cpu_hour_cost_sandbox"]) + 4 * float(
                    rates["mem_gib_hour_cost_sandbox"]
                )
            except (KeyError, TypeError, ValueError) as exc:
                raise InputValidationError("Research workspace pricing is unavailable") from exc
            action = research.claim(
                agent,
                f"workspace:{generation}",
                "workspace_lease",
                {"seconds": seconds, "generation": generation},
                hourly * seconds / 3600 / 0.8,
            )
            if action.state == "denied":
                raise InputValidationError(action.result["error"])
            saved = {
                "snapshot": saved.get("snapshot"),
                "source_cells": saved.get("source_cells", []),
                "discarded_sources_at": saved.get("discarded_sources_at"),
                "generation": generation,
                "network": network_access(agent),
                "lease": str(action.pk),
                "seconds": seconds,
                "name": f"research-{agent.pk}-{generation}",
                "environment": environment(),
                "expires_at": (timezone.now() + timedelta(seconds=seconds)).isoformat(),
                "rate_card": card,
                "creation_started": False,
                "initialization_pending": True,
            }
            agent.workspace = saved
            agent.save(update_fields=["workspace"])
            action.result = saved
            action.save(update_fields=["result"])
    app = modal.App.lookup(APP, create_if_missing=True, environment_name=saved["environment"])
    try:
        sandbox = modal.Sandbox.from_name(APP, saved["name"], environment_name=saved["environment"])
    except modal.exception.NotFoundError:
        if saved["creation_started"]:
            raise InputValidationError(
                "Workspace creation acknowledgement is unknown; reconcile the saved lease before creating another"
            ) from None
        runtime_image = image()
        try:
            require_authority(agent, "prepare")
            saved = save_lease(agent, saved, creation_started=True)
        except InputValidationError:
            stop(agent)
            raise
        sandbox = modal.Sandbox.create(
            "sleep",
            str(saved["seconds"]),
            app=app,
            name=saved["name"],
            image=runtime_image,
            cpu=(2, 2),
            memory=(4096, 4096),
            timeout=saved["seconds"],
            block_network=not saved.get("network"),
            secrets=network_secrets(agent, saved),
            include_oidc_identity_token=False,
        )
    saved = save_lease(agent, saved, sandbox=sandbox.object_id)
    try:
        require_authority(agent, "prepare", sandbox=sandbox)
        if saved.get("snapshot"):
            snapshot_image = modal.Image.from_id(saved["snapshot"]["image"])
            require_authority(agent, "prepare", sandbox=sandbox)
            sandbox.mount_image(ROOT, snapshot_image)
            require_authority(agent, "prepare", sandbox=sandbox)
            cleanup = sandbox.exec(
                "python",
                "-c",
                "from pathlib import Path; p=Path('/workspace/.session/kernel.json'); p.unlink(missing_ok=True)",
                timeout=30,
            )
            if cleanup.wait():
                raise InputValidationError("The restored workspace kernel could not be reset")
        require_authority(agent, "prepare", sandbox=sandbox)
        rpc(sandbox, operation="ensure")
        require_authority(agent, "prepare", sandbox=sandbox)
        with transaction.atomic():
            current = research_team.current_turn(agent)
            if current.workspace.get("sandbox") != sandbox.object_id:
                raise InputValidationError("Workspace initialization was superseded")
            current.workspace = {**current.workspace, "initialization_pending": False}
            current.save(update_fields=["workspace"])
    except InputValidationError:
        stop(agent)
        raise
    return sandbox


def read(agent, path, *, sandbox=None):
    result = checked_rpc(
        agent,
        sandbox if sandbox is not None else attach(agent, initialize=False),
        {"operation": "read", "path": path},
        operation="file",
    )
    data = base64.b64decode(result["base64"], validate=True)
    if len(data) > MAX_FILE:
        raise InputValidationError("Research file exceeds the transfer limit")
    return data


def staged_sources(agent):
    cells = set(agent.workspace.get("source_cells", []))
    actions = agent.actions.filter(tool__in={"inspect_source", "fetch_artifact"})
    if discarded := agent.workspace.get("discarded_sources_at"):
        actions = actions.filter(created_at__gte=discarded)
    artifacts = []
    for tool, arguments in actions.values_list("tool", "arguments"):
        if tool == "inspect_source" and (arguments.get("export") or arguments.get("original")):
            cells.add(str(arguments.get("cell")))
        elif tool == "fetch_artifact":
            try:
                artifacts.append(UUID(str(arguments.get("artifact"))))
            except ValueError:
                continue
    seen = {}
    for artifact in ResearchArtifact.objects.filter(
        pk__in=artifacts, assignment__project=agent.assignment.project
    ).select_related("action__agent__assignment"):
        cells.update(research_evidence.artifact_sources(artifact, seen=seen))
    return cells


def stage(agent, path, data, *, sandbox=None, source_cell=None, source_cells=()):
    if len(data) > MAX_INPUT:
        raise InputValidationError("Research input exceeds the transfer limit")
    if agent is not None:
        agent.refresh_from_db()
        require_authority(agent, "read")
    sandbox = sandbox if sandbox is not None else attach(agent, initialize=False)
    if agent is not None:
        require_authority(agent, "read", sandbox=sandbox)
    sources = set(source_cells) | ({str(source_cell)} if source_cell else set())
    if sources and agent is not None:
        with transaction.atomic():
            current = research_team.current_turn(agent)
            current.workspace = {
                **current.workspace,
                "source_cells": sorted(set(current.workspace.get("source_cells", [])) | sources),
            }
            current.save(update_fields=["workspace"])
            research_notes.extend_workspace_inputs(current, sources)
        agent.refresh_from_db()
    # The root-owned transfer creates immutable inputs outside the kernel's writable directory.
    destination = f"{ROOT}/inputs/{path}"
    if not path or path.startswith("/") or ".." in Path(path).parts:
        raise InputValidationError("Input paths must be relative")
    digest = hashlib.sha256(data).hexdigest()
    temporary = ROOT + "/.session/transfer-" + digest
    if agent is not None:
        require_authority(agent, "read", sandbox=sandbox)
    sandbox.filesystem.write_bytes(data, temporary)
    if agent is not None:
        agent.refresh_from_db()
        require_authority(agent, "read", sandbox=sandbox)
    code = "import hashlib,json,pathlib,sys; p=pathlib.Path(sys.argv[1]); t=pathlib.Path(sys.argv[2]); d=t.read_bytes(); assert hashlib.sha256(d).hexdigest()==sys.argv[3]; p.parent.mkdir(parents=True,exist_ok=True); assert not p.exists() or p.read_bytes()==d, 'Input identity conflict'; t.replace(p); p.chmod(0o444); print(json.dumps({'path':str(p),'sha256':sys.argv[3],'bytes':len(d)}))"
    process = sandbox.exec("python", "-c", code, destination, temporary, digest, timeout=60)
    output = process.stdout.read()
    if process.wait() != 0:
        raise InputValidationError("Research input transfer failed")
    if agent is not None:
        agent.refresh_from_db()
        require_authority(agent, "read", sandbox=sandbox)
    return json.loads(output)


def stage_artifact(agent, identifier, *, fingerprint=None, sandbox=None):
    artifact = research.accessible_artifact(agent.assignment, identifier)
    data = research.artifact_bytes(artifact, limit=MAX_FILE)
    if fingerprint is not None and fingerprint != artifact.sha256:
        raise InputValidationError("The connected artifact differs from its retained identity")
    return stage(
        agent,
        f"artifacts/{artifact.pk}.bin",
        data,
        sandbox=sandbox,
        source_cells=research_evidence.artifact_sources(artifact),
    )


def validate_write_progress(action, request):
    if request.operation != "write":
        return
    previous = list(
        action.agent.actions.filter(state="completed", created_at__lt=action.created_at)
        .exclude(pk=action.pk)
        .exclude(tool__in=["model", "workspace_lease", "inbox", "remember"])
        .order_by("-created_at")[:2]
    )
    if len(previous) == 2 and all(
        prior.tool == "workspace"
        and prior.arguments.get("operation") == "write"
        and prior.arguments.get("path") == request.path
        for prior in previous
    ):
        raise InputValidationError(
            "This file was already written twice without new evidence. Read or validate the saved "
            "file before another revision, or retain_artifact and review it if complete. "
            "Keep the report's dated cost snapshot; authoring and review charges continue changing "
            "the ledger and are not a reason to rewrite the report."
        )


def checked_rpc(agent, sandbox, payload, *, operation="request"):
    agent.refresh_from_db()
    require_identity(agent, sandbox)
    passive = operation == "request" and payload.get("operation") in {
        "status",
        "health",
        "interrupt",
    }
    if (
        passive
        and payload.get("operation") != "health"
        and not agent.actions.filter(
            pk=payload.get("execution"), tool="workspace", arguments__operation__in=WORKSPACE_RUNS
        ).exists()
    ):
        raise InputValidationError("This execution does not belong to this agent")
    if not passive:
        family = "read" if operation == "file" and payload.get("operation") == "read" else "prepare"
        require_authority(agent, family, sandbox=sandbox)
        if operation == "request" and payload.get("operation") in {"submit", "start"}:
            # The ambient continuation may authorize only its exact retained action.
            from overbae.services import execution_mandates

            action = agent.actions.filter(
                pk=payload.get("execution"),
                tool="workspace",
                arguments__operation="python" if payload["operation"] == "submit" else "terminal",
            ).first()
            if action is None:
                raise InputValidationError("This execution does not belong to this agent")
            request = Workspace.model_validate(action.arguments)
            if (
                payload.get("code", "") != request.code
                or payload.get("command", "") != request.command
                or payload.get("timeout") != request.timeout
            ):
                raise InputValidationError("The workspace request differs from its retained action")
            execution_mandates.require_action(action, family)
    result = rpc(sandbox, payload, operation=operation)
    agent.refresh_from_db()
    if not passive:
        require_authority(agent, family, sandbox=sandbox)
    return result


def execute(action, request, *, sandbox=None):
    validate_write_progress(action, request)
    action.agent.refresh_from_db()
    if request.operation in {"write", *WORKSPACE_RUNS}:
        # Retain authored inputs before provider preparation can fail or lose acknowledgement.
        from overbae.services.research_tools import source_boundary

        source_cells = research_notes.retain_sources(
            action,
            "workspace_inputs",
            staged_sources(action.agent) | research_notes.observed_sources(action),
        )
        denied = source_boundary(action.agent.assignment)[1]
        if denied and source_cells & (denied | research_notes.UNRESOLVED):
            raise InputValidationError("This authored operation includes newly sealed source data")
    if request.operation in {"status", "interrupt"}:
        if request.execution is None:
            raise InputValidationError("Supply the retained execution identity")
        if not action.agent.actions.filter(
            pk=request.execution, tool="workspace", arguments__operation__in=WORKSPACE_RUNS
        ).exists():
            raise InputValidationError("This execution does not belong to this agent")
    if sandbox is None:
        sandbox = (
            existing(action.agent)
            if request.operation in {"status", "interrupt"}
            else attach(action.agent, initialize=request.operation != "read")
        )
    if sandbox is None:
        return {
            "state": "unknown",
            "reason": "workspace_exited",
            "execution": str(request.execution),
        }
    if request.operation in {"write", *WORKSPACE_RUNS}:
        with transaction.atomic():
            current = research_team.current_turn(action.agent)
            source_cells = staged_sources(current) | research_notes.retained_sources(
                action, "workspace_inputs"
            )
            current.workspace = {**current.workspace, "source_cells": sorted(source_cells)}
            current.save(update_fields=["workspace"])
            research_notes.retain_sources(
                action, "workspace_inputs", source_cells, workspace=current.workspace
            )
            research_notes.extend_workspace_inputs(current, source_cells)
        action.agent.refresh_from_db()
    source_cells = staged_sources(action.agent)

    def with_sources(result):
        return {**result, "source_cells": sorted(source_cells | staged_sources(action.agent))}

    if request.operation == "read":
        data = read(action.agent, request.path, sandbox=sandbox).decode()
        return with_sources(
            {
                "path": request.path,
                "text": data[request.offset : request.offset + request.limit],
                "next_offset": request.offset + request.limit
                if len(data) > request.offset + request.limit
                else None,
            }
        )
    if request.operation == "write":
        result = checked_rpc(
            action.agent,
            sandbox,
            {"operation": "write", "path": request.path, "text": request.text},
            operation="file",
        )
        checkpoint(action.agent, sandbox, covered=str(action.pk))
        return with_sources(result)
    if request.operation in WORKSPACE_RUNS:
        terminal = request.operation == "terminal"
        result = checked_rpc(
            action.agent,
            sandbox,
            {
                "execution": str(action.pk),
                "timeout": request.timeout,
                **(
                    {"operation": "start", "command": request.command}
                    if terminal
                    else {"operation": "submit", "code": request.code}
                ),
            },
        )
        # Most programs finish in seconds: return their output with the call instead of
        # spending a model turn on polling. A longer one keeps running under its receipt.
        deadline = time.monotonic() + min(request.timeout, SETTLE_SECONDS)
        while result.get("state") in {"accepted", "running"} and time.monotonic() < deadline:
            time.sleep(0.5)
            result = checked_rpc(
                action.agent, sandbox, {"operation": "status", "execution": str(action.pk)}
            )
            if terminal:
                # The experiment's chat shows the job's output as it arrives.
                ResearchAction.objects.filter(pk=action.pk, state="running").update(result=result)
        return with_sources(result)
    if request.operation in {"status", "interrupt"}:
        return with_sources(
            checked_rpc(
                action.agent,
                sandbox,
                {
                    "operation": request.operation,
                    "execution": str(request.execution),
                    "offset": request.offset,
                },
            )
        )
    return with_sources(checked_rpc(action.agent, sandbox, {"operation": "reset"}))


def import_state(dataset):
    cell = dataset.active_cell
    if cell is None or cell.state != "ok":
        return {"state": dataset.state, **({"error": dataset.error} if dataset.error else {})}
    return {"state": "landed", "cell": str(cell.pk), "rows": cell.rows}


def import_dataset(action, request):
    agent = action.agent
    assignment = agent.assignment
    # A repeated call is a status read: landing is asynchronous and must not duplicate the dataset.
    previous = (
        assignment.events.filter(
            kind="dataset_imported", payload__path=request.path, payload__name=request.name
        )
        .order_by("-pk")
        .first()
    )
    if previous:
        dataset = Dataset.objects.select_related("active").get(pk=previous.payload["dataset"])
        return previous.payload | import_state(dataset)
    path = Path(request.path)
    if path.is_absolute() or ".." in path.parts:
        raise InputValidationError(f"Name a file relative to the working directory {ROOT}/work")
    sandbox = attach(agent, initialize=False)
    upload, filename = files.begin_upload(path.name)
    stored = files.upload_data_path(upload)
    try:
        measured = sandbox.exec("stat", "-c", "%s", f"{ROOT}/work/{path}", timeout=30)
        size = measured.stdout.read().strip()
        if measured.wait() or not size.isdigit():
            raise InputValidationError(f"{request.path} is not a file in the working directory")
        if int(size) > files.upload_byte_limit(filename):
            raise InputValidationError(
                f"{request.path} exceeds the {files.upload_byte_limit(filename)} byte import limit"
            )
        require_authority(agent, "prepare", sandbox=sandbox)
        sandbox.filesystem.copy_to_local(f"{ROOT}/work/{path}", stored)
        require_authority(agent, "prepare", sandbox=sandbox)
        inspected = files.inspect_upload(upload, size=files.stored_stat(stored).st_size)
        with transaction.atomic():
            dataset = dispatch.create_dataset(
                project=assignment.project,
                user=assignment.created_by,
                name=request.name,
                source={"uploads": [upload]},
                capability=assignment.capability,
                infer_capability=False,
            )
            result = {
                "action": str(action.pk),
                "dataset": str(dataset.pk),
                "name": dataset.name,
                "path": request.path,
                "bytes": inspected["bytes"],
                "rows": inspected["rows"],
            }
            research.event(assignment, "dataset_imported", result, agent)
            result |= import_state(dataset)
    except (InputValidationError, DatasetError) as refused:
        shutil.rmtree(files.upload_dir(upload), ignore_errors=True)
        raise InputValidationError(str(refused)) from None
    return result


def stop(agent, *, actor=None):
    with transaction.atomic():
        if actor is not None:
            research_team.current_turn(actor)
        current = ResearchAgent.objects.select_for_update().get(pk=agent.pk)
        saved = current.workspace
        if saved.get("stopped_at"):
            return True
        if not saved.get("sandbox") and not saved.get("creation_started"):
            if saved.get("lease"):
                saved = {**saved, "not_submitted": True, "stopped_at": timezone.now().isoformat()}
                current.workspace = saved
                current.save(update_fields=["workspace"])
                research.complete(current.actions.get(pk=saved["lease"]), saved, cost=0)
            return True
    if not saved.get("sandbox"):
        if not all(saved.get(key) for key in ("name", "environment", "lease")):
            return False
        try:
            sandbox = modal.Sandbox.from_name(
                APP, saved["name"], environment_name=saved["environment"]
            )
        except modal.exception.NotFoundError:
            return False
        saved = save_lease(agent, saved, sandbox=sandbox.object_id)
    else:
        try:
            sandbox = modal.Sandbox.from_id(saved["sandbox"])
        except modal.exception.NotFoundError:
            return False
    if sandbox.poll() is None:
        checkpoint(agent, sandbox, covered=f"stop:{saved['generation']}", force=True)
    code = terminate(sandbox)
    if code is None:
        return False
    saved = {**saved, "exit_code": code, "stopped_at": timezone.now().isoformat()}
    with transaction.atomic():
        current = ResearchAgent.objects.select_for_update().get(pk=agent.pk)
        if current.workspace.get("sandbox") == sandbox.object_id:
            current.workspace = {
                **current.workspace,
                "exit_code": code,
                "stopped_at": saved["stopped_at"],
            }
            current.save(update_fields=["workspace"])
    action = agent.actions.get(pk=saved["lease"])
    research.complete(action, saved)
    return True