Skip to content

Commit 79c95d9

Browse files
committed
version bump
1 parent 5056228 commit 79c95d9

6 files changed

Lines changed: 270 additions & 33 deletions

File tree

‎README.md‎

Lines changed: 51 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -107,37 +107,64 @@ All callbacks are optional.
107107

108108
## Reconnection
109109

110-
**The Python SDK does not reconnect automatically.** A network change mid-call
111-
ends the session, and recovery means calling `connect()` again — which starts a
112-
new conversation, without the previous history.
110+
A network change mid-call is recovered automatically, and the conversation
111+
survives it: the agent still knows who you are and does not replay its
112+
greeting.
113113

114-
This is an aiortc limitation, not a protocol one. The server supports ICE
115-
restart (`PATCH /whip/{sessionId}`, RFC 9725 §4.4), and the TypeScript, React
116-
Native, Go, and Rust SDKs use it to recover a dropped connection on the *same*
117-
session, conversation intact. aiortc cannot: `RTCPeerConnection.createOffer()`
118-
takes no options, aioice fixes its ICE credentials at construction, and aiortc
119-
has no `disconnected` connection state to trigger on — it goes straight from
120-
`connected` to `failed`. Performing a restart would mean rebuilding the ICE
121-
layer under a live DTLS session.
114+
The mechanism differs from the other SDKs. They keep the transport alive with
115+
an ICE restart; aiortc cannot do that (`RTCPeerConnection.createOffer()` takes
116+
no options, aioice fixes its ICE credentials at construction, and aiortc has no
117+
`disconnected` state to act on — it goes straight from `connected` to
118+
`failed`). So Python recovers by **redialling with a resume token**: a brand
119+
new peer connection, reattached server-side to the session it was already
120+
running. The transport is new; the conversation is not.
122121

123-
If mid-call network changes matter for your use case, prefer one of the other
124-
SDKs.
125-
126-
The wire format ships here regardless, tested and ready, for callers driving
127-
another WebRTC stack:
122+
Status goes `connected` → `reconnecting` → `connected`:
128123

129124
```python
130-
from streamcore import (
131-
whip_restart_ice,
132-
ice_fragment_from_sdp,
133-
apply_ice_fragment,
134-
)
125+
import streamcore
135126

136-
result = await whip_restart_ice(session_url, ice_fragment_from_sdp(local_sdp), etag, token)
137-
answer_sdp = apply_ice_fragment(previous_answer_sdp, result.fragment)
127+
client = streamcore.Client(
128+
streamcore.Config(
129+
whip_endpoint="http://localhost:8080/whip",
130+
reconnect_attempts=3,
131+
reconnect_delay=2.0,
132+
),
133+
streamcore.EventHandler(
134+
on_reconnect=lambda e: print(f"redial {e.attempt}/{e.max_attempts}: {e.outcome}"),
135+
),
136+
)
138137
```
139138

140-
`whip_offer` returns the session's `etag` for use as `If-Match`.
139+
One outcome deserves handling rather than logging:
140+
141+
- `RECOVERED` — reattached; history intact.
142+
- `RECOVERED_WITHOUT_HISTORY` — **the call works but the agent has forgotten
143+
everything.** The server had already reaped the session, so the redial
144+
started a fresh conversation. Surface this to the user rather than letting
145+
them discover it by being asked their name again.
146+
- `FAILED` — every attempt failed; status becomes `disconnected`.
147+
148+
The window is the server's `session_grace_ms` (30s by default), measured from
149+
when the connection dropped — not the ~25s ICE deadline the other SDKs work
150+
against. Keep `reconnect_attempts × reconnect_delay` (doubling each retry)
151+
inside it. Set `reconnect_attempts=0` to disable and handle drops yourself.
152+
153+
Two caveats specific to this stack:
154+
155+
- **Realtime (speech-to-speech) sessions cannot be resumed.** Their history
156+
lives inside the provider, so the server issues no token and a redial starts
157+
a new conversation.
158+
- **A caller-supplied `user_track` is reused across the redial.** The built-in
159+
track (the `send_pcm` path) is rebuilt automatically; if you pass your own
160+
track to `connect()`, make sure it is still live, or reconnect yourself.
161+
162+
The wire-format helpers for ICE restart still ship in `streamcore.icerestart`
163+
for callers driving another WebRTC stack:
164+
165+
```python
166+
from streamcore import whip_restart_ice, ice_fragment_from_sdp, apply_ice_fragment
167+
```
141168

