Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 22 additions & 4 deletions src/agent_env/task_step/task_steps/post_turn_hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -195,8 +195,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)
Expand All @@ -212,6 +216,19 @@ 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, 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
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, note: Optional[str] = None) -> Answer:
"""Today's user side: agent triggers, then a human or the LLM user sim, which sees only replies sent here.

Expand Down Expand Up @@ -281,12 +298,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:
Expand Down
1 change: 1 addition & 0 deletions src/agent_env/task_step/task_steps/prompt_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -765,6 +765,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)
Expand Down
60 changes: 60 additions & 0 deletions tst/unit/task_step/test_prompt_agent_post_turn_hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -618,6 +618,66 @@ async def test_with_no_armed_env_clock_stored_messages_carry_none(monkeypatch):
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):
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)

# 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")]

@pytest.mark.asyncio
async def test_a_note_passed_after_the_user_side_was_asked_raises_instead_of_being_dropped():
Expand Down
Loading