@johnhenry/browsermesh-apps 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -18,12 +18,18 @@ Application layer for BrowserMesh: marketplace, chat, payments, compute orchestr
18
18
  - [CloudStorage bucket authorization and key distribution](#cloudstorage-bucket-authorization-and-key-distribution)
19
19
  - [CloudStorage: the ergonomic SDK](#cloudstorage-the-ergonomic-sdk)
20
20
  - [Torrent service: durable stores, authorization and serve limits](#torrent-service-durable-stores-authorization-and-serve-limits)
21
+ - [Downloading: `onManifest`, `onProgress`, concurrency, bounds](#downloading-onmanifest-onprogress-concurrency-bounds)
22
+ - [Using real WebTorrent](#using-real-webtorrent)
23
+ - [Ledgers and escrow: which class is which](#ledgers-and-escrow-which-class-is-which)
21
24
  - [Putting it all together: sync + kernel-gated mesh + relay on one connection](#putting-it-all-together-sync--kernel-gated-mesh--relay-on-one-connection)
22
25
  - [Sending to peers: wire format, the bulk lane and `broadcast()`](#sending-to-peers-wire-format-the-bulk-lane-and-broadcast)
23
26
  - [`fetch()`/`WebSocket`-shaped mesh access: `browserMeshFetch` and `BrowserMeshWebSocket`](#fetchwebsocket-shaped-mesh-access-browsermeshfetch-and-browsermeshwebsocket)
24
27
  - [`browserMeshFetch`](#browsermeshfetch)
25
28
  - [`BrowserMeshWebSocket`](#browsermeshwebsocket)
26
29
  - [LLM tool-calling: `BrowserToolRegistry` and `createAgentRuntime`](#llm-tool-calling-browsertoolregistry-and-createagentruntime)
30
+ - [IoT tools (opt-in)](#iot-tools-opt-in)
31
+ - [Runtime classes and placement lanes](#runtime-classes-and-placement-lanes)
32
+ - [Pod host service: spawning and controlling hosted pods](#pod-host-service-spawning-and-controlling-hosted-pods)
27
33
  - [License](#license)
28
34
 
29
35
  ## Provenance
@@ -38,7 +44,7 @@ Extracted from the private `clawser` monorepo (previously `packages/browsermesh-
38
44
  | apps | `AppRegistry`, `AppStore`, `AppRPC`, `AppEventBus` |
39
45
  | marketplace | `Marketplace`, `MarketplaceIndex`, `ServiceListing` |
40
46
  | chat | `MeshChat`, `ChatRoom`, `ChatMessage` |
41
- | payments | `PaymentChannel`, `EscrowManager`, `CreditLedger`, `PaymentRouter` |
47
+ | payments | `PaymentChannel`, `CreditLedger` (single-owner), `SimpleEscrowBook`, `PaymentRouter` (see [Ledgers and escrow](#ledgers-and-escrow-which-class-is-which)) |
42
48
  | quotas | `QuotaManager`, `QuotaEnforcer` |
43
49
  | resources | `ResourceRegistry`, `ComputeRequest`, `ResourceScorer`, `JobQueue` |
44
50
  | gpu | `TrainingOrchestrator`, `GpuProbe`, `GradientAggregator` |
@@ -48,11 +54,11 @@ Extracted from the private `clawser` monorepo (previously `packages/browsermesh-
48
54
  | mesh-orchestrator | `createOrchestratorService` (`MeshService` wrapper: real, gated wire dispatch for `execOnPod`/`deploySkill`/`drainPod`, ungated local aggregation for `listPods`/`getPodStatus`/`topPods`) |
49
55
  | compat | `BrowserTool`, `BrowserToolRegistry` (base class + registry an LLM-drivable agent loop dispatches tool calls through) |
50
56
  | agent-runtime | `createAgentRuntime` (the LLM tool-calling dispatch loop: bring-your-own `llmFn`, real registry-backed tool execution) |
51
- | mesh-orchestrator-tools | `registerOrchestratorTools`, `createOrchestratorToolRegistry` (wires the 8 real `Meshctl*Tool`s into a `BrowserToolRegistry` against a real, attached `MeshOrchestrator`) |
57
+ | mesh-orchestrator-tools | `registerOrchestratorTools`, `createOrchestratorToolRegistry` (wires the 15 real `Meshctl*Tool`s into a `BrowserToolRegistry` against a real, attached `MeshOrchestrator`) |
52
58
  | audit | `AuditChain`, `AuditStore`, `detectFork`, `buildMerkleRoot` |
53
59
  | visualizations | `TopologyLayout`, `TrustGraphLayout`, `TrustHeatmap` |
54
60
  | devtools | `MeshInspector`, `MeshInspectTool` |
55
- | tools | `registerMeshTools` + stream/file/DHT/GPU/IoT BrowserTool subclasses |
61
+ | tools | `registerMeshTools` + stream/file/DHT/GPU BrowserTool subclasses; the IoT tools register only when you pass an IoT bridge (see [IoT tools](#iot-tools-opt-in)) |
56
62
  | peer-agent | `AgentHost`, `AgentClient`, `bridgePeerAgent` |
57
63
  | peer-agent-swarm | `AgentSwarmCoordinator` |
58
64
  | peer-chat | `PeerChat` |
@@ -64,7 +70,7 @@ Extracted from the private `clawser` monorepo (previously `packages/browsermesh-
64
70
  | peer-ipfs | `IPFSStore` (also exported as `MeshLocalCidStore`): a mesh-local content-addressed store. CIDs are SHA-256 hex digests, not IPFS CIDs, and nothing talks to the IPFS network |
65
71
  | peer-node | `PeerNode` |
66
72
  | peer-node-transport | `createPeerNodeTransport` |
67
- | peer-payments | `CreditLedger`, `WebLNProvider` |
73
+ | peer-payments | `MultiPartyCreditLedger`, `WebLNProvider` |
68
74
  | peer-registry | `PeerRegistry` |
69
75
  | peer-routing | `MeshRouter`, `ServerSharing` |
70
76
  | peer-services | `ServiceAdvertiser`, `ServiceBrowser` |
@@ -394,7 +400,77 @@ const info = await torrent.api.seed('some text') // strings are UTF-8 encoded
394
400
  downloaders back off and retry. Caps and `authorize` never apply to the
395
401
  downloading side.
396
402
  - Events: `torrent:chunk-served`, `torrent:chunk-received` (as before), plus
397
- `torrent:request-denied` and `torrent:serve-busy`.
403
+ `torrent:request-denied`, `torrent:serve-busy` and `torrent:download-failed`.
404
+
405
+ ### Downloading: `onManifest`, `onProgress`, concurrency, bounds
406
+
407
+ ```js
408
+ const { data, info } = await torrent.api.download(magnetURI, {
409
+ peers: [seederPubKey],
410
+ // Awaited once the manifest is known and BEFORE any piece is requested or
411
+ // stored: a quota gate. Return false (or throw) to abort; nothing is fetched.
412
+ onManifest: async (manifest) => manifest.size <= await myQuota.remaining(),
413
+ // Once per piece: { received, total, bytes, size, cid, from } (from is null
414
+ // for a piece already in the local store). A throw in here is logged only.
415
+ onProgress: ({ received, total, bytes, size }) => bar.set(bytes / size),
416
+ concurrency: 4, // pieces in flight, 1-32; 1 is strictly sequential
417
+ })
418
+ ```
419
+
420
+ - **`onManifest(manifest)`** gets a copy with `magnetURI`, `infoHash`, `name`,
421
+ `size`, `chunkSize`, `chunkCids`, `cid`. Returning `false` rejects the download
422
+ with `err.code === 'manifest-rejected'`; a throw or rejection propagates as
423
+ is; any other return value lets it proceed.
424
+ - **`concurrency`** defaults to the service's `downloadConcurrency` (4). Each
425
+ provider is still held to its own serve caps: a `busy` answer is retried with
426
+ backoff (`busyRetries`, `busyBackoffMs`) rather than failing the download.
427
+ - **Cleanup.** If a download fails after storing some pieces, the pieces that
428
+ call wrote itself, and that no held torrent lists, are removed again, so a host
429
+ that accounts for storage stays consistent. Pieces already in the store before
430
+ the download are never touched.
431
+ - **Remote manifests are bounded.** A manifest another peer announces or sends
432
+ is ignored (and its sender recorded as nobody's provider) unless it lists at
433
+ most `maxManifestChunks` pieces (default 16384), declares at most
434
+ `maxManifestSize` bytes (default unlimited), has only 64-hex SHA-256 piece
435
+ CIDs, and has a piece count that matches its size (`ceil(size / chunkSize)`).
436
+ At most `maxRemoteManifests` (default 64) are remembered: the least recently
437
+ used is forgotten together with the providers recorded only for its pieces. A
438
+ manifest an in-flight download is using is never evicted.
439
+
440
+ ### Using real WebTorrent
441
+
442
+ `TorrentManager` and `createTorrentService()` never load anything from the
443
+ network. For real BitTorrent swarming give them the library:
444
+
445
+ ```js
446
+ import WebTorrent from 'webtorrent'
447
+ createTorrentService({ webtorrent: WebTorrent }) // the class: built and destroyed for you
448
+ createTorrentService({ webtorrent: new WebTorrent() }) // or a client of your own, left running on destroy()
449
+ ```
450
+
451
+ `window.WebTorrent` / `globalThis.WebTorrent` is still picked up when present.
452
+ With neither, `available` is `false` and the in-memory mesh-native path is used
453
+ (the one `createTorrentService()` serves from anyway). Earlier releases
454
+ imported `webtorrent` from `esm.sh` on first use, which hangs offline and fails
455
+ under a strict CSP; that import is gone.
456
+
457
+ ## Ledgers and escrow: which class is which
458
+
459
+ Four classes cover two ideas, and each public name belongs to exactly one:
460
+
461
+ | Name | Module | Model | Use it for |
462
+ | --- | --- | --- | --- |
463
+ | `CreditLedger` | `payments.mjs` | **Canonical ledger.** One pod, one balance: `credit(amount, from)`, `debit(amount, to)`, `transfer(peerLedger, amount)`, every change an immutable entry. | A pod's own balance; what `PaymentRouter.getLedger()` returns; what the replicated/consensus path assumes. |
464
+ | `MultiPartyCreditLedger` | `peer-payments.mjs` | One book, a balance per pod: `charge(podId, amount)`, `credit(podId, amount)`, `transfer(from, to, amount)`, `calculateCost()`, events. | A hub that keeps everyone's credits (a compute marketplace). Formerly also called `CreditLedger`. |
465
+ | `EscrowManager` | `peer-escrow.mjs` | **Canonical escrow.** Contracts with conditions (`result_hash_match`, `attestation_quorum`, `manual_approval`, timeouts), `dispute()`, a `mutateLedger` hook, `createEscrowService()` for the wire. It moves funds through a ledger. | Anything that actually holds credits. `createMeshNode({ enableEscrow })` uses it. |
466
+ | `SimpleEscrowBook` | `payments.mjs` | A flat record: `held` then `released`/`refunded`/`expired`. No conditions, no disputes, and it moves **no** balance. | What `PaymentRouter.getEscrow()` keeps to track `ESCROW_CREATE` wire messages. Formerly also called `EscrowManager`. |
467
+
468
+ `EscrowManager` accepts either ledger: with a `CreditLedger` it calls
469
+ `debit()`/`credit()` (that ledger has one balance, so use it when the local pod
470
+ is the payer, or pass `mutateLedger` to account for a counterparty); with a
471
+ `MultiPartyCreditLedger` it calls `charge()`/`credit()` so payer and payee each
472
+ move their own balance. `PaymentRouter`'s `SimpleEscrowBook` and an
473
+ `EscrowManager` you create are separate books and do not see each other.
398
474
 
399
475
  ## Putting it all together: sync + kernel-gated mesh + relay on one connection
400
476
 
@@ -433,7 +509,10 @@ back as the parsed object through `ctx.onIncomingData()`. That parse accepts
433
509
  either form, so it works for transports that deliver text and for in-process
434
510
  nodes that pass objects. `PeerNode.onIncomingData()` is the raw bus: it hands
435
511
  subscribers exactly what the transport delivered, so a direct subscriber that
436
- wants objects should parse JSON-object text itself. If you write your own
512
+ wants objects should parse JSON-object text itself (every raw subscriber in this
513
+ package -- mesh-sync, the relay host and backend, the pod-host service,
514
+ `BrowserMeshWebSocket`, `createPeerNodeTransport` -- does, through one shared
515
+ `decodeWireData`; a test fails if a new one does not). If you write your own
437
516
  transport, make `send()` follow the same rule -- forwarding an object to
438
517
  `RTCDataChannel.send()` turns it into the text `"[object Object]"` with no
439
518
  error.
@@ -628,23 +707,126 @@ dependency anywhere in this family); `llmFn(messages, toolSpecs) ->
628
707
 
629
708
  `mesh-orchestrator-tools.mjs`'s `registerOrchestratorTools()` is the worked
630
709
  example of wiring a *mesh-backed* capability into this pattern: it
631
- constructs `orchestrator.mjs`'s 8 real `Meshctl*Tool`s
710
+ constructs `orchestrator.mjs`'s 15 real `Meshctl*Tool`s
632
711
  (`meshctl_pods`/`meshctl_status`/`meshctl_exec`/`meshctl_deploy`/
633
- `meshctl_top`/`meshctl_compute`/`meshctl_expose`/`meshctl_drain`) against a
634
- real, attached `mesh-orchestrator.mjs` service, so an LLM-requested
635
- `meshctl_exec` tool call really dispatches through that service's
636
- `checkAccess()`-gated wire protocol to a real remote peer.
712
+ `meshctl_top`/`meshctl_compute`/`meshctl_expose`/`meshctl_drain`, plus issue
713
+ #185 §8a item 4's hosted-pods control surface five —
714
+ `meshctl_spawn`/`meshctl_snapshot`/`meshctl_restore`/`meshctl_hosted_pods`/
715
+ `meshctl_hosts`) against a real, attached `mesh-orchestrator.mjs` service,
716
+ so an LLM-requested `meshctl_exec` tool call really dispatches through that
717
+ service's `checkAccess()`-gated wire protocol to a real remote peer.
637
718
  `createMeshNode({enableAgentRuntime: true, enableOrchestrator: true})` wires
638
719
  all of this for you, returning `node.toolRegistry` pre-populated and ready
639
720
  to drive `createAgentRuntime({registry: node.toolRegistry, llmFn})`.
640
721
 
641
- `examples/11-agent-tool-calling.mjs` runs the whole story end to end over
722
+ `examples/11-agent-tool-calling.mjs` runs the original eight end to end over
642
723
  two real `createMeshNode()` peers, with a deterministic test `llmFn`. See
643
724
  `docs/building-mesh-services.md`'s own "`BrowserTool`/`BrowserToolRegistry`/
644
725
  agent runtime" section for the full design writeup, including two real bugs
645
726
  found while building it and the recommended DI pattern for new tools going
646
727
  forward.
647
728
 
729
+ ### `meshctl_*` tools for hosted pods (issue #185 §8a item 4)
730
+
731
+ The five hosted-pods tools project `pod-host-service.mjs`'s eight-verb
732
+ control surface (see "Pod host service" below) into the same
733
+ `BrowserTool` shape, each calling straight through to `MeshOrchestrator`'s
734
+ own `spawnPod`/`snapshotPod`/`restorePod`/`listHostedPods`/`listPodHosts`
735
+ methods — which already dispatch over `pod-host-service.mjs`'s own mesh
736
+ protocol and are already gated by the target HOST's own
737
+ `checkAccess()`, independently of `mesh-orchestrator.mjs`'s
738
+ `RISKY_ACTIONS` gate that `meshctl_exec`/`meshctl_deploy`/`meshctl_drain`
739
+ use:
740
+
741
+ | Tool | Args | Calls |
742
+ | --- | --- | --- |
743
+ | `meshctl_spawn` | `{host, name, lane?, run, limits?, caps?, env?, budget?, restart?}` | `spawnPod()` |
744
+ | `meshctl_snapshot` | `{host, name}` | `snapshotPod()` |
745
+ | `meshctl_restore` | `{host, name}` | `restorePod()` |
746
+ | `meshctl_hosted_pods` | `{host}` | `listHostedPods()` |
747
+ | `meshctl_hosts` | `{}` | `listPodHosts()` |
748
+
749
+ **Auto host selection** (`meshctl_spawn` with `host: 'auto'`, or omitted):
750
+ the orchestrator "proposes, the host accepts" — it picks exactly one host
751
+ and never silently retries a different one after a refusal (an `EACCES`,
752
+ or any other `PodHostDriverError`, is reported as-is). Selection prefers
753
+ `listComputeCandidates()` (the same descriptor list `meshctl_compute`
754
+ reads), narrowed to hosts advertising `runtime:<lane>` and preferring one
755
+ with `availability: 'online'`. Because an ISOLATE-lane host has no `exec`
756
+ by lane definition, it never produces a compute descriptor at all (see
757
+ "Known limitation" below) — so for `isolate`/`browser` lanes, selection
758
+ falls back to `listPodHosts()`, which reads the same runtime-registry peers
759
+ directly, without that filter. `MeshOrchestrator#listPodHosts()` is new
760
+ read-only bookkeeping this item adds: runtime-registry peers carrying a
761
+ `metadata.podHost` entry (i.e. anything projected through
762
+ `podHostRuntimePeer()`), returned as `{podId, lane, verbs, runtimeClasses,
763
+ shellBackend, resource, capabilities, hostedBy}`.
764
+
765
+ **Error mapping**: each tool's `error` field turns a `PodHostDriverError`
766
+ code into a lane-aware message rather than the raw errno-shaped code —
767
+ `ELANE` on `snapshot`/`restore` against an isolate host reads "isolate
768
+ pods cannot snapshot/restore; Durable Object hibernation is automatic, not
769
+ a verb you drive" (the same mapping the docs/hosted-pods.md §8a lane table
770
+ documents), `EACCES` names the host and the verb that was denied, and so
771
+ on for `ENOENT`/`EEXIST`/`ENOTSUP`/`ETIMEDOUT`/`EBUSY`.
772
+
773
+ **The `meshctl` text-command grammar** (`registerMeshctlBuiltins()`) grew
774
+ five subcommands matching the new tools one-for-one, usable from any shell
775
+ wired to `MeshOrchestrator`:
776
+
777
+ ```
778
+ meshctl spawn <host|auto> <name> --lane <lane> --kind <kind> --ref <ref> [--entry <entry>]
779
+ meshctl snapshot <host> <name>
780
+ meshctl restore <host> <name>
781
+ meshctl hosted <host>
782
+ meshctl hosts
783
+ ```
784
+
785
+ `examples/15-agent-spawns-hosted-pod.mjs` runs the whole story end to end:
786
+ a deterministic `llmFn` calls `meshctl_hosts`, then `meshctl_spawn` with
787
+ `host: 'auto'`, then `meshctl_hosted_pods`, `meshctl_snapshot`,
788
+ `meshctl_restore`, and finally the pre-existing `meshctl_drain` to drain
789
+ the host pod itself — composing the five new tools with the original
790
+ eight.
791
+
792
+ **Item 6's supervisor tools** (`meshctl_supervise`/`meshctl_supervised`,
793
+ and the `meshctl supervise`/`meshctl supervised` text commands) bring the
794
+ tool count to 15. `meshctl_supervise` accepts the same args as
795
+ `meshctl_spawn` plus `restart`/`links`, and calls
796
+ `orchestrator.getSupervisor()` then that supervisor's own `supervise()` —
797
+ see "Pod supervisor" above.
798
+
799
+ ### IoT tools (opt-in)
800
+
801
+ `registerMeshTools()` registers the stream, file, DHT and GPU tools (12). The
802
+ three IoT tools need an implementation this package does not ship, so they are
803
+ registered only when you pass one, and the agent never sees tools that could
804
+ only fail:
805
+
806
+ ```js
807
+ registerMeshTools(registry, multiplexer, fileTransfer, {
808
+ iotBridge, // enables iot_list and iot_send
809
+ iotTelemetry, // enables iot_telemetry
810
+ })
811
+ ```
812
+
813
+ The duck types (also `IoTBridgeLike` / `IoTTelemetryLike` typedefs in `tools.mjs`):
814
+
815
+ ```js
816
+ iotBridge = {
817
+ // filter is undefined, or { protocol?, capability? }
818
+ listDevices(filter) { return [{ deviceId, name, protocol, capabilities: ['read', 'write'] }] },
819
+ async send(deviceId, payload) { /* deliver; throw or reject on failure */ },
820
+ }
821
+ iotTelemetry = {
822
+ query(deviceId, since, until) { return [{ ts: 1700000000000, value: 21.5 }] }, // oldest first
823
+ getStats(deviceId) { return { min, max, avg, count, last } /* or null when no samples */ },
824
+ }
825
+ ```
826
+
827
+ A bridge or telemetry object missing one of those methods makes
828
+ `registerMeshTools()` throw a `TypeError` instead of failing later inside a tool.
829
+
648
830
  ## Verify argument order (caller-supplied callbacks)
649
831
 
650
832
  Every signature check in BrowserMesh takes `(identity, signature, data)`, the
@@ -680,6 +862,457 @@ is fed to your callback once, spies on `verifyFn` see one extra call with
680
862
  The `peer-timestamp` paths also throw a `TypeError` if the first argument is a
681
863
  64-byte signature.
682
864
 
865
+ ## Runtime classes and placement lanes
866
+
867
+ [Issue #185](https://github.com/johnhenry/browsermesh/issues/185) ("Hosted
868
+ pods") proposes running `Pod` outside the browser, on a host someone else
869
+ operates, in one of two isolation lanes that the orchestrator places work
870
+ across. This package's WP4 slice wires the *vocabulary* and the
871
+ `ResourceScorer`/`execOnPod()` placement logic those lanes need; it does
872
+ **not** implement the placement RPC itself (spawning or restoring a hosted
873
+ pod) -- that is issue #185's WP2 (isolate pod host) and WP3 (microVM pod
874
+ host), separate deliverables.
875
+
876
+ `resources.mjs` exports two frozen constants naming the lanes:
877
+
878
+ | `RUNTIME_CLASS` | Meaning | Boundary | Good for |
879
+ | --- | --- | --- | --- |
880
+ | `'browser'` | A tab/iframe/worker pod the user owns | n/a (same trust domain) | everything today's mesh already does |
881
+ | `'node'` | A `ServerPod`-style Node process | OS process | shell, filesystem, native modules |
882
+ | `'isolate'` | A V8 isolate (workerd / Durable Object) | Language-level (V8) | JS/Wasm skills, agents, CRDT replicas |
883
+ | `'microvm'` | A Firecracker microVM running `ServerPod` | Hardware (KVM) | `execOnPod` shell commands, native binaries |
884
+
885
+ `ISOLATION` names the lane a `ComputeRequest` can require:
886
+ `'any'` (default), `'isolate'`, or `'microvm'`.
887
+
888
+ A `ResourceDescriptor` advertises which lanes it supports as
889
+ `runtime:<class>` capability strings (e.g. `'runtime:isolate'`), the same
890
+ convention `preferRuntimeClass` already used for
891
+ `runtime:<preferRuntimeClass>`. `runtimePeerToComputeDescriptor()` in
892
+ `orchestrator.mjs` derives these from a runtime-registry peer's
893
+ `metadata.runtimeClasses`, and also copies `metadata.hostedBy` onto the
894
+ descriptor's own `hostedBy` field -- the podId of the lane host a hosted
895
+ pod is a `child` of (issue #185 §7: "hosted pods are child-role pods of the
896
+ host pod").
897
+
898
+ ### `ComputeRequest` placement fields
899
+
900
+ - `moduleType` now also accepts `'shell'` (alongside the existing `'wasm'`
901
+ and `'js'`), for jobs that are a shell command rather than a
902
+ wasm/js module.
903
+ - `constraints.isolation` (default `'any'`) is the request's lane
904
+ requirement: `'any'` lets the scorer prefer a lane without requiring it;
905
+ `'isolate'`/`'microvm'` hard-require that lane.
906
+ - Both are validated at construction time and round-trip through
907
+ `toJSON()`/`fromJSON()`.
908
+
909
+ ### `ResourceScorer` rules
910
+
911
+ `ResourceScorer.score()` applies the isolation lane **before** any of the
912
+ existing scoring (`preferRuntimeClass`, memory headroom, CPU, bandwidth --
913
+ all unchanged):
914
+
915
+ 1. **Hard zero for `moduleType: 'shell'`** unless the descriptor advertises
916
+ `runtime:microvm` -- a shell command can only ever run in a microVM pod,
917
+ regardless of `constraints.isolation`.
918
+ 2. **Hard zero when `constraints.isolation` is `'isolate'` or `'microvm'`**
919
+ unless the descriptor advertises the matching `runtime:<isolation>`
920
+ capability.
921
+ 3. **`+25` lane preference when `constraints.isolation` is `'any'`**:
922
+ `js`/`wasm` jobs get `+25` for `runtime:isolate`; `shell` jobs get `+25`
923
+ for `runtime:microvm` (this is the same condition as rule 1's gate, so a
924
+ shell job that clears the hard gate always gets the bonus too).
925
+
926
+ `ResourceScorer.lane(request)` is a static helper that reports the
927
+ *effective* lane for a request without consulting any descriptor --
928
+ `{ required, preferred }`, where `required` is set for a hard requirement
929
+ (explicit `isolation` or `moduleType: 'shell'`) and `preferred` is set when
930
+ `isolation` is `'any'` and the module type implies a lane. Useful for
931
+ logging/audit without re-deriving the scorer's own branching.
932
+
933
+ ### `execOnPod()` isolate guard
934
+
935
+ Dispatching `execOnPod()` against a pod whose only advertised runtime class
936
+ is `'isolate'` (no `'microvm'`/`'node'`/`'browser'` class and no
937
+ `shellBackend`) is rejected before any remote dispatch: it records a
938
+ `remote_exec_denied` audit entry (`reason: 'isolate runtime cannot execute
939
+ shell commands'`, `layer: 'runtime'`, mirroring the existing
940
+ `remote_deploy_denied` record shape) and returns
941
+ `{ exitCode: 126, output: 'pod runtime "isolate" cannot execute shell
942
+ commands; use deploySkill or a microvm pod' }` instead of silently
943
+ dispatching a command the pod has no way to run. Use `deploySkill()`
944
+ (isolate pods can receive deployed skill code) or target a `'microvm'` pod
945
+ for shell execution.
946
+
947
+ ### Placement audit vocabulary
948
+
949
+ `orchestrator.mjs` exports `PLACEMENT_AUDIT`, naming the placement
950
+ lifecycle this and future work packages write to the audit chain:
951
+ `placement_requested`, `placement_denied`, `placement_started`,
952
+ `placement_ready`, `placement_evicted` -- mirroring the existing
953
+ `remote_deploy_*`/`remote_exec_*`/`remote_compute_*` record families.
954
+ `MeshOrchestrator#recordPlacement(kind, details)` writes one through the
955
+ same `#recordAudit` path those use. The pod host service below is what
956
+ actually writes through it today, from both sides of a placement.
957
+
958
+ ## Pod host service: spawning and controlling hosted pods
959
+
960
+ `createPodHostService()` is the gated, audited mesh service for **hosted
961
+ pods** — pods running on a machine someone else operates ([issue
962
+ #185](https://github.com/johnhenry/browsermesh/issues/185),
963
+ [`docs/hosted-pods.md`](../../docs/hosted-pods.md)). It serves one
964
+ lane-agnostic verb set:
965
+
966
+ ```
967
+ spawn status send exec snapshot restore drain list
968
+ ```
969
+
970
+ The protocol itself — the verbs, the podspec, the lifecycle state machine,
971
+ the wire envelopes, the error codes — is plain data in
972
+ `@johnhenry/browsermesh-pod`'s `host-protocol.mjs`, deliberately *outside*
973
+ this package so a Worker or a microVM guest can import it without the app
974
+ runtime. What lives here is everything that needs a `PeerNode`:
975
+ `PeerRegistry.checkAccess()`, the `AuditChain`, and the orchestrator's
976
+ `PLACEMENT_AUDIT` vocabulary.
977
+
978
+ Every later surface is a projection of this one service: `mesh://` routes,
979
+ `meshctl` LLM tools, an external CLI, a supervisor. None of them should
980
+ re-implement access control, validation or audit.
981
+
982
+ ### Hosting: attach the service
983
+
984
+ ```js
985
+ import { attachService, createPodHostService } from '@johnhenry/browsermesh-apps'
986
+ import { InMemoryPodHostDriver } from '@johnhenry/browsermesh-pod'
987
+
988
+ const handle = attachService(peerNode, undefined, createPodHostService({
989
+ driver: new InMemoryPodHostDriver({ lane: 'node' }), // or a real lane driver
990
+ resource: 'pod-host', // ACL resource every verb is checked against
991
+ auditChain, // optional; writes PLACEMENT_AUDIT records
992
+ hostLabel: 'alice-laptop',
993
+ }))
994
+
995
+ handle.api.describe()
996
+ // { podId, lane: 'node', verbs: [...8], runtimeClasses: ['node'],
997
+ // shellBackend: 'pty', deploymentSupport: { canDeploy: true },
998
+ // capabilities: ['pod-host', 'exec'], resource: 'pod-host', hostLabel }
999
+
1000
+ handle.api.runtimePeer() // the runtime-registry peer shape the orchestrator reads
1001
+ ```
1002
+
1003
+ The `driver` is any object implementing `PodHostDriver` (a JSDoc typedef,
1004
+ not a base class). Three exist today:
1005
+
1006
+ | Driver | Lane | Where |
1007
+ | --- | --- | --- |
1008
+ | `InMemoryPodHostDriver` | configurable (default `node`) | `@johnhenry/browsermesh-pod` — tests, examples, the reference implementation |
1009
+ | `createVmPodDriver(vmPodHost)` | `microvm` | `spikes/vm-pod-host/src/driver.mjs` — Firecracker, via WP3's `VmPodHost` |
1010
+ | `createIsolatePodDriver({baseUrl})` | `isolate` | `spikes/isolate-pod-host/src/driver.mjs` — workerd/Durable Objects, over HTTP |
1011
+
1012
+ ### Driving: the client
1013
+
1014
+ ```js
1015
+ import { createPodHostClient } from '@johnhenry/browsermesh-apps'
1016
+
1017
+ const client = createPodHostClient({ peerNode, timeoutMs: 10_000 })
1018
+
1019
+ await client.spawn(hostPubKey, {
1020
+ name: 'transcoder',
1021
+ lane: 'microvm',
1022
+ run: { kind: 'command', ref: '/usr/bin/ffmpeg' },
1023
+ limits: { vcpus: 2, memMib: 512 },
1024
+ caps: ['net', 'fs'],
1025
+ budget: { credits: 25 },
1026
+ restart: { policy: 'on-failure', maxRestarts: 3 },
1027
+ })
1028
+
1029
+ await client.exec(hostPubKey, 'transcoder', ['ffmpeg', '-version'])
1030
+ await client.snapshot(hostPubKey, 'transcoder')
1031
+ await client.restore(hostPubKey, 'transcoder')
1032
+ await client.drain(hostPubKey, 'transcoder', { cascade: true })
1033
+ await client.list(hostPubKey)
1034
+ await client.describe(hostPubKey)
1035
+
1036
+ client.onEvent((hostPubKey, event) => {
1037
+ // event.kind is 'lifecycle' | 'log' | 'exit'
1038
+ })
1039
+ client.close()
1040
+ ```
1041
+
1042
+ One client talks to any number of hosts; responses are correlated by
1043
+ `requestId`, so several verbs can be in flight at once. A request with no
1044
+ answer inside `timeoutMs` rejects with `PodHostDriverError` / `ETIMEDOUT`,
1045
+ and a remote `{code, message}` is rethrown as a local `PodHostDriverError`
1046
+ — so `err.code === 'EACCES'` reads the same whether the refusal came from
1047
+ the local driver or six hops away.
1048
+
1049
+ `MeshOrchestrator` wraps the four placement-shaped verbs and writes the
1050
+ requester half of the audit trail itself:
1051
+
1052
+ ```js
1053
+ const orchestrator = new MeshOrchestrator({ peerNode, auditRecorder, podHostClient })
1054
+ await orchestrator.spawnPod(hostPodId, spec) // placement_requested → placement_ready
1055
+ await orchestrator.snapshotPod(hostPodId, 'transcoder') // placement_evicted
1056
+ await orchestrator.restorePod(hostPodId, 'transcoder') // placement_requested → placement_ready
1057
+ await orchestrator.listHostedPods(hostPodId)
1058
+ ```
1059
+
1060
+ `podHostClient` is optional — one is built lazily from `peerNode` on first
1061
+ use.
1062
+
1063
+ ### Gating
1064
+
1065
+ Every verb is checked as `registry.checkAccess(pubKey, resource, verb)`,
1066
+ i.e. the scope grammar is `pod-host:spawn`, `pod-host:exec`, … A denial
1067
+ answers `EACCES`, emits `pod-host:denied` on the service's event bus, and
1068
+ writes a `placement_denied` audit record. Verbs are independent: granting
1069
+ `pod-host:status` does not grant `pod-host:exec`. A host serving several
1070
+ tenants gives each its own resource (`resource: 'pod-host:tenant-a'`)
1071
+ rather than trying to express tenancy inside one scope.
1072
+
1073
+ `describe()` is **not** gated, and travels on its own `pod-host:describe`
1074
+ envelope rather than as a ninth verb: it returns only what the host would
1075
+ publish in its announce metadata anyway, and a peer has to be able to find
1076
+ out a host exists before it can ask to be granted anything on it.
1077
+
1078
+ ### Which lane can do what
1079
+
1080
+ ```js
1081
+ import { POD_LANE_VERBS, laneSupports } from '@johnhenry/browsermesh-pod'
1082
+ ```
1083
+
1084
+ | Lane | `spawn` | `status` | `send` | `exec` | `snapshot` | `restore` | `drain` | `list` |
1085
+ | --- | --- | --- | --- | --- | --- | --- | --- | --- |
1086
+ | `isolate` | ✓ | ✓ | ✓ | `ELANE` | `ELANE` | `ELANE` | ✓ | ✓ |
1087
+ | `microvm` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
1088
+ | `node` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
1089
+ | `browser` | ✓ | ✓ | ✓ | `ELANE` | `ELANE` | `ELANE` | ✓ | ✓ |
1090
+
1091
+ `ELANE` means "this lane structurally cannot" (a V8 isolate has no shell);
1092
+ `ENOTSUP` means "this driver did not implement an otherwise lane-compatible
1093
+ verb" (WP3's `VmPodHost` has no message path yet, so the microvm driver
1094
+ answers `send` with `ENOTSUP`). The distinction matters to a caller
1095
+ deciding whether to retry elsewhere or give up on the whole lane.
1096
+
1097
+ ### Observability and audit
1098
+
1099
+ The service's `attachService()` handle emits `pod-host:request`,
1100
+ `pod-host:denied`, `pod-host:completed` and `pod-host:event`. With an
1101
+ `auditChain`, the host writes `placement_requested` / `placement_started` /
1102
+ `placement_ready` / `placement_denied` / `placement_evicted`. The requester
1103
+ writes its own records through `MeshOrchestrator#recordPlacement()`: the two
1104
+ chains are independent, with independent authors, by design — a host's audit
1105
+ log is not evidence to the requester and vice versa.
1106
+
1107
+ ### Known limitation: isolate hosts produce no compute descriptor
1108
+
1109
+ `runtimePeerToComputeDescriptor()` only returns a descriptor for peers whose
1110
+ capabilities include `shell`/`exec`/`tools`. An isolate-lane pod host has no
1111
+ `exec` by definition, so `podHostRuntimePeer()` output for one is correctly
1112
+ scored as *not* a compute target and can only be reached through this service
1113
+ directly, not through `dispatchCompute()`. Teaching the scorer that "can
1114
+ spawn" is a kind of compute even without a shell is a change to WP4's scoring
1115
+ surface, not to this service.
1116
+
1117
+ A runnable end-to-end walkthrough is
1118
+ [`examples/13-pod-host-service.mjs`](../../examples/13-pod-host-service.mjs).
1119
+
1120
+ ## Pod supervisor
1121
+
1122
+ `createPodSupervisor()` (`pod-supervisor.mjs`) is [issue
1123
+ #185](https://github.com/johnhenry/browsermesh/issues/185)'s item 6: the
1124
+ last row of the control-surface table, `restart` policy + `status`/`spawn`/
1125
+ `drain` in a loop. The precedent is OTP, three ideas composed rather than
1126
+ reinvented:
1127
+
1128
+ - **links** — parent/child pod relationships that cascade on drain (a
1129
+ general form of [§7](../../docs/hosted-pods.md#7-identity-trust-and-what-hosting-cannot-promise)'s
1130
+ "hosted pods are child-role pods of the host").
1131
+ - **monitors** — be told when a pod you care about dies, without taking
1132
+ responsibility for it.
1133
+ - **supervisors** — `podspec.restart` (`host-protocol.mjs`) finally gets an
1134
+ implementation.
1135
+
1136
+ **The one rule that matters: a restart is a NEW `spawn` request the host
1137
+ may refuse.** Every (re)spawn goes through `orchestrator.spawnPod()` (the
1138
+ gated `PodHostClient` round trip, which also writes the requester-side
1139
+ `PLACEMENT_AUDIT` trail for free) or, with no orchestrator, straight
1140
+ through an injected `PodHostClient` — never the driver directly, never
1141
+ bypassing `pod-host-service.mjs`'s gate.
1142
+
1143
+ ```js
1144
+ import { createPodSupervisor } from '@johnhenry/browsermesh-apps'
1145
+
1146
+ const supervisor = createPodSupervisor({ orchestrator }) // or { client, peerNode }
1147
+
1148
+ const { ref } = await supervisor.supervise(hostPodId, {
1149
+ name: 'worker', lane: 'node', run: { kind: 'command', ref: '/bin/worker' },
1150
+ restart: { policy: 'on-failure', maxRestarts: 3, backoffMs: 1000 },
1151
+ })
1152
+
1153
+ supervisor.monitor(ref, ({ ref, event }) => console.log(ref.name, event.kind, event.data))
1154
+ supervisor.on('supervisor:restarted', ({ ref, attempt, host }) => { /* ... */ })
1155
+
1156
+ await supervisor.drain(ref, { cascade: true }) // children first, depth-first, then ref itself
1157
+ supervisor.stop() // clears every pending backoff timer
1158
+ ```
1159
+
1160
+ Everything is event-driven by default — the `PodHostClient`'s own
1161
+ `onEvent()` (`lifecycle`/`log`/`exit`) and, for host loss, the `PeerNode`'s
1162
+ `'peer:disconnect'` signal, synthesizing `{reason: 'host-lost',
1163
+ restartable: true}` for every pod that host was running. An opt-in,
1164
+ slow `reconcileIntervalMs` sweep is a safety net for an event that never
1165
+ arrives, not the primary mechanism. `links.parent`/`links.detachOnParentExit`
1166
+ on the podspec (`host-protocol.mjs`) imply a `link()` call at `supervise()`
1167
+ time; `drain(parent, {cascade: true})` drains every descendant depth-first
1168
+ (grandchildren, then children, then the parent) and emits
1169
+ `supervisor:cascade` with the full order.
1170
+
1171
+ `AutoMigrator` (`peer-health.mjs`) already does "move work when a peer
1172
+ degrades" for the MESH-PEER population; this does the analogous thing for
1173
+ the HOSTED-POD population. They watch different signals and move different
1174
+ things, so a mesh using both gets whole-peer failover from one and
1175
+ single-pod supervision from the other with no overlap.
1176
+
1177
+ `MeshOrchestrator#getSupervisor()` lazily builds one supervisor per
1178
+ orchestrator, and `drainPod(hostPodId)` consults it (without creating one
1179
+ it didn't need) to cascade-drain every pod that host supervises before the
1180
+ pre-existing mesh-peer drain logic runs. `meshctl_supervise`/
1181
+ `meshctl_supervised` (`orchestrator.mjs`) are the LLM-tool and
1182
+ `meshctl supervise`/`meshctl supervised` the text-command projections —
1183
+ see [`packages/browsermesh-meshctl`'s README](../browsermesh-meshctl/README.md#supervision)
1184
+ for the external-CLI surface, and
1185
+ [`examples/16-supervised-hosted-pods.mjs`](../../examples/16-supervised-hosted-pods.mjs)
1186
+ for a runnable walkthrough (crash a pod twice, watch backoff and two
1187
+ restarts, then drain the parent with cascade).
1188
+
1189
+ ## Pod host over mesh:// and the HTTP gateway
1190
+
1191
+ [Issue #185](https://github.com/johnhenry/browsermesh/issues/185) control-surface
1192
+ item 3: an HTTP-shaped view of the pod host service above, two ways --
1193
+ `pod-host-routes.mjs` projects the eight verbs onto `mesh://` routes for
1194
+ mesh peers, and `pod-host-gateway.mjs` fronts the same client with a real
1195
+ Node HTTP server for callers who aren't on the mesh at all. Neither
1196
+ re-implements access control, validation or audit -- see below for exactly
1197
+ how each reuses `pod-host-service.mjs`'s gate.
1198
+
1199
+ ### The route table
1200
+
1201
+ | Method | Path | Verb |
1202
+ | --- | --- | --- |
1203
+ | `GET` | `/pods` | `list` |
1204
+ | `POST` | `/pods` | `spawn` (body = podspec) |
1205
+ | `GET` | `/pods/:name` | `status` |
1206
+ | `POST` | `/pods/:name/send` | `send` |
1207
+ | `POST` | `/pods/:name/exec` | `exec` |
1208
+ | `POST` | `/pods/:name/snapshot` | `snapshot` |
1209
+ | `POST` | `/pods/:name/restore` | `restore` |
1210
+ | `DELETE` | `/pods/:name` | `drain` (`?cascade=true`) |
1211
+ | `GET` | `/host` | `describe` (ungated, like the envelope protocol's `pod-host:describe`) |
1212
+
1213
+ Status mapping: `ok` → 200 (201 for `spawn`, 204 for `drain` -- no body, per
1214
+ HTTP's own rule); `EINVAL` → 400; `EACCES` → 403; `ENOENT` → 404; `EEXIST` →
1215
+ 409; `ELANE` → 405 with an `Allow` header listing the verbs the driver's
1216
+ lane supports; `ENOTSUP` → 501; `ETIMEDOUT` → 504; `EBUSY` → 409; anything
1217
+ else → 500. Bodies are JSON `{ok, result}` or `{ok: false, error: {code,
1218
+ message}}`. `matchPodHostRoute(method, pathname) -> {verb, params}|null`
1219
+ and `POD_HOST_ROUTES` are exported for anything that wants to reuse the
1220
+ table itself.
1221
+
1222
+ ### Mounting the router on `mesh://`
1223
+
1224
+ `browserMeshFetch('mesh://<podId>/path')` is answered, host-side, by
1225
+ whatever `onRequest` a peer attached via `createMeshRpcService({onRequest})`
1226
+ (see "`fetch()`/`WebSocket`-shaped mesh access" above) -- that slot was
1227
+ already fully composable, so no change to `mesh-fetch.mjs`/`mesh-rpc.mjs`
1228
+ was needed to mount this router there:
1229
+
1230
+ ```js
1231
+ import {
1232
+ attachService, createMeshRpcService,
1233
+ createPodHostRouter, createPodHostMeshRpcHandler,
1234
+ } from '@johnhenry/browsermesh-apps'
1235
+
1236
+ const router = createPodHostRouter({ driver, registry: peerNode.registry })
1237
+ attachService(peerNode, undefined, createMeshRpcService({
1238
+ onRequest: createPodHostMeshRpcHandler(router),
1239
+ }))
1240
+ ```
1241
+
1242
+ `createPodHostRouter({driver|api, registry, resource?, onLog?})`'s `route(request)
1243
+ -> Promise<Response|null>` is shaped exactly like `@johnhenry/browsermesh-discovery`'s
1244
+ `MeshFetchRouter.route()` -- useful on its own (e.g. for tests), and reused
1245
+ unmodified by the HTTP gateway below. **`registry` (`peerNode.registry`) is
1246
+ required and cannot be defaulted or derived from `api`**: `createPodHostService()`'s
1247
+ `attach()` returns an `api` with `driver`/`resource`/`describe()` but no
1248
+ gated-dispatch method, so routing straight through `api.driver` would bypass
1249
+ `checkAccess()` entirely. This router instead calls
1250
+ `registry.checkAccess(pubKey, resource, verb)` itself, exactly where
1251
+ `pod-host-service.mjs`'s own `handleRequest()` does -- never create a second
1252
+ code path around that gate.
1253
+
1254
+ `podHostFetch(hostPodId, {fetch})` is the matching client, "control from
1255
+ within" for code that would rather call fetch-shaped methods than build
1256
+ `pod-host:*` envelopes by hand:
1257
+
1258
+ ```js
1259
+ import { createBrowserMeshFetch, podHostFetch } from '@johnhenry/browsermesh-apps'
1260
+
1261
+ const browserMeshFetch = createBrowserMeshFetch(meshRpcApi) // bound to YOUR peerNode
1262
+ const pods = podHostFetch(hostPodId, { fetch: browserMeshFetch })
1263
+
1264
+ await pods.spawn({ name: 'alpha', lane: 'node', run: { kind: 'command', ref: '/bin/echo' } })
1265
+ await pods.exec('alpha', ['echo', 'hi'])
1266
+ await pods.drain('alpha', { cascade: true })
1267
+ ```
1268
+
1269
+ ### The HTTP gateway: control from outside the mesh
1270
+
1271
+ `createPodHostGatewayHandler({client|peerNode, resolveHost, auth})` is a
1272
+ plain `(req: Request) => Promise<Response>` handler -- Web-standard only, so
1273
+ it runs in a Worker, Deno, or (via `serveNodeGateway()`) Node's `node:http`.
1274
+ Paths are `/hosts/:hostPodId/pods...` (plus `GET /hosts`, listing the hosts
1275
+ `resolveHost` knows about), mapped onto the identical route table above.
1276
+
1277
+ **Identity caveat, worth repeating because it's easy to miss:** the gateway
1278
+ is itself a mesh peer. `checkAccess()` on the remote host sees the
1279
+ *gateway's own* mesh identity (`client`'s pubKey), never whoever made the
1280
+ HTTP request -- exactly like an API gateway in front of a backend that
1281
+ trusts mTLS client certs, where the backend sees the gateway's cert, not the
1282
+ original caller's. Because of this, `auth(req) -> {ok, pubKey?}` is a
1283
+ REQUIRED argument -- there is no default-open gateway -- and deciding who
1284
+ gets to use the gateway's mesh identity, and how (bearer token, mTLS
1285
+ terminated upstream, a signed JWT...), is entirely the **operator's**
1286
+ responsibility; this package has no opinion on the scheme:
1287
+
1288
+ ```js
1289
+ import {
1290
+ createPodHostClient, createPodHostGatewayHandler, serveNodeGateway,
1291
+ } from '@johnhenry/browsermesh-apps'
1292
+
1293
+ const client = createPodHostClient({ peerNode: gatewayPeerNode })
1294
+ const handler = createPodHostGatewayHandler({
1295
+ client,
1296
+ resolveHost: { alice: aliceHostPodId }, // token in the URL -> real pubKey
1297
+ auth: (req) => {
1298
+ const token = (req.headers.get('authorization') || '').replace('Bearer ', '')
1299
+ return { ok: token === process.env.GATEWAY_TOKEN }
1300
+ },
1301
+ })
1302
+
1303
+ const gateway = await serveNodeGateway({ handler, port: 0 })
1304
+ // POST http://127.0.0.1:<port>/hosts/alice/pods, Authorization: Bearer <token>
1305
+ await gateway.close()
1306
+ ```
1307
+
1308
+ `serveNodeGateway()` `await import('node:http')`s lazily, so this module
1309
+ stays reachable from the package root's `export *` graph without breaking
1310
+ in a browser bundle merely by being imported.
1311
+
1312
+ A runnable end-to-end walkthrough of both transports against the same host
1313
+ is
1314
+ [`examples/14-pod-host-over-mesh-fetch.mjs`](../../examples/14-pod-host-over-mesh-fetch.mjs).
1315
+
683
1316
  ## License
684
1317
 
685
1318
  MIT