Skip to content
Merged
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
39 changes: 28 additions & 11 deletions src/agent_env/a2a_agent/conversation_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,9 @@ def create_conversation(
target="human_agent".

Raises `agent_env.store.DuplicateKeyError` if `conversation_id` already
exists — callers should treat that as "use the existing conversation."
exists and the store has the unique index `ensure_indexes` creates. A store
without that index inserts a second document with the same id, so a caller
that may re-run looks for the conversation first (`reopen`).
"""
now = datetime.now(timezone.utc)
doc = {
Expand Down Expand Up @@ -139,12 +141,15 @@ def add_a2a_task(
(never rewritten), so no entry is dropped.

Returns the post-update conversation doc, or None if `conversation_id`
doesn't exist.
doesn't exist or is no longer `active`. The status is read under the same
swap, so a close that lands first refuses the append rather than racing it.
"""
now = datetime.now(timezone.utc)
new_message = _message(role, parts, now, env_clock)

def _mutate(doc: dict) -> UpdateSpec:
def _mutate(doc: dict) -> Optional[UpdateSpec]:
if doc.get("status") != "active":
return None
idx = len(doc.get("messages", []))
new_a2a_task = {
"a2a_task_id": a2a_task_id,
Expand All @@ -171,8 +176,10 @@ def complete_a2a_task(
parts: list[dict],
role: str,
env_clock: Optional[list[dict]] = None,
state: TaskState = TaskState.completed,
) -> Optional[dict]:
"""Append a responder-side message and complete the oldest working a2a_task.
"""Append a responder-side message and end the oldest working a2a_task in `state`,
the terminal state the responder's own task reached.

Called when the responder replies. The responder's role depends on the
conversation direction:
Expand Down Expand Up @@ -226,7 +233,7 @@ def complete_a2a_task(
_REV, rev_precondition(existing, _REV)
)
if oldest_working_idx is not None:
spec.set[f"a2a_tasks.{oldest_working_idx}.state"] = TaskState.completed.value
spec.set[f"a2a_tasks.{oldest_working_idx}.state"] = TaskState(state).value
spec.set[f"a2a_tasks.{oldest_working_idx}.response_message_idx"] = idx
spec.set[f"a2a_tasks.{oldest_working_idx}.ended_at"] = now.isoformat()
filter_ = filter_.where(
Expand Down Expand Up @@ -304,15 +311,14 @@ def cancel_a2a_task(
)


def mark_closed(conversation_id: str) -> Optional[dict]:
"""Set `status=closed` and cancel any working a2a_tasks.
def _end_working_tasks(conversation_id: str, status: str) -> Optional[dict]:
"""Set `status`, clear `pending` and cancel any working a2a_tasks.

Reads the conversation, cancels working a2a_tasks in Python, and writes the
transformed array back under a `rev` compare-and-swap so a concurrently
appended a2a_task (e.g. a `start_a2a_task` push that lands between the read
and the write) is not clobbered by this whole-array write. On a lost swap we
re-read and re-transform; a task that landed mid-close is then canceled too,
which is correct for a terminal close.
re-read and re-transform; a task that landed mid-write is then canceled too.

Returns the post-update conversation doc, or None if not found.
"""
Expand All @@ -338,7 +344,7 @@ def mark_closed(conversation_id: str) -> Optional[dict]:
),
UpdateSpec(
set={
"status": "closed",
"status": status,
"pending": False,
"updated_at_utc": now,
"a2a_tasks": new_tasks,
Expand All @@ -349,10 +355,21 @@ def mark_closed(conversation_id: str) -> Optional[dict]:
if result is not None:
return result
raise RuntimeError(
f"mark_closed: rev CAS did not converge for conversation_id={conversation_id}"
f"set status {status}: rev CAS did not converge for conversation_id={conversation_id}"
)


def mark_closed(conversation_id: str) -> Optional[dict]:
"""Set `status=closed` and cancel any working a2a_tasks. Returns the post-update doc, or None if not found."""
return _end_working_tasks(conversation_id, "closed")


def reopen(conversation_id: str) -> Optional[dict]:
"""Set `status=active` for a re-run of the conversation's owner, canceling any working a2a_tasks an earlier
run left, so the next reply completes the re-run's own task. Returns the post-update doc, or None if not found."""
return _end_working_tasks(conversation_id, "active")


def list_pending(limit: int = 50) -> list[dict]:
"""Return active conversations awaiting a user reply, most-recently-updated first.

Expand Down
64 changes: 42 additions & 22 deletions src/agent_env/task_step/task_steps/prompt_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,10 @@ def _parse_structured_output(text: str) -> Optional[dict]:
return last


class _ConversationClosed(Exception):
"""The store refused the turn because someone closed the conversation, so the message is not sent."""


def _duplicates_prompt_text(parts: list[dict], prompt_text: Optional[str]) -> bool:
"""True when ``parts`` is exactly the single text part already persisted as
``PromptResponse.prompt_text`` — i.e. the first conversation turn of a
Expand Down Expand Up @@ -653,22 +657,6 @@ async def _converse(
conversation_id = f"{self.context_id}-{run_component}-{len(run_component)}"
else:
conversation_id = solver_context_id
try:
conversation_store.create_conversation(
conversation_id=conversation_id,
task_instance_id=context.instance_id or "",
source_agent_name=self.user_agent_name,
target_agent_name=self.agent_name,
)
except DuplicateKeyError:
# reuse a pre-existing conversation on retry/resume (store raises agent_env.store.DuplicateKeyError, not pymongo's)
logger.info(f"Reusing existing conversation {conversation_id} on re-run")
context.metadata.setdefault("a2a_conversations", {})[self.id] = conversation_id
logger.info(
f"Started multi-turn conversation {conversation_id} (max {self.max_conversation_turns} turns) "
f"between {self.user_agent_name} and {self.agent_name}"
)

current_user_parts = initial_parts
clock_envs = [d for d in context.deployed_envs if d.supports(EXT_CLOCK_URI, "state")]
# What comes due for the agent's role on these envs (notifications/v1) opens its next message.
Expand Down Expand Up @@ -715,6 +703,25 @@ async def _converse(
# 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

# A re-run under the same instance id (a retry) takes back the conversation its earlier run closed.
if conversation_store.reopen(conversation_id) is not None:
logger.info(f"Reusing existing conversation {conversation_id} on re-run")
else:
try:
conversation_store.create_conversation(
conversation_id=conversation_id,
task_instance_id=context.instance_id or "",
source_agent_name=self.user_agent_name,
target_agent_name=self.agent_name,
)
except DuplicateKeyError: # another run created it after our reopen found none
conversation_store.reopen(conversation_id)
context.metadata.setdefault("a2a_conversations", {})[self.id] = conversation_id
logger.info(
f"Started multi-turn conversation {conversation_id} (max {self.max_conversation_turns} turns) "
f"between {self.user_agent_name} and {self.agent_name}"
)

try:
for turn in range(self.max_conversation_turns):
# `target_a2a_task_id` is the client A2A message id sent to the target
Expand All @@ -726,14 +733,16 @@ async def _converse(
# The turn records the objects' own URLs, and only once the parts are ready to send, so an
# object the agent can't be sent leaves no turn waiting.
def record_turn() -> None:
sent_to_target.update(_file_uris(current_user_parts))
conversation_store.add_a2a_task(
recorded = conversation_store.add_a2a_task(
conversation_id=conversation_id,
parts=current_user_parts,
a2a_task_id=target_a2a_task_id,
role="user",
**sent_clock,
)
if recorded is None:
raise _ConversationClosed()
sent_to_target.update(_file_uris(current_user_parts))
# Turn 0 of a prompt-mode step re-sends exactly the text already
# persisted as PromptResponse.prompt_text; store a None placeholder
# instead of a second copy so the doc doesn't carry the prompt twice.
Expand All @@ -753,6 +762,13 @@ def record_turn() -> None:
poll_interval_seconds=self.poll_interval_seconds, before_send=record_turn,
on_sent=live_turn.follow if live_turn else None,
)
except _ConversationClosed:
if turn == 0:
raise RuntimeError(
f"conversation {conversation_id} was closed before the first turn; "
"nothing was sent to the agent") from None
logger.info(f"Conversation {conversation_id} was closed before turn {turn+1}; ending multi-turn")
break
except (TimeoutError, asyncio.CancelledError):
usage.cut_off(ModelRole.SOLVER)
raise
Expand All @@ -769,6 +785,7 @@ def record_turn() -> None:
conversation_id=conversation_id,
parts=agent_response_parts,
role="agent",
state=target_state,
**(await self._env_clock(clock_envs)),
)

Expand Down Expand Up @@ -857,6 +874,13 @@ def record_turn() -> None:
atif_copies.cancel()
raise
finally:
# Before any await, so a cancellation landing in this cleanup can't skip it.
try:
final_conv = conversation_store.get_conversation(conversation_id)
if final_conv and final_conv.get("status") == "active":
conversation_store.mark_closed(conversation_id)
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
except Exception:
logger.warning(f"Could not close conversation {conversation_id}", exc_info=True)
# On failure too, so a reader of the last turn knows no other follows.
if live_turns is not None:
await live_turns.end()
Expand All @@ -865,10 +889,6 @@ def record_turn() -> None:

await self._persist_env_trigger_state(context)

final_conv = conversation_store.get_conversation(conversation_id)
if final_conv and final_conv.get("status") == "active":
conversation_store.mark_closed(conversation_id)

if trig_ext and triggers_registered: # best-effort firing-log readback (provenance only; never fails the run)
try:
async with httpx.AsyncClient() as client:
Expand Down
Loading
Loading