The platform for continuously improving AI agents.
import json
from typing import Literal
from uuid import UUID
from pydantic import Field, model_validator
from agent_runtime.contracts import Contract
from agent_runtime.tool_contract import Operation, ToolDefinition
from overbae.core.errors import InputValidationError
from overbae.services.evaluation_contract import (
MAX_EVALUATION_PARTICIPANTS,
InferenceSettings,
PromptParticipant,
require_selectable,
)
from overbae.services.execution_mandates import ExecutionMandate
from overbae.services.experiment_asset_contract import (
AssetRequest,
CandidateDefinition,
ComponentDefinition,
ComponentRequest,
PredictionRequest,
ScoreRequest,
SuiteDefinition,
)
from overbae.services.experiment_contract import StageKind
class ResearchBudget(Contract):
max_seconds: int = Field(default=14400, ge=60, le=2592000)
max_agents: int = Field(default=6, ge=2, le=16)
max_concurrent_agents: int = Field(default=3, ge=1, le=8)
max_depth: int = Field(default=1, ge=1, le=1)
max_model_calls: int = Field(default=120, ge=1, le=1000)
workspace_seconds: int = Field(default=3600, ge=60, le=14400)
class ResearchRequest(Contract):
execution_mandate: ExecutionMandate | None = None
request_key: str = Field(min_length=1, max_length=100)
objective: str = Field(min_length=1, max_length=16000)
capability: UUID | None = None
task: dict = Field(default_factory=dict)
acceptance: dict = Field(default_factory=dict)
context_roots: list[str] = Field(default_factory=list, max_length=30)
sealed_cells: list[UUID] = Field(default_factory=list, max_length=30)
constraints: dict = Field(default_factory=dict)
budget: ResearchBudget = Field(default_factory=ResearchBudget)
@model_validator(mode="after")
def task_semantics(self):
if self.capability is None and not self.task:
raise ValueError("Select a capability or supply a task specification")
examples = self.acceptance.get("serving_examples", [])
parsed = [ServingExample.model_validate(example) for example in examples]
if len(parsed) > 20 or len({example.id for example in parsed}) != len(parsed):
raise ValueError("Supply at most twenty uniquely named serving examples")
return self
class ServingExample(Contract):
id: str = Field(min_length=1, max_length=100)
cell: UUID
cell_fingerprint: str = Field(pattern="^[a-f0-9]{64}$")
input_sha256: str = Field(pattern="^[a-f0-9]{64}$")
row: int = Field(ge=0)
input_path: list[str] = Field(default_factory=list, max_length=10)
requirements: list[str] = Field(min_length=1, max_length=20)
class Explore(Contract):
operation: Literal["catalog", "contracts", "search", "traverse", "read", "partitions"]
kind: str | None = None
reference: str | None = Field(default=None, max_length=400)
query: str = Field(
default="",
max_length=200,
description="For search: a case-insensitive substring of a currently visible label, or an exact object ID. Exact ID lookup takes precedence.",
)
direction: Literal["incoming", "outgoing", "both"] = "both"
order: Literal["identity", "newest"] = Field(
default="identity",
description="For search: newest requires a kind with a recorded created_at field; index refresh time is never creation time.",
)
relationship: str | None = Field(default=None, max_length=64)
cursor: str | None = Field(
default=None,
max_length=4000,
description="The next_cursor of a search or traverse result. A read or contracts result continues with its returned continuation instead.",
)
offset: int = Field(default=0, ge=0)
limit: int = Field(
default=20,
ge=1,
le=50,
description="The maximum matching records returned per page.",
)
length: int = Field(default=4000, ge=100, le=6000)
fingerprint: str | None = Field(default=None, pattern="^[a-f0-9]{64}$")
path: str = Field(
default="",
max_length=500,
description="Optional JSON Pointer selecting one field or schema within a read/contracts result.",
)
@model_validator(mode="before")
@classmethod
def continued(cls, data):
"""A continuation handed back whole in ``cursor`` is the paging it names."""
if not isinstance(data, dict) or data.get("operation") not in {"read", "contracts"}:
return data
cursor, data = data.get("cursor"), {**data, "cursor": None}
try:
paging = json.loads(cursor) if isinstance(cursor, str) else None
except ValueError:
paging = None
if isinstance(paging, dict):
for key in ("offset", "fingerprint", "path", "kind", "reference"):
if key in paging and data.get(key) in (None, "", 0):
data[key] = paging[key]
return data
@model_validator(mode="after")
def exact_reads(self):
if self.operation == "traverse" and not self.reference:
raise ValueError("Supply an exact graph reference")
return self
class Source(Contract):
cell: UUID = Field(description="Exact published cell UUID, not a dataset UUID.")
offset: int = Field(default=0, ge=0)
limit: int = Field(
default=20,
ge=1,
le=100,
description="Maximum records. Large records shorten the page; follow next_offset without guessing the next position.",
)
export: bool = Field(
default=False,
description="Export this exact cell into the workspace; leave original null for cell rows.",
)
original: str | None = Field(
default=None,
pattern="^[a-f0-9]{64}$",
description=(
"Optional original-file ID from a prior inspect_source response's originals list. "
"This is not the cell fingerprint. Leave null to inspect or export the cell."
),
)
# Workspace operations that start an execution read later with status.
WORKSPACE_RUNS = ("python", "terminal")
class Workspace(Contract):
operation: Literal["python", "terminal", "read", "write", "status", "interrupt", "reset"]
code: str = Field(default="", max_length=64000)
command: str = Field(
default="",
max_length=8000,
description="A bash command line for terminal, run in the working directory.",
)
path: str = Field(
default="",
max_length=512,
description="Relative to the working directory /workspace/work, where python runs: "
"report.md, not /workspace/report.md. Task data is read-only under data/.",
)
text: str = Field(default="", max_length=200000)
execution: UUID | None = None
timeout: int = Field(
default=120,
ge=1,
le=14400,
description="Seconds before the run is stopped: at most 900 for python, 14400 for terminal.",
)
offset: int = Field(default=0, ge=0)
limit: int = Field(default=12000, ge=1, le=32000)
@model_validator(mode="after")
def bounded(self):
if self.operation != "terminal" and self.timeout > 900:
raise ValueError("Only a terminal job may run longer than 900 seconds")
return self
class EvidenceReference(Contract):
kind: Literal["action", "artifact"]
id: UUID
class Finding(Contract):
kind: Literal["observation", "hypothesis", "decision", "question"]
statement: str = Field(min_length=1, max_length=4000)
evidence: list[EvidenceReference] = Field(default_factory=list, max_length=20)
limitations: list[str] = Field(default_factory=list, max_length=10)
@model_validator(mode="after")
def grounded(self):
if self.kind in {"observation", "decision"} and not self.evidence:
raise ValueError("Observations and decisions require retained evidence")
return self
class Deliverable(Contract):
name: str = Field(min_length=1, max_length=100)
kind: Literal[
"code", "report", "benchmark", "model", "training_plan", "evaluation", "data", "finding"
]
acceptance: str = Field(min_length=1, max_length=2000)
class DeliverableResult(Contract):
name: str = Field(min_length=1, max_length=100)
artifacts: list[UUID] = Field(
default_factory=list,
max_length=20,
description="Your own retained deliverables only, also listed in finish.artifacts. Leave empty for a finding-only deliverable; reviewed candidates belong in reviewed_artifacts.",
)
findings: list[Finding] = Field(
default_factory=list,
max_length=20,
description="Structured observations with exact action/artifact evidence. Required for finding deliverables and independent verification; top-level prose evidence does not replace these.",
)
class Delegate(Contract):
request_key: str = Field(min_length=1, max_length=100)
role: Literal["data", "training", "evaluation", "runtime", "research"]
responsibility: str = Field(min_length=1, max_length=100, pattern="^[a-z0-9][a-z0-9_-]*$")
task: str = Field(min_length=1, max_length=12000)
artifacts: list[UUID] = Field(default_factory=list, max_length=10)
depends_on: list[UUID] = Field(default_factory=list, max_length=10)
deliverables: list[Deliverable] = Field(min_length=1, max_length=10)
@model_validator(mode="after")
def unique_deliverables(self):
if len({item.name for item in self.deliverables}) != len(self.deliverables):
raise ValueError("Deliverable names must be unique")
return self
TEAMMATE = "Omit to address your only teammate: the lead for a specialist, the single specialist for the lead."
class HandoffReview(Contract):
agent: UUID | None = Field(
default=None, description="Omit when exactly one handoff awaits review."
)
handoff: UUID | None = Field(
default=None, description="Omit when exactly one handoff awaits review."
)
decision: Literal["accepted", "needs_revision", "rejected"]
rationale: str = Field(min_length=1, max_length=4000)
evidence: list[EvidenceReference] = Field(
default_factory=list,
max_length=20,
description="Retained actions or artifacts you checked. Omit to cite the handoff itself.",
)
class Inbox(Contract):
operation: Literal["read", "acknowledge"]
after: int = Field(default=0, ge=0)
limit: int = Field(default=20, ge=1, le=50)
events: list[int] = Field(default_factory=list, max_length=50)
class InspectAgent(Contract):
agent: UUID | None = Field(default=None, description=TEAMMATE)
after: int = Field(default=0, ge=0)
class MessageAgent(Contract):
agent: UUID | None = Field(default=None, description=TEAMMATE)
message: str = Field(min_length=1, max_length=4000)
artifacts: list[UUID] = Field(default_factory=list, max_length=10)
class ManageAgent(Contract):
agent: UUID | None = Field(default=None, description=TEAMMATE)
operation: Literal["stop", "resume"]
reason: str = Field(min_length=1, max_length=2000)
class Note(Contract):
text: str = Field(min_length=1, max_length=16000)
class Artifact(Contract):
path: str = Field(min_length=1, max_length=512)
title: str = Field(min_length=1, max_length=255)
kind: Literal["code", "report", "benchmark", "model", "training_plan", "evaluation", "data"]
metadata: dict = Field(default_factory=dict)
class FetchArtifact(Contract):
artifact: UUID
class Platform(Contract):
name: str = Field(min_length=1, max_length=80)
arguments: dict = Field(default_factory=dict)
describe: bool = False
class Workshop(Contract):
operation: Literal["prepare", "inspect"]
source_cell: UUID | None = None
objective: str = Field(default="", max_length=8000)
downstream_context: str = Field(default="", max_length=4000)
task: UUID | None = Field(
default=None, description="For inspect; omit to read your most recent Workshop task."
)
class Package(Contract):
path: str = Field(default="", max_length=512)
describe: bool = False
class InspectAction(Contract):
action: UUID = Field(description="An action receipt or artifact identifier.")
offset: int = Field(default=0, ge=0)
limit: int = Field(default=12000, ge=1, le=32000)
class History(Contract):
query: str = Field(default="", max_length=300)
tool: str = Field(default="", max_length=80)
state: Literal["", "pending", "running", "completed", "failed", "unknown", "denied"] = ""
offset: int = Field(default=0, ge=0)
limit: int = Field(default=10, ge=1, le=20)
class TrainingRequest(Contract):
run: dict = Field(
description="The start_finetune arguments every run shares: base_model, the train "
"cell, validation_cell, hyperparameters, monitoring and execution_limits. The "
"platform sets request_key."
)
trials: int = Field(
default=1,
ge=1,
le=5,
description="The most runs. After each run the training agent plans the next "
"learning rate and epochs, or stops; the campaign keeps the lowest development loss.",
)
class Campaign(Contract):
operation: Literal["create", "inspect", "stop"]
campaign: UUID | None = None
arguments: dict = Field(default_factory=dict)
describe: bool = False
class Benchmark(Contract):
operation: Literal["catalog", "run", "inspect", "stop"]
offset: int = Field(default=0, ge=0, description="Catalogue page offset.")
search: str = Field(
default="",
max_length=100,
description="For catalog: text matched against OpenRouter model ids and names, e.g. openai.",
)
evaluation: UUID | None = None
detail: bool = Field(
default=False,
description="Inspect full retained results and rate cards; default returns per-model metrics, coverage, hashes and cost estimates.",
)
phase: Literal["development", "final"] = "development"
cell: UUID | None = None
name: str = Field(default="Model comparison", max_length=255)
eval_set: UUID | None = Field(
default=None, description="Saved project eval set for every model."
)
suite: UUID | None = Field(
default=None, description="Immutable benchmark suite asset bound by the flow."
)
participants: list[PromptParticipant] = Field(
default_factory=list, max_length=MAX_EVALUATION_PARTICIPANTS
)
baseline: str = Field(
default="",
max_length=48,
description="The key of one supplied participant. Required when participants are explicit.",
)
max_seconds: int = Field(default=1800, ge=180, le=14400)
inference: InferenceSettings = Field(default_factory=InferenceSettings)
@model_validator(mode="after")
def baseline_participant(self):
if self.eval_set and self.suite:
raise ValueError("Choose one eval set or connect one benchmark suite")
if (
self.operation == "run"
and self.participants
and self.baseline not in {participant.key for participant in self.participants}
):
raise ValueError("Choose one of the participants as the baseline")
try:
require_selectable([participant.model_dump() for participant in self.participants])
except InputValidationError as exc:
raise ValueError(exc.detail) from None
return self
class Serving(Contract):
execution_seconds: int = Field(
default=600,
ge=30,
le=600,
description="Set either time limit explicitly for bounded Research serving. "
"This limits each deployment request's execution. Omit both for persistent publication.",
)
ttl_seconds: int = Field(
default=3600,
ge=180,
le=3600,
description="Explicitly requests bounded Research serving: seconds after ready, "
"bounded by the flow deadline. Starting is not counted. Omit both time limits "
"for persistent publication. Bounded serving enforces one container and zero provider "
"retries; these are runtime guarantees, not configurable fields.",
)
max_requests: int = Field(
default=1,
ge=1,
le=100,
description="Initial serving request allocation; additional requests retain their own receipts.",
)
operation: Literal["deploy", "inspect", "infer", "stop"]
campaign: UUID | None = None
deployment: UUID | None = None
messages: list[dict] = Field(
default_factory=list, max_length=20, description="Chat messages, for a chat model."
)
decisions: list[dict] = Field(
default_factory=list,
max_length=16,
description="For a decision model: each with exactly state, question, kind and options.",
)
max_tokens: int = Field(default=512, ge=1, le=4096)
enable_thinking: bool = False
example: str | None = Field(
default=None,
max_length=100,
description="The id of a frozen serving example in this assignment's acceptance "
"contract, for a chat model. Unset otherwise.",
)
class Review(Contract):
operation: Literal["facts", "data", "definition", "report", "inference"]
artifact: UUID | None = None
inference: UUID | None = None
class UserQuestion(Contract):
id: str = Field(min_length=1, max_length=80)
question: str = Field(min_length=1, max_length=500)
options: list[str] = Field(default_factory=list, max_length=6)
multi_select: bool = False
@model_validator(mode="after")
def valid_options(self):
if any(not value.strip() or len(value) > 200 for value in self.options) or len(
set(self.options)
) != len(self.options):
raise ValueError("Options must be unique, nonempty and at most 200 characters")
return self
class AskUser(Contract):
questions: list[UserQuestion] = Field(min_length=1, max_length=3)
@model_validator(mode="after")
def unique_questions(self):
if len({item.id for item in self.questions}) != len(self.questions):
raise ValueError("Question IDs must be unique")
return self
class RequestAccess(Contract):
purpose: str = Field(min_length=1, max_length=500)
hosts: list[str] = Field(min_length=1, max_length=10)
@model_validator(mode="after")
def named_hosts(self):
if any(
not value or len(value) > 253 or not value.replace("-", "").replace(".", "").isalnum()
for value in self.hosts
) or len(set(self.hosts)) != len(self.hosts):
raise ValueError("Hosts must be unique hostnames such as huggingface.co")
return self
class JudgeOption(Contract):
label: str = Field(min_length=1, max_length=100)
score: float = Field(ge=0, le=1)
class EvalCriterion(Contract):
name: str = Field(min_length=1, max_length=255)
type: Literal["deterministic", "llm"]
source: str = Field(
min_length=1,
max_length=20000,
description="deterministic: a Python script defining evaluate(span). llm: one question the output must meet, at most 1000 characters.",
)
output: Literal["yes_no", "multiple_choice"] | None = Field(
default=None, description="Required for llm. yes_no takes the options Yes and No."
)
options: list[JudgeOption] = Field(
default_factory=list,
max_length=20,
description="Required for llm: 2 to 20 answers, each with its score from 0 to 1.",
)
class EvalSetRequest(Contract):
operation: Literal["list", "inspect", "draft"]
eval_set: UUID | None = Field(
default=None,
description="inspect: the set to read. draft: an existing set to amend; omit to draft a new set.",
)
name: str = Field(default="", max_length=255)
description: str = Field(default="", max_length=4000)
criteria: list[EvalCriterion] = Field(
default_factory=list,
max_length=50,
description="draft: the complete proposed criteria. An amendment replaces the set's criteria with this list.",
)
rationale: str = Field(
default="", max_length=1000, description="draft: why the set or the change is proposed."
)
offset: int = Field(default=0, ge=0)
limit: int = Field(default=20, ge=1, le=100)
@model_validator(mode="after")
def complete_draft(self):
if self.operation == "draft" and not (
self.name.strip() and self.criteria and self.rationale.strip()
):
raise ValueError("A draft needs a name, at least one criterion and a rationale")
return self
class ImportDataset(Contract):
path: str = Field(
min_length=1,
max_length=500,
description="A Parquet, JSONL or CSV file relative to the working directory /workspace/work.",
)
name: str = Field(min_length=1, max_length=255)
class Wait(Contract):
reason: str = Field(min_length=1, max_length=2000)
seconds: int = Field(default=30, ge=5, le=600)
class Supervise(Contract):
operation: Literal["inspect", "note", "retry"]
run: UUID | None = Field(
default=None,
description="A supervised flow run. inspect without one returns every recent run.",
)
node: str | None = Field(
default=None,
max_length=600,
description="A stage of the run. With inspect, returns its definition, bound inputs, "
"outputs and the full result of its operation.",
)
kind: Literal["observation", "mistake", "suggestion"] | None = None
severity: Literal["info", "warning", "error"] = "info"
summary: str = Field(default="", max_length=4000)
proposal: str = Field(
default="",
max_length=8000,
description="For a suggestion: the exact stage, setting and value to change.",
)
@model_validator(mode="after")
def addressed(self):
if self.operation == "note" and not (self.kind and self.summary.strip()):
raise ValueError("A note names its kind and says what was found")
if self.operation == "retry" and self.run is None:
raise ValueError("Name the run to retry")
return self
class Stage(Contract):
id: str | None = Field(default=None, min_length=1, max_length=100, pattern=r"^[a-zA-Z0-9_-]+$")
kind: StageKind | None = None
title: str | None = Field(default=None, min_length=1, max_length=200)
inputs: dict[str, str | list[str] | None] | None = None
settings: dict | None = None
notes: str | None = Field(default=None, max_length=8000)
@model_validator(mode="after")
def addressed(self):
if self.id is None and self.kind is None:
raise ValueError("Name the stage to update by id, or the kind of stage to add")
return self
class ExperimentDecision(Contract):
parent_run: UUID
expected_revision: int = Field(
ge=1,
description=(
"The experiment's current version from experiment inspect, not the parent run's "
"pinned revision or a proposed next revision. Save intended flow edits first, "
"inspect or plan that revision, record this decision, then run without further "
"edits. Later edits invalidate this decision's run admission."
),
)
evidence: list[str] = Field(
default_factory=list,
max_length=40,
description=(
"Retained development evidence references: run:<assignment UUID>, "
"evaluation:<evaluation UUID>, comparison:<node execution UUID>, or "
"action:<measurement action UUID>. Bare UUIDs and context-graph references "
"are not evidence references. A settled failed run is valid failure evidence."
),
)
hypothesis: str = Field(min_length=1, max_length=4000)
alternatives: list[str] = Field(min_length=1, max_length=10)
planned_change: str = Field(min_length=1, max_length=4000)
expected_effect: str = Field(min_length=1, max_length=2000)
comparison_criterion: str = Field(min_length=1, max_length=2000)
outcome: Literal[
"investigate",
"continue",
"retain_incumbent",
"recommend",
"satisfied",
"inconclusive",
"blocked",
]
class ExperimentAdmission(Contract):
kind: Literal["adaptive", "configured_rerun", "initial"]
parent_run: UUID | None = None
decision: UUID | None = None
@model_validator(mode="after")
def complete_admission(self):
if self.kind == "adaptive" and (self.parent_run is None or self.decision is None):
raise ValueError("Adaptive continuation requires a parent run and scientific decision")
if self.kind != "adaptive" and (self.parent_run is not None or self.decision is not None):
raise ValueError("Only adaptive continuation carries scientific lineage")
return self
class Experiment(Contract):
automation: bool = False
evidence_fire: UUID | None = None
evidence_cursor: int = Field(default=0, ge=0)
page_size: int = Field(default=100, ge=1, le=100)
admission: ExperimentAdmission | None = Field(
default=None,
description=(
"Omit for an initial run or correction after all prior attempts failed before "
"any native work was admitted. The platform checks that history. Once work "
"has executed, adaptive follow-ups require a retained scientific decision for "
"the already-saved revision. Save edits, inspect/plan, record the decision, then "
"run that exact revision. Plan checks executable work, not scientific admission. "
"A define(run=true) that changes the flow cannot use a decision made before those edits."
),
)
file: str | None = Field(default=None, max_length=512)
offset: int = Field(default=0, ge=0)
limit: int = Field(default=8000, ge=1, le=16000)
operation: Literal[
"inspect", "define", "stage", "remove", "run", "plan", "source", "save_source", "preview"
]
plan_fingerprint: str | None = Field(default=None, min_length=64, max_length=64)
files: dict[str, str] | None = Field(default=None, max_length=100)
manifest: dict | None = None
expected_version: int | None = Field(default=None, ge=1)
step: str | None = Field(default=None, max_length=64)
preview_rows: int = Field(default=100, ge=1, le=1000)
flow: list[Stage] = Field(
default_factory=list,
max_length=30,
description="For define: the stages to add or update, in order, each written as a stage call is: id, kind, inputs, settings. A later stage names an earlier one in its inputs. Saved together as one revision. Terminal outputs are inferred only when available on every branch. Conditional deployment and shutdown receipts remain in their node results; they are not required flow outputs on a rejected branch.",
)
run: bool = Field(
default=False,
description="For define: request execution after saving. Experiment chat saves the draft for the user to run from the canvas.",
)
id: str | None = Field(
default=None,
min_length=1,
max_length=600,
pattern=r"^[a-zA-Z0-9_/-]+$",
description="For source: node path, e.g. variants/train. For stage: the stage to add or update. An existing id updates that stage; a new id adds one. Omit for a generated id.",
)
kind: StageKind | None = Field(
default=None,
description="For stage: required when adding one. The flow node catalogue lists every kind with its inputs and outputs.",
)
title: str | None = Field(default=None, min_length=1, max_length=200)
inputs: dict[str, str | list[str] | None] | None = Field(
default=None,
description='For stage: where each input comes from, by input name: "stage.output", "stage" when it has one output that fits, or a dataset cell for a data input. A list for an input that takes several. Null disconnects. An input you do not name keeps its connection.',
)
settings: dict | None = Field(
default=None,
description="For stage: the kind's settings; omitted ones take their defaults. On an existing stage they are merged into its settings: objects merge and null removes a setting.",
)
notes: str | None = Field(default=None, max_length=8000)
stages: list[str] = Field(
default_factory=list,
max_length=100,
description="For remove: the stages to remove, with their connections.",
)
note: str = Field(
default="", max_length=2000, description="For stage and remove: why the flow changed."
)
revision: int | None = Field(
default=None, ge=1, description="For run: a saved revision. Omit for the current one."
)
parameters: dict = Field(default_factory=dict)
max_seconds: int = Field(default=3600, ge=60, le=86400)
reuse_run: UUID | None = Field(
default=None,
description="For run: the settled flow run whose results unchanged stages keep: immutable data, verified model checkpoints and development measurements. Omit for your latest settled run. A changed stage and everything after it always execute; serving and final qualification are never reused.",
)
rerun_from: list[str] = Field(
default_factory=list,
max_length=100,
description="For run: stages to execute again, with their dependents, although unchanged.",
)
@model_validator(mode="after")
def addressed(self):
if self.operation in {"source", "save_source", "preview"} and not self.id:
raise ValueError("Name the node whose retained source to inspect or execute")
if self.operation == "save_source" and (
self.files is None or self.manifest is None or self.expected_version is None
):
raise ValueError(
"Source edits require files, manifest and the inspected expected_version"
)
if self.operation == "preview" and not self.step:
raise ValueError("Name the preparation step whose dependency closure to preview")
if self.operation == "stage" and self.id is None and self.kind is None:
raise ValueError("Name the stage to update by id, or the kind of stage to add")
if self.operation == "remove" and not self.stages:
raise ValueError("List the stages to remove")
if self.operation == "define" and not self.flow:
raise ValueError("List the stages of the flow")
return self
class Finish(Contract):
delivery: Literal["outputs", "definition", "answer"] = Field(
default="outputs",
description="What this request leaves. outputs: retained results of the requested work, produced through a flow or native operations. definition: the request was to design, draft or change the flow without running it. answer: a grounded reply or report. An answer cannot waive missing requested work. Explicit requests to execute a saved flow require that flow's declared outputs; an agent-authored flow is not an additional user requirement.",
)
outcome: Literal["completed", "unmet", "blocked"]
summary: str = Field(
min_length=1,
max_length=8000,
description="The complete user-facing answer, including requested results, measured comparisons and remaining limitations. Write the report itself, not a title or an instruction to finalize it.",
)
artifacts: list[UUID] = Field(default_factory=list, max_length=50)
evidence: list[str] = Field(default_factory=list, max_length=50)
limitations: list[str] = Field(default_factory=list, max_length=30)
deliverables: list[DeliverableResult] = Field(default_factory=list, max_length=10)
reviewed_artifacts: list[UUID] = Field(
default_factory=list,
max_length=50,
description="For independent evaluators: exact candidate artifacts authored by another agent. Exclude your own verification report. Cite each candidate in deliverables[].findings[].evidence.",
)
reviewed_campaigns: list[UUID] = Field(
default_factory=list,
max_length=20,
description="For independent evaluators: settled campaigns you assessed, with structured observations in deliverables[].findings and verification_verdict. Failed, stopped or exhausted campaigns accept only failed/insufficient verdicts; passed requires completed campaigns.",
)
verification_verdict: Literal["passed", "failed", "insufficient"] | None = None
@model_validator(mode="before")
@classmethod
def handoff_bindings(cls, data):
"""Verification bindings written inside a deliverable belong to the handoff."""
if not isinstance(data, dict) or not isinstance(data.get("deliverables"), list):
return data
data = {
**data,
"deliverables": [
dict(item) if isinstance(item, dict) else item for item in data["deliverables"]
],
}
for item in data["deliverables"]:
if not isinstance(item, dict):
continue
for field in ("reviewed_artifacts", "reviewed_campaigns", "verification_verdict"):
if field in item:
value = item.pop(field)
if not data.get(field):
data[field] = value
return data
class NoArguments(Contract):
pass
def platform_schema(operation=None):
# Platform services import request contracts from this module.
from overbae.services import research_services
return research_services.tool_schema([operation] if operation else research_services.OPERATIONS)
def platform_effect(arguments):
# Platform services import the request contracts declared here.
from overbae.services import research_services
return "read" if arguments.get("name") in research_services.READS else "mutation"
TOOLS = {
"experiment_decision": ToolDefinition(
request=ExperimentDecision,
description="Retain a scientific decision before an adaptive follow-up flow. Cite settled development run, evaluation or measurement action references. Final results cannot guide continuation.",
returns="Decision receipt, exact evidence identities and proposed outcome. This does not execute a flow.",
),
"asset": ToolDefinition(
request=AssetRequest,
description="Publish and discover immutable candidate, component and benchmark-suite assets. Use list to find an existing asset, inspect for its exact definition, and publish to retain a new revision.",
returns="Immutable asset identity, kind, fingerprint and definition, or available asset records. Publishing creates a revision; listing and inspection do not execute it.",
operations={
"list": Operation(required=(), effect="read"),
"inspect": Operation(required=("asset",), effect="read"),
"publish": Operation(required=("kind", "name", "definition")),
},
definition_types={
"candidate": CandidateDefinition,
"component": ComponentDefinition,
"suite": SuiteDefinition,
},
),
"component": ToolDefinition(
request=ComponentRequest,
description="Execute a retained component in the isolated runtime, or validate retained JSON inputs against a schema. Outputs remain authored artifacts and do not grant native model or evaluation authority.",
returns="Validation evidence or execution identity with retained outputs. An admitted execution may still be running.",
operations={
"run": Operation(required=("component",), effect="submission"),
"validate": Operation(required=("schema", "inputs"), effect="read"),
},
),
"prediction": ToolDefinition(
request=PredictionRequest,
description="Run an immutable candidate on exact development inputs without a scorer. Inspect/resume retains completed rows; unknown provider outcomes are never replayed. Catalogue, recorded-tool agent and isolated component adapters are supported. Selected checkpoints use native benchmark.run.",
returns="Prediction-set identity, execution state, source coverage and retained outputs. Resume continues the same set; it does not regenerate completed rows.",
operations={
"run": Operation(required=("candidate", "cell"), effect="submission"),
"inspect": Operation(required=("prediction_set",), effect="read"),
"resume": Operation(required=("prediction_set",)),
"cancel": Operation(required=("prediction_set",)),
},
),
"score": ToolDefinition(
request=ScoreRequest,
description="Score retained predictions against an immutable benchmark suite without running the candidate again. Use native for a completed native decision benchmark and an explicit participant key; it applies the suite's saved judges to output={kind,options,probabilities,log_probabilities}, with the original source input and expected output. Exact source coverage, errors, phase and acceptance remain visible.",
returns="Evaluation identity, state and measured scores linked to the prediction set and suite. No new candidate inference.",
operations={
"run": Operation(required=("prediction_set", "suite"), effect="submission"),
"native": Operation(
required=("evaluation", "participant", "suite"), effect="submission"
),
"inspect": Operation(required=("evaluation",), effect="read"),
"cancel": Operation(required=("evaluation",)),
},
),
"benchmark": ToolDefinition(
request=Benchmark,
description="Compare models on the same pinned dataset and scoring criteria. For chat, select eval_set or connect a published suite, and pass that selection to catalog to list OpenRouter models (search and offset are optional). Choose participants as key/name/kind=external/model for an exact OpenRouter ID, or key/name/kind=trained/job for a verified project job with a ready chat deployment. Supply one participant key as the baseline. Without an eval set, the saved native decision protocol applies. Use phase=development for iteration. phase=final requires a sealed input and trusted development measurements for the same candidates, and locks further training. Stop cancels this assignment's benchmark.",
returns="Catalogue entries, a benchmark's identity and state, or retained per-model results and failures. Admission is separate from completion.",
operations={
"catalog": Operation(required=(), effect="read"),
"run": Operation(required=("cell",), effect="submission"),
"inspect": Operation(effect="read"),
"stop": Operation(required=("evaluation",)),
},
),
"experiment": ToolDefinition(
request=Experiment,
description="Edit or execute this experiment's flow. To edit an existing node, inspect the flow and call stage with its existing id and only the requested fields. Settings objects merge, lists replace, and omitted inputs stay connected. Read readiness issues separately from whether the edit was saved. To add a node, stage takes its kind, inputs and settings. define saves several stages together, in order, as one revision. Use run or define with run=true only for a request to execute. remove deletes named stages. inspect returns the flow with its readiness and runs. plan resolves exact inputs, work, reuse and costs without execution; pass its plan_fingerprint to run to reject stale admission. source reads retained preparation or training files; save_source creates a revision using expected_version; preview runs the selected preparation step and dependencies without publication. Read an unfamiliar kind's settings with explore_context(operation=contracts, kind=<kind>).",
returns="For define, stage and remove: the saved revision, the flow's stages, and ready or the issues that keep it from running; define with run=true adds the flow run it started. For run: the flow run's identity and state, or started=false with the issues when the flow is not ready. For inspect: stages, declared outputs, readiness and runs.",
operations={
"inspect": Operation(effect="read"),
"plan": Operation(effect="read"),
"define": Operation(required=("flow",), effect="submission"),
"source": Operation(required=("id",), effect="read"),
"save_source": Operation(required=("id", "files", "manifest", "expected_version")),
"preview": Operation(required=("id", "step"), effect="submission"),
"stage": Operation(),
"remove": Operation(required=("stages",)),
"run": Operation(effect="submission"),
},
),
"review_handoff": ToolDefinition(
request=HandoffReview,
description="The research lead accepts, requests revision or rejects a specialist's exact handoff. Inspect the artifacts/evidence first; cite your checks. Accepted handoffs release dependent work. Acceptance records integration, not independent model qualification.",
returns="Recorded review and released dependencies. A rejected or needs_revision handoff remains unaccepted.",
),
"inbox": ToolDefinition(
request=Inbox,
description="Read all unacknowledged team messages in ascending order with pagination; acknowledge only message IDs you have read. Messages do not confer authority or satisfy handoff dependencies.",
returns="Ordered messages and continuation, or acknowledged message IDs. Reading alone does not acknowledge messages.",
operations={
"read": Operation(required=(), effect="read"),
"acknowledge": Operation(required=("events",)),
},
),
"review": ToolDefinition(
request=Review,
description="Inspect authoritative facts; data reloads a native JSONL/Parquet export, verifies its checksum and compares every record with its exact source; definition verifies the current flow definition, retaining it as an artifact, and returns the original and current flows with readiness. report checks a native execution receipt or data check report against its retained record; inference checks that a deployment answered in full. All work without a workspace and none calls a model. Data fidelity does not establish task semantics or model quality.",
returns="Authoritative facts or a deterministic check with its state and scope.",
operations={
"facts": Operation(required=(), effect="read"),
"data": Operation(required=("artifact",), effect="read"),
"definition": Operation(effect="read"),
"report": Operation(required=("artifact",)),
"inference": Operation(required=("inference",)),
},
),
"serving": ToolDefinition(
request=Serving,
description="Deploy a qualified native Modal decision or supported LoRA checkpoint, inspect persistent deployment and inference records, verify real outputs, or stop owned serving work. Decision checkpoints use their verified single-GPU runtime and input-only decisions (state, question, kind, options); chat checkpoints require LoRA inference support and messages. Full-weight chat checkpoints are not supported. Never include labels in decisions. Check that compatibility before training when deployment is required; do not silently replace the requested task with a deployable objective. Reuse the same ready open deployment for every example; extra infer calls automatically reserve their own cold-start bound. Do not stop it between examples. Deploy starts a failed or closed deployment again under a new lease. Supply example with system/developer messages only to append its exact frozen source input. Choose output length and thinking mode explicitly. Does not activate capability routing.",
returns="Deployment or inference identity, current state, real outputs and measured usage. Inspect is read-only; other operations affect owned serving work.",
operations={
"deploy": Operation(required=("campaign",), effect="submission"),
"inspect": Operation(required=(), effect="read"),
"infer": Operation(required=("deployment",), effect="submission"),
"stop": Operation(required=("deployment",)),
},
),
"manage_agent": ToolDefinition(
request=ManageAgent,
description="Stop an unnecessary descendant helper, or resume a stopped helper after resolving its blocker when its deadline and call allowance still have room. Existing costs, calls, notes and limits are preserved; completed helpers cannot be rewritten.",
returns="Current helper state and coordination options. Resume preserves prior evidence and execution limits.",
operations={"stop": Operation(), "resume": Operation()},
),
"inspect_action": ToolDefinition(
request=InspectAction,
effect="read",
description="Read a retained record in full by its identifier: an action receipt of this assignment or of a flow run it started, or a retained artifact. Paginated, for use after context compaction.",
returns="Exact retained text and next_offset. Continue with the same identifier until next_offset is null.",
),
"history": ToolDefinition(
request=History,
effect="read",
description="Search this assignment's retained tool results and failures after compaction or restart. Model-call transcripts and search requests are excluded unless tool=model is explicitly selected. Filter by query, tool or state and paginate. Use inspect_action on a returned receipt for full detail. Does not rerun work.",
returns="Matching action receipts and next_offset. Read a receipt with inspect_action rather than repeating the original work.",
),
"explore_context": ToolDefinition(
request=Explore,
description="Query durable project knowledge without loading it into the prompt. catalog lists valid kinds, supported search ordering and directed source/relationship/target routes; search returns identities; traverse follows typed relationships in either direction (campaign train/development inputs link to their cells); search with kind and order=newest uses recorded creation time where available; read pages exact facts with fingerprint-checked continuation. contracts with kind=tools searches native tools; kind=tool:<name> returns operation schemas, return contracts and current availability. Other kinds return compact component interfaces and exact read requests for configuration/argument schemas, objective-specific monitoring, binding formats and dataset consumers (select kind); partitions returns permitted retained input partitions. Follow returned continuation payloads for read/contracts; only search/traverse use opaque cursors. Reads refresh native records. All published project data is readable, including final splits; attachments are starting points, not a read allowlist. Available before planning.",
returns="Project identities, relationships or facts with exact continuation instructions. Graph references are not interchangeable with cell or job UUIDs.",
operations={
"catalog": Operation(required=(), effect="read"),
"contracts": Operation(required=(), effect="read"),
"search": Operation(required=()),
"traverse": Operation(required=("reference",)),
"read": Operation(required=("reference",), effect="read"),
"partitions": Operation(required=()),
},
),
"inspect_source": ToolDefinition(
request=Source,
description="Read the actual schema and exact rows of an approved dataset; do not infer native fields from its title. Export approved cells into the workspace to investigate and author transformations before planning. Exports retain the source fingerprint and row identities.",
effect_factory=lambda args: (
"workspace" if args.get("export") or args.get("original") else "read"
),
returns="Cell identity, fingerprint, schema, requested rows and next_offset; exports additionally return an immutable workspace path.",
),
"workspace": ToolDefinition(
request=Workspace,
description="Persistent Python kernel, files and a terminal. python runs code in the kernel and is for analysis and short programs. terminal runs a bash command as a background job that outlives the call and runs beside the kernel: use it for a script, a download, an install or anything long-running, and set timeout to the time it needs. The user watches a terminal job's output live in the chat. Both return the output when the run settles within 45 seconds; a longer one returns state=running, so carry on with other work and read it with status. interrupt stops either. Read/write are bounded. The network is closed and provider credentials are absent until the user approves request_access; use platform tools for platform effects and import_dataset to land a downloaded file as a project dataset.",
returns="Final state, exit code and output for a python or terminal run that settled; a running receipt otherwise. File text and continuation for read; write confirmation for write.",
operations={
"python": Operation(required=("code",), effect="workspace"),
"terminal": Operation(required=("command",), effect="workspace"),
"read": Operation(required=("path",)),
"write": Operation(required=("path", "text"), effect="workspace"),
"status": Operation(required=("execution",)),
"interrupt": Operation(required=("execution",)),
"reset": Operation(required=()),
},
),
"delegate": ToolDefinition(
request=Delegate,
description="The research lead assigns a bounded specialist task with a unique responsibility, exact deliverables and optional predecessor agents. Independent tasks run in parallel; dependencies wait for accepted handoffs. Each specialist has its own workspace and shares this assignment's execution limits. Specialists propose work; the lead admits platform mutations.",
returns="Helper identity, responsibility and state. The helper runs asynchronously and returns a reviewable handoff.",
),
"inspect_agent": ToolDefinition(
request=InspectAgent,
effect="read",
description="Inspect a helper's status, new actions, findings and artifact references.",
returns="Helper state, actions, findings and artifact identities. This is not a native training-job status.",
),
"message_agent": ToolDefinition(
request=MessageAgent,
description="Queue a durable finding or question for an active teammate. Does not change their task or authority. If the recipient finishes concurrently, returns delivery=not_delivered with their current coordination action. Review submitted handoffs first; the independent evaluator can resume after review, while completed specialist tasks require a new bounded delegation.",
returns="Durable delivery receipt or not_delivered with current recipient state. Does not restart a finished teammate.",
),
"remember": ToolDefinition(
request=Note,
description="Replace your concise working notebook: evidence, hypotheses, decisions, failed approaches, open questions and next actions. Full receipts remain retained.",
returns="Saved notebook confirmation. Notes do not count as verified evidence.",
),
"retain_artifact": ToolDefinition(
request=Artifact,
description="Retain a workspace file as an immutable deliverable. Authored metrics remain authored observations, not independent qualification.",
returns="Immutable artifact identity, fingerprint and metadata. Retaining a file does not verify its claims.",
),
"fetch_artifact": ToolDefinition(
request=FetchArtifact,
description="Copy an assignment artifact into your workspace without overwriting working files; use to integrate a helper's output.",
returns="Workspace path and retained artifact identity. Does not overwrite existing working files.",
),
"platform": ToolDefinition(
request=Platform,
effect_factory=platform_effect,
description="Invoke a named native operation using its attached argument schema, or inspect it with describe=true. get_model_catalog discovers all training model families; get_job reads a known job; inspect_training_progress reads measured checks; dataset operations inspect, prepare or update approved data. No launch occurs during discovery.",
returns="Native operation result with exact identities, availability, state or continuation. describe returns its schema without execution.",
schema_factory=platform_schema,
),
"workshop": ToolDefinition(
request=Workshop,
description="Delegate data preparation that a transform stage's spec cannot state (text to extract, files to join, conversation data) to the Data Workshop agent, which interprets, transforms and publishes. Use prepare with an approved source_cell, objective and downstream_context describing the intended consumer, target meaning and constraints. The platform adds the request context. The platform cuts a partition when the Workshop publishes, so one delegation cannot also sample from that partition: a subset or variant of the training rows (a random half, a filtered slice) is a second delegation whose source_cell is the partition's train output. Ask for a random subset as a random sample drawn with a named seed, not as a sort or a prefix. prepare returns when the Workshop has settled, which takes a few minutes, and its result is the complete record. inspect rereads a task's record later. Do not reimplement its transformation in the research workspace.",
returns="The settled Workshop task: its state and summary, the prepared dataset, the partition and each output's role, row count and readable cell. training_format is the trainer whose format a version's rows are in (decision or conversation); null means neither. A train stage reads a partition's train output; trainable says whether it also reads an unpartitioned version as it stands, which it does not when the version holds rows a partition of the same task held out. Every published output carries a readable cell, including final splits. A task that published several datasets lists each under publications. A blocked task's summary says what it needs.",
operations={
"prepare": Operation(required=("source_cell", "objective"), effect="submission"),
"inspect": Operation(effect="read"),
},
),
"retain_pipeline": ToolDefinition(
request=Package,
description="Retain an authored dataset transformation ZIP from the workspace using the platform package contract. Then save and run it through platform tools.",
returns="Retained executable package identity and validated manifest; describe returns the package contract. Retention does not launch a transformation.",
),
"training": ToolDefinition(
request=Campaign,
description="Train models in a training campaign. For a saved experiment, configure a train stage with experiment(operation=stage); experiment(operation=run) owns launch. Outside a saved flow, create starts a campaign of one to five runs on one dataset version: the training agent plans each later run and the campaign keeps the run with the lowest development loss. get_model_catalog discovers supported models; inspect reads a campaign's runs, checks and kept checkpoint; stop cancels it.",
returns="The campaign, its runs with their development checks and checkpoints, and the kept run. inspect and describe are read-only; create admits asynchronous training.",
operations={
"create": Operation(payload=TrainingRequest, effect="submission"),
"inspect": Operation(required=("campaign",), payload=NoArguments, effect="read"),
"stop": Operation(required=("campaign",), payload=NoArguments),
},
),
"ask_user": ToolDefinition(
request=AskUser,
description="Ask one to three concise questions when a user decision or missing fact blocks progress. Offer short options where useful; free text is always available. This pauses the lead until the user replies. Do not use for routine implementation decisions or facts available in the project. Call alone, after completing any independent work.",
returns="Retained questions and awaiting_answer state. The reply arrives as a user message.",
),
"request_access": ToolDefinition(
request=RequestAccess,
description="Ask the user to open the workspace to the internet, for example to download a dataset. State the purpose and the hosts you will reach. This pauses the lead until the user approves or denies. Call alone, and only when the work needs something the project does not hold.",
returns="The retained request and awaiting_answer state. The decision arrives as a user message. After approval the workspace restarts with network access for the rest of this request: files are kept and Python state is fresh.",
),
"eval_set": ToolDefinition(
request=EvalSetRequest,
description="Read the project's offline eval sets and draft one for the user's review. list and inspect return saved sets and their criteria. draft proposes a new set, or an amendment to an existing one when eval_set is given, and pauses the lead until the user decides: the user can edit or drop individual criteria before approving. Nothing is saved before approval, and a rejected draft leaves nothing behind. Call draft alone, after completing other work. Unavailable in a run started by a trigger.",
returns="Saved sets with their criteria for list and inspect. For draft, the retained proposal and awaiting_answer state; the decision arrives as a user message naming the saved set and the criteria the user changed or dropped.",
operations={
"list": Operation(required=(), effect="read"),
"inspect": Operation(required=("eval_set",), effect="read"),
"draft": Operation(required=("name", "criteria", "rationale")),
},
),
"import_dataset": ToolDefinition(
request=ImportDataset,
description="Land one Parquet, JSONL or CSV file from the workspace as a new project dataset, so platform tools, training and evaluation can use it. Landing is asynchronous: call again with the same path and name to read its state. Use a new name to import a changed file.",
returns="The dataset identity and landing state. Once state is landed, cell is the readable source cell for inspect_source and platform tools.",
),
"supervise": ToolDefinition(
request=Supervise,
description="An experiment operator's view of the flow runs it supervises and its journal. inspect returns the recent supervised runs with every stage's state, error and failure report; with run it adds that run's events in order; with run and node it returns that stage's definition, bound inputs, outputs and the full result of its operation. note records an observation, a mistake or a suggested amendment in the experiment's journal; it changes nothing. retry runs the failed and cancelled stages of an unmet run again, unchanged, and is refused under suggest.",
returns="For inspect: the run or stage record. For note: the recorded entry. For retry: the run's identity and state.",
operations={
"inspect": Operation(effect="read"),
"note": Operation(required=("kind", "summary")),
"retry": Operation(required=("run",), effect="submission"),
},
),
"wait": ToolDefinition(
request=Wait,
description="Yield while asynchronous work continues. New observations wake the assignment; no model call is charged merely to poll unchanged work.",
returns="Waiting state and wake conditions. The harness resumes on new evidence rather than repeated model polling.",
),
"finish": ToolDefinition(
request=Finish,
description="Deliver retained artifacts and evidence. A completed process alone does not establish task success. Finish refuses pending work; helpers finish only their own task. Report what the platform's records show: read them with review(operation=facts) before stating a measured result.",
returns="Recorded task outcome, or accepted=false with the reason the request stays open.",
),
}