Spaces:
Paused

File size: 161,152 Bytes
bc9f3e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
"""

agent_streaming.py β€” Shared live step-streaming for every smolagents

CodeAgent-driven chat handler in this app (General Chat / RAG Chat /

Deep Research / Data Analysis β€” see chat.py / data_analysis.py).



smolagents' own streamed UI (see smolagents' `gradio_ui.py` /

`stream_to_gradio()`) streams each ActionStep/PlanningStep live by

calling `agent.run(task, stream=True, ...)` and iterating the returned

generator, rather than blocking silently until the whole run finishes β€”

the LAST item that generator yields is the plain final answer itself

(not wrapped in a step object). This module adapts that exact pattern to

this app's own chat history shape (plain {"role", "content"} dicts

served over the web UI), so every agentic tab here

(chat.py's chat_general_agentic / chat_rag / chat_deep_research, and

data_analysis.py's run_data_analysis()) can show live progress instead

of a single frozen "thinking…" bubble for however long a multi-step run

takes.



Public contract

----------------

stream_agent_steps(agent, task, reset=True) is a generator yielding

(step_msg, is_final, final_output, diagnostics) 4-tuples:



  - While the run is still in progress: `step_msg` is a plain

    {"role": "assistant", "content": "..."} dict describing the step

    that just happened (or None if that particular step produced

    nothing worth showing), `is_final` is False, `final_output` is

    None, and `diagnostics` is None. Callers append step_msg to their

    chat history and yield.



  - On the LAST item: `step_msg` is None, `is_final` is True,

    `final_output` holds the agent's actual final answer (whatever a

    plain, non-streaming `agent.run()` call would have returned), and

    `diagnostics` is a SNAPSHOT dict {total_steps,

    max_consecutive_errors, aborted, last_error, loop_detected,

    loop_call} of that run's failure diagnostics (see the fail-fast

    section below) β€” callers use this as the "real"

    result to post-process (citations, formatting, etc.) instead of

    trying to parse it back out of the step stream, and read their

    failure hint straight from `diagnostics` (no get_last_run() call

    needed after the loop).



Every call site in this app follows the same loop shape:



    result = None

    for step_msg, is_final, final_output, diag in agent_streaming.stream_agent_steps(agent, task, reset=not use_memory):

        if not is_final:

            if step_msg is not None:

                history.append(step_msg)

                yield history, ...

            continue

        result = final_output

    # diag now holds this run's diagnostics snapshot



Version compatibility

----------------------

Different smolagents releases expose live streaming slightly

differently. This module tries, in order:



  1. `agent.run(task, reset=reset, stream=True)` β€” the standard way to

     get a live generator of memory steps as they happen. Each yielded

     item is either a memory-step object (ActionStep / PlanningStep /

     ...) or, on the very last item, the final answer itself.

  2. If `stream=True` isn't accepted at all (raises TypeError β€” an

     older smolagents without streaming support), falls back to a

     single non-streaming `agent.run(task, reset=reset)` call and

     yields just ONE (None, True, result, diagnostics) tuple β€” no live

     steps, but the app still works exactly as it did before streaming

     existed.



Because the exact memory-step shape/attributes can also vary by

version, step formatting below is defensive: every attribute is read

with getattr(..., default) inside a try/except, so a field this

installed version doesn't have (or a totally unrecognized step type)

degrades to a shorter message β€” or is silently skipped β€” instead of

crashing the whole run.

"""

import ast
import html
import json
import re
import threading
import traceback
from typing import Optional

from ui import i18n

# Best-effort import of smolagents' own memory-step classes, for a
# precise isinstance() check. Falls back to matching on the class NAME
# string (see _is_memory_step()) if this smolagents version has moved
# or renamed these β€” the same defensive fallback pattern general_agent.py
# / rag_agent.py already use for other smolagents version differences
# (e.g. the `code_block_tags` / `instructions` kwarg probing).
try:
    from smolagents.memory import ActionStep, PlanningStep, TaskStep, SystemPromptStep
    _MEMORY_STEP_TYPES = (ActionStep, PlanningStep, TaskStep, SystemPromptStep)
except ImportError:
    _MEMORY_STEP_TYPES = ()

_MEMORY_STEP_CLASS_NAMES = (
    "ActionStep", "PlanningStep", "TaskStep", "SystemPromptStep", "FinalAnswerStep",
)

# DeepSeek's native code fence: '<|DSML|python>…</|DSML|python>'. The
# '|' is the full-width vertical bar U+FF5C (DeepSeek chat/reasoner models
# emit this instead of the ASCII ```python fence), but ASCII '|' variants
# appear in the wild too, so both are tolerated β€” and the ASCII closing tag
# typically carries a LEADING pipe too ('|</DSML|python|>'), so an optional
# pipe before the closing '</' is accepted. `python`/`py` (or no language
# tag) is allowed inside the markers.
_DSML_FENCE_RE = re.compile(
    r"<\s*[\uFF5C|]\s*DSML\s*[\uFF5C|]\s*(?:python|py)?\s*[\uFF5C|]?\s*>"
    r"(.*?)"
    r"\s*[\uFF5C|]?\s*</\s*[\uFF5C|]?\s*DSML\s*[\uFF5C|]\s*(?:python|py)?\s*[\uFF5C|]?\s*>",
    re.DOTALL | re.IGNORECASE,
)

# ── ReAct envelope recovery ────────────────────────────────────────────
# llama.cpp's Gemma chat template renders smolagents tool calls as the
# classic ReAct envelope:
#
#     Action:
#     {
#       "name": "final_answer",
#       "arguments": { "answer": "..." }
#     }
#
# The primary smolagents JSON parser handles CLEAN envelopes fine, but
# small local GGUFs frequently write UNESCAPED quotes inside the answer
# text (or unquoted JSON keys), which makes json.loads throw β€” and the
# smart fallback previously wrapped the WHOLE raw envelope into the final
# answer as plain text (the "Action: {…} JSON leak"). These helpers
# recover the real tool call from a malformed envelope instead.


def _tool_call_dict(name: str, arguments) -> dict:
    """Normalize a recovered tool call into the shape smolagents expects."""
    return {
        "name": name,
        "arguments": arguments,
        "action": name,
        "action_input": arguments,
    }


# ── Small-model schema-echo recovery ───────────────────────────────────
# A small GGUF model sometimes echoes a tool's JSON-Schema declaration back
# as the VALUE of an argument instead of the actual value β€” e.g.
#
#     web_search(query={'type': 'string', 'description': 'What is the
#     capital of France?'})
#
# where the description field carries what the model actually wanted to
# search for. Without recovery the tool receives a dict where a string is
# expected and the step hard-fails with an argument-type error, burning a
# whole slow generation (and, repeated, tripping the fail-fast abort). The
# helpers below unwrap schema-shaped values back into the real value the
# model meant.


def _looks_like_schema(value) -> bool:
    """True when `value` is a dict that reads as a JSON-Schema declaration

    (a 'type' key plus schema-ish metadata). Ordinary dict arguments

    (retrieved chunks, API params, query results…) never match."""
    return (
        isinstance(value, dict)
        and isinstance(value.get("type"), str)
        and any(key in value for key in ("description", "title", "default", "properties"))
    )


def _unwrap_schema_value(value):
    """Recover the intended value from a schema-shaped value. Small models

    put the REAL content into the schema's description (the observed

    shape), so description wins; a title is the next best string hint;

    a default is an actual value too (any JSON type) but only as a LAST

    resort β€” a schema echo with an empty default (e.g. DraftCodexSkillTool's

    `skill_name` carries `"default": ""`) must never swallow the real

    content sitting in the description. Non-schema values pass through

    unchanged."""
    if not _looks_like_schema(value):
        return value
    for key in ("description", "title"):
        v = value.get(key)
        if isinstance(v, str) and v.strip():
            return v
    v = value.get("default")
    if v is not None:
        return v
    return value


def _normalize_schema_echo(arguments) -> dict:
    """Undo a small model echoing a tool's JSON Schema as its arguments.



    Two shapes are handled:

      1. Whole-schema arguments β€” the ENTIRE arguments dict is a schema

         object ({type: 'object', properties: {...}}); rebuild the real

         arguments by unwrapping each property.

      2. Per-value schema echo β€” one argument's VALUE is a schema dict

         (web_search(query={'type': 'string', 'description': '…'})).



    Anything not schema-shaped passes through untouched."""
    if not isinstance(arguments, dict):
        return arguments
    props = arguments.get("properties")
    if (
        arguments.get("type") == "object"
        and isinstance(props, dict)
        and any(_looks_like_schema(v) for v in props.values())
    ):
        return {
            k: (_unwrap_schema_value(v) if isinstance(v, dict) else v)
            for k, v in props.items()
        }
    out = dict(arguments)
    for key in out:
        out[key] = _unwrap_schema_value(out[key])
    return out


def _match_braces(text: str, start: int) -> Optional[str]:
    """Return the balanced {...} block starting at text[start] (must be

    '{'), or None if the block is unterminated (truncated model output)."""
    depth = 0
    i = start
    while i < len(text):
        ch = text[i]
        if ch == "{":
            depth += 1
        elif ch == "}":
            depth -= 1
            if depth == 0:
                return text[start:i + 1]
        i += 1
    return None


def _recover_answer_from_args(args_blob: str) -> Optional[dict]:
    """Last-resort extraction of the 'answer' string from a malformed

    arguments object. Tolerates unescaped inner quotes by taking everything

    up to the LAST quote in the fragment β€” the corrupted inner quotes all

    come BEFORE the real closing quote of the answer string."""
    m = re.search(r'''["']?answer["']?\s*:\s*["']''', args_blob)
    if not m:
        return None
    tail = args_blob[m.end():]
    close = tail.rfind('"')
    if close == -1:
        close = tail.rfind("'")
    if close == -1:
        return None
    return {"answer": tail[:close].strip()}


def _parse_react_envelope(text: str) -> Optional[dict]:
    """Best-effort recovery of a ReAct 'Action:' tool-call envelope whose

    inner JSON the primary parser rejected. Returns a normalized tool-call

    dict ({name, arguments, action, action_input}) or None if `text` is not

    a recoverable envelope.



    The marker is searched ANYWHERE (the LAST 'Action:' line wins), not just

    at the start of the text: a small model narrates first ('Final answer:

    …'), leaks search-result fragments BEFORE the envelope, and smolagents'

    own step log ('[Step 2: Duration …]') trails AFTER it β€” the observed

    E2B final-output shape. Requiring the envelope at position 0 made all

    of those leak the raw narration + envelope as the final answer."""
    m = None
    for _m in re.finditer(r'(?ism)^\s*Action:?\s*(\{.*)$', text):
        m = _m  # keep the LAST 'Action:' marker β€” the final action
    if m is None:
        return None
    blob = m.group(1).strip()
    end = blob.rfind("}")
    if end == -1:
        return None
    blob = blob[:end + 1].strip()
    if not blob:
        return None

    # 1. Clean JSON β€” the primary parser normally handles this before the
    #    fallback runs, but stay robust anyway.
    try:
        data = json.loads(blob, strict=False)
        if isinstance(data, dict):
            name = str(data.get("name") or data.get("action") or "final_answer")
            arguments = data.get("arguments")
            if arguments is None:
                arguments = {"answer": data.get("answer", "")}
            if isinstance(arguments, str):
                arguments = {"answer": arguments}
            return _tool_call_dict(name, arguments)
    except Exception:
        pass

    # 2. Bare "{tool_name: <value>}" shape β€” Gemma's unquoted-key style,
    #    e.g.  Action: {final_answer: "..."}
    m_bare = re.match(r'^\{\s*([a-zA-Z0-9_]+)\s*:\s*(.*)\}\s*$', blob, re.DOTALL)
    if m_bare:
        name = m_bare.group(1).strip()
        val = m_bare.group(2).strip()
        try:
            parsed = json.loads(val, strict=False)
        except Exception:
            parsed = None
        if isinstance(parsed, dict):
            return _tool_call_dict(name, parsed)
        if val.lstrip().startswith("{"):
            # Value is itself an object with (probably unquoted) keys β€”
            # recover its 'answer' field the same way step 3 does.
            recovered = _recover_answer_from_args(val)
            if recovered:
                return _tool_call_dict(name, recovered)
        return _tool_call_dict(name, {"answer": val.strip('"\'')})

    # 3. Malformed multi-key JSON β€” recover name and arguments separately.
    name = None
    m_name = re.search(r'''["']?name["']?\s*:\s*["']([^"']+)["']''', blob)
    if m_name:
        name = m_name.group(1).strip()
    arguments = None
    m_args = re.search(r'''["']?arguments["']?\s*:\s*(\{)''', blob)
    if m_args:
        args_blob = _match_braces(blob, m_args.start(1))
        if args_blob:
            try:
                arguments = json.loads(args_blob, strict=False)
            except Exception:
                arguments = _recover_answer_from_args(args_blob)
    if name and arguments:
        if isinstance(arguments, str):
            arguments = {"answer": arguments}
        return _tool_call_dict(name, arguments)
    return None


_INVALID_CODE_CHAR_MAP = {
    # Dashes and hyphens
    "\u2010": "-",    # hyphen
    "\u2011": "-",    # non-breaking hyphen
    "\u2012": "-",    # figure dash
    "\u2013": "-",    # en dash
    "\u2014": "-",    # em dash
    "\u2015": "-",    # horizontal bar
    "\u2212": "-",    # minus sign
    # Quotation marks
    "\u2018": "'",    # left single quote
    "\u2019": "'",    # right single quote
    "\u201a": "'",    # single low-9 quotation mark
    "\u201b": "'",    # single high-reversed-9 quotation mark
    "\u201c": '"',    # left double quote
    "\u201d": '"',    # right double quote
    "\u201e": '"',    # double low-9 quotation mark
    "\u201f": '"',    # double high-reversed-9 quotation mark
    "\u00ab": '"',    # left-pointing double angle quotation mark
    "\u00bb": '"',    # right-pointing double angle quotation mark
    "\u2039": "'",    # single left-pointing angle quotation mark
    "\u203a": "'",    # single right-pointing angle quotation mark
    # Punctuation & spaces
    "\u2026": "...",  # ellipsis
    "\u00a0": " ",    # non-breaking space
    "\u202f": " ",    # narrow no-break space
    "\u2009": " ",    # thin space
    "\u2002": " ",    # en space
    "\u2003": " ",    # em space
    # Zero-width / control noise
    "\u200b": "",     # zero width space
    "\u200c": "",     # zero width non-joiner
    "\u200d": "",     # zero width joiner
    "\ufeff": "",     # zero width no-break space / BOM
}


def sanitize_python_text(text: str) -> str:
    """Best-effort ASCII normalization of characters that CPython's

    tokenizer REJECTS outright when they appear in generated code:

    em/en dashes (a Gemma-style CodeAgent frequently copies a search

    result title like '2026 FIFA World Cup β€” Wikipedia' straight into

    its Python block), typographic quotes, ellipses, NBSP. Returns the

    text unchanged when it contains nothing problematic. NEVER raises.



    This is NOT an attempt to fix genuinely broken Python β€” it only

    replaces characters that are categorically invalid as tokens, so a

    small model's "code" that is really just scraped prose degrades to

    a parseable string instead of a hard 'Code parsing failed on line

    N due to: SyntaxError: invalid character' step failure."""
    if not text or not any(ch in text for ch in _INVALID_CODE_CHAR_MAP):
        return text
    for ch, repl in _INVALID_CODE_CHAR_MAP.items():
        if ch in text:
            text = text.replace(ch, repl)
    return text


def _strip_code_xml_tags(text: str) -> str:
    """Strip leaked tool-call XML tags (e.g. `</arg_value></tool_call>`,

    `<tool_call>`, `<|tool_call|>`, `</tool_call>`, `</arg_value>`, etc.)

    that models (e.g. GLM-4.7-Flash, Qwen, Gemma) append or wrap around

    Python code blocks or `final_answer(...)` calls. Returns the text

    unchanged when no XML/tool tags are found. NEVER raises."""
    if not text or "<" not in text:
        return text
    # Strip trailing XML/tool-call tags (e.g. </arg_value></tool_call>, </tool_call>)
    cleaned = re.sub(r"(?:\s*</?[a-zA-Z0-9_\-|:]+>\s*)+$", "", text).rstrip()
    # Strip leading XML/tool-call tags (e.g. <tool_call><arg_name>...</arg_name><arg_value>)
    cleaned = re.sub(r"^(?:\s*</?[a-zA-Z0-9_\-|:]+>\s*)+", "", cleaned).lstrip()
    return cleaned


# ── Windows-path escape recovery ─────────────────────────────────────
# A raw single-backslash Windows path (e.g. G:\...\uploads\...) inside a
# Python string literal is NOT valid source: '\u' in '\uploads' trips
# "SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes
# ... truncated \uXXXX escape" (and '\l' / '\d' / octal digits silently
# corrupt the string value on some Python versions). This is the #1
# reason a REAL code block β€” the Data Analysis manager delegating to
# data_worker with the dataset path β€” fails ast.parse() and the smart
# fallback mis-wraps the whole program as a "final answer" instead of
# running it. The fix doubles every backslash that is NOT an
# unambiguous, well-formed escape ('\\', quotes, valid \x/\u/\U/\N,
# line-continuation), so 'G:\...\uploads\...' becomes the valid literal
# 'G:\\...\\uploads\\...' with the SAME raw path value. Only ever a
# fallback for code that already failed to parse; valid escapes are
# preserved verbatim.
_VALID_STRING_ESCAPE_RE = re.compile(
    r"\\[\\'\"]"
    r"|\\x[0-9a-fA-F]{2}"
    r"|\\u[0-9a-fA-F]{4}"
    r"|\\U[0-9a-fA-F]{8}"
    r"|\\N\{[^}]*\}"
    r"|\\\r?\n"
)


