Skip to content
Open
6 changes: 5 additions & 1 deletion src/agent_env/agents/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,11 @@ terminal state, `completed`, `failed` or `canceled`. Your `run()` is one turn.
`requirements.txt` protocol floor at the first release that has them.
- **Errors:** `agent_error`, the default, means the agent tried and failed; `infra_error` means the run couldn't
happen, and agent-env may retry it. An exception that escapes `run()` becomes an opaque `infra_error`, its text
never sent.
never sent. prompt_agent fails its step on either. always_on ends its run on either, but grades only an
`agent_error` turn (a rubrics judge's 0): an `infra_error` turn fails the step once the run is recorded
(`AgentTurnInfraError`), so no verifier grades it, and the run is redone once from its env deploy (always_on's
default `retry_config`, which a task's own replaces). So a failure that may be the
model's (a limit it ran into, a refusal, a malformed call) is an `agent_error`, not an `infra_error`.
- **Context and sessions:** turns of one `context_id` run one at a time; different contexts run concurrently, and the
validator relies on it, so don't serialize them. Return your runtime's conversation id as `session_ref` and the next
turn in that context gets it back; bind it before the runtime starts, so a live trajectory read or a mid-turn
Expand Down
7 changes: 4 additions & 3 deletions src/agent_env/task/outcome.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

import httpx

from agent_env.task_step.context import VerifierNotPassingError
from agent_env.task_step.context import AgentTurnInfraError, VerifierNotPassingError
from agent_env.task_step.task_step import StepRole

if TYPE_CHECKING:
Expand Down Expand Up @@ -54,8 +54,9 @@ class FailureCause(StrEnum):
)),
)

# A failure of one of these types is one the A2A client or the model SDK retries, whatever its message says.
_TRANSIENT_TYPES = (TimeoutError, ConnectionError, httpx.TransportError)
# A failure of one of these types is one the A2A client or the model SDK retries, whatever its message says; or, for
# an agent turn that failed for an infrastructure reason, one its agent says agent-env may retry.
_TRANSIENT_TYPES = (TimeoutError, ConnectionError, httpx.TransportError, AgentTurnInfraError)


def _chain(exc: BaseException) -> Iterator[BaseException]:
Expand Down
27 changes: 27 additions & 0 deletions src/agent_env/task/task.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,8 @@ def _sub(value):
seeded = attach_base_fields(type(step).from_dict(data), data)
if (keep := getattr(seeded, "seeded_from", None)) is not None: # a step that keeps something as written
keep(step)
if seeded.retry_config is None and (implied := getattr(step, "retry_config", None)) is not None:
seeded.retry_config = implied # its type's default, which to_dict leaves out
out.append(seeded)
return out

