@johnhenry/browsermesh-apps 0.12.0 → 0.14.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/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.
@@ -984,15 +987,35 @@ export class PaymentChannel {
984
987
  * @property {number|null} resolvedAt
985
988
  */
986
989
 
990
+ /** A conditional-manager contract as the flat record `listEscrows()` returns. */
991
+ function normalizeManagerContract(c) {
992
+ return {
993
+ escrowId: c.id,
994
+ payerPodId: c.payer,
995
+ payeePodId: c.payee,
996
+ amount: c.amount,
997
+ status: c.status,
998
+ source: 'manager',
999
+ };
1000
+ }
1001
+
987
1002
  // ---------------------------------------------------------------------------
988
- // EscrowManager
1003
+ // SimpleEscrowBook
989
1004
  // ---------------------------------------------------------------------------
990
1005
 
991
1006
  /**
992
- * Manages escrow holds between pods. Funds are locked until
993
- * explicitly released, refunded, or expired.
1007
+ * A flat record of escrow holds between pods: `held` then `released`,
1008
+ * `refunded` or `expired`. It is a book only -- it does NOT move any balance,
1009
+ * and has no release conditions, disputes or ledger hook. `PaymentRouter` keeps
1010
+ * one (`getEscrow()`) to track the `ESCROW_CREATE` wire messages it receives.
1011
+ *
1012
+ * It is NOT the package's `EscrowManager`: that name is the conditional escrow
1013
+ * in `peer-escrow.mjs`, which does move funds and supports conditions,
1014
+ * disputes and a `mutateLedger` hook. This class was also called
1015
+ * `EscrowManager` before 0.13, which collided with it; see the README's
1016
+ * "Ledgers and escrow" table.
994
1017
  */
995
- export class EscrowManager {
1018
+ export class SimpleEscrowBook {
996
1019
  /** @type {Map<string, object>} escrowId -> Escrow */
997
1020
  #escrows = new Map();
998
1021
 
@@ -1088,6 +1111,11 @@ export class EscrowManager {
1088
1111
  return true;
1089
1112
  }
1090
1113
 
1114
+ /** Copies of every escrow in the book. */
1115
+ listAll() {
1116
+ return [...this.#escrows.values()].map((e) => ({ ...e }));
1117
+ }
1118
+
1091
1119
  /**
1092
1120
  * List all escrows involving a pod (as payer or payee).
1093
1121
  *
@@ -1155,9 +1183,12 @@ export class PaymentRouter {
1155
1183
  /** @type {Map<string, PaymentChannel>} remotePodId -> channel */
1156
1184
  #channels = new Map();
1157
1185
 
1158
- /** @type {EscrowManager} */
1186
+ /** @type {SimpleEscrowBook} */
1159
1187
  #escrow;
1160
1188
 
1189
+ /** @type {object|null} Optional conditional EscrowManager (peer-escrow.mjs), see attachEscrowManager(). */
1190
+ #escrowManager = null;
1191
+
1161
1192
  /** @type {function|null} */
1162
1193
  #broadcastFn = null;
1163
1194
 
@@ -1179,7 +1210,7 @@ export class PaymentRouter {
1179
1210
  }
1180
1211
  this.#localPodId = localPodId;
1181
1212
  this.#ledger = new CreditLedger(localPodId);
1182
- this.#escrow = new EscrowManager();
1213
+ this.#escrow = new SimpleEscrowBook();
1183
1214
  }
1184
1215
 
1185
1216
  /**
@@ -1297,15 +1328,71 @@ export class PaymentRouter {
1297
1328
  /**
1298
1329
  * Get the escrow manager.
1299
1330
  *
1300
- * @returns {EscrowManager}
1331
+ * @returns {SimpleEscrowBook}
1301
1332
  */
1302
1333
  getEscrow() {
1303
1334
  return this.#escrow;
1304
1335
  }
1305
1336
 
1337
+ /**
1338
+ * Make a conditional `EscrowManager` (peer-escrow.mjs) visible to this
1339
+ * router. The router's own `SimpleEscrowBook` stays what it was: a
1340
+ * wire-level mirror of the `ESCROW_CREATE` messages other pods send, which
1341
+ * moves no balance. The manager is the escrow that debits and credits a
1342
+ * ledger. After attaching, `listEscrows()` / `getEscrowById()` show both, and
1343
+ * the escrow sweeper also expires (and refunds) the manager's due contracts.
1344
+ *
1345
+ * @param {object} manager - An `EscrowManager`
1346
+ * @returns {this}
1347
+ */
1348
+ attachEscrowManager(manager) {
1349
+ if (!manager || typeof manager.create !== 'function' || typeof manager.listContracts !== 'function'
1350
+ || typeof manager.checkExpired !== 'function' || typeof manager.getContract !== 'function') {
1351
+ throw new TypeError('attachEscrowManager requires an EscrowManager');
1352
+ }
1353
+ this.#escrowManager = manager;
1354
+ return this;
1355
+ }
1356
+
1357
+ /** The attached conditional EscrowManager, or null. */
1358
+ getEscrowManager() {
1359
+ return this.#escrowManager;
1360
+ }
1361
+
1362
+ /**
1363
+ * One view over every escrow this router knows about: the wire mirror
1364
+ * (`source: 'wire'`) and, if attached, the manager's contracts
1365
+ * (`source: 'manager'`). Records are normalized copies with
1366
+ * `escrowId`, `payerPodId`, `payeePodId`, `amount`, `status`, `source`.
1367
+ * Statuses are each model's own (`held`/`released`/... vs `funded`/...).
1368
+ *
1369
+ * @param {string} [podId] - Only escrows where this pod is payer or payee
1370
+ * @returns {object[]}
1371
+ */
1372
+ listEscrows(podId) {
1373
+ const out = [];
1374
+ for (const e of this.#escrow.listAll()) out.push({ ...e, source: 'wire' });
1375
+ if (this.#escrowManager) {
1376
+ for (const c of this.#escrowManager.listContracts()) out.push(normalizeManagerContract(c));
1377
+ }
1378
+ return podId ? out.filter((e) => e.payerPodId === podId || e.payeePodId === podId) : out;
1379
+ }
1380
+
1381
+ /**
1382
+ * Look up an escrow by id in either book.
1383
+ * @param {string} escrowId
1384
+ * @returns {object|null}
1385
+ */
1386
+ getEscrowById(escrowId) {
1387
+ const wire = this.#escrow.get(escrowId);
1388
+ if (wire) return { ...wire, source: 'wire' };
1389
+ const c = this.#escrowManager?.getContract(escrowId);
1390
+ return c ? normalizeManagerContract(c) : null;
1391
+ }
1392
+
1306
1393
  /**
1307
1394
  * Start periodic escrow-timeout enforcement. Without this,
1308
- * `EscrowManager.pruneExpired()` exists but nothing ever calls it, so
1395
+ * `SimpleEscrowBook.pruneExpired()` exists but nothing ever calls it, so
1309
1396
  * timed-out escrows sit in `held` status forever.
1310
1397
  *
1311
1398
  * There is no dedicated wire message for escrow expiry in the mesh
@@ -1320,11 +1407,26 @@ export class PaymentRouter {
1320
1407
  */
1321
1408
  startEscrowSweeper(intervalMs = 30000, onExpired = null) {
1322
1409
  this.stopEscrowSweeper();
1323
- this.#escrowSweeperTimer = setInterval(() => {
1324
- const expired = this.#escrow.pruneExpiredDetailed();
1410
+ const report = (expired) => {
1325
1411
  if (expired.length > 0 && onExpired) {
1326
1412
  try { onExpired(expired); } catch (e) { silentCatch('clawser-mesh-payments', 'onExpired', e) }
1327
1413
  }
1414
+ };
1415
+ this.#escrowSweeperTimer = setInterval(() => {
1416
+ const expired = this.#escrow.pruneExpiredDetailed().map((e) => ({ ...e, source: 'wire' }));
1417
+ report(expired);
1418
+ const mgr = this.#escrowManager;
1419
+ if (mgr) {
1420
+ // Manager contracts expire by refunding the payer through its ledger,
1421
+ // which is async; report the ones that were due once that settles.
1422
+ const now = Date.now();
1423
+ const due = mgr.listContracts({ status: 'funded' }).filter((c) => c.isExpired(now)).map((c) => c.id);
1424
+ if (due.length > 0) {
1425
+ mgr.checkExpired(now)
1426
+ .then(() => report(due.map((id) => mgr.getContract(id)).filter((c) => c && c.status === 'expired').map(normalizeManagerContract)))
1427
+ .catch((e) => silentCatch('clawser-mesh-payments', 'manager-checkExpired', e));
1428
+ }
1429
+ }
1328
1430
  }, intervalMs);
1329
1431
  }
1330
1432
 
@@ -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
  }