The platform for continuously improving AI agents.
import hashlib
import json
from urllib.parse import quote, urlencode
from uuid import UUID
from django.core.serializers.json import DjangoJSONEncoder
from django.db import transaction
from django.db.models import Count, F, Max, Prefetch, Q, TextField
from django.db.models.functions import MD5, Cast, JSONObject, Left
from overbae.core.errors import InputValidationError
from overbae.models import (
Cell,
ExperimentNodeExecution,
ResearchAction,
ResearchAssignment,
ResearchEvent,
ResearchExperiment,
ResearchExperimentMessage,
TrainingTrial,
WorkshopChatEvent,
WorkshopTask,
)
from overbae.services import (
context_graph,
execution_mandates,
experiment_preflight,
experiment_stages,
experiment_training,
research,
research_experiments,
research_questions,
research_requests,
research_team,
research_workshop,
)
from overbae.services.research_contract import WORKSPACE_RUNS
# How a tool call the platform would not run is recorded: its arguments did not fit the
# tool, or the request named something that is not so.
REFUSALS = {"ValidationError", "InputValidationError"}
# Platform bookkeeping the agent did not call, and calls the chat shows in another form.
UNLISTED = {
"finish",
"ask_user",
"request_access",
"workspace_lease",
"campaign_allocation",
"benchmark_allocation",
"flow_allocation",
}
# A call's arguments are read no further than this to name what it acted on.
READ_LIMIT = 20000
def clipped(text, limit):
return text if len(text) <= limit else text[:limit].rstrip() + "…"
def call_target(arguments):
"""One line naming what a call acts on, from its own arguments."""
operations = arguments.get("operations")
if (
isinstance(operations, list)
and operations
and all(isinstance(item, dict) and item.get("cmd") for item in operations)
):
parts = [
" ".join([str(item["cmd"]), *(str(value) for value in item.get("args", []))])
for item in operations
]
else:
parts = []
for key, value in arguments.items():
if key == "operation":
continue
if isinstance(value, list) and 0 < len(value) <= 5:
if not all(isinstance(item, str | int | float) for item in value):
continue
value = ", ".join(str(item) for item in value)
if isinstance(value, bool) or not isinstance(value, str | int | float):
continue
value = str(value)
if value and len(value) <= 160 and "\n" not in value:
parts.append(f"{key} {value}")
return clipped(" · ".join(parts), 400)
def call_detail(stored):
"""What a call acted on, from the opening of its stored arguments."""
try:
arguments = json.loads(stored or "{}")
except ValueError:
# The read stopped inside a long argument.
return ""
if not isinstance(arguments, dict):
return ""
return call_target(
{
key: value
for key, value in arguments.items()
if key not in {"description", "code", "text"}
}
)
def message_record(message):
return {
"id": f"{message.assignment_id}:{message.pk}",
"role": "user",
"text": message.text,
"status": message.state,
"revision": message.revision,
"queue_position": message.position,
}
def lead_run(experiment):
"""The run the experiment's chat talks to: its newest that is not a flow run."""
return (
ResearchAssignment.objects.filter(
experiment_revision__experiment=experiment, execution__isnull=True
)
.order_by("-created_at")
.first()
)
def wake(run):
"""Advance the run's agents once the change that asks for it is committed."""
from overbae.tasks.research import advance # lazy: the tasks import the agents' services
for owner in run.agents.filter(state__in=["ready", "waiting"]):
transaction.on_commit(
lambda identifier=str(owner.pk): advance.delay(identifier), robust=True
)
def admit_canvas_sources(run, experiment):
roots = list(run.specification.get("context_roots", []))
attached = [
f"cell:{node['config']['cell']}"
for node in experiment.revisions.get(number=experiment.version).document["nodes"]
if node["kind"] == "data" and isinstance(node["config"].get("cell"), str)
]
added = list(dict.fromkeys(root for root in attached if root not in roots))
if not added:
return
cells = list(
Cell.objects.filter(
pk__in=[root.split(":", 1)[1] for root in added],
dataset__project=experiment.project,
state="ok",
).select_related("dataset")
)
if len(cells) != len(added):
raise InputValidationError("An attached dataset version is unavailable")
grant = execution_mandates.admission(roots=added)
mandate = execution_mandates.normalize(
{**run.execution_mandate, "sources": [*run.execution_mandate["sources"], *grant["sources"]]}
)
run.specification = {**run.specification, "context_roots": [*roots, *added]}
run.fingerprint = context_graph.fingerprint(run.specification)
run.execution_mandate = mandate
run.mandate_fingerprint = execution_mandates.identity(mandate)
run.save(
update_fields=["specification", "fingerprint", "execution_mandate", "mandate_fingerprint"]
)
@transaction.atomic
def send(experiment, user, *, text, request_key, question=None, approved=None, criteria=None):
experiment = ResearchExperiment.objects.select_for_update().get(pk=experiment.pk)
if experiment.deleted_at is not None:
raise InputValidationError("The experiment has been deleted")
identity = context_graph.fingerprint(
{"text": text, **({"question": str(question)} if question else {})}
| ({} if approved is None else {"approved": approved})
| ({} if criteria is None else {"criteria": criteria})
)
previous = experiment.messages.filter(request_key=request_key).first()
if previous:
if previous.fingerprint != identity:
raise InputValidationError("This message request key has different text")
return previous.assignment
run = lead_run(experiment)
if question and run is None:
raise InputValidationError("This question is no longer waiting for an answer")
initial = run is None
resumed = False
budget = {}
if initial:
run = research_experiments.start(
experiment,
user,
revision=experiment.version,
request_key=request_key,
budget=budget,
instructions=text,
)
research.event(run, "request_received", {"instructions": text, "request_key": request_key})
else:
run = ResearchAssignment.objects.select_for_update().get(pk=run.pk)
if question and run.state != "running":
raise InputValidationError("This question is no longer waiting for an answer")
if run.state == "stopping":
raise InputValidationError("Wait for the run to stop before sending another message")
admit_canvas_sources(run, experiment)
if run.state in research.TERMINAL:
resumed = True
run = research.resume(
run, request_key=request_key, instructions=text, renewal_budget=budget
)
answering = question or (
entry.payload["question"]
if (entry := research_questions.pending(run)) and run.state == "running"
else None
)
if answering:
research_questions.answer(
run,
question=answering,
text=text,
request_key=request_key,
approved=approved,
criteria=criteria,
)
elif approved is not None:
raise InputValidationError("This question is no longer waiting for an answer")
position = (run.user_messages.aggregate(last=Max("position"))["last"] or 0) + 1
ResearchExperimentMessage.objects.create(
experiment=experiment,
assignment=run,
created_by=user,
request_key=request_key,
fingerprint=identity,
text=text,
position=position,
state="delivered" if initial or resumed or answering else "pending",
)
return run
@transaction.atomic
def deliver(agent):
if agent.parent_id or not agent.assignment.experiment_revision_id:
return
run = ResearchAssignment.objects.select_for_update().get(pk=agent.assignment_id)
research_team.current_turn(agent)
if run.state != "running":
return
scope = research_requests.current(agent)
message = run.user_messages.filter(state="pending").order_by("position", "created_at").first()
if message is None:
return
research.event(
run,
"agent_message",
{
"sender": "user",
"recipient": str(agent.pk),
"message": message.text,
"artifacts": [],
"user_message": str(message.pk),
},
)
message.state = "delivered"
# A message that arrives while a request is open adds to it; one that follows its answer
# opens the next.
if scope and research_requests.settled(run, scope):
research.event(
run, "request_received", {"instructions": message.text, "message": str(message.pk)}
)
message.revision += 1
message.save(update_fields=["state", "revision"])
@transaction.atomic
def control(experiment, *, message, command, revision, request_key, text=None, position=None):
experiment = ResearchExperiment.objects.select_for_update().get(pk=experiment.pk)
# The experiment lists a message as "<run>:<message>"; either form selects it.
message = str(message).rpartition(":")[2]
try:
identifier = UUID(message)
except ValueError as exc:
raise InputValidationError("Select an experiment message") from exc
entry = experiment.messages.filter(pk=identifier).first()
if entry is None:
raise InputValidationError("This message is not part of the experiment")
run = ResearchAssignment.objects.select_for_update().get(pk=entry.assignment_id)
entry.refresh_from_db()
change = {
"message": message,
"command": command,
"revision": revision,
"text": text,
"position": position,
}
identity = context_graph.fingerprint(change)
prior = run.events.filter(kind="message_control", payload__request_key=request_key).first()
if prior:
if prior.payload["fingerprint"] != identity:
raise InputValidationError("This message control request has different arguments")
return
if entry.state != "pending" or entry.revision != revision or run.state != "running":
raise InputValidationError("This message has changed or has already been delivered")
if command == "edit":
if not text or not text.strip():
raise InputValidationError("Enter a message")
entry.text = text.strip()
elif command == "remove":
entry.state = "removed"
elif command == "move":
if position is None:
raise InputValidationError("Choose a queue position")
queue = list(
run.user_messages.filter(state="pending")
.exclude(pk=entry.pk)
.order_by("position", "created_at")
)
queue.insert(min(position, len(queue)), entry)
for index, item in enumerate(queue):
item.position = index
item.revision += 1
item.save(update_fields=["position", "revision"])
entry.revision += 1
entry.save(update_fields=["text", "state", "position", "revision"])
research.event(run, "message_control", {"request_key": request_key, "fingerprint": identity})
def digest(value):
return hashlib.sha256(
json.dumps(value, cls=DjangoJSONEncoder, sort_keys=True).encode()
).hexdigest()
def revision(experiment):
"""Two values a stream compares instead of rebuilding the chat: one that changes when a
run or a stage changes state, and one that changes when anything the chat shows from the
experiment's own runs may have. Cheap enough to read several times a second."""
runs = ResearchAssignment.objects.filter(experiment_revision__experiment=experiment)
record = digest(
[
list(runs.order_by("pk").values_list("pk", "state")),
list(
ExperimentNodeExecution.objects.filter(execution__assignment__in=runs)
.order_by("pk")
.values_list("pk", "state")
),
experiment.revisions.aggregate(latest=Max("number"))["latest"],
]
)
actions = ResearchAction.objects.filter(agent__assignment__in=runs)
chat = digest(
[
record,
actions.aggregate(n=Count("pk"), settled=Count("completed_at")),
# A reply still arriving grows in place; a run's newest output replaces its last.
list(
actions.filter(tool__in=["model", "workspace"], state="running")
.annotate(written=MD5(Cast("result", TextField())))
.values_list("pk", "written")
),
list(
experiment.messages.order_by("pk").values_list(
"pk", "state", "revision", "position"
)
),
runs.aggregate(n=Count("events"))["n"],
list(
WorkshopTask.objects.filter(
project=experiment.project,
request_key__in=[
f"research:{key}"
for key in actions.filter(tool="workshop").values_list("pk", flat=True)
],
)
.order_by("pk")
.annotate(latest_event=Max("chat_events__pk"))
.values_list("pk", "state", "updated_at", "latest_event")
),
]
)
return record, chat
def delivered_outputs(experiment, outputs, flow=None):
project = {"projectId": str(experiment.project_id)}
links = []
for name, value in outputs.items():
if not isinstance(value, dict):
continue
binding = flow.execution.document.get("outputs", {}).get(name) if flow else None
if value.get("dataset") and value.get("cell"):
dataset = quote(str(value["dataset"]), safe="")
url = f"/datasets/{dataset}?{urlencode({**project, 'cell': value['cell']})}"
elif value.get("deployment"):
url = f"/inference/{quote(str(value['deployment']), safe='')}?{urlencode(project)}"
elif value.get("job"):
url = f"/training?{urlencode({**project, 'job': value['job']})}"
elif binding:
query = urlencode(
{**project, "run": str(flow.pk), "focus": f"result:{binding['node']}"}
)
url = f"/experiments/{experiment.pk}?{query}"
else:
continue
label = name.replace("_", " ").replace("[", r"\[").replace("]", r"\]")
links.append(f"- [{label}]({url})")
if not links and flow:
query = urlencode({**project, "run": str(flow.pk)})
links.append(f"- [Flow run](/experiments/{experiment.pk}?{query})")
return "\n\n**Outputs**\n\n" + "\n".join(links) if links else ""
def conversation(experiment):
rows = []
for message in experiment.messages.all():
rows.append((message.created_at, 0, message_record(message)))
runs = list(
ResearchAssignment.objects.filter(experiment_revision__experiment=experiment)
.select_related("execution")
.order_by("created_at")
)
flows = {str(run.pk): run for run in runs if hasattr(run, "execution")}
lead = next((run for run in reversed(runs) if str(run.pk) not in flows), None)
parents = {
f"flow-research:{node}": str(run)
for node, run in ExperimentNodeExecution.objects.filter(
execution__assignment__in=runs, action__tool="adaptive_research"
).values_list("pk", "execution_id")
}
children = list(
ResearchAssignment.objects.filter(project=experiment.project, request_key__in=parents)
)
chat_runs = {str(child.pk): parents[child.request_key] for child in children}
runs.extend(children)
delivered = list(
ResearchAction.objects.filter(
agent__assignment__in=runs,
agent__parent__isnull=True,
tool="finish",
state="completed",
completed_at__isnull=False,
)
.filter(Q(result__accepted__isnull=True) | ~Q(result__accepted=False))
.values("agent_id", "completed_at", "result__summary")
)
user_boundary = {}
for event in ResearchEvent.objects.filter(
assignment__in=runs,
kind="sdk_event",
agent__parent__isnull=True,
payload__kind__in=["action", "message"],
).order_by("created_at", "sdk_sequence"):
payload = event.payload
if payload["kind"] == "message" and payload.get("role") == "user":
user_boundary[event.agent_id] = event.created_at
if (
payload["kind"] == "message"
and payload.get("role") == "assistant"
and any(
answer["agent_id"] == event.agent_id
and answer["result__summary"] == payload.get("text")
and answer["completed_at"] <= event.created_at
and (
event.agent_id not in user_boundary
or answer["completed_at"] > user_boundary[event.agent_id]
)
for answer in delivered
)
):
continue
if not payload.get("text") or (
payload["kind"] == "message" and payload.get("role") != "assistant"
):
continue
rows.append(
(
event.created_at,
1,
{
"id": f"{event.assignment_id}:sdk:{event.sdk_event_id}",
"role": "thinking" if payload["kind"] == "action" else "assistant",
"text": payload["text"],
"status": "completed",
},
)
)
training_jobs = {
str(trial.campaign_id): trial.job
for trial in TrainingTrial.objects.filter(campaign__in=experiment_training.campaigns(runs))
.select_related("job")
.order_by("created_at")
}
# A delegation returns at once; its line follows the Workshop task it started.
workshop_tasks = {
task.request_key: task
for task in WorkshopTask.objects.filter(
project=experiment.project,
request_key__in=[
f"research:{key}"
for key in ResearchAction.objects.filter(
agent__assignment__in=runs, tool="workshop", arguments__operation="prepare"
).values_list("pk", flat=True)
],
)
.select_related("dataset")
.prefetch_related(
Prefetch(
"chat_events",
queryset=WorkshopChatEvent.objects.filter(message__role="activity").order_by("pk"),
to_attr="handoff_events",
)
)
}
if not experiment.messages.exists():
rows.append(
(
experiment.created_at,
0,
{
"id": f"{experiment.pk}:request",
"role": "user",
"text": experiment.objective,
"status": "delivered",
},
)
)
for run in runs:
reserved = list(run.events.filter(kind="input_reserved"))
for entry in reserved:
text = f"{entry.payload['dataset']}: project data is available to the agent, including final splits."
rows.append(
(
entry.created_at,
1,
{
"id": f"{run.pk}:{entry.pk}:reserved",
"role": "assistant",
"text": text,
"status": "completed",
},
)
)
actions = (
ResearchAction.objects.filter(agent__assignment__in=runs)
.filter(experimentnodeexecution__isnull=True)
.defer("arguments", "result")
.annotate(
chat_assignment=F("agent__assignment_id"),
chat_parent=F("agent__parent_id"),
chat_text=F("result__text"),
chat_thinking=F("result__thinking"),
chat_executed=F("result__executed"),
chat_accepted=F("result__accepted"),
chat_error=F("result__error"),
chat_reason=F("result__reason"),
chat_type=F("result__type"),
chat_delivery=F("result__delivery"),
chat_outcome=F("result__outcome"),
chat_flow=F("result__delivered_flow"),
chat_prepared=F("result__prepared"),
chat_summary=F("result__summary"),
chat_input=Left(Cast("arguments", TextField()), READ_LIMIT),
chat_arguments=JSONObject(
description=F("arguments__description"),
operation=F("arguments__operation"),
name=F("arguments__name"),
describe=F("arguments__describe"),
code=F("arguments__code"),
command=F("arguments__command"),
),
)
.order_by("created_at")
)
# A terminal job and the later reads of it are one terminal: the newest read is its state.
jobs = {
str(pk)
for pk in ResearchAction.objects.filter(
agent__assignment__in=runs, tool="workspace", arguments__operation="terminal"
).values_list("pk", flat=True)
}
executions, reads = {}, set()
for pk, execution, *read in (
ResearchAction.objects.filter(
agent__assignment__in=runs, tool="workspace", result__has_key="tail"
)
.order_by("created_at")
.values_list(
"pk",
"arguments__execution",
"result__state",
"result__tail",
"result__tail_truncated",
"result__exit_code",
"result__started_at",
"result__finished_at",
)
):
if (execution or str(pk)) in jobs:
executions[execution or str(pk)] = read
if execution:
reads.add(pk)
settled_runs = {run.pk for run in runs if run.state in research.TERMINAL}
# Stops and resumes of each run in order: a step that ended after a stop was requested,
# with no resume since, was ended by that stop.
turns = {}
for run_id, kind, at in (
ResearchEvent.objects.filter(assignment__in=runs, kind__in=["stop_requested", "resumed"])
.order_by("created_at")
.values_list("assignment_id", "kind", "created_at")
):
turns.setdefault(run_id, []).append((at, kind))
def stopped(action):
ended = action.completed_at or action.created_at
before = [kind for at, kind in turns.get(action.chat_assignment, ()) if at <= ended]
return bool(before) and before[-1] == "stop_requested"
# The newest accepted completion of each run, which that run's outcome line restates.
concluded = {}
last_answer = {}
deliveries = {}
for action in actions:
prefix = f"{chat_runs.get(str(action.chat_assignment), action.chat_assignment)}:{action.pk}"
if action.tool == "model":
text = action.chat_text
if action.chat_parent is None and action.chat_accepted is not False:
# A request still with the model shows what it has written so far.
arriving = action.state == "running"
if action.chat_thinking:
rows.append(
(
action.created_at,
1,
{
"id": f"{prefix}:thinking",
"role": "thinking",
"text": action.chat_thinking,
"status": "streaming" if arriving and not text else "completed",
},
)
)
if text:
rows.append(
(
action.created_at,
1,
{
"id": prefix,
"role": "assistant",
"text": text,
"status": "streaming" if arriving else "completed",
},
)
)
continue
if (
action.tool == "finish"
and action.state == "completed"
and action.chat_parent is None
and action.chat_accepted is not False
and action.chat_summary
):
# Each request's answer stays in the chat. A run holds only its latest result, so
# a follow-up would otherwise replace the answer before it.
finished_at = action.completed_at or action.created_at
if action.chat_outcome == "completed" and action.chat_delivery == "outputs":
flow = flows.get(action.chat_flow)
if not flow:
previous = last_answer.get(action.chat_assignment)
candidates = [
run
for run in flows.values()
if run.specification.get("task", {}).get("controller_assignment")
== str(action.chat_assignment)
and run.state == "completed"
and run.completed_at
and run.completed_at <= finished_at
and (previous is None or previous < run.created_at)
]
if len(candidates) == 1:
flow = candidates[0]
if flow:
deliveries[prefix] = delivered_outputs(
experiment, flow.result.get("outputs", {}), flow
)
if action.chat_outcome == "completed" and action.chat_prepared:
published = action.chat_prepared
prepared = published.get("prepared") or {}
outputs = {
output["role"]: output
for output in published.get("outputs", [])
if output.get("access") == "readable"
}
if prepared.get("access") == "readable":
outputs[prepared["title"]] = {**prepared, "dataset": prepared["dataset"]["id"]}
deliveries[prefix] = delivered_outputs(experiment, outputs)
last_answer[action.chat_assignment] = finished_at
rows.append(
(
finished_at,
1,
{
"id": prefix,
"role": "assistant",
"text": action.chat_summary,
"status": "completed",
},
)
)
concluded[action.chat_assignment] = rows[-1]
continue
if (
action.tool == "finish"
and action.state == "completed"
and action.chat_accepted is False
):
# A finish sent back leaves its request open; the line says what held it.
rows.append(
(
action.created_at,
2,
{
"id": prefix,
"role": "activity",
"text": "Finish held",
"status": "refused",
"tool": "finish",
"code": "",
"error": action.chat_reason,
},
)
)
continue
args = action.chat_arguments
if action.pk in reads:
continue
if action.state not in {"failed", "unknown", "denied"} and (
action.chat_executed is False
or action.tool in UNLISTED
# A draft is shown as its review.
or (action.tool == "eval_set" and args.get("operation") == "draft")
):
continue
tool = (
args["operation"]
if action.tool == "workspace" and args.get("operation") in WORKSPACE_RUNS
else action.tool
)
title = (
args.get("description")
or (tool == "terminal" and (args.get("command") or "").strip()[:2000])
or (
f"{args['operation']} {action.tool}"
if args.get("operation") and tool not in WORKSPACE_RUNS
else None
)
or args.get("name")
or ("run python" if tool == "python" else None)
# A connector's tool is named <connection>__<tool>.
or " · ".join(part.replace("_", " ") for part in action.tool.split("__"))
)
if args.get("describe"):
title = f"{title} contract"
unsettled = action.state in {"failed", "unknown", "denied"}
state = (
"cancelled"
if unsettled and stopped(action)
# The platform read the call and refused it before anything ran; the agent is
# sent the reason. Nothing of the experiment failed.
else "refused"
if (action.state == "failed" and action.chat_type in REFUSALS)
or (action.state == "denied" and action.chat_reason == "unread_user_message")
else {"pending": "preparing", "unknown": "failed", "denied": "failed"}.get(
action.state, action.state
)
)
task = workshop_tasks.get(f"research:{action.pk}")
if task is not None and action.state in {"running", "completed"}:
# The delegation is open while the Workshop works; its line says what it is doing.
working = task.state not in research_workshop.SETTLED and task.result.get("activity")
title = f"Data Workshop · {task.result['activity']}" if working else "Data Workshop"
detail = call_detail(action.chat_input)
terminal = None
execution = executions.get(str(action.pk))
if tool == "terminal" and execution:
ran, output, truncated, exit_code, started, finished = execution
if ran in {"accepted", "running"}:
# Nothing reads a run after its assignment ends.
state = "cancelled" if action.chat_assignment in settled_runs else "running"
elif state == "completed" and exit_code != 0:
state = "failed"
terminal = {
"output": output,
"truncated": bool(truncated),
"exit_code": exit_code,
"started_at": started and int(started * 1000),
"duration_ms": int((finished - started) * 1000) if started and finished else None,
}
elif tool == "terminal" and state in {"preparing", "running"}:
terminal = {"output": "", "truncated": False}
rows.append(
(
action.created_at,
2,
{
"id": prefix,
"role": "activity",
"text": str(title) if tool == "terminal" else str(title).replace("_", " "),
"status": state,
"tool": tool,
"code": (args.get("code") or "") if tool == "python" else "",
"error": action.chat_error if state in {"failed", "refused"} else None,
"detail": detail,
**({"terminal": terminal} if terminal else {}),
**(
{
"dataset_activity": {
"task": str(task.pk),
"dataset": str(task.dataset_id),
"name": task.dataset.name,
"state": task.state,
"actions": list(
{
event.message["id"]: {
key: event.message[key]
for key in ("id", "text", "status")
}
for event in task.handoff_events
if event.message.get("tool") != "finish"
}.values()
),
}
}
if task is not None
else {}
),
},
)
)
for run in runs:
pending_question = research_questions.pending(run)
answered = {
event.payload["question"]: event.payload
for event in run.events.filter(kind="question_answered")
}
for entry in run.events.filter(kind="user_question"):
question = entry.payload["question"]
rows.append(
(
entry.created_at,
2,
{
"id": f"{run.pk}:{question}:question",
"role": "assistant",
"text": "Access request"
if "internet_access" in entry.payload
else "Eval set review"
if "eval_set_draft" in entry.payload
else "Questions",
"questions": entry.payload["questions"],
"question": question,
**(
{
"access": entry.payload["internet_access"],
"approved": answered.get(question, {}).get("approved"),
}
if "internet_access" in entry.payload
else {}
),
**(
{
"eval_set_draft": {
**entry.payload["eval_set_draft"],
# Once decided, the criteria are the ones that were saved.
**answered.get(question, {}).get("saved", {}),
},
"approved": answered.get(question, {}).get("approved"),
}
if "eval_set_draft" in entry.payload
else {}
),
"status": "question_answered"
if question in answered
else "question_cancelled"
if run.state in research.TERMINAL
or pending_question is None
or pending_question.pk != entry.pk
else "question_pending",
},
)
)
if hasattr(run, "execution"):
for node in run.execution.nodes.filter(scope__parent__isnull=True).select_related(
"scope", "action"
):
if node.state == "pending":
continue
definition = next(
item for item in node.scope.document["nodes"] if item["id"] == node.node
)
if definition["kind"] in {"data", "model", "join"} and not node.error:
continue
state = {"waiting": "running", "skipped": "completed"}.get(node.state, node.state)
title = definition["title"]
if node.state == "waiting" and definition["kind"] == "train":
job = (
training_jobs.get(str(node.action.result.get("id")))
if node.action_id
else None
)
if job is None or job.status in {
"queued",
"preparing",
"preprocessing",
"awaiting_launch",
"submission_unknown",
}:
state = "preparing"
title = f"Preparing training · {title}"
rows.append(
(
node.started_at or run.created_at,
2,
{
"id": f"{run.pk}:{node.pk}",
"role": "activity",
"text": title,
"status": state,
"tool": "python"
if node.action_id and node.action.tool == "workspace"
else node.action.tool
if node.action_id
else definition["kind"],
"error": node.error or None,
"code": node.action.arguments.get("code", "")
if node.action_id and node.action.tool == "workspace"
else "",
},
)
)
if run.state in research.TERMINAL:
result = run.result
text = (
result.get("summary")
or result.get("error")
or {
"model_call_limit": "The run reached its model-call limit.",
"admission_denied": "The run no longer has authority or time to start another action.",
}.get(result.get("reason"))
or (result.get("reason") or "").replace("_", " ")
or {"cancelled": "Stopped."}.get(run.state)
or run.state.replace("_", " ")
)
restated = concluded.get(run.pk)
outcome_id = (
f"{chat_runs[str(run.pk)]}:{run.pk}:outcome"
if str(run.pk) in chat_runs
else f"{run.pk}:outcome"
)
standalone = str(run.pk) not in chat_runs and not run.specification.get("task", {}).get(
"controller_assignment"
)
if standalone and run.state == "completed" and str(run.pk) in flows:
deliveries[outcome_id] = delivered_outputs(
experiment, run.result.get("outputs", {}), run
)
if restated is not None and restated[2]["text"].strip() == str(text).strip():
# The outcome line below is this completion: it is shown once, as the outcome.
rows.remove(restated)
if output := deliveries.pop(restated[2]["id"], None):
deliveries[outcome_id] = output
previous = next(
(
row[2]
for row in reversed(rows)
if row[2]["role"] == "assistant" and row[2]["id"].startswith(f"{run.pk}:")
),
None,
)
if (
run.state not in {"cancelled", "blocked", "exhausted"}
and previous
and previous["text"].strip() == str(text).strip()
):
if output := deliveries.pop(outcome_id, None):
deliveries[previous["id"]] = output
continue
rows.append(
(
run.completed_at or run.created_at,
3,
{
"id": outcome_id,
"role": "assistant",
"text": str(text),
"status": "cancelled"
if run.state == "cancelled"
else "interrupted"
if run.state in {"blocked", "exhausted"}
else "completed",
},
)
)
for _, _, row in rows:
if output := deliveries.get(row["id"]):
row["text"] += output
if (
lead
and lead.state == "completed"
and lead.completed_at
and not any(run.execution.revision.number == experiment.version for run in flows.values())
):
draft = experiment.revisions.filter(
number=experiment.version, agent__assignment_id=lead.pk
).first()
if (
draft
and any(
node["kind"] not in experiment_stages.SOURCES for node in draft.document["nodes"]
)
and experiment_preflight.readiness(experiment.project, draft.document)["ready"]
):
rows.append(
(
lead.completed_at,
4,
{
"id": f"{lead.pk}:{draft.pk}:run-invitation",
"role": "assistant",
"status": "completed",
"text": f"Revision {draft.number} is ready. {research_requests.RUN_INVITATION}",
},
)
)
return [row for _, _, row in sorted(rows, key=lambda item: (item[0], item[1]))]