Skip to content

Nerve and siphon

Signals travel to agent tentacles on the signal nerve. What a reflex does travels on the event nerve, and each channel draws what reaches it through its siphon. Feelers explains how a channel draws a run.

octomate.nerve

The nerve: what a thread does, as it happens, for whoever is watching.

Publish and subscribe, keyed by channel, thread, user or habitat topics. The nerve carries wire events, including habitat lifecycle observations. Local publishers and subscribers use memory fibers by default; supplied fibers use the same lifecycle. Wire events are the run's stream as a wire consumer sees it, and what the graph says around a run — its start and end, a move, a failure, the reflex waking and falling asleep, an authorization. Every way in and out is a stream end the nerve hands over. A kick publishes on the send end of a stream opened on the thread it was asked on, as impulses: an event and the address it happens at. The nerve pumps the other end, delivering each impulse to the channel it happens on and to the subscribers of its thread and of the asking thread, so a console follows the kick wherever a move carries it. A channel holds one subscription for all its threads and draws every run on them; it misses nothing and holds nobody up, since what it has yet to read is kept for it. A thread's subscriber — the console's live socket — reads the receive end of a stream of its own, for as long as its block runs, and one that falls further behind than its backlog reads what was held for it and is cut off, never quietly skipped ahead. Each local stream is a fiber: a pair of buffered ends in memory. Publishing is one way and knows nothing of who subscribed, and nothing is kept for a reader that is not there: an event published to a thread nobody subscribes to goes nowhere, and a console re-reads the thread ledger when it opens. The one exception is asked for on both sides. A publisher opened with retain has what it routes to the thread it was asked on kept, in order, and that thread's subscriber opened with replay starts with what is kept past the offset it names. The retaining publishers open on one thread keep in one stream, which lasts until the last of them closes. The nerve does not know what a block or an impulse stands for: whoever opens a block decides how long what is said in it is worth keeping, and the reader counts its offset in what is kept.

Nerve.deliver reaches every subscriber of exactly one topic. A publisher sends user notifications by delivering separately to each authorized user's topic. Nerve.publish owns channel and thread routing for kicks and native tails.

A nerve runs one way and carries one kind of envelope. Events run outbound, as impulses, from whoever acted to whoever watches. Signals run inbound to whoever is to act, on a nerve of their own over the same topics, so a subscriber of one direction never reads the other. Kick routing belongs to the outbound nerve alone: Nerve.publish takes impulses.

EventT module-attribute

EventT = TypeVar(
    "EventT", default=WireEvent, covariant=True
)

NerveEventT module-attribute

NerveEventT = TypeVar('NerveEventT', default=WireEvent)

SentT module-attribute

SentT = TypeVar('SentT', default=Impulse[WireEvent])

wire_impulse_adapter module-attribute

wire_impulse_adapter: TypeAdapter[Impulse[WireEvent]] = (
    TypeAdapter(Impulse[WireEvent])
)

EventTopic

EventTopic = ChannelTopic | ThreadTopic | UserTopic

Topic

Topic = (
    EventTopic | HabitatTopic | InvocationTopic | AgentTopic
)

Impulse dataclass

Bases: Generic[EventT]

One event with an optional address and the routing metadata used by Nerve.publish. Direct topic publication carries it unchanged.

Source code in octomate/nerve.py
@with_config(
    ConfigDict(
        extra="forbid",
        ser_json_bytes="base64",
        val_json_bytes="base64",
    )
)
@dataclass(frozen=True)
class Impulse(Generic[EventT]):
    """One event with an optional address and the routing metadata
    used by `Nerve.publish`. Direct topic publication carries it unchanged."""

    event: EventT
    address: ChannelAddress | None = None
    # Whether Nerve.publish excludes the origin thread for a private delivery.
    private: bool = False
    # The thread Nerve.publish stamps on the event: the asking thread
    # for a kick, the native thread for a tail, or None when neither names a thread.
    origin: ThreadKey | None = None
    replay: bool = False  # Historical transcript events must not animate live activity.

event instance-attribute

event: EventT

address class-attribute instance-attribute

address: ChannelAddress | None = None

private class-attribute instance-attribute

private: bool = False

origin class-attribute instance-attribute

origin: ThreadKey | None = None

replay class-attribute instance-attribute

replay: bool = False

ChannelTopic dataclass

Every impulse at one channel's addresses, each once.

Source code in octomate/nerve.py
@dataclass(frozen=True)
class ChannelTopic:
    """Every impulse at one channel's addresses, each once."""

    channel_tentacle_id: str

channel_tentacle_id instance-attribute

channel_tentacle_id: str

ThreadTopic dataclass

The impulses published to one thread.

Source code in octomate/nerve.py
@dataclass(frozen=True)
class ThreadTopic:
    """The impulses published to one thread."""

    key: ThreadKey

