@johnhenry/browsermesh-apps 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -18,12 +18,16 @@ Application layer for BrowserMesh: marketplace, chat, payments, compute orchestr
18
18
  - [CloudStorage bucket authorization and key distribution](#cloudstorage-bucket-authorization-and-key-distribution)
19
19
  - [CloudStorage: the ergonomic SDK](#cloudstorage-the-ergonomic-sdk)
20
20
  - [Torrent service: durable stores, authorization and serve limits](#torrent-service-durable-stores-authorization-and-serve-limits)
21
+ - [Downloading: `onManifest`, `onProgress`, concurrency, bounds](#downloading-onmanifest-onprogress-concurrency-bounds)
22
+ - [Using real WebTorrent](#using-real-webtorrent)
23
+ - [Ledgers and escrow: which class is which](#ledgers-and-escrow-which-class-is-which)
21
24
  - [Putting it all together: sync + kernel-gated mesh + relay on one connection](#putting-it-all-together-sync--kernel-gated-mesh--relay-on-one-connection)
22
25
  - [Sending to peers: wire format, the bulk lane and `broadcast()`](#sending-to-peers-wire-format-the-bulk-lane-and-broadcast)
23
26
  - [`fetch()`/`WebSocket`-shaped mesh access: `browserMeshFetch` and `BrowserMeshWebSocket`](#fetchwebsocket-shaped-mesh-access-browsermeshfetch-and-browsermeshwebsocket)
24
27
  - [`browserMeshFetch`](#browsermeshfetch)
25
28
  - [`BrowserMeshWebSocket`](#browsermeshwebsocket)
26
29
  - [LLM tool-calling: `BrowserToolRegistry` and `createAgentRuntime`](#llm-tool-calling-browsertoolregistry-and-createagentruntime)
30
+ - [IoT tools (opt-in)](#iot-tools-opt-in)
27
31
  - [Runtime classes and placement lanes](#runtime-classes-and-placement-lanes)
28
32
  - [Pod host service: spawning and controlling hosted pods](#pod-host-service-spawning-and-controlling-hosted-pods)
29
33
  - [License](#license)
@@ -40,7 +44,7 @@ Extracted from the private `clawser` monorepo (previously `packages/browsermesh-
40
44
  | apps | `AppRegistry`, `AppStore`, `AppRPC`, `AppEventBus` |
41
45
  | marketplace | `Marketplace`, `MarketplaceIndex`, `ServiceListing` |
42
46
  | chat | `MeshChat`, `ChatRoom`, `ChatMessage` |
43
- | payments | `PaymentChannel`, `EscrowManager`, `CreditLedger`, `PaymentRouter` |
47
+ | payments | `PaymentChannel`, `CreditLedger` (single-owner), `SimpleEscrowBook`, `PaymentRouter` (see [Ledgers and escrow](#ledgers-and-escrow-which-class-is-which)) |
44
48
  | quotas | `QuotaManager`, `QuotaEnforcer` |
45
49
  | resources | `ResourceRegistry`, `ComputeRequest`, `ResourceScorer`, `JobQueue` |
46
50
  | gpu | `TrainingOrchestrator`, `GpuProbe`, `GradientAggregator` |
@@ -54,7 +58,7 @@ Extracted from the private `clawser` monorepo (previously `packages/browsermesh-
54
58
  | audit | `AuditChain`, `AuditStore`, `detectFork`, `buildMerkleRoot` |
55
59
  | visualizations | `TopologyLayout`, `TrustGraphLayout`, `TrustHeatmap` |
56
60
  | devtools | `MeshInspector`, `MeshInspectTool` |
57
- | tools | `registerMeshTools` + stream/file/DHT/GPU/IoT BrowserTool subclasses |
61
+ | tools | `registerMeshTools` + stream/file/DHT/GPU BrowserTool subclasses; the IoT tools register only when you pass an IoT bridge (see [IoT tools](#iot-tools-opt-in)) |
58
62
  | peer-agent | `AgentHost`, `AgentClient`, `bridgePeerAgent` |
59
63
  | peer-agent-swarm | `AgentSwarmCoordinator` |
60
64
  | peer-chat | `PeerChat` |
@@ -66,7 +70,7 @@ Extracted from the private `clawser` monorepo (previously `packages/browsermesh-
66
70
  | peer-ipfs | `IPFSStore` (also exported as `MeshLocalCidStore`): a mesh-local content-addressed store. CIDs are SHA-256 hex digests, not IPFS CIDs, and nothing talks to the IPFS network |
67
71
  | peer-node | `PeerNode` |
68
72
  | peer-node-transport | `createPeerNodeTransport` |
69
- | peer-payments | `CreditLedger`, `WebLNProvider` |
73
+ | peer-payments | `MultiPartyCreditLedger`, `WebLNProvider` |
70
74
  | peer-registry | `PeerRegistry` |
71
75
  | peer-routing | `MeshRouter`, `ServerSharing` |
72
76
  | peer-services | `ServiceAdvertiser`, `ServiceBrowser` |
@@ -396,7 +400,77 @@ const info = await torrent.api.seed('some text') // strings are UTF-8 encoded
396
400
  downloaders back off and retry. Caps and `authorize` never apply to the
397
401
  downloading side.
398
402
  - Events: `torrent:chunk-served`, `torrent:chunk-received` (as before), plus
399
- `torrent:request-denied` and `torrent:serve-busy`.
403
+ `torrent:request-denied`, `torrent:serve-busy` and `torrent:download-failed`.
404
+
405
+ ### Downloading: `onManifest`, `onProgress`, concurrency, bounds
406
+
407
+ ```js
408
+ const { data, info } = await torrent.api.download(magnetURI, {
409
+ peers: [seederPubKey],
410
+ // Awaited once the manifest is known and BEFORE any piece is requested or
411
+ // stored: a quota gate. Return false (or throw) to abort; nothing is fetched.
412
+ onManifest: async (manifest) => manifest.size <= await myQuota.remaining(),
413
+ // Once per piece: { received, total, bytes, size, cid, from } (from is null
414
+ // for a piece already in the local store). A throw in here is logged only.
415
+ onProgress: ({ received, total, bytes, size }) => bar.set(bytes / size),
416
+ concurrency: 4, // pieces in flight, 1-32; 1 is strictly sequential
417
+ })
418
+ ```
419
+
420
+ - **`onManifest(manifest)`** gets a copy with `magnetURI`, `infoHash`, `name`,
421
+ `size`, `chunkSize`, `chunkCids`, `cid`. Returning `false` rejects the download
422
+ with `err.code === 'manifest-rejected'`; a throw or rejection propagates as
423
+ is; any other return value lets it proceed.
424
+ - **`concurrency`** defaults to the service's `downloadConcurrency` (4). Each
425
+ provider is still held to its own serve caps: a `busy` answer is retried with
426
+ backoff (`busyRetries`, `busyBackoffMs`) rather than failing the download.
427
+ - **Cleanup.** If a download fails after storing some pieces, the pieces that
428
+ call wrote itself, and that no held torrent lists, are removed again, so a host
429
+ that accounts for storage stays consistent. Pieces already in the store before
430
+ the download are never touched.
431
+ - **Remote manifests are bounded.** A manifest another peer announces or sends
432
+ is ignored (and its sender recorded as nobody's provider) unless it lists at
433
+ most `maxManifestChunks` pieces (default 16384), declares at most
434
+ `maxManifestSize` bytes (default unlimited), has only 64-hex SHA-256 piece
435
+ CIDs, and has a piece count that matches its size (`ceil(size / chunkSize)`).
436
+ At most `maxRemoteManifests` (default 64) are remembered: the least recently
437
+ used is forgotten together with the providers recorded only for its pieces. A
438
+ manifest an in-flight download is using is never evicted.
439
+
440
+ ### Using real WebTorrent
441
+
442
+ `TorrentManager` and `createTorrentService()` never load anything from the
443
+ network. For real BitTorrent swarming give them the library:
444
+
445
+ ```js
446
+ import WebTorrent from 'webtorrent'
447
+ createTorrentService({ webtorrent: WebTorrent }) // the class: built and destroyed for you
448
+ createTorrentService({ webtorrent: new WebTorrent() }) // or a client of your own, left running on destroy()
449
+ ```
450
+
451
+ `window.WebTorrent` / `globalThis.WebTorrent` is still picked up when present.
452
+ With neither, `available` is `false` and the in-memory mesh-native path is used
453
+ (the one `createTorrentService()` serves from anyway). Earlier releases
454
+ imported `webtorrent` from `esm.sh` on first use, which hangs offline and fails
455
+ under a strict CSP; that import is gone.
456
+
457
+ ## Ledgers and escrow: which class is which
458
+
459
+ Four classes cover two ideas, and each public name belongs to exactly one:
460
+
461
+ | Name | Module | Model | Use it for |
462
+ | --- | --- | --- | --- |
463
+ | `CreditLedger` | `payments.mjs` | **Canonical ledger.** One pod, one balance: `credit(amount, from)`, `debit(amount, to)`, `transfer(peerLedger, amount)`, every change an immutable entry. | A pod's own balance; what `PaymentRouter.getLedger()` returns; what the replicated/consensus path assumes. |
464
+ | `MultiPartyCreditLedger` | `peer-payments.mjs` | One book, a balance per pod: `charge(podId, amount)`, `credit(podId, amount)`, `transfer(from, to, amount)`, `calculateCost()`, events. | A hub that keeps everyone's credits (a compute marketplace). Formerly also called `CreditLedger`. |
465
+ | `EscrowManager` | `peer-escrow.mjs` | **Canonical escrow.** Contracts with conditions (`result_hash_match`, `attestation_quorum`, `manual_approval`, timeouts), `dispute()`, a `mutateLedger` hook, `createEscrowService()` for the wire. It moves funds through a ledger. | Anything that actually holds credits. `createMeshNode({ enableEscrow })` uses it. |
466
+ | `SimpleEscrowBook` | `payments.mjs` | A flat record: `held` then `released`/`refunded`/`expired`. No conditions, no disputes, and it moves **no** balance. | What `PaymentRouter.getEscrow()` keeps to track `ESCROW_CREATE` wire messages. Formerly also called `EscrowManager`. |
467
+
468
+ `EscrowManager` accepts either ledger: with a `CreditLedger` it calls
469
+ `debit()`/`credit()` (that ledger has one balance, so use it when the local pod
470
+ is the payer, or pass `mutateLedger` to account for a counterparty); with a
471
+ `MultiPartyCreditLedger` it calls `charge()`/`credit()` so payer and payee each
472
+ move their own balance. `PaymentRouter`'s `SimpleEscrowBook` and an
473
+ `EscrowManager` you create are separate books and do not see each other.
400
474
 
401
475
  ## Putting it all together: sync + kernel-gated mesh + relay on one connection
402
476
 
@@ -435,7 +509,10 @@ back as the parsed object through `ctx.onIncomingData()`. That parse accepts
435
509
  either form, so it works for transports that deliver text and for in-process
436
510
  nodes that pass objects. `PeerNode.onIncomingData()` is the raw bus: it hands
437
511
  subscribers exactly what the transport delivered, so a direct subscriber that
438
- wants objects should parse JSON-object text itself. If you write your own
512
+ wants objects should parse JSON-object text itself (every raw subscriber in this
513
+ package -- mesh-sync, the relay host and backend, the pod-host service,
514
+ `BrowserMeshWebSocket`, `createPeerNodeTransport` -- does, through one shared
515
+ `decodeWireData`; a test fails if a new one does not). If you write your own
439
516
  transport, make `send()` follow the same rule -- forwarding an object to
440
517
  `RTCDataChannel.send()` turns it into the text `"[object Object]"` with no
441
518
  error.
@@ -719,6 +796,37 @@ tool count to 15. `meshctl_supervise` accepts the same args as
719
796
  `orchestrator.getSupervisor()` then that supervisor's own `supervise()` —
720
797
  see "Pod supervisor" above.
721
798
 
799
+ ### IoT tools (opt-in)
800
+
801
+ `registerMeshTools()` registers the stream, file, DHT and GPU tools (12). The
802
+ three IoT tools need an implementation this package does not ship, so they are
803
+ registered only when you pass one, and the agent never sees tools that could
804
+ only fail:
805
+
806
+ ```js
807
+ registerMeshTools(registry, multiplexer, fileTransfer, {
808
+ iotBridge, // enables iot_list and iot_send
809
+ iotTelemetry, // enables iot_telemetry
810
+ })
811
+ ```
812
+
813
+ The duck types (also `IoTBridgeLike` / `IoTTelemetryLike` typedefs in `tools.mjs`):
814
+
815
+ ```js
816
+ iotBridge = {
817
+ // filter is undefined, or { protocol?, capability? }
818
+ listDevices(filter) { return [{ deviceId, name, protocol, capabilities: ['read', 'write'] }] },
819
+ async send(deviceId, payload) { /* deliver; throw or reject on failure */ },
820
+ }
821
+ iotTelemetry = {
822
+ query(deviceId, since, until) { return [{ ts: 1700000000000, value: 21.5 }] }, // oldest first
823
+ getStats(deviceId) { return { min, max, avg, count, last } /* or null when no samples */ },
824
+ }
825
+ ```
826
+
827
+ A bridge or telemetry object missing one of those methods makes
828
+ `registerMeshTools()` throw a `TypeError` instead of failing later inside a tool.
829
+
722
830
  ## Verify argument order (caller-supplied callbacks)
723
831
 
724
832
  Every signature check in BrowserMesh takes `(identity, signature, data)`, the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/browsermesh-apps",
3
- "version": "0.12.0",
3
+ "version": "0.13.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",
package/src/index.mjs CHANGED
@@ -79,10 +79,16 @@ export { BrowserTool, BrowserToolRegistry } from './compat.mjs';
79
79
  export * from './agent-runtime.mjs';
80
80
  export * from './mesh-orchestrator-tools.mjs';
81
81
 
82
- // `CreditLedger` is defined in both payments.mjs and peer-payments.mjs;
83
- // `EscrowManager` is defined in both payments.mjs and peer-escrow.mjs.
84
- // Ambiguous `export *` bindings are silently dropped, so disambiguate
85
- // explicitly in favor of the pair actually used together (mesh-level
86
- // payments.mjs's CreditLedger + peer-escrow.mjs's opts-based EscrowManager).
82
+ // One implementation per public name:
83
+ //
84
+ // CreditLedger payments.mjs single owner: one pod, one balance
85
+ // EscrowManager peer-escrow.mjs conditional escrow that moves funds
86
+ //
87
+ // The other two models keep their own, unambiguous names (also exported through
88
+ // the `export *` lines above): `MultiPartyCreditLedger` (peer-payments.mjs, a
89
+ // book of every peer's balance) and `SimpleEscrowBook` (payments.mjs, the flat
90
+ // record `PaymentRouter` keeps). Neither module defines a `CreditLedger` or
91
+ // `EscrowManager` any more, so no `export *` here is ambiguous; the explicit
92
+ // lines below just say which file each canonical name comes from.
87
93
  export { CreditLedger } from './payments.mjs';
88
94
  export { EscrowManager } from './peer-escrow.mjs';
@@ -578,7 +578,8 @@ import { registerOrchestratorTools } from './mesh-orchestrator-tools.mjs'
578
578
  * Passed straight through to `createTorrentService()`
579
579
  * (`trackerUrl`/`chunkSize`/`envelopeType`/`manifestTimeoutMs`/`chunkTimeoutMs`,
580
580
  * plus the hooks `chunkStore`/`manifestStore`/`authorize`/`maxConcurrentServes`/
581
- * `maxConcurrentServesPerPeer`/`maxBytesPerPeerPerSec`/`maxAnnouncesPerPeerPerMinute`).
581
+ * `maxConcurrentServesPerPeer`/`maxBytesPerPeerPerSec`/`maxAnnouncesPerPeerPerMinute`,
582
+ * and `downloadConcurrency`/`maxManifestChunks`/`maxManifestSize`/`maxRemoteManifests`/`webtorrent`).
582
583
  * @param {boolean} [options.enableEscrow=false] - Attach `peer-escrow.mjs`'s
583
584
  * `createEscrowService()` (issue #117): real escrow-contract create/
584
585
  * release/refund/dispute against `escrowOptions.creditLedger`, with
@@ -590,9 +591,9 @@ import { registerOrchestratorTools } from './mesh-orchestrator-tools.mjs'
590
591
  * @param {object} [options.escrowOptions] - Required when `enableEscrow`.
591
592
  * Passed straight through to `createEscrowService()`
592
593
  * (`creditLedger`/`onLog`/`envelopeType`/`requestTimeoutMs`) -- see that
593
- * function's own doc comment. `escrowOptions.creditLedger` (must have
594
- * `charge()`/`credit()`/`getBalance()`) is required; this function throws
595
- * if it's missing.
594
+ * function's own doc comment. `escrowOptions.creditLedger` (a `CreditLedger`
595
+ * or `MultiPartyCreditLedger`, or anything `EscrowManager` accepts) is
596
+ * required; this function throws if it's missing.
596
597
  * @param {boolean} [options.enableChat=false] - Attach `peer-chat.mjs`'s
597
598
  * `createChatService()` (issue #84, Phase 9): P2P chat with optional
598
599
  * message signing/verification, history, typing indicators, and an
@@ -1229,6 +1230,11 @@ export async function createMeshNode(options = {}) {
1229
1230
  maxConcurrentServesPerPeer: torrentOptions?.maxConcurrentServesPerPeer,
1230
1231
  maxBytesPerPeerPerSec: torrentOptions?.maxBytesPerPeerPerSec,
1231
1232
  maxAnnouncesPerPeerPerMinute: torrentOptions?.maxAnnouncesPerPeerPerMinute,
1233
+ downloadConcurrency: torrentOptions?.downloadConcurrency,
1234
+ maxManifestChunks: torrentOptions?.maxManifestChunks,
1235
+ maxManifestSize: torrentOptions?.maxManifestSize,
1236
+ maxRemoteManifests: torrentOptions?.maxRemoteManifests,
1237
+ webtorrent: torrentOptions?.webtorrent,
1232
1238
  onLog,
1233
1239
  })
1234
1240
  const torrentHandle = attachService(node, servicesNetwork, torrentDescriptor)
@@ -1272,7 +1278,7 @@ export async function createMeshNode(options = {}) {
1272
1278
  if (!escrowOptions?.creditLedger) {
1273
1279
  throw new Error(
1274
1280
  'createMeshNode: options.escrowOptions.creditLedger is required when enableEscrow is true ' +
1275
- '(must implement charge()/credit()/getBalance() -- see peer-escrow.mjs\'s EscrowManager).',
1281
+ '(a CreditLedger, a MultiPartyCreditLedger, or anything with debit()/credit() or charge()/credit() -- see peer-escrow.mjs\'s EscrowManager).',
1276
1282
  )
1277
1283
  }
1278
1284
  const escrowDescriptor = createEscrowService({
@@ -212,6 +212,21 @@ const DEFAULT_BUSY_RETRIES = 3
212
212
  /** Backoff before the first `busy` retry; grows linearly per attempt. */
213
213
  const DEFAULT_BUSY_BACKOFF_MS = 250
214
214
 
215
+ /** Pieces `download()` keeps in flight at once unless told otherwise. */
216
+ const DEFAULT_DOWNLOAD_CONCURRENCY = 4
217
+
218
+ /** Hard ceiling on piece concurrency, whatever a caller asks for. */
219
+ const MAX_DOWNLOAD_CONCURRENCY = 32
220
+
221
+ /** Longest `chunkCids` list accepted in a manifest a remote peer sends (`maxManifestChunks`); 16384 x 64KB = 1GiB. */
222
+ const DEFAULT_MAX_MANIFEST_CHUNKS = 16384
223
+
224
+ /** Remembered remote manifests, least recently used evicted first (`maxRemoteManifests`). */
225
+ const DEFAULT_MAX_REMOTE_MANIFESTS = 64
226
+
227
+ /** A piece CID: the lowercase hex SHA-256 of the piece. */
228
+ const CID_RE = /^[0-9a-f]{64}$/
229
+
215
230
  // ---------------------------------------------------------------------------
216
231
  // Base64 helpers -- deliberately duplicated rather than shared, matching
217
232
  // this family's established convention (see chunk-replication.mjs's /
@@ -258,12 +273,49 @@ function isUsableManifest(m) {
258
273
  && Number.isSafeInteger(m.size) && m.size >= 0
259
274
  }
260
275
 
276
+ /**
277
+ * A manifest a REMOTE peer sent us, held to the bounds the receiver chose:
278
+ * the basic shape of `isUsableManifest`, plus at most `maxChunks` pieces (and
279
+ * `maxSize` bytes), every piece CID a 64-hex SHA-256, and a piece count that
280
+ * matches the declared size (`ceil(size / chunkSize)` when the manifest says
281
+ * its `chunkSize`). Returns the reason it was refused, or `null` when fine.
282
+ *
283
+ * @param {*} m
284
+ * @param {{ maxChunks: number, maxSize: number }} bounds - `Infinity` = unbounded
285
+ * @returns {string|null}
286
+ */
287
+ function remoteManifestProblem(m, { maxChunks, maxSize }) {
288
+ if (!isUsableManifest(m)) return 'malformed'
289
+ if (m.chunkCids.length > maxChunks) return 'too-many-chunks'
290
+ if (m.size > maxSize) return 'too-large'
291
+ for (const cid of m.chunkCids) {
292
+ if (!CID_RE.test(cid)) return 'bad-chunk-cid'
293
+ }
294
+ if (m.cid !== undefined && !(typeof m.cid === 'string' && CID_RE.test(m.cid))) return 'bad-cid'
295
+ if (m.name !== undefined && (typeof m.name !== 'string' || m.name.length > 1024)) return 'bad-name'
296
+ if (m.chunkSize !== undefined && !(Number.isSafeInteger(m.chunkSize) && m.chunkSize > 0)) return 'bad-chunk-size'
297
+ const expected = m.size === 0 ? 0 : (m.chunkSize !== undefined ? Math.ceil(m.size / m.chunkSize) : null)
298
+ if (expected !== null) {
299
+ if (m.chunkCids.length !== expected) return 'size-mismatch'
300
+ } else if (m.chunkCids.length < 1 || m.chunkCids.length > m.size) {
301
+ return 'size-mismatch'
302
+ }
303
+ return null
304
+ }
305
+
261
306
  function checkLimit(name, value) {
262
307
  if (typeof value !== 'number' || Number.isNaN(value) || value < 0) {
263
308
  throw new TypeError(`createTorrentService: ${name} must be a non-negative number (0 or Infinity = unlimited), got ${String(value)}`)
264
309
  }
265
310
  }
266
311
 
312
+ /** A piece concurrency: a whole number from 1 to MAX_DOWNLOAD_CONCURRENCY. */
313
+ function checkConcurrency(name, value) {
314
+ if (!Number.isInteger(value) || value < 1 || value > MAX_DOWNLOAD_CONCURRENCY) {
315
+ throw new TypeError(`createTorrentService: ${name} must be a whole number from 1 to ${MAX_DOWNLOAD_CONCURRENCY}, got ${String(value)}`)
316
+ }
317
+ }
318
+
267
319
  /** Treat 0 as "no limit" for every cap option. */
268
320
  const orUnlimited = (n) => (n === 0 ? Infinity : n)
269
321
 
@@ -310,6 +362,22 @@ const orUnlimited = (n) => (n === 0 ? Infinity : n)
310
362
  * `announce`s accepted per peer per rolling minute; extras are dropped. `0` = unlimited.
311
363
  * @param {number} [opts.busyRetries=3] - Downloader: retries on one provider after `busy`.
312
364
  * @param {number} [opts.busyBackoffMs=250] - Downloader: first backoff after `busy` (grows linearly).
365
+ * @param {number} [opts.downloadConcurrency=4] - Default number of pieces
366
+ * `api.download()` fetches in parallel (a per-call `concurrency` overrides it).
367
+ * Whole numbers 1-32; `1` fetches strictly one piece at a time.
368
+ * @param {number} [opts.maxManifestChunks=16384] - Longest `chunkCids` list
369
+ * accepted in a manifest sent by another peer. Longer ones are ignored, as
370
+ * are manifests whose piece CIDs are not 64-hex SHA-256 digests or whose piece
371
+ * count does not match their declared size. `0` or `Infinity` = unlimited.
372
+ * @param {number} [opts.maxManifestSize=0] - Largest `size` (bytes) accepted in
373
+ * a manifest sent by another peer. `0` = unlimited.
374
+ * @param {number} [opts.maxRemoteManifests=64] - Manifests learned from other
375
+ * peers (via `announce` or a manifest request) that are remembered at once;
376
+ * the least recently used is forgotten, along with the providers recorded only
377
+ * for its pieces. `0` = unlimited.
378
+ * @param {Function|object} [opts.webtorrent] - Forwarded to `new TorrentManager()`:
379
+ * the WebTorrent constructor or client to use for real BitTorrent swarming.
380
+ * Nothing is ever loaded from a CDN. See `TorrentManager`.
313
381
  * @param {() => number} [opts.now] - Clock for rate limits (tests).
314
382
  * @param {(ms: number) => Promise<void>} [opts.sleep] - Sleep for rate limits/backoff (tests).
315
383
  * @returns {import('./mesh-service.mjs').MeshService}
@@ -330,6 +398,11 @@ export function createTorrentService({
330
398
  maxAnnouncesPerPeerPerMinute = DEFAULT_MAX_ANNOUNCES_PER_PEER_PER_MINUTE,
331
399
  busyRetries = DEFAULT_BUSY_RETRIES,
332
400
  busyBackoffMs = DEFAULT_BUSY_BACKOFF_MS,
401
+ downloadConcurrency = DEFAULT_DOWNLOAD_CONCURRENCY,
402
+ maxManifestChunks = DEFAULT_MAX_MANIFEST_CHUNKS,
403
+ maxManifestSize = 0,
404
+ maxRemoteManifests = DEFAULT_MAX_REMOTE_MANIFESTS,
405
+ webtorrent,
333
406
  now = Date.now,
334
407
  sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
335
408
  } = {}) {
@@ -338,9 +411,13 @@ export function createTorrentService({
338
411
  if (authorize !== undefined && typeof authorize !== 'function') {
339
412
  throw new TypeError('createTorrentService: authorize must be a function (fromPubKey, request) => boolean|Promise<boolean>')
340
413
  }
341
- for (const [n, v] of Object.entries({ maxConcurrentServes, maxConcurrentServesPerPeer, maxBytesPerPeerPerSec, maxAnnouncesPerPeerPerMinute })) {
414
+ for (const [n, v] of Object.entries({
415
+ maxConcurrentServes, maxConcurrentServesPerPeer, maxBytesPerPeerPerSec, maxAnnouncesPerPeerPerMinute,
416
+ maxManifestChunks, maxManifestSize, maxRemoteManifests,
417
+ })) {
342
418
  checkLimit(n, v)
343
419
  }
420
+ checkConcurrency('downloadConcurrency', downloadConcurrency)
344
421
  for (const [n, o] of [['chunkStore', injectedChunkStore], ['manifestStore', injectedManifestStore]]) {
345
422
  if (o !== undefined && (o === null || typeof o !== 'object')) {
346
423
  throw new TypeError(`createTorrentService: ${n} must be an object`)
@@ -359,6 +436,8 @@ export function createTorrentService({
359
436
  const globalServeCap = orUnlimited(maxConcurrentServes)
360
437
  const perPeerServeCap = orUnlimited(maxConcurrentServesPerPeer)
361
438
  const announceCap = orUnlimited(maxAnnouncesPerPeerPerMinute)
439
+ const manifestBounds = { maxChunks: orUnlimited(maxManifestChunks), maxSize: orUnlimited(maxManifestSize) }
440
+ const remoteCap = orUnlimited(maxRemoteManifests)
362
441
 
363
442
  return {
364
443
  name: 'torrent',
@@ -373,6 +452,7 @@ export function createTorrentService({
373
452
  chunkSize,
374
453
  chunkStore,
375
454
  manifestStore,
455
+ webtorrent,
376
456
  onLog: (level, msg) => log('mesh-torrent:internal', { level, msg }),
377
457
  })
378
458
 
@@ -383,16 +463,73 @@ export function createTorrentService({
383
463
  */
384
464
  const held = new Map()
385
465
 
386
- /** magnetURI -> manifest a peer announced or answered with, for content we do NOT hold. Memory only. */
466
+ /**
467
+ * magnetURI -> manifest a peer announced or answered with, for content we do NOT hold. Memory only.
468
+ * Bounded (`maxRemoteManifests`): Map insertion order is recency order, oldest first.
469
+ */
387
470
  const remoteManifests = new Map()
388
471
 
472
+ /** piece cid -> number of `remoteManifests` listing it, so providers recorded only for forgotten manifests can be dropped. */
473
+ const remoteCidRefs = new Map()
474
+
475
+ /** magnetURI -> number of in-flight downloads using that remote manifest; those are never evicted. */
476
+ const pinnedRemote = new Map()
477
+
389
478
  /** piece cid -> magnetURIs (in `held`) that list it: what a chunk-request may be served from. */
390
479
  const chunkIndex = new Map()
391
480
 
392
481
  /** @type {Map<string, Set<string>>} cid -> pubKeys known to currently hold that piece */
393
482
  const chunkOwners = new Map()
394
483
 
395
- const manifestFor = (magnetURI) => held.get(magnetURI) ?? remoteManifests.get(magnetURI)
484
+ function manifestFor(magnetURI) {
485
+ const mine = held.get(magnetURI)
486
+ if (mine) return mine
487
+ const remote = remoteManifests.get(magnetURI)
488
+ if (remote) {
489
+ // Use counts as recency: move it to the young end.
490
+ remoteManifests.delete(magnetURI)
491
+ remoteManifests.set(magnetURI, remote)
492
+ }
493
+ return remote
494
+ }
495
+
496
+ /** Forget a remote manifest, and the providers known only because of it. */
497
+ function dropRemote(magnetURI) {
498
+ const manifest = remoteManifests.get(magnetURI)
499
+ if (!manifest) return false
500
+ remoteManifests.delete(magnetURI)
501
+ for (const cid of new Set(manifest.chunkCids)) {
502
+ const left = (remoteCidRefs.get(cid) ?? 1) - 1
503
+ if (left > 0) {
504
+ remoteCidRefs.set(cid, left)
505
+ continue
506
+ }
507
+ remoteCidRefs.delete(cid)
508
+ if (!chunkIndex.has(cid)) chunkOwners.delete(cid)
509
+ }
510
+ return true
511
+ }
512
+
513
+ /** Remember a remote manifest, evicting the least recently used ones past `maxRemoteManifests`. */
514
+ function rememberRemote(magnetURI, manifest) {
515
+ dropRemote(magnetURI)
516
+ remoteManifests.set(magnetURI, manifest)
517
+ for (const cid of new Set(manifest.chunkCids)) remoteCidRefs.set(cid, (remoteCidRefs.get(cid) ?? 0) + 1)
518
+ if (remoteCap === Infinity) return
519
+ for (const key of [...remoteManifests.keys()]) {
520
+ if (remoteManifests.size <= remoteCap) break
521
+ if (key === magnetURI || pinnedRemote.has(key)) continue
522
+ dropRemote(key)
523
+ }
524
+ }
525
+
526
+ /** Vet a manifest another peer sent; log and return false when it is outside the configured bounds. */
527
+ function acceptableRemote(manifest, from, magnetURI) {
528
+ const problem = remoteManifestProblem(manifest, manifestBounds)
529
+ if (!problem) return true
530
+ log('mesh-torrent:remote-manifest-rejected', { from, magnetURI, reason: problem })
531
+ return false
532
+ }
396
533
 
397
534
  function indexHeld(magnetURI, manifest) {
398
535
  for (const cid of manifest.chunkCids) {
@@ -515,8 +652,8 @@ export function createTorrentService({
515
652
  log('mesh-torrent:announce-rate-limited', { from: fromPubKey })
516
653
  return
517
654
  }
518
- if (isUsableManifest(msg.manifest)) {
519
- if (!held.has(msg.magnetURI)) remoteManifests.set(msg.magnetURI, msg.manifest)
655
+ if (acceptableRemote(msg.manifest, fromPubKey, msg.magnetURI)) {
656
+ if (!held.has(msg.magnetURI)) rememberRemote(msg.magnetURI, msg.manifest)
520
657
  recordOwner(fromPubKey, msg.manifest.chunkCids)
521
658
  }
522
659
  ctx.emit('torrent:announce-received', {
@@ -546,10 +683,10 @@ export function createTorrentService({
546
683
  const pending = pendingManifestRequests.get(msg.requestId)
547
684
  if (!pending || !pending.targets.has(fromPubKey)) return
548
685
  pending.targets.delete(fromPubKey)
549
- if (isUsableManifest(msg.manifest)) {
686
+ if (acceptableRemote(msg.manifest, fromPubKey, pending.magnetURI)) {
550
687
  clearTimeout(pending.timer)
551
688
  pendingManifestRequests.delete(msg.requestId)
552
- if (!held.has(pending.magnetURI)) remoteManifests.set(pending.magnetURI, msg.manifest)
689
+ if (!held.has(pending.magnetURI)) rememberRemote(pending.magnetURI, msg.manifest)
553
690
  recordOwner(fromPubKey, msg.manifest.chunkCids)
554
691
  pending.resolve(msg.manifest)
555
692
  return
@@ -734,11 +871,12 @@ export function createTorrentService({
734
871
  * whichever known/candidate provider actually delivers it.
735
872
  * @param {string} cid
736
873
  * @param {string[]} [candidatePeers]
737
- * @returns {Promise<Uint8Array>}
874
+ * @returns {Promise<{ bytes: Uint8Array, from: string|null, written: boolean }>} `from` is
875
+ * null and `written` false when the piece was already in the local store.
738
876
  */
739
877
  async function fetchChunk(cid, candidatePeers) {
740
878
  const already = await chunkStore.get(cid)
741
- if (already) return already
879
+ if (already) return { bytes: already, from: null, written: false }
742
880
 
743
881
  const owners = new Set([...(chunkOwners.get(cid) || []), ...(candidatePeers || [])])
744
882
  owners.delete(peerNode.podId)
@@ -759,7 +897,7 @@ export function createTorrentService({
759
897
  await chunkStore.save(cid, bytes)
760
898
  recordOwner(pubKey, [cid])
761
899
  ctx.emit('torrent:chunk-received', { from: pubKey, cid, size: bytes.length })
762
- return bytes
900
+ return { bytes, from: pubKey, written: true }
763
901
  } catch (err) {
764
902
  lastErr = err
765
903
  if (err?.code === 'busy' && attempt < busyRetries) {
@@ -786,8 +924,8 @@ export function createTorrentService({
786
924
  const prior = held.get(magnetURI)
787
925
  if (prior) unindexHeld(magnetURI, prior)
788
926
  held.set(magnetURI, manifest)
789
- remoteManifests.delete(magnetURI)
790
927
  indexHeld(magnetURI, manifest)
928
+ dropRemote(magnetURI) // after indexHeld, so providers of pieces we now hold are kept
791
929
  await manifestStore.set(magnetURI, manifest)
792
930
  }
793
931
 
@@ -840,75 +978,188 @@ export function createTorrentService({
840
978
  })
841
979
  }
842
980
 
981
+ /** piece cid -> number of in-flight downloads that newly wrote it (cleanup must not delete a piece another download is still using) */
982
+ const inflightWrites = new Map()
983
+
843
984
  /**
844
985
  * Download content from the swarm: piece-by-piece, from whichever
845
986
  * peer(s) are known (via a prior `announce`, or `opts.peers`) to hold
846
987
  * each piece -- not necessarily the original seeder. See module doc
847
988
  * comment's "WHAT MAKES THIS A REAL SWARM" section.
989
+ *
990
+ * Between learning the manifest and requesting the first piece,
991
+ * `opts.onManifest` can veto the download (a storage-quota gate). Pieces
992
+ * are fetched `opts.concurrency` at a time (default `downloadConcurrency`,
993
+ * 4); `1` is strictly sequential. If the download fails after some pieces
994
+ * were stored, the ones this call wrote itself (and no held torrent lists)
995
+ * are removed again, so a quota-accounting host stays consistent.
996
+ *
848
997
  * @param {string} magnetURI
849
998
  * @param {object} [opts]
850
999
  * @param {string[]} [opts.peers] - Candidate peers to ask for the
851
1000
  * manifest (if not already known) and/or any piece with no other
852
1001
  * known provider.
1002
+ * @param {(manifest: { magnetURI: string, infoHash: string, name: string,
1003
+ * size: number, chunkSize?: number, chunkCids: string[], cid?: string }) => boolean|void|Promise<boolean|void>} [opts.onManifest]
1004
+ * Awaited once the manifest is known and before any piece is requested
1005
+ * or written. Return `false` (or throw/reject) to abort: the download
1006
+ * rejects, nothing is fetched. A `false` rejects with `code:
1007
+ * 'manifest-rejected'`; a throw propagates unchanged. Any other return
1008
+ * value lets the download proceed. The manifest is a copy; mutating it
1009
+ * changes nothing.
1010
+ * @param {(p: { received: number, total: number, bytes: number, size: number,
1011
+ * cid: string, from: string|null }) => void} [opts.onProgress] - Called
1012
+ * after each piece is in hand: `received` of `total` pieces, `bytes`
1013
+ * received so far of `size`; `from` is the provider's pubKey, or `null`
1014
+ * for a piece already in the local store. A throw here is logged, not fatal.
1015
+ * @param {number} [opts.concurrency] - Pieces fetched in parallel, a whole
1016
+ * number from 1 to 32. Defaults to the service's `downloadConcurrency`.
1017
+ * Each provider is still held to its own `busy` limits (see `busyRetries`).
853
1018
  * @returns {Promise<{data: Uint8Array, info: import('./peer-torrent.mjs').TorrentInfo}>}
854
1019
  */
855
1020
  async function download(magnetURI, opts = {}) {
1021
+ const { onManifest, onProgress, peers } = opts
1022
+ if (onManifest !== undefined && typeof onManifest !== 'function') {
1023
+ throw new TypeError('download: onManifest must be a function')
1024
+ }
1025
+ if (onProgress !== undefined && typeof onProgress !== 'function') {
1026
+ throw new TypeError('download: onProgress must be a function')
1027
+ }
1028
+ const concurrency = opts.concurrency ?? downloadConcurrency
1029
+ checkConcurrency('concurrency', concurrency)
1030
+
856
1031
  await ready
857
1032
  ctx.emit('torrent:download-start', { magnetURI })
858
1033
 
859
- const manifest = manifestFor(magnetURI) || await requestManifest(magnetURI, opts.peers)
1034
+ const manifest = manifestFor(magnetURI) || await requestManifest(magnetURI, peers)
860
1035
  if (!manifest) {
861
1036
  throw new Error(
862
1037
  `mesh-torrent: no manifest known for ${magnetURI} (no prior announce, and no peer responded -- supply opts.peers)`,
863
1038
  )
864
1039
  }
865
1040
 
866
- const pieces = []
867
- for (const cid of manifest.chunkCids) {
868
- pieces.push(await fetchChunk(cid, opts.peers))
869
- }
870
- const data = concatChunks(pieces)
871
- if (data.length !== manifest.size) {
872
- throw new Error(
873
- `mesh-torrent: reassembled ${data.length} bytes but manifest for ${magnetURI} declares size ${manifest.size}`,
874
- )
875
- }
876
- const contentCid = await ChunkStore.computeCid(data)
877
- if (typeof manifest.cid === 'string' && manifest.cid !== contentCid) {
878
- throw new Error(`mesh-torrent: reassembled content for ${magnetURI} does not match the manifest's cid`)
1041
+ // While this download runs its remote manifest must not be evicted by other announces.
1042
+ const pinned = remoteManifests.has(magnetURI)
1043
+ if (pinned) pinnedRemote.set(magnetURI, (pinnedRemote.get(magnetURI) ?? 0) + 1)
1044
+ /** pieces this call newly wrote */
1045
+ const written = new Set()
1046
+ let finished = false
1047
+ const settleWrites = async (keep) => {
1048
+ if (finished) return
1049
+ finished = true
1050
+ const removable = []
1051
+ for (const cid of written) {
1052
+ const left = (inflightWrites.get(cid) ?? 1) - 1
1053
+ if (left > 0) inflightWrites.set(cid, left)
1054
+ else {
1055
+ inflightWrites.delete(cid)
1056
+ if (!keep && !chunkIndex.has(cid)) removable.push(cid)
1057
+ }
1058
+ }
1059
+ if (pinned) {
1060
+ const n = (pinnedRemote.get(magnetURI) ?? 1) - 1
1061
+ if (n > 0) pinnedRemote.set(magnetURI, n)
1062
+ else pinnedRemote.delete(magnetURI)
1063
+ }
1064
+ await Promise.all(removable.map((cid) => Promise.resolve(chunkStore.remove(cid)).catch((err) => {
1065
+ log('mesh-torrent:cleanup-failed', { cid, error: err?.message || String(err) })
1066
+ })))
879
1067
  }
880
1068
 
881
- // Register this peer as a full holder via TorrentManager's own
882
- // seed() -- genuinely correct, not a hack: a peer with every piece
883
- // of a torrent IS, in real BitTorrent terms, now a seed for it, and
884
- // content-addressing makes this self-consistent -- tm.seed() on
885
- // these identical bytes deterministically reproduces the SAME
886
- // magnetURI/infoHash (same hash, same truncation), so this doesn't
887
- // create a second, different torrent identity for the same content.
888
- // The pieces are re-cut at the size the manifest used (inferred from
889
- // its first piece when the announcing peer did not say), so they are
890
- // the ones already in the store and nothing is stored twice.
891
- const pieceSize = manifest.chunkSize
892
- ?? (pieces.length > 1 ? pieces[0].length : Math.max(data.length, 1))
893
- const info = await tm.seed(data, { name: manifest.name, chunkSize: pieceSize })
894
- if (info.magnetURI !== magnetURI) {
895
- log('mesh-torrent:magnet-mismatch-after-reassembly', { expected: magnetURI, got: info.magnetURI })
896
- }
897
- const stored = await tm.getManifest(info.magnetURI)
898
- await holdManifest(info.magnetURI, stored ?? {
899
- infoHash: info.infoHash, name: manifest.name, size: data.length, chunkSize: pieceSize,
900
- chunkCids: manifest.chunkCids, cid: contentCid,
901
- })
902
- if (info.magnetURI !== magnetURI) remoteManifests.delete(magnetURI)
1069
+ try {
1070
+ if (onManifest) {
1071
+ const verdict = await onManifest({ ...manifest, magnetURI, chunkCids: [...manifest.chunkCids] })
1072
+ if (verdict === false) {
1073
+ const err = new Error(`mesh-torrent: download of ${magnetURI} refused by onManifest`)
1074
+ err.code = 'manifest-rejected'
1075
+ throw err
1076
+ }
1077
+ }
1078
+
1079
+ const cids = manifest.chunkCids
1080
+ const total = cids.length
1081
+ const pieces = new Array(total)
1082
+ let next = 0
1083
+ let received = 0
1084
+ let bytes = 0
1085
+ let failure = null
1086
+ const worker = async () => {
1087
+ while (failure === null) {
1088
+ const index = next++
1089
+ if (index >= total) return
1090
+ try {
1091
+ const got = await fetchChunk(cids[index], peers)
1092
+ if (got.written && !written.has(cids[index])) {
1093
+ written.add(cids[index])
1094
+ inflightWrites.set(cids[index], (inflightWrites.get(cids[index]) ?? 0) + 1)
1095
+ }
1096
+ pieces[index] = got.bytes
1097
+ received++
1098
+ bytes += got.bytes.length
1099
+ if (onProgress) {
1100
+ try {
1101
+ onProgress({ received, total, bytes, size: manifest.size, cid: cids[index], from: got.from })
1102
+ } catch (err) {
1103
+ log('mesh-torrent:progress-callback-error', { magnetURI, error: err?.message || String(err) })
1104
+ }
1105
+ }
1106
+ } catch (err) {
1107
+ failure ??= err
1108
+ return
1109
+ }
1110
+ }
1111
+ }
1112
+ await Promise.all(Array.from({ length: Math.min(concurrency, total) }, worker))
1113
+ if (failure) throw failure
1114
+
1115
+ const data = concatChunks(pieces)
1116
+ if (data.length !== manifest.size) {
1117
+ throw new Error(
1118
+ `mesh-torrent: reassembled ${data.length} bytes but manifest for ${magnetURI} declares size ${manifest.size}`,
1119
+ )
1120
+ }
1121
+ const contentCid = await ChunkStore.computeCid(data)
1122
+ if (typeof manifest.cid === 'string' && manifest.cid !== contentCid) {
1123
+ throw new Error(`mesh-torrent: reassembled content for ${magnetURI} does not match the manifest's cid`)
1124
+ }
1125
+
1126
+ // Register this peer as a full holder via TorrentManager's own
1127
+ // seed() -- genuinely correct, not a hack: a peer with every piece
1128
+ // of a torrent IS, in real BitTorrent terms, now a seed for it, and
1129
+ // content-addressing makes this self-consistent -- tm.seed() on
1130
+ // these identical bytes deterministically reproduces the SAME
1131
+ // magnetURI/infoHash (same hash, same truncation), so this doesn't
1132
+ // create a second, different torrent identity for the same content.
1133
+ // The pieces are re-cut at the size the manifest used (inferred from
1134
+ // its first piece when the announcing peer did not say), so they are
1135
+ // the ones already in the store and nothing is stored twice.
1136
+ const pieceSize = manifest.chunkSize
1137
+ ?? (pieces.length > 1 ? pieces[0].length : Math.max(data.length, 1))
1138
+ const info = await tm.seed(data, { name: manifest.name, chunkSize: pieceSize })
1139
+ if (info.magnetURI !== magnetURI) {
1140
+ log('mesh-torrent:magnet-mismatch-after-reassembly', { expected: magnetURI, got: info.magnetURI })
1141
+ }
1142
+ const stored = await tm.getManifest(info.magnetURI)
1143
+ await holdManifest(info.magnetURI, stored ?? {
1144
+ infoHash: info.infoHash, name: manifest.name, size: data.length, chunkSize: pieceSize,
1145
+ chunkCids: manifest.chunkCids, cid: contentCid,
1146
+ })
1147
+ if (info.magnetURI !== magnetURI) dropRemote(magnetURI)
903
1148
 
904
- ctx.emit('torrent:download-complete', { magnetURI, name: manifest.name, size: data.length })
905
- return { data, info }
1149
+ ctx.emit('torrent:download-complete', { magnetURI, name: manifest.name, size: data.length })
1150
+ await settleWrites(true)
1151
+ return { data, info }
1152
+ } catch (err) {
1153
+ await settleWrites(false)
1154
+ ctx.emit('torrent:download-failed', { magnetURI, error: err?.message || String(err) })
1155
+ throw err
1156
+ }
906
1157
  }
907
1158
 
908
1159
  /** Stop serving a torrent now; its stored manifest and unshared pieces are released in the background (`flush()` waits for that). */
909
1160
  function removeTorrent(magnetURI) {
910
1161
  const removedByTm = tm.removeTorrent(magnetURI)
911
- remoteManifests.delete(magnetURI)
1162
+ dropRemote(magnetURI)
912
1163
  const manifest = held.get(magnetURI)
913
1164
  if (!manifest) return removedByTm
914
1165
  held.delete(magnetURI)
@@ -928,6 +1179,8 @@ export function createTorrentService({
928
1179
  if (!injectedManifestStore && typeof manifestStore.clear === 'function') await manifestStore.clear()
929
1180
  held.clear()
930
1181
  remoteManifests.clear()
1182
+ remoteCidRefs.clear()
1183
+ pinnedRemote.clear()
931
1184
  chunkIndex.clear()
932
1185
  chunkOwners.clear()
933
1186
  }
package/src/payments.mjs CHANGED
@@ -138,7 +138,10 @@ function canonicalBytes(fields) {
138
138
  // ---------------------------------------------------------------------------
139
139
 
140
140
  /**
141
- * Double-entry accounting ledger for a single pod.
141
+ * Double-entry accounting ledger for a single pod -- the package's canonical
142
+ * `CreditLedger` (one owner, one balance, `credit(amount, from)` /
143
+ * `debit(amount, to)` / `transfer(peerLedger, amount)`). For a book that holds
144
+ * every peer's balance see `MultiPartyCreditLedger` in `peer-payments.mjs`.
142
145
  *
143
146
  * Every mutation produces an immutable LedgerEntry recording amount,
144
147
  * counterparty, running balance, and optional memo.
@@ -985,14 +988,22 @@ export class PaymentChannel {
985
988
  */
986
989
 
987
990
  // ---------------------------------------------------------------------------
988
- // EscrowManager
991
+ // SimpleEscrowBook
989
992
  // ---------------------------------------------------------------------------
990
993
 
991
994
  /**
992
- * Manages escrow holds between pods. Funds are locked until
993
- * explicitly released, refunded, or expired.
995
+ * A flat record of escrow holds between pods: `held` then `released`,
996
+ * `refunded` or `expired`. It is a book only -- it does NOT move any balance,
997
+ * and has no release conditions, disputes or ledger hook. `PaymentRouter` keeps
998
+ * one (`getEscrow()`) to track the `ESCROW_CREATE` wire messages it receives.
999
+ *
1000
+ * It is NOT the package's `EscrowManager`: that name is the conditional escrow
1001
+ * in `peer-escrow.mjs`, which does move funds and supports conditions,
1002
+ * disputes and a `mutateLedger` hook. This class was also called
1003
+ * `EscrowManager` before 0.13, which collided with it; see the README's
1004
+ * "Ledgers and escrow" table.
994
1005
  */
995
- export class EscrowManager {
1006
+ export class SimpleEscrowBook {
996
1007
  /** @type {Map<string, object>} escrowId -> Escrow */
997
1008
  #escrows = new Map();
998
1009
 
@@ -1155,7 +1166,7 @@ export class PaymentRouter {
1155
1166
  /** @type {Map<string, PaymentChannel>} remotePodId -> channel */
1156
1167
  #channels = new Map();
1157
1168
 
1158
- /** @type {EscrowManager} */
1169
+ /** @type {SimpleEscrowBook} */
1159
1170
  #escrow;
1160
1171
 
1161
1172
  /** @type {function|null} */
@@ -1179,7 +1190,7 @@ export class PaymentRouter {
1179
1190
  }
1180
1191
  this.#localPodId = localPodId;
1181
1192
  this.#ledger = new CreditLedger(localPodId);
1182
- this.#escrow = new EscrowManager();
1193
+ this.#escrow = new SimpleEscrowBook();
1183
1194
  }
1184
1195
 
1185
1196
  /**
@@ -1297,7 +1308,7 @@ export class PaymentRouter {
1297
1308
  /**
1298
1309
  * Get the escrow manager.
1299
1310
  *
1300
- * @returns {EscrowManager}
1311
+ * @returns {SimpleEscrowBook}
1301
1312
  */
1302
1313
  getEscrow() {
1303
1314
  return this.#escrow;
@@ -1305,7 +1316,7 @@ export class PaymentRouter {
1305
1316
 
1306
1317
  /**
1307
1318
  * Start periodic escrow-timeout enforcement. Without this,
1308
- * `EscrowManager.pruneExpired()` exists but nothing ever calls it, so
1319
+ * `SimpleEscrowBook.pruneExpired()` exists but nothing ever calls it, so
1309
1320
  * timed-out escrows sit in `held` status forever.
1310
1321
  *
1311
1322
  * There is no dedicated wire message for escrow expiry in the mesh
@@ -4,8 +4,11 @@
4
4
  * Enables trustless compute marketplace, dispute resolution, and
5
5
  * guaranteed payment for services.
6
6
  *
7
- * `EscrowManager` itself is plain and dependency-injected (`{creditLedger,
8
- * onLog}`), with no `PeerNode`/mesh-transport awareness of its own -- see
7
+ * `EscrowManager` is the package's one escrow implementation under that name:
8
+ * conditional release, disputes, expiry, and real balance movement through the
9
+ * ledger it is given. (`payments.mjs`'s flat `SimpleEscrowBook`, which
10
+ * `PaymentRouter` keeps, only records holds and moves nothing.) It is plain and
11
+ * dependency-injected (`{creditLedger, onLog}`), with no `PeerNode`/mesh-transport awareness of its own -- see
9
12
  * `createEscrowService()` below (issue #117, `mesh-service.mjs`'s `MeshService`
10
13
  * convention) for the wrapper that wires it onto a real `PeerNode`'s
11
14
  * `ctx.sendTo()`/`ctx.onIncomingData()`/`ctx.registry.checkAccess()`.
@@ -235,8 +238,20 @@ export class EscrowContract {
235
238
  /**
236
239
  * Manages escrow contracts — creation, funding, release, refund, dispute.
237
240
  *
238
- * Works with a credit ledger (e.g. CreditLedger from clawser-peer-payments.js)
239
- * to hold funds in escrow until conditions are met.
241
+ * Works with a credit ledger to hold funds in escrow until conditions are met.
242
+ * Two ledgers are understood out of the box:
243
+ *
244
+ * - `CreditLedger` (`payments.mjs`, one pod's own balance): `create()` calls
245
+ * `debit(amount, payerPodId, memo)`, release/refund call
246
+ * `credit(amount, podId, memo)`. That ledger has a single balance, so every
247
+ * mutation lands on it whatever `podId` says -- use it when the local pod is
248
+ * the payer, or supply `mutateLedger` to account for the counterparty.
249
+ * - `MultiPartyCreditLedger` (`peer-payments.mjs`, a balance per pod):
250
+ * `create()` calls `charge(payerPodId, amount, memo)` (an insufficient balance
251
+ * throws, as the single-owner `debit()` does) and release/refund call
252
+ * `credit(podId, amount, memo)`, so payer and payee each move their own balance.
253
+ *
254
+ * Anything else can be wired with `mutateLedger`.
240
255
  */
241
256
  export class EscrowManager {
242
257
  /** @type {Map<string, EscrowContract>} */
@@ -256,7 +271,9 @@ export class EscrowManager {
256
271
 
257
272
  /**
258
273
  * @param {object} opts
259
- * @param {object} opts.creditLedger - Must have charge(), credit(), getBalance()
274
+ * @param {object} opts.creditLedger - A `CreditLedger` (`debit()`/`credit()`) or a
275
+ * `MultiPartyCreditLedger` (`charge()`/`credit()`); see the class comment.
276
+ * Without a `mutateLedger` hook it must be one of those two shapes.
260
277
  * @param {Function} [opts.onLog] - Logging callback (level, msg)
261
278
  * @param {(op: 'debit'|'credit', amount: number, podId: string, memo: string) => (any|Promise<any>)} [opts.mutateLedger] -
262
279
  * Async (or sync) hook invoked in place of a direct `creditLedger.debit()`/`.credit()`
@@ -281,11 +298,32 @@ export class EscrowManager {
281
298
  }
282
299
  this.#creditLedger = opts.creditLedger
283
300
  this.#onLog = opts.onLog ?? (() => {})
284
- this.#mutateLedger = opts.mutateLedger ?? ((op, amount, podId, memo) => (
285
- op === 'debit'
286
- ? this.#creditLedger.debit(amount, podId, memo)
287
- : this.#creditLedger.credit(amount, podId, memo)
288
- ))
301
+ if (opts.mutateLedger) {
302
+ this.#mutateLedger = opts.mutateLedger
303
+ return
304
+ }
305
+ const ledger = this.#creditLedger
306
+ if (typeof ledger.debit === 'function' && typeof ledger.credit === 'function') {
307
+ // Single-owner CreditLedger: debit(amount, toPodId, memo) / credit(amount, fromPodId, memo)
308
+ this.#mutateLedger = (op, amount, podId, memo) => (
309
+ op === 'debit' ? ledger.debit(amount, podId, memo) : ledger.credit(amount, podId, memo)
310
+ )
311
+ } else if (typeof ledger.charge === 'function' && typeof ledger.credit === 'function') {
312
+ // MultiPartyCreditLedger: charge(podId, amount, memo) / credit(podId, amount, memo)
313
+ this.#mutateLedger = (op, amount, podId, memo) => {
314
+ if (op === 'credit') return ledger.credit(podId, amount, memo)
315
+ const result = ledger.charge(podId, amount, memo)
316
+ if (!result.success) {
317
+ throw new Error(`Insufficient balance: ${podId} needs ${amount}, has ${result.balance}`)
318
+ }
319
+ return result
320
+ }
321
+ } else {
322
+ throw new Error(
323
+ 'EscrowManager: creditLedger must implement debit()/credit() (CreditLedger) or ' +
324
+ 'charge()/credit() (MultiPartyCreditLedger), or pass a mutateLedger hook',
325
+ )
326
+ }
289
327
  }
290
328
 
291
329
  // ── Create ─────────────────────────────────────────────────────
@@ -755,7 +793,7 @@ const DEFAULT_ESCROW_REQUEST_TIMEOUT_MS = 10000
755
793
 
756
794
  /**
757
795
  * @param {object} opts
758
- * @param {object} opts.creditLedger - Must have charge(), credit(), getBalance() -- forwarded to `new EscrowManager()`.
796
+ * @param {object} opts.creditLedger - A `CreditLedger` or `MultiPartyCreditLedger` (see `EscrowManager`) -- forwarded to `new EscrowManager()`.
759
797
  * @param {Function} [opts.onLog] - Logging callback (level, msg) -- forwarded to `EscrowManager`'s own `onLog`, PLUS this wrapper's own wire-level logging (send/handling failures, denied requests).
760
798
  * @param {string} [opts.envelopeType='escrow'] - `envelope.type` used for request/response traffic.
761
799
  * @param {number} [opts.requestTimeoutMs=10000] - How long `requestCreate()`/`requestRelease()`/`requestRefund()`/`requestDispute()` wait for a response.
@@ -2,11 +2,15 @@
2
2
  * clawser-peer-payments.js -- Payment mechanisms for resource sharing.
3
3
  *
4
4
  * Provides a PaymentProvider abstraction with two implementations:
5
- * 1. CreditLedger — internal credit system (no real money)
5
+ * 1. MultiPartyCreditLedger — internal credit system (no real money)
6
6
  * 2. WebLNProvider — Lightning Network payments (optional, requires browser extension)
7
7
  *
8
- * CreditLedger manages multi-peer balances and transaction history with
9
- * resource-based cost calculation. WebLNProvider wraps the WebLN browser API
8
+ * MultiPartyCreditLedger manages every peer's balance in one book, with a
9
+ * transaction history and resource-based cost calculation. It is NOT the
10
+ * package's `CreditLedger`: that name is the single-owner ledger in
11
+ * `payments.mjs` (one pod, one balance). This class was also called
12
+ * `CreditLedger` before 0.13, which collided with it; see the README's
13
+ * "Ledgers and escrow" table. WebLNProvider wraps the WebLN browser API
10
14
  * for optional real-money Lightning payments.
11
15
  *
12
16
  * No browser-only imports at module level. All dependencies injected.
@@ -43,16 +47,19 @@ function generateTxId() {
43
47
  }
44
48
 
45
49
  // ---------------------------------------------------------------------------
46
- // CreditLedger
50
+ // MultiPartyCreditLedger
47
51
  // ---------------------------------------------------------------------------
48
52
 
49
53
  /**
50
- * Multi-peer credit ledger for resource sharing.
54
+ * Multi-peer credit ledger for resource sharing: one book holding a balance
55
+ * per pod (`charge(podId, amount)` / `credit(podId, amount)` /
56
+ * `transfer(from, to, amount)`). For one pod's own balance see `CreditLedger`
57
+ * in `payments.mjs`.
51
58
  *
52
59
  * Tracks per-pod balances with automatic initialization at a configurable
53
60
  * credit amount. Maintains a transaction log with optional capping.
54
61
  */
55
- export class CreditLedger {
62
+ export class MultiPartyCreditLedger {
56
63
  /** @type {Map<string, number>} podId -> balance */
57
64
  #balances = new Map()
58
65
 
@@ -336,12 +343,12 @@ export class CreditLedger {
336
343
  }
337
344
 
338
345
  /**
339
- * Restore a CreditLedger from serialized data.
346
+ * Restore a MultiPartyCreditLedger from serialized data.
340
347
  * @param {object} data
341
- * @returns {CreditLedger}
348
+ * @returns {MultiPartyCreditLedger}
342
349
  */
343
350
  static fromJSON(data) {
344
- const ledger = new CreditLedger({
351
+ const ledger = new MultiPartyCreditLedger({
345
352
  initialCredits: data.initialCredits,
346
353
  maxTransactions: data.maxTransactions,
347
354
  })
@@ -252,6 +252,7 @@ export class TimestampAuthority {
252
252
  #identity
253
253
  #clockSkewMs
254
254
  #onLog
255
+ #now
255
256
 
256
257
  /**
257
258
  * @param {object} opts
@@ -259,8 +260,11 @@ export class TimestampAuthority {
259
260
  * @param {object} opts.identity - Object with sign(data) and podId
260
261
  * @param {number} [opts.clockSkewMs] - Max allowed clock skew in ms (default 30000)
261
262
  * @param {Function} [opts.onLog] - Logging callback (level, msg)
263
+ * @param {() => number} [opts.now] - Local clock in ms, default `Date.now`.
264
+ * Injected by tests so outlier rejection (which compares peer clocks to the
265
+ * local one) does not depend on how long the test took to run.
262
266
  */
263
- constructor({ sessions, identity, clockSkewMs, onLog }) {
267
+ constructor({ sessions, identity, clockSkewMs, onLog, now }) {
264
268
  if (!sessions || typeof sessions.listSessions !== 'function') {
265
269
  throw new Error('sessions is required and must have listSessions()')
266
270
  }
@@ -272,6 +276,10 @@ export class TimestampAuthority {
272
276
  this.#identity = identity
273
277
  this.#clockSkewMs = clockSkewMs ?? TIMESTAMP_DEFAULTS.clockSkewMs
274
278
  this.#onLog = onLog ?? (() => {})
279
+ if (now !== undefined && typeof now !== 'function') {
280
+ throw new Error('now must be a function returning milliseconds')
281
+ }
282
+ this.#now = now ?? Date.now
275
283
  }
276
284
 
277
285
  /**
@@ -290,7 +298,7 @@ export class TimestampAuthority {
290
298
  throw new Error('eventHash is required and must be a non-empty string')
291
299
  }
292
300
 
293
- const localTime = Date.now()
301
+ const localTime = this.#now()
294
302
  const localPodId = this.#identity.podId
295
303
 
296
304
  // Build the full timestamp map: local + peers
@@ -423,7 +431,7 @@ export class TimestampAuthority {
423
431
  * @returns {number} Median timestamp in ms
424
432
  */
425
433
  getNetworkTime(peerTimestamps) {
426
- const values = [Date.now()]
434
+ const values = [this.#now()]
427
435
 
428
436
  if (peerTimestamps) {
429
437
  for (const ts of peerTimestamps.values()) {
@@ -2,8 +2,12 @@
2
2
  // STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
3
3
  * clawser-peer-torrent.js -- WebTorrent integration for P2P file distribution.
4
4
  *
5
- * CDN-loads webtorrent browser bundle for swarm-based file sharing.
6
- * Falls back to direct chunked transfer when WebTorrent unavailable.
5
+ * Uses a WebTorrent client the caller supplies (`new TorrentManager({
6
+ * webtorrent })`: the `WebTorrent` constructor or a ready client) or one
7
+ * already on `window.WebTorrent`/`globalThis.WebTorrent`, for swarm-based file
8
+ * sharing. This module never fetches WebTorrent itself -- there is no CDN or
9
+ * other runtime import -- so it works offline and under a strict CSP. Without
10
+ * a client it falls back to direct chunked transfer.
7
11
  *
8
12
  * DURABILITY (fallback path only): by default the fallback keeps whole blobs
9
13
  * in a private in-memory map. Pass `chunkStore` and/or `manifestStore`
@@ -122,14 +126,21 @@ class FallbackStore {
122
126
  /**
123
127
  * Manages WebTorrent-based file sharing across the mesh.
124
128
  *
125
- * When WebTorrent is available (browser with CDN access), uses real
126
- * BitTorrent swarming. When unavailable (Node.js tests, offline), falls
127
- * back to an in-memory store that mimics the seed/download API.
129
+ * When a WebTorrent client is available (injected through the `webtorrent`
130
+ * option, or on `window`/`globalThis`), uses real BitTorrent swarming. When
131
+ * none is (Node.js tests, offline), falls back to an in-memory store that
132
+ * mimics the seed/download API.
128
133
  */
129
134
  export class TorrentManager {
130
- /** @type {object|null} WebTorrent client instance (lazy-loaded) */
135
+ /** @type {object|null} WebTorrent client instance (created on ensureLoaded) */
131
136
  #client = null
132
137
 
138
+ /** @type {Function|object|null} Injected WebTorrent constructor or client */
139
+ #webtorrent = null
140
+
141
+ /** @type {boolean} True when `#client` was built here (from a constructor/global), so destroy() may destroy it */
142
+ #ownsClient = false
143
+
133
144
  /** @type {Map<string, TorrentInfo>} magnetURI -> TorrentInfo */
134
145
  #activeTorrents = new Map()
135
146
 
@@ -180,8 +191,20 @@ export class TorrentManager {
180
191
  * keyed by magnet URI (sync or async). Defaults to in-memory when only
181
192
  * `chunkStore` is given.
182
193
  * @param {number} [opts.chunkSize=65536] - Piece size when `chunkStore` is used.
194
+ * @param {Function|object} [opts.webtorrent] - The WebTorrent library to use
195
+ * for real BitTorrent swarming: either the `WebTorrent` constructor (this
196
+ * class instantiates and later destroys the client) or an already-built
197
+ * client with `seed()`/`add()`/`remove()`/`destroy()` (yours; `destroy()`
198
+ * here leaves it running). Nothing is ever loaded from the network. Omit it
199
+ * and `window.WebTorrent`/`globalThis.WebTorrent` is used if present,
200
+ * otherwise the in-memory fallback.
183
201
  */
184
202
  constructor(opts = {}) {
203
+ if (opts.webtorrent !== undefined && opts.webtorrent !== null
204
+ && typeof opts.webtorrent !== 'function' && typeof opts.webtorrent !== 'object') {
205
+ throw new TypeError('TorrentManager: webtorrent must be the WebTorrent constructor or a client instance')
206
+ }
207
+ this.#webtorrent = opts.webtorrent ?? null
185
208
  this.#trackerUrl = opts.trackerUrl ?? TORRENT_DEFAULTS.trackerUrl
186
209
  this.#onLog = opts.onLog || (() => {})
187
210
  this.#chunkSize = opts.chunkSize ?? TORRENT_DEFAULTS.chunkSize
@@ -191,42 +214,48 @@ export class TorrentManager {
191
214
  }
192
215
  }
193
216
 
194
- // ── CDN Loading ──────────────────────────────────────────────────────
217
+ // ── WebTorrent client ─────────────────────────────────────────────────
195
218
 
196
219
  /**
197
- * Lazy-load WebTorrent from CDN.
198
- * Sets #wtAvailable based on whether the load succeeded.
220
+ * Set up the WebTorrent client from what the caller provided, and restore
221
+ * persisted torrents when running on the fallback store.
222
+ *
223
+ * Order: the injected `webtorrent` option, then `window.WebTorrent`, then
224
+ * `globalThis.WebTorrent`. Nothing is fetched; with none of them present
225
+ * `available` stays false and the in-memory fallback is used.
226
+ * Sets #wtAvailable based on whether a client was created.
199
227
  */
200
228
  async ensureLoaded() {
201
229
  if (this.#loaded) return
202
230
 
203
231
  try {
204
- // Only attempt in browser-like environments with dynamic import support
205
- if (typeof window !== 'undefined' && typeof window.WebTorrent === 'function') {
232
+ const injected = this.#webtorrent
233
+ if (injected && typeof injected === 'object') {
234
+ this.#client = injected
235
+ this.#ownsClient = false
236
+ this.#wtAvailable = true
237
+ this.#onLog(2, 'WebTorrent client supplied by the caller')
238
+ } else if (typeof injected === 'function') {
239
+ this.#client = new injected()
240
+ this.#ownsClient = true
241
+ this.#wtAvailable = true
242
+ this.#onLog(2, 'WebTorrent client created from the injected constructor')
243
+ } else if (typeof window !== 'undefined' && typeof window.WebTorrent === 'function') {
206
244
  this.#client = new window.WebTorrent()
245
+ this.#ownsClient = true
207
246
  this.#wtAvailable = true
208
247
  this.#onLog(2, 'WebTorrent client initialized from window.WebTorrent')
209
248
  } else if (typeof globalThis.WebTorrent === 'function') {
210
249
  this.#client = new globalThis.WebTorrent()
250
+ this.#ownsClient = true
211
251
  this.#wtAvailable = true
212
252
  this.#onLog(2, 'WebTorrent client initialized from globalThis.WebTorrent')
213
253
  } else {
214
- // Try CDN load via esm.sh — this will fail in Node.js test env
215
- try {
216
- const mod = await import('https://esm.sh/webtorrent@2.8.5')
217
- const WT = mod.default || mod.WebTorrent
218
- if (typeof WT === 'function') {
219
- globalThis.WebTorrent = WT
220
- this.#client = new WT()
221
- this.#wtAvailable = true
222
- this.#onLog(2, 'WebTorrent loaded from CDN (esm.sh)')
223
- }
224
- } catch {
225
- this.#wtAvailable = false
226
- this.#onLog(1, 'WebTorrent CDN load failed — using fallback store')
227
- }
254
+ this.#wtAvailable = false
255
+ this.#onLog(1, 'No WebTorrent client supplied (pass { webtorrent }) — using fallback store')
228
256
  }
229
257
  } catch (err) {
258
+ this.#client = null
230
259
  this.#wtAvailable = false
231
260
  this.#onLog(1, `WebTorrent initialization failed: ${err.message}`)
232
261
  }
@@ -718,8 +747,8 @@ export class TorrentManager {
718
747
  this.#fallback.clear()
719
748
  this.#listeners.clear()
720
749
 
721
- // Destroy real client if present
722
- if (this.#client) {
750
+ // Destroy the real client if we built it; one the caller passed in stays theirs.
751
+ if (this.#client && this.#ownsClient) {
723
752
  try {
724
753
  await new Promise((resolve, reject) => {
725
754
  this.#client.destroy((err) => {
@@ -730,8 +759,9 @@ export class TorrentManager {
730
759
  } catch {
731
760
  // best effort
732
761
  }
733
- this.#client = null
734
762
  }
763
+ this.#client = null
764
+ this.#ownsClient = false
735
765
 
736
766
  this.#loaded = false
737
767
  this.#wtAvailable = false
package/src/tools.mjs CHANGED
@@ -9,6 +9,38 @@
9
9
 
10
10
  import { BrowserTool } from './compat.mjs';
11
11
 
12
+ // ── IoT duck types ───────────────────────────────────────────────────
13
+ //
14
+ // This package ships no IoT implementation. The three iot_* tools call into a
15
+ // bridge and a telemetry store that the host application supplies, and are only
16
+ // registered (see `registerMeshTools()`) when one is passed in.
17
+
18
+ /**
19
+ * What `iot_list` and `iot_send` call. Supply an object with these methods as
20
+ * `registerMeshTools(registry, mux, ft, { iotBridge })`.
21
+ *
22
+ * @typedef {object} IoTBridgeLike
23
+ * @property {(filter?: { protocol?: string, capability?: string }) =>
24
+ * Array<{ deviceId: string, name?: string, protocol: string, capabilities: string[] }>} listDevices
25
+ * Registered devices, optionally filtered by `protocol` and/or `capability`
26
+ * (called with `undefined` when neither is given).
27
+ * @property {(deviceId: string, payload: object) => Promise<void>|void} send
28
+ * Deliver `payload` to the device; throw or reject on failure.
29
+ */
30
+
31
+ /**
32
+ * What `iot_telemetry` calls. Supply as
33
+ * `registerMeshTools(registry, mux, ft, { iotTelemetry })`.
34
+ *
35
+ * @typedef {object} IoTTelemetryLike
36
+ * @property {(deviceId: string, since?: number, until?: number) =>
37
+ * Array<{ ts: number, value: * }>} query
38
+ * Samples for a device, oldest first; `ts` is epoch milliseconds.
39
+ * @property {(deviceId: string) =>
40
+ * { min: number, max: number, avg: number, count: number, last: * }|null} getStats
41
+ * Summary statistics, or `null` when the device has no samples.
42
+ */
43
+
12
44
  // ── Shared state ─────────────────────────────────────────────────────
13
45
 
14
46
  /**
@@ -35,10 +67,14 @@ export class MeshToolsContext {
35
67
  setTrainingOrchestrator(orch) { this.#trainingOrchestrator = orch; }
36
68
  getTrainingOrchestrator() { return this.#trainingOrchestrator; }
37
69
 
70
+ /** @param {IoTBridgeLike|null} bridge */
38
71
  setIoTBridge(bridge) { this.#iotBridge = bridge; }
72
+ /** @returns {IoTBridgeLike|null} */
39
73
  getIoTBridge() { return this.#iotBridge; }
40
74
 
75
+ /** @param {IoTTelemetryLike|null} telemetry */
41
76
  setIoTTelemetry(telemetry) { this.#iotTelemetry = telemetry; }
77
+ /** @returns {IoTTelemetryLike|null} */
42
78
  getIoTTelemetry() { return this.#iotTelemetry; }
43
79
  }
44
80
 
@@ -641,14 +677,32 @@ export class IoTTelemetryTool extends BrowserTool {
641
677
  // ── Registry helper ──────────────────────────────────────────────────
642
678
 
643
679
  /**
644
- * Register all mesh stream/file tools with a BrowserToolRegistry.
680
+ * Register the mesh stream/file/DHT/GPU tools with a BrowserToolRegistry (12
681
+ * tools), plus the IoT tools the caller opts into.
682
+ *
683
+ * The IoT tools need an implementation this package does not ship, so they are
684
+ * registered only when you supply one: `iot_list` and `iot_send` when
685
+ * `options.iotBridge` is given, `iot_telemetry` when `options.iotTelemetry` is.
686
+ * Without them the agent never sees tools that could only fail. See
687
+ * {@link IoTBridgeLike} and {@link IoTTelemetryLike} for the duck types.
688
+ *
645
689
  * @param {import('./compat.mjs').BrowserToolRegistry} registry
646
690
  * @param {import('@johnhenry/browsermesh-transport').StreamMultiplexer} [multiplexer]
647
691
  * @param {import('@johnhenry/browsermesh-sync').MeshFileTransfer} [fileTransfer]
692
+ * @param {object} [options]
693
+ * @param {IoTBridgeLike} [options.iotBridge] - Enables `iot_list` and `iot_send`.
694
+ * @param {IoTTelemetryLike} [options.iotTelemetry] - Enables `iot_telemetry`.
695
+ * @throws {TypeError} If a supplied bridge/telemetry lacks a required method.
648
696
  */
649
- export function registerMeshTools(registry, multiplexer, fileTransfer) {
697
+ export function registerMeshTools(registry, multiplexer, fileTransfer, options = {}) {
698
+ const { iotBridge, iotTelemetry } = options || {};
699
+ assertHasMethods('iotBridge', iotBridge, ['listDevices', 'send']);
700
+ assertHasMethods('iotTelemetry', iotTelemetry, ['query', 'getStats']);
701
+
650
702
  if (multiplexer) meshToolsContext.setMultiplexer(multiplexer);
651
703
  if (fileTransfer) meshToolsContext.setFileTransfer(fileTransfer);
704
+ if (iotBridge) meshToolsContext.setIoTBridge(iotBridge);
705
+ if (iotTelemetry) meshToolsContext.setIoTTelemetry(iotTelemetry);
652
706
 
653
707
  registry.register(new MeshStreamOpenTool());
654
708
  registry.register(new MeshStreamCloseTool());
@@ -662,7 +716,21 @@ export function registerMeshTools(registry, multiplexer, fileTransfer) {
662
716
  registry.register(new DhtPeersTool());
663
717
  registry.register(new GpuTrainStartTool());
664
718
  registry.register(new GpuTrainStatusTool());
665
- registry.register(new IoTListTool());
666
- registry.register(new IoTSendTool());
667
- registry.register(new IoTTelemetryTool());
719
+ if (iotBridge) {
720
+ registry.register(new IoTListTool());
721
+ registry.register(new IoTSendTool());
722
+ }
723
+ if (iotTelemetry) {
724
+ registry.register(new IoTTelemetryTool());
725
+ }
726
+ }
727
+
728
+ /** @param {string} name @param {*} value @param {string[]} methods */
729
+ function assertHasMethods(name, value, methods) {
730
+ if (value === undefined || value === null) return;
731
+ for (const m of methods) {
732
+ if (typeof value[m] !== 'function') {
733
+ throw new TypeError(`registerMeshTools: options.${name} must implement ${m}()`);
734
+ }
735
+ }
668
736
  }