@johnhenry/browsermesh-apps 0.1.1 → 0.3.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 (50) hide show
  1. package/README.md +443 -1
  2. package/package.json +18 -3
  3. package/src/agent-runtime.mjs +342 -0
  4. package/src/chunk-replication.mjs +751 -0
  5. package/src/cloud-storage-backend.mjs +932 -0
  6. package/src/cloud-storage.mjs +799 -0
  7. package/src/compat.mjs +98 -0
  8. package/src/gpu-kernel.mjs +242 -0
  9. package/src/gpu.mjs +101 -7
  10. package/src/grant-log.mjs +840 -0
  11. package/src/index.mjs +32 -2
  12. package/src/kernel-mesh.mjs +56 -0
  13. package/src/key-distribution.mjs +525 -0
  14. package/src/manifest-sync.mjs +363 -0
  15. package/src/mesh-agent-swarm.mjs +376 -0
  16. package/src/mesh-bootstrap.mjs +1481 -0
  17. package/src/mesh-compute.mjs +397 -0
  18. package/src/mesh-dht.mjs +182 -0
  19. package/src/mesh-fetch.mjs +246 -0
  20. package/src/mesh-hardening.mjs +226 -0
  21. package/src/mesh-health.mjs +282 -0
  22. package/src/mesh-keepalive.mjs +353 -0
  23. package/src/mesh-kv.mjs +673 -0
  24. package/src/mesh-orchestrator-tools.mjs +251 -0
  25. package/src/mesh-orchestrator.mjs +343 -0
  26. package/src/mesh-relay-backend.mjs +289 -0
  27. package/src/mesh-relay-host.mjs +362 -0
  28. package/src/mesh-rpc.mjs +300 -0
  29. package/src/mesh-service.mjs +403 -0
  30. package/src/mesh-swarm.mjs +677 -0
  31. package/src/mesh-sync.mjs +253 -0
  32. package/src/mesh-timestamp.mjs +265 -0
  33. package/src/mesh-torrent.mjs +683 -0
  34. package/src/mesh-verification.mjs +367 -0
  35. package/src/mesh-websocket.mjs +722 -0
  36. package/src/observability-bridge.mjs +453 -0
  37. package/src/orchestrator.mjs +18 -5
  38. package/src/peer-agent-swarm.mjs +12 -1
  39. package/src/peer-chat.mjs +230 -61
  40. package/src/peer-compute.mjs +66 -3
  41. package/src/peer-escrow.mjs +350 -1
  42. package/src/peer-files.mjs +362 -168
  43. package/src/peer-ipfs.mjs +205 -10
  44. package/src/peer-node.mjs +127 -19
  45. package/src/peer-registry.mjs +242 -18
  46. package/src/peer-routing.mjs +369 -5
  47. package/src/peer-terminal.mjs +400 -130
  48. package/src/signaling.mjs +231 -0
  49. package/src/webrtc-negotiator.mjs +209 -0
  50. package/src/peer-session.mjs +0 -937
