Skip to content

Browsing Isolation API

Create and manage secure Silo browsing contexts. Requires ADMIN_TOKEN.

See Authentication for token setup and Wire Protocol for how requests are structured.

Bases: BaseAPIClient

API client for Silo browsing isolation operations.

This class provides methods for creating, managing, and deleting secure browsing session contexts using the Authentic8 Silo platform.

The browsing isolation API allows you to: - Create secure browsing contexts with custom policies - Retrieve context information and status - Delete contexts when no longer needed - Bulk create multiple contexts - Generate launch URLs for contexts

Note

Available policy types (not exhaustive — see MkDocs browsing policy reference for full param lists):

  • readonly: Make session read-only ("true" / "false")
  • file_transfer: File upload/download control ("block_all", "allow_all")
  • clipboard: Clipboard direction control ("block_all", "allow_all", "allow_to_local", "block_to_silo")
  • ad_block: Ad blocking ("enable", "disable")
  • browser_chrome: UI mode for the Silo ribbon/chrome. "standard" — default ribbon UI; "seamless" — hides the ribbon (non-catchall users only; catchall users are always forced to "minimal" regardless of this setting); "minimal" — minimal ribbon mode (Ribbon Mode)
  • domain_allow: Whitelist specific domains (added automatically when url is provided)
  • domain_block: Blacklist specific domains
  • ribbon_background_color: HUD banner background (hex string)
  • ribbon_text_color: HUD banner text color (hex string)
  • ribbon_message: HUD banner message (max 100 chars)

Examples:

>>> from silo_sdk import BrowsingAPI, load_config
>>> config = load_config()
>>> browsing = BrowsingAPI(config)
>>>
>>> # Create a context
>>> context_id = browsing.create_context(
...     url="https://example.com",
...     username="user@company.com",
...     policy=[{"type": "readonly", "params": ["true"]}]
... )
>>>
>>> # Generate launch URL
>>> launch_url = browsing.create_ctx_url(context_id)
>>> print(f"Launch URL: {launch_url}")
Source code in silo_sdk/browsing/isolation_api.py
 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
