File size: 110,971 Bytes
5b48487
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# ===== file: gateway/backing.py =====
"""Pluggable backing stores for the harness gateway.

The gateway needs three capabilities from the outside world, and nothing else:

  GraphStore   — session/harness/response/api-key records + ownership edges
  BlobStore    — traces, response records, workspace checkpoints, produced files
  SecretStore  — model-provider connections/policies ("bring your own keys")

Two implementations of each:

  local (this file)      — SQLite + filesystem + env/file, zero cloud dependencies. The whole
                           gateway runs on a laptop: HR_BACKING=local (or just leave
                           VG_GATEWAY_URL unset). Point POOL_MGMT_ENDPOINT at a single runner
                           process (the pool is only an identifier-routing proxy in front of
                           runner replicas — the routes are identical).
  vg (backing_vg.py)     — the production AgentStudio infra: vg-gateway (Cosmos graph + Azure
                           blob) and the vault service. Verbatim the code that always ran here.

Selection is one env var: HR_BACKING=vg|local; unset = vg when VG_GATEWAY_URL is set, local
otherwise. The interface is deliberately SEMANTIC (get/upsert/find/add_edge), not query-shaped:
call sites never build backend query strings, so an implementation is free to be a graph, a
relational table, or anything else that can look up records by label + property equality.
"""
from __future__ import annotations

import asyncio
import base64
import contextlib
import hashlib
import secrets as secrets_mod
import io
import json
import mimetypes
import os
import posixpath
import re
import shutil
import sqlite3
import tarfile
import time
import uuid
from pathlib import Path
from typing import Protocol

import httpx


# ── interfaces ────────────────────────────────────────────────────────────────────
class GraphStore(Protocol):
    async def get(self, vid: str, label: str | None = None) -> dict | None: ...
    async def upsert(self, label: str, vid: str, props: dict, *, raise_on_fail: bool = False) -> None: ...
    async def add_edge(self, label: str, src: str, dst: str) -> None: ...
    async def find(self, label: str, eq: dict | None = None, neq: dict | None = None) -> list[dict]: ...
    async def delete(self, vid: str, label: str | None = None) -> bool:
        """Remove one vertex and its edges; False when there was none (or the label differs)."""
        ...
    async def probe(self) -> None:
        """Raise if the store is unreachable/misconfigured. Used by /readyz, which must FAIL on a
        broken plane — the normal read paths swallow errors and return empty."""
        ...


class BlobStore(Protocol):
    async def get(self, kb: str, file_id: str) -> bytes | None: ...
    async def put(self, kb: str, file_id: str, data: bytes) -> bool: ...
    async def delete(self, kb: str, file_id: str) -> bool: ...
    async def list(self, kb: str, prefix: str, limit: int = 20, cursor: str | None = None) -> dict: ...
    async def probe(self) -> None: ...


class SecretStore(Protocol):
    async def get(self, tenant: str, name: str) -> str | None: ...
    async def delete(self, tenant: str, name: str) -> None:
        """Forget a stored secret; nothing happens when there is none."""
        ...

    async def put(self, tenant: str, name: str, value: str, *,
                  require_encryption: bool = False) -> None:
        """`require_encryption=True` is the caller saying "this is a customer credential, not a
        provider key injected by the operator" — a database connection string, for instance. A
        store that cannot encrypt must raise SecretsNotConfigured rather than write it in the
        clear. Part of the interface, not of one implementation: a datasource must be refused
        the same way whichever backing is configured."""
        ...


class WorkspaceFiles(Protocol):
    """Reading and writing one file inside a session's workspace.

    Two environments, genuinely different storage, one interface:

    * **Self-hosted** — the runner shares this container and the workspace is a live directory on
      the data volume. A write is a write.
    * **Hosted** — sandboxes are ephemeral, so between turns a workspace exists ONLY as the
      checkpoint tarball in blob storage (`sessions/<sid>/workspace.tgz`). A write has to rewrite
      that archive, because there is no filesystem to write to until the next turn hydrates one.

    This exists so an app built on a Harness can own state the agent also edits — the slides kit
    keeps deck.json here — without either side needing to know which deployment it is running in.
    """
    async def read(self, sid: str, path: str) -> bytes | None: ...
    async def write(self, sid: str, path: str, data: bytes) -> bool: ...


class Backing:
    def __init__(self, graph: GraphStore, blob: BlobStore, secrets: SecretStore, mode: str,
                 workspace: "WorkspaceFiles"):
        self.graph, self.blob, self.secrets, self.mode = graph, blob, secrets, mode
        self.workspace = workspace


# ── local: SQLite graph ───────────────────────────────────────────────────────────
class SqliteGraphStore:
    """Vertices/edges in one SQLite file. VG upsert semantics preserved: property() sets the
    listed props and keeps the rest (merge, not replace); edge ids are the same uuid5(src|label|dst)
    so re-adds are idempotent. find() filters by property equality in Python — dev-scale data,
    no json_extract dialect games."""

    def __init__(self, path: str):
        self._path = path
        Path(path).parent.mkdir(parents=True, exist_ok=True)
        with self._conn() as c:
            c.execute("CREATE TABLE IF NOT EXISTS vertices (vid TEXT PRIMARY KEY, label TEXT NOT NULL, props TEXT NOT NULL)")
            c.execute("CREATE INDEX IF NOT EXISTS idx_vertices_label ON vertices(label)")
            c.execute("CREATE TABLE IF NOT EXISTS edges (eid TEXT PRIMARY KEY, label TEXT NOT NULL, src TEXT NOT NULL, dst TEXT NOT NULL)")

    def _conn(self) -> sqlite3.Connection:
        c = sqlite3.connect(self._path, timeout=30)
        c.execute("PRAGMA journal_mode=WAL")
        return c

    async def get(self, vid: str, label: str | None = None) -> dict | None:
        def _do():
            with self._conn() as c:
                row = c.execute("SELECT vid, label, props FROM vertices WHERE vid=?", (vid,)).fetchone()
            if not row:
                return None
            if label is not None and row[1] != label:
                return None      # label filter is load-bearing where the id is caller-controlled
            return {"id": row[0], **json.loads(row[2])}
        return await asyncio.to_thread(_do)

    async def upsert(self, label: str, vid: str, props: dict, *, raise_on_fail: bool = False) -> None:
        clean = {k: str(v) for k, v in props.items()}   # VG stores string props; keep parity

        def _do():
            with self._conn() as c:
                row = c.execute("SELECT props FROM vertices WHERE vid=?", (vid,)).fetchone()
                merged = {**(json.loads(row[0]) if row else {}), **clean}
                c.execute("INSERT INTO vertices(vid,label,props) VALUES(?,?,?) "
                          "ON CONFLICT(vid) DO UPDATE SET props=excluded.props",
                          (vid, label, json.dumps(merged)))
        try:
            await asyncio.to_thread(_do)
        except Exception:
            if raise_on_fail:
                raise RuntimeError("graph write failed")

    async def add_edge(self, label: str, src: str, dst: str) -> None:
        if not (src and dst):
            return
        eid = str(uuid.uuid5(uuid.NAMESPACE_URL, f"{src}|{label}|{dst}"))

        def _do():
            with self._conn() as c:
                c.execute("INSERT OR IGNORE INTO edges(eid,label,src,dst) VALUES(?,?,?,?)",
                          (eid, label, src, dst))
        try:
            await asyncio.to_thread(_do)
        except Exception:  # noqa: BLE001 — best-effort, matches VG edge semantics
            pass

    async def delete(self, vid: str, label: str | None = None) -> bool:
        def _do():
            with self._conn() as c:
                row = c.execute("SELECT label FROM vertices WHERE vid=?", (vid,)).fetchone()
                if not row or (label is not None and row[0] != label):
                    return False
                c.execute("DELETE FROM vertices WHERE vid=?", (vid,))
                c.execute("DELETE FROM edges WHERE src=? OR dst=?", (vid, vid))
                return True
        try:
            return await asyncio.to_thread(_do)
        except Exception:  # noqa: BLE001
            return False

    async def find(self, label: str, eq: dict | None = None, neq: dict | None = None) -> list[dict]:
        def _do():
            with self._conn() as c:
                rows = c.execute("SELECT vid, props FROM vertices WHERE label=?", (label,)).fetchall()
            out = []
            for vid, props_json in rows:
                p = json.loads(props_json)
                if eq and any(str(p.get(k, "")) != str(v) for k, v in eq.items()):
                    continue
                if neq and any(str(p.get(k, "")) == str(v) for k, v in neq.items()):
                    continue
                out.append({"id": vid, **p})
            return out
        try:
            return await asyncio.to_thread(_do)
        except Exception:  # noqa: BLE001
            return []

    async def probe(self) -> None:
        def _do():
            with self._conn() as c:
                c.execute("SELECT 1 FROM vertices LIMIT 1").fetchone()
        await asyncio.to_thread(_do)


# ── local: filesystem blobs ───────────────────────────────────────────────────────
class FileBlobStore:
    """Objects as plain files under {root}/{kb}/{file_id}. Listing is ascending-lexical over the
    relative keys — the SAME ordering contract the trace machinery relies on from Azure blob
    listing (inverted-timestamp keys ⇒ newest-first)."""

    def __init__(self, root: str):
        self._root = Path(root)

    def _p(self, kb: str, file_id: str) -> Path:
        p = (self._root / kb / file_id).resolve()
        base = (self._root / kb).resolve()
        if not str(p).startswith(str(base)):        # refuse path escape
            raise ValueError(f"blob id escapes store: {file_id!r}")
        return p

    async def get(self, kb: str, file_id: str) -> bytes | None:
        def _do():
            try:
                return self._p(kb, file_id).read_bytes()
            except (OSError, ValueError):
                return None
        return await asyncio.to_thread(_do)

    async def put(self, kb: str, file_id: str, data: bytes) -> bool:
        if not data:
            return False

        def _do():
            try:
                p = self._p(kb, file_id)
                p.parent.mkdir(parents=True, exist_ok=True)
                tmp = p.with_suffix(p.suffix + ".tmp")
                tmp.write_bytes(data)
                tmp.replace(p)                      # atomic: a torn write never replaces a good blob
                return True
            except (OSError, ValueError):
                return False
        return await asyncio.to_thread(_do)

    async def delete(self, kb: str, file_id: str) -> bool:
        def _do():
            try:
                path = self._p(kb, file_id)
                path.unlink(missing_ok=True)
            except (OSError, ValueError):
                return False
            # The directories a key's slashes created go with the last object in them, up to the
            # store root. A blob store has no directories; this one only borrows them from the file
            # system, and left alone they outlive every object: hr-test held 3,696 empty
            # sessions/<sid>/ shells on 2026-09-16, one per session ever deleted. rmdir refuses a
            # directory that still holds anything, which is the whole check.
            base = (self._root / kb).resolve()
            for parent in path.parents:
                if parent == base or base not in parent.parents:
                    break
                try:
                    parent.rmdir()
                except OSError:
                    break
            return True
        return await asyncio.to_thread(_do)

    async def purge(self, kb: str, prefix: str) -> None:
        """Remove everything under a folder-shaped prefix ("sessions/<sid>/"), including the
        temporary files a torn write leaves and `list` does not show. A deleted session's folder
        held a lone `changed.json.tmp` after every listed object was gone (hr-test copy,
        2026-10-08)."""
        def _do():
            base = (self._root / kb).resolve()
            if not prefix.endswith("/") or prefix.strip("/") == "":
                return
            top = (base / prefix).resolve()
            if top == base or base not in top.parents or not top.is_dir():
                return
            shutil.rmtree(top, ignore_errors=True)
            for parent in top.parents:
                if parent == base or base not in parent.parents:
                    break
                try:
                    parent.rmdir()
                except OSError:
                    break
        await asyncio.to_thread(_do)

    async def list(self, kb: str, prefix: str, limit: int = 20, cursor: str | None = None) -> dict:
        # Walk only the subtree the prefix names: everything before its last "/" is a directory
        # under the store, the rest a name prefix inside it. Walking the whole store cost every
        # blob on every call, and a paged listing repeated the walk per page: with 15k blobs on a
        # self-hosted volume one turns read took 55 s and the gateway sat at 150% CPU (2026-09-06).
        def _do():
            base = (self._root / kb).resolve()
            dir_part, _, _ = prefix.rpartition("/")
            top = (base / dir_part).resolve() if dir_part else base
            if not str(top).startswith(str(base)) or not top.is_dir():   # escape or nothing there
                return {"items": [], "cursor": None}
            root_len = len(str(base)) + 1
            keys: list[str] = []
            for root, _dirs, files in os.walk(top):
                rel = root[root_len:].replace(os.sep, "/") if len(root) > root_len else ""
                for name in files:
                    if name.endswith(".tmp"):
                        continue
                    key = f"{rel}/{name}" if rel else name
                    if key.startswith(prefix) and (not cursor or key > cursor):
                        keys.append(key)
            keys.sort()
            page = keys[:limit]
            nxt = page[-1] if len(keys) > limit else None
            return {"items": [{"file_id": k} for k in page], "cursor": nxt}
        return await asyncio.to_thread(_do)

    async def probe(self) -> None:
        def _do():
            self._root.mkdir(parents=True, exist_ok=True)
            if not os.access(self._root, os.W_OK):
                raise RuntimeError(f"blob root not writable: {self._root}")
        await asyncio.to_thread(_do)