key instance-attribute

key: ThreadKey

UserTopic dataclass

Notifications explicitly published to one registered user.

Source code in octomate/nerve.py
@dataclass(frozen=True)
class UserTopic:
    """Notifications explicitly published to one registered user."""

    user_id: UUID7

user_id instance-attribute

user_id: UUID7

HabitatTopic dataclass

A user's habitat lifecycle observations.

Source code in octomate/nerve.py
@dataclass(frozen=True)
class HabitatTopic:
    """A user's habitat lifecycle observations."""

    user_id: UUID7

user_id instance-attribute

user_id: UUID7

InvocationTopic dataclass

Signals addressed to one agent invocation.

Source code in octomate/nerve.py
@dataclass(frozen=True)
class InvocationTopic:
    """Signals addressed to one agent invocation."""

    invocation_id: UUID7

invocation_id instance-attribute

invocation_id: UUID7

AgentTopic dataclass

One agent's long-lived signal receiver.

Source code in octomate/nerve.py
@dataclass(frozen=True)
class AgentTopic:
    """One agent's long-lived signal receiver."""

    agent_id: str

agent_id instance-attribute

agent_id: str

Nerve

Bases: Generic[SentT]

Route one kind of payload, impulses or signals, through publishers and subscribers backed by any fiber.