def _neutralize_invalid_escapes(text: str) -> str:
    """Double every backslash that is not part of an unambiguous valid

    Python string escape, turning a raw Windows path into a valid string

    literal with the same value. Well-formed escapes ('\\n', '\\t', '\\"',

    '\\\\', '\\u0041', ...) pass through untouched. Returns the text

    unchanged when there is nothing to fix. NEVER raises."""
    if not text or "\\" not in text:
        return text
    out = []
    i = 0
    n = len(text)
    while i < n:
        ch = text[i]
        if ch != "\\":
            out.append(ch)
            i += 1
            continue
        m = _VALID_STRING_ESCAPE_RE.match(text, i)
        if m:
            out.append(m.group(0))
            i = m.end()
        else:
            out.append("\\\\")
            i += 1
    fixed = "".join(out)
    return fixed if fixed != text else text


# ── DeepSeek DSML code-fence recovery ─────────────────────────────────
# DeepSeek-V4 / DeepSeek-R1 family models (HF Inference API) emit their
# Python code inside DeepSeek's OWN code fence instead of the ```python
# fence smolagents' CodeAgent expects:
#
#     <|DSML|python>
#     import pandas as pd
#     df = pd.read_excel(path)
#     print(df.shape)
#     </|DSML|python>
#
# The fence markers use the full-width vertical bar '|' (U+FF5C), so
# smolagents' extract_code_from_text() (which looks for ```python) never
# matches, ast.parse() on the raw fence text fails, and the smart fallback
# used to wrap the WHOLE fence (markers + code) into final_answer("""…""").
# On the Data Analysis tab that wrapped string then blows up with
# "SyntaxError: (unicode error) 'unicodeescape' … truncated \uXXXX escape"
# (a raw Windows path like G:\...\uploads\… inside the triple-quoted
# string) β€” the analysis never executes and the model burns its whole step
# budget retrying, then surrenders with raw code as the "final answer".
# Unwrapping the fence back to its inner code is the root-cause fix.


def _unwrap_dsml_fence(text: str):
    """Extract Python code from a DeepSeek '<|DSML|python>…</|DSML|python>'

    fence (tolerating ASCII '|' markers too). Returns the inner code, or

    None when no DSML fence is present (so the caller falls through to the

    other recovery paths)."""
    if not text or "<" not in text:
        return None
    m = _DSML_FENCE_RE.search(text)
    if not m:
        return None
    code = m.group(1).strip()
    return code or None


# ── Qwen / Gemma native tool-call recovery ──────────────────────────────
# Qwen and Gemma-family local GGUFs frequently emit their OWN native tool
# call syntax instead of smolagents' ReAct envelope or a ```python fence:
#
#     thought
#     thought
#     <|tool_call|>call:list_columns(file_path='G:\\...\\file.xlsx')<tool_call|>
#
# Sometimes the call is even wrapped inside a final_answer("""…""") string
# (the model echoes the CodeAgent idiom it was trained on). On the
# CodeAgent path (Data Analysis) that wrapped shape is VALID Python, so
# smolagents' parse_code_blobs returns the leaked call as the final answer
# and the tool never runs β€” the model then wastes the next step narrating
# "Let me see the output of the list_columns call…" with no output to see,
# and eventually surrenders with raw code as the "final answer". The
# helpers below detect the native blocks and rewrite them into plain
# Python tool calls (a bare `tool(args)` expression resolves the tool in
# the executor and its result becomes the step's observation), or recover
# them as normalized tool-call dicts for the ToolCallingAgent JSON path.

# The Qwen token renders as <|tool_call|> on BOTH sides (no closing
# slash), while Gemma-style output closes with <tool_call|> β€” the pipe is
# optional on either side, so both shapes are tolerated.
_NATIVE_TOOL_CALL_RE = re.compile(
    r"<\|?tool_call\|?>\s*(.*?)\s*<\|?/?tool_call\|?>",
    re.DOTALL,
)

# Gemma-family `call:` envelope closed by EITHER a `</tool_call>`-style
# tag or (the observed E4B shapes) a closing ``` code fence β€” see
# _rewrite_native_tool_calls. Two bodies, both of which the old
# _NATIVE_TOOL_CALL_RE (tag-closing-only) leaked:
#   * `call:python\n<whole program>` β€” the body is executable Python
#     (assignment + print of a managed-agent / tool call);
#   * `call:list_columns(file_path='…')` β€” a BARE call whose envelope is
#     closed by a fence instead of a tag.
_CALL_BLOCK_RE = re.compile(
    r"<\|?tool_call\|?>\s*call:([a-zA-Z0-9_]+)\s*(.*?)\s*(?:<\|?/?tool_call\|?>|```)",
    re.DOTALL,
)


def _py_literal(value) -> str:
    """Render a JSON-ish value as a valid Python literal expression

    (JSON's true/false/null become True/False/None; Khmer strings stay

    readable via ensure_ascii=False)."""
    if isinstance(value, bool):
        return "True" if value else "False"
    if value is None:
        return "None"
    if isinstance(value, str):
        return json.dumps(value, ensure_ascii=False)
    if isinstance(value, (int, float)):
        return repr(value)
    if isinstance(value, dict):
        return "{" + ", ".join(
            f"{_py_literal(k)}: {_py_literal(v)}" for k, v in value.items()
        ) + "}"
    if isinstance(value, (list, tuple)):
        return "[" + ", ".join(_py_literal(x) for x in value) + "]"
    return json.dumps(value, ensure_ascii=False)


def _quote_unquoted_keys(text: str) -> str:
    """Quote unquoted JSON-ish keys (Gemma's call:tool{key: value}) so the

    blob becomes parseable JSON."""
    return re.sub(r"([\"']?)([a-zA-Z0-9_]+)([\"']?)\s*:", r'"\2":', text)


def _braces_to_dict(brace_args: str) -> Optional[dict]:
    """Parse Gemma-style '{key: value, ...}' tool arguments into a dict:

    strict JSON first, then single-quoted / unquoted keys, then a

    last-resort regex pair split. Returns None when nothing parses."""
    if not brace_args.strip():
        return {}
    for attempt in (brace_args, _quote_unquoted_keys(brace_args)):
        try:
            parsed = json.loads("{" + attempt + "}", strict=False)
            if isinstance(parsed, dict):
                return parsed
        except Exception:
            continue
    pairs = re.findall(r"""["']?([a-zA-Z0-9_]+)["']?\s*:\s*(".*?"|'.*?'|[^,}]+)""", brace_args, re.DOTALL)
    if not pairs:
        return None
    out = {}
    for key, val in pairs:
        out[key] = val.strip().strip('\"\'')
    return out


def _parse_native_call(blob: str):
    """Parse ONE native tool-call body into (name, args_text, args_dict):

    - args_dict is a dict when the arguments were written in JSON-ish

      braces form ({"file_path": "..."} or call:tool{key: 'val'});

    - args_text is the verbatim Python kwargs text when the model wrote

      key='val' style inside parens (the observed Qwen shape).

    Returns None when the body isn't a parseable native call."""
    blob = blob.strip()
    if not blob:
        return None
    # GLM-4.7-Flash (the llama-server native tool-call format) appends a
    # stray `</arg_value>` XML fragment AFTER the call's close paren, before
    # the `</tool_call>` close tag (observed end-to-end: the manager's
    # intended `data_worker(task='…')` delegation carried it, which broke
    # the anchored `\s*$` parse below and leaked the whole envelope). Strip
    # trailing tag-ish garbage so the call still parses cleanly.
    blob = re.sub(r"(?:</?[a-zA-Z_][a-zA-Z0-9_]*>\s*)+$", "", blob).rstrip()
    if not blob:
        return None
    if blob.startswith("{"):
        try:
            data = json.loads(blob, strict=False)
        except Exception:
            data = None
        if not isinstance(data, dict):
            return None
        name = data.get("name") or data.get("action")
        arguments = data.get("arguments")
        if not name or not isinstance(arguments, dict):
            return None
        return (str(name), "", dict(arguments))
    m = re.match(
        r"^(?:call\s*:\s*)?([a-zA-Z0-9_]+)\s*(?:\((.*)\)|\{(.*)\})\s*$",
        blob,
        re.DOTALL,
    )
    if not m:
        return None
    name = m.group(1).strip()
    brace_args = m.group(3)
    if brace_args is not None:
        args_dict = _braces_to_dict(brace_args)
        if args_dict is None:
            return None
        return (name, "", args_dict)
    args_text = (m.group(2) or "").strip()
    # A JSON object inside the parens (call:tool({"key": "v"})) isn't the
    # Python kwargs the tool expects β€” convert it to kwargs.
    if args_text.startswith("{"):
        try:
            data = json.loads(args_text, strict=False)
            if isinstance(data, dict):
                return (name, "", dict(data))
        except Exception:
            pass
    return (name, args_text, None)


def _native_expr_parses(expr: str) -> bool:
    try:
        ast.parse(expr)
        return True
    except SyntaxError:
        return False


def _native_call_to_python(blob: str) -> Optional[str]:
    """Rewrite ONE native tool-call body into a plain Python expression

    ('list_columns(file_path="...")') the CodeAgent executor can run. The

    tools live in the executor's environment, so the bare call executes the

    tool and its result becomes the step's observation. Returns None when

    the body isn't a parseable native call."""
    parsed = _parse_native_call(blob)
    if parsed is None:
        return None
    name, args_text, args_dict = parsed
    if name == "final_answer":
        # A native envelope that CALLS final_answer (Gemma-family
        # `call:final_answer(report="...")` and the nested-inside-string
        # variant) is a final-answer delivery, not a tool call. The
        # FinalAnswerTool only accepts a POSITIONAL `answer` β€” a model that
        # emits `final_answer(report="...")` (or answer=/text=) hard-fails
        # with "unexpected keyword argument 'report'". Normalize the payload
        # to the positional triple-quoted form so the report text survives.
        payload = None
        if args_dict is not None:
            for val in args_dict.values():
                if isinstance(val, str):
                    payload = val
                    break
        else:
            m_kw = re.match(r"^[a-zA-Z_][a-zA-Z0-9_]*\s*=\s*(.*)$", args_text.strip(), re.DOTALL)
            raw = m_kw.group(1) if m_kw else args_text.strip()
            raw = raw.strip()
            if raw.startswith('"""') and raw.endswith('"""'):
                payload = raw[3:-3]
            elif len(raw) >= 2 and raw[0] == raw[-1] and raw[0] in "\"'":
                payload = raw[1:-1]
            else:
                payload = raw
        if payload is not None:
            payload = sanitize_python_text(payload)
            payload = _neutralize_invalid_escapes(payload)
            escaped = payload.replace('"""', '\\"\\"\\"')
            expr = f'final_answer("""{escaped}""")'
            if _native_expr_parses(expr):
                return expr
    if args_dict is not None:
        kwargs = ", ".join(
            f"{key}={_py_literal(val)}" for key, val in args_dict.items()
        )
        expr = f"{name}({kwargs})"
    else:
        # The parens form is Python-kwargs text (task='…'). Re-render it
        # as a dict FIRST: the verbatim text can carry raw NEWLINES (the
        # observed GLM-4.7-Flash delegation task spans several lines β€” a
        # literal newline inside a '…' string is a SyntaxError), embedded
        # quotes, and double-backslash Windows paths that a verbatim
        # re-wrap can never survive. json.dumps escaping (via _py_literal)
        # renders the SAME value as a valid literal.
        kwargs_dict = _kwargs_text_to_dict(args_text)
        if kwargs_dict is not None:
            kwargs = ", ".join(
                f"{key}={_py_literal(val)}" for key, val in kwargs_dict.items()
            )
            expr = f"{name}({kwargs})"
            if _native_expr_parses(expr):
                return expr
        expr = f"{name}({args_text})"
        if not _native_expr_parses(expr):
            # A raw Windows path (single backslashes, e.g. G:\user_data\...)
            # is not valid Python source β€” '\u' trips a 'truncated \uXXXX'
            # unicodeescape SyntaxError. Doubling the backslashes makes the
            # string literal valid while keeping the SAME raw path value.
            fixed_args = args_text.replace("\\", "\\\\")
            expr = f"{name}({fixed_args})"
    if not _native_expr_parses(expr):
        return None
    return expr


def _kwargs_text_to_dict(args_text: str) -> Optional[dict]:
    """Parse Python-kwargs-style call arguments ('task="…", file_path="…"'

    β€” with raw newlines, embedded quotes and Windows paths) into a dict of

    string values, tolerantly: strict JSON first, then a regex pair split

    (same pattern the ToolCallingAgent path uses). Returns None when

    nothing parses. Values keep their exact bytes β€” the caller re-renders

    them with proper Python-literal escaping."""
    if not args_text or not args_text.strip():
        return {}
    try:
        data = json.loads("{" + args_text + "}", strict=False)
        if isinstance(data, dict):
            return data
    except Exception:
        pass
    pairs = re.findall(
        r'([a-zA-Z0-9_]+)\s*[:=]\s*(".*?"|\'.*?\'|[^,}]+)', args_text, re.DOTALL
    )
    if not pairs:
        return None
    out = {}
    for key, val in pairs:
        out[key] = val.strip().strip('\"\'')
    return out


# Some models (Qwen3-4B-Q8_0 observed end-to-end) emit a `from tools
# import list_columns` line β€” the smolagents tutorial idiom for running
# tool calls. This sandbox exposes tools as PLAIN CALLABLES in the
# executor's static_tools (there is no `tools` module), so that import
# raises `InterpreterError: Module tools has no attribute list_columns`
# and the worker's step fails. The names ARE available bare, so stripping
# the import (and the equivalent `tools.list_columns(...)` attribute
# access) lets the code run β€” the same tool, reached the way the sandbox
# actually provides it.
_TOOLS_IMPORT_LINE_RE = re.compile(r"(?m)^[ \t]*from[ \t]+tools[ \t]+import[ \t]+[^\r\n]*$")
_TOOLS_ATTR_CALL_RE = re.compile(r"\btools\.([a-zA-Z_][a-zA-Z0-9_]*)\s*(\()")


def _normalize_tools_module_idiom(text: str) -> str:
    """Rewrite the `from tools import X` / `tools.X(...)` idiom into plain

    bare-name calls the sandbox's static_tools resolve. Pure text

    normalization; never raises. Leaves every other import untouched."""
    if not text:
        return text
    text = _TOOLS_IMPORT_LINE_RE.sub("", text)
    return _TOOLS_ATTR_CALL_RE.sub(r"\1\2", text)


def _unwrap_nested_final_answer(text: str) -> Optional[str]:
    """Detect an INNER final_answer(...) call embedded inside an OUTER

    final_answer wrapper string (the E2B manager shape observed end-to-end:

    the model narrates its reasoning as a `final_answer` triple-quoted

    string and then delivers the REAL report as a nested

    `final_answer(report=...)` call before the closing fence/quote). The

    outer call is VALID Python, so

    the original parser returns the whole leaked narration as the final

    answer (the leaked-code validator then rejects it). Extract the

    innermost call and normalize it β€” the same kwargs-to-positional handling

    _native_call_to_python applies β€” so the real report text survives.

    Returns None when there is no nested call."""
    if not text or text.count("final_answer(") < 2:
        return None
    inner = text.rfind("final_answer(")
    tail = text[inner:]
    # The inner call is closed by a ``` fence (observed) or the outer
    # string's own quotes β€” cut the tail there so rfind(')') in the
    # final_answer recovery sees the INNER call's close, not the outer
    # wrapper's.
    fence = tail.find("```")
    if fence != -1:
        tail = tail[:fence]
    expr = _native_call_to_python(tail)
    if expr is not None and _native_expr_parses(expr):
        return expr
    return None


def _recover_final_answer_call(text: str) -> Optional[str]:
    """Recover a final_answer(...) call whose string argument contains

    unescaped quotes (the E4B failure: a report body with `24" Monitor` or

    quoted Khmer column names inside `final_answer("...")`, which is an

    unterminated string literal and fails ast.parse). The smart fallback's

    non-greedy final_answer-regex would cut the payload at the

    FIRST ')' inside the report, so this helper takes everything up to the

    LAST ')' and re-wraps it with triple-quote escaping β€” the answer text

    is preserved verbatim and the emitted code always parses. Returns None

    when the text holds no recoverable final_answer call (normal parsing

    proceeds)."""
    if not text:
        return None
    start = text.find("final_answer(")
    if start == -1:
        return None
    open_idx = start + len("final_answer(")
    end = text.rfind(")")
    if end <= open_idx:
        return None
    payload = text[open_idx:end]
    # Strip a wrapping quote layer the model added (the call was
    # final_answer("...") or final_answer("""...""")), so the payload is
    # the raw report text.
    payload = payload.strip()
    if payload.startswith('"""') and payload.endswith('"""'):
        payload = payload[3:-3]
    elif payload.startswith('"') and payload.endswith('"'):
        payload = payload[1:-1]
    elif payload.startswith("'") and payload.endswith("'"):
        payload = payload[1:-1]
    payload = _strip_code_xml_tags(payload)
    payload = sanitize_python_text(payload)
    payload = _neutralize_invalid_escapes(payload)
    escaped = payload.replace('"""', '\\"\\"\\"')
    expr = f'final_answer("""{escaped}""")'
    try:
        import ast
        ast.parse(expr)
        return expr
    except Exception:
        return None


