Skip to content

Runtime Package

paglets.runtime owns host execution, active child processes, mailbox delivery, transfer envelopes, and runtime resource cleanup.

Responsibilities

  • Start, supervise, stop, deactivate, activate, clone, dispatch, and dispose paglet instances.
  • Expose the host HTTP API and route incoming control/movement requests.
  • Run active paglets in spawned child Python processes.
  • Serialize active state over shared-memory streams at the host/child boundary.
  • Deliver queued messages through per-paglet mailboxes.
  • Store and clean up host-owned artifact blobs used for registered file mobility and explicit artifact transfer.
  • Track resources that must be cleaned up during lifecycle transitions.

Main Modules

paglets.runtime.host
The orchestration center. Host is the public runtime facade and owns active child controllers, inactive records, service records, storage roots, mesh state, authentication, placement, and lifecycle operations.
paglets.runtime.lifecycle
Contains the Host movement and lifecycle flows: create, dispatch, clone, retract, deactivate, activate, dispose, transfer tickets, and movement envelope handling.
paglets.runtime.resident_services
Contains resident service declaration, activation, service leasing, registry lookup, and idle shutdown behavior.
paglets.runtime.child_calls
Routes host calls arriving from child processes and completes child-initiated dispatch, clone, deactivate, dispose, service, storage, and messaging operations.
paglets.runtime.inactive_records
Loads and writes inactive records, schedules activation, drains queued messages, and deactivates active paglets during shutdown.
paglets.runtime.http_api
Contains the host HTTP server and request handler. It maps endpoint shape, authentication, JSON control payloads, binary movement payloads, admin calls, and relay HTTP endpoints onto Host methods without owning host state.
paglets.runtime.relay
Contains relay/connect-mode state, relay delivery queues, polling, acknowledgements, local relay URL submission, and client registration loops. Host mixes this behavior in while keeping the public facade at paglets.runtime.host.Host.
paglets.runtime.binding
Resolves bind hosts, public host names, auto LAN addresses, and --bind-public behavior for the host CLI/runtime boundary.
paglets.runtime.process_runtime
Compatibility facade for the split process runtime modules.
paglets.runtime.process_controller, paglets.runtime.child_endpoint,
paglets.runtime.child_facade, paglets.runtime.child_bootstrap, and
paglets.runtime.process_protocol
Implement parent-side child process control, child pipe protocol handling, child-visible host/storage facades, process bootstrap, and shared protocol values.
paglets.runtime.mailbox
Implements queued delivery, priority ordering, mailbox status, and wait/notify behavior for message handlers.
paglets.runtime.envelope
Defines the transfer envelope used for create, dispatch, clone, retract, and activation flows.
paglets.runtime.resources
Tracks resource cleanup callbacks and reports cleanup failures as lifecycle errors.

Implementation Notes

The host is the only component that mutates host-wide registries. Child processes request operations through a facade, and the parent host validates and performs those operations.

Same-host movement bypasses HTTP and delivers the envelope directly to the local host instance. Different host processes on the same machine still use the HTTP transport path over loopback.

HTTP routing and relay mechanics deliberately live outside host.py; they delegate into the host facade and do not define a second public runtime object. This keeps endpoint behavior stable while making the implementation easier to read and test.

The child process must be able to import the paglet class and state class by qualified name. Classes defined in __main__, REPL sessions, or temporary scripts are not valid paglet classes.

API Reference

paglets.runtime.host

Host

Bases: _LifecycleMixin, _ResidentServicesMixin, _ChildCallMixin, _InactiveRecordsMixin, RelayMixin

A paglet host/context served over a small JSON HTTP API.

One process can run one host. For development, one Python process can also start multiple hosts on different ports. Migration always uses the same envelope model: class path + dataclass state + lifecycle metadata.

