File size: 45,303 Bytes
8ad8249
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddc4d15
 
8ad8249
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddc4d15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ad8249
 
 
 
 
 
 
ddc4d15
 
8ad8249
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddc4d15
 
 
 
8ad8249
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddc4d15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ad8249
 
 
 
 
 
 
 
 
 
ddc4d15
 
 
 
 
 
 
 
8ad8249
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddc4d15
 
 
 
8ad8249
 
ddc4d15
8ad8249
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddc4d15
8ad8249
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddc4d15
 
 
 
 
 
 
 
 
 
 
 
 
8ad8249
 
 
 
 
 
 
 
 
 
ddc4d15
8ad8249
 
 
 
 
 
 
 
 
ddc4d15
8ad8249
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddc4d15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ad8249
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddc4d15
 
8ad8249
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
"""Single-user duplex demo: independent receive, floor, thinker and TTS work."""
from __future__ import annotations

import ast
import asyncio
import base64
import hashlib
import hmac
import io
import json
import logging
import math
import operator
import re
import struct
import threading
import time
import wave
from collections import deque
from dataclasses import dataclass, field
from urllib.parse import urlsplit

import numpy as np
import aiohttp
from aiohttp import WSMsgType, web

from avatar_sink import AvatarSink

LOG = logging.getLogger(__name__)
RATE = 16000
ACCESS_COOKIE = '__Host-aiden_access'
LOGIN = '''<!doctype html><html><head><meta charset="utf-8"><meta name="viewport"
content="width=device-width,initial-scale=1"><title>Aiden · private demo</title></head>
<body style="max-width:36rem;margin:3rem auto;padding:1rem;font:1rem system-ui">
<h1>Aiden · live demo</h1><form method="post" action="/access">
<label>Access code <input type="password" name="code" required autofocus></label>
<button>Open demo</button></form></body></html>'''
PLAYBACK_TAIL = .45
HISTORY_TURNS = 24          # how many exchanges may be kept
HISTORY_CHARS = 24000       # ~6k tokens; the 4B window is far larger than this
ACK_WORD = r'(?:ok(?:ay)?|(?:m+\s*h+m+|m{2,})|uh\s*huh|yeah|yep|yup|right|sure|thanks|thank you|got it|I see)'
BACKCHANNEL = re.compile(rf'{ACK_WORD}(?:\s+{ACK_WORD})*', re.I)
STOP_REQUEST = re.compile(r'(?:stop|wait|hold on|one second|just a second)', re.I)
BLOCK = re.compile(r'<tool_call>\s*<function=(\w+)>\s*(.*?)\s*</function>\s*</tool_call>', re.S)
PARAM = re.compile(r'<parameter=(\w+)>\s*(.*?)\s*</parameter>', re.S)
WEATHER = re.compile(r'\b(?:weather|forecast|temperature\s+(?:in|for)|chance of rain|will it rain)\b', re.I)
WEATHER_FOLLOWUP = re.compile(
    r'^\s*(?:and (?:in|for)|what about|how about|no[,.]?\s+|ok(?:ay)?[,.]?\s+but\s+)\b', re.I)
STORE_RETURNS = re.compile(
    r'\b(?:returns?|refunds?)\s+(?:policy|rules|window|period)|'
    r'\b(?:store|product|laptop)\s+returns?\b|\b(?:can|may|how (?:do|can)) I return\b|'
    r'\breturns?\s+for\s+(?:a |the )?(?:laptops?|products?|orders?)\b', re.I)
ARITHMETIC = re.compile(r'\b(?:calculate|compute)\b|\d\s*(?:[%+*/×÷−=-]|plus\b|minus\b|times\b)|'
                        r'\b(?:tip|total|percent)\b.*\d|\d.*\b(?:tip|total|percent)\b', re.I)
WEB_PREFIX = re.compile(r'^\s*(?:please\s+)?(?:/search\s+|(?:search|check) (?:the )?(?:web|internet)\b|'
                        r'search online\b|look up online\b|find online\b|google\b)\s*(?:for\s+)?', re.I)
SEARCH_VERB = re.compile(r'\b(?:search|look\s*up|find|check|google|browse)\b', re.I)
SEARCH_NOUN = re.compile(r'\b(?:web|net|internet|online)\b', re.I)
# A bare imperative search verb is already an explicit request: "search up the movie
# obsession", "search for X", "look up X", "google X". These used to need a web noun,
# and when the noun was missing no tool was offered, so the no-tool prompt made Aiden
# answer "I can't search". Missing the verb is far worse than an extra search.
SEARCH_IMPERATIVE = re.compile(
    r'^\s*(?:(?:ok(?:ay)?|now|hey|please|so|and|but|um+|uh+)[,.]?\s+)*'
    r'(?:search|look\s*up|google|browse|find\s+out)\b', re.I)
# ...but "search results", "search history" name a thing, they are not requests.
SEARCH_META = re.compile(r'^\s*(?:results?|history|bar|box|engine|settings?|terms?)\b', re.I)
SEARCH_FILLER = re.compile(r'^\s*(?:(?:up|around|for|about|on|at|of|the|a|an|'
                           r'web|net|internet|online|please)\s+)+', re.I)