# ── local: env/file secrets ("bring your own provider keys") ──────────────────────
class SecretsNotConfigured(RuntimeError):
    """Raised when a secret must be written but there is nowhere safe to write it.

    Deliberately an error rather than a fallback. A provider key injected read-only through the
    environment is one risk; a customer's production database connection string written to a file
    in plaintext is another entirely, and the difference is not something to decide silently on
    the operator's behalf."""


class FileSecretStore:
    """Reads HR_SECRET_{TENANT}_{NAME} from the environment first (read-only injection — the
    open-repo way to supply provider credentials without any vault), then falls back to files
    under {root}/{tenant}/{name}.

    Files are ENCRYPTED when HR_SECRET_KEY is set: AES-256-GCM under a key derived from it, with
    a random nonce per write, stored as `hrenc1:<b64 nonce||ciphertext>`. Reads accept both forms,
    so a store written before this existed keeps working and re-encrypts on its next write.

    Without HR_SECRET_KEY, `put(..., require_encryption=True)` REFUSES. That is the whole point:
    the caller that stores a database credential says so, and on an instance with no key it gets
    an error telling the operator what to set, instead of a plaintext file nobody knew about."""

    _MAGIC = "hrenc1:"

    def __init__(self, root: str):
        self._root = Path(root)
        self._key = self._derive(os.environ.get("HR_SECRET_KEY", ""))

    @property
    def encrypts(self) -> bool:
        return self._key is not None

    @staticmethod
    def _derive(passphrase: str) -> bytes | None:
        """A 32-byte key from the operator's passphrase. Scrypt with a fixed salt: the salt's job
        is to stop cross-deployment rainbow tables, and there is nowhere to keep a random one that
        would not sit beside the ciphertext anyway."""
        if not passphrase:
            return None
        return hashlib.scrypt(passphrase.encode(), salt=b"harnessrouter.secret.v1",
                              n=2 ** 14, r=8, p=1, dklen=32)

    def _seal(self, value: str) -> str:
        from cryptography.hazmat.primitives.ciphers.aead import AESGCM
        nonce = secrets_mod.token_bytes(12)
        blob = nonce + AESGCM(self._key).encrypt(nonce, value.encode(), None)
        return self._MAGIC + base64.b64encode(blob).decode()

    def _open(self, raw: str) -> str:
        if not raw.startswith(self._MAGIC):
            return raw                      # written before encryption existed
        if self._key is None:
            raise SecretsNotConfigured(
                "This secret is encrypted but HR_SECRET_KEY is not set. Set it to the passphrase "
                "used when the secret was stored.")
        from cryptography.hazmat.primitives.ciphers.aead import AESGCM
        blob = base64.b64decode(raw[len(self._MAGIC):])
        return AESGCM(self._key).decrypt(blob[:12], blob[12:], None).decode()

    @staticmethod
    def _env_key(tenant: str, name: str) -> str:
        return "HR_SECRET_" + re.sub(r"[^A-Za-z0-9]", "_", f"{tenant}_{name}").upper()

    def _p(self, tenant: str, name: str) -> Path:
        safe = re.sub(r"[^A-Za-z0-9._-]", "_", name)
        return self._root / re.sub(r"[^A-Za-z0-9._-]", "_", tenant) / safe

    async def get(self, tenant: str, name: str) -> str | None:
        v = os.environ.get(self._env_key(tenant, name))
        if v:
            return v

        def _do():
            try:
                return self._p(tenant, name).read_text()
            except OSError:
                return None
        raw = await asyncio.to_thread(_do)
        return self._open(raw) if raw is not None else None

    async def put(self, tenant: str, name: str, value: str, *, require_encryption: bool = False) -> None:
        if require_encryption and self._key is None:
            raise SecretsNotConfigured(
                "Refusing to store this credential: HR_SECRET_KEY is not set, so it could only be "
                "written to disk in plaintext. Set HR_SECRET_KEY to a passphrase and restart.")
        body = self._seal(value) if self._key is not None else value

        def _do():
            p = self._p(tenant, name)
            p.parent.mkdir(parents=True, exist_ok=True)
            p.write_text(body)
            with contextlib.suppress(OSError):
                p.chmod(0o600)              # belt to the encryption's braces
        await asyncio.to_thread(_do)

    async def delete(self, tenant: str, name: str) -> None:
        def _do():
            with contextlib.suppress(OSError):
                self._p(tenant, name).unlink()
        await asyncio.to_thread(_do)

    async def blank(self) -> list[tuple[str, str]]:
        """Every stored secret whose value is empty, as (tenant, name). Before 0.32.0 a removed
        credential was overwritten with nothing rather than deleted; the retention sweep removes
        those files. A value that cannot be opened (encrypted, and no key) is not reported."""
        def _do():
            out: list[tuple[str, str]] = []
            if not self._root.is_dir():
                return out
            for tdir in sorted(self._root.iterdir()):
                if not tdir.is_dir():
                    continue
                for f in sorted(tdir.iterdir()):
                    if not f.is_file():
                        continue
                    try:
                        if self._open(f.read_text()) == "":
                            out.append((tdir.name, f.name))
                    except Exception:  # noqa: BLE001 — unreadable is not empty
                        continue
            return out
        return await asyncio.to_thread(_do)


# ── selection ─────────────────────────────────────────────────────────────────────

# ── workspace files ───────────────────────────────────────────────────────────────
def _safe_member(path: str) -> str | None:
    """A workspace-relative path, or None if it tries to leave the workspace.

    Rejected rather than sanitised: a path that needed cleaning was not the path the caller meant,
    and silently writing somewhere else is worse than refusing."""
    p = (path or "").strip().lstrip("/")
    if not p or p != posixpath.normpath(p) or p.startswith("../") or "\\" in p:
        return None
    return p


class RunnerWorkspaceFiles:
    """Self-hosted: a session's workspace is a live directory on the data volume, and the RUNNER is
    the only principal that touches it. Behind the write-wall each session directory belongs to that
    session's own uid and the product deliberately cannot read or write there (see _isolate_session
    in the runner), so a live read or write goes through the runner, which acts as the session,
    rather than through this process's own filesystem access. One door, whether the wall is up or
    not: the runner is beside the gateway in every self-hosted deployment.

    Live, unlike the checkpoint the listing route reads: an app sees a file the moment a tool call
    creates it, rather than when the turn ends."""

    def __init__(self, endpoint: str, key: str, blob=None, kb: str = ""):
        self.endpoint = (endpoint or "").rstrip("/")
        self.key = key
        self.blob, self.kb = blob, kb
        self._client: httpx.AsyncClient | None = None

    def _c(self) -> httpx.AsyncClient:
        if self._client is None:
            self._client = httpx.AsyncClient(timeout=httpx.Timeout(60.0, connect=5.0))
        return self._client

    def _headers(self) -> dict:
        return {"X-Harness-Internal": self.key} if self.key else {}

    async def read(self, sid: str, path: str) -> bytes | None:
        member = _safe_member(path)
        if not member or not self.endpoint:
            return None
        try:
            r = await self._c().get(f"{self.endpoint}/file", params={"identifier": sid, "path": member},
                                    headers=self._headers())
        except Exception:      # noqa: BLE001 — a runner that is down reads as "no file", never a 500
            return None
        return r.content if r.status_code == 200 else None

    async def write(self, sid: str, path: str, data: bytes) -> bool:
        member = _safe_member(path)
        if not member or not self.endpoint:
            return False
        try:
            r = await self._c().put(f"{self.endpoint}/file", params={"identifier": sid, "path": member},
                                    headers={**self._headers(), "content-type": "application/octet-stream"},
                                    content=data)
        except Exception:      # noqa: BLE001
            return False
        if r.status_code != 200:
            return False
        await self._capture(sid, member, data)
        return True

    async def _capture(self, sid: str, member: str, data: bytes) -> None:
        """Persist the app's copy of this file so it outlives the live directory.

        THIS is why the class takes a blob store. The live workspace is reaped after
        HR_WORKSPACE_TTL_HOURS and is only ever refreshed by a TURN's checkpoint, so a file an app
        wrote BETWEEN turns lived in exactly one place and was deleted with it: a sheet somebody
        typed into and never asked the agent about again came back empty, and so did every agent
        column they had bound by hand. The hosted sibling writes straight into the durable tarball
        and never had the hole, which is the tell — one Protocol, two meanings for `write`.

        The id is derived from the path, so a sheet saved a thousand times keeps ONE blob instead
        of leaking one per save. `written_at` is what makes the read side deterministic: the
        agent's own capture of the same filename carries one too, and the newer of the two wins
        rather than whichever the blob listing happened to return last."""
        if not self.blob or not self.kb:
            return
        cfile = "cfile_" + hashlib.sha256(f"app:{member}".encode()).hexdigest()[:32]
        meta = json.dumps({"filename": member,
                           "media_type": mimetypes.guess_type(member)[0] or "application/octet-stream",
                           "written_at": time.time(),
                           "source": "app"}).encode()
        try:
            if await self.blob.put(self.kb, f"containers/{sid}/{cfile}", data):
                await self.blob.put(self.kb, f"containers/{sid}/{cfile}.meta", meta)
                return
        except Exception as e:   # noqa: BLE001
            print(f"[workspace] durable capture failed sid={sid} path={member}: {e}", flush=True)
            return
        # A live write that was not captured is the old silent-loss shape. Say so rather than
        # letting it look like a clean save.
        print(f"[workspace] durable capture rejected sid={sid} path={member}", flush=True)


class CheckpointWorkspaceFiles:
    """Hosted: between turns the workspace is only the checkpoint tarball, so a write rewrites
    that archive — copy every member across, substituting the one being written.

    Rewriting rather than appending is deliberate: tar allows duplicate names and readers take the
    LAST one, so appending would work until something read the archive differently, and the bug
    would be a stale file appearing at random."""

    def __init__(self, blob, kb: str, key_for):
        self.blob, self.kb, self.key_for = blob, kb, key_for

    async def read(self, sid: str, path: str) -> bytes | None:
        member = _safe_member(path)
        if not member:
            return None
        raw = await self.blob.get(self.kb, self.key_for(sid))
        if not raw:
            return None

        def _extract() -> bytes | None:
            with tarfile.open(fileobj=io.BytesIO(raw), mode="r:gz") as tf:
                for name in (member, f"./{member}"):
                    try:
                        f = tf.extractfile(name)
                    except KeyError:
                        continue
                    if f:
                        return f.read()
            return None
        try:
            return await asyncio.to_thread(_extract)
        except Exception:      # noqa: BLE001 — a corrupt archive reads as "not there"
            return None

    async def write(self, sid: str, path: str, data: bytes) -> bool:
        member = _safe_member(path)
        if not member:
            return False
        key = self.key_for(sid)
        raw = await self.blob.get(self.kb, key)

        def _rewrite() -> bytes:
            out = io.BytesIO()
            wrote = False
            with tarfile.open(fileobj=out, mode="w:gz") as dst:
                if raw:
                    with tarfile.open(fileobj=io.BytesIO(raw), mode="r:gz") as src:
                        for m in src.getmembers():
                            name = m.name[2:] if m.name.startswith("./") else m.name
                            if name == member:
                                continue          # replaced below
                            f = src.extractfile(m) if m.isfile() else None
                            dst.addfile(m, f)
                info = tarfile.TarInfo(member)
                info.size = len(data)
                info.mtime = int(time.time())
                info.mode = 0o644
                dst.addfile(info, io.BytesIO(data))
                wrote = True
            return out.getvalue() if wrote else b""

        try:
            tar = await asyncio.to_thread(_rewrite)
        except Exception:      # noqa: BLE001
            return False
        return bool(tar) and await self.blob.put(self.kb, key, tar)