Source code in src/paglets/runtime/host.py
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
class Host(_LifecycleMixin, _ResidentServicesMixin, _ChildCallMixin, _InactiveRecordsMixin, RelayMixin):
    """A paglet host/context served over a small JSON HTTP API.

    One process can run one host. For development, one Python process can also
    start multiple hosts on different ports. Migration always uses the same
    envelope model: class path + dataclass state + lifecycle metadata.
    """

    def __init__(
        self,
        name: str,
        host: str | Sequence[str] = "127.0.0.1",
        port: int = 0,
        *,
        client: HostClient | None = None,
        api_key: str | None = None,
        public_url: str | None = None,
        connect_to: str | None = None,
        mesh: bool = True,
        peers: list[str] | None = None,
        mesh_multicast: bool = True,
        mesh_lan_discovery: bool = True,
        mesh_version: str | None = None,
        mesh_gossip_interval: float = 1.0,
        mesh_offline_after: float = 10.0,
        persistence_dir: str | Path | None = None,
        persistent_storage_quota_bytes: int | None = DEFAULT_PERSISTENT_STORAGE_QUOTA_BYTES,
        artifact_max_bytes: int | None = DEFAULT_ARTIFACT_MAX_BYTES,
        artifact_storage_quota_bytes: int | None = DEFAULT_ARTIFACT_STORAGE_QUOTA_BYTES,
        artifact_spool_ttl_seconds: float = DEFAULT_ARTIFACT_SPOOL_TTL_SECONDS,
        launch_config: LaunchConfig | None = None,
        launch_config_sync_result: LaunchConfigSyncResult | None = None,
        auto_update_from_git: bool = False,
        git_repo_root: str | Path | None = None,
        git_process_start_head: str | None = None,
        auto_update_restart_callback: Callable[[], None] | None = None,
        auto_update_reporter: Callable[[str], None] | None = None,
        auto_update_restart_delay: float = AUTO_UPDATE_RESTART_DELAY_SECONDS,
        bind_watch_interval: float = NETWORK_BIND_WATCH_INTERVAL_SECONDS,
        relay_offline_after: float = RELAY_OFFLINE_AFTER_SECONDS,
        relay_delivery_timeout: float | None = None,
        relay_queue_limit: int = RELAY_QUEUE_LIMIT,
        tags: Sequence[str] | None = None,
        properties: dict[str, str] | None = None,
    ):
        self.name = name
        self.tags = _normalize_host_tags(tags or ())
        self.host_properties = _normalize_host_properties(properties or {})
        self.api_key = api_key
        self.public_url = public_url.strip().rstrip("/") if public_url else None
        self.connect_to = connect_to.strip().rstrip("/") if connect_to else None
        self.relay_mode = bool(self.public_url or self.connect_to)
        self._bind_host_specs = _bind_host_specs(host)
        self._auto_bind_enabled = any(value.casefold() == "auto" for value in self._bind_host_specs)
        self._bind_watch_interval = max(0.1, float(bind_watch_interval))
        self._bind_watch_stop = threading.Event()
        self._bind_watch_thread: threading.Thread | None = None
        self._server_lock = threading.RLock()
        self.bind_hosts = _resolve_bind_hosts(self._bind_host_specs)
        self.bind_host = self.bind_hosts[0]
        self.public_host = _resolve_public_host(self.bind_host)
        self.port = int(port)
        self.address = (
            self._connect_relay_url() if self.connect_to else (self.public_url or f"http://{self.public_host}:{port}")
        )
        self.client = client or HostClient(api_key=api_key)
        if api_key and getattr(self.client, "api_key", None) is None:
            self.client.api_key = api_key
        self._agents: dict[str, ChildProcessController] = {}
        self._mailboxes: dict[str, MessageMailbox] = {}
        self.persistence_dir = (
            Path(persistence_dir).expanduser()
            if persistence_dir is not None
            else DEFAULT_PERSISTENCE_ROOT / self._safe_host_name(name)
        )
        self._inactive_dir = self.persistence_dir / "inactive"
        self._work_root = self.persistence_dir / "work"
        self._storage_root = self.persistence_dir / "storage"
        self._artifact_root = self.persistence_dir / "artifacts"
        self.persistent_storage_quota_bytes = persistent_storage_quota_bytes
        self.artifact_max_bytes = 0 if artifact_max_bytes is None else max(0, int(artifact_max_bytes))
        self.artifact_storage_quota_bytes = (
            None if artifact_storage_quota_bytes is None else max(0, int(artifact_storage_quota_bytes))
        )
        self.artifact_spool_ttl_seconds = max(1.0, float(artifact_spool_ttl_seconds))
        self.artifacts = ArtifactStore(
            self._artifact_root,
            host_url=self.address,
            max_artifact_bytes=self.artifact_max_bytes,
            quota_bytes=self.artifact_storage_quota_bytes,
            spool_ttl_seconds=self.artifact_spool_ttl_seconds,
        )
        self._registered_files: dict[str, dict[str, PagletFileRef]] = {}
        self._inactive: dict[str, InactiveRecord] = {}
        self._services = ServiceRegistry()
        self._resident_services: dict[str, _ManagedResidentService] = {}
        self._resident_activation_locks: dict[str, threading.Lock] = {}
        self._events = ContextEventLog()
        self._properties: dict[str, Any] = {}
        self.launch_config = launch_config
        self.launch_config_sync_result = launch_config_sync_result
        self._lock = threading.RLock()
        self._server: _PagletHTTPServer | None = None
        self._servers: list[_PagletHTTPServer] = []
        self._thread: threading.Thread | None = None
        self._threads: list[threading.Thread] = []
        self._activation_stop = threading.Event()
        self._activation_thread: threading.Thread | None = None
        self._artifact_cleanup_stop = threading.Event()
        self._artifact_cleanup_thread: threading.Thread | None = None
        self._relay_stop = threading.Event()
        self._relay_client_thread: threading.Thread | None = None
        self._relay_nodes: dict[str, _RelayNode] = {}
        self._relay_queues: dict[str, queue.Queue[_RelayDelivery]] = {}
        self._relay_pending: dict[str, _RelayDelivery] = {}
        self.relay_offline_after = max(0.1, float(relay_offline_after))
        self.relay_delivery_timeout = (
            10.0 if relay_delivery_timeout is None else max(0.01, float(relay_delivery_timeout))
        )
        self.relay_queue_limit = max(1, int(relay_queue_limit))
        self.auto_update_from_git = bool(auto_update_from_git)
        self.git_repo_root = Path(git_repo_root).resolve() if git_repo_root is not None else None
        self.git_process_start_head = git_process_start_head or ""
        self._git_update_status: dict[str, Any] | None = None
        self._auto_update_restart_callback = auto_update_restart_callback
        self._auto_update_reporter = auto_update_reporter
        self._auto_update_restart_delay = max(0.0, float(auto_update_restart_delay))
        self._auto_update_restart_scheduled = False
        self._auto_update_request_times: dict[str, float] = {}
        if self.auto_update_from_git:
            if self.git_repo_root is None:
                self.git_repo_root = git_update.find_repo_root(Path.cwd())
            if not self.git_process_start_head:
                self.git_process_start_head = git_update.current_head(self.git_repo_root)
        self.mesh = MeshRegistry(
            self,
            enabled=mesh,
            peers=peers,
            code_version=mesh_version,
            multicast=mesh_multicast,
            lan_discovery=mesh_lan_discovery,
            gossip_interval=mesh_gossip_interval,
            offline_after=mesh_offline_after,
        )
        self._load_inactive_records()

    def start_background(self) -> None:
        if self.connect_to:
            self._start_connect_background()
            return
        with self._server_lock:
            if self._server is not None:
                return
            self._clear_work_root()
            servers = self._open_http_servers(self.bind_hosts, self.port)
            self._install_http_servers(servers, self.bind_hosts)
        self._activation_stop.clear()
        self._emit_launch_config_sync_result()
        self._start_resident_services()
        self._activate_startup_records()
        self._start_launch_agents()
        self._start_activation_scheduler()
        self.mesh.start()
        self._start_bind_watcher()
        self._start_artifact_cleanup()
        self._emit("context-start")

    def serve_forever(self) -> None:
        self.start_background()
        try:
            while True:
                with self._server_lock:
                    if self._server is None:
                        return
                    threads = list(self._threads)
                if not threads:
                    return
                for thread in threads:
                    thread.join(timeout=0.5)
        except KeyboardInterrupt:  # pragma: no cover - CLI convenience
            self.shutdown()

    def shutdown(self) -> None:
        self.stop(deactivate_active=True)

    def stop(self, *, deactivate_active: bool = False) -> None:
        self._stop_bind_watcher()
        with self._server_lock:
            server = self._server
            if server is None and self._relay_client_thread is None:
                return
            servers = list(self._servers or ([server] if server is not None else []))
            threads = list(self._threads)
            if not threads and self._thread is not None:
                threads = [self._thread]
        self._stop_relay_client()
        self._stop_activation_scheduler()
        self._stop_artifact_cleanup()
        if deactivate_active:
            self._deactivate_active_for_shutdown()
        self._terminate_active_children()
        self.mesh.stop()
        self._emit("context-shutdown")
        with self._server_lock:
            self._clear_http_servers()
        if servers:
            self._shutdown_http_servers(servers, threads)

    def _start_connect_background(self) -> None:
        with self._server_lock:
            if self._relay_client_thread is not None:
                return
            self._clear_work_root()
            self.artifacts.set_host_url(self.address)
            self.artifacts.cleanup_temporary()
        self._activation_stop.clear()
        self._emit_launch_config_sync_result()
        self._activate_startup_records()
        self._start_resident_services()
        self._start_launch_agents()
        self._start_activation_scheduler()
        self.mesh.refresh_self()
        self._start_relay_client()
        self._start_artifact_cleanup()
        self._emit("context-start")

    def _open_http_servers(self, bind_hosts: list[str], port: int) -> list[_PagletHTTPServer]:
        servers: list[_PagletHTTPServer] = []
        try:
            for index, bind_host in enumerate(bind_hosts):
                bind_port = port if index == 0 or port != 0 else int(servers[0].server_address[1])
                servers.append(_PagletHTTPServer((bind_host, bind_port), _RequestHandler, self))
        except Exception:
            for server in servers:
                server.server_close()
            raise
        return servers

    def _install_http_servers(self, servers: list[_PagletHTTPServer], bind_hosts: list[str]) -> None:
        _actual_host, actual_port = servers[0].server_address[:2]
        self.bind_hosts = list(bind_hosts)
        self.bind_host = self.bind_hosts[0]
        self.public_host = _resolve_public_host(self.bind_host)
        self.port = int(actual_port)
        self.address = self.public_url or f"http://{self.public_host}:{actual_port}"
        self._servers = servers
        self._server = servers[0]
        self.artifacts.set_host_url(self.address)
        self.artifacts.cleanup_temporary()
        self._threads = [
            threading.Thread(target=server.serve_forever, name=f"paglets-{self.name}-{index}", daemon=True)
            for index, server in enumerate(servers)
        ]
        self._thread = self._threads[0]
        for thread in self._threads:
            thread.start()

    def _clear_http_servers(self) -> None:
        self._servers = []
        self._server = None
        self._threads = []
        self._thread = None

    def _shutdown_http_servers(
        self,
        servers: list[_PagletHTTPServer],
        threads: list[threading.Thread],
    ) -> None:
        for running_server in servers:
            running_server.shutdown()
        for running_server in servers:
            running_server.server_close()
        current_thread = threading.current_thread()
        for thread in threads:
            if thread is not current_thread and thread.is_alive():
                thread.join(timeout=2)

    def _start_bind_watcher(self) -> None:
        if not self._auto_bind_enabled:
            return
        if self._bind_watch_thread is not None and self._bind_watch_thread.is_alive():
            return
        self._bind_watch_stop.clear()
        self._bind_watch_thread = threading.Thread(
            target=self._bind_watch_loop,
            name=f"paglets-bind-watch-{self.name}",
            daemon=True,
        )
        self._bind_watch_thread.start()

    def _stop_bind_watcher(self) -> None:
        self._bind_watch_stop.set()
        thread = self._bind_watch_thread
        self._bind_watch_thread = None
        if thread is not None and thread is not threading.current_thread() and thread.is_alive():
            thread.join(timeout=2)

    def _start_artifact_cleanup(self) -> None:
        if self._artifact_cleanup_thread is not None and self._artifact_cleanup_thread.is_alive():
            return
        self._artifact_cleanup_stop.clear()
        self._artifact_cleanup_thread = threading.Thread(
            target=self._artifact_cleanup_loop,
            name=f"paglets-artifacts-cleanup-{self.name}",
            daemon=True,
        )
        self._artifact_cleanup_thread.start()

    def _stop_artifact_cleanup(self) -> None:
        self._artifact_cleanup_stop.set()
        thread = self._artifact_cleanup_thread
        self._artifact_cleanup_thread = None
        if thread is not None and thread is not threading.current_thread() and thread.is_alive():
            thread.join(timeout=2)

    def _artifact_cleanup_loop(self) -> None:
        interval = max(1.0, min(float(self.artifact_spool_ttl_seconds), 300.0))
        while not self._artifact_cleanup_stop.wait(interval):
            with contextlib.suppress(Exception):
                self.artifacts.cleanup_temporary()

    def _bind_watch_loop(self) -> None:
        while not self._bind_watch_stop.wait(self._bind_watch_interval):
            try:
                self._check_auto_bind_change()
            except Exception as exc:  # pragma: no cover - defensive background boundary
                self.mesh._debug(f"auto bind refresh failed: {exc}")

    def _check_auto_bind_change(self) -> bool:
        if not self._auto_bind_enabled:
            return False
        with self._server_lock:
            if self._server is None:
                return False
            current_bind_hosts = list(self.bind_hosts)
        next_bind_hosts = _resolve_bind_hosts(self._bind_host_specs)
        if next_bind_hosts == current_bind_hosts:
            return False
        return self._rebind_http_servers(next_bind_hosts)

    def _rebind_http_servers(self, next_bind_hosts: list[str]) -> bool:
        with self._server_lock:
            server = self._server
            if server is None:
                return False
            current_bind_hosts = list(self.bind_hosts)
            if next_bind_hosts == current_bind_hosts:
                return False
            old_address = self.address
            old_port = self.port
            old_servers = list(self._servers or [server])
            old_threads = list(self._threads)
            if not old_threads and self._thread is not None:
                old_threads = [self._thread]
            try:
                self._shutdown_http_servers(old_servers, old_threads)
                new_servers = self._open_http_servers(next_bind_hosts, old_port)
            except Exception as exc:
                try:
                    restored_servers = self._open_http_servers(current_bind_hosts, old_port)
                except Exception as restore_exc:
                    self._clear_http_servers()
                    self.mesh._debug(f"auto bind refresh failed and restore failed: {exc}; restore: {restore_exc}")
                    raise
                self._install_http_servers(restored_servers, current_bind_hosts)
                self.mesh._debug(f"auto bind refresh failed; restored previous bind hosts: {exc}")
                return False
            self._install_http_servers(new_servers, next_bind_hosts)
            new_address = self.address
        self.mesh.local_address_changed(old_address)
        self._emit(
            "context-rebind",
            data={
                "old_address": old_address,
                "new_address": new_address,
                "bind_hosts": list(next_bind_hosts),
            },
        )
        return True

    # ------------------------------------------------------------------
    # Local management API
    # ------------------------------------------------------------------
    def get_proxy(self, agent_id: str, *, include_inactive: bool = False) -> PagletProxy | None:
        with self._lock:
            record = self._agents.get(agent_id)
            if record is not None:
                if record.ready and not record.crashed:
                    return PagletProxy(self.address, agent_id, self.client)
                return None
            if include_inactive and agent_id in self._inactive:
                return PagletProxy(self.address, agent_id, self.client)
            return None

    def get_proxies(self, state: int = ACTIVE) -> list[PagletProxy]:
        proxies: list[PagletProxy] = []
        with self._lock:
            if state & ACTIVE:
                proxies.extend(
                    PagletProxy(self.address, agent_id, self.client)
                    for agent_id, record in self._agents.items()
                    if record.ready and not record.crashed
                )
            if state & INACTIVE:
                proxies.extend(PagletProxy(self.address, agent_id, self.client) for agent_id in self._inactive)
        return proxies

    def get_property(self, key: str, default: Any = None) -> Any:
        with self._lock:
            return self._properties.get(key, default)

    def set_property(self, key: str, value: Any) -> None:
        with self._lock:
            if value is None:
                self._properties.pop(key, None)
            else:
                self._properties[key] = value

    def get_state(self, agent_id: str, state_cls: type[PagletState]) -> PagletState:
        record = self._require_agent(agent_id)
        state_payload = record.fetch_state()
        state = dataclass_from_wire(state_cls, state_payload)
        if not isinstance(state, state_cls):
            raise HostError(f"Paglet {agent_id!r} state is not {state_cls!r}")
        return state

    def resources_for(self, agent_id: str):
        return _RemoteResourceRegistry(self, agent_id)

    def work_dir_for(self, agent_id: str, *, create: bool = True) -> Path:
        self._require_agent(agent_id)
        path = self._work_path(agent_id)
        if create:
            path.mkdir(parents=True, exist_ok=True)
        return path

    def persistent_storage_for(self, agent_id: str, *, quota_bytes: int | None = None) -> ManagedStorage:
        record = self._require_agent(agent_id)
        quota = self.persistent_storage_quota_bytes if quota_bytes is None else quota_bytes
        return ManagedStorage(
            self._storage_root / self._storage_class_key(record.agent_class_name),
            quota_bytes=quota,
        )

    def register_file_for(
        self,
        agent_id: str,
        path: str | Path,
        *,
        name: str | None = None,
        mode: str = "copy",
    ) -> PagletFileRef:
        self._require_agent(agent_id)
        ref = paglet_file_ref_from_path(
            path,
            name=name,
            mode=mode,
            host_name=self.name,
            host_url=self.address,
        )
        with self._lock:
            files = self._registered_files.setdefault(agent_id, {})
            files[ref.name] = ref
        return ref

    def registered_files_for(self, agent_id: str) -> list[PagletFileRef]:
        with self._lock:
            return [PagletFileRef.from_wire(ref.to_wire()) for ref in self._registered_files.get(agent_id, {}).values()]

    def unregister_file_for(self, agent_id: str, name_or_ref: str | PagletFileRef) -> None:
        name = name_or_ref.name if isinstance(name_or_ref, PagletFileRef) else str(name_or_ref)
        with self._lock:
            files = self._registered_files.get(agent_id)
            if files is not None:
                files.pop(name, None)
                if not files:
                    self._registered_files.pop(agent_id, None)

    def registered_file_path_for(self, agent_id: str, name_or_ref: str | PagletFileRef) -> Path:
        name = name_or_ref.name if isinstance(name_or_ref, PagletFileRef) else str(name_or_ref)
        with self._lock:
            ref = self._registered_files.get(agent_id, {}).get(name)
        if ref is None:
            raise HostError(f"No registered file {name!r} for paglet {agent_id!r}")
        return Path(ref.current_path)

    def list_agents(
        self,
        *,
        active: bool = True,
        inactive: bool = False,
        include_state: bool = False,
    ) -> list[dict[str, Any]]:
        with self._lock:
            active_records = list(self._agents.values()) if active else []
            inactive_records = list(self._inactive.values()) if inactive else []
            agents = [self._summary(agent) for agent in active_records]
            if inactive:
                agents.extend(self._inactive_summary(record) for record in inactive_records)
        if not include_state:
            return agents
        return [self._summary_with_state(item) for item in agents]

    def health(self) -> dict[str, Any]:
        with self._lock:
            active_count = sum(1 for record in self._agents.values() if record.ready and not record.crashed)
            inactive_count = len(self._inactive)
        capabilities = list(HOST_CAPABILITIES)
        if self.relay_mode and "admin:git-update" in capabilities:
            capabilities.remove("admin:git-update")
        if not self.connect_to:
            capabilities.extend(["relay:connect", "relay:poll"])
        payload = {
            "name": self.name,
            "address": self.address,
            "active_count": active_count,
            "inactive_count": inactive_count,
            "code_version": self.mesh.code_version,
            "capabilities": capabilities,
            "tags": list(self.tags),
            "properties": dict(self.host_properties),
        }
        if self._relay_nodes:
            payload["relay_nodes"] = self.relay_diagnostics()["nodes"]
        payload.update(self._git_update_health())
        return payload

    def list_hosts(self, *, online_only: bool = False, include_self: bool = True) -> list[HostRef]:
        return self.mesh.hosts(online_only=online_only, include_self=include_self)

    def join_mesh(self, payload: dict[str, Any]) -> list[HostRef]:
        self.mesh.register_wire(payload)
        return self.mesh.hosts(include_self=True)

    def handle_git_update_request(self, payload: dict[str, Any]) -> dict[str, Any]:
        if not self.auto_update_from_git or self.git_repo_root is None:
            status = {
                "ok": False,
                "status": "disabled",
                "error": "git auto-update is disabled for this host",
                "target_hash": str(payload.get("target_hash") or ""),
            }
            self._store_git_update_status(status)
            return status

        target_hash = str(payload.get("target_hash") or "").strip()
        source_name = str(payload.get("source_name") or "")
        source_url = str(payload.get("source_url") or "")
        result = git_update.update_checkout(
            self.git_repo_root,
            process_start_head=self.git_process_start_head,
            target_hash=target_hash,
            sync_dependencies=os.name != "nt",
        )
        status = result.to_wire()
        status.update(
            {
                "source_name": source_name,
                "source_url": source_url,
                "restart_scheduled": False,
            }
        )
        self._store_git_update_status(status)
        if result.restart_required:
            status["restart_scheduled"] = self._schedule_auto_update_restart()
            self._store_git_update_status(status)
        return status

    def broadcast_git_update(
        self,
        targets: list[str] | None = None,
        *,
        validate_targets: bool = False,
        report_unreachable: bool = True,
    ) -> list[dict[str, Any]]:
        if not self.auto_update_from_git:
            return []
        urls = set(targets or [])
        urls.update(self.mesh.peer_urls(include_known=True))
        responses: list[dict[str, Any]] = []
        for url in sorted(urls):
            response = self.request_peer_git_update(
                url,
                validate_health=validate_targets,
                report_unreachable=report_unreachable,
            )
            if response is not None:
                responses.append(response)
        return responses

    def request_peer_git_update(
        self,
        url: str,
        *,
        target_hash: str | None = None,
        health: dict[str, Any] | None = None,
        throttle: bool = True,
        validate_health: bool = False,
        report_unreachable: bool = True,
    ) -> dict[str, Any] | None:
        if not self.auto_update_from_git:
            return None
        normalized = url.rstrip("/")
        if validate_health and health is None:
            try:
                probed = self.client.get_json(
                    f"{normalized}/health",
                    timeout=AUTO_UPDATE_REQUEST_TIMEOUT_SECONDS,
                )
            except Exception as exc:
                if report_unreachable:
                    failure = {"ok": False, "status": "unreachable", "error": str(exc), "url": normalized}
                    self._report_git_update_failure(normalized, failure)
                    return failure
                return None
            if not isinstance(probed, dict):
                failure = {
                    "ok": False,
                    "status": "invalid-health",
                    "error": f"unexpected health {probed!r}",
                    "url": normalized,
                }
                self._report_git_update_failure(normalized, failure)
                return failure
            health = probed
        if health is not None and health.get("auto_update_from_git") is False:
            return None
        try:
            normalized = HostRef.from_wire(
                {
                    "name": health.get("name", url) if health else url,
                    "url": health.get("address", url) if health else url,
                    "code_version": health.get("code_version", self.mesh.code_version)
                    if health
                    else self.mesh.code_version,
                    "online": True,
                    "last_seen": time.time(),
                    "active_count": health.get("active_count", 0) if health else 0,
                    "inactive_count": health.get("inactive_count", 0) if health else 0,
                }
            ).url
        except Exception:
            normalized = url.rstrip("/")
        if normalized.rstrip("/") == self.address.rstrip("/"):
            return None
        if throttle and not self._reserve_git_update_request(normalized):
            return None

        target = (target_hash or self._current_git_head()).strip()
        if not target:
            return None
        try:
            response = self.client.post_json(
                f"{normalized.rstrip('/')}/admin/git-update",
                {
                    "target_hash": target,
                    "source_name": self.name,
                    "source_url": self.address,
                },
                timeout=AUTO_UPDATE_REQUEST_TIMEOUT_SECONDS,
            )
            if isinstance(response, dict):
                response.setdefault("url", normalized)
                if not response.get("ok"):
                    self._report_git_update_failure(normalized, response)
                return response
            failure = {
                "ok": False,
                "status": "invalid-response",
                "error": f"unexpected response {response!r}",
                "url": normalized,
            }
            self._report_git_update_failure(normalized, failure)
            return failure
        except Exception as exc:
            failure = {
                "ok": False,
                "status": "request-failed",
                "error": str(exc),
                "target_hash": target,
                "url": normalized,
            }
            self._report_git_update_failure(normalized, failure)
            return failure

    def _git_update_health(self) -> dict[str, Any]:
        payload: dict[str, Any] = {
            "auto_update_from_git": self.auto_update_from_git,
            "auto_update_restart_scheduled": self._auto_update_restart_scheduled,
        }
        if self.git_repo_root is not None:
            payload["git_repo_root"] = str(self.git_repo_root)
            payload["git_head"] = self._current_git_head()
            payload["git_process_start_head"] = self.git_process_start_head
        status = self._git_update_status
        if status is not None:
            payload["git_update"] = dict(status)
        return payload

    def _current_git_head(self) -> str:
        if self.git_repo_root is None:
            return ""
        try:
            return git_update.current_head(self.git_repo_root)
        except git_update.GitUpdateError:
            return self.git_process_start_head

    def _store_git_update_status(self, status: dict[str, Any]) -> None:
        with self._lock:
            self._git_update_status = dict(status)

    def _reserve_git_update_request(self, url: str) -> bool:
        now = time.monotonic()
        with self._lock:
            last = self._auto_update_request_times.get(url, 0.0)
            if now - last < AUTO_UPDATE_REQUEST_INTERVAL_SECONDS:
                return False
            self._auto_update_request_times[url] = now
            return True

    def _schedule_auto_update_restart(self) -> bool:
        if self._auto_update_restart_callback is None:
            self._report_auto_update("restart required, but no restart callback is configured")
            return False
        with self._lock:
            if self._auto_update_restart_scheduled:
                return True
            self._auto_update_restart_scheduled = True
        thread = threading.Thread(
            target=self._run_auto_update_restart,
            name=f"paglets-auto-update-restart-{self.name}",
            daemon=True,
        )
        thread.start()
        return True

    def _run_auto_update_restart(self) -> None:
        time.sleep(self._auto_update_restart_delay)
        callback = self._auto_update_restart_callback
        try:
            self._report_auto_update("restart scheduled; shutting down host for re-exec")
            self.shutdown()
        finally:
            if callback is not None:
                callback()

    def _report_git_update_failure(self, url: str, response: dict[str, Any]) -> None:
        status = str(response.get("status") or "failed")
        target = str(response.get("target_hash") or "")
        error = str(response.get("error") or "")
        pieces = [f"{url}: git auto-update {status}"]
        if target:
            pieces.append(f"target {target}")
        if error:
            pieces.append(error)
        if status == "target-missing":
            pieces.append(
                "The commit may not have been pushed yet; run git push and restart this host to broadcast again."
            )
        stderr = _trim_git_output(str(response.get("stderr") or ""))
        stdout = _trim_git_output(str(response.get("stdout") or ""))
        if stderr:
            pieces.append(f"stderr: {stderr}")
        if stdout:
            pieces.append(f"stdout: {stdout}")
        self._report_auto_update("; ".join(pieces))

    def _report_auto_update(self, message: str) -> None:
        reporter = self._auto_update_reporter
        if reporter is not None:
            reporter(message)

    def add_listener(self, listener: ContextListener) -> None:
        self._events.add_listener(listener)

    def remove_listener(self, listener: ContextListener) -> None:
        self._events.remove_listener(listener)

    def list_events(self, *, since: int = 0, limit: int = 100) -> list[ContextEvent]:
        return self._events.events_since(since, limit=limit)

    def deliver_message(
        self,
        agent_id: str,
        message: Message,
        *,
        oneway: bool = False,
        activate_if_inactive: bool = True,
        no_delay: bool = False,
    ) -> Any:
        if message.kind == DEACTIVATE:
            proxy = self.deactivate(
                agent_id,
                DeactivationRequest.from_wire(message.args.get("request")),
            )
            return None if oneway else {"deactivated": True, "proxy": proxy.to_wire()}
        with self._lock:
            agent = self._agents.get(agent_id)
            inactive = self._inactive.get(agent_id)
            is_resident_service = agent_id in self._resident_services
        if agent is None:
            if is_resident_service and activate_if_inactive:
                self._ensure_resident_service_active(agent_id)
            else:
                if inactive is None:
                    raise InvalidAgentError(f"No active paglet {agent_id!r} on {self.name}")
                if activate_if_inactive and inactive.policy.activate_on_message:
                    self.activate(agent_id)
                elif no_delay or not inactive.policy.queue_messages_when_inactive:
                    raise PagletInactiveError(f"Paglet {agent_id!r} is inactive on {self.name}")
                else:
                    inactive.queued_messages.append(QueuedMessage(message=message, oneway=oneway))
                    self._write_inactive_record(inactive)
                    self._emit("message-queued", agent_id=agent_id, message_id=message.message_id)
                    return None if oneway else {"queued": True, "message_id": message.message_id}
        with self._lock:
            mailbox = self._mailboxes.get(agent_id)
        if mailbox is None:
            raise InvalidAgentError(f"No active paglet {agent_id!r} on {self.name}")
        if message.priority == UNQUEUED_PRIORITY:
            future = mailbox.submit_unqueued(message, oneway=oneway)
        else:
            future = mailbox.submit(message, oneway=oneway)
            self._emit("message-queued", agent_id=agent_id, message_id=message.message_id)
        return None if oneway else future.result()

    def _deliver_active_message(self, agent_id: str, message: Message, *, oneway: bool = False) -> Any:
        with self._lock:
            record = self._agents.get(agent_id)
        if record is None:
            error = InvalidAgentError(f"No active paglet {agent_id!r} on {self.name}")
            self._emit("message-failed", agent_id=agent_id, message_id=message.message_id, error=str(error))
            raise error
        self._begin_resident_service_call(agent_id)
        try:
            try:
                result = record.request_message(message, oneway=oneway)
            except Exception as exc:
                self._emit("message-failed", agent_id=agent_id, message_id=message.message_id, error=str(exc))
                raise
            self._emit("message-delivered", agent_id=agent_id, message_id=message.message_id)
            return None if oneway else result
        finally:
            self._end_resident_service_call(agent_id)

    def multicast_message(
        self,
        kind: str | Message,
        args: dict[str, Any] | None = None,
        *,
        exclude: set[str] | None = None,
    ) -> ReplySet:
        exclude = exclude or set()
        reply_set = ReplySet()
        for proxy in self.get_proxies(ACTIVE):
            if proxy.agent_id in exclude:
                continue
            message = (
                Message.from_wire(kind.to_wire())
                if isinstance(kind, Message)
                else Message(kind=kind, args=args or {}, sender=self.address)
            )
            if message.sender is None:
                message.sender = self.address
            reply_set.add_future_reply(proxy.send_future(message))
        return reply_set

    def wait_message(self, agent_id: str, *, timeout: float | None = None) -> bool:
        return self._require_mailbox(agent_id).wait_message(timeout)

    def notify_message(self, agent_id: str) -> None:
        self._require_mailbox(agent_id).notify_message()

    def notify_all_messages(self, agent_id: str) -> None:
        self._require_mailbox(agent_id).notify_all_messages()

    def mailbox_status(self, agent_id: str) -> dict[str, int]:
        return self._require_mailbox(agent_id).status().to_wire()

    def _require_mailbox(self, agent_id: str) -> MessageMailbox:
        with self._lock:
            mailbox = self._mailboxes.get(agent_id)
        if mailbox is None:
            raise InvalidAgentError(f"No active paglet {agent_id!r} on {self.name}")
        return mailbox

    def _clear_work_root(self) -> None:
        with contextlib.suppress(FileNotFoundError):
            shutil.rmtree(self._work_root)
        self._work_root.mkdir(parents=True, exist_ok=True)

    def _cleanup_agent_work_dir(self, agent_id: str) -> None:
        with contextlib.suppress(FileNotFoundError):
            shutil.rmtree(self._work_path(agent_id))

    def _work_path(self, agent_id: str) -> Path:
        return self._work_root / self._safe_storage_name(agent_id)

    @classmethod
    def _storage_class_key(cls, class_name: str) -> str:
        return cls._safe_storage_name(class_name.replace(":", "."))

    @staticmethod
    def _safe_storage_name(value: str) -> str:
        return "".join(char if char.isalnum() or char in "._-" else "_" for char in value) or "storage"

    def _start_child(
        self,
        *,
        agent_id: str,
        agent_class_name: str,
        state_class_name: str,
        state: dict[str, Any],
    ) -> ChildProcessController:
        self._validate_agent_classes(agent_class_name, state_class_name)
        config = make_child_config(
            host_name=self.name,
            host_address=self.address,
            host_api_key=self.api_key,
            agent_id=agent_id,
            agent_class_name=agent_class_name,
            state_class_name=state_class_name,
            state=state,
        )
        record = ChildProcessController(
            config,
            host_call_handler=lambda op, payload, child_id=agent_id: self._handle_child_host_call(
                child_id, op, payload
            ),
            crash_handler=self._handle_child_crash,
        )
        mailbox = MessageMailbox(
            agent_id,
            lambda message, oneway, child_id=agent_id: self._deliver_active_message(child_id, message, oneway=oneway),
            max_workers=1,
        )
        with self._lock:
            old_record = self._agents.pop(agent_id, None)
            old_mailbox = self._mailboxes.pop(agent_id, None)
            self._agents[agent_id] = record
            self._mailboxes[agent_id] = mailbox
        if old_mailbox is not None:
            old_mailbox.close()
        if old_record is not None and not old_record.departing:
            old_record.terminate(timeout=0.5, kill_timeout=0.5)
        return record

    def _remove_active_agent(
        self,
        agent_id: str,
        expected: ChildProcessController | None = None,
        *,
        terminate: bool = False,
    ) -> None:
        with self._lock:
            current = self._agents.get(agent_id)
            if expected is not None and current is not expected:
                return
            if current is not None:
                current.departing = True
            self._agents.pop(agent_id, None)
            mailbox = self._mailboxes.pop(agent_id, None)
        if mailbox is not None:
            mailbox.close()
        for record in self._services.remove_agent(agent_id, keep=self._is_resident_service_record):
            self._emit("service-remove", agent_id=agent_id, service_name=record.name)
        if current is not None and terminate:
            current.terminate(timeout=0.5, kill_timeout=0.5)

    def _require_agent(self, agent_id: str) -> ChildProcessController:
        with self._lock:
            record = self._agents.get(agent_id)
        if record is None:
            raise InvalidAgentError(f"No active paglet {agent_id!r} on {self.name}")
        if record.crashed:
            raise PagletCrashedError(f"Paglet {agent_id!r} crashed: {record.last_error}")
        return record

    def _summary(self, record: ChildProcessController) -> dict[str, Any]:
        mailbox = self._mailboxes.get(record.agent_id)
        return {
            "agent_id": record.agent_id,
            "class_name": record.agent_class_name,
            "state_class_name": record.state_class_name,
            "host": self.name,
            "address": self.address,
            "active": not record.crashed,
            "pid": record.pid,
            "crashed": record.crashed,
            "exitcode": record.exitcode,
            "error": record.last_error,
            "mailbox": mailbox.status().to_wire() if mailbox is not None else None,
            "resources": record.resource_status_snapshot(),
        }

    def _inactive_summary(self, record: InactiveRecord) -> dict[str, Any]:
        return {
            "agent_id": record.envelope.agent_id,
            "class_name": record.envelope.agent_class_name,
            "state_class_name": record.envelope.state_class_name,
            "host": self.name,
            "address": self.address,
            "active": False,
            "deactivated_at": record.deactivated_at,
        }

    def _summary_with_state(self, summary: dict[str, Any]) -> dict[str, Any]:
        try:
            state_payload = self._state_payload(str(summary["agent_id"]))
        except Exception as exc:
            enriched = dict(summary)
            enriched["state_error"] = str(exc)
            return enriched
        enriched = dict(summary)
        enriched.update(state_payload)
        return enriched

    def _state_payload(self, agent_id: str) -> dict[str, Any]:
        with self._lock:
            record = self._agents.get(agent_id)
            mailbox = self._mailboxes.get(agent_id)
            inactive = self._inactive.get(agent_id)
        if record is not None:
            try:
                state_payload = record.fetch_state(timeout=2.0)
            except Exception:
                state_payload = dict(record.state)
            return {
                "agent_id": record.agent_id,
                "class_name": record.agent_class_name,
                "state_class_name": record.state_class_name,
                "host": self.name,
                "address": self.address,
                "active": not record.crashed,
                "pid": record.pid,
                "crashed": record.crashed,
                "exitcode": record.exitcode,
                "error": record.last_error,
                "state": state_payload,
                "mailbox": mailbox.status().to_wire() if mailbox is not None else None,
                "resources": record.resource_status_snapshot(),
            }
        if inactive is not None:
            return {
                "agent_id": inactive.envelope.agent_id,
                "class_name": inactive.envelope.agent_class_name,
                "state_class_name": inactive.envelope.state_class_name,
                "host": self.name,
                "address": self.address,
                "active": False,
                "state": inactive.envelope.state,
                "deactivation_policy": inactive.policy.to_wire(),
                "queued_message_count": len(inactive.queued_messages),
            }
        raise InvalidAgentError(f"No paglet {agent_id!r} on {self.name}")

    def _emit_launch_config_sync_result(self) -> None:
        result = self.launch_config_sync_result
        if result is None:
            return
        if result.action is LaunchConfigSyncAction.COPIED:
            self._emit("launch-config-copy", data={"path": str(result.path), "message": result.message})
        elif result.action is LaunchConfigSyncAction.UPDATED:
            self._emit(
                "launch-config-update",
                data={
                    "path": str(result.path),
                    "backup_path": str(result.backup_path) if result.backup_path is not None else None,
                    "message": result.message,
                },
            )

    def _start_launch_agents(self) -> None:
        config = self.launch_config
        if config is None:
            return
        for startup_agent in config.startup_agents:
            if not startup_agent.enabled:
                self._emit(
                    "startup-agent-skip",
                    data={"reason": "disabled", "use": startup_agent.use, "class": startup_agent.class_name},
                )
                continue
            try:
                resolved = resolve_startup_agent(startup_agent)
                class_name = qualified_name(resolved.agent_cls)
                if resolved.singleton and resolved.agent_id:
                    with self._lock:
                        active = resolved.agent_id in self._agents
                        inactive = resolved.agent_id in self._inactive
                    if active:
                        self._emit(
                            "startup-agent-skip",
                            agent_id=resolved.agent_id,
                            class_name=class_name,
                            data={"reason": "already-active"},
                        )
                        continue
                    if inactive:
                        self.activate(resolved.agent_id)
                        self._emit(
                            "startup-agent-activate",
                            agent_id=resolved.agent_id,
                            class_name=class_name,
                            data={"source": "launch-config"},
                        )
                        continue

                proxy = self.create(
                    resolved.agent_cls,
                    resolved.state,
                    init=resolved.init,
                    agent_id=resolved.agent_id,
                )
                self._emit(
                    "startup-agent-create",
                    agent_id=proxy.agent_id,
                    class_name=class_name,
                    data={"source": "launch-config"},
                )
            except Exception as exc:
                self._emit(
                    "startup-agent-failed",
                    agent_id=startup_agent.agent_id,
                    data={
                        "use": startup_agent.use,
                        "class": startup_agent.class_name,
                        "error": str(exc),
                    },
                )

    def _emit(
        self,
        kind: str,
        *,
        agent_id: str | None = None,
        class_name: str | None = None,
        message_id: str | None = None,
        service_name: str | None = None,
        data: dict[str, Any] | None = None,
        error: str | None = None,
    ) -> ContextEvent:
        return self._events.emit(
            kind=kind,
            host_name=self.name,
            host_address=self.address,
            agent_id=agent_id,
            class_name=class_name,
            message_id=message_id,
            service_name=service_name,
            data=data or {},
            error=error,
        )

    @staticmethod
    def _safe_host_name(name: str) -> str:
        return "".join(char if char.isalnum() or char in "._-" else "_" for char in name) or "host"