def _payload_from_final_answer_args(args_dict, args_text: str) -> Optional[str]:
    """Extract the report payload from a final_answer call's parsed

    arguments, PRESERVING the text verbatim (no tokenizer sanitize β€” this is

    a displayed answer, and em-dashes / typographic quotes are legitimate

    there). Handles both the JSON-braces form (preferring the conventional

    `answer` / `report` / `text` keys) and the Python-kwargs form

    (`final_answer(report="…")` / positional quoted strings). Returns None

    when no string payload is found."""
    if args_dict is not None:
        for key in ("answer", "report", "text"):
            val = args_dict.get(key)
            if isinstance(val, str) and val.strip():
                return val
        for val in args_dict.values():
            if isinstance(val, str) and val.strip():
                return val
        return None
    m = re.match(r"^[a-zA-Z_][a-zA-Z0-9_]*\s*=\s*(.*)$", (args_text or "").strip(), re.DOTALL)
    raw = (m.group(1) if m else (args_text or "")).strip()
    if raw.startswith('"""') and raw.endswith('"""'):
        return raw[3:-3]
    if len(raw) >= 2 and raw[0] == raw[-1] and raw[0] in "\"'":
        return raw[1:-1]
    return raw or None


# ── Chat-template token leak recovery ─────────────────────────────────
# A model can leak its chat template's control tokens into a final answer
# instead of (or trailing) real content. The observed case: Muse Glimmer
# (Meta's agent model β€” its template frames turns as
# <|start|>role<|message|>…<|eot|> and the assistant writes answer
# channels, "to=user" for the reply, "to=self" for reasoning) β€” a
# community "-UD-" GGUF quant emitted its channel-close fragment
# "to=user<|eot|>" as the WHOLE payload of a final_answer tool call. The
# fragments below are tokenizer/control tokens and channel markers β€”
# never legitimate answer text β€” so stripping them from a delivered
# answer is safe, and the shared final-answer validator
# (agent_factory.reject_leaked_or_empty_final_answer) rejects an answer
# that becomes EMPTY after the strip (pure template garbage) instead of
# shipping it as the answer bubble.

_TEMPLATE_TOKEN_RE = re.compile(
    r"<\|?(?:"
    r"start|message|eot|im_start|im_end|endoftext|eos|eot_id|eos_id|"
    r"start_of_turn|end_of_turn|tool_call|/?tool_call|think|/?think|"
    r"reasoning|/?reasoning"
    r")\|?>|</s>",
    re.IGNORECASE,
)

# Muse Glimmer's channel markers ("to=user" / "to=assistant" / "to=self" /
# "to=<tool>"). The fragment must be STANDALONE β€” preceded by whitespace/
# start (so `--to=user` or `param.to=user` in a coding answer is never
# touched) and NOT continuing into an identifier ('to=users', 'to=user_id'
# survive) β€” but ANY non-identifier follower is allowed, so a BARE marker
# with no trailing <|eot|> token is still caught: 'to=self```' (glued to a
# code-fence opener), 'to=user###', 'to=self' at end of text.
_CHANNEL_MARKER_RE = re.compile(
    r"(?<![^\s])to=(?:user|assistant|self|<[a-z_][a-z0-9_]*>)(?![A-Za-z0-9_])",
    re.IGNORECASE,
)

# After the marker is stripped, a marker glued to a code-fence opener
# ('to=self```') leaves only the fence behind β€” pure-fence residue is
# still the leak, never answer content.
_FENCE_ONLY_RE = re.compile(r"^[\s`]+$")


def strip_template_tokens(text: str) -> str:
    """Remove chat-template control tokens (Qwen3's <|eot|>, ChatML's

    <|im_start|>/<|im_end|>, Llama-3's <|eot_id|>/<|eos_id|>, Gemma's

    <|start_of_turn|>/<|end_of_turn|>, <|endoftext|>, </s>, Qwen native

    <|tool_call|>, Muse Glimmer's <|start|>/<|message|>/channel markers

    β€” both with the <|eot|> token (to=user<|eot|>) and BARE with no token

    at all (to=self```, to=user###, to=user at end of text; the <tool>

    channel form to=<tool> is covered too). Real content around the

    tokens survives ("…X.<|eot|>" β†’ "…X."); the whole text disappears

    only when it WAS the leak. Returns the text unchanged when nothing

    matches. NEVER raises."""
    if not text or not isinstance(text, str):
        return text
    if "<" not in text and "to=" not in text:
        return text
    # The channel-marker pass runs BEFORE and AFTER the token pass: a
    # marker only becomes standalone once a preceding token is removed
    # ("</s>to=assistant" β†’ "to=assistant").
    text = _CHANNEL_MARKER_RE.sub("", text)
    text = _TEMPLATE_TOKEN_RE.sub("", text)
    text = _CHANNEL_MARKER_RE.sub("", text)
    # The removals can leave doubled spaces ("… X. <|eot|>" β†’ "… X. ").
    text = re.sub(r" {2,}", " ", text)
    text = text.strip()
    # A bare channel marker glued to a code-fence opener ('to=self```')
    # leaves only the fence behind β€” pure-fence residue is still the leak.
    if text and _FENCE_ONLY_RE.match(text):
        return ""
    return text


# ── Degenerate-repetition detection ──────────────────────────────────
# A broken generation β€” e.g. a TEXT request that landed on an EMBEDDING
# model through a shared llama-server port (the observed "skills skills
# skills …" failure) β€” produces one token repeated until the token budget
# is exhausted. No real answer looks like that, so it can be detected
# cheaply and rejected before it is shipped as an answer or fed back as a
# giant garbage observation.
_DEGEN_MIN_TOKENS = 100      # only judge answers with enough material
_DEGEN_MAX_RUN = 30          # >30 consecutive identical tokens = loop
_DEGEN_DOMINANT_RATIO = 0.5  # one token > half of a long answer = loop
_DEGEN_MAX_CHAR_RUN = 200    # one letter/digit repeated 200+ times = loop

# Alphanumeric only, so decorative rules ('──────', '══════') and table
# borders are never flagged; U+1780–U+17FF covers Khmer letters.
_DEGEN_CHAR_LOOP_RE = re.compile(
    r"([A-Za-z0-9\u1780-\u17FF])\1{%d,}" % (_DEGEN_MAX_CHAR_RUN - 1)
)


def is_degenerate_repetition(text) -> bool:
    """True when `text` is degenerate token repetition instead of an

    answer: one word/token repeated over and over ("skills skills skills

    …") until the budget ran out, or a single letter/digit repeated

    hundreds of times in a row.



    Deliberately conservative so real answers are never rejected:

      - fewer than _DEGEN_MIN_TOKENS whitespace tokens is never judged

        (Khmer prose splits into very few whitespace tokens);

      - the word-level checks need _DEGEN_MAX_RUN consecutive identical

        tokens, or one token filling more than half of a long answer;

      - the character-level check fires only on ALPHANUMERIC runs of

        _DEGEN_MAX_CHAR_RUN+ β€” decorative rules survive.

    NEVER raises."""
    try:
        if not text or not isinstance(text, str):
            return False
        tokens = text.split()
        if len(tokens) >= _DEGEN_MIN_TOKENS:
            norm = [t.lower() for t in tokens]
            run = best = 1
            for i in range(1, len(norm)):
                run = run + 1 if norm[i] == norm[i - 1] else 1
                if run > best:
                    best = run
            if best >= _DEGEN_MAX_RUN:
                return True
            counts = {}
            for t in norm:
                counts[t] = counts.get(t, 0) + 1
            if max(counts.values()) / len(norm) > _DEGEN_DOMINANT_RATIO:
                return True
        return bool(_DEGEN_CHAR_LOOP_RE.search(text))
    except Exception:
        return False


def _payload_from_openai_call(call) -> Optional[str]:
    """Extract the payload of a final_answer call from ONE OpenAI-style

    tool-call dict (the shape smolagents prints in its 'Calling tools:'

    line). `arguments` may be a dict or a JSON-encoded string; the payload

    key may be `answer` / `report` / `text` / `answer_text`."""
    if not isinstance(call, dict):
        return None
    fn = call.get("function")
    if not isinstance(fn, dict):
        return None
    if str(fn.get("name", "")).strip() != "final_answer":
        return None
    arguments = fn.get("arguments")
    if isinstance(arguments, str):
        try:
            arguments = json.loads(arguments)
        except Exception:
            arguments = None
    if not isinstance(arguments, dict):
        return None
    payload = _payload_from_final_answer_args(arguments, "")
    return payload if payload and payload.strip() else None


_CALLING_TOOLS_ENVELOPE_RE = re.compile(
    r"Calling tools\s*:\s*(\[.*\])", re.DOTALL | re.IGNORECASE)


def _payload_from_calling_tools_envelope(text) -> Optional[str]:
    """Recover the final_answer payload from smolagents' OWN 'Calling

    tools:' line followed by a Python-repr list of OpenAI-style tool calls

    β€” the shape a ToolCallingAgent model (observed: Muse Glimmer via

    llama-server) emits when it writes the final_answer call as PLAIN TEXT

    instead of a structured tool call:



      Calling tools:

      [{'id': 'a1b2c3d4-…', 'type': 'function',

        'function': {'name': 'final_answer',

                     'arguments': {'answer_text': '### …'}}}]



    The max-steps fallback then ships that text verbatim as the answer

    bubble. Returns the payload string, or None when the text isn't such

    an envelope (normal parsing proceeds). The literal_eval path handles

    the complete list; a tolerant scan handles a cut-off tail (the

    observed Muse Glimmer output is truncated mid-dict with NO closing

    ']')."""
    if not text or not isinstance(text, str):
        return None
    stripped = text.strip()
    m = _CALLING_TOOLS_ENVELOPE_RE.search(stripped)
    if m:
        block = m.group(1).strip()
    else:
        # No closing ']' β€” the output was cut mid-envelope. Everything
        # after the 'Calling tools:' label is the fragment to scan.
        head = re.split(r"Calling tools\s*:", stripped, maxsplit=1,
                        flags=re.IGNORECASE)
        block = head[1].strip() if len(head) == 2 and head[1].strip() else None
    if not block:
        return None
    calls = None
    try:
        import ast
        calls = ast.literal_eval(block)
    except Exception:
        calls = None
    if isinstance(calls, list):
        for call in calls:
            payload = _payload_from_openai_call(call)
            if payload:
                return payload
    # Tolerant fallback: literal_eval fails on a truncated list tail β€”
    # scan the raw fragment for a final_answer call's arguments dict.
    if "final_answer" not in block:
        return None
    args_m = re.search(r"['\"]arguments['\"]\s*:\s*(\{.*)", block, re.DOTALL)
    if args_m:
        brace = args_m.group(1).strip()
        # Best-effort: pass the dict CONTENT (drop the outer brace and a
        # truncated trailing '}'/']') so _braces_to_dict sees clean pairs.
        if brace.startswith("{"):
            brace = brace[1:]
        brace = brace.rstrip("}]")
        args_dict = _braces_to_dict(brace)
        if args_dict:
            payload = _payload_from_final_answer_args(args_dict, "")
            if payload:
                return payload
    return None


_PREAMBLE_TRANSITION_RE = re.compile(
    r"(?:\b(?:I have sufficient info(?:rmation)?|I have enough info(?:rmation)?|"
    r"I will now write the (?:final )?answer|Here is the (?:final )?(?:answer|summary|response|report)|"
    r"I will compile the answer in Khmer|I will write the response in(?: natural)? Khmer|"
    r"Constructing (?:Final )?Output|Final Output)\b[.:\s]*)"
    r"(.*)$",
    re.IGNORECASE | re.DOTALL,
)

_KHMER_CHAR_RE = re.compile(r"[\u1780-\u17FF]")

_META_ENGLISH_STARTS = (
    "the user is", "the user wants", "the user asked", "user is asking", "the user's query",
    "the user's message", "the greeting is", "this is a", "this is simply", "since this is",
    "the search results provide", "search results show", "key themes:", "summary structure",
    "plan:", "refined summary:", "wait, i should", "i will compile the answer", "i will write the response",
    "i should respond", "i need to respond", "let's respond", "let me respond",
    "analyze the request", "analyzing the request", "analyze the input", "analyzing the input",
    "drafting the content", "input: ",
    # GLM-4.7-Flash and similar reasoning GGUFs often open their final answer
    # with a long English planning monologue instead of a <think> block. These
    # openings identify that monologue so the answer after it can be extracted.
    "i need to analyze", "let me understand", "let me analyze", "i need to understand",
    "let me think", "let me break", "the task is", "i'm being asked", "i should figure",
    "let's analyze", "i will analyze", "the instructions are", "the task says",
    "i'm supposed to", "here is my analysis", "my task is", "the prompt is",
    "step 1:",
    # GLM-4.7-Flash also opens with a third-person summary of what it was
    # given ("The user has provided a task in Khmer. The task appears to be
    # asking me to respond...") before either its answer or a full echo of
    # the task text.
    "the user has", "the task appears",
)
# NOTE: deliberately NOT meta-starts (too generic β€” legit answers open with
# them and stripping would chop real content): "looking at the", "first, i",
# "to answer this".

# Khmer meta-reasoning / prompt-analysis phrases β€” third-person reference to
# the user's question, tool-usage decisions, or response planning in Khmer.
# When the model outputs its chain-of-thought in Khmer (instead of wrapping
# it in <think> tags), these patterns identify the reasoning preamble so the
# actual answer following it can be extracted.
_META_KHMER_PHRASES = (
    "αžŸαŸ†αžŽαž½αžšαžšαž”αžŸαŸ‹αž’αŸ’αž“αž€αž”αŸ’αžšαžΎαž‚αžΊ",    # "The user's question is"
    "αžŸαŸ†αžŽαž½αžšαžšαž”αžŸαŸ‹αž’αŸ’αž“αž€αž‚αžΊ",          # "Your question is"
    "αžŸαŸ†αžŽαž½αžšαž“αŸαŸ‡αž‚αžΊ",               # "This question is"
    "αž“αŸαŸ‡αž‚αžΊαž‡αžΆαžŸαŸ†αžŽαž½αžš",             # "This is a question"
    "αž“αŸαŸ‡αž‚αžΊαž‡αžΆ",                   # "This is"
    "αžœαžΆαž‚αžΊαž‡αžΆ",                     # "It is"
    "αžŠαžΌαž…αŸ’αž“αŸαŸ‡αžαŸ’αž‰αž»αŸ†αž‚αž·αžαžαžΆ",         # "So I think"
    "αžŠαžΌαž…αŸ’αž“αŸαŸ‡αžαŸ’αž‰αž»αŸ†αž‚αŸ’αžšαžΆαž“αŸ‹",         # "So I just"
    "αžŠαžΌαž…αŸ’αž“αŸαŸ‡αžαŸ’αž‰αž»αŸ†αž“αžΉαž„",            # "So I will"
    "αžαŸ’αž‰αž»αŸ†αž˜αž·αž“αžαŸ’αžšαžΌαžœαž€αžΆαžšαž”αŸ’αžšαžΎ",      # "I don't need to use"
    "αžαŸ’αž‰αž»αŸ†αžαŸ’αžšαžΌαžœαžαŸ‚αž†αŸ’αž›αžΎαž™",         # "I need to answer"
    "αžαŸ’αž‰αž»αŸ†αž“αžΉαž„αž†αŸ’αž›αžΎαž™",              # "I will answer"
    "αžŸαž˜αŸ’αžšαžΆαž”αŸ‹αžŸαŸ†αžŽαž½αžšαž“αŸαŸ‡",          # "For this question"
    "αžŸαž˜αŸ’αžšαžΆαž”αŸ‹αžŸαŸ†αžŽαž½αžšαžŸαžΆαž€αž›αŸ’αž”αž„",     # "For this test question"
    "αž€αž»αŸ†αž”αŸ’αžšαžΎ",                    # "Don't use"
    "αž˜αž·αž“αž…αžΆαŸ†αž”αžΆαž…αŸ‹αž”αŸ’αžšαžΎ",             # "No need to use"
    "αžαŸ’αž‰αž»αŸ†αž‚αž·αžαžαžΆ",                 # "I think that"
    "αžαŸ’αž‰αž»αŸ†αž“αžΉαž„αž•αŸ’αžαž›αŸ‹",              # "I will provide"
    "αžŠαžΌαž…αŸ’αž“αŸαŸ‡αžαŸ’αž‰αž»αŸ†αž‚αŸ’αžšαžΆαž“αŸ‹αžαŸ‚",       # "So I just"
    "αž“αŸαŸ‡αž˜αž·αž“αž˜αŸ‚αž“αž‡αžΆ",               # "This is not"
    "αž‚αŸ’αž˜αžΆαž“αž€αžΆαžšαžŸαŸ’αžœαŸ‚αž„αžšαž€",           # "No search needed"
    "αž˜αž·αž“αžαŸ’αžšαžΌαžœαž€αžΆαžšαžŸαŸ’αžœαŸ‚αž„αžšαž€",        # "No need to search"
)


# Deliberation-shaped SENTENCE markers for English-only leaks β€” third-person
# narration of what the user said / tool-usage decisions / output planning.
# Only whole leading sentences carrying one of these are ever dropped, so a
# legitimate answer sentence without them is never eaten.
_META_ENGLISH_SENTENCE_MARKERS = (
    "i should respond", "i should follow", "i should not include",
    "i don't need to use any tools", "no tools are needed", "i don't need any tool",
    "this is a simple greeting", "this is a straightforward",
    "the user has just said", "the user has provided a task",
    "the user wants me to", "they want me to respond",
    "i'll just give", "i will give a natural", "i will provide a direct",
    "not output internal plan", "internal planning or thinking",
)


