Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
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, DeployUserSimAgentTaskStep
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 (
ALWAYS_ON_KEY,
ERROR_ENDS,
Expand Down Expand Up @@ -263,7 +264,7 @@ async def _ask(self, agent: DeployedAgent, session: _Session, text: str, deadlin
term = turn.reply
usage.turn(ModelRole.USER_SIMULATOR, term)
if turn.state != TaskState.completed and str(turn.state) != "completed":
return {"text": None, "structured": None, "error": f"state {turn.state}"}
return {"text": None, "structured": None, "error": ended_turn_error(turn.state, term)}
raw = next((p["text"] for p in turn.message.get("parts") or [] if p.get("kind") == "text"), term.response_text)
structured = term.structured_output if isinstance(term.structured_output, dict) else None
return {"text": raw, "structured": structured,
Expand Down
3 changes: 2 additions & 1 deletion src/agent_env/task_step/task_steps/always_on.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@
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, user_sim_model
from agent_env.task_step.task_steps.notification_delivery import delivered_parts, label_time, take_due
from agent_env.task_step.task_steps.sandbox_utils.sandbox_utils import ended_turn_error
from agent_env.task_step.task_steps.prompt_agent import (
PromptAgentTaskStep,
fetch_native_trajectory,
Expand Down Expand Up @@ -1577,7 +1578,7 @@ async def _ask_user_sim(self, text: str, deadline: float) -> dict:
user_task_id, term = turn.task_id, turn.reply
self.usage.turn(ModelRole.USER_SIMULATOR, term)
if turn.state != TaskState.completed and str(turn.state) != "completed":
return {"text": None, "structured": None, "error": f"state {turn.state}"}
return {"text": None, "structured": None, "error": ended_turn_error(turn.state, term)}
raw = next((p["text"] for p in turn.message.get("parts") or [] if p.get("kind") == "text"), term.response_text)
structured = term.structured_output
if structured is None:
Expand Down
3 changes: 2 additions & 1 deletion src/agent_env/task_step/task_steps/prompt_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
from agent_env.task_step.task_steps.agent.user_sim_common import attached, for_agent, opening_text, recorded_opening
from agent_env.task_step.task_steps.sandbox_utils.sandbox_utils import (
agent_error_text,
ended_turn_error,
fetch_container_logs,
)
from agent_env.task_step.snapshot_utils.agent_state_capture import (
Expand Down Expand Up @@ -1196,7 +1197,7 @@ async def _ask_built_in(self, text: str) -> dict:
return {"text": None, "error": f"timeout: {e}"}
self._record_usage(turn.reply)
if turn.state != TaskState.completed:
return {"text": None, "error": f"state {turn.state}"}
return {"text": None, "error": ended_turn_error(turn.state, turn.reply)}
term = turn.reply
raw = next((p["text"] for p in turn.message.get("parts") or [] if p.get("kind") == "text"), term.response_text)
return {"text": raw, "structured": term.structured_output if isinstance(term.structured_output, dict) else None,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
from __future__ import annotations

import logging
from typing import Optional
from typing import Any, Optional

from agent_env.a2a_agent.protocol import TerminalResponse
from agent_env.providers.sandbox_providers.sandbox_provider import build_sandbox_provider, get_sandbox_provider

logger = logging.getLogger(__name__)
Expand All @@ -24,6 +25,15 @@ def agent_error_text(error_message: Optional[str], response_text: Optional[str])
return (error_message or response_text or "")[:_AGENT_ERROR_TEXT_LIMIT]


def ended_turn_error(state: Any, reply: TerminalResponse) -> str:
"""Why an A2A turn ended without completing, for a record: its state, then the agent's own error type and text
(``state failed: error_type=api_error: ...``), so the cause survives the sandbox."""
detail = ", ".join(f"{k}={v}" for k, v in (("error_type", reply.error_type), ("error_code", reply.error_code),
("exception", reply.error_class)) if v)
text = agent_error_text(reply.error_message, reply.response_text)
return ": ".join(part for part in (f"state {state}", detail, text) if part)


async def fetch_container_logs(agent, tail: int = 500) -> Optional[str]:
"""Tail the docker logs of the agent's container, so a failed A2A task stays diagnosable
after its sandbox is reaped.
Expand Down
11 changes: 8 additions & 3 deletions tst/unit/task_step/test_prompt_agent_built_in_user_sim.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@ def said(outcome: str, message: str = "", used: str = "none") -> list[dict]:
return text(json.dumps({"outcome": outcome, "message": message, "used": used}))


# A user sim task that failed as an agent reports it: its error in a data part.
FAILED = ("failed", [{"kind": "data", "data": {"error_type": "api_error", "error_message": "the model was refused"}}])
FAILED_ERROR = "state failed: error_type=api_error: the model was refused"


async def _context(monkeypatch, **deployed) -> TaskStepContext:
"""A run where the real deploy_user_sim_agent step recorded hannah, who answers at USER."""
record = await _published(monkeypatch, _deploy_step(**{"multi_day": False, "opening_prompt": PROMPT, **deployed}))
Expand Down Expand Up @@ -149,18 +154,18 @@ async def test_a_malformed_answer_is_retried_once_in_the_same_session(monkeypatc

@pytest.mark.asyncio
async def test_a_user_sim_turn_that_does_not_complete_ends_the_run_and_is_recorded(monkeypatch):
peers = Peers(monkeypatch, {AGENT: [text("draft one")], USER: [("failed", said("reply", "ignored"))]})
peers = Peers(monkeypatch, {AGENT: [text("draft one")], USER: [FAILED]})
ctx = await _context(monkeypatch)

await _step().execute(ctx)

assert len(peers.requests(ctx)) == 4
assert _reads(ctx)[0]["user_sim_error"] == "state failed"
assert _reads(ctx)[0]["user_sim_error"] == FAILED_ERROR
assert _stored(ctx, peers)["status"] == "closed"


@pytest.mark.asyncio
@pytest.mark.parametrize("user,timeout,error", [(("failed", said("reply", "ignored")), 600, "state failed"),
@pytest.mark.parametrize("user,timeout,error", [(FAILED, 600, FAILED_ERROR),
(HANG, 0, "timeout: ")], ids=["failed", "timeout"])
async def test_a_user_sim_failure_marks_the_run_as_an_error_so_verifiers_skip_it(monkeypatch, user, timeout, error):
Peers(monkeypatch, {AGENT: [text("draft one")], USER: [user]})
Expand Down
16 changes: 15 additions & 1 deletion tst/unit/task_step/test_sandbox_utils_logs.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""fetch_container_logs tails the agent's own container, and agent_error_text bounds the agent's report."""
"""fetch_container_logs tails the agent's own container, agent_error_text bounds the agent's report, and
ended_turn_error says why a turn ended without completing."""

from __future__ import annotations

Expand All @@ -10,8 +11,10 @@
from agent_env.task_step.task_steps.sandbox_utils import sandbox_utils
from agent_env.task_step.task_steps.sandbox_utils.sandbox_utils import (
agent_error_text,
ended_turn_error,
fetch_container_logs,
)
from agent_env.a2a_agent.protocol import TerminalResponse


class FakeSandbox:
Expand Down Expand Up @@ -128,3 +131,14 @@ def test_agent_error_text_prefers_the_error_message():
def test_agent_error_text_is_bounded():
assert len(agent_error_text("e" * 2000, None)) == 2000
assert len(agent_error_text("e" * 2001, None)) == 2000


@pytest.mark.parametrize("reply,expected", [
(TerminalResponse(response_text="", error_type="api_error", error_code="400", error_class="BadRequestError",
error_message="the model was refused"),
"state failed: error_type=api_error, error_code=400, exception=BadRequestError: the model was refused"),
(TerminalResponse(response_text="it broke"), "state failed: it broke"),
(TerminalResponse(response_text=""), "state failed"),
], ids=["full", "text-only", "nothing"])
def test_a_turn_that_ended_without_completing_keeps_the_agents_own_error(reply, expected):
assert ended_turn_error("failed", reply) == expected
4 changes: 2 additions & 2 deletions tst/unit/task_step/test_user_sim_satisfaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -536,13 +536,13 @@ async def test_after_a_prompt_agent_chat_a_malformed_answer_gets_one_retry(monke

@pytest.mark.asyncio
async def test_a_prompt_agent_chat_the_user_sim_broke_is_not_rated(monkeypatch):
peers = Peers(monkeypatch, {AGENT: [text("draft one")], USER: [("failed", said("reply", "x"))]})
peers = Peers(monkeypatch, {AGENT: [text("draft one")], USER: [("failed", [{"kind": "data", "data": {"error_message": "the model was refused"}}])]})
ctx = await _context(monkeypatch)
await _step().execute(ctx)
await _hannah_rater().execute(ctx)
assert len(_user_asks(peers)) == 1
rating = ctx.metadata[SATISFACTION_KEY]["talk"]
assert rating["skipped"] == "the user sim failed: state failed" and rating["score"] is None
assert rating["skipped"] == "the user sim failed: state failed: the model was refused" and rating["score"] is None


@pytest.mark.asyncio
Expand Down
Loading