paglets.runtime.lifecycle

paglets.runtime.resident_services

paglets.runtime.child_calls

paglets.runtime.inactive_records

paglets.runtime.http_api

paglets.runtime.relay

paglets.runtime.binding

paglets.runtime.process_runtime

ChildProcessController

Parent-side controller for one isolated paglet child process.

Source code in src/paglets/runtime/process_controller.py
class ChildProcessController:
    """Parent-side controller for one isolated paglet child process."""

    def __init__(
        self,
        config: ChildConfig,
        *,
        host_call_handler: Callable[[str, dict[str, Any]], Any],
        crash_handler: Callable[[ChildProcessController], None],
    ):
        self.config = config
        self.agent_id = config.agent_id
        self.agent_class_name = config.agent_class_name
        self.state_class_name = config.state_class_name
        self.state: dict[str, Any] = dict(config.state or {})
        self.resource_status: dict[str, bool] = {}
        self.ready = False
        self.crashed = False
        self.exitcode: int | None = None
        self.last_error = ""
        self.departing = False
        self._host_call_handler = host_call_handler
        self._crash_handler = crash_handler
        self._pending: dict[str, Future[Any]] = {}
        self._pending_ops: dict[str, str] = {}
        self._pending_lock = threading.Lock()
        self._send_lock = threading.Lock()
        self._closed = threading.Event()
        self._process_closed = False
        self._terminal_message_result: Any = None
        self._has_terminal_message_result = False
        self._terminal_host_call_complete = threading.Event()
        self._terminal_host_call_complete.set()
        self._run_complete = threading.Event()
        self._run_complete.set()
        context = mp.get_context("spawn")
        parent_conn, child_conn = context.Pipe(duplex=True)
        self._conn = parent_conn
        self.process = context.Process(
            target=_child_main,
            args=(config, child_conn),
            name=config.process_title,
            daemon=True,
        )
        self.process.start()
        self._pid = self.process.pid
        child_conn.close()
        self._reader = threading.Thread(
            target=self._reader_loop,
            name=f"paglets-child-reader-{self.agent_id[:8]}",
            daemon=True,
        )
        self._reader.start()

    @property
    def pid(self) -> int | None:
        return self._pid

    def terminal_proxy_wire(self) -> dict[str, str] | None:
        if not self._has_terminal_message_result or not isinstance(self._terminal_message_result, dict):
            return None
        if "host_url" not in self._terminal_message_result or "agent_id" not in self._terminal_message_result:
            return None
        return {
            "host_url": str(self._terminal_message_result["host_url"]),
            "agent_id": str(self._terminal_message_result["agent_id"]),
        }

    def set_terminal_proxy_wire(self, proxy: dict[str, Any]) -> None:
        self._has_terminal_message_result = True
        self._terminal_message_result = {
            "host_url": str(proxy["host_url"]),
            "agent_id": str(proxy["agent_id"]),
        }

    def request(self, op: str, payload: dict[str, Any] | None = None, *, timeout: float | None = None) -> Any:
        if self._closed.is_set():
            raise PagletCrashedError(f"Paglet {self.agent_id!r} is not running")
        request_id = uuid.uuid4().hex
        future: Future[Any] = Future()
        with self._pending_lock:
            self._pending[request_id] = future
            self._pending_ops[request_id] = op
        try:
            self._send({"type": "request", "id": request_id, "op": op, "payload": payload or {}})
        except Exception:
            with self._pending_lock:
                self._pending.pop(request_id, None)
                self._pending_ops.pop(request_id, None)
            raise
        return future.result(timeout=timeout)

    def request_lifecycle(self, name: str, event: dict[str, Any]) -> dict[str, Any]:
        if name in {"arrival"}:
            self._run_complete.clear()
        reply = self.request("lifecycle", {"name": name, "event": event})
        self._update_from_reply(reply)
        return dict(reply)

    def wait_for_run_complete_or_departure(self, *, timeout: float = 30.0) -> None:
        deadline = time.monotonic() + max(0.0, timeout)
        while not self.departing and not self._closed.is_set():
            remaining = deadline - time.monotonic()
            if remaining <= 0:
                return
            if self._run_complete.wait(min(0.05, remaining)):
                return
        if self.departing and not self._terminal_host_call_complete.is_set():
            remaining = deadline - time.monotonic()
            if remaining > 0:
                self._terminal_host_call_complete.wait(remaining)

    def request_message(self, message: Message, *, oneway: bool = False) -> Any:
        reply = self.request("message", {"message": message.to_wire(), "oneway": oneway})
        self._update_from_reply(reply)
        return None if oneway else reply.get("result")

    def fetch_state(self, *, timeout: float | None = None) -> dict[str, Any]:
        reply = self.request("state", timeout=timeout)
        self._update_from_reply(reply)
        return dict(self.state)

    def cleanup_resources(self, *, reason: str) -> dict[str, Any]:
        reply = self.request("cleanup_resources", {"reason": reason})
        self._update_from_reply(reply)
        return dict(reply)

    def resource_status_snapshot(self) -> dict[str, bool]:
        try:
            reply = self.request("resource_status", timeout=2.0)
            self._update_from_reply(reply)
        except Exception:
            pass
        return dict(self.resource_status)

    def shutdown(self, *, graceful: bool = True, timeout: float = 2.0) -> None:
        if self._closed.is_set():
            return
        if graceful:
            with contextlib.suppress(Exception):
                self.request("shutdown", timeout=timeout)
        self._closed.set()
        with contextlib.suppress(Exception):
            self._conn.close()

    def terminate(self, *, timeout: float = 2.0, kill_timeout: float = 1.0) -> None:
        self.shutdown(graceful=True, timeout=timeout)
        if self._process_closed:
            self._closed.set()
            return
        if self._is_process_alive():
            self.process.terminate()
            self.process.join(timeout=timeout)
        if self._is_process_alive():
            self.process.kill()
            self.process.join(timeout=kill_timeout)
        self.exitcode = self._safe_exitcode()
        self._close_process_handle()
        self._closed.set()

    def _send(self, message: dict[str, Any]) -> None:
        with self._send_lock:
            self._conn.send(message)

    def _reader_loop(self) -> None:
        try:
            while not self._closed.is_set():
                try:
                    message = self._conn.recv()
                except EOFError:
                    break
                except TypeError:
                    break
                if not isinstance(message, dict):
                    continue
                kind = message.get("type")
                if kind == "reply":
                    self._complete_reply(message)
                elif kind == "host_call":
                    threading.Thread(
                        target=self._handle_host_call,
                        args=(message,),
                        name=f"paglets-host-call-{self.agent_id[:8]}",
                        daemon=True,
                    ).start()
                elif kind == "event":
                    if message.get("event") == "run_complete":
                        self._run_complete.set()
                    _handle_local_pickle_stream_event(message)
                    continue
        except OSError:
            pass
        finally:
            with contextlib.suppress(Exception):
                self.process.join(timeout=0.5)
            self.exitcode = self._safe_exitcode()
            self._close_process_handle()
            if not self.departing and self.exitcode not in (0, None):
                self._mark_crashed(f"process exited with code {self.exitcode}")
            self._fail_pending(PagletCrashedError(f"Paglet {self.agent_id!r} process exited"))
            self._closed.set()
            if self.crashed:
                self._crash_handler(self)

    def _close_process_handle(self) -> None:
        return

    def _is_process_alive(self) -> bool:
        if self._process_closed:
            return False
        try:
            return self.process.is_alive()
        except ValueError:
            self._process_closed = True
            return False

    def _safe_exitcode(self) -> int | None:
        if self._process_closed:
            return self.exitcode
        try:
            return self.process.exitcode
        except ValueError:
            self._process_closed = True
            return self.exitcode

    def _complete_reply(self, message: dict[str, Any]) -> None:
        request_id = str(message.get("id") or "")
        with self._pending_lock:
            future = self._pending.pop(request_id, None)
            self._pending_ops.pop(request_id, None)
        if future is None:
            return
        if message.get("ok", False):
            token = _state_stream_token(message.get("payload"))
            payload = _materialize_state_stream(message.get("payload"))
            if token:
                self._send({"type": "event", "event": "local_pickle_stream_received", "token": token})
            future.set_result(payload)
            return
        future.set_exception(_error_from_wire(message.get("error") or {}))

    def _handle_host_call(self, message: dict[str, Any]) -> None:
        request_id = str(message.get("id") or "")
        op = str(message.get("op") or "")
        is_terminal_op = op in {"complete_dispatch", "complete_deactivate", "complete_dispose"}
        if is_terminal_op:
            self._terminal_host_call_complete.clear()
        try:
            raw_payload = dict(message.get("payload") or {})
            token = _state_stream_token(raw_payload)
            request_payload = _materialize_state_stream(raw_payload)
            if token:
                self._send({"type": "event", "event": "local_pickle_stream_received", "token": token})
            payload = self._host_call_handler(op, request_payload)
            if is_terminal_op:
                self._has_terminal_message_result = True
                self._terminal_message_result = payload.get("proxy") if isinstance(payload, dict) else None
        except Exception as exc:
            reply = {"type": "reply", "id": request_id, "ok": False, "error": _error_to_wire(exc)}
        else:
            reply = {"type": "reply", "id": request_id, "ok": True, "payload": payload}
        finally:
            if is_terminal_op:
                self._terminal_host_call_complete.set()
        try:
            self._send(reply)
        except Exception:
            self._mark_crashed("could not reply to child host call")

    def _update_from_reply(self, reply: dict[str, Any] | None) -> None:
        if not isinstance(reply, dict):
            return
        if "state" in reply and isinstance(reply["state"], dict):
            self.state = dict(reply["state"])
        if "resources" in reply and isinstance(reply["resources"], dict):
            self.resource_status = {str(key): bool(value) for key, value in reply["resources"].items()}

    def _mark_crashed(self, error: str) -> None:
        self.crashed = True
        self.last_error = error

    def _fail_pending(self, exc: Exception) -> None:
        with self._pending_lock:
            pending = list(self._pending.items())
            pending_ops = {request_id: self._pending_ops.get(request_id, "") for request_id, _ in pending}
            self._pending.clear()
            self._pending_ops.clear()
        for request_id, future in pending:
            if not future.done():
                if self.departing and self._has_terminal_message_result and pending_ops.get(request_id) == "message":
                    future.set_result(
                        {
                            "state": dict(self.state),
                            "resources": dict(self.resource_status),
                            "result": self._terminal_message_result,
                        }
                    )
                else:
                    future.set_exception(exc)