def _strip_leading_english_meta_sentences(text, max_sentences=15):
    """Drop leading deliberation sentences from an ENGLISH-only leak (meta

    monologue followed by an English answer β€” no Khmer anywhere, so the

    Khmer-block extraction paths can never fire). Each dropped chunk must

    contain a deliberation marker and end at a real sentence/line terminator;

    the walk stops at the first sentence without one. Returns '' when nothing

    survives (caller keeps the original text)."""
    tail = text.strip()
    low = ""
    for _ in range(max_sentences):
        low = tail.lower()
        hit = -1
        for marker in _META_ENGLISH_SENTENCE_MARKERS:
            idx = low.find(marker)
            if idx != -1 and (hit == -1 or idx < hit):
                hit = idx
        if hit == -1:
            break
        end = len(tail)
        for j in range(hit, len(tail)):
            if tail[j] in ".!?\n":
                end = j + 1
                break
        if end >= len(tail):
            break
        while end < len(tail) and tail[end] in ".!?\n \t\r":
            end += 1
        tail = tail[end:].lstrip()
    return tail if tail and len(tail.strip()) >= 4 else ""


def _strip_deliberation_preamble(text: str) -> str:
    """Strip internal chain-of-thought / deliberation / scratchpad preambles

    from final answer text when an actual answer follows.



    Handles cases where a model (e.g. Gemma-4, GLM, Qwen) outputs internal

    English monologue or planning notes (e.g. 'The search results provide a good overview...

    Plan: ... Refined Summary: ... I have sufficient info.', 'Analyze the Request: ...

    Constructing Final Output.', or 'The user is greeting me in Khmer. I should respond in Khmer...

    Since this is a simple greeting. αžŸαž½αžŸαŸ’αžαžΈ!...') before transitioning into the actual answer.



    Returns the stripped, clean answer. If no preamble is detected or the text

    is pure scratchpad without an answer, returns the original text unchanged.

    """
    if not text or not isinstance(text, str):
        return text

    # 1. Direct transition phrase (e.g. "I have sufficient info. αž“αŸαŸ‡αž‚αžΊαž‡αžΆ...",
    # "Constructing Final Output. # αž…αŸ†αžŽαž„αž‡αžΎαž„...", "Here is the summary: ...")
    m = _PREAMBLE_TRANSITION_RE.search(text)
    if m:
        tail = m.group(1).strip()
        if tail and not any(tail.lower().startswith(s) for s in _META_ENGLISH_STARTS):
            return tail

    # 2. English planning / prompt-analysis scratchpad followed by a Khmer answer:
    low = text.lower().strip()
    is_meta_start = any(low.startswith(s) for s in _META_ENGLISH_STARTS)
    has_meta_phrase = any(s in low[:2500] for s in (
        "plan:", "refined summary:", "analyze the request:", "drafting the content",
        "constructing final output", "i should respond in", "the user is greeting",
        "the greeting is simply",
        # GLM-4.7-Flash planning-monologue markers (often appear mid-text, not
        # at the very start of the answer):
        "i need to analyze", "let me understand what's being asked", "let me analyze",
        "i should not include any planning", "i should respond directly",
        "the instructions are asking", "the task says", "i'm supposed to respond",
        "i need to respond in", "i should respond in", "let me think about",
        "let me break this down", "here is my analysis",
    ))

    if (is_meta_start or has_meta_phrase) and _KHMER_CHAR_RE.search(text):
        # Look for terminal Khmer text block (after all English meta-talk)
        m_khmer = re.search(r"(?:^|[.!?\n]\s*)([\u1780-\u17FF][^\n]*(?:[.!?\n]|\Z).*)$", text, re.DOTALL)
        if m_khmer:
            candidate = m_khmer.group(1).strip()
            if candidate and not any(candidate.lower().startswith(s) for s in _META_ENGLISH_STARTS):
                if len(_KHMER_CHAR_RE.findall(candidate)) >= 5:
                    return candidate

        # Also check inline transition: e.g. "...greeting.αžŸαž½αžŸαŸ’αžαžΈ!..."
        m_inline = re.search(r"[a-zA-Z0-9_\-'\"]+[.!?:\s]+([\u1780-\u17FF].*)$", text, re.DOTALL)
        if m_inline:
            candidate = m_inline.group(1).strip()
            if candidate and len(_KHMER_CHAR_RE.findall(candidate)) >= 5:
                return candidate

        # Line-by-line fallback
        lines = text.splitlines()
        cut_idx = None
        for idx in range(len(lines) - 1, -1, -1):
            line_s = lines[idx].strip()
            if not line_s:
                continue
            if _KHMER_CHAR_RE.search(line_s) and not any(line_s.lower().startswith(s) for s in _META_ENGLISH_STARTS):
                cut_idx = idx
                break

        if cut_idx is not None and cut_idx > 0:
            candidate = "\n".join(lines[cut_idx:]).strip()
            m_inline_fallback = re.search(r"[a-zA-Z0-9_\-'\"]+[.!?:\s]+([\u1780-\u17FF].*)$", candidate, re.DOTALL)
            if m_inline_fallback:
                candidate = m_inline_fallback.group(1).strip()
            if candidate:
                return candidate

    # 2b. ENGLISH-ONLY deliberation leak β€” same monologue class but the
    #     actual answer is English too (no Khmer anywhere), so every
    #     Khmer-block extraction above can never fire. Drop each leading
    #     sentence that itself carries a deliberation marker and return what
    #     remains (e.g. GLM's 'The user has just said "hi". ... response.' +
    #     'Hi there! ...' β†’ 'Hi there! ...').
    if (is_meta_start or has_meta_phrase) and not _KHMER_CHAR_RE.search(text):
        tail = _strip_leading_english_meta_sentences(text)
        if tail:
            return tail

    # 3. Khmer-only meta-reasoning / prompt-analysis scratchpad:
    #    GLM-4.7-Flash and similar models sometimes output their entire
    #    chain-of-thought in Khmer instead of wrapping it in <think> tags.
    #    The text is ALL Khmer (no English meta-starts), but the first
    #    paragraph(s) reference the user's question in third person or
    #    discuss tool-usage decisions. Extract the first non-meta paragraph
    #    as the actual answer.
    if _KHMER_CHAR_RE.search(text) and not is_meta_start:
        low_full = text.lower()
        has_kh_meta = any(p in low_full[:2500] for p in _META_KHMER_PHRASES)
        if has_kh_meta:
            # Split into paragraphs (double-newline or paragraph boundaries)
            paragraphs = re.split(r"\n\s*\n", text)
            for i, para in enumerate(paragraphs):
                para_strip = para.strip()
                if not para_strip:
                    continue
                para_low = para_strip.lower()
                # If this paragraph does NOT start with a Khmer meta-phrase,
                # it's likely the actual answer.
                if not any(p in para_low[:80] for p in _META_KHMER_PHRASES):
                    if len(_KHMER_CHAR_RE.findall(para_strip)) >= 3:
                        return para_strip
            # Fallback: look for a Khmer text block after the last
            # meta-reasoning paragraph (same pattern as step 2).
            m_khmer = re.search(
                r"(?:^|[.!?\u17D4\n]\s*)([\u1780-\u17FF][^\n]*(?:[.!?\u17D4\n]|\Z).*)$",
                text, re.DOTALL)
            if m_khmer:
                candidate = m_khmer.group(1).strip()
                if candidate and not any(
                    p in candidate.lower()[:80] for p in _META_KHMER_PHRASES):
                    if len(_KHMER_CHAR_RE.findall(candidate)) >= 3:
                        return candidate

    return text


def sanitize_surrogates(text: str) -> str:
    """Sanitize invalid Unicode surrogate code points (U+D800 - U+DFFF)

    so that strings can safely be encoded to UTF-8 without raising UnicodeEncodeError."""
    if not isinstance(text, str):
        return str(text) if text is not None else ""
    try:
        return text.encode("utf-8", errors="replace").decode("utf-8")
    except Exception:
        return "".join(c for c in text if not (0xD800 <= ord(c) <= 0xDFFF))


def _unwrap_leaked_final_answer(text) -> str:
    """Wrapper around _unwrap_leaked_final_answer_raw: after the leaked

    envelope is unwrapped (or plain text passes through), strip any

    chat-template control tokens from whatever survived (see

    strip_template_tokens) and any internal thinking/scratchpad preamble

    (see _strip_deliberation_preamble) β€” ensuring that the delivered answer

    bubble is clean, structured, and free of meta-planning/scratchpad noise."""
    if not text or not isinstance(text, str):
        return text
    result = _unwrap_leaked_final_answer_raw(text)
    if isinstance(result, str) and result:
        result = strip_template_tokens(result)
        result = _strip_deliberation_preamble(result)
        result = sanitize_surrogates(result)
    return result


def _unwrap_leaked_final_answer_raw(text) -> str:
    """Recover the real answer/report from a final-answer string that leaked

    the model's tool-call envelope instead of its payload.



    The step-parsing path is covered by the parse_json_blob patch, but

    smolagents' max-steps fallback (`_handle_max_steps_reached` β†’

    `provide_final_answer`) takes the model's RAW text as the final answer

    WITHOUT any tool-call parsing. A transformers model trained on

    smolagents transcripts answers the "give your final answer" prompt with

    its trained call format as plain text β€” the observed E2B shape

    `call:final_answer{answer: "### …"}` (and `…} />` variants) β€” which

    then renders verbatim as the answer bubble. Shapes handled:

      call:final_answer{answer: "..."}          (native call, quoted/unquoted keys)

      call:final_answer(report="...")           (native call, kwargs)

      final_answer("...") / triple-quoted final_answer(...) / final_answer(report="…")

      Action: {final_answer: "..."}              (ReAct envelope)

    Non-envelope text is returned unchanged β€” a plain answer is never

    touched."""
    if not text or not isinstance(text, str):
        return text
    stripped = text.strip()
    if not stripped:
        return text

    # A trailing self-close marker (…} />) some models append after the
    # envelope's closing brace would break the anchored parse β€” drop it.
    cleaned = stripped[:-2].strip() if stripped.endswith("/>") else stripped

    # 1) Whole-text native call / final_answer(...) β€” anchored, so prose
    #    that merely mentions a call is never touched.
    parsed = _parse_native_call(cleaned)
    if parsed is not None:
        name, args_text, args_dict = parsed
        if name == "final_answer":
            payload = _payload_from_final_answer_args(args_dict, args_text)
            if payload is not None and payload.strip():
                return payload

    # 2) Tolerant non-anchored recovery for the wrapped/`/>`-terminated
    #    shapes the anchored parse rejects β€” recover the arguments dict the
    #    same way _smart_parse_json_blob does.
    m = re.search(r"call\s*:\s*final_answer\s*\{(.*)\}", cleaned, re.DOTALL)
    if m:
        args_dict = _braces_to_dict(m.group(1)) or {}
        for key in ("answer", "report", "text"):
            val = args_dict.get(key)
            if isinstance(val, str) and val.strip():
                return val.strip()
        for val in args_dict.values():
            if isinstance(val, str) and val.strip():
                return val.strip()

    # 3) ReAct 'Action:' envelope (searched anywhere β€” the model narrates
    #    and leaks fragments around it, and smolagents' step log trails it).
    react = _parse_react_envelope(stripped)
    if react is not None:
        payload = (react.get("arguments") or {}).get("answer")
        if isinstance(payload, str) and payload.strip():
            return payload.strip()

    # 3.5) smolagents' own 'Calling tools:' line + OpenAI-style call list
    #    β€” the shape Muse Glimmer writes its final_answer call in as plain
    #    text (no structured tool call), which the max-steps fallback then
    #    ships verbatim.
    envelope_payload = _payload_from_calling_tools_envelope(cleaned)
    if envelope_payload is not None:
        return envelope_payload

    # 4) A model-narrated 'Final answer:' label with no envelope at all β€”
    #    strip the label so it doesn't render as the bubble's first line.
    prefix_stripped = _strip_final_answer_prefix(text)
    return prefix_stripped if prefix_stripped != text else text


def _rewrite_native_tool_calls(text: str) -> Optional[str]:
    """Detect Qwen/Gemma native <|tool_call|> blocks in model output and

    rewrite them into plain Python tool calls for the CodeAgent path.

    Returns the rewritten program (one tool call per line) or None when

    the text contains no parseable native call β€” so normal parsing

    proceeds. Runs BEFORE smolagents' own parser because the wrapped shape

    (a native call inside a final_answer(...) string) is VALID Python that the

    original parser happily returns as a leaked final answer."""
    if not text or "<" not in text:
        return None
    if not re.search(r"<\|?tool_call", text):
        return None
    # Gemma-family `call:` envelopes closed by a ``` code fence (or a
    # tag), two observed E4B shapes:
    #   * `call:python\n<whole program>` β€” the body IS executable Python
    #     (assignment + print of the managed-agent call), so extract and
    #     run it as-is;
    #   * `call:list_columns(file_path='…')``` β€” a BARE call whose
    #     envelope is closed by a fence instead of a `</tool_call>` tag,
    #     which the old _NATIVE_TOOL_CALL_RE below never matched and the
    #     whole block leaked as the final answer.
    lines = []
    for block in _CALL_BLOCK_RE.finditer(text):
        kind = block.group(1)
        body = block.group(2).strip()
        if kind == "python":
            # Raw single-backslash Windows paths ('G:\user_data\…' β€” a
            # '\u' unicodeescape SyntaxError) get the same backslash
            # doubling cure as the bare-call shape.
            if not _native_expr_parses(body):
                fixed = body.replace("\\", "\\\\")
                if _native_expr_parses(fixed):
                    body = fixed
            if _native_expr_parses(body):
                lines.append(body)
        else:
            expr = _native_call_to_python(f"call:{kind}{body}")
            if expr is not None:
                lines.append(expr)
    if lines:
        return "\n".join(lines)
    # Tag-closed bare calls / JSON-object / brace-style shapes (the
    # original handling) β€” _CALL_BLOCK_RE above already covered the
    # `call:`-prefixed ones, this catches the rest.
    lines = []
    for block in _NATIVE_TOOL_CALL_RE.finditer(text):
        expr = _native_call_to_python(block.group(1))
        if expr is None:
            continue
        lines.append(expr)
    if not lines:
        return None
    return "\n".join(lines)


def _parse_native_tool_call_blob(text: str) -> Optional[dict]:
    """Recover the FIRST native tool call from model output as a

    normalized tool-call dict (the same shape the ReAct envelope recovery

    returns) for the ToolCallingAgent JSON path. Returns None when no

    native call is present."""
    if not text or "<" not in text:
        return None
    m = _NATIVE_TOOL_CALL_RE.search(text)
    if not m:
        return None
    parsed = _parse_native_call(m.group(1))
    if parsed is None:
        return None
    name, args_text, args_dict = parsed
    if args_dict is not None:
        arguments = args_dict
    else:
        # Verbatim Python kwargs ('file_path="..."') β€” split into a dict
        # the same way the existing call:tool{...} fallback does. The parens
        # form uses '=' (Python kwargs) while the brace form uses ':', so
        # both separators are accepted.
        arguments = {}
        try:
            arguments = json.loads("{" + args_text + "}", strict=False)
        except Exception:
            pairs = re.findall(
                r'([a-zA-Z0-9_]+)\s*[:=]\s*(".*?"|\'.*?\'|[^,}]+)', args_text, re.DOTALL
            )
            for key, val in pairs:
                arguments[key] = val.strip().strip('\"\'')
    return _tool_call_dict(name, arguments)


def _strip_react_envelope(text: str) -> str:
    """Strip a leading ReAct 'Action: {...}' envelope (or a truncated

    fragment of one) from plain text, so raw JSON can never leak into a

    final answer even if full recovery fails. Plain sentences that merely

    start with the word "Action:" are left untouched."""
    m = re.match(r'^\s*Action:?\s*', text, re.DOTALL | re.IGNORECASE)
    if not m:
        return text
    rest = text[m.end():]
    if not rest.lstrip().startswith("{"):
        return text
    end = rest.rfind("}")
    if end != -1:
        return rest[end + 1:].lstrip()
    # Truncated envelope with no closing brace β€” discard the fragment.
    return ""


def _strip_final_answer_prefix(text: str) -> str:
    """Cut a model-narrated 'Final answer:' / 'final_answer:' / 'Final

    Answer:' prefix from the START of a final-answer text. Small models

    announce their answer with this label before writing it; without the

    strip the label renders as the first line of the bubble. Plain text

    without the prefix is returned unchanged."""
    m = re.match(r'(?is)^\s*(?:final\s*_?answer)\s*:\s*', text)
    if not m:
        return text
    rest = text[m.end():].lstrip()
    return rest or text


