From 961a0ccabc9531dbaafb9826830416baeccc4e4e Mon Sep 17 00:00:00 2001 From: kaihackney-scale Date: Fri, 20 Nov 2026 16:50:41 -0500 Subject: [PATCH 1/2] feat(post_turn_hooks): a hook can read the agent's per-turn trajectories A post-turn hook could read the envs and the agent's reply, but not what the agent did to get there: the tool calls and their results. prompt_agent already stores each turn's native trajectory before the hooks run. Turn now carries trajectory_urls, one per turn so far (None for a turn without one, empty when the agent's card offers none), and read_trajectory(n) returns turn n's as text. A hook can then check a milestone against the work itself, as a trajectory-reading verifier does, without its own copy of the env state. Co-Authored-By: Claude Opus 5.5 --- .../task_step/task_steps/post_turn_hooks.py | 25 +++++++-- .../task_step/task_steps/prompt_agent.py | 1 + .../test_prompt_agent_post_turn_hooks.py | 55 +++++++++++++++++++ 3 files changed, 77 insertions(+), 4 deletions(-) diff --git a/src/agent_env/task_step/task_steps/post_turn_hooks.py b/src/agent_env/task_step/task_steps/post_turn_hooks.py index 0afb54b71..3c471aa61 100644 --- a/src/agent_env/task_step/task_steps/post_turn_hooks.py +++ b/src/agent_env/task_step/task_steps/post_turn_hooks.py @@ -10,7 +10,7 @@ import sys import tempfile import uuid -from collections.abc import Awaitable, Callable, Mapping +from collections.abc import Awaitable, Callable, Mapping, Sequence from dataclasses import dataclass from types import MappingProxyType from typing import Any, Optional @@ -187,8 +187,12 @@ class Turn: """What a hook is handed after an agent turn; ``last`` after the final one, when a returned message is ignored.""" def __init__(self, *, context: TaskStepContext, step_id: str, hook: PostTurnHook, answer: _Answer, number: int, - last: bool, agent_reply: str, agent_parts: list[dict]) -> None: + last: bool, agent_reply: str, agent_parts: list[dict], + trajectory_urls: Sequence[Optional[str]] = ()) -> None: self.number = number + # The agent's native trajectory of each turn so far, oldest first: None for a turn whose trajectory the + # agent returned none of or couldn't be fetched; empty when the agent's card offers no trajectories. + self.trajectory_urls: tuple[Optional[str], ...] = tuple(trajectory_urls) self.last = last self.agent_reply = agent_reply self.agent_parts = copy.deepcopy(agent_parts) @@ -204,6 +208,18 @@ def metadata(self) -> Mapping[str, Any]: """A read-only copy of the run's metadata, its secret keys stripped.""" return MappingProxyType(_strip_redacted_keys(self._context.metadata)) + async def read_trajectory(self, number: int) -> Optional[str]: + """Turn ``number``'s trajectory (1 is the first turn) as the agent stored it, as text; None when that turn + has none. Raises IndexError for a turn that hasn't happened.""" + if not 1 <= number <= len(self.trajectory_urls): + raise IndexError(f"turn {number}: the conversation has {len(self.trajectory_urls)} turn trajectories") + url = self.trajectory_urls[number - 1] + if url is None: + return None + from agent_env.config import get_config + data = await asyncio.to_thread(lambda: get_config().get_object_store_at(url).get(url)) + return data.decode("utf-8", errors="replace") + async def ask_user(self) -> Answer: """Today's user side: agent triggers, then a human or the LLM user sim, which sees only replies sent here.""" return await self._answer.ask_user() @@ -264,12 +280,13 @@ def _parts(message: Any, hook: PostTurnHook) -> list[dict]: async def run_post_turn_hooks(hooks: PostTurnHooks, *, context: TaskStepContext, step_id: str, number: int, last: bool, agent_reply: str, agent_parts: list[dict], ask_user: Callable[[], Awaitable[Answer]], - user_triggers: Callable[[], Awaitable[Optional[Answer]]]) -> Optional[Answer]: + user_triggers: Callable[[], Awaitable[Optional[Answer]]], + trajectory_urls: Sequence[Optional[str]] = ()) -> Optional[Answer]: """Run the hooks in order; the first to return a message or an end decides, and one that asked returns that.""" answer = _Answer(ask_user, user_triggers) for hook in hooks.hooks: turn = Turn(context=context, step_id=step_id, hook=hook, answer=answer, number=number, last=last, - agent_reply=agent_reply, agent_parts=agent_parts) + agent_reply=agent_reply, agent_parts=agent_parts, trajectory_urls=trajectory_urls) returned = await hook.post_turn(turn, copy.deepcopy(hook.params)) if answer.value is not None: if returned != answer.value: 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 3dde0d933..aa0b8be9a 100644 --- a/src/agent_env/task_step/task_steps/prompt_agent.py +++ b/src/agent_env/task_step/task_steps/prompt_agent.py @@ -764,6 +764,7 @@ def record_turn() -> None: agent_parts=agent_response_parts, ask_user=functools.partial(user_side.ask, turn + 1, reply, agent_response_parts), user_triggers=functools.partial(user_side.triggers, turn + 1, reply), + trajectory_urls=per_turn_trajectory_urls, ) if answer is None and not last: answer = await user_side.ask(turn + 1, final_terminal.response_text, agent_response_parts) 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 f54d8a200..3d3f8accf 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 @@ -571,3 +571,58 @@ async def test_with_no_armed_env_clock_stored_messages_carry_none(monkeypatch): poll_interval_seconds=0).execute(ctx) assert all("env_clock" not in m for m in _stored(ctx, peers)["messages"]) + + +@pytest.mark.asyncio +async def test_a_hook_sees_each_turns_trajectory_so_far_and_can_read_it(monkeypatch): + from agent_env.a2a_agent import A2AAgent + from agent_env.config import get_config + from agent_env.task_step.task_steps import prompt_agent as pa + + EnvPeers(monkeypatch, {AGENT: [text("one"), text("two"), text("three")]}) + ctx = _context() + ctx.deployed_agents[0].a2a_card = {"capabilities": {"extensions": [{"uri": A2AAgent.EXT_TRAJECTORY, "params": {}}]}} + stored = {"task-1": b'[{"turn": 1}]', "task-3": b'[{"turn": 3}]'} # turn 2's agent returned none + + async def fetch(url, ext, task_id, prefix, name, *, sandbox_type, headers, card=None): + if task_id not in stored: + return pa.StoredTrajectory() + return pa.StoredTrajectory(get_config().get_object_store().put(f"traj/{task_id}.json", stored[task_id])) + + monkeypatch.setattr(pa, "fetch_native_trajectory", fetch) + hook = _hook("reads", """ + async def post_turn(turn, params): + urls = turn.trajectory_urls + texts = [await turn.read_trajectory(n) for n in range(1, len(urls) + 1)] + try: + await turn.read_trajectory(len(urls) + 1) + ahead = "read" + except IndexError: + ahead = "refused" + turn.record({"count": len(urls), "missing": [n for n, u in enumerate(urls, 1) if u is None], + "texts": texts, "ahead": ahead}) + return {"message": f"wake {turn.number}"} + """) + + await _step(hook, turns=3).execute(ctx) + + assert [(e["count"], e["missing"], e["texts"], e["ahead"]) for e in _recorded(ctx)] == [ + (1, [], ['[{"turn": 1}]'], "refused"), + (2, [2], ['[{"turn": 1}]', None], "refused"), + (3, [2], ['[{"turn": 1}]', None, '[{"turn": 3}]'], "refused"), + ] + + +@pytest.mark.asyncio +async def test_an_agent_that_offers_no_trajectories_hands_a_hook_none(monkeypatch): + EnvPeers(monkeypatch, {AGENT: [text("one")]}) + ctx = _context() + hook = _hook("none", """ + async def post_turn(turn, params): + turn.record({"urls": list(turn.trajectory_urls)}) + return None + """) + + await _step(hook, turns=1).execute(ctx) + + assert [e["urls"] for e in _recorded(ctx)] == [[]] From 2832dbe500f26e59c7cfbbe04fa6703c55c9a31a Mon Sep 17 00:00:00 2001 From: kaihackney-scale Date: Fri, 20 Nov 2026 17:34:19 -0500 Subject: [PATCH 2/2] fix(post_turn_hooks): read_trajectory returns None for an agent that offers no trajectories With no trajectories, trajectory_urls is empty, so reading a turn that happened raised IndexError instead of returning None. The turn number is now checked against the conversation's turn, and a turn with no entry is None. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/task_step/task_steps/post_turn_hooks.py | 9 +++++---- .../task_step/test_prompt_agent_post_turn_hooks.py | 11 +++++++++-- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/src/agent_env/task_step/task_steps/post_turn_hooks.py b/src/agent_env/task_step/task_steps/post_turn_hooks.py index 3c471aa61..61abf1773 100644 --- a/src/agent_env/task_step/task_steps/post_turn_hooks.py +++ b/src/agent_env/task_step/task_steps/post_turn_hooks.py @@ -210,10 +210,11 @@ def metadata(self) -> Mapping[str, Any]: async def read_trajectory(self, number: int) -> Optional[str]: """Turn ``number``'s trajectory (1 is the first turn) as the agent stored it, as text; None when that turn - has none. Raises IndexError for a turn that hasn't happened.""" - if not 1 <= number <= len(self.trajectory_urls): - raise IndexError(f"turn {number}: the conversation has {len(self.trajectory_urls)} turn trajectories") - url = self.trajectory_urls[number - 1] + has none, including every turn of an agent whose card offers no trajectories. Raises IndexError for a turn + that hasn't happened.""" + if not 1 <= number <= self.number: + raise IndexError(f"turn {number}: the conversation is at turn {self.number}") + url = self.trajectory_urls[number - 1] if number <= len(self.trajectory_urls) else None if url is None: return None from agent_env.config import get_config 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 3d3f8accf..b171619c3 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 @@ -619,10 +619,17 @@ async def test_an_agent_that_offers_no_trajectories_hands_a_hook_none(monkeypatc ctx = _context() hook = _hook("none", """ async def post_turn(turn, params): - turn.record({"urls": list(turn.trajectory_urls)}) + try: + await turn.read_trajectory(turn.number + 1) + ahead = "read" + except IndexError: + ahead = "refused" + turn.record({"urls": list(turn.trajectory_urls), "this_turn": await turn.read_trajectory(turn.number), + "ahead": ahead}) return None """) await _step(hook, turns=1).execute(ctx) - assert [e["urls"] for e in _recorded(ctx)] == [[]] + # A turn that happened has no trajectory (None), not an error; one that hasn't is still refused. + assert [(e["urls"], e["this_turn"], e["ahead"]) for e in _recorded(ctx)] == [([], None, "refused")]