Source code in octomate/nerve.py
class Nerve(Generic[SentT]):
    """Route one kind of payload, impulses or signals, through publishers and
    subscribers backed by any fiber."""

    def __init__(self) -> None:
        # Each subscriber's fiber, by the topic it hears.
        self.subscribers: defaultdict[Topic, set[Fiber[SentT]]] = defaultdict(set)
        # Retained envelopes live until the last retaining publisher closes.
        self.retained: dict[Topic, list[SentT]] = {}
        self.retaining: Counter[Topic] = Counter()

    @contextmanager
    def accept(self, topic: Topic, fiber: Fiber[SentT]) -> Generator[None]:
        """Have a fiber accept what is delivered to the topic, for the block.

        The fiber stays its caller's to buffer and close; leaving only ends
        its deliveries.
        """
        if fiber.closed or fiber in self.subscribers.get(topic, set()):
            raise ValueError("Fiber is already subscribed or closed")
        self.subscribers[topic].add(fiber)
        try:
            yield
        finally:
            self.subscribers[topic].discard(fiber)
            if not self.subscribers[topic]:
                del self.subscribers[topic]

    def deliver(self, topic: Topic, sent: SentT) -> None:
        """Fan out to every subscriber of one topic.

        A slow local subscriber is cut off at its backlog. A full or broken peer
        fiber is disconnected independently; other subscribers keep receiving.
        Message handling belongs to receivers; unobserved publications are dropped.
        """
        recipients = self.subscribers.get(topic, set())
        for fiber in recipients:
            if fiber.closed:
                continue
            try:
                fiber.send_nowait(sent)
            except (
                anyio.WouldBlock,
                anyio.BrokenResourceError,
                anyio.ClosedResourceError,
            ):
                fiber.fail(FiberError("Subscriber fiber cannot accept publication"))

    def dispatch(self, topic: Topic, sent: SentT) -> None:
        """Send to exactly one ready receiver, refusing missing or ambiguous delivery."""
        recipients = [
            fiber
            for fiber in self.subscribers.get(topic, set())
            if not fiber.closed and fiber.failure is None
        ]
        if len(recipients) != 1:
            raise FiberError("Directed delivery requires exactly one ready receiver")
        recipients[0].send_nowait(sent)

    @asynccontextmanager
    async def subscribe(
        self,
        topic: Topic,
        *,
        backlog: float = math.inf,
        fiber: Fiber[SentT] | None = None,
        replay: int | None = None,
    ) -> AsyncGenerator[ObjectReceiveStream[SentT]]:
        """The receive end of a stream of what the topic is sent, from now until
        the block ends. Nothing is dropped: a reader that falls more than
        `backlog` behind reads what was held for it, and then its stream ends.

        With `replay`, the stream starts with what is `retained` for the topic
        past that many impulses, before what arrives; 0 starts with all of it.
        They are read one at a time and do not count against `backlog`. A
        supplied fiber cannot replay.

        `ChannelTopic` names a channel's addresses, `ThreadTopic` wraps one
        `ThreadKey`, `UserTopic` wraps a registered user's UUID, and `HabitatTopic`
        names the habitat lifecycle. Receivers select the events they handle.
        Publishers choose authorized topics before publishing; the nerve does
        not filter subscribers within a topic.

        A supplied fiber receives the same as a local subscription.
        Its caller owns its buffering and closure; leaving only unsubscribes it.
        """
        if fiber is not None and replay is not None:
            raise ValueError("A supplied fiber cannot replay")
        # No await separates taking what is retained from joining the live set,
        # so the subscriber neither misses an impulse nor reads one twice.
        replayed = [] if replay is None else self.retained.get(topic, [])[replay:]
        subscriber = (
            fiber if fiber is not None else ReplayFiber[SentT](replayed, backlog)
        )
        try:
            with self.accept(topic, subscriber):
                yield subscriber
        finally:
            if fiber is None:
                subscriber.close()

    @asynccontextmanager
    async def publish(
        self: Nerve[Impulse[NerveEventT]],
        origin: ChannelAddress | Topic | None,
        *,
        fiber: Fiber[Impulse[NerveEventT]] | None = None,
        retain: bool = False,
    ) -> AsyncGenerator[ObjectSendStream[Impulse[NerveEventT]]]:
        """A buffered publisher for kicks and native tails, open for the block.

        A kick names the thread it was asked on as `origin`; a native tail names
        its native thread and scopes the stream to its connection. The publisher
        stamps that origin on each impulse and publishes separately to its channel,
        its destination thread, and its origin thread unless private. Each distinct
        topic receives one publication.

        Sending may wait for the pump, never for a subscriber. Everything sent before
        the block ends is published; closing emits no lifecycle events of its own.

        With `retain`, what an addressed publisher routes to the thread it was
        asked on is kept for that thread's replaying subscribers. The retaining
        publishers open on one thread keep in one stream, in the order the nerve
        routed, and it is dropped when the last of them closes: what one kept
        outlasts its block while another is still open there.

        A topic publishes impulses unchanged to that topic. A supplied fiber is
        read for the block's lifetime and remains owned by its caller. Its incoming
        impulses are delivered to subscribers on the core-bound topic.
        """
        publisher = fiber if fiber is not None else MemoryFiber[Impulse[NerveEventT]]()
        if publisher.closed:
            raise ValueError("Publisher fiber is closed")
        asked = (
            ThreadKey.model_validate(origin)
            if isinstance(origin, ChannelAddress)
            else None
        )
        topic = (
            origin
            if isinstance(
                origin,
                ChannelTopic
                | ThreadTopic
                | UserTopic
                | HabitatTopic
                | InvocationTopic
                | AgentTopic,
            )
            else None
        )

        retaining = ThreadTopic(asked) if retain and asked is not None else None

        async def pump() -> None:
            if retaining is not None:
                self.retaining[retaining] += 1
            try:
                async for sent in publisher:
                    if topic is not None:
                        self.deliver(topic, sent)
                        continue
                    impulse = replace(sent, origin=asked)
                    topics: set[Topic] = set()
                    if impulse.address is not None:
                        topics.add(ChannelTopic(impulse.address.channel_tentacle_id))
                        topics.add(
                            ThreadTopic(ThreadKey.model_validate(impulse.address))
                        )
                    if not impulse.private and asked is not None:
                        topics.add(ThreadTopic(asked))
                    if retaining is not None and retaining in topics:
                        self.retained.setdefault(retaining, []).append(impulse)
                    for destination in topics:
                        self.deliver(destination, impulse)
            except (anyio.BrokenResourceError, anyio.ClosedResourceError):
                pass  # The owner closed the supplied fiber while its pump was waiting.
            finally:
                if retaining is not None:
                    self.retaining[retaining] -= 1
                    if not self.retaining[retaining]:
                        del self.retaining[retaining]
                        self.retained.pop(retaining, None)
                if fiber is None:
                    publisher.close()

        pumping = asyncio.create_task(pump())
        try:
            yield publisher
        finally:
            if fiber is not None:
                if not publisher.closed or publisher.failure is not None:
                    pumping.cancel()
                with suppress(asyncio.CancelledError):
                    await pumping
            else:
                publisher.close_send()
                try:
                    await pumping
                finally:
                    publisher.close()

subscribers instance-attribute

subscribers: defaultdict[Topic, set[Fiber[SentT]]] = (
    defaultdict(set)
)

retained instance-attribute

retained: dict[Topic, list[SentT]] = {}

retaining instance-attribute

retaining: Counter[Topic] = Counter()

accept

accept(
    topic: Topic, fiber: Fiber[SentT]
) -> Generator[None]

Have a fiber accept what is delivered to the topic, for the block.

The fiber stays its caller's to buffer and close; leaving only ends its deliveries.

Source code in octomate/nerve.py
@contextmanager
def accept(self, topic: Topic, fiber: Fiber[SentT]) -> Generator[None]:
    """Have a fiber accept what is delivered to the topic, for the block.

    The fiber stays its caller's to buffer and close; leaving only ends
    its deliveries.
    """
    if fiber.closed or fiber in self.subscribers.get(topic, set()):
        raise ValueError("Fiber is already subscribed or closed")
    self.subscribers[topic].add(fiber)
    try:
        yield
    finally:
        self.subscribers[topic].discard(fiber)
        if not self.subscribers[topic]:
            del self.subscribers[topic]