class BrowsingAPI(BaseAPIClient):
    """API client for Silo browsing isolation operations.

    This class provides methods for creating, managing, and deleting secure
    browsing session contexts using the Authentic8 Silo platform.

    The browsing isolation API allows you to:
    - Create secure browsing contexts with custom policies
    - Retrieve context information and status
    - Delete contexts when no longer needed
    - Bulk create multiple contexts
    - Generate launch URLs for contexts

    Note:
        **Available policy types** (not exhaustive — see MkDocs browsing
        policy reference for full param lists):

        - ``readonly``: Make session read-only (``"true"`` / ``"false"``)
        - ``file_transfer``: File upload/download control
          (``"block_all"``, ``"allow_all"``)
        - ``clipboard``: Clipboard direction control
          (``"block_all"``, ``"allow_all"``, ``"allow_to_local"``,
          ``"block_to_silo"``)
        - ``ad_block``: Ad blocking (``"enable"``, ``"disable"``)
        - ``browser_chrome``: UI mode for the Silo ribbon/chrome.
          ``"standard"`` — default ribbon UI;
          ``"seamless"`` — hides the ribbon (**non-catchall users only**;
          catchall users are always forced to ``"minimal"``
          regardless of this setting);
          ``"minimal"`` — minimal ribbon mode (Ribbon Mode)
        - ``domain_allow``: Whitelist specific domains (added automatically
          when ``url`` is provided)
        - ``domain_block``: Blacklist specific domains
        - ``ribbon_background_color``: HUD banner background (hex string)
        - ``ribbon_text_color``: HUD banner text color (hex string)
        - ``ribbon_message``: HUD banner message (max 100 chars)

    Examples:
        >>> from silo_sdk import BrowsingAPI, load_config
        >>> config = load_config()
        >>> browsing = BrowsingAPI(config)
        >>>
        >>> # Create a context
        >>> context_id = browsing.create_context(
        ...     url="https://example.com",
        ...     username="user@company.com",
        ...     policy=[{"type": "readonly", "params": ["true"]}]
        ... )
        >>>
        >>> # Generate launch URL
        >>> launch_url = browsing.create_ctx_url(context_id)
        >>> print(f"Launch URL: {launch_url}")
    """

    def __init__(self, config: dict[str, Any]) -> None:
        """Initialize the browsing API client.

        Args:
            config: Configuration dictionary containing API settings

        Raises:
            ConfigurationError: If required configuration is missing
        """
        super().__init__(config)

        # Validate required configuration
        validate_config_for_api(config, ["ADMIN_TOKEN"])

        self.auth_token = config["ADMIN_TOKEN"]
        # Off by default: it costs a list_egresses round trip per context
        # created. The MCP server turns it on (MCP_EGRESS_VALIDATION).
        self.live_egress_validation = _config_flag(
            config.get("LIVE_EGRESS_VALIDATION", False)
        )
        self.logger.info("Initialized BrowsingAPI client")

    @api_tag(MethodType.API_COMMAND, api_command="create_context")
    def create_context(
        self,
        url: str | None = None,
        username: str | None = None,
        policy: list[dict[str, Any]] | None = None,
        max_uses: int | None = None,
        expires: int | float | str | None = None,
        restrict_client_ips: list[str] | None = None,
        org: str | None = None,
        session_type: Literal["silo-ruby", "toolbox-standalone"] | None = None,
        egress_region: str | None = None,
        browser_profile: BrowserProfile | None = None,
        categories: Categories | None = None,
        auto_domain_allow: bool = False,
        egress_info: EgressInfo | None = None,
        validate_egress: bool | None = None,
    ) -> str:
        """Create a new browsing context.

        Creates a secure browsing context that can be used to launch isolated
        browsing sessions with the specified URL and policies.

        Args:
            url: Target URL for the context (optional for toolbox-standalone).
                Sent as ``"urls": [url]`` (array) in the wire format. The domain
                is automatically extracted and added as a ``domain_allow`` policy
                entry to the provided policy list.
            username: Username associated with the context.
                Either username or org must be provided (but not both). Sent as
                ``"user"`` in the wire format (field name differs from this param).
            policy: List of policy dictionaries, each with ``"type"`` and
                ``"params"`` keys. See class-level ``Attributes`` for available
                policy types and valid param values.

                **Seamless UI constraint:** ``{"type": "browser_chrome",
                "params": ["seamless"]}`` is only effective for
                **non-catchall users**. Catchall users — via a catchall
                account, an org configured to treat all users as catchall, or
                partner SSO — are always forced to ``"minimal"`` (Ribbon Mode)
                regardless of this policy setting.
            max_uses: Maximum number of times the context can be used.
                Sent at the **command level** (not inside ``context_data``).
            expires: Context expiration: epoch seconds as a **number**,
                ``"+SECONDS"`` (relative), or an ISO 8601 string. An all-digit
                string such as ``"1792253988"`` is converted to an int before
                sending, because the server parses strings as ISO 8601 and
                would reject it. Sent at the **command level** (not inside ``context_data``),
                same as ``max_uses``.
            restrict_client_ips: List of IP addresses/CIDRs to restrict access.
                Sent as ``"restrict_ips"`` in the wire format (field name differs
                from this param).
            org: Org slug/vanity URL for SAML-enabled organizations.
                Either username or org must be provided (but not both).
            session_type: Session type — ``"silo-ruby"`` (default, Safe Access)
                or ``"toolbox-standalone"`` (Silo for Research).
            egress_region: Egress location name from the managed attribution
                network. Accepts a specific city (e.g., ``"New York, NY"``),
                a country (``"United States"``), a region (``"North America"``),
                or ``"World"`` for random assignment. The backend resolves
                via ``hierarchy_tag`` lookup. See
                ``silo_sdk.harvesting.egress_validation.VALID_EGRESS_NAMES``
                for the complete list. A name missing from that list logs a
                warning and is still sent — the list is compiled into the SDK
                and can lag the platform, so the platform has the final say.

                **Important — mixed licensing:** Even if a location passes SDK
                validation, the user may receive an egress error when the browsing
                context is launched if their license does not include rights to that
                specific location. SDK validation confirms the location name is valid
                for the platform's shared network, but per-user license entitlements
                are enforced at session launch time, not at context creation.
            browser_profile: Browser profile dict for user-agent selection.
                Keys: ``"os"``, ``"browser"``, and optionally ``"timezone"``
                (IANA name) and ``"languages"`` (Accept-Language string).
            categories: Egress category settings with ``"availability"``,
                ``"connectivity"``, and ``"protocol"`` keys. ``"connectivity"``
                and ``"protocol"`` are validated against what is actually
                available at ``egress_region`` (or any location, if
                ``egress_region`` is omitted) — see
                ``get_egress_locations()`` for per-location details.
            auto_domain_allow: If ``True``, automatically append a
                ``domain_allow`` policy entry for the URL's domain when
                ``url`` is provided. Defaults to ``False``.

                Leave this ``False`` (the default) if you want to construct
                your own ``domain_allow`` policy entry — for example, to
                allow multiple domains in a single entry::

                    policy=[{
                        "type": "domain_allow",
                        "params": ["google.com", "yahoo.com"]
                    }]

                When ``auto_domain_allow=True``, only the domain extracted
                from ``url`` is injected. It cannot be used to allow
                additional domains beyond the target URL's domain.
            egress_info: Egress selection as a single object, with ``"name"``
                and optional ``"server_set"`` and ``"categories"`` keys. This
                is the newer form and the only way to request a
                ``server_set``.

                **Mutually exclusive with** ``egress_region`` and
                ``categories`` — pass either this or those, never both. The
                platform rejects the mixture, and so does this method, so the
                error arrives before the round trip rather than after it.
            validate_egress: Check the requested egress against the
                platform's live directory for ``username``
                (:meth:`list_egresses`) before creating the context, and
                raise :class:`ValidationError` if it is not offered. ``None``
                (default) uses the ``LIVE_EGRESS_VALIDATION`` config key.
                Skipped, with a warning, when there is no ``username`` (an
                org-level directory is not authoritative for its users) or
                the directory cannot be fetched; an empty directory means the
                platform chooses the egress and is never refused.

        Note:
            Wire format parameter mappings:

            - Python ``username`` → wire ``"user"``
              (inside ``context_data``)
            - Python ``url`` (string) → wire ``"urls"`` (list,
              inside ``context_data``)
            - ``max_uses`` and ``expires`` go at the **command level**
              (alongside ``"command"``, not inside ``context_data``)
            - ``domain_allow`` is only added when ``auto_domain_allow=True``

            Wire format structure::

                {
                    "command": "create_context",
                    "max_uses": 5,       # ← command level
                    "expires": "2026-12-31T23:59:59Z",  # ← command level (or epoch int)
                    "context_data": {
                        "user": "user@company.com",  # ← username → "user"
                        "urls": ["https://example.com"],  # ← url → "urls" (list)
                        "policy": [...]
                    }
                }

        Returns:
            Browse context ID (``browse_context_id``) that can be used to launch
            sessions. Pass this to ``create_ctx_url()`` to get a launch URL, or
            use the GET ``/ctx/`` shorthand endpoint directly (see Note).

        Raises:
            BrowsingAPIError: If context creation fails
            ValidationError: If parameters are invalid
            EgressNotOfferedError: A ``ValidationError`` subclass, when live
                egress validation is on and the directory does not offer the
                requested egress

        Note:
            **GET /ctx shorthand:** As an alternative to the two-step
            create → launch flow, the ``/ctx/`` endpoint at
            ``https://extapi.authentic8.com/ctx/`` creates and launches a context
            in a single GET request using inline query parameters::

                GET https://extapi.authentic8.com/ctx/
                    ?auth=<admin_token>
                    &user=<username>
                    &url=<target_url>
                    &response=url

            The ``response`` parameter controls the return format:

            - ``url`` (default) — returns the launch URL as plain text (useful for automation)
            - ``redirect`` — HTTP redirect directly into the Silo session
            - ``id`` — returns just the context launch ID as plain text

            This shorthand does **not** go through the ``/api/`` command-array format.

        Examples:
            >>> # Basic isolation context
            >>> policy = [
            ...     {"type": "file_transfer", "params": ["block_all"]},
            ...     {"type": "clipboard", "params": ["allow_to_local"]},
            ... ]
            >>> context_id = api.create_context(
            ...     url="https://example.com",
            ...     username="user@company.com",
            ...     policy=policy,
            ...     max_uses=5
            ... )

            >>> # Silo for Research session with egress
            >>> context_id = api.create_context(
            ...     url="https://example.com",
            ...     username="researcher@company.com",
            ...     session_type="toolbox-standalone",
            ...     egress_region="New York, NY",
            ...     browser_profile={"os": "win", "browser": "chrome"},
            ...     categories={"availability": "public", "connectivity": "datacenter"}
            ... )

            >>> # Same egress selection via the egress_info object, which also
            >>> # allows a server_set. Do not combine it with egress_region.
            >>> context_id = api.create_context(
            ...     url="https://example.com",
            ...     username="researcher@company.com",
            ...     session_type="toolbox-standalone",
            ...     egress_info={
            ...         "name": "New York, NY",
            ...         "server_set": "dedicated-pool-a",
            ...         "categories": {
            ...             "availability": "public",
            ...             "connectivity": "datacenter",
            ...         },
            ...     },
            ... )
        """
        # Validate user/org - exactly one must be provided
        if not username and not org:
            raise ValidationError("Either username or org must be provided")
        if username and org:
            raise ValidationError("Only one of username or org should be provided")

        if username and not isinstance(username, str):
            raise ValidationError("Username must be a non-empty string")

        if org and not isinstance(org, str):
            raise ValidationError("Org must be a non-empty string")

        # Initialize policy if not provided
        if policy is None:
            policy = []
        elif not isinstance(policy, list):
            raise ValidationError("Policy must be a list of dictionaries")

        # Build context data
        context_data: dict[str, Any] = {}

        # Add user or org
        if username:
            context_data["user"] = username
        if org:
            context_data["org"] = org

        # Add URL(s) if provided
        if url:
            if not isinstance(url, str):
                raise ValidationError("URL must be a non-empty string")
            try:
                parsed_url = urlparse(url)
                if not parsed_url.netloc:
                    raise ValidationError(f"Invalid URL format: {url}")
                if auto_domain_allow:
                    policy = policy + [
                        {"type": "domain_allow", "params": [parsed_url.netloc]}
                    ]
            except ValidationError:
                # Don't let the generic handler below re-wrap our own clean
                # ValidationError message (e.g. "Invalid URL format: ...")
                # into a confusing "Failed to parse URL: Invalid URL format:
                # ..." double-wrap.
                raise
            except Exception as e:
                raise ValidationError(f"Failed to parse URL: {e}") from e
            context_data["urls"] = [url]

        # Add policy if not empty
        if policy:
            context_data["policy"] = policy

        # Add session type for Silo for Research
        _validate_session_type(session_type)
        if session_type:
            context_data["session_type"] = session_type

        # Validate the legacy egress parameters (see _validate_legacy_egress).
        _validate_legacy_egress(egress_region, categories)
        if egress_region:
            context_data["egress_region"] = egress_region

        # Add browser profile
        if browser_profile:
            context_data["browser_profile"] = browser_profile

        if categories:
            context_data["categories"] = categories

        # egress_info supersedes the separate egress_region/categories params
        # and cannot be mixed with them. The platform returns
        # "cannot combine 'egress_info' with legacy egress fields: ..." for
        # the mixture; catching it here names the same conflict without
        # spending a round trip, and reaches callers who never see the
        # response body.
        if egress_info is not None:
            conflicting = [
                name
                for name, value in (
                    ("egress_region", egress_region),
                    ("categories", categories),
                )
                if value
            ]
            if conflicting:
                raise ValidationError(
                    f"cannot combine 'egress_info' with legacy egress fields: "
                    f"{', '.join(conflicting)}. Move them into egress_info "
                    f"instead — 'egress_region' becomes its 'name'."
                )
            validate_egress_info(egress_info)
            context_data["egress_info"] = egress_info

        live = (
            self.live_egress_validation if validate_egress is None else validate_egress
        )
        if live:
            requested = self._requested_egress(egress_info, egress_region, categories)
            if requested is not None:
                self._check_egress_live(requested, username, session_type)

        # Add optional parameters
        if restrict_client_ips is not None:
            if not isinstance(restrict_client_ips, list):
                raise ValidationError("restrict_client_ips must be a list")
            context_data["restrict_ips"] = restrict_client_ips

        # Build create_context command
        create_cmd: dict[str, Any] = {
            "command": "create_context",
            "context_data": context_data,
        }

        # Add max_uses to command (not context_data per API spec)
        if max_uses is not None:
            if not isinstance(max_uses, int) or max_uses <= 0:
                raise ValidationError("max_uses must be a positive integer")
            create_cmd["max_uses"] = max_uses

        # Add expires at command level (not inside context_data, same as max_uses)
        if expires is not None:
            create_cmd["expires"] = _normalize_expires(expires)

        # Prepare API request
        payload = [create_cmd]

        try:
            self.logger.debug("Creating browsing context for URL: %s", url)
            response = self._make_api_request("POST", "api/", self.auth_token, payload)

            # _extract_api_result raises with the server's own message for
            # both error shapes, {"error": ...} and {"result": {"error": ...}}.
            result = self._extract_api_result(response)
            browse_context_id: str | None = (
                result.get("browse_context_id") if isinstance(result, dict) else None
            )
            if browse_context_id:
                self.logger.info("Created context with ID: %s", browse_context_id)
                return browse_context_id

            raise BrowsingAPIError(
                f"Failed to retrieve context ID from response: {response}"
            )

        except Exception as e:
            if isinstance(e, BrowsingAPIError):
                raise
            if isinstance(e, SiloError):
                raise BrowsingAPIError(
                    f"Failed to create context: {e}",
                    status_code=e.status_code,
                    response_data=e.response_data,
                    request_id=e.request_id,
                ) from e
            raise BrowsingAPIError(f"Failed to create context: {e}") from e

    @staticmethod
    def _requested_egress(
        egress_info: EgressInfo | None,
        egress_region: str | None,
        categories: Categories | None,
    ) -> dict[str, Any] | None:
        """The egress a request asks for, in egress_info form, or None."""
        if egress_info is not None:
            return dict(egress_info)
        if egress_region or categories:
            requested: dict[str, Any] = {"name": egress_region or "World"}
            if categories:
                requested["categories"] = dict(categories)
            return requested
        return None

    def _check_egress_live(
        self,
        egress: dict[str, Any],
        username: str | None,
        session_type: str | None,
    ) -> None:
        """Validate ``egress`` against the live directory, or explain why not.

        Raises only for a real "not offered". Every other outcome falls back
        to the advisory checks create_context has already run.
        """
        if egress.get("server_set"):
            self.logger.warning(
                "Live egress validation skipped: egress_info names a server_set, "
                "and the platform checks that set directly; it can hold egress "
                "the directory does not list. The request has NOT been blocked."
            )
            return
        if not username:
            self.logger.warning(
                "Live egress validation skipped: it needs a username. A context "
                "created for an org names it by slug, which the directory cannot "
                "be queried by. The request has NOT been blocked."
            )
            return
        try:
            directory = self.list_egresses(username, session_type=session_type)
        except BrowsingAPIError as e:
            self.logger.warning(
                "Live egress validation skipped: %s. The compiled-in checks "
                "still ran; the request has NOT been blocked.",
                e,
            )
            return
        if not directory:
            if session_type in (None, "silo-ruby"):
                self.logger.warning(
                    "Live egress validation: no egress a standard session may pin "
                    "for %s. If the org runs Traffic Manager rules the platform "
                    "will refuse a pinned egress; otherwise none is provisioned "
                    "for standard sessions. The request has NOT been blocked.",
                    username,
                )
            else:
                self.logger.info(
                    "Live egress validation: no pinnable egress for %s (the "
                    "platform chooses it); not validating.",
                    username,
                )
            return
        try:
            check_egress_against_directory(egress, directory)
        except ValidationError as e:
            raise EgressNotOfferedError(
                f"{e} An org's Launcher Options can hide a region from this list; "
                "if you are sure, pass validate_egress=False to send it anyway."
            ) from e

    @api_tag(MethodType.API_COMMAND, api_command="get_context")
    def get_context(self, browse_context_id: str) -> dict[str, Any]:
        """Retrieve details of a browsing context.

        Gets detailed information about an existing browsing context including
        creation time, usage count, policies, and expiration details.

        Args:
            browse_context_id: ID of the browsing context

        Returns:
            Dictionary containing context details:

            - ``browse_context_id``: The context ID
            - ``name``: Context name
            - ``user_id``: Associated user ID
            - ``org_id`` / ``launch_org_id``: Owning and launching org
            - ``use_count``: Number of times the context has been used
            - ``max_uses``: Maximum allowed uses
            - ``create_ts``: Creation timestamp
            - ``expires``: Expiration timestamp
            - ``last_use``: Timestamp of the most recent use
            - ``enabled``: Whether the context is currently usable
            - ``commonality``: Context sharing scope
            - ``context_data``: The context's configuration, as supplied to
                :meth:`create_context`

            **Three names in an earlier version of this list were never
            sent** -- ``created_ts`` (the field is ``create_ts``),
            ``expires_ts`` (it is ``expires``) and ``policy`` (the
            configuration comes back under ``context_data``).

        Raises:
            BrowsingAPIError: If context retrieval fails
            ValidationError: If browse_context_id is invalid

        Examples:
            >>> context_info = api.get_context("0123456789abcdef0123456789abcdef")
            >>> print(f"Context used {context_info['use_count']} times")
        """
        if not browse_context_id or not isinstance(browse_context_id, str):
            raise ValidationError("browse_context_id must be a non-empty string")

        payload = [{"command": "get_context", "browse_context_id": browse_context_id}]

        try:
            self.logger.debug("Retrieving context: %s", browse_context_id)
            response = self._make_api_request("POST", "api/", self.auth_token, payload)

            # _extract_api_result raises with the server's own message for
            # both error shapes — a deleted context ID comes back as
            # {"result": {"error": ...}}, which used to surface only as
            # "No context data found".
            result = self._extract_api_result(response)
            if isinstance(result, dict) and "browse_context_id" in result:
                self.logger.debug("Retrieved context details")
                return cast(dict[str, Any], result)

            raise BrowsingAPIError(
                f"No context data found in response for ID: {browse_context_id}"
            )

        except Exception as e:
            if isinstance(e, BrowsingAPIError):
                raise
            if isinstance(e, SiloError):
                raise BrowsingAPIError(
                    f"Failed to retrieve context: {e}",
                    status_code=e.status_code,
                    response_data=e.response_data,
                    request_id=e.request_id,
                ) from e
            raise BrowsingAPIError(f"Failed to retrieve context: {e}") from e

    @api_tag(MethodType.API_COMMAND, api_command="delete_context")
    def delete_context(self, browse_context_id: str) -> bool:
        """Delete a browsing context.

        Permanently deletes a browsing context, making it unusable for future
        sessions. This action cannot be undone.

        Args:
            browse_context_id: ID of the browsing context to delete

        Returns:
            True if deletion was successful, False otherwise

        Raises:
            BrowsingAPIError: If context deletion fails
            ValidationError: If browse_context_id is invalid

        Examples:
            >>> success = api.delete_context("0123456789abcdef0123456789abcdef")
            >>> if success:
            ...     print("Context deleted successfully")
        """
        if not browse_context_id or not isinstance(browse_context_id, str):
            raise ValidationError("browse_context_id must be a non-empty string")

        payload = [
            {"command": "delete_context", "browse_context_id": browse_context_id}
        ]

        try:
            self.logger.debug("Deleting context: %s", browse_context_id)
            response = self._make_api_request("POST", "api/", self.auth_token, payload)

            result = self._extract_api_result(response)
            if isinstance(result, dict) and result.get("deleted") in (1, True):
                self.logger.info("Successfully deleted context: %s", browse_context_id)
                return True

            self.logger.warning(
                "Unexpected response format when deleting context %s: %s",
                browse_context_id,
                result,
            )
            return False

        except Exception as e:
            if isinstance(e, BrowsingAPIError):
                raise
            raise BrowsingAPIError(f"Failed to delete context: {e}") from e

    @api_tag(MethodType.API_COMMAND, api_command="update_context")
    def update_context(
        self,
        browse_context_id: str,
        context_data: dict[str, Any] | None = None,
        max_uses: int | None = None,
        expires: int | float | str | None = None,
        name: str | None = None,
        enabled: bool | None = None,
    ) -> dict[str, Any]:
        """Update an existing browsing context.

        Modifies an existing context. The top-level fields (``name``,
        ``enabled``, ``max_uses``, ``expires``) are independent: omitted ones
        are left unchanged. ``context_data`` is different: it **replaces** the
        stored object entirely.

        Warning:
            Send the **complete** ``context_data`` (fetch it with
            :meth:`get_context`, change what you need, send it all back).
            Fields omitted are removed -- e.g. an update carrying only
            ``urls`` drops ``restrict_ips`` (the IP lock) and
            ``egress_region``. The server then re-applies create defaults:
            ``session_type`` becomes ``"silo-ruby"`` if missing, and a
            ``toolbox-standalone`` context without an egress region falls back
            to the org root.

        Warning:
            Unlike create, the server skips egress-provisioning and
            dynamic-policy checks on update. An update can store an egress the
            org cannot use (the context then fails at launch), and a
            ``domain_allow`` set through update gets no automatic
            ``domain_block *`` entry. This method does not validate either.

        Note:
            A nonexistent or deleted ``browse_context_id`` is **not** reported
            as an error: the server answers ``{"result": 0}`` and this method
            returns ``{}`` (a warning is logged).

        Args:
            browse_context_id: ID of the context to update (required).
            context_data: Complete replacement session configuration (same
                structure as ``create_context()``). **Replaces** the stored
                object; omitted fields are removed. Supports ``policy``,
                ``egress_region``, ``session_type``, ``browser_profile``,
                ``categories``, etc.
            max_uses: New maximum number of times the context may be used.
            expires: New expiration: epoch seconds as a number,
                ``"+SECONDS"`` (relative), or ISO 8601. An all-digit string is
                converted to an int before sending.
            name: New display name for the context.
            enabled: Whether the context is enabled.

        Returns:
            Dictionary containing the updated context details from the server.

        Raises:
            BrowsingAPIError: If the update request fails
            ValidationError: If browse_context_id is invalid

        Examples:
            >>> api.update_context(
            ...     "0123456789abcdef0123456789abcdef",
            ...     max_uses=10,
            ...     name="updated-context",
            ... )
        """
        if not browse_context_id or not isinstance(browse_context_id, str):
            raise ValidationError("browse_context_id must be a non-empty string")

        command: dict[str, Any] = {
            "command": "update_context",
            "browse_context_id": browse_context_id,
        }
        if context_data is not None:
            command["context_data"] = context_data
            if "session_type" not in context_data:
                self.logger.warning(
                    "update_context(%s): context_data has no session_type, so the "
                    "server will set it to 'silo-ruby'; context_data replaces the "
                    "stored object, so any field omitted from it is dropped",
                    browse_context_id,
                )
        if max_uses is not None:
            command["max_uses"] = max_uses
        if expires is not None:
            command["expires"] = _normalize_expires(expires)
        if name is not None:
            command["name"] = name
        if enabled is not None:
            command["enabled"] = enabled

        payload = [command]

        try:
            self.logger.debug("Updating context: %s", browse_context_id)
            response = self._make_api_request("POST", "api/", self.auth_token, payload)

            result = self._extract_api_result(response)
            if result == 0 and not isinstance(result, bool):
                self.logger.warning(
                    "update_context(%s): server returned 0; the context may not "
                    "exist (deleted or unknown id) and nothing was updated",
                    browse_context_id,
                )
            else:
                self.logger.info("Successfully updated context: %s", browse_context_id)
            if isinstance(result, dict):
                return result
            return {}

        except Exception as e:
            if isinstance(e, BrowsingAPIError):
                raise
            raise BrowsingAPIError(f"Failed to update context: {e}") from e

    @api_tag(MethodType.UTILITY)
    @staticmethod
    def create_ctx_url(ctx: str, base_url: str = "https://a8silo.com") -> str:
        """Create a Silo web client launch URL for a browsing context.

        Generates a ``https://a8silo.com/launch?ctx=<id>`` URL for opening an
        already-created context in the Silo web client. The context must first
        be created via ``create_context()``.

        For a single-step alternative that creates and launches in one GET
        request, see the ``/ctx/`` shorthand documented in ``create_context()``.

        Args:
            ctx: Browse context ID (from ``create_context()``)
            base_url: Base URL for the Silo web client (default: ``https://a8silo.com``)

        Returns:
            Full URL for launching the Silo session in the web client

        Examples:
            >>> context_id = api.create_context(url="https://example.com", username="user@co.com")
            >>> launch_url = BrowsingAPI.create_ctx_url(context_id)
            >>> print(launch_url)
            https://a8silo.com/launch?ctx=abc123def456
        """
        if not ctx:
            raise ValidationError("Context ID cannot be empty")

        return f"{base_url.rstrip('/')}/launch?ctx={ctx}"

    @api_tag(MethodType.UTILITY)
    @staticmethod
    def defang_url(url: str) -> str:
        """Defang a URL by replacing certain characters.

        Makes a URL "safe" for sharing by replacing potentially dangerous
        characters that might cause accidental navigation.

        Args:
            url: URL to defang

        Returns:
            Defanged URL with replaced characters

        Examples:
            >>> defanged = BrowsingAPI.defang_url("https://malicious.com")
            >>> print(defanged)
            hxxps://malicious[.]com
        """
        if not url:
            return url

        return (
            url.replace("http://", "hxxp://")
            .replace("https://", "hxxps://")
            .replace(":", "[:]")
            .replace(".", "[.]")
        )

    @api_tag(MethodType.UTILITY)
    @staticmethod
    def refang_url(url: str) -> str:
        """Refang a URL by restoring certain characters.

        Restores a defanged URL back to its original form for actual use.

        Args:
            url: Defanged URL to refang

        Returns:
            Refanged URL with restored characters

        Examples:
            >>> refanged = BrowsingAPI.refang_url("hxxps://example[.]com")
            >>> print(refanged)
            https://example.com
        """
        if not url:
            return url

        return (
            url.replace("hxxp://", "http://")
            .replace("hxxps://", "https://")
            .replace("[.]", ".")
            .replace("[:]", ":")
        )

    @api_tag(MethodType.CONVENIENCE, wraps=["create_context"])
    def bulk_create_contexts(
        self,
        urls: list[str],
        username: str | None = None,
        policy: list[dict[str, Any]] | None = None,
        max_uses: int | None = None,
        expires: int | float | str | None = None,
        org: str | None = None,
        session_type: Literal["silo-ruby", "toolbox-standalone"] | None = None,
        egress_region: str | None = None,
        browser_profile: BrowserProfile | None = None,
        categories: Categories | None = None,
        validate_egress: bool | None = None,
    ) -> dict[str, list[str]]:
        """Create multiple browsing contexts for a list of URLs.

        Efficiently creates contexts for multiple URLs with the same user and
        policy settings. Failed context creations are logged but don't stop
        the process for other URLs.

        Args:
            urls: List of URLs to create contexts for
            username: Username associated with all contexts
            policy: List of policy dictionaries for all contexts
            max_uses: Maximum number of times each context can be used
            expires: Expiration time for all contexts (epoch seconds as a
                number, ``"+SECONDS"``, or ISO 8601; see :meth:`create_context`)
            org: Org slug for SAML-enabled organizations
            session_type: 'silo-ruby' or 'toolbox-standalone'
            egress_region: Egress location (e.g., 'New York, NY')
            browser_profile: Browser profile settings
            categories: Egress category settings
            validate_egress: As for :meth:`create_context`, but checked once for
                the whole batch before any context is created.

        Returns:
            Dictionary containing list of successfully created context URLs

        Raises:
            ValidationError: If parameters are invalid

        Examples:
            >>> urls = ["https://site1.com", "https://site2.com"]
            >>> policy = [{"type": "readonly", "params": ["true"]}]
            >>> result = api.bulk_create_contexts(urls, "user@company.com", policy)
            >>> print(f"Created {len(result['context_urls'])} contexts")

            >>> # With Silo for Research settings
            >>> result = api.bulk_create_contexts(
            ...     urls=urls,
            ...     username="researcher@company.com",
            ...     session_type="toolbox-standalone",
            ...     egress_region="London"
            ... )
        """
        if not isinstance(urls, list) or not urls:
            raise ValidationError("URLs must be a non-empty list")

        if not username and not org:
            raise ValidationError("Either username or org must be provided")

        if policy is not None and not isinstance(policy, list):
            raise ValidationError("Policy must be a list of dictionaries")

        _validate_session_type(session_type)
        _validate_legacy_egress(egress_region, categories)

        live = (
            self.live_egress_validation if validate_egress is None else validate_egress
        )
        if live:
            requested = self._requested_egress(None, egress_region, categories)
            if requested is not None:
                # Once for the batch: every context shares the egress.
                self._check_egress_live(requested, username, session_type)

        context_urls: list[str] = []

        self.logger.info("Creating contexts for %d URLs", len(urls))

        # The shared egress was validated above; don't repeat it (and its
        # warnings) for every context in the batch.
        batch_token = _BATCH_EGRESS_VALIDATED.set(True)
        try:
            self._create_batch(
                urls,
                context_urls,
                username=username,
                policy=policy,
                max_uses=max_uses,
                expires=expires,
                org=org,
                session_type=session_type,
                egress_region=egress_region,
                browser_profile=browser_profile,
                categories=categories,
            )
        finally:
            _BATCH_EGRESS_VALIDATED.reset(batch_token)

        self.logger.info(
            "Successfully created %d/%d contexts", len(context_urls), len(urls)
        )

        return {"context_urls": context_urls}

    def _create_batch(
        self,
        urls: list[str],
        context_urls: list[str],
        **context_kwargs: Any,
    ) -> None:
        """Create one context per URL, appending launch URLs; log and skip failures."""
        for i, url in enumerate(urls):
            try:
                # Refang URL in case it was defanged
                refanged_url = self.refang_url(url)

                # Create context with all parameters
                context_id = self.create_context(
                    url=refanged_url, validate_egress=False, **context_kwargs
                )

                # Generate launch URL
                launch_url = self.create_ctx_url(context_id)
                context_urls.append(launch_url)

                self.logger.debug("Created context %d/%d", i + 1, len(urls))

            except Exception as e:
                self.logger.error("Failed to create context for URL %s: %s", url, e)
                # Continue with other URLs
                continue

    @api_tag(MethodType.CONVENIENCE, wraps=["create_context"])
    def create_research_session(
        self,
        username: str,
        egress_region: str,
        url: str | None = None,
        browser_profile: BrowserProfile | None = None,
        categories: Categories | None = None,
        policy: list[dict[str, Any]] | None = None,
        max_uses: int | None = None,
        expires: int | float | str | None = None,
        auto_domain_allow: bool = False,
        validate_egress: bool | None = None,
    ) -> str:
        """Create a Silo for Research (toolbox-standalone) session.

        Convenience method for creating research sessions with egress routing
        and browser profile configuration.

        Args:
            username: Username for the session
            egress_region: Egress location (e.g., 'New York, NY', 'London').
                See ``get_egress_locations()`` for available options.
            url: Optional URL to open in the session
            browser_profile: Browser profile with 'os', 'browser', and optional
                'timezone'/'languages' settings.
                Options for os: 'win', 'mac', 'linux', 'android', 'ios'
                Options for browser: 'chrome', 'firefox', 'edge', 'safari', 'tor'
            categories: Egress category settings. Example:
                {"availability": "public", "connectivity": "datacenter"}
            policy: Optional policy list for the session
            max_uses: Maximum number of times the context can be used
            expires: Context expiration time (epoch seconds as a number,
                ``"+SECONDS"``, or ISO 8601; see :meth:`create_context`)
            validate_egress: Forwarded to :meth:`create_context`.

        Returns:
            Browse context ID that can be used to launch the session

        Raises:
            BrowsingAPIError: If session creation fails
            ValidationError: If parameters are invalid

        Examples:
            >>> context_id = api.create_research_session(
            ...     username="researcher@company.com",
            ...     egress_region="New York, NY",
            ...     url="https://example.com",
            ...     browser_profile={"os": "win", "browser": "chrome"},
            ...     categories={"availability": "public", "connectivity": "isp"}
            ... )
            >>> launch_url = api.create_ctx_url(context_id)
        """
        return self.create_context(
            url=url,
            username=username,
            policy=policy,
            max_uses=max_uses,
            expires=expires,
            session_type="toolbox-standalone",
            egress_region=egress_region,
            browser_profile=browser_profile,
            categories=categories,
            auto_domain_allow=auto_domain_allow,
            validate_egress=validate_egress,
        )

    @api_tag(MethodType.UTILITY)
    @staticmethod
    def get_egress_locations(
        include_details: bool = False,
    ) -> dict[str, Any]:
        """Get available egress locations by region.

        Args:
            include_details: When ``False`` (default), returns a dict mapping
                region names to lists of location name strings — backward-compatible
                with prior behavior. When ``True``, each location is a dict with
                ``name``, ``connectivity``, ``availability``, and ``protocol`` keys.

        Returns:
            When ``include_details=False``:
                ``{region: [city_name, ...]}``

            When ``include_details=True``:
                ``{region: [{"name": city, "connectivity": [...],
                "availability": [...], "protocol": [...]}]}``

            Cities absent from the canonical location data (see
            ``silo_sdk.harvesting.egress_validation.get_egress_locations_with_details()``)
            are omitted from the enriched output entirely, rather than
            appearing with empty detail lists.

        Examples:
            >>> locations = BrowsingAPI.get_egress_locations()
            >>> print(locations["North America"])
            ['Toronto', 'Vancouver', 'Mexico City', ...]

            >>> details = BrowsingAPI.get_egress_locations(include_details=True)
            >>> sao_paulo = next(
            ...     e for e in details["Central & South America"]
            ...     if e["name"] == "Sao Paulo"
            ... )
            >>> print("datacenter" in sao_paulo["connectivity"])
            True
            >>> sydney = next(
            ...     e for e in details["Asia-Pacific"] if e["name"] == "Sydney"
            ... )
            >>> print("tor" in sydney["protocol"])
            True
        """
        if not include_details:
            details = get_egress_locations_with_details()
            return {
                region: [e["name"] for e in entries]
                for region, entries in details.items()
            }

        return get_egress_locations_with_details()

    @api_tag(MethodType.API_COMMAND, api_command="egresses")
    def list_egresses(
        self,
        username: str | None = None,
        *,
        user_id: str | int | None = None,
        org_id: str | int | None = None,
        org_name: str | None = None,
        session_type: str | None = None,
        service_type: str | None = None,
    ) -> list[EgressDirectoryEntry]:
        """Ask the platform which egress locations are actually available.

        The live counterpart to :meth:`get_egress_locations`, which reads a
        table compiled into the SDK. Prefer this one when the answer matters.
        The static table lists every location the platform has; this reports
        the subset a given org or user can really select right now, after the
        server applies entitlements, the org's Launcher Options policy, and
        an up/down check. Keep the static table for offline use, tests, and
        fast validation.

        Args:
            username: The user to report for. Give exactly one selector.
            user_id: Numeric user ID, as an alternative to ``username``.
            org_id: Numeric org ID, to report for a whole organization.
            org_name: Organization name (sent as ``orgname``), as an
                alternative to ``org_id``. A name that appears more than
                once in the hierarchy is ambiguous and the platform rejects
                it with ``400``; use ``org_id`` for those.
            session_type: What the egress will be used for. ``"silo-ruby"``
                (the server's default) restricts the answer to locations a
                browsing context can pin; ``"toolbox-standalone"`` does not.
                Leave unset unless you specifically need the wider list.
            service_type: Which server pool to report. ``"egress"`` (the
                server's default) is the pool browsing contexts and
                ``visual``/``video``/``single`` harvest tasks draw from;
                ``"harvest-asset"`` is the separate pool for ``asset`` and
                ``wget`` tasks. For a harvest task, prefer
                :meth:`HarvesterAPI.list_harvest_egresses`, which picks the
                pool, session type and org for you.

        Returns:
            One :class:`~silo_sdk.base.types.EgressDirectoryEntry` per
            location, each with its ``name``, its ``path`` through the
            location hierarchy, and the ``categories`` combinations it
            offers. Sorted by path, then name.

            The directory returns **every hierarchy node** -- the ``World``
            root, regions, countries and cities -- not just leaf cities. A
            parent node carries the union of its children's categories, and
            ``path[-1] == name``. Filter to leaves (nodes that are nobody's
            parent) when you want concrete locations.

        Raises:
            BrowsingAPIError: If the request fails.
            ValidationError: If the selectors, ``session_type`` or
                ``service_type`` are invalid.

        Note:
            **An empty list is a real answer, not an error.** It means no
            egress can be pinned — most often because the org runs Traffic
            Manager rules, which choose the egress themselves, but also when
            the org's policy has disabled every provisioned region or none is
            currently up. Treat it as "let the platform decide", not as a
            failed lookup.

            An org selector reports the egress provisioned to that org, not
            to orgs beneath it, so a top-level org whose egress sits on its
            sub-orgs also returns an empty list. To see what a user can
            select, pass ``username`` or ``user_id``; the platform answers
            for that user's own org.

        Note:
            This is a plain REST endpoint rather than a command-array call,
            so it behaves differently in two ways. Failures arrive as real
            HTTP status codes instead of an ``error`` element inside a
            ``200``, and the token travels in an ``Authorization: Bearer``
            header instead of the usual command-array ``setauth``. It needs
            an ``ADMIN_TOKEN``; a sync token is refused with ``403``, and so
            is an admin grant that does not cover users when you select by
            ``username`` or ``user_id``.

        Examples:
            >>> egresses = api.list_egresses("user@company.com")
            >>> print(egresses[0]["name"])
            'Amsterdam'

            Keep only leaf locations (nodes that are not the parent of any
            other node). ``path`` runs from broadest to narrowest and
            ``path[-1] == name``:

            >>> parents = {
            ...     e["path"][-2] for e in egresses if len(e.get("path", [])) > 1
            ... }
            >>> leaves = [e for e in egresses if e["name"] not in parents]

            Group the leaves by region; guard against short paths, since the
            ``World`` root has only one element:

            >>> by_region: dict[str, list[str]] = {}
            >>> for e in leaves:
            ...     region = e["path"][1] if len(e["path"]) > 1 else "World"
            ...     by_region.setdefault(region, []).append(e["name"])

            Find the leaf locations that offer a Tor exit (a parent would
            match too, since it carries its children's categories):

            >>> tor = [
            ...     e["name"] for e in leaves
            ...     if any(c.get("protocol") == "tor" for c in e["categories"])
            ... ]

            Confirm a location before pinning it on a context:

            >>> available = {e["name"] for e in api.list_egresses("u@x.com")}
            >>> if "Singapore" in available:
            ...     api.create_context(
            ...         url="https://example.com",
            ...         username="u@x.com",
            ...         egress_info={"name": "Singapore"},
            ...     )
        """
        selectors = {
            "username": username,
            "user_id": user_id,
            "org_id": org_id,
            "orgname": org_name,
        }
        named = {k: v for k, v in selectors.items() if v is not None and v != ""}

        if len(named) != 1:
            # The server enforces this too, as a 400. Checking locally keeps a
            # typo from costing a round trip, and names the parameters the way
            # the caller wrote them.
            raise ValidationError(
                "list_egresses needs exactly one of username, user_id, "
                f"org_id or org_name; got {len(named)}."
            )

        params: dict[str, Any] = dict(named)

        if session_type is not None:
            _validate_session_type(session_type)
            params["session_type"] = session_type

        if service_type is not None:
            if service_type not in EGRESS_SERVICE_TYPES:
                # The platform answers an unknown pool with [], which is
                # indistinguishable from "Traffic Manager chooses".
                raise ValidationError(
                    f"Invalid service_type: {service_type!r}. Expected one of "
                    f"{sorted(EGRESS_SERVICE_TYPES)}."
                )
            params["service_type"] = service_type

        try:
            self.logger.debug("Listing egresses for %s", next(iter(named)))
            response = self._make_api_request(
                "GET",
                "egresses/",
                "",
                params=params,
                headers={"Authorization": f"Bearer {self.auth_token}"},
            )
        except Exception as e:
            if isinstance(e, BrowsingAPIError):
                raise
            # Unlike the command-array path, this endpoint reports failures as
            # real HTTP status codes and _handle_response parses the body into
            # SiloError.response_data. Re-raising with only str(e) would drop
            # the actionable half — the server's "pass org_id" remedy never
            # reaches the caller. Carry the detail and the fields through.
            if isinstance(e, SiloError):
                detail = e.server_message
                raise BrowsingAPIError(
                    f"Failed to list egresses: {detail or e}",
                    status_code=e.status_code,
                    response_data=e.response_data,
                    request_id=e.request_id,
                ) from e
            raise BrowsingAPIError(f"Failed to list egresses: {e}") from e

        # _handle_response wraps a non-list JSON body in a list, so a dict
        # body would arrive here as a one-element list. Reject anything whose
        # elements are not the location objects this endpoint documents.
        if not all(isinstance(e, dict) and "name" in e for e in response):
            raise BrowsingAPIError(f"Unexpected egress directory response: {response}")

        self.logger.info("Server reports %d egress locations", len(response))
        return cast("list[EgressDirectoryEntry]", response)