142169
## Audio I/O
143170

‎pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
44

55
[project]
66
name = "streamcore"
7-
version = "0.1.2"
7+
version = "0.1.3"
88
description = "Python SDK for connecting to a Pion Voice Agent server via WebRTC + WHIP"
99
readme = "README.md"
1010
license = "Apache-2.0"

‎src/streamcore/__init__.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
DataChannelMessage,
88
Config,
99
EventHandler,
10+
ReconnectEvent,
11+
ReconnectOutcome,
1012
)
1113
from .client import Client
1214
from .icerestart import (
@@ -26,6 +28,8 @@
2628
"TranscriptEntry",
2729
"TimingEvent",
2830
"DataChannelMessage",
31+
"ReconnectEvent",
32+
"ReconnectOutcome",
2933
"whip_offer",
3034
"whip_delete",
3135
"whip_restart_ice",

‎src/streamcore/client.py‎

Lines changed: 152 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@
2323
ConnectionStatus,
2424
DataChannelMessage,
2525
EventHandler,
26+
ReconnectEvent,
27+
ReconnectOutcome,
2628
TimingEvent,
2729
TranscriptEntry,
2830
)
@@ -59,6 +61,14 @@ def __init__(
5961
#: for callers driving an ICE restart themselves — see
6062
#: :mod:`streamcore.icerestart` for why the SDK cannot.
6163
self._etag: str = ""
64+
#: Credential that reattaches a redial to this conversation. Rotated by
65+
#: the server on every response, so it is single-use.
66+
self._resume_token: str = ""
67+
self._resume_status: str = ""
68+
#: Bumped by connect/disconnect so a redial scheduled by a dying peer
69+
#: connection abandons itself rather than fighting the new one.
70+
self._generation: int = 0
71+
self._user_track = None
6272
self._blackhole: MediaBlackhole | None = None
6373

6474
self._lock = Lock()
@@ -91,7 +101,26 @@ async def connect(self, user_track=None) -> None:
91101
microphone audio. If provided it will be added to the peer
92102
connection so the server receives audio from the user.
93103
"""
94-
self._set_status(ConnectionStatus.CONNECTING)
104+
# Remembered so a redial can rebuild the transport with the same audio
105+
# source. A fresh connect abandons any conversation being resumed.
106+
self._user_track = user_track
107+
self._resume_token = ""
108+
self._generation += 1
109+
await self._establish(resume_token="")
110+
111+
async def _establish(self, resume_token: str) -> None:
112+
"""Build a peer connection and complete WHIP signaling.
113+
114+
With a resume token the server reattaches this new transport to the
115+
conversation the previous one was having, so the history, the rolling
116+
summary and the agent's memory of the call all survive — see
117+
:mod:`streamcore.icerestart` for why Python recovers this way rather
118+
than with an ICE restart.
119+
"""
120+
self._set_status(
121+
ConnectionStatus.RECONNECTING if resume_token else ConnectionStatus.CONNECTING
122+
)
123+
user_track = self._user_track
95124

96125
try:
97126
ice_servers = [RTCIceServer(urls=url) for url in self.config.ice_servers]
@@ -132,18 +161,24 @@ def on_track(track):
132161
self.remote_track = track
133162
self._remote_track_ready.set()
134163

164+
generation = self._generation
165+
135166
@pc.on("connectionstatechange")
136167
async def on_connection_state_change():
137168
state = pc.connectionState
138169
if state == "connected":
139170
self._set_status(ConnectionStatus.CONNECTED)
140171
elif state in ("failed", "closed"):
141172
# aiortc has no "disconnected" state — it goes straight
142-
# from connected to failed — so unlike the other SDKs
143-
# there is no transient window to attempt an ICE restart
144-
# in. See streamcore.icerestart for why, and prefer one of
145-
# the other SDKs where mid-call network changes matter.
146-
self._set_status(ConnectionStatus.DISCONNECTED)
173+
# from connected to failed — so there is no transient
174+
# window to attempt an ICE restart in, and no ICE restart
175+
# primitive to use if there were. Recovery is therefore a
176+
# full redial carrying the resume token, which rebuilds the
177+
# transport but keeps the conversation.
178+
if state == "failed" and generation == self._generation:
179+
asyncio.ensure_future(self._reconnect(generation))
180+
else:
181+
self._set_status(ConnectionStatus.DISCONNECTED)
147182

148183
# Create offer and gather ICE candidates.
149184
offer = await pc.createOffer()
@@ -170,9 +205,13 @@ async def on_connection_state_change():
170205
self._last_token = token or ""
171206

172207
# WHIP exchange.
173-
result = await whip_offer(self.config.whip_endpoint, offer_sdp, token)
208+
result = await whip_offer(
209+
self.config.whip_endpoint, offer_sdp, token, resume_token
210+
)
174211
self._session_url = result.session_url
175212
self._etag = result.etag
213+
self._resume_token = result.resume_token
214+
self._resume_status = result.resume_status
176215

177216
answer = RTCSessionDescription(sdp=result.answer_sdp, type="answer")
178217
await pc.setRemoteDescription(answer)
@@ -184,8 +223,109 @@ async def on_connection_state_change():
184223
self.events.on_error(exc)
185224
raise
186225

226+
async def _reconnect(self, generation: int) -> None:
227+
"""Redial after a dropped connection, keeping the conversation.
228+
229+
aiortc cannot restart ICE, so the transport is rebuilt from scratch.
230+
What makes this a reconnection rather than a new call is the resume
231+
token: the server reattaches the fresh peer to the session it was
232+
already running, history intact and no repeated greeting.
233+
234+
The window is the server's ``session_grace_ms`` (30s by default) —
235+
after that the session is reaped and a redial genuinely does start
236+
over, which is reported as RECOVERED_WITHOUT_HISTORY rather than
237+
passed off as a full recovery.
238+
"""
239+
attempts = self.config.reconnect_attempts
240+
if attempts <= 0 or generation != self._generation:
241+
self._set_status(ConnectionStatus.DISCONNECTED)
242+
return
243+
244+
token = self._resume_token
245+
delay = self.config.reconnect_delay
246+
self._set_status(ConnectionStatus.RECONNECTING)
247+
248+
# The dead peer connection holds the microphone track and a socket;
249+
# drop it before building its replacement.
250+
await self._teardown_peer()
251+
252+
for attempt in range(1, attempts + 1):
253+
await asyncio.sleep(delay)
254+
delay *= 2
255+
256+
if generation != self._generation:
257+
return # connect() or disconnect() superseded this redial
258+
259+
self._emit_reconnect(attempt, attempts, ReconnectOutcome.ATTEMPTING)
260+
try:
261+
await self._establish(resume_token=token)
262+
except Exception as exc:
263+
if attempt == attempts:
264+
self._set_status(ConnectionStatus.DISCONNECTED)
265+
self._emit_reconnect(
266+
attempt, attempts, ReconnectOutcome.FAILED, exc
267+
)
268+
return
269+
logger.warning("Reconnect attempt %d failed: %s", attempt, exc)
270+
await self._teardown_peer()
271+
continue
272+
273+
resumed = self._resume_status == "resumed"
274+
self._emit_reconnect(
275+
attempt,
276+
attempts,
277+
ReconnectOutcome.RECOVERED
278+
if resumed
279+
else ReconnectOutcome.RECOVERED_WITHOUT_HISTORY,
280+
)
281+
if not resumed:
282+
logger.warning(
283+
"Reconnected, but the server could not resume the session "
284+
"(status=%r) — the agent has no memory of the earlier "
285+
"conversation",
286+
self._resume_status,
287+
)
288+
return
289+
290+
def _emit_reconnect(
291+
self,
292+
attempt: int,
293+
max_attempts: int,
294+
outcome: ReconnectOutcome,
295+
error: Exception | None = None,
296+
) -> None:
297+
if self.events.on_reconnect:
298+
self.events.on_reconnect(
299+
ReconnectEvent(
300+
attempt=attempt,
301+
max_attempts=max_attempts,
302+
outcome=outcome,
303+
error=error,
304+
)
305+
)
306+
307+
async def _teardown_peer(self) -> None:
308+
"""Close the peer connection and its audio track, leaving the
309+
session URL and resume token intact so a redial can still use them."""
310+
if self._sdk_track is not None:
311+
self._sdk_track.stop()
312+
self._sdk_track = None
313+
if self._pc is not None:
314+
pc, self._pc = self._pc, None
315+
try:
316+
await asyncio.wait_for(pc.close(), timeout=3)
317+
except Exception:
318+
pass
319+
self._remote_track_ready.clear()
320+
self._resampler = None
321+
187322
async def disconnect(self) -> None:
188323
"""Tear down the WebRTC connection and free resources."""
324+
# Abandons any redial in flight: it would otherwise resume a session
325+
# this call is about to DELETE.
326+
self._generation += 1
327+
self._resume_token = ""
328+
189329
# Stop SDK track first so aiortc's internal consumer unblocks.
190330
if self._sdk_track is not None:
191331
self._sdk_track.stop()
@@ -236,6 +376,11 @@ async def send_pcm(self, pcm: np.ndarray) -> None:
236376
Typically ``FRAME_SIZE`` (960) samples for a 20 ms frame.
237377
"""
238378
if self._sdk_track is None:
379+
if self._status == ConnectionStatus.RECONNECTING:
380+
# Mid-redial the track is being rebuilt. Audio recorded now has
381+
# nowhere to go and would be stale by the time it did, so drop
382+
# it rather than fail a caller who is doing nothing wrong.
383+
return
239384
raise RuntimeError(
240385
"send_pcm requires the built-in audio track; "
241386
"do not pass user_track to connect()"

‎src/streamcore/types.py‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,33 @@ class ConnectionStatus(str, Enum):
99
IDLE = "idle"
1010
CONNECTING = "connecting"
1111
CONNECTED = "connected"
12+
#: The transport is gone and the client is redialling with a resume token.
13+
#: The conversation is still alive on the server, so this is not terminal.
14+
RECONNECTING = "reconnecting"
1215
ERROR = "error"
1316
DISCONNECTED = "disconnected"
1417

1518

19+
class ReconnectOutcome(str, Enum):
20+
ATTEMPTING = "attempting"
21+
#: Reattached to the same server-side conversation.
22+
RECOVERED = "recovered"
23+
#: Reconnected, but the server could not resume — this is a fresh
24+
#: conversation and the agent has no memory of what came before.
25+
RECOVERED_WITHOUT_HISTORY = "recovered_without_history"
26+
FAILED = "failed"
27+
28+
29+
@dataclass
30+
class ReconnectEvent:
31+
"""Progress of the redial sequence after a dropped connection."""
32+
33+
attempt: int # 1-based
34+
max_attempts: int
35+
outcome: ReconnectOutcome
36+
error: Exception | None = None
37+
38+
1639
@dataclass
1740
class TranscriptEntry:
1841
role: str # "user" or "assistant"
@@ -55,6 +78,18 @@ class Config:
5578
default_factory=lambda: ["stun:stun.l.google.com:19302"]
5679
)
5780

81+
#: How many times to redial after a dropped connection. aiortc cannot
82+
#: perform an ICE restart, so recovery here means a fresh peer connection
83+
#: carrying the session's resume token — which keeps the *conversation*
84+
#: even though the transport is new. 0 disables automatic reconnection.
85+
reconnect_attempts: int = 3
86+
87+
#: Delay before the first redial, doubling for each retry. Unlike the ICE
88+
#: restart path in the other SDKs there is no ~25s deadline to fit inside:
89+
#: the server holds the conversation for ``server.session_grace_ms``
90+
#: (30s by default), so keep the total under that.
91+
reconnect_delay: float = 2.0
92+
5893

5994
@dataclass
6095
class EventHandler:
@@ -68,3 +103,7 @@ class EventHandler:
68103
on_timing: Callable[[TimingEvent], None] | None = None
69104
on_agent_state_change: Callable[[AgentState], None] | None = None
70105
on_data_channel_message: Callable[[DataChannelMessage], None] | None = None
106+
#: Called for each redial attempt and once when the outcome is known.
107+
#: Watch for RECOVERED_WITHOUT_HISTORY — the call works, but the agent has
108+
#: forgotten the conversation and your UI may want to say so.
109+
on_reconnect: Callable[[ReconnectEvent], None] | None = None

0 commit comments

Comments
 (0)