deliver

deliver(topic: Topic, sent: SentT) -> None

Fan out to every subscriber of one topic.

A slow local subscriber is cut off at its backlog. A full or broken peer fiber is disconnected independently; other subscribers keep receiving. Message handling belongs to receivers; unobserved publications are dropped.

Source code in octomate/nerve.py
def deliver(self, topic: Topic, sent: SentT) -> None:
    """Fan out to every subscriber of one topic.

    A slow local subscriber is cut off at its backlog. A full or broken peer
    fiber is disconnected independently; other subscribers keep receiving.
    Message handling belongs to receivers; unobserved publications are dropped.
    """
    recipients = self.subscribers.get(topic, set())
    for fiber in recipients:
        if fiber.closed:
            continue
        try:
            fiber.send_nowait(sent)
        except (
            anyio.WouldBlock,
            anyio.BrokenResourceError,
            anyio.ClosedResourceError,
        ):
            fiber.fail(FiberError("Subscriber fiber cannot accept publication"))

dispatch

dispatch(topic: Topic, sent: SentT) -> None

Send to exactly one ready receiver, refusing missing or ambiguous delivery.

Source code in octomate/nerve.py
def dispatch(self, topic: Topic, sent: SentT) -> None:
    """Send to exactly one ready receiver, refusing missing or ambiguous delivery."""
    recipients = [
        fiber
        for fiber in self.subscribers.get(topic, set())
        if not fiber.closed and fiber.failure is None
    ]
    if len(recipients) != 1:
        raise FiberError("Directed delivery requires exactly one ready receiver")
    recipients[0].send_nowait(sent)

subscribe async

subscribe(
    topic: Topic,
    *,
    backlog: float = math.inf,
    fiber: Fiber[SentT] | None = None,
    replay: int | None = None,
) -> AsyncGenerator[ObjectReceiveStream[SentT]]

The receive end of a stream of what the topic is sent, from now until the block ends. Nothing is dropped: a reader that falls more than backlog behind reads what was held for it, and then its stream ends.

With replay, the stream starts with what is retained for the topic past that many impulses, before what arrives; 0 starts with all of it. They are read one at a time and do not count against backlog. A supplied fiber cannot replay.

ChannelTopic names a channel's addresses, ThreadTopic wraps one ThreadKey, UserTopic wraps a registered user's UUID, and HabitatTopic names the habitat lifecycle. Receivers select the events they handle. Publishers choose authorized topics before publishing; the nerve does not filter subscribers within a topic.

A supplied fiber receives the same as a local subscription. Its caller owns its buffering and closure; leaving only unsubscribes it.

Source code in octomate/nerve.py
@asynccontextmanager
async def subscribe(
    self,
    topic: Topic,
    *,
    backlog: float = math.inf,
    fiber: Fiber[SentT] | None = None,
    replay: int | None = None,
) -> AsyncGenerator[ObjectReceiveStream[SentT]]:
    """The receive end of a stream of what the topic is sent, from now until
    the block ends. Nothing is dropped: a reader that falls more than
    `backlog` behind reads what was held for it, and then its stream ends.

    With `replay`, the stream starts with what is `retained` for the topic
    past that many impulses, before what arrives; 0 starts with all of it.
    They are read one at a time and do not count against `backlog`. A
    supplied fiber cannot replay.

    `ChannelTopic` names a channel's addresses, `ThreadTopic` wraps one
    `ThreadKey`, `UserTopic` wraps a registered user's UUID, and `HabitatTopic`
    names the habitat lifecycle. Receivers select the events they handle.
    Publishers choose authorized topics before publishing; the nerve does
    not filter subscribers within a topic.

    A supplied fiber receives the same as a local subscription.
    Its caller owns its buffering and closure; leaving only unsubscribes it.
    """
    if fiber is not None and replay is not None:
        raise ValueError("A supplied fiber cannot replay")
    # No await separates taking what is retained from joining the live set,
    # so the subscriber neither misses an impulse nor reads one twice.
    replayed = [] if replay is None else self.retained.get(topic, [])[replay:]
    subscriber = (
        fiber if fiber is not None else ReplayFiber[SentT](replayed, backlog)
    )
    try:
        with self.accept(topic, subscriber):
            yield subscriber
    finally:
        if fiber is None:
            subscriber.close()

publish async

publish(
    origin: ChannelAddress | Topic | None,
    *,
    fiber: Fiber[Impulse[NerveEventT]] | None = None,
    retain: bool = False,
) -> AsyncGenerator[ObjectSendStream[Impulse[NerveEventT]]]

A buffered publisher for kicks and native tails, open for the block.