__init__

__init__(config: dict[str, Any]) -> None

Initialize the browsing API client.

Parameters:

Name Type Description Default
config dict[str, Any]

Configuration dictionary containing API settings

required

Raises:

Type Description
ConfigurationError

If required configuration is missing

Source code in silo_sdk/browsing/isolation_api.py
def __init__(self, config: dict[str, Any]) -> None:
    """Initialize the browsing API client.

    Args:
        config: Configuration dictionary containing API settings

    Raises:
        ConfigurationError: If required configuration is missing
    """
    super().__init__(config)

    # Validate required configuration
    validate_config_for_api(config, ["ADMIN_TOKEN"])

    self.auth_token = config["ADMIN_TOKEN"]
    # Off by default: it costs a list_egresses round trip per context
    # created. The MCP server turns it on (MCP_EGRESS_VALIDATION).
    self.live_egress_validation = _config_flag(
        config.get("LIVE_EGRESS_VALIDATION", False)
    )
    self.logger.info("Initialized BrowsingAPI client")

create_context

create_context(url: str | None = None, username: str | None = None, policy: list[dict[str, Any]] | None = None, max_uses: int | None = None, expires: int | float | str | None = None, restrict_client_ips: list[str] | None = None, org: str | None = None, session_type: Literal['silo-ruby', 'toolbox-standalone'] | None = None, egress_region: str | None = None, browser_profile: BrowserProfile | None = None, categories: Categories | None = None, auto_domain_allow: bool = False, egress_info: EgressInfo | None = None, validate_egress: bool | None = None) -> str