def make_backing(*, client_getter, vg_url: str, vg_key: str, vg_tenant: str,
                 vault_url: str, vault_key: str) -> Backing:
    """Build the configured backing. HR_BACKING=vg|local; unset ⇒ vg when VG_GATEWAY_URL is
    configured (production), local otherwise (a laptop clone works with zero env)."""
    mode = os.environ.get("HR_BACKING", "").strip().lower() or ("vg" if vg_url else "local")
    # Where a session's workspace actually lives, which is the one thing that differs most between
    # the two deployments: a live directory the runner owns and serves, or a checkpoint tarball
    # that is the only copy between turns.
    ws_key = lambda sid: f"sessions/{sid}/workspace.tgz"   # noqa: E731 — matches gateway._ws_blob
    if mode == "vg":
        from backing_vg import VgBlobStore, VgGraphStore, VaultSecretStore
        blob = VgBlobStore(client_getter, vg_url, vg_key)
        return Backing(
            graph=VgGraphStore(client_getter, vg_url, vg_key, vg_tenant),
            blob=blob,
            secrets=VaultSecretStore(client_getter, vault_url, vault_key),
            mode="vg",
            workspace=CheckpointWorkspaceFiles(blob, os.environ.get("HARNESS_BLOB_KB", "harness-sessions"), ws_key))
    data = os.environ.get("HR_DATA_DIR", ".hr-data")
    local_blob = FileBlobStore(os.path.join(data, "blobs"))
    return Backing(
        graph=SqliteGraphStore(os.path.join(data, "graph.db")),
        blob=local_blob,
        secrets=FileSecretStore(os.path.join(data, "secrets")),
        mode="local",
        workspace=RunnerWorkspaceFiles(os.environ.get("POOL_MGMT_ENDPOINT", "http://127.0.0.1:8081"),
                                       os.environ.get("HARNESS_INTERNAL_KEY", ""),
                                       local_blob,
                                       os.environ.get("HARNESS_RESP_BLOB_KB", "harness-responses")))

# ===== file: gateway/browser_plane.py =====
"""The browser server's plane: a real browser, in a vendor's cloud or the operator's own, driven
from this gateway over the Chrome DevTools Protocol, handed to the agent as a dozen typed tools
and nothing else.

The operator's own browser (HR_BROWSER_CDP_URL, a Chrome started with --remote-debugging-port or
any CDP endpoint) takes the vendor's place whole: no vendor session, no live view, no charge, one
browser context per harness session on the one browser, and the private-address rule lifted,
since that browser sits on the operator's own network and reaches what the operator's shell
already can (a customer's crawler behind a headful Chrome broker, 2026-09-30).

One browser session per harness session, made on the first call and stopped at the end of the
turn, after idle, or at the session cap. The vendor is behind one adapter (Browser Use Cloud
first; Browserbase has the same shape: a session id and a CDP address), so the tools, the guards
and the metering never learn a vendor's name.

What the agent is never given: a JavaScript evaluator, downloads, cookies, the vendor's key, the
CDP address. What every request is checked against, subresources and redirects included: the
harness's allow and deny lists and the private, loopback, link-local and metadata address ranges.

Money: the vendor's list price, no markup. A session is priced BEFORE it starts as the session cap
times the per-minute rate (that is what counts against the task's cost cap), and metered AFTER
from the vendor's own figures for the minutes it ran (rounded up, one-minute minimum). The prices
below are the estimate's; the meter reads what the vendor reports.
"""
from __future__ import annotations

import asyncio
import ipaddress
import json
import math
import os
import socket
import time
import urllib.parse

import httpx

CDP_URL = os.environ.get("HR_BROWSER_CDP_URL", "").strip()     # the operator's own browser, instead of the vendor
API_KEY = os.environ.get("BROWSER_USE_API_KEY", "")
# The key as a mounted secret file, read at every use: a rotated Key Vault secret reaches a
# mounted file without a new revision, where an environment variable holds the value the process
# started with.
API_KEY_FILE = os.environ.get("BROWSER_USE_API_KEY_FILE", "")
API_BASE = os.environ.get("BROWSER_USE_API_BASE", "https://api.browser-use.com/api/v4").rstrip("/")
SESSION_CAP_MIN = int(os.environ.get("HR_BROWSER_SESSION_MINUTES", "20"))      # per harness session
# Fair share of the vendor's concurrency (10 sessions until $1,000 lifetime spend, then 250):
# no org holds more than its share, and this process stops one below the vendor's ceiling so the
# refusal an agent reads is ours, in a sentence, not the vendor's 429. Per process: a second
# gateway replica has its own counts.
ORG_SESSIONS = int(os.environ.get("HR_BROWSER_ORG_SESSIONS", "3"))
MAX_SESSIONS = int(os.environ.get("HR_BROWSER_MAX_SESSIONS", "9"))
CALL_CAP_S = float(os.environ.get("HR_BROWSER_CALL_SECONDS", "60"))            # per tool call
IDLE_S = float(os.environ.get("HR_BROWSER_IDLE_SECONDS", "120"))               # no call for this long: stopped
TEXT_CAP = 20000                                                               # characters of extracted text
SNAPSHOT_CAP = 150                                                             # elements in a snapshot

# The vendor's list prices, no markup (browser-use.com/pricing and the v4 API docs, read
# 2026-09-24): browser time $0.02 per hour, rounded up to whole minutes, one-minute minimum;
# residential proxy $5 per GB (this slice runs with no proxy, so the unit never appears);
# screenshots are Playwright's and cost nothing. The meter posts dollars under one unit.
PRICES = {"browser.minute": 0.02 / 60, "browser.proxy_mb": 0.005, "browser.screenshot": 0.0}
UNIT = "browser.usd"
VENDOR = "browser-use"

transport: httpx.BaseTransport | None = None     # tests: the vendor's API
connector = None                                  # tests: async (cdp_url) -> a browser-like object


def api_key() -> str:
    if API_KEY_FILE:
        try:
            with open(API_KEY_FILE, encoding="utf-8") as f:
                key = f.read().strip()
            if key:
                return key
        except OSError:
            pass
    return API_KEY


def own_browser() -> bool:
    """Whether the operator's own browser is the browser here."""
    return bool(CDP_URL)


def configured() -> bool:
    return own_browser() or bool(api_key())


def pricing() -> dict:
    """The browser's price line, for the page that shows it before a workspace turns it on."""
    if own_browser():
        return {"type": "browser", "unit": "browser hour", "usd_per_unit": 0.0, "markup": 0.0,
                "source": "your own browser", "vendor": "own", "billed_as": UNIT,
                "rounding": "none", "session_cap_minutes": SESSION_CAP_MIN, "session_estimate_usd": 0.0}
    return {"type": "browser", "unit": "browser hour", "usd_per_unit": round(PRICES["browser.minute"] * 60, 6),
            "markup": 0.0, "source": "vendor list price", "vendor": VENDOR, "billed_as": UNIT,
            "rounding": "up to the minute, one-minute minimum", "session_cap_minutes": SESSION_CAP_MIN,
            "session_estimate_usd": session_estimate_usd()}


def session_estimate_usd() -> float:
    """What a session may cost at most, before it starts: the cap in minutes at the list price;
    nothing on the operator's own browser."""
    return 0.0 if own_browser() else round(SESSION_CAP_MIN * PRICES["browser.minute"], 6)


class BrowserRefused(RuntimeError):
    """A call that must not run, with the sentence the agent reads."""

    def __init__(self, code: str, message: str):
        super().__init__(message)
        self.code = code


class BrowserToolError(RuntimeError):
    """A call that ran and failed in a way the agent can act on."""


# ── the vendor ───────────────────────────────────────────────────────────────────────────────
def _vendor_client() -> httpx.AsyncClient:
    return httpx.AsyncClient(transport=transport, timeout=60,
                             headers={"X-Browser-Use-API-Key": api_key(), "content-type": "application/json"})


async def vendor_create(timeout_min: int, metadata: dict) -> dict:
    """A browser in the vendor's cloud: no proxy, no CAPTCHA solving, no recording, so the only
    unit that can bill is time. 402 is the vendor's wallet, 429 its concurrency. The screen is the
    vendor's default, landscape: what the live view streams is that screen, whatever the shape of
    the card showing it (measured on hr-test, 2026-09-28: neither an emulated viewport over CDP
    nor allowResizing changed the streamed frame), so the console fits the frame inside the card.

    The operator's own browser is already running: its record names the CDP address and no
    vendor session (an empty id is what marks it), and there is no live view of it."""
    if own_browser():
        return {"id": "", "cdpUrl": CDP_URL, "liveUrl": ""}
    async with _vendor_client() as c:
        r = await c.post(f"{API_BASE}/browsers", json={
            "timeout": int(timeout_min), "proxyCountryCode": None, "solveCaptchas": False,
            "enableRecording": False, "metadata": {k: str(v)[:100] for k, v in metadata.items()}})
    if r.status_code == 402:
        raise BrowserRefused("vendor_credits", "The browser service has no credit left. Tell the person.")
    if r.status_code == 429:
        raise BrowserRefused("vendor_busy", "Every browser is in use right now. Try again in a minute.")
    if r.status_code >= 400:
        raise BrowserRefused("vendor_error", f"The browser service refused to start a browser ({r.status_code}).")
    d = r.json()
    if not d.get("id") or not d.get("cdpUrl"):
        raise BrowserRefused("vendor_error", "The browser service answered without a browser address.")
    return d


async def vendor_stop(vendor_id: str) -> dict:
    """Stop the browser and read what it cost: closing the CDP socket alone keeps the meter
    running on the vendor's side."""
    async with _vendor_client() as c:
        r = await c.patch(f"{API_BASE}/browsers/{vendor_id}", json={"action": "stop"})
        if r.status_code >= 400:
            r = await c.get(f"{API_BASE}/browsers/{vendor_id}")
    try:
        return r.json() if r.status_code < 400 else {}
    except ValueError:
        return {}


def vendor_cost(d: dict) -> float | None:
    """Dollars the vendor reports for a session: its browser time, plus proxy traffic when any.
    None when it reported no browser cost, which is the figure of record."""
    if d.get("browserCost") is None:
        return None
    total = 0.0
    for p in (d.get("browserCost"), d.get("proxyCost")):
        try:
            total += float(p or 0)
        except (TypeError, ValueError):
            pass
    return round(total, 6)


# ── the address guard ────────────────────────────────────────────────────────────────────────
_PRIVATE_NAMES = ("localhost", ".localhost", ".local", ".internal", ".home.arpa", ".lan", ".corp")


def _ip_private(ip: str) -> bool:
    try:
        a = ipaddress.ip_address(ip)
    except ValueError:
        return False
    return (a.is_private or a.is_loopback or a.is_link_local or a.is_multicast or a.is_reserved
            or a.is_unspecified or (a.version == 6 and a.ipv4_mapped is not None and _ip_private(str(a.ipv4_mapped))))


def _suffix_match(host: str, patterns: list[str]) -> bool:
    for p in patterns:
        p = (p or "").strip().lower().lstrip("*").lstrip(".")
        if p and (host == p or host.endswith("." + p)):
            return True
    return False


def host_policy(host: str, allow: list[str], deny: list[str], private_ok: bool = False) -> str | None:
    """Why this host may not be reached, or None. Name rules only; the address rule follows.
    `private_ok` lifts the private-address names and literals: the operator's own browser sits on
    the operator's own network (HR_BROWSER_CDP_URL), and a loopback address was still refused here
    by name after the plane had opened that browser (hr-test, 2026-09-30)."""
    h = (host or "").strip().lower().rstrip(".")
    if not h:
        return "no host"
    if h.startswith("[") and h.endswith("]"):
        h = h[1:-1]
    if not private_ok and _ip_private(h):
        return "a private or local address"
    if not private_ok and (h == "localhost" or any(h.endswith(s) for s in _PRIVATE_NAMES[1:])):
        return "a private or local address"
    if deny and _suffix_match(h, deny):
        return "a site this agent is not allowed to visit"
    if allow and not _suffix_match(h, allow):
        return "a site outside the ones this agent is allowed to visit"
    return None