# "and ethereum?" names a new subject and still needs a fresh lookup; without this
# the model reuses the previous turn's number and calls it the new subject.
FOLLOWUP = re.compile(r'^\s*(?:and|what\s+about|how\s+about|also|plus)\b', re.I)
# Questions about the conversation itself must never spend a search.
META_TALK = re.compile(r'\b(?:what\s+did\s+i\s+(?:ask|say)|what\s+am\s+i\s+asking|'
                       r'my\s+(?:first|last|previous|original)\s+(?:question|request)|'
                       r'you\s+(?:said|told|mentioned))\b', re.I)
# A question about a value that changes (score, race, price) needs the web even
# when the user does not say "search" or name a fresh-fact noun.
LIVE_QUESTION = re.compile(r'^\s*(?:(?:ok(?:ay)?|so|and|but|now|hey)[,.]?\s+)*'
                           r'(?:who|what|when|where|which|how|is|are|was|were|did|does|do|'
                           r'will|would|can|could|should)\b', re.I)
TIME_DEICTIC = re.compile(r'\b(?:today|tonight|tomorrow|yesterday|'
                          r'last\s+(?:night|week|weekend|month|season)|'
                          r'this\s+(?:week|weekend|month|year|season)|latest|newest|'
                          r'current(?:ly)?|right\s+now|at\s+the\s+moment|'
                          r'recent(?:ly)?|upcoming|so\s+far)\b', re.I)
# Words that make a 1-3 word utterance a reaction, not a subject to look up.
FILLER_WORDS = frozenset('''that this it its is was are were be the a an great good nice
cool ok okay right yes no thanks thank you wow amazing interesting really sure ha haha
hmm mm oh ah'''.split())
# Words that carry no subject of their own: "just say what the current price is" is the
# previous question again, and searching the literal sentence returns dictionary pages.
ELLIPTICAL = frozenset('''just please now ok okay so and but say tell me us give show what is are
was were the a an current currently exactly actually again number figure amount price cost
value rate it its that this there about more'''.split())
# Leading conversational scaffolding stripped from a query before it reaches Tavily.
QUERY_LEAD = re.compile(
    r'^(?:(?:ok(?:ay)?|now|so|and|hey|please|um+|uh+|well)[,.]?\s+|'
    r'tell\s+me\s+(?:about|of|the)?\s*|what\s+about\s+|how\s+about\s+|'
    r'(?:do|can|could|would|will)\s+you\s+(?:tell|know|find)\s+|'
    r'i\s+(?:want|need)\s+to\s+know\s+(?:about\s+)?)+', re.I)
FRESH_EXTRA = re.compile(r'\b(?:stock|share)\s+prices?\b|\bstocks?\b|\bshare\s+prices?\b|'
                         r'\bexchange\s+rates?\b|\bworld\s+cup\b|'
                         r'\bprices?\s+(?:of|for)\b|\bhow\s+much\s+is\b|'
                         r'\belections?\b|\bbreaking\s+news\b|\bcurrent\s+(?:price|value)\b|'
                         r'\b(?:dow\s+jones|nasdaq|s&p\s*500)\b', re.I)
FRESH_INFO = re.compile(r'\b(?:latest (?:news|updates?|price|version)|current (?:price|exchange rate|weather)|'
                        r'(?:price|exchange rate|news) (?:now|today)|announced today)\b', re.I)
REFERENCE = re.compile(r'\b(?:it|that|this|there|its|their|the same|both)\b', re.I)
NO_WEB = re.compile(r"\b(?:(?:do not|don['’]t|no)\s+(?:new\s+)?(?:search|look up|use the web)|"
                    r'without (?:searching|looking it up))\b', re.I)


def utterance_text(text):
    words = ' '.join(re.findall(r"[^\W_]+(?:['’][^\W_]+)?", text.lower()))
    return re.sub(r'\bo k\b', 'ok', words)


def is_backchannel(text):
    return BACKCHANNEL.fullmatch(utterance_text(text)) is not None


def confirms_interruption(text):
    """Require lexical evidence before turning a speculative YIELD into a stop."""
    normalized = utterance_text(text)
    if STOP_REQUEST.fullmatch(normalized):
        return True
    if not normalized or BACKCHANNEL.fullmatch(normalized):
        return False
    content = re.sub(rf'^(?:{ACK_WORD}\s+)+', '', normalized, flags=re.I)
    return len(content.split()) >= 2 and content.split()[-1] not in ('but', 'and', 'so')


def _norm_words(text):
    return ' '.join(re.findall(r"[a-z0-9']+", text.lower()))


def split_lead(text, max_words=8):
    """Short first clause: TTS cost scales with audio length, so a ~1 s lead-in
    gets the avatar moving while the rest of the sentence synthesises."""
    words = text.split()
    if len(words) <= max_words:
        return text, ''
    cut = text.find(',')
    if 0 < cut < len(text) - 1 and len(text[:cut].split()) <= max_words:
        return text[:cut + 1].strip(), text[cut + 1:].strip()
    return ' '.join(words[:max_words]), ' '.join(words[max_words:])


def clean_query(text, limit=256):
    """Strip spoken scaffolding so the search box gets the topic, not the sentence."""
    query = text.strip(' .,:?!')
    for _ in range(4):
        stripped = QUERY_LEAD.sub('', query, count=1).strip(' .,:?!')
        if stripped == query:
            break
        query = stripped
    return query[:limit].strip()


def _previous_turn_used_tool(history):
    """True when the most recent turn already ran a tool."""
    for m in reversed(history):
        if m.get('role') == 'tool':
            return True
        if m.get('role') == 'user':
            return False
    return False