Create a new browsing context.

Creates a secure browsing context that can be used to launch isolated browsing sessions with the specified URL and policies.

Parameters:

Name Type Description Default
url str | None

Target URL for the context (optional for toolbox-standalone). Sent as "urls": [url] (array) in the wire format. The domain is automatically extracted and added as a domain_allow policy entry to the provided policy list.

None
username str | None

Username associated with the context. Either username or org must be provided (but not both). Sent as "user" in the wire format (field name differs from this param).

None
policy list[dict[str, Any]] | None

List of policy dictionaries, each with "type" and "params" keys. See class-level Attributes for available policy types and valid param values.

Seamless UI constraint: {"type": "browser_chrome", "params": ["seamless"]} is only effective for non-catchall users. Catchall users — via a catchall account, an org configured to treat all users as catchall, or partner SSO — are always forced to "minimal" (Ribbon Mode) regardless of this policy setting.

None
max_uses int | None

Maximum number of times the context can be used. Sent at the command level (not inside context_data).

None
expires int | float | str | None

Context expiration: epoch seconds as a number, "+SECONDS" (relative), or an ISO 8601 string. An all-digit string such as "1792253988" is converted to an int before sending, because the server parses strings as ISO 8601 and would reject it. Sent at the command level (not inside context_data), same as max_uses.

None
restrict_client_ips list[str] | None

List of IP addresses/CIDRs to restrict access. Sent as "restrict_ips" in the wire format (field name differs from this param).

None
org str | None

Org slug/vanity URL for SAML-enabled organizations. Either username or org must be provided (but not both).

None
session_type Literal['silo-ruby', 'toolbox-standalone'] | None

Session type — "silo-ruby" (default, Safe Access) or "toolbox-standalone" (Silo for Research).

None
egress_region str | None

Egress location name from the managed attribution network. Accepts a specific city (e.g., "New York, NY"), a country ("United States"), a region ("North America"), or "World" for random assignment. The backend resolves via hierarchy_tag lookup. See silo_sdk.harvesting.egress_validation.VALID_EGRESS_NAMES for the complete list. A name missing from that list logs a warning and is still sent — the list is compiled into the SDK and can lag the platform, so the platform has the final say.

Important — mixed licensing: Even if a location passes SDK validation, the user may receive an egress error when the browsing context is launched if their license does not include rights to that specific location. SDK validation confirms the location name is valid for the platform's shared network, but per-user license entitlements are enforced at session launch time, not at context creation.

None
browser_profile BrowserProfile | None

Browser profile dict for user-agent selection. Keys: "os", "browser", and optionally "timezone" (IANA name) and "languages" (Accept-Language string).

None
categories Categories | None

Egress category settings with "availability", "connectivity", and "protocol" keys. "connectivity" and "protocol" are validated against what is actually available at egress_region (or any location, if egress_region is omitted) — see get_egress_locations() for per-location details.

None
auto_domain_allow bool

If True, automatically append a domain_allow policy entry for the URL's domain when url is provided. Defaults to False.

Leave this False (the default) if you want to construct your own domain_allow policy entry — for example, to allow multiple domains in a single entry::

policy=[{
    "type": "domain_allow",
    "params": ["google.com", "yahoo.com"]
}]

When auto_domain_allow=True, only the domain extracted from url is injected. It cannot be used to allow additional domains beyond the target URL's domain.

False
egress_info EgressInfo | None

Egress selection as a single object, with "name" and optional "server_set" and "categories" keys. This is the newer form and the only way to request a server_set.

Mutually exclusive with egress_region and categories — pass either this or those, never both. The platform rejects the mixture, and so does this method, so the error arrives before the round trip rather than after it.

None
validate_egress bool | None

Check the requested egress against the platform's live directory for username (:meth:list_egresses) before creating the context, and raise :class:ValidationError if it is not offered. None (default) uses the LIVE_EGRESS_VALIDATION config key. Skipped, with a warning, when there is no username (an org-level directory is not authoritative for its users) or the directory cannot be fetched; an empty directory means the platform chooses the egress and is never refused.

None
Note

Wire format parameter mappings:

  • Python username → wire "user" (inside context_data)
  • Python url (string) → wire "urls" (list, inside context_data)
  • max_uses and expires go at the command level (alongside "command", not inside context_data)
  • domain_allow is only added when auto_domain_allow=True

Wire format structure::

{
    "command": "create_context",
    "max_uses": 5,       # ← command level
    "expires": "2026-12-31T23:59:59Z",  # ← command level (or epoch int)
    "context_data": {
        "user": "user@company.com",  # ← username → "user"
        "urls": ["https://example.com"],  # ← url → "urls" (list)
        "policy": [...]
    }
}

Returns:

Type Description
str

Browse context ID (browse_context_id) that can be used to launch

str

sessions. Pass this to create_ctx_url() to get a launch URL, or

str

use the GET /ctx/ shorthand endpoint directly (see Note).

Raises:

Type Description
BrowsingAPIError

If context creation fails

ValidationError

If parameters are invalid

EgressNotOfferedError

A ValidationError subclass, when live egress validation is on and the directory does not offer the requested egress

Note

GET /ctx shorthand: As an alternative to the two-step create → launch flow, the /ctx/ endpoint at https://extapi.authentic8.com/ctx/ creates and launches a context in a single GET request using inline query parameters::

GET https://extapi.authentic8.com/ctx/
    ?auth=<admin_token>
    &user=<username>
    &url=<target_url>
    &response=url

The response parameter controls the return format:

  • url (default) — returns the launch URL as plain text (useful for automation)
  • redirect — HTTP redirect directly into the Silo session
  • id — returns just the context launch ID as plain text

This shorthand does not go through the /api/ command-array format.

Examples:

>>> # Basic isolation context
>>> policy = [
...     {"type": "file_transfer", "params": ["block_all"]},
...     {"type": "clipboard", "params": ["allow_to_local"]},
... ]
>>> context_id = api.create_context(
...     url="https://example.com",
...     username="user@company.com",
...     policy=policy,
...     max_uses=5
... )
>>> # Silo for Research session with egress
>>> context_id = api.create_context(
...     url="https://example.com",
...     username="researcher@company.com",
...     session_type="toolbox-standalone",
...     egress_region="New York, NY",
...     browser_profile={"os": "win", "browser": "chrome"},
...     categories={"availability": "public", "connectivity": "datacenter"}
... )
>>> # Same egress selection via the egress_info object, which also
>>> # allows a server_set. Do not combine it with egress_region.
>>> context_id = api.create_context(
...     url="https://example.com",
...     username="researcher@company.com",
...     session_type="toolbox-standalone",
...     egress_info={
...         "name": "New York, NY",
...         "server_set": "dedicated-pool-a",
...         "categories": {
...             "availability": "public",
...             "connectivity": "datacenter",
...         },
...     },
... )
Source code in silo_sdk/browsing/isolation_api.py
@api_tag(MethodType.API_COMMAND, api_command="create_context")
def create_context(
    self,
    url: str | None = None,
    username: str | None = None,
    policy: list[dict[str, Any]] | None = None,
    max_uses: int | None = None,
    expires: int | float | str | None = None,
    restrict_client_ips: list[str] | None = None,
    org: str | None = None,
    session_type: Literal["silo-ruby", "toolbox-standalone"] | None = None,
    egress_region: str | None = None,
    browser_profile: BrowserProfile | None = None,
    categories: Categories | None = None,
    auto_domain_allow: bool = False,
    egress_info: EgressInfo | None = None,
    validate_egress: bool | None = None,
) -> str:
    """Create a new browsing context.

    Creates a secure browsing context that can be used to launch isolated
    browsing sessions with the specified URL and policies.

    Args:
        url: Target URL for the context (optional for toolbox-standalone).
            Sent as ``"urls": [url]`` (array) in the wire format. The domain
            is automatically extracted and added as a ``domain_allow`` policy
            entry to the provided policy list.
        username: Username associated with the context.
            Either username or org must be provided (but not both). Sent as
            ``"user"`` in the wire format (field name differs from this param).
        policy: List of policy dictionaries, each with ``"type"`` and
            ``"params"`` keys. See class-level ``Attributes`` for available
            policy types and valid param values.

            **Seamless UI constraint:** ``{"type": "browser_chrome",
            "params": ["seamless"]}`` is only effective for
            **non-catchall users**. Catchall users — via a catchall
            account, an org configured to treat all users as catchall, or
            partner SSO — are always forced to ``"minimal"`` (Ribbon Mode)
            regardless of this policy setting.
        max_uses: Maximum number of times the context can be used.
            Sent at the **command level** (not inside ``context_data``).
        expires: Context expiration: epoch seconds as a **number**,
            ``"+SECONDS"`` (relative), or an ISO 8601 string. An all-digit
            string such as ``"1792253988"`` is converted to an int before
            sending, because the server parses strings as ISO 8601 and
            would reject it. Sent at the **command level** (not inside ``context_data``),
            same as ``max_uses``.
        restrict_client_ips: List of IP addresses/CIDRs to restrict access.
            Sent as ``"restrict_ips"`` in the wire format (field name differs
            from this param).
        org: Org slug/vanity URL for SAML-enabled organizations.
            Either username or org must be provided (but not both).
        session_type: Session type — ``"silo-ruby"`` (default, Safe Access)
            or ``"toolbox-standalone"`` (Silo for Research).
        egress_region: Egress location name from the managed attribution
            network. Accepts a specific city (e.g., ``"New York, NY"``),
            a country (``"United States"``), a region (``"North America"``),
            or ``"World"`` for random assignment. The backend resolves
            via ``hierarchy_tag`` lookup. See
            ``silo_sdk.harvesting.egress_validation.VALID_EGRESS_NAMES``
            for the complete list. A name missing from that list logs a
            warning and is still sent — the list is compiled into the SDK
            and can lag the platform, so the platform has the final say.

            **Important — mixed licensing:** Even if a location passes SDK
            validation, the user may receive an egress error when the browsing
            context is launched if their license does not include rights to that
            specific location. SDK validation confirms the location name is valid
            for the platform's shared network, but per-user license entitlements
            are enforced at session launch time, not at context creation.
        browser_profile: Browser profile dict for user-agent selection.
            Keys: ``"os"``, ``"browser"``, and optionally ``"timezone"``
            (IANA name) and ``"languages"`` (Accept-Language string).
        categories: Egress category settings with ``"availability"``,
            ``"connectivity"``, and ``"protocol"`` keys. ``"connectivity"``
            and ``"protocol"`` are validated against what is actually
            available at ``egress_region`` (or any location, if
            ``egress_region`` is omitted) — see
            ``get_egress_locations()`` for per-location details.
        auto_domain_allow: If ``True``, automatically append a
            ``domain_allow`` policy entry for the URL's domain when
            ``url`` is provided. Defaults to ``False``.

            Leave this ``False`` (the default) if you want to construct
            your own ``domain_allow`` policy entry — for example, to
            allow multiple domains in a single entry::

                policy=[{
                    "type": "domain_allow",
                    "params": ["google.com", "yahoo.com"]
                }]

            When ``auto_domain_allow=True``, only the domain extracted
            from ``url`` is injected. It cannot be used to allow
            additional domains beyond the target URL's domain.
        egress_info: Egress selection as a single object, with ``"name"``
            and optional ``"server_set"`` and ``"categories"`` keys. This
            is the newer form and the only way to request a
            ``server_set``.

            **Mutually exclusive with** ``egress_region`` and
            ``categories`` — pass either this or those, never both. The
            platform rejects the mixture, and so does this method, so the
            error arrives before the round trip rather than after it.
        validate_egress: Check the requested egress against the
            platform's live directory for ``username``
            (:meth:`list_egresses`) before creating the context, and
            raise :class:`ValidationError` if it is not offered. ``None``
            (default) uses the ``LIVE_EGRESS_VALIDATION`` config key.
            Skipped, with a warning, when there is no ``username`` (an
            org-level directory is not authoritative for its users) or
            the directory cannot be fetched; an empty directory means the
            platform chooses the egress and is never refused.

    Note:
        Wire format parameter mappings:

        - Python ``username`` → wire ``"user"``
          (inside ``context_data``)
        - Python ``url`` (string) → wire ``"urls"`` (list,
          inside ``context_data``)
        - ``max_uses`` and ``expires`` go at the **command level**
          (alongside ``"command"``, not inside ``context_data``)
        - ``domain_allow`` is only added when ``auto_domain_allow=True``

        Wire format structure::

            {
                "command": "create_context",
                "max_uses": 5,       # ← command level
                "expires": "2026-12-31T23:59:59Z",  # ← command level (or epoch int)
                "context_data": {
                    "user": "user@company.com",  # ← username → "user"
                    "urls": ["https://example.com"],  # ← url → "urls" (list)
                    "policy": [...]
                }
            }

    Returns:
        Browse context ID (``browse_context_id``) that can be used to launch
        sessions. Pass this to ``create_ctx_url()`` to get a launch URL, or
        use the GET ``/ctx/`` shorthand endpoint directly (see Note).

    Raises:
        BrowsingAPIError: If context creation fails
        ValidationError: If parameters are invalid
        EgressNotOfferedError: A ``ValidationError`` subclass, when live
            egress validation is on and the directory does not offer the
            requested egress

    Note:
        **GET /ctx shorthand:** As an alternative to the two-step
        create → launch flow, the ``/ctx/`` endpoint at
        ``https://extapi.authentic8.com/ctx/`` creates and launches a context
        in a single GET request using inline query parameters::

            GET https://extapi.authentic8.com/ctx/
                ?auth=<admin_token>
                &user=<username>
                &url=<target_url>
                &response=url

        The ``response`` parameter controls the return format:

        - ``url`` (default) — returns the launch URL as plain text (useful for automation)
        - ``redirect`` — HTTP redirect directly into the Silo session
        - ``id`` — returns just the context launch ID as plain text

        This shorthand does **not** go through the ``/api/`` command-array format.

    Examples:
        >>> # Basic isolation context
        >>> policy = [
        ...     {"type": "file_transfer", "params": ["block_all"]},
        ...     {"type": "clipboard", "params": ["allow_to_local"]},
        ... ]
        >>> context_id = api.create_context(
        ...     url="https://example.com",
        ...     username="user@company.com",
        ...     policy=policy,
        ...     max_uses=5
        ... )

        >>> # Silo for Research session with egress
        >>> context_id = api.create_context(
        ...     url="https://example.com",
        ...     username="researcher@company.com",
        ...     session_type="toolbox-standalone",
        ...     egress_region="New York, NY",
        ...     browser_profile={"os": "win", "browser": "chrome"},
        ...     categories={"availability": "public", "connectivity": "datacenter"}
        ... )

        >>> # Same egress selection via the egress_info object, which also
        >>> # allows a server_set. Do not combine it with egress_region.
        >>> context_id = api.create_context(
        ...     url="https://example.com",
        ...     username="researcher@company.com",
        ...     session_type="toolbox-standalone",
        ...     egress_info={
        ...         "name": "New York, NY",
        ...         "server_set": "dedicated-pool-a",
        ...         "categories": {
        ...             "availability": "public",
        ...             "connectivity": "datacenter",
        ...         },
        ...     },
        ... )
    """
    # Validate user/org - exactly one must be provided
    if not username and not org:
        raise ValidationError("Either username or org must be provided")
    if username and org:
        raise ValidationError("Only one of username or org should be provided")

    if username and not isinstance(username, str):
        raise ValidationError("Username must be a non-empty string")

    if org and not isinstance(org, str):
        raise ValidationError("Org must be a non-empty string")

    # Initialize policy if not provided
    if policy is None:
        policy = []
    elif not isinstance(policy, list):
        raise ValidationError("Policy must be a list of dictionaries")

    # Build context data
    context_data: dict[str, Any] = {}

    # Add user or org
    if username:
        context_data["user"] = username
    if org:
        context_data["org"] = org

    # Add URL(s) if provided
    if url:
        if not isinstance(url, str):
            raise ValidationError("URL must be a non-empty string")
        try:
            parsed_url = urlparse(url)
            if not parsed_url.netloc:
                raise ValidationError(f"Invalid URL format: {url}")
            if auto_domain_allow:
                policy = policy + [
                    {"type": "domain_allow", "params": [parsed_url.netloc]}
                ]
        except ValidationError:
            # Don't let the generic handler below re-wrap our own clean
            # ValidationError message (e.g. "Invalid URL format: ...")
            # into a confusing "Failed to parse URL: Invalid URL format:
            # ..." double-wrap.
            raise
        except Exception as e:
            raise ValidationError(f"Failed to parse URL: {e}") from e
        context_data["urls"] = [url]

    # Add policy if not empty
    if policy:
        context_data["policy"] = policy

    # Add session type for Silo for Research
    _validate_session_type(session_type)
    if session_type:
        context_data["session_type"] = session_type

    # Validate the legacy egress parameters (see _validate_legacy_egress).
    _validate_legacy_egress(egress_region, categories)
    if egress_region:
        context_data["egress_region"] = egress_region

    # Add browser profile
    if browser_profile:
        context_data["browser_profile"] = browser_profile

    if categories:
        context_data["categories"] = categories

    # egress_info supersedes the separate egress_region/categories params
    # and cannot be mixed with them. The platform returns
    # "cannot combine 'egress_info' with legacy egress fields: ..." for
    # the mixture; catching it here names the same conflict without
    # spending a round trip, and reaches callers who never see the
    # response body.
    if egress_info is not None:
        conflicting = [
            name
            for name, value in (
                ("egress_region", egress_region),
                ("categories", categories),
            )
            if value
        ]
        if conflicting:
            raise ValidationError(
                f"cannot combine 'egress_info' with legacy egress fields: "
                f"{', '.join(conflicting)}. Move them into egress_info "
                f"instead — 'egress_region' becomes its 'name'."
            )
        validate_egress_info(egress_info)
        context_data["egress_info"] = egress_info

    live = (
        self.live_egress_validation if validate_egress is None else validate_egress
    )
    if live:
        requested = self._requested_egress(egress_info, egress_region, categories)
        if requested is not None:
            self._check_egress_live(requested, username, session_type)

    # Add optional parameters
    if restrict_client_ips is not None:
        if not isinstance(restrict_client_ips, list):
            raise ValidationError("restrict_client_ips must be a list")
        context_data["restrict_ips"] = restrict_client_ips

    # Build create_context command
    create_cmd: dict[str, Any] = {
        "command": "create_context",
        "context_data": context_data,
    }

    # Add max_uses to command (not context_data per API spec)
    if max_uses is not None:
        if not isinstance(max_uses, int) or max_uses <= 0:
            raise ValidationError("max_uses must be a positive integer")
        create_cmd["max_uses"] = max_uses

    # Add expires at command level (not inside context_data, same as max_uses)
    if expires is not None:
        create_cmd["expires"] = _normalize_expires(expires)

    # Prepare API request
    payload = [create_cmd]

    try:
        self.logger.debug("Creating browsing context for URL: %s", url)
        response = self._make_api_request("POST", "api/", self.auth_token, payload)

        # _extract_api_result raises with the server's own message for
        # both error shapes, {"error": ...} and {"result": {"error": ...}}.
        result = self._extract_api_result(response)
        browse_context_id: str | None = (
            result.get("browse_context_id") if isinstance(result, dict) else None
        )
        if browse_context_id:
            self.logger.info("Created context with ID: %s", browse_context_id)
            return browse_context_id

        raise BrowsingAPIError(
            f"Failed to retrieve context ID from response: {response}"
        )

    except Exception as e:
        if isinstance(e, BrowsingAPIError):
            raise
        if isinstance(e, SiloError):
            raise BrowsingAPIError(
                f"Failed to create context: {e}",
                status_code=e.status_code,
                response_data=e.response_data,
                request_id=e.request_id,
            ) from e
        raise BrowsingAPIError(f"Failed to create context: {e}") from e

get_context

get_context(browse_context_id: str) -> dict[str, Any]

Retrieve details of a browsing context.

Gets detailed information about an existing browsing context including creation time, usage count, policies, and expiration details.

Parameters:

Name Type Description Default
browse_context_id str

ID of the browsing context

required

Returns:

Type Description
dict[str, Any]

Dictionary containing context details:

dict[str, Any]
  • browse_context_id: The context ID
dict[str, Any]
  • name: Context name
dict[str, Any]
  • user_id: Associated user ID
dict[str, Any]
  • org_id / launch_org_id: Owning and launching org
dict[str, Any]
  • use_count: Number of times the context has been used
dict[str, Any]
  • max_uses: Maximum allowed uses
dict[str, Any]
  • create_ts: Creation timestamp
dict[str, Any]
  • expires: Expiration timestamp
dict[str, Any]
  • last_use: Timestamp of the most recent use
dict[str, Any]
  • enabled: Whether the context is currently usable
dict[str, Any]
  • commonality: Context sharing scope
dict[str, Any]
  • context_data: The context's configuration, as supplied to :meth:create_context
dict[str, Any]

**Three names in an earlier version of this list were never

dict[str, Any]

sent** -- created_ts (the field is create_ts),

dict[str, Any]

expires_ts (it is expires) and policy (the

dict[str, Any]

configuration comes back under context_data).

Raises:

Type Description
BrowsingAPIError

If context retrieval fails

ValidationError

If browse_context_id is invalid

Examples:

>>> context_info = api.get_context("0123456789abcdef0123456789abcdef")
>>> print(f"Context used {context_info['use_count']} times")
Source code in silo_sdk/browsing/isolation_api.py
@api_tag(MethodType.API_COMMAND, api_command="get_context")
def get_context(self, browse_context_id: str) -> dict[str, Any]:
    """Retrieve details of a browsing context.

    Gets detailed information about an existing browsing context including
    creation time, usage count, policies, and expiration details.

    Args:
        browse_context_id: ID of the browsing context

    Returns:
        Dictionary containing context details:

        - ``browse_context_id``: The context ID
        - ``name``: Context name
        - ``user_id``: Associated user ID
        - ``org_id`` / ``launch_org_id``: Owning and launching org
        - ``use_count``: Number of times the context has been used
        - ``max_uses``: Maximum allowed uses
        - ``create_ts``: Creation timestamp
        - ``expires``: Expiration timestamp
        - ``last_use``: Timestamp of the most recent use
        - ``enabled``: Whether the context is currently usable
        - ``commonality``: Context sharing scope
        - ``context_data``: The context's configuration, as supplied to
            :meth:`create_context`

        **Three names in an earlier version of this list were never
        sent** -- ``created_ts`` (the field is ``create_ts``),
        ``expires_ts`` (it is ``expires``) and ``policy`` (the
        configuration comes back under ``context_data``).

    Raises:
        BrowsingAPIError: If context retrieval fails
        ValidationError: If browse_context_id is invalid

    Examples:
        >>> context_info = api.get_context("0123456789abcdef0123456789abcdef")
        >>> print(f"Context used {context_info['use_count']} times")
    """
    if not browse_context_id or not isinstance(browse_context_id, str):
        raise ValidationError("browse_context_id must be a non-empty string")

    payload = [{"command": "get_context", "browse_context_id": browse_context_id}]

    try:
        self.logger.debug("Retrieving context: %s", browse_context_id)
        response = self._make_api_request("POST", "api/", self.auth_token, payload)

        # _extract_api_result raises with the server's own message for
        # both error shapes — a deleted context ID comes back as
        # {"result": {"error": ...}}, which used to surface only as
        # "No context data found".
        result = self._extract_api_result(response)
        if isinstance(result, dict) and "browse_context_id" in result:
            self.logger.debug("Retrieved context details")
            return cast(dict[str, Any], result)

        raise BrowsingAPIError(
            f"No context data found in response for ID: {browse_context_id}"
        )

    except Exception as e:
        if isinstance(e, BrowsingAPIError):
            raise
        if isinstance(e, SiloError):
            raise BrowsingAPIError(
                f"Failed to retrieve context: {e}",
                status_code=e.status_code,
                response_data=e.response_data,
                request_id=e.request_id,
            ) from e
        raise BrowsingAPIError(f"Failed to retrieve context: {e}") from e

delete_context

delete_context(browse_context_id: str) -> bool

Delete a browsing context.

Permanently deletes a browsing context, making it unusable for future sessions. This action cannot be undone.

Parameters:

Name Type Description Default
browse_context_id str

ID of the browsing context to delete

required

Returns:

Type Description
bool

True if deletion was successful, False otherwise

Raises:

Type Description
BrowsingAPIError

If context deletion fails

ValidationError

If browse_context_id is invalid

Examples:

>>> success = api.delete_context("0123456789abcdef0123456789abcdef")
>>> if success:
...     print("Context deleted successfully")
Source code in silo_sdk/browsing/isolation_api.py
@api_tag(MethodType.API_COMMAND, api_command="delete_context")
def delete_context(self, browse_context_id: str) -> bool:
    """Delete a browsing context.

    Permanently deletes a browsing context, making it unusable for future
    sessions. This action cannot be undone.

    Args:
        browse_context_id: ID of the browsing context to delete

    Returns:
        True if deletion was successful, False otherwise

    Raises:
        BrowsingAPIError: If context deletion fails
        ValidationError: If browse_context_id is invalid

    Examples:
        >>> success = api.delete_context("0123456789abcdef0123456789abcdef")
        >>> if success:
        ...     print("Context deleted successfully")
    """
    if not browse_context_id or not isinstance(browse_context_id, str):
        raise ValidationError("browse_context_id must be a non-empty string")

    payload = [
        {"command": "delete_context", "browse_context_id": browse_context_id}
    ]

    try:
        self.logger.debug("Deleting context: %s", browse_context_id)
        response = self._make_api_request("POST", "api/", self.auth_token, payload)

        result = self._extract_api_result(response)
        if isinstance(result, dict) and result.get("deleted") in (1, True):
            self.logger.info("Successfully deleted context: %s", browse_context_id)
            return True

        self.logger.warning(
            "Unexpected response format when deleting context %s: %s",
            browse_context_id,
            result,
        )
        return False

    except Exception as e:
        if isinstance(e, BrowsingAPIError):
            raise
        raise BrowsingAPIError(f"Failed to delete context: {e}") from e

update_context

update_context(browse_context_id: str, context_data: dict[str, Any] | None = None, max_uses: int | None = None, expires: int | float | str | None = None, name: str | None = None, enabled: bool | None = None) -> dict[str, Any]