async def resolves_private(host: str) -> bool:
    """Whether any address the name resolves to is private. A name that does not resolve counts
    as private: this is an address a page chose, and it is asked again on every request."""
    h = (host or "").strip().lower().rstrip(".").strip("[]")
    if _ip_private(h):
        return True
    try:
        ipaddress.ip_address(h)
        return False
    except ValueError:
        pass
    try:
        infos = await asyncio.wait_for(asyncio.to_thread(socket.getaddrinfo, h, None), 4)
    except Exception:  # noqa: BLE001
        return True
    return any(_ip_private(str(i[4][0])) for i in infos) or not infos


# ── the session ──────────────────────────────────────────────────────────────────────────────
# One browser per harness session, wherever the call lands. The RECORD of it (the vendor's id,
# the CDP address, when it opened and was last used, its counts, its lists) is kept once for every
# gateway process by the registry below; the ATTACHMENT (the CDP connection, the context, the
# page) is this process's own, made by the first call that reaches it and dropped when the record
# goes. A CLI's tool calls are load-balanced over every replica, and a per-process record let one
# turn open a browser on each replica it reached (four for one turn on 2026-09-25, three of them
# stopped only by the idle reaper, none of them the page the agent had opened).
class Session:
    """This process's attachment to a session's browser, built from its record."""

    def __init__(self, rec: dict):
        self.sid, self.hid, self.org, self.workspace = str(rec["sid"]), str(rec["hid"]), str(rec["org"]), str(rec["workspace"])
        self.allow, self.deny = list(rec.get("allow") or []), list(rec.get("deny") or [])
        self.vendor_id = str(rec.get("vendor_id") or "")
        self.cdp_url = str(rec.get("cdp_url") or "")
        self.live_url = str(rec.get("live_url") or "")
        self.created = float(rec.get("created") or time.time())
        self.reserved = float(rec.get("reserved") or 0.0)   # what was counted against the task before the browser opened
        self.browser = None
        self.context = None
        self.page = None
        self.blocked: list[str] = []            # hosts this attachment refused, so each is recorded once
        self.host_cache: dict[str, bool] = {}
        self.lock = asyncio.Lock()
        self.closed = False
        self.opened = False                     # this call made the browser at the vendor: the caller writes the open row once
        self.pointer: dict | None = None        # where the agent last acted (the element's centre), for the console's ghost cursor; kept across navigations so the next action glides from there


def minutes(rec: dict) -> int:
    return max(1, math.ceil((time.time() - float(rec.get("created") or time.time())) / 60))


def expired(rec: dict, now: float | None = None) -> str | None:
    now = now or time.time()
    if now - float(rec.get("created") or now) > SESSION_CAP_MIN * 60:
        return "session_cap"
    if now - float(rec.get("last_used") or now) > IDLE_S:
        return "idle"
    return None


# ── the registry ─────────────────────────────────────────────────────────────────────────────
# Where the records live. In this process by default, which is right for one gateway process (a
# self-hosted instance); a deployment that runs several installs one over its shared store, so
# the same session reads the same browser from every replica. `bump` increments the counters
# named in COUNTERS, appends to the lists named in LISTS and sets anything else.
COUNTERS = ("calls", "screenshots")
LISTS = ("blocked",)


class LocalRegistry:
    def __init__(self):
        self._recs: dict[str, dict] = {}

    async def get(self, sid: str) -> dict | None:
        return self._recs.get(sid)

    async def create(self, sid: str, rec: dict) -> bool:
        """True iff this call made the record; False when one is there already."""
        if sid in self._recs:
            return False
        self._recs[sid] = rec
        return True

    async def bump(self, sid: str, **fields) -> None:
        rec = self._recs.get(sid)
        if rec is None:
            return
        for k, v in fields.items():
            if k in COUNTERS:
                rec[k] = int(rec.get(k) or 0) + int(v)
            elif k in LISTS:
                rec.setdefault(k, []).append(v)
            else:
                rec[k] = v

    async def delete(self, sid: str) -> bool:
        """True iff this call removed the record: the remover stops the browser and writes its row."""
        return self._recs.pop(sid, None) is not None

    async def all(self) -> list[dict]:
        return list(self._recs.values())

    async def lock(self, sid: str, ttl_s: int) -> bool:
        return True                             # one process: the caller's own lock serialises its opens

    async def unlock(self, sid: str) -> None:
        pass


registry = LocalRegistry()
_SESSIONS: dict[str, Session] = {}            # this process's attachments, by session
_pw = None


def sessions() -> dict[str, Session]:
    return _SESSIONS


def _record(sid: str, hid: str, org: str, workspace: str, allow: list[str], deny: list[str], d: dict,
            reserved: float) -> dict:
    now = time.time()
    return {"sid": sid, "hid": hid, "org": org, "workspace": workspace, "allow": list(allow), "deny": list(deny),
            "vendor_id": str(d["id"]), "cdp_url": str(d["cdpUrl"]), "live_url": str(d.get("liveUrl") or ""),
            "created": now, "last_used": now, "calls": 0, "screenshots": 0, "blocked": [],
            "reserved": float(reserved)}


async def _connect(cdp_url: str):
    global _pw
    if connector is not None:
        return await connector(cdp_url)
    from playwright.async_api import async_playwright
    if _pw is None:
        _pw = await async_playwright().start()
    return await _pw.chromium.connect_over_cdp(cdp_url, timeout=30000)


async def _allowed(s: Session, url: str) -> str | None:
    """Why this URL may not be requested from this session, or None; resolved once per host."""
    try:
        u = urllib.parse.urlsplit(url)
    except ValueError:
        return "not a valid address"
    if u.scheme not in ("http", "https"):
        return f"a {u.scheme or 'non-web'} address" if u.scheme not in ("about", "data", "blob") else None
    host = u.hostname or ""
    own = not s.vendor_id           # the operator's own browser, on the operator's own network
    why = host_policy(host, s.allow, s.deny, private_ok=own)
    if why:
        return why
    if own:
        return None
    if host not in s.host_cache:
        s.host_cache[host] = await resolves_private(host)
    return "a private or local address" if s.host_cache[host] else None


async def open_session(sid: str, hid: str, org: str, workspace: str, allow: list[str], deny: list[str],
                       reserved: float = 0.0) -> Session:
    """The session's browser, attached here: the recorded one when there is one, else a new one at
    the vendor, recorded for every process first. One opener at a time across processes: the
    others wait for its record. `opened` on the result says this call made the browser."""
    if not configured():
        raise BrowserRefused("not_configured", "The browser service is not set up on this deployment. Tell the person.")
    rec = await registry.get(sid)
    locked = False
    if rec is None:
        for _ in range(60):
            if await registry.lock(sid, 30):
                locked = True
                break
            await asyncio.sleep(0.5)
            rec = await registry.get(sid)
            if rec is not None:
                break
        else:
            raise BrowserRefused("busy", "The browser is still being started. Try again in a moment.")
    opened = False
    try:
        if rec is None:
            live = await registry.all()
            if sum(1 for x in live if x.get("org") == org) >= ORG_SESSIONS:
                raise BrowserRefused("org_busy", f"This account already has {ORG_SESSIONS} browsers open. Try again when one of them finishes.")
            if len(live) >= MAX_SESSIONS:
                raise BrowserRefused("busy", "Every browser is in use right now. Try again in a minute.")
            d = await vendor_create(SESSION_CAP_MIN, {"harness": hid, "session": sid})
            rec = _record(sid, hid, org, workspace, allow, deny, d, reserved)
            if await registry.create(sid, rec):
                opened = True
            else:
                # Made elsewhere between the lock and here (a lock the store could not keep): theirs stands.
                try:
                    await vendor_stop(rec["vendor_id"])
                except Exception:  # noqa: BLE001
                    pass
                rec = await registry.get(sid)
                if rec is None:
                    raise BrowserRefused("busy", "The browser could not be started. Try again.")
    finally:
        if locked:
            await registry.unlock(sid)
    try:
        s = await attach(rec)
    except Exception:
        if opened:                              # a browser nobody can reach: not left for the reaper
            await registry.delete(sid)
            try:
                await vendor_stop(rec["vendor_id"])
            except Exception:  # noqa: BLE001
                pass
        raise
    s.opened = opened
    return s


async def attach(rec: dict) -> Session:
    """This process's attachment to the recorded browser, made on first use and kept. Every process
    uses the browser's own default context and its first tab, so the page is the same page from
    every replica; the request gate is installed per attachment and reads the record's lists."""
    sid = str(rec["sid"])
    s = _SESSIONS.get(sid)
    if s is not None and not s.closed and s.vendor_id == str(rec.get("vendor_id") or ""):
        return s
    if s is not None:
        await detach(s)                         # the record names another browser: this one is gone
    s = Session(rec)
    s.browser = await _connect(s.cdp_url)
    try:
        # The operator's own browser is shared by every session, so each gets a context of its own
        # (its own cookies and tabs), made over this attachment's connection and closed with it; a
        # vendor browser is one session's alone and its default context is the page.
        contexts = [] if not s.vendor_id else list(getattr(s.browser, "contexts", None) or [])
        s.context = contexts[0] if contexts else await s.browser.new_context(accept_downloads=False, viewport={"width": 1280, "height": 800})

        async def gate(route, request):
            why = await _allowed(s, request.url)
            if why:
                host = urllib.parse.urlsplit(request.url).hostname or request.url[:60]
                if host not in s.blocked:
                    s.blocked.append(host)
                    await registry.bump(sid, blocked=host)
                await route.abort("blockedbyclient")
            else:
                await route.continue_()

        await s.context.route("**/*", gate)
        pages = list(getattr(s.context, "pages", None) or [])
        s.page = pages[0] if pages else await s.context.new_page()
        s.page.set_default_timeout(30000)
        on = getattr(s.context, "on", None)
        if callable(on):
            on("page", lambda pg: asyncio.ensure_future(_follow_new_tab(s, sid, pg)))
    except Exception:
        await detach(s)
        raise
    _SESSIONS[sid] = s
    return s


async def _follow_new_tab(s: Session, sid: str, pg) -> None:
    """A link the person opened in a new tab while they have the browser is followed in the tab the
    live view shows: the new page's address goes to the shown page and the new page closes, so the
    view stays with them (the console's live view shows one tab, and a link marked to open in a new
    one looked like a click that did nothing: the LinkedIn and X icons on a directory page,
    2026-09-27). Only while the person has the browser: the agent's own tabs are its to manage
    (list_tabs, switch_tab)."""
    try:
        rec = await registry.get(sid)
        if (rec or {}).get("control") != "user" or pg is s.page:
            return
        try:
            await pg.wait_for_load_state("domcontentloaded", timeout=8000)
        except Exception:  # noqa: BLE001
            pass
        url = str(getattr(pg, "url", "") or "")
        if url and url != "about:blank":
            await s.page.goto(url, wait_until="domcontentloaded", timeout=30000)
        await pg.close()
    except Exception:  # noqa: BLE001
        pass


async def detach(s: Session) -> None:
    """Drop this process's attachment; the browser itself stays as it is (a connected browser's
    close disconnects it and closes only the contexts this attachment made)."""
    s.closed = True
    if _SESSIONS.get(s.sid) is s:
        _SESSIONS.pop(s.sid, None)
    closer = getattr(s.browser, "close", None)
    if closer:
        try:
            await asyncio.wait_for(closer(), 10)
        except Exception:  # noqa: BLE001
            pass


async def close_session_browser(rec: dict, s: Session | None) -> dict:
    """Stop the recorded browser and read the vendor's figures, dropping this process's attachment
    when it has one. Every step is best effort: a browser that would not close must not keep its
    minutes from being metered."""
    if s is not None:
        s.closed = True
        if _SESSIONS.get(s.sid) is s:
            _SESSIONS.pop(s.sid, None)
        for closer in (getattr(s.context, "close", None), getattr(s.browser, "close", None)):
            if closer:
                try:
                    await asyncio.wait_for(closer(), 10)
                except Exception:  # noqa: BLE001
                    pass
    figures: dict = {}
    if rec.get("vendor_id"):
        try:
            figures = await vendor_stop(str(rec["vendor_id"]))
        except Exception:  # noqa: BLE001
            figures = {}
    usd = vendor_cost(figures)
    source = "vendor"
    if not rec.get("vendor_id"):
        usd, source = 0.0, "own"                 # the operator's own browser: nothing to meter
    elif usd is None:
        usd, source = round(minutes(rec) * PRICES["browser.minute"], 6), "table"
    return {"minutes": minutes(rec), "usd": usd, "usd_source": source, "calls": int(rec.get("calls") or 0),
            "screenshots": int(rec.get("screenshots") or 0), "blocked": list(rec.get("blocked") or [])[:20],
            "proxy_mb": figures.get("proxyUsedMb") or 0}