def _previous_query(history):
    """The query string of the last search, so a pronoun can be resolved against it."""
    for m in reversed(history):
        if m.get('role') == 'tool':
            try:
                data = json.loads(m.get('content') or '{}')
            except ValueError:
                continue
            query = data.get('query')
            if isinstance(query, str) and query:
                return query[:115]
    return ''


def _topic_query(text, history):
    query = clean_query(text)
    if not query:
        return ''
    if REFERENCE.search(query):
        topic = _previous_query(history)
        if topic and topic.lower() not in query.lower():
            return f'{query} — topic: {topic}'[:256]
    return query[:256]


def _subject_words(text):
    return [w for w in (x.strip('.,!?;:').lower() for x in text.split())
            if w and w not in ELLIPTICAL]


def followup_search(text, history):
    """A short follow-up inherits the previous lookup instead of reusing its numbers.

    "the price of bitcoin" then "and ethereum?" must search ethereum. Otherwise the
    model answers with bitcoin's price and presents it as ethereum.
    """
    if not history or not _previous_turn_used_tool(history):
        return None
    if WEATHER.search(text) or META_TALK.search(text) or NO_WEB.search(text):
        return None
    if not _subject_words(text):
        # No subject of its own: repeat the previous lookup instead of searching
        # "what is the current price" and answering from dictionary pages.
        previous = _previous_query(history)
        return previous[:256] if previous else None
    words = text.split()
    if not (FOLLOWUP.match(text) or len(words) <= 3
            or (REFERENCE.search(text) and len(words) <= 8)):
        return None
    if len(words) <= 3 and all(w.strip('.,!?;:').lower() in FILLER_WORDS for w in words):
        return None
    query = _topic_query(text, history)
    if not query or SEARCH_META.match(query):
        return None
    return query


def requested_search(text, history=()):
    """Return a query for explicit searches and narrowly recognized fresh facts.

    Deliberately tolerant about phrasing: people say "Now, we'll search the web
    for X", "search the net for X", "look up X online", "search up X". Missing the
    verb phrase is worse than an extra search, because the fallback prompt then
    refuses the request outright.
    """
    if NO_WEB.search(text):
        return None
    # Before any keyword rule: an utterance with no subject of its own ("just say what
    # the current price is") is the previous question again, and must reuse its query
    # instead of sending the literal sentence to the search engine.
    if (history and _previous_turn_used_tool(history) and not _subject_words(text)
            and not WEATHER.search(text) and not META_TALK.search(text)):
        previous = _previous_query(history)
        if previous:
            return previous[:256]
    verb = SEARCH_VERB.search(text)
    if verb and SEARCH_NOUN.search(text[verb.end():]):
        tail = text[verb.end():]
        m = re.search(r'\bfor\b\s*(.+)', tail, re.I)
        query = m.group(1) if m else SEARCH_NOUN.sub(' ', tail)
        query = query.strip(' .,:?!')
        if not query:
            query = next((x['content'] for x in reversed(history)
                          if x['role'] == 'user'), '')
        return query[:256].strip() or None
    bare = SEARCH_IMPERATIVE.match(text)
    if bare:
        rest = text[bare.end():].strip(' .,:?!')
        if rest and not SEARCH_META.match(rest):
            query = SEARCH_FILLER.sub('', rest).strip(' .,:?!')
            if query:
                return clean_query(query)
    if FRESH_EXTRA.search(text) or FRESH_INFO.search(text):
        # "Now tell me about stocks." is a request for current facts but carries no
        # URL-shaped query, so it still needs the pronoun/topic resolution below.
        query = clean_query(text)
    else:
        if (LIVE_QUESTION.match(text) and TIME_DEICTIC.search(text)
                and not META_TALK.search(text) and not WEATHER.search(text)):
            # "What's the latest NBA score?" must search, not produce a plausible number.
            return _topic_query(text, history) or None
        match = WEB_PREFIX.match(text)
        if not match:
            return followup_search(text, history)
        query = clean_query(text[match.end():].strip(' :?.'))
    if REFERENCE.search(query) and len(query.split()) <= 8:
        # Use only the immediately preceding user topic, never the whole history.
        topic = next((m['content'] for m in reversed(history) if m['role'] == 'user'), '')
        if topic and not WEB_PREFIX.fullmatch(topic):
            query = f'{query} — topic: {clean_query(topic)[:115]}'
    return query[:256].strip() or None


def tools_for_turn(tools, text, history=()):
    """Offer only native tools relevant to the latest utterance."""
    if requested_search(text, history):
        web = [t for t in tools if t['function']['name'] == 'web_search']
        if web:
            return web
    wanted = set()
    previous = next((m['content'] for m in reversed(history) if m['role'] == 'user'), '')
    if WEATHER.search(text) or (WEATHER.search(previous) and WEATHER_FOLLOWUP.match(text)
                                and len(text.split()) <= 7 and not STORE_RETURNS.search(text)
                                and not ARITHMETIC.search(text)):
        wanted.add('get_weather')
    if STORE_RETURNS.search(text):
        wanted.add('search_local_docs')
    if ARITHMETIC.search(text):
        wanted.add('calculate')
    return [t for t in tools if t['function']['name'] in wanted]