def _patch_smolagents_code_parser():
    """Patch smolagents.utils.parse_code_blobs and smolagents.utils.parse_json_blob

    with smart fallback parsers.

    Handles:

    1. CodeAgent: Plain text final answers without ```python ... ``` code block tags.

    2. ToolCallingAgent: Model tool calls output in call:tool_name{key: val} format

       or unquoted JSON key format (common with Gemma-4 and local LLMs).

    """
    try:
        import smolagents.utils as su
        if getattr(su, "_smart_parser_installed", False):
            return
        _orig_parse_code_blobs = su.parse_code_blobs
        _orig_parse_json_blob = su.parse_json_blob

        def _smart_parse_code_blobs(text: str, code_block_tags: tuple) -> str:
            # Qwen3-4B emits a `from tools import list_columns` tutorial idiom
            # that parses fine but FAILS at runtime (the sandbox exposes tools
            # as plain callables, not via a `tools` module). Normalize it to
            # bare-name calls BEFORE the original parser extracts the code, so
            # the runtime InterpreterError never happens (see
            # _normalize_tools_module_idiom).
            text = _normalize_tools_module_idiom(text)
            # Qwen/Gemma native tool calls FIRST (see _rewrite_native_tool_calls):
            # the wrapped shape β€” a native call inside final_answer("""…""") β€” is
            # VALID Python, so the original parser returns the leaked call as the
            # final answer and this smart fallback never runs. Pre-scanning
            # rewrites the call into executed Python for both the wrapped and the
            # raw shapes, so the Data Analysis tools actually run.
            native = _rewrite_native_tool_calls(text)
            if native is not None:
                try:
                    res = _orig_parse_code_blobs(native, code_block_tags)
                    cleaned = _strip_code_xml_tags(res)
                    if cleaned != res:
                        try:
                            import ast
                            ast.parse(cleaned)
                            return cleaned
                        except Exception:
                            pass
                    return res
                except Exception:
                    return _strip_code_xml_tags(native)
            # E2B manager shape: the REAL report is a nested
            # final_answer(report="...") call INSIDE an outer
            # final_answer("""Thought: ...""") wrapper string β€” valid Python,
            # so the original parser would return the whole leaked narration
            # as the final answer (rejected by the leaked-code validator).
            # Unwrap the innermost call BEFORE the original parser runs.
            unwrapped = _unwrap_nested_final_answer(text)
            if unwrapped is not None:
                return _strip_code_xml_tags(unwrapped)
            try:
                res = _orig_parse_code_blobs(text, code_block_tags)
                cleaned = _strip_code_xml_tags(res)
                if cleaned != res:
                    try:
                        import ast
                        ast.parse(cleaned)
                        return cleaned
                    except Exception:
                        pass
                return res
            except Exception:
                if not text or not isinstance(text, str):
                    return 'final_answer("")'
                clean_text = text.strip()
                clean_text = _strip_code_xml_tags(clean_text)

                # DeepSeek DSML fence unwrap FIRST β€” the inner code IS the
                # real program (e.g. "import pandas as pd …"), so feeding it
                # back through the normal parser lets the analysis actually
                # run instead of being swallowed as a "final answer". Without
                # this, a DeepSeek-V4 step hard-fails with a unicode-escape
                # SyntaxError (a Windows raw path inside the wrapped string)
                # and the model burns its whole step budget retrying.
                dsml_code = _unwrap_dsml_fence(clean_text)
                if dsml_code is not None:
                    try:
                        return _orig_parse_code_blobs(dsml_code, code_block_tags)
                    except Exception:
                        return dsml_code

                # Windows-path escape recovery: a REAL code block (the Data
                # manager delegating to data_worker with the dataset path) can
                # fail ast.parse ONLY because a raw single-backslash path in a
                # string literal trips a unicodeescape SyntaxError ('\u' in
                # '\uploads'). The program is genuinely executable β€” neutralize
                # the invalid escapes and retry the REAL parser so the code
                # RUNS, instead of the whole block being mis-wrapped into a
                # final_answer string the model then sees as "code snippets,
                # not results".
                fixed_text = _neutralize_invalid_escapes(clean_text)
                if fixed_text != clean_text:
                    try:
                        return _orig_parse_code_blobs(fixed_text, code_block_tags)
                    except Exception:
                        pass

                if "final_answer(" in clean_text:
                    m = re.search(r"final_answer\(.*?\)", clean_text, re.DOTALL)
                    if m:
                        # Fast path: a cleanly-quoted call (final_answer("…")
                        # or final_answer("""…""")) is returned as-is.
                        try:
                            import ast
                            ast.parse(m.group(0))
                            return m.group(0)
                        except SyntaxError:
                            pass
                    # The model wrapped its report in final_answer("...") but
                    # the report body contains unescaped quotes (e.g. a product
                    # named 24" Monitor, or quoted Khmer column names), so the
                    # string literal is unterminated and ast.parse fails β€” and
                    # the non-greedy regex above would cut the payload at the
                    # FIRST ')' inside the report, returning a fragment that is
                    # STILL an unterminated string (the observed E4B final-
                    # answer failure: "Code parsing failed … unterminated
                    # string literal"). Recover the FULL payload (up to the
                    # last ')') and re-wrap it with the same triple-quote
                    # escaping the plain-text path uses, so the answer is
                    # always parseable.
                    recovered = _recover_final_answer_call(clean_text)
                    if recovered is not None:
                        return recovered

                # ReAct 'Action:' envelope recovery β€” same bug class as the
                # JSON parser below. If the model wrapped its output in a
                # raw ReAct envelope, answer with the envelope's payload
                # instead of leaking the raw JSON into the final answer.
                react = _parse_react_envelope(clean_text)
                if react is not None:
                    payload = (react.get("arguments") or {}).get("answer")
                    if isinstance(payload, str) and payload.strip():
                        clean_text = payload.strip()
                    else:
                        clean_text = _strip_react_envelope(clean_text)

                clean_text = _strip_final_answer_prefix(clean_text)

                # Tokenizer-rejected characters (em-dash etc. copied from
                # scraped search results) and invalid backslash escapes (raw
                # Windows paths) must be normalized BEFORE the text is wrapped
                # into a Python string β€” otherwise the wrapped
                # 'final_answer("""...""")' fails ast.parse() in the executor
                # with 'invalid character' / a truncated-\u unicodeescape
                # error and the whole step hard-fails.
                clean_text = sanitize_python_text(clean_text)
                clean_text = _neutralize_invalid_escapes(clean_text)
                escaped = clean_text.replace('"""', '\\"\\"\\"')
                return f'final_answer("""{escaped}""")'

        def _smart_parse_json_blob(json_blob: str) -> tuple:
            try:
                return _orig_parse_json_blob(json_blob)
            except Exception as orig_err:
                if not json_blob or not isinstance(json_blob, str):
                    clean_text = ""
                else:
                    clean_text = json_blob.strip()

                # Qwen/Gemma native <|tool_call|> recovery β€” same leak class
                # as the CodeAgent path: a local GGUF emits its own native
                # tool-call syntax instead of smolagents' ReAct envelope;
                # recover the real call instead of wrapping the raw markers
                # into the final answer.
                native = _parse_native_tool_call_blob(clean_text)
                if native is not None:
                    return native, ""

                # Match call:tool_name{key: val} format used by Gemma-4 and local LLMs
                call_match = re.search(r'call:([a-zA-Z0-9_]+)\s*\{(.*)\}', clean_text, re.DOTALL)
                if call_match:
                    tool_name = call_match.group(1).strip()
                    args_str = call_match.group(2).strip()
                    args_dict = {}
                    if args_str:
                        try:
                            args_dict = json.loads("{" + args_str + "}", strict=False)
                        except Exception:
                            pairs = re.findall(r'([a-zA-Z0-9_]+)\s*:\s*(".*?"|\'.*?\'|[^,}]+)', args_str, re.DOTALL)
                            for k, v in pairs:
                                v = v.strip().strip('"\'')
                                args_dict[k] = v

                    res_dict = {
                        "name": tool_name,
                        "arguments": args_dict,
                        "action": tool_name,
                        "action_input": args_dict,
                    }
                    return res_dict, clean_text[:call_match.start()]

                # ReAct 'Action:' envelope β€” recover the real tool call from
                # a malformed envelope (unescaped quotes / unquoted keys in
                # small local GGUF output) instead of leaking the raw
                # envelope text into the final answer.
                react = _parse_react_envelope(clean_text)
                if react is not None:
                    return react, ""

                # Fallback for plain text or markdown model outputs without a JSON blob.
                # Belt-and-braces: strip any leading envelope fragment that full
                # recovery couldn't unwrap, so raw JSON never shows in the answer.
                clean_text = _strip_react_envelope(clean_text)
                clean_text = _strip_final_answer_prefix(clean_text)

                res_dict = {
                    "name": "final_answer",
                    "arguments": {"answer": clean_text},
                    "action": "final_answer",
                    "action_input": {"answer": clean_text},
                }
                return res_dict, ""

        su.parse_code_blobs = _smart_parse_code_blobs
        su.parse_json_blob = _smart_parse_json_blob

        # CodeAgent executor resilience: smolagents' evaluate_python_code()
        # runs ast.parse() on the model's code block and, on ANY SyntaxError,
        # hard-fails the whole step with "Code parsing failed on line N ...".
        # A small GGUF (e.g. Gemma-4-E2B) that copies a scraped title with an
        # em-dash into its Python block triggers exactly that β€” an invalid-
        # character SyntaxError that is really just "prose, not code". Retry
        # once with the sanitized text (see sanitize_python_text) so the step
        # executes instead of wasting a whole generation on a parse error.
        try:
            import smolagents.local_python_executor as lpe
            _orig_evaluate_python_code = lpe.evaluate_python_code
            if not getattr(lpe, "_smart_sanitize_installed", False):

                def _smart_evaluate_python_code(code: str, *args, **kwargs):
                    try:
                        return _orig_evaluate_python_code(code, *args, **kwargs)
                    except Exception as e:
                        err_text = str(e)
                        # The `from <toolname> import X` mangled-import class
                        # (Qwen3-4B observed: `from list_columns import
                        # list_columns` and `from tools import list_columns` β€”
                        # smolagents tutorial idioms) fails at runtime because
                        # there is no such MODULE: import_module() raises
                        # ModuleNotFoundError; when the name isn't in the
                        # authorized list the executor raises an "Import from
                        # X is not allowed" InterpreterError first. Either way
                        # the bare name IS available (evaluate_name resolves
                        # it from static_tools), so strip the import line and
                        # retry. Only do this when the imported module name
                        # is a REAL static tool β€” a genuine missing-package
                        # import must keep its error.
                        is_mangled_tool_import = "ModuleNotFoundError: No module named" in err_text or (
                            "Import from" in err_text and "is not allowed" in err_text
                        )
                        if is_mangled_tool_import and not getattr(lpe, "_smart_tools_import_retried", False):
                            static_tools = kwargs.get("static_tools")
                            if static_tools is None and args:
                                static_tools = args[0]
                            if isinstance(static_tools, dict):
                                import ast as _ast
                                try:
                                    tree = _ast.parse(code)
                                except Exception:
                                    tree = None
                                if tree is not None:
                                    tool_names = set(static_tools.keys())
                                    bad_lines = set()
                                    for node in _ast.walk(tree):
                                        if isinstance(node, _ast.ImportFrom) and node.module in tool_names:
                                            bad_lines.add(node.lineno)
                                    if bad_lines:
                                        lines = code.split("\n")
                                        cleaned = "\n".join(
                                            ln for i, ln in enumerate(lines, 1) if i not in bad_lines
                                        )
                                        if cleaned.strip() != code.strip():
                                            lpe._smart_tools_import_retried = True
                                            try:
                                                return _orig_evaluate_python_code(cleaned, *args, **kwargs)
                                            finally:
                                                lpe._smart_tools_import_retried = False
                        # Syntax / tokenizer / parsing error recovery:
                        # 1. Leaked XML / special tool-call tags (e.g. </arg_value></tool_call> from GLM-4.7-Flash)
                        # 2. Tokenizer-rejected characters (em-dashes, typographic quotes)
                        # 3. Raw Windows paths in string literals (truncated \u in \uploads)
                        cleaned = _strip_code_xml_tags(code)
                        cleaned = sanitize_python_text(cleaned)
                        cleaned = _neutralize_invalid_escapes(cleaned)
                        if cleaned != code:
                            try:
                                import ast
                                ast.parse(cleaned)
                                return _orig_evaluate_python_code(cleaned, *args, **kwargs)
                            except Exception:
                                pass
                        raise

                lpe.evaluate_python_code = _smart_evaluate_python_code
                lpe._orig_evaluate_python_code = _orig_evaluate_python_code
                lpe._smart_sanitize_installed = True
        except Exception:
            pass

        try:
            import smolagents.models as sm
            sm.parse_json_blob = _smart_parse_json_blob
        except Exception:
            pass

        try:
            import smolagents.agents as sa
            sa.parse_json_blob = _smart_parse_json_blob
            # CodeAgent._step_stream calls its OWN module-level binding
            # `parse_code_blobs` (captured from smolagents.utils at agents.py
            # import time), NOT smolagents.utils.parse_code_blobs β€” so the
            # smart fallback above never fired for CodeAgent tabs (Data
            # Analysis) and a model that emitted no ```python fence (e.g. a
            # Gemma-4 "thought…" stream) hard-failed the step with the raw
            # "Your code snippet is invalid" ValueError. Rebind the agents
            # module's copy to the smart wrapper too.
            sa.parse_code_blobs = _smart_parse_code_blobs
        except Exception:
            pass

        # Smart tool execution & argument normalization patch
        try:
            import smolagents.agents as sa
            if hasattr(sa, "ToolCallingAgent") and not getattr(sa.ToolCallingAgent, "_smart_tool_call_installed", False):
                _orig_execute_tool_call = sa.ToolCallingAgent.execute_tool_call

                def _smart_execute_tool_call(self, tool_name: str, arguments):
                    available_tools = {**self.tools, **self.managed_agents}
                    if tool_name not in available_tools:
                        lower_map = {k.lower(): k for k in available_tools}
                        if tool_name.lower() in lower_map:
                            tool_name = lower_map[tool_name.lower()]
                        else:
                            return _orig_execute_tool_call(self, tool_name, arguments)

                    tool = available_tools[tool_name]
                    is_managed = tool_name in self.managed_agents

                    if not isinstance(arguments, dict):
                        if arguments is None:
                            arguments = {}
                        elif isinstance(arguments, str):
                            arguments = {"task": arguments} if is_managed else {"answer": arguments} if tool_name == "final_answer" else {"query": arguments}
                        else:
                            arguments = {}
                    else:
                        arguments = dict(arguments)

                    # Small-model schema-echo recovery β€” see the module-level
                    # helpers above. A value (or the whole arguments object)
                    # that is really the tool's JSON Schema (the model pasted
                    # the schema instead of the value, putting the real
                    # question in the description) must be unwrapped BEFORE
                    # execution, or the tool hard-fails on an argument-type
                    # error and burns a whole step.
                    arguments = _normalize_schema_echo(arguments)

                    if is_managed:
                        if "task" not in arguments or not arguments.get("task"):
                            for alias in ("query", "question", "search", "search_query", "search_task", "keywords", "prompt", "text", "input", "topic", "q", "contract", "doc", "document"):
                                if alias in arguments and arguments[alias]:
                                    arguments["task"] = str(arguments.pop(alias))
                                    break
                            if not arguments.get("task"):
                                task_str = getattr(self, "task", "") or "search the indexed knowledge base"
                                if "Question:" in task_str:
                                    task_str = task_str.split("Question:", 1)[1].split("\n\n", 1)[0].strip()
                                arguments["task"] = task_str
                        allowed = set(getattr(tool, "inputs", {}).keys()) | {"task", "additional_args"}
                        arguments = {k: v for k, v in arguments.items() if k in allowed}
                    elif tool_name == "final_answer":
                        if "answer" not in arguments or not arguments.get("answer"):
                            for alias in ("answer_text", "text", "content", "markdown", "response", "report"):
                                if alias in arguments and arguments[alias]:
                                    arguments["answer"] = str(arguments.pop(alias))
                                    break
                            if not arguments.get("answer"):
                                for k, v in list(arguments.items()):
                                    if v and isinstance(v, str):
                                        arguments["answer"] = v
                                        break
                                if not arguments.get("answer"):
                                    arguments["answer"] = ""
                        allowed = set(getattr(tool, "inputs", {}).keys()) | {"answer"}
                        arguments = {k: v for k, v in arguments.items() if k in allowed}
                    else:
                        tool_inputs = getattr(tool, "inputs", {})
                        custom_aliases = getattr(tool, "input_aliases", None)
                        for req_k in tool_inputs.keys():
                            if req_k not in arguments:
                                aliases = (custom_aliases.get(req_k) if isinstance(custom_aliases, dict) else None) or {
                                    "source": ("doc", "document", "file", "filename", "path", "source_file", "name", "title"),
                                    "theme": ("topic", "category", "theme_name", "name"),
                                    "subtheme": ("sub_theme", "subtopic", "sub_category"),
                                    "query": ("question", "search", "search_query", "keywords", "task", "text", "prompt", "q"),
                                    "file_path": ("filepath", "file", "path", "data_path", "filename"),
                                }.get(req_k, ())
                                for a in aliases:
                                    if a in arguments and arguments[a]:
                                        arguments[req_k] = arguments.pop(a)
                                        break
                        if tool_inputs:
                            arguments = {k: v for k, v in arguments.items() if k in tool_inputs}

                    return _orig_execute_tool_call(self, tool_name, arguments)

                sa.ToolCallingAgent.execute_tool_call = _smart_execute_tool_call
                sa.ToolCallingAgent._smart_tool_call_installed = True
        except Exception:
            pass

        try:
            import smolagents.agents as sa
            if hasattr(sa, "MultiStepAgent") and not getattr(sa.MultiStepAgent, "_smart_agent_call_installed", False):
                _orig_agent_call = sa.MultiStepAgent.__call__

                def _smart_agent_call(self, task: str = "", **kwargs):
                    if not task:
                        for alias in ("query", "question", "search", "search_query", "search_task", "keywords", "prompt", "text", "input", "topic", "q", "contract", "doc", "document"):
                            if alias in kwargs and kwargs[alias]:
                                task = str(kwargs.pop(alias))
                                break
                    if not task:
                        task = getattr(self, "default_task", "") or getattr(self, "task", "") or "search the indexed knowledge base"
                        if "Question:" in task:
                            task = task.split("Question:", 1)[1].split("\n\n", 1)[0].strip()
                    return _orig_agent_call(self, task=task, **kwargs)

                sa.MultiStepAgent.__call__ = _smart_agent_call
                sa.MultiStepAgent._smart_agent_call_installed = True
        except Exception:
            pass

        su._smart_parser_installed = True
    except Exception:
        pass


_patch_smolagents_code_parser()


def _truncate(text, limit: int = 1500, lang_key: str = "kh") -> str:
    text = str(text or "")
    if len(text) <= limit:
        return text
    l = i18n.LANGUAGES.get(lang_key, i18n.LANGUAGES["kh"])
    suffix = l.get("agent_step_truncated", "…(truncated)")
    return text[:limit].rstrip() + "\n" + suffix