A kick names the thread it was asked on as origin; a native tail names its native thread and scopes the stream to its connection. The publisher stamps that origin on each impulse and publishes separately to its channel, its destination thread, and its origin thread unless private. Each distinct topic receives one publication.

Sending may wait for the pump, never for a subscriber. Everything sent before the block ends is published; closing emits no lifecycle events of its own.

With retain, what an addressed publisher routes to the thread it was asked on is kept for that thread's replaying subscribers. The retaining publishers open on one thread keep in one stream, in the order the nerve routed, and it is dropped when the last of them closes: what one kept outlasts its block while another is still open there.

A topic publishes impulses unchanged to that topic. A supplied fiber is read for the block's lifetime and remains owned by its caller. Its incoming impulses are delivered to subscribers on the core-bound topic.

Source code in octomate/nerve.py
@asynccontextmanager
async def publish(
    self: Nerve[Impulse[NerveEventT]],
    origin: ChannelAddress | Topic | None,
    *,
    fiber: Fiber[Impulse[NerveEventT]] | None = None,
    retain: bool = False,
) -> AsyncGenerator[ObjectSendStream[Impulse[NerveEventT]]]:
    """A buffered publisher for kicks and native tails, open for the block.

    A kick names the thread it was asked on as `origin`; a native tail names
    its native thread and scopes the stream to its connection. The publisher
    stamps that origin on each impulse and publishes separately to its channel,
    its destination thread, and its origin thread unless private. Each distinct
    topic receives one publication.

    Sending may wait for the pump, never for a subscriber. Everything sent before
    the block ends is published; closing emits no lifecycle events of its own.

    With `retain`, what an addressed publisher routes to the thread it was
    asked on is kept for that thread's replaying subscribers. The retaining
    publishers open on one thread keep in one stream, in the order the nerve
    routed, and it is dropped when the last of them closes: what one kept
    outlasts its block while another is still open there.

    A topic publishes impulses unchanged to that topic. A supplied fiber is
    read for the block's lifetime and remains owned by its caller. Its incoming
    impulses are delivered to subscribers on the core-bound topic.
    """
    publisher = fiber if fiber is not None else MemoryFiber[Impulse[NerveEventT]]()
    if publisher.closed:
        raise ValueError("Publisher fiber is closed")
    asked = (
        ThreadKey.model_validate(origin)
        if isinstance(origin, ChannelAddress)
        else None
    )
    topic = (
        origin
        if isinstance(
            origin,
            ChannelTopic
            | ThreadTopic
            | UserTopic
            | HabitatTopic
            | InvocationTopic
            | AgentTopic,
        )
        else None
    )

    retaining = ThreadTopic(asked) if retain and asked is not None else None

    async def pump() -> None:
        if retaining is not None:
            self.retaining[retaining] += 1
        try:
            async for sent in publisher:
                if topic is not None:
                    self.deliver(topic, sent)
                    continue
                impulse = replace(sent, origin=asked)
                topics: set[Topic] = set()
                if impulse.address is not None:
                    topics.add(ChannelTopic(impulse.address.channel_tentacle_id))
                    topics.add(
                        ThreadTopic(ThreadKey.model_validate(impulse.address))
                    )
                if not impulse.private and asked is not None:
                    topics.add(ThreadTopic(asked))
                if retaining is not None and retaining in topics:
                    self.retained.setdefault(retaining, []).append(impulse)
                for destination in topics:
                    self.deliver(destination, impulse)
        except (anyio.BrokenResourceError, anyio.ClosedResourceError):
            pass  # The owner closed the supplied fiber while its pump was waiting.
        finally:
            if retaining is not None:
                self.retaining[retaining] -= 1
                if not self.retaining[retaining]:
                    del self.retaining[retaining]
                    self.retained.pop(retaining, None)
            if fiber is None:
                publisher.close()

    pumping = asyncio.create_task(pump())
    try:
        yield publisher
    finally:
        if fiber is not None:
            if not publisher.closed or publisher.failure is not None:
                pumping.cancel()
            with suppress(asyncio.CancelledError):
                await pumping
        else:
            publisher.close_send()
            try:
                await pumping
            finally:
                publisher.close()

Nerves dataclass

The host's independent inbound signals and outbound event stream.

Source code in octomate/nerve.py
@dataclass
class Nerves:
    """The host's independent inbound signals and outbound event stream."""

    signals: Nerve[Signal] = field(default_factory=Nerve[Signal])
    events: Nerve[Impulse[WireEvent]] = field(default_factory=Nerve[Impulse[WireEvent]])

signals class-attribute instance-attribute

signals: Nerve[Signal] = field(
    default_factory=Nerve[Signal]
)

events class-attribute instance-attribute

events: Nerve[Impulse[WireEvent]] = field(
    default_factory=Nerve[Impulse[WireEvent]]
)

octomate.tentacles.siphon

A channel's siphon: where what the nerve carries leaves for the platform.