async def expired_sessions(now: float | None = None) -> list[tuple[dict, str]]:
    """Every recorded browser past its cap or idle, from any process."""
    now = now or time.time()
    return [(rec, why) for rec in await registry.all() if (why := expired(rec, now))]


async def sweep_attachments() -> None:
    """Drop the attachments whose browser was stopped from another process."""
    for s in list(_SESSIONS.values()):
        if await registry.get(s.sid) is None:
            await detach(s)


# ── the tools ────────────────────────────────────────────────────────────────────────────────
_TOOLS: list[dict] = []


def _tool(name: str, risk: str, description: str, schema: dict):
    _TOOLS.append({"name": name, "risk": risk, "description": description,
                   "inputSchema": {"type": "object", "properties": schema.get("properties", {}),
                                   "required": schema.get("required", []), "additionalProperties": False}})


_REF = {"ref": {"type": "string", "description": "An element ref from the last snapshot, like e12."},
        "selector": {"type": "string", "description": "A CSS selector, when there is no ref for the element."}}

_tool("navigate", "act", "Open a web address in the current tab and read what is on the page.",
      {"properties": {"url": {"type": "string", "description": "An http or https address."}}, "required": ["url"]})
_tool("get_url", "read", "The current tab's address and title.", {})
_tool("snapshot", "read", "What is on the page: headings, links, buttons and fields, each with a ref to act on.",
      {"properties": {"max_elements": {"type": "integer", "description": f"At most this many elements (default {SNAPSHOT_CAP})."}}})
_tool("extract_text", "read", "The readable text of the page, or of one element.",
      {"properties": {"selector": {"type": "string", "description": "A CSS selector; the whole page when absent."},
                      "max_chars": {"type": "integer", "description": f"At most this many characters (default {TEXT_CAP})."}}})
_tool("click", "act", "Click an element, by ref or selector.", {"properties": dict(_REF)})
_tool("type", "act", "Type text into a field, by ref or selector, replacing what is there.",
      {"properties": {**_REF, "text": {"type": "string"}, "submit": {"type": "boolean", "description": "Press Enter afterwards."}},
       "required": ["text"]})
_tool("press_key", "act", "Press a key, like Enter, Tab, Escape or ArrowDown.",
      {"properties": {"key": {"type": "string"}}, "required": ["key"]})
_tool("scroll", "act", "Scroll the page.",
      {"properties": {"direction": {"type": "string", "enum": ["down", "up"]},
                      "pixels": {"type": "integer", "description": "How far (default 600)."}}})
_tool("wait_for", "read", "Wait until text or an element appears, or for a number of milliseconds.",
      {"properties": {"text": {"type": "string"}, "selector": {"type": "string"},
                      "ms": {"type": "integer", "description": f"Milliseconds, at most {int(CALL_CAP_S * 1000)}."}}})
_tool("screenshot", "read", "A picture of the current tab, kept with the task's files and shown to you.",
      {"properties": {"full_page": {"type": "boolean", "description": "The whole page, not only the visible part."}}})
_tool("back", "act", "Go back one page in the current tab.", {})
_tool("list_tabs", "read", "The open tabs, with their index, address and title.", {})
_tool("switch_tab", "act", "Make one of the open tabs the current tab.",
      {"properties": {"index": {"type": "integer"}}, "required": ["index"]})


def tool_list() -> list[dict]:
    return [{"name": f"browser_{t['name']}", "description": f"[browser, {t['risk']}] {t['description']}",
             "inputSchema": t["inputSchema"],
             "annotations": {"readOnlyHint": t["risk"] == "read", "destructiveHint": False}} for t in _TOOLS]


def find(name: str) -> dict | None:
    return next((t for t in _TOOLS if t["name"] == name), None)


_SNAPSHOT_JS = """
(max) => {
  const out = []; let n = 0;
  const seen = new Set();
  // Visible to a person: laid out, not hidden, and at least 8 px each way. Sites keep tiny proxy
  // controls (DuckDuckGo's 4 x 4 search input beside the field people see); an agent that types
  // into one of those types into nothing anyone can see (hr-test, 2026-09-28).
  const vis = (el) => { const r = el.getBoundingClientRect(); const cs = getComputedStyle(el);
    return r.width >= 8 && r.height >= 8 && cs.visibility !== 'hidden' && cs.display !== 'none'; };
  const nameOf = (el) => (el.getAttribute('aria-label') || el.getAttribute('title') || el.getAttribute('placeholder')
    || (el.labels && el.labels[0] && el.labels[0].innerText) || el.getAttribute('alt') || el.innerText || el.value || '').trim().replace(/\\s+/g, ' ').slice(0, 80);
  const sel = 'h1,h2,h3,a[href],button,input,select,textarea,[role=button],[role=link],[role=tab],[role=menuitem],[role=checkbox],[role=radio],[role=textbox],[contenteditable=true],summary';
  for (const el of document.querySelectorAll(sel)) {
    if (n >= max) { out.push({truncated: true}); break; }
    if (!vis(el) || seen.has(el)) continue;
    seen.add(el);
    const tag = el.tagName.toLowerCase();
    const role = el.getAttribute('role') || (tag === 'a' ? 'link' : tag === 'button' || tag === 'summary' ? 'button'
      : tag === 'select' ? 'combobox' : tag === 'textarea' ? 'textbox' : tag === 'input' ? ((el.type === 'checkbox' || el.type === 'radio' || el.type === 'submit' || el.type === 'button') ? el.type : 'textbox')
      : /^h[1-3]$/.test(tag) ? 'heading' : tag);
    const row = {role, name: nameOf(el)};
    if (role !== 'heading') { const ref = 'e' + (++n); el.setAttribute('data-hr-ref', ref); row.ref = ref; }
    else row.level = Number(tag[1]);
    if (tag === 'a') row.href = (el.getAttribute('href') || '').slice(0, 120);
    if (tag === 'input' || tag === 'textarea') { if (el.value && el.type !== 'password') row.value = String(el.value).slice(0, 60); if (el.disabled) row.disabled = true; }
    if (el.type === 'checkbox' || el.type === 'radio') row.checked = !!el.checked;
    out.push(row);
  }
  return out;
}
"""


def _fmt_snapshot(rows: list[dict]) -> str:
    lines = []
    for r in rows:
        if r.get("truncated"):
            lines.append("… more elements below; scroll or ask for a larger snapshot")
            continue
        if r.get("role") == "heading":
            lines.append(f"h{r.get('level', 2)} \"{r.get('name', '')}\"")
            continue
        extra = ""
        if r.get("href"):
            extra += f" href={r['href']}"
        if "value" in r:
            extra += f" value=\"{r['value']}\""
        if "checked" in r:
            extra += " checked" if r["checked"] else " unchecked"
        if r.get("disabled"):
            extra += " disabled"
        lines.append(f"{r.get('ref')} {r.get('role')} \"{r.get('name', '')}\"{extra}")
    return "\n".join(lines) if lines else "(nothing interactive is visible on this page)"


async def _snapshot(s: Session, max_elements: int) -> str:
    rows = await s.page.evaluate(_SNAPSHOT_JS, max(1, min(int(max_elements or SNAPSHOT_CAP), 500)))
    return _fmt_snapshot(rows or [])


def _target(s: Session, args: dict):
    ref, selector = str(args.get("ref") or "").strip(), str(args.get("selector") or "").strip()
    if ref:
        return s.page.locator(f'[data-hr-ref="{ref}"]').first
    if selector:
        return s.page.locator(selector).first
    raise BrowserToolError("Say which element: a ref from the snapshot or a selector.")


async def _where(s: Session) -> str:
    try:
        title = await s.page.title()
    except Exception:  # noqa: BLE001
        title = ""
    return f"{s.page.url}" + (f" ({title})" if title else "")


async def _settled(s: Session) -> None:
    with_timeout = getattr(s.page, "wait_for_load_state", None)
    if with_timeout:
        try:
            await asyncio.wait_for(s.page.wait_for_load_state("domcontentloaded"), 8)
        except Exception:  # noqa: BLE001
            pass


async def _mark(s: Session, loc) -> None:
    """Remember the centre of the element about to be acted on, in page coordinates, so the console
    can show a ghost cursor going there. Best effort: a locator that cannot be measured leaves the
    last point standing."""
    try:
        box = await loc.bounding_box()
    except Exception:  # noqa: BLE001
        return
    if isinstance(box, dict) and box.get("width") is not None:
        s.pointer = {"x": round(float(box["x"]) + float(box["width"]) / 2, 1), "y": round(float(box["y"]) + float(box["height"]) / 2, 1)}


async def viewport_of(s: Session) -> dict:
    """The page's own layout viewport (window.innerWidth/innerHeight), the coordinate space of
    `pointer`. Asked of the page, not of the context: the vendor's default context carries its
    window's size, not the 1280 x 800 this plane asks for when it makes a context of its own, and
    a cursor placed on the assumed size landed low and right of the element the agent clicked
    (hr-test, 2026-09-27)."""
    try:
        v = await s.page.evaluate("() => [window.innerWidth, window.innerHeight]")
        if isinstance(v, (list, tuple)) and len(v) == 2 and int(v[0]) > 0:
            return {"w": int(v[0]), "h": int(v[1])}
    except Exception:  # noqa: BLE001
        pass
    try:
        vs = s.page.viewport_size if s.page is not None else None
    except Exception:  # noqa: BLE001
        vs = None
    return {"w": int((vs or {}).get("width") or 1280), "h": int((vs or {}).get("height") or 800)}