def _step_error_bubble(e, lang_key: str = "kh") -> str:
    """Bilingual error bubble for a failed agentic run: the localized

    'Execution Error:' prefix frames the (inherently English) Python

    traceback so a Khmer UI doesn't open with a bare English '❌ …'."""
    l = i18n.LANGUAGES.get(lang_key, i18n.LANGUAGES["kh"])
    prefix = l.get("agent_step_error_bubble", "❌ Execution Error:")
    return f"{prefix} {e}\n\n{traceback.format_exc()}"


def _step_error_text(e, lang_key: str = "kh") -> str:
    """The plain-error slot of the failed run's final yield (no traceback,

    no HTML) β€” same localized prefix as _step_error_bubble."""
    l = i18n.LANGUAGES.get(lang_key, i18n.LANGUAGES["kh"])
    prefix = l.get("agent_step_error_bubble", "❌ Execution Error:")
    return f"{prefix} {e}"


def _error_snippet(e, limit: int = 500) -> str:
    """A compact single-line rendering of a step's failure for the abort

    diagnostics (`last_error`): the exception message with its type (e.g.

    `KeyError: 'Quantity'`), truncated so a giant traceback-like error can

    never bloat the abort message. Returns '' for empty/None errors."""
    if e is None:
        return ""
    text = str(e)
    if not text:
        text = e.__class__.__name__
    else:
        text = f"{e.__class__.__name__}: {text}"
    text = " ".join(text.split())
    if len(text) > limit:
        text = text[:limit] + "…"
    return text


def _format_tool_calls(tool_calls, lang_key: str = "kh") -> str:
    if not tool_calls:
        return ""
    l = i18n.LANGUAGES.get(lang_key, i18n.LANGUAGES["kh"])
    exec_label = l.get("agent_step_tool_execution", "πŸ› οΈ Tool Execution:")
    truncated = l.get("agent_step_truncated", "…(truncated)")
    lines = []
    for tc in tool_calls:
        name = (
            getattr(tc, "name", None)
            or (tc.get("name") if isinstance(tc, dict) else None)
            or "tool"
        )
        if name == "final_answer":
            continue
        args = getattr(tc, "arguments", None)
        if args is None and isinstance(tc, dict):
            args = tc.get("arguments")
        args_str = str(args) if args is not None else ""
        if len(args_str) > 800:
            args_str = args_str[:800] + truncated
        name_esc = html.escape(str(name))
        args_esc = html.escape(args_str)
        lines.append(
            f'<div class="tool-header"><b>{exec_label}</b> <code>{name_esc}</code></div>\n'
            f'<pre class="obs-code"><code>{args_esc}</code></pre>'
        )
    return "\n".join(lines)


def _format_step(step, lang_key: str = "kh") -> Optional[str]:
    """Best-effort human-readable rendition of one smolagents memory step

    (ActionStep / PlanningStep / ...) formatted with distinct step log styling.

    All user-visible labels are bilingual (ui.i18n), so a Khmer UI streams

    Khmer step headers and an English UI English ones.

    Dynamic output fields are HTML-escaped for safety.

    """
    try:
        cls_name = step.__class__.__name__
        l = i18n.LANGUAGES.get(lang_key, i18n.LANGUAGES["kh"])
        planning_label = l.get("agent_step_planning", "πŸ—ΊοΈ Planning & Strategy Step")
        strategy_label = l.get("agent_step_strategy", "πŸ—ΊοΈ Strategy")
        header_tpl = l.get("agent_step_header", "βš™οΈ Step {n} β€” Execution Log & Tools")
        header_plain = l.get("agent_step_header_plain", "βš™οΈ Agent Step β€” Execution Log")
        reasoning_label = l.get("agent_step_reasoning", "🧠 Reasoning:")
        obs_label = l.get("agent_step_observations", "πŸ“ Execution Logs & Terminal Output")
        err_label = l.get("agent_step_error", "⚠️ Execution Error")

        if cls_name == "PlanningStep":
            plan = getattr(step, "plan", None) or getattr(step, "facts", None)
            if not plan:
                return None
            plan_esc = html.escape(_truncate(plan, lang_key=lang_key))
            return (
                '<details class="agent-step-details">\n'
                f'<summary class="agent-step-summary"><b>{planning_label}</b></summary>\n'
                '<div class="agent-log-block">\n'
                f'<div class="agent-plan-box"><div class="plan-header">{strategy_label}</div><div>{plan_esc}</div></div>\n'
                '</div>\n</details>'
            )

        if cls_name in ("TaskStep", "SystemPromptStep"):
            return None

        step_number = getattr(step, "step_number", None)
        try:
            header_text = header_tpl.format(n=step_number) if step_number is not None else header_plain
        except (KeyError, ValueError):
            # A future translation edit that drops the {n} placeholder must
            # never blank the whole step header β€” fall back to the plain one.
            header_text = header_plain

        # Timing breakdown badge (if step.timing exposes generation / execution durations)
        timing = getattr(step, "timing", None)
        timing_badge = ""
        if timing is not None:
            gen_d = getattr(timing, "generation_duration", None)
            if gen_d is None:
                gen_d = getattr(timing, "model_time", None)
            exec_d = getattr(timing, "execution_duration", None)
            if exec_d is None:
                exec_d = getattr(timing, "tool_time", None)
            durs = []
            if isinstance(gen_d, (int, float)) and gen_d > 0:
                durs.append(f"🧠 {gen_d:.1f}s")
            if isinstance(exec_d, (int, float)) and exec_d > 0:
                durs.append(f"πŸ› οΈ {exec_d:.1f}s")
            if durs:
                timing_badge = f' <span class="step-timing">({", ".join(durs)})</span>'

        tool_calls = getattr(step, "tool_calls", None)
        is_final_call = bool(
            tool_calls
            and all(
                (getattr(tc, "name", None) or (tc.get("name") if isinstance(tc, dict) else None)) == "final_answer"
                for tc in tool_calls
            )
        )
        error = getattr(step, "error", None)
        if is_final_call and not error:
            return None

        parts = []

        model_output = getattr(step, "model_output", None)
        if model_output:
            cleaned_out = _truncate(model_output, lang_key=lang_key)
            cleaned_esc = html.escape(cleaned_out)
            parts.append(f'<div class="agent-thought-box"><b>{reasoning_label}</b>\n{cleaned_esc}</div>')

        has_real_tool = any(
            (getattr(tc, "name", None) or (tc.get("name") if isinstance(tc, dict) else None)) != "final_answer"
            for tc in (tool_calls or [])
        )
        tc_str = _format_tool_calls(tool_calls, lang_key=lang_key)
        if tc_str:
            parts.append(f'<div class="agent-tool-box">{tc_str}</div>')

        observations = getattr(step, "observations", None)
        if observations and (has_real_tool or not tool_calls):
            obs_text = _truncate(observations, 1200, lang_key=lang_key)
            obs_esc = html.escape(obs_text)
            parts.append(
                f'<div class="agent-obs-box">\n'
                f'<div class="obs-header">{obs_label}</div>\n'
                f'<pre class="obs-code"><code>{obs_esc}</code></pre>\n'
                '</div>'
            )

        error = getattr(step, "error", None)
        if error:
            err_text = _truncate(str(error), 800, lang_key=lang_key)
            err_esc = html.escape(err_text)
            parts.append(
                f'<div class="agent-err-box">\n'
                f'<div class="err-header">{err_label}</div>\n'
                f'<div>{err_esc}</div>\n'
                '</div>'
            )

        if not parts:
            return None

        body_html = "\n".join(parts)
        rendered = (
            f'<details class="agent-step-details">\n'
            f'<summary class="agent-step-summary">{header_text}{timing_badge}</summary>\n'
            f'<div class="agent-log-block">\n{body_html}\n</div>\n'
            '</details>'
        )
        return sanitize_surrogates(rendered)
    except Exception:
        # Never let a formatting glitch break the whole streamed run
        return None


def _is_memory_step(item) -> bool:
    """Distinguish a smolagents memory-step object (ActionStep,

    PlanningStep, ...) from the final answer itself. smolagents' own

    streaming run yields the plain final answer, UNWRAPPED, as the very

    last item β€” so anything that isn't recognizably a memory step is

    treated as the final answer by the caller (see stream_agent_steps()).

    """
    if _MEMORY_STEP_TYPES and isinstance(item, _MEMORY_STEP_TYPES):
        return True
    return item.__class__.__name__ in _MEMORY_STEP_CLASS_NAMES


# ── Fail-fast guard & run diagnostics ───────────────────────────────────
# A model stuck in a loop of errored steps (tool-call parse failures, tool
# exceptions, failed final-answer checks…) burns its whole step budget one
# slow generation at a time β€” on a large local GGUF each failed step can
# take a minute or more. The stream loop below tracks CONSECUTIVE errored
# steps and aborts early with bilingual guidance once the threshold is
# hit, instead of grinding through every remaining step. The per-run
# diagnostics dict is read back by the chat handlers (chat.py) to surface
# a soft "consider a larger model" hint when a run COMPLETES but still
# stumbled repeatedly.
_ERROR_ABORT_THRESHOLD = 3
_STUMBLE_HINT_THRESHOLD = 2

# ── Repetition-loop guard ──────────────────────────────────────────────
# A model stuck repeating the SAME tool call over and over (a degenerate
# repetition loop β€” the observation is sitting right there in its context,
# but it keeps re-emitting the identical call, then surrenders with
# meta-commentary like "I don't see any observations") burns the whole
# step budget one slow generation at a time. Unlike the error guard above
# (which keys on FAILED steps), this loop produces successful steps, so it
# needs its own detector: N identical consecutive tool-call signatures. On
# the threshold the run first INJECTS a corrective reminder into the
# agent's memory (the fresh context breaks the deterministic
# re-generation β€” the standard cure); if the model still repeats the same
# call after that, the run aborts with the same bilingual machinery as the
# error guard.
#
# A stuck model often VARIES its code slightly each time (drops a
# try/except, switches path escaping, re-imports) while still re-reading
# the SAME data file with the SAME tool β€” each variant's full signature
# differs, so the exact-signature channel above never fires. A second,
# coarser channel counts consecutive same-tool + same-file accesses
# (parsed out of the code text / call arguments and path-normalized), so
# a model grinding on one file is caught even when the surrounding code
# changes every step. Both channels share the nudge-once-then-abort
# lifecycle.
_LOOP_NUDGE_THRESHOLD = 3

_last_run_local = threading.local()


def get_last_run() -> dict:
    """Thread-local per-run diagnostics for the most recent agentic run on

    THIS thread: {total_steps, max_consecutive_errors, aborted, last_error}.



    Thread-local so two agentic tabs running concurrently (parallel

    workers) can never cross-wire each other's failure data β€” each run's

    chat handler reads back exactly the diagnostics its own thread just

    produced, even when a run on another thread is aborting/stumbling at

    the same time."""
    d = getattr(_last_run_local, "last_run", None)
    if d is None:
        d = {"total_steps": 0, "max_consecutive_errors": 0, "aborted": False,
             "last_error": "", "loop_detected": False, "loop_call": ""}
        _last_run_local.last_run = d
    return d


def _tool_calls_signature(step):
    """Canonical identity of the tool call(s) a step executed β€” the loop

    guard's equality key. On the CodeAgent path every step's tool_calls is

    [ToolCall(name='python_interpreter', arguments=<code text>)], so an

    identical repeated code block yields an identical signature; on the

    ToolCallingAgent path it's the real tool name + normalized arguments

    (dict ordering ignored β€” the same call with keys in a different order

    is still the same call). Returns None when the step carries no

    readable tool call (final-answer steps, parse failures) β€” nothing to

    compare, so the guard stands down. Never raises: any odd step shape

    just returns None."""
    try:
        tcs = getattr(step, "tool_calls", None)
        if not tcs:
            return None
        sigs = []
        for tc in tcs:
            name = getattr(tc, "name", None)
            if name is None and isinstance(tc, dict):
                name = tc.get("name")
            args = getattr(tc, "arguments", None)
            if args is None and isinstance(tc, dict):
                args = tc.get("arguments")
            if name is None:
                return None
            if isinstance(args, dict):
                args_sig = tuple(sorted((str(k), str(v)) for k, v in args.items()))
            else:
                args_sig = str(args)
            sigs.append((str(name), args_sig))
        return tuple(sigs)
    except Exception:
        return None


def _signature_call_names(sig) -> str:
    """Human-readable label of a loop signature for the abort message: the

    first call's tool name (with a '+N more' suffix when the step carried

    several calls). On the CodeAgent path the executor name is the generic

    'python_interpreter', so the first function called inside the code text

    (e.g. 'list_columns' from `list_columns("G:\\data.xlsx")`) is surfaced

    instead β€” that's the tool the user actually sees looping. Returns ''

    for empty/unreadable signatures."""
    try:
        if not sig:
            return ""
        first_name, first_args = sig[0]
        if first_name == "python_interpreter" and isinstance(first_args, str):
            m = re.match(r"\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\(", first_args.strip())
            if m:
                first_name = m.group(1)
        names = [first_name] + [s[0] for s in sig[1:]]
        label = names[0]
        if len(names) > 1:
            label += f" (+{len(names) - 1} more)"
        return label
    except Exception:
        return ""


# ── Same-tool + same-file loop channel ─────────────────────────────────
# The exact-signature guard above catches a model re-emitting the
# IDENTICAL call, but a stuck model often VARIES its code slightly each
# time (drops a try/except, switches escaping, re-imports) while still
# re-reading the SAME data file with the SAME tool β€” each variant's full
# signature differs, so the exact channel never fires. These helpers
# derive a coarser fingerprint: every call in the step that accesses a
# data file, keyed on (tool name, normalized path, effective arguments).
# Path normalization unifies the same file written as a raw string, an
# escaped string, or via a variable (G:\x vs g:/x), so the variants
# collapse to one fingerprint the guard can count; the effective
# arguments (everything but the file itself) keep DIFFERENT operations on
# the same file (aggregate by αžαŸαžαŸ’αž vs by αž—αŸαž‘) distinct β€” a thorough
# multi-step EDA never trips the channel.
#
# Incidental SETUP/utility calls are filtered OUT of the fingerprint so
# they can't break a genuine read loop: a model that re-reads the SAME
# data file with read_excel while also calling os.makedirs on the outputs
# dir (or os.path.join / os.path.exists / mkdir / …) is still doing the
# same repeated read β€” the makedirs call is noise, not a different
# operation. Only calls that touch a DATA file (reads, aggregates, chart
# saves, exports) contribute to the fingerprint.
_INCIDENTAL_TOOL_NAMES = frozenset({
    # filesystem setup / teardown / listing β€” never the data read itself
    "makedirs", "mkdir", "mkdirs", "rmdir", "removedirs",
    "listdir", "scandir", "walk", "glob", "iglob",
    "exists", "lexists", "isfile", "isdir", "islink", "isabs",
    "remove", "unlink", "rename", "replace", "rmtree",
    "copytree", "copy", "copy2", "move", "chdir", "getcwd",
    # path construction / munging / metadata
    "join", "abspath", "normpath", "realpath", "expanduser",
    "expandvars", "basename", "dirname", "splitext",
    "commonpath", "relpath", "getsize", "getmtime", "stat", "lstat",
    # generic chatter / setup that can carry a path-shaped string
    "print", "set_option", "reset_option", "get_option",
    "install_package", "check_call", "run", "call", "system", "Popen",
})

_FILE_PATH_ARG_KEYS = (
    "file_path", "filepath", "path", "file", "filename",
    "source", "src", "doc", "document", "data_path", "input_file",
)

_PATH_LIKE_RE = re.compile(
    r"[\\/]|\.(?:xlsx?|csv|tsv|json|parquet|txt|png|jpe?g|pdf)$",
    re.IGNORECASE,
)


def _path_like(value) -> bool:
    """True when a string reads as a file path β€” contains a path

    separator, or ends with a data-file extension (so bare 'data.xlsx'

    counts, but 'sum' / 'αžαŸαžαŸ’αž' never do). Non-strings and empty strings

    are never paths."""
    if not isinstance(value, str) or not value.strip():
        return False
    return bool(_PATH_LIKE_RE.search(value))


def _normalize_path(path: str) -> str:
    """Canonical form of a file path for fingerprint comparison: strip

    quotes, unify separators to '/', lowercase everything (Windows paths

    are case-insensitive β€” this app ships on the Microsoft Store) and

    collapse duplicate slashes β€” so the same file written as

    'G:\\\\Data\\\\A.XLSX', r'G:\\data\\a.xlsx' or 'g:/data/a.xlsx' all compare

    equal. Never raises; garbage input degrades to its stripped self."""
    try:
        p = (path or "").strip().strip("\"'")
        p = p.replace("\\", "/")
        p = p.lower()
        p = re.sub(r"/+", "/", p)
        return p.rstrip("/")
    except Exception:
        return str(path or "")


def _arg_value_str(value, consts) -> str:
    """Stringify one call argument for the fingerprint's 'effective

    arguments' slot: constants and simple variable assignments resolve to

    their real values (so a literal 'sum' and a variable holding 'sum'

    compare equal); anything unparseable degrades to its AST node type β€”

    never raises."""
    try:
        if isinstance(value, ast.Constant):
            return repr(value.value)
        if isinstance(value, ast.Name) and value.id in consts:
            return repr(consts[value.id])
        return repr(ast.literal_eval(value))
    except Exception:
        return f"<{type(value).__name__}>"


def _call_func_name(func) -> Optional[str]:
    """Bare name of the function a Call invokes: 'list_columns' for a

    plain Name, 'read_excel' for 'pd.read_excel' (attribute calls are

    normalized to their method name so the same tool imported directly or

    via a module compares equal). None for anything odd."""
    if isinstance(func, ast.Name):
        return func.id
    if isinstance(func, ast.Attribute):
        return func.attr
    return None


