@johnhenry/browsermesh-core 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,959 @@
1
+ /**
2
+ * clawser-mesh-peer-tools.js — BrowserTool subclasses for mesh peer subsystems
3
+ *
4
+ * Exposes chat, compute, scheduling, health, escrow, routing, timestamp,
5
+ * stealth, delta-sync, gateway, torrent, IPFS, ACL, and capability tools
6
+ * to the AI agent.
7
+ *
8
+ * @module clawser-mesh-peer-tools
9
+ */
10
+
11
+ import { BrowserTool } from './compat.mjs'
12
+
13
+ // ── Shared context ────────────────────────────────────────────────────
14
+
15
+ export class MeshPeerToolsContext {
16
+ #meshChat = null
17
+ #meshScheduler = null
18
+ #federatedCompute = null
19
+ #agentSwarmCoordinator = null
20
+ #healthMonitor = null
21
+ #escrowManager = null
22
+ #meshRouter = null
23
+ #timestampAuthority = null
24
+ #stealthAgent = null
25
+ #syncCoordinator = null
26
+ #gatewayNode = null
27
+ #torrentManager = null
28
+ #ipfsStore = null
29
+ #meshACL = null
30
+ #capabilityValidator = null
31
+ #sessionManager = null
32
+ #crossOriginBridge = null
33
+ #verificationQuorum = null
34
+ #migrationEngine = null
35
+ #creditLedger = null
36
+
37
+ set(key, value) { this[`#${key}`] = value }
38
+
39
+ setMeshChat(v) { this.#meshChat = v }
40
+ getMeshChat() { return this.#meshChat }
41
+ setMeshScheduler(v) { this.#meshScheduler = v }
42
+ getMeshScheduler() { return this.#meshScheduler }
43
+ setFederatedCompute(v) { this.#federatedCompute = v }
44
+ getFederatedCompute() { return this.#federatedCompute }
45
+ setAgentSwarmCoordinator(v) { this.#agentSwarmCoordinator = v }
46
+ getAgentSwarmCoordinator() { return this.#agentSwarmCoordinator }
47
+ setHealthMonitor(v) { this.#healthMonitor = v }
48
+ getHealthMonitor() { return this.#healthMonitor }
49
+ setEscrowManager(v) { this.#escrowManager = v }
50
+ getEscrowManager() { return this.#escrowManager }
51
+ setMeshRouter(v) { this.#meshRouter = v }
52
+ getMeshRouter() { return this.#meshRouter }
53
+ setTimestampAuthority(v) { this.#timestampAuthority = v }
54
+ getTimestampAuthority() { return this.#timestampAuthority }
55
+ setStealthAgent(v) { this.#stealthAgent = v }
56
+ getStealthAgent() { return this.#stealthAgent }
57
+ setSyncCoordinator(v) { this.#syncCoordinator = v }
58
+ getSyncCoordinator() { return this.#syncCoordinator }
59
+ setGatewayNode(v) { this.#gatewayNode = v }
60
+ getGatewayNode() { return this.#gatewayNode }
61
+ setTorrentManager(v) { this.#torrentManager = v }
62
+ getTorrentManager() { return this.#torrentManager }
63
+ setIpfsStore(v) { this.#ipfsStore = v }
64
+ getIpfsStore() { return this.#ipfsStore }
65
+ setMeshACL(v) { this.#meshACL = v }
66
+ getMeshACL() { return this.#meshACL }
67
+ setCapabilityValidator(v) { this.#capabilityValidator = v }
68
+ getCapabilityValidator() { return this.#capabilityValidator }
69
+ setSessionManager(v) { this.#sessionManager = v }
70
+ getSessionManager() { return this.#sessionManager }
71
+ setCrossOriginBridge(v) { this.#crossOriginBridge = v }
72
+ getCrossOriginBridge() { return this.#crossOriginBridge }
73
+ setVerificationQuorum(v) { this.#verificationQuorum = v }
74
+ getVerificationQuorum() { return this.#verificationQuorum }
75
+ setMigrationEngine(v) { this.#migrationEngine = v }
76
+ getMigrationEngine() { return this.#migrationEngine }
77
+ setCreditLedger(v) { this.#creditLedger = v }
78
+ getCreditLedger() { return this.#creditLedger }
79
+ }
80
+
81
+ export const peerToolsContext = new MeshPeerToolsContext()
82
+
83
+ // ── Chat tools ────────────────────────────────────────────────────────
84
+
85
+ export class MeshChatCreateRoomTool extends BrowserTool {
86
+ get name() { return 'mesh_chat_create_room' }
87
+ get description() { return 'Create a new mesh chat room.' }
88
+ get parameters() {
89
+ return {
90
+ type: 'object',
91
+ properties: {
92
+ name: { type: 'string', description: 'Room name' },
93
+ maxMembers: { type: 'number', description: 'Maximum members (default: 256)' },
94
+ },
95
+ required: ['name'],
96
+ }
97
+ }
98
+ get permission() { return 'write' }
99
+
100
+ async execute({ name, maxMembers }) {
101
+ const chat = peerToolsContext.getMeshChat()
102
+ if (!chat) return { success: false, output: '', error: 'Mesh chat not initialized.' }
103
+ try {
104
+ const room = chat.createRoom({ name, opts: maxMembers ? { maxMembers } : undefined })
105
+ return { success: true, output: `Room created: ${room.id} (${room.name})` }
106
+ } catch (err) {
107
+ return { success: false, output: '', error: err.message }
108
+ }
109
+ }
110
+ }
111
+
112
+ export class MeshChatSendTool extends BrowserTool {
113
+ get name() { return 'mesh_chat_send' }
114
+ get description() { return 'Send a message to a mesh chat room.' }
115
+ get parameters() {
116
+ return {
117
+ type: 'object',
118
+ properties: {
119
+ roomId: { type: 'string', description: 'Target room ID' },
120
+ body: { type: 'string', description: 'Message body' },
121
+ type: { type: 'string', description: 'Message type (default: text)' },
122
+ },
123
+ required: ['roomId', 'body'],
124
+ }
125
+ }
126
+ get permission() { return 'write' }
127
+
128
+ async execute({ roomId, body, type }) {
129
+ const chat = peerToolsContext.getMeshChat()
130
+ if (!chat) return { success: false, output: '', error: 'Mesh chat not initialized.' }
131
+ try {
132
+ const msg = chat.sendMessage({ roomId, body, type: type || 'text' })
133
+ return { success: true, output: `Message sent: ${msg.id} to room ${roomId}` }
134
+ } catch (err) {
135
+ return { success: false, output: '', error: err.message }
136
+ }
137
+ }
138
+ }
139
+
140
+ export class MeshChatHistoryTool extends BrowserTool {
141
+ get name() { return 'mesh_chat_history' }
142
+ get description() { return 'Get message history from a mesh chat room.' }
143
+ get parameters() {
144
+ return {
145
+ type: 'object',
146
+ properties: {
147
+ roomId: { type: 'string', description: 'Room ID' },
148
+ limit: { type: 'number', description: 'Max messages to return (default: 20)' },
149
+ },
150
+ required: ['roomId'],
151
+ }
152
+ }
153
+ get permission() { return 'read' }
154
+
155
+ async execute({ roomId, limit }) {
156
+ const chat = peerToolsContext.getMeshChat()
157
+ if (!chat) return { success: false, output: '', error: 'Mesh chat not initialized.' }
158
+ try {
159
+ const messages = chat.getHistory(roomId, limit || 20)
160
+ if (!messages || messages.length === 0) return { success: true, output: 'No messages.' }
161
+ const lines = messages.map(m => `[${m.sender}] ${m.body}`)
162
+ return { success: true, output: lines.join('\n') }
163
+ } catch (err) {
164
+ return { success: false, output: '', error: err.message }
165
+ }
166
+ }
167
+ }
168
+
169
+ export class MeshChatListRoomsTool extends BrowserTool {
170
+ get name() { return 'mesh_chat_list_rooms' }
171
+ get description() { return 'List all mesh chat rooms.' }
172
+ get parameters() { return { type: 'object', properties: {} } }
173
+ get permission() { return 'read' }
174
+
175
+ async execute() {
176
+ const chat = peerToolsContext.getMeshChat()
177
+ if (!chat) return { success: true, output: 'Mesh chat not initialized.' }
178
+ try {
179
+ const rooms = chat.listRooms()
180
+ if (!rooms || rooms.length === 0) return { success: true, output: 'No rooms.' }
181
+ const lines = rooms.map(r => `${r.id} | ${r.name} | ${r.memberCount ?? '?'} members`)
182
+ return { success: true, output: `ID | NAME | MEMBERS\n${lines.join('\n')}` }
183
+ } catch (err) {
184
+ return { success: false, output: '', error: err.message }
185
+ }
186
+ }
187
+ }
188
+
189
+ // ── Scheduler tools ───────────────────────────────────────────────────
190
+
191
+ export class MeshSchedulerSubmitTool extends BrowserTool {
192
+ get name() { return 'mesh_scheduler_submit' }
193
+ get description() { return 'Submit a task to the mesh scheduler for distributed execution.' }
194
+ get parameters() {
195
+ return {
196
+ type: 'object',
197
+ properties: {
198
+ type: { type: 'string', description: 'Task type (e.g., compute, io, transfer)' },
199
+ payload: { type: 'object', description: 'Task payload data' },
200
+ priority: { type: 'string', description: 'Priority: low, normal, high, critical (default: normal)' },
201
+ },
202
+ required: ['type', 'payload'],
203
+ }
204
+ }
205
+ get permission() { return 'approve' }
206
+
207
+ async execute({ type, payload, priority }) {
208
+ const sched = peerToolsContext.getMeshScheduler()
209
+ if (!sched) return { success: false, output: '', error: 'Mesh scheduler not initialized.' }
210
+ try {
211
+ // ScheduledTask lives in the sibling browsermesh-apps package, which
212
+ // itself depends on browsermesh-core (peerDependency) — core can't
213
+ // depend back on apps without a cycle, so this reaches across via a
214
+ // relative path that only resolves inside this monorepo, pre-existing
215
+ // from before this package was re-extracted. Contained by the
216
+ // surrounding try/catch: if apps isn't present, this one tool fails
217
+ // gracefully rather than crashing the module.
218
+ const { ScheduledTask } = await import('../../browsermesh-apps/src/scheduler.mjs')
219
+ const task = new ScheduledTask({
220
+ id: crypto.randomUUID(),
221
+ type,
222
+ payload,
223
+ priority: priority || 'normal',
224
+ submittedBy: 'agent',
225
+ })
226
+ const id = await sched.submit(task)
227
+ return { success: true, output: `Task submitted: ${id}` }
228
+ } catch (err) {
229
+ return { success: false, output: '', error: err.message }
230
+ }
231
+ }
232
+ }
233
+
234
+ export class MeshSchedulerListTool extends BrowserTool {
235
+ get name() { return 'mesh_scheduler_list' }
236
+ get description() { return 'List tasks in the mesh scheduler.' }
237
+ get parameters() {
238
+ return {
239
+ type: 'object',
240
+ properties: {
241
+ status: { type: 'string', description: 'Filter by status (optional)' },
242
+ },
243
+ }
244
+ }
245
+ get permission() { return 'read' }
246
+
247
+ async execute({ status } = {}) {
248
+ const sched = peerToolsContext.getMeshScheduler()
249
+ if (!sched) return { success: true, output: 'Mesh scheduler not initialized.' }
250
+ try {
251
+ const tasks = sched.listTasks?.(status) || []
252
+ if (tasks.length === 0) return { success: true, output: 'No tasks.' }
253
+ const lines = tasks.map(t => `${t.id} | ${t.type} | ${t.status} | ${t.priority}`)
254
+ return { success: true, output: `ID | TYPE | STATUS | PRIORITY\n${lines.join('\n')}` }
255
+ } catch (err) {
256
+ return { success: false, output: '', error: err.message }
257
+ }
258
+ }
259
+ }
260
+
261
+ // ── Compute tools ─────────────────────────────────────────────────────
262
+
263
+ export class FederatedComputeSubmitTool extends BrowserTool {
264
+ get name() { return 'federated_compute_submit' }
265
+ get description() { return 'Submit a federated compute job across mesh peers.' }
266
+ get parameters() {
267
+ return {
268
+ type: 'object',
269
+ properties: {
270
+ type: { type: 'string', description: 'Compute type: map_reduce, pipeline, broadcast, scatter_gather' },
271
+ payload: { type: 'object', description: 'Job payload' },
272
+ },
273
+ required: ['payload'],
274
+ }
275
+ }
276
+ get permission() { return 'approve' }
277
+
278
+ async execute({ type, payload }) {
279
+ const fc = peerToolsContext.getFederatedCompute()
280
+ if (!fc) return { success: false, output: '', error: 'Federated compute not initialized.' }
281
+ try {
282
+ const job = await fc.submit({
283
+ type: type || 'scatter_gather',
284
+ payload,
285
+ splitFn: (p) => [p],
286
+ mergeFn: (results) => results[0],
287
+ })
288
+ return { success: true, output: `Job submitted: ${job.id || job}` }
289
+ } catch (err) {
290
+ return { success: false, output: '', error: err.message }
291
+ }
292
+ }
293
+ }
294
+
295
+ // ── Swarm tools ───────────────────────────────────────────────────────
296
+
297
+ export class SwarmCreateTool extends BrowserTool {
298
+ get name() { return 'agent_swarm_create' }
299
+ get description() { return 'Create a multi-agent swarm to collaboratively solve a goal.' }
300
+ get parameters() {
301
+ return {
302
+ type: 'object',
303
+ properties: {
304
+ goal: { type: 'string', description: 'The goal for the swarm' },
305
+ strategy: { type: 'string', description: 'Strategy: competitive, collaborative, hierarchical' },
306
+ members: { type: 'array', items: { type: 'string' }, description: 'Peer IDs to include' },
307
+ },
308
+ required: ['goal'],
309
+ }
310
+ }
311
+ get permission() { return 'approve' }
312
+
313
+ async execute({ goal, strategy, members }) {
314
+ const swarm = peerToolsContext.getAgentSwarmCoordinator()
315
+ if (!swarm) return { success: false, output: '', error: 'Agent swarm coordinator not initialized.' }
316
+ try {
317
+ const instance = swarm.createSwarm({ goal, strategy, members: members || [] })
318
+ return { success: true, output: `Swarm created: ${instance.id} (goal: ${goal})` }
319
+ } catch (err) {
320
+ return { success: false, output: '', error: err.message }
321
+ }
322
+ }
323
+ }
324
+
325
+ export class SwarmStatusTool extends BrowserTool {
326
+ get name() { return 'agent_swarm_status' }
327
+ get description() { return 'Get the status of an agent swarm.' }
328
+ get parameters() {
329
+ return {
330
+ type: 'object',
331
+ properties: {
332
+ swarmId: { type: 'string', description: 'Swarm ID' },
333
+ },
334
+ required: ['swarmId'],
335
+ }
336
+ }
337
+ get permission() { return 'read' }
338
+
339
+ async execute({ swarmId }) {
340
+ const swarm = peerToolsContext.getAgentSwarmCoordinator()
341
+ if (!swarm) return { success: false, output: '', error: 'Agent swarm coordinator not initialized.' }
342
+ try {
343
+ const status = swarm.getStatus(swarmId)
344
+ if (!status) return { success: false, output: '', error: `Swarm ${swarmId} not found.` }
345
+ return { success: true, output: JSON.stringify(status, null, 2) }
346
+ } catch (err) {
347
+ return { success: false, output: '', error: err.message }
348
+ }
349
+ }
350
+ }
351
+
352
+ // ── Health tools ──────────────────────────────────────────────────────
353
+
354
+ export class MeshHealthStatusTool extends BrowserTool {
355
+ get name() { return 'mesh_health_status' }
356
+ get description() { return 'Get health status of mesh peers.' }
357
+ get parameters() {
358
+ return {
359
+ type: 'object',
360
+ properties: {
361
+ podId: { type: 'string', description: 'Specific peer to check (optional, omit for all)' },
362
+ },
363
+ }
364
+ }
365
+ get permission() { return 'read' }
366
+
367
+ async execute({ podId } = {}) {
368
+ const monitor = peerToolsContext.getHealthMonitor()
369
+ if (!monitor) return { success: true, output: 'Health monitor not initialized.' }
370
+ try {
371
+ if (podId) {
372
+ const health = monitor.getHealth(podId)
373
+ if (!health) return { success: true, output: `No health data for ${podId}.` }
374
+ return { success: true, output: `${podId}: ${health.status} (latency: ${health.latencyMs}ms, uptime: ${health.uptimeMs}ms)` }
375
+ }
376
+ const all = monitor.getAllHealth?.() || []
377
+ if (all.length === 0) return { success: true, output: 'No peer health data.' }
378
+ const lines = all.map(h => `${h.podId} | ${h.status} | ${h.latencyMs}ms`)
379
+ return { success: true, output: `POD | STATUS | LATENCY\n${lines.join('\n')}` }
380
+ } catch (err) {
381
+ return { success: false, output: '', error: err.message }
382
+ }
383
+ }
384
+ }
385
+
386
+ // ── Escrow tools ──────────────────────────────────────────────────────
387
+
388
+ export class EscrowCreateTool extends BrowserTool {
389
+ get name() { return 'escrow_create' }
390
+ get description() { return 'Create an escrow contract holding funds until conditions are met.' }
391
+ get parameters() {
392
+ return {
393
+ type: 'object',
394
+ properties: {
395
+ payer: { type: 'string', description: 'Payer pod ID' },
396
+ payee: { type: 'string', description: 'Payee pod ID' },
397
+ amount: { type: 'number', description: 'Amount to escrow' },
398
+ description: { type: 'string', description: 'Contract description' },
399
+ conditions: { type: 'array', items: { type: 'object' }, description: 'Release conditions' },
400
+ },
401
+ required: ['payer', 'payee', 'amount'],
402
+ }
403
+ }
404
+ get permission() { return 'approve' }
405
+
406
+ async execute({ payer, payee, amount, description, conditions }) {
407
+ const mgr = peerToolsContext.getEscrowManager()
408
+ if (!mgr) return { success: false, output: '', error: 'Escrow manager not initialized.' }
409
+ try {
410
+ const contract = mgr.createEscrow(payer, payee, amount, { description, conditions })
411
+ return { success: true, output: `Escrow created: ${contract.id} (${amount} from ${payer} to ${payee})` }
412
+ } catch (err) {
413
+ return { success: false, output: '', error: err.message }
414
+ }
415
+ }
416
+ }
417
+
418
+ export class EscrowListTool extends BrowserTool {
419
+ get name() { return 'escrow_list' }
420
+ get description() { return 'List escrow contracts.' }
421
+ get parameters() {
422
+ return {
423
+ type: 'object',
424
+ properties: {
425
+ status: { type: 'string', description: 'Filter by status: pending, locked, released, refunded' },
426
+ },
427
+ }
428
+ }
429
+ get permission() { return 'read' }
430
+
431
+ async execute({ status } = {}) {
432
+ const mgr = peerToolsContext.getEscrowManager()
433
+ if (!mgr) return { success: true, output: 'Escrow manager not initialized.' }
434
+ try {
435
+ const contracts = mgr.listContracts(status)
436
+ if (!contracts || contracts.length === 0) return { success: true, output: 'No escrow contracts.' }
437
+ const lines = contracts.map(c => `${c.id} | ${c.status} | ${c.amount} | ${c.payer} → ${c.payee}`)
438
+ return { success: true, output: `ID | STATUS | AMOUNT | FLOW\n${lines.join('\n')}` }
439
+ } catch (err) {
440
+ return { success: false, output: '', error: err.message }
441
+ }
442
+ }
443
+ }
444
+
445
+ export class EscrowReleaseTool extends BrowserTool {
446
+ get name() { return 'escrow_release' }
447
+ get description() { return 'Release an escrow contract, transferring funds to the payee.' }
448
+ get parameters() {
449
+ return {
450
+ type: 'object',
451
+ properties: {
452
+ contractId: { type: 'string', description: 'Escrow contract ID' },
453
+ },
454
+ required: ['contractId'],
455
+ }
456
+ }
457
+ get permission() { return 'approve' }
458
+
459
+ async execute({ contractId }) {
460
+ const mgr = peerToolsContext.getEscrowManager()
461
+ if (!mgr) return { success: false, output: '', error: 'Escrow manager not initialized.' }
462
+ try {
463
+ mgr.releaseEscrow(contractId)
464
+ return { success: true, output: `Escrow ${contractId} released.` }
465
+ } catch (err) {
466
+ return { success: false, output: '', error: err.message }
467
+ }
468
+ }
469
+ }
470
+
471
+ // ── Router tools ──────────────────────────────────────────────────────
472
+
473
+ export class MeshRouterAddRouteTool extends BrowserTool {
474
+ get name() { return 'mesh_router_add_route' }
475
+ get description() { return 'Add a route to the mesh routing table.' }
476
+ get parameters() {
477
+ return {
478
+ type: 'object',
479
+ properties: {
480
+ destination: { type: 'string', description: 'Destination pod ID' },
481
+ nextHop: { type: 'string', description: 'Next hop pod ID' },
482
+ cost: { type: 'number', description: 'Route cost/metric (default: 1)' },
483
+ },
484
+ required: ['destination', 'nextHop'],
485
+ }
486
+ }
487
+ get permission() { return 'write' }
488
+
489
+ async execute({ destination, nextHop, cost }) {
490
+ const router = peerToolsContext.getMeshRouter()
491
+ if (!router) return { success: false, output: '', error: 'Mesh router not initialized.' }
492
+ try {
493
+ router.addRoute(destination, nextHop, cost ?? 1)
494
+ return { success: true, output: `Route added: ${destination} via ${nextHop} (cost: ${cost ?? 1})` }
495
+ } catch (err) {
496
+ return { success: false, output: '', error: err.message }
497
+ }
498
+ }
499
+ }
500
+
501
+ export class MeshRouterLookupTool extends BrowserTool {
502
+ get name() { return 'mesh_router_lookup' }
503
+ get description() { return 'Look up the best route to a destination pod.' }
504
+ get parameters() {
505
+ return {
506
+ type: 'object',
507
+ properties: {
508
+ destination: { type: 'string', description: 'Destination pod ID' },
509
+ },
510
+ required: ['destination'],
511
+ }
512
+ }
513
+ get permission() { return 'read' }
514
+
515
+ async execute({ destination }) {
516
+ const router = peerToolsContext.getMeshRouter()
517
+ if (!router) return { success: false, output: '', error: 'Mesh router not initialized.' }
518
+ try {
519
+ const route = router.resolve(destination)
520
+ if (!route) return { success: true, output: `No route to ${destination}.` }
521
+ return { success: true, output: `Route to ${destination}: next hop ${route.nextHop}, cost ${route.cost}` }
522
+ } catch (err) {
523
+ return { success: false, output: '', error: err.message }
524
+ }
525
+ }
526
+ }
527
+
528
+ // ── Timestamp tools ───────────────────────────────────────────────────
529
+
530
+ export class TimestampProofTool extends BrowserTool {
531
+ get name() { return 'mesh_timestamp_proof' }
532
+ get description() { return 'Request a cryptographic timestamp proof for an event.' }
533
+ get parameters() {
534
+ return {
535
+ type: 'object',
536
+ properties: {
537
+ eventHash: { type: 'string', description: 'Hash of the event to timestamp' },
538
+ },
539
+ required: ['eventHash'],
540
+ }
541
+ }
542
+ get permission() { return 'network' }
543
+
544
+ async execute({ eventHash }) {
545
+ const ta = peerToolsContext.getTimestampAuthority()
546
+ if (!ta) return { success: false, output: '', error: 'Timestamp authority not initialized.' }
547
+ try {
548
+ const proof = await ta.createProof(eventHash)
549
+ return { success: true, output: `Proof created: timestamp=${proof.canonicalTimestamp}, confidence=${proof.confidence}, witnesses=${proof.witnesses?.length || 0}` }
550
+ } catch (err) {
551
+ return { success: false, output: '', error: err.message }
552
+ }
553
+ }
554
+ }
555
+
556
+ // ── Stealth tools ─────────────────────────────────────────────────────
557
+
558
+ export class StealthSaveTool extends BrowserTool {
559
+ get name() { return 'stealth_save' }
560
+ get description() { return 'Save agent state as threshold-encrypted shards distributed across the DHT.' }
561
+ get parameters() {
562
+ return {
563
+ type: 'object',
564
+ properties: {
565
+ state: { type: 'object', description: 'State object to shard and distribute' },
566
+ },
567
+ required: ['state'],
568
+ }
569
+ }
570
+ get permission() { return 'approve' }
571
+
572
+ async execute({ state }) {
573
+ const agent = peerToolsContext.getStealthAgent()
574
+ if (!agent) return { success: false, output: '', error: 'Stealth agent not initialized.' }
575
+ try {
576
+ await agent.saveState(state)
577
+ return { success: true, output: 'State saved as distributed shards.' }
578
+ } catch (err) {
579
+ return { success: false, output: '', error: err.message }
580
+ }
581
+ }
582
+ }
583
+
584
+ export class StealthRestoreTool extends BrowserTool {
585
+ get name() { return 'stealth_restore' }
586
+ get description() { return 'Restore agent state from threshold-encrypted DHT shards.' }
587
+ get parameters() { return { type: 'object', properties: {} } }
588
+ get permission() { return 'approve' }
589
+
590
+ async execute() {
591
+ const agent = peerToolsContext.getStealthAgent()
592
+ if (!agent) return { success: false, output: '', error: 'Stealth agent not initialized.' }
593
+ try {
594
+ const state = await agent.restoreState()
595
+ return { success: true, output: state ? JSON.stringify(state) : 'No state found.' }
596
+ } catch (err) {
597
+ return { success: false, output: '', error: err.message }
598
+ }
599
+ }
600
+ }
601
+
602
+ // ── ACL tools ─────────────────────────────────────────────────────────
603
+
604
+ export class MeshACLAddEntryTool extends BrowserTool {
605
+ get name() { return 'mesh_acl_add' }
606
+ get description() { return 'Add a peer to the mesh access control list with a role template.' }
607
+ get parameters() {
608
+ return {
609
+ type: 'object',
610
+ properties: {
611
+ identity: { type: 'string', description: 'Peer fingerprint/pod ID' },
612
+ template: { type: 'string', description: 'Role template: guest, collaborator, admin' },
613
+ label: { type: 'string', description: 'Display label (optional)' },
614
+ },
615
+ required: ['identity', 'template'],
616
+ }
617
+ }
618
+ get permission() { return 'approve' }
619
+
620
+ async execute({ identity, template, label }) {
621
+ const acl = peerToolsContext.getMeshACL()
622
+ if (!acl) return { success: false, output: '', error: 'Mesh ACL not initialized.' }
623
+ try {
624
+ acl.addEntry(identity, template, { label })
625
+ return { success: true, output: `Added ${identity} as ${template}${label ? ` (${label})` : ''}.` }
626
+ } catch (err) {
627
+ return { success: false, output: '', error: err.message }
628
+ }
629
+ }
630
+ }
631
+
632
+ export class MeshACLListTool extends BrowserTool {
633
+ get name() { return 'mesh_acl_list' }
634
+ get description() { return 'List all entries in the mesh access control list.' }
635
+ get parameters() { return { type: 'object', properties: {} } }
636
+ get permission() { return 'read' }
637
+
638
+ async execute() {
639
+ const acl = peerToolsContext.getMeshACL()
640
+ if (!acl) return { success: true, output: 'Mesh ACL not initialized.' }
641
+ try {
642
+ const entries = acl.listEntries()
643
+ if (!entries || entries.length === 0) return { success: true, output: 'No ACL entries.' }
644
+ const lines = entries.map(e => `${e.identity} | ${e.templateName} | ${e.label || ''}`)
645
+ return { success: true, output: `IDENTITY | ROLE | LABEL\n${lines.join('\n')}` }
646
+ } catch (err) {
647
+ return { success: false, output: '', error: err.message }
648
+ }
649
+ }
650
+ }
651
+
652
+ export class MeshACLCheckTool extends BrowserTool {
653
+ get name() { return 'mesh_acl_check' }
654
+ get description() { return 'Check if a peer has a specific scope/permission.' }
655
+ get parameters() {
656
+ return {
657
+ type: 'object',
658
+ properties: {
659
+ identity: { type: 'string', description: 'Peer fingerprint/pod ID' },
660
+ scope: { type: 'string', description: 'Scope to check (e.g., read, write, admin)' },
661
+ },
662
+ required: ['identity', 'scope'],
663
+ }
664
+ }
665
+ get permission() { return 'read' }
666
+
667
+ async execute({ identity, scope }) {
668
+ const acl = peerToolsContext.getMeshACL()
669
+ if (!acl) return { success: false, output: '', error: 'Mesh ACL not initialized.' }
670
+ try {
671
+ const allowed = acl.check(identity, scope)
672
+ return { success: true, output: `${identity} ${allowed ? 'HAS' : 'DOES NOT HAVE'} scope "${scope}".` }
673
+ } catch (err) {
674
+ return { success: false, output: '', error: err.message }
675
+ }
676
+ }
677
+ }
678
+
679
+ // ── Session tools ─────────────────────────────────────────────────────
680
+
681
+ export class MeshSessionListTool extends BrowserTool {
682
+ get name() { return 'mesh_session_list' }
683
+ get description() { return 'List active peer sessions.' }
684
+ get parameters() { return { type: 'object', properties: {} } }
685
+ get permission() { return 'read' }
686
+
687
+ async execute() {
688
+ const mgr = peerToolsContext.getSessionManager()
689
+ if (!mgr) return { success: true, output: 'Session manager not initialized.' }
690
+ try {
691
+ const sessions = mgr.listSessions()
692
+ if (!sessions || sessions.length === 0) return { success: true, output: 'No active sessions.' }
693
+ const lines = sessions.map(s => `${s.sessionId} | ${s.remoteIdentity || '?'} | ${s.state || 'active'}`)
694
+ return { success: true, output: `SESSION | PEER | STATE\n${lines.join('\n')}` }
695
+ } catch (err) {
696
+ return { success: false, output: '', error: err.message }
697
+ }
698
+ }
699
+ }
700
+
701
+ // ── Gateway tools ─────────────────────────────────────────────────────
702
+
703
+ export class MeshGatewayStatusTool extends BrowserTool {
704
+ get name() { return 'mesh_gateway_status' }
705
+ get description() { return 'Get status of the local mesh gateway node.' }
706
+ get parameters() { return { type: 'object', properties: {} } }
707
+ get permission() { return 'read' }
708
+
709
+ async execute() {
710
+ const gw = peerToolsContext.getGatewayNode()
711
+ if (!gw) return { success: true, output: 'Gateway node not initialized.' }
712
+ try {
713
+ const stats = gw.getStats?.() || {}
714
+ const peers = gw.connectedPeers?.() || []
715
+ return {
716
+ success: true,
717
+ output: `Gateway: ${peers.length} connected peers, ${stats.routeCount || 0} routes, relay=${stats.allowRelay ?? true}`,
718
+ }
719
+ } catch (err) {
720
+ return { success: false, output: '', error: err.message }
721
+ }
722
+ }
723
+ }
724
+
725
+ // ── Torrent tools ─────────────────────────────────────────────────────
726
+
727
+ export class TorrentSeedTool extends BrowserTool {
728
+ get name() { return 'torrent_seed' }
729
+ get description() { return 'Seed a file or data via BitTorrent-style P2P distribution.' }
730
+ get parameters() {
731
+ return {
732
+ type: 'object',
733
+ properties: {
734
+ name: { type: 'string', description: 'Content name/identifier' },
735
+ data: { type: 'string', description: 'Base64-encoded data or text to seed' },
736
+ },
737
+ required: ['name', 'data'],
738
+ }
739
+ }
740
+ get permission() { return 'approve' }
741
+
742
+ async execute({ name, data }) {
743
+ const tm = peerToolsContext.getTorrentManager()
744
+ if (!tm) return { success: false, output: '', error: 'Torrent manager not initialized.' }
745
+ try {
746
+ const result = await tm.seed(name, data)
747
+ return { success: true, output: `Seeding: ${result?.infoHash || name}` }
748
+ } catch (err) {
749
+ return { success: false, output: '', error: err.message }
750
+ }
751
+ }
752
+ }
753
+
754
+ // ── IPFS tools ────────────────────────────────────────────────────────
755
+
756
+ export class IpfsStoreTool extends BrowserTool {
757
+ get name() { return 'ipfs_store' }
758
+ get description() { return 'Store data in the IPFS-compatible content-addressed store.' }
759
+ get parameters() {
760
+ return {
761
+ type: 'object',
762
+ properties: {
763
+ data: { type: 'string', description: 'Data to store' },
764
+ },
765
+ required: ['data'],
766
+ }
767
+ }
768
+ get permission() { return 'write' }
769
+
770
+ async execute({ data }) {
771
+ const store = peerToolsContext.getIpfsStore()
772
+ if (!store) return { success: false, output: '', error: 'IPFS store not initialized.' }
773
+ try {
774
+ const cid = await store.add(data)
775
+ return { success: true, output: `Stored with CID: ${cid}` }
776
+ } catch (err) {
777
+ return { success: false, output: '', error: err.message }
778
+ }
779
+ }
780
+ }
781
+
782
+ export class IpfsRetrieveTool extends BrowserTool {
783
+ get name() { return 'ipfs_retrieve' }
784
+ get description() { return 'Retrieve data from the IPFS-compatible store by CID.' }
785
+ get parameters() {
786
+ return {
787
+ type: 'object',
788
+ properties: {
789
+ cid: { type: 'string', description: 'Content identifier (CID)' },
790
+ },
791
+ required: ['cid'],
792
+ }
793
+ }
794
+ get permission() { return 'read' }
795
+
796
+ async execute({ cid }) {
797
+ const store = peerToolsContext.getIpfsStore()
798
+ if (!store) return { success: false, output: '', error: 'IPFS store not initialized.' }
799
+ try {
800
+ const data = await store.get(cid)
801
+ if (!data) return { success: true, output: `CID ${cid} not found.` }
802
+ return { success: true, output: typeof data === 'string' ? data : JSON.stringify(data) }
803
+ } catch (err) {
804
+ return { success: false, output: '', error: err.message }
805
+ }
806
+ }
807
+ }
808
+
809
+ // ── Credit ledger tools ───────────────────────────────────────────────
810
+
811
+ export class CreditBalanceTool extends BrowserTool {
812
+ get name() { return 'credit_balance' }
813
+ get description() { return 'Check the local credit balance or balance with a specific peer.' }
814
+ get parameters() {
815
+ return {
816
+ type: 'object',
817
+ properties: {
818
+ peerId: { type: 'string', description: 'Peer pod ID (optional, omit for local balance)' },
819
+ },
820
+ }
821
+ }
822
+ get permission() { return 'read' }
823
+
824
+ async execute({ peerId } = {}) {
825
+ const ledger = peerToolsContext.getCreditLedger()
826
+ if (!ledger) return { success: true, output: 'Credit ledger not initialized.' }
827
+ try {
828
+ const balance = ledger.balance ?? ledger.getBalance?.(peerId) ?? 0
829
+ return { success: true, output: `Balance${peerId ? ` (${peerId})` : ''}: ${balance} credits` }
830
+ } catch (err) {
831
+ return { success: false, output: '', error: err.message }
832
+ }
833
+ }
834
+ }
835
+
836
+ // ── Migration tools ───────────────────────────────────────────────────
837
+
838
+ export class MeshMigrationStatusTool extends BrowserTool {
839
+ get name() { return 'mesh_migration_status' }
840
+ get description() { return 'Get the status of active mesh migrations.' }
841
+ get parameters() { return { type: 'object', properties: {} } }
842
+ get permission() { return 'read' }
843
+
844
+ async execute() {
845
+ const engine = peerToolsContext.getMigrationEngine()
846
+ if (!engine) return { success: true, output: 'Migration engine not initialized.' }
847
+ try {
848
+ const migrations = engine.listMigrations?.() || []
849
+ if (migrations.length === 0) return { success: true, output: 'No active migrations.' }
850
+ const lines = migrations.map(m => `${m.migrationId} | ${m.state} | ${m.sourcePodId} → ${m.targetPodId}`)
851
+ return { success: true, output: `ID | STATE | FLOW\n${lines.join('\n')}` }
852
+ } catch (err) {
853
+ return { success: false, output: '', error: err.message }
854
+ }
855
+ }
856
+ }
857
+
858
+ // ── Delta sync tools ──────────────────────────────────────────────────
859
+
860
+ export class DeltaSyncStatusTool extends BrowserTool {
861
+ get name() { return 'delta_sync_status' }
862
+ get description() { return 'Get the status of the delta sync coordinator.' }
863
+ get parameters() { return { type: 'object', properties: {} } }
864
+ get permission() { return 'read' }
865
+
866
+ async execute() {
867
+ const sc = peerToolsContext.getSyncCoordinator()
868
+ if (!sc) return { success: true, output: 'Delta sync coordinator not initialized.' }
869
+ try {
870
+ const state = sc.state
871
+ const sessions = sc.listSessions?.() || []
872
+ return {
873
+ success: true,
874
+ output: `Delta sync: ${sessions.length} session(s), state keys: ${Object.keys(state).length}`,
875
+ }
876
+ } catch (err) {
877
+ return { success: false, output: '', error: err.message }
878
+ }
879
+ }
880
+ }
881
+
882
+ // ── Registry helper ───────────────────────────────────────────────────
883
+
884
+ /**
885
+ * Register all mesh peer tools with a BrowserToolRegistry.
886
+ * @param {import('./compat.mjs').BrowserToolRegistry} registry
887
+ * @param {object} deps - Subsystem instances
888
+ */
889
+ export function registerMeshPeerTools(registry, deps = {}) {
890
+ // Wire context
891
+ if (deps.meshChat) peerToolsContext.setMeshChat(deps.meshChat)
892
+ if (deps.meshScheduler) peerToolsContext.setMeshScheduler(deps.meshScheduler)
893
+ if (deps.federatedCompute) peerToolsContext.setFederatedCompute(deps.federatedCompute)
894
+ if (deps.agentSwarmCoordinator) peerToolsContext.setAgentSwarmCoordinator(deps.agentSwarmCoordinator)
895
+ if (deps.healthMonitor) peerToolsContext.setHealthMonitor(deps.healthMonitor)
896
+ if (deps.escrowManager) peerToolsContext.setEscrowManager(deps.escrowManager)
897
+ if (deps.meshRouter) peerToolsContext.setMeshRouter(deps.meshRouter)
898
+ if (deps.timestampAuthority) peerToolsContext.setTimestampAuthority(deps.timestampAuthority)
899
+ if (deps.stealthAgent) peerToolsContext.setStealthAgent(deps.stealthAgent)
900
+ if (deps.syncCoordinator) peerToolsContext.setSyncCoordinator(deps.syncCoordinator)
901
+ if (deps.gatewayNode) peerToolsContext.setGatewayNode(deps.gatewayNode)
902
+ if (deps.torrentManager) peerToolsContext.setTorrentManager(deps.torrentManager)
903
+ if (deps.ipfsStore) peerToolsContext.setIpfsStore(deps.ipfsStore)
904
+ if (deps.meshACL) peerToolsContext.setMeshACL(deps.meshACL)
905
+ if (deps.capabilityValidator) peerToolsContext.setCapabilityValidator(deps.capabilityValidator)
906
+ if (deps.sessionManager) peerToolsContext.setSessionManager(deps.sessionManager)
907
+ if (deps.crossOriginBridge) peerToolsContext.setCrossOriginBridge(deps.crossOriginBridge)
908
+ if (deps.verificationQuorum) peerToolsContext.setVerificationQuorum(deps.verificationQuorum)
909
+ if (deps.migrationEngine) peerToolsContext.setMigrationEngine(deps.migrationEngine)
910
+ if (deps.creditLedger) peerToolsContext.setCreditLedger(deps.creditLedger)
911
+
912
+ // Register tools
913
+ // Chat
914
+ registry.register(new MeshChatCreateRoomTool())
915
+ registry.register(new MeshChatSendTool())
916
+ registry.register(new MeshChatHistoryTool())
917
+ registry.register(new MeshChatListRoomsTool())
918
+ // Scheduler
919
+ registry.register(new MeshSchedulerSubmitTool())
920
+ registry.register(new MeshSchedulerListTool())
921
+ // Compute
922
+ registry.register(new FederatedComputeSubmitTool())
923
+ // Swarm
924
+ registry.register(new SwarmCreateTool())
925
+ registry.register(new SwarmStatusTool())
926
+ // Health
927
+ registry.register(new MeshHealthStatusTool())
928
+ // Escrow
929
+ registry.register(new EscrowCreateTool())
930
+ registry.register(new EscrowListTool())
931
+ registry.register(new EscrowReleaseTool())
932
+ // Router
933
+ registry.register(new MeshRouterAddRouteTool())
934
+ registry.register(new MeshRouterLookupTool())
935
+ // Timestamp
936
+ registry.register(new TimestampProofTool())
937
+ // Stealth
938
+ registry.register(new StealthSaveTool())
939
+ registry.register(new StealthRestoreTool())
940
+ // ACL
941
+ registry.register(new MeshACLAddEntryTool())
942
+ registry.register(new MeshACLListTool())
943
+ registry.register(new MeshACLCheckTool())
944
+ // Sessions
945
+ registry.register(new MeshSessionListTool())
946
+ // Gateway
947
+ registry.register(new MeshGatewayStatusTool())
948
+ // Torrent
949
+ registry.register(new TorrentSeedTool())
950
+ // IPFS
951
+ registry.register(new IpfsStoreTool())
952
+ registry.register(new IpfsRetrieveTool())
953
+ // Credits
954
+ registry.register(new CreditBalanceTool())
955
+ // Migration
956
+ registry.register(new MeshMigrationStatusTool())
957
+ // Delta sync
958
+ registry.register(new DeltaSyncStatusTool())
959
+ }