@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/README.md +118 -5
- package/package.json +1 -1
- package/src/index.mjs +11 -5
- package/src/mesh-bootstrap.mjs +11 -5
- package/src/mesh-torrent.mjs +303 -50
- package/src/payments.mjs +113 -11
- package/src/peer-escrow.mjs +49 -11
- package/src/peer-payments.mjs +16 -9
- package/src/peer-timestamp.mjs +11 -3
- package/src/peer-torrent.mjs +58 -28
- package/src/tools.mjs +73 -5
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`, `
|
|
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
|
|
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 | `
|
|
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,82 @@ 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:
|
|
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` stays a wire
|
|
473
|
+
mirror and is a separate book from an `EscrowManager` you create, but the router
|
|
474
|
+
can see both: `router.attachEscrowManager(manager)` makes `router.listEscrows(podId?)`
|
|
475
|
+
and `router.getEscrowById(id)` return one normalized view (`source: 'wire'` or
|
|
476
|
+
`'manager'`), and the escrow sweeper also expires the manager's due contracts.
|
|
477
|
+
An inbound `ESCROW_CREATE` is still only recorded in the book; it does not debit
|
|
478
|
+
anything (the payer is a remote pod).
|
|
400
479
|
|
|
401
480
|
## Putting it all together: sync + kernel-gated mesh + relay on one connection
|
|
402
481
|
|
|
@@ -435,7 +514,10 @@ back as the parsed object through `ctx.onIncomingData()`. That parse accepts
|
|
|
435
514
|
either form, so it works for transports that deliver text and for in-process
|
|
436
515
|
nodes that pass objects. `PeerNode.onIncomingData()` is the raw bus: it hands
|
|
437
516
|
subscribers exactly what the transport delivered, so a direct subscriber that
|
|
438
|
-
wants objects should parse JSON-object text itself
|
|
517
|
+
wants objects should parse JSON-object text itself (every raw subscriber in this
|
|
518
|
+
package -- mesh-sync, the relay host and backend, the pod-host service,
|
|
519
|
+
`BrowserMeshWebSocket`, `createPeerNodeTransport` -- does, through one shared
|
|
520
|
+
`decodeWireData`; a test fails if a new one does not). If you write your own
|
|
439
521
|
transport, make `send()` follow the same rule -- forwarding an object to
|
|
440
522
|
`RTCDataChannel.send()` turns it into the text `"[object Object]"` with no
|
|
441
523
|
error.
|
|
@@ -719,6 +801,37 @@ tool count to 15. `meshctl_supervise` accepts the same args as
|
|
|
719
801
|
`orchestrator.getSupervisor()` then that supervisor's own `supervise()` —
|
|
720
802
|
see "Pod supervisor" above.
|
|
721
803
|
|
|
804
|
+
### IoT tools (opt-in)
|
|
805
|
+
|
|
806
|
+
`registerMeshTools()` registers the stream, file, DHT and GPU tools (12). The
|
|
807
|
+
three IoT tools need an implementation this package does not ship, so they are
|
|
808
|
+
registered only when you pass one, and the agent never sees tools that could
|
|
809
|
+
only fail:
|
|
810
|
+
|
|
811
|
+
```js
|
|
812
|
+
registerMeshTools(registry, multiplexer, fileTransfer, {
|
|
813
|
+
iotBridge, // enables iot_list and iot_send
|
|
814
|
+
iotTelemetry, // enables iot_telemetry
|
|
815
|
+
})
|
|
816
|
+
```
|
|
817
|
+
|
|
818
|
+
The duck types (also `IoTBridgeLike` / `IoTTelemetryLike` typedefs in `tools.mjs`):
|
|
819
|
+
|
|
820
|
+
```js
|
|
821
|
+
iotBridge = {
|
|
822
|
+
// filter is undefined, or { protocol?, capability? }
|
|
823
|
+
listDevices(filter) { return [{ deviceId, name, protocol, capabilities: ['read', 'write'] }] },
|
|
824
|
+
async send(deviceId, payload) { /* deliver; throw or reject on failure */ },
|
|
825
|
+
}
|
|
826
|
+
iotTelemetry = {
|
|
827
|
+
query(deviceId, since, until) { return [{ ts: 1700000000000, value: 21.5 }] }, // oldest first
|
|
828
|
+
getStats(deviceId) { return { min, max, avg, count, last } /* or null when no samples */ },
|
|
829
|
+
}
|
|
830
|
+
```
|
|
831
|
+
|
|
832
|
+
A bridge or telemetry object missing one of those methods makes
|
|
833
|
+
`registerMeshTools()` throw a `TypeError` instead of failing later inside a tool.
|
|
834
|
+
|
|
722
835
|
## Verify argument order (caller-supplied callbacks)
|
|
723
836
|
|
|
724
837
|
Every signature check in BrowserMesh takes `(identity, signature, data)`, the
|
package/package.json
CHANGED
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
|
-
//
|
|
83
|
-
//
|
|
84
|
-
//
|
|
85
|
-
//
|
|
86
|
-
//
|
|
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';
|
package/src/mesh-bootstrap.mjs
CHANGED
|
@@ -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` (
|
|
594
|
-
* `
|
|
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
|
-
'(
|
|
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({
|