class PublicSpeech:
    """Never send markup or reasoning to TTS, even across token boundaries."""

    def __init__(self):
        self.offset = 0

    @staticmethod
    def public(raw):
        raw = re.sub(r'^\s*<think>.*?</think>\s*', '', raw, flags=re.S)
        return raw.split('<', 1)[0]

    @staticmethod
    def in_tool(raw):
        return raw.rfind('<tool_call>') > raw.rfind('</tool_call>')

    def feed(self, raw, final=False):
        text = self.public(raw)
        out = []
        while rest := text[self.offset:]:
            # Wait for following whitespace so decimal points do not split numbers.
            boundary = re.search(r'[.!?](?=\s)|[,;](?=\s)', rest)
            end = boundary.end() if boundary and boundary.end() >= 18 else 0
            if not end:
                phrase = re.search(r'[.!?](?=\s)', rest[18:])
                end = 18 + phrase.end() if phrase else 0
            if not end and len(rest) > 75:
                end = rest.rfind(' ', 24, 76)
            if end <= 0 and (final or text != raw and '<tool_call>' in raw):
                end = len(rest)
            if end <= 0:
                break
            if rest[:end].strip():
                out.append(rest[:end].strip())
            self.offset += end
        return out


def tool_calls(raw, tools):
    schema = {t['function']['name']: t['function']['parameters'] for t in tools}
    tail = re.sub(r'^\s*<think>.*?</think>\s*', '', raw, flags=re.S)
    if '<' not in tail:
        return []
    tail = tail[tail.index('<'):].strip()
    calls = []
    while tail:
        match = BLOCK.match(tail)
        if not match:
            raise ValueError('Incomplete or invalid tool block; nothing executed')
        name, body = match.groups()
        args = {}
        while body:
            arg = PARAM.match(body)
            if not arg or arg[1] in args or not 0 < len(arg[2].strip()) <= 256 or '<' in arg[2]:
                raise ValueError('Invalid tool arguments; nothing executed')
            args[arg[1]] = arg[2].strip()
            body = body[arg.end():].strip()
        spec = schema.get(name, {})
        if name == 'get_weather' and 'date' in spec.get('properties', {}):
            args.setdefault('date', 'today')
        if not spec or not set(spec.get('required', ())) <= args.keys() <= spec['properties'].keys():
            raise ValueError('Unknown tool or invalid arguments; nothing executed')
        calls.append({'type': 'function', 'function': {'name': name, 'arguments': args}})
        if len(calls) > 4:
            raise ValueError('Too many calls; nothing executed')
        tail = tail[match.end():].strip()
    return calls


def demo_tool(call):
    name, args = call['function']['name'], call['function']['arguments']
    if name == 'get_weather':
        k = hashlib.sha256(args['city'].lower().encode()).digest()[0]
        return {'status': 'ok', 'mock': True, **args, 'condition': 'partly cloudy',
                'temperature_c': 10 + k % 15, 'precipitation_chance_percent': 20 + k % 20,
                'wind_kph': 8 + k % 12}
    if name == 'search_local_docs':
        if not STORE_RETURNS.search(args['query']):
            return {'status': 'no_match', 'mock': True,
                    'message': 'No matching store-return document.'}
        return {'status': 'ok', 'mock': True, **args,
                'policy': 'Returns are accepted within 30 days with the original receipt.'}
    if name == 'calculate':
        ops = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul,
               ast.Div: operator.truediv, ast.Mod: operator.mod, ast.Pow: operator.pow}

        def number(node, depth=0):
            if depth > 12:
                raise ValueError('expression too deep')
            if isinstance(node, ast.Constant) and type(node.value) in (int, float):
                v = float(node.value)
            elif isinstance(node, ast.UnaryOp) and type(node.op) in (ast.UAdd, ast.USub):
                v = number(node.operand, depth + 1) * (-1 if isinstance(node.op, ast.USub) else 1)
            elif isinstance(node, ast.BinOp) and type(node.op) in ops:
                x, y = number(node.left, depth + 1), number(node.right, depth + 1)
                if isinstance(node.op, ast.Pow) and (abs(y) > 10 or x < 0 and not y.is_integer()):
                    raise ValueError('power out of range')
                v = ops[type(node.op)](x, y)
            else:
                raise ValueError('not arithmetic')
            if not math.isfinite(v) or abs(v) > 1e15:
                raise ValueError('number out of range')
            return v

        try:
            expr = args['expression'].replace('×', '*').replace('÷', '/')
            result = number(ast.parse(expr, mode='eval').body)
            return {'status': 'ok', 'expression': args['expression'], 'result': result}
        except (ValueError, SyntaxError, ArithmeticError):
            return {'status': 'error', 'message': 'Unsupported arithmetic expression.'}
    return {'status': 'error', 'message': 'Tool not available in this demo.'}


def audio_payload(pcm, op):
    f = io.BytesIO()
    with wave.open(f, 'wb') as w:
        w.setparams((1, 2, RATE, 0, 'NONE', 'not compressed'))
        w.writeframes(pcm)
    return {'op': op, 'wav_b64': base64.b64encode(f.getvalue()).decode()}


@dataclass
class Prompt:
    events: list
    history: list = field(default_factory=list)
    played: str = ''
    tools_ctx: list = field(default_factory=list)
    available_tools: list | None = None


