Subscribe to events from this session. Events include assistant messages, tool executions, errors, and session state changes. Multiple handlers can be registered and will all receive events. Args: handler: A callback function that receives sessi
(self, handler: Callable[[SessionEvent], None])
| 1682 | unsubscribe() |
| 1683 | |
| 1684 | def on(self, handler: Callable[[SessionEvent], None]) -> Callable[[], None]: |
| 1685 | """ |
| 1686 | Subscribe to events from this session. |
| 1687 | |
| 1688 | Events include assistant messages, tool executions, errors, and session |
| 1689 | state changes. Multiple handlers can be registered and will all receive |
| 1690 | events. |
| 1691 | |
| 1692 | Args: |
| 1693 | handler: A callback function that receives session events. The function |
| 1694 | takes a single :class:`SessionEvent` argument and returns None. |
| 1695 | |
| 1696 | Returns: |
| 1697 | A function that, when called, unsubscribes the handler. |
| 1698 | |
| 1699 | Example: |
| 1700 | >>> from copilot.session_events import AssistantMessageData, SessionErrorData |
| 1701 | >>> def handle_event(event): |
| 1702 | ... match event.data: |
| 1703 | ... case AssistantMessageData() as data: |
| 1704 | ... print(f"Assistant: {data.content}") |
| 1705 | ... case SessionErrorData() as data: |
| 1706 | ... print(f"Error: {data.message}") |
| 1707 | >>> unsubscribe = session.on(handle_event) |
| 1708 | >>> # Later, to stop receiving events: |
| 1709 | >>> unsubscribe() |
| 1710 | """ |
| 1711 | with self._event_handlers_lock: |
| 1712 | self._event_handlers.add(handler) |
| 1713 | |
| 1714 | def unsubscribe(): |
| 1715 | with self._event_handlers_lock: |
| 1716 | self._event_handlers.discard(handler) |
| 1717 | |
| 1718 | return unsubscribe |
| 1719 | |
| 1720 | def _dispatch_event(self, event: SessionEvent) -> None: |
| 1721 | """ |