Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
6bbac7d
feat(prompt_agent): an opt-in gate on user-sim messages
Nov 10, 2026
fcec1e1
fix(prompt_agent): empty user_sim_gate settings turn the gate on; nam…
Nov 10, 2026
e63d512
feat(prompt_agent): run_gate for any conversation loop; refuse the ga…
Nov 10, 2026
1647dbf
Merge main into kai/usersim-gate
Nov 12, 2026
489b507
fix(user_sim_gate): saved always_on steps refuse the gate; judge setu…
Nov 12, 2026
095a14f
fix(user_sim_gate): a judge-only gate whose judge can't be set up kee…
Nov 12, 2026
cd653e8
Merge remote-tracking branch 'framework/main' into kai/usersim-gate
Nov 16, 2026
ed9b37c
feat(user sim): the gate checks the built-in user sim too, in prompt_…
Nov 16, 2026
8e76591
fix(user_sim_gate): a gate-failed response carries error_type; a rewr…
Nov 16, 2026
b46e22d
Merge branch 'main' of github.com:scaleapi/agentenv-framework into ka…
kaihackney-scale Nov 20, 2026
11cb3f9
fix(user_sim_gate): route the judge call as the rubrics verifier rout…
kaihackney-scale Nov 20, 2026
4ed6044
Merge branch 'main' of github.com:scaleapi/agentenv-framework into ka…
kaihackney-scale Nov 20, 2026
7abdcb4
fix(always_on): a gated read's time cap covers the gate's rewrites an…
kaihackney-scale Nov 20, 2026
83c5876
Merge main into kai/usersim-gate
kaihackney-scale Nov 20, 2026
278f28d
fix(user_sim_gate): address review: phrases users say, a judge that c…
kaihackney-scale Nov 20, 2026
730fe2f
fix(user_sim_gate): context_turns 0 shows the judge no history
kaihackney-scale Nov 20, 2026
e486141
Merge main (with #828) into kai/usersim-gate
kaihackney-scale Nov 21, 2026
5df699e
fix(always_on): a gate rewrite is read with the plugin's parse; a gat…
kaihackney-scale Nov 21, 2026
362f83c
fix(user_sim_gate): count judge calls in usage, read curly apostrophe…
kaihackney-scale Nov 22, 2026
d710662
Merge main into kai/usersim-gate; cost each judge call on its own
kaihackney-scale Nov 22, 2026
5167c62
fix(usage): keep judge call estimates apart from bills
kaihackney-scale Nov 22, 2026
9aee3f9
feat(user_sim_gate)!: the judge alone holds a message back, reads the…
kaihackney-scale Nov 22, 2026
72677ea
fix(prompt_agent): fail the step again when the user-sim gate rejects…
kaihackney-scale Nov 22, 2026
8756ef5
Merge main into kai/usersim-gate
kaihackney-scale Nov 23, 2026
e6f8291
Merge main into kai/usersim-gate
kaihackney-scale Nov 23, 2026
fd9c3b3
fix(user-sim): a gate judge call cut off by its timeout or a cancel c…
kaihackney-scale Nov 23, 2026
347fe45
Merge main into kai/usersim-gate
kaihackney-scale Nov 23, 2026
fefca80
fix(user-sim): a built-in user sim's rewritten answer is stored, so i…
kaihackney-scale Nov 23, 2026
7ef9d1b
Merge main into kai/usersim-gate
kaihackney-scale Nov 23, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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"}


Expand Down
119 changes: 114 additions & 5 deletions src/agent_env/task_step/task_steps/always_on.py

Large diffs are not rendered by default.

202 changes: 194 additions & 8 deletions src/agent_env/task_step/task_steps/prompt_agent.py

Large diffs are not rendered by default.

434 changes: 434 additions & 0 deletions src/agent_env/task_step/task_steps/user_sim_gate.py

Large diffs are not rendered by default.

61 changes: 53 additions & 8 deletions src/agent_env/task_step/usage.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,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",
Expand Down Expand Up @@ -87,14 +88,16 @@ class UsageEntry(CostFields):
@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. ``call_costs`` are the costs of calls core
made itself (``StepUsage.reply``), each costed when it was made; a role with them is costed from them alone."""

role: str
model: Optional[str] = None
endpoint_host: Optional[str] = None
attempt: Optional[int] = field(default_factory=ATTEMPT_EPOCH.get)
turns: list[Optional[Usage]] = field(default_factory=list)
unparsed: list[dict] = field(default_factory=list)
call_costs: list[Cost] = field(default_factory=list)
# Whose figure a turn's ``cost_usd`` is: an agent's own (the price map wins over it), or an endpoint's bill (it
# wins over the map).
reported_by: ReportedBy = ReportedBy.HARNESS
Expand Down Expand Up @@ -123,9 +126,14 @@ def entry(self, prices: PriceTable = PriceTable()) -> UsageEntry:
partial = (0 < len(counted) < len(self.turns) or bool(unreported)
or any(usage.provider_details.get("unreported") for usage in reported))
figures = [usage.cost_usd if usage is not None else None for usage in self.turns]
models = self._by_model(counted, prices) if any(usage.models for usage in counted) else None
cost = (_cost_of(_tokens(counted), figures, model=self.model, prices=prices, reported_by=self.reported_by)
if models is None else _summed([cost for _, cost in models], _total(reported, "cost_usd")))
models = (self._by_model(counted, prices)
if not self.call_costs and any(usage.models for usage in counted) else None)
if self.call_costs:
cost = _combined(self.call_costs)
elif models is None:
cost = _cost_of(_tokens(counted), figures, model=self.model, prices=prices, reported_by=self.reported_by)
else:
cost = _summed([cost for _, cost in models], _total(reported, "cost_usd"))
entry = UsageEntry(role=self.role, model=self.model, endpoint_host=self.endpoint_host, attempt=self.attempt,
turns=len(self.turns), **{name: _total(reported, name) for name in _COUNTERS},
input_includes_cache=_agreed(counted), **cost.fields(), partial=partial)
Expand Down Expand Up @@ -200,6 +208,26 @@ def _summed(costs: list[Cost], reported_usd: Optional[float]) -> Cost:
return Cost(sum(cost.usd for cost in costs), least.status, least.source, reported_usd, assumed=assumed)


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() -> Usage:
"""A turn or call whose usage never came back."""
return Usage(provider_details={"unreported": True})
Expand Down Expand Up @@ -244,6 +272,26 @@ def call(self, role: ModelRole, usage: Optional[Usage], *, model: Optional[str],
``cost_usd`` is, and the role keeps its first call's."""
self._add_call(role, usage, model, endpoint_host, reported_by)

def reply(self, role: ModelRole, reply: ModelReply) -> None:
"""One model call the step made itself as ``role`` through ``model_call`` (a user-sim gate's judge), written
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._role_for_call(role, reply.model, reply.endpoint_host, ReportedBy.HARNESS)
counts = Usage.from_model_response(reply.usage) if reply.usage else Usage()
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()

def _role_for_call(self, role: ModelRole, model: Optional[str], endpoint_host: Optional[str],
reported_by: ReportedBy) -> RoleUsage:
"""The role a call is counted under, started at its first call."""
if role not in self._roles:
self._context.record_model_endpoint(role.value, self._step_id, model, endpoint_host)
self._roles[role] = RoleUsage(role.value, model, endpoint_host, reported_by=reported_by)
return self._roles[role]

def cut_off(self, role: ModelRole) -> None:
"""A turn of ``role`` that was sent but never replied: cut off by a time limit, by a cancel, or by its agent no
longer answering (``AgentUnreachableError``, a ``TimeoutError``). Its calls are billed but their usage is
Expand All @@ -263,10 +311,7 @@ def cut_off_call(self, role: ModelRole, *, model: Optional[str], endpoint_host:

def _add_call(self, role: ModelRole, usage: Optional[Usage], model: Optional[str], endpoint_host: Optional[str],
reported_by: ReportedBy) -> None:
if role not in self._roles:
self._context.record_model_endpoint(role.value, self._step_id, model, endpoint_host)
self._roles[role] = RoleUsage(role.value, model, endpoint_host, reported_by=reported_by)
self._roles[role].add(usage)
self._role_for_call(role, model, endpoint_host, reported_by).add(usage)
self.entries()

def entries(self) -> Optional[list[UsageEntry]]:
Expand Down
3 changes: 3 additions & 0 deletions tst/unit/task_step/always_on_harness.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,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"
Expand Down Expand Up @@ -377,4 +378,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
11 changes: 11 additions & 0 deletions tst/unit/task_step/test_always_on_budget.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
214 changes: 214 additions & 0 deletions tst/unit/task_step/test_always_on_user_sim_gate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
"""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, pattern_judge # noqa: F401

pytestmark = pytest.mark.usefixtures("local_stores", "pattern_judge")

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, "judge_model": "judge", **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 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"


@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_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
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_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


@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, "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}])
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



@pytest.mark.asyncio
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")

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.*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")


class _OwnFormatPlugin:
"""A plugin whose user sim answers "REPLY: <text>" 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))
Loading
Loading