async def call(s: Session, name: str, args: dict):
    """Run one tool on this session. Returns text, or ("image", png bytes, caption) for a
    screenshot the caller stores. Raises BrowserToolError with a sentence the agent can act on."""
    await registry.bump(s.sid, last_used=time.time(), calls=1)
    page = s.page
    if name == "navigate":
        url = str(args.get("url") or "").strip()
        if not url:
            raise BrowserToolError("Give a web address to open.")
        if "://" not in url:
            url = "https://" + url
        why = await _allowed(s, url)
        if why:
            raise BrowserToolError(f"That address is {why}, so it cannot be opened.")
        try:
            await page.goto(url, wait_until="domcontentloaded")
        except Exception as e:  # noqa: BLE001
            raise BrowserToolError(f"The page did not open: {str(e).splitlines()[0][:200]}") from None
        return f"Opened {await _where(s)}\n\n{await _snapshot(s, 80)}"
    if name == "get_url":
        return await _where(s)
    if name == "snapshot":
        return f"{await _where(s)}\n\n{await _snapshot(s, args.get('max_elements') or SNAPSHOT_CAP)}"
    if name == "extract_text":
        selector = str(args.get("selector") or "").strip() or "body"
        cap = max(200, min(int(args.get("max_chars") or TEXT_CAP), TEXT_CAP))
        try:
            text = await page.locator(selector).first.inner_text()
        except Exception as e:  # noqa: BLE001
            raise BrowserToolError(f"No readable text at {selector!r}: {str(e).splitlines()[0][:160]}") from None
        text = "\n".join(line.strip() for line in text.splitlines() if line.strip())
        return text[:cap] + (f"\n… {len(text) - cap} more characters" if len(text) > cap else "")
    if name == "click":
        loc = _target(s, args)
        await _mark(s, loc)
        try:
            await loc.click(timeout=15000)
        except Exception as e:  # noqa: BLE001
            raise BrowserToolError(f"The click did not land: {str(e).splitlines()[0][:160]}") from None
        await _settled(s)
        return f"Clicked. Now at {await _where(s)}"
    if name == "type":
        loc = _target(s, args)
        await _mark(s, loc)
        text = str(args.get("text") or "")
        try:
            await loc.fill(text, timeout=15000)
            if args.get("submit"):
                await loc.press("Enter")
                await _settled(s)
        except Exception as e:  # noqa: BLE001
            raise BrowserToolError(f"Typing failed: {str(e).splitlines()[0][:160]}") from None
        return f"Typed {len(text)} characters." + (f" Now at {await _where(s)}" if args.get("submit") else "")
    if name == "press_key":
        key = str(args.get("key") or "").strip()
        if not key:
            raise BrowserToolError("Say which key.")
        await page.keyboard.press(key)
        await _settled(s)
        return f"Pressed {key}. Now at {await _where(s)}"
    if name == "scroll":
        px = max(50, min(int(args.get("pixels") or 600), 5000))
        dy = -px if str(args.get("direction") or "down") == "up" else px
        await page.mouse.wheel(0, dy)
        return f"Scrolled {'up' if dy < 0 else 'down'} {abs(dy)} pixels."
    if name == "wait_for":
        text, selector = str(args.get("text") or "").strip(), str(args.get("selector") or "").strip()
        ms = int(args.get("ms") or 0)
        budget = int(CALL_CAP_S * 1000) - 2000
        try:
            if text:
                await page.get_by_text(text).first.wait_for(timeout=budget)
                return f"\"{text}\" is on the page."
            if selector:
                await page.locator(selector).first.wait_for(timeout=budget)
                return f"{selector} is on the page."
        except Exception:  # noqa: BLE001
            raise BrowserToolError("It did not appear within the wait.") from None
        if ms > 0:
            await asyncio.sleep(min(ms, budget) / 1000)
            return f"Waited {min(ms, budget)} ms."
        raise BrowserToolError("Say what to wait for: text, a selector or a number of milliseconds.")
    if name == "screenshot":
        try:
            png = await page.screenshot(type="png", full_page=bool(args.get("full_page")))
        except Exception as e:  # noqa: BLE001
            raise BrowserToolError(f"The screenshot failed: {str(e).splitlines()[0][:160]}") from None
        await registry.bump(s.sid, screenshots=1)
        return ("image", png, f"Screenshot of {await _where(s)}")
    if name == "back":
        try:
            await page.go_back(wait_until="domcontentloaded")
        except Exception as e:  # noqa: BLE001
            raise BrowserToolError(f"Could not go back: {str(e).splitlines()[0][:160]}") from None
        return f"Back at {await _where(s)}"
    if name == "list_tabs":
        rows = []
        for i, p in enumerate(s.context.pages):
            try:
                t = await p.title()
            except Exception:  # noqa: BLE001
                t = ""
            rows.append(f"{i}{' *' if p is s.page else ''} {p.url}" + (f" ({t})" if t else ""))
        return "\n".join(rows) or "(no tabs)"
    if name == "switch_tab":
        pages = s.context.pages
        i = int(args.get("index") or 0)
        if i < 0 or i >= len(pages):
            raise BrowserToolError(f"There is no tab {i}; there are {len(pages)}.")
        s.page = pages[i]
        s.page.set_default_timeout(30000)
        return f"Current tab is now {i}: {await _where(s)}"
    raise BrowserToolError(f"No tool named browser_{name}.")


def audit_line(d: dict) -> str:
    """The record's one-line shape, for the trace and the log."""
    return json.dumps(d, separators=(",", ":"))

# ===== file: gateway/control_sqlite.py =====
"""SQLite control-store container — the self-hosted sibling of the hosted document store.

WHY THIS EXISTS
The control store holds the coordination state that keeps concurrent turns honest:
idempotency reservations, per-session execution leases (with fencing), response
cursors/terminal state, and API-key cache entries. It was originally written against a
hosted document database, which meant a self-hosted deployment had no control plane at
all — and any request carrying an `Idempotency-Key` failed closed with a 503.

Rather than fork the ~20 control-store functions into a second implementation (two copies
of subtle concurrency logic is how they drift apart), this module supplies a *container*
with the same five operations and the same error semantics the hosted client exposes:

    read_item / create_item / replace_item / upsert_item / delete_item

`control_store` picks the container at runtime, so every function above it — the fencing
maths, the CAS retries, the TTL handling — is byte-for-byte the same code in both
deployments. That is the whole point: one codebase, two backings.

CONCURRENCY
Compare-and-swap is the load-bearing primitive: `replace_item(..., etag=...)` must fail if
another writer changed the document first, or two turns could both believe they hold a
session lease. Here `_etag` is a monotonically bumped counter and the CAS is performed
inside a single IMMEDIATE transaction, so a concurrent writer either loses the race
cleanly (raising the access-condition error the callers already catch) or serialises
behind it. SQLite is opened per-operation in WAL mode, which safely supports the multiple
readers + single writer this workload produces.

TTL
The hosted store expires documents by a `ttl` field. SQLite has no background expiry, so
reads treat an expired document as absent (the same observable behaviour) and writes
opportunistically sweep. Expiry is thus lazy but never *late* from a caller's point of
view, which is what the lease and idempotency logic actually depends on.
"""
from __future__ import annotations

import json
import os
import sqlite3
import time


# ── error types ───────────────────────────────────────────────────────────────
# Named to match the hosted client's exceptions so `except cex.CosmosResourceNotFoundError`
# in control_store works against either backing without a single conditional at the call
# site. control_store resolves `cex` to this module when running self-hosted.
class CosmosResourceNotFoundError(Exception):
    status_code = 404


class CosmosResourceExistsError(Exception):
    status_code = 409


class CosmosAccessConditionFailedError(Exception):
    """Raised when a CAS `replace_item` loses the race (etag no longer current)."""
    status_code = 412


class CosmosHttpResponseError(Exception):
    status_code = 500


def _connect(path: str) -> sqlite3.Connection:
    con = sqlite3.connect(path, timeout=30, isolation_level=None)
    con.execute("PRAGMA journal_mode=WAL")
    con.execute("PRAGMA busy_timeout=30000")
    con.execute("PRAGMA synchronous=NORMAL")
    con.execute("CREATE TABLE IF NOT EXISTS control ("
                "id TEXT PRIMARY KEY, pk TEXT NOT NULL, body TEXT NOT NULL, "
                "etag INTEGER NOT NULL, expires REAL)")
    con.execute("CREATE INDEX IF NOT EXISTS control_pk ON control(pk)")
    return con


def _expires_at(body: dict) -> float | None:
    """Absolute expiry from the document's relative `ttl`, or None for no expiry.

    `ts` is the write time the callers already stamp; falling back to now() keeps a
    document with a ttl but no ts from living forever."""
    try:
        ttl = int(body.get("ttl") or 0)
    except (TypeError, ValueError):
        return None
    if ttl <= 0:
        return None
    try:
        base = float(body.get("ts") or time.time())
    except (TypeError, ValueError):
        base = time.time()
    return base + ttl


class SqliteContainer:
    """Async-shaped container over one SQLite file.

    The methods are `async def` purely to match the hosted client's surface — the work is
    synchronous and fast (single-row, indexed). Making it genuinely async would buy
    nothing here and would add a thread hop to every lease heartbeat.
    """

    def __init__(self, path: str):
        self._path = path
        os.makedirs(os.path.dirname(os.path.abspath(path)) or ".", exist_ok=True)
        _connect(path).close()          # create schema up front, surface I/O errors early

    # -- helpers ---------------------------------------------------------------
    @staticmethod
    def _row_to_doc(row) -> dict:
        doc = json.loads(row[0])
        doc["_etag"] = str(row[1])
        return doc

    def _live(self, con, item_id: str):
        """Fetch a row, treating an expired document as absent (and sweeping it)."""
        row = con.execute("SELECT body, etag, expires FROM control WHERE id=?",
                          (item_id,)).fetchone()
        if row is None:
            return None
        if row[2] is not None and row[2] <= time.time():
            con.execute("DELETE FROM control WHERE id=?", (item_id,))
            return None
        return row

    # -- container operations --------------------------------------------------
    async def read_item(self, item: str, partition_key: str = "", **_kw) -> dict:
        con = _connect(self._path)
        try:
            row = self._live(con, item)
            if row is None:
                raise CosmosResourceNotFoundError(item)
            return self._row_to_doc(row)
        finally:
            con.close()

    async def create_item(self, body: dict, **_kw) -> dict:
        """Insert, or raise Exists — this is the atom idempotency reservation rides on."""
        item_id = str(body.get("id") or "")
        con = _connect(self._path)
        try:
            con.execute("BEGIN IMMEDIATE")
            if self._live(con, item_id) is not None:
                con.execute("ROLLBACK")
                raise CosmosResourceExistsError(item_id)
            # An expired row may still occupy the primary key — _live swept it above.
            con.execute("INSERT OR REPLACE INTO control(id, pk, body, etag, expires) "
                        "VALUES(?,?,?,?,?)",
                        (item_id, str(body.get("pk") or ""), json.dumps(body), 1,
                         _expires_at(body)))
            con.execute("COMMIT")
            return {**body, "_etag": "1"}
        except CosmosResourceExistsError:
            raise
        except Exception as e:  # noqa: BLE001
            try:
                con.execute("ROLLBACK")
            except Exception:  # noqa: BLE001
                pass
            raise CosmosHttpResponseError(str(e)) from e
        finally:
            con.close()

    async def replace_item(self, item: str, body: dict, etag: str | None = None,
                           match_condition=None, **_kw) -> dict:
        """Replace; when `etag` is supplied this is a compare-and-swap.

        Losing the CAS raises the access-condition error rather than overwriting — the
        fencing logic in control_store depends on that being a hard failure, because a
        silent overwrite would let two owners believe they hold the same lease.
        """
        con = _connect(self._path)
        try:
            con.execute("BEGIN IMMEDIATE")
            row = self._live(con, item)
            if row is None:
                con.execute("ROLLBACK")
                raise CosmosResourceNotFoundError(item)
            if etag is not None and str(row[1]) != str(etag):
                con.execute("ROLLBACK")
                raise CosmosAccessConditionFailedError(item)
            new_etag = int(row[1]) + 1
            stored = {k: v for k, v in body.items() if k != "_etag"}
            con.execute("UPDATE control SET pk=?, body=?, etag=?, expires=? WHERE id=?",
                        (str(body.get("pk") or ""), json.dumps(stored), new_etag,
                         _expires_at(stored), item))
            con.execute("COMMIT")
            return {**stored, "_etag": str(new_etag)}
        except (CosmosResourceNotFoundError, CosmosAccessConditionFailedError):
            raise
        except Exception as e:  # noqa: BLE001
            try:
                con.execute("ROLLBACK")
            except Exception:  # noqa: BLE001
                pass
            raise CosmosHttpResponseError(str(e)) from e
        finally:
            con.close()

    async def upsert_item(self, body: dict, **_kw) -> dict:
        item_id = str(body.get("id") or "")
        con = _connect(self._path)
        try:
            con.execute("BEGIN IMMEDIATE")
            row = con.execute("SELECT etag FROM control WHERE id=?", (item_id,)).fetchone()
            new_etag = (int(row[0]) + 1) if row else 1
            stored = {k: v for k, v in body.items() if k != "_etag"}
            con.execute("INSERT OR REPLACE INTO control(id, pk, body, etag, expires) "
                        "VALUES(?,?,?,?,?)",
                        (item_id, str(body.get("pk") or ""), json.dumps(stored), new_etag,
                         _expires_at(stored)))
            con.execute("COMMIT")
            return {**stored, "_etag": str(new_etag)}
        except Exception as e:  # noqa: BLE001
            try:
                con.execute("ROLLBACK")
            except Exception:  # noqa: BLE001
                pass
            raise CosmosHttpResponseError(str(e)) from e
        finally:
            con.close()

    async def delete_item(self, item: str, partition_key: str = "", **_kw) -> None:
        con = _connect(self._path)
        try:
            if self._live(con, item) is None:
                raise CosmosResourceNotFoundError(item)
            con.execute("DELETE FROM control WHERE id=?", (item,))
        finally:
            con.close()