def _call_file_path(node, consts):
    """The data-file path a Call reads/writes, or None. The curated Data

    tools' first positional argument IS the file path; path-named

    keywords (file_path=/path=/file=...) are also accepted. Name

    arguments resolve through simple string assignments ('path =

    "G:\\..."; list_columns(path)'). Returns (path, True) when the path

    was positional, (path, False) when it came from a keyword β€” the

    caller uses that to know which arguments are the 'effective

    arguments' and which was the file itself."""
    def _str_of(v):
        if isinstance(v, ast.Constant) and isinstance(v.value, str):
            return v.value
        if isinstance(v, ast.Name) and v.id in consts:
            return consts[v.id]
        return None

    if node.args:
        p = _str_of(node.args[0])
        if p is not None:
            return p, True
    for kw in node.keywords:
        if kw.arg in _FILE_PATH_ARG_KEYS:
            p = _str_of(kw.value)
            if p is not None:
                return p, False
    return None


def _code_file_access_fps(code_text: str) -> tuple:
    """Parse a Python program and return the sorted tuple of

    (tool, normalized_path, effective_args) fingerprints for EVERY call

    that accesses a data file with a resolvable string path. The

    'effective arguments' (everything but the file itself) make two calls

    to the SAME file with DIFFERENT operations (aggregate by αžαŸαžαŸ’αž vs by

    αž—αŸαž‘) distinct fingerprints β€” only a genuinely repeated operation on

    the same file collapses. Returns () when the code doesn't parse or

    nothing touches a file β€” the caller treats that as 'no file loop',

    never a crash."""
    if not code_text:
        return ()
    try:
        tree = ast.parse(code_text)
    except Exception:
        return ()
    # Resolve simple module-level string assignments ('path = "G:\\..."')
    # so calls passing the file via a variable fingerprint identically to
    # calls inlining the literal.
    consts = {}
    for node in ast.walk(tree):
        if isinstance(node, ast.Assign) and isinstance(node.value, ast.Constant) \
                and isinstance(node.value.value, str) and len(node.targets) == 1 \
                and isinstance(node.targets[0], ast.Name):
            consts[node.targets[0].id] = node.value.value
        elif isinstance(node, ast.AnnAssign) and isinstance(node.value, ast.Constant) \
                and isinstance(node.value.value, str) and isinstance(node.target, ast.Name):
            consts[node.target.id] = node.value.value
    pairs = set()
    for node in ast.walk(tree):
        if not isinstance(node, ast.Call):
            continue
        name = _call_func_name(node.func)
        if name is None:
            continue
        name_l = name.lower()
        # Incidental setup/utility calls (os.makedirs, os.path.join, …)
        # are noise β€” they never represent the repeated data access, and a
        # model that interleaves one with its re-reads must still collapse
        # to the same fingerprint (see the section comment).
        if name_l in _INCIDENTAL_TOOL_NAMES:
            continue
        found = _call_file_path(node, consts)
        if found is None:
            continue
        path, path_pos = found
        # Only a real path (separator or data-file extension) is a file
        # access β€” a bare column name, an agg value or a print() string
        # must never count as 'reading the file'.
        if not _path_like(path):
            continue
        if path_pos:
            rest = list(node.args[1:])
        else:
            rest = list(node.args)
        vals = [_arg_value_str(a, consts) for a in rest]
        vals.extend(
            f"{kw.arg}={_arg_value_str(kw.value, consts)}"
            for kw in node.keywords if kw.arg not in _FILE_PATH_ARG_KEYS)
        pairs.add((name.lower(), _normalize_path(path), tuple(sorted(vals))))
    return tuple(sorted(pairs))


def _file_access_fingerprint(step):
    """Coarser loop key than `_tool_calls_signature`: a sorted tuple of

    (tool, normalized_path, effective_args) for every call in the step

    that accesses a data file. CodeAgent steps (python_interpreter) are

    parsed from the code text; ToolCallingAgent steps read path-named

    string values from their arguments dict. Returns None when the step

    carries no file access β€” the file loop channel stands down. Never

    raises; odd step shapes just return None."""
    try:
        tcs = getattr(step, "tool_calls", None)
        if not tcs:
            return None
        pairs = []
        for tc in tcs:
            name = getattr(tc, "name", None)
            if name is None and isinstance(tc, dict):
                name = tc.get("name")
            args = getattr(tc, "arguments", None)
            if args is None and isinstance(tc, dict):
                args = tc.get("arguments")
            if name is None:
                continue
            if name == "python_interpreter":
                if isinstance(args, str):
                    pairs.extend(_code_file_access_fps(args))
                continue
            if isinstance(args, dict):
                name_l = str(name).lower()
                if name_l in _INCIDENTAL_TOOL_NAMES:
                    continue
                path_key = next(
                    (k for k in _FILE_PATH_ARG_KEYS
                     if _path_like(args.get(k))), None)
                if path_key is not None:
                    sem = tuple(sorted(
                        str(v) for k, v in args.items() if k != path_key))
                    pairs.append(
                        (name_l, _normalize_path(args[path_key]), sem))
        if not pairs:
            return None
        return tuple(sorted(set(pairs)))
    except Exception:
        return None


def _file_fp_call_names(ffp) -> str:
    """Human-readable label of a repeated (tool, file) fingerprint for the

    loop abort message: the tool name plus the data file's basename (e.g.

    'list_columns on data.xlsx') β€” far more actionable than the generic

    python_interpreter executor name when the model is stuck re-reading

    one file. Returns '' for empty fingerprints."""
    try:
        if not ffp:
            return ""
        name, path, _sem = ffp[0]
        base = path.rstrip("/").rsplit("/", 1)[-1] or path
        if len(base) > 60:
            base = base[:57] + "…"
        return f"{name} on {base}"
    except Exception:
        return ""


def _inject_loop_nudge(agent, lang_key: str = "kh") -> bool:
    """Append a corrective assistant message to the agent's memory telling

    the model the repeated call's output is already in its context β€” the

    standard cure for the degenerate repetition loop (fresh context breaks

    the deterministic re-generation). The appended step renders as a plain

    assistant message in the model's next prompt (ActionStep.to_messages

    turns model_output into an assistant ChatMessage). Returns False when

    the memory isn't writable (never raises)."""
    try:
        if agent is None:
            return False
        memory = getattr(agent, "memory", None)
        if memory is None or not hasattr(memory, "steps"):
            return False
        l = i18n.LANGUAGES.get(lang_key, i18n.LANGUAGES["kh"])
        nudge = l.get("agent_loop_nudge", "")
        if not nudge:
            return False
        try:
            from smolagents.memory import ActionStep
        except Exception:
            return False
        memory.steps.append(ActionStep(step_number=len(memory.steps) or 1,
                                       timing=None, model_output=nudge))
        return True
    except Exception:
        return False


def _loop_nudge_bubble(lang_key: str = "kh") -> str:
    """User-visible line shown when the loop guard injected the corrective

    reminder β€” so the streamed log shows the app intervened, not just the

    model's identical steps."""
    l = i18n.LANGUAGES.get(lang_key, i18n.LANGUAGES["kh"])
    return l.get("agent_loop_nudge_bubble",
                 "⚠️ The model repeated the same tool call β€” a reminder was sent to continue.")


def _rejected_at_delivery(text) -> bool:
    """True when `text` fails the shared final-answer validator at the

    DELIVERY choke point. smolagents only runs `final_answer_checks`

    against an EXPLICIT final_answer() tool call β€” the max-steps fallback

    (provide_final_answer) ships the model's raw last output with NO

    validation, which is exactly how the Muse-Glimmer deliberation

    monologue ("We need to gather more detailed info … Let's call

    web_search_agent …") reached the answer bubble after burning all 12

    steps. Re-checking here closes that gap; a validator hiccup must

    never block delivery, so any exception passes the text through."""
    try:
        from agents.agent_factory import reject_leaked_or_empty_final_answer
        return not reject_leaked_or_empty_final_answer(text)
    except Exception:
        return False


def _rejected_answer_bubble(lang_key: str = "kh") -> str:
    """Honest bilingual replacement for a final answer that failed the

    delivery-time validation β€” never ship the raw garbage instead."""
    l = i18n.LANGUAGES.get(lang_key, i18n.LANGUAGES["kh"])
    return l.get(
        "agent_final_answer_rejected",
        "⚠️ The model could not produce a valid final answer β€” its last "
        "output was internal task reasoning, not an actual report (the run "
        "reached its step limit). Try running the research again, or use a "
        "stronger model (e.g. Gemma-4-E4B or above).")


def _agent_steps_budget_txt(agent) -> str:
    """The EFFECTIVE step budget(s) the built agent actually runs with β€” the

    number that really capped this turn, read off the agent object

    (agent.max_steps, plus each managed sub-agent's max_steps: RAG's

    knowledge_searcher, Deep Research's web_search_agent, Data Analysis's

    data_worker). This is what

    'what actually ran' means: when the per-tab Max Steps control is on

    'auto', the builder applied the model-scaled default (see

    model_registry.get_max_steps_for_model) inside get_*_agent, so the

    request value passed in was None while the agent runs a scaled number β€”

    the footer must reflect the latter. Returns 'steps: N' or

    'steps: N (+M <label>)' (label derived from the managed agent's name:

    'search' for the RAG/Deep Research searchers, 'data worker' for Data

    Analysis), or '' when the agent exposes no budget (never breaks a

    footer on an odd/None agent). Shared by the General / RAG / Deep

    Research / Data Analysis footers (the chat.py call sites keep the

    same-name alias for continuity)."""
    if agent is None:
        return ""
    steps = getattr(agent, "max_steps", None)
    if steps is None:
        return ""
    txt = f"steps: {steps}"
    subs = []
    # smolagents 1.26 stores managed_agents as {name: agent}; guard the shape
    # anyway so a hand-built/older agent can never turn the footer into an
    # error (the helper is called inside each chat path's try/except).
    managed = getattr(agent, "managed_agents", None)
    if not isinstance(managed, dict):
        return txt
    # The label comes from the managed agent's NAME (the dict key β€” smolagents
    # 1.26+ stores managed_agents as {name: agent}): RAG's
    # knowledge_searcher / Deep Research's web_search_agent read as 'search',
    # Data Analysis's data_worker reads as 'data worker', and an unknown
    # name falls back to the generic 'worker'. The same helper serves all
    # four agentic tabs, so the footer stays accurate now that a non-search
    # managed agent exists.
    for sub_name, sub in managed.items():
        s = getattr(sub, "max_steps", None)
        if s is not None:
            name_l = str(sub_name or "").lower()
            if "search" in name_l:
                label = "search"
            elif "data" in name_l:
                label = "data worker"
            else:
                label = "worker"
            subs.append(f"{s} {label}")
    if subs:
        txt += f" (+{'/'.join(subs)})"
    return txt


def _agent_exec_timeout_txt(agent) -> str:
    """The EFFECTIVE per-step execution timeout (seconds) the built agent

    actually runs with β€” read off the agent's Python executor

    (agent.python_executor.timeout_seconds), which ONLY exists on a

    CodeAgent. A ToolCallingAgent never executes Python, so it has no

    executor and the footer must not claim a timeout β€” gating on the

    executor's presence is exactly the 'when the tab runs a CodeAgent'

    condition. Exception: the Data Analysis MANAGER is a ToolCallingAgent

    whose Python executor lives on its managed `data_worker` CodeAgent β€”

    when the agent itself has no executor, the helper falls through to its

    managed agents before giving up. The executor's timeout_seconds is the

    value the factory really applied: the explicit per-tab Exec timeout, or

    smolagents' own 30s default when the control is on auto. Returns

    'exec timeout: Ns' or '' when there is no executor / no timeout (never

    breaks a footer on an odd/None agent)."""
    if agent is None:
        return ""
    executor = getattr(agent, "python_executor", None)
    if executor is None:
        # A ToolCallingAgent manager whose Python executor lives on a
        # managed CodeAgent sub-agent (the Data Analysis manager + its
        # data_worker): surface the worker's executor timeout. All other
        # tabs' managed agents are ToolCallingAgents too (no executor), so
        # the fallthrough only ever fires for the Data Analysis tab.
        managed = getattr(agent, "managed_agents", None)
        if isinstance(managed, dict):
            for sub in managed.values():
                executor = getattr(sub, "python_executor", None)
                if executor is not None:
                    break
    if executor is None:
        return ""
    seconds = getattr(executor, "timeout_seconds", None)
    if seconds is None:
        return ""
    return f"exec timeout: {int(seconds)}s"


# ── Managed-sub-agent max-steps findings hand-off ──────────────────────
# When a managed sub-agent (Data Analysis's `data_worker`, Deep Research's
# `web_search_agent`, …) burns its whole step budget without emitting a
# real final_answer, smolagents' `_handle_max_steps_reached` fallback
# takes the model's RAW last-ditch text as the sub-agent's return β€” the
# manager then receives a leaked code fence / channel marker instead of
# the findings the sub-agent actually COMPUTED/GATHERED (the Muse Glimmer
# Data-leg failure; the same runs' DR search agent shipped `to=user<|eot|>`
# as its "final answer"). The REAL findings live in the sub-agent's
# ActionStep observations (the verbatim tool outputs). The two helpers
# below are the shared cure: collect the run's observations, and prefer
# them over the model's surrender at max steps. Both the data worker and
# the DR search agent instance-patch their `_handle_max_steps_reached`
# onto `max_steps_findings_handoff` at build time (see the *_agent.py
# builders).


def collect_agent_observations(agent, cap: int = 8000) -> str:
    """A managed sub-agent's run transcript β€” the verbatim tool outputs it

    COMPUTED/GATHERED but never delivered via final_answer. Joins every

    non-empty ActionStep observation in run order (list-shaped

    observations flattened, exact duplicates dropped), capped at `cap`

    chars. Returns '' when there is nothing meaningful. NEVER raises.



    Shared by the Data Analysis `data_worker` (cap 8000 β€” its findings

    are compact tables) and the Deep Research `web_search_agent` (larger

    cap β€” its findings are verbatim search results / page contents)."""
    try:
        memory = getattr(agent, "memory", None)
        steps = getattr(memory, "steps", None)
        if not steps:
            return ""
        parts = []
        seen = set()
        for step in steps:
            obs = getattr(step, "observations", None)
            if isinstance(obs, list):
                text = "\n".join(str(o) for o in obs if str(o).strip())
            else:
                text = str(obs or "")
            text = text.strip()
            if not text or text in seen:
                continue
            seen.add(text)
            parts.append(text)
        transcript = "\n\n".join(parts)
        if len(transcript) > cap:
            transcript = transcript[:cap]
        return transcript.strip()
    except Exception:
        return ""


def max_steps_findings_handoff(self, task, cap: int = 8000):
    """The managed-sub-agent max-steps fallback (instance-patched onto the

    sub-agent's `_handle_max_steps_reached` at build time): when

    smolagents' stock handler produces the model's last-ditch raw-text

    answer, prefer the run's REAL findings β€” the verbatim tool

    observations β€” so the manager receives the computed/gathered content

    instead of a leaked envelope or channel marker. Falls back to the

    stock answer when there are no meaningful observations. NEVER raises."""
    orig = getattr(self, "_orig_handle_max_steps_reached", None)
    try:
        model_answer = orig(task) if orig is not None else None
    except Exception:
        model_answer = None
    findings = collect_agent_observations(self, cap=cap)
    if findings:
        return findings
    return model_answer


def _build_abort_message(lang_key: str = "kh", diagnostics: Optional[dict] = None) -> str:
    """Bilingual fail-fast guidance message (see i18n 'agent_error_abort').



    When the run's diagnostics carry a captured `last_error`, the ACTUAL

    failing error (e.g. `KeyError: 'Quantity'`) is appended so the user sees

    what really went wrong instead of a generic model-size guess β€” the

    concrete cause is far more actionable than "try a bigger model"."""
    l = i18n.LANGUAGES.get(lang_key, i18n.LANGUAGES["kh"])
    d = diagnostics or {}
    if d.get("loop_detected"):
        # Repetition-loop abort (see the loop guard section): the model
        # kept re-emitting the SAME tool call even after the corrective
        # nudge β€” surface the repeated call instead of an error guess.
        msg = l.get("agent_loop_abort",
                    "⚠️ The model kept calling the same tool over and over β€” the run was stopped to save time.")
        call = (d.get("loop_call") or "").strip()
        if call:
            label = l.get("agent_loop_abort_last_call", "Repeated tool call: {call}")
            try:
                label = label.format(call=call)
            except (KeyError, ValueError):
                label = f"Repeated tool call: {call}"
            msg = f"{msg}\n\n{label}"
        return msg
    msg = l.get("agent_error_abort",
                "⚠️ The model kept failing β€” the run was stopped to save time.")
    err = d.get("last_error")
    if err:
        label = l.get("agent_abort_last_error", "Last error: {err}")
        try:
            label = label.format(err=err)
        except (KeyError, ValueError):
            label = f"Last error: {err}"
        msg = f"{msg}\n\n{label}"
    return msg