An octopus pushes its ink out through its siphon. A channel's siphon pushes out what the nerve carries to it, through the channel's feelers — a run as a timeline when the channel streams, or its sends, batches and reply when it does not, and around runs a move's line, a failure, a send, an authorization. It holds the channel's subscription to its own addresses, and draws each thread in order in a lane of its own, so a slow thread holds up no other. A row the graph recorded comes with its id, and is marked with the platform id it was rendered as.

logger module-attribute

logger = logging.getLogger(__name__)

Siphon

Draws what the nerve carries to one channel, thread by thread.

Source code in octomate/tentacles/siphon.py
class Siphon:
    """Draws what the nerve carries to one channel, thread by thread."""

    def __init__(self, channel: ChannelTentacle) -> None:
        self.channel = channel
        # Each thread's lane: the impulses it has yet to draw.
        self.lanes: dict[ThreadKey, MemoryObjectSendStream[Impulse]] = {}
        self.subscription: (
            AbstractAsyncContextManager[ObjectReceiveStream[Impulse]] | None
        ) = None
        self.reading: asyncio.Task[None] | None = None

    async def __aenter__(self) -> Self:
        """Subscribe to the channel's addresses now, so nothing published from
        here on is missed, and read in the background until the context exits."""
        self.subscription = self.channel.nerve.subscribe(ChannelTopic(self.channel.id))
        impulses = await self.subscription.__aenter__()
        self.reading = asyncio.create_task(self.read(impulses))
        return self

    async def __aexit__(
        self,
        exc_type: type[BaseException] | None,
        exc: BaseException | None,
        traceback: TracebackType | None,
    ) -> None:
        try:
            if self.reading is not None:
                self.reading.cancel()
                with suppress(asyncio.CancelledError):
                    await self.reading
        finally:
            if self.subscription is not None:
                await self.subscription.__aexit__(exc_type, exc, traceback)
            await self.channel.feelers.status.close()

    async def read(self, impulses: ObjectReceiveStream[Impulse]) -> None:
        """Hand each impulse to its thread's lane, opening one where none is."""
        async with asyncio.TaskGroup() as lanes:
            async for impulse in impulses:
                if impulse.address is None:
                    continue  # The nerve hands a channel only what has an address.
                self.channel.feelers.status.feed(impulse.address, impulse.event)
                key = ThreadKey.model_validate(impulse.address)
                lane = self.lanes.get(key)
                if lane is None:
                    lane, waiting = anyio.create_memory_object_stream[Impulse](math.inf)
                    self.lanes[key] = lane
                    lanes.create_task(self.draw(key, waiting))
                lane.send_nowait(impulse)

    async def draw(
        self, key: ThreadKey, impulses: MemoryObjectReceiveStream[Impulse]
    ) -> None:
        """Draw one thread's impulses in order, and close the lane once nothing
        is left in it. A rendering that fails is logged and never ends the lane."""
        with impulses:
            async for impulse in impulses:
                try:
                    await self.feel(impulse, impulses)
                except Exception:
                    logger.warning(
                        "Channel %s: rendering %s failed",
                        self.channel.id,
                        type(impulse.event).__name__,
                        exc_info=True,
                    )
                if impulses.statistics().current_buffer_used == 0:
                    self.lanes.pop(key).close()
                    return

    async def feel(
        self, impulse: Impulse, impulses: MemoryObjectReceiveStream[Impulse]
    ) -> None:
        """Draw one impulse; a run's start draws the whole run, through its end."""
        feelers = self.channel.feelers
        address = impulse.address
        if address is None:
            return
        match impulse.event:
            case RunStartedEvent():
                await self.run(address, impulses)
            case GatewayEvent() as event:
                line = await feelers.present(address, event)
                await self.mark(event.thread_message_id, line)
            case RunErrorEvent() as event:
                await feelers.present(address, event)
            case MessageSentEvent() as event:
                sent = await feelers.segments.present(
                    event.destination or address, event.segments
                )
                await self.mark(event.thread_message_id, sent)
            case OAuthAuthorizationEvent() as event:
                await feelers.oauth.present(address, event)
            case ArtifactAvailableEvent() as event:
                await feelers.artifacts.present(address, event)
            case ActionBatchAnsweredEvent() | ActionBatchUpdatedEvent() as event:
                await feelers.approvals.settle(
                    address,
                    event,
                    action_manager=self.channel.octomate.deferred_actions,
                )
                await feelers.ask_questions.settle(
                    address,
                    event,
                    action_manager=self.channel.octomate.deferred_actions,
                )
            case _:
                pass

    async def run(
        self, address: ChannelAddress, impulses: MemoryObjectReceiveStream[Impulse]
    ) -> None:
        """Draw one agent run from the lane, up to its end: as a timeline when the
        channel streams, else quietly. What a failed rendering left unread is
        drained, so the lane resumes after the run."""
        ended: list[RunEndedEvent] = []

        async def events() -> AsyncGenerator[WireEvent]:
            async for impulse in impulses:
                if isinstance(impulse.event, RunEndedEvent):
                    ended.append(impulse.event)
                    return
                yield impulse.event

        stream = events()
        try:
            if self.channel.config.stream.enabled:
                async with self.channel.feelers.timeline.open(address) as timeline:
                    timeline.artifacts = self.channel.feelers.artifacts
                    await timeline.drive(stream)
                rendered = timeline.message_id
            else:
                rendered = await self.quietly(address, stream)
        except Exception:
            async for _ in stream:
                pass
            raise
        if ended:
            await self.mark(ended[0].thread_message_id, rendered)

    async def quietly(
        self, address: ChannelAddress, events: AsyncGenerator[WireEvent]
    ) -> IMMessageID | None:
        """A run on a channel that does not stream: its sends, batches and
        authorizations as they come, then its reply once. Answers the platform id
        the reply was posted as."""
        feelers = self.channel.feelers
        output: str | list[MessageSegment] | None = None
        async for event in events:
            match event:
                case MessageSentEvent():
                    await feelers.segments.present(
                        event.destination or address, event.segments
                    )
                case ActionBatchEvent():
                    await feelers.present_actions(
                        address,
                        event,
                        action_manager=self.channel.octomate.deferred_actions,
                    )
                case ActionBatchAnsweredEvent() | ActionBatchUpdatedEvent():
                    await feelers.approvals.settle(
                        address,
                        event,
                        action_manager=self.channel.octomate.deferred_actions,
                    )
                    await feelers.ask_questions.settle(
                        address,
                        event,
                        action_manager=self.channel.octomate.deferred_actions,
                    )
                case OAuthAuthorizationEvent():
                    await feelers.oauth.present(address, event)
                case ArtifactAvailableEvent():
                    await feelers.artifacts.present(address, event)
                case RunResultEvent():
                    output = event.output
                case _:
                    pass
        if isinstance(output, str):
            return await feelers.markdown.present(address, output) if output else None
        return await feelers.segments.present(address, output) if output else None

    async def mark(
        self, thread_message_id: UUID7 | None, platform_message_id: str | None
    ) -> None:
        """Name the platform message a recorded row was rendered as."""
        if thread_message_id is not None:
            await self.channel.octomate.threads.mark_presented(
                thread_message_id, platform_message_id
            )