Update an existing browsing context.

Modifies an existing context. The top-level fields (name, enabled, max_uses, expires) are independent: omitted ones are left unchanged. context_data is different: it replaces the stored object entirely.

Warning

Send the complete context_data (fetch it with :meth:get_context, change what you need, send it all back). Fields omitted are removed -- e.g. an update carrying only urls drops restrict_ips (the IP lock) and egress_region. The server then re-applies create defaults: session_type becomes "silo-ruby" if missing, and a toolbox-standalone context without an egress region falls back to the org root.

Warning

Unlike create, the server skips egress-provisioning and dynamic-policy checks on update. An update can store an egress the org cannot use (the context then fails at launch), and a domain_allow set through update gets no automatic domain_block * entry. This method does not validate either.

Note

A nonexistent or deleted browse_context_id is not reported as an error: the server answers {"result": 0} and this method returns {} (a warning is logged).

Parameters:

Name Type Description Default
browse_context_id str

ID of the context to update (required).

required
context_data dict[str, Any] | None

Complete replacement session configuration (same structure as create_context()). Replaces the stored object; omitted fields are removed. Supports policy, egress_region, session_type, browser_profile, categories, etc.

None
max_uses int | None

New maximum number of times the context may be used.

None
expires int | float | str | None

New expiration: epoch seconds as a number, "+SECONDS" (relative), or ISO 8601. An all-digit string is converted to an int before sending.

None
name str | None

New display name for the context.

None
enabled bool | None

Whether the context is enabled.

None

Returns:

Type Description
dict[str, Any]

Dictionary containing the updated context details from the server.

Raises:

Type Description
BrowsingAPIError

If the update request fails

ValidationError

If browse_context_id is invalid

Examples:

>>> api.update_context(
...     "0123456789abcdef0123456789abcdef",
...     max_uses=10,
...     name="updated-context",
... )
Source code in silo_sdk/browsing/isolation_api.py
@api_tag(MethodType.API_COMMAND, api_command="update_context")
def update_context(
    self,
    browse_context_id: str,
    context_data: dict[str, Any] | None = None,
    max_uses: int | None = None,
    expires: int | float | str | None = None,
    name: str | None = None,
    enabled: bool | None = None,
) -> dict[str, Any]:
    """Update an existing browsing context.

    Modifies an existing context. The top-level fields (``name``,
    ``enabled``, ``max_uses``, ``expires``) are independent: omitted ones
    are left unchanged. ``context_data`` is different: it **replaces** the
    stored object entirely.

    Warning:
        Send the **complete** ``context_data`` (fetch it with
        :meth:`get_context`, change what you need, send it all back).
        Fields omitted are removed -- e.g. an update carrying only
        ``urls`` drops ``restrict_ips`` (the IP lock) and
        ``egress_region``. The server then re-applies create defaults:
        ``session_type`` becomes ``"silo-ruby"`` if missing, and a
        ``toolbox-standalone`` context without an egress region falls back
        to the org root.

    Warning:
        Unlike create, the server skips egress-provisioning and
        dynamic-policy checks on update. An update can store an egress the
        org cannot use (the context then fails at launch), and a
        ``domain_allow`` set through update gets no automatic
        ``domain_block *`` entry. This method does not validate either.

    Note:
        A nonexistent or deleted ``browse_context_id`` is **not** reported
        as an error: the server answers ``{"result": 0}`` and this method
        returns ``{}`` (a warning is logged).

    Args:
        browse_context_id: ID of the context to update (required).
        context_data: Complete replacement session configuration (same
            structure as ``create_context()``). **Replaces** the stored
            object; omitted fields are removed. Supports ``policy``,
            ``egress_region``, ``session_type``, ``browser_profile``,
            ``categories``, etc.
        max_uses: New maximum number of times the context may be used.
        expires: New expiration: epoch seconds as a number,
            ``"+SECONDS"`` (relative), or ISO 8601. An all-digit string is
            converted to an int before sending.
        name: New display name for the context.
        enabled: Whether the context is enabled.

    Returns:
        Dictionary containing the updated context details from the server.

    Raises:
        BrowsingAPIError: If the update request fails
        ValidationError: If browse_context_id is invalid

    Examples:
        >>> api.update_context(
        ...     "0123456789abcdef0123456789abcdef",
        ...     max_uses=10,
        ...     name="updated-context",
        ... )
    """
    if not browse_context_id or not isinstance(browse_context_id, str):
        raise ValidationError("browse_context_id must be a non-empty string")

    command: dict[str, Any] = {
        "command": "update_context",
        "browse_context_id": browse_context_id,
    }
    if context_data is not None:
        command["context_data"] = context_data
        if "session_type" not in context_data:
            self.logger.warning(
                "update_context(%s): context_data has no session_type, so the "
                "server will set it to 'silo-ruby'; context_data replaces the "
                "stored object, so any field omitted from it is dropped",
                browse_context_id,
            )
    if max_uses is not None:
        command["max_uses"] = max_uses
    if expires is not None:
        command["expires"] = _normalize_expires(expires)
    if name is not None:
        command["name"] = name
    if enabled is not None:
        command["enabled"] = enabled

    payload = [command]

    try:
        self.logger.debug("Updating context: %s", browse_context_id)
        response = self._make_api_request("POST", "api/", self.auth_token, payload)

        result = self._extract_api_result(response)
        if result == 0 and not isinstance(result, bool):
            self.logger.warning(
                "update_context(%s): server returned 0; the context may not "
                "exist (deleted or unknown id) and nothing was updated",
                browse_context_id,
            )
        else:
            self.logger.info("Successfully updated context: %s", browse_context_id)
        if isinstance(result, dict):
            return result
        return {}

    except Exception as e:
        if isinstance(e, BrowsingAPIError):
            raise
        raise BrowsingAPIError(f"Failed to update context: {e}") from e

create_ctx_url staticmethod

create_ctx_url(ctx: str, base_url: str = 'https://a8silo.com') -> str

Create a Silo web client launch URL for a browsing context.

Generates a https://a8silo.com/launch?ctx=<id> URL for opening an already-created context in the Silo web client. The context must first be created via create_context().

For a single-step alternative that creates and launches in one GET request, see the /ctx/ shorthand documented in create_context().

Parameters:

Name Type Description Default
ctx str

Browse context ID (from create_context())

required
base_url str