paglets.runtime.process_controller

ChildProcessController

Parent-side controller for one isolated paglet child process.

Source code in src/paglets/runtime/process_controller.py
class ChildProcessController:
    """Parent-side controller for one isolated paglet child process."""

    def __init__(
        self,
        config: ChildConfig,
        *,
        host_call_handler: Callable[[str, dict[str, Any]], Any],
        crash_handler: Callable[[ChildProcessController], None],
    ):
        self.config = config
        self.agent_id = config.agent_id
        self.agent_class_name = config.agent_class_name
        self.state_class_name = config.state_class_name
        self.state: dict[str, Any] = dict(config.state or {})
        self.resource_status: dict[str, bool] = {}
        self.ready = False
        self.crashed = False
        self.exitcode: int | None = None
        self.last_error = ""
        self.departing = False
        self._host_call_handler = host_call_handler
        self._crash_handler = crash_handler
        self._pending: dict[str, Future[Any]] = {}
        self._pending_ops: dict[str, str] = {}
        self._pending_lock = threading.Lock()
        self._send_lock = threading.Lock()
        self._closed = threading.Event()
        self._process_closed = False
        self._terminal_message_result: Any = None
        self._has_terminal_message_result = False
        self._terminal_host_call_complete = threading.Event()
        self._terminal_host_call_complete.set()
        self._run_complete = threading.Event()
        self._run_complete.set()
        context = mp.get_context("spawn")
        parent_conn, child_conn = context.Pipe(duplex=True)
        self._conn = parent_conn
        self.process = context.Process(
            target=_child_main,
            args=(config, child_conn),
            name=config.process_title,
            daemon=True,
        )
        self.process.start()
        self._pid = self.process.pid
        child_conn.close()
        self._reader = threading.Thread(
            target=self._reader_loop,
            name=f"paglets-child-reader-{self.agent_id[:8]}",
            daemon=True,
        )
        self._reader.start()

    @property
    def pid(self) -> int | None:
        return self._pid

    def terminal_proxy_wire(self) -> dict[str, str] | None:
        if not self._has_terminal_message_result or not isinstance(self._terminal_message_result, dict):
            return None
        if "host_url" not in self._terminal_message_result or "agent_id" not in self._terminal_message_result:
            return None
        return {
            "host_url": str(self._terminal_message_result["host_url"]),
            "agent_id": str(self._terminal_message_result["agent_id"]),
        }

    def set_terminal_proxy_wire(self, proxy: dict[str, Any]) -> None:
        self._has_terminal_message_result = True
        self._terminal_message_result = {
            "host_url": str(proxy["host_url"]),
            "agent_id": str(proxy["agent_id"]),
        }

    def request(self, op: str, payload: dict[str, Any] | None = None, *, timeout: float | None = None) -> Any:
        if self._closed.is_set():
            raise PagletCrashedError(f"Paglet {self.agent_id!r} is not running")
        request_id = uuid.uuid4().hex
        future: Future[Any] = Future()
        with self._pending_lock:
            self._pending[request_id] = future
            self._pending_ops[request_id] = op
        try:
            self._send({"type": "request", "id": request_id, "op": op, "payload": payload or {}})
        except Exception:
            with self._pending_lock:
                self._pending.pop(request_id, None)
                self._pending_ops.pop(request_id, None)
            raise
        return future.result(timeout=timeout)

    def request_lifecycle(self, name: str, event: dict[str, Any]) -> dict[str, Any]:
        if name in {"arrival"}:
            self._run_complete.clear()
        reply = self.request("lifecycle", {"name": name, "event": event})
        self._update_from_reply(reply)
        return dict(reply)

    def wait_for_run_complete_or_departure(self, *, timeout: float = 30.0) -> None:
        deadline = time.monotonic() + max(0.0, timeout)
        while not self.departing and not self._closed.is_set():
            remaining = deadline - time.monotonic()
            if remaining <= 0:
                return
            if self._run_complete.wait(min(0.05, remaining)):
                return
        if self.departing and not self._terminal_host_call_complete.is_set():
            remaining = deadline - time.monotonic()
            if remaining > 0:
                self._terminal_host_call_complete.wait(remaining)

    def request_message(self, message: Message, *, oneway: bool = False) -> Any:
        reply = self.request("message", {"message": message.to_wire(), "oneway": oneway})
        self._update_from_reply(reply)
        return None if oneway else reply.get("result")

    def fetch_state(self, *, timeout: float | None = None) -> dict[str, Any]:
        reply = self.request("state", timeout=timeout)
        self._update_from_reply(reply)
        return dict(self.state)

    def cleanup_resources(self, *, reason: str) -> dict[str, Any]:
        reply = self.request("cleanup_resources", {"reason": reason})
        self._update_from_reply(reply)
        return dict(reply)

    def resource_status_snapshot(self) -> dict[str, bool]:
        try:
            reply = self.request("resource_status", timeout=2.0)
            self._update_from_reply(reply)
        except Exception:
            pass
        return dict(self.resource_status)

    def shutdown(self, *, graceful: bool = True, timeout: float = 2.0) -> None:
        if self._closed.is_set():
            return
        if graceful:
            with contextlib.suppress(Exception):
                self.request("shutdown", timeout=timeout)
        self._closed.set()
        with contextlib.suppress(Exception):
            self._conn.close()

    def terminate(self, *, timeout: float = 2.0, kill_timeout: float = 1.0) -> None:
        self.shutdown(graceful=True, timeout=timeout)
        if self._process_closed:
            self._closed.set()
            return
        if self._is_process_alive():
            self.process.terminate()
            self.process.join(timeout=timeout)
        if self._is_process_alive():
            self.process.kill()
            self.process.join(timeout=kill_timeout)
        self.exitcode = self._safe_exitcode()
        self._close_process_handle()
        self._closed.set()

    def _send(self, message: dict[str, Any]) -> None:
        with self._send_lock:
            self._conn.send(message)

    def _reader_loop(self) -> None:
        try:
            while not self._closed.is_set():
                try:
                    message = self._conn.recv()
                except EOFError:
                    break
                except TypeError:
                    break
                if not isinstance(message, dict):
                    continue
                kind = message.get("type")
                if kind == "reply":
                    self._complete_reply(message)
                elif kind == "host_call":
                    threading.Thread(
                        target=self._handle_host_call,
                        args=(message,),
                        name=f"paglets-host-call-{self.agent_id[:8]}",
                        daemon=True,
                    ).start()
                elif kind == "event":
                    if message.get("event") == "run_complete":
                        self._run_complete.set()
                    _handle_local_pickle_stream_event(message)
                    continue
        except OSError:
            pass
        finally:
            with contextlib.suppress(Exception):
                self.process.join(timeout=0.5)
            self.exitcode = self._safe_exitcode()
            self._close_process_handle()
            if not self.departing and self.exitcode not in (0, None):
                self._mark_crashed(f"process exited with code {self.exitcode}")
            self._fail_pending(PagletCrashedError(f"Paglet {self.agent_id!r} process exited"))
            self._closed.set()
            if self.crashed:
                self._crash_handler(self)

    def _close_process_handle(self) -> None:
        return

    def _is_process_alive(self) -> bool:
        if self._process_closed:
            return False
        try:
            return self.process.is_alive()
        except ValueError:
            self._process_closed = True
            return False

    def _safe_exitcode(self) -> int | None:
        if self._process_closed:
            return self.exitcode
        try:
            return self.process.exitcode
        except ValueError:
            self._process_closed = True
            return self.exitcode

    def _complete_reply(self, message: dict[str, Any]) -> None:
        request_id = str(message.get("id") or "")
        with self._pending_lock:
            future = self._pending.pop(request_id, None)
            self._pending_ops.pop(request_id, None)
        if future is None:
            return
        if message.get("ok", False):
            token = _state_stream_token(message.get("payload"))
            payload = _materialize_state_stream(message.get("payload"))
            if token:
                self._send({"type": "event", "event": "local_pickle_stream_received", "token": token})
            future.set_result(payload)
            return
        future.set_exception(_error_from_wire(message.get("error") or {}))

    def _handle_host_call(self, message: dict[str, Any]) -> None:
        request_id = str(message.get("id") or "")
        op = str(message.get("op") or "")
        is_terminal_op = op in {"complete_dispatch", "complete_deactivate", "complete_dispose"}
        if is_terminal_op:
            self._terminal_host_call_complete.clear()
        try:
            raw_payload = dict(message.get("payload") or {})
            token = _state_stream_token(raw_payload)
            request_payload = _materialize_state_stream(raw_payload)
            if token:
                self._send({"type": "event", "event": "local_pickle_stream_received", "token": token})
            payload = self._host_call_handler(op, request_payload)
            if is_terminal_op:
                self._has_terminal_message_result = True
                self._terminal_message_result = payload.get("proxy") if isinstance(payload, dict) else None
        except Exception as exc:
            reply = {"type": "reply", "id": request_id, "ok": False, "error": _error_to_wire(exc)}
        else:
            reply = {"type": "reply", "id": request_id, "ok": True, "payload": payload}
        finally:
            if is_terminal_op:
                self._terminal_host_call_complete.set()
        try:
            self._send(reply)
        except Exception:
            self._mark_crashed("could not reply to child host call")

    def _update_from_reply(self, reply: dict[str, Any] | None) -> None:
        if not isinstance(reply, dict):
            return
        if "state" in reply and isinstance(reply["state"], dict):
            self.state = dict(reply["state"])
        if "resources" in reply and isinstance(reply["resources"], dict):
            self.resource_status = {str(key): bool(value) for key, value in reply["resources"].items()}

    def _mark_crashed(self, error: str) -> None:
        self.crashed = True
        self.last_error = error

    def _fail_pending(self, exc: Exception) -> None:
        with self._pending_lock:
            pending = list(self._pending.items())
            pending_ops = {request_id: self._pending_ops.get(request_id, "") for request_id, _ in pending}
            self._pending.clear()
            self._pending_ops.clear()
        for request_id, future in pending:
            if not future.done():
                if self.departing and self._has_terminal_message_result and pending_ops.get(request_id) == "message":
                    future.set_result(
                        {
                            "state": dict(self.state),
                            "resources": dict(self.resource_status),
                            "result": self._terminal_message_result,
                        }
                    )
                else:
                    future.set_exception(exc)