channel instance-attribute

channel = channel

lanes instance-attribute

lanes: dict[ThreadKey, MemoryObjectSendStream[Impulse]] = {}

subscription instance-attribute

subscription: (
    AbstractAsyncContextManager[
        ObjectReceiveStream[Impulse]
    ]
    | None
) = None

reading instance-attribute

reading: Task[None] | None = None

read async

read(impulses: ObjectReceiveStream[Impulse]) -> None

Hand each impulse to its thread's lane, opening one where none is.

Source code in octomate/tentacles/siphon.py
async def read(self, impulses: ObjectReceiveStream[Impulse]) -> None:
    """Hand each impulse to its thread's lane, opening one where none is."""
    async with asyncio.TaskGroup() as lanes:
        async for impulse in impulses:
            if impulse.address is None:
                continue  # The nerve hands a channel only what has an address.
            self.channel.feelers.status.feed(impulse.address, impulse.event)
            key = ThreadKey.model_validate(impulse.address)
            lane = self.lanes.get(key)
            if lane is None:
                lane, waiting = anyio.create_memory_object_stream[Impulse](math.inf)
                self.lanes[key] = lane
                lanes.create_task(self.draw(key, waiting))
            lane.send_nowait(impulse)

draw async

draw(
    key: ThreadKey,
    impulses: MemoryObjectReceiveStream[Impulse],
) -> None

Draw one thread's impulses in order, and close the lane once nothing is left in it. A rendering that fails is logged and never ends the lane.

Source code in octomate/tentacles/siphon.py
async def draw(
    self, key: ThreadKey, impulses: MemoryObjectReceiveStream[Impulse]
) -> None:
    """Draw one thread's impulses in order, and close the lane once nothing
    is left in it. A rendering that fails is logged and never ends the lane."""
    with impulses:
        async for impulse in impulses:
            try:
                await self.feel(impulse, impulses)
            except Exception:
                logger.warning(
                    "Channel %s: rendering %s failed",
                    self.channel.id,
                    type(impulse.event).__name__,
                    exc_info=True,
                )
            if impulses.statistics().current_buffer_used == 0:
                self.lanes.pop(key).close()
                return

feel async

feel(
    impulse: Impulse,
    impulses: MemoryObjectReceiveStream[Impulse],
) -> None

Draw one impulse; a run's start draws the whole run, through its end.

