@johnhenry/browsermesh-apps 0.11.0 → 0.12.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
@@ -24,6 +24,8 @@ Application layer for BrowserMesh: marketplace, chat, payments, compute orchestr
24
24
  - [`browserMeshFetch`](#browsermeshfetch)
25
25
  - [`BrowserMeshWebSocket`](#browsermeshwebsocket)
26
26
  - [LLM tool-calling: `BrowserToolRegistry` and `createAgentRuntime`](#llm-tool-calling-browsertoolregistry-and-createagentruntime)
27
+ - [Runtime classes and placement lanes](#runtime-classes-and-placement-lanes)
28
+ - [Pod host service: spawning and controlling hosted pods](#pod-host-service-spawning-and-controlling-hosted-pods)
27
29
  - [License](#license)
28
30
 
29
31
  ## Provenance
@@ -48,7 +50,7 @@ Extracted from the private `clawser` monorepo (previously `packages/browsermesh-
48
50
  | mesh-orchestrator | `createOrchestratorService` (`MeshService` wrapper: real, gated wire dispatch for `execOnPod`/`deploySkill`/`drainPod`, ungated local aggregation for `listPods`/`getPodStatus`/`topPods`) |
49
51
  | compat | `BrowserTool`, `BrowserToolRegistry` (base class + registry an LLM-drivable agent loop dispatches tool calls through) |
50
52
  | 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`) |
53
+ | mesh-orchestrator-tools | `registerOrchestratorTools`, `createOrchestratorToolRegistry` (wires the 15 real `Meshctl*Tool`s into a `BrowserToolRegistry` against a real, attached `MeshOrchestrator`) |
52
54
  | audit | `AuditChain`, `AuditStore`, `detectFork`, `buildMerkleRoot` |
53
55
  | visualizations | `TopologyLayout`, `TrustGraphLayout`, `TrustHeatmap` |
54
56
  | devtools | `MeshInspector`, `MeshInspectTool` |
@@ -628,23 +630,95 @@ dependency anywhere in this family); `llmFn(messages, toolSpecs) ->
628
630
 
629
631
  `mesh-orchestrator-tools.mjs`'s `registerOrchestratorTools()` is the worked
630
632
  example of wiring a *mesh-backed* capability into this pattern: it
631
- constructs `orchestrator.mjs`'s 8 real `Meshctl*Tool`s
633
+ constructs `orchestrator.mjs`'s 15 real `Meshctl*Tool`s
632
634
  (`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.
635
+ `meshctl_top`/`meshctl_compute`/`meshctl_expose`/`meshctl_drain`, plus issue
636
+ #185 §8a item 4's hosted-pods control surface five —
637
+ `meshctl_spawn`/`meshctl_snapshot`/`meshctl_restore`/`meshctl_hosted_pods`/
638
+ `meshctl_hosts`) against a real, attached `mesh-orchestrator.mjs` service,
639
+ so an LLM-requested `meshctl_exec` tool call really dispatches through that
640
+ service's `checkAccess()`-gated wire protocol to a real remote peer.
637
641
  `createMeshNode({enableAgentRuntime: true, enableOrchestrator: true})` wires
638
642
  all of this for you, returning `node.toolRegistry` pre-populated and ready
639
643
  to drive `createAgentRuntime({registry: node.toolRegistry, llmFn})`.
640
644
 
641
- `examples/11-agent-tool-calling.mjs` runs the whole story end to end over
645
+ `examples/11-agent-tool-calling.mjs` runs the original eight end to end over
642
646
  two real `createMeshNode()` peers, with a deterministic test `llmFn`. See
643
647
  `docs/building-mesh-services.md`'s own "`BrowserTool`/`BrowserToolRegistry`/
644
648
  agent runtime" section for the full design writeup, including two real bugs
645
649
  found while building it and the recommended DI pattern for new tools going
646
650
  forward.
647
651
 
652
+ ### `meshctl_*` tools for hosted pods (issue #185 §8a item 4)
653
+
654
+ The five hosted-pods tools project `pod-host-service.mjs`'s eight-verb
655
+ control surface (see "Pod host service" below) into the same
656
+ `BrowserTool` shape, each calling straight through to `MeshOrchestrator`'s
657
+ own `spawnPod`/`snapshotPod`/`restorePod`/`listHostedPods`/`listPodHosts`
658
+ methods — which already dispatch over `pod-host-service.mjs`'s own mesh
659
+ protocol and are already gated by the target HOST's own
660
+ `checkAccess()`, independently of `mesh-orchestrator.mjs`'s
661
+ `RISKY_ACTIONS` gate that `meshctl_exec`/`meshctl_deploy`/`meshctl_drain`
662
+ use:
663
+
664
+ | Tool | Args | Calls |
665
+ | --- | --- | --- |
666
+ | `meshctl_spawn` | `{host, name, lane?, run, limits?, caps?, env?, budget?, restart?}` | `spawnPod()` |
667
+ | `meshctl_snapshot` | `{host, name}` | `snapshotPod()` |
668
+ | `meshctl_restore` | `{host, name}` | `restorePod()` |
669
+ | `meshctl_hosted_pods` | `{host}` | `listHostedPods()` |
670
+ | `meshctl_hosts` | `{}` | `listPodHosts()` |
671
+
672
+ **Auto host selection** (`meshctl_spawn` with `host: 'auto'`, or omitted):
673
+ the orchestrator "proposes, the host accepts" — it picks exactly one host
674
+ and never silently retries a different one after a refusal (an `EACCES`,
675
+ or any other `PodHostDriverError`, is reported as-is). Selection prefers
676
+ `listComputeCandidates()` (the same descriptor list `meshctl_compute`
677
+ reads), narrowed to hosts advertising `runtime:<lane>` and preferring one
678
+ with `availability: 'online'`. Because an ISOLATE-lane host has no `exec`
679
+ by lane definition, it never produces a compute descriptor at all (see
680
+ "Known limitation" below) — so for `isolate`/`browser` lanes, selection
681
+ falls back to `listPodHosts()`, which reads the same runtime-registry peers
682
+ directly, without that filter. `MeshOrchestrator#listPodHosts()` is new
683
+ read-only bookkeeping this item adds: runtime-registry peers carrying a
684
+ `metadata.podHost` entry (i.e. anything projected through
685
+ `podHostRuntimePeer()`), returned as `{podId, lane, verbs, runtimeClasses,
686
+ shellBackend, resource, capabilities, hostedBy}`.
687
+
688
+ **Error mapping**: each tool's `error` field turns a `PodHostDriverError`
689
+ code into a lane-aware message rather than the raw errno-shaped code —
690
+ `ELANE` on `snapshot`/`restore` against an isolate host reads "isolate
691
+ pods cannot snapshot/restore; Durable Object hibernation is automatic, not
692
+ a verb you drive" (the same mapping the docs/hosted-pods.md §8a lane table
693
+ documents), `EACCES` names the host and the verb that was denied, and so
694
+ on for `ENOENT`/`EEXIST`/`ENOTSUP`/`ETIMEDOUT`/`EBUSY`.
695
+
696
+ **The `meshctl` text-command grammar** (`registerMeshctlBuiltins()`) grew
697
+ five subcommands matching the new tools one-for-one, usable from any shell
698
+ wired to `MeshOrchestrator`:
699
+
700
+ ```
701
+ meshctl spawn <host|auto> <name> --lane <lane> --kind <kind> --ref <ref> [--entry <entry>]
702
+ meshctl snapshot <host> <name>
703
+ meshctl restore <host> <name>
704
+ meshctl hosted <host>
705
+ meshctl hosts
706
+ ```
707
+
708
+ `examples/15-agent-spawns-hosted-pod.mjs` runs the whole story end to end:
709
+ a deterministic `llmFn` calls `meshctl_hosts`, then `meshctl_spawn` with
710
+ `host: 'auto'`, then `meshctl_hosted_pods`, `meshctl_snapshot`,
711
+ `meshctl_restore`, and finally the pre-existing `meshctl_drain` to drain
712
+ the host pod itself — composing the five new tools with the original
713
+ eight.
714
+
715
+ **Item 6's supervisor tools** (`meshctl_supervise`/`meshctl_supervised`,
716
+ and the `meshctl supervise`/`meshctl supervised` text commands) bring the
717
+ tool count to 15. `meshctl_supervise` accepts the same args as
718
+ `meshctl_spawn` plus `restart`/`links`, and calls
719
+ `orchestrator.getSupervisor()` then that supervisor's own `supervise()` —
720
+ see "Pod supervisor" above.
721
+
648
722
  ## Verify argument order (caller-supplied callbacks)
649
723
 
650
724
  Every signature check in BrowserMesh takes `(identity, signature, data)`, the
@@ -680,6 +754,457 @@ is fed to your callback once, spies on `verifyFn` see one extra call with
680
754
  The `peer-timestamp` paths also throw a `TypeError` if the first argument is a
681
755
  64-byte signature.
682
756
 
757
+ ## Runtime classes and placement lanes
758
+
759
+ [Issue #185](https://github.com/johnhenry/browsermesh/issues/185) ("Hosted
760
+ pods") proposes running `Pod` outside the browser, on a host someone else
761
+ operates, in one of two isolation lanes that the orchestrator places work
762
+ across. This package's WP4 slice wires the *vocabulary* and the
763
+ `ResourceScorer`/`execOnPod()` placement logic those lanes need; it does
764
+ **not** implement the placement RPC itself (spawning or restoring a hosted
765
+ pod) -- that is issue #185's WP2 (isolate pod host) and WP3 (microVM pod
766
+ host), separate deliverables.
767
+
768
+ `resources.mjs` exports two frozen constants naming the lanes:
769
+
770
+ | `RUNTIME_CLASS` | Meaning | Boundary | Good for |
771
+ | --- | --- | --- | --- |
772
+ | `'browser'` | A tab/iframe/worker pod the user owns | n/a (same trust domain) | everything today's mesh already does |
773
+ | `'node'` | A `ServerPod`-style Node process | OS process | shell, filesystem, native modules |
774
+ | `'isolate'` | A V8 isolate (workerd / Durable Object) | Language-level (V8) | JS/Wasm skills, agents, CRDT replicas |
775
+ | `'microvm'` | A Firecracker microVM running `ServerPod` | Hardware (KVM) | `execOnPod` shell commands, native binaries |
776
+
777
+ `ISOLATION` names the lane a `ComputeRequest` can require:
778
+ `'any'` (default), `'isolate'`, or `'microvm'`.
779
+
780
+ A `ResourceDescriptor` advertises which lanes it supports as
781
+ `runtime:<class>` capability strings (e.g. `'runtime:isolate'`), the same
782
+ convention `preferRuntimeClass` already used for
783
+ `runtime:<preferRuntimeClass>`. `runtimePeerToComputeDescriptor()` in
784
+ `orchestrator.mjs` derives these from a runtime-registry peer's
785
+ `metadata.runtimeClasses`, and also copies `metadata.hostedBy` onto the
786
+ descriptor's own `hostedBy` field -- the podId of the lane host a hosted
787
+ pod is a `child` of (issue #185 §7: "hosted pods are child-role pods of the
788
+ host pod").
789
+
790
+ ### `ComputeRequest` placement fields
791
+
792
+ - `moduleType` now also accepts `'shell'` (alongside the existing `'wasm'`
793
+ and `'js'`), for jobs that are a shell command rather than a
794
+ wasm/js module.
795
+ - `constraints.isolation` (default `'any'`) is the request's lane
796
+ requirement: `'any'` lets the scorer prefer a lane without requiring it;
797
+ `'isolate'`/`'microvm'` hard-require that lane.
798
+ - Both are validated at construction time and round-trip through
799
+ `toJSON()`/`fromJSON()`.
800
+
801
+ ### `ResourceScorer` rules
802
+
803
+ `ResourceScorer.score()` applies the isolation lane **before** any of the
804
+ existing scoring (`preferRuntimeClass`, memory headroom, CPU, bandwidth --
805
+ all unchanged):
806
+
807
+ 1. **Hard zero for `moduleType: 'shell'`** unless the descriptor advertises
808
+ `runtime:microvm` -- a shell command can only ever run in a microVM pod,
809
+ regardless of `constraints.isolation`.
810
+ 2. **Hard zero when `constraints.isolation` is `'isolate'` or `'microvm'`**
811
+ unless the descriptor advertises the matching `runtime:<isolation>`
812
+ capability.
813
+ 3. **`+25` lane preference when `constraints.isolation` is `'any'`**:
814
+ `js`/`wasm` jobs get `+25` for `runtime:isolate`; `shell` jobs get `+25`
815
+ for `runtime:microvm` (this is the same condition as rule 1's gate, so a
816
+ shell job that clears the hard gate always gets the bonus too).
817
+
818
+ `ResourceScorer.lane(request)` is a static helper that reports the
819
+ *effective* lane for a request without consulting any descriptor --
820
+ `{ required, preferred }`, where `required` is set for a hard requirement
821
+ (explicit `isolation` or `moduleType: 'shell'`) and `preferred` is set when
822
+ `isolation` is `'any'` and the module type implies a lane. Useful for
823
+ logging/audit without re-deriving the scorer's own branching.
824
+
825
+ ### `execOnPod()` isolate guard
826
+
827
+ Dispatching `execOnPod()` against a pod whose only advertised runtime class
828
+ is `'isolate'` (no `'microvm'`/`'node'`/`'browser'` class and no
829
+ `shellBackend`) is rejected before any remote dispatch: it records a
830
+ `remote_exec_denied` audit entry (`reason: 'isolate runtime cannot execute
831
+ shell commands'`, `layer: 'runtime'`, mirroring the existing
832
+ `remote_deploy_denied` record shape) and returns
833
+ `{ exitCode: 126, output: 'pod runtime "isolate" cannot execute shell
834
+ commands; use deploySkill or a microvm pod' }` instead of silently
835
+ dispatching a command the pod has no way to run. Use `deploySkill()`
836
+ (isolate pods can receive deployed skill code) or target a `'microvm'` pod
837
+ for shell execution.
838
+
839
+ ### Placement audit vocabulary
840
+
841
+ `orchestrator.mjs` exports `PLACEMENT_AUDIT`, naming the placement
842
+ lifecycle this and future work packages write to the audit chain:
843
+ `placement_requested`, `placement_denied`, `placement_started`,
844
+ `placement_ready`, `placement_evicted` -- mirroring the existing
845
+ `remote_deploy_*`/`remote_exec_*`/`remote_compute_*` record families.
846
+ `MeshOrchestrator#recordPlacement(kind, details)` writes one through the
847
+ same `#recordAudit` path those use. The pod host service below is what
848
+ actually writes through it today, from both sides of a placement.
849
+
850
+ ## Pod host service: spawning and controlling hosted pods
851
+
852
+ `createPodHostService()` is the gated, audited mesh service for **hosted
853
+ pods** — pods running on a machine someone else operates ([issue
854
+ #185](https://github.com/johnhenry/browsermesh/issues/185),
855
+ [`docs/hosted-pods.md`](../../docs/hosted-pods.md)). It serves one
856
+ lane-agnostic verb set:
857
+
858
+ ```
859
+ spawn status send exec snapshot restore drain list
860
+ ```
861
+
862
+ The protocol itself — the verbs, the podspec, the lifecycle state machine,
863
+ the wire envelopes, the error codes — is plain data in
864
+ `@johnhenry/browsermesh-pod`'s `host-protocol.mjs`, deliberately *outside*
865
+ this package so a Worker or a microVM guest can import it without the app
866
+ runtime. What lives here is everything that needs a `PeerNode`:
867
+ `PeerRegistry.checkAccess()`, the `AuditChain`, and the orchestrator's
868
+ `PLACEMENT_AUDIT` vocabulary.
869
+
870
+ Every later surface is a projection of this one service: `mesh://` routes,
871
+ `meshctl` LLM tools, an external CLI, a supervisor. None of them should
872
+ re-implement access control, validation or audit.
873
+
874
+ ### Hosting: attach the service
875
+
876
+ ```js
877
+ import { attachService, createPodHostService } from '@johnhenry/browsermesh-apps'
878
+ import { InMemoryPodHostDriver } from '@johnhenry/browsermesh-pod'
879
+
880
+ const handle = attachService(peerNode, undefined, createPodHostService({
881
+ driver: new InMemoryPodHostDriver({ lane: 'node' }), // or a real lane driver
882
+ resource: 'pod-host', // ACL resource every verb is checked against
883
+ auditChain, // optional; writes PLACEMENT_AUDIT records
884
+ hostLabel: 'alice-laptop',
885
+ }))
886
+
887
+ handle.api.describe()
888
+ // { podId, lane: 'node', verbs: [...8], runtimeClasses: ['node'],
889
+ // shellBackend: 'pty', deploymentSupport: { canDeploy: true },
890
+ // capabilities: ['pod-host', 'exec'], resource: 'pod-host', hostLabel }
891
+
892
+ handle.api.runtimePeer() // the runtime-registry peer shape the orchestrator reads
893
+ ```
894
+
895
+ The `driver` is any object implementing `PodHostDriver` (a JSDoc typedef,
896
+ not a base class). Three exist today:
897
+
898
+ | Driver | Lane | Where |
899
+ | --- | --- | --- |
900
+ | `InMemoryPodHostDriver` | configurable (default `node`) | `@johnhenry/browsermesh-pod` — tests, examples, the reference implementation |
901
+ | `createVmPodDriver(vmPodHost)` | `microvm` | `spikes/vm-pod-host/src/driver.mjs` — Firecracker, via WP3's `VmPodHost` |
902
+ | `createIsolatePodDriver({baseUrl})` | `isolate` | `spikes/isolate-pod-host/src/driver.mjs` — workerd/Durable Objects, over HTTP |
903
+
904
+ ### Driving: the client
905
+
906
+ ```js
907
+ import { createPodHostClient } from '@johnhenry/browsermesh-apps'
908
+
909
+ const client = createPodHostClient({ peerNode, timeoutMs: 10_000 })
910
+
911
+ await client.spawn(hostPubKey, {
912
+ name: 'transcoder',
913
+ lane: 'microvm',
914
+ run: { kind: 'command', ref: '/usr/bin/ffmpeg' },
915
+ limits: { vcpus: 2, memMib: 512 },
916
+ caps: ['net', 'fs'],
917
+ budget: { credits: 25 },
918
+ restart: { policy: 'on-failure', maxRestarts: 3 },
919
+ })
920
+
921
+ await client.exec(hostPubKey, 'transcoder', ['ffmpeg', '-version'])
922
+ await client.snapshot(hostPubKey, 'transcoder')
923
+ await client.restore(hostPubKey, 'transcoder')
924
+ await client.drain(hostPubKey, 'transcoder', { cascade: true })
925
+ await client.list(hostPubKey)
926
+ await client.describe(hostPubKey)
927
+
928
+ client.onEvent((hostPubKey, event) => {
929
+ // event.kind is 'lifecycle' | 'log' | 'exit'
930
+ })
931
+ client.close()
932
+ ```
933
+
934
+ One client talks to any number of hosts; responses are correlated by
935
+ `requestId`, so several verbs can be in flight at once. A request with no
936
+ answer inside `timeoutMs` rejects with `PodHostDriverError` / `ETIMEDOUT`,
937
+ and a remote `{code, message}` is rethrown as a local `PodHostDriverError`
938
+ — so `err.code === 'EACCES'` reads the same whether the refusal came from
939
+ the local driver or six hops away.
940
+
941
+ `MeshOrchestrator` wraps the four placement-shaped verbs and writes the
942
+ requester half of the audit trail itself:
943
+
944
+ ```js
945
+ const orchestrator = new MeshOrchestrator({ peerNode, auditRecorder, podHostClient })
946
+ await orchestrator.spawnPod(hostPodId, spec) // placement_requested → placement_ready
947
+ await orchestrator.snapshotPod(hostPodId, 'transcoder') // placement_evicted
948
+ await orchestrator.restorePod(hostPodId, 'transcoder') // placement_requested → placement_ready
949
+ await orchestrator.listHostedPods(hostPodId)
950
+ ```
951
+
952
+ `podHostClient` is optional — one is built lazily from `peerNode` on first
953
+ use.
954
+
955
+ ### Gating
956
+
957
+ Every verb is checked as `registry.checkAccess(pubKey, resource, verb)`,
958
+ i.e. the scope grammar is `pod-host:spawn`, `pod-host:exec`, … A denial
959
+ answers `EACCES`, emits `pod-host:denied` on the service's event bus, and
960
+ writes a `placement_denied` audit record. Verbs are independent: granting
961
+ `pod-host:status` does not grant `pod-host:exec`. A host serving several
962
+ tenants gives each its own resource (`resource: 'pod-host:tenant-a'`)
963
+ rather than trying to express tenancy inside one scope.
964
+
965
+ `describe()` is **not** gated, and travels on its own `pod-host:describe`
966
+ envelope rather than as a ninth verb: it returns only what the host would
967
+ publish in its announce metadata anyway, and a peer has to be able to find
968
+ out a host exists before it can ask to be granted anything on it.
969
+
970
+ ### Which lane can do what
971
+
972
+ ```js
973
+ import { POD_LANE_VERBS, laneSupports } from '@johnhenry/browsermesh-pod'
974
+ ```
975
+
976
+ | Lane | `spawn` | `status` | `send` | `exec` | `snapshot` | `restore` | `drain` | `list` |
977
+ | --- | --- | --- | --- | --- | --- | --- | --- | --- |
978
+ | `isolate` | ✓ | ✓ | ✓ | `ELANE` | `ELANE` | `ELANE` | ✓ | ✓ |
979
+ | `microvm` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
980
+ | `node` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
981
+ | `browser` | ✓ | ✓ | ✓ | `ELANE` | `ELANE` | `ELANE` | ✓ | ✓ |
982
+
983
+ `ELANE` means "this lane structurally cannot" (a V8 isolate has no shell);
984
+ `ENOTSUP` means "this driver did not implement an otherwise lane-compatible
985
+ verb" (WP3's `VmPodHost` has no message path yet, so the microvm driver
986
+ answers `send` with `ENOTSUP`). The distinction matters to a caller
987
+ deciding whether to retry elsewhere or give up on the whole lane.
988
+
989
+ ### Observability and audit
990
+
991
+ The service's `attachService()` handle emits `pod-host:request`,
992
+ `pod-host:denied`, `pod-host:completed` and `pod-host:event`. With an
993
+ `auditChain`, the host writes `placement_requested` / `placement_started` /
994
+ `placement_ready` / `placement_denied` / `placement_evicted`. The requester
995
+ writes its own records through `MeshOrchestrator#recordPlacement()`: the two
996
+ chains are independent, with independent authors, by design — a host's audit
997
+ log is not evidence to the requester and vice versa.
998
+
999
+ ### Known limitation: isolate hosts produce no compute descriptor
1000
+
1001
+ `runtimePeerToComputeDescriptor()` only returns a descriptor for peers whose
1002
+ capabilities include `shell`/`exec`/`tools`. An isolate-lane pod host has no
1003
+ `exec` by definition, so `podHostRuntimePeer()` output for one is correctly
1004
+ scored as *not* a compute target and can only be reached through this service
1005
+ directly, not through `dispatchCompute()`. Teaching the scorer that "can
1006
+ spawn" is a kind of compute even without a shell is a change to WP4's scoring
1007
+ surface, not to this service.
1008
+
1009
+ A runnable end-to-end walkthrough is
1010
+ [`examples/13-pod-host-service.mjs`](../../examples/13-pod-host-service.mjs).
1011
+
1012
+ ## Pod supervisor
1013
+
1014
+ `createPodSupervisor()` (`pod-supervisor.mjs`) is [issue
1015
+ #185](https://github.com/johnhenry/browsermesh/issues/185)'s item 6: the
1016
+ last row of the control-surface table, `restart` policy + `status`/`spawn`/
1017
+ `drain` in a loop. The precedent is OTP, three ideas composed rather than
1018
+ reinvented:
1019
+
1020
+ - **links** — parent/child pod relationships that cascade on drain (a
1021
+ general form of [§7](../../docs/hosted-pods.md#7-identity-trust-and-what-hosting-cannot-promise)'s
1022
+ "hosted pods are child-role pods of the host").
1023
+ - **monitors** — be told when a pod you care about dies, without taking
1024
+ responsibility for it.
1025
+ - **supervisors** — `podspec.restart` (`host-protocol.mjs`) finally gets an
1026
+ implementation.
1027
+
1028
+ **The one rule that matters: a restart is a NEW `spawn` request the host
1029
+ may refuse.** Every (re)spawn goes through `orchestrator.spawnPod()` (the
1030
+ gated `PodHostClient` round trip, which also writes the requester-side
1031
+ `PLACEMENT_AUDIT` trail for free) or, with no orchestrator, straight
1032
+ through an injected `PodHostClient` — never the driver directly, never
1033
+ bypassing `pod-host-service.mjs`'s gate.
1034
+
1035
+ ```js
1036
+ import { createPodSupervisor } from '@johnhenry/browsermesh-apps'
1037
+
1038
+ const supervisor = createPodSupervisor({ orchestrator }) // or { client, peerNode }
1039
+
1040
+ const { ref } = await supervisor.supervise(hostPodId, {
1041
+ name: 'worker', lane: 'node', run: { kind: 'command', ref: '/bin/worker' },
1042
+ restart: { policy: 'on-failure', maxRestarts: 3, backoffMs: 1000 },
1043
+ })
1044
+
1045
+ supervisor.monitor(ref, ({ ref, event }) => console.log(ref.name, event.kind, event.data))
1046
+ supervisor.on('supervisor:restarted', ({ ref, attempt, host }) => { /* ... */ })
1047
+
1048
+ await supervisor.drain(ref, { cascade: true }) // children first, depth-first, then ref itself
1049
+ supervisor.stop() // clears every pending backoff timer
1050
+ ```
1051
+
1052
+ Everything is event-driven by default — the `PodHostClient`'s own
1053
+ `onEvent()` (`lifecycle`/`log`/`exit`) and, for host loss, the `PeerNode`'s
1054
+ `'peer:disconnect'` signal, synthesizing `{reason: 'host-lost',
1055
+ restartable: true}` for every pod that host was running. An opt-in,
1056
+ slow `reconcileIntervalMs` sweep is a safety net for an event that never
1057
+ arrives, not the primary mechanism. `links.parent`/`links.detachOnParentExit`
1058
+ on the podspec (`host-protocol.mjs`) imply a `link()` call at `supervise()`
1059
+ time; `drain(parent, {cascade: true})` drains every descendant depth-first
1060
+ (grandchildren, then children, then the parent) and emits
1061
+ `supervisor:cascade` with the full order.
1062
+
1063
+ `AutoMigrator` (`peer-health.mjs`) already does "move work when a peer
1064
+ degrades" for the MESH-PEER population; this does the analogous thing for
1065
+ the HOSTED-POD population. They watch different signals and move different
1066
+ things, so a mesh using both gets whole-peer failover from one and
1067
+ single-pod supervision from the other with no overlap.
1068
+
1069
+ `MeshOrchestrator#getSupervisor()` lazily builds one supervisor per
1070
+ orchestrator, and `drainPod(hostPodId)` consults it (without creating one
1071
+ it didn't need) to cascade-drain every pod that host supervises before the
1072
+ pre-existing mesh-peer drain logic runs. `meshctl_supervise`/
1073
+ `meshctl_supervised` (`orchestrator.mjs`) are the LLM-tool and
1074
+ `meshctl supervise`/`meshctl supervised` the text-command projections —
1075
+ see [`packages/browsermesh-meshctl`'s README](../browsermesh-meshctl/README.md#supervision)
1076
+ for the external-CLI surface, and
1077
+ [`examples/16-supervised-hosted-pods.mjs`](../../examples/16-supervised-hosted-pods.mjs)
1078
+ for a runnable walkthrough (crash a pod twice, watch backoff and two
1079
+ restarts, then drain the parent with cascade).
1080
+
1081
+ ## Pod host over mesh:// and the HTTP gateway
1082
+
1083
+ [Issue #185](https://github.com/johnhenry/browsermesh/issues/185) control-surface
1084
+ item 3: an HTTP-shaped view of the pod host service above, two ways --
1085
+ `pod-host-routes.mjs` projects the eight verbs onto `mesh://` routes for
1086
+ mesh peers, and `pod-host-gateway.mjs` fronts the same client with a real
1087
+ Node HTTP server for callers who aren't on the mesh at all. Neither
1088
+ re-implements access control, validation or audit -- see below for exactly
1089
+ how each reuses `pod-host-service.mjs`'s gate.
1090
+
1091
+ ### The route table
1092
+
1093
+ | Method | Path | Verb |
1094
+ | --- | --- | --- |
1095
+ | `GET` | `/pods` | `list` |
1096
+ | `POST` | `/pods` | `spawn` (body = podspec) |
1097
+ | `GET` | `/pods/:name` | `status` |
1098
+ | `POST` | `/pods/:name/send` | `send` |
1099
+ | `POST` | `/pods/:name/exec` | `exec` |
1100
+ | `POST` | `/pods/:name/snapshot` | `snapshot` |
1101
+ | `POST` | `/pods/:name/restore` | `restore` |
1102
+ | `DELETE` | `/pods/:name` | `drain` (`?cascade=true`) |
1103
+ | `GET` | `/host` | `describe` (ungated, like the envelope protocol's `pod-host:describe`) |
1104
+
1105
+ Status mapping: `ok` → 200 (201 for `spawn`, 204 for `drain` -- no body, per
1106
+ HTTP's own rule); `EINVAL` → 400; `EACCES` → 403; `ENOENT` → 404; `EEXIST` →
1107
+ 409; `ELANE` → 405 with an `Allow` header listing the verbs the driver's
1108
+ lane supports; `ENOTSUP` → 501; `ETIMEDOUT` → 504; `EBUSY` → 409; anything
1109
+ else → 500. Bodies are JSON `{ok, result}` or `{ok: false, error: {code,
1110
+ message}}`. `matchPodHostRoute(method, pathname) -> {verb, params}|null`
1111
+ and `POD_HOST_ROUTES` are exported for anything that wants to reuse the
1112
+ table itself.
1113
+
1114
+ ### Mounting the router on `mesh://`
1115
+
1116
+ `browserMeshFetch('mesh://<podId>/path')` is answered, host-side, by
1117
+ whatever `onRequest` a peer attached via `createMeshRpcService({onRequest})`
1118
+ (see "`fetch()`/`WebSocket`-shaped mesh access" above) -- that slot was
1119
+ already fully composable, so no change to `mesh-fetch.mjs`/`mesh-rpc.mjs`
1120
+ was needed to mount this router there:
1121
+
1122
+ ```js
1123
+ import {
1124
+ attachService, createMeshRpcService,
1125
+ createPodHostRouter, createPodHostMeshRpcHandler,
1126
+ } from '@johnhenry/browsermesh-apps'
1127
+
1128
+ const router = createPodHostRouter({ driver, registry: peerNode.registry })
1129
+ attachService(peerNode, undefined, createMeshRpcService({
1130
+ onRequest: createPodHostMeshRpcHandler(router),
1131
+ }))
1132
+ ```
1133
+
1134
+ `createPodHostRouter({driver|api, registry, resource?, onLog?})`'s `route(request)
1135
+ -> Promise<Response|null>` is shaped exactly like `@johnhenry/browsermesh-discovery`'s
1136
+ `MeshFetchRouter.route()` -- useful on its own (e.g. for tests), and reused
1137
+ unmodified by the HTTP gateway below. **`registry` (`peerNode.registry`) is
1138
+ required and cannot be defaulted or derived from `api`**: `createPodHostService()`'s
1139
+ `attach()` returns an `api` with `driver`/`resource`/`describe()` but no
1140
+ gated-dispatch method, so routing straight through `api.driver` would bypass
1141
+ `checkAccess()` entirely. This router instead calls
1142
+ `registry.checkAccess(pubKey, resource, verb)` itself, exactly where
1143
+ `pod-host-service.mjs`'s own `handleRequest()` does -- never create a second
1144
+ code path around that gate.
1145
+
1146
+ `podHostFetch(hostPodId, {fetch})` is the matching client, "control from
1147
+ within" for code that would rather call fetch-shaped methods than build
1148
+ `pod-host:*` envelopes by hand:
1149
+
1150
+ ```js
1151
+ import { createBrowserMeshFetch, podHostFetch } from '@johnhenry/browsermesh-apps'
1152
+
1153
+ const browserMeshFetch = createBrowserMeshFetch(meshRpcApi) // bound to YOUR peerNode
1154
+ const pods = podHostFetch(hostPodId, { fetch: browserMeshFetch })
1155
+
1156
+ await pods.spawn({ name: 'alpha', lane: 'node', run: { kind: 'command', ref: '/bin/echo' } })
1157
+ await pods.exec('alpha', ['echo', 'hi'])
1158
+ await pods.drain('alpha', { cascade: true })
1159
+ ```
1160
+
1161
+ ### The HTTP gateway: control from outside the mesh
1162
+
1163
+ `createPodHostGatewayHandler({client|peerNode, resolveHost, auth})` is a
1164
+ plain `(req: Request) => Promise<Response>` handler -- Web-standard only, so
1165
+ it runs in a Worker, Deno, or (via `serveNodeGateway()`) Node's `node:http`.
1166
+ Paths are `/hosts/:hostPodId/pods...` (plus `GET /hosts`, listing the hosts
1167
+ `resolveHost` knows about), mapped onto the identical route table above.
1168
+
1169
+ **Identity caveat, worth repeating because it's easy to miss:** the gateway
1170
+ is itself a mesh peer. `checkAccess()` on the remote host sees the
1171
+ *gateway's own* mesh identity (`client`'s pubKey), never whoever made the
1172
+ HTTP request -- exactly like an API gateway in front of a backend that
1173
+ trusts mTLS client certs, where the backend sees the gateway's cert, not the
1174
+ original caller's. Because of this, `auth(req) -> {ok, pubKey?}` is a
1175
+ REQUIRED argument -- there is no default-open gateway -- and deciding who
1176
+ gets to use the gateway's mesh identity, and how (bearer token, mTLS
1177
+ terminated upstream, a signed JWT...), is entirely the **operator's**
1178
+ responsibility; this package has no opinion on the scheme:
1179
+
1180
+ ```js
1181
+ import {
1182
+ createPodHostClient, createPodHostGatewayHandler, serveNodeGateway,
1183
+ } from '@johnhenry/browsermesh-apps'
1184
+
1185
+ const client = createPodHostClient({ peerNode: gatewayPeerNode })
1186
+ const handler = createPodHostGatewayHandler({
1187
+ client,
1188
+ resolveHost: { alice: aliceHostPodId }, // token in the URL -> real pubKey
1189
+ auth: (req) => {
1190
+ const token = (req.headers.get('authorization') || '').replace('Bearer ', '')
1191
+ return { ok: token === process.env.GATEWAY_TOKEN }
1192
+ },
1193
+ })
1194
+
1195
+ const gateway = await serveNodeGateway({ handler, port: 0 })
1196
+ // POST http://127.0.0.1:<port>/hosts/alice/pods, Authorization: Bearer <token>
1197
+ await gateway.close()
1198
+ ```
1199
+
1200
+ `serveNodeGateway()` `await import('node:http')`s lazily, so this module
1201
+ stays reachable from the package root's `export *` graph without breaking
1202
+ in a browser bundle merely by being imported.
1203
+
1204
+ A runnable end-to-end walkthrough of both transports against the same host
1205
+ is
1206
+ [`examples/14-pod-host-over-mesh-fetch.mjs`](../../examples/14-pod-host-over-mesh-fetch.mjs).
1207
+
683
1208
  ## License
684
1209
 
685
1210
  MIT
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/browsermesh-apps",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "description": "Application layer: marketplace, chat, payments, compute, orchestration, and agent tools for BrowserMesh",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
@@ -28,6 +28,7 @@
28
28
  },
29
29
  "peerDependencies": {
30
30
  "@johnhenry/browsermesh-primitives": ">=0.2.0 <1.0.0",
31
+ "@johnhenry/browsermesh-pod": ">=0.1.0 <1.0.0",
31
32
  "@johnhenry/browsermesh-core": ">=0.5.0 <1.0.0",
32
33
  "@johnhenry/browsermesh-transport": ">=0.1.0 <1.0.0",
33
34
  "@johnhenry/browsermesh-sync": ">=0.0.0 <1.0.0",
@@ -58,6 +59,7 @@
58
59
  },
59
60
  "devDependencies": {
60
61
  "@johnhenry/andbox": ">=0.0.1 <1.0.0",
62
+ "@johnhenry/browsermesh-pod": "^0.1.0",
61
63
  "node-datachannel": "^0.33.4",
62
64
  "fake-indexeddb": "^6.2.5",
63
65
  "webgpu": "^0.6.1"
package/src/index.mjs CHANGED
@@ -62,6 +62,10 @@ export * from './serverless-peer-select.mjs';
62
62
  export * from './serverless-sites.mjs';
63
63
  export * from './observability-bridge.mjs';
64
64
  export * from './mesh-kv.mjs';
65
+ export * from './pod-host-service.mjs';
66
+ export * from './pod-host-routes.mjs';
67
+ export * from './pod-host-gateway.mjs';
68
+ export * from './pod-supervisor.mjs';
65
69
  export * from './peer-payments.mjs';
66
70
  export * from './peer-registry.mjs';
67
71
  export * from './peer-routing.mjs';
@@ -1476,7 +1476,7 @@ export async function createMeshNode(options = {}) {
1476
1476
  // exists (and is always empty at minimum) when this flag is set, so a
1477
1477
  // caller wanting only its own non-orchestrator BrowserTools never has to
1478
1478
  // opt into orchestrator wiring it doesn't want. Only pre-populated with the
1479
- // 8 real Meshctl*Tools when enableOrchestrator was ALSO set -- see
1479
+ // 15 real Meshctl*Tools when enableOrchestrator was ALSO set -- see
1480
1480
  // mesh-orchestrator-tools.mjs's own doc comment for exactly which of those
1481
1481
  // route through the orchestrator service's gated wire dispatch.
1482
1482
  if (enableAgentRuntime) {