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
3 changes: 2 additions & 1 deletion src/toad/acp/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
from toad.core import events as core_events
from toad.client.platform import host
from toad.core.events import UpdateStatusLine
from toad.core.link_context_changed import CoreEventStream


@rich.repr.auto
Expand All @@ -53,7 +54,7 @@ def __init__(
session_id: AcpSessionId | NoAcpSessionId,
session_pk: int | None = None,
*,
app_events: core_events.CoreEventStream,
app_events: CoreEventStream,
transcripts: CoordinationTranscriptReader,
) -> None:
"""
Expand Down
33 changes: 2 additions & 31 deletions src/toad/acp/agent_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

import asyncio
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from functools import partial
from typing import TYPE_CHECKING

Expand All @@ -20,14 +19,12 @@
)
from agent_comms.acp_extension import InputFailedUpdate
from agent_comms.execution.acp_failure import ACPFailure, RequestFailure
from agent_comms.nominal.field_codec import AcpSessionId, FieldCodec, NoAcpSessionId
from agent_comms.registry.thread_identity import ThreadIncarnation
from agent_comms.transcript.transcripts import TranscriptReadIdentity
from agent_comms.nominal.field_codec import NoAcpSessionId

from toad.acp.client_session import ClientSessionRequest, QueueSessionRequest
from toad.acp.prompt import build as build_prompt
from toad.acp.queue_attachment import QueueActionRefused
from toad.acp.session_output import SessionOutput
from toad.acp.session_binding import SessionBinding
from toad.acp.status import StopReason
from toad.acp.terminal_owner import OperationalTerminalOwner
from toad.client.transcript_reader import CoordinationTranscriptReader
Expand All @@ -53,32 +50,6 @@
from toad.acp.agent import Agent


class SourceIdentity:
def matches_source(self, root: str, thread: ThreadIncarnation) -> bool:
return False


@dataclass(frozen=True)
class SessionBinding:
"""Actual ACP binding identity, preserved only until session replacement."""

session_id: AcpSessionId | NoAcpSessionId
output: SessionOutput = field(default_factory=SessionOutput, compare=False)

@property
def bound(self) -> bool:
return self.session_id.bound

def accepts_notification(self, session_id: AcpSessionId):
return self.session_id == session_id

def accepts_snapshot(
self, identity: TranscriptReadIdentity, owner: SourceIdentity
) -> bool:
return (self.accepts_notification(FieldCodec.decode(AcpSessionId, identity.requested_name))
and owner.matches_source(identity.root, identity.thread.incarnation))


class TaskRunner(ABC):
@abstractmethod
async def run[Result](self, task: RenderTask[Result]) -> Result: ...
Expand Down
9 changes: 3 additions & 6 deletions src/toad/acp/agent_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
UnsupportedResumeAgentFail,
)
from toad.client.db import DB, SessionMeta
from toad.core.link_context_changed import CoreEventStream

PROTOCOL_VERSION = 1

Expand Down Expand Up @@ -136,16 +137,12 @@ class RefusedSessionDisposition(UnheldSessionDisposition, FailedSessionDispositi
"""The agent process answered the handshake with an error; it holds no session."""


class LoginNotReady(ValueError):
"""A terminal login finished, but the session it restarted did not become ready."""


class AgentSession:
"""Own readiness and durable session effects; binding identity stays on the controller."""

reconnect_timeout_seconds = 30

def __init__(self, agent, pk, app_events: core_events.CoreEventStream) -> None:
def __init__(self, agent, pk, app_events: CoreEventStream) -> None:
self.agent = agent
# The app's stream: its thread rows show this session's state, attached to a view or not.
self.app_events = app_events
Expand Down Expand Up @@ -365,7 +362,7 @@ async def reconnect_after_login(self) -> None:
"""Only a session that is ready after its restart counts as a finished login."""
await self.reconnect()
if not self.ready:
raise LoginNotReady(self.disposition.refusal_notice)
raise ValueError(self.disposition.refusal_notice)

async def authenticate(self, method_id: str) -> None:
authority = ClientSessionRequest(self.agent, self.agent.session_id)
Expand Down
2 changes: 1 addition & 1 deletion src/toad/acp/client_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@
from agent_comms.acp_extension import CoordinationChangedUpdate

from toad.acp.queue_attachment import QueueActionRefused
from toad.acp.session_binding import SessionBinding
from toad.acp.status import StopReason, UnreportedStopReason

if TYPE_CHECKING:
from toad.acp.agent import Agent
from toad.acp.agent_controller import SessionBinding
from toad.acp.agent_session import SessionDisposition
from acp.exceptions import RequestError
from agent_comms.nominal.field_codec import AcpSessionId, FieldCodec, NoAcpSessionId
Expand Down
3 changes: 2 additions & 1 deletion src/toad/acp/session_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,11 @@
from agent_comms.ui_model.observation import ReadOwnerOperation
from pydantic import JsonValue

from toad.acp.agent_controller import AgentController, SourceIdentity
from toad.acp.agent_controller import AgentController
from toad.acp.client_session import ClientSessionRequest, OwnerRequest
from toad.acp.comms_updates import PendingThreadRead
from toad.acp.goal_control import ClientGoalControls
from toad.acp.session_binding import SourceIdentity
from toad.agent import AgentBase
from toad.core import events as core_events

Expand Down
34 changes: 34 additions & 0 deletions src/toad/acp/session_binding.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from __future__ import annotations

from dataclasses import dataclass, field

from agent_comms.nominal.field_codec import AcpSessionId, FieldCodec, NoAcpSessionId
from agent_comms.registry.thread_identity import ThreadIncarnation
from agent_comms.transcript.transcripts import TranscriptReadIdentity
from toad.acp.session_output import SessionOutput


class SourceIdentity:
def matches_source(self, root: str, thread: ThreadIncarnation) -> bool:
return False


@dataclass(frozen=True)
class SessionBinding:
"""Actual ACP binding identity, preserved only until session replacement."""

session_id: AcpSessionId | NoAcpSessionId
output: SessionOutput = field(default_factory=SessionOutput, compare=False)

@property
def bound(self) -> bool:
return self.session_id.bound

def accepts_notification(self, session_id: AcpSessionId):
return self.session_id == session_id

def accepts_snapshot(
self, identity: TranscriptReadIdentity, owner: SourceIdentity
) -> bool:
return (self.accepts_notification(FieldCodec.decode(AcpSessionId, identity.requested_name))
and owner.matches_source(identity.root, identity.thread.incarnation))
3 changes: 2 additions & 1 deletion src/toad/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
from toad.agent_presentation import LocalAgentPresentation
from toad.client.db import DB
from toad.conversation_turn import NoTurn, TurnOwner
from toad.core.events import CoreEventStream, SessionAgentAttached
from toad.core.events import SessionAgentAttached
from toad.core.link_context_changed import CoreEventStream
from toad.session_observation import SessionObservation
from toad.submission_queue import QueueSource
from toad.surface_binding import SurfaceBinding
Expand Down
3 changes: 1 addition & 2 deletions src/toad/agent_binding.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,12 @@
from toad.acp.agent_controller import AgentController
from toad.acp.agent_session import SessionDisposition, UnopenedSessionDisposition
from toad.client.submission import SubmissionStart
from toad.core.link_context_changed import CoreEventStream, Publication
from toad.goal_controls import GoalSource
from toad.agent_presentation import AgentPresentation, LocalAgentPresentation
from toad.core.events import CoreEventStream
from toad.client.input_decision import InputAccepted, InputDecision, NoLiveAgent
from toad.commit_claims import CommitSource
from toad.conversation_turn import TurnOwner
from toad.core.events import Publication
from toad.acp.comms_updates import ThreadRead
from agent_comms.nominal.field_codec import AcpSessionId

Expand Down
2 changes: 1 addition & 1 deletion src/toad/agent_surface.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
from toad.acp.terminal_owner import OperationalTerminalOwner
from toad.ansi import TerminalState
from toad.answer import Answer
from toad.core.events import CoreEventStream
from toad.core.link_context_changed import CoreEventStream
from toad.core_event_carrier import CoreEventMessage
from toad.shell_output import ShellOutput
from toad.terminal_execution import TerminalExecution
Expand Down
11 changes: 6 additions & 5 deletions src/toad/agent_turn_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from metaclass_registry.mro_dispatch import MroDispatch, handles

from toad.core import events as core_events
from toad.core.link_context_changed import Publication


class AgentTurnEvents(MroDispatch):
Expand All @@ -33,7 +34,7 @@ def update_slash_commands(self) -> object:
"""Offer the agent's current commands in the composer."""

