@johnhenry/browsermesh-apps 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +232 -1
  2. package/package.json +7 -3
  3. package/src/agent-runtime.mjs +342 -0
  4. package/src/chunk-replication.mjs +751 -0
  5. package/src/cloud-storage-backend.mjs +932 -0
  6. package/src/cloud-storage.mjs +859 -0
  7. package/src/compat.mjs +98 -0
  8. package/src/grant-log.mjs +840 -0
  9. package/src/index.mjs +34 -2
  10. package/src/key-distribution.mjs +525 -0
  11. package/src/manifest-sync.mjs +363 -0
  12. package/src/mesh-agent-swarm.mjs +376 -0
  13. package/src/mesh-bootstrap.mjs +1131 -12
  14. package/src/mesh-compute.mjs +397 -0
  15. package/src/mesh-dht.mjs +182 -0
  16. package/src/mesh-fetch.mjs +246 -0
  17. package/src/mesh-hardening.mjs +226 -0
  18. package/src/mesh-health.mjs +282 -0
  19. package/src/mesh-keepalive.mjs +353 -0
  20. package/src/mesh-kv.mjs +673 -0
  21. package/src/mesh-orchestrator-tools.mjs +251 -0
  22. package/src/mesh-orchestrator.mjs +343 -0
  23. package/src/mesh-rpc.mjs +300 -0
  24. package/src/mesh-service.mjs +403 -0
  25. package/src/mesh-swarm.mjs +677 -0
  26. package/src/mesh-timestamp.mjs +265 -0
  27. package/src/mesh-torrent.mjs +683 -0
  28. package/src/mesh-verification.mjs +367 -0
  29. package/src/mesh-websocket.mjs +722 -0
  30. package/src/observability-bridge.mjs +453 -0
  31. package/src/orchestrator.mjs +18 -5
  32. package/src/peer-agent-swarm.mjs +12 -1
  33. package/src/peer-chat.mjs +230 -61
  34. package/src/peer-compute.mjs +66 -3
  35. package/src/peer-escrow.mjs +350 -1
  36. package/src/peer-files.mjs +362 -168
  37. package/src/peer-ipfs.mjs +205 -10
  38. package/src/peer-node.mjs +33 -2
  39. package/src/peer-routing.mjs +369 -5
  40. package/src/peer-terminal.mjs +400 -130
  41. package/src/serverless-executor-andbox.mjs +136 -0
  42. package/src/serverless-fetch.mjs +70 -0
  43. package/src/serverless-functions.mjs +67 -0
  44. package/src/serverless-peer-select.mjs +69 -0
  45. package/src/serverless-proxy.mjs +127 -0
  46. package/src/serverless-router.mjs +115 -0
  47. package/src/serverless-sites.mjs +116 -0
  48. package/src/serverless-static.mjs +202 -0
  49. package/src/serverless-wire.mjs +87 -0
  50. package/src/peer-session.mjs +0 -937
