From 4e78195cdee30d2c1ba10fb96ed23b919cd2dcc4 Mon Sep 17 00:00:00 2001 From: kaihackney-scale Date: Mon, 23 Nov 2026 11:41:26 -0500 Subject: [PATCH] fix(prompt_agent): a user sim turn that fails keeps the agent's own error A user sim whose task ended failed was recorded as `state failed` alone: the error type and message the agent reported in its status message were dropped, so the cause was gone with the sandbox. prompt_agent's built-in user sim, always_on's and rate_user_satisfaction's now record `state failed: error_type=...: `, read as the solver's failure already is (agent_error_text). Co-Authored-By: Claude Opus 5.5 --- .../task_steps/agent/rate_user_satisfaction.py | 3 ++- src/agent_env/task_step/task_steps/always_on.py | 3 ++- .../task_step/task_steps/prompt_agent.py | 3 ++- .../task_steps/sandbox_utils/sandbox_utils.py | 12 +++++++++++- .../test_prompt_agent_built_in_user_sim.py | 11 ++++++++--- tst/unit/task_step/test_sandbox_utils_logs.py | 16 +++++++++++++++- tst/unit/task_step/test_user_sim_satisfaction.py | 4 ++-- 7 files changed, 42 insertions(+), 10 deletions(-) diff --git a/src/agent_env/task_step/task_steps/agent/rate_user_satisfaction.py b/src/agent_env/task_step/task_steps/agent/rate_user_satisfaction.py index 4930e3172..0576fc0a5 100644 --- a/src/agent_env/task_step/task_steps/agent/rate_user_satisfaction.py +++ b/src/agent_env/task_step/task_steps/agent/rate_user_satisfaction.py @@ -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, @@ -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, diff --git a/src/agent_env/task_step/task_steps/always_on.py b/src/agent_env/task_step/task_steps/always_on.py index d449ecce8..89c551c94 100644 --- a/src/agent_env/task_step/task_steps/always_on.py +++ b/src/agent_env/task_step/task_steps/always_on.py @@ -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, @@ -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: diff --git a/src/agent_env/task_step/task_steps/prompt_agent.py b/src/agent_env/task_step/task_steps/prompt_agent.py index ed9d4d98a..d26f5587d 100644 --- a/src/agent_env/task_step/task_steps/prompt_agent.py +++ b/src/agent_env/task_step/task_steps/prompt_agent.py @@ -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 ( @@ -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, diff --git a/src/agent_env/task_step/task_steps/sandbox_utils/sandbox_utils.py b/src/agent_env/task_step/task_steps/sandbox_utils/sandbox_utils.py index 10149ee41..c8c34f4a6 100644 --- a/src/agent_env/task_step/task_steps/sandbox_utils/sandbox_utils.py +++ b/src/agent_env/task_step/task_steps/sandbox_utils/sandbox_utils.py @@ -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__) @@ -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. diff --git a/tst/unit/task_step/test_prompt_agent_built_in_user_sim.py b/tst/unit/task_step/test_prompt_agent_built_in_user_sim.py index b35933747..a1363a8a1 100644 --- a/tst/unit/task_step/test_prompt_agent_built_in_user_sim.py +++ b/tst/unit/task_step/test_prompt_agent_built_in_user_sim.py @@ -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})) @@ -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]}) diff --git a/tst/unit/task_step/test_sandbox_utils_logs.py b/tst/unit/task_step/test_sandbox_utils_logs.py index 0fc47bbd9..2c0a5177e 100644 --- a/tst/unit/task_step/test_sandbox_utils_logs.py +++ b/tst/unit/task_step/test_sandbox_utils_logs.py @@ -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 @@ -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: @@ -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 diff --git a/tst/unit/task_step/test_user_sim_satisfaction.py b/tst/unit/task_step/test_user_sim_satisfaction.py index 1f1bb6785..dabd24e2a 100644 --- a/tst/unit/task_step/test_user_sim_satisfaction.py +++ b/tst/unit/task_step/test_user_sim_satisfaction.py @@ -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