@johnhenry/browsermesh-apps 0.0.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.
@@ -0,0 +1,478 @@
1
+ /**
2
+ // STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
3
+ * clawser-peer-services.js -- Service advertising and discovery for P2P mesh.
4
+ *
5
+ * Peers advertise capabilities (agent, terminal, files, compute, http-proxy, model)
6
+ * and others can discover and connect to them.
7
+ *
8
+ * ServiceAdvertiser manages local service advertisements with broadcast to peers.
9
+ * ServiceBrowser tracks remote services discovered from other peers.
10
+ *
11
+ * No browser-only imports at module level. All dependencies injected.
12
+ *
13
+ * Run tests:
14
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-services.test.mjs
15
+ */
16
+
17
+ // ---------------------------------------------------------------------------
18
+ // Constants
19
+ // ---------------------------------------------------------------------------
20
+
21
+ /**
22
+ * Well-known service types that peers can advertise.
23
+ */
24
+ export const SERVICE_TYPES = Object.freeze({
25
+ AGENT: 'agent',
26
+ TERMINAL: 'terminal',
27
+ FILES: 'files',
28
+ COMPUTE: 'compute',
29
+ MODEL: 'model',
30
+ HTTP_PROXY: 'http-proxy',
31
+ })
32
+
33
+ /** Default TTL for service descriptors (5 minutes). */
34
+ export const SERVICE_TTL_DEFAULT = 300_000
35
+
36
+ // ---------------------------------------------------------------------------
37
+ // ServiceDescriptor (plain object factory)
38
+ // ---------------------------------------------------------------------------
39
+
40
+ /**
41
+ * Create a ServiceDescriptor — a plain-object record describing an advertised
42
+ * service on the mesh.
43
+ *
44
+ * @param {object} opts
45
+ * @param {string} opts.name - Service name (unique per pod)
46
+ * @param {string} opts.type - One of SERVICE_TYPES values
47
+ * @param {string} opts.podId - Pod that owns the service
48
+ * @param {string} [opts.version] - Semver version string
49
+ * @param {string[]} [opts.capabilities] - Fine-grained capability tags
50
+ * @param {object} [opts.pricing] - Pricing metadata (free-form)
51
+ * @param {object} [opts.metadata] - Arbitrary metadata
52
+ * @param {string} [opts.address] - mesh:// address
53
+ * @param {number} [opts.registeredAt]
54
+ * @param {number} [opts.ttl]
55
+ * @returns {object}
56
+ */
57
+ function createDescriptor({
58
+ name,
59
+ type,
60
+ podId,
61
+ version = '1.0.0',
62
+ capabilities = [],
63
+ pricing = null,
64
+ metadata = null,
65
+ address = null,
66
+ registeredAt = Date.now(),
67
+ ttl = SERVICE_TTL_DEFAULT,
68
+ }) {
69
+ return {
70
+ name,
71
+ type,
72
+ podId,
73
+ version,
74
+ capabilities: [...capabilities],
75
+ pricing: pricing ? { ...pricing } : null,
76
+ metadata: metadata ? { ...metadata } : null,
77
+ address: address ?? `mesh://${podId}/${name}`,
78
+ registeredAt,
79
+ ttl,
80
+ }
81
+ }
82
+
83
+ // ---------------------------------------------------------------------------
84
+ // ServiceAdvertiser
85
+ // ---------------------------------------------------------------------------
86
+
87
+ /**
88
+ * Manages services advertised by the local pod and broadcasts changes to
89
+ * connected peers.
90
+ */
91
+ export class ServiceAdvertiser {
92
+ /** @type {string} */
93
+ #localPodId
94
+
95
+ /** @type {Map<string, object>} name -> ServiceDescriptor */
96
+ #services = new Map()
97
+
98
+ /** @type {Function|null} */
99
+ #broadcastFn
100
+
101
+ /** @type {Function} */
102
+ #onLog
103
+
104
+ /** @type {Map<string, Function[]>} */
105
+ #listeners = new Map()
106
+
107
+ /**
108
+ * @param {object} opts
109
+ * @param {string} opts.localPodId - This pod's identifier
110
+ * @param {Function} [opts.broadcastFn] - (message) => void, broadcast to peers
111
+ * @param {Function} [opts.onLog] - Logging callback
112
+ */
113
+ constructor({ localPodId, broadcastFn, onLog }) {
114
+ if (!localPodId || typeof localPodId !== 'string') {
115
+ throw new Error('localPodId is required and must be a non-empty string')
116
+ }
117
+ this.#localPodId = localPodId
118
+ this.#broadcastFn = broadcastFn ?? null
119
+ this.#onLog = onLog ?? (() => {})
120
+ }
121
+
122
+ // ── Advertising ───────────────────────────────────────────────────
123
+
124
+ /**
125
+ * Advertise a new service from this pod.
126
+ *
127
+ * @param {object} service
128
+ * @param {string} service.name - Service name (unique per pod)
129
+ * @param {string} service.type - Service type (one of SERVICE_TYPES)
130
+ * @param {string} [service.version] - Version string
131
+ * @param {string[]} [service.capabilities] - Capability tags
132
+ * @param {object} [service.pricing] - Pricing metadata
133
+ * @param {object} [service.metadata] - Arbitrary metadata
134
+ * @returns {object} ServiceDescriptor
135
+ */
136
+ advertise(service) {
137
+ if (!service || !service.name || typeof service.name !== 'string') {
138
+ throw new Error('service.name is required and must be a non-empty string')
139
+ }
140
+ if (!service.type || typeof service.type !== 'string') {
141
+ throw new Error('service.type is required and must be a non-empty string')
142
+ }
143
+
144
+ const descriptor = createDescriptor({
145
+ name: service.name,
146
+ type: service.type,
147
+ podId: this.#localPodId,
148
+ version: service.version,
149
+ capabilities: service.capabilities,
150
+ pricing: service.pricing,
151
+ metadata: service.metadata,
152
+ })
153
+
154
+ this.#services.set(service.name, descriptor)
155
+
156
+ // Broadcast to connected peers
157
+ if (this.#broadcastFn) {
158
+ this.#broadcastFn({
159
+ type: 'service:advertise',
160
+ service: descriptor,
161
+ })
162
+ }
163
+
164
+ this.#onLog(`Advertised service: ${service.name} (${service.type})`)
165
+ this.#emit('advertise', descriptor)
166
+
167
+ return descriptor
168
+ }
169
+
170
+ /**
171
+ * Withdraw (remove) a previously advertised service.
172
+ *
173
+ * @param {string} serviceName
174
+ * @returns {boolean} true if the service existed and was removed
175
+ */
176
+ withdraw(serviceName) {
177
+ const descriptor = this.#services.get(serviceName)
178
+ if (!descriptor) return false
179
+
180
+ this.#services.delete(serviceName)
181
+
182
+ // Broadcast withdrawal to connected peers
183
+ if (this.#broadcastFn) {
184
+ this.#broadcastFn({
185
+ type: 'service:withdraw',
186
+ address: descriptor.address,
187
+ podId: this.#localPodId,
188
+ name: serviceName,
189
+ })
190
+ }
191
+
192
+ this.#onLog(`Withdrew service: ${serviceName}`)
193
+ this.#emit('withdraw', descriptor)
194
+
195
+ return true
196
+ }
197
+
198
+ // ── Queries ───────────────────────────────────────────────────────
199
+
200
+ /**
201
+ * List all locally advertised services.
202
+ * @returns {object[]} Array of ServiceDescriptor
203
+ */
204
+ listServices() {
205
+ return [...this.#services.values()]
206
+ }
207
+
208
+ /**
209
+ * Get a single advertised service by name.
210
+ * @param {string} name
211
+ * @returns {object|null} ServiceDescriptor or null
212
+ */
213
+ getService(name) {
214
+ return this.#services.get(name) ?? null
215
+ }
216
+
217
+ // ── Peer Announcement ─────────────────────────────────────────────
218
+
219
+ /**
220
+ * Announce all current services to a newly connected peer.
221
+ *
222
+ * @param {Function} sendFn - (message) => void, sends to the specific peer
223
+ */
224
+ announceToNewPeer(sendFn) {
225
+ if (typeof sendFn !== 'function') {
226
+ throw new Error('sendFn must be a function')
227
+ }
228
+ for (const descriptor of this.#services.values()) {
229
+ sendFn({
230
+ type: 'service:advertise',
231
+ service: descriptor,
232
+ })
233
+ }
234
+ }
235
+
236
+ // ── Events ────────────────────────────────────────────────────────
237
+
238
+ /**
239
+ * Subscribe to an event.
240
+ * @param {string} event - 'advertise' | 'withdraw'
241
+ * @param {Function} cb
242
+ */
243
+ on(event, cb) {
244
+ if (!this.#listeners.has(event)) {
245
+ this.#listeners.set(event, [])
246
+ }
247
+ this.#listeners.get(event).push(cb)
248
+ }
249
+
250
+ /**
251
+ * Unsubscribe from an event.
252
+ * @param {string} event
253
+ * @param {Function} cb
254
+ */
255
+ off(event, cb) {
256
+ const cbs = this.#listeners.get(event)
257
+ if (!cbs) return
258
+ const idx = cbs.indexOf(cb)
259
+ if (idx !== -1) cbs.splice(idx, 1)
260
+ }
261
+
262
+ /**
263
+ * Emit an event to all listeners.
264
+ * @param {string} event
265
+ * @param {...any} args
266
+ */
267
+ #emit(event, ...args) {
268
+ const cbs = this.#listeners.get(event)
269
+ if (!cbs) return
270
+ for (const cb of [...cbs]) {
271
+ try { cb(...args) } catch { /* listener errors do not propagate */ }
272
+ }
273
+ }
274
+
275
+ // ── Serialization ─────────────────────────────────────────────────
276
+
277
+ /**
278
+ * Serialize to a JSON-safe object.
279
+ * @returns {object}
280
+ */
281
+ toJSON() {
282
+ return {
283
+ localPodId: this.#localPodId,
284
+ services: [...this.#services.values()],
285
+ }
286
+ }
287
+ }
288
+
289
+ // ---------------------------------------------------------------------------
290
+ // ServiceBrowser
291
+ // ---------------------------------------------------------------------------
292
+
293
+ /**
294
+ * Tracks services discovered from remote peers on the mesh.
295
+ */
296
+ export class ServiceBrowser {
297
+ /** @type {Map<string, object>} address -> ServiceDescriptor */
298
+ #remoteServices = new Map()
299
+
300
+ /** @type {Map<string, Function[]>} */
301
+ #listeners = new Map()
302
+
303
+ /** @type {Function} */
304
+ #onLog
305
+
306
+ /**
307
+ * @param {object} [opts]
308
+ * @param {Function} [opts.onLog] - Logging callback
309
+ */
310
+ constructor(opts = {}) {
311
+ this.#onLog = opts.onLog ?? (() => {})
312
+ }
313
+
314
+ // ── Incoming Messages ─────────────────────────────────────────────
315
+
316
+ /**
317
+ * Handle an incoming service advertisement from a peer.
318
+ * Adds or updates the service in the remote services map.
319
+ *
320
+ * @param {object} service - ServiceDescriptor from a peer
321
+ */
322
+ handleAdvertisement(service) {
323
+ if (!service || !service.address) {
324
+ return
325
+ }
326
+ this.#remoteServices.set(service.address, service)
327
+ this.#onLog(`Discovered service: ${service.name} at ${service.address}`)
328
+ this.#emit('discovered', service)
329
+ }
330
+
331
+ /**
332
+ * Handle a service withdrawal notification from a peer.
333
+ *
334
+ * @param {string} address - mesh:// address of the withdrawn service
335
+ */
336
+ handleWithdrawal(address) {
337
+ const service = this.#remoteServices.get(address)
338
+ if (!service) return
339
+ this.#remoteServices.delete(address)
340
+ this.#onLog(`Lost service: ${address}`)
341
+ this.#emit('lost', service)
342
+ }
343
+
344
+ // ── Discovery Queries ─────────────────────────────────────────────
345
+
346
+ /**
347
+ * Discover remote services matching an optional filter.
348
+ *
349
+ * @param {object} [filter]
350
+ * @param {string} [filter.type] - Filter by service type
351
+ * @param {string} [filter.capability] - Filter by capability tag
352
+ * @param {string} [filter.podId] - Filter by owning pod
353
+ * @returns {object[]} Array of matching ServiceDescriptor
354
+ */
355
+ discover(filter) {
356
+ const results = []
357
+ for (const svc of this.#remoteServices.values()) {
358
+ if (filter) {
359
+ if (filter.type && svc.type !== filter.type) continue
360
+ if (filter.capability && (!svc.capabilities || !svc.capabilities.includes(filter.capability))) continue
361
+ if (filter.podId && svc.podId !== filter.podId) continue
362
+ }
363
+ results.push(svc)
364
+ }
365
+ return results
366
+ }
367
+
368
+ /**
369
+ * Get a single remote service by its mesh address.
370
+ * @param {string} address
371
+ * @returns {object|null}
372
+ */
373
+ getService(address) {
374
+ return this.#remoteServices.get(address) ?? null
375
+ }
376
+
377
+ /**
378
+ * Get all services from a specific pod.
379
+ * @param {string} podId
380
+ * @returns {object[]}
381
+ */
382
+ getServicesByPod(podId) {
383
+ const results = []
384
+ for (const svc of this.#remoteServices.values()) {
385
+ if (svc.podId === podId) results.push(svc)
386
+ }
387
+ return results
388
+ }
389
+
390
+ /**
391
+ * Get all services of a given type.
392
+ * @param {string} type
393
+ * @returns {object[]}
394
+ */
395
+ getServicesByType(type) {
396
+ const results = []
397
+ for (const svc of this.#remoteServices.values()) {
398
+ if (svc.type === type) results.push(svc)
399
+ }
400
+ return results
401
+ }
402
+
403
+ // ── Maintenance ───────────────────────────────────────────────────
404
+
405
+ /**
406
+ * Remove services whose TTL has expired.
407
+ *
408
+ * @param {number} [now=Date.now()]
409
+ * @returns {number} Number of services pruned
410
+ */
411
+ pruneExpired(now = Date.now()) {
412
+ let count = 0
413
+ for (const [address, svc] of this.#remoteServices) {
414
+ if (now >= svc.registeredAt + svc.ttl) {
415
+ this.#remoteServices.delete(address)
416
+ this.#emit('lost', svc)
417
+ count++
418
+ }
419
+ }
420
+ return count
421
+ }
422
+
423
+ // ── Events ────────────────────────────────────────────────────────
424
+
425
+ /**
426
+ * Subscribe to an event.
427
+ * @param {string} event - 'discovered' | 'lost'
428
+ * @param {Function} cb
429
+ */
430
+ on(event, cb) {
431
+ if (!this.#listeners.has(event)) {
432
+ this.#listeners.set(event, [])
433
+ }
434
+ this.#listeners.get(event).push(cb)
435
+ }
436
+
437
+ /**
438
+ * Unsubscribe from an event.
439
+ * @param {string} event
440
+ * @param {Function} cb
441
+ */
442
+ off(event, cb) {
443
+ const cbs = this.#listeners.get(event)
444
+ if (!cbs) return
445
+ const idx = cbs.indexOf(cb)
446
+ if (idx !== -1) cbs.splice(idx, 1)
447
+ }
448
+
449
+ /**
450
+ * Emit an event to all listeners.
451
+ * @param {string} event
452
+ * @param {...any} args
453
+ */
454
+ #emit(event, ...args) {
455
+ const cbs = this.#listeners.get(event)
456
+ if (!cbs) return
457
+ for (const cb of [...cbs]) {
458
+ try { cb(...args) } catch { /* listener errors do not propagate */ }
459
+ }
460
+ }
461
+
462
+ // ── Accessors ─────────────────────────────────────────────────────
463
+
464
+ /** @returns {number} Number of known remote services */
465
+ get size() {
466
+ return this.#remoteServices.size
467
+ }
468
+
469
+ /**
470
+ * Serialize to a JSON-safe object.
471
+ * @returns {object}
472
+ */
473
+ toJSON() {
474
+ return {
475
+ services: [...this.#remoteServices.values()],
476
+ }
477
+ }
478
+ }