package/README.md CHANGED
@@ -21,6 +21,10 @@ Extracted from the private `clawser` monorepo (previously `packages/browsermesh-
21
21
  | scheduler | `MeshScheduler`, `TaskQueue` |
22
22
  | consensus | `ConsensusManager`, `Proposal`, `Ballot` |
23
23
  | orchestrator | `MeshOrchestrator` + meshctl BrowserTool subclasses |
24
+ | mesh-orchestrator | `createOrchestratorService` (`MeshService` wrapper: real, gated wire dispatch for `execOnPod`/`deploySkill`/`drainPod`, ungated local aggregation for `listPods`/`getPodStatus`/`topPods`) |
25
+ | compat | `BrowserTool`, `BrowserToolRegistry` (base class + registry an LLM-drivable agent loop dispatches tool calls through) |
26
+ | agent-runtime | `createAgentRuntime` (the LLM tool-calling dispatch loop: bring-your-own `llmFn`, real registry-backed tool execution) |
27
+ | mesh-orchestrator-tools | `registerOrchestratorTools`, `createOrchestratorToolRegistry` (wires the 8 real `Meshctl*Tool`s into a `BrowserToolRegistry` against a real, attached `MeshOrchestrator`) |
24
28
  | audit | `AuditChain`, `AuditStore`, `detectFork`, `buildMerkleRoot` |
25
29
  | visualizations | `TopologyLayout`, `TrustGraphLayout`, `TrustHeatmap` |
26
30
  | devtools | `MeshInspector`, `MeshInspectTool` |
@@ -39,12 +43,86 @@ Extracted from the private `clawser` monorepo (previously `packages/browsermesh-
39
43
  | peer-registry | `PeerRegistry` |
40
44
  | peer-routing | `MeshRouter`, `ServerSharing` |
41
45
  | peer-services | `ServiceAdvertiser`, `ServiceBrowser` |
42
- | peer-session | `PeerSession`, `SessionManager` |
43
46
  | peer-terminal | `TerminalHost`, `TerminalClient` |
44
47
  | peer-timestamp | `TimestampAuthority`, `TimestampProof` |
45
48
  | peer-torrent | `TorrentManager` |
46
49
  | peer-verification | `VerificationQuorum`, `Attestation` |
47
50
  | marketplace-ui | `SkillMarketplace` |
51
+ | mesh-relay-host | `MeshRelayHost` |
52
+ | mesh-relay-backend | `MeshRelayBackend` |
53
+ | mesh-service | `attachService`, `MeshService` (attach convention) |
54
+ | cloud-storage-backend | `CloudStorageBackend` |
55
+ | grant-log | `GrantLog`, `createGrantLogService` |
56
+ | key-distribution | `createKeyDistributionService` |
57
+ | manifest-sync | `createManifestSyncService` |
58
+ | chunk-replication | `createChunkReplicationService` |
59
+ | cloud-storage | `CloudStorage`, `CloudStorageNotFoundError` (the ergonomic S3-like SDK) |
60
+
61
+ ## GPU compute
62
+
63
+ `GradientAggregator.aggregateGPU(device)` runs a real WGSL compute shader
64
+ (`src/gpu-kernel.mjs`) to aggregate submitted gradients when given a usable
65
+ `GPUDevice` -- one thread per output parameter index, covering both
66
+ `aggregate()`'s aggregation strategies (weighted `federated_avg`, unweighted
67
+ `sync_allreduce`/`async_parameter_server`) via a uniform flag. The compiled
68
+ shader module/pipeline is cached per-device.
69
+
70
+ It is entirely optional and degrades safely: called with no device, or a
71
+ device whose `limits.maxStorageBufferBindingSize` is too small for the
72
+ flattened gradient buffer, it falls back to the existing synchronous
73
+ `aggregate()` CPU implementation (wrapped in a resolved Promise). That
74
+ fallback is exercised unconditionally in `test/gpu.test.mjs` and needs no
75
+ GPU -- it is what keeps this package's normal `npm test` green everywhere,
76
+ including CI.
77
+
78
+ `TrainingOrchestrator` accepts an optional `{ gpuDevice }` constructor
79
+ option; when supplied, `handleGradientPush()` uses it once a job's
80
+ aggregator has every shard's gradient, and stores the result on the job
81
+ record (retrievable via `getJobResult(jobId)`, and included in
82
+ `getJobStatus()`'s return).
83
+
84
+ Coverage against a *real* WebGPU implementation (not just the fallback
85
+ branch) lives in `test/gpu-real-webgpu/kernel.test.mjs`, gated behind the
86
+ optional `webgpu` devDependency, run via `npm run test:real-gpu`
87
+ (`REQUIRE_WEBGPU=1 npm run test:real-gpu` to make an absent/non-functional
88
+ binding a hard failure rather than a silent skip -- see that file for the
89
+ full rationale, which mirrors `browsermesh-transport`'s `test:real-peer`
90
+ pattern).
91
+
92
+ **Headless CI finding**: this tier is deliberately **not** wired into CI
93
+ (see `.github/workflows/ci.yml`) -- run it locally/manually via
94
+ `npm run test:real-gpu`. Getting a real adapter/device at all took work: on
95
+ a bare `ubuntu-latest`-equivalent image with no GPU hardware,
96
+ `requestAdapter()` returns `null` -- Dawn's Vulkan backend has no ICD to
97
+ talk to at all (`libvulkan.so.1` isn't installed by default, so there's
98
+ nothing to even attempt a software fallback through). Installing
99
+ `libvulkan1` and `mesa-vulkan-drivers` (Mesa's `llvmpipe`/lavapipe software
100
+ rasterizer) does make a real adapter/device available headlessly, and the
101
+ shader's actual compute output (both the weighted and unweighted branches)
102
+ was verified correct against it, cross-checked against the CPU
103
+ `aggregate()` path -- confirmed on a local emulated approximation of that
104
+ environment.
105
+
106
+ But wiring that into an actual CI step and running it against this repo's
107
+ real GitHub-hosted `ubuntu-latest` runner surfaced a second problem the
108
+ local approximation didn't: a deterministic **native crash** inside the
109
+ `webgpu` binding itself, partway through the very first test, right as
110
+ `GPUBuffer.mapAsync()`'s cross-thread completion callback fires:
111
+
112
+ ```
113
+ Fatal glibc error: pthread_mutex_lock.c:94 (___pthread_mutex_lock): assertion failed: mutex->__data.__owner == 0
114
+ ```
115
+
116
+ That's a threading bug in `dawn.node`'s own native code (a pthread mutex
117
+ locked from the wrong owning thread), not in this package's WGSL or JS --
118
+ and it didn't reproduce locally, most likely because the local
119
+ approximation ran the same Ubuntu image under QEMU emulation, which serializes/
120
+ slows execution enough to mask a real-hardware timing race. There is no
121
+ JS-level try/catch that can turn a native process crash into a clean test
122
+ failure, let alone a graceful skip, so this tier cannot be safely made a
123
+ required CI check today. It stays a real, valuable, but local-only/manual
124
+ verification path until either the upstream binding fixes this, or a
125
+ different Node WebGPU binding is adopted.
48
126
 
49
127
  ## Install
50
128
 
@@ -58,6 +136,370 @@ npm install @johnhenry/browsermesh-apps @johnhenry/browsermesh-primitives @johnh
58
136
  import { MeshChat, AppRegistry, MeshOrchestrator } from 'browsermesh-apps';
59
137
  ```
60
138
 
139
+ ## Connecting a real mesh node: `createMeshNode()`
140
+
141
+ `mesh-bootstrap.mjs`'s `createMeshNode(options)` is the composition root that
142
+ wires a real Ed25519 identity, discovery, and a real WebRTC transport
143
+ negotiator into a booted `PeerNode`. A minimal call needs only an injectable
144
+ signaling transport (see `signaling.mjs`) to relay WebRTC offer/answer/ICE
145
+ messages between peers:
146
+
147
+ ```js
148
+ import { createMeshNode } from '@johnhenry/browsermesh-apps';
149
+
150
+ const node = await createMeshNode({
151
+ signalingTransport, // a {send(msg), onMessage(cb)} bus -- see signaling.mjs
152
+ });
153
+ ```
154
+
155
+ ### TURN server configuration
156
+
157
+ By default, `createMeshNode()` gathers **no ICE servers at all** (no STUN,
158
+ no TURN) -- host candidates only, which is enough for peers on the same LAN
159
+ and discloses nothing to a third party. That's fine for typical NAT, but
160
+ peers behind symmetric or restrictive NATs need a STUN and/or TURN server to
161
+ connect at all.
162
+
163
+ Pass standard `RTCIceServer`-shaped entries via `options.iceServers`:
164
+
165
+ ```js
166
+ import { createMeshNode } from '@johnhenry/browsermesh-apps';
167
+ import { PUBLIC_STUN_SERVERS } from '@johnhenry/browsermesh-transport';
168
+
169
+ const node = await createMeshNode({
170
+ signalingTransport,
171
+ iceServers: [
172
+ ...PUBLIC_STUN_SERVERS, // opt-in public STUN (see browsermesh-transport's webrtc.mjs)
173
+ { urls: 'turn:turn.example.com:3478', username: 'alice', credential: 's3cr3t' },
174
+ ],
175
+ });
176
+ ```
177
+
178
+ `iceServers` is merged with `DEFAULT_ICE_SERVERS` via
179
+ `@johnhenry/browsermesh-transport`'s `mergeIceServers()` -- the same
180
+ extension point `webrtc.mjs` already exposes, reused here rather than
181
+ reimplemented:
182
+
183
+ - Omit the option, or pass `undefined`/`null`, to keep the default (no ICE
184
+ servers).
185
+ - Pass a non-empty array (TURN and/or STUN entries) to **add** them
186
+ alongside the defaults; malformed entries (missing `urls`) are silently
187
+ dropped rather than passed through to `RTCPeerConnection`.
188
+ - Pass an explicit `iceServers: []` to mean "no ICE servers at all" --
189
+ honoured as given, never replaced by the defaults. This is what this
190
+ package's own `test/real-peer/mesh-bootstrap.test.mjs` uses for a
191
+ hermetic, loopback-only connection in CI.
192
+
193
+ This reaches the `WebRTCMeshManager` that `createMeshNode()` attaches to the
194
+ returned node as `node.meshManager`, and from there every
195
+ `WebRTCPeerConnection` it creates.
196
+
197
+ ## Sharing a `VirtualNetwork` with specific peers: mesh relay
198
+
199
+ Real-world scenario: your peer already reaches a real local service (e.g. an
200
+ S3-compatible emulator, via `@johnhenry/browsermesh-netway`'s `GatewayBackend`
201
+ tunneling real TCP through a local `wsh` server) on its own `VirtualNetwork`.
202
+ `MeshRelayHost`/`MeshRelayBackend` let you share *that specific access* with
203
+ specific, authorized mesh peers over the real WebRTC connection you already
204
+ have -- gated per-peer, per-service, per-action, with zero new authorization
205
+ machinery.
206
+
207
+ On the host side (the peer whose `VirtualNetwork` is being shared), either
208
+ pass `{ enableRelayHost: true, relayHostNetwork }` to `createMeshNode()`:
209
+
210
+ ```js
211
+ import { createMeshNode } from '@johnhenry/browsermesh-apps';
212
+
213
+ const alice = await createMeshNode({
214
+ signalingTransport,
215
+ enableRelayHost: true,
216
+ relayHostNetwork: aliceNetwork, // alice's own VirtualNetwork
217
+ relayHostServices: { 's3-local': 'tcp://127.0.0.1:9000' },
218
+ });
219
+ // alice.relayHost.exposeService(name, targetAddress) / .hideService(name)
220
+ // are also available for exposing services after boot.
221
+ ```
222
+
223
+ or construct a `MeshRelayHost` directly against any booted `PeerNode`. Then
224
+ grant specific peers access to specific services via `PeerRegistry`'s
225
+ existing capability API -- no new scope grammar, just
226
+ `mesh-relay:<service>:connect` (wildcards like `mesh-relay:*:connect` work
227
+ too, since `MeshACL`'s scope matching already supports them):
228
+
229
+ ```js
230
+ alice.registry.grantCapabilities(bob.podId, ['mesh-relay:s3-local:connect']);
231
+ // ...later, to cut Bob off:
232
+ alice.registry.revokeCapabilities(bob.podId, ['mesh-relay:s3-local:connect']);
233
+ ```
234
+
235
+ On the client side (the peer being granted access), `MeshRelayBackend` is a
236
+ `browsermesh-netway` `Backend` -- register it on your own `VirtualNetwork`
237
+ under any scheme you like, and connect through the normal API, treating the
238
+ service name as the "host":
239
+
240
+ ```js
241
+ import { MeshRelayBackend } from '@johnhenry/browsermesh-apps';
242
+ import { VirtualNetwork } from '@johnhenry/browsermesh-netway';
243
+
244
+ const bobNetwork = new VirtualNetwork();
245
+ bobNetwork.addBackend('via-alice', new MeshRelayBackend({ node: bob, relayPeerPubKey: alice.podId }));
246
+
247
+ const socket = await bobNetwork.connect('via-alice://s3-local'); // refused (ConnectionRefusedError) until granted
248
+ ```
249
+
250
+ TCP-only for now (`listen()`/`bindDatagram()` on `MeshRelayBackend` are the
251
+ inherited `Backend` "not implemented" throws). See
252
+ `examples/06-mesh-relay.mjs` for a full runnable walkthrough (in-process
253
+ simulated mesh connection) and
254
+ `test/real-peer/mesh-relay.test.mjs` for the real-WebRTC, real-TCP proof.
255
+
256
+ ## CloudStorage bucket authorization and key distribution
257
+
258
+ `grant-log.mjs`'s `GrantLog` (`createGrantLogService()`) is a replicated,
259
+ Ed25519-signed append-log of `grant`/`revoke` records per bucket resource
260
+ (`s3:<bucketId>`), used to propagate a CloudStorage bucket's access-control
261
+ decisions to every peer independently enforcing them (each peer replays the
262
+ merged log into its own, unmodified `PeerRegistry.grantCapabilities()`/
263
+ `revokeCapabilities()`).
264
+
265
+ `key-distribution.mjs`'s `createKeyDistributionService()` builds on top of
266
+ `GrantLog`'s change notifications: whenever a peer's merged, effective grants
267
+ on a bucket go from none to some, a peer that already holds that bucket's
268
+ AES-256-GCM key (`cloud-storage-backend.mjs`'s `CloudStorageBackend`) sends it
269
+ to the newly-granted peer over a dedicated, signed, point-to-point channel,
270
+ encrypted to a companion X25519 key the recipient generates and advertises
271
+ for exactly this purpose (Ed25519 identity keys can't do ECDH directly, and
272
+ this repo intentionally has no Ed25519-to-X25519 conversion utility -- see
273
+ that file's own doc comment for the full writeup, including why the wrap/
274
+ unwrap step itself reuses `browsermesh-core`'s existing `wrapKeyForMember()`/
275
+ `unwrapKeyForMember()` rather than adding a new crypto primitive).
276
+
277
+ **Permanent limitation, not a bug to fix later:** revoking a peer's grant
278
+ (via `GrantLog.revoke()`) stops *future* key distribution and *future* chunk
279
+ replication to that peer, but cannot retroactively erase a key -- or any
280
+ plaintext already decrypted with it -- already delivered to that peer before
281
+ the revoke. A bucket's AES key is never rotated on revoke anywhere in this
282
+ plan. Any since-revoked peer that retained the key (or any chunk ciphertext
283
+ plus the key) can still decrypt that data offline, forever. This is a
284
+ fundamental property of any scheme that hands symmetric key material to
285
+ multiple independent parties -- the same is true of, say, a downloaded S3
286
+ object whose bucket policy changes afterward -- not something a future phase
287
+ of this plan is expected to close.
288
+
289
+ ## CloudStorage: the ergonomic SDK
290
+
291
+ `cloud-storage.mjs`'s `CloudStorage` class is the actual developer-facing
292
+ surface the whole plan above was building toward:
293
+
294
+ ```js
295
+ import { CloudStorage as s3 } from '@johnhenry/browsermesh-apps'
296
+ const store = new s3({ bucket: 'my-bucket', node: peerNode })
297
+ await store.becomeAdmin() // bootstrap: this peer owns the bucket
298
+ await store.grant(otherPubKey, ['read', 'write'])
299
+ const { durability, replicatedTo } = await store.put('key', data)
300
+ const bytes = await store.get('key') // falls back to a remote peer request if not held locally
301
+ ```
302
+
303
+ It composes `CloudStorageBackend` (local, durable, encrypted-at-rest reads/
304
+ writes) with `createGrantLogService()`, `createKeyDistributionService()`,
305
+ `createManifestSyncService()`, and `createChunkReplicationService()` — all
306
+ four attached via `attachService()` with no `network` required — behind
307
+ `put`/`get`/`delete`/`list` plus bucket-admin methods
308
+ (`becomeAdmin`/`grant`/`revoke`/`designateReplica`/`effectiveGrants`). See
309
+ `src/cloud-storage.mjs`'s own module doc comment for the full design
310
+ writeup, including several real gaps the plan's original brief left open and
311
+ exactly how each was resolved.
312
+
313
+ `examples/09-cloud-storage.mjs` is the full story end to end, runnable with
314
+ plain `node`. `test/real-peer/cloud-storage.test.mjs` proves the identical
315
+ composition over an actual WebRTC connection. **New to building a
316
+ mesh-native service yourself?** `docs/building-mesh-services.md` is the
317
+ reusable guide this phase (K, the plan's capstone) produced — the
318
+ `MeshService` attach contract, the control/data-plane transport split, the
319
+ CRDT-manifest-plus-content-addressed-chunk pattern, the signed
320
+ GrantLog pattern, and the key-distribution pattern, each with pointers to
321
+ the real code, written so the *next* mesh-native service doesn't have to
322
+ rediscover these same design questions from scratch.
323
+
324
+ ## Putting it all together: sync + kernel-gated mesh + relay on one connection
325
+
326
+ Every composition layer above (`enableSync`, a `Kernel` wired via
327
+ `createMeshKernel({ peerNode })`, and `enableRelayHost`) attaches to the
328
+ *same* `PeerNode` independently -- nothing about wiring one requires or
329
+ excludes the others, and each dispatches on `PeerNode`'s shared
330
+ `onIncomingData()` bus, filtering by its own `envelope.type` (`'mesh-sync'`,
331
+ `'mesh-relay'`; the kernel's `caps.mesh` view is unfiltered -- see below).
332
+
333
+ `test/real-peer/full-pipeline.test.mjs` proves all three actually compose on
334
+ one live, real WebRTC connection: CRDT sync converges, a kernel tenant's
335
+ `caps.mesh.send()`/`onReceive()` moves real bytes, and a mesh-relay round
336
+ trip completes, all interleaved on the same `PeerNode` pair, with no
337
+ envelope-type collisions or dispatch corruption between them.
338
+ `examples/07-full-mesh-pipeline.mjs` is the same story narrated for a human
339
+ reader (in-process simulated connection, like `06`).
340
+
341
+ One property worth knowing if you wire a kernel mesh capability alongside
342
+ sync/relay: `Kernel#meshFor()`'s `onReceive` is **not** scoped by
343
+ `envelope.type` the way `MeshSyncBinding`/`MeshRelayHost` are -- a kernel
344
+ tenant's `caps.mesh.onReceive` callback sees every inbound payload on the
345
+ connection, including `mesh-sync`/`mesh-relay`-typed envelopes not meant for
346
+ it (harmless -- those envelopes are just plain objects with a `.type` field
347
+ tenant code can filter on itself if it cares, but worth knowing rather than
348
+ assuming the view is pre-filtered).
349
+
350
+ ## `fetch()`/`WebSocket`-shaped mesh access: `browserMeshFetch` and `BrowserMeshWebSocket`
351
+
352
+ Two web-standard-API-shaped wrappers over a mesh connection, so existing
353
+ code that already expects `fetch(url) -> Response` or `new WebSocket(url)`
354
+ can reach a mesh-addressable pod (`mesh://podId/path`) without learning
355
+ `PeerNode`'s raw `sendTo()`/`onIncomingData()` API. Both are built on
356
+ `mesh-rpc.mjs`'s `createMeshRpcService()`, a general-purpose request/response
357
+ transport over the same `ctx.sendTo()`/`ctx.onIncomingData()` convention
358
+ every `MeshService` in this family uses (attach it via
359
+ `attachService(peerNode, network, createMeshRpcService({ onRequest }))`, or
360
+ pass it through `createMeshNode({ services: [...] })`).
361
+
362
+ **Authorization boundary, stated explicitly because it's easy to miss:**
363
+ neither transport checks `registry.checkAccess()` against any fixed
364
+ resource/scope -- a general-purpose RPC/duplex channel has no fixed resource
365
+ to check a scope against. Deciding what `{method, path}` combinations (for
366
+ `browserMeshFetch`) or which `(fromPubKey, path)` connections (for
367
+ `BrowserMeshWebSocket`) are allowed is the *responding pod's own*
368
+ `onRequest`/`onConnection` handler's job, the same way a real HTTP server's
369
+ application code owns its own authorization, not its TCP/TLS transport
370
+ layer.
371
+
372
+ ### `browserMeshFetch`
373
+
374
+ `createBrowserMeshFetch(meshRpcApi) -> (url, init) => Promise<Response>` binds
375
+ once to a live `mesh-rpc` service's `api` (the `{ request }` object
376
+ `attachService()` returns as `.api`) and hands back a plain function whose
377
+ call signature matches real `fetch(url, init)` exactly -- so it can be
378
+ dropped in anywhere something expects "a fetch-shaped function", with no
379
+ adapter:
380
+
381
+ ```js
382
+ import { attachService, createMeshRpcService, createBrowserMeshFetch } from '@johnhenry/browsermesh-apps'
383
+
384
+ // on the peer being called:
385
+ attachService(bobNode, undefined, createMeshRpcService({
386
+ onRequest: async ({ method, path, body }) => {
387
+ if (method === 'GET' && path === '/status') return { status: 200, body: { ok: true } }
388
+ return { status: 404, body: { error: 'not found' } }
389
+ },
390
+ }))
391
+
392
+ // on the calling peer:
393
+ const { api } = attachService(aliceNode, undefined, createMeshRpcService({}))
394
+ const browserMeshFetch = createBrowserMeshFetch(api)
395
+
396
+ const res = await browserMeshFetch('mesh://bob-pod-id/status')
397
+ const data = await res.json() // { ok: true }
398
+ ```
399
+
400
+ Error-vs-reject semantics deliberately match real `fetch()`, not a Service
401
+ Worker interceptor's "always resolve some Response" convention: a malformed
402
+ `mesh://`/`*.mesh.local` URL throws a `TypeError` *synchronously*, before any
403
+ Promise exists; a responding pod's `onRequest` throwing or returning a
404
+ non-2xx `status` still resolves a genuine `Response` (status/headers/body
405
+ shaped from whatever it returned); only a transport-level failure -- no
406
+ matching response within the timeout, or the peer being unreachable --
407
+ *rejects* the returned promise, matching what a real network-level `fetch()`
408
+ failure means.
409
+
410
+ ### `BrowserMeshWebSocket`
411
+
412
+ A class implementing the standard `WebSocket` *instance* surface
413
+ (`readyState`, `onopen`/`onmessage`/`onerror`/`onclose`,
414
+ `addEventListener`/`removeEventListener`, `send()`, `close()`) over a
415
+ persistent mesh envelope channel. **One real, deliberate deviation from the
416
+ standard constructor:** `new WebSocket(url)` needs no extra arguments
417
+ because a browser's networking stack is an ambient, process-wide resource --
418
+ there is no mesh equivalent, so `new BrowserMeshWebSocket(url, opts)`
419
+ requires `opts.peerNode` (anything exposing `podId`, `sendTo()`,
420
+ `onIncomingData()` -- a real `PeerNode` satisfies this). Everything else
421
+ matches the standard instance shape as closely as this transport allows.
422
+
423
+ ```js
424
+ import { BrowserMeshWebSocket, attachService, createMeshWebSocketService } from '@johnhenry/browsermesh-apps'
425
+
426
+ // on the peer accepting connections -- the ONLY side that needs a MeshService
427
+ // attached; a client-role BrowserMeshWebSocket subscribes directly to its
428
+ // own peerNode and needs nothing pre-attached:
429
+ attachService(bobNode, undefined, createMeshWebSocketService({
430
+ onConnection: (fromPubKey, path) => path === '/chat', // accept/reject policy lives here
431
+ onIncomingConnection: (session) => {
432
+ session.onmessage = (event) => session.send(`echo: ${event.data}`)
433
+ },
434
+ }))
435
+
436
+ // on the connecting peer:
437
+ const socket = new BrowserMeshWebSocket('mesh://bob-pod-id/chat', { peerNode: aliceNode })
438
+ socket.onopen = () => socket.send('hello')
439
+ socket.onmessage = (event) => console.log(event.data) // 'echo: hello'
440
+ ```
441
+
442
+ The accept/reject handshake is `createMeshWebSocketService({ onConnection })`'s
443
+ job entirely: `onConnection(fromPubKey, path) -> boolean|Promise<boolean>`
444
+ decides per inbound connection attempt. No `onConnection` registered means
445
+ every inbound connection is rejected (the safe default -- an "open door" is a
446
+ worse default than an RPC transport's "not implemented" 501). A rejected
447
+ attempt fires the connecting side's `onerror` then `onclose` with code
448
+ `4403`; a connection that never gets a response within the open timeout
449
+ (10s default) closes with code `1006`, mirroring real `WebSocket`'s own
450
+ abnormal-closure code. `send()` throws `InvalidStateError` both before OPEN
451
+ *and* after CLOSE -- the latter a deliberate deviation from the WHATWG spec
452
+ (which silently drops a post-close `send()`), judged a worse default for
453
+ mesh code than a loud, discoverable throw. `close()` is a one-directional
454
+ notification, not a two-phase closing handshake -- there's no TCP-level
455
+ half-open state to model over a persistent mesh envelope channel. See
456
+ `src/mesh-websocket.mjs`'s module doc comment for the full wire-protocol and
457
+ binary-encoding (base64-over-JSON) writeup.
458
+
459
+ `examples/08-mesh-fetch-websocket.mjs` runs both APIs together end to end
460
+ (request/response, and a duplex exchange including both the accept and
461
+ reject halves of the handshake) over a simulated in-process connection.
462
+
463
+ **Considered, deferred:** extending this same "web-standard-API-shaped
464
+ wrapper" treatment to `WebTransport`/`RTCDataChannel` was evaluated and
465
+ deliberately not scoped here -- see `browsermesh-fetch-websocket.md`'s own
466
+ "Considered, deferred" section for the reasoning (mostly: avoid adding more
467
+ unconsumed wrapper surface before these two have a real caller).
468
+
469
+ ## LLM tool-calling: `BrowserToolRegistry` and `createAgentRuntime`
470
+
471
+ A second, deliberately different composition pattern from `MeshService`:
472
+ where `MeshService`/`attachService()` (above) is "how a capability attaches
473
+ to a `PeerNode`," `BrowserTool`/`BrowserToolRegistry`/`createAgentRuntime`
474
+ is "how you expose local OR mesh-backed capabilities to an LLM-driven agent
475
+ loop." `compat.mjs`'s `BrowserToolRegistry` holds any number of `BrowserTool`
476
+ instances (`register`/`get`/`list`/`listSpecs`/`unregister`); `agent-runtime.mjs`'s
477
+ `createAgentRuntime({registry, llmFn})` is the actual conversation loop —
478
+ **browsermesh never calls a real LLM API itself** (no Anthropic/OpenAI SDK
479
+ dependency anywhere in this family); `llmFn(messages, toolSpecs) ->
480
+ {content?, toolCalls?}` is a required, caller-supplied callback, matching
481
+ `mesh-compute.mjs`'s `executeFn`/`mesh-agent-swarm.mjs`'s `agentProxy`
482
+ "bring your own X" precedent.
483
+
484
+ `mesh-orchestrator-tools.mjs`'s `registerOrchestratorTools()` is the worked
485
+ example of wiring a *mesh-backed* capability into this pattern: it
486
+ constructs `orchestrator.mjs`'s 8 real `Meshctl*Tool`s
487
+ (`meshctl_pods`/`meshctl_status`/`meshctl_exec`/`meshctl_deploy`/
488
+ `meshctl_top`/`meshctl_compute`/`meshctl_expose`/`meshctl_drain`) against a
489
+ real, attached `mesh-orchestrator.mjs` service, so an LLM-requested
490
+ `meshctl_exec` tool call really dispatches through that service's
491
+ `checkAccess()`-gated wire protocol to a real remote peer.
492
+ `createMeshNode({enableAgentRuntime: true, enableOrchestrator: true})` wires
493
+ all of this for you, returning `node.toolRegistry` pre-populated and ready
494
+ to drive `createAgentRuntime({registry: node.toolRegistry, llmFn})`.
495
+
496
+ `examples/11-agent-tool-calling.mjs` runs the whole story end to end over
497
+ two real `createMeshNode()` peers, with a deterministic test `llmFn`. See
498
+ `docs/building-mesh-services.md`'s own "`BrowserTool`/`BrowserToolRegistry`/
499
+ agent runtime" section for the full design writeup, including two real bugs
500
+ found while building it and the recommended DI pattern for new tools going
501
+ forward.
502
+
61
503
  ## License
62
504
 
63
505
  MIT
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/browsermesh-apps",
3
- "version": "0.1.1",
3
+ "version": "0.3.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",
@@ -24,7 +24,9 @@
24
24
  "@johnhenry/browsermesh-core": ">=0.1.0 <1.0.0",
25
25
  "@johnhenry/browsermesh-transport": ">=0.1.0 <1.0.0",
26
26
  "@johnhenry/browsermesh-sync": ">=0.0.0 <1.0.0",
27
- "@johnhenry/browsermesh-discovery": ">=0.0.1 <1.0.0"
27
+ "@johnhenry/browsermesh-discovery": ">=0.0.1 <1.0.0",
28
+ "@johnhenry/browsermesh-kernel": ">=0.0.0 <1.0.0",
29
+ "@johnhenry/browsermesh-netway": ">=0.0.0 <1.0.0"
28
30
  },