# ===== file: gateway/control_store.py =====
"""Durable transactional control state for the harness gateway (HR-INF-010/011/012/013).

Hot control state (idempotency reservations, per-session execution leases with
fencing tokens, and monotonic response/cancellation state) lives here in a
dedicated Cosmos NoSQL container — NOT on the shared Gremlin partition, and NOT
in per-process dicts that don't survive a replica or coordinate across replicas.

Why Cosmos NoSQL: point reads, atomic create (409 on duplicate id → race-safe
reservation), ETag optimistic concurrency (if_match CAS), per-item TTL, and a
partition key so one org can't be a global hot spot. Auth is AAD via the
gateway's managed identity (no key on the hot path).

Design contract:
- Every item has `pk` (partition key) = f"org::{org}" so all of an org's control
  state co-locates and no cross-org scan is ever needed.
- Idempotency: id=f"idem::{org}::{sha}". reserve() does create_item; a 409 means
  another request already reserved it — the caller reads the winner and replays.
- Lease: id=f"lease::{org}::{sid}". A monotonic integer `fence` is bumped once per
  turn; the turn carries its fence and only commits a checkpoint if the lease
  fence still equals it (a newer turn would have advanced it → stale writer skips).
- Response control: id=f"resp::{org}::{rid}". `terminal` is a one-way latch — once
  a terminal status (cancelled/completed/failed/incomplete) is set, no later write
  may move it back to a live status. This makes cancellation monotonic.

FAIL-CLOSED where correctness demands it (idempotency reserve), best-effort where
it only optimizes (lease/heartbeat) — each call site decides. When COSMOS_ENDPOINT
is unset (local dev), enabled() is False and callers fall back to prior behavior.
"""
from __future__ import annotations

import os
import time

_ENDPOINT = os.environ.get("COSMOS_ENDPOINT", "").strip()
_DB = os.environ.get("HR_CONTROL_DB", "agentstudio")
_CONTAINER = os.environ.get("HR_CONTROL_CONTAINER", "hr_control")
# Optional master key (fallback); AAD via managed identity is preferred.
_KEY = os.environ.get("COSMOS_KEY", "").strip()

_client = None          # CosmosClient (aio)
_cont = None            # ContainerProxy


def _local_mode() -> bool:
    """Self-hosted: no hosted document store configured, so use the SQLite container.
    Mirrors how backing.py chooses its storage, so one env var story covers both."""
    if _ENDPOINT:
        return False
    return (os.environ.get("HR_BACKING", "").strip().lower() or "local") == "local"


def _exceptions():
    """The error namespace matching the ACTIVE container.

    Both namespaces expose the same class names, so every `except cex.CosmosX` below is
    correct under either backing and none of the control-store logic needs a conditional."""
    if _local_mode():
        import control_sqlite
        return control_sqlite
    from azure.cosmos import exceptions as cex
    return cex


def enabled() -> bool:
    """True when a control plane is available. Self-hosted always has one (SQLite), so
    idempotency and leases work there instead of failing closed with a 503."""
    return bool(_ENDPOINT) or _local_mode()


def _pk(org: str) -> str:
    return f"org::{org}"


async def _retryable(coro_factory, attempts: int = 3):
    """Run a Cosmos coroutine with a tiny backoff on TRANSIENT errors (429/503/408/
    network) so a momentary hiccup doesn't turn a keyed request into a hard 503.
    Non-transient errors (409/404/412) propagate immediately — the caller handles
    them as control-flow. coro_factory must return a FRESH awaitable each call."""
    import asyncio as _a
    cex = _exceptions()
    last = None
    for i in range(attempts):
        try:
            return await coro_factory()
        except cex.CosmosHttpResponseError as e:
            if getattr(e, "status_code", None) not in (408, 429, 449, 503):
                raise
            last = e
        except Exception as e:  # azure.core ServiceRequestError/ServiceResponseError (network)
            name = type(e).__name__
            if "ServiceRequest" not in name and "ServiceResponse" not in name:
                raise
            last = e
        await _a.sleep(0.2 * (i + 1))
    raise last  # exhausted transient retries — caller fails closed


async def _container():
    """Lazily build the async Cosmos container proxy. Raises on misconfig so
    fail-closed call sites surface a retryable error instead of running open."""
    global _client, _cont
    if _cont is not None:
        return _cont
    if _local_mode():
        # Self-hosted: one SQLite file beside the rest of the local data.
        import control_sqlite
        root = os.environ.get("HR_DATA_DIR", ".hr-data")
        _cont = control_sqlite.SqliteContainer(os.path.join(root, "control.db"))
        return _cont
    if not _ENDPOINT:
        raise RuntimeError("control store not configured (COSMOS_ENDPOINT unset)")
    from azure.cosmos.aio import CosmosClient
    if _KEY:
        _client = CosmosClient(_ENDPOINT, credential=_KEY)
    else:
        # Managed identity — same UAMI the gateway uses for the session pool.
        from azure.identity.aio import DefaultAzureCredential
        cred = DefaultAzureCredential(
            managed_identity_client_id=os.environ.get("AZURE_CLIENT_ID") or None)
        _client = CosmosClient(_ENDPOINT, credential=cred)
    db = _client.get_database_client(_DB)
    _cont = db.get_container_client(_CONTAINER)
    return _cont


# ── idempotency ───────────────────────────────────────────────────────────────
async def idem_reserve(org: str, sha: str, resp_id: str, req_hash: str,
                       ttl_s: int) -> dict | None:
    """Atomically reserve (org, sha) for resp_id. Returns None if WE won the race
    (caller proceeds to execute). Returns the EXISTING record if someone else
    already reserved it (caller replays that resp_id). Raises on store failure so
    the caller can fail closed with a retryable 503."""
    cont = await _container()
    item = {"id": f"idem::{org}::{sha}", "pk": _pk(org), "kind": "idem",
            "resp_id": resp_id, "req_hash": req_hash, "state": "reserved",
            "ts": time.time(), "ttl": int(ttl_s)}
    cex = _exceptions()
    try:
        await _retryable(lambda: cont.create_item(item))
        return None                      # we won
    except cex.CosmosResourceExistsError:
        try:
            return await _retryable(lambda: cont.read_item(item["id"], partition_key=_pk(org)))
        except cex.CosmosResourceNotFoundError:
            # The item existed at create time but is gone now — a TTL expiry between the
            # 409 and this read. Genuinely nobody holds it → treat as won. Any OTHER error
            # (network/transient) must PROPAGATE so the caller fails closed; swallowing it
            # here would let BOTH racers execute and map the key to the wrong resp_id.
            return None


async def idem_get(org: str, sha: str) -> dict | None:
    cont = await _container()
    cex = _exceptions()
    try:
        return await _retryable(lambda: cont.read_item(f"idem::{org}::{sha}", partition_key=_pk(org)))
    except cex.CosmosResourceNotFoundError:
        return None


async def idem_release(org: str, sha: str, resp_id: str) -> None:
    """Best-effort release of a reservation whose request failed BEFORE it
    persisted any response record — otherwise a retry would replay a resp_id that
    never produced a result (a 'poisoned' key). Only deletes the item if it still
    points at OUR resp_id (never clobber a reservation that a retry already reused)."""
    cex = _exceptions()
    try:
        cont = await _container()
        cur = await cont.read_item(f"idem::{org}::{sha}", partition_key=_pk(org))
        if str(cur.get("resp_id") or "") == resp_id:
            await cont.delete_item(f"idem::{org}::{sha}", partition_key=_pk(org))
    except cex.CosmosResourceNotFoundError:
        return
    except Exception:  # noqa: BLE001
        return


# ── per-session execution lease (fencing) ──────────────────────────────────────
async def lease_acquire(org: str, sid: str, owner: str, ttl_s: int) -> int:
    """Bump and take the session lease; returns THIS turn's fence token (monotonic
    int). A newer turn will get a higher fence, so a stale turn detects it lost the
    workspace at checkpoint time. Best-effort: returns 0 on contention exhaustion OR
    any store error (the caller then behaves as today — no fencing, but the turn
    still runs). NOTE: fencing is not yet wired into the turn path (deferred)."""
    cex = _exceptions()
    try:
        cont = await _container()
        doc_id = f"lease::{org}::{sid}"
        for _ in range(5):                   # bounded CAS retry
            try:
                cur = await cont.read_item(doc_id, partition_key=_pk(org))
                fence = int(cur.get("fence", 0)) + 1
                cur.update(fence=fence, owner=owner, expires=time.time() + ttl_s,
                           ts=time.time(), ttl=max(int(ttl_s) * 4, 3600))
                await cont.replace_item(doc_id, cur,
                                        etag=cur["_etag"], match_condition=_IF_MATCH)
                return fence
            except cex.CosmosResourceNotFoundError:
                try:
                    await cont.create_item({"id": doc_id, "pk": _pk(org), "kind": "lease",
                                            "fence": 1, "owner": owner,
                                            "expires": time.time() + ttl_s,
                                            "ts": time.time(), "ttl": max(int(ttl_s) * 4, 3600)})
                    return 1
                except cex.CosmosResourceExistsError:
                    continue                 # someone created it first — retry the read/bump
            except cex.CosmosAccessConditionFailedError:
                continue                     # ETag moved under us — retry
        return 0                             # gave up (contention) → unfenced fallback
    except Exception:                        # noqa: BLE001 — store down: fail open per docstring
        return 0


async def lease_admit(org: str, sid: str, owner: str, ttl_s: int, *,
                      reject_on_conflict: bool = False, fresh_s: float = 75.0) -> dict:
    """Admission gate at turn start. Reads the session lease and classifies the incumbent:
    a DIFFERENT owner counts as an ACTIVE conflict only if its lease is BOTH live (expires in
    the future) AND fresh (heartbeated within `fresh_s`) — so a crashed/completed-but-unreleased
    lease (which stops renewing) does NOT falsely reject a legitimate follow-up.

    Returns {fence, conflict, rejected, holder}.
    - reject_on_conflict=False (observe): ALWAYS take ownership (bump fence) and just report the
      conflict — the turn proceeds; fence identifies it for checkpoint/heartbeat.
    - reject_on_conflict=True (enforce): on an ACTIVE conflict, DO NOT touch the lease (never steal
      the running turn's fence — that would make ITS checkpoint stale) and return rejected=True so
      the caller refuses the duplicate. Otherwise take ownership.
    Best-effort: on any store error returns {fence:0, conflict:False, rejected:False} → fail OPEN."""
    cex = _exceptions()
    doc_id = f"lease::{org}::{sid}"
    now = time.time()
    try:
        cont = await _container()
        for _ in range(5):
            try:
                cur = await cont.read_item(doc_id, partition_key=_pk(org))
                held_by = str(cur.get("owner") or "")
                live = float(cur.get("expires") or 0) > now
                fresh = (now - float(cur.get("ts") or 0)) < fresh_s
                other = bool(held_by and held_by != owner)
                conflict = bool(live and other)
                active_conflict = bool(conflict and fresh)
                if reject_on_conflict and active_conflict:
                    # Refuse WITHOUT modifying the lease — the incumbent keeps its fence.
                    return {"fence": 0, "conflict": True, "rejected": True, "holder": held_by}
                fence = int(cur.get("fence", 0)) + 1
                cur.update(fence=fence, owner=owner, expires=now + ttl_s, ts=now,
                           ttl=max(int(ttl_s) * 4, 3600))
                try:
                    await cont.replace_item(doc_id, cur, etag=cur["_etag"], match_condition=_IF_MATCH)
                    return {"fence": fence, "conflict": conflict, "rejected": False, "holder": held_by}
                except cex.CosmosAccessConditionFailedError:
                    continue                 # another writer moved it — re-read
            except cex.CosmosResourceNotFoundError:
                try:
                    await cont.create_item({"id": doc_id, "pk": _pk(org), "kind": "lease",
                                            "fence": 1, "owner": owner, "expires": now + ttl_s,
                                            "ts": now, "ttl": max(int(ttl_s) * 4, 3600)})
                    return {"fence": 1, "conflict": False, "rejected": False, "holder": ""}
                except cex.CosmosResourceExistsError:
                    continue
        return {"fence": 0, "conflict": False, "rejected": False, "holder": ""}
    except Exception:  # noqa: BLE001 — store down: fail open (turn runs unfenced)
        return {"fence": 0, "conflict": False, "rejected": False, "holder": ""}


async def lease_renew(org: str, sid: str, owner: str, fence: int, ttl_s: int) -> bool:
    """Heartbeat: extend the lease expiry while WE still hold `fence`. Without this a long turn's
    lease would expire and a follow-up could steal it and wipe the live workspace. Best-effort."""
    if fence <= 0:
        return False
    cex = _exceptions()
    doc_id = f"lease::{org}::{sid}"
    try:
        cont = await _container()
        cur = await cont.read_item(doc_id, partition_key=_pk(org))
        if int(cur.get("fence", 0)) != fence or str(cur.get("owner") or "") != owner:
            return False                     # superseded — we no longer hold it
        cur.update(expires=time.time() + ttl_s, ts=time.time())
        try:
            await cont.replace_item(doc_id, cur, etag=cur["_etag"], match_condition=_IF_MATCH)
            return True
        except cex.CosmosAccessConditionFailedError:
            return False
    except Exception:  # noqa: BLE001
        return False


