Skip to content

The platform for continuously improving AI agents.

2.6 KB
Raw Blame
"""What a finished stage records beside its state: the tool it called, the platform record it
ended on, how long it ran and, when it did not complete, the class of its failure. The
message stays in the step's ``error``."""

# Whether running the stage again unchanged can succeed. A class that is absent is unknown.
RETRYABLE = {
    "stopped": True,
    "code_error": False,
    "check_failed": False,
    "output_contract": False,
    "invalid_configuration": False,
    "admission_denied": False,
    # An uncertain provider outcome is reconciled from its saved identity, never resubmitted.
    "outcome_unknown": False,
}
DENIED = frozenset(
    {
        "authentication_failed",
        "authentication_required",
        "holdout_sealed",
        "insufficient_credits",
        "permission_denied",
        "protected_setting",
    }
)
TRACEBACK = "Traceback (most recent call last):"


def tool_error(code) -> str:
    """The class of a catalog tool's refusal, from its error code."""
    if code == "request_in_progress":
        return "outcome_unknown"
    if code == "internal_error":
        return "operation_failed"
    return "admission_denied" if code in DENIED else "invalid_configuration"


def last_exception(text) -> str | None:
    """The exception line that ends the last Python traceback in a program's output."""
    lines = str(text or "").splitlines()
    starts = [index for index, line in enumerate(lines) if line.startswith(TRACEBACK)]
    if not starts:
        return None
    return next(
        (line.strip()[:500] for line in lines[starts[-1] + 1 :] if line and not line[0].isspace()),
        None,
    )


def failed_job(job: dict) -> dict:
    """The failure of a stage whose platform record ended without success, as get_job reads it."""
    status = job.get("status")
    if status == "submission_unknown":
        return {"code": "outcome_unknown"}
    if status != "failed":
        return {"code": "stopped"}
    exception = last_exception(job.get("job_error"))
    if exception:
        return {"code": "code_error", "exception": exception}
    return {"code": "operation_failed"}


def report(step, failure: dict | None, action: dict | None) -> dict:
    receipt = action or (step.receipts[0] if step.receipts else None)
    out = {
        "tool": next((call["tool"] for call in step.calls if call.get("tool")), None),
        "action": {"kind": receipt["kind"], "id": receipt["id"]} if receipt else None,
        "duration_seconds": round((step.ended_at - step.started_at).total_seconds(), 3),
    }
    if failure is not None:
        out["failure"] = {**failure, "retryable": RETRYABLE.get(failure["code"])}
    return out