From 6bbac7d1659ff125f4e430611c1921d7fb63e886 Mon Sep 17 00:00:00 2001 From: t Date: Tue, 10 Nov 2026 11:19:15 -0500 Subject: [PATCH 01/18] feat(prompt_agent): an opt-in gate on user-sim messages prompt_agent's new user_sim_gate checks each LLM user-sim message before the agent receives it: phrase patterns for the assistant's side of a conversation, and optionally a small judge model that decides only whose voice the message is in. A message that fails is held back and the user-sim is asked to rewrite it, up to max_rewrites times; on_fail then fails the step, ends the conversation, or sends it anyway. Every verdict is recorded in context.metadata["user_sim_gate"]. Co-Authored-By: Claude Opus 5.5 --- .../task_step/task_steps/prompt_agent.py | 73 ++++- .../task_step/task_steps/user_sim_gate.py | 256 ++++++++++++++++++ .../task_step/test_prompt_agent_user_side.py | 128 +++++++++ tst/unit/task_step/test_user_sim_gate.py | 71 +++++ 4 files changed, 527 insertions(+), 1 deletion(-) create mode 100644 src/agent_env/task_step/task_steps/user_sim_gate.py create mode 100644 tst/unit/task_step/test_user_sim_gate.py 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 c11fb716b..3bce8bae4 100644 --- a/src/agent_env/task_step/task_steps/prompt_agent.py +++ b/src/agent_env/task_step/task_steps/prompt_agent.py @@ -41,6 +41,7 @@ from agent_env.task_step.task_step import RetryConfig, TaskStep, TaskStepDependency from agent_env.task_step.task_steps.notification_delivery import delivered_parts, next_message, take_due from agent_env.task_step.task_steps.post_turn_hooks import PostTurnHooks, run_post_turn_hooks, validate_hook_specs +from agent_env.task_step.task_steps.user_sim_gate import UserSimGate, rewrite_request from agent_env.task_step.task_steps.sandbox_utils.sandbox_utils import ( agent_error_text, fetch_container_logs, @@ -177,6 +178,7 @@ def __init__( snapshot_config: Optional[SnapshotConfig] = None, live_trajectory: bool = False, post_turn_hooks: Optional[list[dict]] = None, + user_sim_gate: Optional[UserSimGate | dict] = None, ): # `prompt` is the legacy text-only field; `parts` is the multimodal # form that's the authoritative A2A wire shape. Exactly one must be set: @@ -223,6 +225,10 @@ def __init__( self.snapshot_config = snapshot_config self.live_trajectory = live_trajectory self.post_turn_hooks = post_turn_hooks + # Checks each user-sim message before the agent gets it (user_sim_gate.py). A dict is accepted + # too, as JSON task files and the kwargs form of put() carry it. + self.user_sim_gate = (UserSimGate.from_dict(user_sim_gate) if isinstance(user_sim_gate, dict) + else user_sim_gate) @staticmethod def _validate_parts(parts: list[dict]) -> None: @@ -300,6 +306,8 @@ def to_dict(self) -> dict: base["live_trajectory"] = True if self.post_turn_hooks is not None: base["post_turn_hooks"] = self.post_turn_hooks + if self.user_sim_gate is not None: + base["user_sim_gate"] = self.user_sim_gate.to_dict() return base @classmethod @@ -337,6 +345,7 @@ def from_dict(cls, data: dict) -> PromptAgentTaskStep: ), live_trajectory=data.get("live_trajectory", False), post_turn_hooks=data.get("post_turn_hooks"), + user_sim_gate=data.get("user_sim_gate"), ) def _trajectory_prefix(self) -> str: @@ -574,7 +583,11 @@ async def _converse( self, context, url=user_url, user_sim=user_sim, is_user_sim=is_user_sim, conversation_id=conversation_id, decide_url=decide_url, shareable=sent_to_target, decides_quietly=card_request_accepts(decide_method.get("request") or {}, _QUIET_DECIDE), + opening_text="\n".join(p.get("text", "") for p in initial_parts if p.get("kind") == "text"), ) + if self.user_sim_gate is not None and not is_user_sim: + logger.warning(f"prompt_agent '{self.id}': user_sim_gate is set but the user side isn't a user-sim " + "agent-env deployed; no message is checked") try: for turn in range(self.max_conversation_turns): @@ -764,6 +777,9 @@ def record_turn() -> None: structured_output=structured_output, )) + if user_side.gate_failure is not None: + raise RuntimeError(f"user_sim_gate: {user_side.gate_failure}") + if final_state == TaskState.failed: detail_parts = [] if final_terminal.error_type: @@ -1031,7 +1047,8 @@ class _UserSide: def __init__(self, step: PromptAgentTaskStep, context: TaskStepContext, *, url: Optional[str], user_sim: Optional[DeployedAgent], is_user_sim: bool, conversation_id: str, - decide_url: Optional[str], decides_quietly: bool, shareable: set[str]) -> None: + decide_url: Optional[str], decides_quietly: bool, shareable: set[str], + opening_text: str = "") -> None: self._step = step self._context = context self._url = url @@ -1041,9 +1058,23 @@ def __init__(self, step: PromptAgentTaskStep, context: TaskStepContext, *, url: self._decide_url = decide_url self._decides_quietly = decides_quietly self._shareable = shareable + # The conversation as the user-sim gate reads it: (role, text), role "user" or "assistant". + self._history: list[tuple[str, str]] = [("user", opening_text)] if opening_text else [] + self._gate = step.user_sim_gate if is_user_sim else None + self._gate_call_config = None + # Set once a user-sim message fails the gate after its rewrites, with on_fail "fail". + self.gate_failure: Optional[str] = None async def ask(self, number: int, solver_message: str, agent_parts: list[dict]) -> dict: """The user side's answer: ``{"message": parts}``, or ``{"end": reason}`` with any closing message to record.""" + self._history.append(("assistant", solver_message or "")) + answer = await self._answer(number, agent_parts, solver_message) + if "message" in answer and "end" not in answer: + self._history.append(("user", "\n".join(p.get("text", "") for p in answer["message"] + if p.get("kind") == "text"))) + return answer + + async def _answer(self, number: int, agent_parts: list[dict], solver_message: str) -> dict: if self._decide_url is not None: env_triggers = await self._step._read_env_triggers(self._context) self._record("env_trigger_snapshots", {"turn": number, "envs": env_triggers}) @@ -1076,6 +1107,46 @@ async def triggers(self, number: int, solver_message: str) -> Optional[dict]: return answer async def _ask_peer(self, number: int, agent_parts: list[dict]) -> dict: + answer = await self._send_to_peer(number, agent_parts) + if self._gate is None or "end" in answer: + return answer + return await self._gated(number, answer) + + async def _gated(self, number: int, answer: dict) -> dict: + """Check the user-sim's message; ask for a rewrite while it fails, up to the gate's limit.""" + gate = self._gate + if self._gate_call_config is None and gate.judge_model: + config = get_config() + overrides = self._context.metadata.get("user_overrides", {}) + self._gate_call_config = config.resolve_model_call( + gate.judge_model, + default_api_key=config.resolve_reference( + overrides.get("judge_litellm_api_key") or overrides.get("litellm_api_key")), + base_override=overrides.get("judge_litellm_base_url") or overrides.get("litellm_base_url"), + ) + for attempt in range(gate.max_rewrites + 1): + text = "\n".join(p.get("text", "") for p in answer["message"] if p.get("kind") == "text") + verdict = await gate.check(text, self._history, call_config=self._gate_call_config) + self._record("user_sim_gate", {"turn": number, "attempt": attempt, "chars": len(text), **verdict.to_dict()}) + if verdict.passed: + return answer + logger.warning(f"Turn {number}: user-sim message failed the gate (attempt {attempt + 1}/" + f"{gate.max_rewrites + 1}): {'; '.join(verdict.reasons())[:300]}") + if attempt == gate.max_rewrites: + break + answer = await self._send_to_peer(number, [{"kind": "text", "text": rewrite_request(verdict)}]) + if "end" in answer: + return answer + if gate.on_fail == "send": + return answer + self._context.metadata.setdefault("user_sim_invalid", {})[self._step.id] = { + "turn": number, "reasons": verdict.reasons()} + if gate.on_fail == "fail": + self.gate_failure = (f"user-sim message at turn {number} still reads as the assistant's after " + f"{gate.max_rewrites} rewrite(s): {'; '.join(verdict.reasons())[:500]}") + return {"end": "user_sim_invalid"} + + async def _send_to_peer(self, number: int, agent_parts: list[dict]) -> dict: step = self._step if self._url is None: self._url = get_config().get_default_human_a2a_url() diff --git a/src/agent_env/task_step/task_steps/user_sim_gate.py b/src/agent_env/task_step/task_steps/user_sim_gate.py new file mode 100644 index 000000000..93880ce55 --- /dev/null +++ b/src/agent_env/task_step/task_steps/user_sim_gate.py @@ -0,0 +1,256 @@ +"""A check on every simulated-user message before prompt_agent sends it to the agent. + +An LLM playing the user can slip into the assistant's role: it answers its own question, reports work as +done, or offers to do the agent's job. Once one such message is in the conversation the rest of the run +is no longer a test of the agent. The gate checks each user-sim message, asks the user-sim to rewrite one +that fails, and, if the rewrites fail too, ends the conversation and marks the run. + +Two checks, either of which can fail a message: + +- ``patterns``: phrases and shapes that belong to the assistant's side (a report of work done, a + formatted deliverable, offers to do the work). Free, and deliberately narrow. +- ``judge_model``: one model call that reads the last turns and the candidate message and says whether + the message is written as the user. + +Opt in with ``user_sim_gate`` on a ``prompt_agent`` step that has a user-sim:: + + {"judge_model": "", "max_rewrites": 2, "on_fail": "fail"} +""" +from __future__ import annotations + +import json +import logging +import re +from dataclasses import asdict, dataclass, field +from typing import Optional + +logger = logging.getLogger(__name__) + +ON_FAIL = ("fail", "end", "send") + +# ── Patterns ────────────────────────────────────────────────────────────────────────────────────────── + +_REPORT_OPENING = re.compile( + r"^\s*(?:\*\*)?(?:done\b|all done|checked\b|short (?:answer|version)\b" + r"|here'?s (?:what (?:i|we) (?:found|did|checked|changed)|the (?:full |short |whole )?(?:picture|summary|breakdown" + r"|rundown|update|status)|where (?:things|we|it|you) stands?|how (?:it|things) (?:stands?|looks?))" + r"|summary\b|update:|findings\b|tl;?dr\b)", + re.I, +) +_WORK_DONE = re.compile( + r"\bI(?:'ve| have)? (?:checked|reviewed|pulled|updated|put together|drafted|flagged|verified|" + r"cross-checked|went through|compared|audited|analy[sz]ed|reconciled|fixed|created|added|" + r"rewrote|built|calculated|ran)\b", + re.I, +) +_NOW_LIVE = re.compile(r"\b(?:now live|is now (?:up|live|updated)|has been (?:updated|created|sent|posted))\b", re.I) +_DELIVERED = re.compile( + r"\b(?:(?:emails?|messages?|drafts?|replies|invites?|notes?) (?:sent|drafted|posted|scheduled)\b|incorporated\b|" + r"(?:the|a|my) (?:cleaner|updated|revised|corrected|final) version\b)", + re.I, +) +_AS_ASSISTANT = re.compile( + r"\b(?:as an ai|i'?m an? (?:ai|assistant|language model)|my previous (?:answer|response|reply)|" + r"i apologi[sz]e for (?:the|my)|let me know if you'?d like me to|" + r"would you like me to|want me to (?:draft|send|update|create|go ahead)|" + r"standing by|ready when you are|parked until|" + r"anything else (?:you(?:'d)? (?:want|like) (?:me )?to|to (?:cover|look at|dig into))|" + r"what do you want (?:me )?to do next|should i (?:send|draft|go ahead)|" + r"i'll (?:draft|fold|pull|search|put together|pick (?:it |this )?up|rerun|re-run)|" + r"i can (?:send|draft|search|pull) (?:it|that|them)|" + r"i (?:don't|do not) have (?:the )?(?:tools|access)|corrections (?:noted|taken)|" + r"(?:send|drop) me (?:whatever|that phrase|the results)|" + r"how (?:can|may) i (?:help|assist)|i'?m (?:here|ready) to help|what would you like (?:me )?to (?:work on|do) today)\b", + re.I, +) +_TABLE = re.compile(r"^\s*\|?\s*:?-{3,}:?\s*\|", re.M) +_HEADER = re.compile(r"^\s*#{1,4} \S", re.M) +_BOLD_BULLET = re.compile(r"^\s*(?:[-*•]|\d+\.)\s+\*\*", re.M) + + +def pattern_reasons(text: str) -> list[str]: + """Why ``text`` reads as the assistant's message, one reason per pattern that matched; empty if none.""" + reasons = [] + n = len(text) + if _AS_ASSISTANT.search(text): + reasons.append("it talks like the assistant (offers to do the work, waits on the user, or speaks as the AI)") + if _REPORT_OPENING.search(text) and n > 300: + reasons.append("it opens like a report of work done") + if _NOW_LIVE.search(text): + reasons.append("it says something is now live or updated") + if _DELIVERED.search(text) and n > 300: + reasons.append("it reports something delivered or revised") + if (_TABLE.search(text) or len(_HEADER.findall(text)) >= 2 or len(_BOLD_BULLET.findall(text)) >= 3) and n > 600: + reasons.append("it is a formatted deliverable (a table, headings or bold bullet points)") + work = _WORK_DONE.findall(text) + if work and (n > 500 or len(work) >= 2): + reasons.append("it reports checking or building things itself") + return reasons + + +# ── Judge ───────────────────────────────────────────────────────────────────────────────────────────── + +_JUDGE_PROMPT = """You check one message in a test conversation. A model is playing a USER who gave an AI ASSISTANT \ +a task. The assistant does the work; the user asks, answers questions the assistant put to them, decides, approves, \ +pushes back, or ends the conversation. + +Decide whether the CANDIDATE message is written as the user. It is NOT written as the user when it does the \ +assistant's job: it answers the question the user should be asking, reports work as done or findings it produced \ +("Done. Here's what I found", "I've updated the page"), presents analysis or a deliverable, apologizes for "my \ +previous answer", offers to do work ("I'll draft it", "Standing by", "Want me to send it?"), or speaks as the AI. + +It IS written as the user when it asks, instructs, approves, pushes back, answers a question the assistant asked, \ +or shares the user's own knowledge, even if it is long, formatted, quotes the assistant's numbers, or pastes an \ +email or document. Length and markdown alone are not evidence. + +Judge only whose voice the message is in. A user message that repeats an earlier one, ignores or contradicts what \ +the assistant said, states a decision or a fact the user holds, or seems off topic is still written as the user. + +CONVERSATION SO FAR (most recent last): +{history} + +CANDIDATE (the user's next message): +<<< +{candidate} +>>> + +Answer in JSON: {{"in_role": true or false, "reason": "one sentence citing the candidate"}}""" + +_JUDGE_SCHEMA = { + "type": "object", + "properties": {"in_role": {"type": "boolean"}, "reason": {"type": "string"}}, + "required": ["in_role", "reason"], + "additionalProperties": False, +} + + +def render_history(history: list[tuple[str, str]], turns: int, max_chars: int) -> str: + """The last ``turns`` messages as ``USER:`` / ``ASSISTANT:`` blocks, each cut to ``max_chars``.""" + out = [] + for role, text in history[-turns:]: + body = text if len(text) <= max_chars else text[:max_chars] + f"\n[… {len(text) - max_chars} more characters]" + out.append(f"{role.upper()}:\n{body}") + return "\n\n".join(out) or "(nothing yet)" + + +def parse_judge(content: str) -> Optional[dict]: + """The judge's JSON object, tolerating text around it; None if there's none with a boolean ``in_role``.""" + start = content.find("{") + if start < 0: + return None + try: + obj = json.JSONDecoder().raw_decode(content[start:])[0] + except ValueError: + return None + return obj if isinstance(obj, dict) and isinstance(obj.get("in_role"), bool) else None + + +# ── The gate ────────────────────────────────────────────────────────────────────────────────────────── + +@dataclass +class UserSimGate: + """How ``prompt_agent`` checks user-sim messages; see the module docstring.""" + + patterns: bool = True + judge_model: Optional[str] = None + max_rewrites: int = 2 + # What happens when a message still fails after its rewrites: "fail" ends the conversation and fails the + # step, "end" ends the conversation and lets the step finish, "send" sends it anyway (record only). + on_fail: str = "fail" + context_turns: int = 4 + # The judge alone fails only a message at least this long; a shorter one also needs a pattern. Swaps are long or + # match a pattern, and without the scenario the judge misreads short scripted answers that correct the agent. + judge_min_chars: int = 300 + context_chars: int = 3000 + judge_timeout_seconds: float = 60 + + def __post_init__(self) -> None: + if self.on_fail not in ON_FAIL: + raise ValueError(f"user_sim_gate.on_fail must be one of {ON_FAIL}, not {self.on_fail!r}") + if self.max_rewrites < 0: + raise ValueError("user_sim_gate.max_rewrites must be >= 0") + if not self.patterns and not self.judge_model: + raise ValueError("user_sim_gate needs patterns, a judge_model, or both") + + @classmethod + def from_dict(cls, data: Optional[dict]) -> Optional[UserSimGate]: + if not data: + return None + known = set(cls.__dataclass_fields__) + unknown = set(data) - known + if unknown: + raise ValueError(f"user_sim_gate: unknown keys {sorted(unknown)}") + return cls(**data) + + def to_dict(self) -> dict: + return asdict(self) + + async def check(self, candidate: str, history: list[tuple[str, str]], *, call_config=None) -> GateVerdict: + """Check one message. ``history`` is the conversation so far as ``(role, text)``, role user/assistant. + A judge call that errors or can't be parsed doesn't fail the message: the patterns' verdict stands.""" + reasons = pattern_reasons(candidate) if self.patterns else [] + verdict = GateVerdict(passed=not reasons, pattern_reasons=reasons) + if self.judge_model: + try: + judged = await self._judge(candidate, history, call_config) + except Exception as e: # the judge is a second opinion; never let it take the conversation down + logger.warning(f"user-sim gate judge call failed ({type(e).__name__}: {e}); using patterns only") + verdict.judge_error = f"{type(e).__name__}: {e}"[:300] + return verdict + if judged is None: + verdict.judge_error = "unparseable judge output" + return verdict + verdict.judge_in_role = judged["in_role"] + verdict.judge_reason = str(judged.get("reason", ""))[:500] + if not judged["in_role"] and (reasons or len(candidate) >= self.judge_min_chars): + verdict.passed = False + return verdict + + async def _judge(self, candidate: str, history: list[tuple[str, str]], call_config) -> Optional[dict]: + import litellm + + from agent_env.config.model import ModelParam + + prompt = _JUDGE_PROMPT.format( + history=render_history(history, self.context_turns, self.context_chars), + candidate=candidate[: self.context_chars * 2], + ) + response = await litellm.acompletion( + model=self.judge_model, + messages=[{"role": "user", "content": prompt}], + timeout=self.judge_timeout_seconds, + **{ModelParam.RESPONSE_FORMAT: {"type": "json_schema", + "json_schema": {"name": "user_sim_gate", "schema": _JUDGE_SCHEMA, + "strict": True}}}, + **(call_config.client_kwargs() if call_config is not None else {}), + ) + return parse_judge(response.choices[0].message.content or "") + + +@dataclass +class GateVerdict: + passed: bool + pattern_reasons: list[str] = field(default_factory=list) + judge_in_role: Optional[bool] = None + judge_reason: Optional[str] = None + judge_error: Optional[str] = None + + def reasons(self) -> list[str]: + out = list(self.pattern_reasons) + if self.judge_in_role is False and self.judge_reason: + out.append(self.judge_reason) + return out + + def to_dict(self) -> dict: + return {k: v for k, v in asdict(self).items() if v not in (None, [])} + + +def rewrite_request(verdict: GateVerdict) -> str: + """What the user-sim is told when its message was held back.""" + why = "; ".join(verdict.reasons()) or "it reads as the assistant's message" + return ( + "[Conversation system note, not from the assistant.] Your last message was not sent to the assistant, " + f"because it reads as the assistant's reply rather than yours: {why}. You are the user. The assistant does " + "the work and reports it; you ask, answer what you were asked, decide, push back, or end. Write your next " + "message to the assistant again, as yourself, in the same reply format as before." + ) diff --git a/tst/unit/task_step/test_prompt_agent_user_side.py b/tst/unit/task_step/test_prompt_agent_user_side.py index 0aba179a8..971bef3c8 100644 --- a/tst/unit/task_step/test_prompt_agent_user_side.py +++ b/tst/unit/task_step/test_prompt_agent_user_side.py @@ -479,3 +479,131 @@ async def test_with_no_user_agent_the_configured_human_peer_answers(monkeypatch) *exchange(HUMAN, text("one"), "", "", "task-2"), *exchange(AGENT, text("go on"), "", "", "task-3"), ] + + +# ---- the user-sim gate ---------------------------------------------------------------------------------------------- + +_SWAP = ("Done. Here's what I found when I checked the figures against the records:\n\n" + "| Metric | Reported | Actual |\n|---|---|---|\n| Installs | 1,400 | 901 |\n| Retention | 43% | 25% |\n\n" + "None of the three reported numbers hold up, and I've updated the summary page to say so. " * 2) + + +_TAKEOVER = "I'll handle the rest of it from here, so there's no need for you to keep going on this. " * 4 + + +def _gated(turns: int = 2, **gate) -> PromptAgentTaskStep: + return _step(turns=turns, user_agent_name="human_agent", user_sim_gate={"patterns": True, **gate}) + + +@pytest.mark.asyncio +async def test_the_gate_lets_a_user_message_through_and_records_its_verdict(monkeypatch): + peers = Peers(monkeypatch, {AGENT: [text("draft one"), text("draft two")], USER: [sim("make it shorter")]}) + ctx = _context(user_card=_USER_SIM_CARD) + + await _gated().execute(ctx) + + assert peers.requests(ctx)[-2] == send(AGENT, text("make it shorter"), "", "") + assert ctx.metadata["user_sim_gate"] == {"talk": [{"turn": 1, "attempt": 0, "chars": 15, "passed": True}]} + assert "user_sim_invalid" not in ctx.metadata + + +@pytest.mark.asyncio +async def test_a_message_that_reads_as_the_assistants_is_held_back_and_rewritten(monkeypatch): + peers = Peers(monkeypatch, {AGENT: [text("draft one"), text("draft two")], + USER: [sim(_SWAP), sim("do those numbers hold up?")]}) + ctx = _context(user_card=_USER_SIM_CARD) + + await _gated().execute(ctx) + + sent = [r for r in peers.requests(ctx) if r[2] and r[2].get("method") == "message/send"] + to_user = [r[2]["params"]["message"]["parts"][0]["text"] for r in sent if r[1].startswith(USER)] + to_agent = [r[2]["params"]["message"]["parts"] for r in sent if r[1].startswith(AGENT)] + assert to_user[0] == "draft one" + assert to_user[1].startswith("[Conversation system note, not from the assistant.] Your last message was not sent") + assert to_agent == [text("plan my week"), text("do those numbers hold up?")] # the swap never reached it + verdicts = ctx.metadata["user_sim_gate"]["talk"] + assert [(v["attempt"], v["passed"]) for v in verdicts] == [(0, False), (1, True)] + assert "it opens like a report of work done" in verdicts[0]["pattern_reasons"] + + +@pytest.mark.asyncio +async def test_a_message_that_still_fails_after_its_rewrites_ends_the_run_and_fails_the_step(monkeypatch): + peers = Peers(monkeypatch, {AGENT: [text("draft one")], USER: [sim(_SWAP), sim(_SWAP), sim(_SWAP)]}) + ctx = _context(user_card=_USER_SIM_CARD) + + with pytest.raises(RuntimeError, match=r"user_sim_gate: user-sim message at turn 1 still reads as the assistant's"): + await _gated(turns=3).execute(ctx) + + assert [v["passed"] for v in ctx.metadata["user_sim_gate"]["talk"]] == [False, False, False] + assert ctx.metadata["user_sim_invalid"]["talk"]["turn"] == 1 + assert _stored(ctx, peers)["status"] == "closed" + assert [m["role"] for m in _stored(ctx, peers)["messages"]] == ["user", "agent"] # nothing more was sent + assert ctx.prompt_responses[-1].response == "draft one" # the run kept its record + + +@pytest.mark.asyncio +async def test_on_fail_end_closes_the_conversation_without_failing_the_step(monkeypatch): + Peers(monkeypatch, {AGENT: [text("draft one")], USER: [sim(_SWAP), sim(_SWAP)]}) + ctx = _context(user_card=_USER_SIM_CARD) + + await _gated(turns=3, max_rewrites=1, on_fail="end").execute(ctx) + + assert ctx.metadata["user_sim_invalid"]["talk"]["turn"] == 1 + assert len(ctx.metadata["user_sim_gate"]["talk"]) == 2 + + +@pytest.mark.asyncio +async def test_the_judge_fails_a_message_the_patterns_pass_and_sees_the_conversation(monkeypatch): + from agent_env.task_step.task_steps import user_sim_gate + + seen = [] + + async def judge(self, candidate, history, call_config): + seen.append((candidate, list(history))) + return {"in_role": candidate != _TAKEOVER, "reason": "it offers to do the work"} + + monkeypatch.setattr(user_sim_gate.UserSimGate, "_judge", judge) + Peers(monkeypatch, {AGENT: [text("draft one"), text("draft two")], + USER: [sim(_TAKEOVER), sim("shorter, please")]}) + ctx = _context(user_card=_USER_SIM_CARD) + monkeypatch.setattr("agent_env.config.Config.resolve_model_call", lambda self, model, **kw: None, raising=False) + + await _gated(judge_model="judge-model").execute(ctx) + + verdicts = ctx.metadata["user_sim_gate"]["talk"] + assert [(v["passed"], v.get("judge_in_role")) for v in verdicts] == [(False, False), (True, True)] + assert verdicts[0]["judge_reason"] == "it offers to do the work" + assert seen[0][1] == [("user", "plan my week"), ("assistant", "draft one")] + + +@pytest.mark.asyncio +async def test_a_judge_that_errors_leaves_the_patterns_verdict(monkeypatch): + from agent_env.task_step.task_steps import user_sim_gate + + async def judge(self, candidate, history, call_config): + raise TimeoutError("judge timed out") + + monkeypatch.setattr(user_sim_gate.UserSimGate, "_judge", judge) + Peers(monkeypatch, {AGENT: [text("draft one"), text("draft two")], USER: [sim("shorter, please")]}) + ctx = _context(user_card=_USER_SIM_CARD) + monkeypatch.setattr("agent_env.config.Config.resolve_model_call", lambda self, model, **kw: None, raising=False) + + await _gated(judge_model="judge-model").execute(ctx) + + (verdict,) = ctx.metadata["user_sim_gate"]["talk"] + assert verdict["passed"] is True + assert verdict["judge_error"] == "TimeoutError: judge timed out" + + +def test_the_gate_round_trips_through_the_step_dict_and_rejects_bad_settings(): + step = _gated(judge_model="judge-model", max_rewrites=1) + again = PromptAgentTaskStep.from_dict(step.to_dict()) + assert again.user_sim_gate == step.user_sim_gate + assert again.user_sim_gate.max_rewrites == 1 + assert "user_sim_gate" not in _step().to_dict() + with pytest.raises(ValueError, match="unknown keys"): + _step(user_sim_gate={"judge": "x"}) + with pytest.raises(ValueError, match="on_fail"): + _step(user_sim_gate={"on_fail": "retry"}) + with pytest.raises(ValueError, match="needs patterns"): + _step(user_sim_gate={"patterns": False}) diff --git a/tst/unit/task_step/test_user_sim_gate.py b/tst/unit/task_step/test_user_sim_gate.py new file mode 100644 index 000000000..fca748ad4 --- /dev/null +++ b/tst/unit/task_step/test_user_sim_gate.py @@ -0,0 +1,71 @@ +"""The user-sim gate's own checks: the patterns, the judge's output parsing and the history it is shown.""" + +from agent_env.task_step.task_steps.user_sim_gate import ( + GateVerdict, parse_judge, pattern_reasons, render_history, rewrite_request) + +_FILLER = " The details are in the shared folder and the numbers come from last month's records." * 6 + + +def test_the_patterns_pass_what_users_write(): + for message in [ + "and the numbers she gave the board, do those hold up?", + "ok. who actually worked on it, and what does each of them cost per month?", + "Here's the email my manager sent, pasted so you have it:\n\n> Please hold the order until Friday." + _FILLER, + "No, go ahead and send it. Use the second draft.", + "I checked my inbox and there's nothing from them yet.", + ]: + assert pattern_reasons(message) == [], message + + +def test_the_patterns_catch_the_assistants_side(): + cases = { + "Done. Here's what I found when I went through the files." + _FILLER: "it opens like a report of work done", + "Here's where things stand after the changes." + _FILLER: "it opens like a report of work done", + "Understood. Standing by.": "it talks like the assistant", + "Want me to draft the reply to them now?": "it talks like the assistant", + "I'm ready to help! What would you like to work on today?": "it talks like the assistant", + "The page is now live, with the corrected totals." : "it says something is now live or updated", + "Thanks for those corrections, incorporated. The cleaner version:" + _FILLER: "it reports something delivered", + "| Item | Was | Is |\n|---|---|---|\n| A | 1 | 2 |\n" + _FILLER * 2: "it is a formatted deliverable", + "I've reviewed the contract and I've compared it with the invoice." + _FILLER: "it reports checking or building", + } + for message, expected in cases.items(): + reasons = pattern_reasons(message) + assert any(r.startswith(expected) for r in reasons), (message[:60], reasons) + + +def test_the_judge_output_is_read_through_surrounding_text_and_rejected_without_a_boolean(): + assert parse_judge('{"in_role": false, "reason": "reports work"}') == {"in_role": False, "reason": "reports work"} + assert parse_judge('Sure.\n{"in_role": true, "reason": "asks"} trailing') == {"in_role": True, "reason": "asks"} + assert parse_judge('{"in_role": "no"}') is None + assert parse_judge("no json here") is None + + +def test_the_history_shows_the_last_turns_each_cut_to_size(): + history = [("user", "first"), ("assistant", "x" * 50), ("user", "second"), ("assistant", "third")] + shown = render_history(history, turns=3, max_chars=10) + assert shown.startswith("ASSISTANT:\nxxxxxxxxxx\n[… 40 more characters]") + assert "first" not in shown and shown.endswith("ASSISTANT:\nthird") + assert render_history([], turns=4, max_chars=10) == "(nothing yet)" + + +def test_the_rewrite_request_names_why_and_says_it_is_not_from_the_assistant(): + note = rewrite_request(GateVerdict(passed=False, pattern_reasons=["it opens like a report of work done"], + judge_in_role=False, judge_reason="it answers its own question")) + assert note.startswith("[Conversation system note, not from the assistant.]") + assert "it opens like a report of work done; it answers its own question" in note + + +def test_the_judge_alone_fails_only_a_long_message(): + import asyncio + from agent_env.task_step.task_steps.user_sim_gate import UserSimGate + + class Gate(UserSimGate): + async def _judge(self, candidate, history, call_config): + return {"in_role": False, "reason": "reads as analysis"} + + gate = Gate(judge_model="judge-model") + short = asyncio.run(gate.check("Contracted physicians are required in two states.", [])) + long = asyncio.run(gate.check("The two states that need contracted physicians are these." + _FILLER, [])) + assert (short.passed, short.judge_in_role) == (True, False) # recorded, not failed + assert long.passed is False From fcec1e1184a2140bde141cb86888b29ef6aa3676 Mon Sep 17 00:00:00 2001 From: t Date: Tue, 10 Nov 2026 12:43:00 -0500 Subject: [PATCH 02/18] fix(prompt_agent): empty user_sim_gate settings turn the gate on; name its cutoffs `user_sim_gate={}` now enables the gate with its defaults; only None leaves it off. The patterns' length and count cutoffs, and how much of a judge's reason and error a verdict keeps, are named class constants. Co-Authored-By: Claude Opus 5.5 --- .../task_step/task_steps/user_sim_gate.py | 38 +++++++++++++++---- .../task_step/test_prompt_agent_user_side.py | 2 + 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/src/agent_env/task_step/task_steps/user_sim_gate.py b/src/agent_env/task_step/task_steps/user_sim_gate.py index 93880ce55..a4807ac82 100644 --- a/src/agent_env/task_step/task_steps/user_sim_gate.py +++ b/src/agent_env/task_step/task_steps/user_sim_gate.py @@ -22,7 +22,7 @@ import logging import re from dataclasses import asdict, dataclass, field -from typing import Optional +from typing import ClassVar, Optional logger = logging.getLogger(__name__) @@ -68,22 +68,39 @@ _BOLD_BULLET = re.compile(r"^\s*(?:[-*•]|\d+\.)\s+\*\*", re.M) +class PatternLimits: + """How long or how formatted a message must be before a shape-based pattern counts. Phrases that only the + assistant says (offers, "standing by", "now live") count at any length; shapes a user can also write (an + opening like "Done.", a table, "I checked") count only on a message long enough to be a report.""" + + REPORT_OPENING_MIN_CHARS: ClassVar[int] = 300 + DELIVERED_MIN_CHARS: ClassVar[int] = 300 + FORMATTED_MIN_CHARS: ClassVar[int] = 600 + FORMATTED_MIN_HEADERS: ClassVar[int] = 2 + FORMATTED_MIN_BOLD_BULLETS: ClassVar[int] = 3 + WORK_REPORT_MIN_CHARS: ClassVar[int] = 500 + WORK_REPORT_MIN_PHRASES: ClassVar[int] = 2 + + def pattern_reasons(text: str) -> list[str]: """Why ``text`` reads as the assistant's message, one reason per pattern that matched; empty if none.""" + lim = PatternLimits reasons = [] n = len(text) if _AS_ASSISTANT.search(text): reasons.append("it talks like the assistant (offers to do the work, waits on the user, or speaks as the AI)") - if _REPORT_OPENING.search(text) and n > 300: + if _REPORT_OPENING.search(text) and n > lim.REPORT_OPENING_MIN_CHARS: reasons.append("it opens like a report of work done") if _NOW_LIVE.search(text): reasons.append("it says something is now live or updated") - if _DELIVERED.search(text) and n > 300: + if _DELIVERED.search(text) and n > lim.DELIVERED_MIN_CHARS: reasons.append("it reports something delivered or revised") - if (_TABLE.search(text) or len(_HEADER.findall(text)) >= 2 or len(_BOLD_BULLET.findall(text)) >= 3) and n > 600: + formatted = (_TABLE.search(text) or len(_HEADER.findall(text)) >= lim.FORMATTED_MIN_HEADERS + or len(_BOLD_BULLET.findall(text)) >= lim.FORMATTED_MIN_BOLD_BULLETS) + if formatted and n > lim.FORMATTED_MIN_CHARS: reasons.append("it is a formatted deliverable (a table, headings or bold bullet points)") work = _WORK_DONE.findall(text) - if work and (n > 500 or len(work) >= 2): + if work and (n > lim.WORK_REPORT_MIN_CHARS or len(work) >= lim.WORK_REPORT_MIN_PHRASES): reasons.append("it reports checking or building things itself") return reasons @@ -164,6 +181,10 @@ class UserSimGate: context_chars: int = 3000 judge_timeout_seconds: float = 60 + # How much of a judge error and of the judge's reason a verdict keeps. + RECORDED_ERROR_CHARS: ClassVar[int] = 300 + RECORDED_REASON_CHARS: ClassVar[int] = 500 + def __post_init__(self) -> None: if self.on_fail not in ON_FAIL: raise ValueError(f"user_sim_gate.on_fail must be one of {ON_FAIL}, not {self.on_fail!r}") @@ -174,7 +195,8 @@ def __post_init__(self) -> None: @classmethod def from_dict(cls, data: Optional[dict]) -> Optional[UserSimGate]: - if not data: + """None (no gate) for None; the defaults for {}, as for ``UserSimGate()``.""" + if data is None: return None known = set(cls.__dataclass_fields__) unknown = set(data) - known @@ -195,13 +217,13 @@ async def check(self, candidate: str, history: list[tuple[str, str]], *, call_co judged = await self._judge(candidate, history, call_config) except Exception as e: # the judge is a second opinion; never let it take the conversation down logger.warning(f"user-sim gate judge call failed ({type(e).__name__}: {e}); using patterns only") - verdict.judge_error = f"{type(e).__name__}: {e}"[:300] + verdict.judge_error = f"{type(e).__name__}: {e}"[: self.RECORDED_ERROR_CHARS] return verdict if judged is None: verdict.judge_error = "unparseable judge output" return verdict verdict.judge_in_role = judged["in_role"] - verdict.judge_reason = str(judged.get("reason", ""))[:500] + verdict.judge_reason = str(judged.get("reason", ""))[: self.RECORDED_REASON_CHARS] if not judged["in_role"] and (reasons or len(candidate) >= self.judge_min_chars): verdict.passed = False return verdict diff --git a/tst/unit/task_step/test_prompt_agent_user_side.py b/tst/unit/task_step/test_prompt_agent_user_side.py index 971bef3c8..a18ccb134 100644 --- a/tst/unit/task_step/test_prompt_agent_user_side.py +++ b/tst/unit/task_step/test_prompt_agent_user_side.py @@ -601,6 +601,8 @@ def test_the_gate_round_trips_through_the_step_dict_and_rejects_bad_settings(): assert again.user_sim_gate == step.user_sim_gate assert again.user_sim_gate.max_rewrites == 1 assert "user_sim_gate" not in _step().to_dict() + defaults = _step(user_sim_gate={}).user_sim_gate # empty settings turn the gate on with its defaults + assert defaults is not None and defaults.patterns and defaults.judge_model is None and defaults.max_rewrites == 2 with pytest.raises(ValueError, match="unknown keys"): _step(user_sim_gate={"judge": "x"}) with pytest.raises(ValueError, match="on_fail"): From e63d512fe64d116dd196b06c913aa07b40f51efd Mon Sep 17 00:00:00 2001 From: t Date: Tue, 10 Nov 2026 13:52:41 -0500 Subject: [PATCH 03/18] feat(prompt_agent): run_gate for any conversation loop; refuse the gate where it would be ignored The check-and-rewrite loop moves to user_sim_gate.run_gate, with a rewrite callback, so a step type that runs its own conversation can apply the gate; prompt_agent's user side now calls it. A PromptAgentTaskStep subclass that replaces prompt_agent's conversation refuses user_sim_gate at construction, instead of accepting and ignoring it, unless it sets USER_SIM_GATE_SUPPORTED = True. Co-Authored-By: Claude Opus 5.5 --- .../task_step/task_steps/prompt_agent.py | 68 ++++++++++------- .../task_step/task_steps/user_sim_gate.py | 68 ++++++++++++++++- tst/unit/task_step/test_user_sim_gate.py | 73 +++++++++++++++++++ 3 files changed, 180 insertions(+), 29 deletions(-) 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 3bce8bae4..ed9a069f5 100644 --- a/src/agent_env/task_step/task_steps/prompt_agent.py +++ b/src/agent_env/task_step/task_steps/prompt_agent.py @@ -41,7 +41,7 @@ from agent_env.task_step.task_step import RetryConfig, TaskStep, TaskStepDependency from agent_env.task_step.task_steps.notification_delivery import delivered_parts, next_message, take_due from agent_env.task_step.task_steps.post_turn_hooks import PostTurnHooks, run_post_turn_hooks, validate_hook_specs -from agent_env.task_step.task_steps.user_sim_gate import UserSimGate, rewrite_request +from agent_env.task_step.task_steps.user_sim_gate import UserSimGate, judge_call_config, run_gate from agent_env.task_step.task_steps.sandbox_utils.sandbox_utils import ( agent_error_text, fetch_container_logs, @@ -143,6 +143,16 @@ class PromptAgentTaskStep(TaskStep): FieldScope.USER)} DEFAULT_PROMPT_TIMEOUT_SECONDS: ClassVar[int] = 600 DEFAULT_POLL_INTERVAL_SECONDS: ClassVar[int] = 2 + # Whether this step type applies user_sim_gate. None: it does when it keeps prompt_agent's conversation; a + # subclass that runs its own loop sets True once that loop calls user_sim_gate.run_gate. + USER_SIM_GATE_SUPPORTED: ClassVar[Optional[bool]] = None + _CONVERSATION_METHODS: ClassVar[tuple[str, ...]] = ("_execute", "_execute_conversation", "_converse") + + @classmethod + def applies_user_sim_gate(cls) -> bool: + if cls.USER_SIM_GATE_SUPPORTED is not None: + return cls.USER_SIM_GATE_SUPPORTED + return all(getattr(cls, m) is getattr(PromptAgentTaskStep, m) for m in cls._CONVERSATION_METHODS) def __init__( self, @@ -229,6 +239,11 @@ def __init__( # too, as JSON task files and the kwargs form of put() carry it. self.user_sim_gate = (UserSimGate.from_dict(user_sim_gate) if isinstance(user_sim_gate, dict) else user_sim_gate) + if self.user_sim_gate is not None and not type(self).applies_user_sim_gate(): + raise ValueError( + f"{type(self).__name__} '{id}': user_sim_gate is applied by prompt_agent's own conversation, which " + f"this step type replaces; it would be ignored. Call user_sim_gate.run_gate from its loop and set " + f"USER_SIM_GATE_SUPPORTED = True, or leave user_sim_gate out") @staticmethod def _validate_parts(parts: list[dict]) -> None: @@ -1113,37 +1128,32 @@ async def _ask_peer(self, number: int, agent_parts: list[dict]) -> dict: return await self._gated(number, answer) async def _gated(self, number: int, answer: dict) -> dict: - """Check the user-sim's message; ask for a rewrite while it fails, up to the gate's limit.""" + """Check the user-sim's message; ask for a rewrite while it fails, up to the gate's limit (``run_gate``).""" gate = self._gate - if self._gate_call_config is None and gate.judge_model: - config = get_config() - overrides = self._context.metadata.get("user_overrides", {}) - self._gate_call_config = config.resolve_model_call( - gate.judge_model, - default_api_key=config.resolve_reference( - overrides.get("judge_litellm_api_key") or overrides.get("litellm_api_key")), - base_override=overrides.get("judge_litellm_base_url") or overrides.get("litellm_base_url"), - ) - for attempt in range(gate.max_rewrites + 1): - text = "\n".join(p.get("text", "") for p in answer["message"] if p.get("kind") == "text") - verdict = await gate.check(text, self._history, call_config=self._gate_call_config) + if self._gate_call_config is None: + self._gate_call_config = judge_call_config(gate, self._context.metadata.get("user_overrides", {})) + latest = {"answer": answer} + + async def rewrite(note: str) -> Optional[str]: + reply = await self._send_to_peer(number, [{"kind": "text", "text": note}]) + latest["answer"] = reply + return None if "end" in reply else _text_of(reply["message"]) + + def on_verdict(attempt: int, text: str, verdict) -> None: self._record("user_sim_gate", {"turn": number, "attempt": attempt, "chars": len(text), **verdict.to_dict()}) - if verdict.passed: - return answer - logger.warning(f"Turn {number}: user-sim message failed the gate (attempt {attempt + 1}/" - f"{gate.max_rewrites + 1}): {'; '.join(verdict.reasons())[:300]}") - if attempt == gate.max_rewrites: - break - answer = await self._send_to_peer(number, [{"kind": "text", "text": rewrite_request(verdict)}]) - if "end" in answer: - return answer - if gate.on_fail == "send": - return answer + if not verdict.passed: + logger.warning(f"Turn {number}: user-sim message failed the gate (attempt {attempt + 1}/" + f"{gate.max_rewrites + 1}): {'; '.join(verdict.reasons())[:300]}") + + outcome = await run_gate(gate, _text_of(answer["message"]), self._history, rewrite, + call_config=self._gate_call_config, on_verdict=on_verdict) + if not outcome.invalid: + return latest["answer"] self._context.metadata.setdefault("user_sim_invalid", {})[self._step.id] = { - "turn": number, "reasons": verdict.reasons()} + "turn": number, "reasons": outcome.reasons()} if gate.on_fail == "fail": self.gate_failure = (f"user-sim message at turn {number} still reads as the assistant's after " - f"{gate.max_rewrites} rewrite(s): {'; '.join(verdict.reasons())[:500]}") + f"{gate.max_rewrites} rewrite(s): {'; '.join(outcome.reasons())[:500]}") return {"end": "user_sim_invalid"} async def _send_to_peer(self, number: int, agent_parts: list[dict]) -> dict: @@ -1198,6 +1208,10 @@ def _record(self, key: str, entry: dict) -> None: self._context.metadata.setdefault(key, {}).setdefault(self._step.id, []).append(entry) +def _text_of(parts: list[dict]) -> str: + return "\n".join(p.get("text", "") for p in parts if p.get("kind") == "text") + + def _trigger_answer(resp: dict) -> Optional[dict]: """An agent-trigger decide's answer: it ended the conversation, it speaks for the user, or None when none fired.""" if bool(resp.get("done")): diff --git a/src/agent_env/task_step/task_steps/user_sim_gate.py b/src/agent_env/task_step/task_steps/user_sim_gate.py index a4807ac82..8a127d42b 100644 --- a/src/agent_env/task_step/task_steps/user_sim_gate.py +++ b/src/agent_env/task_step/task_steps/user_sim_gate.py @@ -12,7 +12,8 @@ - ``judge_model``: one model call that reads the last turns and the candidate message and says whether the message is written as the user. -Opt in with ``user_sim_gate`` on a ``prompt_agent`` step that has a user-sim:: +Opt in with ``user_sim_gate`` on a ``prompt_agent`` step that has a user-sim (a step type that runs its own +conversation loop applies the gate with ``run_gate``, and sets ``USER_SIM_GATE_SUPPORTED``):: {"judge_model": "", "max_rewrites": 2, "on_fail": "fail"} """ @@ -22,7 +23,7 @@ import logging import re from dataclasses import asdict, dataclass, field -from typing import ClassVar, Optional +from typing import Awaitable, Callable, ClassVar, Optional logger = logging.getLogger(__name__) @@ -276,3 +277,66 @@ def rewrite_request(verdict: GateVerdict) -> str: "the work and reports it; you ask, answer what you were asked, decide, push back, or end. Write your next " "message to the assistant again, as yourself, in the same reply format as before." ) + + +@dataclass +class GateOutcome: + """How one user-sim message fared: the text to send (the last one checked), every verdict in order, and + ``invalid`` when it still failed after the rewrites and ``on_fail`` isn't "send". ``stopped`` is set when the + rewrite callback ended the exchange instead of returning a new message.""" + + text: Optional[str] + verdicts: list[GateVerdict] = field(default_factory=list) + invalid: bool = False + stopped: bool = False + + def reasons(self) -> list[str]: + return self.verdicts[-1].reasons() if self.verdicts else [] + + +async def run_gate( + gate: UserSimGate, + text: str, + history: list[tuple[str, str]], + rewrite: Callable[[str], Awaitable[Optional[str]]], + *, + call_config=None, + on_verdict: Optional[Callable[[int, str, GateVerdict], None]] = None, +) -> GateOutcome: + """Check ``text``; while it fails, send the user-sim ``rewrite_request`` through ``rewrite`` and check its new + message, up to ``gate.max_rewrites`` times. ``rewrite`` returns the new message, or None when the user side + ended instead. ``on_verdict(attempt, text, verdict)`` sees every check, for recording. Any conversation loop + can call this; ``prompt_agent`` does, between a user-sim's reply and the agent's next turn.""" + outcome = GateOutcome(text=text) + for attempt in range(gate.max_rewrites + 1): + verdict = await gate.check(text, history, call_config=call_config) + outcome.verdicts.append(verdict) + if on_verdict is not None: + on_verdict(attempt, text, verdict) + if verdict.passed: + return outcome + if attempt == gate.max_rewrites: + break + new_text = await rewrite(rewrite_request(verdict)) + if new_text is None: + outcome.stopped = True + return outcome + text = outcome.text = new_text + outcome.invalid = gate.on_fail != "send" + return outcome + + +def judge_call_config(gate: UserSimGate, user_overrides: dict): + """The model call settings for the gate's judge, honoring a run's judge or LiteLLM overrides the way the + rubrics verifier does; None without a judge.""" + if not gate.judge_model: + return None + from agent_env.store import get_config + + config = get_config() + return config.resolve_model_call( + gate.judge_model, + default_api_key=config.resolve_reference( + user_overrides.get("judge_litellm_api_key") or user_overrides.get("litellm_api_key")), + base_override=user_overrides.get("judge_litellm_base_url") or user_overrides.get("litellm_base_url"), + ) diff --git a/tst/unit/task_step/test_user_sim_gate.py b/tst/unit/task_step/test_user_sim_gate.py index fca748ad4..e305d47ee 100644 --- a/tst/unit/task_step/test_user_sim_gate.py +++ b/tst/unit/task_step/test_user_sim_gate.py @@ -69,3 +69,76 @@ async def _judge(self, candidate, history, call_config): long = asyncio.run(gate.check("The two states that need contracted physicians are these." + _FILLER, [])) assert (short.passed, short.judge_in_role) == (True, False) # recorded, not failed assert long.passed is False + + +# ---- run_gate, for any conversation loop ------------------------------------------------------------------------------ + +def _scripted_gate(verdicts, **settings): + from agent_env.task_step.task_steps.user_sim_gate import GateVerdict, UserSimGate + + class Gate(UserSimGate): + async def check(self, candidate, history, *, call_config=None): + return GateVerdict(passed=verdicts.pop(0), pattern_reasons=["it opens like a report of work done"]) + + return Gate(**settings) + + +def test_run_gate_rewrites_until_a_message_passes(): + import asyncio + from agent_env.task_step.task_steps.user_sim_gate import run_gate + + asked, seen = [], [] + + async def rewrite(note): + asked.append(note) + return f"rewrite {len(asked)}" + + outcome = asyncio.run(run_gate(_scripted_gate([False, False, True]), "draft", [], rewrite, + on_verdict=lambda attempt, text, v: seen.append((attempt, text, v.passed)))) + assert (outcome.text, outcome.invalid, outcome.stopped) == ("rewrite 2", False, False) + assert seen == [(0, "draft", False), (1, "rewrite 1", False), (2, "rewrite 2", True)] + assert asked[0].startswith("[Conversation system note, not from the assistant.]") + + +def test_run_gate_marks_a_message_that_never_passes_and_honors_send(): + import asyncio + from agent_env.task_step.task_steps.user_sim_gate import run_gate + + async def rewrite(note): + return "still the assistant" + + failed = asyncio.run(run_gate(_scripted_gate([False, False], max_rewrites=1), "draft", [], rewrite)) + sent = asyncio.run(run_gate(_scripted_gate([False, False], max_rewrites=1, on_fail="send"), "draft", [], rewrite)) + assert (failed.invalid, len(failed.verdicts)) == (True, 2) + assert (sent.invalid, sent.text) == (False, "still the assistant") + + +def test_run_gate_stops_when_the_user_side_ends_instead_of_rewriting(): + import asyncio + from agent_env.task_step.task_steps.user_sim_gate import run_gate + + async def rewrite(note): + return None + + outcome = asyncio.run(run_gate(_scripted_gate([False]), "draft", [], rewrite)) + assert (outcome.stopped, outcome.invalid, len(outcome.verdicts)) == (True, False, 1) + + +# ---- step types that run their own conversation ------------------------------------------------------------------ + +def test_a_step_type_that_replaces_the_conversation_refuses_the_gate_unless_it_applies_it(): + import pytest + from agent_env.task_step.task_steps.prompt_agent import PromptAgentTaskStep + + class OwnLoop(PromptAgentTaskStep): + async def _execute(self, context): + return context + + class OwnLoopWithGate(OwnLoop): + USER_SIM_GATE_SUPPORTED = True + + with pytest.raises(ValueError, match="OwnLoop 'talk': user_sim_gate is applied by prompt_agent's own conversation"): + OwnLoop(id="talk", version=None, prompt="hi", user_sim_gate={}) + assert OwnLoop(id="talk", version=None, prompt="hi").user_sim_gate is None + assert OwnLoopWithGate(id="talk", version=None, prompt="hi", user_sim_gate={}).user_sim_gate is not None + assert PromptAgentTaskStep.applies_user_sim_gate() and not OwnLoop.applies_user_sim_gate() From 489b507a2be3f57a9b5f6391033b61ec99027557 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 17:18:44 -0500 Subject: [PATCH 04/18] fix(user_sim_gate): saved always_on steps refuse the gate; judge setup errors fall back to the patterns - AlwaysOnTaskStep.from_dict passes user_sim_gate on, so a saved step is refused as one built in code is, rather than running with the setting dropped. - A judge whose setup fails (its key or endpoint) no longer ends the conversation: like a failed judge call, the patterns' verdict stands and the error is recorded on each verdict. Co-Authored-By: Claude Opus 5.5 --- .../task_step/task_steps/always_on.py | 3 ++ .../task_step/task_steps/prompt_agent.py | 17 +++++++++-- .../task_step/test_prompt_agent_user_side.py | 28 +++++++++++++++++++ tst/unit/task_step/test_user_sim_gate.py | 12 ++++++++ 4 files changed, 57 insertions(+), 3 deletions(-) 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 bb60c912a..5d40062ce 100644 --- a/src/agent_env/task_step/task_steps/always_on.py +++ b/src/agent_env/task_step/task_steps/always_on.py @@ -327,6 +327,9 @@ def to_dict(self) -> dict: def from_dict(cls, data: dict) -> AlwaysOnTaskStep: fields = {k: data[k] for k in cls._PROMPT_FIELDS if k in data and data[k] is not None} own = {k: data[k] for k in cls._OWN if k in data and data[k] is not None} + # Passed on so the constructor refuses it, as it does a step built in code, rather than dropping it unread. + if data.get("user_sim_gate") is not None: + fields["user_sim_gate"] = data["user_sim_gate"] return cls(**cls._base_from_dict(data), retry_config=data.get("retry_config"), **fields, **own) def task_problems(self, steps: list[TaskStep]) -> list[str]: 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 b171de0e6..1a2325271 100644 --- a/src/agent_env/task_step/task_steps/prompt_agent.py +++ b/src/agent_env/task_step/task_steps/prompt_agent.py @@ -9,6 +9,7 @@ import time import uuid from contextlib import nullcontext +from dataclasses import replace from datetime import datetime, timezone from typing import Any, ClassVar, Optional import httpx @@ -1139,6 +1140,7 @@ def __init__(self, step: PromptAgentTaskStep, context: TaskStepContext, *, url: self._history: list[tuple[str, str]] = [("user", opening_text)] if opening_text else [] self._gate = step.user_sim_gate if is_user_sim else None self._gate_call_config = None + self._gate_judge_setup_error: Optional[str] = None # Set once a user-sim message fails the gate after its rewrites, with on_fail "fail". self.gate_failure: Optional[str] = None self._end_after: Optional[str] = None @@ -1240,8 +1242,15 @@ async def _ask_peer(self, number: int, agent_parts: list[dict]) -> dict: async def _gated(self, number: int, answer: dict) -> dict: """Check the user-sim's message; ask for a rewrite while it fails, up to the gate's limit (``run_gate``).""" gate = self._gate - if self._gate_call_config is None: - self._gate_call_config = judge_call_config(gate, self._context.metadata.get("user_overrides", {})) + if self._gate_call_config is None and self._gate_judge_setup_error is None and gate.judge_model: + # Judge setup (its key, its endpoint) can fail as the judge call can: like a call, it never takes the + # conversation down; the patterns' verdict stands, with the error recorded on it. + try: + self._gate_call_config = judge_call_config(gate, self._context.metadata.get("user_overrides", {})) + except Exception as e: + self._gate_judge_setup_error = f"judge setup: {type(e).__name__}: {e}"[: gate.RECORDED_ERROR_CHARS] + logger.warning(f"user-sim gate {self._gate_judge_setup_error}; using patterns only") + checking = replace(gate, judge_model=None) if self._gate_judge_setup_error else gate latest = {"answer": answer} async def rewrite(note: str) -> Optional[str]: @@ -1250,12 +1259,14 @@ async def rewrite(note: str) -> Optional[str]: return None if "end" in reply else _text_of(reply["message"]) def on_verdict(attempt: int, text: str, verdict) -> None: + if self._gate_judge_setup_error and verdict.judge_error is None: + verdict.judge_error = self._gate_judge_setup_error self._record("user_sim_gate", {"turn": number, "attempt": attempt, "chars": len(text), **verdict.to_dict()}) if not verdict.passed: logger.warning(f"Turn {number}: user-sim message failed the gate (attempt {attempt + 1}/" f"{gate.max_rewrites + 1}): {'; '.join(verdict.reasons())[:300]}") - outcome = await run_gate(gate, _text_of(answer["message"]), self._history, rewrite, + outcome = await run_gate(checking, _text_of(answer["message"]), self._history, rewrite, call_config=self._gate_call_config, on_verdict=on_verdict) if not outcome.invalid: return latest["answer"] diff --git a/tst/unit/task_step/test_prompt_agent_user_side.py b/tst/unit/task_step/test_prompt_agent_user_side.py index a18ccb134..67a26c8d1 100644 --- a/tst/unit/task_step/test_prompt_agent_user_side.py +++ b/tst/unit/task_step/test_prompt_agent_user_side.py @@ -609,3 +609,31 @@ def test_the_gate_round_trips_through_the_step_dict_and_rejects_bad_settings(): _step(user_sim_gate={"on_fail": "retry"}) with pytest.raises(ValueError, match="needs patterns"): _step(user_sim_gate={"patterns": False}) + + +@pytest.mark.asyncio +async def test_a_judge_whose_setup_fails_leaves_the_patterns_verdict_and_is_not_called(monkeypatch): + from agent_env.task_step.task_steps import user_sim_gate + + called = [] + + async def judge(self, candidate, history, call_config): + called.append(candidate) + return {"in_role": True} + + def no_endpoint(self, model, **kw): + raise KeyError("no endpoint configured for judge-model") + + monkeypatch.setattr(user_sim_gate.UserSimGate, "_judge", judge) + monkeypatch.setattr("agent_env.config.Config.resolve_model_call", no_endpoint, raising=False) + peers = Peers(monkeypatch, {AGENT: [text("draft one"), text("draft two")], + USER: [sim(_SWAP), sim("shorter, please")]}) + ctx = _context(user_card=_USER_SIM_CARD) + + await _gated(judge_model="judge-model").execute(ctx) + + verdicts = ctx.metadata["user_sim_gate"]["talk"] + assert [v["passed"] for v in verdicts] == [False, True] # the patterns still held the swap back + assert all(v["judge_error"].startswith("judge setup: KeyError") for v in verdicts) + assert called == [] + assert peers.requests(ctx)[-2] == send(AGENT, text("shorter, please"), "", "") diff --git a/tst/unit/task_step/test_user_sim_gate.py b/tst/unit/task_step/test_user_sim_gate.py index e305d47ee..f3316bc92 100644 --- a/tst/unit/task_step/test_user_sim_gate.py +++ b/tst/unit/task_step/test_user_sim_gate.py @@ -142,3 +142,15 @@ class OwnLoopWithGate(OwnLoop): assert OwnLoop(id="talk", version=None, prompt="hi").user_sim_gate is None assert OwnLoopWithGate(id="talk", version=None, prompt="hi", user_sim_gate={}).user_sim_gate is not None assert PromptAgentTaskStep.applies_user_sim_gate() and not OwnLoop.applies_user_sim_gate() + + +def test_a_saved_always_on_step_with_the_gate_is_refused_as_one_built_in_code_is(): + import pytest + from agent_env.task_step.task_steps.always_on import AlwaysOnTaskStep + + step = AlwaysOnTaskStep("week", None, user_sim="user-sim", prompt_id="ask", agent_name="solver") + saved = {**step.to_dict(), "user_sim_gate": {}} + + with pytest.raises(ValueError, match="AlwaysOnTaskStep 'week': user_sim_gate is applied by prompt_agent's own"): + AlwaysOnTaskStep.from_dict(saved) + assert AlwaysOnTaskStep.from_dict(step.to_dict()).user_sim_gate is None From 095a14f33ab9cef0f07b3571c672fd171dd1287c Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 17:27:48 -0500 Subject: [PATCH 05/18] fix(user_sim_gate): a judge-only gate whose judge can't be set up keeps checking The fallback rebuilt the gate without its judge, which a judge-only gate (patterns off) refuses, so its setup error ended the conversation. The gate's check now takes judge_unavailable instead: the judge isn't called, the patterns' verdict stands (a pass with patterns off), and the reason is recorded on the verdict, as for a judge call that fails. run_gate passes it only when set, so a check override with the old signature still works. Co-Authored-By: Claude Opus 5.5 --- .../task_step/task_steps/prompt_agent.py | 11 ++++------- .../task_step/task_steps/user_sim_gate.py | 16 ++++++++++++---- .../task_step/test_prompt_agent_user_side.py | 16 ++++++++++++++++ tst/unit/task_step/test_user_sim_gate.py | 16 +++++++++++++++- 4 files changed, 47 insertions(+), 12 deletions(-) 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 1a2325271..574f81d72 100644 --- a/src/agent_env/task_step/task_steps/prompt_agent.py +++ b/src/agent_env/task_step/task_steps/prompt_agent.py @@ -9,7 +9,6 @@ import time import uuid from contextlib import nullcontext -from dataclasses import replace from datetime import datetime, timezone from typing import Any, ClassVar, Optional import httpx @@ -1244,13 +1243,12 @@ async def _gated(self, number: int, answer: dict) -> dict: gate = self._gate if self._gate_call_config is None and self._gate_judge_setup_error is None and gate.judge_model: # Judge setup (its key, its endpoint) can fail as the judge call can: like a call, it never takes the - # conversation down; the patterns' verdict stands, with the error recorded on it. + # conversation down; the patterns' verdict stands, with the error recorded on it (run_gate). try: self._gate_call_config = judge_call_config(gate, self._context.metadata.get("user_overrides", {})) except Exception as e: self._gate_judge_setup_error = f"judge setup: {type(e).__name__}: {e}"[: gate.RECORDED_ERROR_CHARS] logger.warning(f"user-sim gate {self._gate_judge_setup_error}; using patterns only") - checking = replace(gate, judge_model=None) if self._gate_judge_setup_error else gate latest = {"answer": answer} async def rewrite(note: str) -> Optional[str]: @@ -1259,15 +1257,14 @@ async def rewrite(note: str) -> Optional[str]: return None if "end" in reply else _text_of(reply["message"]) def on_verdict(attempt: int, text: str, verdict) -> None: - if self._gate_judge_setup_error and verdict.judge_error is None: - verdict.judge_error = self._gate_judge_setup_error self._record("user_sim_gate", {"turn": number, "attempt": attempt, "chars": len(text), **verdict.to_dict()}) if not verdict.passed: logger.warning(f"Turn {number}: user-sim message failed the gate (attempt {attempt + 1}/" f"{gate.max_rewrites + 1}): {'; '.join(verdict.reasons())[:300]}") - outcome = await run_gate(checking, _text_of(answer["message"]), self._history, rewrite, - call_config=self._gate_call_config, on_verdict=on_verdict) + outcome = await run_gate(gate, _text_of(answer["message"]), self._history, rewrite, + call_config=self._gate_call_config, judge_unavailable=self._gate_judge_setup_error, + on_verdict=on_verdict) if not outcome.invalid: return latest["answer"] self._context.metadata.setdefault("user_sim_invalid", {})[self._step.id] = { diff --git a/src/agent_env/task_step/task_steps/user_sim_gate.py b/src/agent_env/task_step/task_steps/user_sim_gate.py index 8a127d42b..02b7f3300 100644 --- a/src/agent_env/task_step/task_steps/user_sim_gate.py +++ b/src/agent_env/task_step/task_steps/user_sim_gate.py @@ -208,11 +208,16 @@ def from_dict(cls, data: Optional[dict]) -> Optional[UserSimGate]: def to_dict(self) -> dict: return asdict(self) - async def check(self, candidate: str, history: list[tuple[str, str]], *, call_config=None) -> GateVerdict: + async def check(self, candidate: str, history: list[tuple[str, str]], *, call_config=None, + judge_unavailable: Optional[str] = None) -> GateVerdict: """Check one message. ``history`` is the conversation so far as ``(role, text)``, role user/assistant. - A judge call that errors or can't be parsed doesn't fail the message: the patterns' verdict stands.""" + A judge call that errors or can't be parsed doesn't fail the message: the patterns' verdict stands. So does a + judge that couldn't be set up (``judge_unavailable``, the reason), which isn't called.""" reasons = pattern_reasons(candidate) if self.patterns else [] verdict = GateVerdict(passed=not reasons, pattern_reasons=reasons) + if self.judge_model and judge_unavailable is not None: + verdict.judge_error = judge_unavailable[: self.RECORDED_ERROR_CHARS] + return verdict if self.judge_model: try: judged = await self._judge(candidate, history, call_config) @@ -301,15 +306,18 @@ async def run_gate( rewrite: Callable[[str], Awaitable[Optional[str]]], *, call_config=None, + judge_unavailable: Optional[str] = None, on_verdict: Optional[Callable[[int, str, GateVerdict], None]] = None, ) -> GateOutcome: """Check ``text``; while it fails, send the user-sim ``rewrite_request`` through ``rewrite`` and check its new message, up to ``gate.max_rewrites`` times. ``rewrite`` returns the new message, or None when the user side - ended instead. ``on_verdict(attempt, text, verdict)`` sees every check, for recording. Any conversation loop + ended instead. ``judge_unavailable`` is why the judge couldn't be set up, if it couldn't (see ``check``). + ``on_verdict(attempt, text, verdict)`` sees every check, for recording. Any conversation loop can call this; ``prompt_agent`` does, between a user-sim's reply and the agent's next turn.""" outcome = GateOutcome(text=text) for attempt in range(gate.max_rewrites + 1): - verdict = await gate.check(text, history, call_config=call_config) + extra = {} if judge_unavailable is None else {"judge_unavailable": judge_unavailable} + verdict = await gate.check(text, history, call_config=call_config, **extra) outcome.verdicts.append(verdict) if on_verdict is not None: on_verdict(attempt, text, verdict) diff --git a/tst/unit/task_step/test_prompt_agent_user_side.py b/tst/unit/task_step/test_prompt_agent_user_side.py index 67a26c8d1..7db9284d1 100644 --- a/tst/unit/task_step/test_prompt_agent_user_side.py +++ b/tst/unit/task_step/test_prompt_agent_user_side.py @@ -637,3 +637,19 @@ def no_endpoint(self, model, **kw): assert all(v["judge_error"].startswith("judge setup: KeyError") for v in verdicts) assert called == [] assert peers.requests(ctx)[-2] == send(AGENT, text("shorter, please"), "", "") + + +@pytest.mark.asyncio +async def test_a_judge_only_gate_whose_setup_fails_sends_the_message_on_with_the_error_recorded(monkeypatch): + def no_endpoint(self, model, **kw): + raise KeyError("no endpoint configured for judge-model") + + monkeypatch.setattr("agent_env.config.Config.resolve_model_call", no_endpoint, raising=False) + peers = Peers(monkeypatch, {AGENT: [text("draft one"), text("draft two")], USER: [sim("shorter, please")]}) + ctx = _context(user_card=_USER_SIM_CARD) + + await _gated(patterns=False, judge_model="judge-model").execute(ctx) + + (verdict,) = ctx.metadata["user_sim_gate"]["talk"] + assert verdict["passed"] is True and verdict["judge_error"].startswith("judge setup: KeyError") + assert peers.requests(ctx)[-2] == send(AGENT, text("shorter, please"), "", "") diff --git a/tst/unit/task_step/test_user_sim_gate.py b/tst/unit/task_step/test_user_sim_gate.py index f3316bc92..bc662fe23 100644 --- a/tst/unit/task_step/test_user_sim_gate.py +++ b/tst/unit/task_step/test_user_sim_gate.py @@ -77,7 +77,7 @@ def _scripted_gate(verdicts, **settings): from agent_env.task_step.task_steps.user_sim_gate import GateVerdict, UserSimGate class Gate(UserSimGate): - async def check(self, candidate, history, *, call_config=None): + async def check(self, candidate, history, *, call_config=None, judge_unavailable=None): return GateVerdict(passed=verdicts.pop(0), pattern_reasons=["it opens like a report of work done"]) return Gate(**settings) @@ -154,3 +154,17 @@ def test_a_saved_always_on_step_with_the_gate_is_refused_as_one_built_in_code_is with pytest.raises(ValueError, match="AlwaysOnTaskStep 'week': user_sim_gate is applied by prompt_agent's own"): AlwaysOnTaskStep.from_dict(saved) assert AlwaysOnTaskStep.from_dict(step.to_dict()).user_sim_gate is None + + +def test_a_judge_that_couldnt_be_set_up_isnt_called_and_the_patterns_verdict_stands(): + import asyncio + from agent_env.task_step.task_steps.user_sim_gate import UserSimGate + + class NeverCalled(UserSimGate): + async def _judge(self, candidate, history, call_config): + raise AssertionError("the judge was called") + + for patterns in (True, False): + gate = NeverCalled(patterns=patterns, judge_model="judge-model") + verdict = asyncio.run(gate.check("shorter, please", [], judge_unavailable="judge setup: KeyError: x")) + assert (verdict.passed, verdict.judge_error) == (True, "judge setup: KeyError: x") From ed9b37c66c6f79f59ed9d68e0d2927f70f13e29b Mon Sep 17 00:00:00 2001 From: t Date: Mon, 16 Nov 2026 12:19:04 -0500 Subject: [PATCH 06/18] feat(user sim): the gate checks the built-in user sim too, in prompt_agent and always_on prompt_agent applies user_sim_gate to the user deploy_user_sim_agent deployed: a held-back answer is rewritten in its session and parsed as its own answer, and the read's record keeps the first answer and lists each rewrite. always_on applies it at each read before an answer is held: one that still fails is never delivered and ends the run (user_sim_invalid; an error with on_fail fail). Co-Authored-By: Claude Opus 5.5 --- .../task_step/task_steps/always_on.py | 83 +++++++++++++- .../task_step/task_steps/prompt_agent.py | 55 ++++++++- .../task_step/task_steps/user_sim_gate.py | 6 +- .../task_step/test_always_on_user_sim_gate.py | 105 ++++++++++++++++++ .../test_prompt_agent_built_in_user_sim.py | 61 +++++++++- tst/unit/task_step/test_user_sim_gate.py | 15 +-- 6 files changed, 306 insertions(+), 19 deletions(-) create mode 100644 tst/unit/task_step/test_always_on_user_sim_gate.py 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 5d40062ce..d64680fe3 100644 --- a/src/agent_env/task_step/task_steps/always_on.py +++ b/src/agent_env/task_step/task_steps/always_on.py @@ -46,7 +46,7 @@ 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, step_error. With no end_time, a world that only repeats ends the run too (``IDLE_JUMPS_MAX``, in the + 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 @@ -62,6 +62,12 @@ being when the reply reached the agent, so checks built on those records grade the run instead of skipping it. A reply that never reached it (her last read's, or one still held at the end) has ``delivered`` false and no ``user_reads_at``. +- ``user_sim_gate`` (user_sim_gate.py) checks each answer the user sim would send before the agent gets it. One that + reads as the assistant's is held back and the user sim, told why in its session, answers again, up to the gate's + ``max_rewrites``; each read's event records the checks (``user_sim_gate``: verdicts, rewrites, the first message). + An answer that still fails is never delivered and ends the run (user_sim_invalid, also recorded in + ``metadata["user_sim_invalid"][step_id]``): with ``on_fail`` "fail" it sets ``error_type`` too, so verifiers skip + the run; "end" ends it plainly; "send" delivers it anyway. Her last read's answer, never delivered, isn't checked. - The run's metadata keeps a summary in ``metadata["always_on"][step_id]`` (small enough for a running job to report back); the full timeline goes to the object store, at the summary's ``object_url``. - An always_on_agent_verifier (``verifiers/always_on_agent_verifier.py``) grades the step's prompt from the user's chat @@ -114,6 +120,7 @@ from agent_env.task_step.task_steps.agent.deploy_user_sim_agent import USER_SIMS_KEY from agent_env.task_step.task_steps.notification_delivery import delivered_parts, label_time, take_due from agent_env.task_step.task_steps.prompt_agent import PromptAgentTaskStep +from agent_env.task_step.task_steps.user_sim_gate import judge_call_config, run_gate from agent_env.task_step.task_steps.agent.user_sim_common import iso as _iso, person_of, task_zone, utc as _utc logger = logging.getLogger(__name__) @@ -171,6 +178,7 @@ "agent_turn_failed": "The assistant's turn failed.", "agent_turn_timeout": "The assistant's turn timed out.", "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.", } # The run's metadata keeps a summary; the full timeline goes to the object store. When storing fails, the summary keeps @@ -207,6 +215,8 @@ # ================================================================================================================== class AlwaysOnTaskStep(PromptAgentTaskStep): type: ClassVar[str] = "always_on" + # Its own loop checks each user-sim answer before the agent gets it (_Run._gate, with user_sim_gate.run_gate). + USER_SIM_GATE_SUPPORTED: ClassVar[Optional[bool]] = True entity_refs = () field_scopes = {k: v for k, v in PromptAgentTaskStep.field_scopes.items() if k != "user_model"} @@ -321,13 +331,14 @@ def to_dict(self) -> dict: base[k] = getattr(self, k) for k in self._OWN: base[k] = getattr(self, k) + if self.user_sim_gate is not None: + base["user_sim_gate"] = self.user_sim_gate.to_dict() return base @classmethod def from_dict(cls, data: dict) -> AlwaysOnTaskStep: fields = {k: data[k] for k in cls._PROMPT_FIELDS if k in data and data[k] is not None} own = {k: data[k] for k in cls._OWN if k in data and data[k] is not None} - # Passed on so the constructor refuses it, as it does a step built in code, rather than dropping it unread. if data.get("user_sim_gate") is not None: fields["user_sim_gate"] = data["user_sim_gate"] return cls(**cls._base_from_dict(data), retry_config=data.get("retry_config"), **fields, **own) @@ -374,6 +385,10 @@ def __init__(self, step: AlwaysOnTaskStep, context: TaskStepContext): self.held: list[dict] = [] # user replies held for their response time: {deliver_at, text} self.you_sent: list[dict] = [] # the user's own lines since their last read: {at, text} self.history: list[dict] = [] # every read and its answer, for the plug-in + # The conversation as the user-sim gate reads it, (role, text); and the gate's judge settings, set up once. + self.gate_history: list[tuple[str, str]] = [] + self.gate_call_config = None + self.gate_setup_error: Optional[str] = None self.replies = 0 self.gave_up = False self.final_sent = False @@ -1005,6 +1020,8 @@ async def _capped(self, work, what: str, seconds: Optional[float] = None): async def _open(self) -> None: """The opening wake: the user's request, with what came due for the agent.""" self.you_sent.append(dict(self.opening)) + if self.opening.get("text"): + self.gate_history.append(("user", self.opening["text"])) opened_at = _utc(self.opening["at"]) await self._chat_user(self._opening_parts(lambda text: self._chat_part(opened_at, text, kind="opening"))) due = await take_due(self.notification_envs, self.recipient) if self.notification_envs else [] @@ -1491,6 +1508,13 @@ async def ask(text: str) -> dict: except TimeoutError: # the plug-in ran past the read's cap: a user sim error, as a failed ask is ans = {"outcome": "no_reply", "message": ""} calls.append({"text": None, "structured": None, "error": f"the read ran past its cap ({cap:.0f}s)"}) + self.gate_history += [("assistant", m["text"]) for m in seen] + gate_record = None + if (self.step.user_sim_gate is not None and not last and ans.get("outcome") in ("reply", "done") + and (ans.get("message") or "").strip() and not (calls and calls[-1].get("error"))): + ans, gate_record = await self._gate(ans, ask) + if ans.get("outcome") in ("reply", "done") and (ans.get("message") or "").strip(): + self.gate_history.append(("user", ans["message"])) self.history.append({"read": read, "answer": ans}) mode = self.read_mode latency = self._latency(mode) @@ -1505,7 +1529,8 @@ async def ask(text: str) -> dict: user_sim_trajectory_urls=[c.get("trajectory_url") for c in calls], user_sim_turns=ans.get("turns", len(calls)), shown=ans.get("shown"), past_turn_cap=ans.get("past_turn_cap"), last_read=last, - retried=ans.get("retried"), first_answer=ans.get("first_answer")) + retried=ans.get("retried"), first_answer=ans.get("first_answer"), + **({"user_sim_gate": gate_record} if gate_record else {})) outcome = ans.get("outcome") said = (ans.get("message") or "").strip() hook = {"hook": HOOK_NAME, "turn": self.wakes, "read_at": _iso(now), @@ -1541,6 +1566,58 @@ async def ask(text: str) -> dict: if calls and calls[-1].get("error") and not last: self.end_reason = self.end_reason or "user_sim_error" + async def _gate(self, ans: dict, ask) -> tuple[dict, dict]: + """The user sim's answer after the user-sim gate (user_sim_gate.py): each failing message is held back and the + user sim, told why through ``ask`` in its session, answers again, up to the gate's limit. Returns the answer to + use and the gate's record for the read. A message that still fails is never delivered: the answer becomes a + no_reply, and the run ends ("user_sim_invalid"; an error, so verifiers skip it, when ``on_fail`` is "fail"), + unless ``on_fail`` is "send".""" + gate = self.step.user_sim_gate + if self.gate_call_config is None and self.gate_setup_error is None and gate.judge_model: + try: + self.gate_call_config = judge_call_config(gate, self.ctx.metadata.get("user_overrides", {})) + except Exception as e: # as in prompt_agent: the patterns' verdict stands, with the error on it + self.gate_setup_error = f"judge setup: {type(e).__name__}: {e}"[: gate.RECORDED_ERROR_CHARS] + logger.warning(f"always_on: user-sim gate {self.gate_setup_error}; using patterns only") + latest = {"ans": ans} + verdicts: list[dict] = [] + rewrites: list[dict] = [] + + async def rewrite(note: str) -> Optional[str]: + got = await ask(note) + new = user_sim_versions.parse(got["structured"] if isinstance(got.get("structured"), dict) + else got.get("text")) + rewrites.append({**{k: new.get(k) for k in ("outcome", "message", "used", "schema_errors")}, + "user_sim_error": got.get("error")}) + if got.get("error"): # read() ends the run on it (user_sim_error), as on any failed ask + latest["ans"] = {**ans, "outcome": "no_reply", "message": "", "used": None} + return None + latest["ans"] = {**ans, **new} + said = (new.get("message") or "").strip() + return said if new.get("outcome") in ("reply", "done") and said else None + + def on_verdict(attempt: int, text: str, verdict) -> None: + verdicts.append({"attempt": attempt, "chars": len(text), **verdict.to_dict()}) + if not verdict.passed: + logger.warning(f"always_on wake {self.wakes}: user-sim answer failed the gate (attempt {attempt + 1}/" + f"{gate.max_rewrites + 1}): {'; '.join(verdict.reasons())[:300]}") + + outcome = await run_gate(gate, ans["message"], self.gate_history, rewrite, call_config=self.gate_call_config, + judge_unavailable=self.gate_setup_error, on_verdict=on_verdict) + record = {"verdicts": verdicts, "rewrites": rewrites, "invalid": outcome.invalid} + if rewrites: + record["first_message"] = ans["message"] + if not outcome.invalid: + return latest["ans"], record + reasons = outcome.reasons() + self.ctx.metadata.setdefault("user_sim_invalid", {})[self.step.id] = {"wake": self.wakes, "reasons": reasons} + if gate.on_fail == "fail": + self.error = (f"user-sim answer at wake {self.wakes} still reads as the assistant's after " + f"{gate.max_rewrites} rewrite(s): {'; '.join(reasons)[:500]}") + self.error_type = "user_sim_invalid" + self.end_reason = self.end_reason or "user_sim_invalid" + return {**latest["ans"], "outcome": "no_reply", "message": "", "used": None}, record + async def _ask_user_sim(self, text: str, deadline: float) -> dict: """One user sim turn on ``text``, cut off at its time limit and grace or at the read's ``deadline`` (time.monotonic()), whichever comes first.""" 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 b4b880b1a..394fdf7b2 100644 --- a/src/agent_env/task_step/task_steps/prompt_agent.py +++ b/src/agent_env/task_step/task_steps/prompt_agent.py @@ -650,8 +650,8 @@ async def _converse( opening_text="\n".join(p.get("text", "") for p in initial_parts if p.get("kind") == "text"), built_in=sim, ) - if self.user_sim_gate is not None and (not is_user_sim or sim is not None): - logger.warning(f"prompt_agent '{self.id}': user_sim_gate is set but the user side isn't a peer user-sim " + if self.user_sim_gate is not None and not is_user_sim: + logger.warning(f"prompt_agent '{self.id}': user_sim_gate is set but the user side isn't a user-sim " "agent-env deployed; no message is checked") # Set by a user's done with a message: the agent answers it, then the conversation ends for this reason. end_after: Optional[str] = None @@ -1171,6 +1171,13 @@ async def _answer(self, number: int, agent_parts: list[dict], solver_message: st # no trigger fired -> fall through to the LLM user-sim for this turn (hybrid) if self._built_in is not None: answer = await self._built_in.ask(number, _agent_text(solver_message, agent_parts), self._ask_built_in) + if self._gate is not None and "message" in answer: + kept = answer.get("end_after") + + async def rewrite_built_in(note: str) -> dict: + return await self._built_in.rewrite(number, note, self._ask_built_in, kept) + + answer = await self._gated(number, answer, rewrite_built_in) self._end_after = answer.get("end_after") return answer return await self._ask_peer(number, agent_parts) @@ -1236,10 +1243,15 @@ async def _ask_peer(self, number: int, agent_parts: list[dict]) -> dict: answer = await self._send_to_peer(number, agent_parts) if self._gate is None or "end" in answer: return answer - return await self._gated(number, answer) - async def _gated(self, number: int, answer: dict) -> dict: - """Check the user-sim's message; ask for a rewrite while it fails, up to the gate's limit (``run_gate``).""" + async def rewrite_peer(note: str) -> dict: + return await self._send_to_peer(number, [{"kind": "text", "text": note}]) + + return await self._gated(number, answer, rewrite_peer) + + async def _gated(self, number: int, answer: dict, ask_rewrite) -> dict: + """Check the user-sim's message; while it fails, ask for a rewrite with ``ask_rewrite(note)``, which returns an + answer shaped as ``ask``'s, up to the gate's limit (``run_gate``).""" gate = self._gate if self._gate_call_config is None and self._gate_judge_setup_error is None and gate.judge_model: # Judge setup (its key, its endpoint) can fail as the judge call can: like a call, it never takes the @@ -1252,7 +1264,7 @@ async def _gated(self, number: int, answer: dict) -> dict: latest = {"answer": answer} async def rewrite(note: str) -> Optional[str]: - reply = await self._send_to_peer(number, [{"kind": "text", "text": note}]) + reply = await ask_rewrite(note) latest["answer"] = reply return None if "end" in reply else _text_of(reply["message"]) @@ -1390,6 +1402,37 @@ async def ask(text: str) -> dict: return {"message": [{"kind": "text", "text": ans["message"]}], "end_after": "user_done"} return {"end": "user_done" if outcome == "done" else "user_no_reply"} + async def rewrite(self, number: int, note: str, ask_user_sim, end_after: Optional[str]) -> dict: + """The user's answer again, after the user-sim gate held its message back with ``note``, in the same session; + shaped as ``ask``'s. ``end_after`` is the held message's (its last reply before max_replies, say), which a reply + keeps. The read's record keeps what the user sim first answered and lists each rewrite under ``gate_rewrites``.""" + got = await ask_user_sim(note) + ans = user_sim_versions.parse(got["structured"] if isinstance(got.get("structured"), dict) else got.get("text")) + error = got.get("error") + rewrite = {k: ans.get(k) for k in ("outcome", "message", "used", "schema_errors")} + rewrite.update(user_sim_error=error, user_sim_trajectory_url=got.get("trajectory_url")) + reads = self._context.metadata.get("user_sim_reads", {}).get(self._step.id) or [] + if reads: + reads[-1].setdefault("gate_rewrites", []).append(rewrite) + outcome, said = ans.get("outcome"), (ans.get("message") or "").strip() + if self.history: + held = self.history[-1]["answer"] + if held.get("outcome") == "reply" and (held.get("message") or "").strip() and not ( + outcome == "reply" and said and not error): + self.replies -= 1 # the held reply was counted toward max_replies, and this answer isn't one + # What the user is shown later counts this answer as hers: the one that reached the agent. + self.history[-1]["answer"] = {**held, **ans} + logger.info(f"Turn {number} user sim rewrite: outcome={outcome} error={error}") + if error: + self.error = error + return {"end": "user_sim_error"} + if outcome == "reply" and said: + return {"message": [{"kind": "text", "text": ans["message"]}], + **({"end_after": end_after} if end_after == "user_gave_up" else {})} + if outcome == "done" and said: + return {"message": [{"kind": "text", "text": ans["message"]}], "end_after": "user_done"} + return {"end": "user_done" if outcome == "done" else "user_no_reply"} + async def _record(self, number: int, read: dict, ans: dict, calls: list[dict], error: Optional[str]) -> None: """Record the read as always_on does: a summary in ``metadata["user_sim_reads"][step_id]``, the whole read (what the user sim was shown, and its raw answers) in the object store at the summary's ``object_url``.""" diff --git a/src/agent_env/task_step/task_steps/user_sim_gate.py b/src/agent_env/task_step/task_steps/user_sim_gate.py index 02b7f3300..11b0bdc96 100644 --- a/src/agent_env/task_step/task_steps/user_sim_gate.py +++ b/src/agent_env/task_step/task_steps/user_sim_gate.py @@ -12,8 +12,10 @@ - ``judge_model``: one model call that reads the last turns and the candidate message and says whether the message is written as the user. -Opt in with ``user_sim_gate`` on a ``prompt_agent`` step that has a user-sim (a step type that runs its own -conversation loop applies the gate with ``run_gate``, and sets ``USER_SIM_GATE_SUPPORTED``):: +Opt in with ``user_sim_gate`` on a ``prompt_agent`` step whose user is a user-sim agent-env deployed: a peer +user-sim, or the built-in one deploy_user_sim_agent deploys, whose rewrite is parsed as its own answer. ``always_on`` +applies it to each of the built-in user-sim's answers. A step type that runs its own conversation loop applies the gate +with ``run_gate``, and sets ``USER_SIM_GATE_SUPPORTED``:: {"judge_model": "", "max_rewrites": 2, "on_fail": "fail"} """ diff --git a/tst/unit/task_step/test_always_on_user_sim_gate.py b/tst/unit/task_step/test_always_on_user_sim_gate.py new file mode 100644 index 000000000..f4e0a0779 --- /dev/null +++ b/tst/unit/task_step/test_always_on_user_sim_gate.py @@ -0,0 +1,105 @@ +"""always_on with ``user_sim_gate``: an answer of the user sim's that reads as the assistant's is held back, the user +sim answers again in its session, and an answer that still fails never reaches the agent and ends the run.""" + +from __future__ import annotations + +import json + +import pytest + +from tst.unit.task_step.always_on_harness import Rig +from tst.unit.task_step.test_prompt_agent_user_side import _SWAP + +pytestmark = pytest.mark.usefixtures("local_stores") + +NOTE = "[Conversation system note, not from the assistant.] Your last message was not sent" + + +def _answer(outcome: str, message: str = "") -> str: + return json.dumps({"outcome": outcome, "message": message, "used": "none"}) + + +def _messages_once(n, texts, rig): + if n == 1: + rig.message("here's the plan for the weekend") + return "sent" + rig.quiet() + return "" + + +def _gated(rig: Rig, **gate): + return rig.step(max_wakes=4, user_sim_gate={"patterns": True, **gate}) + + +def _got(rig: Rig, text: str) -> bool: + return any(text in t for wake in rig.sent for t in wake) + + +@pytest.mark.asyncio +async def test_an_answer_that_reads_as_the_assistants_is_held_back_and_the_rewrite_reaches_the_agent(monkeypatch, + tmp_path): + rig = Rig(monkeypatch, tmp_path, agent=_messages_once, answers=[{"outcome": "reply", "message": _SWAP}], + user_texts=(_answer("reply", "do those numbers hold up?"),)) + await rig.arm() + ctx = await rig.run(_gated(rig)) + + assert [c["parts"][0]["text"][:len(NOTE)] for c in rig.user_calls] == [NOTE] # asked again, in her session + assert _got(rig, "do those numbers hold up?") and not _got(rig, "None of the three reported numbers") + (read, *_) = rig.events(ctx, "user_sim_read") + assert read["message"] == "do those numbers hold up?" + gate = read["user_sim_gate"] + assert [(v["attempt"], v["passed"]) for v in gate["verdicts"]] == [(0, False), (1, True)] + assert gate["first_message"] == _SWAP and gate["invalid"] is False + assert [r["message"] for r in gate["rewrites"]] == ["do those numbers hold up?"] + assert "user_sim_invalid" not in ctx.metadata + assert rig.record(ctx)["end_reason"] != "user_sim_invalid" + + +@pytest.mark.asyncio +async def test_an_answer_that_still_fails_never_reaches_the_agent_and_ends_the_run_as_an_error(monkeypatch, tmp_path): + rig = Rig(monkeypatch, tmp_path, agent=_messages_once, answers=[{"outcome": "reply", "message": _SWAP}], + user_texts=(_answer("reply", _SWAP), _answer("reply", _SWAP))) + await rig.arm() + ctx = await rig.run(_gated(rig)) + + assert not _got(rig, "None of the three reported numbers") + assert len(rig.sent) == 1 # no wake after hers: the run ended at her read + record = rig.record(ctx) + assert record["end_reason"] == "user_sim_invalid" + assert record["error_type"] == "user_sim_invalid" # verifiers skip a run that broke, as on a user sim error + assert ctx.metadata["user_sim_invalid"]["week"]["wake"] == 1 + (read,) = rig.events(ctx, "user_sim_read") + assert read["outcome"] == "no_reply" and read["user_sim_gate"]["invalid"] is True + assert [v["passed"] for v in read["user_sim_gate"]["verdicts"]] == [False, False, False] + + +@pytest.mark.asyncio +async def test_on_fail_end_ends_the_run_without_marking_it_an_error(monkeypatch, tmp_path): + rig = Rig(monkeypatch, tmp_path, agent=_messages_once, answers=[{"outcome": "reply", "message": _SWAP}], + user_texts=(_answer("reply", _SWAP),)) + await rig.arm() + ctx = await rig.run(_gated(rig, max_rewrites=1, on_fail="end")) + + record = rig.record(ctx) + assert record["end_reason"] == "user_sim_invalid" and record["error_type"] is None + assert not _got(rig, "None of the three reported numbers") + + +@pytest.mark.asyncio +async def test_an_in_role_answer_passes_with_no_rewrite(monkeypatch, tmp_path): + rig = Rig(monkeypatch, tmp_path, agent=_messages_once, answers=[{"outcome": "reply", "message": "shorter, please"}]) + await rig.arm() + ctx = await rig.run(_gated(rig)) + (read, *_) = rig.events(ctx, "user_sim_read") + assert read["user_sim_gate"] == {"verdicts": [{"attempt": 0, "chars": 15, "passed": True}], "rewrites": [], + "invalid": False} + assert rig.user_calls == [] + + +@pytest.mark.asyncio +async def test_without_the_gate_nothing_is_checked(monkeypatch, tmp_path): + plain = Rig(monkeypatch, tmp_path, agent=_messages_once, answers=[{"outcome": "reply", "message": _SWAP}]) + await plain.arm() + ctx = await plain.run(plain.step(max_wakes=4)) + assert "user_sim_gate" not in plain.events(ctx, "user_sim_read")[0] + assert _got(plain, "None of the three reported numbers") # unchanged without the gate 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 3bdae6d29..b0e426883 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 @@ -16,7 +16,8 @@ from agent_env.task_step.task_steps.prompt_agent import PromptAgentTaskStep from agent_env.task_step.task_steps.verifiers.agent_prompt_response_verifier import AgentPromptResponseVerifierTaskStep from tst.unit.task_step.test_deploy_user_sim_agent import HANNAH, _published, _step as _deploy_step -from tst.unit.task_step.test_prompt_agent_user_side import AGENT, HANG, HUMAN, USER, Peers, _stored, exchange, text +from tst.unit.task_step.test_prompt_agent_user_side import ( + _SWAP, AGENT, HANG, HUMAN, USER, Peers, _stored, exchange, text) pytestmark = pytest.mark.usefixtures("local_stores") @@ -411,3 +412,61 @@ async def test_agent_triggers_registered_for_the_built_in_user_are_refused_befor "user sim aren't supported yet"): await _step().execute(ctx) assert "user_sim_reads" not in ctx.metadata + + +# ---- the user-sim gate ---------------------------------------------------------------------------------------------- +def _gated(turns: int = 3, **gate) -> PromptAgentTaskStep: + return _step(turns=turns, user_sim_gate={"patterns": True, **gate}) + + +def _to(peers: Peers, ctx: TaskStepContext, url: str) -> list[str]: + sent = [r for r in peers.requests(ctx) if r[2] and r[2].get("method") == "message/send"] + return [r[2]["params"]["message"]["parts"][0]["text"] for r in sent if r[1].startswith(url)] + + +@pytest.mark.asyncio +async def test_the_gate_holds_back_a_built_in_users_answer_that_reads_as_the_assistants_and_she_answers_again( + monkeypatch): + peers = Peers(monkeypatch, {AGENT: [text("draft one"), text("draft two"), text("you're welcome")], + USER: [said("reply", _SWAP), said("reply", "do those numbers hold up?", "D1"), + said("done", "great, thanks")]}) + ctx = await _context(monkeypatch) + + await _gated().execute(ctx) + + to_user, to_agent = _to(peers, ctx, USER), _to(peers, ctx, AGENT) + assert to_user[1].startswith("[Conversation system note, not from the assistant.] Your last message was not sent") + assert to_agent == ["plan my parents' visit", "do those numbers hold up?", "great, thanks"] # no swap reached it + verdicts = ctx.metadata["user_sim_gate"]["talk"] + assert [(v["turn"], v["attempt"], v["passed"]) for v in verdicts] == [(1, 0, False), (1, 1, True), (2, 0, True)] + first = _reads(ctx)[0] + assert first["message"] == _SWAP # the read keeps what she first answered, for whoever grades her + assert [(r["outcome"], r["message"], r["used"]) for r in first["gate_rewrites"]] == [ + ("reply", "do those numbers hold up?", "D1")] + assert "user_sim_invalid" not in ctx.metadata + + +@pytest.mark.asyncio +async def test_a_built_in_users_answer_that_still_fails_ends_the_run_and_fails_the_step(monkeypatch): + peers = Peers(monkeypatch, {AGENT: [text("draft one")], USER: [said("reply", _SWAP)] * 3}) + ctx = await _context(monkeypatch) + + with pytest.raises(RuntimeError, match=r"user_sim_gate: user-sim message at turn 1 still reads as the assistant's"): + await _gated().execute(ctx) + + assert [v["passed"] for v in ctx.metadata["user_sim_gate"]["talk"]] == [False, False, False] + assert ctx.metadata["user_sim_invalid"]["talk"]["turn"] == 1 + assert len(_reads(ctx)[0]["gate_rewrites"]) == 2 + assert _to(peers, ctx, AGENT) == ["plan my parents' visit"] # nothing she wrote reached the agent + + +@pytest.mark.asyncio +async def test_a_rewrite_that_says_nothing_ends_the_conversation_as_her_no_reply(monkeypatch): + peers = Peers(monkeypatch, {AGENT: [text("draft one")], USER: [said("reply", _SWAP), said("no_reply")]}) + ctx = await _context(monkeypatch) + + await _gated().execute(ctx) + + assert _to(peers, ctx, AGENT) == ["plan my parents' visit"] + assert "user_sim_invalid" not in ctx.metadata + assert [(v["attempt"], v["passed"]) for v in ctx.metadata["user_sim_gate"]["talk"]] == [(0, False)] diff --git a/tst/unit/task_step/test_user_sim_gate.py b/tst/unit/task_step/test_user_sim_gate.py index bc662fe23..846ed3b8b 100644 --- a/tst/unit/task_step/test_user_sim_gate.py +++ b/tst/unit/task_step/test_user_sim_gate.py @@ -144,16 +144,17 @@ class OwnLoopWithGate(OwnLoop): assert PromptAgentTaskStep.applies_user_sim_gate() and not OwnLoop.applies_user_sim_gate() -def test_a_saved_always_on_step_with_the_gate_is_refused_as_one_built_in_code_is(): - import pytest +def test_an_always_on_step_keeps_its_gate_through_the_step_dict(): from agent_env.task_step.task_steps.always_on import AlwaysOnTaskStep - step = AlwaysOnTaskStep("week", None, user_sim="user-sim", prompt_id="ask", agent_name="solver") - saved = {**step.to_dict(), "user_sim_gate": {}} + step = AlwaysOnTaskStep("week", None, user_sim="user-sim", prompt_id="ask", agent_name="solver", + user_sim_gate={"max_rewrites": 1, "on_fail": "end"}) + again = AlwaysOnTaskStep.from_dict(step.to_dict()) - with pytest.raises(ValueError, match="AlwaysOnTaskStep 'week': user_sim_gate is applied by prompt_agent's own"): - AlwaysOnTaskStep.from_dict(saved) - assert AlwaysOnTaskStep.from_dict(step.to_dict()).user_sim_gate is None + assert again.user_sim_gate == step.user_sim_gate and again.user_sim_gate.on_fail == "end" + plain = AlwaysOnTaskStep("week", None, user_sim="user-sim", prompt_id="ask", agent_name="solver") + assert "user_sim_gate" not in plain.to_dict() + assert AlwaysOnTaskStep.from_dict(plain.to_dict()).user_sim_gate is None def test_a_judge_that_couldnt_be_set_up_isnt_called_and_the_patterns_verdict_stands(): From 8e765913060ba6d1d012fe40c1099b3678ba08a5 Mon Sep 17 00:00:00 2001 From: t Date: Mon, 16 Nov 2026 13:07:33 -0500 Subject: [PATCH 07/18] fix(user_sim_gate): a gate-failed response carries error_type; a rewrite counts toward max_replies A conversation the gate cut off with on_fail fail now records error_type user_sim_invalid on its PromptResponse, so verifiers skip it as they skip a user-sim error. A built-in user sim's rewrite replaces the held answer in the reply count, so a done rewritten into a reply counts, and max_replies ends the conversation after it. Co-Authored-By: Claude Opus 5.5 --- .../task_step/task_steps/prompt_agent.py | 26 +++++++++------- .../test_prompt_agent_built_in_user_sim.py | 31 +++++++++++++++++++ .../task_step/test_prompt_agent_user_side.py | 1 + 3 files changed, 47 insertions(+), 11 deletions(-) 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 394fdf7b2..17e6cb353 100644 --- a/src/agent_env/task_step/task_steps/prompt_agent.py +++ b/src/agent_env/task_step/task_steps/prompt_agent.py @@ -833,6 +833,10 @@ def record_turn() -> None: # As always_on marks it: verifiers skip the run instead of grading the agent's latest draft as its answer. error_type = "user_sim_error" final_error_for_response = final_error_for_response or f"The user simulator failed: {sim.error}" + if not error_type and user_side.gate_failure is not None: + # The conversation was cut off by the gate: verifiers skip it rather than grade the agent's latest draft. + error_type = "user_sim_invalid" + final_error_for_response = final_error_for_response or f"user_sim_gate: {user_side.gate_failure}" context.prompt_responses.append(PromptResponse( prompt_id=self.prompt_id, response=final_terminal.response_text, @@ -1172,10 +1176,8 @@ async def _answer(self, number: int, agent_parts: list[dict], solver_message: st if self._built_in is not None: answer = await self._built_in.ask(number, _agent_text(solver_message, agent_parts), self._ask_built_in) if self._gate is not None and "message" in answer: - kept = answer.get("end_after") - async def rewrite_built_in(note: str) -> dict: - return await self._built_in.rewrite(number, note, self._ask_built_in, kept) + return await self._built_in.rewrite(number, note, self._ask_built_in) answer = await self._gated(number, answer, rewrite_built_in) self._end_after = answer.get("end_after") @@ -1402,10 +1404,10 @@ async def ask(text: str) -> dict: return {"message": [{"kind": "text", "text": ans["message"]}], "end_after": "user_done"} return {"end": "user_done" if outcome == "done" else "user_no_reply"} - async def rewrite(self, number: int, note: str, ask_user_sim, end_after: Optional[str]) -> dict: + async def rewrite(self, number: int, note: str, ask_user_sim) -> dict: """The user's answer again, after the user-sim gate held its message back with ``note``, in the same session; - shaped as ``ask``'s. ``end_after`` is the held message's (its last reply before max_replies, say), which a reply - keeps. The read's record keeps what the user sim first answered and lists each rewrite under ``gate_rewrites``.""" + shaped as ``ask``'s. It replaces the held answer in the reply count, so ``max_replies`` holds whichever answer is + sent. The read's record keeps what the user sim first answered and lists each rewrite under ``gate_rewrites``.""" got = await ask_user_sim(note) ans = user_sim_versions.parse(got["structured"] if isinstance(got.get("structured"), dict) else got.get("text")) error = got.get("error") @@ -1417,9 +1419,9 @@ async def rewrite(self, number: int, note: str, ask_user_sim, end_after: Optiona outcome, said = ans.get("outcome"), (ans.get("message") or "").strip() if self.history: held = self.history[-1]["answer"] - if held.get("outcome") == "reply" and (held.get("message") or "").strip() and not ( - outcome == "reply" and said and not error): - self.replies -= 1 # the held reply was counted toward max_replies, and this answer isn't one + # ask counted the held answer if it was a reply; count this one in its place. + held_counted = held.get("outcome") == "reply" and bool((held.get("message") or "").strip()) + self.replies += int(outcome == "reply" and bool(said) and not error) - int(held_counted) # What the user is shown later counts this answer as hers: the one that reached the agent. self.history[-1]["answer"] = {**held, **ans} logger.info(f"Turn {number} user sim rewrite: outcome={outcome} error={error}") @@ -1427,8 +1429,10 @@ async def rewrite(self, number: int, note: str, ask_user_sim, end_after: Optiona self.error = error return {"end": "user_sim_error"} if outcome == "reply" and said: - return {"message": [{"kind": "text", "text": ans["message"]}], - **({"end_after": end_after} if end_after == "user_gave_up" else {})} + if self._max_replies and self.replies >= int(self._max_replies): + logger.info(f"Turn {number} user sim: reply {self.replies} of max_replies {self._max_replies}") + return {"message": [{"kind": "text", "text": ans["message"]}], "end_after": "user_gave_up"} + return {"message": [{"kind": "text", "text": ans["message"]}]} if outcome == "done" and said: return {"message": [{"kind": "text", "text": ans["message"]}], "end_after": "user_done"} return {"end": "user_done" if outcome == "done" else "user_no_reply"} 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 b0e426883..9924bd5ec 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 @@ -457,6 +457,9 @@ async def test_a_built_in_users_answer_that_still_fails_ends_the_run_and_fails_t assert [v["passed"] for v in ctx.metadata["user_sim_gate"]["talk"]] == [False, False, False] assert ctx.metadata["user_sim_invalid"]["talk"]["turn"] == 1 assert len(_reads(ctx)[0]["gate_rewrites"]) == 2 + # Verifiers skip a response with an error_type, so a cut-off conversation isn't graded as the agent's answer. + assert ctx.prompt_responses[-1].error_type == "user_sim_invalid" + assert ctx.prompt_responses[-1].error_message.startswith("user_sim_gate: user-sim message at turn 1") assert _to(peers, ctx, AGENT) == ["plan my parents' visit"] # nothing she wrote reached the agent @@ -470,3 +473,31 @@ async def test_a_rewrite_that_says_nothing_ends_the_conversation_as_her_no_reply assert _to(peers, ctx, AGENT) == ["plan my parents' visit"] assert "user_sim_invalid" not in ctx.metadata assert [(v["attempt"], v["passed"]) for v in ctx.metadata["user_sim_gate"]["talk"]] == [(0, False)] + + +@pytest.mark.asyncio +async def test_a_done_rewritten_into_a_reply_counts_toward_max_replies(monkeypatch): + # Her first answer is a done, which isn't counted; its rewrite is a reply, which is, and it is her last. + peers = Peers(monkeypatch, {AGENT: [text("draft one"), text("draft two")], + USER: [said("done", _SWAP), said("reply", "do those numbers hold up?")]}) + ctx = await _context(monkeypatch, persona={**HANNAH, "max_replies": 1}) + + result = await _gated().execute(ctx) + + assert _to(peers, ctx, AGENT) == ["plan my parents' visit", "do those numbers hold up?"] + assert len(_to(peers, ctx, USER)) == 2 # her read and the rewrite: she isn't asked again past the limit + assert result.prompt_responses[-1].response == "draft two" + assert result.prompt_responses[-1].error_type is None + + +@pytest.mark.asyncio +async def test_a_reply_rewritten_into_a_done_no_longer_counts(monkeypatch): + peers = Peers(monkeypatch, {AGENT: [text("draft one"), text("draft two"), text("draft three")], + USER: [said("reply", _SWAP), said("reply", "shorter, please"), + said("reply", "and cheaper")]}) + ctx = await _context(monkeypatch, persona={**HANNAH, "max_replies": 2}) + + await _gated().execute(ctx) + + # The held reply and its rewrite count once, so her second reply is the one that reaches the limit. + assert _to(peers, ctx, AGENT) == ["plan my parents' visit", "shorter, please", "and cheaper"] diff --git a/tst/unit/task_step/test_prompt_agent_user_side.py b/tst/unit/task_step/test_prompt_agent_user_side.py index 7db9284d1..32172f5d9 100644 --- a/tst/unit/task_step/test_prompt_agent_user_side.py +++ b/tst/unit/task_step/test_prompt_agent_user_side.py @@ -539,6 +539,7 @@ async def test_a_message_that_still_fails_after_its_rewrites_ends_the_run_and_fa assert _stored(ctx, peers)["status"] == "closed" assert [m["role"] for m in _stored(ctx, peers)["messages"]] == ["user", "agent"] # nothing more was sent assert ctx.prompt_responses[-1].response == "draft one" # the run kept its record + assert ctx.prompt_responses[-1].error_type == "user_sim_invalid" # which verifiers skip @pytest.mark.asyncio From 11cb3f9286554f8d328cf37b8ec85dc140b78986 Mon Sep 17 00:00:00 2001 From: kaihackney-scale Date: Thu, 19 Nov 2026 22:31:16 -0500 Subject: [PATCH 08/18] fix(user_sim_gate): route the judge call as the rubrics verifier routes its judge Through an endpoint, a Claude judge now drops the base's trailing /v1 (its client appends /v1/messages), and a bare name litellm can't place goes as openai/. Before, both failed every call, and the gate fell back to its patterns alone. Co-Authored-By: Claude Opus 5.5 --- .../task_step/task_steps/user_sim_gate.py | 12 +++++- tst/unit/task_step/test_user_sim_gate.py | 40 +++++++++++++++++++ 2 files changed, 50 insertions(+), 2 deletions(-) diff --git a/src/agent_env/task_step/task_steps/user_sim_gate.py b/src/agent_env/task_step/task_steps/user_sim_gate.py index 11b0bdc96..832309bfd 100644 --- a/src/agent_env/task_step/task_steps/user_sim_gate.py +++ b/src/agent_env/task_step/task_steps/user_sim_gate.py @@ -24,7 +24,7 @@ import json import logging import re -from dataclasses import asdict, dataclass, field +from dataclasses import asdict, dataclass, field, replace from typing import Awaitable, Callable, ClassVar, Optional logger = logging.getLogger(__name__) @@ -240,13 +240,21 @@ async def _judge(self, candidate: str, history: list[tuple[str, str]], call_conf import litellm from agent_env.config.model import ModelParam + from agent_env.task_step.task_steps.verifiers.rubrics_verifier import _judge_route prompt = _JUDGE_PROMPT.format( history=render_history(history, self.context_turns, self.context_chars), candidate=candidate[: self.context_chars * 2], ) + # Routed as the rubrics verifier routes its judge: through an endpoint, a Claude model drops the base's + # trailing /v1 and a bare name litellm can't place goes as openai/. + model = self.judge_model + if call_config is not None: + model, route_base = _judge_route(model, call_config.api_base, litellm.get_llm_provider, + call_config.params.get("custom_llm_provider")) + call_config = replace(call_config, api_base=route_base) response = await litellm.acompletion( - model=self.judge_model, + model=model, messages=[{"role": "user", "content": prompt}], timeout=self.judge_timeout_seconds, **{ModelParam.RESPONSE_FORMAT: {"type": "json_schema", diff --git a/tst/unit/task_step/test_user_sim_gate.py b/tst/unit/task_step/test_user_sim_gate.py index 846ed3b8b..1b4787dc9 100644 --- a/tst/unit/task_step/test_user_sim_gate.py +++ b/tst/unit/task_step/test_user_sim_gate.py @@ -169,3 +169,43 @@ async def _judge(self, candidate, history, call_config): gate = NeverCalled(patterns=patterns, judge_model="judge-model") verdict = asyncio.run(gate.check("shorter, please", [], judge_unavailable="judge setup: KeyError: x")) assert (verdict.passed, verdict.judge_error) == (True, "judge setup: KeyError: x") + + +def _judge_call(monkeypatch, model, api_base, params=None): + """The model and api_base the gate's judge handed litellm, for a judge ``model`` through ``api_base``.""" + import asyncio + import json + from types import SimpleNamespace + + import litellm + + from agent_env.config.model import ModelCallConfig + from agent_env.task_step.task_steps.user_sim_gate import UserSimGate + + sent = {} + + async def acompletion(**kwargs): + sent.update(kwargs) + content = json.dumps({"in_role": True, "reason": "ok"}) + return SimpleNamespace(choices=[SimpleNamespace(message=SimpleNamespace(content=content))]) + + monkeypatch.setattr(litellm, "acompletion", acompletion) + config = ModelCallConfig(api_key="k", api_base=api_base, params=params or {}) + asyncio.run(UserSimGate(judge_model=model)._judge("thanks, looks good", [], config)) + return sent["model"], sent.get("api_base") + + +def test_a_claude_judge_through_an_endpoint_drops_the_bases_trailing_v1(monkeypatch): + assert _judge_call(monkeypatch, "claude-sonnet-5-5", "https://llm.example/v1") == ( + "claude-sonnet-5-5", "https://llm.example") + + +def test_a_bare_judge_name_litellm_cant_place_goes_through_the_endpoint_as_openai(monkeypatch): + assert _judge_call(monkeypatch, "qwen3:8b", "https://llm.example/v1") == ( + "openai/qwen3:8b", "https://llm.example/v1") + + +def test_a_judge_with_no_endpoint_or_a_provider_prefix_keeps_its_route(monkeypatch): + assert _judge_call(monkeypatch, "claude-sonnet-5-5", None) == ("claude-sonnet-5-5", None) + assert _judge_call(monkeypatch, "openai/gpt-x", "https://llm.example/v1") == ( + "openai/gpt-x", "https://llm.example/v1") From 7abdcb46666ae1b356feec2f625428358ae4ed58 Mon Sep 17 00:00:00 2001 From: kaihackney-scale Date: Fri, 20 Nov 2026 12:58:38 -0500 Subject: [PATCH 09/18] fix(always_on): a gated read's time cap covers the gate's rewrites and judge calls read_cap_seconds allowed READ_ASKS user-sim turns, and the gate's rewrites ran against the same deadline, so a slow sim could run out of time before max_rewrites and end an otherwise working run as user_sim_error. The cap now adds a user-sim turn per rewrite and, with a judge, a judge call per message checked; wake_reserve_seconds grows with it. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/task_step/task_steps/always_on.py | 11 +++++++++-- tst/unit/task_step/test_always_on_budget.py | 11 +++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) 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 210144536..ad8f129ea 100644 --- a/src/agent_env/task_step/task_steps/always_on.py +++ b/src/agent_env/task_step/task_steps/always_on.py @@ -283,8 +283,15 @@ def settle_cap_seconds(self, contact_seconds: float = CONTACT_TIMEOUT_DEFAULT_SE def read_cap_seconds(self) -> float: """The longest one read's answer may take: READ_ASKS user sim turns, each with its grace and trajectory - fetch; an ask past it is refused, and an answer past it ends the read as a user sim error.""" - return READ_ASKS * (self.user_timeout_seconds + TURN_GRACE_SECONDS + TRAJECTORY_FETCH_SECONDS) + fetch, and with a user_sim_gate one more turn per rewrite and a judge call per check (every message, the + first and each rewrite); an ask past it is refused, and an answer past it ends the read as a user sim error.""" + asks, judging = READ_ASKS, 0.0 + gate = self.user_sim_gate + if gate is not None: + asks += gate.max_rewrites + if gate.judge_model: + judging = (gate.max_rewrites + 1) * gate.judge_timeout_seconds + return asks * (self.user_timeout_seconds + TURN_GRACE_SECONDS + TRAJECTORY_FETCH_SECONDS) + judging def wake_reserve_seconds(self, contact_seconds: float = CONTACT_TIMEOUT_DEFAULT_SECONDS) -> float: """The longest one turn of the loop, or the run's closing, can take, each part hard-capped: a clock jump's diff --git a/tst/unit/task_step/test_always_on_budget.py b/tst/unit/task_step/test_always_on_budget.py index a5bb85aa3..269951dec 100644 --- a/tst/unit/task_step/test_always_on_budget.py +++ b/tst/unit/task_step/test_always_on_budget.py @@ -258,3 +258,14 @@ async def hangs_once(run): with pytest.raises(RuntimeError, match="the opening wake ran past its worst case"): await asyncio.wait_for(rig.run(rig.step(), ctx), 10) assert ctx.metadata[ao.ALWAYS_ON_KEY]["week"]["end_reason"] == "step_error" + + +@pytest.mark.parametrize("gate", [{"patterns": True, "max_rewrites": 2}, + {"judge_model": "j", "max_rewrites": 3, "judge_timeout_seconds": 45}], + ids=["patterns", "judge"]) +def test_a_gated_read_has_time_for_every_rewrite_and_judge_call_and_the_reserve_grows_with_it(gate): + plain, gated = _step(), _step(user_sim_gate=gate) + turn = plain.user_timeout_seconds + ao.TURN_GRACE_SECONDS + ao.TRAJECTORY_FETCH_SECONDS + judging = (gate["max_rewrites"] + 1) * gate["judge_timeout_seconds"] if "judge_model" in gate else 0 + assert gated.read_cap_seconds() == (ao.READ_ASKS + gate["max_rewrites"]) * turn + judging + assert gated.wake_reserve_seconds() - plain.wake_reserve_seconds() == gated.read_cap_seconds() - plain.read_cap_seconds() From 278f28d780984beee6dacd2f6c6c03f5a0bc733d Mon Sep 17 00:00:00 2001 From: kaihackney-scale Date: Fri, 20 Nov 2026 17:14:00 -0500 Subject: [PATCH 10/18] fix(user_sim_gate): address review: phrases users say, a judge that clears phrase-only hits, typed settings - Phrases a user says no longer count: "I don't have access", "should I send", "I'll pull", "I can send it", "I apologize for the", "send me the results"; "has been sent/updated" counts only at a report's length. - With a judge, an in-role verdict clears a hit on a phrase alone (PHRASE_REASONS); a report's shape and length stays a failure. - UserSimGate checks each setting's type and range when the task loads, not mid-run. - prompt_agent's read holds the answer delivered, with first_message for the first one, as always_on's does; a message held back for good is a no_reply. - A judge that can't be set up fails the step when patterns are off, in both loops; with patterns on, they still stand alone. - rate_user_satisfaction skips a run the gate cut off as the user sim's doing, not the agent's. Co-Authored-By: Claude Opus 5.5 --- .../agent/rate_user_satisfaction.py | 4 + .../task_step/task_steps/always_on.py | 11 ++- .../task_step/task_steps/prompt_agent.py | 24 ++++-- .../task_step/task_steps/user_sim_gate.py | 75 ++++++++++++++----- .../task_step/test_always_on_user_sim_gate.py | 17 +++++ .../test_prompt_agent_built_in_user_sim.py | 6 +- .../task_step/test_prompt_agent_user_side.py | 11 +-- tst/unit/task_step/test_user_sim_gate.py | 57 +++++++++++++- .../task_step/test_user_sim_satisfaction.py | 15 ++++ 9 files changed, 187 insertions(+), 33 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 2098450d1..8814e6a35 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 @@ -369,6 +369,10 @@ async def _prompt_agent_session(context: TaskStepContext, run_id: str, response: if response.error_type == "user_sim_error": session.skipped = f"the user sim failed: {(response.error_message or '').removeprefix(SIM_FAILED_PREFIX)}" return session + if response.error_type == "user_sim_invalid": + # The user-sim gate cut the conversation off: the user sim, not the agent, broke it. + session.skipped = "the user sim's message still read as the assistant's after its rewrites" + return session if response.error_type or response.error_message: session.skipped = "the agent's turn failed" return session 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 e2ef7aae7..99a3d5fc2 100644 --- a/src/agent_env/task_step/task_steps/always_on.py +++ b/src/agent_env/task_step/task_steps/always_on.py @@ -129,7 +129,7 @@ fetch_native_trajectory, prescribe_formats, ) -from agent_env.task_step.task_steps.user_sim_gate import judge_call_config, run_gate +from agent_env.task_step.task_steps.user_sim_gate import judge_call_config, judge_setup_failed, run_gate from agent_env.task_step.task_steps.agent.user_sim_common import iso as _iso, person_of, task_zone, utc as _utc from agent_env.task_step.task_steps.agent.user_sim_common import attached, file_name, for_agent, recorded_opening @@ -1555,7 +1555,10 @@ async def ask(text: str) -> dict: user_sim_turns=ans.get("turns", len(calls)), shown=ans.get("shown"), past_turn_cap=ans.get("past_turn_cap"), last_read=last, retried=ans.get("retried"), first_answer=ans.get("first_answer"), - **({"user_sim_gate": gate_record} if gate_record else {})) + **({"user_sim_gate": gate_record} if gate_record else {}), + # as prompt_agent's read: what reached the agent is ``message``, what she first wrote this + **({"first_message": gate_record["first_message"]} + if gate_record and "first_message" in gate_record else {})) outcome = ans.get("outcome") said = (ans.get("message") or "").strip() hook = {"hook": HOOK_NAME, "turn": self.wakes, "read_at": _iso(now), @@ -1601,8 +1604,8 @@ async def _gate(self, ans: dict, ask) -> tuple[dict, dict]: if self.gate_call_config is None and self.gate_setup_error is None and gate.judge_model: try: self.gate_call_config = judge_call_config(gate, self.ctx.metadata.get("user_overrides", {})) - except Exception as e: # as in prompt_agent: the patterns' verdict stands, with the error on it - self.gate_setup_error = f"judge setup: {type(e).__name__}: {e}"[: gate.RECORDED_ERROR_CHARS] + except Exception as e: # as in prompt_agent: the patterns' verdict stands; with patterns off, it raises + self.gate_setup_error = judge_setup_failed(gate, e) logger.warning(f"always_on: user-sim gate {self.gate_setup_error}; using patterns only") latest = {"ans": ans} verdicts: list[dict] = [] 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 ed532f46e..03f059b2b 100644 --- a/src/agent_env/task_step/task_steps/prompt_agent.py +++ b/src/agent_env/task_step/task_steps/prompt_agent.py @@ -50,7 +50,7 @@ from agent_env.task_step.task_step import RetryConfig, StepRole, TaskStep, TaskStepDependency from agent_env.task_step.task_steps.notification_delivery import delivered_parts, labels_zone, next_message, take_due from agent_env.task_step.task_steps.post_turn_hooks import PostTurnHooks, run_post_turn_hooks, validate_hook_specs -from agent_env.task_step.task_steps.user_sim_gate import UserSimGate, judge_call_config, run_gate +from agent_env.task_step.task_steps.user_sim_gate import UserSimGate, judge_call_config, judge_setup_failed, run_gate from agent_env.task_step.task_steps.agent import user_sim_versions from agent_env.task_step.task_steps.agent.user_sim_common import iso, person_of, task_zone, utc from agent_env.task_step.task_steps.agent.user_sim_common import attached, for_agent, opening_text, recorded_opening @@ -1279,12 +1279,12 @@ async def _gated(self, number: int, answer: dict, ask_rewrite) -> dict: answer shaped as ``ask``'s, up to the gate's limit (``run_gate``).""" gate = self._gate if self._gate_call_config is None and self._gate_judge_setup_error is None and gate.judge_model: - # Judge setup (its key, its endpoint) can fail as the judge call can: like a call, it never takes the - # conversation down; the patterns' verdict stands, with the error recorded on it (run_gate). + # Judge setup (its key, its endpoint) failing leaves the patterns' verdict standing, with the error + # recorded on it (run_gate); with patterns off it fails the step (judge_setup_failed). try: self._gate_call_config = judge_call_config(gate, self._context.metadata.get("user_overrides", {})) except Exception as e: - self._gate_judge_setup_error = f"judge setup: {type(e).__name__}: {e}"[: gate.RECORDED_ERROR_CHARS] + self._gate_judge_setup_error = judge_setup_failed(gate, e) logger.warning(f"user-sim gate {self._gate_judge_setup_error}; using patterns only") latest = {"answer": answer} @@ -1306,6 +1306,8 @@ def on_verdict(attempt: int, text: str, verdict) -> None: return latest["answer"] self._context.metadata.setdefault("user_sim_invalid", {})[self._step.id] = { "turn": number, "reasons": outcome.reasons()} + if self._built_in is not None: + self._built_in.withhold() if gate.on_fail == "fail": self.gate_failure = (f"user-sim message at turn {number} still reads as the assistant's after " f"{gate.max_rewrites} rewrite(s): {'; '.join(outcome.reasons())[:500]}") @@ -1439,10 +1441,20 @@ async def ask(text: str) -> dict: return {"message": [{"kind": "text", "text": ans["message"]}], "end_after": "user_done"} return {"end": "user_done" if outcome == "done" else "user_no_reply"} + def withhold(self) -> None: + """The gate held the read's answer back for good (its rewrites failed too): as in always_on, the read's record + becomes a no_reply with no message, keeping ``first_message`` and ``gate_rewrites``.""" + reads = self._context.metadata.get("user_sim_reads", {}).get(self._step.id) or [] + if reads: + reads[-1].setdefault("first_message", reads[-1].get("message")) + reads[-1].update(outcome="no_reply", message="", used=None) + async def rewrite(self, number: int, note: str, ask_user_sim) -> dict: """The user's answer again, after the user-sim gate held its message back with ``note``, in the same session; shaped as ``ask``'s. It replaces the held answer in the reply count, so ``max_replies`` holds whichever answer is - sent. The read's record keeps what the user sim first answered and lists each rewrite under ``gate_rewrites``.""" + sent. As always_on's does, the read's record holds the answer delivered (``outcome``, ``message``, ``used``, + ``schema_errors`` are the latest rewrite's), keeps what the user sim first answered as ``first_message``, and + lists each rewrite under ``gate_rewrites``.""" got = await ask_user_sim(note) ans = user_sim_versions.parse(got["structured"] if isinstance(got.get("structured"), dict) else got.get("text")) error = got.get("error") @@ -1450,7 +1462,9 @@ async def rewrite(self, number: int, note: str, ask_user_sim) -> dict: rewrite.update(user_sim_error=error, user_sim_trajectory_url=got.get("trajectory_url")) reads = self._context.metadata.get("user_sim_reads", {}).get(self._step.id) or [] if reads: + reads[-1].setdefault("first_message", reads[-1].get("message")) reads[-1].setdefault("gate_rewrites", []).append(rewrite) + reads[-1].update({k: v for k, v in rewrite.items() if k in ("outcome", "message", "used", "schema_errors")}) outcome, said = ans.get("outcome"), (ans.get("message") or "").strip() if self.history: held = self.history[-1]["answer"] diff --git a/src/agent_env/task_step/task_steps/user_sim_gate.py b/src/agent_env/task_step/task_steps/user_sim_gate.py index 00eaa9611..e40576fb1 100644 --- a/src/agent_env/task_step/task_steps/user_sim_gate.py +++ b/src/agent_env/task_step/task_steps/user_sim_gate.py @@ -12,6 +12,9 @@ - ``judge_model``: one model call that reads the last turns and the candidate message and says whether the message is written as the user. +With both, a judge that reads the message as the user's clears a hit on a phrase alone (``PHRASE_REASONS``), which +counts at any length; a hit on a report's shape and length stays a failure. + Opt in with ``user_sim_gate`` on a ``prompt_agent`` step whose user is a user-sim agent-env deployed: a peer user-sim, or the built-in one deploy_user_sim_agent deploys, whose rewrite is parsed as its own answer. ``always_on`` applies it to each of the built-in user-sim's answers. A step type that runs its own conversation loop applies the gate @@ -46,23 +49,24 @@ r"rewrote|built|calculated|ran)\b", re.I, ) -_NOW_LIVE = re.compile(r"\b(?:now live|is now (?:up|live|updated)|has been (?:updated|created|sent|posted))\b", re.I) +_NOW_LIVE = re.compile(r"\b(?:now live|is now (?:up|live))\b", re.I) +# A user says these about someone else's work too ("the invoice has been sent to me already"), so they count only on a +# message long enough to be a report. _DELIVERED = re.compile( r"\b(?:(?:emails?|messages?|drafts?|replies|invites?|notes?) (?:sent|drafted|posted|scheduled)\b|incorporated\b|" - r"(?:the|a|my) (?:cleaner|updated|revised|corrected|final) version\b)", + r"(?:the|a|my) (?:cleaner|updated|revised|corrected|final) version\b|has been (?:updated|created|sent|posted))", re.I, ) +# Phrases the assistant says and a user doesn't, at any length. A user does say "I don't have access to that folder", +# "Should I send you the spreadsheet?", "I'll pull the numbers tonight", "I can send it to you", "I apologize for the +# confusion" and "send me the results", so those aren't here. _AS_ASSISTANT = re.compile( r"\b(?:as an ai|i'?m an? (?:ai|assistant|language model)|my previous (?:answer|response|reply)|" - r"i apologi[sz]e for (?:the|my)|let me know if you'?d like me to|" - r"would you like me to|want me to (?:draft|send|update|create|go ahead)|" + r"i apologi[sz]e for my (?:previous|earlier|last) (?:answer|response|reply|message)|" + r"let me know if you'?d like me to|would you like me to|want me to (?:draft|send|update|create|go ahead)|" r"standing by|ready when you are|parked until|" r"anything else (?:you(?:'d)? (?:want|like) (?:me )?to|to (?:cover|look at|dig into))|" - r"what do you want (?:me )?to do next|should i (?:send|draft|go ahead)|" - r"i'll (?:draft|fold|pull|search|put together|pick (?:it |this )?up|rerun|re-run)|" - r"i can (?:send|draft|search|pull) (?:it|that|them)|" - r"i (?:don't|do not) have (?:the )?(?:tools|access)|corrections (?:noted|taken)|" - r"(?:send|drop) me (?:whatever|that phrase|the results)|" + r"what do you want (?:me )?to do next|corrections (?:noted|taken)|" r"how (?:can|may) i (?:help|assist)|i'?m (?:here|ready) to help|what would you like (?:me )?to (?:work on|do) today)\b", re.I, ) @@ -85,17 +89,24 @@ class PatternLimits: WORK_REPORT_MIN_PHRASES: ClassVar[int] = 2 +TALKS_LIKE_THE_ASSISTANT = "it talks like the assistant (offers to do the work, waits on the user, or speaks as the AI)" +NOW_LIVE = "it says something is now live" +# The reasons a phrase gives at any length: a judge that reads the message as the user's clears them. The rest need a +# report's shape and length, and stay failures whatever the judge says. +PHRASE_REASONS = frozenset({TALKS_LIKE_THE_ASSISTANT, NOW_LIVE}) + + def pattern_reasons(text: str) -> list[str]: """Why ``text`` reads as the assistant's message, one reason per pattern that matched; empty if none.""" lim = PatternLimits reasons = [] n = len(text) if _AS_ASSISTANT.search(text): - reasons.append("it talks like the assistant (offers to do the work, waits on the user, or speaks as the AI)") + reasons.append(TALKS_LIKE_THE_ASSISTANT) if _REPORT_OPENING.search(text) and n > lim.REPORT_OPENING_MIN_CHARS: reasons.append("it opens like a report of work done") if _NOW_LIVE.search(text): - reasons.append("it says something is now live or updated") + reasons.append(NOW_LIVE) if _DELIVERED.search(text) and n > lim.DELIVERED_MIN_CHARS: reasons.append("it reports something delivered or revised") formatted = (_TABLE.search(text) or len(_HEADER.findall(text)) >= lim.FORMATTED_MIN_HEADERS @@ -189,10 +200,24 @@ class UserSimGate: RECORDED_REASON_CHARS: ClassVar[int] = 500 def __post_init__(self) -> None: - if self.on_fail not in ON_FAIL: - raise ValueError(f"user_sim_gate.on_fail must be one of {ON_FAIL}, not {self.on_fail!r}") - if self.max_rewrites < 0: - raise ValueError("user_sim_gate.max_rewrites must be >= 0") + """Refuse a setting of the wrong type or range here, when the task loads, rather than mid-conversation.""" + def need(ok: bool, name: str, what: str) -> None: + if not ok: + raise ValueError(f"user_sim_gate.{name} must be {what}, not {getattr(self, name)!r}") + + def whole(v: object) -> bool: # an int, and not a bool (which is one in Python) + return isinstance(v, int) and not isinstance(v, bool) + + need(isinstance(self.patterns, bool), "patterns", "true or false") + need(self.judge_model is None or (isinstance(self.judge_model, str) and bool(self.judge_model.strip())), + "judge_model", "a model name or null") + need(whole(self.max_rewrites) and self.max_rewrites >= 0, "max_rewrites", "a whole number >= 0") + need(self.on_fail in ON_FAIL, "on_fail", f"one of {ON_FAIL}") + need(whole(self.context_turns) and self.context_turns >= 0, "context_turns", "a whole number >= 0") + need(whole(self.judge_min_chars) and self.judge_min_chars >= 0, "judge_min_chars", "a whole number >= 0") + need(whole(self.context_chars) and self.context_chars > 0, "context_chars", "a whole number > 0") + need(isinstance(self.judge_timeout_seconds, (int, float)) and not isinstance(self.judge_timeout_seconds, bool) + and self.judge_timeout_seconds > 0, "judge_timeout_seconds", "a number > 0") if not self.patterns and not self.judge_model: raise ValueError("user_sim_gate needs patterns, a judge_model, or both") @@ -213,8 +238,9 @@ def to_dict(self) -> dict: async def check(self, candidate: str, history: list[tuple[str, str]], *, call_config=None, judge_unavailable: Optional[str] = None) -> GateVerdict: """Check one message. ``history`` is the conversation so far as ``(role, text)``, role user/assistant. - A judge call that errors or can't be parsed doesn't fail the message: the patterns' verdict stands. So does a - judge that couldn't be set up (``judge_unavailable``, the reason), which isn't called.""" + A judge that reads the message as the user's clears a hit on a phrase alone (``PHRASE_REASONS``); a shape hit + stays a failure. A judge call that errors or can't be parsed doesn't fail the message: the patterns' verdict + stands. So does a judge that couldn't be set up (``judge_unavailable``, the reason), which isn't called.""" reasons = pattern_reasons(candidate) if self.patterns else [] verdict = GateVerdict(passed=not reasons, pattern_reasons=reasons) if self.judge_model and judge_unavailable is not None: @@ -234,6 +260,9 @@ async def check(self, candidate: str, history: list[tuple[str, str]], *, call_co verdict.judge_reason = str(judged.get("reason", ""))[: self.RECORDED_REASON_CHARS] if not judged["in_role"] and (reasons or len(candidate) >= self.judge_min_chars): verdict.passed = False + elif judged["in_role"] and reasons and set(reasons) <= PHRASE_REASONS: + verdict.passed = True # a phrase alone, which the judge reads as the user's + verdict.cleared_by_judge = True return verdict async def _judge(self, candidate: str, history: list[tuple[str, str]], route) -> Optional[dict]: @@ -261,6 +290,7 @@ class GateVerdict: judge_in_role: Optional[bool] = None judge_reason: Optional[str] = None judge_error: Optional[str] = None + cleared_by_judge: Optional[bool] = None # the judge read a phrase-only hit as the user's def reasons(self) -> list[str]: out = list(self.pattern_reasons) @@ -336,6 +366,17 @@ async def run_gate( JUDGE_KEY_HOW = "judge_litellm_api_key, or litellm_api_key, in the run's overrides" +def judge_setup_failed(gate: UserSimGate, error: Exception) -> str: + """What a step records when the gate's judge can't be set up (``judge_call_config`` raised), so the patterns' + verdict stands. With patterns off nothing would check the user sim's messages for the rest of the run, and a + setup failure won't recover, so that raises instead.""" + reason = f"judge setup: {type(error).__name__}: {error}" + if not gate.patterns: + raise RuntimeError(f"user_sim_gate: {reason}; with patterns off, nothing would check the user sim's " + "messages, so the step fails rather than run unchecked") from error + return reason[: gate.RECORDED_ERROR_CHARS] + + def judge_call_config(gate: UserSimGate, user_overrides: dict): """The route of the gate's judge calls (a ``model_call.ModelRoute``), honoring a run's judge or LiteLLM overrides as the rubrics verifier does; None without a judge. Raises ConfigError, as a setup failure, for an diff --git a/tst/unit/task_step/test_always_on_user_sim_gate.py b/tst/unit/task_step/test_always_on_user_sim_gate.py index f4e0a0779..7d4c1ff50 100644 --- a/tst/unit/task_step/test_always_on_user_sim_gate.py +++ b/tst/unit/task_step/test_always_on_user_sim_gate.py @@ -50,6 +50,7 @@ async def test_an_answer_that_reads_as_the_assistants_is_held_back_and_the_rewri gate = read["user_sim_gate"] assert [(v["attempt"], v["passed"]) for v in gate["verdicts"]] == [(0, False), (1, True)] assert gate["first_message"] == _SWAP and gate["invalid"] is False + assert read["first_message"] == _SWAP # where prompt_agent's read keeps it too assert [r["message"] for r in gate["rewrites"]] == ["do those numbers hold up?"] assert "user_sim_invalid" not in ctx.metadata assert rig.record(ctx)["end_reason"] != "user_sim_invalid" @@ -103,3 +104,19 @@ async def test_without_the_gate_nothing_is_checked(monkeypatch, tmp_path): ctx = await plain.run(plain.step(max_wakes=4)) assert "user_sim_gate" not in plain.events(ctx, "user_sim_read")[0] assert _got(plain, "None of the three reported numbers") # unchanged without the gate + + + +@pytest.mark.asyncio +async def test_a_judge_only_gate_whose_judge_cant_be_set_up_fails_the_step(monkeypatch, tmp_path): + # A setup failure won't recover, and with patterns off nothing else would check her answers. + def no_endpoint(model, **kw): + raise KeyError("no endpoint configured for judge-model") + + monkeypatch.setattr("agent_env.config.model_call.resolve_route", no_endpoint) + rig = Rig(monkeypatch, tmp_path, agent=_messages_once, answers=[{"outcome": "reply", "message": "looks good"}]) + await rig.arm() + + with pytest.raises(Exception, match="judge setup: KeyError.*with patterns off"): + await rig.run(rig.step(max_wakes=4, user_sim_gate={"patterns": False, "judge_model": "judge-model"})) + assert not _got(rig, "looks good") 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 be5e77bc0..eac838df7 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 @@ -441,7 +441,8 @@ async def test_the_gate_holds_back_a_built_in_users_answer_that_reads_as_the_ass verdicts = ctx.metadata["user_sim_gate"]["talk"] assert [(v["turn"], v["attempt"], v["passed"]) for v in verdicts] == [(1, 0, False), (1, 1, True), (2, 0, True)] first = _reads(ctx)[0] - assert first["message"] == _SWAP # the read keeps what she first answered, for whoever grades her + # As in always_on: the read holds what reached the agent, and keeps what she first answered for whoever grades her. + assert (first["message"], first["first_message"]) == ("do those numbers hold up?", _SWAP) assert [(r["outcome"], r["message"], r["used"]) for r in first["gate_rewrites"]] == [ ("reply", "do those numbers hold up?", "D1")] assert "user_sim_invalid" not in ctx.metadata @@ -458,6 +459,9 @@ async def test_a_built_in_users_answer_that_still_fails_ends_the_run_and_fails_t assert [v["passed"] for v in ctx.metadata["user_sim_gate"]["talk"]] == [False, False, False] assert ctx.metadata["user_sim_invalid"]["talk"]["turn"] == 1 assert len(_reads(ctx)[0]["gate_rewrites"]) == 2 + # Nothing reached the agent, so the read is a no_reply with no message, as in always_on. + read = _reads(ctx)[0] + assert (read["outcome"], read["message"], read["first_message"]) == ("no_reply", "", _SWAP) # Verifiers skip a response with an error_type, so a cut-off conversation isn't graded as the agent's answer. assert ctx.prompt_responses[-1].error_type == "user_sim_invalid" assert ctx.prompt_responses[-1].error_message.startswith("user_sim_gate: user-sim message at turn 1") diff --git a/tst/unit/task_step/test_prompt_agent_user_side.py b/tst/unit/task_step/test_prompt_agent_user_side.py index 1855a9521..9b0b06417 100644 --- a/tst/unit/task_step/test_prompt_agent_user_side.py +++ b/tst/unit/task_step/test_prompt_agent_user_side.py @@ -641,7 +641,9 @@ def no_endpoint(model, **kw): @pytest.mark.asyncio -async def test_a_judge_only_gate_whose_setup_fails_sends_the_message_on_with_the_error_recorded(monkeypatch): +async def test_a_judge_only_gate_whose_setup_fails_fails_the_step_before_any_unchecked_message_reaches_the_agent( + monkeypatch): + # A setup failure won't recover, and with patterns off nothing else would check the user sim's messages. def no_endpoint(model, **kw): raise KeyError("no endpoint configured for judge-model") @@ -649,8 +651,7 @@ def no_endpoint(model, **kw): peers = Peers(monkeypatch, {AGENT: [text("draft one"), text("draft two")], USER: [sim("shorter, please")]}) ctx = _context(user_card=_USER_SIM_CARD) - await _gated(patterns=False, judge_model="judge-model").execute(ctx) + with pytest.raises(RuntimeError, match="judge setup: KeyError.*with patterns off"): + await _gated(patterns=False, judge_model="judge-model").execute(ctx) - (verdict,) = ctx.metadata["user_sim_gate"]["talk"] - assert verdict["passed"] is True and verdict["judge_error"].startswith("judge setup: KeyError") - assert peers.requests(ctx)[-2] == send(AGENT, text("shorter, please"), "", "") + assert not any(r == send(AGENT, text("shorter, please"), "", "") for r in peers.requests(ctx)) diff --git a/tst/unit/task_step/test_user_sim_gate.py b/tst/unit/task_step/test_user_sim_gate.py index f6bd65d5c..828971152 100644 --- a/tst/unit/task_step/test_user_sim_gate.py +++ b/tst/unit/task_step/test_user_sim_gate.py @@ -1,5 +1,7 @@ """The user-sim gate's own checks: the patterns, the judge's output parsing and the history it is shown.""" +import pytest + from agent_env.task_step.task_steps.user_sim_gate import ( GateVerdict, parse_judge, pattern_reasons, render_history, rewrite_request) @@ -13,6 +15,14 @@ def test_the_patterns_pass_what_users_write(): "Here's the email my manager sent, pasted so you have it:\n\n> Please hold the order until Friday." + _FILLER, "No, go ahead and send it. Use the second draft.", "I checked my inbox and there's nothing from them yet.", + "I don't have access to that folder.", + "Should I send you the spreadsheet?", + "I'll pull the numbers from my bank tonight.", + "I can send it to you after lunch.", + "I apologize for the confusion, I meant March.", + "The invoice has been sent to me already.", + "My manager said the page has been updated.", + "ok, send me the results when you have them", ]: assert pattern_reasons(message) == [], message @@ -24,7 +34,8 @@ def test_the_patterns_catch_the_assistants_side(): "Understood. Standing by.": "it talks like the assistant", "Want me to draft the reply to them now?": "it talks like the assistant", "I'm ready to help! What would you like to work on today?": "it talks like the assistant", - "The page is now live, with the corrected totals." : "it says something is now live or updated", + "The page is now live, with the corrected totals." : "it says something is now live", + "I apologize for my previous answer, here is the corrected one.": "it talks like the assistant", "Thanks for those corrections, incorporated. The cleaner version:" + _FILLER: "it reports something delivered", "| Item | Was | Is |\n|---|---|---|\n| A | 1 | 2 |\n" + _FILLER * 2: "it is a formatted deliverable", "I've reviewed the contract and I've compared it with the invoice." + _FILLER: "it reports checking or building", @@ -198,3 +209,47 @@ async def complete(route, messages, *, timeout, response_format=None): assert resolved == [("claude-sonnet-5-5", "secret:k", "https://llm.example/v1", "user_sim_gate")] assert sent == [("route", 45, "user_sim_gate")] and judged["in_role"] is True + + + +def _judged(in_role): + from agent_env.task_step.task_steps.user_sim_gate import UserSimGate + + class Gate(UserSimGate): + async def _judge(self, candidate, history, call_config): + return {"in_role": in_role, "reason": "judged"} + + return Gate(judge_model="judge-model") + + +def test_a_judge_reading_it_as_the_user_clears_a_phrase_but_not_a_reports_shape(): + import asyncio + + phrase = "Understood. Standing by." + shape = "Done. Here's what I found when I went through the files." + _FILLER + cleared = asyncio.run(_judged(True).check(phrase, [])) + assert (cleared.passed, cleared.cleared_by_judge) == (True, True) and cleared.pattern_reasons + assert asyncio.run(_judged(True).check(shape, [])).passed is False # shape + length: a failure whatever the judge + assert asyncio.run(_judged(False).check(phrase, [])).passed is False + + + +@pytest.mark.parametrize("settings, field", [ + ({"max_rewrites": 1.5}, "max_rewrites"), ({"max_rewrites": True}, "max_rewrites"), + ({"max_rewrites": -1}, "max_rewrites"), ({"judge_min_chars": None}, "judge_min_chars"), + ({"patterns": "false"}, "patterns"), ({"context_turns": "4"}, "context_turns"), + ({"context_chars": 0}, "context_chars"), ({"judge_timeout_seconds": 0}, "judge_timeout_seconds"), + ({"judge_model": ""}, "judge_model"), ({"on_fail": "skip"}, "on_fail"), +], ids=lambda v: str(v)) +def test_a_setting_of_the_wrong_type_or_range_is_refused_when_the_task_loads(settings, field): + from agent_env.task_step.task_steps.user_sim_gate import UserSimGate + + with pytest.raises(ValueError, match=f"user_sim_gate.{field} must be"): + UserSimGate.from_dict(settings) + + +def test_good_settings_load_and_round_trip(): + from agent_env.task_step.task_steps.user_sim_gate import UserSimGate + + gate = UserSimGate.from_dict({"patterns": False, "judge_model": "j", "max_rewrites": 0, "judge_timeout_seconds": 30}) + assert UserSimGate.from_dict(gate.to_dict()) == gate diff --git a/tst/unit/task_step/test_user_sim_satisfaction.py b/tst/unit/task_step/test_user_sim_satisfaction.py index 8c9a39e40..c7361480c 100644 --- a/tst/unit/task_step/test_user_sim_satisfaction.py +++ b/tst/unit/task_step/test_user_sim_satisfaction.py @@ -519,6 +519,21 @@ async def test_a_prompt_agent_chat_the_user_sim_broke_is_not_rated(monkeypatch): assert rating["skipped"] == "the user sim failed: state failed" and rating["score"] is None +@pytest.mark.asyncio +async def test_a_prompt_agent_chat_the_user_sim_gate_cut_off_is_not_rated_and_the_agent_isnt_blamed(monkeypatch): + from agent_env.task_step.context import PromptResponse + + ctx = await _context(monkeypatch) + ctx.metadata.setdefault("a2a_conversations", {})["talk"] = None + ctx.prompt_responses.append(PromptResponse(prompt_id="p", response="draft", error_type="user_sim_invalid", + error_message="user_sim_gate: user-sim message at turn 1 ...", + step_id="talk")) + await _hannah_rater().execute(ctx) + rating = ctx.metadata[SATISFACTION_KEY]["talk"] + assert rating["skipped"] == "the user sim's message still read as the assistant's after its rewrites" + assert rating["score"] is None + + @pytest.mark.asyncio async def test_a_prompt_agent_chat_whose_agent_turn_failed_is_not_rated(monkeypatch): Peers(monkeypatch, {AGENT: [("failed", text("it broke"))], USER: []}) From 730fe2f1cf9dc8d1aaf51a3809c148269ebcfef9 Mon Sep 17 00:00:00 2001 From: kaihackney-scale Date: Fri, 20 Nov 2026 17:19:43 -0500 Subject: [PATCH 11/18] fix(user_sim_gate): context_turns 0 shows the judge no history history[-0:] is the whole list, so 0 sent the entire conversation instead of none. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/task_step/task_steps/user_sim_gate.py | 4 ++-- tst/unit/task_step/test_user_sim_gate.py | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/agent_env/task_step/task_steps/user_sim_gate.py b/src/agent_env/task_step/task_steps/user_sim_gate.py index e40576fb1..ce3825c74 100644 --- a/src/agent_env/task_step/task_steps/user_sim_gate.py +++ b/src/agent_env/task_step/task_steps/user_sim_gate.py @@ -156,9 +156,9 @@ def pattern_reasons(text: str) -> list[str]: def render_history(history: list[tuple[str, str]], turns: int, max_chars: int) -> str: - """The last ``turns`` messages as ``USER:`` / ``ASSISTANT:`` blocks, each cut to ``max_chars``.""" + """The last ``turns`` messages as ``USER:`` / ``ASSISTANT:`` blocks, each cut to ``max_chars``; none for 0.""" out = [] - for role, text in history[-turns:]: + for role, text in (history[-turns:] if turns else []): # history[-0:] would be all of it body = text if len(text) <= max_chars else text[:max_chars] + f"\n[… {len(text) - max_chars} more characters]" out.append(f"{role.upper()}:\n{body}") return "\n\n".join(out) or "(nothing yet)" diff --git a/tst/unit/task_step/test_user_sim_gate.py b/tst/unit/task_step/test_user_sim_gate.py index 828971152..3acc02177 100644 --- a/tst/unit/task_step/test_user_sim_gate.py +++ b/tst/unit/task_step/test_user_sim_gate.py @@ -58,6 +58,7 @@ def test_the_history_shows_the_last_turns_each_cut_to_size(): assert shown.startswith("ASSISTANT:\nxxxxxxxxxx\n[… 40 more characters]") assert "first" not in shown and shown.endswith("ASSISTANT:\nthird") assert render_history([], turns=4, max_chars=10) == "(nothing yet)" + assert render_history(history, turns=0, max_chars=10) == "(nothing yet)" # context_turns 0: no history def test_the_rewrite_request_names_why_and_says_it_is_not_from_the_assistant(): From 5df699e8b4d6c32618f99b7408a05fdd8c16721f Mon Sep 17 00:00:00 2001 From: kaihackney-scale Date: Fri, 20 Nov 2026 19:28:03 -0500 Subject: [PATCH 12/18] fix(always_on): a gate rewrite is read with the plugin's parse; a gate-failed run isn't rated - A rewrite is parsed with the user-sim plugin's own parse(raw), as its answers are, so a plugin with another answer format keeps its rewrites instead of reading them as an empty no_reply. A plugin without parse can't support rewrites, so user_sim_gate with one is refused when the run starts. - rate_user_satisfaction skips an always_on run the gate failed as an error (on_fail "fail", error_type user_sim_invalid); a plain on_fail "end" sets no error and is still rated. Co-Authored-By: Claude Opus 5.5 --- .../agent/rate_user_satisfaction.py | 5 ++ .../task_step/task_steps/always_on.py | 9 +++- tst/unit/task_step/always_on_harness.py | 3 ++ .../task_step/test_always_on_user_sim_gate.py | 48 +++++++++++++++++++ .../task_step/test_user_sim_satisfaction.py | 12 +++++ 5 files changed, 75 insertions(+), 2 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 8814e6a35..89cc8cc22 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 @@ -341,6 +341,11 @@ def _always_on_session(record: dict) -> _Session: if record.get("end_reason") in ERROR_ENDS: session.skipped = f"the run ended on {record['end_reason']}" return session + if record.get("error_type") == "user_sim_invalid": + # The user-sim gate cut the run off as an error (on_fail "fail"): the user sim broke it, not the agent. A plain + # on_fail "end" sets no error, and the run is rated as one that ended. + session.skipped = "the user sim's answer still read as the assistant's after its rewrites" + return session timeline = record.get("timeline_tail") or [] if record.get("object_url"): try: 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 99a3d5fc2..94329c869 100644 --- a/src/agent_env/task_step/task_steps/always_on.py +++ b/src/agent_env/task_step/task_steps/always_on.py @@ -502,6 +502,11 @@ async def go(self) -> None: raise StepContextError(f"always_on: the user sim agent '{us['agent_name']}' is not deployed") self.user_url = self.user_agent.a2a_url or self.user_agent.api_url self.plugin = await self._load_plugin(us.get("plugin")) + if self.step.user_sim_gate is not None and not callable(getattr(self.plugin, "parse", None)): + # A rewrite is the user sim's answer again, in the plugin's own format: without its parse, a rewrite + # would read as nothing and never reach the agent. + raise ValueError(f"always_on: user_sim_gate needs the user sim's plugin to define parse(raw), which reads " + f"one of its answers as answer() does; plugin {us.get('plugin')!r} has none") self.tz = ZoneInfo(self.zone) self.clock_envs = [d for d in ctx.deployed_envs if d.supports(EXT_CLOCK_URI, "state")] @@ -1613,8 +1618,8 @@ async def _gate(self, ans: dict, ask) -> tuple[dict, dict]: async def rewrite(note: str) -> Optional[str]: got = await ask(note) - new = user_sim_versions.parse(got["structured"] if isinstance(got.get("structured"), dict) - else got.get("text")) + # The plugin's own parse: a plugin with another answer format reads its rewrite as it reads its answers. + new = self.plugin.parse(got["structured"] if isinstance(got.get("structured"), dict) else got.get("text")) rewrites.append({**{k: new.get(k) for k in ("outcome", "message", "used", "schema_errors")}, "user_sim_error": got.get("error")}) if got.get("error"): # read() ends the run on it (user_sim_error), as on any failed ask diff --git a/tst/unit/task_step/always_on_harness.py b/tst/unit/task_step/always_on_harness.py index 8e40c3bcb..e68b6a19b 100644 --- a/tst/unit/task_step/always_on_harness.py +++ b/tst/unit/task_step/always_on_harness.py @@ -20,6 +20,7 @@ from agent_env.env.gateway.triggers import TriggerEngine from agent_env.task_step.context import DeployedAgent, TaskStepContext from agent_env.task_step.task_steps import always_on as ao +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 GATEWAY = "http://gateway.test" @@ -295,4 +296,6 @@ async def answer(version, person, history, read, ask): rig.reads.append(read) return rig.answers.pop(0) if rig.answers else {"outcome": "no_reply", "message": ""} + parse = staticmethod(user_sim_versions.parse) # its answers (user_texts) are in our format + return Plugin diff --git a/tst/unit/task_step/test_always_on_user_sim_gate.py b/tst/unit/task_step/test_always_on_user_sim_gate.py index 7d4c1ff50..38e944b47 100644 --- a/tst/unit/task_step/test_always_on_user_sim_gate.py +++ b/tst/unit/task_step/test_always_on_user_sim_gate.py @@ -120,3 +120,51 @@ def no_endpoint(model, **kw): with pytest.raises(Exception, match="judge setup: KeyError.*with patterns off"): await rig.run(rig.step(max_wakes=4, user_sim_gate={"patterns": False, "judge_model": "judge-model"})) assert not _got(rig, "looks good") + + +class _OwnFormatPlugin: + """A plugin whose user sim answers "REPLY: " instead of our JSON, with its own parse.""" + + def __init__(self, answers): + self.answers = list(answers) + + def setup(self, version, person): + return {"system_prompt": "you are linda", "output_format": None} + + async def answer(self, version, person, history, read, ask): + return self.answers.pop(0) + + @staticmethod + def parse(raw): + text = raw if isinstance(raw, str) else "" + return {"outcome": "reply", "message": text.removeprefix("REPLY: "), "used": "none"} if text else {} + + +@pytest.mark.asyncio +async def test_a_plugins_rewrite_is_read_with_its_own_parse_and_reaches_the_agent(monkeypatch, tmp_path): + rig = Rig(monkeypatch, tmp_path, agent=_messages_once, user_texts=("REPLY: do those numbers hold up?",)) + rig.plugin = _OwnFormatPlugin([{"outcome": "reply", "message": _SWAP}]) + await rig.arm() + ctx = await rig.run(_gated(rig)) + + assert _got(rig, "do those numbers hold up?") # parsed its way, not read as an empty no_reply + (read, *_) = rig.events(ctx, "user_sim_read") + assert read["message"] == "do those numbers hold up?" + + +@pytest.mark.asyncio +async def test_a_gate_with_a_plugin_that_cant_read_its_rewrites_is_refused_when_the_run_starts(monkeypatch, tmp_path): + class NoParse: + @staticmethod + def setup(version, person): + return {"system_prompt": "you are linda", "output_format": None} + + @staticmethod + async def answer(version, person, history, read, ask): + return {"outcome": "reply", "message": "ok"} + + rig = Rig(monkeypatch, tmp_path, agent=_messages_once) + rig.plugin = NoParse + await rig.arm() + with pytest.raises(ValueError, match="user_sim_gate needs the user sim's plugin to define parse"): + await rig.run(_gated(rig)) diff --git a/tst/unit/task_step/test_user_sim_satisfaction.py b/tst/unit/task_step/test_user_sim_satisfaction.py index c7361480c..1153accd9 100644 --- a/tst/unit/task_step/test_user_sim_satisfaction.py +++ b/tst/unit/task_step/test_user_sim_satisfaction.py @@ -542,3 +542,15 @@ async def test_a_prompt_agent_chat_whose_agent_turn_failed_is_not_rated(monkeypa await _step().execute(ctx) await _hannah_rater().execute(ctx) assert ctx.metadata[SATISFACTION_KEY]["talk"]["skipped"] == "the agent's turn failed" + + + +@pytest.mark.parametrize("record, skipped", [ + ({"end_reason": "user_sim_invalid", "error_type": "user_sim_invalid"}, + "the user sim's answer still read as the assistant's after its rewrites"), + ({"end_reason": "user_sim_invalid"}, None), # on_fail "end": no error, so the run is rated as one that ended +], ids=["on_fail fail", "on_fail end"]) +def test_an_always_on_run_the_gate_failed_as_an_error_is_not_rated(record, skipped): + from agent_env.task_step.task_steps.agent import rate_user_satisfaction as rus + + assert rus._always_on_session({"user_sim": {"name": "linda"}, **record}).skipped == skipped From 362f83c781aec599bc761ca17a5b9ff4f1c4f66c Mon Sep 17 00:00:00 2001 From: kaihackney-scale Date: Sat, 21 Nov 2026 23:57:55 -0500 Subject: [PATCH 13/18] fix(user_sim_gate): count judge calls in usage, read curly apostrophes, fail a rewrite with nothing to send - Each gate judge call goes into the step's usage as a judge entry, costed as its endpoint billed it (StepUsage.call), in prompt_agent and always_on. - The patterns read curly apostrophes as straight ones. - In always_on, a rewrite that comes back as a no_reply or an empty reply holds the message back for good and fails the run like a failed rewrite, instead of becoming a no_reply the run carries on from. - The always_on and gate docstrings note what the gate reserves from the run's time budget even when it never fires. Co-Authored-By: Claude Opus 5.5 --- .../task_step/task_steps/always_on.py | 22 +++++++++--- .../task_step/task_steps/prompt_agent.py | 6 +++- .../task_step/task_steps/user_sim_gate.py | 36 ++++++++++++++----- src/agent_env/task_step/usage.py | 22 ++++++++++-- .../task_step/test_always_on_user_sim_gate.py | 16 +++++++++ .../test_prompt_agent_post_turn_hooks.py | 2 +- .../task_step/test_prompt_agent_user_side.py | 6 ++-- tst/unit/task_step/test_user_sim_gate.py | 33 ++++++++++++++--- tst/unit/task_step/usage_test.py | 19 +++++++++- 9 files changed, 136 insertions(+), 26 deletions(-) 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 94329c869..e6a49d6e2 100644 --- a/src/agent_env/task_step/task_steps/always_on.py +++ b/src/agent_env/task_step/task_steps/always_on.py @@ -69,7 +69,11 @@ ``max_rewrites``; each read's event records the checks (``user_sim_gate``: verdicts, rewrites, the first message). An answer that still fails is never delivered and ends the run (user_sim_invalid, also recorded in ``metadata["user_sim_invalid"][step_id]``): with ``on_fail`` "fail" it sets ``error_type`` too, so verifiers skip - the run; "end" ends it plainly; "send" delivers it anyway. Her last read's answer, never delivered, isn't checked. + the run; "end" ends it plainly; "send" delivers it anyway. A rewrite with nothing to send (a no_reply, an empty reply) + holds the message back for good too. Her last read's answer, never delivered, isn't checked. The gate's judge calls + are in the step's usage, role ``judge``. Turning the gate on reserves each read's worst case out of the run's time + budget whether or not it ever fires: ``max_rewrites`` more user sim turns, each up to ``user_timeout_seconds`` plus its + grace and trajectory fetch, and with a judge ``max_rewrites + 1`` judge timeouts (``read_budget_seconds``). - The run's metadata keeps a summary in ``metadata["always_on"][step_id]`` (small enough for a running job to report back); the full timeline goes to the object store, at the summary's ``object_url``. Its ``user_sim`` names the user sim's session (``context_id``), which rate_user_satisfaction asks in once the run is over. @@ -1612,7 +1616,7 @@ async def _gate(self, ans: dict, ask) -> tuple[dict, dict]: except Exception as e: # as in prompt_agent: the patterns' verdict stands; with patterns off, it raises self.gate_setup_error = judge_setup_failed(gate, e) logger.warning(f"always_on: user-sim gate {self.gate_setup_error}; using patterns only") - latest = {"ans": ans} + latest = {"ans": ans, "dropped": False} verdicts: list[dict] = [] rewrites: list[dict] = [] @@ -1627,7 +1631,12 @@ async def rewrite(note: str) -> Optional[str]: return None latest["ans"] = {**ans, **new} said = (new.get("message") or "").strip() - return said if new.get("outcome") in ("reply", "done") and said else None + if new.get("outcome") in ("reply", "done") and said: + return said + # A rewrite with nothing to send in place of the held message, a no_reply or an empty reply, holds it back + # for good, as a failed one does; a done without a message ends the run as the user's own end. + latest["dropped"] = new.get("outcome") != "done" + return None def on_verdict(attempt: int, text: str, verdict) -> None: verdicts.append({"attempt": attempt, "chars": len(text), **verdict.to_dict()}) @@ -1636,13 +1645,16 @@ def on_verdict(attempt: int, text: str, verdict) -> None: f"{gate.max_rewrites + 1}): {'; '.join(verdict.reasons())[:300]}") outcome = await run_gate(gate, ans["message"], self.gate_history, rewrite, call_config=self.gate_call_config, - judge_unavailable=self.gate_setup_error, on_verdict=on_verdict) + judge_unavailable=self.gate_setup_error, on_verdict=on_verdict, + on_call=lambda reply: self.usage.call(ModelRole.JUDGE, reply)) + if latest["dropped"] and gate.on_fail != "send": + outcome.invalid = True record = {"verdicts": verdicts, "rewrites": rewrites, "invalid": outcome.invalid} if rewrites: record["first_message"] = ans["message"] if not outcome.invalid: return latest["ans"], record - reasons = outcome.reasons() + reasons = outcome.reasons() + (["its rewrite sent nothing in its place"] if latest["dropped"] else []) self.ctx.metadata.setdefault("user_sim_invalid", {})[self.step.id] = {"wake": self.wakes, "reasons": reasons} if gate.on_fail == "fail": self.error = (f"user-sim answer at wake {self.wakes} still reads as the assistant's after " 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 a67064cf4..5f9fee546 100644 --- a/src/agent_env/task_step/task_steps/prompt_agent.py +++ b/src/agent_env/task_step/task_steps/prompt_agent.py @@ -1314,7 +1314,8 @@ def on_verdict(attempt: int, text: str, verdict) -> None: outcome = await run_gate(gate, _text_of(answer["message"]), self._history, rewrite, call_config=self._gate_call_config, judge_unavailable=self._gate_judge_setup_error, - on_verdict=on_verdict, user_note=hook_note) + on_verdict=on_verdict, user_note=hook_note, + on_call=self._judge_call if self._usage is not None else None) if not outcome.invalid: return latest["answer"] self._context.metadata.setdefault("user_sim_invalid", {})[self._step.id] = { @@ -1326,6 +1327,9 @@ def on_verdict(attempt: int, text: str, verdict) -> None: f"{gate.max_rewrites} rewrite(s): {'; '.join(outcome.reasons())[:500]}") return {"end": "user_sim_invalid"} + def _judge_call(self, reply) -> None: + self._usage.call(ModelRole.JUDGE, reply) + async def _send_to_peer(self, number: int, agent_parts: list[dict], note: Optional[str] = None) -> dict: step = self._step if note is not None and self._is_user_sim: diff --git a/src/agent_env/task_step/task_steps/user_sim_gate.py b/src/agent_env/task_step/task_steps/user_sim_gate.py index 7778a3b10..a8f37a541 100644 --- a/src/agent_env/task_step/task_steps/user_sim_gate.py +++ b/src/agent_env/task_step/task_steps/user_sim_gate.py @@ -21,6 +21,9 @@ with ``run_gate``, and sets ``USER_SIM_GATE_SUPPORTED``:: {"judge_model": "", "max_rewrites": 2, "on_fail": "fail"} + +Each judge call is in the step's usage, role ``judge``. In ``always_on`` the gate costs time budget even when it never +fires: each read reserves room for ``max_rewrites`` more user sim turns and, with a judge, a judge timeout per check. """ from __future__ import annotations @@ -28,7 +31,10 @@ import logging import re from dataclasses import asdict, dataclass, field -from typing import Awaitable, Callable, ClassVar, Optional +from typing import TYPE_CHECKING, Awaitable, Callable, ClassVar, Optional + +if TYPE_CHECKING: + from agent_env.config.model_call import ModelReply logger = logging.getLogger(__name__) @@ -96,9 +102,14 @@ class PatternLimits: PHRASE_REASONS = frozenset({TALKS_LIKE_THE_ASSISTANT, NOW_LIVE}) +_APOSTROPHES = str.maketrans({"\u2019": "'", "\u2018": "'", "\u02bc": "'"}) + + def pattern_reasons(text: str) -> list[str]: - """Why ``text`` reads as the assistant's message, one reason per pattern that matched; empty if none.""" + """Why ``text`` reads as the assistant's message, one reason per pattern that matched; empty if none. Curly + apostrophes read as straight ones, as many models write them.""" lim = PatternLimits + text = text.translate(_APOSTROPHES) reasons = [] n = len(text) if _AS_ASSISTANT.search(text): @@ -246,11 +257,13 @@ def to_dict(self) -> dict: return asdict(self) async def check(self, candidate: str, history: list[tuple[str, str]], *, call_config=None, - judge_unavailable: Optional[str] = None, user_note: Optional[str] = None) -> GateVerdict: + judge_unavailable: Optional[str] = None, user_note: Optional[str] = None, + on_call: Optional[Callable[[ModelReply], None]] = None) -> GateVerdict: """Check one message. ``history`` is the conversation so far as ``(role, text)``, role user/assistant. A judge that reads the message as the user's clears a hit on a phrase alone (``PHRASE_REASONS``); a shape hit stays a failure. A judge call that errors or can't be parsed doesn't fail the message: the patterns' verdict - stands. So does a judge that couldn't be set up (``judge_unavailable``, the reason), which isn't called.""" + stands. So does a judge that couldn't be set up (``judge_unavailable``, the reason), which isn't called. + ``on_call`` sees each judge call's reply, for the step's usage.""" reasons = pattern_reasons(candidate) if self.patterns else [] verdict = GateVerdict(passed=not reasons, pattern_reasons=reasons) if self.judge_model and judge_unavailable is not None: @@ -258,8 +271,8 @@ async def check(self, candidate: str, history: list[tuple[str, str]], *, call_co return verdict if self.judge_model: try: - judged = await (self._judge(candidate, history, call_config, user_note=user_note) if user_note - else self._judge(candidate, history, call_config)) + extra = {k: v for k, v in (("user_note", user_note), ("on_call", on_call)) if v} + judged = await self._judge(candidate, history, call_config, **extra) except Exception as e: # the judge is a second opinion; never let it take the conversation down logger.warning(f"user-sim gate judge call failed ({type(e).__name__}: {e}); using patterns only") verdict.judge_error = f"{type(e).__name__}: {e}"[: self.RECORDED_ERROR_CHARS] @@ -277,7 +290,8 @@ async def check(self, candidate: str, history: list[tuple[str, str]], *, call_co return verdict async def _judge(self, candidate: str, history: list[tuple[str, str]], route, - user_note: Optional[str] = None) -> Optional[dict]: + user_note: Optional[str] = None, + on_call: Optional[Callable[[ModelReply], None]] = None) -> Optional[dict]: """One judge call through core's one model-call path (config/model_call.py), on ``route`` (``judge_call_config``'s), or on the configured endpoint when none was given.""" from agent_env.config import model_call @@ -293,6 +307,8 @@ async def _judge(self, candidate: str, history: list[tuple[str, str]], route, route, [{"role": "user", "content": prompt}], timeout=self.judge_timeout_seconds, response_format={"type": "json_schema", "json_schema": {"name": "user_sim_gate", "schema": _JUDGE_SCHEMA, "strict": True}}) + if on_call is not None: + on_call(reply) return parse_judge(reply.content) @@ -351,18 +367,22 @@ async def run_gate( judge_unavailable: Optional[str] = None, on_verdict: Optional[Callable[[int, str, GateVerdict], None]] = None, user_note: Optional[str] = None, + on_call: Optional[Callable[[ModelReply], None]] = None, ) -> GateOutcome: """Check ``text``; while it fails, send the user-sim ``rewrite_request`` through ``rewrite`` and check its new message, up to ``gate.max_rewrites`` times. ``rewrite`` returns the new message, or None when the user side ended instead. ``judge_unavailable`` is why the judge couldn't be set up, if it couldn't (see ``check``). ``on_verdict(attempt, text, verdict)`` sees every check, for recording. ``user_note`` is what a post-turn hook - told the user sim it found, shown to the judge. Any conversation loop + told the user sim it found, shown to the judge. ``on_call`` sees each judge call's reply, for the step's usage. + Any conversation loop can call this; ``prompt_agent`` does, between a user-sim's reply and the agent's next turn.""" outcome = GateOutcome(text=text) for attempt in range(gate.max_rewrites + 1): extra = {} if judge_unavailable is None else {"judge_unavailable": judge_unavailable} if user_note: # what a post-turn hook told the user sim it found: the judge reads a report of it as the user's extra["user_note"] = user_note + if on_call is not None: + extra["on_call"] = on_call verdict = await gate.check(text, history, call_config=call_config, **extra) outcome.verdicts.append(verdict) if on_verdict is not None: diff --git a/src/agent_env/task_step/usage.py b/src/agent_env/task_step/usage.py index 1488489ab..aa4b410ed 100644 --- a/src/agent_env/task_step/usage.py +++ b/src/agent_env/task_step/usage.py @@ -5,7 +5,7 @@ from __future__ import annotations import operator -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from functools import reduce from typing import TYPE_CHECKING, Any, NotRequired, Optional, TypedDict @@ -17,6 +17,7 @@ if TYPE_CHECKING: from agent_env.a2a_agent.protocol import TerminalResponse + from agent_env.config.model_call import ModelReply STEP_USAGE_KEY = "step_usage" _COUNTERS = ("tool_call_count", "input_tokens", "output_tokens", "total_tokens", "cache_read_tokens", @@ -62,7 +63,8 @@ class UsageEntry(TypedDict): @dataclass class RoleUsage: """One role's turns in one step: the model it ran, the host of the endpoint it called, the attempt epoch the step - ran under, and each turn's usage, None for a turn that reported none.""" + ran under, and each turn's usage, None for a turn that reported none. ``reported_by`` is who reports its cost: an + agent's harness, or, for calls core makes itself, the endpoint that billed them.""" role: str model: Optional[str] = None @@ -70,6 +72,7 @@ class RoleUsage: attempt: Optional[int] = field(default_factory=ATTEMPT_EPOCH.get) turns: list[Optional[Usage]] = field(default_factory=list) unparsed: list[dict] = field(default_factory=list) + reported_by: ReportedBy = ReportedBy.HARNESS def add(self, usage: Optional[Usage], unparsed: Optional[dict] = None) -> None: """One finished turn's usage, and what of it couldn't be read.""" @@ -102,7 +105,7 @@ def total(name: str) -> Any: charged = [Tokens.of(usage.to_dict()) for usage in counted] tokens = reduce(operator.add, charged) if charged and None not in charged else None cost = price(tokens, total("cost_usd"), model=self.model, - prices=prices, reported_by=ReportedBy.HARNESS) + prices=prices, reported_by=self.reported_by) entry = UsageEntry(role=self.role, model=self.model, endpoint_host=self.endpoint_host, attempt=self.attempt, turns=len(self.turns), **counts, input_includes_cache=includes, **cost.fields(), partial=partial) @@ -146,6 +149,19 @@ def turn(self, role: ModelRole, reply: TerminalResponse) -> None: usage.add(reply.usage, reply.usage_unparsed) self.entries() + def call(self, role: ModelRole, reply: ModelReply) -> None: + """One model call the step made itself as ``role`` (a user-sim gate's judge, through ``model_call``), written + at once; its cost is what the endpoint billed when it says, else the map's price.""" + usage = self._roles.get(role) + if usage is None: + usage = self._roles[role] = RoleUsage(role.value, reply.model, reply.endpoint_host, + reported_by=ReportedBy.PROVIDER) + counts = Usage.from_model_response(reply.usage) if reply.usage else None + if reply.cost.reported_usd is not None: + counts = replace(counts or Usage(), cost_usd=reply.cost.reported_usd) + usage.add(counts) + self.entries() + def entries(self) -> Optional[list[UsageEntry]]: """The entries of the roles that ran turns, written to ``metadata["step_usage"]``; None, and nothing written, when none did.""" diff --git a/tst/unit/task_step/test_always_on_user_sim_gate.py b/tst/unit/task_step/test_always_on_user_sim_gate.py index 38e944b47..4fe37ba54 100644 --- a/tst/unit/task_step/test_always_on_user_sim_gate.py +++ b/tst/unit/task_step/test_always_on_user_sim_gate.py @@ -74,6 +74,22 @@ async def test_an_answer_that_still_fails_never_reaches_the_agent_and_ends_the_r assert [v["passed"] for v in read["user_sim_gate"]["verdicts"]] == [False, False, False] +@pytest.mark.asyncio +@pytest.mark.parametrize("rewrite", [_answer("no_reply"), _answer("reply", " ")]) +async def test_a_rewrite_with_nothing_to_send_holds_the_message_back_and_fails_the_run(monkeypatch, tmp_path, rewrite): + rig = Rig(monkeypatch, tmp_path, agent=_messages_once, answers=[{"outcome": "reply", "message": _SWAP}], + user_texts=(rewrite,)) + await rig.arm() + ctx = await rig.run(_gated(rig)) + + assert not _got(rig, "None of the three reported numbers") + record = rig.record(ctx) + assert record["end_reason"] == "user_sim_invalid" and record["error_type"] == "user_sim_invalid" + assert ctx.metadata["user_sim_invalid"]["week"]["reasons"][-1] == "its rewrite sent nothing in its place" + (read,) = rig.events(ctx, "user_sim_read") + assert read["outcome"] == "no_reply" and read["user_sim_gate"]["invalid"] is True + + @pytest.mark.asyncio async def test_on_fail_end_ends_the_run_without_marking_it_an_error(monkeypatch, tmp_path): rig = Rig(monkeypatch, tmp_path, agent=_messages_once, answers=[{"outcome": "reply", "message": _SWAP}], diff --git a/tst/unit/task_step/test_prompt_agent_post_turn_hooks.py b/tst/unit/task_step/test_prompt_agent_post_turn_hooks.py index f78b97f61..0a0cd9f03 100644 --- a/tst/unit/task_step/test_prompt_agent_post_turn_hooks.py +++ b/tst/unit/task_step/test_prompt_agent_post_turn_hooks.py @@ -667,7 +667,7 @@ async def test_with_a_user_sim_gate_the_note_goes_with_the_first_send_only_and_t shown = [] - async def judge(self, candidate, history, call_config, user_note=None): + async def judge(self, candidate, history, call_config, user_note=None, **_): shown.append(user_note) return {"in_role": not candidate.startswith("Done."), "reason": "judged"} diff --git a/tst/unit/task_step/test_prompt_agent_user_side.py b/tst/unit/task_step/test_prompt_agent_user_side.py index 9b0b06417..6d7e20003 100644 --- a/tst/unit/task_step/test_prompt_agent_user_side.py +++ b/tst/unit/task_step/test_prompt_agent_user_side.py @@ -559,7 +559,7 @@ async def test_the_judge_fails_a_message_the_patterns_pass_and_sees_the_conversa seen = [] - async def judge(self, candidate, history, call_config): + async def judge(self, candidate, history, call_config, **_): seen.append((candidate, list(history))) return {"in_role": candidate != _TAKEOVER, "reason": "it offers to do the work"} @@ -581,7 +581,7 @@ async def judge(self, candidate, history, call_config): async def test_a_judge_that_errors_leaves_the_patterns_verdict(monkeypatch): from agent_env.task_step.task_steps import user_sim_gate - async def judge(self, candidate, history, call_config): + async def judge(self, candidate, history, call_config, **_): raise TimeoutError("judge timed out") monkeypatch.setattr(user_sim_gate.UserSimGate, "_judge", judge) @@ -618,7 +618,7 @@ async def test_a_judge_whose_setup_fails_leaves_the_patterns_verdict_and_is_not_ called = [] - async def judge(self, candidate, history, call_config): + async def judge(self, candidate, history, call_config, **_): called.append(candidate) return {"in_role": True} diff --git a/tst/unit/task_step/test_user_sim_gate.py b/tst/unit/task_step/test_user_sim_gate.py index 8481b3a7f..94f9f24c3 100644 --- a/tst/unit/task_step/test_user_sim_gate.py +++ b/tst/unit/task_step/test_user_sim_gate.py @@ -1,9 +1,13 @@ """The user-sim gate's own checks: the patterns, the judge's output parsing and the history it is shown.""" +import asyncio + import pytest +from agent_env.config import model_call +from agent_env.config.model_pricing import Cost, CostStatus from agent_env.task_step.task_steps.user_sim_gate import ( - GateVerdict, parse_judge, pattern_reasons, render_history, rewrite_request) + TALKS_LIKE_THE_ASSISTANT, GateVerdict, UserSimGate, parse_judge, pattern_reasons, render_history, rewrite_request) _FILLER = " The details are in the shared folder and the numbers come from last month's records." * 6 @@ -73,7 +77,7 @@ def test_the_judge_alone_fails_only_a_long_message(): from agent_env.task_step.task_steps.user_sim_gate import UserSimGate class Gate(UserSimGate): - async def _judge(self, candidate, history, call_config): + async def _judge(self, candidate, history, call_config, **_): return {"in_role": False, "reason": "reads as analysis"} gate = Gate(judge_model="judge-model") @@ -174,7 +178,7 @@ def test_a_judge_that_couldnt_be_set_up_isnt_called_and_the_patterns_verdict_sta from agent_env.task_step.task_steps.user_sim_gate import UserSimGate class NeverCalled(UserSimGate): - async def _judge(self, candidate, history, call_config): + async def _judge(self, candidate, history, call_config, **_): raise AssertionError("the judge was called") for patterns in (True, False): @@ -217,7 +221,7 @@ def _judged(in_role): from agent_env.task_step.task_steps.user_sim_gate import UserSimGate class Gate(UserSimGate): - async def _judge(self, candidate, history, call_config): + async def _judge(self, candidate, history, call_config, **_): return {"in_role": in_role, "reason": "judged"} return Gate(judge_model="judge-model") @@ -276,3 +280,24 @@ async def complete(route, messages, *, timeout, response_format=None): assert "WHAT THE USER FOUND" in prompts[0] and "no sheet in the folder" in prompts[0] assert "WHAT THE USER FOUND" not in prompts[1] + + +@pytest.mark.parametrize("text", ["I\u2019m an AI, so I can\u2019t open that.", + "Let me know if you\u2019d like me to resend it."]) +def test_curly_apostrophes_read_as_straight_ones(text): + assert TALKS_LIKE_THE_ASSISTANT in pattern_reasons(text) + + +def test_each_judge_call_is_handed_to_on_call_for_the_steps_usage(monkeypatch): + reply = model_call.ModelReply('{"in_role": true, "reason": "asks"}', "judge-m", None, None, + Cost(0.001, CostStatus.REPORTED, "provider", 0.001)) + + async def complete(route, messages, **kw): + return reply + + monkeypatch.setattr(model_call, "complete", complete) + seen = [] + verdict = asyncio.run(UserSimGate(judge_model="judge-m").check("can you check the totals?", [], call_config=object(), + on_call=seen.append)) + + assert verdict.passed and seen == [reply] diff --git a/tst/unit/task_step/usage_test.py b/tst/unit/task_step/usage_test.py index 63d5ddf99..852ae11fc 100644 --- a/tst/unit/task_step/usage_test.py +++ b/tst/unit/task_step/usage_test.py @@ -5,7 +5,8 @@ from agent_env.a2a_agent.protocol import TerminalResponse from agent_env.config.model import ModelRole -from agent_env.config.model_pricing import ModelPrice, PriceTable +from agent_env.config.model_call import ModelReply +from agent_env.config.model_pricing import Cost, CostStatus, ModelPrice, PriceTable from agent_env.task_step.context import ATTEMPT_EPOCH, DeployedAgent, TaskStepContext from agent_env.task_step import usage as usage_module from agent_env.task_step.usage import RoleUsage, StepUsage @@ -65,6 +66,22 @@ def test_a_step_records_each_started_role_as_each_turn_ends_and_skips_one_never_ assert context.metadata["model_endpoints"] == {"solver": {"solve": {"model": "m", "endpoint_host": "gw:443"}}} +def test_a_judge_call_the_step_made_itself_is_its_own_entry_costed_as_its_endpoint_billed_it(): + context = TaskStepContext() + usage = StepUsage(context, "talk") + billed = Cost(0.002, CostStatus.REPORTED, "provider", 0.002) + + for _ in range(2): + usage.call(ModelRole.JUDGE, ModelReply("{}", "judge-m", "gw:443", {"prompt_tokens": 50, "completion_tokens": 5}, + billed)) + + [entry] = context.metadata["step_usage"]["talk"] + assert (entry["role"], entry["model"], entry["endpoint_host"], entry["turns"]) == ("judge", "judge-m", "gw:443", 2) + assert (entry["input_tokens"], entry["output_tokens"]) == (100, 10) + assert (entry["cost_usd"], entry["cost_status"], entry["cost_source"]) == (pytest.approx(0.004), "reported", + "provider") + + def test_a_turn_that_reported_any_token_count_makes_a_turn_that_reported_none_partial(): role = RoleUsage("solver") role.add(Usage(total_tokens=100)) From 5167c622e42311a7d18b31b161ce0a2f003de751 Mon Sep 17 00:00:00 2001 From: kaihackney-scale Date: Sun, 22 Nov 2026 00:14:19 -0500 Subject: [PATCH 14/18] fix(usage): keep judge call estimates apart from bills StepUsage.call keeps each judge call's Cost as model_call costed it, and the role's entry combines them (_combined): reported only when every costed call was billed, otherwise priced, an estimate, with the priced calls' source, the assumptions any made, their uncached input and unit prices when they agree, and the bills in reported_cost_usd. RoleUsage no longer takes reported_by. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/task_step/usage.py | 44 ++++++++++++++++++++++---------- tst/unit/task_step/usage_test.py | 24 ++++++++++++++--- 2 files changed, 51 insertions(+), 17 deletions(-) diff --git a/src/agent_env/task_step/usage.py b/src/agent_env/task_step/usage.py index 812c6e601..e37142333 100644 --- a/src/agent_env/task_step/usage.py +++ b/src/agent_env/task_step/usage.py @@ -12,7 +12,7 @@ from agentenv_protocol.a2a_agent import Usage from agent_env.config.model import ModelRole -from agent_env.config.model_pricing import PriceTable, ReportedBy, Tokens, litellm_prices, price +from agent_env.config.model_pricing import Cost, CostStatus, PriceTable, ReportedBy, Tokens, litellm_prices, price from agent_env.task_step.context import ATTEMPT_EPOCH, DeployedAgent, TaskStepContext if TYPE_CHECKING: @@ -63,8 +63,8 @@ class UsageEntry(TypedDict): @dataclass class RoleUsage: """One role's turns in one step: the model it ran, the host of the endpoint it called, the attempt epoch the step - ran under, and each turn's usage, None for a turn that reported none. ``reported_by`` is who reports its cost: an - agent's harness, or, for calls core makes itself, the endpoint that billed them.""" + ran under, and each turn's usage, None for a turn that reported none. ``call_costs`` are the costs of calls core + made itself (``StepUsage.call``), each costed when it was made; a role with them is costed from them alone.""" role: str model: Optional[str] = None @@ -72,7 +72,7 @@ class RoleUsage: attempt: Optional[int] = field(default_factory=ATTEMPT_EPOCH.get) turns: list[Optional[Usage]] = field(default_factory=list) unparsed: list[dict] = field(default_factory=list) - reported_by: ReportedBy = ReportedBy.HARNESS + call_costs: list[Cost] = field(default_factory=list) def add(self, usage: Optional[Usage], unparsed: Optional[dict] = None) -> None: """One finished turn's usage, and what of it couldn't be read.""" @@ -105,8 +105,8 @@ def total(name: str) -> Any: includes = flags.pop() if len(flags) == 1 else None charged = [Tokens.of(usage.to_dict()) for usage in counted] tokens = reduce(operator.add, charged) if charged and None not in charged else None - cost = price(tokens, total("cost_usd"), model=self.model, - prices=prices, reported_by=self.reported_by) + cost = (_combined(self.call_costs) if self.call_costs + else price(tokens, total("cost_usd"), model=self.model, prices=prices, reported_by=ReportedBy.HARNESS)) entry = UsageEntry(role=self.role, model=self.model, endpoint_host=self.endpoint_host, attempt=self.attempt, turns=len(self.turns), **counts, input_includes_cache=includes, **cost.fields(), partial=partial) @@ -118,6 +118,26 @@ def total(name: str) -> Any: return entry +def _combined(costs: list[Cost]) -> Cost: + """Calls' costs summed: billed (``reported``) only when every costed call was billed, otherwise ``priced``, an + estimate, with the source of the priced calls, the assumptions any made, and the bills kept in ``reported_usd``. + Unpriced when none was costed; a call with no cost is left out of the sum, which ``partial`` marks.""" + costed = [c for c in costs if c.usd is not None] + if not costed: + return Cost(None, CostStatus.UNPRICED, None, None, unpriced=costs[-1].unpriced) + status = CostStatus.REPORTED if all(c.status is CostStatus.REPORTED for c in costed) else CostStatus.PRICED + sources = {c.source for c in costed if c.status is status} + bills = [c.reported_usd for c in costs if c.reported_usd is not None] + assumed = tuple(dict.fromkeys(a for c in costed for a in c.assumed)) + priced = [c for c in costed if c.status is CostStatus.PRICED] + uncached = [c.uncached_input for c in priced] + rates = {repr(c.unit_prices): c.unit_prices for c in priced} + return Cost(sum(c.usd for c in costed), status, sources.pop() if len(sources) == 1 else None, + sum(bills) if bills else None, + uncached_input=sum(uncached) if priced and None not in uncached else None, + unit_prices=next(iter(rates.values())) if len(rates) == 1 else None, assumed=assumed) + + def _unreported_calls(usage: Usage) -> int: """The calls a turn's usage says reported none, as the shipped agents put it in ``provider_details``.""" value = usage.provider_details.get("unreported_calls") @@ -152,17 +172,15 @@ def turn(self, role: ModelRole, reply: TerminalResponse) -> None: def call(self, role: ModelRole, reply: ModelReply) -> None: """One model call the step made itself as ``role`` (a user-sim gate's judge, through ``model_call``), written - at once. Each call carries its own cost, what the endpoint billed, else the map's price, so the role's entry - sums every call; one with neither leaves the entry a lower bound, as ``cut_off`` does.""" + at once. Its cost is kept as the call was costed (``_combined`` sums them); one with no cost leaves the entry a + lower bound, as ``cut_off`` does.""" usage = self._roles.get(role) if usage is None: - usage = self._roles[role] = RoleUsage(role.value, reply.model, reply.endpoint_host, - reported_by=ReportedBy.PROVIDER) + usage = self._roles[role] = RoleUsage(role.value, reply.model, reply.endpoint_host) counts = Usage.from_model_response(reply.usage) if reply.usage else Usage() - if reply.cost.usd is not None: - counts = replace(counts, cost_usd=reply.cost.usd) - else: + if reply.cost.usd is None: counts = replace(counts, provider_details={**counts.provider_details, "unreported": True}) + usage.call_costs.append(reply.cost) usage.add(counts) self.entries() diff --git a/tst/unit/task_step/usage_test.py b/tst/unit/task_step/usage_test.py index aa0c6a0a2..8fad2e4b6 100644 --- a/tst/unit/task_step/usage_test.py +++ b/tst/unit/task_step/usage_test.py @@ -6,7 +6,7 @@ from agent_env.a2a_agent.protocol import TerminalResponse from agent_env.config.model import ModelRole from agent_env.config.model_call import ModelReply -from agent_env.config.model_pricing import Cost, CostStatus, ModelPrice, PriceTable +from agent_env.config.model_pricing import Assumed, Cost, CostStatus, ModelPrice, PriceTable, Unpriced from agent_env.task_step.context import ATTEMPT_EPOCH, DeployedAgent, TaskStepContext from agent_env.task_step import usage as usage_module from agent_env.task_step.usage import RoleUsage, StepUsage @@ -81,17 +81,22 @@ def test_a_judge_call_the_step_made_itself_is_its_own_entry_costed_as_its_endpoi assert (entry["cost_usd"], entry["cost_status"], entry["cost_source"]) == (pytest.approx(0.004), "reported", "provider") -def test_judge_calls_costed_differently_each_count_their_own_cost_and_an_uncosted_one_makes_the_entry_partial(): +def test_judge_calls_billed_and_priced_sum_as_an_estimate_that_keeps_the_bills_and_assumptions_apart(): context = TaskStepContext() usage = StepUsage(context, "talk") tokens = {"prompt_tokens": 50, "completion_tokens": 5} + rates = {"input": 1.0, "output": 2.0} usage.call(ModelRole.JUDGE, ModelReply("{}", "judge-m", None, tokens, Cost(0.002, CostStatus.REPORTED, "provider", 0.002))) - usage.call(ModelRole.JUDGE, ModelReply("{}", "judge-m", None, tokens, Cost(0.001, CostStatus.PRICED, "litellm@1", - None))) + usage.call(ModelRole.JUDGE, ModelReply("{}", "judge-m", None, tokens, Cost( + 0.001, CostStatus.PRICED, "litellm@1", None, uncached_input=50, unit_prices=rates, + assumed=(Assumed.CACHE_READ_RATE,)))) [entry] = context.metadata["step_usage"]["talk"] assert (entry["turns"], entry["cost_usd"], entry["partial"]) == (2, pytest.approx(0.003), False) + assert (entry["cost_status"], entry["cost_source"], entry["reported_cost_usd"]) == ("priced", "litellm@1", 0.002) + assert (entry["cost_assumed"], entry["uncached_input_tokens"], entry["unit_prices"]) == (["cache_read_rate"], 50, + rates) usage.call(ModelRole.JUDGE, ModelReply("{}", "judge-m", None, tokens, Cost(None, CostStatus.UNPRICED, None, None))) @@ -99,6 +104,17 @@ def test_judge_calls_costed_differently_each_count_their_own_cost_and_an_uncoste assert (entry["turns"], entry["cost_usd"], entry["partial"]) == (3, pytest.approx(0.003), True) +def test_judge_calls_none_of_which_was_costed_leave_the_entry_unpriced(): + context = TaskStepContext() + usage = StepUsage(context, "talk") + usage.call(ModelRole.JUDGE, ModelReply("{}", "judge-m", None, None, Cost(None, CostStatus.UNPRICED, None, None, + unpriced=Unpriced.NO_PRICE))) + + [entry] = context.metadata["step_usage"]["talk"] + assert (entry["cost_usd"], entry["cost_status"], entry["unpriced_reason"], entry["partial"]) == ( + None, "unpriced", "no_price", True) + + def test_a_turn_cut_off_before_its_reply_is_a_turn_of_unknown_usage(): context = TaskStepContext() usage = StepUsage(context, "solve") From 9aee3f94c88586785b87929953c796c1b576c31c Mon Sep 17 00:00:00 2001 From: kaihackney-scale Date: Sun, 22 Nov 2026 00:27:41 -0500 Subject: [PATCH 15/18] feat(user_sim_gate)!: the judge alone holds a message back, reads the user sim's instructions, and a failure is a user_sim_error - The judge decides, by user_sim_judge's rogue rule ("spoke as the assistant"), and is shown the user sim's own instructions (rebuilt from its user_sims record, or the plugin's setup prompt in always_on), so it can tell the user reporting their own check from the assistant reporting work. The judge_min_chars floor is gone. - Pattern matches are recorded on each verdict and never hold a message back on their own; without a judge the gate only records them. - A judge that can't be set up fails the step, since nothing else would hold a message back; a judge call that errors sends the message, with the error recorded. - A message that still fails with on_fail "fail" marks the run error_type user_sim_error (always_on's end reason too), as a failed user sim does, so it is redone and existing readers handle it; the error message names the gate's reason. prompt_agent no longer raises for it. rate_user_satisfaction's user_sim_invalid special cases are gone. Co-Authored-By: Claude Opus 5.5 --- .../task_steps/agent/deploy_user_sim_agent.py | 11 ++ .../agent/rate_user_satisfaction.py | 9 - .../task_step/task_steps/always_on.py | 34 ++-- .../task_step/task_steps/prompt_agent.py | 34 ++-- .../task_step/task_steps/user_sim_gate.py | 155 +++++++++--------- .../task_step/test_always_on_user_sim_gate.py | 52 ++++-- .../test_prompt_agent_built_in_user_sim.py | 38 ++++- .../task_step/test_prompt_agent_user_side.py | 69 ++++---- tst/unit/task_step/test_user_sim_gate.py | 81 +++++---- .../task_step/test_user_sim_satisfaction.py | 11 +- 10 files changed, 271 insertions(+), 223 deletions(-) diff --git a/src/agent_env/task_step/task_steps/agent/deploy_user_sim_agent.py b/src/agent_env/task_step/task_steps/agent/deploy_user_sim_agent.py index 756f46835..e3a8653f1 100644 --- a/src/agent_env/task_step/task_steps/agent/deploy_user_sim_agent.py +++ b/src/agent_env/task_step/task_steps/agent/deploy_user_sim_agent.py @@ -217,6 +217,17 @@ def recorded_person(us: dict, seed: dict, multi_day: Optional[bool] = None) -> d us["multi_day"] if us.get("multi_day") is not None else multi_day) +def recorded_instructions(us: dict, seed: dict, multi_day: Optional[bool] = None) -> Optional[str]: + """The user sim's system prompt, rebuilt from its ``metadata["user_sims"]`` record as this step wrote it; None when + the record can't be rebuilt.""" + try: + return user_sim_versions.setup(us.get("user_version") or user_sim_versions.VERSION, + recorded_person(us, seed, multi_day))["system_prompt"] + except Exception as e: + logger.warning(f"user sim {us.get('name')!r}: its instructions could not be rebuilt ({type(e).__name__}: {e})") + return None + + _USER_SIM_MODEL_SOURCES = {ModelSource.STEP_PARAMS: "user_sim_step_params", ModelSource.RUN: "run_user_model"} 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 844c42f19..4930e3172 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 @@ -351,11 +351,6 @@ def _always_on_session(record: dict) -> _Session: if record.get("end_reason") in ERROR_ENDS: session.skipped = f"the run ended on {record['end_reason']}" return session - if record.get("error_type") == "user_sim_invalid": - # The user-sim gate cut the run off as an error (on_fail "fail"): the user sim broke it, not the agent. A plain - # on_fail "end" sets no error, and the run is rated as one that ended. - session.skipped = "the user sim's answer still read as the assistant's after its rewrites" - return session timeline = record.get("timeline_tail") or [] if record.get("object_url"): try: @@ -384,10 +379,6 @@ async def _prompt_agent_session(context: TaskStepContext, run_id: str, response: if response.error_type == "user_sim_error": session.skipped = f"the user sim failed: {(response.error_message or '').removeprefix(SIM_FAILED_PREFIX)}" return session - if response.error_type == "user_sim_invalid": - # The user-sim gate cut the conversation off: the user sim, not the agent, broke it. - session.skipped = "the user sim's message still read as the assistant's after its rewrites" - return session if response.error_type or response.error_message: session.skipped = "the agent's turn failed" return session 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 852667498..7c5021ff1 100644 --- a/src/agent_env/task_step/task_steps/always_on.py +++ b/src/agent_env/task_step/task_steps/always_on.py @@ -67,9 +67,11 @@ - ``user_sim_gate`` (user_sim_gate.py) checks each answer the user sim would send before the agent gets it. One that reads as the assistant's is held back and the user sim, told why in its session, answers again, up to the gate's ``max_rewrites``; each read's event records the checks (``user_sim_gate``: verdicts, rewrites, the first message). - An answer that still fails is never delivered and ends the run (user_sim_invalid, also recorded in - ``metadata["user_sim_invalid"][step_id]``): with ``on_fail`` "fail" it sets ``error_type`` too, so verifiers skip - the run; "end" ends it plainly; "send" delivers it anyway. A rewrite with nothing to send (a no_reply, an empty reply) + Only the gate's judge, which reads the user sim's own instructions, holds an answer back; its pattern matches are + recorded. An answer that still fails is never delivered and ends the run (recorded in + ``metadata["user_sim_invalid"][step_id]``): with ``on_fail`` "fail" as a failed user sim, ``user_sim_error`` for both + the end reason and ``error_type``, so the run is redone; "end" ends it plainly (user_sim_invalid); "send" delivers it + anyway. A rewrite with nothing to send (a no_reply, an empty reply) holds the message back for good too. Her last read's answer, never delivered, isn't checked. The gate's judge calls are in the step's usage, role ``judge``. Turning the gate on reserves each read's worst case out of the run's time budget whether or not it ever fires: ``max_rewrites`` more user sim turns, each up to ``user_timeout_seconds`` plus its @@ -126,14 +128,14 @@ from agent_env.task_step.usage import StepUsage from agent_env.task_step.task_step import 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, user_sim_model +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 from agent_env.task_step.task_steps.prompt_agent import ( PromptAgentTaskStep, fetch_native_trajectory, prescribe_formats, ) -from agent_env.task_step.task_steps.user_sim_gate import judge_call_config, judge_setup_failed, run_gate +from agent_env.task_step.task_steps.user_sim_gate import judge_call_config, run_gate from agent_env.task_step.task_steps.agent.user_sim_common import iso as _iso, person_of, task_zone, utc as _utc from agent_env.task_step.task_steps.agent.user_sim_common import attached, file_name, for_agent, recorded_opening @@ -405,7 +407,7 @@ def __init__(self, step: AlwaysOnTaskStep, context: TaskStepContext): # The conversation as the user-sim gate reads it, (role, text); and the gate's judge settings, set up once. self.gate_history: list[tuple[str, str]] = [] self.gate_call_config = None - self.gate_setup_error: Optional[str] = None + self.user_sim_prompt: Optional[str] = None # its system prompt, as the gate's judge reads it self.replies = 0 self.gave_up = False self.final_sent = False @@ -649,8 +651,11 @@ async def _configure_agents(self) -> None: self.user_model, self.user_model_from = self.us["model"], self.us["model_source"] self.user_setup = dict(self.us["setup"]) self.usage.start(ModelRole.USER_SIMULATOR, self.user_model, self.user_agent) + if step.user_sim_gate is not None and step.user_sim_gate.judge_model: + self.user_sim_prompt = recorded_instructions(self.us, ctx.metadata.get("seed") or {}, self.multi_day) return setup = self.plugin.setup(self.version, self.person) + self.user_sim_prompt = setup.get("system_prompt") self.user_model, self.user_model_from = self._user_model() user_config = {"model": self.user_model, "system_prompt": setup.get("system_prompt"), "output_format": setup.get("output_format")} @@ -1607,15 +1612,11 @@ async def _gate(self, ans: dict, ask) -> tuple[dict, dict]: """The user sim's answer after the user-sim gate (user_sim_gate.py): each failing message is held back and the user sim, told why through ``ask`` in its session, answers again, up to the gate's limit. Returns the answer to use and the gate's record for the read. A message that still fails is never delivered: the answer becomes a - no_reply, and the run ends ("user_sim_invalid"; an error, so verifiers skip it, when ``on_fail`` is "fail"), - unless ``on_fail`` is "send".""" + no_reply, and the run ends: as a failed user sim (``user_sim_error``) when ``on_fail`` is "fail", plainly + ("user_sim_invalid") when it is "end"; "send" sends it.""" gate = self.step.user_sim_gate - if self.gate_call_config is None and self.gate_setup_error is None and gate.judge_model: - try: - self.gate_call_config = judge_call_config(gate, self.ctx.metadata.get("user_overrides", {})) - except Exception as e: # as in prompt_agent: the patterns' verdict stands; with patterns off, it raises - self.gate_setup_error = judge_setup_failed(gate, e) - logger.warning(f"always_on: user-sim gate {self.gate_setup_error}; using patterns only") + if self.gate_call_config is None and gate.judge_model: # a judge that can't be set up fails the step + self.gate_call_config = judge_call_config(gate, self.ctx.metadata.get("user_overrides", {})) latest = {"ans": ans, "dropped": False} verdicts: list[dict] = [] rewrites: list[dict] = [] @@ -1645,7 +1646,7 @@ def on_verdict(attempt: int, text: str, verdict) -> None: f"{gate.max_rewrites + 1}): {'; '.join(verdict.reasons())[:300]}") outcome = await run_gate(gate, ans["message"], self.gate_history, rewrite, call_config=self.gate_call_config, - judge_unavailable=self.gate_setup_error, on_verdict=on_verdict, + instructions=self.user_sim_prompt, on_verdict=on_verdict, on_call=lambda reply: self.usage.call(ModelRole.JUDGE, reply)) if latest["dropped"] and gate.on_fail != "send": outcome.invalid = True @@ -1659,7 +1660,8 @@ def on_verdict(attempt: int, text: str, verdict) -> None: if gate.on_fail == "fail": self.error = (f"user-sim answer at wake {self.wakes} still reads as the assistant's after " f"{gate.max_rewrites} rewrite(s): {'; '.join(reasons)[:500]}") - self.error_type = "user_sim_invalid" + self.error_type = "user_sim_error" # a failed user sim: the run is redone + self.end_reason = self.end_reason or "user_sim_error" self.end_reason = self.end_reason or "user_sim_invalid" return {**latest["ans"], "outcome": "no_reply", "message": "", "used": None}, record 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 ca2c5b2dd..ddb68137d 100644 --- a/src/agent_env/task_step/task_steps/prompt_agent.py +++ b/src/agent_env/task_step/task_steps/prompt_agent.py @@ -50,7 +50,7 @@ from agent_env.task_step.task_step import RetryConfig, StepRole, TaskStep, TaskStepDependency from agent_env.task_step.task_steps.notification_delivery import delivered_parts, labels_zone, next_message, take_due from agent_env.task_step.task_steps.post_turn_hooks import PostTurnHooks, run_post_turn_hooks, validate_hook_specs -from agent_env.task_step.task_steps.user_sim_gate import UserSimGate, judge_call_config, judge_setup_failed, run_gate +from agent_env.task_step.task_steps.user_sim_gate import UserSimGate, judge_call_config, run_gate from agent_env.task_step.task_steps.agent import user_sim_versions from agent_env.task_step.task_steps.agent.user_sim_common import iso, person_of, task_zone, utc from agent_env.task_step.task_steps.agent.user_sim_common import attached, for_agent, opening_text, recorded_opening @@ -878,9 +878,10 @@ def record_turn() -> None: error_type = "user_sim_error" final_error_for_response = final_error_for_response or f"The user simulator failed: {sim.error}" if not error_type and user_side.gate_failure is not None: - # The conversation was cut off by the gate: verifiers skip it rather than grade the agent's latest draft. - error_type = "user_sim_invalid" - final_error_for_response = final_error_for_response or f"user_sim_gate: {user_side.gate_failure}" + # The gate cut the conversation off: a failed user sim, as above, so the run is redone. + error_type = "user_sim_error" + final_error_for_response = (final_error_for_response + or f"The user simulator failed: user_sim_gate: {user_side.gate_failure}") context.prompt_responses.append(PromptResponse( prompt_id=self.prompt_id, response=final_terminal.response_text, @@ -903,9 +904,6 @@ def record_turn() -> None: usage=usage.entries(), )) - if user_side.gate_failure is not None: - raise RuntimeError(f"user_sim_gate: {user_side.gate_failure}") - if final_state == TaskState.failed: detail_parts = [] if final_terminal.error_type: @@ -1172,7 +1170,6 @@ def __init__(self, step: PromptAgentTaskStep, context: TaskStepContext, *, url: self._history: list[tuple[str, str]] = [("user", opening_text)] if opening_text else [] self._gate = step.user_sim_gate if is_user_sim else None self._gate_call_config = None - self._gate_judge_setup_error: Optional[str] = None # Set once a user-sim message fails the gate after its rewrites, with on_fail "fail". self.gate_failure: Optional[str] = None self._end_after: Optional[str] = None @@ -1297,14 +1294,8 @@ async def _gated(self, number: int, answer: dict, ask_rewrite, hook_note: Option answer shaped as ``ask``'s, up to the gate's limit (``run_gate``). The judge is shown ``hook_note``, what a post-turn hook told the user sim it found, so a message reporting that check reads as the user's.""" gate = self._gate - if self._gate_call_config is None and self._gate_judge_setup_error is None and gate.judge_model: - # Judge setup (its key, its endpoint) failing leaves the patterns' verdict standing, with the error - # recorded on it (run_gate); with patterns off it fails the step (judge_setup_failed). - try: - self._gate_call_config = judge_call_config(gate, self._context.metadata.get("user_overrides", {})) - except Exception as e: - self._gate_judge_setup_error = judge_setup_failed(gate, e) - logger.warning(f"user-sim gate {self._gate_judge_setup_error}; using patterns only") + if self._gate_call_config is None and gate.judge_model: # a judge that can't be set up fails the step + self._gate_call_config = judge_call_config(gate, self._context.metadata.get("user_overrides", {})) latest = {"answer": answer} async def rewrite(note: str) -> Optional[str]: @@ -1319,8 +1310,8 @@ def on_verdict(attempt: int, text: str, verdict) -> None: f"{gate.max_rewrites + 1}): {'; '.join(verdict.reasons())[:300]}") outcome = await run_gate(gate, _text_of(answer["message"]), self._history, rewrite, - call_config=self._gate_call_config, judge_unavailable=self._gate_judge_setup_error, - on_verdict=on_verdict, user_note=hook_note, + call_config=self._gate_call_config, on_verdict=on_verdict, user_note=hook_note, + instructions=self._built_in.instructions if self._built_in is not None else None, on_call=self._judge_call if self._usage is not None else None) if not outcome.invalid: return latest["answer"] @@ -1424,6 +1415,7 @@ def __init__(self, step: PromptAgentTaskStep, context: TaskStepContext, person: self._max_replies = person.get("max_replies") self.replies = 0 self.error: Optional[str] = None # the user sim's error, once a read ended on one + self.instructions: Optional[str] = None # its system prompt, as the user-sim gate's judge reads it @classmethod async def start(cls, step: PromptAgentTaskStep, context: TaskStepContext, record: dict, zone: str, @@ -1437,7 +1429,11 @@ async def start(cls, step: PromptAgentTaskStep, context: TaskStepContext, record if text else None) person = {**person_of(record), "max_replies": record.get("max_replies"), "time_zone": zone, "opening": opening, "done_ends_run": True} - return cls(step, context, person, opening, clock_envs) + sim = cls(step, context, person, opening, clock_envs) + if step.user_sim_gate is not None and step.user_sim_gate.judge_model: + from agent_env.task_step.task_steps.agent.deploy_user_sim_agent import recorded_instructions + sim.instructions = recorded_instructions(record, context.metadata.get("seed") or {}) + return sim async def ask(self, number: int, reply: str, ask_user_sim, note: Optional[str] = None) -> dict: """The user's answer to the agent's ``reply``: ``{"message": parts}``, with ``end_after`` when the agent's answer diff --git a/src/agent_env/task_step/task_steps/user_sim_gate.py b/src/agent_env/task_step/task_steps/user_sim_gate.py index a8f37a541..01a897434 100644 --- a/src/agent_env/task_step/task_steps/user_sim_gate.py +++ b/src/agent_env/task_step/task_steps/user_sim_gate.py @@ -5,15 +5,14 @@ is no longer a test of the agent. The gate checks each user-sim message, asks the user-sim to rewrite one that fails, and, if the rewrites fail too, ends the conversation and marks the run. -Two checks, either of which can fail a message: +The judge decides: -- ``patterns``: phrases and shapes that belong to the assistant's side (a report of work done, a - formatted deliverable, offers to do the work). Free, and deliberately narrow. -- ``judge_model``: one model call that reads the last turns and the candidate message and says whether - the message is written as the user. - -With both, a judge that reads the message as the user's clears a hit on a phrase alone (``PHRASE_REASONS``), which -counts at any length; a hit on a report's shape and length stays a failure. +- ``judge_model``: one model call that reads the user sim's instructions, the last turns and the candidate message, + and says whether the message is written as the user, by the rule user_sim_judge's rogue check fails a run for + ("spoke as the assistant"). Only the judge holds a message back. +- ``patterns``: phrases and shapes that belong to the assistant's side (a report of work done, a formatted + deliverable, offers to do the work). Free and narrow; a match is recorded on the verdict, never a reason to hold a + message back on its own. Without a judge the gate only records them. Opt in with ``user_sim_gate`` on a ``prompt_agent`` step whose user is a user-sim agent-env deployed: a peer user-sim, or the built-in one deploy_user_sim_agent deploys, whose rewrite is parsed as its own answer. ``always_on`` @@ -22,6 +21,9 @@ {"judge_model": "", "max_rewrites": 2, "on_fail": "fail"} +A message that still fails after its rewrites, with ``on_fail`` "fail", marks the run ``error_type: user_sim_error``, +as a failed user sim does, so the run is redone. + Each judge call is in the step's usage, role ``judge``. In ``always_on`` the gate costs time budget even when it never fires: each read reserves room for ``max_rewrites`` more user sim turns and, with a judge, a judge timeout per check. """ @@ -97,9 +99,6 @@ class PatternLimits: TALKS_LIKE_THE_ASSISTANT = "it talks like the assistant (offers to do the work, waits on the user, or speaks as the AI)" NOW_LIVE = "it says something is now live" -# The reasons a phrase gives at any length: a judge that reads the message as the user's clears them. The rest need a -# report's shape and length, and stay failures whatever the judge says. -PHRASE_REASONS = frozenset({TALKS_LIKE_THE_ASSISTANT, NOW_LIVE}) _APOSTROPHES = str.maketrans({"\u2019": "'", "\u2018": "'", "\u02bc": "'"}) @@ -136,18 +135,20 @@ def pattern_reasons(text: str) -> list[str]: a task. The assistant does the work; the user asks, answers questions the assistant put to them, decides, approves, \ pushes back, or ends the conversation. -Decide whether the CANDIDATE message is written as the user. It is NOT written as the user when it does the \ -assistant's job: it answers the question the user should be asking, reports work as done or findings it produced \ -("Done. Here's what I found", "I've updated the page"), presents analysis or a deliverable, apologizes for "my \ -previous answer", offers to do work ("I'll draft it", "Standing by", "Want me to send it?"), or speaks as the AI. +Decide whether the CANDIDATE message is written as the user. It is NOT written as the user when it speaks as the \ +assistant: a report or summary in the assistant's voice (findings it produced, work it says it did for the task), \ +an offer to do the assistant's tasks ("Want me to send it to you?" offering the assistant's own work, "Standing by"), \ +the person's own questions asked back as if it were the assistant, an apology for "my previous answer", or \ +speaking as the AI. It IS written as the user when it asks, instructs, approves, pushes back, answers a question the assistant asked, \ -or shares the user's own knowledge, even if it is long, formatted, quotes the assistant's numbers, or pastes an \ -email or document. Length and markdown alone are not evidence. +or says what the user knows, has, did or checked themselves, as the user's instructions describe this person, even \ +if it is long, formatted, quotes the assistant's numbers, or pastes an email or document. "I checked my bank app \ +and the charge is there" is the user reporting their own check. Length and markdown alone are not evidence. Judge only whose voice the message is in. A user message that repeats an earlier one, ignores or contradicts what \ the assistant said, states a decision or a fact the user holds, or seems off topic is still written as the user. - +{instructions} CONVERSATION SO FAR (most recent last): {history} {user_note} @@ -168,6 +169,14 @@ def pattern_reasons(text: str) -> list[str]: >>> """ +# What the model playing the user was told: who this person is and what they know, do and decide. +_INSTRUCTIONS = """ +THE USER'S INSTRUCTIONS (what the model playing the user was told; the assistant never saw them): +<<< +{instructions} +>>> +""" + _JUDGE_SCHEMA = { "type": "object", "properties": {"in_role": {"type": "boolean"}, "reason": {"type": "string"}}, @@ -206,19 +215,18 @@ class UserSimGate: patterns: bool = True judge_model: Optional[str] = None max_rewrites: int = 2 - # What happens when a message still fails after its rewrites: "fail" ends the conversation and fails the - # step, "end" ends the conversation and lets the step finish, "send" sends it anyway (record only). + # What happens when a message still fails after its rewrites: "fail" ends the conversation as a failed user sim + # (error_type user_sim_error, so the run is redone), "end" ends it plainly, "send" sends it anyway (record only). on_fail: str = "fail" context_turns: int = 4 - # The judge alone fails only a message at least this long; a shorter one also needs a pattern. Swaps are long or - # match a pattern, and without the scenario the judge misreads short scripted answers that correct the agent. - judge_min_chars: int = 300 context_chars: int = 3000 judge_timeout_seconds: float = 60 # How much of a judge error and of the judge's reason a verdict keeps. RECORDED_ERROR_CHARS: ClassVar[int] = 300 RECORDED_REASON_CHARS: ClassVar[int] = 500 + # How much of the user sim's instructions the judge is shown. + INSTRUCTIONS_MAX_CHARS: ClassVar[int] = 40_000 def __post_init__(self) -> None: """Refuse a setting of the wrong type or range here, when the task loads, rather than mid-conversation.""" @@ -235,7 +243,6 @@ def whole(v: object) -> bool: # an int, and not a bool (which is one in Python) need(whole(self.max_rewrites) and self.max_rewrites >= 0, "max_rewrites", "a whole number >= 0") need(self.on_fail in ON_FAIL, "on_fail", f"one of {ON_FAIL}") need(whole(self.context_turns) and self.context_turns >= 0, "context_turns", "a whole number >= 0") - need(whole(self.judge_min_chars) and self.judge_min_chars >= 0, "judge_min_chars", "a whole number >= 0") need(whole(self.context_chars) and self.context_chars > 0, "context_chars", "a whole number > 0") need(isinstance(self.judge_timeout_seconds, (int, float)) and not isinstance(self.judge_timeout_seconds, bool) and self.judge_timeout_seconds > 0, "judge_timeout_seconds", "a number > 0") @@ -257,40 +264,33 @@ def to_dict(self) -> dict: return asdict(self) async def check(self, candidate: str, history: list[tuple[str, str]], *, call_config=None, - judge_unavailable: Optional[str] = None, user_note: Optional[str] = None, + user_note: Optional[str] = None, instructions: Optional[str] = None, on_call: Optional[Callable[[ModelReply], None]] = None) -> GateVerdict: - """Check one message. ``history`` is the conversation so far as ``(role, text)``, role user/assistant. - A judge that reads the message as the user's clears a hit on a phrase alone (``PHRASE_REASONS``); a shape hit - stays a failure. A judge call that errors or can't be parsed doesn't fail the message: the patterns' verdict - stands. So does a judge that couldn't be set up (``judge_unavailable``, the reason), which isn't called. - ``on_call`` sees each judge call's reply, for the step's usage.""" - reasons = pattern_reasons(candidate) if self.patterns else [] - verdict = GateVerdict(passed=not reasons, pattern_reasons=reasons) - if self.judge_model and judge_unavailable is not None: - verdict.judge_error = judge_unavailable[: self.RECORDED_ERROR_CHARS] + """Check one message. ``history`` is the conversation so far as ``(role, text)``, role user/assistant; + ``instructions`` the user sim's own, shown to the judge. Only the judge fails a message; pattern matches are + recorded. A judge call that errors or can't be parsed passes the message with the error recorded. ``on_call`` + sees each judge call's reply, for the step's usage.""" + verdict = GateVerdict(passed=True, pattern_reasons=pattern_reasons(candidate) if self.patterns else []) + if not self.judge_model: + return verdict + try: + extra = {k: v for k, v in (("user_note", user_note), ("instructions", instructions), + ("on_call", on_call)) if v} + judged = await self._judge(candidate, history, call_config, **extra) + except Exception as e: # never let the judge take the conversation down + logger.warning(f"user-sim gate judge call failed ({type(e).__name__}: {e}); the message is sent") + verdict.judge_error = f"{type(e).__name__}: {e}"[: self.RECORDED_ERROR_CHARS] + return verdict + if judged is None: + verdict.judge_error = "unparseable judge output" return verdict - if self.judge_model: - try: - extra = {k: v for k, v in (("user_note", user_note), ("on_call", on_call)) if v} - judged = await self._judge(candidate, history, call_config, **extra) - except Exception as e: # the judge is a second opinion; never let it take the conversation down - logger.warning(f"user-sim gate judge call failed ({type(e).__name__}: {e}); using patterns only") - verdict.judge_error = f"{type(e).__name__}: {e}"[: self.RECORDED_ERROR_CHARS] - return verdict - if judged is None: - verdict.judge_error = "unparseable judge output" - return verdict - verdict.judge_in_role = judged["in_role"] - verdict.judge_reason = str(judged.get("reason", ""))[: self.RECORDED_REASON_CHARS] - if not judged["in_role"] and (reasons or len(candidate) >= self.judge_min_chars): - verdict.passed = False - elif judged["in_role"] and reasons and set(reasons) <= PHRASE_REASONS: - verdict.passed = True # a phrase alone, which the judge reads as the user's - verdict.cleared_by_judge = True + verdict.judge_in_role = judged["in_role"] + verdict.judge_reason = str(judged.get("reason", ""))[: self.RECORDED_REASON_CHARS] + verdict.passed = judged["in_role"] return verdict async def _judge(self, candidate: str, history: list[tuple[str, str]], route, - user_note: Optional[str] = None, + user_note: Optional[str] = None, instructions: Optional[str] = None, on_call: Optional[Callable[[ModelReply], None]] = None) -> Optional[dict]: """One judge call through core's one model-call path (config/model_call.py), on ``route`` (``judge_call_config``'s), or on the configured endpoint when none was given.""" @@ -300,6 +300,8 @@ async def _judge(self, candidate: str, history: list[tuple[str, str]], route, history=render_history(history, self.context_turns, self.context_chars), candidate=candidate[: self.context_chars * 2], user_note=_USER_NOTE.format(note=user_note.strip()) if user_note else "", + instructions=(_INSTRUCTIONS.format(instructions=instructions.strip()[: self.INSTRUCTIONS_MAX_CHARS]) + if instructions else ""), ) if route is None: route = judge_call_config(self, {}) @@ -319,13 +321,10 @@ class GateVerdict: judge_in_role: Optional[bool] = None judge_reason: Optional[str] = None judge_error: Optional[str] = None - cleared_by_judge: Optional[bool] = None # the judge read a phrase-only hit as the user's def reasons(self) -> list[str]: - out = list(self.pattern_reasons) - if self.judge_in_role is False and self.judge_reason: - out.append(self.judge_reason) - return out + """Why the judge held the message back; empty for one it passed.""" + return [self.judge_reason or "it reads as the assistant's message"] if self.judge_in_role is False else [] def to_dict(self) -> dict: return {k: v for k, v in asdict(self).items() if v not in (None, [])} @@ -364,23 +363,26 @@ async def run_gate( rewrite: Callable[[str], Awaitable[Optional[str]]], *, call_config=None, - judge_unavailable: Optional[str] = None, on_verdict: Optional[Callable[[int, str, GateVerdict], None]] = None, user_note: Optional[str] = None, + instructions: Optional[str] = None, on_call: Optional[Callable[[ModelReply], None]] = None, ) -> GateOutcome: """Check ``text``; while it fails, send the user-sim ``rewrite_request`` through ``rewrite`` and check its new message, up to ``gate.max_rewrites`` times. ``rewrite`` returns the new message, or None when the user side - ended instead. ``judge_unavailable`` is why the judge couldn't be set up, if it couldn't (see ``check``). + ended instead. ``on_verdict(attempt, text, verdict)`` sees every check, for recording. ``user_note`` is what a post-turn hook - told the user sim it found, shown to the judge. ``on_call`` sees each judge call's reply, for the step's usage. + told the user sim it found, and ``instructions`` the user sim's own, both shown to the judge. ``on_call`` sees each + judge call's reply, for the step's usage. Any conversation loop can call this; ``prompt_agent`` does, between a user-sim's reply and the agent's next turn.""" outcome = GateOutcome(text=text) for attempt in range(gate.max_rewrites + 1): - extra = {} if judge_unavailable is None else {"judge_unavailable": judge_unavailable} + extra = {} if user_note: # what a post-turn hook told the user sim it found: the judge reads a report of it as the user's extra["user_note"] = user_note + if instructions: + extra["instructions"] = instructions if on_call is not None: extra["on_call"] = on_call verdict = await gate.check(text, history, call_config=call_config, **extra) @@ -403,27 +405,20 @@ async def run_gate( JUDGE_KEY_HOW = "judge_litellm_api_key, or litellm_api_key, in the run's overrides" -def judge_setup_failed(gate: UserSimGate, error: Exception) -> str: - """What a step records when the gate's judge can't be set up (``judge_call_config`` raised), so the patterns' - verdict stands. With patterns off nothing would check the user sim's messages for the rest of the run, and a - setup failure won't recover, so that raises instead.""" - reason = f"judge setup: {type(error).__name__}: {error}" - if not gate.patterns: - raise RuntimeError(f"user_sim_gate: {reason}; with patterns off, nothing would check the user sim's " - "messages, so the step fails rather than run unchecked") from error - return reason[: gate.RECORDED_ERROR_CHARS] - - def judge_call_config(gate: UserSimGate, user_overrides: dict): """The route of the gate's judge calls (a ``model_call.ModelRoute``), honoring a run's judge or LiteLLM - overrides as the rubrics verifier does; None without a judge. Raises ConfigError, as a setup failure, for an - endpoint the run gives no key for.""" + overrides as the rubrics verifier does; None without a judge. A judge that can't be set up (an endpoint the run + gives no key for) raises, failing the step: without its judge the gate holds nothing back.""" if not gate.judge_model: return None from agent_env.config import model_call - return model_call.resolve_route( - gate.judge_model, - api_key=user_overrides.get("judge_litellm_api_key") or user_overrides.get("litellm_api_key"), - api_base=user_overrides.get("judge_litellm_base_url") or user_overrides.get("litellm_base_url"), - who="user_sim_gate", key_how=JUDGE_KEY_HOW) + try: + return model_call.resolve_route( + gate.judge_model, + api_key=user_overrides.get("judge_litellm_api_key") or user_overrides.get("litellm_api_key"), + api_base=user_overrides.get("judge_litellm_base_url") or user_overrides.get("litellm_base_url"), + who="user_sim_gate", key_how=JUDGE_KEY_HOW) + except Exception as e: + raise RuntimeError(f"user_sim_gate: judge setup: {type(e).__name__}: {e}; only the judge holds a message " + "back, so the step fails rather than run unchecked") from e diff --git a/tst/unit/task_step/test_always_on_user_sim_gate.py b/tst/unit/task_step/test_always_on_user_sim_gate.py index 4fe37ba54..9b2a821d1 100644 --- a/tst/unit/task_step/test_always_on_user_sim_gate.py +++ b/tst/unit/task_step/test_always_on_user_sim_gate.py @@ -8,9 +8,9 @@ import pytest from tst.unit.task_step.always_on_harness import Rig -from tst.unit.task_step.test_prompt_agent_user_side import _SWAP +from tst.unit.task_step.test_prompt_agent_user_side import _SWAP, pattern_judge # noqa: F401 -pytestmark = pytest.mark.usefixtures("local_stores") +pytestmark = pytest.mark.usefixtures("local_stores", "pattern_judge") NOTE = "[Conversation system note, not from the assistant.] Your last message was not sent" @@ -28,7 +28,7 @@ def _messages_once(n, texts, rig): def _gated(rig: Rig, **gate): - return rig.step(max_wakes=4, user_sim_gate={"patterns": True, **gate}) + return rig.step(max_wakes=4, user_sim_gate={"patterns": True, "judge_model": "judge", **gate}) def _got(rig: Rig, text: str) -> bool: @@ -66,8 +66,8 @@ async def test_an_answer_that_still_fails_never_reaches_the_agent_and_ends_the_r assert not _got(rig, "None of the three reported numbers") assert len(rig.sent) == 1 # no wake after hers: the run ended at her read record = rig.record(ctx) - assert record["end_reason"] == "user_sim_invalid" - assert record["error_type"] == "user_sim_invalid" # verifiers skip a run that broke, as on a user sim error + assert record["end_reason"] == "user_sim_error" # a failed user sim: the run is redone + assert record["error_type"] == "user_sim_error" assert ctx.metadata["user_sim_invalid"]["week"]["wake"] == 1 (read,) = rig.events(ctx, "user_sim_read") assert read["outcome"] == "no_reply" and read["user_sim_gate"]["invalid"] is True @@ -84,7 +84,7 @@ async def test_a_rewrite_with_nothing_to_send_holds_the_message_back_and_fails_t assert not _got(rig, "None of the three reported numbers") record = rig.record(ctx) - assert record["end_reason"] == "user_sim_invalid" and record["error_type"] == "user_sim_invalid" + assert record["end_reason"] == "user_sim_error" and record["error_type"] == "user_sim_error" assert ctx.metadata["user_sim_invalid"]["week"]["reasons"][-1] == "its rewrite sent nothing in its place" (read,) = rig.events(ctx, "user_sim_read") assert read["outcome"] == "no_reply" and read["user_sim_gate"]["invalid"] is True @@ -108,11 +108,39 @@ async def test_an_in_role_answer_passes_with_no_rewrite(monkeypatch, tmp_path): await rig.arm() ctx = await rig.run(_gated(rig)) (read, *_) = rig.events(ctx, "user_sim_read") - assert read["user_sim_gate"] == {"verdicts": [{"attempt": 0, "chars": 15, "passed": True}], "rewrites": [], - "invalid": False} + assert read["user_sim_gate"] == {"verdicts": [{"attempt": 0, "chars": 15, "passed": True, "judge_in_role": True, + "judge_reason": "written as the user"}], + "rewrites": [], "invalid": False} assert rig.user_calls == [] +@pytest.mark.asyncio +async def test_a_gate_without_a_judge_records_pattern_matches_and_holds_nothing_back(monkeypatch, tmp_path): + rig = Rig(monkeypatch, tmp_path, agent=_messages_once, answers=[{"outcome": "reply", "message": _SWAP}]) + await rig.arm() + ctx = await rig.run(rig.step(max_wakes=4, user_sim_gate={})) + (read, *_) = rig.events(ctx, "user_sim_read") + assert read["user_sim_gate"]["verdicts"][0]["passed"] is True and read["user_sim_gate"]["verdicts"][0]["pattern_reasons"] + assert _got(rig, "None of the three reported numbers") and rig.user_calls == [] + + +@pytest.mark.asyncio +async def test_the_judge_reads_the_user_sims_own_instructions(monkeypatch, tmp_path): + from agent_env.task_step.task_steps.user_sim_gate import UserSimGate + + seen = [] + + async def judge(self, candidate, history, call_config, instructions=None, **_): + seen.append(instructions) + return {"in_role": True, "reason": "asks"} + + monkeypatch.setattr(UserSimGate, "_judge", judge) + rig = Rig(monkeypatch, tmp_path, agent=_messages_once, answers=[{"outcome": "reply", "message": "shorter, please"}]) + await rig.arm() + await rig.run(_gated(rig)) + assert len(seen) == 1 and seen[0] and "Linda" in seen[0] + + @pytest.mark.asyncio async def test_without_the_gate_nothing_is_checked(monkeypatch, tmp_path): plain = Rig(monkeypatch, tmp_path, agent=_messages_once, answers=[{"outcome": "reply", "message": _SWAP}]) @@ -124,8 +152,8 @@ async def test_without_the_gate_nothing_is_checked(monkeypatch, tmp_path): @pytest.mark.asyncio -async def test_a_judge_only_gate_whose_judge_cant_be_set_up_fails_the_step(monkeypatch, tmp_path): - # A setup failure won't recover, and with patterns off nothing else would check her answers. +async def test_a_gate_whose_judge_cant_be_set_up_fails_the_step(monkeypatch, tmp_path): + # A setup failure won't recover, and only the judge holds an answer back. def no_endpoint(model, **kw): raise KeyError("no endpoint configured for judge-model") @@ -133,8 +161,8 @@ def no_endpoint(model, **kw): rig = Rig(monkeypatch, tmp_path, agent=_messages_once, answers=[{"outcome": "reply", "message": "looks good"}]) await rig.arm() - with pytest.raises(Exception, match="judge setup: KeyError.*with patterns off"): - await rig.run(rig.step(max_wakes=4, user_sim_gate={"patterns": False, "judge_model": "judge-model"})) + with pytest.raises(Exception, match="judge setup: KeyError.*only the judge holds"): + await rig.run(rig.step(max_wakes=4, user_sim_gate={"judge_model": "judge-model"})) assert not _got(rig, "looks good") 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 996b80fef..96e9a9bfd 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 @@ -18,9 +18,9 @@ from agent_env.task_step.task_steps.verifiers.agent_prompt_response_verifier import AgentPromptResponseVerifierTaskStep from tst.unit.task_step.test_deploy_user_sim_agent import HANNAH, _published, _step as _deploy_step from tst.unit.task_step.test_prompt_agent_user_side import ( - _SWAP, AGENT, HANG, HUMAN, USER, Peers, _stored, exchange, text) + _SWAP, AGENT, HANG, HUMAN, USER, Peers, _stored, exchange, pattern_judge, text) # noqa: F401 -pytestmark = pytest.mark.usefixtures("local_stores") +pytestmark = pytest.mark.usefixtures("local_stores", "pattern_judge") _CONFIG_CARD = {"capabilities": {"extensions": [{"uri": "urn:agentenv:agent-config/v1", "params": { "endpoint": "/ext/agent-config", "methods": {"set": {"request": {"supported": ["output_format", "model"]}}}}}]}} @@ -417,7 +417,7 @@ async def test_agent_triggers_registered_for_the_built_in_user_are_refused_befor # ---- the user-sim gate ---------------------------------------------------------------------------------------------- def _gated(turns: int = 3, **gate) -> PromptAgentTaskStep: - return _step(turns=turns, user_sim_gate={"patterns": True, **gate}) + return _step(turns=turns, user_sim_gate={"patterns": True, "judge_model": "judge", **gate}) def _to(peers: Peers, ctx: TaskStepContext, url: str) -> list[str]: @@ -449,12 +449,11 @@ async def test_the_gate_holds_back_a_built_in_users_answer_that_reads_as_the_ass @pytest.mark.asyncio -async def test_a_built_in_users_answer_that_still_fails_ends_the_run_and_fails_the_step(monkeypatch): +async def test_a_built_in_users_answer_that_still_fails_ends_the_run_as_a_failed_user_sim(monkeypatch): peers = Peers(monkeypatch, {AGENT: [text("draft one")], USER: [said("reply", _SWAP)] * 3}) ctx = await _context(monkeypatch) - with pytest.raises(RuntimeError, match=r"user_sim_gate: user-sim message at turn 1 still reads as the assistant's"): - await _gated().execute(ctx) + await _gated().execute(ctx) assert [v["passed"] for v in ctx.metadata["user_sim_gate"]["talk"]] == [False, False, False] assert ctx.metadata["user_sim_invalid"]["talk"]["turn"] == 1 @@ -462,9 +461,10 @@ async def test_a_built_in_users_answer_that_still_fails_ends_the_run_and_fails_t # Nothing reached the agent, so the read is a no_reply with no message, as in always_on. read = _reads(ctx)[0] assert (read["outcome"], read["message"], read["first_message"]) == ("no_reply", "", _SWAP) - # Verifiers skip a response with an error_type, so a cut-off conversation isn't graded as the agent's answer. - assert ctx.prompt_responses[-1].error_type == "user_sim_invalid" - assert ctx.prompt_responses[-1].error_message.startswith("user_sim_gate: user-sim message at turn 1") + # A failed user sim: verifiers skip the run and it is redone, rather than graded as the agent's answer. + assert ctx.prompt_responses[-1].error_type == "user_sim_error" + assert ctx.prompt_responses[-1].error_message.startswith( + "The user simulator failed: user_sim_gate: user-sim message at turn 1") assert _to(peers, ctx, AGENT) == ["plan my parents' visit"] # nothing she wrote reached the agent @@ -531,3 +531,23 @@ async def post_turn(turn, params): sent_to_agent = [r[2]["params"]["message"]["parts"] for r in peers.requests(ctx) if r[1] == f"{AGENT}/a2a" and r[2].get("method") == "message/send"] assert all("no total" not in json.dumps(parts) for parts in sent_to_agent) + + +@pytest.mark.asyncio +async def test_the_judge_reads_the_built_in_users_own_instructions(monkeypatch): + from agent_env.task_step.task_steps.user_sim_gate import UserSimGate + + seen = [] + + async def judge(self, candidate, history, call_config, instructions=None, **_): + seen.append(instructions) + return {"in_role": True, "reason": "asks"} + + monkeypatch.setattr(UserSimGate, "_judge", judge) + Peers(monkeypatch, {AGENT: [text("draft one"), text("you're welcome")], + USER: [said("done", "great, thanks")]}) + ctx = await _context(monkeypatch) + + await _gated().execute(ctx) + + assert len(seen) == 1 and seen[0] and "Hannah" in seen[0] diff --git a/tst/unit/task_step/test_prompt_agent_user_side.py b/tst/unit/task_step/test_prompt_agent_user_side.py index 6d7e20003..920d50d79 100644 --- a/tst/unit/task_step/test_prompt_agent_user_side.py +++ b/tst/unit/task_step/test_prompt_agent_user_side.py @@ -13,6 +13,7 @@ from agent_env.env.gateway.constants import EXT_TRIGGERS_URI, GATEWAY_EXTENSIONS, WELL_KNOWN_PATH from agent_env.task_step.context import DeployedAgent, TaskStepContext from agent_env.task_step.task_steps.prompt_agent import PromptAgentTaskStep +from agent_env.task_step.task_steps.user_sim_gate import UserSimGate, pattern_reasons AGENT = "http://agent.test" USER = "http://user.test" @@ -492,7 +493,25 @@ async def test_with_no_user_agent_the_configured_human_peer_answers(monkeypatch) def _gated(turns: int = 2, **gate) -> PromptAgentTaskStep: - return _step(turns=turns, user_agent_name="human_agent", user_sim_gate={"patterns": True, **gate}) + return _step(turns=turns, user_agent_name="human_agent", + user_sim_gate={"patterns": True, "judge_model": "judge", **gate}) + + +async def _pattern_judge(self, candidate, history, call_config, **_): + """A stand-in for the gate's judge: it reads a message as the assistant's exactly when the patterns match it.""" + reasons = pattern_reasons(candidate) + return {"in_role": not reasons, "reason": "; ".join(reasons) or "written as the user"} + + +@pytest.fixture +def pattern_judge(monkeypatch): + monkeypatch.setattr(UserSimGate, "_judge", _pattern_judge) + monkeypatch.setattr("agent_env.config.model_call.resolve_route", lambda model, **kw: None) + + +@pytest.fixture(autouse=True) +def _judged_by_patterns(pattern_judge): + pass @pytest.mark.asyncio @@ -503,7 +522,8 @@ async def test_the_gate_lets_a_user_message_through_and_records_its_verdict(monk await _gated().execute(ctx) assert peers.requests(ctx)[-2] == send(AGENT, text("make it shorter"), "", "") - assert ctx.metadata["user_sim_gate"] == {"talk": [{"turn": 1, "attempt": 0, "chars": 15, "passed": True}]} + assert ctx.metadata["user_sim_gate"] == {"talk": [{"turn": 1, "attempt": 0, "chars": 15, "passed": True, + "judge_in_role": True, "judge_reason": "written as the user"}]} assert "user_sim_invalid" not in ctx.metadata @@ -527,19 +547,20 @@ async def test_a_message_that_reads_as_the_assistants_is_held_back_and_rewritten @pytest.mark.asyncio -async def test_a_message_that_still_fails_after_its_rewrites_ends_the_run_and_fails_the_step(monkeypatch): +async def test_a_message_that_still_fails_after_its_rewrites_ends_the_run_as_a_failed_user_sim(monkeypatch): peers = Peers(monkeypatch, {AGENT: [text("draft one")], USER: [sim(_SWAP), sim(_SWAP), sim(_SWAP)]}) ctx = _context(user_card=_USER_SIM_CARD) - with pytest.raises(RuntimeError, match=r"user_sim_gate: user-sim message at turn 1 still reads as the assistant's"): - await _gated(turns=3).execute(ctx) + await _gated(turns=3).execute(ctx) assert [v["passed"] for v in ctx.metadata["user_sim_gate"]["talk"]] == [False, False, False] assert ctx.metadata["user_sim_invalid"]["talk"]["turn"] == 1 assert _stored(ctx, peers)["status"] == "closed" assert [m["role"] for m in _stored(ctx, peers)["messages"]] == ["user", "agent"] # nothing more was sent assert ctx.prompt_responses[-1].response == "draft one" # the run kept its record - assert ctx.prompt_responses[-1].error_type == "user_sim_invalid" # which verifiers skip + assert ctx.prompt_responses[-1].error_type == "user_sim_error" # redone, as a failed user sim + assert ctx.prompt_responses[-1].error_message.startswith( + "The user simulator failed: user_sim_gate: user-sim message at turn 1 still reads as the assistant's") @pytest.mark.asyncio @@ -613,37 +634,9 @@ def test_the_gate_round_trips_through_the_step_dict_and_rejects_bad_settings(): @pytest.mark.asyncio -async def test_a_judge_whose_setup_fails_leaves_the_patterns_verdict_and_is_not_called(monkeypatch): - from agent_env.task_step.task_steps import user_sim_gate - - called = [] - - async def judge(self, candidate, history, call_config, **_): - called.append(candidate) - return {"in_role": True} - - def no_endpoint(model, **kw): - raise KeyError("no endpoint configured for judge-model") - - monkeypatch.setattr(user_sim_gate.UserSimGate, "_judge", judge) - monkeypatch.setattr("agent_env.config.model_call.resolve_route", no_endpoint) - peers = Peers(monkeypatch, {AGENT: [text("draft one"), text("draft two")], - USER: [sim(_SWAP), sim("shorter, please")]}) - ctx = _context(user_card=_USER_SIM_CARD) - - await _gated(judge_model="judge-model").execute(ctx) - - verdicts = ctx.metadata["user_sim_gate"]["talk"] - assert [v["passed"] for v in verdicts] == [False, True] # the patterns still held the swap back - assert all(v["judge_error"].startswith("judge setup: KeyError") for v in verdicts) - assert called == [] - assert peers.requests(ctx)[-2] == send(AGENT, text("shorter, please"), "", "") - - -@pytest.mark.asyncio -async def test_a_judge_only_gate_whose_setup_fails_fails_the_step_before_any_unchecked_message_reaches_the_agent( +async def test_a_gate_whose_judge_setup_fails_fails_the_step_before_any_unchecked_message_reaches_the_agent( monkeypatch): - # A setup failure won't recover, and with patterns off nothing else would check the user sim's messages. + # A setup failure won't recover, and only the judge holds a message back. def no_endpoint(model, **kw): raise KeyError("no endpoint configured for judge-model") @@ -651,7 +644,7 @@ def no_endpoint(model, **kw): peers = Peers(monkeypatch, {AGENT: [text("draft one"), text("draft two")], USER: [sim("shorter, please")]}) ctx = _context(user_card=_USER_SIM_CARD) - with pytest.raises(RuntimeError, match="judge setup: KeyError.*with patterns off"): - await _gated(patterns=False, judge_model="judge-model").execute(ctx) + with pytest.raises(RuntimeError, match="judge setup: KeyError.*only the judge holds"): + await _gated(judge_model="judge-model").execute(ctx) assert not any(r == send(AGENT, text("shorter, please"), "", "") for r in peers.requests(ctx)) diff --git a/tst/unit/task_step/test_user_sim_gate.py b/tst/unit/task_step/test_user_sim_gate.py index 94f9f24c3..a94b563af 100644 --- a/tst/unit/task_step/test_user_sim_gate.py +++ b/tst/unit/task_step/test_user_sim_gate.py @@ -7,7 +7,7 @@ from agent_env.config import model_call from agent_env.config.model_pricing import Cost, CostStatus from agent_env.task_step.task_steps.user_sim_gate import ( - TALKS_LIKE_THE_ASSISTANT, GateVerdict, UserSimGate, parse_judge, pattern_reasons, render_history, rewrite_request) + TALKS_LIKE_THE_ASSISTANT, GateVerdict, UserSimGate, judge_call_config, parse_judge, pattern_reasons, render_history, rewrite_request) _FILLER = " The details are in the shared folder and the numbers come from last month's records." * 6 @@ -69,22 +69,25 @@ def test_the_rewrite_request_names_why_and_says_it_is_not_from_the_assistant(): note = rewrite_request(GateVerdict(passed=False, pattern_reasons=["it opens like a report of work done"], judge_in_role=False, judge_reason="it answers its own question")) assert note.startswith("[Conversation system note, not from the assistant.]") - assert "it opens like a report of work done; it answers its own question" in note + assert "rather than yours: it answers its own question." in note # the judge's reason; patterns are records -def test_the_judge_alone_fails_only_a_long_message(): - import asyncio - from agent_env.task_step.task_steps.user_sim_gate import UserSimGate +def test_only_the_judge_holds_a_message_back_at_any_length_and_patterns_are_recorded(): + phrase = "Want me to send it to you?" + shape = "Done. Here's what I found when I went through the files." + _FILLER + short = "Contracted physicians are required in two states." + + assert asyncio.run(_judged(False).check(short, [])).passed is False # no length floor + for text in (phrase, shape): + cleared = asyncio.run(_judged(True).check(text, [])) + assert cleared.passed is True and cleared.pattern_reasons # a match alone holds nothing back + held = asyncio.run(_judged(False).check(shape, [])) + assert (held.passed, held.reasons()) == (False, ["judged"]) - class Gate(UserSimGate): - async def _judge(self, candidate, history, call_config, **_): - return {"in_role": False, "reason": "reads as analysis"} - gate = Gate(judge_model="judge-model") - short = asyncio.run(gate.check("Contracted physicians are required in two states.", [])) - long = asyncio.run(gate.check("The two states that need contracted physicians are these." + _FILLER, [])) - assert (short.passed, short.judge_in_role) == (True, False) # recorded, not failed - assert long.passed is False +def test_without_a_judge_the_gate_only_records_pattern_matches(): + verdict = asyncio.run(UserSimGate().check("I checked my bank app and I verified the charge is there.", [])) + assert verdict.passed is True and verdict.pattern_reasons # ---- run_gate, for any conversation loop ------------------------------------------------------------------------------ @@ -93,7 +96,7 @@ def _scripted_gate(verdicts, **settings): from agent_env.task_step.task_steps.user_sim_gate import GateVerdict, UserSimGate class Gate(UserSimGate): - async def check(self, candidate, history, *, call_config=None, judge_unavailable=None): + async def check(self, candidate, history, *, call_config=None, **_): return GateVerdict(passed=verdicts.pop(0), pattern_reasons=["it opens like a report of work done"]) return Gate(**settings) @@ -173,18 +176,22 @@ def test_an_always_on_step_keeps_its_gate_through_the_step_dict(): assert AlwaysOnTaskStep.from_dict(plain.to_dict()).user_sim_gate is None -def test_a_judge_that_couldnt_be_set_up_isnt_called_and_the_patterns_verdict_stands(): - import asyncio - from agent_env.task_step.task_steps.user_sim_gate import UserSimGate +def test_a_judge_that_cant_be_set_up_fails_the_step_since_nothing_else_holds_a_message_back(monkeypatch): + def refuse(model, **kw): + raise KeyError("no key") + + monkeypatch.setattr(model_call, "resolve_route", refuse) + with pytest.raises(RuntimeError, match="user_sim_gate: judge setup: KeyError"): + judge_call_config(UserSimGate(judge_model="judge-model"), {}) + - class NeverCalled(UserSimGate): +def test_a_judge_call_that_errors_sends_the_message_with_the_error_recorded(): + class Failing(UserSimGate): async def _judge(self, candidate, history, call_config, **_): - raise AssertionError("the judge was called") + raise TimeoutError("judge timed out") - for patterns in (True, False): - gate = NeverCalled(patterns=patterns, judge_model="judge-model") - verdict = asyncio.run(gate.check("shorter, please", [], judge_unavailable="judge setup: KeyError: x")) - assert (verdict.passed, verdict.judge_error) == (True, "judge setup: KeyError: x") + verdict = asyncio.run(Failing(judge_model="judge-model").check("Want me to send it to you?", [])) + assert (verdict.passed, verdict.judge_error) == (True, "TimeoutError: judge timed out") def test_the_judge_calls_through_the_one_model_call_path_on_the_runs_route(monkeypatch): @@ -227,21 +234,11 @@ async def _judge(self, candidate, history, call_config, **_): return Gate(judge_model="judge-model") -def test_a_judge_reading_it_as_the_user_clears_a_phrase_but_not_a_reports_shape(): - import asyncio - - phrase = "Understood. Standing by." - shape = "Done. Here's what I found when I went through the files." + _FILLER - cleared = asyncio.run(_judged(True).check(phrase, [])) - assert (cleared.passed, cleared.cleared_by_judge) == (True, True) and cleared.pattern_reasons - assert asyncio.run(_judged(True).check(shape, [])).passed is False # shape + length: a failure whatever the judge - assert asyncio.run(_judged(False).check(phrase, [])).passed is False - @pytest.mark.parametrize("settings, field", [ ({"max_rewrites": 1.5}, "max_rewrites"), ({"max_rewrites": True}, "max_rewrites"), - ({"max_rewrites": -1}, "max_rewrites"), ({"judge_min_chars": None}, "judge_min_chars"), + ({"max_rewrites": -1}, "max_rewrites"), ({"patterns": "false"}, "patterns"), ({"context_turns": "4"}, "context_turns"), ({"context_chars": 0}, "context_chars"), ({"judge_timeout_seconds": 0}, "judge_timeout_seconds"), ({"judge_model": ""}, "judge_model"), ({"on_fail": "skip"}, "on_fail"), @@ -282,6 +279,22 @@ async def complete(route, messages, *, timeout, response_format=None): assert "WHAT THE USER FOUND" not in prompts[1] +def test_the_judge_is_shown_the_user_sims_instructions(monkeypatch): + prompts = [] + + async def complete(route, messages, *, timeout, response_format=None): + prompts.append(messages[0]["content"]) + return model_call.ModelReply('{"in_role": true, "reason": "ok"}', "m", None, None, None) + + monkeypatch.setattr(model_call, "complete", complete) + gate = UserSimGate(judge_model="judge-model") + asyncio.run(gate._judge("i checked my bank app", [], "route", instructions="You are Ana. You check your bank app.")) + asyncio.run(gate._judge("i checked my bank app", [], "route")) + + assert "THE USER'S INSTRUCTIONS" in prompts[0] and "You check your bank app." in prompts[0] + assert "THE USER'S INSTRUCTIONS" not in prompts[1] + + @pytest.mark.parametrize("text", ["I\u2019m an AI, so I can\u2019t open that.", "Let me know if you\u2019d like me to resend it."]) def test_curly_apostrophes_read_as_straight_ones(text): diff --git a/tst/unit/task_step/test_user_sim_satisfaction.py b/tst/unit/task_step/test_user_sim_satisfaction.py index fe07babbb..57eefcb11 100644 --- a/tst/unit/task_step/test_user_sim_satisfaction.py +++ b/tst/unit/task_step/test_user_sim_satisfaction.py @@ -551,12 +551,12 @@ async def test_a_prompt_agent_chat_the_user_sim_gate_cut_off_is_not_rated_and_th ctx = await _context(monkeypatch) ctx.metadata.setdefault("a2a_conversations", {})["talk"] = None - ctx.prompt_responses.append(PromptResponse(prompt_id="p", response="draft", error_type="user_sim_invalid", - error_message="user_sim_gate: user-sim message at turn 1 ...", - step_id="talk")) + ctx.prompt_responses.append(PromptResponse( + prompt_id="p", response="draft", error_type="user_sim_error", + error_message="The user simulator failed: user_sim_gate: user-sim message at turn 1 ...", step_id="talk")) await _hannah_rater().execute(ctx) rating = ctx.metadata[SATISFACTION_KEY]["talk"] - assert rating["skipped"] == "the user sim's message still read as the assistant's after its rewrites" + assert rating["skipped"] == "the user sim failed: user_sim_gate: user-sim message at turn 1 ..." assert rating["score"] is None @@ -572,8 +572,7 @@ async def test_a_prompt_agent_chat_whose_agent_turn_failed_is_not_rated(monkeypa @pytest.mark.parametrize("record, skipped", [ - ({"end_reason": "user_sim_invalid", "error_type": "user_sim_invalid"}, - "the user sim's answer still read as the assistant's after its rewrites"), + ({"end_reason": "user_sim_error", "error_type": "user_sim_error"}, "the run ended on user_sim_error"), ({"end_reason": "user_sim_invalid"}, None), # on_fail "end": no error, so the run is rated as one that ended ], ids=["on_fail fail", "on_fail end"]) def test_an_always_on_run_the_gate_failed_as_an_error_is_not_rated(record, skipped): From 72677ea59e1ce9447ef62861e72969383db1d7b6 Mon Sep 17 00:00:00 2001 From: kaihackney-scale Date: Sun, 22 Nov 2026 00:37:48 -0500 Subject: [PATCH 16/18] fix(prompt_agent): fail the step again when the user-sim gate rejects every rewrite The response is still recorded as a failed user sim (error_type user_sim_error), then the step raises, so retry_config redoes the run and fail_task_on_error applies instead of dependent steps starting. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/task_step/task_steps/prompt_agent.py | 4 ++++ src/agent_env/task_step/task_steps/user_sim_gate.py | 3 ++- tst/unit/task_step/test_prompt_agent_built_in_user_sim.py | 5 +++-- tst/unit/task_step/test_prompt_agent_user_side.py | 5 +++-- 4 files changed, 12 insertions(+), 5 deletions(-) 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 ddb68137d..666df1865 100644 --- a/src/agent_env/task_step/task_steps/prompt_agent.py +++ b/src/agent_env/task_step/task_steps/prompt_agent.py @@ -904,6 +904,10 @@ def record_turn() -> None: usage=usage.entries(), )) + if user_side.gate_failure is not None: + # Recorded above as a failed user sim; raising lets retry_config redo the run and fail_task_on_error apply. + raise RuntimeError(f"user_sim_gate: {user_side.gate_failure}") + if final_state == TaskState.failed: detail_parts = [] if final_terminal.error_type: diff --git a/src/agent_env/task_step/task_steps/user_sim_gate.py b/src/agent_env/task_step/task_steps/user_sim_gate.py index 01a897434..e2fb0a03f 100644 --- a/src/agent_env/task_step/task_steps/user_sim_gate.py +++ b/src/agent_env/task_step/task_steps/user_sim_gate.py @@ -216,7 +216,8 @@ class UserSimGate: judge_model: Optional[str] = None max_rewrites: int = 2 # What happens when a message still fails after its rewrites: "fail" ends the conversation as a failed user sim - # (error_type user_sim_error, so the run is redone), "end" ends it plainly, "send" sends it anyway (record only). + # (error_type user_sim_error; prompt_agent also fails the step, so its retry_config redoes it), "end" ends it + # plainly, "send" sends it anyway (record only). on_fail: str = "fail" context_turns: int = 4 context_chars: int = 3000 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 96e9a9bfd..742ff8458 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 @@ -449,11 +449,12 @@ async def test_the_gate_holds_back_a_built_in_users_answer_that_reads_as_the_ass @pytest.mark.asyncio -async def test_a_built_in_users_answer_that_still_fails_ends_the_run_as_a_failed_user_sim(monkeypatch): +async def test_a_built_in_users_answer_that_still_fails_fails_the_step_as_a_failed_user_sim(monkeypatch): peers = Peers(monkeypatch, {AGENT: [text("draft one")], USER: [said("reply", _SWAP)] * 3}) ctx = await _context(monkeypatch) - await _gated().execute(ctx) + with pytest.raises(RuntimeError, match=r"user_sim_gate: user-sim message at turn 1 still reads as the assistant's"): + await _gated().execute(ctx) assert [v["passed"] for v in ctx.metadata["user_sim_gate"]["talk"]] == [False, False, False] assert ctx.metadata["user_sim_invalid"]["talk"]["turn"] == 1 diff --git a/tst/unit/task_step/test_prompt_agent_user_side.py b/tst/unit/task_step/test_prompt_agent_user_side.py index 920d50d79..4cd596fba 100644 --- a/tst/unit/task_step/test_prompt_agent_user_side.py +++ b/tst/unit/task_step/test_prompt_agent_user_side.py @@ -547,11 +547,12 @@ async def test_a_message_that_reads_as_the_assistants_is_held_back_and_rewritten @pytest.mark.asyncio -async def test_a_message_that_still_fails_after_its_rewrites_ends_the_run_as_a_failed_user_sim(monkeypatch): +async def test_a_message_that_still_fails_after_its_rewrites_fails_the_step_as_a_failed_user_sim(monkeypatch): peers = Peers(monkeypatch, {AGENT: [text("draft one")], USER: [sim(_SWAP), sim(_SWAP), sim(_SWAP)]}) ctx = _context(user_card=_USER_SIM_CARD) - await _gated(turns=3).execute(ctx) + with pytest.raises(RuntimeError, match=r"user_sim_gate: user-sim message at turn 1 still reads as the assistant's"): + await _gated(turns=3).execute(ctx) assert [v["passed"] for v in ctx.metadata["user_sim_gate"]["talk"]] == [False, False, False] assert ctx.metadata["user_sim_invalid"]["talk"]["turn"] == 1 From fd9c3b3ca8c10b4b6e537b564d86cd7309f18a13 Mon Sep 17 00:00:00 2001 From: kaihackney-scale Date: Mon, 23 Nov 2026 02:18:51 -0500 Subject: [PATCH 17/18] fix(user-sim): a gate judge call cut off by its timeout or a cancel counts in the step's usage It may still be billed, so on_call gets it as a reply of unknown usage, which marks the judge's usage entry a lower bound. Co-Authored-By: Claude Opus 5.5 --- .../task_step/task_steps/user_sim_gate.py | 19 ++++++++--- tst/unit/task_step/test_user_sim_gate.py | 34 +++++++++++++++++++ 2 files changed, 48 insertions(+), 5 deletions(-) diff --git a/src/agent_env/task_step/task_steps/user_sim_gate.py b/src/agent_env/task_step/task_steps/user_sim_gate.py index e2fb0a03f..adc9b98b2 100644 --- a/src/agent_env/task_step/task_steps/user_sim_gate.py +++ b/src/agent_env/task_step/task_steps/user_sim_gate.py @@ -294,8 +294,11 @@ async def _judge(self, candidate: str, history: list[tuple[str, str]], route, user_note: Optional[str] = None, instructions: Optional[str] = None, on_call: Optional[Callable[[ModelReply], None]] = None) -> Optional[dict]: """One judge call through core's one model-call path (config/model_call.py), on ``route`` - (``judge_call_config``'s), or on the configured endpoint when none was given.""" + (``judge_call_config``'s), or on the configured endpoint when none was given. A call cut off by its timeout or + a cancel may still be billed, so ``on_call`` sees it as a reply of unknown usage, marking the usage a lower + bound.""" from agent_env.config import model_call + from agent_env.config.model_pricing import Cost, CostStatus, Unpriced prompt = _JUDGE_PROMPT.format( history=render_history(history, self.context_turns, self.context_chars), @@ -306,10 +309,16 @@ async def _judge(self, candidate: str, history: list[tuple[str, str]], route, ) if route is None: route = judge_call_config(self, {}) - reply = await model_call.complete( - route, [{"role": "user", "content": prompt}], timeout=self.judge_timeout_seconds, - response_format={"type": "json_schema", - "json_schema": {"name": "user_sim_gate", "schema": _JUDGE_SCHEMA, "strict": True}}) + try: + reply = await model_call.complete( + route, [{"role": "user", "content": prompt}], timeout=self.judge_timeout_seconds, + response_format={"type": "json_schema", + "json_schema": {"name": "user_sim_gate", "schema": _JUDGE_SCHEMA, "strict": True}}) + except BaseException as exc: + if on_call is not None and model_call.cut_off(exc): + on_call(model_call.ModelReply("", route.model, route.endpoint_host, None, + Cost(None, CostStatus.UNPRICED, None, None, unpriced=Unpriced.NO_TOKENS))) + raise if on_call is not None: on_call(reply) return parse_judge(reply.content) diff --git a/tst/unit/task_step/test_user_sim_gate.py b/tst/unit/task_step/test_user_sim_gate.py index a94b563af..ae7662f83 100644 --- a/tst/unit/task_step/test_user_sim_gate.py +++ b/tst/unit/task_step/test_user_sim_gate.py @@ -314,3 +314,37 @@ async def complete(route, messages, **kw): on_call=seen.append)) assert verdict.passed and seen == [reply] + + +@pytest.mark.parametrize("error, recorded", [ + (lambda: __import__("litellm").Timeout("judge timed out", model="judge-m", llm_provider="openai"), True), + (lambda: ValueError("bad route"), False), +], ids=["timed-out", "never-sent"]) +def test_a_judge_call_cut_off_by_its_timeout_is_still_handed_to_on_call_as_one_of_unknown_usage( + monkeypatch, error, recorded): + from types import SimpleNamespace + + from agent_env.config.model import ModelRole + from agent_env.task_step.context import TaskStepContext + from agent_env.task_step.usage import StepUsage + + async def complete(route, messages, **kw): + raise error() + + monkeypatch.setattr(model_call, "complete", complete) + context = TaskStepContext() + usage = StepUsage(context, "talk") + seen = [] + route = SimpleNamespace(model="judge-m", endpoint_host="gw:443") + verdict = asyncio.run(UserSimGate(judge_model="judge-m").check( + "can you check the totals?", [], call_config=route, + on_call=lambda reply: (seen.append(reply), usage.reply(ModelRole.JUDGE, reply)))) + + assert verdict.passed and verdict.judge_error + if not recorded: + assert seen == [] and "talk" not in context.metadata.get("step_usage", {}) + return + [reply] = seen + assert (reply.model, reply.endpoint_host, reply.usage, reply.cost.usd) == ("judge-m", "gw:443", None, None) + [entry] = context.metadata["step_usage"]["talk"] + assert entry["role"] == "judge" and entry["partial"] and entry["cost_usd"] is None From fefca802e4b6a3657f7da9b73964f066c0185f64 Mon Sep 17 00:00:00 2001 From: kaihackney-scale Date: Mon, 23 Nov 2026 13:15:50 -0500 Subject: [PATCH 18/18] fix(user-sim): a built-in user sim's rewritten answer is stored, so its judge grades what was sent prompt_agent stores a read before the gate checks it. A rewrite updated only the read's summary, and the user-sim judge reads the stored read over the summary, so it graded the held-back draft. The rewrite now stores the read again with the answer that was sent (the store is write-once: under a new key, which the summary's object_url now names), as always_on's read already holds it. Co-Authored-By: Claude Opus 5.5 --- .../task_step/task_steps/prompt_agent.py | 35 ++++++++++++++++--- .../test_prompt_agent_built_in_user_sim.py | 7 ++++ 2 files changed, 37 insertions(+), 5 deletions(-) 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 d5ac5b3c3..b96bd2b6b 100644 --- a/src/agent_env/task_step/task_steps/prompt_agent.py +++ b/src/agent_env/task_step/task_steps/prompt_agent.py @@ -1439,6 +1439,8 @@ def __init__(self, step: PromptAgentTaskStep, context: TaskStepContext, person: self.replies = 0 self.error: Optional[str] = None # the user sim's error, once a read ended on one self.instructions: Optional[str] = None # its system prompt, as the user-sim gate's judge reads it + # The last read stored whole: its object key and what was stored, so a rewrite can store what replaced it. + self._stored: Optional[tuple[str, dict]] = None @classmethod async def start(cls, step: PromptAgentTaskStep, context: TaskStepContext, record: dict, zone: str, @@ -1517,6 +1519,7 @@ async def rewrite(self, number: int, note: str, ask_user_sim) -> dict: reads[-1].setdefault("first_message", reads[-1].get("message")) reads[-1].setdefault("gate_rewrites", []).append(rewrite) reads[-1].update({k: v for k, v in rewrite.items() if k in ("outcome", "message", "used", "schema_errors")}) + await self._restore(reads[-1]) outcome, said = ans.get("outcome"), (ans.get("message") or "").strip() if self.history: held = self.history[-1]["answer"] @@ -1538,6 +1541,30 @@ async def rewrite(self, number: int, note: str, ask_user_sim) -> dict: return {"message": [{"kind": "text", "text": ans["message"]}], "end_after": "user_done"} return {"end": "user_done" if outcome == "done" else "user_no_reply"} + async def _restore(self, summary: dict) -> None: + """Store the read again with the answer a rewrite put in its summary, and point the summary's ``object_url`` at + it, so the stored read, which the user-sim judge reads over the summary, holds the message that reached the + agent, as always_on's does. The store is write-once: the read as first stored stays at its own key.""" + if self._stored is None or self._stored[1].get("turn") != summary.get("turn"): + return + full = self._stored[1] + full.update({k: summary[k] for k in ("outcome", "message", "used", "schema_errors", "first_message", + "gate_rewrites") if k in summary}) + try: + key = self._read_key(full["turn"]) + summary["object_url"] = await asyncio.to_thread( + get_config().get_object_store().put, key, json.dumps(full, indent=1, default=str).encode(), + content_type="application/json") + self._stored = (key, full) + except Exception as e: + logger.warning(f"prompt_agent '{self._step.id}': could not store user sim read {full['turn']} again: {e}") + summary["store_error"] = f"{type(e).__name__}: {str(e)[:300]}" + + def _read_key(self, number: int) -> str: + """A fresh object key for read ``number`` of this step.""" + return (f"{get_config().get_artifact_key_prefix()}prompt_agent_user_sim_reads/" + f"instance_id={self._context.instance_id or 'adhoc'}/{self._step.id}-{number}-{uuid.uuid4().hex[:8]}.json") + async def _record(self, number: int, read: dict, ans: dict, calls: list[dict], error: Optional[str]) -> None: """Record the read as always_on does: a summary in ``metadata["user_sim_reads"][step_id]``, the whole read (what the user sim was shown, and its raw answers) in the object store at the summary's ``object_url``.""" @@ -1550,13 +1577,11 @@ async def _record(self, number: int, read: dict, ans: dict, calls: list[dict], e if ans.get("first_answer"): # its raw answer is in the stored read summary["first_answer"] = {"schema_errors": ans["first_answer"].get("schema_errors")} try: - config = get_config() - key = (f"{config.get_artifact_key_prefix()}prompt_agent_user_sim_reads/" - f"instance_id={self._context.instance_id or 'adhoc'}/" - f"{self._step.id}-{number}-{uuid.uuid4().hex[:8]}.json") + key = self._read_key(number) summary["object_url"] = await asyncio.to_thread( - config.get_object_store().put, key, json.dumps(full, indent=1, default=str).encode(), + get_config().get_object_store().put, key, json.dumps(full, indent=1, default=str).encode(), content_type="application/json") + self._stored = (key, full) except Exception as e: logger.warning(f"prompt_agent '{self._step.id}': could not store user sim read {number}: {e}") summary["store_error"] = f"{type(e).__name__}: {str(e)[:300]}" 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 742ff8458..aaf9c211d 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 @@ -16,6 +16,7 @@ from agent_env.task_step.task_steps import prompt_agent as pa from agent_env.task_step.task_steps.prompt_agent import PromptAgentTaskStep, StoredTrajectory from agent_env.task_step.task_steps.verifiers.agent_prompt_response_verifier import AgentPromptResponseVerifierTaskStep +from agent_env.task_step.task_steps.verifiers.user_sim_judge import _chat_reads from tst.unit.task_step.test_deploy_user_sim_agent import HANNAH, _published, _step as _deploy_step from tst.unit.task_step.test_prompt_agent_user_side import ( _SWAP, AGENT, HANG, HUMAN, USER, Peers, _stored, exchange, pattern_judge, text) # noqa: F401 @@ -446,6 +447,12 @@ async def test_the_gate_holds_back_a_built_in_users_answer_that_reads_as_the_ass assert [(r["outcome"], r["message"], r["used"]) for r in first["gate_rewrites"]] == [ ("reply", "do those numbers hold up?", "D1")] assert "user_sim_invalid" not in ctx.metadata + # The stored read says the same, and the user-sim judge, which reads it over the summary, grades what was sent. + stored = _full(first) + assert (stored["message"], stored["used"], stored["first_message"]) == ("do those numbers hold up?", "D1", _SWAP) + assert stored["gate_rewrites"] == first["gate_rewrites"] and stored["raw"] is not None + judged, _ = _chat_reads(_reads(ctx)) + assert judged[0]["message"] == "do those numbers hold up?" @pytest.mark.asyncio