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
64 changes: 53 additions & 11 deletions src/agent_comms/execution/antigravity_acp.py
Original file line number Diff line number Diff line change
Expand Up @@ -551,7 +551,37 @@ def resolve_agy_binary() -> str:
return "agy"


class AcpLivePrompt:
class AcpTurnPrompt(ABC):
"""The ``session/prompt`` a backend's next turn continues: a held live prompt or none."""

@abstractmethod
async def continue_with(
self,
process: AntigravityAcpProcess,
session_id: AcpSessionId,
blocks: Sequence[Mapping[str, object]],
) -> AcpLivePrompt: ...

@abstractmethod
def close(self) -> None: ...


class NoLivePrompt(AcpTurnPrompt):
"""No prompt outlived the previous turn; the next turn opens its own."""

async def continue_with(
self,
process: AntigravityAcpProcess,
session_id: AcpSessionId,
blocks: Sequence[Mapping[str, object]],
) -> AcpLivePrompt:
return await process.open_prompt(session_id, blocks)

def close(self) -> None:
pass


class AcpLivePrompt(AcpTurnPrompt):
"""One live ``session/prompt`` turn on ``agy acp`` supporting concurrent mid-turn steers."""

def __init__(
Expand All @@ -565,6 +595,9 @@ def __init__(
self._session_id = session_id
self._queue = queue
self._in_flight: set[Task[dict[str, JsonValue]]] = {initial_task}
# One read outlives each next_frames call: a turn that stops reading a held
# prompt never takes a frame with it.
self._reading: Task[AcpQueueItem] = asyncio.create_task(queue.get())
self._last_stop_reason: str = ""
self._finished = False

Expand All @@ -582,6 +615,17 @@ def steer(self, blocks: Sequence[Mapping[str, object]]) -> None:
)
self._in_flight.add(task)

async def continue_with(
self,
process: AntigravityAcpProcess,
session_id: AcpSessionId,
blocks: Sequence[Mapping[str, object]],
) -> AcpLivePrompt:
"""A prompt held open by agy past its reply takes the next turn's input as a steer."""
del process, session_id
self.steer(blocks)
return self

def _drain_queued_nowait(self) -> list[AcpPromptFrame]:
frames: list[AcpPromptFrame] = []
while not self._queue.empty():
Expand All @@ -600,24 +644,21 @@ async def next_frames(self) -> tuple[AcpPromptFrame, ...]:
result = AcpPromptResultWire.model_validate(await task)
if result.stop_reason:
self._last_stop_reason = result.stop_reason
if self._reading.done():
frames = [*self._reading.result().frames(), *self._drain_queued_nowait()]
self._reading = asyncio.create_task(self._queue.get())
return tuple(frames)
if not self._in_flight:
self._finished = True
self._reading.cancel()
queued = self._drain_queued_nowait()
queued.append(AcpResultFrame(self._last_stop_reason))
return tuple(queued)
if not self._queue.empty():
return tuple(self._drain_queued_nowait())
get_task: Task[AcpQueueItem] = asyncio.create_task(self._queue.get())
wait_set: set[Task[object]] = {*self._in_flight, get_task}
done, _ = await asyncio.wait(wait_set, return_when=asyncio.FIRST_COMPLETED)
if get_task in done:
return tuple(get_task.result().frames())
get_task.cancel()
with suppress(asyncio.CancelledError):
await get_task
await asyncio.wait({*self._in_flight, self._reading}, return_when=asyncio.FIRST_COMPLETED)

async def cancel_and_close(self) -> None:
self._finished = True
self._reading.cancel()
with suppress(AcpRpcError):
await self._process.cancel(self._session_id)
for task in list(self._in_flight):
Expand All @@ -632,6 +673,7 @@ async def cancel_and_close(self) -> None:

def close(self) -> None:
self._finished = True
self._reading.cancel()
self._process._session_queues.pop(self._session_id, None)


Expand Down
100 changes: 80 additions & 20 deletions src/agent_comms/execution/antigravity_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,10 @@

import asyncio
import uuid
from abc import abstractmethod
from collections.abc import AsyncIterator
from contextlib import suppress
from dataclasses import dataclass
from pathlib import Path
from typing import ClassVar, Self

Expand All @@ -29,12 +31,15 @@
)
from agent_comms.execution.agent_event import AgentEvent
from agent_comms.execution.antigravity_acp import (
AcpLivePrompt,
AcpRpcError,
AcpTurnPrompt,
AntigravityAcpPool,
AntigravityAcpProcess,
AntigravityConversationId,
AntigravitySessionFiles,
AntigravitySessionStorage,
NoLivePrompt,
)
from agent_comms.execution.antigravity_acp_events import (
ANTIGRAVITY_ACP_EVENT_KINDS,
Expand All @@ -49,7 +54,7 @@
AntigravitySessionDeclaration,
)
from agent_comms.execution.backend_query import TurnInputContent
from agent_comms.execution.process_identity import ProcessState
from agent_comms.execution.process_identity import ProcessIdentity, ProcessState
from agent_comms.execution.launch_runtime import LaunchRuntime
from agent_comms.execution.runtime_observations import (
AgentInfo,
Expand All @@ -61,6 +66,7 @@
from agent_comms.execution.turn_phase import (
NativePhaseChanged,
SettlingStatsPhase,
SilenceEndings,
TurnPhase,
)
from agent_comms.cli_bridges.history import AntigravityAcpSession
Expand Down Expand Up @@ -118,6 +124,61 @@ def _selected_model_name(*, provider: object = "", model_id: object = "") -> str
return str(model_id)


class AcpTurnEnding(SilenceEndings["AcpTurnEnding"]):
"""How one ACP turn leaves its live prompt and which terminal events it reports."""

@classmethod
def stalled(cls, message: str) -> AcpTurnEnding:
return StalledAcpTurn(message)

@classmethod
def held(cls) -> AcpTurnEnding:
return HeldAcpTurn()

async def release(self, backend: AntigravityAcpBackend, live: AcpLivePrompt) -> None:
live.close()

@abstractmethod
def events(
self, state: AcpTurnStreamState, identity: ProcessIdentity
) -> tuple[AgentEvent, ...]: ...


class SettledAcpTurn(AcpTurnEnding):
def events(
self, state: AcpTurnStreamState, identity: ProcessIdentity
) -> tuple[AgentEvent, ...]:
return (
NativePhaseChanged(SettlingStatsPhase(), identity),
events.StreamSettled(),
events.Done(text=state.full_text, ok=True),
)


class HeldAcpTurn(SettledAcpTurn):
"""The reply is complete while agy holds the prompt open for a background task:
the turn settles and the backend's next turn continues the prompt."""

async def release(self, backend: AntigravityAcpBackend, live: AcpLivePrompt) -> None:
backend._held = live


@dataclass(frozen=True)
class StalledAcpTurn(AcpTurnEnding):
message: str

async def release(self, backend: AntigravityAcpBackend, live: AcpLivePrompt) -> None:
await live.cancel_and_close()

def events(
self, state: AcpTurnStreamState, identity: ProcessIdentity
) -> tuple[AgentEvent, ...]:
return (
events.Error(text=self.message),
events.Done(text=self.message, ok=False, failure=ModelStalled(self.message)),
)


class AntigravityAcpBackend(
ServedAgentBackend, AntigravityAcpBackendDeclaration
):
Expand All @@ -126,7 +187,7 @@ class AntigravityAcpBackend(
location_type: ClassVar[type[RuntimeLocation]] = AntigravitySession
event_kinds: ClassVar[frozenset[str]] = ANTIGRAVITY_ACP_EVENT_KINDS
REPLY_QUIET_SECONDS: ClassVar[float] = 15.0
POST_REPLY_STALL_SECONDS: ClassVar[float] = 180.0
POST_REPLY_HOLD_SECONDS: ClassVar[float] = 180.0
MODEL_STALL_SECONDS: ClassVar[float] = 360.0

@classmethod
Expand Down Expand Up @@ -168,6 +229,7 @@ def turn_transcript_sink(
def __init__(self, process: AntigravityAcpProcess) -> None:
self._process = process
self._acp_session: AcpSessionSelection = NoAcpSessionId()
self._held: AcpTurnPrompt = NoLivePrompt()
self._applied_model: str = ""
self._applied_thinking: str = ""
self._lock = asyncio.Lock()
Expand Down Expand Up @@ -221,6 +283,8 @@ async def _ensure_acp_session(
bound_sessions = self._bound_sessions()
if bound_sessions and self._process.alive:
return bound_sessions[0], False, storage.db_path
# A prompt held on a session this process no longer serves cannot continue.
self._held = NoLivePrompt()
if storage.exists:
descriptor = await self._process.resume_session(
AcpSessionId(str(storage.conversation_id)), worktree
Expand Down Expand Up @@ -292,7 +356,11 @@ async def run_turn(
)
last_phase: TurnPhase = state.phase
yield NativePhaseChanged(last_phase, self._process._state.require_identity())
live = await self._process.open_prompt(session_id, content.acp_prompt_blocks())
live = await self._held.continue_with(
self._process, session_id, content.acp_prompt_blocks()
)
self._held = NoLivePrompt()
ending: AcpTurnEnding = SettledAcpTurn()
inbox_task: asyncio.Task[TurnInboxItem] = asyncio.create_task(delivery.inbox.get())
frames_task: asyncio.Task[tuple[AcpPromptFrame, ...]] = asyncio.create_task(
live.next_frames()
Expand All @@ -307,7 +375,7 @@ async def run_turn(
deadlines.append(max(0.0, self.REPLY_QUIET_SECONDS - idle))
stall_budget = state.phase.silence_budget(
model_wait=self.MODEL_STALL_SECONDS,
post_reply_wait=self.POST_REPLY_STALL_SECONDS,
post_reply_wait=self.POST_REPLY_HOLD_SECONDS,
)
if stall_budget is not None:
deadlines.append(max(0.0, stall_budget - idle))
Expand All @@ -328,18 +396,11 @@ async def run_turn(
)
stall_budget = state.phase.silence_budget(
model_wait=self.MODEL_STALL_SECONDS,
post_reply_wait=self.POST_REPLY_STALL_SECONDS,
post_reply_wait=self.POST_REPLY_HOLD_SECONDS,
)
if stall_budget is not None and idle >= stall_budget:
stall_message = state.phase.stalled().stall_message(stall_budget)
await live.cancel_and_close()
yield events.Error(text=stall_message)
yield events.Done(
text=stall_message,
ok=False,
failure=ModelStalled(stall_message),
)
return
ending = state.phase.silence_ending(stall_budget, AcpTurnEnding)
break
continue
if inbox_task in done:
last_activity = loop.time()
Expand Down Expand Up @@ -382,12 +443,9 @@ async def run_turn(
pending_task.cancel()
with suppress(asyncio.CancelledError):
await pending_task
live.close()
yield NativePhaseChanged(
SettlingStatsPhase(), self._process._state.require_identity()
)
yield events.StreamSettled()
yield events.Done(text=state.full_text, ok=True)
await ending.release(self, live)
for event in ending.events(state, self._process._state.require_identity()):
yield event
except (AcpRpcError, ConnectionError, TimeoutError) as error:
message = str(error)
yield events.Error(text=message)
Expand All @@ -403,6 +461,8 @@ async def close_idle(self) -> None:
async with self._lock:
bound_sessions = self._bound_sessions()
self._acp_session = NoAcpSessionId()
self._held.close()
self._held = NoLivePrompt()
self._applied_model = ""
self._applied_thinking = ""
for active in bound_sessions:
Expand Down
32 changes: 25 additions & 7 deletions src/agent_comms/execution/turn_phase.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

from abc import ABC, abstractmethod
from dataclasses import dataclass, field, replace
from typing import TYPE_CHECKING, ClassVar, Self

Expand Down Expand Up @@ -29,6 +30,18 @@ def model_progress(self) -> TurnPhase:
return self


class SilenceEndings[Ending](ABC):
"""The endings a backend gives a stream silent past its phase's budget."""

@classmethod
@abstractmethod
def stalled(cls, message: str) -> Ending: ...

@classmethod
@abstractmethod
def held(cls) -> Ending: ...


class NoModelWait:
"""Native-owned excursions have no Core model-progress deadline."""

Expand Down Expand Up @@ -162,6 +175,10 @@ def stalled(self) -> TurnPhase:
def stall_message(self, budget: float) -> str:
return f"Model produced no RPC progress for {budget:g} seconds."

def silence_ending[Ending](self, budget: float, endings: type[SilenceEndings[Ending]]) -> Ending:
"""How a stream silent past this phase's budget ends: a stall cancels the turn."""
return endings.stalled(self.stalled().stall_message(budget))

def phase_effects(self, agents: AgentActivity, lease: TurnLeaseFence) -> None:
agents.publish_phase()

Expand Down Expand Up @@ -254,10 +271,13 @@ def quiet_phase(self, *, background_tasks: tuple[str, ...]) -> TurnPhase:

@dataclass(frozen=True)
class BackgroundTaskWaitPhase(StallExempt, Excursion):
"""Reply text stopped streaming, but a background task still holds the ACP turn open."""
"""Reply text stopped streaming, but a background task still holds the ACP turn open.

agy holds ``session/prompt`` open while the task runs and wakes the model when it
ends, so silence here is the model waiting, never a stall: past the budget the turn
ends with its reply and the next turn continues the held prompt."""

tasks: tuple[str, ...] = ()
stall_reason = "background_task_no_progress"
activity_state = ActivityState.WORKING
label = "Waiting on background task"

Expand All @@ -273,11 +293,9 @@ def silence_budget(self, *, model_wait: float, post_reply_wait: float) -> float
del model_wait
return post_reply_wait

def stall_message(self, budget: float) -> str:
return (
f"Antigravity ACP turn produced no progress for {budget:g} seconds "
"while waiting on a background task."
)
def silence_ending[Ending](self, budget: float, endings: type[SilenceEndings[Ending]]) -> Ending:
del budget
return endings.held()


class SettlingStatsPhase(NonFollowupTurnPhase):
Expand Down
Loading
Loading