@dataclass
class Reply:
    epoch: int
    text: str
    cancelled: threading.Event = field(default_factory=threading.Event)
    speech: asyncio.Queue = field(default_factory=asyncio.Queue)
    chunks: dict = field(default_factory=dict)
    heard: dict = field(default_factory=dict)
    playing: set = field(default_factory=set)
    playback: asyncio.Event = field(default_factory=asyncio.Event)
    messages: list = field(default_factory=list)
    holding: bool = False
    generated: bool = False
    task: asyncio.Task | None = None

    @property
    def played(self):
        return ' '.join(self.heard[k] for k in sorted(self.heard))


@dataclass
class MicTurn:
    onset_at: float
    overlap: Reply | None
    prosody_control: str | None = None
    checks: int = 0
    floor_job: asyncio.Task | None = None


class Connection:
    def __init__(self, demo, ws):
        self.demo, self.ws = demo, ws
        self.history = deque()
        self.epoch, self.reply = 0, None
        self.pre = deque(maxlen=6)
        self.pcm, self.quiet, self.voiced = bytearray(), 0, 0
        self.mic: MicTurn | None = None
        self.recent_playback: tuple[float, Reply] | None = None
        self.input_jobs = set()
        self.input_clear = asyncio.Event()
        self.input_clear.set()
        self.end_lock = asyncio.Lock()
        self.send_lock = asyncio.Lock()
        self.asr_revision = 0
        self.finishing = set()

    async def send(self, kind, **payload):
        if not self.ws.closed:
            async with self.send_lock:
                await self.ws.send_json({'type': kind, **payload})

    async def send_raw(self, data: bytes):
        if not self.ws.closed:
            async with self.send_lock:
                await self.ws.send_bytes(data)

    def spawn(self, coro):
        async def observe():
            try:
                await coro
            except asyncio.CancelledError:
                raise
            except Exception:
                LOG.exception('Live demo task failed')
                await self.send('error', message='A live worker failed. Check the server log.')
        task = asyncio.create_task(observe())
        self.finishing.add(task)
        task.add_done_callback(self.finishing.discard)
        return task

    async def cancel(self, reason):
        r = self.reply
        if not r:
            return
        if r.playing:
            self.recent_playback = (time.monotonic(), r)
        r.cancelled.set()
        if r.task:
            r.task.cancel()
        self.history.append([{'role': 'user', 'content': r.text.replace('<', '‹').replace('>', '›')}] +
                            ([{'role': 'assistant', 'content': r.played}] if r.played else []))
        self.reply = None
        await self.send('cancel', epoch=r.epoch, reason=reason)
        await self.send('state', state='listening')

    async def begin(self, text, words=(), *, reason='new request'):
        await self.cancel(reason)
        self.epoch += 1
        r = self.reply = Reply(self.epoch, text)
        await self.send('state', state='thinking', epoch=r.epoch)
        events = [{'text': w['w'], 'vec': w.get('vec_b64')} for w in words]
        r.task = self.spawn(self.generate(r, events or [{'text': text}]))

    def history_messages(self):
        """Most recent turns that fit the budget, oldest dropped first.

        A fixed 6-turn deque made the model forget the start of any real
        conversation. The window is large; this cap is what should bound it.
        """
        turns, size = [], 0
        for turn in reversed(self.history):
            tsize = sum(len(m.get('content') or '') for m in turn)
            if turns and (len(turns) >= HISTORY_TURNS or size + tsize > HISTORY_CHARS):
                break
            turns.append(turn)
            size += tsize
        return [m for turn in reversed(turns) for m in turn]

    async def generate(self, r, events):
        loop = asyncio.get_running_loop()
        queue = asyncio.Queue()

        def emit(kind, **payload):
            loop.call_soon_threadsafe(queue.put_nowait, (kind, payload))

        audio = self.spawn(self.speak(r))
        public = []
        ack_norm = ''
        seen = set()
        history = self.history_messages()
        available = tools_for_turn(self.demo.brain.tools, r.text, history)
        try:
            search_query = requested_search(r.text, history)
            if search_query and any(t['function']['name'] == 'web_search' for t in available):
                call = {'type': 'function', 'function': {'name': 'web_search',
                                                         'arguments': {'query': search_query}}}
                ack = 'I’ll check the web.'
                ack_norm = _norm_words(ack)
                public.append(ack)
                r.speech.put_nowait(ack)
                results = await self.resolve_tools(r, [call])
                if results is None:
                    return
                available = []  # summarize the result; never start a second search here
                if results[0]['status'] != 'ok':
                    notice = 'I couldn’t verify that with web search right now.'
                    public.append(notice)
                    r.speech.put_nowait(notice)
                    await self.complete(r, audio, public)
                    return
            for attempt in range(3):
                prompt = Prompt(events, history, tools_ctx=list(r.messages), available_tools=available)

                async def inference():
                    try:
                        return await asyncio.to_thread(self.demo.brain.turn, prompt, emit, r.cancelled)
                    finally:
                        queue.put_nowait((None, {}))

                task = asyncio.create_task(inference())
                try:
                    while True:
                        kind, payload = await queue.get()
                        if kind is None:
                            break
                        if kind == 'sentence':
                            text = payload['text']
                            if not public and self.demo.avatar:
                                head, tail = split_lead(text)
                                if tail:
                                    r.speech.put_nowait(head)
                                    r.speech.put_nowait(tail)
                                    public.append(text)
                                    continue
                            public.append(text)
                            r.speech.put_nowait(text)
                        else:
                            await self.send(kind, epoch=r.epoch, **payload)
                    raw = await task
                    print(f'[turn {r.epoch}] inference done chars={len(raw)}', flush=True)
                finally:
                    if not task.done():
                        task.cancel()
                try:
                    calls = tool_calls(raw, available)
                except ValueError as exc:
                    await self.send('error', message=str(exc))
                    message = 'I couldn’t complete that lookup. Could you rephrase the request?'
                    public.append(message)
                    r.speech.put_nowait(message)
                    break
                if not calls:
                    break
                keys = [json.dumps(c, sort_keys=True) for c in calls]
                if attempt == 2 or len(set(keys)) != len(keys) or seen.intersection(keys):
                    await self.send('error', message='Repeated tool call suppressed.')
                    break
                seen.update(keys)
                if await self.resolve_tools(r, calls) is None:
                    return
                if any(c['function']['name'] == 'get_weather' for c in calls):
                    notice = 'This is a demo forecast, not live weather.'
                    public.append(notice)
                    r.speech.put_nowait(notice)
            print(f'[turn {r.epoch}] complete', flush=True)
            await self.complete(r, audio, public)
        finally:
            audio.cancel()

    async def resolve_tools(self, r, calls):
        r.holding = True
        await self.send('state', state='hold', epoch=r.epoch)
        for call in calls:
            f = call['function']
            await self.send('tool', stage='pending', name=f['name'], args=f['arguments'], epoch=r.epoch)

        async def run(call):
            f = call['function']
            if f['name'] == 'web_search' and self.demo.web_search:
                return await self.demo.web_search(f['arguments']['query'])
            await asyncio.sleep(self.demo.tool_delay)
            return demo_tool(call)

        results = await asyncio.gather(*(run(c) for c in calls))
        # If user audio is being resolved, do not let an old result race it.
        await self.input_clear.wait()
        if self.reply is not r:
            return None
        r.messages.append({'role': 'assistant', 'content': r.played if not r.messages else '',
                           'tool_calls': calls})
        for call, result in zip(calls, results):
            name = call['function']['name']
            r.messages.append({'role': 'tool', 'content': json.dumps(result, ensure_ascii=False)})
            await self.send('tool', stage='ready', name=name, result=result, epoch=r.epoch)
        r.holding = False
        await self.send('state', state='thinking', epoch=r.epoch)
        return results

    async def complete(self, r, audio, public):
        print(f'[complete {r.epoch}] sentinel, awaiting audio', flush=True)
        r.speech.put_nowait(None)
        await audio
        print(f'[complete {r.epoch}] audio done sentences={len(r.chunks)} heard={len(r.heard)}', flush=True)
        if self.reply is r:
            r.generated = True
            await self.send('reply', text=' '.join(public), epoch=r.epoch)
            # The avatar keeps emitting frames after the text is done; the UI must
            # not wait for the frame clock to accept input again.
            await self.send('state', state='listening')
            await self.finish(r)

    async def speak(self, r):
        done = False
        while not done:
            while not self.demo.avatar and len(r.chunks) - len(r.heard) >= 2:
                # The avatar's own PCM return stream is the pacing clock in avatar
                # mode; only the browser-audio path needs this client-ack gate.
                r.playback.clear()
                try:
                    await asyncio.wait_for(r.playback.wait(), 10)
                except asyncio.TimeoutError:
                    # A client that never acknowledges (headless test, flaky tab)
                    # must degrade, not kill the turn: assume the oldest clause played.
                    for seq in sorted(r.chunks):
                        if seq not in r.heard:
                            r.heard[seq] = r.chunks[seq]
                            break
                    r.playback.set()
            # Serial synthesis is measurably faster than the model's list path
            # (4.6 s vs 2.3 s for the first sentence), so one clause at a time.
            batch = []
            item = await r.speech.get()
            if item is None:
                done = True
            else:
                batch.append(item)
            if not batch:
                break
            # Two clauses per synthesis call: the TTS model runs at ~1x real time
            # per sentence, so batching is what lets it feed ahead of playback.
            result = await self.demo.tts.call({'op': 'tts', 'texts': batch})
            if self.reply is not r:
                return
            audios = result.get('audios') or [{
                'audio_b64': result['audio_b64'], 'dur': result.get('dur')}]
            for text, audio in zip(batch, audios):
                seq = len(r.chunks) + 1
                r.chunks[seq] = text
                if self.demo.avatar:
                    await self.demo.avatar.speak_wav(audio['audio_b64'], r.epoch, seq)
                else:
                    await self.send('audio', epoch=r.epoch, seq=seq, text=text,
                                    b64=audio['audio_b64'], ms=result.get('ms'),
                                    dur=audio.get('dur'))
            print(f'[speak {r.epoch}] batch={len(batch)} tts={result.get("ms")}ms', flush=True)
        if self.demo.avatar:
            await self.demo.avatar.end_reply()
            print(f'[speak {r.epoch}] end_reply done', flush=True)

    async def mark_played(self, seq):
        r = self.reply
        if r and seq in r.chunks and seq not in r.heard:
            r.heard[seq] = r.chunks[seq]
            r.playback.set()
            await self.finish(r)

    async def finish(self, r):
        if self.reply is r and r.generated and len(r.chunks) == len(r.heard):
            turn = [{'role': 'user', 'content': r.text.replace('<', '‹').replace('>', '›')}]
            # The final played transcript already contains the audible preamble.
            turn.extend({**m, 'content': ''} if m.get('tool_calls') else m for m in r.messages)
            if r.played:
                turn.append({'role': 'assistant', 'content': r.played})
            self.history.append(turn)
            self.reply = None
            await self.send('state', state='listening')

    def overlap_at(self, now):
        r = self.reply
        # Keep the context during synthesis gaps and between queued audio chunks.
        if r and (r.holding or r.chunks):
            return r
        if self.recent_playback and now - self.recent_playback[0] <= PLAYBACK_TAIL:
            return self.recent_playback[1]
        return None

    def pcm_frame(self, pcm):
        if not 0 < len(pcm) <= 8192 or len(pcm) % 2:
            return
        x = np.frombuffer(pcm, dtype='<i2').astype(np.float32)
        voiced = np.sqrt(np.mean(x * x)) > 360
        if not self.pcm and not voiced:
            self.pre.append(pcm)
            return
        if not self.pcm:
            self.pcm.extend(b''.join(self.pre))
            self.pre.clear()
            at = time.monotonic()
            self.mic = MicTurn(at, self.overlap_at(at))
            self.input_clear.clear()
        mic = self.mic
        assert mic is not None
        self.pcm.extend(pcm)
        self.voiced += len(x) if voiced else 0
        self.quiet = 0 if voiced else self.quiet + len(x)
        if (voiced and mic.overlap and self.reply is mic.overlap and mic.checks < 2
                and self.voiced >= (3200, 9600)[mic.checks]
                and (not mic.floor_job or mic.floor_job.done())):
            mic.checks += 1
            mic.floor_job = self.spawn(self.floor(mic, bytes(self.pcm)[-25600:], mic.checks == 2))
        if self.quiet >= int(.56 * RATE) or len(self.pcm) >= 28 * RATE:
            self.endpoint()

    async def floor(self, mic, pcm, confirmed):
        r = mic.overlap
        if not r or self.mic is not mic or self.reply is not r:
            return
        v = (await self.demo.input.call(audio_payload(pcm, 'onset')))['vec']
        if not v or self.mic is not mic or self.reply is not r:
            return
        ctrl, _ = await asyncio.to_thread(self.demo.brain.decide,
                                          Prompt([{'vec': v}], played=r.played))
        if self.mic is not mic or self.reply is not r:
            return
        mic.prosody_control = ctrl
        await self.send('floor', control=ctrl, source='prosody', provisional=True,
                        epoch=r.epoch, ms=round((time.monotonic()-mic.onset_at)*1000))
        if ctrl == '<|yield|>' and confirmed and self.mic is mic and self.reply is r:
            partial = await self.demo.input.call(audio_payload(pcm, 'partial'))
            if self.mic is mic and self.reply is r and confirms_interruption(partial.get('text', '')):
                await self.send('floor', control='<|yield|>', source='confirmed interruption',
                                epoch=r.epoch, ms=round((time.monotonic()-mic.onset_at)*1000))
                await self.cancel('voice interruption')

    def endpoint(self):
        pcm, mic, voice = bytes(self.pcm), self.mic, self.voiced
        self.pcm.clear()
        self.voiced = self.quiet = 0
        self.mic = None
        if mic is not None and voice >= .11 * RATE:
            task = self.spawn(self.transcribe(pcm, mic, self.asr_revision))
            self.input_jobs.add(task)
            task.add_done_callback(self.input_done)
        else:
            self.input_done(None)

    def input_done(self, task):
        self.input_jobs.discard(task)
        if not self.pcm and not self.input_jobs:
            self.input_clear.set()

    @staticmethod
    def _looks_like_echo(text, r):
        """Ignore the mic hearing Aiden: words already in his own output.

        Speaker bleed arrives as one or two half-recognised words, so a short
        transcript must be entirely his, while a longer one only needs half. The
        flat 0.6 threshold let a two-word echo become a "voice interruption".
        """
        words = re.findall(r"[a-z0-9']+", text.lower())
        if not words:
            return False
        own = set(re.findall(r"[a-z0-9']+", ' '.join(r.chunks.values()).lower()))
        if not own:
            return False
        hit = sum(1 for w in words if w in own)
        if len(words) <= 2:
            return hit == len(words)
        return hit / len(words) >= 0.5

    async def transcribe(self, pcm, mic, revision):
        async with self.end_lock:
            if revision != self.asr_revision:
                return
            res = await self.demo.input.call(audio_payload(pcm, 'asr'))
            text = res['text'].strip()
            if not text or revision != self.asr_revision:
                return
            overlap = mic.overlap
            if overlap and self._looks_like_echo(text, overlap):
                await self.send('floor', control='<|continue|>', source='echo of own speech',
                                text=text, epoch=overlap.epoch)
                return
            if overlap and is_backchannel(text):
                await self.send('floor', control='<|continue|>', source='acknowledgment only',
                                epoch=overlap.epoch, prosody_control=mic.prosody_control,
                                ms=round((time.monotonic()-mic.onset_at)*1000), asr_ms=res.get('ms'))
                return
            if overlap and STOP_REQUEST.fullmatch(utterance_text(text)):
                if self.reply is overlap:
                    await self.cancel('voice stop request')
                return
            if overlap and self.reply is overlap:
                await self.send('floor', control='<|yield|>', source='finalized spoken request',
                                epoch=overlap.epoch, prosody_control=mic.prosody_control,
                                ms=round((time.monotonic()-mic.onset_at)*1000))
            await self.send('user', text=text, asr_ms=res.get('ms'))
            await self.begin(text, res.get('words') or [],
                             reason='voice interruption' if overlap else 'new request')

    async def message(self, data):
        kind = data.get('type')
        r = self.reply
        if kind in ('stop', 'text'):
            self.asr_revision += 1
            self.pcm.clear()
            self.mic = None
            self.pre.clear()
            self.voiced = self.quiet = 0
            self.input_done(None)
        if kind == 'stop':
            await self.cancel('Stop button')
        elif kind == 'text' and isinstance(data.get('text'), str):
            text = data['text'][:1500].strip()
            if text:
                await self.begin(text)
        elif kind in ('playing', 'played') and r and data.get('epoch') == r.epoch:
            seq = data.get('seq')
            if type(seq) is int and seq in r.chunks:
                if kind == 'playing':
                    r.playing.add(seq)
                    if self.mic and not self.mic.overlap:
                        self.mic.overlap = r
                elif seq not in r.heard:
                    r.playing.discard(seq)
                    r.heard[seq] = r.chunks[seq]
                    self.recent_playback = (time.monotonic(), r)
                    r.playback.set()
                    await self.finish(r)


