@johnhenry/browsermesh-apps 0.2.0 → 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 (41) hide show
  1. package/README.md +232 -1
  2. package/package.json +2 -2
  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/grant-log.mjs +840 -0
  9. package/src/index.mjs +25 -2
  10. package/src/key-distribution.mjs +525 -0
  11. package/src/manifest-sync.mjs +363 -0
  12. package/src/mesh-agent-swarm.mjs +376 -0
  13. package/src/mesh-bootstrap.mjs +1131 -12
  14. package/src/mesh-compute.mjs +397 -0
  15. package/src/mesh-dht.mjs +182 -0
  16. package/src/mesh-fetch.mjs +246 -0
  17. package/src/mesh-hardening.mjs +226 -0
  18. package/src/mesh-health.mjs +282 -0
  19. package/src/mesh-keepalive.mjs +353 -0
  20. package/src/mesh-kv.mjs +673 -0
  21. package/src/mesh-orchestrator-tools.mjs +251 -0
  22. package/src/mesh-orchestrator.mjs +343 -0
  23. package/src/mesh-rpc.mjs +300 -0
  24. package/src/mesh-service.mjs +403 -0
  25. package/src/mesh-swarm.mjs +677 -0
  26. package/src/mesh-timestamp.mjs +265 -0
  27. package/src/mesh-torrent.mjs +683 -0
  28. package/src/mesh-verification.mjs +367 -0
  29. package/src/mesh-websocket.mjs +722 -0
  30. package/src/observability-bridge.mjs +453 -0
  31. package/src/orchestrator.mjs +18 -5
  32. package/src/peer-agent-swarm.mjs +12 -1
  33. package/src/peer-chat.mjs +230 -61
  34. package/src/peer-compute.mjs +66 -3
  35. package/src/peer-escrow.mjs +350 -1
  36. package/src/peer-files.mjs +362 -168
  37. package/src/peer-ipfs.mjs +205 -10
  38. package/src/peer-node.mjs +33 -2
  39. package/src/peer-routing.mjs +369 -5
  40. package/src/peer-terminal.mjs +400 -130
  41. package/src/peer-session.mjs +0 -937
@@ -56,6 +56,250 @@
56
56
  * `MeshRelayBackend`, constructed directly (not via this function) and
57
57
  * registered on the *client's own* `VirtualNetwork`.
58
58
  *