Base URL for the Silo web client (default: https://a8silo.com)

'https://a8silo.com'

Returns:

Type Description
str

Full URL for launching the Silo session in the web client

Examples:

>>> context_id = api.create_context(url="https://example.com", username="user@co.com")
>>> launch_url = BrowsingAPI.create_ctx_url(context_id)
>>> print(launch_url)
https://a8silo.com/launch?ctx=abc123def456
Source code in silo_sdk/browsing/isolation_api.py
@api_tag(MethodType.UTILITY)
@staticmethod
def create_ctx_url(ctx: str, base_url: str = "https://a8silo.com") -> str:
    """Create a Silo web client launch URL for a browsing context.

    Generates a ``https://a8silo.com/launch?ctx=<id>`` URL for opening an
    already-created context in the Silo web client. The context must first
    be created via ``create_context()``.

    For a single-step alternative that creates and launches in one GET
    request, see the ``/ctx/`` shorthand documented in ``create_context()``.

    Args:
        ctx: Browse context ID (from ``create_context()``)
        base_url: Base URL for the Silo web client (default: ``https://a8silo.com``)

    Returns:
        Full URL for launching the Silo session in the web client

    Examples:
        >>> context_id = api.create_context(url="https://example.com", username="user@co.com")
        >>> launch_url = BrowsingAPI.create_ctx_url(context_id)
        >>> print(launch_url)
        https://a8silo.com/launch?ctx=abc123def456
    """
    if not ctx:
        raise ValidationError("Context ID cannot be empty")

    return f"{base_url.rstrip('/')}/launch?ctx={ctx}"

defang_url staticmethod

defang_url(url: str) -> str

Defang a URL by replacing certain characters.

Makes a URL "safe" for sharing by replacing potentially dangerous characters that might cause accidental navigation.

Parameters:

Name Type Description Default
url str

URL to defang

required

Returns:

Type Description
str

Defanged URL with replaced characters

Examples:

>>> defanged = BrowsingAPI.defang_url("https://malicious.com")
>>> print(defanged)
hxxps://malicious[.]com
Source code in silo_sdk/browsing/isolation_api.py
@api_tag(MethodType.UTILITY)
@staticmethod
def defang_url(url: str) -> str:
    """Defang a URL by replacing certain characters.

    Makes a URL "safe" for sharing by replacing potentially dangerous
    characters that might cause accidental navigation.

    Args:
        url: URL to defang

    Returns:
        Defanged URL with replaced characters

    Examples:
        >>> defanged = BrowsingAPI.defang_url("https://malicious.com")
        >>> print(defanged)
        hxxps://malicious[.]com
    """
    if not url:
        return url

    return (
        url.replace("http://", "hxxp://")
        .replace("https://", "hxxps://")
        .replace(":", "[:]")
        .replace(".", "[.]")
    )

refang_url staticmethod

refang_url(url: str) -> str

Refang a URL by restoring certain characters.

Restores a defanged URL back to its original form for actual use.

Parameters:

Name Type Description Default
url str

Defanged URL to refang

required

Returns:

Type Description
str

Refanged URL with restored characters

Examples:

>>> refanged = BrowsingAPI.refang_url("hxxps://example[.]com")
>>> print(refanged)
https://example.com
Source code in silo_sdk/browsing/isolation_api.py
@api_tag(MethodType.UTILITY)
@staticmethod
def refang_url(url: str) -> str:
    """Refang a URL by restoring certain characters.

    Restores a defanged URL back to its original form for actual use.

    Args:
        url: Defanged URL to refang

    Returns:
        Refanged URL with restored characters

    Examples:
        >>> refanged = BrowsingAPI.refang_url("hxxps://example[.]com")
        >>> print(refanged)
        https://example.com
    """
    if not url:
        return url

    return (
        url.replace("hxxp://", "http://")
        .replace("hxxps://", "https://")
        .replace("[.]", ".")
        .replace("[:]", ":")
    )

bulk_create_contexts

bulk_create_contexts(urls: list[str], username: str | None = None, policy: list[dict[str, Any]] | None = None, max_uses: int | None = None, expires: int | float | str | None = None, org: str | None = None, session_type: Literal['silo-ruby', 'toolbox-standalone'] | None = None, egress_region: str | None = None, browser_profile: BrowserProfile | None = None, categories: Categories | None = None, validate_egress: bool | None = None) -> dict[str, list[str]]

Create multiple browsing contexts for a list of URLs.

Efficiently creates contexts for multiple URLs with the same user and policy settings. Failed context creations are logged but don't stop the process for other URLs.

Parameters:

Name Type Description Default
urls list[str]

List of URLs to create contexts for

required
username str | None

Username associated with all contexts

None
policy list[dict[str, Any]] | None

List of policy dictionaries for all contexts

None
max_uses int | None

Maximum number of times each context can be used

None
expires int | float | str | None

Expiration time for all contexts (epoch seconds as a number, "+SECONDS", or ISO 8601; see :meth:create_context)

None
org str | None

Org slug for SAML-enabled organizations

None
session_type Literal['silo-ruby', 'toolbox-standalone'] | None

'silo-ruby' or 'toolbox-standalone'

None
egress_region str | None

Egress location (e.g., 'New York, NY')

None
browser_profile BrowserProfile | None

Browser profile settings

None
categories Categories | None

Egress category settings

None
validate_egress bool | None

As for :meth:create_context, but checked once for the whole batch before any context is created.

None

Returns:

Type Description
dict[str, list[str]]

Dictionary containing list of successfully created context URLs

Raises:

Type Description
ValidationError

If parameters are invalid

Examples:

>>> urls = ["https://site1.com", "https://site2.com"]
>>> policy = [{"type": "readonly", "params": ["true"]}]
>>> result = api.bulk_create_contexts(urls, "user@company.com", policy)
>>> print(f"Created {len(result['context_urls'])} contexts")
>>> # With Silo for Research settings
>>> result = api.bulk_create_contexts(
...     urls=urls,
...     username="researcher@company.com",
...     session_type="toolbox-standalone",
...     egress_region="London"
... )
Source code in silo_sdk/browsing/isolation_api.py
@api_tag(MethodType.CONVENIENCE, wraps=["create_context"])
def bulk_create_contexts(
    self,
    urls: list[str],
    username: str | None = None,
    policy: list[dict[str, Any]] | None = None,
    max_uses: int | None = None,
    expires: int | float | str | None = None,
    org: str | None = None,
    session_type: Literal["silo-ruby", "toolbox-standalone"] | None = None,
    egress_region: str | None = None,
    browser_profile: BrowserProfile | None = None,
    categories: Categories | None = None,
    validate_egress: bool | None = None,
) -> dict[str, list[str]]:
    """Create multiple browsing contexts for a list of URLs.

    Efficiently creates contexts for multiple URLs with the same user and
    policy settings. Failed context creations are logged but don't stop
    the process for other URLs.

    Args:
        urls: List of URLs to create contexts for
        username: Username associated with all contexts
        policy: List of policy dictionaries for all contexts
        max_uses: Maximum number of times each context can be used
        expires: Expiration time for all contexts (epoch seconds as a
            number, ``"+SECONDS"``, or ISO 8601; see :meth:`create_context`)
        org: Org slug for SAML-enabled organizations
        session_type: 'silo-ruby' or 'toolbox-standalone'
        egress_region: Egress location (e.g., 'New York, NY')
        browser_profile: Browser profile settings
        categories: Egress category settings
        validate_egress: As for :meth:`create_context`, but checked once for
            the whole batch before any context is created.

    Returns:
        Dictionary containing list of successfully created context URLs

    Raises:
        ValidationError: If parameters are invalid

    Examples:
        >>> urls = ["https://site1.com", "https://site2.com"]
        >>> policy = [{"type": "readonly", "params": ["true"]}]
        >>> result = api.bulk_create_contexts(urls, "user@company.com", policy)
        >>> print(f"Created {len(result['context_urls'])} contexts")

        >>> # With Silo for Research settings
        >>> result = api.bulk_create_contexts(
        ...     urls=urls,
        ...     username="researcher@company.com",
        ...     session_type="toolbox-standalone",
        ...     egress_region="London"
        ... )
    """
    if not isinstance(urls, list) or not urls:
        raise ValidationError("URLs must be a non-empty list")

    if not username and not org:
        raise ValidationError("Either username or org must be provided")

    if policy is not None and not isinstance(policy, list):
        raise ValidationError("Policy must be a list of dictionaries")

    _validate_session_type(session_type)
    _validate_legacy_egress(egress_region, categories)

    live = (
        self.live_egress_validation if validate_egress is None else validate_egress
    )
    if live:
        requested = self._requested_egress(None, egress_region, categories)
        if requested is not None:
            # Once for the batch: every context shares the egress.
            self._check_egress_live(requested, username, session_type)

    context_urls: list[str] = []

    self.logger.info("Creating contexts for %d URLs", len(urls))

    # The shared egress was validated above; don't repeat it (and its
    # warnings) for every context in the batch.
    batch_token = _BATCH_EGRESS_VALIDATED.set(True)
    try:
        self._create_batch(
            urls,
            context_urls,
            username=username,
            policy=policy,
            max_uses=max_uses,
            expires=expires,
            org=org,
            session_type=session_type,
            egress_region=egress_region,
            browser_profile=browser_profile,
            categories=categories,
        )
    finally:
        _BATCH_EGRESS_VALIDATED.reset(batch_token)

    self.logger.info(
        "Successfully created %d/%d contexts", len(context_urls), len(urls)
    )

    return {"context_urls": context_urls}

create_research_session

create_research_session(username: str, egress_region: str, url: str | None = None, browser_profile: BrowserProfile | None = None, categories: Categories | None = None, policy: list[dict[str, Any]] | None = None, max_uses: int | None = None, expires: int | float | str | None = None, auto_domain_allow: bool = False, validate_egress: bool | None = None) -> str

Create a Silo for Research (toolbox-standalone) session.

Convenience method for creating research sessions with egress routing and browser profile configuration.

Parameters:

Name Type Description Default
username str

Username for the session

required
egress_region str

Egress location (e.g., 'New York, NY', 'London'). See get_egress_locations() for available options.

required
url str | None

Optional URL to open in the session

None
browser_profile BrowserProfile | None

Browser profile with 'os', 'browser', and optional 'timezone'/'languages' settings. Options for os: 'win', 'mac', 'linux', 'android', 'ios' Options for browser: 'chrome', 'firefox', 'edge', 'safari', 'tor'

None
categories Categories | None

Egress category settings. Example:

None
policy list[dict[str, Any]] | None

Optional policy list for the session

None
max_uses int | None

Maximum number of times the context can be used

None
expires int | float | str | None

Context expiration time (epoch seconds as a number, "+SECONDS", or ISO 8601; see :meth:create_context)

None
validate_egress bool | None

Forwarded to :meth:create_context.

None

Returns:

Type Description
str

Browse context ID that can be used to launch the session

Raises:

Type Description
BrowsingAPIError

If session creation fails

ValidationError

If parameters are invalid

Examples:

>>> context_id = api.create_research_session(
...     username="researcher@company.com",
...     egress_region="New York, NY",
...     url="https://example.com",
...     browser_profile={"os": "win", "browser": "chrome"},
...     categories={"availability": "public", "connectivity": "isp"}
... )
>>> launch_url = api.create_ctx_url(context_id)
Source code in silo_sdk/browsing/isolation_api.py
@api_tag(MethodType.CONVENIENCE, wraps=["create_context"])
def create_research_session(
    self,
    username: str,
    egress_region: str,
    url: str | None = None,
    browser_profile: BrowserProfile | None = None,
    categories: Categories | None = None,
    policy: list[dict[str, Any]] | None = None,
    max_uses: int | None = None,
    expires: int | float | str | None = None,
    auto_domain_allow: bool = False,
    validate_egress: bool | None = None,
) -> str:
    """Create a Silo for Research (toolbox-standalone) session.

    Convenience method for creating research sessions with egress routing
    and browser profile configuration.

    Args:
        username: Username for the session
        egress_region: Egress location (e.g., 'New York, NY', 'London').
            See ``get_egress_locations()`` for available options.
        url: Optional URL to open in the session
        browser_profile: Browser profile with 'os', 'browser', and optional
            'timezone'/'languages' settings.
            Options for os: 'win', 'mac', 'linux', 'android', 'ios'
            Options for browser: 'chrome', 'firefox', 'edge', 'safari', 'tor'
        categories: Egress category settings. Example:
            {"availability": "public", "connectivity": "datacenter"}
        policy: Optional policy list for the session
        max_uses: Maximum number of times the context can be used
        expires: Context expiration time (epoch seconds as a number,
            ``"+SECONDS"``, or ISO 8601; see :meth:`create_context`)
        validate_egress: Forwarded to :meth:`create_context`.

    Returns:
        Browse context ID that can be used to launch the session

    Raises:
        BrowsingAPIError: If session creation fails
        ValidationError: If parameters are invalid

    Examples:
        >>> context_id = api.create_research_session(
        ...     username="researcher@company.com",
        ...     egress_region="New York, NY",
        ...     url="https://example.com",
        ...     browser_profile={"os": "win", "browser": "chrome"},
        ...     categories={"availability": "public", "connectivity": "isp"}
        ... )
        >>> launch_url = api.create_ctx_url(context_id)
    """
    return self.create_context(
        url=url,
        username=username,
        policy=policy,
        max_uses=max_uses,
        expires=expires,
        session_type="toolbox-standalone",
        egress_region=egress_region,
        browser_profile=browser_profile,
        categories=categories,
        auto_domain_allow=auto_domain_allow,
        validate_egress=validate_egress,
    )

get_egress_locations staticmethod

get_egress_locations(include_details: bool = False) -> dict[str, Any]

Get available egress locations by region.

Parameters:

Name Type Description Default
include_details bool

When False (default), returns a dict mapping region names to lists of location name strings — backward-compatible with prior behavior. When True, each location is a dict with name, connectivity, availability, and protocol keys.

False

Returns:

Type Description
dict[str, Any]

When include_details=False: {region: [city_name, ...]}

dict[str, Any]

When include_details=True: {region: [{"name": city, "connectivity": [...], "availability": [...], "protocol": [...]}]}

dict[str, Any]

Cities absent from the canonical location data (see

dict[str, Any]

silo_sdk.harvesting.egress_validation.get_egress_locations_with_details())

dict[str, Any]

are omitted from the enriched output entirely, rather than

dict[str, Any]

appearing with empty detail lists.

Examples:

>>> locations = BrowsingAPI.get_egress_locations()
>>> print(locations["North America"])
['Toronto', 'Vancouver', 'Mexico City', ...]
>>> details = BrowsingAPI.get_egress_locations(include_details=True)
>>> sao_paulo = next(
...     e for e in details["Central & South America"]
...     if e["name"] == "Sao Paulo"
... )
>>> print("datacenter" in sao_paulo["connectivity"])
True
>>> sydney = next(
...     e for e in details["Asia-Pacific"] if e["name"] == "Sydney"
... )
>>> print("tor" in sydney["protocol"])
True
Source code in silo_sdk/browsing/isolation_api.py
@api_tag(MethodType.UTILITY)
@staticmethod
def get_egress_locations(
    include_details: bool = False,
) -> dict[str, Any]:
    """Get available egress locations by region.

    Args:
        include_details: When ``False`` (default), returns a dict mapping
            region names to lists of location name strings — backward-compatible
            with prior behavior. When ``True``, each location is a dict with
            ``name``, ``connectivity``, ``availability``, and ``protocol`` keys.

    Returns:
        When ``include_details=False``:
            ``{region: [city_name, ...]}``

        When ``include_details=True``:
            ``{region: [{"name": city, "connectivity": [...],
            "availability": [...], "protocol": [...]}]}``

        Cities absent from the canonical location data (see
        ``silo_sdk.harvesting.egress_validation.get_egress_locations_with_details()``)
        are omitted from the enriched output entirely, rather than
        appearing with empty detail lists.

    Examples:
        >>> locations = BrowsingAPI.get_egress_locations()
        >>> print(locations["North America"])
        ['Toronto', 'Vancouver', 'Mexico City', ...]

        >>> details = BrowsingAPI.get_egress_locations(include_details=True)
        >>> sao_paulo = next(
        ...     e for e in details["Central & South America"]
        ...     if e["name"] == "Sao Paulo"
        ... )
        >>> print("datacenter" in sao_paulo["connectivity"])
        True
        >>> sydney = next(
        ...     e for e in details["Asia-Pacific"] if e["name"] == "Sydney"
        ... )
        >>> print("tor" in sydney["protocol"])
        True
    """
    if not include_details:
        details = get_egress_locations_with_details()
        return {
            region: [e["name"] for e in entries]
            for region, entries in details.items()
        }

    return get_egress_locations_with_details()

list_egresses

list_egresses(username: str | None = None, *, user_id: str | int | None = None, org_id: str | int | None = None, org_name: str | None = None, session_type: str | None = None, service_type: str | None = None) -> list[EgressDirectoryEntry]

Ask the platform which egress locations are actually available.

The live counterpart to :meth:get_egress_locations, which reads a table compiled into the SDK. Prefer this one when the answer matters. The static table lists every location the platform has; this reports the subset a given org or user can really select right now, after the server applies entitlements, the org's Launcher Options policy, and an up/down check. Keep the static table for offline use, tests, and fast validation.

Parameters:

Name Type Description Default
username str | None

The user to report for. Give exactly one selector.

None
user_id str | int | None

Numeric user ID, as an alternative to username.

None
org_id str | int | None

Numeric org ID, to report for a whole organization.

None
org_name str | None

Organization name (sent as orgname), as an alternative to org_id. A name that appears more than once in the hierarchy is ambiguous and the platform rejects it with 400; use org_id for those.

None
session_type str | None

What the egress will be used for. "silo-ruby" (the server's default) restricts the answer to locations a browsing context can pin; "toolbox-standalone" does not. Leave unset unless you specifically need the wider list.

None
service_type str | None

Which server pool to report. "egress" (the server's default) is the pool browsing contexts and visual/video/single harvest tasks draw from; "harvest-asset" is the separate pool for asset and wget tasks. For a harvest task, prefer :meth:HarvesterAPI.list_harvest_egresses, which picks the pool, session type and org for you.

None

Returns:

Name Type Description
One list[EgressDirectoryEntry]

class:~silo_sdk.base.types.EgressDirectoryEntry per

list[EgressDirectoryEntry]

location, each with its name, its path through the

list[EgressDirectoryEntry]

location hierarchy, and the categories combinations it

list[EgressDirectoryEntry]

offers. Sorted by path, then name.

list[EgressDirectoryEntry]

The directory returns every hierarchy node -- the World

list[EgressDirectoryEntry]

root, regions, countries and cities -- not just leaf cities. A

list[EgressDirectoryEntry]

parent node carries the union of its children's categories, and

list[EgressDirectoryEntry]

path[-1] == name. Filter to leaves (nodes that are nobody's

list[EgressDirectoryEntry]

parent) when you want concrete locations.

Raises:

Type Description
BrowsingAPIError

If the request fails.

ValidationError

If the selectors, session_type or service_type are invalid.

Note

An empty list is a real answer, not an error. It means no egress can be pinned — most often because the org runs Traffic Manager rules, which choose the egress themselves, but also when the org's policy has disabled every provisioned region or none is currently up. Treat it as "let the platform decide", not as a failed lookup.

An org selector reports the egress provisioned to that org, not to orgs beneath it, so a top-level org whose egress sits on its sub-orgs also returns an empty list. To see what a user can select, pass username or user_id; the platform answers for that user's own org.

Note

This is a plain REST endpoint rather than a command-array call, so it behaves differently in two ways. Failures arrive as real HTTP status codes instead of an error element inside a 200, and the token travels in an Authorization: Bearer header instead of the usual command-array setauth. It needs an ADMIN_TOKEN; a sync token is refused with 403, and so is an admin grant that does not cover users when you select by username or user_id.

Examples:

>>> egresses = api.list_egresses("user@company.com")
>>> print(egresses[0]["name"])
'Amsterdam'

Keep only leaf locations (nodes that are not the parent of any other node). path runs from broadest to narrowest and path[-1] == name:

>>> parents = {
...     e["path"][-2] for e in egresses if len(e.get("path", [])) > 1
... }
>>> leaves = [e for e in egresses if e["name"] not in parents]

Group the leaves by region; guard against short paths, since the World root has only one element:

>>> by_region: dict[str, list[str]] = {}
>>> for e in leaves:
...     region = e["path"][1] if len(e["path"]) > 1 else "World"
...     by_region.setdefault(region, []).append(e["name"])

Find the leaf locations that offer a Tor exit (a parent would match too, since it carries its children's categories):

>>> tor = [
...     e["name"] for e in leaves
...     if any(c.get("protocol") == "tor" for c in e["categories"])
... ]

Confirm a location before pinning it on a context:

>>> available = {e["name"] for e in api.list_egresses("u@x.com")}
>>> if "Singapore" in available:
...     api.create_context(
...         url="https://example.com",
...         username="u@x.com",
...         egress_info={"name": "Singapore"},
...     )
Source code in silo_sdk/browsing/isolation_api.py
@api_tag(MethodType.API_COMMAND, api_command="egresses")
def list_egresses(
    self,
    username: str | None = None,
    *,
    user_id: str | int | None = None,
    org_id: str | int | None = None,
    org_name: str | None = None,
    session_type: str | None = None,
    service_type: str | None = None,
) -> list[EgressDirectoryEntry]:
    """Ask the platform which egress locations are actually available.

    The live counterpart to :meth:`get_egress_locations`, which reads a
    table compiled into the SDK. Prefer this one when the answer matters.
    The static table lists every location the platform has; this reports
    the subset a given org or user can really select right now, after the
    server applies entitlements, the org's Launcher Options policy, and
    an up/down check. Keep the static table for offline use, tests, and
    fast validation.

    Args:
        username: The user to report for. Give exactly one selector.
        user_id: Numeric user ID, as an alternative to ``username``.
        org_id: Numeric org ID, to report for a whole organization.
        org_name: Organization name (sent as ``orgname``), as an
            alternative to ``org_id``. A name that appears more than
            once in the hierarchy is ambiguous and the platform rejects
            it with ``400``; use ``org_id`` for those.
        session_type: What the egress will be used for. ``"silo-ruby"``
            (the server's default) restricts the answer to locations a
            browsing context can pin; ``"toolbox-standalone"`` does not.
            Leave unset unless you specifically need the wider list.
        service_type: Which server pool to report. ``"egress"`` (the
            server's default) is the pool browsing contexts and
            ``visual``/``video``/``single`` harvest tasks draw from;
            ``"harvest-asset"`` is the separate pool for ``asset`` and
            ``wget`` tasks. For a harvest task, prefer
            :meth:`HarvesterAPI.list_harvest_egresses`, which picks the
            pool, session type and org for you.

    Returns:
        One :class:`~silo_sdk.base.types.EgressDirectoryEntry` per
        location, each with its ``name``, its ``path`` through the
        location hierarchy, and the ``categories`` combinations it
        offers. Sorted by path, then name.

        The directory returns **every hierarchy node** -- the ``World``
        root, regions, countries and cities -- not just leaf cities. A
        parent node carries the union of its children's categories, and
        ``path[-1] == name``. Filter to leaves (nodes that are nobody's
        parent) when you want concrete locations.

    Raises:
        BrowsingAPIError: If the request fails.
        ValidationError: If the selectors, ``session_type`` or
            ``service_type`` are invalid.

    Note:
        **An empty list is a real answer, not an error.** It means no
        egress can be pinned — most often because the org runs Traffic
        Manager rules, which choose the egress themselves, but also when
        the org's policy has disabled every provisioned region or none is
        currently up. Treat it as "let the platform decide", not as a
        failed lookup.

        An org selector reports the egress provisioned to that org, not
        to orgs beneath it, so a top-level org whose egress sits on its
        sub-orgs also returns an empty list. To see what a user can
        select, pass ``username`` or ``user_id``; the platform answers
        for that user's own org.

    Note:
        This is a plain REST endpoint rather than a command-array call,
        so it behaves differently in two ways. Failures arrive as real
        HTTP status codes instead of an ``error`` element inside a
        ``200``, and the token travels in an ``Authorization: Bearer``
        header instead of the usual command-array ``setauth``. It needs
        an ``ADMIN_TOKEN``; a sync token is refused with ``403``, and so
        is an admin grant that does not cover users when you select by
        ``username`` or ``user_id``.

    Examples:
        >>> egresses = api.list_egresses("user@company.com")
        >>> print(egresses[0]["name"])
        'Amsterdam'

        Keep only leaf locations (nodes that are not the parent of any
        other node). ``path`` runs from broadest to narrowest and
        ``path[-1] == name``:

        >>> parents = {
        ...     e["path"][-2] for e in egresses if len(e.get("path", [])) > 1
        ... }
        >>> leaves = [e for e in egresses if e["name"] not in parents]

        Group the leaves by region; guard against short paths, since the
        ``World`` root has only one element:

        >>> by_region: dict[str, list[str]] = {}
        >>> for e in leaves:
        ...     region = e["path"][1] if len(e["path"]) > 1 else "World"
        ...     by_region.setdefault(region, []).append(e["name"])

        Find the leaf locations that offer a Tor exit (a parent would
        match too, since it carries its children's categories):

        >>> tor = [
        ...     e["name"] for e in leaves
        ...     if any(c.get("protocol") == "tor" for c in e["categories"])
        ... ]

        Confirm a location before pinning it on a context:

        >>> available = {e["name"] for e in api.list_egresses("u@x.com")}
        >>> if "Singapore" in available:
        ...     api.create_context(
        ...         url="https://example.com",
        ...         username="u@x.com",
        ...         egress_info={"name": "Singapore"},
        ...     )
    """
    selectors = {
        "username": username,
        "user_id": user_id,
        "org_id": org_id,
        "orgname": org_name,
    }
    named = {k: v for k, v in selectors.items() if v is not None and v != ""}

    if len(named) != 1:
        # The server enforces this too, as a 400. Checking locally keeps a
        # typo from costing a round trip, and names the parameters the way
        # the caller wrote them.
        raise ValidationError(
            "list_egresses needs exactly one of username, user_id, "
            f"org_id or org_name; got {len(named)}."
        )

    params: dict[str, Any] = dict(named)

    if session_type is not None:
        _validate_session_type(session_type)
        params["session_type"] = session_type

    if service_type is not None:
        if service_type not in EGRESS_SERVICE_TYPES:
            # The platform answers an unknown pool with [], which is
            # indistinguishable from "Traffic Manager chooses".
            raise ValidationError(
                f"Invalid service_type: {service_type!r}. Expected one of "
                f"{sorted(EGRESS_SERVICE_TYPES)}."
            )
        params["service_type"] = service_type

    try:
        self.logger.debug("Listing egresses for %s", next(iter(named)))
        response = self._make_api_request(
            "GET",
            "egresses/",
            "",
            params=params,
            headers={"Authorization": f"Bearer {self.auth_token}"},
        )
    except Exception as e:
        if isinstance(e, BrowsingAPIError):
            raise
        # Unlike the command-array path, this endpoint reports failures as
        # real HTTP status codes and _handle_response parses the body into
        # SiloError.response_data. Re-raising with only str(e) would drop
        # the actionable half — the server's "pass org_id" remedy never
        # reaches the caller. Carry the detail and the fields through.
        if isinstance(e, SiloError):
            detail = e.server_message
            raise BrowsingAPIError(
                f"Failed to list egresses: {detail or e}",
                status_code=e.status_code,
                response_data=e.response_data,
                request_id=e.request_id,
            ) from e
        raise BrowsingAPIError(f"Failed to list egresses: {e}") from e

    # _handle_response wraps a non-list JSON body in a list, so a dict
    # body would arrive here as a one-element list. Reject anything whose
    # elements are not the location objects this endpoint documents.
    if not all(isinstance(e, dict) and "name" in e for e in response):
        raise BrowsingAPIError(f"Unexpected egress directory response: {response}")

    self.logger.info("Server reports %d egress locations", len(response))
    return cast("list[EgressDirectoryEntry]", response)

Policy Reference

Policy coverage

This page documents the confirmed policy types. Additional policy types may be available depending on your Silo license.

Browsing contexts created via BrowsingAPI.create_context() accept an optional policy list that controls session behavior. Each entry is a dict with a "type" string and a "params" list.

policy = [
    {"type": "file_transfer", "params": ["block_all"]},
    {"type": "clipboard",     "params": ["allow_to_local"]},
    {"type": "readonly",      "params": ["false"]},
    {"type": "browser_chrome","params": ["standard"]},
]

context_id = api.create_context(
    url="https://example.com",
    username="analyst@company.com",
    policy=policy,
)

domain_allow injection is opt-in via the auto_domain_allow parameter — it is not added automatically when url is provided. See the domain_allow section below for details.


Policy Types

readonly

Makes the session read-only — blocks downloads, clipboard interaction, and other write operations.

Param Effect
"true" Session is read-only
"false" Session allows interaction (default)
{"type": "readonly", "params": ["true"]}

file_transfer

Controls whether files can be uploaded or downloaded during the session.

Param Effect
"block_all" Block all file transfers (upload and download)
"allow_all" Allow all file transfers
{"type": "file_transfer", "params": ["block_all"]}

clipboard

Controls the direction of clipboard operations between the local machine and the isolated session.

Param Effect
"block_all" Block clipboard in both directions
"allow_all" Allow clipboard in both directions
"allow_to_local" Allow copying from the session to the local machine
"block_to_silo" Block pasting into the session from the local machine

Multiple params can be combined in the same list:

{"type": "clipboard", "params": ["allow_to_local", "block_to_silo"]}

ad_block

Enables or disables ad blocking for the session.

Param Effect
"enable" Ad blocking on
"disable" Ad blocking off
{"type": "ad_block", "params": ["enable"]}

browser_chrome

Controls the visual UI mode of the Silo ribbon (the banner displayed during an isolation session).

Param UI mode Notes
"standard" Full ribbon UI (default) All controls visible
"seamless" Hidden ribbon — transparent browsing Non-catchall users only — see warning below
"minimal" Minimal ribbon (Ribbon Mode) Reduced controls visible
{"type": "browser_chrome", "params": ["seamless"]}

Seamless UI does not apply to catchall users

The "seamless" mode is only effective for non-catchall users.

A user is treated as catchall when accessed via a catchall account, when the org is configured to treat all users as catchall, or via partner SSO. Catchall users are always forced into "minimal" (Ribbon Mode) regardless of the browser_chrome policy value. This is a platform-level enforcement and cannot be overridden via policy.

If you need seamless UI, ensure users are not provisioned as catchall.


domain_allow

Whitelists specific domains that the user is permitted to navigate to during the session.

{"type": "domain_allow", "params": ["example.com"]}

Opt-in auto-injection with auto_domain_allow

When you pass a url to create_context(), a domain_allow entry for the URL's domain is not added automatically. To enable automatic injection of the URL's domain, pass auto_domain_allow=True:

context_id = api.create_context(
    url="https://example.com",
    username="analyst@company.com",
    policy=policy,
    auto_domain_allow=True,  # injects {"type": "domain_allow", "params": ["example.com"]}
)

Leave auto_domain_allow=False (the default) when you want to construct your own domain_allow entry — for example, to allow multiple domains in a single entry:

policy = [
    {
        "type": "domain_allow",
        "params": ["google.com", "yahoo.com"],
    }
]
context_id = api.create_context(
    url="https://google.com",
    username="analyst@company.com",
    policy=policy,
    # auto_domain_allow=False (default) — the policy above takes effect as-is
)

Auto-injection only adds the single domain extracted from url; it cannot be used to allow additional domains beyond the target URL's domain.

Multiple domains can be included in a single domain_allow entry or by adding separate entries:

# Single entry — multiple domains in one params list
policy = [
    {"type": "domain_allow", "params": ["example.com", "trusted-partner.com"]},
]

# Multiple entries — one domain each
policy = [
    {"type": "domain_allow", "params": ["example.com"]},
    {"type": "domain_allow", "params": ["trusted-partner.com"]},
]

domain_block

Blacklists specific domains, preventing the user from navigating to them during the session.

{"type": "domain_block", "params": ["blocked-site.com"]}

ribbon_background_color

Sets a custom background color for the Silo ribbon/HUD banner. Useful for branding or indicating session type (e.g., red for sensitive environments).

{"type": "ribbon_background_color", "params": ["#cc0000"]}

Accepts a CSS hex color string (e.g., "#cc0000", "#ffffff").


ribbon_text_color

Sets a custom text color for the Silo ribbon/HUD banner.

{"type": "ribbon_text_color", "params": ["#ffffff"]}

ribbon_message

Displays a custom message in the Silo ribbon/HUD banner. Maximum 100 characters.

{"type": "ribbon_message", "params": ["Sensitive session — do not share screen"]}

Complete Custom Policy Example

The Postman collection Create Context — Custom Policy request demonstrates a context with multiple policies configured together:

policy = [
    {"type": "file_transfer",  "params": ["block_all"]},
    {"type": "clipboard",      "params": ["allow_to_local", "block_to_silo"]},
    {"type": "readonly",       "params": ["false"]},
    {"type": "browser_chrome", "params": ["standard"]},
]

context_id = api.create_context(
    url="https://secure.example.com",
    username="analyst@company.com",
    policy=policy,
    max_uses=5,
    expires="3600",          # 1 hour
    auto_domain_allow=True,  # automatically allow the URL's domain
)

Seamless UI Example

# Only use this with non-catchall users (catchall users are forced to minimal)
policy = [
    {"type": "browser_chrome", "params": ["seamless"]},
    {"type": "file_transfer",  "params": ["block_all"]},
]

context_id = api.create_context(
    url="https://app.example.com",
    username="authenticated.user@company.com",
    policy=policy,
    max_uses=1,
    auto_domain_allow=True,  # allow the app domain automatically
)

Egress Selection

There are two ways to pin a browsing context to an egress location.

The older form takes egress_region plus an optional categories dict:

context_id = api.create_context(
    url="https://example.com",
    username="user@company.com",
    egress_region="New York, NY",
    categories={"connectivity": "datacenter", "availability": "public"},
)

The newer form takes a single egress_info object. It is the only way to request a server_set:

context_id = api.create_context(
    url="https://example.com",
    username="user@company.com",
    egress_info={
        "name": "New York, NY",
        "server_set": "dedicated-pool-1",
        "categories": {"connectivity": "datacenter", "availability": "public"},
    },
)

The two forms are mutually exclusive

Pass egress_info or egress_region/categories — never both. The platform rejects the mixture, and so does create_context(), so you get the error before the round trip rather than after it.

categories takes scalars: connectivity ("datacenter", "isp", "fixed-wireless", "wireless-carrier"), availability ("public", "private"), and protocol ("direct", "tor", "sovereign").

"sovereign" egress is provisioned per org, and only for toolbox-standalone (Silo for Research) sessions. To find your org's sovereign locations, call list_egresses(..., session_type="toolbox-standalone") and look for "protocol": "sovereign" in a location's categories. World with protocol: "sovereign" lets the platform choose. The SDK does not check whether your org has sovereign egress; the platform rejects the request if not.

context_id = api.create_context(
    username="researcher@company.com",
    session_type="toolbox-standalone",
    egress_info={"name": "World", "categories": {"protocol": "sovereign"}},
)

An egress_region (or egress_info name) that is not in the SDK's bundled location list logs a warning and is still sent. The list can lag the platform, so the platform makes the final decision.

Which Locations Are Available

BrowsingAPI.get_egress_locations() is a static table bundled with the SDK — it lists every location the platform has, not the ones a given account may select. list_egresses() asks the platform:

available = api.list_egresses(username="user@company.com")
# [{"name": "New York, NY", "path": ["North America", "United States"],
#   "categories": [{"connectivity": "datacenter", "availability": "public",
#                   "protocol": "direct"}, ...]}, ...]

The answer depends on the session type. A standard session (session_type="silo-ruby", the default) may pin only egress cleared for it, and gets nothing when the org runs Traffic Manager rules; a research session ("toolbox-standalone") reaches every provisioned location. Which locations a standard session may pin differs from one organization to another, so ask for the one you will create:

api.list_egresses(username="user@company.com", session_type="toolbox-standalone")

With validate_egress=True (or LIVE_EGRESS_VALIDATION), create_context does this lookup itself and raises ValidationError for an egress the platform does not offer. It skips the check for an egress_info that names a server_set, which the platform checks directly, and for a context created for an org rather than a user.

Pass exactly one of username, user_id, org_id, or org_name. The reply reflects entitlements, organization policy, and which egresses are currently up. An empty list is a real answer — it means no egress can be pinned, most often because the organization uses Traffic Manager rules that choose the egress themselves.

An org selector reports that org's own egress

org_id and org_name report the egress provisioned to that organization, not the egress provisioned to organizations beneath it. A top-level organization whose egress is provisioned to its sub-organizations returns an empty list even though its users have egress. To see what a user can select, pass username or user_id: the platform answers for that user's own organization.

categories is shaped differently here

In a list_egresses() reply, categories is a list of objects, one per routing combination the location offers. In egress_info it is a single dict of scalars. The two look similar and are not interchangeable.

This call needs an ADMIN_TOKEN — a sync token is refused.


Browser Profile

create_context() accepts an optional browser_profile dict that controls the emulated user agent for the session.

Key Description Example
os Operating system to emulate "win", "mac", "linux", "android", "ios"
browser Browser to emulate "chrome", "firefox", "edge", "safari", "tor"
timezone IANA timezone name (optional) "America/New_York"
languages Accept-Language header value (optional) "en-US,en"
context_id = api.create_context(
    url="https://example.com",
    username="user@company.com",
    browser_profile={
        "os": "win",
        "browser": "chrome",
        "timezone": "America/New_York",
        "languages": "en-US,en",
    },
)