class Demo:
    def __init__(self, page, ckpt, tool_delay, *, public_origin=None, access_code=None,
                 web_search=None, avatar_origin=None):
        self.page, self.ckpt, self.tool_delay = page, ckpt, tool_delay
        self.connection = None
        self.public_origin = public_origin
        self.access_code = access_code
        self.web_search = web_search
        self.session_key = (hmac.new(access_code.encode(), b'aiden-demo-cookie-v1', 'sha256').hexdigest()
                            if access_code else None)
        self.avatar = (AvatarSink(avatar_origin, self._avatar_relay, self._avatar_played)
                       if avatar_origin else None)

    async def _avatar_relay(self, packet, epoch):
        conn = self.connection
        if conn is None:
            return
        try:
            await conn.send_raw(struct.pack('<4sI', b'ADAV', epoch) + packet)
        except Exception as exc:
            LOG.warning('avatar relay stopped: %r', exc)

    async def _avatar_played(self, seq):
        conn = self.connection
        if conn:
            await conn.mark_played(seq)

    def authorized(self, request):
        return self.session_key is None or hmac.compare_digest(
            request.cookies.get(ACCESS_COOKIE, '').encode(), self.session_key.encode())

    def valid_origin(self, request):
        origin = request.headers.get('Origin')
        if self.public_origin:
            return origin == self.public_origin
        return not origin or urlsplit(origin).netloc == request.host

    async def health(self, _request):
        ready = all(not w.reader.done() for w in (self.input, self.tts))
        payload = {'ready': ready}
        if not self.public_origin:
            payload.update(ckpt=self.ckpt, warm_ms=self.brain.warm_ms)
        return web.json_response(payload, status=200 if ready else 503)

    async def index(self, request):
        return web.Response(text=self.page if self.authorized(request) else LOGIN,
                            content_type='text/html', headers={'Cache-Control': 'no-store'})

    async def access(self, request):
        if not self.access_code or not self.valid_origin(request):
            raise web.HTTPForbidden()
        data = await request.post()
        code = data.get('code')
        if not isinstance(code, str) or not hmac.compare_digest(
                code.strip().encode(), self.access_code.encode()):
            return web.Response(text=LOGIN.replace('</form>', '</form><p>Incorrect access code.</p>'),
                                status=403, content_type='text/html',
                                headers={'Cache-Control': 'no-store'})
        response = web.HTTPSeeOther('/', headers={'Cache-Control': 'no-store'})
        response.set_cookie(ACCESS_COOKIE, self.session_key, secure=True, httponly=True,
                            samesite='Strict', path='/')
        return response

    async def ws(self, request):
        if not self.authorized(request) or not self.valid_origin(request):
            raise web.HTTPForbidden()
        previous = self.connection
        if previous is not None:
            # One live session, but the newest tab wins. A stale or abandoned session
            # used to lock everyone else out with a 503, which the UI shows as
            # "disconnected" with no audio.
            self.connection = None
            LOG.info('replacing an existing demo session')
            try:
                await previous.cancel('replaced by a newer session')
            except Exception:
                LOG.exception('old session cancel failed')
            try:
                await previous.ws.close()
            except Exception:
                pass
        ws = web.WebSocketResponse(heartbeat=20, max_msg_size=16384)
        conn = self.connection = Connection(self, ws)
        try:
            await ws.prepare(request)
            await conn.send('state', state='listening')
            async for msg in ws:
                if msg.type == WSMsgType.BINARY:
                    conn.pcm_frame(msg.data)
                elif msg.type == WSMsgType.TEXT:
                    try:
                        data = json.loads(msg.data)
                    except ValueError:
                        continue
                    if isinstance(data, dict):
                        await conn.message(data)
        finally:
            if self.avatar:
                await self.avatar.cancel()
            if conn.reply:
                conn.reply.cancelled.set()
            pending = list(conn.finishing)
            for task in pending:
                task.cancel()
            await asyncio.gather(*pending, return_exceptions=True)
            if self.connection is conn:
                self.connection = None   # never clear a newer tab's session
        return ws