@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,569 @@
1
+ /**
2
+ // STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
3
+ * clawser-peer-agent-swarm.js — Multi-agent coordination protocol.
4
+ *
5
+ * Agents share goals, decompose tasks, divide work, merge results,
6
+ * and achieve collective objectives across the mesh.
7
+ *
8
+ * Run tests:
9
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-agent-swarm.test.mjs
10
+ */
11
+
12
+ // ---------------------------------------------------------------------------
13
+ // UUID polyfill
14
+ // ---------------------------------------------------------------------------
15
+
16
+ if (!globalThis.crypto) globalThis.crypto = {}
17
+ if (!crypto.randomUUID) crypto.randomUUID = () => 'swarm-' + Math.random().toString(36).slice(2)
18
+
19
+ // ---------------------------------------------------------------------------
20
+ // Constants
21
+ // ---------------------------------------------------------------------------
22
+
23
+ export const SWARM_STRATEGIES = Object.freeze({
24
+ LEADER_DECOMPOSE: 'leader_decompose',
25
+ COLLECTIVE_VOTE: 'collective_vote',
26
+ ROUND_ROBIN: 'round_robin',
27
+ CAPABILITY_MATCH: 'capability_match',
28
+ })
29
+
30
+ export const SWARM_DEFAULTS = Object.freeze({
31
+ maxAgents: 10,
32
+ strategy: 'round_robin',
33
+ timeoutMs: 60000,
34
+ })
35
+
36
+ // ---------------------------------------------------------------------------
37
+ // SubTask
38
+ // ---------------------------------------------------------------------------
39
+
40
+ /**
41
+ * Represents a single unit of work within a swarm's goal.
42
+ */
43
+ export class SubTask {
44
+ /** @type {string} */
45
+ id
46
+
47
+ /** @type {string} */
48
+ description
49
+
50
+ /** @type {string|null} */
51
+ assignee
52
+
53
+ /** @type {string[]} subtask ids that must complete first */
54
+ dependencies
55
+
56
+ /** @type {'pending'|'assigned'|'running'|'completed'|'failed'} */
57
+ status
58
+
59
+ /** @type {string|null} result of execution */
60
+ result = null
61
+
62
+ /**
63
+ * @param {object} opts
64
+ * @param {string} opts.id
65
+ * @param {string} opts.description
66
+ * @param {string} [opts.assignee]
67
+ * @param {string[]} [opts.dependencies]
68
+ * @param {'pending'|'assigned'|'running'|'completed'|'failed'} [opts.status]
69
+ */
70
+ constructor({ id, description, assignee, dependencies, status }) {
71
+ this.id = id
72
+ this.description = description
73
+ this.assignee = assignee ?? null
74
+ this.dependencies = dependencies ?? []
75
+ this.status = status ?? 'pending'
76
+ }
77
+
78
+ toJSON() {
79
+ return {
80
+ id: this.id,
81
+ description: this.description,
82
+ assignee: this.assignee,
83
+ dependencies: [...this.dependencies],
84
+ status: this.status,
85
+ result: this.result,
86
+ }
87
+ }
88
+
89
+ static fromJSON(json) {
90
+ const st = new SubTask({
91
+ id: json.id,
92
+ description: json.description,
93
+ assignee: json.assignee,
94
+ dependencies: json.dependencies,
95
+ status: json.status,
96
+ })
97
+ st.result = json.result ?? null
98
+ return st
99
+ }
100
+ }
101
+
102
+ // ---------------------------------------------------------------------------
103
+ // SwarmInstance
104
+ // ---------------------------------------------------------------------------
105
+
106
+ /**
107
+ * Represents a swarm — a group of agents working toward a shared goal.
108
+ */
109
+ export class SwarmInstance {
110
+ /** @type {string} */
111
+ id
112
+
113
+ /** @type {string} */
114
+ goal
115
+
116
+ /** @type {string} */
117
+ leader
118
+
119
+ /** @type {string[]} podIds */
120
+ members
121
+
122
+ /** @type {string} */
123
+ strategy
124
+
125
+ /** @type {'forming'|'active'|'executing'|'merging'|'completed'|'failed'|'disbanded'} */
126
+ status
127
+
128
+ /** @type {SubTask[]} */
129
+ subtasks = []
130
+
131
+ /** @type {number} */
132
+ timeoutMs
133
+
134
+ /**
135
+ * @param {object} opts
136
+ * @param {string} opts.id
137
+ * @param {string} opts.goal
138
+ * @param {string} opts.leader
139
+ * @param {string[]} [opts.members]
140
+ * @param {string} [opts.strategy]
141
+ * @param {string} [opts.status]
142
+ * @param {number} [opts.timeoutMs]
143
+ */
144
+ constructor({ id, goal, leader, members, strategy, status, timeoutMs }) {
145
+ this.id = id ?? crypto.randomUUID()
146
+ this.goal = goal
147
+ this.leader = leader
148
+ this.members = members ? [...members] : []
149
+ this.strategy = strategy ?? SWARM_STRATEGIES.ROUND_ROBIN
150
+ this.status = status ?? 'forming'
151
+ this.timeoutMs = timeoutMs ?? SWARM_DEFAULTS.timeoutMs
152
+ }
153
+
154
+ /**
155
+ * Add a member pod to this swarm.
156
+ * @param {string} podId
157
+ */
158
+ addMember(podId) {
159
+ if (!this.members.includes(podId)) {
160
+ this.members.push(podId)
161
+ }
162
+ }
163
+
164
+ /**
165
+ * Remove a member pod from this swarm.
166
+ * @param {string} podId
167
+ */
168
+ removeMember(podId) {
169
+ this.members = this.members.filter(m => m !== podId)
170
+ }
171
+
172
+ /**
173
+ * Set the list of subtasks for this swarm.
174
+ * @param {SubTask[]} subtasks
175
+ */
176
+ setSubTasks(subtasks) {
177
+ this.subtasks = subtasks
178
+ }
179
+
180
+ /**
181
+ * Get a subtask by id.
182
+ * @param {string} id
183
+ * @returns {SubTask|null}
184
+ */
185
+ getSubTask(id) {
186
+ return this.subtasks.find(st => st.id === id) ?? null
187
+ }
188
+
189
+ /**
190
+ * Update a subtask's status and/or assignee.
191
+ * @param {string} id
192
+ * @param {object} updates
193
+ * @param {string} [updates.status]
194
+ * @param {string} [updates.assignee]
195
+ */
196
+ updateSubTask(id, updates) {
197
+ const st = this.getSubTask(id)
198
+ if (!st) return
199
+ if (updates.status !== undefined) st.status = updates.status
200
+ if (updates.assignee !== undefined) st.assignee = updates.assignee
201
+ if (updates.result !== undefined) st.result = updates.result
202
+ }
203
+
204
+ /**
205
+ * Get progress statistics for this swarm.
206
+ * @returns {{ total: number, completed: number, failed: number, pct: number }}
207
+ */
208
+ getProgress() {
209
+ const total = this.subtasks.length
210
+ if (total === 0) return { total: 0, completed: 0, failed: 0, pct: 0 }
211
+ const completed = this.subtasks.filter(st => st.status === 'completed').length
212
+ const failed = this.subtasks.filter(st => st.status === 'failed').length
213
+ const pct = Math.round((completed / total) * 100)
214
+ return { total, completed, failed, pct }
215
+ }
216
+
217
+ toJSON() {
218
+ return {
219
+ id: this.id,
220
+ goal: this.goal,
221
+ leader: this.leader,
222
+ members: [...this.members],
223
+ strategy: this.strategy,
224
+ status: this.status,
225
+ timeoutMs: this.timeoutMs,
226
+ subtasks: this.subtasks.map(st => st.toJSON()),
227
+ }
228
+ }
229
+
230
+ static fromJSON(json) {
231
+ const sw = new SwarmInstance({
232
+ id: json.id,
233
+ goal: json.goal,
234
+ leader: json.leader,
235
+ members: json.members,
236
+ strategy: json.strategy,
237
+ status: json.status,
238
+ timeoutMs: json.timeoutMs,
239
+ })
240
+ sw.subtasks = (json.subtasks || []).map(st => SubTask.fromJSON(st))
241
+ return sw
242
+ }
243
+ }
244
+
245
+ // ---------------------------------------------------------------------------
246
+ // AgentSwarmCoordinator
247
+ // ---------------------------------------------------------------------------
248
+
249
+ /**
250
+ * Coordinates multi-agent swarms — creation, task decomposition, assignment,
251
+ * execution, and result collection.
252
+ */
253
+ export class AgentSwarmCoordinator {
254
+ /** @type {object} { async chat(podId, message) => string } */
255
+ #agentProxy
256
+
257
+ /** @type {Function} */
258
+ #onLog
259
+
260
+ /** @type {Map<string, SwarmInstance>} */
261
+ #swarms = new Map()
262
+
263
+ /** @type {Map<string, Set<Function>>} */
264
+ #listeners = new Map()
265
+
266
+ /**
267
+ * @param {object} opts
268
+ * @param {object} opts.agentProxy - { async chat(podId, message) => string }
269
+ * @param {Function} [opts.onLog] - (level, msg) => void
270
+ */
271
+ constructor({ agentProxy, onLog }) {
272
+ if (!agentProxy) throw new Error('agentProxy is required')
273
+ this.#agentProxy = agentProxy
274
+ this.#onLog = onLog || (() => {})
275
+ }
276
+
277
+ // -- Swarm lifecycle -------------------------------------------------------
278
+
279
+ /**
280
+ * Create a new swarm with a shared goal.
281
+ *
282
+ * @param {string} goal
283
+ * @param {object} [opts]
284
+ * @param {string[]} [opts.members]
285
+ * @param {number} [opts.maxAgents]
286
+ * @param {string} [opts.strategy]
287
+ * @param {number} [opts.timeoutMs]
288
+ * @param {Function} [opts.decomposer] - async (goal) => string[]
289
+ * @returns {Promise<SwarmInstance>}
290
+ */
291
+ async createSwarm(goal, opts = {}) {
292
+ const members = (opts.members || []).slice(0, opts.maxAgents ?? SWARM_DEFAULTS.maxAgents)
293
+ const leader = members[0] || 'local'
294
+ const strategy = opts.strategy ?? SWARM_DEFAULTS.strategy
295
+ const timeoutMs = opts.timeoutMs ?? SWARM_DEFAULTS.timeoutMs
296
+
297
+ const swarm = new SwarmInstance({
298
+ id: crypto.randomUUID(),
299
+ goal,
300
+ leader,
301
+ members,
302
+ strategy,
303
+ status: 'active',
304
+ timeoutMs,
305
+ })
306
+
307
+ this.#swarms.set(swarm.id, swarm)
308
+ this.#log('info', `Swarm ${swarm.id} created for goal: ${goal}`)
309
+ this.#emit('created', { swarmId: swarm.id, goal, leader })
310
+
311
+ // Auto-decompose if a decomposer is provided
312
+ if (opts.decomposer) {
313
+ await this.decompose(swarm.id, opts.decomposer)
314
+ }
315
+
316
+ return swarm
317
+ }
318
+
319
+ /**
320
+ * Decompose a swarm's goal into subtasks.
321
+ *
322
+ * @param {string} swarmId
323
+ * @param {Function} [decomposer] - async (goal) => string[]
324
+ * @returns {Promise<SubTask[]>}
325
+ */
326
+ async decompose(swarmId, decomposer) {
327
+ const swarm = this.#swarms.get(swarmId)
328
+ if (!swarm) throw new Error(`Swarm ${swarmId} not found`)
329
+
330
+ let descriptions
331
+ if (typeof decomposer === 'function') {
332
+ descriptions = await decomposer(swarm.goal)
333
+ } else {
334
+ // Default: single subtask with the full goal
335
+ descriptions = [swarm.goal]
336
+ }
337
+
338
+ const subtasks = descriptions.map((desc, i) =>
339
+ new SubTask({
340
+ id: `${swarmId}-st-${i}`,
341
+ description: desc,
342
+ })
343
+ )
344
+
345
+ swarm.setSubTasks(subtasks)
346
+ this.#log('info', `Decomposed swarm ${swarmId} into ${subtasks.length} subtasks`)
347
+ return subtasks
348
+ }
349
+
350
+ /**
351
+ * Assign subtasks to swarm members based on the swarm's strategy.
352
+ *
353
+ * @param {string} swarmId
354
+ * @returns {Promise<Array<{ subtaskId: string, assignee: string }>>}
355
+ */
356
+ async assign(swarmId) {
357
+ const swarm = this.#swarms.get(swarmId)
358
+ if (!swarm) throw new Error(`Swarm ${swarmId} not found`)
359
+
360
+ const assignments = []
361
+ const { subtasks, members, leader, strategy } = swarm
362
+
363
+ if (members.length === 0) {
364
+ this.#log('warn', `Swarm ${swarmId} has no members to assign tasks to`)
365
+ return assignments
366
+ }
367
+
368
+ for (let i = 0; i < subtasks.length; i++) {
369
+ const st = subtasks[i]
370
+ let assignee
371
+
372
+ switch (strategy) {
373
+ case SWARM_STRATEGIES.LEADER_DECOMPOSE:
374
+ assignee = leader
375
+ break
376
+
377
+ case SWARM_STRATEGIES.CAPABILITY_MATCH:
378
+ // Simple keyword matching: pick member whose podId partially matches description
379
+ assignee = members.find(m =>
380
+ st.description.toLowerCase().includes(m.toLowerCase())
381
+ ) || members[i % members.length]
382
+ break
383
+
384
+ case SWARM_STRATEGIES.COLLECTIVE_VOTE:
385
+ // Assign to first available member
386
+ assignee = members[0]
387
+ break
388
+
389
+ case SWARM_STRATEGIES.ROUND_ROBIN:
390
+ default:
391
+ assignee = members[i % members.length]
392
+ break
393
+ }
394
+
395
+ st.assignee = assignee
396
+ st.status = 'assigned'
397
+ assignments.push({ subtaskId: st.id, assignee })
398
+ this.#emit('task-assigned', { swarmId, subtaskId: st.id, assignee })
399
+ }
400
+
401
+ swarm.status = 'executing'
402
+ this.#log('info', `Assigned ${assignments.length} subtasks in swarm ${swarmId}`)
403
+ return assignments
404
+ }
405
+
406
+ /**
407
+ * Execute a single subtask by delegating to the assigned agent.
408
+ *
409
+ * @param {string} swarmId
410
+ * @param {string} subtaskId
411
+ * @param {string} assignee
412
+ * @returns {Promise<{ result: string, success: boolean, error?: string }>}
413
+ */
414
+ async executeSubTask(swarmId, subtaskId, assignee) {
415
+ const swarm = this.#swarms.get(swarmId)
416
+ if (!swarm) throw new Error(`Swarm ${swarmId} not found`)
417
+
418
+ const st = swarm.getSubTask(subtaskId)
419
+ if (!st) throw new Error(`SubTask ${subtaskId} not found`)
420
+
421
+ st.status = 'running'
422
+
423
+ try {
424
+ const result = await this.#withTimeout(
425
+ this.#agentProxy.chat(assignee, st.description),
426
+ swarm.timeoutMs
427
+ )
428
+ st.status = 'completed'
429
+ st.result = result
430
+ this.#log('info', `SubTask ${subtaskId} completed by ${assignee}`)
431
+ this.#emit('subtask-complete', { swarmId, subtaskId, assignee, result })
432
+ return { result, success: true }
433
+ } catch (err) {
434
+ st.status = 'failed'
435
+ const errorMsg = err.message || String(err)
436
+ this.#log('error', `SubTask ${subtaskId} failed: ${errorMsg}`)
437
+ return { result: null, success: false, error: errorMsg }
438
+ }
439
+ }
440
+
441
+ /**
442
+ * Collect and merge results from all completed subtasks.
443
+ *
444
+ * @param {string} swarmId
445
+ * @param {Function} [mergeFn] - (results: string[]) => string
446
+ * @returns {Promise<{ merged: string, individual: Array<{ subtaskId: string, result: string }> }>}
447
+ */
448
+ async collectResults(swarmId, mergeFn) {
449
+ const swarm = this.#swarms.get(swarmId)
450
+ if (!swarm) throw new Error(`Swarm ${swarmId} not found`)
451
+
452
+ const individual = swarm.subtasks
453
+ .filter(st => st.status === 'completed' && st.result !== null)
454
+ .map(st => ({ subtaskId: st.id, result: st.result }))
455
+
456
+ const results = individual.map(r => r.result)
457
+ const merged = typeof mergeFn === 'function'
458
+ ? mergeFn(results)
459
+ : results.join('\n\n')
460
+
461
+ swarm.status = 'completed'
462
+ this.#log('info', `Swarm ${swarmId} completed with ${individual.length} results`)
463
+ this.#emit('completed', { swarmId, merged, individual })
464
+
465
+ return { merged, individual }
466
+ }
467
+
468
+ // -- Queries ---------------------------------------------------------------
469
+
470
+ /**
471
+ * Get a swarm by id.
472
+ * @param {string} id
473
+ * @returns {SwarmInstance|null}
474
+ */
475
+ getSwarm(id) {
476
+ return this.#swarms.get(id) ?? null
477
+ }
478
+
479
+ /**
480
+ * List all swarms.
481
+ * @returns {SwarmInstance[]}
482
+ */
483
+ listSwarms() {
484
+ return [...this.#swarms.values()]
485
+ }
486
+
487
+ /**
488
+ * Disband a swarm.
489
+ * @param {string} swarmId
490
+ */
491
+ async disbandSwarm(swarmId) {
492
+ const swarm = this.#swarms.get(swarmId)
493
+ if (!swarm) throw new Error(`Swarm ${swarmId} not found`)
494
+ swarm.status = 'disbanded'
495
+ this.#log('info', `Swarm ${swarmId} disbanded`)
496
+ this.#emit('disbanded', { swarmId })
497
+ }
498
+
499
+ // -- Events ----------------------------------------------------------------
500
+
501
+ /**
502
+ * Register a listener for a swarm event.
503
+ *
504
+ * Events: created, joined, left, task-assigned, subtask-complete, completed, failed
505
+ *
506
+ * @param {string} event
507
+ * @param {Function} cb
508
+ */
509
+ on(event, cb) {
510
+ if (!this.#listeners.has(event)) {
511
+ this.#listeners.set(event, new Set())
512
+ }
513
+ this.#listeners.get(event).add(cb)
514
+ }
515
+
516
+ /**
517
+ * Remove a listener for a swarm event.
518
+ * @param {string} event
519
+ * @param {Function} cb
520
+ */
521
+ off(event, cb) {
522
+ const set = this.#listeners.get(event)
523
+ if (set) set.delete(cb)
524
+ }
525
+
526
+ // -- Internal --------------------------------------------------------------
527
+
528
+ /**
529
+ * Emit an event to all registered listeners.
530
+ * @param {string} event
531
+ * @param {*} data
532
+ */
533
+ #emit(event, data) {
534
+ const set = this.#listeners.get(event)
535
+ if (!set) return
536
+ for (const cb of [...set]) {
537
+ try {
538
+ cb(data)
539
+ } catch {
540
+ /* listener errors do not propagate */
541
+ }
542
+ }
543
+ }
544
+
545
+ /**
546
+ * Log a message via the onLog callback.
547
+ * @param {string} level
548
+ * @param {string} msg
549
+ */
550
+ #log(level, msg) {
551
+ this.#onLog(level, msg)
552
+ }
553
+
554
+ /**
555
+ * Race a promise against a timeout.
556
+ * @param {Promise} promise
557
+ * @param {number} ms
558
+ * @returns {Promise}
559
+ */
560
+ #withTimeout(promise, ms) {
561
+ return new Promise((resolve, reject) => {
562
+ const timer = setTimeout(() => reject(new Error('Timeout: subtask execution exceeded time limit')), ms)
563
+ promise.then(
564
+ (val) => { clearTimeout(timer); resolve(val) },
565
+ (err) => { clearTimeout(timer); reject(err) },
566
+ ).catch(() => {})
567
+ })
568
+ }
569
+ }