The platform for continuously improving AI agents.
import hashlib
import io
from contextlib import contextmanager
from contextvars import ContextVar
from datetime import timedelta
from pathlib import Path
from uuid import UUID
from django.db import transaction
from django.db.models import Q
from django.utils import timezone
from pydantic import ValidationError
from rest_framework.exceptions import ValidationError as SerializerValidationError
from agent_runtime.tool_contract import ToolArgumentsError
from overbae.core.errors import InputValidationError
from overbae.models import (
Cell,
DataPartitionMember,
DataPartitionPlan,
Dataset,
DatasetPipelineRun,
ExperimentNodeExecution,
FinetuningJob,
InferenceRequest,
NativeEvaluationPlan,
ResearchAction,
ResearchAgent,
ResearchAssignment,
TrainingCampaign,
)
from overbae.services import (
context_graph,
context_query,
execution_mandates,
experiment_operator,
experiment_training,
research,
research_acceptance,
research_benchmarks,
research_catalogue,
research_continuity,
research_effects,
research_evidence,
research_experiments,
research_notes,
research_requests,
research_science,
research_services,
research_serving,
research_team,
research_workshop,
research_workspace,
)
from overbae.services.datasets import (
column_profile,
context,
partition_plans,
paths,
pipeline_packages,
preparation,
rows,
store,
workbench,
)
from overbae.services.research_contract import TOOLS, WORKSPACE_RUNS, TrainingRequest
from overbae.services.research_errors import ToolStateError
from overbae.tasks.context_graph import refresh_project
PLATFORM_READS = set(research_services.READS)
PLATFORM_WRITES = set(research_services.WRITES)
STRUCTURE_ERRORS = {"model_type", "dict_type", "list_type", "model_attributes_type"}
def retained_operation(action):
key = f"research:{action.pk}"
assignment = action.agent.assignment
if action.tool == "workshop" and action.arguments.get("operation") == "prepare":
task = research_workshop.owned(assignment).filter(request_key=key).first()
if task is not None:
return research_workshop.describe(task)
return None
def received(item):
# Data rows and scripts are never echoed. A short scalar written where an object or list
# belongs is a structural slip, and naming it is what lets the model correct it.
value = item.get("input")
if item["type"] in STRUCTURE_ERRORS and isinstance(value, (str, int, float, bool)):
return f"; received {type(value).__name__} {str(value)[:40]!r}"
return ""
def argument_failure(exc):
if isinstance(exc, ToolStateError):
return {"error": str(exc)[:2000], "type": type(exc).__name__, "details": exc.details}
if isinstance(exc, SerializerValidationError):
return {
"error": "Invalid tool arguments",
"type": "ValidationError",
"details": exc.detail,
"recovery": "Correct the named fields before retrying.",
}
if isinstance(exc, ToolArgumentsError):
return {
"error": str(exc),
"type": "ToolArgumentsError",
"details": exc.details,
"recovery": "Correct the named fields using this tool's attached schema before retrying.",
}
validation = exc if isinstance(exc, ValidationError) else exc.__cause__
if not isinstance(validation, ValidationError):
return {"error": str(exc)[:2000], "type": type(exc).__name__}
return {
"error": "Invalid tool arguments",
"type": "ValidationError",
"details": [
{"field": ".".join(map(str, item["loc"])), "message": item["msg"] + received(item)}
for item in validation.errors(include_url=False)[:20]
],
"recovery": "Correct the named fields using this tool's attached schema before retrying.",
}
def owned_work(assignment, *, observe=False):
"""Pipeline runs and partitions this assignment started; ``observe`` adds its flow runs'."""
scope = research_evidence.owners(assignment) if observe else [assignment.pk]
pipelines, partitions = research_effects.owned_data(
ResearchAssignment.objects.filter(pk__in=scope),
workshop_assignments=ResearchAssignment.objects.filter(pk=assignment.pk),
)
return pipelines.select_related("output", "dataset"), partitions.prefetch_related(
"members__cell"
)
def experiment_partitions(assignment):
"""Partitions made by any run of the assignment's experiment, the Workshop tasks those
runs delegated included."""
scope = ResearchAssignment.objects.filter(pk__in=research_evidence.investigation(assignment))
_, partitions = research_effects.owned_data(scope)
return partitions.prefetch_related("members__cell")
def flow_cells(assignment):
"""Readable datasets the completed stages of this flow run wrote or reused. The engine
binds them to the stages downstream; no agent chose them."""
return {
UUID(binding["cell"])
for outputs in ExperimentNodeExecution.objects.filter(
execution_id=assignment.pk, state="completed"
).values_list("outputs", flat=True)
for binding in outputs.values()
if isinstance(binding, dict) and binding.get("kind") == "data" and binding.get("cell")
}
def work_evidence(assignment):
pipelines, partitions = owned_work(assignment)
from overbae.services import (
component_execution,
experiment_predictions,
experiment_scoring,
research_qualification,
)
# The Workshop's own runs and partitions are reported once, in its record.
delegated = Q(request_key__startswith="workshop:")
return {
"workshop": research_workshop.observations(assignment),
"components": component_execution.observations(assignment),
"qualifications": [
{"id": str(action.pk), "state": action.state}
for action in research_qualification.pending_actions([assignment.pk]).only(
"pk", "state"
)
],
"predictions": experiment_predictions.observations(assignment),
"scores": experiment_scoring.observations(assignment),
"pipelines": [
{
"id": str(run.pk),
"state": run.state,
"error": run.error,
"output": str(run.output_id) if run.output_id else None,
}
for run in pipelines.exclude(delegated)
],
"partitions": [
{
"id": str(plan.pk),
"state": plan.state,
"error": plan.error,
"members": [
{
"role": m.role,
"cell": str(m.cell_id),
"access": "readable" if plan.state == "completed" else "unavailable",
}
for m in plan.members.all()
],
}
for plan in partitions.exclude(delegated)
],
}
def stop_work(assignment):
from overbae.innermind import runs
from overbae.models import PredictionEvaluation, PredictionSet
from overbae.services import ( # Native admission uses source_cell.
component_execution,
experiment_native,
experiment_predictions,
research_qualification,
)
if assignment.state not in {"completed", "unmet"}:
research_qualification.cancel(assignment)
research_workshop.cancel(assignment)
experiment_native.cancel(assignment)
component_execution.cancel(assignment)
for predictions in PredictionSet.objects.filter(
assignment=assignment, state__in=["pending", "running"]
):
experiment_predictions.cancel(predictions)
for evaluation in PredictionEvaluation.objects.filter(
assignment=assignment, run__status__in=["pending", "running"]
).select_related("run"):
runs.cancel(evaluation.run)
pipelines, partitions = owned_work(assignment)
for run in pipelines.exclude(state__in=["completed", "failed", "cancelled"]):
workbench.cancel_run(assignment.project, run.pk)
for plan in partitions.exclude(state__in=["completed", "failed", "cancelled"]):
partition_plans.cancel(plan)
def source_lineage(cell):
process = preparation.describe(cell.dataset, cell=cell, include_siblings=False)
cells = {str(node["cell"].pk): node["cell"] for node in process["nodes"]}
parents = {}
for edge in process["edges"]:
parents.setdefault(edge["target"], []).append(edge["source"])
pending, visited = [str(cell.pk)], set()
while pending:
key = pending.pop()
if key in visited:
continue
visited.add(key)
pending.extend(parents.get(key, []))
return [cells[key] for key in visited]
def project_source_boundary(project, *, additional=(), exclude_partition=None):
"""The final holdouts no agent reads: every partition's final member and the versions an
assignment seals, with their fingerprints, so the same bytes landed again stay sealed.
Returns ``(sealed, denied, hashes, sealed_hashes)``; a holdout's rows reach an agent only
through a Qualify stage."""
members = DataPartitionMember.objects.filter(plan__project=project, role="final")
if exclude_partition is not None:
members = members.exclude(plan_id=exclude_partition)
sealed = {str(cell) for cell in members.values_list("cell_id", flat=True)}
sealed |= {str(cell) for cell in additional}
hashes = set(
Cell.objects.filter(pk__in=sealed)
.exclude(fingerprint="")
.values_list("fingerprint", flat=True)
)
return sealed, set(sealed), hashes, set(hashes)
SOURCE_READ_BOUNDARY = ContextVar("research_source_read_boundary", default=None)
@contextmanager
def source_read_scope(assignment):
# Rendering is read-only; model admission rechecks the scope after this snapshot is released.
boundary = source_boundary(assignment)
token = SOURCE_READ_BOUNDARY.set((assignment.pk, boundary))
try:
yield
finally:
SOURCE_READ_BOUNDARY.reset(token)
def source_boundary(assignment, *, exclude_partition=None):
snapshot = SOURCE_READ_BOUNDARY.get()
if snapshot is not None and snapshot[0] == assignment.pk and exclude_partition is None:
return tuple(set(part) for part in snapshot[1])
return project_source_boundary(
assignment.project,
additional=assignment.specification.get("sealed_cells", []),
exclude_partition=exclude_partition,
)
def denied_cells(assignment, *, exclude_partition=None):
sealed, denied, _, _ = source_boundary(assignment, exclude_partition=exclude_partition)
return sealed, denied
def cell_identity(cell):
return {
"cell": str(cell.pk),
"title": cell.title,
"position": cell.position,
"lineage": preparation.lineage(cell),
"fingerprint": cell.fingerprint,
"dataset": {
"id": str(cell.dataset_id),
"name": cell.dataset.name,
"brief": cell.dataset.brief,
},
"row_count": cell.rows,
}
def source_cell(assignment, identifier, *, boundary=None, platform_reads=False):
"""A version the assignment may use. ``platform_reads`` marks work the platform does with
the rows, such as a Qualify stage's measurement; every other read is an agent's, and no
agent reads a final holdout or a version derived from one."""
cell = (
Cell.objects.select_related("dataset")
.filter(pk=identifier, dataset__project=assignment.project, state="ok")
.first()
)
if cell is None:
raise InputValidationError("The source cell is unavailable in this project")
execution_mandates.require_published_cell(cell, project_id=assignment.project_id)
if platform_reads:
return cell
sealed, denied, hashes, sealed_hashes = boundary or source_boundary(assignment)
if str(cell.pk) in denied or cell.fingerprint in hashes:
raise partition_plans.SealedHoldoutError(
f"Version {cell.pk} is a sealed final holdout: only a Qualify stage reads it, once."
)
if sealed and any(
str(parent.pk) in sealed or parent.fingerprint in sealed_hashes
for parent in source_lineage(cell)
):
raise partition_plans.SealedHoldoutError(
f"Version {cell.pk} is derived from a sealed final holdout: only a Qualify stage "
"reads that data, once."
)
return cell
def sources_permitted(assignment, identifiers, *, boundary=None, cache=None):
boundary = boundary or source_boundary(assignment)
cache = {} if cache is None else cache
for identifier in identifiers:
if identifier == "unresolved_evidence":
continue
if identifier not in cache:
try:
source_cell(assignment, UUID(str(identifier)), boundary=boundary)
except (InputValidationError, TypeError, ValueError):
cache[identifier] = False
else:
cache[identifier] = True
if not cache[identifier]:
return False
return True
def readable_input(cell, *, details=True):
if not details:
return cell_identity(cell) | {"access": "readable"}
entry = cell_identity(cell) | {
"access": "readable",
"schema": store.read_manifest(rows.frame_path(cell)),
}
if len(cell.columns) <= column_profile.SHOWN_COLUMNS:
entry["profile"] = column_profile.of(cell)
return entry
def approved_inputs(assignment, *, details=True):
"""What each attached dataset is and how it can be read, so the first read cannot be a guess."""
inputs = []
for root in assignment.specification.get("context_roots", []):
kind, _, identifier = root.partition(":")
if kind != "cell":
continue
try:
cell = source_cell(assignment, identifier)
except InputValidationError:
continue
inputs.append(readable_input(cell, details=details))
return inputs
def visible_context(assignment, request):
if request.operation == "partitions":
partitions = input_partitions(assignment)
end = request.offset + request.limit
return {
"input_partitions": partitions[request.offset : end],
"next_offset": end if end < len(partitions) else None,
}
if request.operation == "read" and request.reference.startswith("cell:"):
source_cell(assignment, request.reference.split(":", 1)[1])
return context_query.execute(assignment.project, request, assignment=assignment)
def approved_source_hashes(assignment):
roots = assignment.specification.get("context_roots", [])
cells = [root.split(":", 1)[1] for root in roots if root.startswith("cell:")]
return set(
Cell.objects.filter(dataset__project=assignment.project, pk__in=cells)
.exclude(fingerprint="")
.values_list("fingerprint", flat=True)
)
def input_partitions(
assignment, *, source=None, boundary=None, include_unavailable=False, plan_ids=None
):
# Authored graph projection calls source permission checks in this dispatcher.
from overbae.services import research_context_authorship
result = []
boundary = boundary or source_boundary(assignment)
lineages = {}
plans = (
DataPartitionPlan.objects.filter(project=assignment.project, state="completed")
.select_related("source_cell__dataset")
.prefetch_related("members__cell__dataset")
.order_by("created_at", "pk")
)
if plan_ids is not None:
plans = plans.filter(pk__in=plan_ids)
for plan in plans:
if source is not None:
if plan.source_cell_id not in lineages:
lineages[plan.source_cell_id] = source_lineage(plan.source_cell)
if not any(
cell.pk == source.pk
or (source.fingerprint and cell.fingerprint == source.fingerprint)
for cell in lineages[plan.source_cell_id]
):
continue
members = list(plan.members.all())
readable = []
unavailable = {}
for member in members:
try:
source_cell(assignment, member.cell_id, boundary=boundary)
except partition_plans.SealedHoldoutError:
unavailable[str(member.cell_id)] = "sealed_final_holdout"
continue
except InputValidationError:
unavailable[str(member.cell_id)] = "source_access_denied"
continue
readable.append(str(member.cell_id))
if not readable and not include_unavailable:
continue
result.append(
{
"partition": str(plan.pk),
"name": plan.name,
"source": {
"cell": str(plan.source_cell_id),
"fingerprint": plan.source_fingerprint,
"dataset": str(plan.source_cell.dataset_id),
"access": "metadata_only",
},
"recipe": research_context_authorship.project_record(
assignment, f"partition:{plan.pk}", {"recipe": plan.recipe}
)["recipe"],
"members": [
{
"role": member.role,
"cell": str(member.cell_id),
"fingerprint": member.cell.fingerprint,
"access": (
"readable" if str(member.cell_id) in readable else "metadata_only"
),
**(
{"reason": unavailable[str(member.cell_id)]}
if str(member.cell_id) in unavailable
else {}
),
}
for member in members
],
}
)
return result
def plan_metadata_cells(assignment, args, partitions):
if not args.get("partition"):
return set()
plan = (
partitions.filter(pk=args["partition"], state="completed")
.select_related("source_cell__dataset")
.first()
)
if (
plan is None
or str(plan.source_cell_id) != args.get("prepared_cell")
or plan.source_cell.fingerprint != plan.source_fingerprint
):
raise InputValidationError("Bind a completed partition and its exact source")
sealed, _ = denied_cells(assignment)
pending, allowed = [plan.source_cell], set()
while pending:
cell = pending.pop()
if str(cell.pk) in allowed:
continue
if str(cell.pk) in sealed or not cell.frozen:
raise InputValidationError("Training-plan metadata must refer to frozen source lineage")
allowed.add(str(cell.pk))
pending.extend(preparation.input_cells(cell))
if len(allowed) > 2000:
raise InputValidationError("Training-plan source lineage exceeds the binding limit")
return allowed
def training_job(jobs, identifier):
"""The training job an identifier names. An agent is shown a campaign with its trials,
their jobs and their executions, and any of those identifiers selects the job."""
return (
jobs.filter(Q(pk=identifier) | Q(trial__pk=identifier)).first()
or jobs.filter(trial__campaign__pk=identifier).order_by("-created_at").first()
)
def platform(action, request):
if request.name not in research_services.OPERATIONS or not research_team.permits(
action.agent, "platform", request.model_dump(mode="json")
):
raise InputValidationError(
"This platform operation is not available to this research agent"
)
contract, description = research_services.OPERATIONS[request.name]
if request.describe:
return {
"name": request.name,
"description": description,
"input_schema": research_services.input_schema(request.name),
"flow": research_catalogue.flow_contracts("platform", request.name),
}
if research_evidence.can_read_final(
action.agent.assignment
) and request.name in PLATFORM_WRITES - {
"export_data",
"check_data",
"verify_deployment",
"measure_serving",
}:
raise InputValidationError(
"Final qualification has locked this assignment's data and model selection"
)
args = dict(request.arguments)
if "request_key" in contract.model_fields:
args["request_key"] = f"research:{action.pk}"
parsed = contract.model_validate(args)
args = parsed.model_dump(mode="json", exclude_unset=True)
assignment = action.agent.assignment
# Work a saved flow ran for this assignment is read the same way as its direct work.
pipelines, partitions = owned_work(assignment, observe=True)
# A completed partition is published project data: every run may name the ones
# context.input_partitions lists, whichever run made them.
partitions = (
DataPartitionPlan.objects.filter(project=assignment.project)
.filter(Q(pk__in=partitions.values("pk")) | Q(state="completed"))
.prefetch_related("members__cell")
)
campaigns = experiment_training.campaigns(research_evidence.owners(assignment))
jobs = FinetuningJob.objects.filter(trial__campaign__in=campaigns)
if request.name in {"get_job", "inspect_training_progress"}:
jobs = FinetuningJob.objects.filter(project=assignment.project)
if request.name == "get_job":
pipelines = DatasetPipelineRun.objects.filter(
dataset__project=assignment.project
).select_related("output", "dataset")
partitions = DataPartitionPlan.objects.filter(project=assignment.project).prefetch_related(
"members__cell"
)
job, dataset, source = None, None, None
metadata_cells = (
plan_metadata_cells(assignment, args, partitions)
if request.name == "save_training_plan"
else set()
)
if request.name == "get_job":
kind, identifier = args.get("kind"), args.get("id")
allowed_job = (
kind == "finetune_job"
and training_job(jobs, identifier) is not None
or kind == "native_evaluation"
and NativeEvaluationPlan.objects.filter(
project=assignment.project, pk=identifier
).exists()
or kind == "dataset_pipeline"
and pipelines.filter(pk=identifier).exists()
or kind == "data_partition"
and partitions.filter(pk=identifier).exists()
)
if not allowed_job:
raise InputValidationError("This work receipt is unavailable in this project")
if args.get("job") or (request.name == "get_job" and args["kind"] == "finetune_job"):
job = training_job(jobs, args.get("job") or args["id"])
if job is None:
raise InputValidationError(
"This training job is unavailable for this operation in this project"
)
for name in (
"cell",
"source_cell",
"train_cell",
"development_cell",
"calibration_cell",
"prepared_cell",
):
if args.get(name):
if name in {"source_cell", "prepared_cell"} and args[name] in metadata_cells:
continue
source = source_cell(
assignment,
args[name],
platform_reads=request.name in {"prepare_dataset", "create_data_partition"},
)
for evidence in args.get("evidence", []):
for identifier in evidence.get("cells", []):
if evidence["kind"] == "audit" and identifier in metadata_cells:
continue
source_cell(assignment, identifier)
if args.get("partition") and not partitions.filter(pk=args["partition"]).exists():
raise InputValidationError(
"Select a completed partition in this project, or one this assignment started"
)
if args.get("dataset"):
dataset = research_services.dataset(assignment.project, args["dataset"])
pinned_destination = (
request.name in research_services.PIPELINE_RUNS
and source is not None
and source.dataset_id == dataset.pk
)
if not pinned_destination:
selected = dataset.active_cell.pk if dataset.active_cell else None
if selected is None:
raise InputValidationError("Select a dataset with a readable source cell")
source_cell(assignment, selected)
if request.name in {"run_dataset_pipeline", "validate_dataset_pipeline"}:
# Authorship projection calls source admission; defer the reverse dependency.
from overbae.services import research_context_authorship
research_context_authorship.require_pipeline(assignment, args.get("pipeline"))
result = research_services.invoke(
request.name,
parsed,
assignment,
dataset=dataset,
job=job,
pipeline_runs=pipelines,
partitions=partitions,
source=source,
action=action,
)
if request.name == "inspect_dataset_workbench":
for index, run in enumerate(result.get("runs", [])):
try:
source_cell(assignment, run["source_cell"])
except InputValidationError:
result["runs"][index] = {
"id": run["id"],
"state": run["state"],
"access": "restricted",
}
return result
def training(action, request):
if not research_team.permits(action.agent, "training", request.model_dump()):
raise InputValidationError(
"Helpers return research evidence; the owner admits training work"
)
assignment = action.agent.assignment
if (
assignment.specification["constraints"].get("no_training")
and request.operation != "inspect"
and request.operation != "stop"
and not request.describe
):
raise InputValidationError("This assignment forbids training work")
if request.describe:
return TOOLS["training"].payload_schema(request.operation)
if request.operation == "create":
args = TrainingRequest.model_validate(request.arguments)
run = dict(args.run)
sealed = set(assignment.specification.get("sealed_cells", []))
for role in ("cell", "validation_cell", "eval_cell"):
if run.get(role) is None:
continue
if str(run[role]) in sealed:
raise InputValidationError("A sealed final version cannot train or validate a run")
source_cell(assignment, run[role])
with transaction.atomic():
reservation = research.claim(
action.agent,
f"campaign:{action.pk}",
"campaign_allocation",
{"run": run, "trials": args.trials},
)
if reservation.state == "denied":
raise InputValidationError(reservation.result["error"])
research_team.admit_mutation(action.agent)
campaign = experiment_training.start(action, run, max_trials=args.trials)
research.complete(reservation, {"campaign": str(campaign.pk)})
return campaign_packet(campaign, assignment=assignment)
# Any campaign of the project can be read; only this run's own campaigns can be stopped.
campaigns = (
TrainingCampaign.objects.filter(project=assignment.project)
if request.operation == "inspect"
else experiment_training.campaigns(research_evidence.owners(assignment))
)
campaign = campaigns.filter(pk=request.campaign).first()
if campaign is None:
raise InputValidationError(
"This campaign is unavailable for this operation in this project"
)
if request.operation == "stop":
if not campaign.request_key.startswith(f"{experiment_training.PREFIX}{assignment.pk}:"):
raise InputValidationError("Only the assignment that started a campaign may stop it")
experiment_training.stop(campaign)
return campaign_packet(campaign, assignment=assignment)
def campaign_packet(campaign, *, assignment=None):
campaign.refresh_from_db()
packet = {
"campaign": experiment_training.describe(campaign),
"selection": experiment_training.selection(campaign),
"runs": [
{
"index": trial.index,
"job": str(trial.job_id),
"status": trial.job.status,
"error": trial.job.error_message,
"development": experiment_training.development(trial.job),
"checkpoint": experiment_training.checkpoint(trial.job),
}
for trial in campaign.trials.select_related("job")
],
}
return research_evidence.visible(assignment, packet) if assignment else packet
def lock_selection(assignment, *, candidates=(), sealed=(), protocol=None):
return research_science.freeze(
assignment, candidates=candidates, sealed=sealed, protocol=protocol
)
def pending_work(assignment, agent=None):
# Flow dispatch shares these native tools but owns its own continuation.
from overbae.services import experiment_dispatch, experiment_native, research_qualification
qualifications = research_qualification.pending_actions([assignment.pk])
if agent is not None:
qualifications = qualifications.filter(agent=agent)
if qualifications.exists():
return True
if research_workshop.pending(assignment):
return True
if experiment_native.pending(assignment):
return True
agents = assignment.agents.all()
if agent is not None:
agents = agents.filter(pk=agent.pk)
for item in agents:
if item.workspace.get("sandbox") and "stopped_at" not in item.workspace:
sandbox = research_workspace.existing(item)
if sandbox is None:
continue
health = research_workspace.rpc(sandbox, {"operation": "health"})
if health.get("active"):
return True
if agent is None:
from overbae.models import ComponentExecution, PredictionEvaluation, PredictionSet
if ComponentExecution.objects.filter(
action__agent__assignment=assignment, state__in=["queued", "running"]
).exists():
return True
if (
PredictionSet.objects.filter(
assignment=assignment, state__in=["pending", "running"]
).exists()
or PredictionEvaluation.objects.filter(
assignment=assignment, run__status__in=["pending", "running"]
).exists()
):
return True
if experiment_dispatch.owned(assignment).exclude(state__in=research.TERMINAL).exists():
return True
if research_serving.pending(assignment) or research_benchmarks.pending(assignment):
return True
pipelines, partitions = owned_work(assignment)
if (
pipelines.filter(state__in=["queued", "running"]).exists()
or partitions.filter(state__in=["queued", "running"]).exists()
):
return True
return experiment_training.pending([assignment.pk])
return False
def progress_possible(agent):
"""Whether anything can change without this agent acting: a teammate that can take a
turn, a program still running in a workspace, or admitted asynchronous work."""
assignment = agent.assignment
if ResearchAction.objects.filter(
agent__assignment=assignment,
tool="workspace",
arguments__operation__in=WORKSPACE_RUNS,
result__state__in=["accepted", "running"],
).exists():
return True
if any(
research_team.ready(member)
for member in assignment.agents.exclude(pk=agent.pk).exclude(state__in=research.TERMINAL)
):
return True
return pending_work(assignment)
def retained_text(assignment, identifier):
"""A retained record by identifier: an action of this assignment or of a flow run it
started, or an artifact visible to it. Agents are handed both kinds of identifier."""
retained = ResearchAction.objects.filter(
pk=identifier, agent__assignment_id__in=research_evidence.owners(assignment)
).first()
if retained is not None:
return context_graph.canonical(
{
"tool": retained.tool,
"arguments": research_evidence.action_arguments(assignment, retained),
"state": retained.state,
"result": research_evidence.action_result(assignment, retained),
}
)
artifact = research_evidence.artifacts(assignment).filter(pk=identifier).first()
if artifact is None:
# A flow run is read through the receipt it left.
artifact = (
research_evidence.artifacts(assignment)
.filter(metadata__flow_run=str(identifier))
.order_by("-created_at")
.first()
)
if artifact is None:
return context_graph.canonical(
{
"found": False,
"reason": "No retained action or artifact of this assignment has that identifier.",
"artifacts": [
{"id": str(item.pk), "kind": item.kind, "title": item.title}
for item in research_evidence.artifacts(assignment).order_by("-created_at")[:20]
],
}
)
record = {"artifact": research.artifact_record(artifact)}
if artifact.size <= 2_000_000:
data = research.artifact_bytes(artifact, limit=artifact.size)
try:
record["text"] = data.decode()
except UnicodeDecodeError:
record["text"] = None
return context_graph.canonical(record)
class NotYetError(Exception):
"""A finish that cannot be accepted as things stand. Its request stays open."""
def require_empty_followup_queue(agent, assignment):
if not agent.parent_id and assignment.user_messages.filter(state="pending").exists():
raise NotYetError(
"A user follow-up is queued. Continue to the next turn and address it before finishing."
)
def returned(reason):
"""A finish sent back to its author. This is a result the agent acts on, not a failed
call: the request stays open and the agent finishes again."""
return {"accepted": False, "reason": reason}
def finish_answer(action, request, scope):
"""Settle a request whose reply is its deliverable."""
agent, assignment = action.agent, action.agent.assignment
if pending_work(assignment, agent):
return returned(
"Work this request started is still running. Read its result before answering."
)
record = None
if agent.actions.filter(
created_at__gte=scope["started_at"],
state="completed",
tool="workshop",
arguments__operation="prepare",
).exists():
task, publication = research_workshop.settled(assignment)
if request.outcome == "completed" and task is None:
return returned(
"The Workshop has published no verified dataset for this assignment. Finish "
"with outcome unmet or blocked and say why."
)
published = research_workshop.published(publication) if task else None
record = {"prepared": published} if published else None
# A queued follow-up continues in the same workspace.
if not assignment.user_messages.filter(
state="pending"
).exists() and not research_workspace.stop(agent):
raise InputValidationError(
"Workspace termination is still unconfirmed; inspect before finishing"
)
return research_requests.finish(action, request, record=record)
def supervise(action, request):
# The engine and its task import the tool dispatcher.
from overbae.services import experiment_engine
from overbae.tasks.research import advance_flow
assignment = action.agent.assignment
if not experiment_operator.is_operator(assignment):
raise InputValidationError("Supervision belongs to an experiment's operator")
if request.operation == "inspect":
if request.run is None:
from overbae.services import research_agent # The agent loop owns this dispatcher.
observed = research_agent.evidence(action.agent)
return {
"supervision": observed["supervision"],
"supervised_runs": observed["supervised_runs"],
"observation_identity": research_agent.evidence_identity(observed),
"epoch": action.agent.execution_epoch,
}
return experiment_operator.inspect(assignment, run=request.run, node=request.node)
if request.operation == "note":
return experiment_operator.note(action, request)
run = experiment_operator.runs(assignment).filter(pk=request.run).first()
if run is None:
raise InputValidationError("This run is not supervised by this operator")
experiment_operator.require_remediation(assignment, run=run)
experiment_engine.retry(run, request_key=f"operator:{action.pk}")
identifier = str(run.pk)
transaction.on_commit(lambda: advance_flow.delay(identifier), robust=True)
return experiment_operator.acted(action, "retry", {"run": identifier, "state": "running"})
def finish(action, request):
agent = action.agent
scope = research_requests.current(agent)
if scope and research_requests.flow_bound(agent.assignment) and not agent.parent_id:
if request.delivery == "answer":
return finish_answer(action, request, scope)
if request.delivery == "definition":
try:
return research_requests.finish(action, request)
except InputValidationError as held:
return returned(str(held.detail))
elif request.delivery == "answer":
raise InputValidationError("An answer is the deliverable of an experiment's chat only")
try:
return conclude(action, request)
except NotYetError as held:
return returned(*held.args)
def conclude(action, request):
agent, assignment = action.agent, action.agent.assignment
# An experiment's lead works alone and completes on the platform's records of its flow.
alone = not agent.parent_id and research_requests.flow_bound(assignment)
require_empty_followup_queue(agent, assignment)
fence = agent.lease
handoff = {}
if agent.parent_id:
try:
handoff = research_team.prepare_handoff(action, request)
except InputValidationError as unacceptable:
# A handoff that cannot be accepted as written goes back to its author.
raise NotYetError(unacceptable.detail) from unacceptable
artifacts = list(
research_evidence.artifacts(assignment)
.filter(pk__in=request.artifacts)
.select_related("action")
)
if len(artifacts) != len(set(request.artifacts)):
raise InputValidationError(
"Every deliverable must reference a retained assignment artifact"
)
if request.delivery == "definition" and not agent.parent_id and not artifacts:
artifacts = [research_experiments.definition(assignment)]
if pending_work(assignment, agent if agent.parent_id else None) or (
not agent.parent_id and experiment_training.pending([assignment.pk])
):
raise NotYetError("Asynchronous work is still active; inspect or stop it before finishing")
if (
agent.parent_id is None
and not alone
and assignment.agents.exclude(pk=agent.pk).exclude(state__in=research.TERMINAL).exists()
):
raise NotYetError("Helpers are still active; collect their results before finishing")
delivery_run = None
if alone and request.outcome == "completed":
try:
delivery_run = research_experiments.require_delivery(
assignment, artifacts, request.delivery
)
except InputValidationError as undelivered:
raise NotYetError(undelivered.detail) from undelivered
elif not agent.parent_id and request.outcome == "completed":
if (
not artifacts
and not experiment_training.campaigns([assignment.pk])
.filter(state="completed")
.exists()
):
raise NotYetError("Completion requires actual retained deliverables or a trained model")
if research_team.unsettled_handoffs(assignment):
raise NotYetError(
"Accept or explicitly reject submitted specialist handoffs before completing"
)
try:
research_team.require_verification(assignment, artifacts)
except InputValidationError as unverified:
raise NotYetError(unverified.detail) from unverified
if not agent.parent_id and request.outcome == "completed":
gaps = research_acceptance.serving_gaps(assignment)
if gaps:
raise NotYetError(" ".join(gaps) + " Then finish again.")
if not research_workspace.stop(agent, actor=agent):
raise InputValidationError(
"Workspace termination is still unconfirmed; inspect before finishing"
)
result = {
**request.model_dump(mode="json"),
**handoff,
"source_cells": sorted(research_notes.observed_sources(action)),
}
if delivery_run:
result["delivered_flow"] = str(delivery_run.pk)
if not agent.parent_id:
manifest = research_acceptance.retain_manifest(action)
result["verified_record"] = research.artifact_record(manifest)
with transaction.atomic():
assignment = ResearchAssignment.objects.select_for_update().get(pk=assignment.pk)
require_empty_followup_queue(agent, assignment)
agent = research_team.transition(
agent, fence=fence, state=request.outcome, result=result, completed_at=timezone.now()
)
if not agent.parent_id:
assignment.state = request.outcome
assignment.result = {
**assignment.result,
**agent.result,
"qualification": "Verified record bindings; scope and limitations remain explicit",
}
assignment.completed_at = timezone.now()
assignment.save(update_fields=["state", "result", "completed_at"])
transaction.on_commit(
lambda: refresh_project.delay(str(assignment.project_id)), robust=True
)
return agent.result
def review(agent, request):
assignment = agent.assignment
if request.operation == "facts":
return research_acceptance.facts(assignment)
if request.operation == "data":
artifact = research.accessible_artifact(assignment, request.artifact)
return research_acceptance.review_data(assignment, artifact)
if request.operation == "definition":
# Unnamed, the subject is the current flow definition.
artifact = (
research.accessible_artifact(assignment, request.artifact)
if request.artifact
else research_experiments.definition(assignment)
)
return research_experiments.require_definition(assignment, [artifact])
if request.operation == "report":
return research_acceptance.verify_report(
assignment, research.accessible_artifact(assignment, request.artifact)
)
inference = InferenceRequest.objects.filter(pk=request.inference).first()
if inference is None:
raise InputValidationError("Select an existing inference")
return research_acceptance.verify_inference(assignment, inference)
# What each review reads, for a call that named something else.
REVIEWS = {
"data": "A native export_data artifact, checked row for row against its source. Data the "
"Workshop published is verified by its replay; read it with inspect_source.",
"report": "A native execution receipt or data check report, checked against its "
"retained record.",
"definition": "The current flow definition; omit artifact to review it.",
"inference": "An inference request of a deployment in this experiment.",
}
def unreviewed(assignment, request, reason):
"""The answer to a review that could not be made of the subject it named."""
named = request.artifact or request.inference
receipt = (
ResearchAction.objects.filter(
pk=named, agent__assignment_id__in=research_evidence.owners(assignment)
).first()
if named
else None
)
return {
"reviewed": False,
"reason": str(reason),
"reviews": REVIEWS.get(request.operation),
**(
{
"identifier": f"The receipt of a {receipt.tool} call, not an artifact. Read a "
"receipt with inspect_action."
}
if receipt
else {}
),
"artifacts": [
{"id": str(artifact.pk), "kind": artifact.kind, "title": artifact.title}
for artifact in research_evidence.artifacts(assignment).order_by("-created_at")[:20]
],
}
def invoke(action, *, workspace=None):
action.refresh_from_db()
TOOLS[action.tool].request.model_validate(action.arguments)
agent = action.agent
agent.refresh_from_db()
research_team.require_turn(agent)
assignment = agent.assignment
if agent.state in research.TERMINAL or assignment.state != "running":
raise InputValidationError("This agent no longer has execution authority")
if action.state not in {"pending", "running"}:
raise InputValidationError("This action has already settled")
family = execution_mandates.operation_family(action.tool, action.arguments)
if (
experiment_operator.is_operator(assignment)
and action.tool not in {"supervise", "wait", "remember"}
and TOOLS[action.tool].execution_effect(action.arguments) != "read"
):
experiment_operator.require_remediation(assignment)
if family:
execution_mandates.require_action(action, family)
if not research_requests.permits(agent, action.tool, action.arguments):
if research_requests.workshop_owned(action.tool, action.arguments):
raise InputValidationError(
"Delegate data processing with workshop(operation=prepare), passing the pinned "
"source_cell, the user's request and downstream_context. Wait for its publication "
"and use the returned cells in the experiment. Do not author or run a pipeline here."
)
raise InputValidationError("This operation is outside the current request scope")
if not research_team.permits(agent, action.tool, action.arguments):
raise InputValidationError(
"This operation belongs to the research lead; return evidence or a proposal"
)
if not research_team.ready(agent):
raise InputValidationError(
"Accepted predecessor handoffs are required before dependent work"
)
if research_requests.owed_to_a_stage(action):
# Nothing started: the answer says where this work is stated.
return {
"executed": False,
"reason": "An experiment's work runs as stages of its flow. State this as a stage "
"with experiment(operation=define) or experiment(operation=stage), then start the "
"flow with experiment(operation=run).",
}
request = TOOLS[action.tool].parse(action.arguments)
if action.tool == "experiment_decision":
return research_science.record(action, request)
if action.tool in {"asset", "component", "prediction", "score"}:
from overbae.services import experiment_asset_tools # Asset executors use source admission.
return experiment_asset_tools.invoke(action, request)
if action.tool == "workshop":
return research_workshop.invoke(action, request)
if action.tool == "ask_user":
from overbae.services import research_questions # Questions share research tool ownership.
return research_questions.ask(action, request)
if action.tool == "request_access":
from overbae.services import research_questions # Questions share research tool ownership.
return research_questions.request_access(action, request)
if action.tool == "import_dataset":
return research_workspace.import_dataset(action, request)
if action.tool == "eval_set":
from overbae.services import research_questions # Questions share research tool ownership.
return research_questions.eval_set(action, request)
if action.tool == "experiment":
remediating = (
experiment_operator.is_operator(assignment)
and request.operation in experiment_operator.MUTATIONS
)
if remediating:
experiment_operator.require_remediation(assignment)
result = research_experiments.agent_operation(action, request)
return (
experiment_operator.acted(action, request.operation, result) if remediating else result
)
if action.tool == "supervise":
return supervise(action, request)
if action.tool == "review_handoff":
return research_team.review_handoff(action, request)
if action.tool == "inbox":
if request.operation == "acknowledge":
return research_team.acknowledge(agent, request.events)
return research_team.inbox(agent, after=request.after, limit=request.limit)
if action.tool == "review":
try:
return review(agent, request)
except InputValidationError as unavailable:
return unreviewed(assignment, request, unavailable.detail)
if action.tool == "explore_context":
# A contract asked for as a read of its name is still a request for that contract.
contract = research_catalogue.contract_request(request)
if contract is not None:
return research_catalogue.contracts(agent, contract)
return visible_context(assignment, request)
if action.tool == "history":
return research_continuity.history(agent, request)
if action.tool == "inspect_action":
text = retained_text(assignment, request.action)
return {
"text": text[request.offset : request.offset + request.limit],
"next_offset": request.offset + request.limit
if len(text) > request.offset + request.limit
else None,
}
if action.tool == "inspect_source":
try:
cell = source_cell(assignment, request.cell)
except InputValidationError:
dataset = Dataset.objects.filter(pk=request.cell, project=assignment.project).first()
if dataset is None:
raise
current = dataset.active_cell
if current is None:
raise InputValidationError(
"That ID identifies a dataset, not a cell; the dataset has no published cell."
) from None
execution_mandates.require_published_cell(current, project_id=assignment.project_id)
raise InputValidationError(
"That ID identifies a dataset, not a cell. Inspect its current published version "
f"with inspect_source(cell='{current.pk}'); retain that exact cell for the flow."
) from None
originals = cell.dataset.source_spec.get("sources", []) if cell.position == 0 else []
if request.original:
original = next((item for item in originals if item["id"] == request.original), None)
if original is None:
raise InputValidationError(
"Select a retained original from this approved source cell"
)
path = paths.source_path(cell.dataset_id, request.original)
with path.open("rb") as stream:
data = stream.read(research_workspace.MAX_INPUT + 1)
if hashlib.sha256(data).hexdigest() != request.original:
raise InputValidationError("The retained original no longer matches its identity")
return research_workspace.stage(
agent,
f"originals/{cell.pk}/{Path(original['filename']).name}",
data,
source_cell=cell.pk,
)
def records():
rows.verify(cell)
path = rows.frame_path(cell)
return (
store.iter_rows(path)
if request.export
else store.read_rows(
path,
list(range(request.offset, min(cell.rows, request.offset + request.limit))),
)
)
if request.export:
buffer = io.BytesIO()
for record in records():
buffer.write((context_graph.canonical(record) + "\n").encode())
if buffer.tell() > research_workspace.MAX_INPUT:
raise InputValidationError(
"Source export exceeds the workspace transfer limit; select a bounded retained source"
)
data = buffer.getvalue()
digest = hashlib.sha256(data).hexdigest()
return {
**research_workspace.stage(
agent, f"{cell.pk}/{digest}.jsonl", data, source_cell=cell.pk
),
"cell": str(cell.pk),
"fingerprint": cell.fingerprint,
}
page, page_size = [], 0
for record in records():
size = len(context_graph.canonical(record))
# Keep whole records; a large requested page must not evict the working contracts.
if page and page_size + size > 16000:
break
page.append(record)
page_size += size
next_offset = request.offset + len(page)
return {
**cell_identity(cell),
"access": "readable",
"schema": store.read_manifest(rows.frame_path(cell)),
# Measured over the stored rows: what a transform spec is chosen from.
**({"profile": column_profile.of(cell)} if request.offset == 0 else {}),
"partition": cell.dataset.source_spec.get("partition_plan"),
"role": cell.dataset.source_spec.get("role"),
"row_format": "Exact stored columns and values. JSONL export preserves these records; no consumer-specific fields are added.",
"originals": originals,
"rows": page,
"next_offset": next_offset if next_offset < cell.rows else None,
}
if action.tool == "workspace":
return research_workspace.execute(action, request, sandbox=workspace)
if action.tool == "delegate":
child = research.delegate(agent, request, writer=action)
return {"agent": str(child.pk), **research_team.record(child)}
if action.tool == "message_agent":
with transaction.atomic():
agent = research_team.current_turn(agent)
assignment = agent.assignment
previous = assignment.events.filter(
kind="agent_message", payload__action=str(action.pk)
).first()
if previous:
return {"event": previous.pk, **previous.payload}
recipient = research_team.addressed(agent, request.agent)
if recipient is None:
raise InputValidationError("Choose another agent in this assignment")
recipient = assignment.agents.select_for_update().get(pk=recipient.pk)
if not research_team.coordination(recipient)["message"]:
return {
"delivery": "not_delivered",
"recipient": research_team.record(recipient),
}
artifacts = list(
research_evidence.artifacts(assignment).filter(pk__in=request.artifacts)
)
if len(artifacts) != len(set(request.artifacts)):
raise InputValidationError(
"Messages may cite only retained artifacts from this assignment"
)
payload = {
"delivery": "queued",
"action": str(action.pk),
"sender": str(agent.pk),
"recipient": str(recipient.pk),
"message": request.message,
"source_cells": sorted(research_notes.observed_sources(action)),
"artifacts": [str(item.pk) for item in artifacts],
}
saved = research.event(assignment, "agent_message", payload, agent)
return {"event": saved.pk, **payload}
if action.tool == "manage_agent":
child = research_team.addressed(agent, request.agent)
cursor = child
while cursor and cursor.parent_id and cursor.parent_id != agent.pk:
cursor = cursor.parent
if child is None or cursor is None or cursor.parent_id != agent.pk:
raise InputValidationError("Only your descendant helpers can be managed")
notes_provenance = None
if request.operation == "resume":
with transaction.atomic():
research_team.current_turn(agent)
child = ResearchAgent.objects.select_for_update().get(pk=child.pk)
if blocker := research_team.resume_blocker(child):
raise InputValidationError(blocker)
research_team.discard_pending_tools(child)
notes_provenance = research_notes.write(
child, "\nOwner follow-up: " + request.reason, writer=action, append=True
)
if child.role == "evaluation":
child.result = {"previous_handoff": child.result.get("handoff")}
child.state = "ready"
child.lease = None
child.lease_expires_at = None
child.completed_at = None
child.save(
update_fields=[
"result",
"state",
"completed_at",
"lease",
"lease_expires_at",
]
)
else:
descendants = [child]
for descendant in descendants:
descendants.extend(descendant.children.all())
if research_team.handoff_status(descendant)["state"] not in {
"accepted",
"rejected",
}:
descendant = research_team.fence_stop(descendant, actor=agent)
research_workspace.stop(descendant, actor=agent)
child.refresh_from_db()
with transaction.atomic():
research_team.current_turn(agent)
research.event(
assignment,
"helper_" + request.operation,
{"helper": str(child.pk), "reason": request.reason},
agent,
)
return {
"agent": str(child.pk),
"state": child.state,
**({"notes_provenance": notes_provenance} if notes_provenance else {}),
}
if action.tool == "inspect_agent":
child = research_team.addressed(agent, request.agent)
if child is None:
raise InputValidationError("The helper does not belong to this assignment")
notes = research_notes.record(child, assignment=assignment)
return {
"agent": str(child.pk),
**research_team.record(child),
"notes": notes["text"],
"notes_provenance": {key: value for key, value in notes.items() if key != "text"},
"result": research_evidence.helper_result(assignment, child.result),
"actions": [
{
"id": str(retained.pk),
"tool": retained.tool,
"state": retained.state,
"result": research_evidence.action_result(assignment, retained),
}
for retained in child.actions.order_by("created_at")[
request.after : request.after + 20
]
],
}
if action.tool == "remember":
with transaction.atomic():
current = research_team.current_turn(agent)
provenance = research_notes.write(current, request.text, writer=action)
return {"saved": True, "notes_provenance": provenance}
if action.tool == "retain_artifact":
source_cells = research_workspace.staged_sources(agent) | research_notes.observed_sources(
action
)
data = research_workspace.read(agent, request.path)
source_cells |= research_workspace.staged_sources(agent)
artifact = research.retain(action, request, data, source_cells=source_cells)
return {
**research.artifact_record(artifact),
"source_cells": sorted(source_cells),
"authored_source_cells": sorted(source_cells),
}
if action.tool == "fetch_artifact":
return research_workspace.stage_artifact(agent, request.artifact)
if action.tool == "platform":
return platform(action, request)
if action.tool == "retain_pipeline":
if agent.parent_id:
raise InputValidationError("Only the research owner may publish data transformations")
if request.describe:
return {
**pipeline_packages.authoring_contract(),
"consumers": context.CONSUMERS,
"upload": 'retain_pipeline(path="pipeline.zip"); the path must be a ZIP file in your native workspace, not a directory.',
}
if research_evidence.can_read_final(assignment):
raise InputValidationError(
"Final-result observers cannot publish reusable transformations"
)
package = pipeline_packages.save(
assignment.project,
assignment.created_by,
io.BytesIO(research_workspace.read(agent, request.path)),
actor=agent,
author=action,
source_cells=research_workspace.staged_sources(agent),
)
return pipeline_packages.record(package)
if action.tool == "serving":
return research_serving.invoke(action, request)
if action.tool == "benchmark":
return research_benchmarks.invoke(action, request)
if action.tool == "training":
return training(action, request)
if action.tool == "wait":
from overbae.services.research_agent import (
evidence,
evidence_identity,
) # Tool execution is owned by this loop.
model = (
agent.actions.filter(tool="model", state="completed").order_by("-created_at").first()
)
observed = model.arguments.get("observation_identity") if model else None
if experiment_operator.is_operator(assignment):
current = evidence_identity(evidence(agent))
if (experiment_operator.seen(agent) or current) != current:
# Standing by here would sleep over an event the operator has not read.
return {
"state": "ready",
"running": False,
"note": "A supervised run changed after you last read it. Read "
"supervise(operation=inspect) with no run, act on it, then wait.",
}
wake = experiment_operator.standing(assignment, current)
research_team.transition(agent, fence=agent.lease, state="waiting", wake=wake)
return wake
if not progress_possible(agent):
# Yielding here would never be woken: return at once and say why.
return {
"state": "ready",
"running": False,
"note": "Nothing is running, so nothing will change while you wait. Take the "
"next action or finish.",
}
wake = {
"after": (timezone.now() + timedelta(seconds=request.seconds)).isoformat(),
"reason": request.reason,
# Anchor to what the model saw, so a completion during its call is not lost.
"evidence": observed or evidence_identity(evidence(agent)),
"observed_by": str(model.pk) if model else None,
}
research_team.transition(agent, fence=agent.lease, state="waiting", wake=wake)
return wake
if action.tool == "finish":
return finish(action, request)
raise InputValidationError("Unknown research tool")