paglets.runtime.child_endpoint

paglets.runtime.child_facade

paglets.runtime.child_bootstrap

paglets.runtime.process_protocol

paglets.runtime.mailbox

MessageMailbox

Priority mailbox for one paglet.

Source code in src/paglets/runtime/mailbox.py
class MessageMailbox:
    """Priority mailbox for one paglet."""

    def __init__(self, agent_id: str, handler: Callable[[Message, bool], Any], *, max_workers: int = 4):
        if max_workers < 1:
            raise ValueError("max_workers must be at least 1")
        self.agent_id = agent_id
        self._handler = handler
        self._max_workers = max_workers
        self._executor = ThreadPoolExecutor(
            max_workers=max_workers + 4,
            thread_name_prefix=f"paglets-mailbox-{agent_id[:8]}",
        )
        self._condition = threading.Condition()
        self._queue: list[tuple[int, int, Message, bool, Future[Any]]] = []
        self._sequence = itertools.count()
        self._closed = False
        self._running = 0
        self._in_flight = 0
        self._delivered = 0
        self._failed = 0

    def submit(self, message: Message, *, oneway: bool = False) -> Future[Any]:
        future: Future[Any] = Future()
        with self._condition:
            if self._closed:
                future.set_exception(RuntimeError(f"Mailbox for {self.agent_id} is closed"))
                return future
            heapq.heappush(self._queue, (-message.priority, next(self._sequence), message, oneway, future))
            self._condition.notify_all()
        self._schedule()
        return future

    def submit_unqueued(self, message: Message, *, oneway: bool = False) -> Future[Any]:
        return self._executor.submit(self._run_message, message, oneway)

    def wait_message(self, timeout: float | None = None) -> bool:
        with self._condition:
            return self._condition.wait(timeout)

    def notify_message(self) -> None:
        with self._condition:
            self._condition.notify(1)

    def notify_all_messages(self) -> None:
        with self._condition:
            self._condition.notify_all()

    def status(self) -> MailboxStatus:
        with self._condition:
            return MailboxStatus(
                queued_count=len(self._queue),
                in_flight_count=self._in_flight,
                delivered_count=self._delivered,
                failed_count=self._failed,
            )

    def close(self) -> None:
        with self._condition:
            self._closed = True
            while self._queue:
                _, _, _, _, future = heapq.heappop(self._queue)
                if not future.done():
                    future.set_exception(RuntimeError(f"Mailbox for {self.agent_id} is closed"))
            self._condition.notify_all()
        self._executor.shutdown(wait=False, cancel_futures=True)

    def _schedule(self) -> None:
        submissions = 0
        with self._condition:
            while self._queue and self._running + submissions < self._max_workers:
                submissions += 1
        for _ in range(submissions):
            self._executor.submit(self._run_next)

    def _run_next(self) -> None:
        with self._condition:
            if not self._queue:
                return
            self._running += 1
            _, _, message, oneway, future = heapq.heappop(self._queue)
            self._in_flight += 1
        try:
            result = self._handler(message, oneway)
        except Exception as exc:
            with self._condition:
                self._failed += 1
                self._in_flight -= 1
                self._running -= 1
                self._condition.notify_all()
            future.set_exception(exc)
        else:
            with self._condition:
                self._delivered += 1
                self._in_flight -= 1
                self._running -= 1
                self._condition.notify_all()
            future.set_result(result)
        self._schedule()

    def _run_message(self, message: Message, oneway: bool) -> Any:
        with self._condition:
            self._in_flight += 1
        try:
            result = self._handler(message, oneway)
        except Exception:
            with self._condition:
                self._failed += 1
                self._in_flight -= 1
                self._condition.notify_all()
            raise
        with self._condition:
            self._delivered += 1
            self._in_flight -= 1
            self._condition.notify_all()
        return result