package/src/peer-chat.mjs CHANGED
@@ -1,15 +1,94 @@
1
1
  /**
2
- // STATUS: EXPERIMENTAL — complete implementation, not yet integrated into main application
3
- * clawser-peer-chat.js -- P2P chat over peer sessions.
2
+ * peer-chat.mjs -- P2P chat as a `MeshService` (Phase 9 of the
3
+ * browsermesh-app-layer-migration plan, issue #84).
4
4
  *
5
- * Provides direct chat between two peers on top of PeerSession, with
6
- * message signing/verification and optional agent auto-response.
5
+ * `PeerChat` used to require a live `PeerSession` instance
6
+ * (`opts.session`), registering itself on that session's `'chat'` service
7
+ * type (`session.registerHandler('chat', ...)`) and sending via
8
+ * `session.send('chat', payload)`. Nothing in this repo ever constructs a
9
+ * `PeerSession` (`SessionManager` is never instantiated outside its own
10
+ * tests -- see issue #84's ground-truth grep), so `PeerChat` had no real
11
+ * caller. This migration removes that dependency entirely: `PeerChat` now
12
+ * talks over a caller-supplied `send(toPubKey, payload)` function and an
13
+ * externally-driven `receiveEnvelope(fromPubKey, envelope)` method, and
14
+ * `createChatService()` (below) wires those onto `ctx.sendTo()`/
15
+ * `ctx.onIncomingData()` (`mesh-service.mjs`, Phase C's `attach()`/`ctx`
16
+ * convention) -- the same "thin `MeshService` wrapper, not a rewrite of the
17
+ * internal logic" pattern `mesh-timestamp.mjs`/`mesh-health.mjs` (Phase 1)
18
+ * and `peer-routing.mjs` (Phase 2) already established.
7
19
  *
8
- * Dependencies are injected (PeerSession, signing functions).
9
- * No browser-only imports at module level.
20
+ * `PeerChat`'s actual chat logic -- message signing/verification, history
21
+ * tracking, typing-indicator handling, the auto-responder hook -- is
22
+ * UNCHANGED by this migration. Two necessary, transport-driven adaptations,
23
+ * both documented here rather than left implicit:
24
+ *
25
+ * 1. **One `PeerChat` no longer means one fixed remote peer.** A
26
+ * `PeerSession` was inherently one-to-one (`session.localPodId`/
27
+ * `session.remotePodId` fixed at session-creation time), so the old
28
+ * `sendMessage(text, opts)`/`sendTyping()` needed no target argument.
29
+ * A `MeshService` is attached ONCE per node and can talk to every
30
+ * connected peer, so `sendMessage()`/`sendTyping()` now take an
31
+ * explicit `toPubKey` first argument, and history is one flat,
32
+ * service-wide log (each message's own `from`/`to` fields -- already
33
+ * part of the message shape -- distinguish which conversation a given
34
+ * entry belongs to; a caller wanting a single thread filters
35
+ * client-side). This is the multi-peer generalization of the old
36
+ * one-remote-per-session model, not a redesign of what a `ChatMessage`
37
+ * looks like or how history accumulates.
38
+ *
39
+ * 2. **Signature verification now keys off the actual sender's pubKey,
40
+ * not one fixed constructor-time `remotePubKey`.** The old
41
+ * constructor accepted a separate, fixed `opts.remotePubKey` (raw
42
+ * Ed25519 public key bytes) used only by `verifyFn`. With no single
43
+ * bound remote peer left, `receiveEnvelope()` instead passes the
44
+ * message's real, per-message `fromPubKey` (the routing fingerprint
45
+ * `ctx.onIncomingData()` hands every subscriber, matching every other
46
+ * `MeshService` in this family) as `verifyFn`'s first argument.
47
+ * `verifyFn` is an entirely caller-injected, duck-typed dependency --
48
+ * it always was -- so this only changes WHAT gets passed as its first
49
+ * argument, not whether verification happens or how. Resolving a
50
+ * routing fingerprint to raw public key bytes (if a caller's
51
+ * `verifyFn` needs that distinction) is left to the caller, exactly
52
+ * the same "podId -> pubkey directory is a real, separate piece of
53
+ * design, out of scope for a thin wrapper" stance `mesh-timestamp.mjs`
54
+ * already takes for its own `identity.verify()`.
55
+ *
56
+ * 3. **The typing-indicator discriminator moved from `payload.type` to
57
+ * `payload.kind`.** The old wire shape reused the session envelope's
58
+ * OWN `type` field (`'chat'`) for routing and a SEPARATE, unrelated
59
+ * `payload.type: 'typing'` field nested one level deeper
60
+ * (`session.send('chat', {type: 'typing', ...})` wrapped that payload
61
+ * inside `{type: 'chat', payload: {...}, ...}` -- no collision).
62
+ * `ctx.sendTo(pubKey, type, payload)` instead merges flat:
63
+ * `{type, ...payload}` (`mesh-service.mjs`) -- if `payload` also had a
64
+ * `type` field, spreading it would silently overwrite the outer
65
+ * `'chat'` envelope type with `'typing'`, breaking
66
+ * `ctx.onIncomingData('chat', ...)`'s own filtering. `kind` is this
67
+ * family's established name for exactly this "sub-message discriminator
68
+ * distinct from the envelope's own routing `type`" concept (see
69
+ * `mesh-websocket.mjs`'s `kind: 'ws-open'|'ws-message'|...` and
70
+ * `mesh-rpc.mjs`'s `kind: 'rpc-request'|'rpc-response'`), so this file
71
+ * adopts it too rather than inventing a third name for the same idea.
72
+ *
73
+ * Everything else -- message id generation, base64 signature encoding,
74
+ * `#addToHistory()`'s cap-at-`maxHistory` behavior, the auto-responder's
75
+ * "never reply to an auto-response" guard, `on`/`off`'s listener-error
76
+ * isolation -- is copied over unchanged.
77
+ *
78
+ * `createChatService()`'s own contribution is intentionally small: it
79
+ * constructs ONE `PeerChat` per `attach()` call, wires its `send` onto
80
+ * `ctx.sendTo(toPubKey, 'chat', payload)`, routes every inbound `'chat'`-typed
81
+ * envelope (`ctx.onIncomingData('chat', ...)`) to `chat.receiveEnvelope()`,
82
+ * and bridges `PeerChat`'s own `on('message:sent'|'message:received'|
83
+ * 'typing', ...)` events through `ctx.emit()` under the
84
+ * `chat:message-sent`/`chat:message-received`/`chat:typing` names (this
85
+ * family's `<service>:<kebab-description>` observability convention -- see
86
+ * `mesh-service.mjs`'s module doc comment). `PeerChat`'s own `on`/`off`
87
+ * stay fully functional too (nothing here removes them) -- `ctx.emit()` is
88
+ * an ADDITIONAL, curated broadcast of the same moments, not a replacement.
10
89
  *
11
90
  * Run tests:
12
- * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-chat.test.mjs
91
+ * node --test packages/browsermesh-apps/test/peer-chat.test.mjs
13
92
  */
