Skip to content

The platform for continuously improving AI agents.

3.0 KB
Raw Blame
from pathlib import PurePosixPath

from overbae.core.errors import InputValidationError
from overbae.services import (
    context_graph,
    execution_mandates,
    research,
    research_evidence,
    research_workspace,
)
from overbae.services.research_contract import Artifact


def directory(key):
    return f".flow/{context_graph.fingerprint(key)}"


def execution_code(code, key):
    return (
        "import os as _flow_os\nfrom pathlib import Path as _FlowPath\n"
        "_flow_previous = _flow_os.getcwd()\n"
        f"_flow_directory = _FlowPath({directory(key)!r})\n"
        "_flow_directory.mkdir(parents=True, exist_ok=True)\n"
        "try:\n"
        "    _flow_os.chdir(_flow_directory)\n"
        f"    exec(compile({code!r}, '<flow-node>', 'exec'), {{'__name__': '__main__'}})\n"
        "finally:\n"
        "    _flow_os.chdir(_flow_previous)\n"
    )


def validate_exports(node):
    exports = node["config"].get("outputs", {})
    if not exports:
        raise InputValidationError(f"Declare retained output files for {node['title']}")
    for port, specification in exports.items():
        request = Artifact.model_validate(
            {**specification, "title": specification.get("title", port)}
        )
        path = PurePosixPath(request.path)
        if path.is_absolute() or ".." in path.parts:
            raise InputValidationError("Output files must be relative to the execution workspace")
    return exports


def collect(action, node):
    with execution_mandates.continuing_node(action):
        return collect_outputs(action, node)


def collect_outputs(action, node):
    # Output retention and source binding share the native action contract.
    from overbae.services.experiment_execution import retain_outputs

    source_cells = research_evidence.input_sources(
        action.agent.assignment.project, action.experiment_inputs
    ) | research_evidence.workspace_sources(action)
    bindings = {}
    for port, specification in validate_exports(node).items():
        request = Artifact.model_validate(
            {
                **specification,
                "title": specification.get("title", port),
                "metadata": {
                    **specification.get("metadata", {}),
                    "producer_action": str(action.pk),
                    "inputs_fingerprint": context_graph.fingerprint(action.experiment_inputs),
                },
            }
        )
        receipt = research.claim(
            action.agent,
            f"flow-output:{action.pk}:{port}",
            "artifact",
            request.model_dump(mode="json"),
        )
        artifact = research.retain(
            receipt,
            request,
            research_workspace.read(
                action.agent, f"{directory(action.request_key)}/{request.path}"
            ),
            source_cells=source_cells,
        )
        research.complete(receipt, research.artifact_record(artifact), cost=0)
        bindings[port] = str(artifact.pk)
    return retain_outputs(action, bindings)