paglets.runtime.envelope

PagletEnvelope dataclass

Serialized mobile-object envelope transferred between hosts.

Source code in src/paglets/runtime/envelope.py
@dataclass(slots=True)
class PagletEnvelope:
    """Serialized mobile-object envelope transferred between hosts."""

    kind: EnvelopeKind
    agent_id: str
    agent_class_name: str
    state_class_name: str
    state: dict[str, Any]
    source_host_name: str
    source_host_address: str
    target_host_name: str
    target_host_address: str
    clone_of: str | None = None
    metadata: dict[str, Any] = field(default_factory=dict)

    def __post_init__(self) -> None:
        require_enum(self.kind, EnvelopeKind, "kind")

    def to_wire(self) -> dict[str, Any]:
        return {
            "kind": self.kind.value,
            "agent_id": self.agent_id,
            "agent_class_name": self.agent_class_name,
            "state_class_name": self.state_class_name,
            "state": self.state,
            "source_host_name": self.source_host_name,
            "source_host_address": self.source_host_address,
            "target_host_name": self.target_host_name,
            "target_host_address": self.target_host_address,
            "clone_of": self.clone_of,
            "metadata": self.metadata,
        }

    @classmethod
    def from_wire(cls, payload: dict[str, Any]) -> PagletEnvelope:
        return cls(
            kind=enum_from_wire(payload["kind"], EnvelopeKind, "kind"),
            agent_id=payload["agent_id"],
            agent_class_name=payload["agent_class_name"],
            state_class_name=payload["state_class_name"],
            state=dict(payload["state"]),
            source_host_name=payload["source_host_name"],
            source_host_address=payload["source_host_address"],
            target_host_name=payload["target_host_name"],
            target_host_address=payload["target_host_address"],
            clone_of=payload.get("clone_of"),
            metadata=dict(payload.get("metadata") or {}),
        )