async def lease_release(org: str, sid: str, owner: str, fence: int) -> None:
    """Turn end: relinquish the lease (expire it now) if we still hold `fence`, so a follow-up
    turn admits without waiting out the TTL. Best-effort; never blocks turn completion."""
    if fence <= 0:
        return
    cex = _exceptions()
    doc_id = f"lease::{org}::{sid}"
    try:
        cont = await _container()
        cur = await cont.read_item(doc_id, partition_key=_pk(org))
        if int(cur.get("fence", 0)) != fence or str(cur.get("owner") or "") != owner:
            return
        cur.update(expires=0, ts=time.time())
        try:
            await cont.replace_item(doc_id, cur, etag=cur["_etag"], match_condition=_IF_MATCH)
        except cex.CosmosAccessConditionFailedError:
            return
    except Exception:  # noqa: BLE001
        return


async def lease_still_held(org: str, sid: str, fence: int) -> bool:
    """True iff the lease fence is UNCHANGED since this turn acquired it. Used to
    gate the checkpoint write so a superseded turn never clobbers newer work.
    Fail-safe: if the store is unreadable we return True (write proceeds) rather
    than silently drop a checkpoint — availability over the rare stale-write race,
    since a single-turn session never advances its own fence."""
    if fence <= 0:
        return True                      # unfenced (store was down at acquire) — don't block
    try:
        cont = await _container()
        cur = await cont.read_item(f"lease::{org}::{sid}", partition_key=_pk(org))
        return int(cur.get("fence", 0)) == fence
    except Exception:
        return True


# ── response control (monotonic cancellation) ──────────────────────────────────
_TERMINAL = {"cancelled", "completed", "failed", "incomplete"}


async def resp_put_running(org: str, rid: str, sid: str, runner_turn_id: str,
                           ttl_s: int) -> None:
    """Upsert a response-control record as live. NEVER downgrades a terminal record
    back to running (monotonic latch) — a cancel that already landed wins."""
    cont = await _container()
    cex = _exceptions()
    doc_id = f"resp::{org}::{rid}"
    try:
        cur = await cont.read_item(doc_id, partition_key=_pk(org))
        if str(cur.get("status")) in _TERMINAL:
            return                       # already terminal — do not revive
        cur.update(status="running", sid=sid, runner_turn_id=runner_turn_id, ts=time.time())
        try:
            await cont.replace_item(doc_id, cur, etag=cur["_etag"], match_condition=_IF_MATCH)
        except cex.CosmosAccessConditionFailedError:
            pass                         # a terminal write raced in — leave it terminal
    except cex.CosmosResourceNotFoundError:
        try:
            await cont.create_item({"id": doc_id, "pk": _pk(org), "kind": "resp",
                                    "status": "running", "sid": sid,
                                    "runner_turn_id": runner_turn_id,
                                    "ts": time.time(), "ttl": int(ttl_s)})
        except cex.CosmosResourceExistsError:
            pass


async def resp_set_cursor(org: str, rid: str, cursor: int) -> None:
    """Persist the turn's harvest cursor — how many of THIS turn's events (sandbox per-turn index)
    have been durably flushed to the trace. This is the resume point if the owning replica dies and
    another adopts the turn: it polls the sandbox with since=cursor, so no already-flushed event is
    re-written or re-emitted. Monotonic (never moves backward); best-effort; never revives a terminal
    record. Cheap single-field patch on the existing resp:: control doc."""
    cont = await _container()
    cex = _exceptions()
    doc_id = f"resp::{org}::{rid}"
    try:
        curr = await cont.read_item(doc_id, partition_key=_pk(org))
    except cex.CosmosResourceNotFoundError:
        return                               # turn not registered yet — nothing to update
    if str(curr.get("status")) in _TERMINAL:
        return                               # already settled — cursor is moot
    if int(cursor) <= int(curr.get("harvest_cursor", 0) or 0):
        return                               # monotonic: never move the resume point backward
    curr["harvest_cursor"] = int(cursor)
    curr["ts"] = time.time()
    try:
        await cont.replace_item(doc_id, curr, etag=curr["_etag"], match_condition=_IF_MATCH)
    except cex.CosmosAccessConditionFailedError:
        pass                                 # a concurrent write won — fine, cursor is advisory


async def resp_get_cursor(org: str, rid: str) -> int:
    """The durable harvest cursor for a turn (0 if none / unreadable). See resp_set_cursor."""
    cont = await _container()
    cex = _exceptions()
    try:
        curr = await cont.read_item(f"resp::{org}::{rid}", partition_key=_pk(org))
        return int(curr.get("harvest_cursor", 0) or 0)
    except cex.CosmosResourceNotFoundError:
        return 0
    except Exception:  # noqa: BLE001
        return 0


async def resp_mark_terminal(org: str, rid: str, status: str, ttl_s: int) -> dict:
    """One-way transition to a terminal status. Returns the record (with sid +
    runner_turn_id) so the caller can propagate cancellation to the runner.
    Idempotent: re-marking an already-terminal record just returns it."""
    cont = await _container()
    cex = _exceptions()
    doc_id = f"resp::{org}::{rid}"
    for _ in range(5):
        try:
            cur = await cont.read_item(doc_id, partition_key=_pk(org))
            if str(cur.get("status")) in _TERMINAL:
                return cur
            cur.update(status=status, ts=time.time())
            try:
                await cont.replace_item(doc_id, cur, etag=cur["_etag"], match_condition=_IF_MATCH)
                return cur
            except cex.CosmosAccessConditionFailedError:
                continue
        except cex.CosmosResourceNotFoundError:
            rec = {"id": doc_id, "pk": _pk(org), "kind": "resp", "status": status,
                   "sid": "", "runner_turn_id": "", "ts": time.time(), "ttl": int(ttl_s)}
            try:
                await cont.create_item(rec)
                return rec
            except cex.CosmosResourceExistsError:
                continue
    return {}


async def resp_is_cancelled(org: str, rid: str) -> bool:
    try:
        cont = await _container()
        cex = _exceptions()
        try:
            cur = await cont.read_item(f"resp::{org}::{rid}", partition_key=_pk(org))
        except cex.CosmosResourceNotFoundError:
            return False
        return str(cur.get("status")) == "cancelled"
    except Exception:
        return False


async def try_lock(name: str, ttl_s: int) -> bool:
    """One-shot distributed mutex via atomic create_item: returns True iff WE created the lock doc
    (nobody else holds it), False if it already exists (another holder — skip this cycle). Per-item
    TTL auto-expires the lock, so a holder that dies never wedges it. RAISES on a store error so the
    caller can distinguish 'someone else has it' (skip) from 'store unavailable' (the caller's choice
    to fall back). Used for single-flight periodic work (the winner runs it, losers skip)."""
    cex = _exceptions()
    try:
        cont = await _container()
        await cont.create_item({"id": f"lock::{name}", "pk": "org::_system", "kind": "lock",
                                "ts": time.time(), "ttl": int(ttl_s)})
        return True
    except cex.CosmosResourceExistsError:
        return False


# ── API-key hot-read cache (HR-INF-010) ────────────────────────────────────────────────
# The public Bearer auth read (_apikey_resolve) hit the shared Gremlin partition on EVERY public
# request. These make the control store the hot-path read: a SELF-KEYED doc (pk == id == the token
# hash — the org is unknown pre-auth, so an org partition can't serve it) that is a write-through
# cache of the graph key record. The graph stays the source of truth (list/durable); dual-writes on
# mint/revoke keep this in sync (instant revocation, no TTL lag), and a lazy backfill on first
# resolve migrates pre-existing keys so Gremlin is never hit on the hot path afterward.
def _apikey_id(sha: str) -> str:
    return f"apikey::{sha}"


# Per-item TTL on key docs: NOT the revocation mechanism (dual-write on revoke is, giving instant
# revocation) — it's a STALENESS BOUND. If a revoke's dual-write ever fails, the stale-valid cache
# doc expires within this window and the next resolve falls back to the authoritative graph
# (revoked). An active key is re-backfilled at most once per TTL (one Gremlin read/hour), negligible.
_APIKEY_TTL_S = int(os.environ.get("HR_APIKEY_TTL_S", "3600"))


async def apikey_get(sha: str) -> dict | None:
    """Point-read a key doc by hash. Returns None on miss OR on ANY error (incl. a missing SDK /
    misconfig) — the caller falls back to the graph (the source of truth), so nothing here can
    ever fail-close public auth."""
    try:
        cex = _exceptions()
        cont = await _container()
        try:
            return await _retryable(lambda: cont.read_item(_apikey_id(sha), partition_key=_apikey_id(sha)))
        except cex.CosmosResourceNotFoundError:
            return None
    except Exception:  # noqa: BLE001 — store down / SDK missing → graph fallback
        return None


async def apikey_put(sha: str, org: str, member: str, workspace: str,
                     workspace_default: bool, revoked: bool = False,
                     create_only: bool = False) -> None:
    """Write the key doc, TTL-bounded. mint uses upsert (authoritative fresh key). The lazy
    BACKFILL uses create_only=True: a create_item that 409s (a doc already exists — possibly a
    revoke tombstone written in the race window) leaves it untouched. A plain upsert here would
    resurrect a just-revoked key for up to a TTL (HR-INF-010 review #1)."""
    cont = await _container()
    item = {"id": _apikey_id(sha), "pk": _apikey_id(sha), "kind": "apikey",
            "org": org, "member": member, "workspace": workspace,
            "workspace_default": bool(workspace_default), "revoked": bool(revoked),
            "ts": time.time(), "ttl": _APIKEY_TTL_S}
    if create_only:
        cex = _exceptions()
        try:
            await _retryable(lambda: cont.create_item(item))
        except cex.CosmosResourceExistsError:
            return                              # a doc (maybe a tombstone) already exists — never clobber
    else:
        await _retryable(lambda: cont.upsert_item(item))


async def apikey_revoke(sha: str) -> None:
    """Mark a key revoked (dual-write on revoke). Upserts a revoked marker even for a key never
    backfilled, so the hot read returns None immediately without consulting the graph. The revoked
    marker gets a LONGER TTL than a live doc so it can't expire back to a graph re-read before the
    graph revocation is certain to be visible."""
    cont = await _container()
    cex = _exceptions()
    ttl = max(_APIKEY_TTL_S * 24, 86400)   # keep the tombstone well past a live doc's lifetime
    try:
        cur = await _retryable(lambda: cont.read_item(_apikey_id(sha), partition_key=_apikey_id(sha)))
        cur["revoked"] = True
        cur["ttl"] = ttl
        await _retryable(lambda: cont.upsert_item(cur))
    except cex.CosmosResourceNotFoundError:
        await _retryable(lambda: cont.upsert_item({
            "id": _apikey_id(sha), "pk": _apikey_id(sha), "kind": "apikey", "revoked": True,
            "ts": time.time(), "ttl": ttl}))


async def healthcheck() -> bool:
    """Readiness probe: can we actually reach the control store? Cheap point read
    of a sentinel id (404 is a healthy answer — the store responded)."""
    cont = await _container()
    cex = _exceptions()
    try:
        await cont.read_item("health::probe", partition_key="org::_health")
    except cex.CosmosResourceNotFoundError:
        return True
    return True


# azure-cosmos uses azure.core.MatchConditions for optimistic concurrency.
try:  # imported lazily-safe so module import never fails when the SDK is absent
    from azure.core import MatchConditions as _MC
    _IF_MATCH = _MC.IfNotModified
except Exception:  # pragma: no cover
    _IF_MATCH = None

# ===== file: gateway/media_plane.py =====
"""Making a picture, a clip, a line of speech — and assembling them into one film.

Two callers, one engine, one place the provider key is resolved:

  * the `media` MCP server this gateway hosts, so an agent can ask for a CAPABILITY
    (text_to_video, text_to_image, …) and be told which model actually ran;
  * the routes a media app calls to read its canvas, poll its jobs and export a film.

WHAT NEVER LEAVES THIS PROCESS. The provider key is resolved from the integrations document
inside the gateway, at the moment of use. The runner never receives it (an agent gets a per-