59
+ * **Transport hardening is opt-in via `{ enableHardening: true,
60
+ * hardeningOptions }`.** When set, the `MeshTransportNegotiator` this
61
+ * function constructs is wrapped (`mesh-hardening.mjs`'s
62
+ * `createHardenedNegotiator()`) with `@johnhenry/browsermesh-core`'s
63
+ * `hardening.mjs` primitives -- `RetryWithBackoff` (exponential backoff +
64
+ * circuit breaker, scoped per peer) and `TransportFailover` (transport-type
65
+ * failover) around every `connectToPeer()`'s negotiation attempt, plus
66
+ * `TransportMetrics`/`MetricsRegistry` for per-peer byte/message/error/
67
+ * latency counters -- before it is handed to `PeerNode`. This is what
68
+ * turns a transient WebRTC/ICE negotiation failure into a retried attempt
69
+ * instead of an immediate `connectToPeer()` rejection (see issue #26's
70
+ * documented WebRTC/ICE flakiness). Exposed as `node.hardening` (the full
71
+ * `{ metrics, failovers, retries }` bundle) and `node.transportMetrics`
72
+ * (alias for `node.hardening.metrics`, matching `node.sync`/`node.relayHost`'s
73
+ * convention of exposing the opt-in subsystem directly on the node).
74
+ * `ConnectionPool` is *not* wired here -- see `mesh-hardening.mjs`'s own
75
+ * header comment for why (no call site under `PeerNode`'s current
76
+ * one-session-per-peer model; deliberately deferred, see issue #110).
77
+ *
78
+ * **`TransportHealthCheck` IS wired, opt-in via `{ enableHealthCheck: true,
79
+ * healthCheckOptions }`** (issue #110, follow-up to the above). Unlike
80
+ * `enableHardening`, this doesn't wrap the negotiator -- it attaches
81
+ * `mesh-keepalive.mjs`'s `createMeshKeepaliveService()` as a `MeshService`
82
+ * (Phase C's `attach()`/`ctx` convention), which runs a real ping/pong
83
+ * keepalive envelope protocol per connected peer and feeds `'unhealthy'`
84
+ * transitions into `enableHardening`'s `TransportFailover` (if also on) and
85
+ * into `ctx.emit()` for observability. See `mesh-keepalive.mjs`'s own header
86
+ * comment for the full wire-protocol/lifecycle writeup. Exposed as
87
+ * `node.healthCheck` (the `attachService()` handle -- also reachable at
88
+ * `node.services.get('keepalive')`, same as any other opt-in service).
89
+ *
90
+ * **Multi-hop mesh routing is opt-in via `{ enableRouting: true,
91
+ * routingOptions }`** (issue #121). When set, this function attaches
92
+ * `peer-routing.mjs`'s `createMeshRoutingService()` -- wiring `MeshRouter`'s
93
+ * `forwardFn` onto `ctx.sendTo()` and its inbound dispatch onto
94
+ * `ctx.onIncomingData()`, so this node can forward messages to peers it has
95
+ * no direct connection to, via any intermediate peer(s) with a known route
96
+ * (see `peer-routing.mjs`'s own header for the full multi-hop design). If
97
+ * `routingOptions.fetchFn` is supplied (even `null`), `ServerSharing` is
98
+ * also wired, letting other peers proxy HTTP requests to a local server this
99
+ * node has `expose()`d. Attached to the returned node as `node.router` (the
100
+ * `attachService()` handle -- also reachable at
101
+ * `node.services.get('mesh-routing')`, same as any other opt-in service).
102
+ *
103
+ * **Mesh-local IPFS-style content storage is opt-in via `{ enableIpfs: true,
104
+ * ipfsOptions }`** (issue #123). When set, this function attaches
105
+ * `peer-ipfs.mjs`'s `createIpfsService()` -- wrapping a fresh `IPFSStore`
106
+ * (content-addressed `add`/`get`/`pin`/`unpin`/`remove`/`listCids`/
107
+ * `getStats`/`close`, `ChunkStore`-compatible SHA-256 CIDs) as a
108
+ * `MeshService`, bridging its own `on`/`off` events through `ctx.emit()`.
109
+ * **Despite the name, this is NOT wired to a real IPFS network today** --
110
+ * see `peer-ipfs.mjs`'s own header comment ("HONEST STATUS OF HELIA/IPFS")
111
+ * for the full, verified explanation: `helia` is not a dependency anywhere
112
+ * in this repo, and even when `ensureLoaded()`'s CDN-loaded Helia instance
113
+ * succeeds, no storage operation actually calls into it. Each node's store
114
+ * is also entirely local -- `createIpfsService()` adds no wire protocol, so
115
+ * content is never visible across peers, unlike `CloudStorage`'s replicated
116
+ * chunks. Attached to the returned node as `node.ipfs` (the
117
+ * `attachService()` handle -- also reachable via
118
+ * `node.services.get('peer-ipfs')`).
119
+ *
120
+ * **Escrow (real credit/payment holds) is opt-in via `{ enableEscrow: true,
121
+ * escrowOptions: { creditLedger } }`** (issue #117). When set, this function
122
+ * attaches `peer-escrow.mjs`'s `createEscrowService()` -- wiring
123
+ * `EscrowManager` (`create`/`release`/`refund`/`dispute`/`checkExpired`
124
+ * against the caller-supplied `creditLedger`) so a peer can ask this node
125
+ * (or this node can ask another peer's own `enableEscrow` node) to hold
126
+ * credits in escrow. `escrowOptions.creditLedger` is REQUIRED -- there is no
127
+ * default ledger, matching the `enableRelayHost`/`relayHostNetwork`
128
+ * "opt-in flag needs its one real dependency supplied explicitly" pattern
129
+ * (this function throws if `enableEscrow` is set with no
130
+ * `escrowOptions.creditLedger`). See `peer-escrow.mjs`'s own
131
+ * `createEscrowService()` doc comment for the full authorization model
132
+ * (peer-initiated `create`/`release`/`refund`/`dispute` are individually
133
+ * gated via `registry.checkAccess()`; `getContract`/`listContracts`/
134
+ * `getStats`/`checkExpired` are local-only, never wire-exposed). Attached
135
+ * to the returned node as `node.escrow` (the `attachService()` handle --
136
+ * also reachable at `node.services.get('escrow')`, same as any other
137
+ * opt-in service).
138
+ *
139
+ * **Mesh-native services are opt-in via `{ services: [...] }`** (Phase C).
140
+ * Each entry is a `MeshService` descriptor (`mesh-service.mjs`) attached via
141
+ * `attachService()`, mirroring the `enableRelayHost`/`relayHostServices`
142
+ * opt-in shape exactly -- this is the generic version of that pattern, for
143
+ * services beyond mesh-relay (the first consumer is the CloudStorage plan's
144
+ * later phases). Results are stored in `node.services`, a `Map<string,
145
+ * { name, backendScheme, teardown }>` keyed by descriptor name, always
146
+ * present (empty if `services` is omitted).
147
+ *
148
+ * **The audit trail is opt-in via `{ enableAudit: true }`** (or by passing
149
+ * an already-constructed `{ auditChain }`, the same "boolean toggle for a
150
+ * default, or supply your own instance" shape `enableSync`/`syncStorage`
151
+ * already establishes). Unlike `sync`/`relayHost`, the resulting
152
+ * `AuditChain` (`audit.mjs`) has to exist *before* `PeerNode` is
153
+ * constructed -- it's a constructor-time dependency, not something attached
154
+ * to the node afterwards -- so this function builds it (or accepts a
155
+ * caller-supplied one) right after the local identity is created and passes
156
+ * it straight into `new PeerNode({ ..., auditChain })`. `AuditChain` itself
157
+ * needs no signing key at construction; `PeerNode`'s `#audit()` already
158
+ * signs every entry with the node's own identity via `wallet.sign()`, so
159
+ * `enableAudit: true` only needs a `chainId` (defaults to `audit-${podId}`,
160
+ * overridable via `auditChainId`). The instance is attached as
161
+ * `node.auditChain`, mirroring `node.sync`/`node.relayHost`'s convention;
162
+ * it is left unset when neither `enableAudit` nor `auditChain` is supplied,
163
+ * so `PeerNode`'s audit path silently no-ops exactly as it did before this
164
+ * option existed.
165
+ *
166
+ * **DHT discovery is opt-in via `{ enableDht: true, dhtBootstrapPeers }`**
167
+ * (Phase D, issue #87). `@johnhenry/browsermesh-discovery`'s
168
+ * `DhtDiscoveryStrategy` (dht.mjs) is a real, tested Kademlia
169
+ * `DiscoveryStrategy` implementation that was never constructed anywhere in
170
+ * this repo -- it only takes a bare `sendFn`, with no transport of its own.
171
+ * When set, this function constructs one via `mesh-dht.mjs`'s
172
+ * `createMeshDht()`, multiplexing its wire traffic onto the same
173
+ * `signalingTransport` bus already required for WebRTC signaling (the one
174
+ * thing in this architecture that already reaches arbitrary podIds before a
175
+ * WebRTC connection exists), and adds it to `discoveryStrategies`. This is
176
+ * NOT a full rendezvous solution: `dhtBootstrapPeers` must supply at least
177
+ * one already-known peer podId out-of-band, or the node has no way to find
178
+ * its first DHT contact -- see `mesh-dht.mjs`'s header for the full
179
+ * explanation of what this does and does not solve. The constructed
180
+ * strategy is attached as `node.dht`.
181
+ *
182
+ * **`peer-timestamp.mjs`/`peer-health.mjs` are opt-in via `{ enableTimestamp,
183
+ * timestampOptions }`/`{ enableHealthMonitor, healthMonitorOptions }`**
184
+ * (Phase 1 of the browsermesh-app-layer-migration plan, issue #120). Both
185
+ * follow the exact `enableHealthCheck`/`healthCheckOptions` shape just
186
+ * above: `mesh-timestamp.mjs`'s `createTimestampService()` and
187
+ * `mesh-health.mjs`'s `createHealthMonitorService()` are each attached via
188
+ * `attachService()` the same way `mesh-keepalive.mjs`'s descriptor is,
189
+ * stored in `node.services` under their own descriptor names (`'timestamp'`/
190
+ * `'health-monitor'`) and ALSO exposed directly as `node.timestamp`/
191
+ * `node.healthMonitor`, mirroring `node.healthCheck`'s "reachable both ways"
192
+ * convention. See those two files' own header comments for the full
193
+ * wire-protocol/design writeup -- both are near-trivial wrappers, per the
194
+ * migration plan's own Phase 1 note, since `TimestampAuthority`/
195
+ * `HealthMonitor` already duck-type against `PeerNode.listSessions()`.
196
+ *
197
+ * **`peer-verification.mjs` is opt-in via `{ enableVerification,
198
+ * verificationOptions }`** (Phase 4 of the browsermesh-app-layer-migration
199
+ * plan, issue #119). Attaches `mesh-verification.mjs`'s
200
+ * `createVerificationService()` -- a real request/response wire protocol
201
+ * (`'verify-request'`/`'verify-response'`) wrapping `peer-verification.mjs`'s
202
+ * `VerificationQuorum`: this node can dispatch a job to a quorum of trusted
203
+ * peers, collect their independently-computed results, and vote on
204
+ * correctness (unanimous/majority/threshold/byzantine). Follows the exact
205
+ * `enableTimestamp`/`timestampOptions` shape just above: attached via
206
+ * `attachService()`, stored in `node.services` under `'verification'`, and
207
+ * also exposed directly as `node.verification`. See `mesh-verification.mjs`'s
208
+ * own header comment for the full design -- in particular, why answering an
209
+ * inbound verification request requires both `ctx.registry.checkAccess()`
210
+ * authorization AND a caller-supplied `verificationOptions.executeFn` (never
211
+ * invented by this file), mirroring the same restraint `peer-compute.mjs`
212
+ * already shows while that module (and `peer-terminal.mjs`) stay blocked on
213
+ * issue #86's still-open execution-gating design pass.
214
+ * **Remote file access is opt-in via `{ enableFileShare: true,
215
+ * fileShareOptions }`** (Phase 8 of the app-layer migration plan, issue
216
+ * #84). `peer-files.mjs`'s `createFileShareService()` is attached via
217
+ * `attachService()`, the same as every other opt-in service above --
218
+ * `FileHost`/`FileClient` now run on `ctx.sendTo()`/`ctx.onIncomingData()`
219
+ * instead of the `peer-session.mjs`/`PeerSession` dependency that module
220
+ * used to have before this migration (see `peer-files.mjs`'s own header for
221
+ * the full writeup). Stored in `node.services` under `'file-share'` and
222
+ * ALSO exposed directly as `node.fileShare`, mirroring `node.router`/
223
+ * `node.healthCheck`'s "reachable both ways" convention.
224
+ * **`peer-chat.mjs` is opt-in via `{ enableChat, chatOptions }`** (Phase 9
225
+ * of the browsermesh-app-layer-migration plan, issue #84 -- a migration off
226
+ * `PeerSession`, not a fresh wire-up: `peer-chat.mjs`'s `PeerChat` used to
227
+ * require a live `PeerSession`, which nothing in this repo ever constructs).
228
+ * Follows the exact `enableTimestamp`/`timestampOptions` shape just above:
229
+ * `createChatService()` is attached via `attachService()` the same way,
230
+ * stored in `node.services` under `'chat'` and ALSO exposed directly as
231
+ * `node.chat` (the `attachService()` handle -- `node.chat.api.sendMessage()`/
232
+ * etc., same "reachable both ways" convention `node.timestamp`/
233
+ * `node.healthMonitor`/`node.router` already establish). See
234
+ * `peer-chat.mjs`'s own header comment for the full design
235
+ * writeup (why `sendMessage()`/`sendTyping()` now take an explicit target
236
+ * pubKey, and why signature verification keys off each message's real
237
+ * sender instead of one fixed constructor-time key).
238
+ *
239
+ * **Federated compute (dispatching code to a remote peer to run) is opt-in
240
+ * via `{ enableCompute: true, computeOptions: { executeFn } }`** (Phase 11 of
241
+ * the browsermesh-app-layer-migration plan, issue #118 -- the last of the
242
+ * two modules that stayed blocked on issue #86's execution-gating design
243
+ * pass, alongside `peer-terminal.mjs`). Attaches `mesh-compute.mjs`'s
244
+ * `createComputeService()`: a real request/response wire protocol
245
+ * (`'compute-request'`/`'compute-response'`) wrapping `peer-compute.mjs`'s
246
+ * `FederatedCompute`, so this node can split a job (via `computeOptions
247
+ * .splitFn` or a per-call `jobSpec.splitFn`), dispatch chunks to connected
248
+ * peers, and merge their results (via `computeOptions.mergeFn`/
249
+ * `jobSpec.mergeFn`). Follows the exact `enableVerification`/
250
+ * `verificationOptions` shape just above -- see `mesh-compute.mjs`'s own
251
+ * header comment for the full design (in particular, why answering an
252
+ * inbound compute-chunk request requires both `ctx.registry.checkAccess()`
253
+ * authorization AND a caller-supplied `computeOptions.executeFn`, never
254
+ * invented by this file, matching issue #86's resolved "bring-your-own,
255
+ * required, no default execution backend" decision). Unlike
256
+ * `enableVerification` (where `executeFn` is optional -- a node can submit
257
+ * verification jobs without ever answering them), `enableCompute` REQUIRES
258
+ * `computeOptions.executeFn` up front: this function throws if it's missing,
259
+ * mirroring `enableEscrow`'s required `escrowOptions.creditLedger` check,
260
+ * since (per issue #86's design pass) there is no real execution backend
261
+ * anywhere in this repo to fall back to, and a compute-only node with no
262
+ * ability to ever serve a chunk has little practical use compared to
263
+ * verification's legitimate "submit-only" role. Attached to the returned
264
+ * node as `node.compute` (the `attachService()` handle -- also reachable via
265
+ * `node.services.get('compute')`).
266
+ *
267
+ * **Remote terminal/shell execution is opt-in via `{ enableTerminal: true,
268
+ * terminalOptions: { shell } }`** (issue #84, Phase 10 of the
269
+ * browsermesh-app-layer-migration plan -- blocked on, and unblocked by,
270
+ * issue #86's design pass). When set, this function attaches
271
+ * `peer-terminal.mjs`'s `createTerminalService()` -- wiring `TerminalHost`/
272
+ * `TerminalClient` (real remote command execution, migrated off
273
+ * `peer-session.mjs`'s `PeerSession`) onto `ctx.sendTo()`/
274
+ * `ctx.onIncomingData()`, gating inbound exec requests via
275
+ * `registry.checkAccess(fromPubKey, 'terminal', 'execute')` -- see that
276
+ * function's own doc comment for the full design (in particular, why this is
277
+ * a single coarse scope rather than per-command/per-target). Just like
278
+ * `enableEscrow`'s `escrowOptions.creditLedger`, `terminalOptions.shell` is
279
+ * REQUIRED -- there is no default shell (no `child_process`, no OS command
280
+ * execution shipped by this package); this function throws if `enableTerminal`
281
+ * is set with no `terminalOptions.shell`, so nobody gets real remote shell
282
+ * execution just by flipping the opt-in flag. Attached to the returned node
283
+ * as `node.terminal` (the `attachService()` handle -- also reachable at
284
+ * `node.services.get('terminal')`, same as any other opt-in service).
285
+ *
286
+ * **SWIM cluster membership + leader election + task distribution is
287
+ * opt-in via `{ enableSwarm: true, swarmOptions }`** (issue #88). When set,
288
+ * this function attaches `mesh-swarm.mjs`'s `createSwarmService()` --
289
+ * wrapping `@johnhenry/browsermesh-discovery`'s `SwarmCoordinator` with an
290
+ * internally-constructed `SwimMembership`, so swarm membership becomes real
291
+ * and SWIM-driven (direct ping -> indirect ping-req -> suspect -> dead, with
292
+ * piggybacked membership dissemination), plus a genuinely new leader-election
293
+ * heartbeat pump and a real `SWARM_TASK_ASSIGN` wire notification when a task
294
+ * is assigned to a remote peer. Peer-initiated join requests and task
295
+ * submissions are individually authorized via `registry.checkAccess()` --
296
+ * see `mesh-swarm.mjs`'s own header comment for the full design (in
297
+ * particular why `SwimMembership`'s single-slot `onJoin`/`onDead` callbacks
298
+ * are composed rather than overwritten, and the SWARM_JOIN/SWARM_LEAVE
299
+ * admission-control design distinct from SWIM's own dead-via-timeout
300
+ * detection). Attached to the returned node as `node.swarm` (the
301
+ * `attachService()` handle -- also reachable via `node.services.get('swarm')`).
302
+ *
59
303
  * No browser-only imports at module level.
60
304
  */
61
305
 
@@ -85,6 +329,27 @@ import { MeshSignalingChannel } from './signaling.mjs'
85
329
  import { createWebRTCTransportFactory } from './webrtc-negotiator.mjs'
86
330
  import { createMeshSync } from './mesh-sync.mjs'
87
331
  import { MeshRelayHost } from './mesh-relay-host.mjs'
332
+ import { attachService } from './mesh-service.mjs'
333
+ import { AuditChain } from './audit.mjs'
334
+ import { createHardenedNegotiator } from './mesh-hardening.mjs'
335
+ import { createMeshDht, shareTransport } from './mesh-dht.mjs'
336
+ import { createMeshKeepaliveService } from './mesh-keepalive.mjs'
337
+ import { createMeshRoutingService } from './peer-routing.mjs'
338
+ import { createFileShareService } from './peer-files.mjs'
339
+ import { createTimestampService } from './mesh-timestamp.mjs'
340
+ import { createHealthMonitorService } from './mesh-health.mjs'
341
+ import { createIpfsService } from './peer-ipfs.mjs'
342
+ import { createVerificationService } from './mesh-verification.mjs'
343
+ import { createTorrentService } from './mesh-torrent.mjs'
344
+ import { createEscrowService } from './peer-escrow.mjs'
345
+ import { createChatService } from './peer-chat.mjs'
346
+ import { createComputeService } from './mesh-compute.mjs'
347
+ import { createTerminalService } from './peer-terminal.mjs'
348
+ import { createSwarmService } from './mesh-swarm.mjs'
349
+ import { createAgentSwarmService } from './mesh-agent-swarm.mjs'
350
+ import { createOrchestratorService } from './mesh-orchestrator.mjs'
351
+ import { BrowserToolRegistry } from './compat.mjs'
352
+ import { registerOrchestratorTools } from './mesh-orchestrator-tools.mjs'
88
353
 
89
354
  /**
90
355
  * Build and boot a real, WebRTC-capable `PeerNode`.
@@ -144,7 +409,6 @@ import { MeshRelayHost } from './mesh-relay-host.mjs'
144
409
  * ],
145
410
  * })
146
411
  * ```
147
- * @param {import('./audit.mjs').AuditChain} [options.auditChain]
148
412
  * @param {Function} [options.onLog]
149
413
  * @param {boolean} [options.skipDiscovery=false] - Passed through to `PeerNode.boot()`.
150
414
  * @param {boolean} [options.skipBoot=false] - Construct but don't boot (caller calls `node.boot()` itself).
@@ -176,13 +440,364 @@ import { MeshRelayHost } from './mesh-relay-host.mjs'
176
440
  * @param {string} [options.relayHostEnvelopeType] - Overrides the
177
441
  * `envelope.type` the relay host routes/sends on `PeerNode`'s dispatch bus
178
442
  * (default `'mesh-relay'`).
443
+ * @param {import('./mesh-service.mjs').MeshService[]} [options.services] -
444
+ * Optional array of `MeshService` descriptors (Phase C, see
445
+ * `mesh-service.mjs`) to attach immediately via `attachService()`,
446
+ * mirroring the `relayHostServices` opt-in shape exactly. Each descriptor
447
+ * is attached in array order; the resulting per-service handle (`{ name,
448
+ * backendScheme, teardown }`) is stored in the returned node's
449
+ * `node.services` map, keyed by `descriptor.name`.
450
+ * @param {boolean} [options.enableFileShare=false] - Attach `peer-files.mjs`'s
451
+ * `createFileShareService()` (issue #84, Phase 8): real, `PeerRegistry`-
452
+ * gated remote file access -- `FileHost` serves `fileShareOptions.fs` (if
453
+ * supplied) to any peer holding `files:read`/`files:write`/`files:delete`
454
+ * capabilities, and `FileClient` (always available once attached) can
455
+ * request files from any other peer running this service, via `node
456
+ * .fileShare.api.listFiles(pubKey, path)`/`.readFile()`/`.writeFile()`/
457
+ * `.deleteFile()`/`.stat()`. Attached to the returned node as
458
+ * `node.fileShare` (the `attachService()` handle -- also reachable via
459
+ * `node.services.get('file-share')`).
460
+ * @param {object} [options.fileShareOptions] - Only used when
461
+ * `enableFileShare`. Passed straight through to `createFileShareService()`
462
+ * (`fs`/`maxFileSize`/`timeout`/`resource`/`requestEnvelopeType`/
463
+ * `responseEnvelopeType`) -- see that function's own doc comment. Omitting
464
+ * `fileShareOptions.fs` means this node only acts as a client (no local
465
+ * filesystem is exposed to other peers).
466
+ * @param {import('@johnhenry/browsermesh-netway').VirtualNetwork} [options.servicesNetwork]
467
+ * `VirtualNetwork` passed through to `attachService()` for each entry in
468
+ * `options.services`. Only required if at least one descriptor declares
469
+ * `createBackend`; `attachService()` throws for any such descriptor if
470
+ * this is omitted.
471
+ * @param {boolean} [options.enableAudit=false] - Construct a default
472
+ * `AuditChain` (`audit.mjs`) and wire it into the returned `PeerNode` as
473
+ * `options.auditChain`, so `PeerNode`'s existing "audit trail for every
474
+ * session action" path (boot, connect, shutdown -- see `peer-node.mjs`'s
475
+ * `#audit()`) actually produces signed entries, using the node's own
476
+ * identity (`node.wallet.sign()`) the same way `PeerNode` already does.
477
+ * Ignored if `options.auditChain` is supplied directly.
478
+ * @param {import('./audit.mjs').AuditChain} [options.auditChain] - Pass a
479
+ * pre-built `AuditChain` instead of letting `enableAudit` construct a
480
+ * default one (e.g. to share one chain across multiple nodes/chainIds, or
481
+ * to restore one via `AuditChain.fromJSON()`). Implies audit logging is
482
+ * active even if `enableAudit` is left `false`, mirroring the
483
+ * `enableSync`/`syncStorage` "boolean toggle for a default, or supply your
484
+ * own instance" pattern.
485
+ * @param {string} [options.auditChainId] - `chainId` for the default
486
+ * `AuditChain` `enableAudit` constructs. Defaults to `audit-${podId}`.
487
+ * Ignored if `options.auditChain` is supplied.
488
+ * @param {boolean} [options.enableHardening=false] - Wrap the constructed
489
+ * `MeshTransportNegotiator` with retry/backoff + failover + metrics (see
490
+ * `mesh-hardening.mjs`) before it is handed to `PeerNode`, so
491
+ * `connectToPeer()` retries transient negotiation failures instead of
492
+ * rejecting immediately. Attached to the returned node as `node.hardening`
493
+ * (`{ metrics, failovers, retries }`) and `node.transportMetrics` (alias
494
+ * for `node.hardening.metrics`).
495
+ * @param {object} [options.hardeningOptions] - Only used when
496
+ * `enableHardening`.
497
+ * @param {object} [options.hardeningOptions.retry] - Passed to each
498
+ * per-peer `new RetryWithBackoff()` (see `hardening.mjs` for
499
+ * `maxRetries`/`baseDelayMs`/`maxDelayMs`/`jitterFactor`/`resetTimeoutMs`).
500
+ * @param {boolean} [options.enableDht=false] - Build a real, wire-connected
501
+ * `DhtDiscoveryStrategy` (Phase D, issue #87; see `mesh-dht.mjs`) and add
502
+ * it to `discoveryStrategies`, in addition to any other strategies
503
+ * (default `BroadcastChannelStrategy`, or caller-supplied
504
+ * `discoveryStrategies`). Its wire traffic is multiplexed onto
505
+ * `signalingTransport` (the same bus already required for WebRTC
506
+ * signaling) via `mesh-dht.mjs`'s `shareTransport()`. Does NOT solve
507
+ * first-contact rendezvous -- see `dhtBootstrapPeers` and `mesh-dht.mjs`'s
508
+ * header.
509
+ * @param {Array<string|{podId: string}>} [options.dhtBootstrapPeers=[]] -
510
+ * Already-known peer podIds (or `{podId}` records) to seed the DHT routing
511
+ * table with. Only used when `enableDht`. Required for this node to
512
+ * discover anyone via DHT at all; without it the strategy starts with an
513
+ * empty routing table and can only ever learn of peers who bootstrap
514
+ * *with* this node directly.
515
+ * @param {number} [options.dhtK] - Kademlia bucket size, forwarded to
516
+ * `DhtDiscoveryStrategy` (defaults to 20 there). Only used when
517
+ * `enableDht`.
518
+ * @param {string} [options.dhtMessageType] - Overrides the `type` tag used
519
+ * to distinguish DHT wire messages sharing `signalingTransport` with
520
+ * WebRTC signaling traffic (default `'dht-relay'`). Only used when
521
+ * `enableDht`.
522
+ * @param {boolean} [options.enableHealthCheck=false] - Attach
523
+ * `mesh-keepalive.mjs`'s `createMeshKeepaliveService()` (issue #110): a
524
+ * real ping/pong keepalive envelope protocol, one
525
+ * `@johnhenry/browsermesh-core` `TransportHealthCheck` per connected peer.
526
+ * `'unhealthy'` transitions feed `enableHardening`'s `TransportFailover`
527
+ * (if also on -- gracefully skipped otherwise) and `ctx.emit()` for
528
+ * observability. Attached to the returned node as `node.healthCheck` (the
529
+ * `attachService()` handle).
530
+ * @param {object} [options.healthCheckOptions] - Only used when
531
+ * `enableHealthCheck`. Passed straight through to each per-peer
532
+ * `TransportHealthCheck`.
533
+ * @param {number} [options.healthCheckOptions.intervalMs] - See `hardening.mjs` (default 10000).
534
+ * @param {number} [options.healthCheckOptions.timeoutMs] - See `hardening.mjs` (default 5000).
535
+ * @param {number} [options.healthCheckOptions.maxMissed] - See `hardening.mjs` (default 3).
536
+ * @param {boolean} [options.enableRouting=false] - Attach `peer-routing.mjs`'s
537
+ * `createMeshRoutingService()` (issue #121): real multi-hop message
538
+ * forwarding via `MeshRouter` (`forwardFn` -> `ctx.sendTo()`), plus
539
+ * `ServerSharing` if `routingOptions.fetchFn` is supplied. Attached to the
540
+ * returned node as `node.router` (the `attachService()` handle -- also
541
+ * reachable via `node.services.get('mesh-routing')`).
542
+ * @param {object} [options.routingOptions] - Only used when `enableRouting`.
543
+ * Passed straight through to `createMeshRoutingService()`
544
+ * (`maxTTL`/`routeCacheMs`/`envelopeType`/`fetchFn`/
545
+ * `serverShareEnvelopeType`/`proxyTimeoutMs`) -- see that function's own
546
+ * doc comment.
547
+ * @param {boolean} [options.enableTimestamp=false] - Attach
548
+ * `mesh-timestamp.mjs`'s `createTimestampService()` (issue #120): signed
549
+ * consensus timestamping wrapping `peer-timestamp.mjs`'s
550
+ * `TimestampAuthority`. Attached to the returned node as `node.timestamp`
551
+ * (the `attachService()` handle -- also reachable via
552
+ * `node.services.get('timestamp')`).
553
+ * @param {object} [options.timestampOptions] - Only used when
554
+ * `enableTimestamp`. Passed straight through to `createTimestampService()`
555
+ * (`identity`/`clockSkewMs`/`witnessTimeoutMs`/`envelopeType`).
556
+ * @param {boolean} [options.enableHealthMonitor=false] - Attach
557
+ * `mesh-health.mjs`'s `createHealthMonitorService()` (issue #120): peer
558
+ * heartbeat liveness tracking (+ opt-in auto-migration) wrapping
559
+ * `peer-health.mjs`'s `HealthMonitor`/`AutoMigrator`. Attached to the
560
+ * returned node as `node.healthMonitor` (the `attachService()` handle --
561
+ * also reachable via `node.services.get('health-monitor')`).
562
+ * @param {object} [options.healthMonitorOptions] - Only used when
563
+ * `enableHealthMonitor`. Passed straight through to
564
+ * `createHealthMonitorService()` (`trust`/`orchestrator`/
565
+ * `resolveWorkload`/`intervalMs`/`thresholds`).
566
+ * @param {boolean} [options.enableIpfs=false] - Attach `peer-ipfs.mjs`'s
567
+ * `createIpfsService()` (issue #123): mesh-LOCAL content-addressed storage
568
+ * wrapping a fresh `IPFSStore`. Despite the name, NOT real IPFS-network
569
+ * interop -- see `peer-ipfs.mjs`'s own header comment. Attached to the
570
+ * returned node as `node.ipfs` (the `attachService()` handle -- also
571
+ * reachable via `node.services.get('peer-ipfs')`).
572
+ * @param {object} [options.ipfsOptions] - Only used when `enableIpfs`.
573
+ * Passed straight through to `createIpfsService()`
574
+ * (`enabled`/`maxStorageMb`).
575
+ * @param {boolean} [options.enableVerification=false] - Attach
576
+ * `mesh-verification.mjs`'s `createVerificationService()` (Phase 4, issue
577
+ * #119): quorum-based job-result verification wrapping
578
+ * `peer-verification.mjs`'s `VerificationQuorum`. Attached to the returned
579
+ * node as `node.verification` (the `attachService()` handle -- also
580
+ * reachable via `node.services.get('verification')`).
581
+ * @param {object} [options.verificationOptions] - Only used when
582
+ * `enableVerification`. Passed straight through to
583
+ * `createVerificationService()` (`scheduler`/`trust`/`executeFn`/
584
+ * `dispatchTimeoutMs`/`envelopeType`/`accessResource`/`accessAction`) --
585
+ * see that function's own doc comment. `executeFn` is REQUIRED for this
586
+ * node to usefully serve as a verifier for other peers' jobs (see
587
+ * `mesh-verification.mjs`'s header for why it is never defaulted).
588
+ * @param {boolean} [options.enableTorrent=false] - Attach
589
+ * `mesh-torrent.mjs`'s `createTorrentService()` (Phase 5, issue #122): a
590
+ * real mesh-native swarm piece-exchange protocol wrapping
591
+ * `peer-torrent.mjs`'s `TorrentManager`. Attached to the returned node as
592
+ * `node.torrent` (the `attachService()` handle -- also reachable via
593
+ * `node.services.get('torrent')`).
594
+ * @param {object} [options.torrentOptions] - Only used when `enableTorrent`.
595
+ * Passed straight through to `createTorrentService()`
596
+ * (`trackerUrl`/`chunkSize`/`envelopeType`/`manifestTimeoutMs`/`chunkTimeoutMs`).
597
+ * @param {boolean} [options.enableEscrow=false] - Attach `peer-escrow.mjs`'s
598
+ * `createEscrowService()` (issue #117): real escrow-contract create/
599
+ * release/refund/dispute against `escrowOptions.creditLedger`, with
600
+ * peer-initiated operations individually authorized via
601
+ * `registry.checkAccess()` -- see that function's own doc comment for the
602
+ * full authorization model. Attached to the returned node as
603
+ * `node.escrow` (the `attachService()` handle -- also reachable via
604
+ * `node.services.get('escrow')`).
605
+ * @param {object} [options.escrowOptions] - Required when `enableEscrow`.
606
+ * Passed straight through to `createEscrowService()`
607
+ * (`creditLedger`/`onLog`/`envelopeType`/`requestTimeoutMs`) -- see that
608
+ * function's own doc comment. `escrowOptions.creditLedger` (must have
609
+ * `charge()`/`credit()`/`getBalance()`) is required; this function throws
610
+ * if it's missing.
611
+ * @param {boolean} [options.enableChat=false] - Attach `peer-chat.mjs`'s
612
+ * `createChatService()` (issue #84, Phase 9): P2P chat with optional
613
+ * message signing/verification, history, typing indicators, and an
614
+ * auto-responder hook, migrated off `PeerSession` onto `ctx.sendTo()`/
615
+ * `ctx.onIncomingData()`. Attached to the returned node as `node.chat`
616
+ * (the `attachService()` handle -- also reachable via
617
+ * `node.services.get('chat')`).
618
+ * @param {object} [options.chatOptions] - Only used when `enableChat`.
619
+ * Passed straight through to `createChatService()`
620
+ * (`signFn`/`verifyFn`/`maxHistory`/`autoResponder`/`onLog`).
621
+ * @param {boolean} [options.enableCompute=false] - Attach `mesh-compute.mjs`'s
622
+ * `createComputeService()` (issue #118, Phase 11): federated compute
623
+ * orchestration -- split a job into chunks, dispatch each to a connected
624
+ * peer over a real `'compute-request'`/`'compute-response'` wire protocol,
625
+ * retry on failure, merge completed results -- wrapping `peer-compute.mjs`'s
626
+ * `FederatedCompute`. Peer-initiated inbound chunk-execution requests are
627
+ * individually authorized via `registry.checkAccess()` -- see that
628
+ * function's own doc comment for the full authorization model. Attached to
629
+ * the returned node as `node.compute` (the `attachService()` handle --
630
+ * also reachable via `node.services.get('compute')`).
631
+ * @param {object} [options.computeOptions] - Required when `enableCompute`.
632
+ * Passed straight through to `createComputeService()`
633
+ * (`scheduler`/`listAvailablePeers`/`splitFn`/`mergeFn`/`executeFn`/
634
+ * `dispatchTimeoutMs`/`envelopeType`/`accessResource`/`accessAction`/
635
+ * `onLog`) -- see that function's own doc comment.
636
+ * `computeOptions.executeFn` is REQUIRED (unlike `verificationOptions
637
+ * .executeFn`, which is merely recommended) for this node to usefully
638
+ * serve as a compute worker for other peers' jobs; this function throws if
639
+ * `enableCompute` is set without it -- see `mesh-compute.mjs`'s header for
640
+ * why, settled by issue #86's resolved design pass.
641
+ * @param {boolean} [options.enableTerminal=false] - Attach `peer-terminal.mjs`'s
642
+ * `createTerminalService()` (issue #84, Phase 10): real remote shell
643
+ * execution, migrated off `PeerSession` onto `ctx.sendTo()`/
644
+ * `ctx.onIncomingData()`, gated via `registry.checkAccess(fromPubKey,
645
+ * 'terminal', 'execute')` (issue #86's resolved gate mechanism). Attached
646
+ * to the returned node as `node.terminal` (the `attachService()` handle --
647
+ * also reachable via `node.services.get('terminal')`).
648
+ * @param {object} [options.terminalOptions] - Required when `enableTerminal`.
649
+ * Passed straight through to `createTerminalService()`
650
+ * (`shell`/`allowedCommands`/`blockedCommands`/`maxOutputLength`/`timeout`/
651
+ * `accessResource`/`accessAction`/`requestEnvelopeType`/
652
+ * `responseEnvelopeType`) -- see that function's own doc comment.
653
+ * `terminalOptions.shell` (must implement `execute(command) ->
654
+ * {output, exitCode}`) is required; this function throws if it's missing
655
+ * (issue #86's resolved "bring-your-own, required, no default" execution-
656
+ * backend decision).
657
+ * @param {boolean} [options.enableSwarm=false] - Attach `mesh-swarm.mjs`'s
658
+ * `createSwarmService()` (issue #88): real SWIM failure detection +
659
+ * leader election + task distribution, wrapping
660
+ * `@johnhenry/browsermesh-discovery`'s `SwarmCoordinator`/`SwimMembership`.
661
+ * Peer-initiated join requests and task submissions are individually
662
+ * authorized via `registry.checkAccess()` -- see `mesh-swarm.mjs`'s own
663
+ * doc comment for the full design. Attached to the returned node as
664
+ * `node.swarm` (the `attachService()` handle -- also reachable via
665
+ * `node.services.get('swarm')`).
666
+ * @param {object} [options.swarmOptions] - Only used when `enableSwarm`.
667
+ * Passed straight through to `createSwarmService()`
668
+ * (`heartbeatMs`/`electionTimeoutMs`/`swimOptions`/`swimEnvelopeType`/
669
+ * `heartbeatEnvelopeType`/`membershipEnvelopeType`/`taskEnvelopeType`/
670
+ * `accessResource`/`requestTimeoutMs`) -- see that function's own doc comment.
671
+ * @param {boolean} [options.enableAgentSwarm=false] - Attach
672
+ * `mesh-agent-swarm.mjs`'s `createAgentSwarmService()` (issue #124): real
673
+ * multi-agent goal decomposition/assignment/execution wrapping
674
+ * `peer-agent-swarm.mjs`'s `AgentSwarmCoordinator`, with `executeSubTask()`
675
+ * now genuinely reaching a REMOTE assignee over a real
676
+ * `'agent-swarm-request'`/`'agent-swarm-response'` wire protocol (self-
677
+ * assigned subtasks stay local, no network round-trip). Peer-initiated
678
+ * inbound execute requests are individually authorized via
679
+ * `registry.checkAccess()` -- see that function's own doc comment for the
680
+ * full design. Distinct from, and independently wireable from,
681
+ * `enableSwarm`/`enableCompute` -- `AgentSwarmCoordinator` has no code
682
+ * dependency on either `SwarmCoordinator` or `FederatedCompute` (see
683
+ * `mesh-agent-swarm.mjs`'s header for the corrected grounding). Attached to
684
+ * the returned node as `node.agentSwarm` (the `attachService()` handle --
685
+ * also reachable via `node.services.get('agent-swarm')`).
686
+ * @param {object} [options.agentSwarmOptions] - Required when `enableAgentSwarm`.
687
+ * Passed straight through to `createAgentSwarmService()`
688
+ * (`agentProxy`/`dispatchTimeoutMs`/`envelopeType`/`accessResource`/
689
+ * `accessAction`/`onLog`) -- see that function's own doc comment.
690
+ * `agentSwarmOptions.agentProxy` (must implement `async chat(podId,
691
+ * message) -> string`) is required; this function throws if it's missing
692
+ * (issue #86's resolved "bring-your-own, required, no default" execution-
693
+ * backend decision -- see `mesh-agent-swarm.mjs`'s header for why this one
694
+ * is checked twice, once here and once inside `createAgentSwarmService()`
695
+ * itself).
696
+ * @param {boolean} [options.enableOrchestrator=false] - Attach
697
+ * `mesh-orchestrator.mjs`'s `createOrchestratorService()` (issue #92,
698
+ * Phase 3 of the agent-runtime plan): wires a real `MeshOrchestrator`
699
+ * (`orchestrator.mjs`) onto this node, with `execOnPod`/`deploySkill`/
700
+ * `drainPod` gated via `registry.checkAccess(fromPubKey, 'orchestrator',
701
+ * action)` when triggered by an inbound peer request, over a real
702
+ * `'orchestrator-request'`/`'orchestrator-response'` wire protocol
703
+ * (self-targeted calls stay local, no network round-trip, mirroring
704
+ * `enableAgentSwarm`'s own local-self-assignment shortcut). `listPods`/
705
+ * `getPodStatus`/`topPods` are local-only aggregation, left ungated --
706
+ * see `mesh-orchestrator.mjs`'s own doc comment for the full design
707
+ * (including why `serviceAdvertiser`/`serviceBrowser` stay `null` and the
708
+ * confirmed non-relationship with `enableSwarm`). When `enableRouting` is
709
+ * also set, `node.router.api` (shape-compatible -- `MeshOrchestrator`
710
+ * only ever calls `addRoute()` on its `router`) is passed straight
711
+ * through as `MeshOrchestrator`'s own `router` dependency. Attached to
712
+ * the returned node as `node.orchestrator` (the `attachService()` handle
713
+ * -- also reachable via `node.services.get('orchestrator')`); the raw
714
+ * `MeshOrchestrator` instance itself is `node.orchestrator.api.orchestrator`,
715
+ * for a later phase's `Meshctl*Tool` registration.
716
+ * @param {object} [options.orchestratorOptions] - Only used when
717
+ * `enableOrchestrator`. Passed straight through to
718
+ * `createOrchestratorService()` (`router`/`runtimeRegistry`/
719
+ * `remoteSessionBroker`/`resourceRegistry`/`auditRecorder`/
720
+ * `dispatchTimeoutMs`/`envelopeType`/`accessResource`/`onLog`) -- see that
721
+ * function's own doc comment. `router` defaults to `node.router?.api`
722
+ * when `enableRouting` is also set and `orchestratorOptions.router` is
723
+ * omitted; explicitly pass `router: null` to opt out.
724
+ * @param {boolean} [options.enableAgentRuntime=false] - Attach a real
725
+ * `BrowserToolRegistry` (`compat.mjs`, Phase 1 of the agent-runtime plan,
726
+ * issue #90) to the returned node as `node.toolRegistry`, ready to drive
727
+ * `agent-runtime.mjs`'s `createAgentRuntime({registry: node.toolRegistry,
728
+ * llmFn})` (Phase 2). Deliberately decoupled from `enableOrchestrator`: a
729
+ * caller may want an agent runtime for entirely non-orchestrator tools (its
730
+ * own `BrowserTool` subclasses registered directly via
731
+ * `node.toolRegistry.register(...)` after `createMeshNode()` returns), so
732
+ * this flag alone always produces an EMPTY registry, never throwing just
733
+ * because `enableOrchestrator` was left off. When BOTH `enableAgentRuntime`
734
+ * AND `enableOrchestrator` are set, this function additionally calls
735
+ * `mesh-orchestrator-tools.mjs`'s `registerOrchestratorTools(node.toolRegistry,
736
+ * node.orchestrator.api)` (Phase 4, issue #92), pre-populating the registry
737
+ * with the 8 real `Meshctl*Tool`s (`meshctl_pods`/`meshctl_status`/
738
+ * `meshctl_exec`/`meshctl_deploy`/`meshctl_top`/`meshctl_compute`/
739
+ * `meshctl_expose`/`meshctl_drain`) wired against this node's own attached
740
+ * orchestrator -- see `mesh-orchestrator-tools.mjs`'s own doc comment for
741
+ * exactly which of those 8 route through the orchestrator service's gated
742
+ * wire dispatch (`meshctl_exec`/`meshctl_deploy`/`meshctl_drain`) vs.
743
+ * straight to the raw `MeshOrchestrator` instance (the rest -- including
744
+ * `meshctl_compute`/`meshctl_expose`, which have no gated equivalent at
745
+ * all, since Phase 3 never built one for either). `enableOrchestrator` set
746
+ * WITHOUT `enableAgentRuntime` is unaffected -- `node.toolRegistry` is only
747
+ * ever created when `enableAgentRuntime` itself is set.
179
748
  * @returns {Promise<PeerNode>} A booted (unless `skipBoot`) PeerNode, with
180
- * `node.meshManager` (`WebRTCMeshManager`) and `node.signaling`
181
- * (`MeshSignalingChannel`) attached for callers/tests that need lower-level
749
+ * `node.meshManager` (`WebRTCMeshManager`), `node.signaling`
750
+ * (`MeshSignalingChannel`), and `node.transportNegotiator` (the real,
751
+ * unwrapped `MeshTransportNegotiator` -- see `enableHardening` below)
752
+ * attached for callers/tests that need lower-level
182
753
  * access beyond what `PeerNode`'s own API exposes, `node.sync`
183
- * (`MeshSyncBinding`, see `mesh-sync.mjs`) attached when `enableSync`, and
754
+ * (`MeshSyncBinding`, see `mesh-sync.mjs`) attached when `enableSync`,
184
755
  * `node.relayHost` (`MeshRelayHost`, see `mesh-relay-host.mjs`) attached
185
- * when `enableRelayHost`.
756
+ * when `enableRelayHost`, `node.services` (a `Map<string, { name,
757
+ * backendScheme, api, teardown }>`, see `mesh-service.mjs`) populated from
758
+ * `options.services` (always present, empty when `options.services` is
759
+ * omitted), `node.auditChain` (`AuditChain`, see `audit.mjs`) attached
760
+ * when `enableAudit` or `options.auditChain` is supplied (left unset
761
+ * otherwise), `node.hardening`/`node.transportMetrics` attached when
762
+ * `enableHardening`, `node.dht` (`DhtDiscoveryStrategy`, see
763
+ * `mesh-dht.mjs`) attached when `enableDht`, `node.healthCheck`
764
+ * (`attachService()`'s handle for `mesh-keepalive.mjs`, also reachable via
765
+ * `node.services.get('keepalive')`) attached when `enableHealthCheck`,
766
+ * `node.router` (`attachService()`'s handle for `peer-routing.mjs`'s
767
+ * `createMeshRoutingService()`, also reachable via
768
+ * `node.services.get('mesh-routing')`) attached when `enableRouting`,
769
+ * `node.timestamp` (`attachService()`'s handle for `mesh-timestamp.mjs`,
770
+ * also reachable via `node.services.get('timestamp')`) attached when
771
+ * `enableTimestamp`, `node.healthMonitor` (`attachService()`'s handle
772
+ * for `mesh-health.mjs`, also reachable via
773
+ * `node.services.get('health-monitor')`) attached when
774
+ * `enableHealthMonitor`, `node.ipfs` (`attachService()`'s handle for
775
+ * `peer-ipfs.mjs`'s `createIpfsService()`, also reachable via
776
+ * `node.services.get('peer-ipfs')`) attached when `enableIpfs`, and
777
+ * `node.verification` (`attachService()`'s handle for
778
+ * `mesh-verification.mjs`, also reachable via
779
+ * `node.services.get('verification')`) attached when `enableVerification`.
780
+ * `node.torrent` (`attachService()`'s handle for `mesh-torrent.mjs`, also
781
+ * reachable via `node.services.get('torrent')`) attached when `enableTorrent`.
782
+ * `node.fileShare` (`attachService()`'s handle for `peer-files.mjs`'s
783
+ * `createFileShareService()`, also reachable via
784
+ * `node.services.get('file-share')`) attached when `enableFileShare`.
785
+ * `node.escrow` (`attachService()`'s handle for `peer-escrow.mjs`'s
786
+ * `createEscrowService()`, also reachable via `node.services.get('escrow')`)
787
+ * attached when `enableEscrow`.
788
+ * `node.chat` (`attachService()`'s handle for `peer-chat.mjs`'s
789
+ * `createChatService()`, also reachable via `node.services.get('chat')`)
790
+ * attached when `enableChat`.
791
+ * `node.compute` (`attachService()`'s handle for `mesh-compute.mjs`'s
792
+ * `createComputeService()`, also reachable via `node.services.get('compute')`)
793
+ * attached when `enableCompute`.
794
+ * `node.orchestrator` (`attachService()`'s handle for `mesh-orchestrator.mjs`'s
795
+ * `createOrchestratorService()`, also reachable via
796
+ * `node.services.get('orchestrator')`) attached when `enableOrchestrator`.
797
+ * `node.toolRegistry` (a `BrowserToolRegistry`, `compat.mjs`) attached when
798
+ * `enableAgentRuntime` -- empty unless `enableOrchestrator` is ALSO set, in
799
+ * which case it is pre-populated with the 8 `Meshctl*Tool`s (see
800
+ * `enableAgentRuntime` above and `mesh-orchestrator-tools.mjs`).
186
801
  */
187
802
  export async function createMeshNode(options = {}) {
188
803
  const {
@@ -198,7 +813,9 @@ export async function createMeshNode(options = {}) {
198
813
  capabilities = [],
199
814
  signalingTransport,
200
815
  iceServers,
201
- auditChain,
816
+ enableAudit = false,
817
+ auditChain: providedAuditChain,
818
+ auditChainId,
202
819
  onLog = () => {},
203
820
  skipDiscovery = false,
204
821
  skipBoot = false,
@@ -211,6 +828,45 @@ export async function createMeshNode(options = {}) {
211
828
  relayHostNetwork,
212
829
  relayHostServices,
213
830
  relayHostEnvelopeType,
831
+ services,
832
+ servicesNetwork,
833
+ enableHardening = false,
834
+ hardeningOptions,
835
+ enableDht = false,
836
+ dhtBootstrapPeers = [],
837
+ dhtK,
838
+ dhtMessageType,
839
+ enableHealthCheck = false,
840
+ healthCheckOptions,
841
+ enableRouting = false,
842
+ routingOptions,
843
+ enableTimestamp = false,
844
+ timestampOptions,
845
+ enableHealthMonitor = false,
846
+ healthMonitorOptions,
847
+ enableIpfs = false,
848
+ ipfsOptions,
849
+ enableVerification = false,
850
+ verificationOptions,
851
+ enableTorrent = false,
852
+ torrentOptions,
853
+ enableFileShare = false,
854
+ fileShareOptions,
855
+ enableEscrow = false,
856
+ escrowOptions,
857
+ enableChat = false,
858
+ chatOptions,
859
+ enableCompute = false,
860
+ computeOptions,
861
+ enableTerminal = false,
862
+ terminalOptions,
863
+ enableSwarm = false,
864
+ swarmOptions,
865
+ enableAgentSwarm = false,
866
+ agentSwarmOptions,
867
+ enableOrchestrator = false,
868
+ orchestratorOptions,
869
+ enableAgentRuntime = false,
214
870
  } = options
215
871
 
216
872
  if (!signalingTransport) {
@@ -225,6 +881,13 @@ export async function createMeshNode(options = {}) {
225
881
  const wallet = new IdentityWallet({ identityManager, onLog })
226
882
  const { podId } = await wallet.createIdentity(label)
227
883
 
884
+ // -- Audit chain (opt-in, boolean enableAudit or pass-your-own via
885
+ // auditChain) -- resolved here, before PeerNode is constructed, since
886
+ // (unlike sync/relayHost) PeerNode takes it as a constructor-time
887
+ // dependency rather than something attached to the node afterwards.
888
+ const auditChain = providedAuditChain
889
+ || (enableAudit ? new AuditChain(auditChainId || `audit-${podId}`) : undefined)
890
+
228
891
  // -- Registry (peers + trust + ACL + capability tokens) -----------------
229
892
  // capabilityValidator/tokenFactory back Phase 5's real granting/revocation
230
893
  // path (see peer-registry.mjs's grantCapabilities()/revokeCapabilities()/
@@ -243,15 +906,42 @@ export async function createMeshNode(options = {}) {
243
906
  // -- Discovery ----------------------------------------------------------
244
907
  let strategies = discoveryStrategies
245
908
  if (!strategies) {
246
- if (typeof BroadcastChannel === 'undefined') {
909
+ if (typeof BroadcastChannel === 'undefined' && !enableDht) {
247
910
  throw new Error(
248
911
  'createMeshNode: no options.discoveryStrategies supplied and BroadcastChannel ' +
249
912
  'is not available in this environment (e.g. Node). Pass a Node-safe strategy, ' +
250
- 'such as [new ManualStrategy()] from @johnhenry/browsermesh-discovery.',
913
+ 'such as [new ManualStrategy()] from @johnhenry/browsermesh-discovery, or set ' +
914
+ '{ enableDht: true, dhtBootstrapPeers } instead.',
251
915
  )
252
916
  }
253
- strategies = [new BroadcastChannelStrategy({ channelName: discoveryChannelName })]
917
+ strategies = typeof BroadcastChannel !== 'undefined'
918
+ ? [new BroadcastChannelStrategy({ channelName: discoveryChannelName })]
919
+ : []
920
+ }
921
+
922
+ // -- DHT discovery (opt-in, Phase D, issue #87) --------------------------
923
+ // DhtDiscoveryStrategy has no transport of its own (see mesh-dht.mjs's
924
+ // header) -- its wire traffic is multiplexed onto signalingTransport, the
925
+ // same bus already required for WebRTC offer/answer/ICE relay, since it's
926
+ // the one thing here that already reaches arbitrary podIds pre-connection.
927
+ // shareTransport() wraps it so both MeshSignalingChannel (below) and the
928
+ // DHT strategy can subscribe independently -- most real transports only
929
+ // support one onMessage() subscriber at a time.
930
+ let effectiveSignalingTransport = signalingTransport
931
+ let dht = null
932
+ if (enableDht) {
933
+ effectiveSignalingTransport = shareTransport(signalingTransport)
934
+ dht = createMeshDht({
935
+ localPodId: podId,
936
+ transport: effectiveSignalingTransport,
937
+ bootstrapPeers: dhtBootstrapPeers,
938
+ k: dhtK,
939
+ messageType: dhtMessageType,
940
+ onLog,
941
+ })
942
+ strategies.push(dht.strategy)
254
943
  }
944
+
255
945
  const localRecord = new DiscoveryRecord({
256
946
  podId,
257
947
  label,
@@ -270,7 +960,7 @@ export async function createMeshNode(options = {}) {
270
960
  // (empty by default), filtering out malformed entries rather than handing
271
961
  // them straight to WebRTCMeshManager.
272
962
  const meshManager = new WebRTCMeshManager({ localPodId: podId, iceServers: mergeIceServers(iceServers), onLog })
273
- const signaling = new MeshSignalingChannel({ localPodId: podId, transport: signalingTransport, onLog })
963
+ const signaling = new MeshSignalingChannel({ localPodId: podId, transport: effectiveSignalingTransport, onLog })
274
964
  await signaling.open()
275
965
 
276
966
  // The negotiator is constructed (and handed to PeerNode) before its
@@ -282,12 +972,27 @@ export async function createMeshNode(options = {}) {
282
972
  // resolving the callee-side session gap (see peer-node.mjs / Phase 3).
283
973
  const transportNegotiator = new MeshTransportNegotiator()
284
974
 
975
+ // -- Transport hardening (opt-in) -----------------------------------------
976
+ // Wrapping happens before PeerNode is constructed, but adapter
977
+ // registration (below, after PeerNode's construction) still targets
978
+ // `transportNegotiator` -- the real, unwrapped instance -- directly:
979
+ // `createHardenedNegotiator()`'s returned `negotiate()` closes over that
980
+ // same `transportNegotiator` reference, so it sees adapters registered on
981
+ // it regardless of when registration happens relative to wrapping.
982
+ const hardening = enableHardening
983
+ ? createHardenedNegotiator({
984
+ negotiator: transportNegotiator,
985
+ retryOptions: hardeningOptions?.retry,
986
+ onLog,
987
+ })
988
+ : null
989
+
285
990
  // -- PeerNode -------------------------------------------------------------
286
991
  const node = new PeerNode({
287
992
  wallet,
288
993
  registry,
289
994
  discovery,
290
- transportNegotiator,
995
+ transportNegotiator: hardening ? hardening : transportNegotiator,
291
996
  auditChain,
292
997
  onLog,
293
998
  })
@@ -318,9 +1023,28 @@ export async function createMeshNode(options = {}) {
318
1023
 
319
1024
  // Not part of PeerNode's own API surface, but real callers/tests
320
1025
  // occasionally need direct access below the PeerNode abstraction
321
- // (e.g. to inspect connection stats, or to close the signaling bus).
1026
+ // (e.g. to inspect connection stats, close the signaling bus, or register
1027
+ // an additional transport adapter directly -- registering on this real,
1028
+ // unwrapped negotiator works identically whether or not enableHardening
1029
+ // wrapped it for PeerNode's own use, since the wrapper closes over this
1030
+ // same instance).
322
1031
  node.meshManager = meshManager
323
1032
  node.signaling = signaling
1033
+ node.transportNegotiator = transportNegotiator
1034
+
1035
+ // -- Audit chain (opt-in) --------------------------------------------------
1036
+ // Attached for inspection/verification, mirroring node.sync/node.relayHost's
1037
+ // convention. Left unset (not even `null`) when neither enableAudit nor
1038
+ // auditChain was supplied, matching those subsystems' "absent means never
1039
+ // opted in" contract -- PeerNode's own #audit() already no-ops in that case.
1040
+ if (auditChain) {
1041
+ node.auditChain = auditChain
1042
+ }
1043
+
1044
+ // -- DHT discovery (opt-in, Phase D, issue #87) -----------------------------
1045
+ if (dht) {
1046
+ node.dht = dht.strategy
1047
+ }
324
1048
 
325
1049
  // -- CRDT sync (opt-in, Phase 3) -------------------------------------------
326
1050
  if (enableSync) {
@@ -358,5 +1082,400 @@ export async function createMeshNode(options = {}) {
358
1082
  }
359
1083
  }
360
1084
 
1085
+ // -- Mesh-native services (opt-in, Phase C) --------------------------------
1086
+ // `node.services` is always present (empty when `services` is omitted) so
1087
+ // callers never need to null-check it before looking up an attached
1088
+ // service by name.
1089
+ node.services = new Map()
1090
+ if (services) {
1091
+ for (const descriptor of services) {
1092
+ const handle = attachService(node, servicesNetwork, descriptor)
1093
+ node.services.set(handle.name, handle)
1094
+ }
1095
+ }
1096
+
1097
+ // -- Transport hardening (opt-in) -----------------------------------------
1098
+ if (hardening) {
1099
+ node.hardening = hardening
1100
+ node.transportMetrics = hardening.metrics
1101
+ }
1102
+
1103
+ // -- Transport health check / keepalive (opt-in, issue #110) --------------
1104
+ // Attached the same way options.services entries are (attachService()),
1105
+ // just after -- so node.services already has whatever the caller listed
1106
+ // in options.services before this one is added under the 'keepalive' key.
1107
+ // Passing the local `hardening` variable (not node.hardening) directly:
1108
+ // both are the same value when enableHardening is on, and mesh-keepalive.mjs
1109
+ // itself handles `hardening` being undefined (enableHardening off) by
1110
+ // skipping failover integration entirely -- see that file's own header
1111
+ // comment.
1112
+ if (enableHealthCheck) {
1113
+ const keepaliveDescriptor = createMeshKeepaliveService({
1114
+ intervalMs: healthCheckOptions?.intervalMs,
1115
+ timeoutMs: healthCheckOptions?.timeoutMs,
1116
+ maxMissed: healthCheckOptions?.maxMissed,
1117
+ hardening,
1118
+ onLog,
1119
+ })
1120
+ const keepaliveHandle = attachService(node, servicesNetwork, keepaliveDescriptor)
1121
+ node.services.set(keepaliveHandle.name, keepaliveHandle)
1122
+ node.healthCheck = keepaliveHandle
1123
+ }
1124
+
1125
+ // -- Multi-hop mesh routing (opt-in, issue #121) ---------------------------
1126
+ // Attached the same way options.services/enableHealthCheck entries are
1127
+ // (attachService()), just after -- so node.services already has whatever
1128
+ // the caller listed in options.services (plus 'keepalive', if enabled)
1129
+ // before this one is added under createMeshRoutingService()'s own
1130
+ // 'mesh-routing' name.
1131
+ if (enableRouting) {
1132
+ const routingDescriptor = createMeshRoutingService({
1133
+ ...routingOptions,
1134
+ onLog: routingOptions?.onLog ?? onLog,
1135
+ })
1136
+ const routingHandle = attachService(node, servicesNetwork, routingDescriptor)
1137
+ node.services.set(routingHandle.name, routingHandle)
1138
+ node.router = routingHandle
1139
+ }
1140
+
1141
+ // -- Signed consensus timestamping (opt-in, Phase 1, issue #120) ----------
1142
+ // Attached the same way enableHealthCheck's keepalive service is above --
1143
+ // see mesh-timestamp.mjs's own header comment for the full design.
1144
+ if (enableTimestamp) {
1145
+ const timestampDescriptor = createTimestampService({
1146
+ identity: timestampOptions?.identity,
1147
+ clockSkewMs: timestampOptions?.clockSkewMs,
1148
+ witnessTimeoutMs: timestampOptions?.witnessTimeoutMs,
1149
+ envelopeType: timestampOptions?.envelopeType,
1150
+ onLog,
1151
+ })
1152
+ const timestampHandle = attachService(node, servicesNetwork, timestampDescriptor)
1153
+ node.services.set(timestampHandle.name, timestampHandle)
1154
+ node.timestamp = timestampHandle
1155
+ }
1156
+
1157
+ // -- Peer health monitoring / auto-migration (opt-in, Phase 1, issue #120) -
1158
+ // Attached the same way enableHealthCheck's keepalive service is above --
1159
+ // see mesh-health.mjs's own header comment for the full design. Distinct
1160
+ // from enableHealthCheck's transport-level keepalive: this is
1161
+ // application-level heartbeat liveness (peer-health.mjs's HealthMonitor),
1162
+ // with opt-in workload auto-migration on failure.
1163
+ if (enableHealthMonitor) {
1164
+ const healthMonitorDescriptor = createHealthMonitorService({
1165
+ trust: healthMonitorOptions?.trust,
1166
+ orchestrator: healthMonitorOptions?.orchestrator,
1167
+ resolveWorkload: healthMonitorOptions?.resolveWorkload,
1168
+ intervalMs: healthMonitorOptions?.intervalMs,
1169
+ thresholds: healthMonitorOptions?.thresholds,
1170
+ onLog,
1171
+ })
1172
+ const healthMonitorHandle = attachService(node, servicesNetwork, healthMonitorDescriptor)
1173
+ node.services.set(healthMonitorHandle.name, healthMonitorHandle)
1174
+ node.healthMonitor = healthMonitorHandle
1175
+ }
1176
+
1177
+ // -- Mesh-local IPFS-style content storage (opt-in, Phase 6, issue #123) --
1178
+ // Attached the same way the other opt-in services above are
1179
+ // (attachService()) -- see peer-ipfs.mjs's own header comment for why this
1180
+ // is NOT real IPFS-network interop despite the name.
1181
+ if (enableIpfs) {
1182
+ const ipfsDescriptor = createIpfsService({
1183
+ enabled: ipfsOptions?.enabled,
1184
+ maxStorageMb: ipfsOptions?.maxStorageMb,
1185
+ onLog: ipfsOptions?.onLog ?? onLog,
1186
+ })
1187
+ const ipfsHandle = attachService(node, servicesNetwork, ipfsDescriptor)
1188
+ node.services.set(ipfsHandle.name, ipfsHandle)
1189
+ node.ipfs = ipfsHandle
1190
+ }
1191
+
1192
+ // -- Quorum-based job-result verification (opt-in, Phase 4, issue #119) ---
1193
+ // Attached the same way enableTimestamp/enableHealthMonitor's services are
1194
+ // above -- see mesh-verification.mjs's own header comment for the full
1195
+ // design (in particular, why executeFn is required-but-not-provided for
1196
+ // this node to usefully serve as a verifier).
1197
+ if (enableVerification) {
1198
+ const verificationDescriptor = createVerificationService({
1199
+ scheduler: verificationOptions?.scheduler,
1200
+ trust: verificationOptions?.trust,
1201
+ executeFn: verificationOptions?.executeFn,
1202
+ dispatchTimeoutMs: verificationOptions?.dispatchTimeoutMs,
1203
+ envelopeType: verificationOptions?.envelopeType,
1204
+ accessResource: verificationOptions?.accessResource,
1205
+ accessAction: verificationOptions?.accessAction,
1206
+ onLog: verificationOptions?.onLog ?? onLog,
1207
+ })
1208
+ const verificationHandle = attachService(node, servicesNetwork, verificationDescriptor)
1209
+ node.services.set(verificationHandle.name, verificationHandle)
1210
+ node.verification = verificationHandle
1211
+ }
1212
+
1213
+ // -- Mesh-native swarm torrent distribution (opt-in, Phase 5, issue #122) --
1214
+ // Attached the same way enableHealthCheck's keepalive service is above --
1215
+ // see mesh-torrent.mjs's own header comment for the full design.
1216
+ if (enableTorrent) {
1217
+ const torrentDescriptor = createTorrentService({
1218
+ trackerUrl: torrentOptions?.trackerUrl,
1219
+ chunkSize: torrentOptions?.chunkSize,
1220
+ envelopeType: torrentOptions?.envelopeType,
1221
+ manifestTimeoutMs: torrentOptions?.manifestTimeoutMs,
1222
+ chunkTimeoutMs: torrentOptions?.chunkTimeoutMs,
1223
+ onLog,
1224
+ })
1225
+ const torrentHandle = attachService(node, servicesNetwork, torrentDescriptor)
1226
+ node.services.set(torrentHandle.name, torrentHandle)
1227
+ node.torrent = torrentHandle
1228
+ }
1229
+
1230
+ // -- Remote file access (opt-in, Phase 8, issue #84) -----------------------
1231
+ // Attached the same way every other opt-in service above is
1232
+ // (attachService()) -- see peer-files.mjs's own header comment for the
1233
+ // full migration writeup (this used to depend on peer-session.mjs's
1234
+ // PeerSession, now runs on ctx.sendTo()/ctx.onIncomingData() like
1235
+ // everything else here).
1236
+ if (enableFileShare) {
1237
+ const fileShareDescriptor = createFileShareService({
1238
+ fs: fileShareOptions?.fs,
1239
+ maxFileSize: fileShareOptions?.maxFileSize,
1240
+ timeout: fileShareOptions?.timeout,
1241
+ resource: fileShareOptions?.resource,
1242
+ requestEnvelopeType: fileShareOptions?.requestEnvelopeType,
1243
+ responseEnvelopeType: fileShareOptions?.responseEnvelopeType,
1244
+ onLog,
1245
+ })
1246
+ const fileShareHandle = attachService(node, servicesNetwork, fileShareDescriptor)
1247
+ node.services.set(fileShareHandle.name, fileShareHandle)
1248
+ node.fileShare = fileShareHandle
1249
+ }
1250
+
1251
+ // -- Escrow (real credit/payment holds, opt-in, issue #117) ----------------
1252
+ // Attached the same way options.services/enableHealthCheck/enableRouting/
1253
+ // enableTimestamp/enableHealthMonitor/enableIpfs entries are
1254
+ // (attachService()), just after -- so node.services already has whatever
1255
+ // the caller listed in options.services (plus 'keepalive'/'mesh-routing'/
1256
+ // 'timestamp'/'health-monitor'/'peer-ipfs', if enabled) before this one is
1257
+ // added under createEscrowService()'s own 'escrow' name. Unlike
1258
+ // enableRouting, creditLedger has no sensible default (there is no
1259
+ // "default ledger" the way there's a default MeshACL/TrustGraph) --
1260
+ // mirrors enableRelayHost's own required-dependency check for
1261
+ // relayHostNetwork.
1262
+ if (enableEscrow) {
1263
+ if (!escrowOptions?.creditLedger) {
1264
+ throw new Error(
1265
+ 'createMeshNode: options.escrowOptions.creditLedger is required when enableEscrow is true ' +
1266
+ '(must implement charge()/credit()/getBalance() -- see peer-escrow.mjs\'s EscrowManager).',
1267
+ )
1268
+ }
1269
+ const escrowDescriptor = createEscrowService({
1270
+ ...escrowOptions,
1271
+ onLog: escrowOptions?.onLog ?? onLog,
1272
+ })
1273
+ const escrowHandle = attachService(node, servicesNetwork, escrowDescriptor)
1274
+ node.services.set(escrowHandle.name, escrowHandle)
1275
+ node.escrow = escrowHandle
1276
+ }
1277
+
1278
+ // -- P2P chat (opt-in, Phase 9 of the browsermesh-app-layer-migration
1279
+ // plan, issue #84) --------------------------------------------------------
1280
+ // Attached the same way enableHealthCheck's keepalive service is above --
1281
+ // see peer-chat.mjs's own header comment for the full design (migration
1282
+ // off PeerSession, not a fresh wire-up).
1283
+ if (enableChat) {
1284
+ const chatDescriptor = createChatService({
1285
+ signFn: chatOptions?.signFn,
1286
+ verifyFn: chatOptions?.verifyFn,
1287
+ maxHistory: chatOptions?.maxHistory,
1288
+ autoResponder: chatOptions?.autoResponder,
1289
+ onLog: chatOptions?.onLog ?? onLog,
1290
+ })
1291
+ const chatHandle = attachService(node, servicesNetwork, chatDescriptor)
1292
+ node.services.set(chatHandle.name, chatHandle)
1293
+ node.chat = chatHandle
1294
+ }
1295
+
1296
+ // -- Federated compute (opt-in, Phase 11 of the browsermesh-app-layer-
1297
+ // migration plan, issue #118) ----------------------------------------------
1298
+ // Attached the same way options.services/enableEscrow/enableVerification
1299
+ // entries are (attachService()), just after -- see mesh-compute.mjs's own
1300
+ // header comment for the full design (in particular why executeFn is
1301
+ // REQUIRED here, unlike enableVerification's optional executeFn). Mirrors
1302
+ // enableEscrow's required-dependency check for escrowOptions.creditLedger:
1303
+ // there is no default execution backend anywhere in this repo (issue #86's
1304
+ // resolved design pass), so a compute-only node with no way to ever serve
1305
+ // a chunk has little practical use.
1306
+ if (enableCompute) {
1307
+ if (typeof computeOptions?.executeFn !== 'function') {
1308
+ throw new Error(
1309
+ 'createMeshNode: options.computeOptions.executeFn is required when enableCompute is true ' +
1310
+ '(a function (job) => Promise<result> that actually runs an inbound, authorized compute ' +
1311
+ 'chunk -- see mesh-compute.mjs\'s createComputeService() for why this is never defaulted).',
1312
+ )
1313
+ }
1314
+ const computeDescriptor = createComputeService({
1315
+ scheduler: computeOptions?.scheduler,
1316
+ listAvailablePeers: computeOptions?.listAvailablePeers,
1317
+ splitFn: computeOptions?.splitFn,
1318
+ mergeFn: computeOptions?.mergeFn,
1319
+ executeFn: computeOptions?.executeFn,
1320
+ dispatchTimeoutMs: computeOptions?.dispatchTimeoutMs,
1321
+ envelopeType: computeOptions?.envelopeType,
1322
+ accessResource: computeOptions?.accessResource,
1323
+ accessAction: computeOptions?.accessAction,
1324
+ onLog: computeOptions?.onLog ?? onLog,
1325
+ })
1326
+ const computeHandle = attachService(node, servicesNetwork, computeDescriptor)
1327
+ node.services.set(computeHandle.name, computeHandle)
1328
+ node.compute = computeHandle
1329
+ }
1330
+
1331
+ // -- Remote terminal/shell execution (opt-in, Phase 10 of the
1332
+ // browsermesh-app-layer-migration plan, issue #84, unblocked by issue #86) -
1333
+ // Attached the same way options.services/enableHealthCheck/enableRouting/
1334
+ // enableTimestamp/enableHealthMonitor/enableIpfs/enableEscrow entries are
1335
+ // (attachService()), just after -- so node.services already has whatever
1336
+ // the caller listed in options.services (plus any other enabled services)
1337
+ // before this one is added under createTerminalService()'s own 'terminal'
1338
+ // name. Unlike enableRouting, `shell` has no sensible default (no
1339
+ // `child_process`, no OS command execution shipped by this package) --
1340
+ // mirrors enableEscrow's own required-dependency check for
1341
+ // escrowOptions.creditLedger (issue #86's resolved "bring-your-own,
1342
+ // required, no default" execution-backend decision).
1343
+ if (enableTerminal) {
1344
+ if (!terminalOptions?.shell) {
1345
+ throw new Error(
1346
+ 'createMeshNode: options.terminalOptions.shell is required when enableTerminal is true ' +
1347
+ '(must implement execute(command) -> {output, exitCode} -- see peer-terminal.mjs\'s TerminalHost). ' +
1348
+ 'No default shell is provided by this package.',
1349
+ )
1350
+ }
1351
+ const terminalDescriptor = createTerminalService({
1352
+ shell: terminalOptions.shell,
1353
+ allowedCommands: terminalOptions?.allowedCommands,
1354
+ blockedCommands: terminalOptions?.blockedCommands,
1355
+ maxOutputLength: terminalOptions?.maxOutputLength,
1356
+ timeout: terminalOptions?.timeout,
1357
+ accessResource: terminalOptions?.accessResource,
1358
+ accessAction: terminalOptions?.accessAction,
1359
+ requestEnvelopeType: terminalOptions?.requestEnvelopeType,
1360
+ responseEnvelopeType: terminalOptions?.responseEnvelopeType,
1361
+ onLog: terminalOptions?.onLog ?? onLog,
1362
+ })
1363
+ const terminalHandle = attachService(node, servicesNetwork, terminalDescriptor)
1364
+ node.services.set(terminalHandle.name, terminalHandle)
1365
+ node.terminal = terminalHandle
1366
+ }
1367
+
1368
+ // -- SWIM cluster membership + leader election + task distribution
1369
+ // (opt-in, issue #88) -----------------------------------------------------
1370
+ // Attached the same way every other opt-in service above is
1371
+ // (attachService()) -- see mesh-swarm.mjs's own header comment for the
1372
+ // full design (SWIM bridge, single-slot callback composition, the leader
1373
+ // election heartbeat pump, and the SWARM_JOIN/SWARM_LEAVE/SWARM_TASK_ASSIGN
1374
+ // wire use).
1375
+ if (enableSwarm) {
1376
+ const swarmDescriptor = createSwarmService({
1377
+ heartbeatMs: swarmOptions?.heartbeatMs,
1378
+ electionTimeoutMs: swarmOptions?.electionTimeoutMs,
1379
+ swimOptions: swarmOptions?.swimOptions,
1380
+ swimEnvelopeType: swarmOptions?.swimEnvelopeType,
1381
+ heartbeatEnvelopeType: swarmOptions?.heartbeatEnvelopeType,
1382
+ membershipEnvelopeType: swarmOptions?.membershipEnvelopeType,
1383
+ taskEnvelopeType: swarmOptions?.taskEnvelopeType,
1384
+ accessResource: swarmOptions?.accessResource,
1385
+ requestTimeoutMs: swarmOptions?.requestTimeoutMs,
1386
+ onLog: swarmOptions?.onLog ?? onLog,
1387
+ })
1388
+ const swarmHandle = attachService(node, servicesNetwork, swarmDescriptor)
1389
+ node.services.set(swarmHandle.name, swarmHandle)
1390
+ node.swarm = swarmHandle
1391
+ }
1392
+
1393
+ // -- Multi-agent goal decomposition/assignment/execution (opt-in,
1394
+ // issue #124) --------------------------------------------------------------
1395
+ // Attached the same way every other opt-in service above is
1396
+ // (attachService()) -- see mesh-agent-swarm.mjs's own header comment for
1397
+ // the full design (the meshAgentProxy local-vs-remote wrapper that gives
1398
+ // executeSubTask() a real cross-peer dispatch path, and why agentProxy is
1399
+ // required unconditionally, unlike enableVerification's optional
1400
+ // executeFn). Mirrors enableCompute's/enableTerminal's required-dependency
1401
+ // check: AgentSwarmCoordinator's own constructor throws on a missing
1402
+ // agentProxy, but this file always hands it an always-truthy
1403
+ // meshAgentProxy wrapper, so that check alone can never catch a caller who
1404
+ // omitted the real one -- check explicitly here too, before any service is
1405
+ // attached.
1406
+ if (enableAgentSwarm) {
1407
+ if (!agentSwarmOptions?.agentProxy) {
1408
+ throw new Error(
1409
+ 'createMeshNode: options.agentSwarmOptions.agentProxy is required when enableAgentSwarm is true ' +
1410
+ '(must implement async chat(podId, message) -> string -- see peer-agent-swarm.mjs\'s AgentSwarmCoordinator). ' +
1411
+ 'No default agentProxy is provided by this package.',
1412
+ )
1413
+ }
1414
+ const agentSwarmDescriptor = createAgentSwarmService({
1415
+ agentProxy: agentSwarmOptions.agentProxy,
1416
+ dispatchTimeoutMs: agentSwarmOptions?.dispatchTimeoutMs,
1417
+ envelopeType: agentSwarmOptions?.envelopeType,
1418
+ accessResource: agentSwarmOptions?.accessResource,
1419
+ accessAction: agentSwarmOptions?.accessAction,
1420
+ onLog: agentSwarmOptions?.onLog ?? onLog,
1421
+ })
1422
+ const agentSwarmHandle = attachService(node, servicesNetwork, agentSwarmDescriptor)
1423
+ node.services.set(agentSwarmHandle.name, agentSwarmHandle)
1424
+ node.agentSwarm = agentSwarmHandle
1425
+ }
1426
+
1427
+ // -- Pod orchestration (opt-in, Phase 3 of the agent-runtime plan,
1428
+ // issue #92) --------------------------------------------------------------
1429
+ // Attached the same way every other opt-in service above is
1430
+ // (attachService()) -- see mesh-orchestrator.mjs's own header comment for
1431
+ // the full design (the local-vs-remote dispatch shortcut for
1432
+ // execOnPod/deploySkill/drainPod, the checkAccess() gate, why
1433
+ // listPods/getPodStatus/topPods stay ungated, the router
1434
+ // shape-compatibility finding, and the confirmed non-relationship with
1435
+ // enableSwarm). Unlike enableCompute/enableTerminal/enableAgentSwarm,
1436
+ // MeshOrchestrator has no required bring-your-own execution backend --
1437
+ // its own constructor already defaults every collaborator (router,
1438
+ // runtimeRegistry, remoteSessionBroker, resourceRegistry, auditRecorder)
1439
+ // to null and stays usable (local-only) with none of them wired -- so
1440
+ // there is nothing to throw on here. `router` defaults to `node.router?.api`
1441
+ // when enableRouting also attached one and the caller didn't already
1442
+ // supply (or explicitly null out) orchestratorOptions.router.
1443
+ if (enableOrchestrator) {
1444
+ const orchestratorRouter = orchestratorOptions && 'router' in orchestratorOptions
1445
+ ? orchestratorOptions.router
1446
+ : (node.router?.api ?? null)
1447
+ const orchestratorDescriptor = createOrchestratorService({
1448
+ router: orchestratorRouter,
1449
+ runtimeRegistry: orchestratorOptions?.runtimeRegistry,
1450
+ remoteSessionBroker: orchestratorOptions?.remoteSessionBroker,
1451
+ resourceRegistry: orchestratorOptions?.resourceRegistry,
1452
+ auditRecorder: orchestratorOptions?.auditRecorder,
1453
+ dispatchTimeoutMs: orchestratorOptions?.dispatchTimeoutMs,
1454
+ envelopeType: orchestratorOptions?.envelopeType,
1455
+ accessResource: orchestratorOptions?.accessResource,
1456
+ onLog: orchestratorOptions?.onLog ?? onLog,
1457
+ })
1458
+ const orchestratorHandle = attachService(node, servicesNetwork, orchestratorDescriptor)
1459
+ node.services.set(orchestratorHandle.name, orchestratorHandle)
1460
+ node.orchestrator = orchestratorHandle
1461
+ }
1462
+
1463
+ // -- Agent tool registry (opt-in, Phase 4 of the agent-runtime plan,
1464
+ // issues #90/#92) -----------------------------------------------------
1465
+ // Deliberately independent of enableOrchestrator -- see enableAgentRuntime's
1466
+ // own doc comment above for the full rationale. node.toolRegistry always
1467
+ // exists (and is always empty at minimum) when this flag is set, so a
1468
+ // caller wanting only its own non-orchestrator BrowserTools never has to
1469
+ // opt into orchestrator wiring it doesn't want. Only pre-populated with the
1470
+ // 8 real Meshctl*Tools when enableOrchestrator was ALSO set -- see
1471
+ // mesh-orchestrator-tools.mjs's own doc comment for exactly which of those
1472
+ // route through the orchestrator service's gated wire dispatch.
1473
+ if (enableAgentRuntime) {
1474
+ node.toolRegistry = new BrowserToolRegistry()
1475
+ if (enableOrchestrator) {
1476
+ registerOrchestratorTools(node.toolRegistry, node.orchestrator.api)
1477
+ }
1478
+ }
1479
+
361
1480
  return node
362
1481
  }