Source code in octomate/tentacles/siphon.py
async def feel(
    self, impulse: Impulse, impulses: MemoryObjectReceiveStream[Impulse]
) -> None:
    """Draw one impulse; a run's start draws the whole run, through its end."""
    feelers = self.channel.feelers
    address = impulse.address
    if address is None:
        return
    match impulse.event:
        case RunStartedEvent():
            await self.run(address, impulses)
        case GatewayEvent() as event:
            line = await feelers.present(address, event)
            await self.mark(event.thread_message_id, line)
        case RunErrorEvent() as event:
            await feelers.present(address, event)
        case MessageSentEvent() as event:
            sent = await feelers.segments.present(
                event.destination or address, event.segments
            )
            await self.mark(event.thread_message_id, sent)
        case OAuthAuthorizationEvent() as event:
            await feelers.oauth.present(address, event)
        case ArtifactAvailableEvent() as event:
            await feelers.artifacts.present(address, event)
        case ActionBatchAnsweredEvent() | ActionBatchUpdatedEvent() as event:
            await feelers.approvals.settle(
                address,
                event,
                action_manager=self.channel.octomate.deferred_actions,
            )
            await feelers.ask_questions.settle(
                address,
                event,
                action_manager=self.channel.octomate.deferred_actions,
            )
        case _:
            pass

run async

run(
    address: ChannelAddress,
    impulses: MemoryObjectReceiveStream[Impulse],
) -> None

Draw one agent run from the lane, up to its end: as a timeline when the channel streams, else quietly. What a failed rendering left unread is drained, so the lane resumes after the run.

Source code in octomate/tentacles/siphon.py
async def run(
    self, address: ChannelAddress, impulses: MemoryObjectReceiveStream[Impulse]
) -> None:
    """Draw one agent run from the lane, up to its end: as a timeline when the
    channel streams, else quietly. What a failed rendering left unread is
    drained, so the lane resumes after the run."""
    ended: list[RunEndedEvent] = []

    async def events() -> AsyncGenerator[WireEvent]:
        async for impulse in impulses:
            if isinstance(impulse.event, RunEndedEvent):
                ended.append(impulse.event)
                return
            yield impulse.event

    stream = events()
    try:
        if self.channel.config.stream.enabled:
            async with self.channel.feelers.timeline.open(address) as timeline:
                timeline.artifacts = self.channel.feelers.artifacts
                await timeline.drive(stream)
            rendered = timeline.message_id
        else:
            rendered = await self.quietly(address, stream)
    except Exception:
        async for _ in stream:
            pass
        raise
    if ended:
        await self.mark(ended[0].thread_message_id, rendered)

quietly async

quietly(
    address: ChannelAddress,
    events: AsyncGenerator[WireEvent],
) -> IMMessageID | None

A run on a channel that does not stream: its sends, batches and authorizations as they come, then its reply once. Answers the platform id the reply was posted as.

Source code in octomate/tentacles/siphon.py
async def quietly(
    self, address: ChannelAddress, events: AsyncGenerator[WireEvent]
) -> IMMessageID | None:
    """A run on a channel that does not stream: its sends, batches and
    authorizations as they come, then its reply once. Answers the platform id
    the reply was posted as."""
    feelers = self.channel.feelers
    output: str | list[MessageSegment] | None = None
    async for event in events:
        match event:
            case MessageSentEvent():
                await feelers.segments.present(
                    event.destination or address, event.segments
                )
            case ActionBatchEvent():
                await feelers.present_actions(
                    address,
                    event,
                    action_manager=self.channel.octomate.deferred_actions,
                )
            case ActionBatchAnsweredEvent() | ActionBatchUpdatedEvent():
                await feelers.approvals.settle(
                    address,
                    event,
                    action_manager=self.channel.octomate.deferred_actions,
                )
                await feelers.ask_questions.settle(
                    address,
                    event,
                    action_manager=self.channel.octomate.deferred_actions,
                )
            case OAuthAuthorizationEvent():
                await feelers.oauth.present(address, event)
            case ArtifactAvailableEvent():
                await feelers.artifacts.present(address, event)
            case RunResultEvent():
                output = event.output
            case _:
                pass
    if isinstance(output, str):
        return await feelers.markdown.present(address, output) if output else None
    return await feelers.segments.present(address, output) if output else None

mark async

mark(
    thread_message_id: UUID7 | None,
    platform_message_id: str | None,
) -> None

Name the platform message a recorded row was rendered as.

Source code in octomate/tentacles/siphon.py
async def mark(
    self, thread_message_id: UUID7 | None, platform_message_id: str | None
) -> None:
    """Name the platform message a recorded row was rendered as."""
    if thread_message_id is not None:
        await self.channel.octomate.threads.mark_presented(
            thread_message_id, platform_message_id
        )