@johnhenry/browsermesh-apps 0.15.0 → 0.17.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.
Files changed (55) hide show
  1. package/README.md +298 -17
  2. package/package.json +13 -9
  3. package/src/apps.mjs +4 -4
  4. package/src/audit.mjs +2 -2
  5. package/src/chat.mjs +3 -3
  6. package/src/cloud-storage-backend.mjs +5 -7
  7. package/src/cloud-storage.mjs +5 -4
  8. package/src/compat.mjs +2 -2
  9. package/src/consensus.mjs +7 -7
  10. package/src/devtools.mjs +3 -3
  11. package/src/gpu.mjs +2 -2
  12. package/src/index.mjs +12 -0
  13. package/src/internal/channel-codec.mjs +179 -0
  14. package/src/internal/json-message.mjs +49 -0
  15. package/src/internal/relay-flow.mjs +178 -0
  16. package/src/internal/request-target.mjs +280 -0
  17. package/src/internal/rpc-body.mjs +33 -0
  18. package/src/marketplace-ui.mjs +1 -1
  19. package/src/mesh-agent-swarm.mjs +1 -1
  20. package/src/mesh-bootstrap.mjs +47 -1
  21. package/src/mesh-channel.mjs +716 -0
  22. package/src/mesh-fetch.mjs +77 -263
  23. package/src/mesh-hardening.mjs +8 -1
  24. package/src/mesh-relay-backend.mjs +116 -22
  25. package/src/mesh-relay-host.mjs +296 -55
  26. package/src/mesh-rpc.mjs +126 -265
  27. package/src/mesh-sync.mjs +1 -1
  28. package/src/orchestrator.mjs +54 -29
  29. package/src/payments.mjs +56 -14
  30. package/src/peer-agent-swarm.mjs +2 -2
  31. package/src/peer-agent.mjs +7 -7
  32. package/src/peer-compute.mjs +2 -2
  33. package/src/peer-encrypted-store.mjs +3 -3
  34. package/src/peer-escrow.mjs +2 -2
  35. package/src/peer-health.mjs +3 -3
  36. package/src/peer-node.mjs +8 -5
  37. package/src/peer-payments.mjs +2 -2
  38. package/src/peer-registry.mjs +45 -3
  39. package/src/peer-routing.mjs +158 -21
  40. package/src/peer-services.mjs +3 -3
  41. package/src/peer-timestamp.mjs +3 -3
  42. package/src/peer-torrent.mjs +112 -47
  43. package/src/peer-verification.mjs +3 -3
  44. package/src/pod-host-service.mjs +48 -7
  45. package/src/pod-placement.mjs +582 -0
  46. package/src/pod-supervisor.mjs +9 -30
  47. package/src/protocol-channel.mjs +327 -0
  48. package/src/resources.mjs +2 -2
  49. package/src/restart-policy.mjs +67 -0
  50. package/src/scheduler.mjs +3 -3
  51. package/src/serverless-proxy.mjs +58 -7
  52. package/src/silent-catch.mjs +22 -9
  53. package/src/tools.mjs +3 -3
  54. package/src/visualizations.mjs +2 -2
  55. package/src/wsh-negotiator.mjs +97 -0