paglets.runtime.resources

ResourceCleanupError

Bases: LifecycleError

Raised when lifecycle-managed resource cleanup fails.

Source code in src/paglets/runtime/resources.py
class ResourceCleanupError(LifecycleError):
    """Raised when lifecycle-managed resource cleanup fails."""

    def __init__(self, failures: dict[str, Exception]):
        self.failures = failures
        details = ", ".join(f"{name}: {exc}" for name, exc in failures.items())
        super().__init__(f"Resource cleanup failed for {details}")

ResourceRegistry

Lifecycle-managed cleanup callbacks owned by one paglet.

Source code in src/paglets/runtime/resources.py
class ResourceRegistry:
    """Lifecycle-managed cleanup callbacks owned by one paglet."""

    def __init__(self):
        self._resources: OrderedDict[str, ResourceRegistration] = OrderedDict()

    def register(self, name: str, cleanup: Cleanup, *, suppress: bool = False) -> None:
        if not name:
            raise ValueError("Resource name cannot be empty")
        self._resources[name] = ResourceRegistration(name=name, cleanup=cleanup, suppress=suppress)

    def track_closeable(self, name: str, obj: object, *, method: str = "close", suppress: bool = False) -> None:
        cleanup = getattr(obj, method)
        if not callable(cleanup):
            raise TypeError(f"{obj!r}.{method} is not callable")
        self.register(name, cleanup, suppress=suppress)

    def remove(self, name: str) -> None:
        self._resources.pop(name, None)

    def cleanup(self, *, reason: str = "lifecycle") -> None:
        failures: dict[str, Exception] = {}
        for name, registration in reversed(list(self._resources.items())):
            try:
                registration.cleanup()
            except Exception as exc:
                if not registration.suppress:
                    failures[name] = exc
                else:
                    self._resources.pop(name, None)
            else:
                self._resources.pop(name, None)
        if failures:
            raise ResourceCleanupError(failures)

    def clear(self) -> None:
        self._resources.clear()

    def status(self) -> dict[str, bool]:
        return {name: registration.suppress for name, registration in self._resources.items()}
  • Core covers the paglet programming model.
  • Remote covers HTTP transport and proxies.
  • Persistence covers inactive records and storage.