def _agent_abort_html(lang_key: str = "kh",

                      diagnostics: Optional[dict] = None) -> str:
    """Bilingual fail-fast abort badge + "Why did this happen?" expander

    rendered by the chat handlers (chat.py / data_analysis.py) when the

    fail-fast guard STOPPED the run. Returns '' for clean runs and for runs

    that merely stumbled β€” those get chat.py's soft `_agent_failure_hint()`

    footer instead. The abort message itself (`_build_abort_message`)

    already carries the base guidance; this adds the visible badge and a

    deeper explanation using the run's ACTUAL failure numbers

    ({max_consecutive_errors} consecutive errored steps out of

    {total_steps}).



    Shared here (not in chat.py) because Data Analysis also consumes the

    streamed diagnostics and renders the same badge β€” one helper, one

    place to update the UI treatment."""
    d = diagnostics or {}
    if not d.get("aborted"):
        return ""
    l = i18n.LANGUAGES.get(lang_key, i18n.LANGUAGES["kh"])
    if d.get("loop_detected"):
        # Repetition-loop variant of the badge β€” the run was stopped because
        # the model repeated the same tool call, not because steps failed.
        badge = l.get("agent_loop_abort_badge", "⚠️ Loop detected β€” run stopped")
        why = l.get("agent_abort_why", "πŸ€” Why did this happen?")
        explanation = l.get("agent_loop_abort_explanation", "")
        if explanation:
            try:
                explanation = explanation.format(
                    steps=d.get("total_steps", 0) or 0,
                    call=d.get("loop_call") or "",
                )
            except (KeyError, ValueError):
                # A future translation edit that leaves a stray {...} must
                # never nuke the whole chat response into a traceback β€” keep
                # the raw template text instead.
                pass
        last_call = (d.get("loop_call") or "").strip()
        last_call_html = ""
        if last_call:
            label = l.get("agent_loop_abort_last_call", "Repeated tool call: {call}")
            try:
                label = label.format(call=last_call)
            except (KeyError, ValueError):
                label = f"Repeated tool call: {last_call}"
            last_call_html = (
                f'\n<div class="agent-err-box"><b>{label}</b></div>'
            )
        return (
            "\n\n" +
            f'<div class="abort-badge">{badge}</div>\n'
            f'<details class="abort-details">\n'
            f'<summary class="agent-step-summary">{why}</summary>\n'
            f'<div class="agent-log-block">\n'
            f'<div class="agent-err-box">{explanation}</div>\n'
            f'{last_call_html}\n'
            f'</div>\n</details>'
        )
    badge = l.get("agent_abort_badge", "⚠️ Run stopped early")
    why = l.get("agent_abort_why", "πŸ€” Why did this happen?")
    explanation = l.get("agent_abort_explanation", "")
    if explanation:
        try:
            explanation = explanation.format(
                errors=d.get("max_consecutive_errors", 0) or 0,
                steps=d.get("total_steps", 0) or 0,
            )
        except (KeyError, ValueError):
            # A future translation edit that leaves a stray {...} must never
            # nuke the whole chat response into a traceback β€” keep the raw
            # template text instead.
            pass
    last_error = (d.get("last_error") or "").strip()
    last_error_html = ""
    if last_error:
        err_label = l.get("agent_abort_last_error", "Last error: {err}")
        try:
            err_label = err_label.format(err=last_error)
        except (KeyError, ValueError):
            err_label = f"Last error: {last_error}"
        last_error_html = (
            f'\n<div class="agent-err-box"><b>{err_label}</b></div>'
        )
    return (
        "\n\n" +
        f'<div class="abort-badge">{badge}</div>\n'
        f'<details class="abort-details">\n'
        f'<summary class="agent-step-summary">{why}</summary>\n'
        f'<div class="agent-log-block">\n'
        f'<div class="agent-err-box">{explanation}</div>\n'
        f'{last_error_html}\n'
        f'</div>\n</details>'
    )


def chunk_final_text(response: str, min_chars: int = 400,

                     chunk_chars: int = 320) -> list:
    """Split a long final response into display chunks for a progressive

    (streamed-looking) reveal in the chatbot β€” the generation itself

    completes before the reveal, but rendering the finished text in

    growing slices makes long answers feel substantially faster. Short

    responses return a single chunk (no change). Newline-aware so

    markdown structure isn't shredded; a single over-long line (no

    newlines) falls back to hard slicing."""
    if not response:
        return [""]
    if len(response) <= min_chars:
        return [response]
    lines = response.split("\n")
    chunks, cur = [], ""
    for i, ln in enumerate(lines):
        # Keep the trailing newline on each piece (except the very last
        # line) so "".join(chunks) reconstructs the original exactly β€”
        # dropping it at flush boundaries would shred the markdown.
        piece = ln + ("" if i == len(lines) - 1 else "\n")
        if cur and len(cur) + len(piece) > chunk_chars:
            chunks.append(cur)
            cur = piece
        else:
            cur += piece
    if cur:
        chunks.append(cur)
    if len(chunks) == 1 and len(chunks[0]) > min_chars:
        return [chunks[0][i:i + chunk_chars]
                for i in range(0, len(chunks[0]), chunk_chars)]
    return chunks


def stream_agent_steps(agent, task: str, reset: bool = True,

                       lang_key: str = "kh"):
    """Run `agent` on `task`, yielding live steps as they happen.



    See this module's docstring for the full (step_msg, is_final,

    final_output, diagnostics) contract every caller in this app relies on.



    In addition to that contract, this run is guarded by the fail-fast

    mechanism: `_ERROR_ABORT_THRESHOLD` consecutive errored steps abort the

    run early with bilingual guidance (yielded as the final message).    A second guard, the repetition-loop guard, catches the model that repeats

    the SAME successful tool call over and over: on `_LOOP_NUDGE_THRESHOLD`

    identical consecutive calls it first injects a corrective reminder into

    the agent's memory (nudging the model to use the data it already has),

    and aborts with bilingual guidance if the same call repeats after that.

    A second detector within the same guard keys on the coarser

    same-tool + same-file fingerprint (parsed from the code / call

    arguments, paths normalized), so a model that keeps re-reading the SAME

    data file with the SAME tool while varying the surrounding code is

    caught too β€” each variant's full signature differs, but the file

    fingerprint collapses them.

    Each FINAL yield carries a snapshot of the run's diagnostics dict

    (total_steps / max_consecutive_errors / aborted / last_error) as its

    4th element,

    so callers never need to read `get_last_run()` after the loop β€” see

    chat.py's `_agent_failure_hint()`. Intermediate yields carry None

    there. The thread-local `get_last_run()` remains the internal backing

    store (and a debugging surface), updated in place as steps arrive.

    """
    # Reset the per-thread diagnostics FIRST, before any code path (including
    # the no-streaming TypeError fallback below) so a run can never leave or
    # inherit stale failure data from a previous run on this thread.
    last_run = get_last_run()
    last_run.update({"total_steps": 0, "max_consecutive_errors": 0, "aborted": False,
                     "last_error": "", "loop_detected": False, "loop_call": ""})
    try:
        run_result = agent.run(task, reset=reset, stream=True)
    except TypeError:
        # Installed smolagents version doesn't accept stream= at all β€”
        # fall back to a single blocking call. No live steps, but the
        # caller still gets a real final answer.
        try:
            result = agent.run(task, reset=reset)
        except Exception as e:
            err_msg = {"role": "assistant", "content": _step_error_bubble(e, lang_key)}
            yield err_msg, True, _step_error_text(e, lang_key), dict(last_run)
            return
        yield None, True, result, dict(last_run)
        return

    # Tracks the most recent item that did NOT look like a full memory
    # step (ActionStep/PlanningStep/...). smolagents' own convention is
    # that the plain final answer is the last thing the stream yields
    # (see module docstring) β€” but some smolagents versions ALSO stream
    # finer-grained intermediate objects mid-run (e.g. raw ToolCall
    # objects, or streamed text-delta chunks) that are NOT the final
    # answer either, just noise to skip rather than display. A single
    # item's type alone can't tell us which case we're in β€” only once
    # the generator is fully exhausted do we know "the very last thing
    # it ever yielded" is genuinely the final answer, rather than a
    # preview of a step still to come. Finalizing on the FIRST
    # unrecognized item (an earlier version of this function did this)
    # incorrectly ended runs the moment ANY such intermediate object
    # appeared β€” sometimes after a single step β€” producing garbage like
    # a raw "ToolCall(name=..., arguments=...)" repr as the "final
    # answer" instead of letting the agent actually finish researching.
    candidate_final = None
    consecutive_errors = 0
    # Repetition-loop guard state (see the fail-fast section above): the
    # signature of the most recently executed tool call, how many
    # consecutive times it has repeated, and which signature has already
    # received the corrective nudge β€” a signature may only be nudged once;
    # a repeat AFTER the nudge means the model is truly stuck β†’ abort.
    prev_call_sig = None
    call_repeat_count = 0
    nudge_sent_for = None
    # Same-tool + same-file channel state (the coarser second detector):
    # which (tool, file) fingerprint the previous step touched, how many
    # consecutive times it has repeated, and which fingerprint already
    # received the corrective nudge β€” a fingerprint may only be nudged
    # once; a repeat AFTER the nudge means the model is truly stuck.
    prev_file_fp = None
    file_repeat_count = 0
    file_nudge_sent_for = None

    last_item = None
    try:
        try:
            for item in run_result:
                last_item = item

                # FinalAnswerStep (present in some newer smolagents
                # versions) is an EXPLICIT, unambiguous signal β€” it wraps
                # the actual completed final answer, so it's safe to act
                # on immediately instead of waiting for the generator to
                # end.
                if item.__class__.__name__ == "FinalAnswerStep":
                    final_answer = getattr(item, "final_answer", None)
                    if final_answer is None:
                        final_answer = getattr(item, "output", item)
                    # The max-steps fallback (provide_final_answer) can
                    # deliver the model's RAW tool-call text as the final
                    # answer (e.g. `call:final_answer{answer: "…"}`) with no
                    # parsing β€” unwrap the leaked envelope so the bubble
                    # shows the report, not the call syntax.
                    yield None, True, _unwrap_leaked_final_answer(final_answer), dict(last_run)
                    return

                if _is_memory_step(item):
                    last_run["total_steps"] += 1
                    msg_text = _format_step(item, lang_key)
                    if msg_text is not None:
                        yield {"role": "assistant", "content": msg_text}, False, None, None
                    # Fail-fast guard: consecutive errored steps mean the
                    # model is stuck (parse failures, tool exceptions,
                    # rejected final answers) β€” abort with guidance instead
                    # of burning the remaining step budget.
                    if getattr(item, "error", None):
                        consecutive_errors += 1
                        last_run["max_consecutive_errors"] = max(
                            last_run["max_consecutive_errors"], consecutive_errors)
                        last_run["last_error"] = _error_snippet(item.error)
                        if consecutive_errors >= _ERROR_ABORT_THRESHOLD:
                            last_run["aborted"] = True
                            abort_msg = _build_abort_message(lang_key, dict(last_run))
                            yield ({"role": "assistant", "content": abort_msg},
                                   True, abort_msg, dict(last_run))
                            return
                    else:
                        consecutive_errors = 0
                    # Repetition-loop guard: identical consecutive tool
                    # calls (SUCCESSFUL ones β€” the error guard above owns
                    # failed steps) mean the model is in the degenerate
                    # repeat-the-same-call loop that burns the whole step
                    # budget one slow generation at a time before
                    # surrendering with meta-commentary. Nudge once (the
                    # fresh context breaks the deterministic
                    # re-generation); abort if it still repeats after that.
                    sig = _tool_calls_signature(item)
                    if sig is None:
                        # No readable tool call (final-answer step, parse
                        # failure) β€” BOTH loop channels stand down.
                        prev_call_sig = None
                        call_repeat_count = 0
                        prev_file_fp = None
                        file_repeat_count = 0
                        file_nudge_sent_for = None
                    else:
                        # The coarser same-tool + same-file fingerprint is
                        # computed up front so the exact channel can hand
                        # its nudge off to it (see below).
                        ffp = _file_access_fingerprint(item)
                        if sig == prev_call_sig:
                            call_repeat_count += 1
                        else:
                            prev_call_sig = sig
                            call_repeat_count = 1
                            nudge_sent_for = None
                        if call_repeat_count >= _LOOP_NUDGE_THRESHOLD:
                            if nudge_sent_for != sig:
                                nudge_sent_for = sig
                                # The exact nudge covers this repeated file
                                # operation too β€” record it so the file
                                # channel below treats a later same-file
                                # repeat as 'after the nudge' β†’ abort,
                                # instead of nudging twice for the same
                                # underlying loop.
                                if ffp is not None:
                                    file_nudge_sent_for = ffp
                                if _inject_loop_nudge(agent, lang_key):
                                    yield ({"role": "assistant",
                                            "content": _loop_nudge_bubble(lang_key)},
                                           False, None, None)
                            else:
                                last_run["aborted"] = True
                                last_run["loop_detected"] = True
                                last_run["loop_call"] = _signature_call_names(sig)
                                abort_msg = _build_abort_message(lang_key, dict(last_run))
                                yield ({"role": "assistant", "content": abort_msg},
                                       True, abort_msg, dict(last_run))
                                return
                        else:
                            # Same-tool + same-file channel: a model stuck
                            # re-reading the SAME data file with the SAME
                            # tool while varying the surrounding code (each
                            # variant's full signature differs, so the
                            # exact channel above can't see the loop) is
                            # caught here by the coarser
                            # (tool, path, effective-args) fingerprint.
                            # Same nudge-once-then-abort lifecycle.
                            if ffp is None:
                                prev_file_fp = None
                                file_repeat_count = 0
                            else:
                                if ffp == prev_file_fp:
                                    file_repeat_count += 1
                                else:
                                    prev_file_fp = ffp
                                    file_repeat_count = 1
                                    file_nudge_sent_for = None
                                if file_repeat_count >= _LOOP_NUDGE_THRESHOLD:
                                    if file_nudge_sent_for != ffp:
                                        file_nudge_sent_for = ffp
                                        if _inject_loop_nudge(agent, lang_key):
                                            yield ({"role": "assistant",
                                                    "content": _loop_nudge_bubble(lang_key)},
                                                   False, None, None)
                                    else:
                                        last_run["aborted"] = True
                                        last_run["loop_detected"] = True
                                        last_run["loop_call"] = _file_fp_call_names(ffp)
                                        abort_msg = _build_abort_message(lang_key, dict(last_run))
                                        yield ({"role": "assistant", "content": abort_msg},
                                               True, abort_msg, dict(last_run))
                                        return
                    # Intra-run memory guard: a long single-run research
                    # (many web-search observations) can grow the manager's
                    # memory past the model's context window MID-RUN β€”
                    # llama-server then 400s every further step
                    # (exceed_context_size_error) and the run dies without
                    # an answer. Trim older/bloated steps BEFORE the next
                    # prompt is built when the estimate crosses the budget.
                    try:
                        from agents.agent_memory import guard_memory_within_run
                        guard_memory_within_run(agent)
                    except Exception:
                        pass
                    # A genuine step just happened β€” the agent is clearly
                    # still going, so any unrecognized "final answer
                    # candidate" picked up right before this was just
                    # noise from an earlier in-progress step, not the
                    # real final answer. Discard it.
                    candidate_final = None
                    continue

                # Not a recognized memory-step type. Could be the plain
                # final answer (the normal end-of-stream case), or it
                # could be an intermediate delta/tool-call object some
                # smolagents versions stream mid-step. Don't decide yet β€”
                # remember it and keep iterating; see candidate_final's
                # declaration above for why.
                candidate_final = item

            # The generator is genuinely exhausted now β€” whatever the
            # LAST unrecognized item was (if any) is the real final
            # answer.
            if candidate_final is not None:
                final_text = _unwrap_leaked_final_answer(candidate_final)
                if _rejected_at_delivery(final_text):
                    # The max-steps fallback (or a leaked non-answer) β€”
                    # never ship it; see _rejected_at_delivery's docstring.
                    last_run["aborted"] = True
                    last_run["last_error"] = "final answer rejected at delivery"
                    bubble = _rejected_answer_bubble(lang_key)
                    yield ({"role": "assistant", "content": bubble},
                           True, bubble, dict(last_run))
                    return
                yield None, True, final_text, dict(last_run)
            elif last_item is not None:
                # Every single item the whole run ever yielded was a
                # recognized memory step (no bare final answer ever
                # appeared, unusual but possible on some versions) β€”
                # fall back to that last step's own text rather than
                # yielding nothing.
                fallback_text = _format_step(last_item, lang_key) or ""
                if _rejected_at_delivery(fallback_text):
                    last_run["aborted"] = True
                    last_run["last_error"] = "final answer rejected at delivery"
                    bubble = _rejected_answer_bubble(lang_key)
                    yield ({"role": "assistant", "content": bubble},
                           True, bubble, dict(last_run))
                    return
                yield None, True, fallback_text, dict(last_run)
            else:
                yield None, True, "", dict(last_run)
        except Exception as e:
            err_msg = {"role": "assistant", "content": _step_error_bubble(e, lang_key)}
            yield err_msg, True, _step_error_text(e, lang_key), dict(last_run)
            return
    finally:
        # See this function's matching comment above the `try:` this is
        # attached to (module docstring section on version compatibility)
        # β€” proactively close the underlying smolagents step generator
        # ourselves, synchronously, rather than leaving it for CPython's
        # garbage collector to close at some later, unpredictable point.
        # If `run_result` was abandoned mid-iteration (an early `return`
        # above, after an error or once the final answer arrived), Python
        # will eventually GC it and call its own `.close()`, sending it a
        # GeneratorExit. Some smolagents versions' internal
        # `MultiStepAgent._run_stream` generator doesn't handle that
        # cleanly β€” it keeps yielding instead of stopping β€” which raises
        # "RuntimeError: generator ignored GeneratorExit", printed by the
        # interpreter as a scary but harmless "Exception ignored in: ..."
        # warning during cleanup (it does not propagate into this app's
        # own control flow or crash the run β€” the real answer above has
        # already been yielded by this point). Closing it here instead,
        # while we still hold a live reference to it, and swallowing that
        # specific error, prevents the noisy warning entirely.
        try:
            run_result.close()
        except RuntimeError:
            pass
        except Exception:
            pass