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()"
0 commit comments