Expand Down Expand Up @@ -383,6 +385,31 @@ def __init__(
self._validate_dag(self.steps)
self._validate_pairings(self.steps)
self._validate_headlines(self.headline_verifiers, self.steps)
self._imply_retries(self.steps)

@staticmethod
def _imply_retries(steps: list[TaskStep]) -> None:
"""Give each step the task left without a ``retry_config`` the one its type implies
(``TaskStep.default_retry_config``), when its rollback covers everything the step depends on: each of the step's
ancestors comes before the step it resumes from or after it, none beside it, which a rollback would leave as the
failed attempt left it. A step built without TaskStep, as some tests build one, has none."""
deps: dict[str, set[str]] | None = None
for step in steps:
if getattr(step, "retry_config", None) is not None or not hasattr(step, "default_retry_config"):
continue
deps = deps if deps is not None else _dependency_ids(steps)
ancestors = _ancestor_ids(step.id, deps)
implied = step.default_retry_config([s for s in steps if s.id in ancestors])
if implied is None:
continue
start = implied.retry_from_step_id
before = _ancestor_ids(start, deps)
beside = [a for a in ancestors - before - {start} if start not in _ancestor_ids(a, deps)]
if beside:
logger.info("%s: no default retry from %s, which doesn't redo %s; give it a retry_config",
step.id, start, ", ".join(sorted(beside)))
continue
step.retry_config = implied

@staticmethod
def _validate_headlines(headlines: list[str] | None, steps: list[TaskStep]) -> None:
Expand Down
9 changes: 9 additions & 0 deletions src/agent_env/task_step/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,15 @@ class VerifierNotPassingError(RuntimeError):
"""A verifier set to fail its task when its verdict isn't passing recorded one that isn't. Grading the same run
again could pass it, so a runner should not retry it."""


# The A2A error_type of a turn that couldn't happen for a reason that isn't the agent's, which agent-env may retry.
INFRA_ERROR = "infra_error"


class AgentTurnInfraError(RuntimeError):
"""An agent turn failed for an infrastructure reason (its agent said ``infra_error``, or stopped answering), so the
run says nothing about the agent: its step fails once the run is recorded, and a ``retry_config`` can redo it."""

_REDACTED_KEYS = {
"litellm_api_key", "judge_litellm_api_key", "usersim_api_key", "remote_tokens", "cf_access_client_secret",
HEARTBEAT_KEY,
Expand Down
14 changes: 12 additions & 2 deletions src/agent_env/task_step/task_step.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,11 @@ class RetryConfig:

retry_from_step_id: str
max_retries: int = 1
# A step type's own default (``TaskStep.default_retry_config``), never written into the stored task.
implied: bool = dataclasses.field(default=False, compare=False)

def to_dict(self) -> dict[str, Any]:
return {"retry_from_step_id": self.retry_from_step_id, "max_retries": self.max_retries}

@classmethod
def from_dict(cls, data: dict[str, Any]) -> "RetryConfig":
Expand Down Expand Up @@ -163,6 +168,11 @@ def config_warnings(self) -> list[str]:
fine. Task lint reports them as warnings, as it reports ``config_problems`` as errors."""
return []

def default_retry_config(self, ancestors: list["TaskStep"]) -> Optional["RetryConfig"]:
"""The retry a step of this type takes when its task gives it none (``ancestors``: the steps it depends on,
directly or not, in task order); None for no retry. A task's own ``retry_config`` always wins."""
return None

def task_problems(self, steps: list["TaskStep"]) -> list[str]:
"""Problems this step has with the task's other steps (``steps``: all of them, this one included, in order),
found without reading a store; empty when fine. A task with any is refused when it loads."""
Expand All @@ -187,8 +197,8 @@ def to_dict(self) -> dict[str, Any]:
base: dict[str, Any] = {"id": self.id, "type": self.type, "version": self.version, "fail_task_on_error": self.fail_task_on_error}
if self.depends_on is not None:
base["depends_on"] = [dataclasses.asdict(d) for d in self.depends_on]
if self.retry_config is not None:
base["retry_config"] = dataclasses.asdict(self.retry_config)
if self.retry_config is not None and not self.retry_config.implied:
base["retry_config"] = self.retry_config.to_dict()
Comment thread
sarah-chitty-1 marked this conversation as resolved.
Resolved
if self.step_role != type(self).step_role:
base["step_role"] = self.step_role.value
return base
Expand Down
69 changes: 54 additions & 15 deletions src/agent_env/task_step/task_steps/always_on.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,15 +48,20 @@
closing wake, with the step's wrap-up line and the last-turn notice, and the run ends with end reason time_budget.
- End reasons: end_time, user_done (one sitting), max_wakes, time_budget, finished_nothing_pending or stuck (nothing
can wake the agent, with nothing pending or with something still pending), agent_turn_failed, agent_turn_timeout,
user_sim_error, user_sim_invalid, step_error. With no end_time, a world that only repeats ends the run too (``IDLE_JUMPS_MAX``, in the
agent_turn_infra_error, user_sim_error, user_sim_invalid, step_error. With no end_time, a world that only repeats ends the run too (``IDLE_JUMPS_MAX``, in the
loop's docstring), so a recurring trigger that never wakes the agent can't move the clock forever. What was still pending is recorded (``pending_at_end``): replies held, messages the user
never read, user lines and alerts never delivered, the agent's checks not yet due, contact replies in progress.
- Graders read what the user saw. The prompt response is every message_user text in order, each with its pretend
time, never the agent's closing text; messages no turn took (a turn that timed out after sending) are taken at the
end and included, and listed as never read. The conversation (``metadata["a2a_conversations"][step_id]``) holds the user's
own messages and the agent's message_user texts, then the user's last word that never reached the agent and an end
marker with the end reason. An agent turn that doesn't complete (failed, canceled, rejected, timed out) ends the run
and sets the response's ``error_type`` (as prompt_agent does for a failed one), so verifiers skip the run.
and sets the response's ``error_type`` (as prompt_agent does for a failed one): a rubrics judge scores the run 0
without judging it (a ``prompt_error`` row), and the user-sim judge and the satisfaction rating skip it. A turn that
failed for an infrastructure reason, its agent's ``error_type`` being ``infra_error`` or the agent having stopped
answering (its sandbox died), is not the agent's failure: the run is recorded the same way, with end reason
agent_turn_infra_error and the turn's ``error_code``, and then the step fails with ``AgentTurnInfraError``, so no
verifier grades it and a ``retry_config`` can redo it.
- With ``continue_after_wake_limit`` on, a turn (a wake's, or its nudge's) that reaches its time limit
(``timeout_seconds``) or its tool-call limit (``max_turns``) ends only that wake: what it did stands, its messages to
the user are taken as any wake's are, and the run goes on to its next event, still bounded by ``max_wakes`` and the
Expand All @@ -67,7 +72,7 @@
can't confirm canceled ends the run as before. The next wake opens with a note that the last turn was cut off
(``CUT_OFF_TEXT``). Each cut-off is in the timeline (``wake_cut_off``, and ``cut_off`` on the turn's end), the run's
record (``cut_off_wakes``) and what the judge reads. A turn that fails for any other reason (an agent crash, a
protocol error) still ends the run.
protocol error) still ends the run, and one that failed for an infrastructure reason fails the step as above.
- Who did what, and in what order, even under a frozen clock: each app change (urn:agentenv:changes/v1) is recorded
with who made it and the wake it was seen in, the agent's own with the wake that made it (``app_changes`` events);
each reply records the agent's message it answers (``reply_to``: its wake, time and text); and each read leaves a
Expand Down Expand Up @@ -138,10 +143,17 @@
)
from agent_env.config.model import ModelRole, run_model
from agent_env.store import DuplicateKeyError, get_config
from agent_env.task_step.context import PromptResponse, StepContextError, TaskStepContext, TurnTrajectory
from agent_env.task_step.context import (
INFRA_ERROR,
AgentTurnInfraError,
PromptResponse,
StepContextError,
TaskStepContext,
TurnTrajectory,
)
from agent_env.task_step.snapshot_utils.atif_copies import AtifCopies
from agent_env.task_step.usage import StepUsage
from agent_env.task_step.task_step import TaskStep
from agent_env.task_step.task_step import RetryConfig, TaskStep
from agent_env.task_step.task_steps.agent import user_sim_versions
from agent_env.task_step.task_steps.agent.deploy_user_sim_agent import USER_SIMS_KEY, recorded_instructions, user_sim_model
from agent_env.task_step.task_steps.notification_delivery import delivered_parts, label_time, take_due
Expand Down Expand Up @@ -199,7 +211,11 @@
# The final check-in's line when the task sets no `final`: the step's, not the user's.
FINAL_DEFAULT_TEXT = "Time's up on this job. Send {first} a short wrap-up: what's done, and anything still open."
NOTHING_CAN_WAKE = "nothing_can_wake_the_agent" # until finish() tells finished_nothing_pending from stuck
ERROR_ENDS = ("agent_turn_failed", "agent_turn_timeout", "user_sim_error", "step_error")
# An agent turn that failed for an infrastructure reason: recorded as any failed turn, then the step fails
# (AgentTurnInfraError). An agent that stopped answering is one, with this error_code.
AGENT_TURN_INFRA_ERROR = "agent_turn_infra_error"
AGENT_UNREACHABLE_CODE = "agent_env.agent_unreachable"
ERROR_ENDS = ("agent_turn_failed", "agent_turn_timeout", AGENT_TURN_INFRA_ERROR, "user_sim_error", "step_error")
# A turn's limits, which continue_after_wake_limit lets end only the wake, and how the agent and the judge are told.
TIME_LIMIT, TOOL_CALL_LIMIT = "time_limit", "tool_call_limit"
LIMIT_WORDS = {TIME_LIMIT: "time limit", TOOL_CALL_LIMIT: "tool-call limit"}
Expand Down Expand Up @@ -228,6 +244,7 @@
"stuck": "Nothing could wake the assistant again, though something was still pending.",
"agent_turn_failed": "The assistant's turn failed.",
"agent_turn_timeout": "The assistant's turn timed out.",
AGENT_TURN_INFRA_ERROR: "The assistant's turn failed for an infrastructure reason, not the assistant's doing.",
"user_sim_error": "The user simulator failed.",
"user_sim_invalid": "The user simulator's answer still read as the assistant's after its rewrites.",
"step_error": "The run stopped on an error.",
Expand Down Expand Up @@ -406,6 +423,12 @@ def from_dict(cls, data: dict) -> AlwaysOnTaskStep:
fields["user_sim_gate"] = data["user_sim_gate"]
return cls(**cls._base_from_dict(data), retry_config=data.get("retry_config"), **fields, **own)

def default_retry_config(self, ancestors: list[TaskStep]) -> Optional[RetryConfig]:
"""A turn that failed for an infrastructure reason (``AgentTurnInfraError``), or an attempt a dead worker lost,
is redone once on a fresh world, from the first env deploy before this step; never in the world it changed."""
deploy = next((s for s in ancestors if s.type == "deploy_env"), None)
return RetryConfig(deploy.id, max_retries=1, implied=True) if deploy is not None else None
Comment thread
sarah-chitty-1 marked this conversation as resolved.
Resolved

def task_problems(self, steps: list[TaskStep]) -> list[str]:
"""Its prompt is graded by always_on_agent_verifier: a plain rubrics_verifier, which would grade it from every
wake's trajectory, is refused."""
Expand Down Expand Up @@ -466,7 +489,7 @@ def __init__(self, step: AlwaysOnTaskStep, context: TaskStepContext):
self.all_messages: list[dict] = []
self.final_task_id = ""
self.error: Optional[str] = None
self.error_type: Optional[str] = None # set as prompt_agent sets it, so verifiers skip a run that broke
self.error_type: Optional[str] = None # set as prompt_agent sets it, so verifiers know the run broke
self.error_code: Optional[str] = None
self.chat_pending: list[dict] = [] # the agent's message_user texts not yet in the graded conversation
self.reaction: Optional[dict] = None # her last read's answer when she said nothing
Expand Down Expand Up @@ -648,6 +671,11 @@ async def go(self) -> None:
raise
finally:
await self.finish()
if self.end_reason == AGENT_TURN_INFRA_ERROR:
raise AgentTurnInfraError(
f"always_on: wake {self.wakes}'s agent turn failed for an infrastructure reason "
f"(error_type={self.error_type}, error_code={self.error_code}); the run is recorded but not graded: "
f"{self.error}")

async def _load_plugin(self, spec: Optional[dict]) -> ModuleType:
if not spec:
Expand Down Expand Up @@ -1474,8 +1502,8 @@ def record() -> None:
except TimeoutError as e:
ended = await self._stopped_at_time_limit(e)
if ended is None:
self._failed("agent_turn_timeout", f"agent turn timed out after {step.timeout_seconds}s: {e}")
self.log("agent_turn_end", n=self.wakes, state="timeout", real_seconds=round(time.time() - t, 1),
state = self._no_answer(e, "agent turn")
self.log("agent_turn_end", n=self.wakes, state=state, real_seconds=round(time.time() - t, 1),
**({"stop": "unconfirmed"} if step.continue_after_wake_limit else {}))
return
turn, stopped = self._stopped_turn(ended, f"agent turn timed out after {step.timeout_seconds}s: {e}")
Expand Down Expand Up @@ -1594,9 +1622,9 @@ def record() -> None:
except TimeoutError as e:
ended = await self._stopped_at_time_limit(e)
if ended is None:
self._failed("agent_turn_timeout", f"agent nudge turn timed out after {step.timeout_seconds}s: {e}")
state = self._no_answer(e, "agent nudge turn")
self.log("nudge", n=self.nudges, wake=self.wakes, virtual_time=_iso(sent_at), closing_text=closing,
state="timeout", outcome="timeout", real_seconds=round(time.time() - t, 1),
state=state, outcome=state, real_seconds=round(time.time() - t, 1),
**({"stop": "unconfirmed"} if step.continue_after_wake_limit else {}))
return
turn, stopped = self._stopped_turn(ended, f"agent nudge turn timed out after {step.timeout_seconds}s: {e}")
Expand Down Expand Up @@ -1701,10 +1729,21 @@ def _sent(self, messages: list[dict], after_nudge: bool = False, leftover: bool

def _failed(self, error_type: str, error: str, error_code: Optional[str] = None) -> None:
"""An agent turn didn't complete (failed, canceled, rejected or timed out): the run ends, and its prompt
response carries ``error_type`` the way prompt_agent's does, so verifiers skip it instead of grading it as a
normal run."""
response carries ``error_type`` the way prompt_agent's does, so a rubrics judge scores it 0 unjudged and other
verifiers skip it. An ``infra_error`` ends it as agent_turn_infra_error, which fails the step once the run is
recorded (``go``), so it is graded by none."""
self.error, self.error_type, self.error_code = error, error_type, error_code
self.end_reason = "agent_turn_timeout" if error_type == "agent_turn_timeout" else "agent_turn_failed"
self.end_reason = (AGENT_TURN_INFRA_ERROR if error_type == INFRA_ERROR
else "agent_turn_timeout" if error_type == "agent_turn_timeout" else "agent_turn_failed")

def _no_answer(self, error: TimeoutError, turn: str) -> str:
"""A turn the agent never answered: one that stopped answering (its sandbox died) failed for an
infrastructure reason; else it timed out. The state the timeline records it in."""
if isinstance(error, protocol.AgentUnreachableError):
self._failed(INFRA_ERROR, f"{turn}: {error}", AGENT_UNREACHABLE_CODE)
return "unreachable"
self._failed("agent_turn_timeout", f"{turn} timed out after {self.step.timeout_seconds}s: {error}")
return "timeout"

async def read(self, now: datetime, last: bool = False) -> None:
"""The user sim reads what the agent sent since her last read, at ``now``; ``last`` marks the read after the
Expand Down Expand Up @@ -2005,7 +2044,7 @@ async def finish(self) -> None:
if step.continue_after_wake_limit:
counts["cut_off_wakes"] = len(self.cut_offs)
record = {"step_id": step.id, "end_reason": self.end_reason, "end_note": self.end_note, "error": self.error,
"error_type": self.error_type, "counts": counts,
"error_type": self.error_type, "error_code": self.error_code, "counts": counts,
"user_sim": {"name": step.user_sim, "version": self.version,
"agent_name": self.us.get("agent_name"), "context_id": self.user_context_id,
**self.user_setup},
Expand Down
Loading
Loading