14
93
 
15
94
  // ---------------------------------------------------------------------------
@@ -70,26 +149,29 @@ function base64ToBytes(b64) {
70
149
  // ---------------------------------------------------------------------------
71
150
 
72
151
  /**
73
- * P2P chat over a single PeerSession.
152
+ * P2P chat, transport-agnostic beyond a caller-supplied `send()` function.
74
153
  *
75
- * Sends and receives chat messages on the 'chat' service type, with
76
- * optional cryptographic signing/verification and an auto-responder
77
- * hook for agent-driven replies.
154
+ * Sends and receives chat messages, with optional cryptographic
155
+ * signing/verification and an auto-responder hook for agent-driven replies.
156
+ * See this file's module doc comment for the full design writeup, including
157
+ * why `sendMessage()`/`sendTyping()` take an explicit target pubKey and why
158
+ * `verifyFn` is called with each message's actual sender rather than one
159
+ * fixed constructor-time key.
78
160
  */
79
161
  export class PeerChat {
80
- /** @type {object} PeerSession */
81
- #session
162
+ /** @type {string} This node's own routing pubKey/podId. */
163
+ #localPubKey
164
+
165
+ /** @type {(toPubKey: string, payload: object) => Promise<void>} */
166
+ #send
82
167
 
83
168
  /** @type {((data: Uint8Array) => Promise<Uint8Array>)|null} */
84
169
  #signFn
85
170
 
86
- /** @type {((pubKey: Uint8Array, data: Uint8Array, sig: Uint8Array) => Promise<boolean>)|null} */
171
+ /** @type {((fromPubKey: string, data: Uint8Array, sig: Uint8Array) => Promise<boolean>)|null} */
87
172
  #verifyFn
88
173
 
89
- /** @type {Uint8Array|null} */
90
- #remotePubKey
91
-
92
- /** @type {Array<object>} ChatMessage objects */
174
+ /** @type {Array<object>} ChatMessage objects, flat across every conversation this instance has seen. */
93
175
  #messageHistory = []
94
176
 
95
177
  /** @type {number} */
@@ -106,49 +188,61 @@ export class PeerChat {
106
188
 
107
189
  /**
108
190
  * @param {object} opts
109
- * @param {object} opts.session - PeerSession instance
191
+ * @param {string} opts.localPubKey - This node's own routing pubKey/podId, used as `message.from`.
192
+ * @param {(toPubKey: string, payload: object) => (void|Promise<void>)} opts.send -
193
+ * Transport hook, replacing the old `session.send('chat', payload)`.
194
+ * Called with the message/typing-indicator payload (NOT pre-wrapped in
195
+ * an envelope -- the caller, typically `createChatService()`, adds
196
+ * whatever envelope shape its own transport needs).
110
197
  * @param {Function} [opts.signFn] - async (data: Uint8Array) => Uint8Array
111
- * @param {Function} [opts.verifyFn] - async (pubKey, data, sig) => boolean
112
- * @param {Uint8Array} [opts.remotePubKey] - Remote peer's public key
198
+ * @param {Function} [opts.verifyFn] - async (fromPubKey, data, sig) => boolean
113
199
  * @param {number} [opts.maxHistory=1000] - Maximum messages to retain
114
200
  * @param {Function} [opts.autoResponder] - async (message) => string|null
115
201
  * @param {Function} [opts.onLog] - Logging callback
116
202
  */
117
- constructor({ session, signFn, verifyFn, remotePubKey, maxHistory, autoResponder, onLog }) {
118
- if (!session) {
119
- throw new Error('session is required')
203
+ constructor({ localPubKey, send, signFn, verifyFn, maxHistory, autoResponder, onLog }) {
204
+ if (!localPubKey || typeof localPubKey !== 'string') {
205
+ throw new Error('localPubKey is required and must be a non-empty string')
206
+ }
207
+ if (typeof send !== 'function') {
208
+ throw new Error('send is required and must be a function')
120
209
  }
121
210
 
122
- this.#session = session
211
+ this.#localPubKey = localPubKey
212
+ this.#send = send
123
213
  this.#signFn = signFn || null
124
214
  this.#verifyFn = verifyFn || null
125
- this.#remotePubKey = remotePubKey || null
126
215
  this.#maxHistory = maxHistory ?? 1000
127
216
  this.#autoResponder = autoResponder || null
128
217
  this.#onLog = onLog || (() => {})
129
-
130
- // Register handler on session for 'chat' service type
131
- this.#session.registerHandler('chat', (envelope) => this.#handleIncoming(envelope))
132
218
  }
133
219
 
220
+ /** @returns {string} */
221
+ get localPubKey() { return this.#localPubKey }
222
+
134
223
  // -- Sending --------------------------------------------------------------
135
224
 
136
225
  /**
137
- * Send a text message to the remote peer.
226
+ * Send a text message to a remote peer.
138
227
  *
139
228
  * Creates a ChatMessage envelope, optionally signs it, transmits via
140
- * the session, records in history, and emits 'message:sent'.
229
+ * `send()`, records in history, and emits 'message:sent'.
141
230
  *
231
+ * @param {string} toPubKey - Recipient's routing pubKey/podId
142
232
  * @param {string} text - Message text
143
233
  * @param {object} [opts] - Options
144
234
  * @param {boolean} [opts.isAutoResponse] - Mark as auto-response to prevent loops
145
235
  * @returns {Promise<object>} The sent ChatMessage
146
236
  */
147
- async sendMessage(text, opts) {
237
+ async sendMessage(toPubKey, text, opts) {
238
+ if (!toPubKey || typeof toPubKey !== 'string') {
239
+ throw new Error('sendMessage: toPubKey is required and must be a non-empty string')
240
+ }
241
+
148
242
  const message = {
149
243
  id: generateChatMessageId(),
150
- from: this.#session.localPodId,
151
- to: this.#session.remotePodId,
244
+ from: this.#localPubKey,
245
+ to: toPubKey,
152
246
  text,
153
247
  timestamp: Date.now(),
154
248
  }
@@ -173,8 +267,8 @@ export class PeerChat {
173
267
  }
174
268
  }
175
269
 
176
- // Send over session
177
- this.#session.send('chat', message)
270
+ // Send over the injected transport
271
+ await this.#send(toPubKey, message)
178
272
 
179
273
  // Add to history
180
274
  this.#addToHistory(message)
@@ -188,31 +282,41 @@ export class PeerChat {
188
282
  // -- Typing indicators ----------------------------------------------------
189
283
 
190
284
  /**
191
- * Send a typing indicator to the remote peer.
285
+ * Send a typing indicator to a remote peer.
286
+ *
287
+ * @param {string} toPubKey - Recipient's routing pubKey/podId
192
288
  */
193
- sendTyping() {
194
- this.#session.send('chat', {
195
- type: 'typing',
196
- from: this.#session.localPodId,
289
+ async sendTyping(toPubKey) {
290
+ if (!toPubKey || typeof toPubKey !== 'string') {
291
+ throw new Error('sendTyping: toPubKey is required and must be a non-empty string')
292
+ }
293
+ await this.#send(toPubKey, {
294
+ kind: 'typing',
295
+ from: this.#localPubKey,
197
296
  })
198
297
  }
199
298
 
200
- // -- Incoming handler (private) -------------------------------------------
299
+ // -- Incoming handler -------------------------------------------------------
201
300
 
202
301
  /**
203
- * Handle an incoming chat message from the session transport.
302
+ * Handle an incoming chat envelope from the transport.
204
303
  *
205
304
  * Verifies signature if verification is available, adds to history,
206
305
  * emits the appropriate event, and triggers auto-response if configured.
306
+ * Replaces the old private, session-driven `#handleIncoming(envelope)` --
307
+ * public now because routing is external (`createChatService()`'s
308
+ * `ctx.onIncomingData()` subscription calls this directly, there is no
309
+ * more `session.registerHandler()` to do it implicitly).
207
310
  *
208
- * @param {object} envelope - Session envelope with payload
311
+ * @param {string} fromPubKey - Sender's routing pubKey/podId
312
+ * @param {object} envelope - Chat payload (message or typing indicator)
209
313
  */
210
- async #handleIncoming(envelope) {
211
- const payload = envelope.payload || envelope
314
+ async receiveEnvelope(fromPubKey, envelope) {
315
+ const payload = envelope || {}
212
316
 
213
317
  // Handle typing indicators
214
- if (payload.type === 'typing') {
215
- this.#emit('typing', { from: payload.from })
318
+ if (payload.kind === 'typing') {
319
+ this.#emit('typing', { from: payload.from || fromPubKey })
216
320
  return
217
321
  }
218
322
 
@@ -225,15 +329,17 @@ export class PeerChat {
225
329
  // Build chat message from payload
226
330
  const message = {
227
331
  id: payload.id || generateChatMessageId(),
228
- from: payload.from || 'unknown',
229
- to: payload.to || this.#session.localPodId,
332
+ from: payload.from || fromPubKey,
333
+ to: payload.to || this.#localPubKey,
230
334
  text: payload.text,
231
335
  timestamp: typeof payload.timestamp === 'number' ? payload.timestamp : Date.now(),
232
336
  signature: payload.signature || undefined,
233
337
  }
234
338
 
235
- // Verify signature if verify function and remote public key are available
236
- if (this.#verifyFn && this.#remotePubKey && message.signature) {
339
+ // Verify signature if verify function is available. Keyed off the
340
+ // ACTUAL sender (fromPubKey), not a fixed constructor-time key -- see
341
+ // module doc comment's point 2.
342
+ if (this.#verifyFn && message.signature) {
237
343
  try {
238
344
  const data = new TextEncoder().encode(JSON.stringify({
239
345
  id: message.id,
@@ -243,12 +349,12 @@ export class PeerChat {
243
349
  timestamp: message.timestamp,
244
350
  }))
245
351
  const sigBytes = base64ToBytes(message.signature)
246
- message.verified = await this.#verifyFn(this.#remotePubKey, data, sigBytes)
352
+ message.verified = await this.#verifyFn(fromPubKey, data, sigBytes)
247
353
  } catch (err) {
248
354
  this.#onLog(1, `Signature verification failed: ${err.message}`)
249
355
  message.verified = false
250
356
  }
251
- } else if (this.#verifyFn && this.#remotePubKey && !message.signature) {
357
+ } else if (this.#verifyFn && !message.signature) {
252
358
  // Expected a signature but none was provided
253
359
  message.verified = false
254
360
  }
@@ -264,7 +370,7 @@ export class PeerChat {
264
370
  try {
265
371
  const reply = await this.#autoResponder(message)
266
372
  if (reply && typeof reply === 'string') {
267
- await this.sendMessage(reply, { isAutoResponse: true })
373
+ await this.sendMessage(fromPubKey, reply, { isAutoResponse: true })
268
374
  }
269
375
  } catch (err) {
270
376
  this.#onLog(0, `Auto-responder error: ${err.message}`)
@@ -350,10 +456,12 @@ export class PeerChat {
350
456
  // -- Cleanup --------------------------------------------------------------
351
457
 
352
458
  /**
353
- * Close the peer chat. Removes the handler from the session.
459
+ * Close the peer chat. Clears listeners. Unlike the old `PeerSession`-bound
460
+ * version, there is no handler to remove from a session -- routing
461
+ * ownership (subscribing/unsubscribing from `ctx.onIncomingData()`) lives
462
+ * in `createChatService()`, which calls this from its own `teardown()`.
354
463
  */
355
464
  close() {
356
- this.#session.removeHandler('chat')
357
465
  this.#listeners.clear()
358
466
  }
359
467
 
@@ -366,16 +474,77 @@ export class PeerChat {
366
474
  */
367
475
  toJSON() {
368
476
  return {
369
- sessionId: this.#session.sessionId,
370
- localPodId: this.#session.localPodId,
371
- remotePodId: this.#session.remotePodId,
477
+ localPubKey: this.#localPubKey,
372
478
  messageCount: this.#messageHistory.length,
373
479
  maxHistory: this.#maxHistory,
374
480
  hasSignFn: !!this.#signFn,
375
481
  hasVerifyFn: !!this.#verifyFn,
376
- hasRemotePubKey: !!this.#remotePubKey,
377
482
  hasAutoResponder: !!this.#autoResponder,
378
483
  messages: this.#messageHistory.map(m => ({ ...m })),
379
484
  }
380
485
  }
381
486
  }
487
+
488
+ // ---------------------------------------------------------------------------
489
+ // createChatService -- the MeshService wrapper
490
+ // ---------------------------------------------------------------------------
491
+
492
+ /**
493
+ * Build a `MeshService` descriptor (`mesh-service.mjs`, Phase C) wrapping
494
+ * `PeerChat`. See this file's module doc comment for the full design
495
+ * writeup (multi-peer generalization, per-message sender-keyed
496
+ * verification, the `type`/`kind` collision this avoids).
497
+ *
498
+ * @param {object} [opts]
499
+ * @param {Function} [opts.signFn] - async (data: Uint8Array) => Uint8Array.
500
+ * Passed straight through to `PeerChat`; omit to send unsigned messages.
501
+ * @param {Function} [opts.verifyFn] - async (fromPubKey, data, sig) => boolean.
502
+ * Passed straight through to `PeerChat`; called with each message's real
503
+ * sender, not a fixed key -- see module doc comment's point 2.
504
+ * @param {number} [opts.maxHistory=1000]
505
+ * @param {Function} [opts.autoResponder] - async (message) => string|null
506
+ * @param {Function} [opts.onLog]
507
+ * @returns {import('./mesh-service.mjs').MeshService}
508
+ */
509
+ export function createChatService({ signFn, verifyFn, maxHistory, autoResponder, onLog } = {}) {
510
+ return {
511
+ name: 'chat',
512
+
513
+ attach(peerNode, ctx) {
514
+ const chat = new PeerChat({
515
+ localPubKey: peerNode.podId,
516
+ send: (toPubKey, payload) => ctx.sendTo(toPubKey, 'chat', payload),
517
+ signFn,
518
+ verifyFn,
519
+ maxHistory,
520
+ autoResponder,
521
+ onLog,
522
+ })
523
+
524
+ // Bridge PeerChat's own on/off events through ctx.emit() -- additive,
525
+ // not a replacement: chat.on()/chat.off() still work for anyone
526
+ // holding the PeerChat instance directly (e.g. a test).
527
+ chat.on('message:sent', (message) => ctx.emit('chat:message-sent', message))
528
+ chat.on('message:received', (message) => ctx.emit('chat:message-received', message))
529
+ chat.on('typing', (data) => ctx.emit('chat:typing', data))
530
+
531
+ const unsubscribe = ctx.onIncomingData('chat', (fromPubKey, envelope) =>
532
+ chat.receiveEnvelope(fromPubKey, envelope))
533
+
534
+ const api = {
535
+ sendMessage: (toPubKey, text, sendOpts) => chat.sendMessage(toPubKey, text, sendOpts),
536
+ sendTyping: (toPubKey) => chat.sendTyping(toPubKey),
537
+ getHistory: () => chat.getHistory(),
538
+ clearHistory: () => chat.clearHistory(),
539
+ }
540
+
541
+ return {
542
+ api,
543
+ teardown() {
544
+ unsubscribe()
545
+ chat.close()
546
+ },
547
+ }
548
+ },
549
+ }
550
+ }
@@ -1,11 +1,20 @@
1
1
  /**
2
- // STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
3
2
  * clawser-peer-compute.js — Federated compute orchestration.
4
3
  *
5
4
  * Split large compute jobs across multiple peers (map/reduce pattern).
6
5
  * Combines scheduling, verification, escrow, and result merging.
7
6
  * Enables "nomadic supercomputer" and "compute marketplace" scenarios.
8
7
  *
8
+ * `FederatedCompute` itself is plain and dependency-injected (`{scheduler,
9
+ * onLog}`), with no `PeerNode`/mesh-transport awareness of its own -- see
10
+ * `mesh-compute.mjs`'s `createComputeService()` (issue #118,
11
+ * `mesh-service.mjs`'s `MeshService` convention) for the wrapper that wires
12
+ * it onto a real `PeerNode`'s `ctx.sendTo()`/`ctx.onIncomingData()`/
13
+ * `ctx.registry.checkAccess()`, plus the required-but-not-provided
14
+ * `executeFn` an operator must supply for this node to actually run a
15
+ * remote peer's compute chunks (see that file's header for the full design,
16
+ * settled by issue #86's resolved design pass).
17
+ *
9
18
  * Run tests:
10
19
  * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-compute.test.mjs
11
20
  */
@@ -313,6 +322,21 @@ export class FederatedCompute {
313
322
  /** @type {Map<string, Function[]>} */
314
323
  #listeners = new Map()
315
324
 
325
+ /**
326
+ * Set once `destroy()` has been called. Checked at the top of every
327
+ * `#dispatchChunk()` retry attempt (see that method) so that no NEW
328
+ * `scheduler.dispatch()` call -- and therefore no new timer/resource a
329
+ * caller-supplied scheduler may allocate per dispatch (e.g.
330
+ * `mesh-compute.mjs`'s per-request `setTimeout`) -- is ever issued once
331
+ * this instance has been destroyed. `destroy()` cannot itself cancel an
332
+ * *already in-flight* `scheduler.dispatch()` promise -- that promise is
333
+ * entirely the scheduler's own to settle (or for a caller who owns that
334
+ * scheduler, such as `mesh-compute.mjs`'s `teardown()`, to reject
335
+ * directly) -- it only guarantees no further ones start.
336
+ * @type {boolean}
337
+ */
338
+ #destroyed = false
339
+
316
340
  /**
317
341
  * @param {object} opts
318
342
  * @param {object} opts.scheduler - Must have dispatch(peerId, job) and listAvailablePeers()
@@ -491,6 +515,34 @@ export class FederatedCompute {
491
515
  return true
492
516
  }
493
517
 
518
+ // ── Destroy ────────────────────────────────────────────────────
519
+
520
+ /**
521
+ * Permanently stop this instance's background dispatch activity.
522
+ *
523
+ * Unlike `cancel(jobId)` (which only marks a single job's bookkeeping),
524
+ * `destroy()` sets an instance-wide flag that `#dispatchChunk()`'s retry
525
+ * loop checks before every attempt (including the very first one for a
526
+ * chunk that hasn't dispatched yet, e.g. a not-yet-reached pipeline
527
+ * stage): once destroyed, no chunk of any job -- in-flight or still
528
+ * queued -- will trigger another `scheduler.dispatch()` call. Any attempt
529
+ * already awaiting `scheduler.dispatch()` when `destroy()` is called
530
+ * keeps awaiting that specific promise (this class has no way to abort a
531
+ * promise it doesn't own); once it settles -- either normally, or via a
532
+ * caller who owns/wraps the scheduler forcing it to reject (e.g.
533
+ * `mesh-compute.mjs`'s `teardown()`, which rejects its own
534
+ * `pendingDispatches`) -- the retry loop sees `#destroyed` and stops
535
+ * instead of dispatching again, so no new timer/resource the scheduler
536
+ * allocates per call is ever created after this returns.
537
+ *
538
+ * Idempotent. Safe to call with no jobs outstanding.
539
+ */
540
+ destroy() {
541
+ if (this.#destroyed) return
542
+ this.#destroyed = true
543
+ this.#onLog('info', 'FederatedCompute destroyed -- no further dispatch attempts will be issued')
544
+ }
545
+
494
546
  // ── Queries ────────────────────────────────────────────────────
495
547
 
496
548
  /**
@@ -635,6 +687,17 @@ export class FederatedCompute {
635
687
  let lastError = null
636
688
 
637
689
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
690
+ // Checked before EVERY attempt (first try and every retry) -- see
691
+ // #destroyed's own doc comment. This is the fix for issue #136: stop
692
+ // issuing new scheduler.dispatch() calls (and therefore new
693
+ // per-dispatch resources a scheduler may allocate, e.g.
694
+ // mesh-compute.mjs's per-request setTimeout) once destroy() has been
695
+ // called, instead of retrying blindly until maxRetries is exhausted.
696
+ if (this.#destroyed) {
697
+ lastError = lastError ?? new Error('FederatedCompute destroyed')
698
+ break
699
+ }
700
+
638
701
  chunk.attempts = attempt + 1
639
702
  chunk.status = 'running'
640
703
 
@@ -655,7 +718,7 @@ export class FederatedCompute {
655
718
  lastError = err
656
719
  this.#onLog('warn', `Chunk ${chunk.id} attempt ${attempt + 1} failed: ${err.message}`)
657
720
 
658
- if (attempt < maxRetries) {
721
+ if (attempt < maxRetries && !this.#destroyed) {
659
722
  // Retry on a different peer if available
660
723
  const currentIdx = peers.indexOf(chunk.assignee)
661
724
  const nextPeer = peers[(currentIdx + 1) % peers.length]
@@ -664,7 +727,7 @@ export class FederatedCompute {
664
727
  }
665
728
  }
666
729
 
667
- // All retries exhausted
730
+ // All retries exhausted (or destroyed mid-flight)
668
731
  chunk.status = 'failed'
669
732
  chunk.error = lastError?.message ?? 'unknown error'
670
733
  this.#emit('chunk-failed', { jobId: job.id, chunkId: chunk.id, error: chunk.error })