Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions src/agent_env/agents/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,12 @@ 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. 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`.
never sent. prompt_agent fails its step on either. always_on goes on past an `agent_error` turn, which ends only
its wake (three in a row end the run), and judges the whole run, the failed turns counted against the agent: an
`infra_error` turn ends the run and 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
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,9 @@
the deploy record's ``tagged_lines``), the whole ask and raw answers in the object store at its ``object_url``. It never reaches the
agent, the graded conversation, or the verifications.

Not rated, recorded with ``skipped`` and why: a run that ended on an error (always_on's error end reasons; a
prompt_agent run whose agent turn or user sim failed; a run step that failed), and a run whose user sim agent is no
longer deployed. A rating that fails or runs past ``timeout_seconds`` (by default one always_on read's worst case) is
Not rated, recorded with ``skipped`` and why: a run that ended on an error (always_on's error end reasons but its
agent's own failures, a run its failed turns ended being rated as any run is; a prompt_agent run whose agent turn or
user sim failed; a run step that failed), and a run whose user sim agent is no longer deployed. A rating that fails or runs past ``timeout_seconds`` (by default one always_on read's worst case) is
recorded with its error; the step fails only when it can't find the run or its user, and by default
(``fail_task_on_error`` false) that doesn't fail the task.
"""
Expand Down Expand Up @@ -61,6 +61,7 @@
from agent_env.task_step.task_steps.agent.user_sim_common import SATISFACTION_KEY, iso, person_of, task_zone, utc
from agent_env.task_step.task_steps.sandbox_utils.sandbox_utils import ended_turn_error
from agent_env.task_step.task_steps.always_on import (
AGENT_FAILURE_ENDS,
ALWAYS_ON_KEY,
ERROR_ENDS,
READ_ASKS,
Expand Down Expand Up @@ -349,7 +350,8 @@ def _always_on_session(record: dict) -> _Session:
sim = record.get("user_sim") or {}
session = _Session("always_on record", user_sim=sim.get("name"), context_id=sim.get("context_id"),
time_zone=record.get("time_zone"))
if record.get("end_reason") in ERROR_ENDS:
if record.get("end_reason") in ERROR_ENDS and record["end_reason"] not in AGENT_FAILURE_ENDS:
# A run its agent's own failure ended is rated as any run is: she rates the job it did.
session.skipped = f"the run ended on {record['end_reason']}"
return session
timeline = record.get("timeline_tail") or []
Expand Down
174 changes: 141 additions & 33 deletions src/agent_env/task_step/task_steps/always_on.py

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ async def verify(self, context: TaskStepContext) -> Verification:
if prompt_response is None:
raise StepContextError(f"PromptResponse with prompt_id='{self.prompt_id}' not found in context")

if prompt_response.error_type:
if prompt_response.error_type and not _ended_on_agent_failure(context, prompt_response.step_id):
logger.warning(
f"Skipping verification '{self.verifier_id}': prompt had error_type={prompt_response.error_type}"
)
Expand Down Expand Up @@ -183,3 +183,11 @@ def _criterion_problems(criterion: Any) -> list[str]:
except re.error as e:
return [f"pattern {pattern!r} doesn't compile: {e}"]
return []


def _ended_on_agent_failure(context: TaskStepContext, step_id: Optional[str]) -> bool:
"""An always_on run that ended on its agent's own failure has a response that stands, every message it sent the
user, and is checked as any run's is (``ended_on_agent_failure``); any other failed prompt scores 0 unchecked."""
from agent_env.task_step.task_steps.always_on import ended_on_agent_failure # here: always_on imports our peers

return ended_on_agent_failure(context.metadata, step_id)
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@
A run that kept no timeline has its turns staged the same way by position, one wake file a turn, so the judge never
reads a trajectory as stored.

A wake whose turn stored no trajectory (a turn agent-env gave up waiting on stores none, nor may a turn that failed) is
staged from the run's record with a line saying its trajectory is missing, which the judge's prompt names too. A run
with failed turns is judged so even when no turn stored one (``_judges_without_trajectory``); a run that failed no turn
and stored none is refused, as rubrics_verifier refuses it.

With full_app_changes (opt-in, with use_trajectory), each staged app change also carries its changed fields in full, an
UPDATE's old and new values, an INSERT's or DELETE's whole row, from the run's ``metadata["env_changes"]`` (what a
snapshot_env step with include_env_changes records, which the task must run after the always_on step and before this
Expand Down Expand Up @@ -44,9 +49,15 @@
from typing import Any, ClassVar, Optional

from agent_env.providers.sandbox_providers.sandbox import into_container
from agent_env.task_step.context import PromptResponse, TaskStepContext
from agent_env.task_step.context import INFRA_ERROR, PromptResponse, TaskStepContext
from agent_env.task_step.task_step import TaskStep
from agent_env.task_step.task_steps.always_on import ALWAYS_ON_KEY, AlwaysOnTaskStep, render_for_judge, stored_timeline
from agent_env.task_step.task_steps.always_on import (
ALWAYS_ON_KEY,
AlwaysOnTaskStep,
ended_on_agent_failure,
render_for_judge,
stored_timeline,
)
from agent_env.task_step.task_steps.prompt_agent import PromptAgentTaskStep
from agent_env.task_step.task_steps.verifiers.always_on_staging import (
EVENTS_FILE,
Expand Down Expand Up @@ -338,6 +349,21 @@ async def _judged(self, context: TaskStepContext) -> RubricsVerdict:
output["assistant_harness"] = harness
return dataclasses.replace(verdict, output=output)

def _judges_failed_run(self, context: TaskStepContext, prompt_response: PromptResponse) -> bool:
"""A run that ended on its agent's own failure (its turns failing too many times in a row, or one agent-env gave
up waiting on) is judged as a whole, like any run: its wakes, failed turns among them, count against the agent.
One the user sim or the step itself broke is still scored 0 unjudged."""
return ended_on_agent_failure(context.metadata, prompt_response.step_id)
Comment thread
sarah-chitty-1 marked this conversation as resolved.
Resolved

def _judges_without_trajectory(self, context: TaskStepContext, prompt_response: PromptResponse) -> bool:
"""A run with a turn that failed as its agent's own failure is judged with use_trajectory even when no turn
stored a trajectory: a turn agent-env gave up waiting on stores none, nor may a turn that failed, so a run that
ended on its opening wake's, or on failed turns alone, can have none. Each such turn is staged from the run's
record with a line saying its trajectory is missing, as any missing one is, and the judge is told. A run that
failed no turn and stored none is refused, as rubrics_verifier refuses it: nothing explains the gap."""
record = (context.metadata.get(ALWAYS_ON_KEY) or {}).get(prompt_response.step_id) or {}
return any(f.get("error_type") != INFRA_ERROR for f in record.get("failed_turns") or [])

def _spec(self) -> JudgeOutputFormatSpec:
"""rubrics_verifier's format; for a run with agent labels or a compaction (``_CONTEXT_LOSS_RUN``), its rows also
take ``context_loss`` and ``context_loss_evidence``."""
Expand Down Expand Up @@ -600,10 +626,14 @@ def _files_note(path: str, staged: StagedRun, *, context_loss: bool = False) ->

def turns_by_position(prompt_response: PromptResponse) -> list[dict]:
"""A timeline for a run that kept none: one wake a turn, in the order the turns ran (a nudge's turn is one of its
own), with its trajectory and the text it was sent (the prompt response keeps each turn's, cut)."""
own), with its trajectory and the text it was sent (the prompt response keeps each turn's, cut). A turn sent that
has no entry among the trajectories (one agent-env gave up waiting on, which ended the run) is one whose
trajectory is missing, never left out."""
sent = prompt_response.source_agent_per_turn_prompt_parts or []
urls = prompt_response.target_agent_per_turn_trajectory_object_urls or []
timeline: list[dict] = []
for n, url in enumerate(prompt_response.target_agent_per_turn_trajectory_object_urls or [], 1):
for n in range(1, max(len(urls), len(sent)) + 1):
url = urls[n - 1] if n <= len(urls) else None
parts = (sent[n - 1] if n <= len(sent) else None) or []
text = "\n".join(p.get("text") or "" for p in parts if isinstance(p, dict) and p.get("kind") == "text")
timeline += [{"event": "wake", "n": n, "parts_text": text},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@
harness put in the turn (``harness_note``: a compaction summary, a message it sent the assistant, its account of
why the wake failed, which has ``failure``), then the rest
of the wake in time order (``app_change`` for every change, ``turn_end`` with its closing reply,
``message_to_user``, a ``nudge`` and its calls, the user's reads). A turn that ended at its time or tool-call limit
``message_to_user``, a ``nudge`` and its calls, ``turn_failed`` for a turn that failed and whether the run went on
after it, the user's reads). A turn that ended at its time or tool-call limit
while the run went on (the step's ``continue_after_wake_limit``) has ``cut_off`` on its ``turn_end`` (or ``nudge``)
and a ``wake_cut_off`` line; the next wake's ``woke`` line has ``cut_off_notice``. A turn's
and a ``wake_cut_off`` line; the next wake's ``woke`` line has ``cut_off_notice``, as it has ``failed_turn_notice``
after a turn that failed while the run went on (the step's note to the assistant, in its ``wake_input``). A turn's
trajectory is matched to its wake by the timeline's ``trajectory_url``; one that's missing is a line saying so. A
helper agent's lines carry ``subagent``; those of a turn the harness asked for carry ``step`` (the PSI harness's
``pre_compaction_save``, where only its memory and history tools work; ``after_compaction`` and ``failed_wake``
Expand Down Expand Up @@ -76,6 +78,7 @@
# A line's fields that say what and where it is; ``fit`` moves only the others.
_IDENTITY = frozenset({"event", "wake", "at", "call", "turn", "tool", "kind", "state", "outcome", "phase", "by",
"step", "subagent", "compaction", "failure", "internal", "cut_off", "cut_off_notice",
"failed_turn_notice",
"limit"})


Expand Down Expand Up @@ -208,7 +211,8 @@ def add(self, event: dict) -> None:
w = self.wake(event["n"])
w.at, w.woke_by = at, list(event.get("woke_by") or [])
w.head.append(_line("woke", w.n, at=at, woke_by=w.woke_by, notifications=event.get("notifications") or None,
last=event.get("last"), cut_off_notice=event.get("cut_off_notice")))
last=event.get("last"), cut_off_notice=event.get("cut_off_notice"),
failed_turn_notice=event.get("failed_turn_notice")))
w.head += [_line(m.pop("event"), w.n, **m) for m in self.pending_user]
self.pending_user = []
w.head.append(_line("wake_input", w.n, text=event.get("parts_text") or ""))
Expand Down Expand Up @@ -463,6 +467,11 @@ def _index_block(w: _Wake, path: str, lines: list[dict], by_changes: bool, run_c
told = line["cut_off_notice"]
out.append(f"- opened by telling the assistant that wake {told.get('wake')}'s turn was cut off at its "
f"{_limit_words(told.get('limit'))} ({path}:{i})")
elif event == "woke" and line.get("failed_turn_notice"):
told = line["failed_turn_notice"]
which = "nudge turn" if told.get("turn") == "nudge" else "turn"
out.append(f"- opened by telling the assistant that wake {told.get('wake')}'s {which} ended with an error "
f"(the run's note, not the user's words) ({path}:{i})")
elif event == "turn_end":
if line.get("stay_quiet_calls"):
out.append(f"- stayed quiet ({path}:{i})")
Expand All @@ -471,6 +480,11 @@ def _index_block(w: _Wake, path: str, lines: list[dict], by_changes: bool, run_c
f"and the run went on ({path}:{i})")
elif line.get("state") not in (None, "completed", "TaskState.completed"):
out.append(f"- error: its turn ended {line.get('state')} ({path}:{i})")
elif event == "turn_failed":
which = "nudge turn" if line.get("turn") == "nudge" else "turn"
then = "the wake ended there and the run went on" if line.get("went_on") else "the run ended there"
out.append(f"- error: its {which} failed ({line.get('error_code') or line.get('error_type')}); {then} "
f"({path}:{i})")
elif event in ("trajectory_missing", "trajectory_unreadable"):
out.append(f"- error: the {line.get('turn')}'s trajectory is "
f"{'missing' if event == 'trajectory_missing' else 'unreadable'}: its tool calls aren't here "
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -821,6 +821,20 @@ def _not_graded(self, reason: str) -> RubricsVerdict:
if self.writes_mistakes_entry else None)
return RubricsVerdict(skipped=reason, output=self._entry_format_fields(), mistakes_entry=mistakes)

def _judges_failed_run(self, context: TaskStepContext, prompt_response: PromptResponse) -> bool:
"""Whether a prompt response whose agent failed (an ``error_type`` that isn't ``infra_error``) is judged as it
stands rather than scored 0 unjudged (a ``prompt_error`` row): never here, since a prompt_agent turn that
failed left no answer to judge. always_on_agent_verifier judges an always_on run that ended on its agent's own
failure, as a whole."""
return False

def _judges_without_trajectory(self, context: TaskStepContext, prompt_response: PromptResponse) -> bool:
"""Whether a run graded with use_trajectory that stored no trajectory at all is judged all the same, from what
else it recorded, its ``stage_trajectory`` staging the run and saying which turns have none, rather than
refused ("No trajectory available"): never here. always_on_agent_verifier judges so an always_on run whose
turns failed, which can leave it none (a turn agent-env gave up waiting on stores none)."""
return False

def _judge_model(self, context: TaskStepContext) -> str:
"""The model this judge asks for in this run: the run's ``judge_model``, the step's own, then the config's judge
role and default, and claude-sonnet-5-5 last."""
Expand Down Expand Up @@ -1128,7 +1142,7 @@ async def _judged(self, context: TaskStepContext) -> RubricsVerdict:
f"{prompt_response.error_code}), not the assistant's")
logger.warning(f"Not grading '{self.verifier_id}': {reason}")
return self._not_graded(reason)
if prompt_response.error_type:
if prompt_response.error_type and not self._judges_failed_run(context, stored_response):
logger.warning(f"Skipping verification '{self.verifier_id}': prompt had error_type={prompt_response.error_type}")
return self._skipped("prompt_error", f"Skipped: prompt had error_type={prompt_response.error_type}")
run_context = None
Expand All @@ -1140,7 +1154,8 @@ async def _judged(self, context: TaskStepContext) -> RubricsVerdict:
extra_sections = await self.judge_prompt_sections(context, stored_response)

per_turn_uris = [u for u in (prompt_response.target_agent_per_turn_trajectory_object_urls or []) if u]
if self.use_trajectory and not (per_turn_uris or prompt_response.agent_trajectory_object_url):
stored_any = bool(per_turn_uris or prompt_response.agent_trajectory_object_url)
if self.use_trajectory and not stored_any and not self._judges_without_trajectory(context, stored_response):
raise RuntimeError(f"No trajectory available for prompt_id='{self.prompt_id}'")
# A run whose turns are atif/1 copies reads each turn by its label; one with none keeps the native path.
atif = atif_turns(prompt_response) if self.use_trajectory else None
Expand Down Expand Up @@ -1183,7 +1198,7 @@ async def _judged(self, context: TaskStepContext) -> RubricsVerdict:
# Single-file compaction is only needed off the multi-turn path. It reads the trajectory,
# and for the DEFAULT filter writes a compacted copy back, so it runs on a thread.
label_ids = {real: short for short, real in real_by_short.items()}
if multiturn:
if multiturn or not stored_any: # none stored: what stage_trajectory stages is all the judge reads
compacted = _CompactedTrajectory.empty()
elif atif is not None:
compacted = await asyncio.to_thread(self._compact_atif_turn, atif[0], documents, filter_to_apply,
Expand Down Expand Up @@ -1249,6 +1264,8 @@ async def judge_agent() -> _JudgeAgent:
elif one.staged is None and multiturn:
await self._load_per_turn_trajectories(
sandbox, per_turn_uris, multiturn_dir, filter_to_apply, one.container)
elif one.staged is None and not stored_any: # _judges_without_trajectory, but nothing staged
raise RuntimeError(f"No trajectory available for prompt_id='{self.prompt_id}'")
elif one.staged is None:
await sandbox.write_file_from_object(compacted.container_object_url, self.TRAJECTORY_CONTAINER_PATH,
**into_container(one.container))
Expand Down
Loading