package/README.md CHANGED
@@ -15,6 +15,7 @@ Application layer for BrowserMesh: marketplace, chat, payments, compute orchestr
15
15
  - [Connecting a real mesh node: `createMeshNode()`](#connecting-a-real-mesh-node-createmeshnode)
16
16
  - [TURN server configuration](#turn-server-configuration)
17
17
  - [Sharing a `VirtualNetwork` with specific peers: mesh relay](#sharing-a-virtualnetwork-with-specific-peers-mesh-relay)
18
+ - [Sharing a local HTTP server: `ServerSharing`](#sharing-a-local-http-server-serversharing)
18
19
  - [CloudStorage bucket authorization and key distribution](#cloudstorage-bucket-authorization-and-key-distribution)
19
20
  - [CloudStorage: the ergonomic SDK](#cloudstorage-the-ergonomic-sdk)
20
21
  - [Torrent service: durable stores, authorization and serve limits](#torrent-service-durable-stores-authorization-and-serve-limits)
@@ -34,7 +35,7 @@ Application layer for BrowserMesh: marketplace, chat, payments, compute orchestr
34
35
 
35
36
  ## Provenance
36
37
 
37
- Extracted from the private `clawser` monorepo (previously `packages/browsermesh-apps`), where it was manually published to npm, unscoped, as `browsermesh-apps@0.1.0` (2026-07-17) with no CI ever automating that publish. This is its first release as part of the `@johnhenry/browsermesh` monorepo; the version restarts at `0.0.0` per family convention.
38
+ Extracted from a private monorepo (previously `packages/browsermesh-apps`), where it was manually published to npm, unscoped, as `browsermesh-apps@0.1.0` (2026-07-17) with no CI ever automating that publish. This is its first release as part of the `@johnhenry/browsermesh` monorepo; the version restarts at `0.0.0` per family convention.
38
39
 
39
40
 
40
41
  ## Modules
@@ -226,6 +227,36 @@ This reaches the `WebRTCMeshManager` that `createMeshNode()` attaches to the
226
227
  returned node as `node.meshManager`, and from there every
227
228
  `WebRTCPeerConnection` it creates.
228
229
 
230
+ ## Sealed, key-authenticated links: `createMeshNode({ wsh })`
231
+
232
+ Opt in (off by default) to carry mesh links on [wsh](https://github.com/johnhenry/wsh)
233
+ sessions: key login in both directions, the host key pinned to the pod id you
234
+ meant to reach, and a session sealed end to end so the relay can read and alter
235
+ nothing. Needs the optional peer `@johnhenry/wsh` and a wsh pipe relay; see
236
+ [`browsermesh-transport`'s README](../browsermesh-transport/README.md#sealed-peer-links-over-wsh)
237
+ and [`docs/security.md`](../../docs/security.md) for what it does and does not
238
+ protect.
239
+
240
+ ```js
241
+ const node = await createMeshNode({
242
+ signalingTransport,
243
+ wsh: { relays: ['wss://relay.example/'] }, // `require: true` to never fall back to another transport
244
+ });
245
+ // The registry decides who may link to this node (default deny):
246
+ node.registry.grantCapabilities(peerPodId, ['mesh:link:connect']);
247
+ await node.connectToPeer(otherPodId, { wsh: otherPodId });
248
+ ```
249
+
250
+ The node's own identity is the wsh identity. An inbound link becomes a
251
+ `PeerNode` session under the pod id derived from the key wsh authenticated, so
252
+ `fromPubKey` in `onIncomingData()` is that key and every service
253
+ (`mesh-rpc`, `mesh-sync`, `mesh-relay`, ...) runs over the link unchanged.
254
+ `createWshAuthorizer(registry)`, `createWshAdapterFactory(links)` and
255
+ `attachWshLinks({ node, links, negotiator })` are the pieces `createMeshNode`
256
+ uses, exported for a hand-built node. `wsh.require` governs outbound
257
+ `connectToPeer()`; inbound WebRTC offers are still answered while a WebRTC
258
+ signaling bus is wired.
259
+
229
260
  ## Sharing a `VirtualNetwork` with specific peers: mesh relay
230
261
 
231
262
  Real-world scenario: your peer already reaches a real local service (e.g. an
@@ -279,12 +310,103 @@ bobNetwork.addBackend('via-alice', createMeshRelayBackend({ node: bob, relayPeer
279
310
  const socket = await bobNetwork.connect('via-alice://s3-local'); // refused (ConnectionRefusedError) until granted
280
311
  ```
281
312
 
313
+ ### Lifetime and limits of relayed connections
314
+
315
+ A relayed connection lasts only as long as the permission that allowed it:
316
+
317
+ - The host re-checks every open connection when the registry announces an
318
+ access change (`registry.onAccessChange()`, fired by `revokeCapabilities()`,
319
+ `removePeer()`, `updatePermissions()` and `notifyAccessChange()`), on
320
+ `host.recheck([pubKey])`, and every `recheckIntervalMs`. It does not check
321
+ per packet. Call `notifyAccessChange(pubKey)` (or `host.recheck()`) after
322
+ changing the ACL by a path the registry does not see.
323
+ - A connection that is no longer allowed, whose service was hidden
324
+ (`hideService()`), or whose host was detached is closed in both directions:
325
+ no further byte is delivered either way, the peer is sent a `close` frame
326
+ with a reason, and the client socket reports it as `socket.closeReason`
327
+ (`access revoked`, `service hidden`, `service detached`, ...). A connect that
328
+ finishes after one of these is not acknowledged and its socket is closed.
329
+ - Flow control uses byte credit per connection: each side advertises a window
330
+ (`highWaterBytes`) in `connect`/`ok`; a sender that has that many bytes
331
+ outstanding stops reading its local socket until credit brings it to
332
+ `lowWaterBytes` or less. Nothing is dropped. Bytes received and not yet
333
+ consumed are capped per connection and per peer; exceeding a cap, or sending
334
+ past the window, closes the connection with a reason (`buffer limit
335
+ exceeded`, `flow control violation`).
336
+ - `host.stats()` and `backend.stats()` report `connections`, `bufferedBytes`
337
+ and `inFlightBytes` (the host also per peer), for monitoring.
338
+
339
+ | Option (`MeshRelayHost`; the client takes the first four) | Default |
340
+ | --- | --- |
341
+ | `highWaterBytes` (window per connection; pause point) | 262144 |
342
+ | `lowWaterBytes` (resume point) | 65536 |
343
+ | `maxBufferedBytesPerConnection` (hard cap) | 1048576 |
344
+ | `maxFrameBytes` (largest data frame) | 65536 |
345
+ | `maxBufferedBytesPerPeer` (hard cap, host) | 4194304 |
346
+ | `maxConnectionsPerPeer` (host) | 16 |
347
+ | `recheckIntervalMs` (host; 0 turns the interval off) | 30000 |
348
+
349
+ With `createMeshNode({ enableRelayHost })` pass these as `relayHostOptions`.
350
+ The memory held for one connection is bounded by `maxBufferedBytesPerConnection`
351
+ plus the service socket's own receive window (`DEFAULT_WINDOW_BYTES` in
352
+ `@johnhenry/browsermesh-netway`: 256 KiB per direction by default).
353
+
354
+ An older peer: it sends no window, so it is never sent `credit` frames and
355
+ cannot be paused; it is held to the byte caps and gets a `close` frame (which
356
+ it already understands) when a cap or a revocation ends its connection. An
357
+ older host answers `ok` without a window; the client then sends no `credit`
358
+ frames and holds the host to the byte cap.
359
+
282
360
  TCP-only for now (`listen()`/`bindDatagram()` on `MeshRelayBackend` are the
283
361
  inherited `Backend` "not implemented" throws). See
284
362
  `examples/06-mesh-relay.mjs` for a full runnable walkthrough (in-process
285
363
  simulated mesh connection) and
286
364
  `test/real-peer/mesh-relay.test.mjs` for the real-WebRTC, real-TCP proof.
287
365
 
366
+ ## Sharing a local HTTP server: `ServerSharing`
367
+
368
+ `ServerSharing` (also wired by `createMeshRoutingService({ fetchFn, registry })`)
369
+ lets a peer make requests to an HTTP server you `expose(port, name, opts)`.
370
+ What it enforces:
371
+
372
+ - **Access.** Every request that arrives from a peer must pass
373
+ `registry.checkAccess(peerKey, 'server-share:<name>', 'request')`, i.e. the
374
+ scope `server-share:<name>:request` (wildcards such as
375
+ `server-share:*:request` work, as for `mesh-relay:<service>:connect`).
376
+ `peerKey` is the key of the session the message arrived on, never a field of
377
+ the message. With no registry, every peer request is refused. A direct
378
+ `handleRequest(request)` call with no second argument is an in-process call
379
+ and is not access-checked.
380
+ Share names may not contain `:` or `*`.
381
+ ```js
382
+ host.registry.grantCapabilities(bob.podId, ['server-share:web:request']);
383
+ ```
384
+ - **Target.** The upstream URL is built from the configured origin
385
+ (`protocol://hostname:port`) as base. The peer supplies a path and query
386
+ only; it must begin with a single `/`, may not contain a scheme, an
387
+ authority, a backslash, whitespace, a control character or a `#` fragment,
388
+ and after resolution the origin must equal the configured one. Anything else
389
+ is refused with status 400 before anything is sent.
390
+ - **Method and headers.** Methods default to `GET, HEAD, POST, PUT, PATCH,
391
+ DELETE, OPTIONS` (`allowedMethods` narrows them). Of the peer's headers only
392
+ `accept`, `accept-language`, `cache-control`, `content-type`, `if-*` and
393
+ `range` are forwarded (`allowedRequestHeaders` adds names); `Host`,
394
+ hop-by-hop headers, `Cookie`, `Authorization`, `Forwarded` and `X-Forwarded-*`
395
+ are never taken from a peer. Headers the sharer sets with
396
+ `expose(port, name, { headers })` are always sent and cannot be overridden.
397
+ - **Redirects** are not followed, for any origin; the 3xx response is returned
398
+ to the peer as it is.
399
+ - **Sizes.** Defaults: path 2048 characters, 32 headers / 8 KiB of headers,
400
+ request body 1 MiB (`maxRequestBodyBytes`), response body 8 MiB
401
+ (`maxResponseBytes`; a larger response is refused with 502, never truncated),
402
+ 30 s per request (`requestTimeoutMs`). Cookies and hop-by-hop headers are
403
+ not passed back to the peer.
404
+
405
+ `createProxyHandler()` (`serverless-proxy.mjs`) applies the same target rule,
406
+ does not follow redirects and bounds the response (`maxResponseBytes`,
407
+ `requestTimeoutMs`). It does not itself check who the caller is; that is done
408
+ by whatever serves the site.
409
+
288
410
  ## CloudStorage bucket authorization and key distribution
289
411
 
290
412
  `grant-log.mjs`'s `GrantLog` (`createGrantLogService()`) is a replicated,
@@ -474,8 +596,15 @@ mirror and is a separate book from an `EscrowManager` you create, but the router
474
596
  can see both: `router.attachEscrowManager(manager)` makes `router.listEscrows(podId?)`
475
597
  and `router.getEscrowById(id)` return one normalized view (`source: 'wire'` or
476
598
  `'manager'`), and the escrow sweeper also expires the manager's due contracts.
477
- An inbound `ESCROW_CREATE` is still only recorded in the book; it does not debit
478
- anything (the payer is a remote pod).
599
+ By default an inbound `ESCROW_CREATE` is still only recorded in the book; it does
600
+ not debit anything (the payer is a remote pod). To have it create a real,
601
+ funded contract, opt in with `router.attachEscrowManager(manager, { delegateWire: true })`:
602
+ the sending pod becomes the payer and the manager debits it, so the manager
603
+ needs a per-pod ledger (a `MultiPartyCreditLedger`, or a `mutateLedger` hook
604
+ that debits that pod; a single-owner `CreditLedger` would debit the local
605
+ balance whoever sent the message). A payer who cannot fund the amount, or a
606
+ malformed message, creates nothing, and the escrow is not also mirrored into the
607
+ book (`listEscrows()` shows it once, as `source: 'manager'`).
479
608
 
480
609
  ## Putting it all together: sync + kernel-gated mesh + relay on one connection
481
610
 
@@ -576,6 +705,55 @@ envelope's own `from` field, which a remote peer could set to anything.
576
705
  `test/real-peer/wire-envelope.test.mjs` runs all three over a real
577
706
  `RTCPeerConnection` pair (`npm run test:real-peer`).
578
707
 
708
+ ## Message channel: `createMeshChannelService`
709
+
710
+ `mesh-rpc` is HTTP-shaped (`{ method, path, headers, body }` in, a status out,
711
+ a JSON body of at most 1 MiB) and stays exactly as it is. A second service,
712
+ `createMeshChannelService()` (`mesh-channel.mjs`, also `@johnhenry/browsermesh-apps/mesh-channel`),
713
+ sits beside it on its own envelope type for protocols that need a message
714
+ layer. Over one link per peer it gives both sides:
715
+
716
+ - requests in both directions (ids are per direction), `notify`, and
717
+ `ctx.progress(value)` per request;
718
+ - cancel per request: the callee's handler gets `ctx.signal`; the caller's
719
+ late results are dropped;
720
+ - native `Uint8Array` values anywhere in a message (a small self-contained
721
+ codec; base64 only carries chunks inside the JSON envelope and is not part
722
+ of the API);
723
+ - a negotiated maximum message size, enforced from a message's first chunk
724
+ (its announced length), before anything is assembled, and locally before
725
+ anything is sent;
726
+ - credit-based flow control in bytes: a sender may have at most the receiver's
727
+ `window` of unconsumed bytes in flight, so a slow reader bounds a sender's
728
+ memory (and a reader that stops stops the sender);
729
+ - `maxInflight` requests per peer, a `close()` that rejects every pending
730
+ request, and the caller's verified identity (`ctx.peer`, the key the session
731
+ is bound to; never a field of the message) in every handler.
732
+
733
+ ```js
734
+ const a = attachService(nodeA, undefined, createMeshChannelService())
735
+ const b = attachService(nodeB, undefined, createMeshChannelService({
736
+ // Runs the moment the link exists, before any request can arrive on it.
737
+ onLink(link) {
738
+ link.onRequest('read', async ({ path }, { peer, signal, progress }) => {
739
+ // authorise `peer` yourself, e.g. ctx.registry.checkAccess(peer, ...)
740
+ await progress({ chunk: new Uint8Array(4) })
741
+ return { data: new Uint8Array(10) }
742
+ })
743
+ },
744
+ }))
745
+ const link = await a.api.open(nodeB.podId)
746
+ const { data } = await link.request('read', { path: 'x' }, { signal, onProgress })
747
+ ```
748
+
749
+ Like `mesh-rpc`, it does not authorise anything itself. Compatibility: the
750
+ first thing sent to a peer is one `hello`; a peer that does not run the
751
+ service ignores it and `open()` rejects with `MeshChannelError`
752
+ (`code -32000`, `reason 'unsupported'`) after `handshakeTimeoutMs`; pass
753
+ `peerSupports(peer)` to refuse without sending even that. See
754
+ `examples/17-mesh-channel.mjs` and the module comment in `mesh-channel.mjs`
755
+ for the wire frames, the memory model and the error codes.
756
+
579
757
  ## `fetch()`/`WebSocket`-shaped mesh access: `browserMeshFetch` and `BrowserMeshWebSocket`
580
758
 
581
759
  Two web-standard-API-shaped wrappers over a mesh connection, so existing
@@ -600,6 +778,36 @@ layer.
600
778
 
601
779
  ### `browserMeshFetch`
602
780
 
781
+ `createBrowserMeshFetch(api, { bodyMode: 'http' })` accepts standard HTTP body
782
+ types and sends their exact bytes, including native multipart form headers.
783
+ Passing a `Request` also selects that behavior. The default `bodyMode:
784
+ 'structured'` retains the original JSON-oriented convention: JSON-looking
785
+ string inputs are parsed before the handler receives them. Both modes preserve
786
+ binary responses and return null bodies for HEAD and status 204, 205 or 304.
787
+ The factory runs in browsers without Node globals. Mesh IDs remain case
788
+ sensitive; prefer `mesh://` addresses when representing cryptographic IDs,
789
+ since ordinary HTTP URL hostname handling can lowercase them.
790
+
791
+ This is bounded, buffered RPC rather than a streaming HTTP tunnel. The default
792
+ body cap is 1 MiB; `maxBodyBytes` can narrow the fetch adapter's upload cap and
793
+ the RPC service's request/response cap. Transport message-size limits still
794
+ apply. Large file transfer needs chunking or a streaming transport.
795
+
796
+ `createMeshRpcService()` accepts `maxInflight` (64), `maxIncoming` (64),
797
+ `maxIncomingPerPeer` (8), `maxBodyBytes` (1 MiB), and `requestTimeoutMs`
798
+ (10 seconds). Call `api.request(peer, request, { signal, timeoutMs })` to cancel
799
+ or bound an individual call. Handlers receive `signal`; only the original
800
+ caller may cancel their work. A matching response ID from another peer is
801
+ ignored. Cancel and timeout end local waiting and request remote cancellation;
802
+ they do not undo side effects or force a handler that ignores its signal to
803
+ stop. An unfinished handler continues to count against receiver admission.
804
+
805
+ Top-level `Uint8Array`, other array-buffer views and `ArrayBuffer` bodies use
806
+ the additive wire field `bodyEncoding: 'base64'`; plain JSON bodies keep their
807
+ previous wire shape. Binary calls and remote cancellation require updated
808
+ responders; older responders still support existing structured calls. This
809
+ transport supplies no resource grants: handlers must authorize the caller.
810
+
603
811
  `createBrowserMeshFetch(meshRpcApi) -> (url, init) => Promise<Response>` binds
604
812
  once to a live `mesh-rpc` service's `api` (the `{ request }` object
605
813
  `attachService()` returns as `.api`) and hands back a plain function whose
@@ -757,11 +965,11 @@ and never silently retries a different one after a refusal (an `EACCES`,
757
965
  or any other `PodHostDriverError`, is reported as-is). Selection prefers
758
966
  `listComputeCandidates()` (the same descriptor list `meshctl_compute`
759
967
  reads), narrowed to hosts advertising `runtime:<lane>` and preferring one
760
- with `availability: 'online'`. Because an ISOLATE-lane host has no `exec`
761
- by lane definition, it never produces a compute descriptor at all (see
762
- "Known limitation" below) — so for `isolate`/`browser` lanes, selection
763
- falls back to `listPodHosts()`, which reads the same runtime-registry peers
764
- directly, without that filter. `MeshOrchestrator#listPodHosts()` is new
968
+ with `availability: 'online'`. An ISOLATE-lane host has no `exec` by lane
969
+ definition, so it only appears in that list when spawn hosts are requested
970
+ (see "Spawn-only hosts and the compute scorer" below), which selection does;
971
+ if the registry exposes no candidates, selection falls back to
972
+ `listPodHosts()`, which reads the same runtime-registry peers directly. `MeshOrchestrator#listPodHosts()` is new
765
973
  read-only bookkeeping this item adds: runtime-registry peers carrying a
766
974
  `metadata.podHost` entry (i.e. anything projected through
767
975
  `podHostRuntimePeer()`), returned as `{podId, lane, verbs, runtimeClasses,
@@ -1075,6 +1283,15 @@ writes a `placement_denied` audit record. Verbs are independent: granting
1075
1283
  tenants gives each its own resource (`resource: 'pod-host:tenant-a'`)
1076
1284
  rather than trying to express tenancy inside one scope.
1077
1285
 
1286
+ A scope applies to every pod under the resource, so within one resource a
1287
+ requester holding `pod-host:status` or `pod-host:list` can read the others'
1288
+ pods. What it reads is limited: `env` values and `run.input` in a pod's
1289
+ `spec` are returned as `"[redacted]"` (the names stay) to every requester
1290
+ except the one that spawned that pod through this service; a pod the service
1291
+ did not spawn is redacted for everyone. Verbs on another requester's pod
1292
+ (`drain`, `exec`, `send`) are still allowed by the scope: separate resources
1293
+ are how tenants are kept apart.
1294
+
1078
1295
  `describe()` is **not** gated, and travels on its own `pod-host:describe`
1079
1296
  envelope rather than as a ninth verb: it returns only what the host would
1080
1297
  publish in its announce metadata anyway, and a peer has to be able to find
@@ -1109,15 +1326,24 @@ writes its own records through `MeshOrchestrator#recordPlacement()`: the two
1109
1326
  chains are independent, with independent authors, by design — a host's audit
1110
1327
  log is not evidence to the requester and vice versa.
1111
1328
 
1112
- ### Known limitation: isolate hosts produce no compute descriptor
1113
-
1114
- `runtimePeerToComputeDescriptor()` only returns a descriptor for peers whose
1115
- capabilities include `shell`/`exec`/`tools`. An isolate-lane pod host has no
1116
- `exec` by definition, so `podHostRuntimePeer()` output for one is correctly
1117
- scored as *not* a compute target and can only be reached through this service
1118
- directly, not through `dispatchCompute()`. Teaching the scorer that "can
1119
- spawn" is a kind of compute even without a shell is a change to WP4's scoring
1120
- surface, not to this service.
1329
+ ### Spawn-only hosts and the compute scorer
1330
+
1331
+ `runtimePeerToComputeDescriptor()` only returns a compute descriptor for peers
1332
+ whose capabilities include `shell`/`exec`/`tools`. An isolate-lane pod host has
1333
+ no `exec` by definition, so `listComputeCandidates()` and
1334
+ `selectComputeTarget()` do not return it by default, and nothing that needs a
1335
+ shell (`runComputeTask()`, `execOnPod()`) can be routed to it.
1336
+
1337
+ For *placement* (choosing where to spawn a pod) pass
1338
+ `{ includeSpawnHosts: true }`: `listComputeCandidates(constraints, { includeSpawnHosts: true })`
1339
+ and `selectComputeTarget({ includeSpawnHosts: true, ... })` then also return
1340
+ pod hosts that serve `spawn` but have no shell. Such a descriptor carries
1341
+ `spawn` and `runtime:<lane>` but never `compute`, and `selectComputeTarget()`
1342
+ only returns one while the scorer rates it above zero for the request (a
1343
+ `shell` module, or a lane it does not offer, never falls through to it).
1344
+ `pickAutoHost()` uses this, so an isolate host is now found by candidate
1345
+ scoring rather than by the `listPodHosts()` fallback (kept for registries that
1346
+ do not expose candidates).
1121
1347
 
1122
1348
  A runnable end-to-end walkthrough is
1123
1349
  [`examples/13-pod-host-service.mjs`](../../examples/13-pod-host-service.mjs).
@@ -1191,6 +1417,61 @@ for the external-CLI surface, and
1191
1417
  for a runnable walkthrough (crash a pod twice, watch backoff and two
1192
1418
  restarts, then drain the parent with cascade).
1193
1419
 
1420
+ ## Pod placement planner
1421
+
1422
+ `planPlacement()`, `HostHealth`, `PlacementLedger` and `createHostPool()`
1423
+ (`pod-placement.mjs`) are the pure half of choosing where a hosted pod goes
1424
+ ([issue #185](https://github.com/johnhenry/browsermesh/issues/185) §6). No
1425
+ clock and no timers are used: time is passed in, and a restart delay is a
1426
+ number the caller schedules, so every rule is unit-tested against fake lane
1427
+ drivers (`InMemoryPodHostDriver`) without sleeping. They are additive:
1428
+ nothing calls them unless you do.
1429
+
1430
+ ```js
1431
+ import { createHostPool, PLACEMENT_BOUNDARY } from '@johnhenry/browsermesh-apps'
1432
+
1433
+ const pool = createHostPool({
1434
+ hosts: [
1435
+ { id: 'edge-1', driver: isolateDriver, boundary: PLACEMENT_BOUNDARY.LANGUAGE, capacity: { pods: 200, memMib: 4096 } },
1436
+ { id: 'kvm-1', driver: microvmDriver, boundary: PLACEMENT_BOUNDARY.HARDWARE, capacity: { pods: 20, vcpus: 16, memMib: 16384 } },
1437
+ ],
1438
+ policy: { perRequesterMaxPods: 5 },
1439
+ })
1440
+ const { hostId, status } = await pool.spawn(podspec, { requester: { id: 'alice' } })
1441
+ ```
1442
+
1443
+ Hard rules, in the order they are checked (each rejected host reports a
1444
+ `code` and a `reason`): `lane` (the podspec's lane), `verb` (serves `spawn`),
1445
+ `draining`, `health` (unhealthy hosts are skipped until their cooldown ends,
1446
+ then probed once), `avoided`, `boundary`, `caps` (every `caps` entry in the
1447
+ podspec), `capacity` (pods, vcpus, MiB against what is already reserved). A
1448
+ requester over `perRequesterMaxPods` is refused before any host is looked at.
1449
+ Ranking among the hosts that pass: headroom, health (degraded and probing
1450
+ hosts rank lower), an optional `preferHost`, then host id, so the answer does
1451
+ not depend on input order.
1452
+
1453
+ **Isolation boundary.** A host states how strongly it separates a pod from
1454
+ the host: `none` (same process: `worker_threads`), `process` (a child process
1455
+ with permission flags), `language` (a V8 isolate in its own process),
1456
+ `hardware` (a microVM). Requesters are untrusted unless they say otherwise,
1457
+ and an untrusted requester is only placed behind `language` or `hardware`
1458
+ (`policy.minBoundary` raises the floor for everyone). This only refuses to
1459
+ place untrusted work where a host says there is no boundary; it does not
1460
+ create one.
1461
+
1462
+ **The host still decides.** A host's refusal (`EACCES`, `EBUSY`, ...) is final
1463
+ for that spawn. Only a transport-level failure (`ETIMEDOUT`) can move a spawn
1464
+ to the next host, and only with `maxAttempts` above its default of 1. Failures
1465
+ count against the host's `HostHealth`.
1466
+
1467
+ `pool.drainHost(id)` stops placing on a host and moves its pods
1468
+ make-before-break; a pod that cannot be re-placed is left running and
1469
+ reported in `failed`. `pool.handleExit({ hostId, name, exit })` applies the
1470
+ restart policy shared with the supervisor (`decideRestart()`: never restart a
1471
+ drain, exponential backoff from the podspec's `backoffMs`, give up at
1472
+ `maxRestarts`) and returns `{ restart, delayMs, run }`; `run()` re-places the
1473
+ pod on a host other than the one that failed.
1474
+
1194
1475
  ## Pod host over mesh:// and the HTTP gateway
1195
1476
 
1196
1477
  [Issue #185](https://github.com/johnhenry/browsermesh/issues/185) control-surface
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/browsermesh-apps",
3
- "version": "0.15.0",
3
+ "version": "0.17.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",
@@ -11,6 +11,8 @@
11
11
  },
12
12
  "./compat": "./src/compat.mjs",
13
13
  "./mesh-rpc": "./src/mesh-rpc.mjs",
14
+ "./mesh-channel": "./src/mesh-channel.mjs",
15
+ "./protocol-channel": "./src/protocol-channel.mjs",
14
16
  "./mesh-fetch": "./src/mesh-fetch.mjs",
15
17
  "./mesh-service": "./src/mesh-service.mjs",
16
18
  "./peer-registry": "./src/peer-registry.mjs"
@@ -27,15 +29,15 @@
27
29
  "directory": "packages/browsermesh-apps"
28
30
  },
29
31
  "peerDependencies": {
30
- "@johnhenry/browsermesh-primitives": ">=0.2.0 <1.0.0",
31
- "@johnhenry/browsermesh-pod": ">=0.1.0 <1.0.0",
32
+ "@johnhenry/andbox": ">=0.0.1 <1.0.0",
32
33
  "@johnhenry/browsermesh-core": ">=0.5.0 <1.0.0",
33
- "@johnhenry/browsermesh-transport": ">=0.1.0 <1.0.0",
34
- "@johnhenry/browsermesh-sync": ">=0.0.0 <1.0.0",
35
34
  "@johnhenry/browsermesh-discovery": ">=0.0.1 <1.0.0",
36
35
  "@johnhenry/browsermesh-kernel": ">=0.0.0 <1.0.0",
37
36
  "@johnhenry/browsermesh-netway": ">=0.0.0 <1.0.0",
38
- "@johnhenry/andbox": ">=0.0.1 <1.0.0"
37
+ "@johnhenry/browsermesh-pod": ">=0.1.0 <1.0.0",
38
+ "@johnhenry/browsermesh-primitives": ">=0.3.1 <1.0.0",
39
+ "@johnhenry/browsermesh-sync": ">=0.0.0 <1.0.0",
40
+ "@johnhenry/browsermesh-transport": ">=0.1.0 <1.0.0"
39
41
  },
40
42
  "peerDependenciesMeta": {
41
43
  "@johnhenry/browsermesh-transport": {
@@ -59,14 +61,16 @@
59
61
  },
60
62
  "devDependencies": {
61
63
  "@johnhenry/andbox": ">=0.0.1 <1.0.0",
62
- "@johnhenry/browsermesh-pod": "^0.1.1",
63
- "node-datachannel": "^0.33.4",
64
+ "@johnhenry/browsermesh-pod": "^0.2.0",
64
65
  "fake-indexeddb": "^6.2.5",
65
- "webgpu": "^0.6.1"
66
+ "node-datachannel": "^0.33.4",
67
+ "webgpu": "^0.6.1",
68
+ "webtorrent": "^3.0.21"
66
69
  },
67
70
  "scripts": {
68
71
  "test": "node --import ./test/_setup-globals.mjs --test test/*.test.mjs",
69
72
  "test:real-peer": "node --import ./test/_setup-globals.mjs --test --test-concurrency=1 test/real-peer/*.test.mjs",
73
+ "test:real-torrent": "node --import ./test/_setup-globals.mjs --test --test-concurrency=1 test/real-torrent/*.test.mjs",
70
74
  "test:real-gpu": "node --import ./test/_setup-globals.mjs --test test/gpu-real-webgpu/*.test.mjs"
71
75
  },
72
76
  "homepage": "https://opensource.johnhenry.me/browsermesh/",
package/src/apps.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * clawser-mesh-apps.js -- Decentralized App Ecosystem for BrowserMesh.
2
+ * apps.mjs --Decentralized App Ecosystem for BrowserMesh.
3
3
  *
4
4
  * Provides a full app lifecycle for mesh-distributed applications:
5
5
  * manifest definition, installation, permission checking, a distributed
@@ -12,7 +12,7 @@
12
12
  * No browser-only imports at module level.
13
13
  *
14
14
  * Run tests:
15
- * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-apps.test.mjs
15
+ * cd packages/browsermesh-apps && node --import ./test/_setup-globals.mjs --test test/apps.test.mjs
16
16
  */
17
17
 
18
18
  import { MESH_TYPE } from '@johnhenry/browsermesh-primitives';
@@ -566,7 +566,7 @@ export class AppRegistry {
566
566
 
567
567
  // Stop if active
568
568
  if (inst.state !== 'stopped' && inst.state !== 'error') {
569
- try { inst.stop(); } catch (e) { silentCatch('clawser-mesh-apps', 'inst.stop', e) }
569
+ try { inst.stop(); } catch (e) { silentCatch('apps', 'inst.stop', e) }
570
570
  }
571
571
 
572
572
  this.#apps.delete(appId);
@@ -664,7 +664,7 @@ export class AppRegistry {
664
664
 
665
665
  // Stop if active
666
666
  if (inst.state !== 'stopped' && inst.state !== 'installed' && inst.state !== 'error') {
667
- try { inst.stop(); } catch (e) { silentCatch('clawser-mesh-apps', 'inst.stop', e) }
667
+ try { inst.stop(); } catch (e) { silentCatch('apps', 'inst.stop', e) }
668
668
  }
669
669
 
670
670
  // Create new instance with new manifest, preserving data
package/src/audit.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * clawser-mesh-audit.js -- Cryptographic audit trail for BrowserMesh.
2
+ * audit.mjs --Cryptographic audit trail for BrowserMesh.
3
3
  *
4
4
  * Provides a tamper-evident, hash-chained log of operations with
5
5
  * Ed25519 signatures, Merkle proof generation/verification, and
@@ -8,7 +8,7 @@
8
8
  * No browser-only imports at module level.
9
9
  *
10
10
  * Run tests:
11
- * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-audit.test.mjs
11
+ * cd packages/browsermesh-apps && node --import ./test/_setup-globals.mjs --test test/audit.test.mjs
12
12
  */
13
13
 
14
14
  import { encodeBase64url, decodeBase64url } from '@johnhenry/browsermesh-primitives';
package/src/chat.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- // STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
3
- * clawser-mesh-chat.js -- CRDT-backed chat rooms for BrowserMesh.
2
+ // STATUS: INTEGRATED — wired into the Pod lifecycle (@johnhenry/browsermesh-pod), proven via E2E testing
3
+ * chat.mjs --CRDT-backed chat rooms for BrowserMesh.
4
4
  *
5
5
  * ChatMessage envelopes, ChatRoom with ORSet membership, LWWMap
6
6
  * presence, moderation, and a multi-room MeshChat manager.
@@ -8,7 +8,7 @@
8
8
  * No browser-only imports at module level.
9
9
  *
10
10
  * Run tests:
11
- * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-chat.test.mjs
11
+ * cd packages/browsermesh-apps && node --import ./test/_setup-globals.mjs --test test/chat.test.mjs
12
12
  */
13
13
 
14
14
  import {
@@ -169,6 +169,7 @@
169
169
  */
170
170
 
171
171
  import { createLazyRequire } from './internal/lazy-node-require.mjs'
172
+ import { readJsonMessage } from './internal/json-message.mjs'
172
173
 
173
174
  import { IndexedDBChunkStore, IndexedDBSyncStorage, TRANSFER_DEFAULTS } from '@johnhenry/browsermesh-sync'
174
175
  import { LWWMap } from '@johnhenry/browsermesh-primitives'
@@ -438,20 +439,17 @@ function resolveCloudStorageBackendClass() {
438
439
 
439
440
  /** @param {import('@johnhenry/browsermesh-netway').StreamSocket} socket */
440
441
  async #handleConnection(socket) {
441
- const decoder = new TextDecoder()
442
442
  const encoder = new TextEncoder()
443
443
 
444
444
  while (true) {
445
- const chunk = await socket.read()
446
- if (chunk === null) break
445
+ const msg = await readJsonMessage(socket)
446
+ if (msg.eof) break
447
447
 
448
- let cmd
449
- try {
450
- cmd = JSON.parse(decoder.decode(chunk))
451
- } catch {
448
+ if (msg.error) {
452
449
  await socket.write(encoder.encode(JSON.stringify({ error: 'Invalid JSON' })))
453
450
  continue
454
451
  }
452
+ const cmd = msg.value
455
453
 
456
454
  let result
457
455
  try {
@@ -199,6 +199,7 @@
199
199
 
200
200
  import { attachService, createEventBus } from './mesh-service.mjs'
201
201
  import { createCloudStorageBackend } from './cloud-storage-backend.mjs'
202
+ import { readJsonMessage } from './internal/json-message.mjs'
202
203
  import { createGrantLogService } from './grant-log.mjs'
203
204
  import { createKeyDistributionService } from './key-distribution.mjs'
204
205
  import { createManifestSyncService } from './manifest-sync.mjs'
@@ -527,13 +528,13 @@ export class CloudStorage {
527
528
  const run = async () => {
528
529
  const socket = await this.#ensureSocket()
529
530
  const encoder = new TextEncoder()
530
- const decoder = new TextDecoder()
531
531
  await socket.write(encoder.encode(JSON.stringify(cmd)))
532
- const chunk = await socket.read()
533
- if (chunk === null) {
532
+ const msg = await readJsonMessage(socket)
533
+ if (msg.eof) {
534
534
  throw new Error('CloudStorage: local backend socket closed unexpectedly')
535
535
  }
536
- return JSON.parse(decoder.decode(chunk))
536
+ if (msg.error) throw msg.error
537
+ return msg.value
537
538
  }
538
539
 
539
540
  const result = this.#socketQueue.then(run, run)
package/src/compat.mjs CHANGED
@@ -1,10 +1,10 @@
1
1
  /**
2
2
  * compat.mjs -- BrowserTool shim for standalone use.
3
3
  *
4
- * In clawser, BrowserTool is the base class for AI-agent-callable tools.
4
+ * In the host application, BrowserTool is the base class for AI-agent-callable tools.
5
5
  * Subclasses override name/description/parameters/permission as GETTERS
6
6
  * (not constructor-assigned properties) — this shim mirrors that exactly
7
- * (see web/clawser-tools.js). An earlier version of this shim tried to
7
+ * (see the host application's tool layer). An earlier version of this shim tried to
8
8
  * assign `this.name = ...` in the constructor, which threw
9
9
  * "Cannot set property name of #<Tool> which has only a getter" for
10
10
  * every real subclass, since none of them define a setter (same bug
package/src/consensus.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * clawser-mesh-consensus.js -- Voting and consensus protocols for BrowserMesh.
2
+ * consensus.mjs --Voting and consensus protocols for BrowserMesh.
3
3
  *
4
4
  * Supports simple majority, super majority (>66.7%), unanimous, and weighted
5
5
  * voting. Each Proposal tracks options, quorum, deadline, and status.
@@ -11,7 +11,7 @@
11
11
  * No browser-only imports at module level.
12
12
  *
13
13
  * Run tests:
14
- * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-consensus.test.mjs
14
+ * cd packages/browsermesh-apps && node --import ./test/_setup-globals.mjs --test test/consensus.test.mjs
15
15
  */
16
16
 
17
17
  import { MESH_TYPE } from '@johnhenry/browsermesh-primitives';
@@ -457,8 +457,8 @@ export class Tally {
457
457
  * weighted VOTING (see VoteType), not PBFT: there's no pre-prepare/
458
458
  * prepare/commit round, no view changes, and no Byzantine fault
459
459
  * tolerance guarantee (3f+1 quorum). For that, see the opt-in
460
- * `@johnhenry/raijin-consensus` package wired at clawser-pod.js's PBFT integration
461
- * (~line 417-478) — a separate, heavier protocol for when Byzantine
460
+ * `@johnhenry/raijin-consensus` package, wired in by the host application's
461
+ * PBFT integration — a separate, heavier protocol for when Byzantine
462
462
  * safety actually matters (e.g. payment finality). This class is the
463
463
  * lightweight default: mesh-wide polls, config changes, elections.
464
464
  */
@@ -711,7 +711,7 @@ export class ConsensusManager {
711
711
  const proposal = Proposal.fromJSON(payload);
712
712
  const tally = new Tally(proposal);
713
713
  this.#tallies.set(proposal.proposalId, tally);
714
- } catch (e) { silentCatch('clawser-mesh-consensus', 'ignore-malformed-proposals', e) }
714
+ } catch (e) { silentCatch('consensus', 'ignore-malformed-proposals', e) }
715
715
  });
716
716
 
717
717
  // Inbound: receive votes
@@ -719,12 +719,12 @@ export class ConsensusManager {
719
719
  try {
720
720
  const { proposalId, choice, weight } = payload;
721
721
  this.vote(proposalId, fromPodId, choice, weight ?? 1);
722
- } catch (e) { silentCatch('clawser-mesh-consensus', 'ignore-invalid-votes', e) }
722
+ } catch (e) { silentCatch('consensus', 'ignore-invalid-votes', e) }
723
723
  });
724
724
 
725
725
  // Inbound: receive close requests
726
726
  subscribeFn(CONSENSUS_CLOSE, (payload, fromPodId) => {
727
- try { this.closeProposal(payload.proposalId); } catch (e) { silentCatch('clawser-mesh-consensus', 'this.closeProposal', e) }
727
+ try { this.closeProposal(payload.proposalId); } catch (e) { silentCatch('consensus', 'this.closeProposal', e) }
728
728
  });
729
729
 
730
730
  // Inbound: receive results (informational, for sync)