29
31
  "peerDependenciesMeta": {
30
32
  "@johnhenry/browsermesh-transport": {
@@ -35,10 +37,23 @@
35
37
  },
36
38
  "@johnhenry/browsermesh-discovery": {
37
39
  "optional": true
40
+ },
41
+ "@johnhenry/browsermesh-kernel": {
42
+ "optional": true
43
+ },
44
+ "@johnhenry/browsermesh-netway": {
45
+ "optional": true
38
46
  }
39
47
  },
48
+ "devDependencies": {
49
+ "node-datachannel": "^0.33.4",
50
+ "fake-indexeddb": "^6.2.5",
51
+ "webgpu": "^0.6.1"
52
+ },
40
53
  "scripts": {
41
- "test": "node --import ./test/_setup-globals.mjs --test test/*.test.mjs"
54
+ "test": "node --import ./test/_setup-globals.mjs --test test/*.test.mjs",
55
+ "test:real-peer": "node --import ./test/_setup-globals.mjs --test --test-concurrency=1 test/real-peer/*.test.mjs",
56
+ "test:real-gpu": "node --import ./test/_setup-globals.mjs --test test/gpu-real-webgpu/*.test.mjs"
42
57
  },
43
58
  "homepage": "https://opensource.johnhenry.me/browsermesh/",
44
59
  "engines": {