@handles(core_events.Update)
async def on_acp_agent_message(self, event: core_events.Update, message: core_events.Publication) -> None:
async def on_acp_agent_message(self, event: core_events.Update, message: Publication) -> None:
self.consumed(message)
if not self.agent_binding.matches_agent(message.publisher):
return
Expand All @@ -42,22 +43,22 @@ async def on_acp_agent_message(self, event: core_events.Update, message: core_ev
await self.output.append(event.stream, event.text)

@handles(core_events.Thinking)
async def on_acp_agent_thinking(self, event: core_events.Thinking, message: core_events.Publication) -> None:
async def on_acp_agent_thinking(self, event: core_events.Thinking, message: Publication) -> None:
self.turns.describe("Thinking…")
await self.output.append(event.stream, event.text)

@handles(core_events.RequestPermission)
async def on_acp_request_permission(self, event: core_events.RequestPermission, message: core_events.Publication) -> None:
async def on_acp_request_permission(self, event: core_events.RequestPermission, message: Publication) -> None:
for request in message.publisher.permissions.pending:
self.request_permissions(request)
self.output.boundary()

@handles(core_events.ToolCall)
async def on_acp_tool_call_update(self, event: core_events.ToolCall, message: core_events.Publication) -> None:
async def on_acp_tool_call_update(self, event: core_events.ToolCall, message: Publication) -> None:
await message.publisher.controller.surface.present_tool(message, self)

@handles(core_events.AvailableCommandsUpdate)
async def on_acp_available_commands_update(
self, event: core_events.AvailableCommandsUpdate, message: core_events.Publication
self, event: core_events.AvailableCommandsUpdate, message: Publication
) -> None:
self.update_slash_commands()
6 changes: 1 addition & 5 deletions src/toad/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,10 +89,6 @@ class ToadLoadingIndicator(TransparentBackground, LoadingIndicator):



class ApplicationNotRunningError(RuntimeError):
"""The application has no event loop to accept cross-thread work."""


class ToadApp(DeclaredWidgetActions, WorkspaceSessionShutdown, WorkspaceHost, ClientApplication, CorePrewarm, Transfers, HostsNeovim, actions=(ApplicationAction,), inherit_bindings=False):
"""The top level app."""

Expand Down Expand Up @@ -456,7 +452,7 @@ def selected_mode(self):
def running_loop(self) -> asyncio.AbstractEventLoop:
loop = self._loop
if loop is None:
raise ApplicationNotRunningError("App is not running")
raise RuntimeError("App is not running")
return loop

def schedule_from_thread(self, callback: Callable[[], object]) -> None:
Expand Down
6 changes: 1 addition & 5 deletions src/toad/application_lifetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,6 @@ async def deliver(self, event_name: str, properties: dict[str, object]) -> None:
return


class ApplicationStartupObserverAlreadyInstalled(RuntimeError):
"""Only one external observer may await the next application startup."""


class ApplicationStartupHook:
"""One-shot startup observation state owned by the application lifetime."""

Expand All @@ -110,7 +106,7 @@ class PendingApplicationStartupHook(ApplicationStartupHook):
observer: Callable[[ApplicationLifetime], None]

def install(self, observer: Callable[[ApplicationLifetime], None]) -> ApplicationStartupHook:
raise ApplicationStartupObserverAlreadyInstalled(
raise RuntimeError(
"An application startup observer is already installed")

def notify(self, lifetime: ApplicationLifetime) -> ApplicationStartupHook:
Expand Down
4 changes: 2 additions & 2 deletions src/toad/client/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@

from toad.client.pending import BusConnecting, awaited
from toad.application_lifetime import ApplicationLifetime, ApplicationStart
from toad.core.link_context_changed import CoreEventStream
from toad.heap import HEAP
from toad.client import bus_connect
from toad.client.bus_selection import (
Expand All @@ -46,7 +47,6 @@
from toad.client.tab_order import TabOrder
from toad.client.view_settings import ApplicationSettings
from toad.constants import WELCOME
from toad.core import events as core_events
from toad.core import session_requests
from toad.launch_binding import AgentBinding
from toad.launch_opening import LaunchOpening, NoLaunchOpening
Expand Down Expand Up @@ -262,7 +262,7 @@ def initialize_client(
constructor runs before a terminal captures stderr, which spawn bookkeeping needs."""
self.preparation.renderer.start()
self.render_processes = self._make_render_processes()
self.events = core_events.CoreEventStream(self)
self.events = CoreEventStream(self)
self.navigation_reader = NavigationReader()
self.agent_binding = agent_binding
self.application = self.lifetime_kind(self, agent_session_id, opening)
Expand Down
43 changes: 43 additions & 0 deletions src/toad/client/block_claim.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
from __future__ import annotations

from typing import TYPE_CHECKING

from metaclass_registry.mro_dispatch import handles
from toad.commit_claims import (
CommitBarrierClaim,
CommitClaim,
CommitParticipant,
RetainedBlockClaim,
)
from toad.core.projection import MroProjection

if TYPE_CHECKING:
from textual.widget import Widget


class CommitBarrier:
"""A local interactive session whose ordering cannot be replaced by a snapshot."""


class BlockClaims(MroProjection[CommitClaim]):
"""Every block a conversation's contents hold has one commit claim; this is where it is read."""

# object, not Widget: a history's MRO reaches Widget before its CommitParticipant base.
@handles(object)
def retained(self, widget: Widget) -> CommitClaim:
return RetainedBlockClaim()

@handles(CommitParticipant)
def participant(self, widget: CommitParticipant) -> CommitClaim:
return widget.commit_claim

@handles(CommitBarrier)
def barrier(self, widget: CommitBarrier) -> CommitClaim:
return CommitBarrierClaim()


BLOCK_CLAIMS = BlockClaims()


def block_claim(widget: object) -> CommitClaim:
return BLOCK_CLAIMS.project_value(widget)
Loading
Loading