@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,1575 @@
1
+ /**
2
+ * clawser-mesh-orchestrator.js -- Pod orchestration engine + tools.
3
+ *
4
+ * MeshOrchestrator coordinates pods across the P2P mesh network.
5
+ * Each operation is also exposed as a BrowserTool subclass so the AI agent
6
+ * can invoke them via structured tool_use.
7
+ *
8
+ * No browser-only imports at module level.
9
+ *
10
+ * Run tests:
11
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-orchestrator.test.mjs
12
+ */
13
+
14
+ // Stub BrowserTool base class for Node.js testing
15
+ const BrowserTool = globalThis.BrowserTool || class {
16
+ constructor() {}
17
+ }
18
+
19
+ import { MESH_TYPE } from '@johnhenry/browsermesh-primitives'
20
+ import { ComputeRequest, ResourceDescriptor, ResourceScorer } from './resources.mjs'
21
+
22
+ // ---------------------------------------------------------------------------
23
+ // Wire constants (re-exported from canonical registry)
24
+ // ---------------------------------------------------------------------------
25
+
26
+ export const ORCH_LIST_PODS = MESH_TYPE.ORCH_LIST_PODS // 0xd8
27
+ export const ORCH_POD_STATUS = MESH_TYPE.ORCH_POD_STATUS // 0xd9
28
+ export const ORCH_EXEC = MESH_TYPE.ORCH_EXEC // 0xda
29
+ export const ORCH_DEPLOY = MESH_TYPE.ORCH_DEPLOY // 0xdb
30
+ export const ORCH_DRAIN = MESH_TYPE.ORCH_DRAIN // 0xdc
31
+ export const ORCH_EXPOSE = MESH_TYPE.ORCH_EXPOSE // 0xdd
32
+ export const ORCH_ROUTE = MESH_TYPE.ORCH_ROUTE // 0xde
33
+
34
+ // ---------------------------------------------------------------------------
35
+ // Valid enumerations
36
+ // ---------------------------------------------------------------------------
37
+
38
+ const VALID_POD_STATUSES = Object.freeze([
39
+ 'online', 'offline', 'draining', 'unknown',
40
+ ])
41
+
42
+ // ---------------------------------------------------------------------------
43
+ // PodInfo
44
+ // ---------------------------------------------------------------------------
45
+
46
+ /**
47
+ * Summary information about a pod in the mesh.
48
+ */
49
+ export class PodInfo {
50
+ /**
51
+ * @param {object} opts
52
+ * @param {string} opts.podId
53
+ * @param {string} [opts.label]
54
+ * @param {string} [opts.status]
55
+ * @param {string[]} [opts.services]
56
+ * @param {number} [opts.connections]
57
+ * @param {boolean} [opts.isLocal]
58
+ */
59
+ constructor({
60
+ podId,
61
+ label = '',
62
+ status = 'online',
63
+ services = [],
64
+ connections = 0,
65
+ isLocal = false,
66
+ }) {
67
+ if (!podId || typeof podId !== 'string') {
68
+ throw new Error('podId is required and must be a non-empty string')
69
+ }
70
+ this.podId = podId
71
+ this.label = label
72
+ this.status = status
73
+ this.services = [...services]
74
+ this.connections = connections
75
+ this.isLocal = isLocal
76
+ }
77
+
78
+ toJSON() {
79
+ return {
80
+ podId: this.podId,
81
+ label: this.label,
82
+ status: this.status,
83
+ services: [...this.services],
84
+ connections: this.connections,
85
+ isLocal: this.isLocal,
86
+ }
87
+ }
88
+
89
+ /**
90
+ * @param {object} data
91
+ * @returns {PodInfo}
92
+ */
93
+ static fromJSON(data) {
94
+ return new PodInfo(data)
95
+ }
96
+ }
97
+
98
+ // ---------------------------------------------------------------------------
99
+ // PodStatus
100
+ // ---------------------------------------------------------------------------
101
+
102
+ /**
103
+ * Detailed status of a specific pod.
104
+ */
105
+ export class PodStatus {
106
+ /**
107
+ * @param {object} opts
108
+ * @param {string} opts.podId
109
+ * @param {string} [opts.status]
110
+ * @param {string[]} [opts.capabilities]
111
+ * @param {string[]} [opts.services]
112
+ * @param {number} [opts.connections]
113
+ * @param {number} [opts.uptime]
114
+ * @param {object} [opts.resources]
115
+ * @param {number} [opts.resources.cpu]
116
+ * @param {number} [opts.resources.memory]
117
+ * @param {number} [opts.resources.storage]
118
+ * @param {boolean} [opts.isLocal]
119
+ */
120
+ constructor({
121
+ podId,
122
+ status = 'online',
123
+ capabilities = [],
124
+ services = [],
125
+ connections = 0,
126
+ uptime = 0,
127
+ resources = {},
128
+ isLocal = false,
129
+ }) {
130
+ if (!podId || typeof podId !== 'string') {
131
+ throw new Error('podId is required and must be a non-empty string')
132
+ }
133
+ this.podId = podId
134
+ this.status = status
135
+ this.capabilities = [...capabilities]
136
+ this.services = [...services]
137
+ this.connections = connections
138
+ this.uptime = uptime
139
+ this.resources = {
140
+ cpu: resources.cpu ?? 0,
141
+ memory: resources.memory ?? 0,
142
+ storage: resources.storage ?? 0,
143
+ }
144
+ this.isLocal = isLocal
145
+ }
146
+
147
+ toJSON() {
148
+ return {
149
+ podId: this.podId,
150
+ status: this.status,
151
+ capabilities: [...this.capabilities],
152
+ services: [...this.services],
153
+ connections: this.connections,
154
+ uptime: this.uptime,
155
+ resources: { ...this.resources },
156
+ isLocal: this.isLocal,
157
+ }
158
+ }
159
+
160
+ /**
161
+ * @param {object} data
162
+ * @returns {PodStatus}
163
+ */
164
+ static fromJSON(data) {
165
+ return new PodStatus(data)
166
+ }
167
+ }
168
+
169
+ // ---------------------------------------------------------------------------
170
+ // PodResourceInfo
171
+ // ---------------------------------------------------------------------------
172
+
173
+ /**
174
+ * Resource usage snapshot for a single pod (used by topPods).
175
+ */
176
+ export class PodResourceInfo {
177
+ /**
178
+ * @param {object} opts
179
+ * @param {string} opts.podId
180
+ * @param {number} [opts.cpu]
181
+ * @param {number} [opts.memory]
182
+ * @param {number} [opts.storage]
183
+ * @param {number} [opts.activeTasks]
184
+ * @param {string} [opts.status]
185
+ */
186
+ constructor({
187
+ podId,
188
+ cpu = 0,
189
+ memory = 0,
190
+ storage = 0,
191
+ activeTasks = 0,
192
+ status = 'online',
193
+ }) {
194
+ this.podId = podId
195
+ this.cpu = cpu
196
+ this.memory = memory
197
+ this.storage = storage
198
+ this.activeTasks = activeTasks
199
+ this.status = status
200
+ }
201
+
202
+ toJSON() {
203
+ return {
204
+ podId: this.podId,
205
+ cpu: this.cpu,
206
+ memory: this.memory,
207
+ storage: this.storage,
208
+ activeTasks: this.activeTasks,
209
+ status: this.status,
210
+ }
211
+ }
212
+ }
213
+
214
+ // ---------------------------------------------------------------------------
215
+ // MeshOrchestrator
216
+ // ---------------------------------------------------------------------------
217
+
218
+ /**
219
+ * Coordinates pods across the P2P mesh network.
220
+ * Provides pod queries, remote execution, deployment, draining,
221
+ * resource monitoring, and service operations.
222
+ */
223
+ export class MeshOrchestrator {
224
+ /** @type {object|null} PeerNode -- the local peer */
225
+ #peerNode
226
+ /** @type {object|null} ServiceAdvertiser */
227
+ #serviceAdvertiser
228
+ /** @type {object|null} ServiceBrowser */
229
+ #serviceBrowser
230
+ /** @type {object|null} MeshRouter */
231
+ #router
232
+ /** @type {Function|null} */
233
+ #onLog
234
+ /** @type {object|null} */
235
+ #runtimeRegistry
236
+ /** @type {object|null} */
237
+ #remoteSessionBroker
238
+ /** @type {object|null} */
239
+ #resourceRegistry
240
+ /** @type {object|null} */
241
+ #auditRecorder
242
+ /** @type {object|null} */
243
+ #peerRegistry
244
+ /** @type {Map<string, object>} podId -> peer info */
245
+ #knownPeers = new Map()
246
+ /** @type {Map<string, object>} name -> { podId, port } */
247
+ #exposedServices = new Map()
248
+ /** @type {Map<string, object>} name -> targetPodId */
249
+ #routes = new Map()
250
+ /** @type {Map<string, object>} tunnelId -> tunnel record */
251
+ #tunnels = new Map()
252
+ /** @type {Set<string>} podIds currently draining */
253
+ #draining = new Set()
254
+ /** @type {number} */
255
+ #tunnelCounter = 0
256
+
257
+ /**
258
+ * @param {object} opts
259
+ * @param {object} opts.peerNode - PeerNode -- the local peer
260
+ * @param {object} [opts.serviceAdvertiser] - ServiceAdvertiser or null
261
+ * @param {object} [opts.serviceBrowser] - ServiceBrowser or null
262
+ * @param {object} [opts.router] - MeshRouter or null
263
+ * @param {object} [opts.runtimeRegistry] - RemoteRuntimeRegistry or null
264
+ * @param {object} [opts.remoteSessionBroker] - RemoteSessionBroker or null
265
+ * @param {object} [opts.resourceRegistry] - ResourceRegistry or null
266
+ * @param {object} [opts.auditRecorder] - RemoteRuntimeAuditRecorder or null
267
+ * @param {object} [opts.peerRegistry] - PeerRegistry or null
268
+ * @param {Function} [opts.onLog] - Logging callback
269
+ */
270
+ constructor({ peerNode, serviceAdvertiser, serviceBrowser, router, runtimeRegistry, remoteSessionBroker, resourceRegistry, auditRecorder, peerRegistry, onLog }) {
271
+ if (!peerNode) {
272
+ throw new Error('peerNode is required')
273
+ }
274
+ this.#peerNode = peerNode
275
+ this.#serviceAdvertiser = serviceAdvertiser ?? null
276
+ this.#serviceBrowser = serviceBrowser ?? null
277
+ this.#router = router ?? null
278
+ this.#runtimeRegistry = runtimeRegistry ?? null
279
+ this.#remoteSessionBroker = remoteSessionBroker ?? null
280
+ this.#resourceRegistry = resourceRegistry ?? null
281
+ this.#auditRecorder = auditRecorder ?? null
282
+ this.#peerRegistry = peerRegistry ?? null
283
+ this.#onLog = onLog ?? null
284
+ }
285
+
286
+ /** @returns {object} The local peer node */
287
+ get peerNode() {
288
+ return this.#peerNode
289
+ }
290
+
291
+ /** @returns {string} Local pod ID (cached from peerNode) */
292
+ get localPodId() {
293
+ return this.#peerNode.podId || this.#peerNode.id || 'local'
294
+ }
295
+
296
+ // -- Logging --------------------------------------------------------------
297
+
298
+ #log(msg) {
299
+ if (this.#onLog) this.#onLog(msg)
300
+ }
301
+
302
+ async #recordAudit(operation, data = {}) {
303
+ await this.#auditRecorder?.record?.(operation, data)
304
+ }
305
+
306
+ #recordComputeReputation(descriptor, score) {
307
+ const fingerprint = descriptor?.identity?.fingerprint || null
308
+ if (!fingerprint || !this.#peerRegistry?.recordObservedTrust) return
309
+ this.#peerRegistry.recordObservedTrust(fingerprint, score)
310
+ }
311
+
312
+ // -- Pod queries ----------------------------------------------------------
313
+
314
+ /**
315
+ * List all known pods (local + remote).
316
+ * @param {string} [filter] - Status filter: 'online', 'offline', 'all'
317
+ * @returns {Promise<PodInfo[]>}
318
+ */
319
+ async listPods(filter) {
320
+ const pods = []
321
+
322
+ // Local pod is always included
323
+ const localPodId = this.localPodId
324
+ const localServices = this.#getLocalServices()
325
+ const localPod = new PodInfo({
326
+ podId: localPodId,
327
+ label: this.#peerNode.label || localPodId,
328
+ status: this.#draining.has(localPodId) ? 'draining' : 'online',
329
+ services: localServices,
330
+ connections: this.#knownPeers.size,
331
+ isLocal: true,
332
+ })
333
+ pods.push(localPod)
334
+
335
+ // Add known remote peers
336
+ for (const [podId, info] of this.#knownPeers) {
337
+ const status = this.#draining.has(podId) ? 'draining' : (info.status || 'online')
338
+ pods.push(new PodInfo({
339
+ podId,
340
+ label: info.label || podId,
341
+ status,
342
+ services: info.services || [],
343
+ connections: info.connections ?? 0,
344
+ isLocal: false,
345
+ }))
346
+ }
347
+
348
+ const knownPodIds = new Set(pods.map((pod) => pod.podId))
349
+ for (const descriptor of this.#runtimeDescriptors()) {
350
+ const podId = this.#descriptorPodId(descriptor)
351
+ if (knownPodIds.has(podId)) continue
352
+ knownPodIds.add(podId)
353
+ pods.push(new PodInfo({
354
+ podId,
355
+ label: this.#descriptorLabel(descriptor),
356
+ status: this.#descriptorStatus(descriptor, podId),
357
+ services: descriptor.metadata?.services || [],
358
+ connections: descriptor.reachability?.length || 0,
359
+ isLocal: false,
360
+ }))
361
+ }
362
+
363
+ // Apply filter
364
+ if (filter && filter !== 'all') {
365
+ return pods.filter(p => p.status === filter)
366
+ }
367
+ return pods
368
+ }
369
+
370
+ /**
371
+ * Get detailed status for a specific pod.
372
+ * @param {string} podId
373
+ * @returns {Promise<PodStatus|null>}
374
+ */
375
+ async getPodStatus(podId) {
376
+ const localPodId = this.localPodId
377
+
378
+ if (podId === localPodId) {
379
+ return new PodStatus({
380
+ podId: localPodId,
381
+ status: this.#draining.has(localPodId) ? 'draining' : 'online',
382
+ capabilities: this.#peerNode.capabilities || [],
383
+ services: this.#getLocalServices(),
384
+ connections: this.#knownPeers.size,
385
+ uptime: this.#peerNode.uptime ?? 0,
386
+ resources: this.#peerNode.resources || {},
387
+ isLocal: true,
388
+ })
389
+ }
390
+
391
+ const info = this.#knownPeers.get(podId)
392
+ if (!info) {
393
+ const descriptor = this.#runtimeDescriptorForPodId(podId)
394
+ if (!descriptor) return null
395
+ return new PodStatus({
396
+ podId,
397
+ status: this.#descriptorStatus(descriptor, podId),
398
+ capabilities: descriptor.capabilities || [],
399
+ services: descriptor.metadata?.services || [],
400
+ connections: descriptor.reachability?.length || 0,
401
+ uptime: descriptor.metadata?.uptime ?? 0,
402
+ resources: descriptor.metadata?.resources || {},
403
+ isLocal: false,
404
+ })
405
+ }
406
+
407
+ return new PodStatus({
408
+ podId,
409
+ status: this.#draining.has(podId) ? 'draining' : (info.status || 'online'),
410
+ capabilities: info.capabilities || [],
411
+ services: info.services || [],
412
+ connections: info.connections ?? 0,
413
+ uptime: info.uptime ?? 0,
414
+ resources: info.resources || {},
415
+ isLocal: false,
416
+ })
417
+ }
418
+
419
+ // -- Remote execution -----------------------------------------------------
420
+
421
+ /**
422
+ * Execute a command on a remote pod via peer session.
423
+ * @param {string} podId
424
+ * @param {string} command
425
+ * @returns {Promise<{ output: string, exitCode: number }>}
426
+ */
427
+ async execOnPod(podId, command) {
428
+ if (!command || typeof command !== 'string') {
429
+ throw new Error('command is required and must be a non-empty string')
430
+ }
431
+
432
+ const localPodId = this.localPodId
433
+ if (podId === localPodId) {
434
+ // Execute locally via peerNode if it has an exec method
435
+ if (this.#peerNode.exec) {
436
+ return await this.#peerNode.exec(command)
437
+ }
438
+ return { output: `Local execution not supported`, exitCode: 1 }
439
+ }
440
+
441
+ const runtime = this.#resolveRuntime(podId)
442
+ if (runtime && this.#remoteSessionBroker) {
443
+ const result = await this.#remoteSessionBroker.openSession(podId, {
444
+ intent: 'exec',
445
+ command,
446
+ })
447
+ if (typeof result?.output === 'string') {
448
+ return { output: result.output, exitCode: result.exitCode ?? 0 }
449
+ }
450
+ }
451
+
452
+ const info = this.#knownPeers.get(podId)
453
+ if (!info) {
454
+ throw new Error(`Pod "${podId}" not found`)
455
+ }
456
+
457
+ // Delegate to the peer's terminal/session if available
458
+ if (info.exec) {
459
+ return await info.exec(command)
460
+ }
461
+ if (info.send) {
462
+ info.send({ type: 'exec', command })
463
+ return { output: `Command sent to ${podId}`, exitCode: 0 }
464
+ }
465
+
466
+ throw new Error(`Pod "${podId}" does not support remote execution`)
467
+ }
468
+
469
+ // -- Deployment -----------------------------------------------------------
470
+
471
+ /**
472
+ * Deploy a skill (SKILL.md content) to a remote pod.
473
+ * @param {string} podId
474
+ * @param {string} skillContent - SKILL.md content to deploy
475
+ * @returns {Promise<{ success: boolean, error?: string }>}
476
+ */
477
+ async deploySkill(podId, skillContent) {
478
+ if (!skillContent || typeof skillContent !== 'string') {
479
+ return { success: false, error: 'skillContent is required' }
480
+ }
481
+
482
+ const runtime = this.#resolveRuntime(podId)
483
+ if (runtime && this.#remoteSessionBroker) {
484
+ if (runtime.metadata?.deploymentSupport?.canDeploy !== true) {
485
+ await this.#recordAudit('remote_deploy_denied', {
486
+ actor: 'operator',
487
+ podId,
488
+ reason: 'target does not advertise deployment support',
489
+ layer: 'capability',
490
+ deploymentType: 'skill',
491
+ })
492
+ return { success: false, error: `Pod "${podId}" does not advertise deployment support` }
493
+ }
494
+ const skillName = deriveSkillName(skillContent)
495
+ const path = `/.skills/${skillName}/SKILL.md`
496
+ await this.#recordAudit('remote_deploy_started', {
497
+ actor: 'operator',
498
+ podId,
499
+ path,
500
+ deploymentType: 'skill',
501
+ })
502
+ await this.#remoteSessionBroker.openSession(podId, {
503
+ intent: 'deployment',
504
+ operation: 'upload',
505
+ path,
506
+ data: skillContent,
507
+ requiredCapabilities: ['fs'],
508
+ actor: 'operator',
509
+ })
510
+ await this.#recordAudit('remote_deploy_completed', {
511
+ actor: 'operator',
512
+ podId,
513
+ path,
514
+ deploymentType: 'skill',
515
+ })
516
+ return { success: true, path }
517
+ }
518
+
519
+ const info = this.#knownPeers.get(podId)
520
+ if (!info) {
521
+ return { success: false, error: `Pod "${podId}" not found` }
522
+ }
523
+
524
+ this.#log(`Deploying skill to ${podId} (${skillContent.length} bytes)`)
525
+
526
+ if (info.deploySkill) {
527
+ return await info.deploySkill(skillContent)
528
+ }
529
+ if (info.send) {
530
+ info.send({ type: 'deploy_skill', content: skillContent })
531
+ return { success: true }
532
+ }
533
+
534
+ return { success: false, error: `Pod "${podId}" does not support deployment` }
535
+ }
536
+
537
+ async listRemoteServices(filter = {}) {
538
+ const discovered = []
539
+
540
+ if (this.#serviceBrowser?.discover) {
541
+ for (const service of this.#serviceBrowser.discover(filter)) {
542
+ discovered.push({ ...service, source: 'service-browser' })
543
+ }
544
+ }
545
+
546
+ for (const descriptor of this.#runtimeDescriptors()) {
547
+ const podId = this.#descriptorPodId(descriptor)
548
+ const details = descriptor.metadata?.serviceDetails || {}
549
+ const names = descriptor.metadata?.services || Object.keys(details)
550
+ for (const name of names) {
551
+ const detail = details[name] || { name }
552
+ if (filter.type && detail.type && detail.type !== filter.type) continue
553
+ if (filter.podId && filter.podId !== podId) continue
554
+ discovered.push({
555
+ ...detail,
556
+ name,
557
+ podId,
558
+ source: 'runtime-registry',
559
+ })
560
+ }
561
+ }
562
+
563
+ return discovered
564
+ }
565
+
566
+ async browseRemoteFiles(podId, path = '/') {
567
+ const runtime = this.#resolveRuntime(podId)
568
+ if (runtime && this.#remoteSessionBroker) {
569
+ const result = await this.#remoteSessionBroker.openSession(podId, {
570
+ intent: 'files',
571
+ operation: 'list',
572
+ path,
573
+ })
574
+ return { entries: result.entries || [] }
575
+ }
576
+ throw new Error(`Pod "${podId}" does not support remote filesystem browsing`)
577
+ }
578
+
579
+ async readRemoteFile(podId, path) {
580
+ if (!path || typeof path !== 'string') {
581
+ throw new Error('path is required')
582
+ }
583
+ const runtime = this.#resolveRuntime(podId)
584
+ if (runtime && this.#remoteSessionBroker) {
585
+ const result = await this.#remoteSessionBroker.openSession(podId, {
586
+ intent: 'files',
587
+ operation: 'read',
588
+ path,
589
+ })
590
+ return result.content || ''
591
+ }
592
+ throw new Error(`Pod "${podId}" does not support remote file reads`)
593
+ }
594
+
595
+ async writeRemoteFile(podId, path, content) {
596
+ if (!path || typeof path !== 'string') {
597
+ throw new Error('path is required')
598
+ }
599
+ const runtime = this.#resolveRuntime(podId)
600
+ if (runtime && this.#remoteSessionBroker) {
601
+ await this.#remoteSessionBroker.openSession(podId, {
602
+ intent: 'files',
603
+ operation: 'write',
604
+ path,
605
+ data: content,
606
+ })
607
+ return { success: true }
608
+ }
609
+ throw new Error(`Pod "${podId}" does not support remote file writes`)
610
+ }
611
+
612
+ async runAutomationOnPod(podId, command) {
613
+ return this.runComputeTask({ selector: podId, command })
614
+ }
615
+
616
+ async listComputeCandidates(constraints = {}) {
617
+ return this.#collectComputeDescriptors(constraints).map((descriptor) => ({
618
+ podId: descriptor.podId,
619
+ resources: { ...descriptor.resources },
620
+ capabilities: [...descriptor.capabilities],
621
+ availability: descriptor.availability,
622
+ source: descriptor.source || 'resource-registry',
623
+ }))
624
+ }
625
+
626
+ selectComputeTarget({ selector = null, constraints = {}, request = null } = {}) {
627
+ const nextRequest = request instanceof ComputeRequest
628
+ ? request
629
+ : new ComputeRequest({
630
+ moduleType: 'js',
631
+ moduleCid: 'runtime-task',
632
+ entry: 'main',
633
+ constraints,
634
+ requesterId: this.localPodId,
635
+ })
636
+
637
+ const descriptors = this.#collectComputeDescriptors(nextRequest.constraints || {})
638
+ if (selector) {
639
+ const selected = descriptors.find((descriptor) => descriptor.podId === selector)
640
+ if (!selected) {
641
+ throw new Error(`Pod "${selector}" is not available for compute`)
642
+ }
643
+ return {
644
+ podId: selected.podId,
645
+ descriptor: selected,
646
+ request: nextRequest,
647
+ source: selected.source || 'resource-registry',
648
+ }
649
+ }
650
+
651
+ const selected = ResourceScorer.selectBest(nextRequest, descriptors)
652
+ if (!selected) {
653
+ throw new Error('No compute-capable runtime matches the requested constraints')
654
+ }
655
+ return {
656
+ podId: selected.podId,
657
+ descriptor: selected,
658
+ request: nextRequest,
659
+ source: selected.source || 'resource-registry',
660
+ }
661
+ }
662
+
663
+ async runComputeTask({ selector = null, command, constraints = {}, timeoutMs = null } = {}) {
664
+ if (!command || typeof command !== 'string') {
665
+ throw new Error('command is required')
666
+ }
667
+
668
+ const selection = this.selectComputeTarget({ selector, constraints })
669
+ const podId = selection.podId
670
+ await this.#recordAudit('remote_compute_dispatched', {
671
+ actor: 'automation',
672
+ podId,
673
+ source: selection.source,
674
+ preferRuntimeClass: constraints?.preferRuntimeClass || null,
675
+ })
676
+ const runtime = this.#resolveRuntime(podId)
677
+ if (runtime && this.#remoteSessionBroker) {
678
+ try {
679
+ const result = await this.#remoteSessionBroker.openSession(podId, {
680
+ intent: 'automation',
681
+ command,
682
+ timeout: timeoutMs || selection.request?.constraints?.timeoutMs || 30_000,
683
+ })
684
+ this.#recordComputeReputation(runtime, (result.exitCode ?? 0) === 0 ? 1 : 0.7)
685
+ await this.#recordAudit('remote_compute_completed', {
686
+ actor: 'automation',
687
+ podId,
688
+ source: selection.source,
689
+ exitCode: result.exitCode ?? 0,
690
+ })
691
+ return {
692
+ podId,
693
+ output: result.output || '',
694
+ exitCode: result.exitCode ?? 0,
695
+ source: selection.source,
696
+ }
697
+ } catch (error) {
698
+ this.#recordComputeReputation(runtime, 0)
699
+ throw error
700
+ }
701
+ }
702
+
703
+ if (podId === this.localPodId && this.#peerNode.exec) {
704
+ const result = await this.#peerNode.exec(command)
705
+ await this.#recordAudit('remote_compute_completed', {
706
+ actor: 'automation',
707
+ podId,
708
+ source: 'local',
709
+ exitCode: result.exitCode ?? 0,
710
+ })
711
+ return { podId, output: result.output || '', exitCode: result.exitCode ?? 0, source: 'local' }
712
+ }
713
+
714
+ const info = this.#knownPeers.get(podId)
715
+ if (info?.exec) {
716
+ const result = await info.exec(command)
717
+ await this.#recordAudit('remote_compute_completed', {
718
+ actor: 'automation',
719
+ podId,
720
+ source: 'known-peer',
721
+ exitCode: result.exitCode ?? 0,
722
+ })
723
+ return { podId, output: result.output || '', exitCode: result.exitCode ?? 0, source: 'known-peer' }
724
+ }
725
+ if (info?.send) {
726
+ info.send({ type: 'compute', command, constraints })
727
+ await this.#recordAudit('remote_compute_completed', {
728
+ actor: 'automation',
729
+ podId,
730
+ source: 'known-peer',
731
+ exitCode: 0,
732
+ })
733
+ return { podId, output: `Compute task sent to ${podId}`, exitCode: 0, source: 'known-peer' }
734
+ }
735
+
736
+ throw new Error(`Pod "${podId}" does not support compute execution`)
737
+ }
738
+
739
+ // -- Pod management -------------------------------------------------------
740
+
741
+ /**
742
+ * Gracefully drain a pod: mark it as draining, migrate tasks, disconnect.
743
+ * @param {string} podId
744
+ * @returns {Promise<{ success: boolean, migrated: number }>}
745
+ */
746
+ async drainPod(podId) {
747
+ const info = this.#knownPeers.get(podId)
748
+ const localPodId = this.localPodId
749
+
750
+ if (podId !== localPodId && !info) {
751
+ return { success: false, migrated: 0 }
752
+ }
753
+
754
+ this.#draining.add(podId)
755
+ this.#log(`Draining pod ${podId}`)
756
+
757
+ let migrated = 0
758
+
759
+ // If the peer has a drain callback, invoke it
760
+ if (info && info.drain) {
761
+ const result = await info.drain()
762
+ migrated = result?.migrated ?? 0
763
+ }
764
+
765
+ // Remove from known peers (disconnect)
766
+ if (podId !== localPodId) {
767
+ this.#knownPeers.delete(podId)
768
+ }
769
+
770
+ return { success: true, migrated }
771
+ }
772
+
773
+ // -- Resource usage -------------------------------------------------------
774
+
775
+ /**
776
+ * Snapshot of resource usage across all known pods.
777
+ * @returns {Promise<{ pods: PodResourceInfo[] }>}
778
+ */
779
+ async topPods() {
780
+ const pods = []
781
+ const localPodId = this.localPodId
782
+ const localRes = this.#peerNode.resources || {}
783
+
784
+ pods.push(new PodResourceInfo({
785
+ podId: localPodId,
786
+ cpu: localRes.cpu ?? 0,
787
+ memory: localRes.memory ?? 0,
788
+ storage: localRes.storage ?? 0,
789
+ activeTasks: this.#peerNode.activeTasks ?? 0,
790
+ status: this.#draining.has(localPodId) ? 'draining' : 'online',
791
+ }))
792
+
793
+ for (const [podId, info] of this.#knownPeers) {
794
+ const res = info.resources || {}
795
+ pods.push(new PodResourceInfo({
796
+ podId,
797
+ cpu: res.cpu ?? 0,
798
+ memory: res.memory ?? 0,
799
+ storage: res.storage ?? 0,
800
+ activeTasks: info.activeTasks ?? 0,
801
+ status: this.#draining.has(podId) ? 'draining' : (info.status || 'online'),
802
+ }))
803
+ }
804
+
805
+ const knownPodIds = new Set(pods.map((pod) => pod.podId))
806
+ for (const descriptor of this.#runtimeDescriptors()) {
807
+ const podId = this.#descriptorPodId(descriptor)
808
+ if (knownPodIds.has(podId)) continue
809
+ knownPodIds.add(podId)
810
+ const resources = descriptor.metadata?.resources || {}
811
+ pods.push(new PodResourceInfo({
812
+ podId,
813
+ cpu: resources.cpu ?? 0,
814
+ memory: resources.memory ?? 0,
815
+ storage: resources.storage ?? 0,
816
+ activeTasks: descriptor.metadata?.activeTasks ?? 0,
817
+ status: this.#descriptorStatus(descriptor, podId),
818
+ }))
819
+ }
820
+
821
+ return { pods }
822
+ }
823
+
824
+ // -- Service operations ---------------------------------------------------
825
+
826
+ /**
827
+ * Expose a pod service on the mesh.
828
+ * @param {string} podId
829
+ * @param {number} port
830
+ * @param {string} name - Service name
831
+ * @returns {Promise<{ success: boolean, address?: string }>}
832
+ */
833
+ async exposePod(podId, port, name) {
834
+ if (!name || typeof name !== 'string') {
835
+ return { success: false }
836
+ }
837
+ if (typeof port !== 'number' || !Number.isFinite(port) || port <= 0 || port > 65535) {
838
+ return { success: false }
839
+ }
840
+
841
+ const address = `${podId}:${port}`
842
+ this.#exposedServices.set(name, { podId, port, address })
843
+ this.#log(`Exposed service "${name}" at ${address}`)
844
+
845
+ // Advertise via service advertiser if available
846
+ if (this.#serviceAdvertiser && this.#serviceAdvertiser.advertise) {
847
+ this.#serviceAdvertiser.advertise({ name, type: 'http-proxy', podId, port })
848
+ }
849
+
850
+ return { success: true, address }
851
+ }
852
+
853
+ /**
854
+ * Route a named service to a target pod.
855
+ * @param {string} name - Service name
856
+ * @param {string} targetPodId
857
+ * @returns {Promise<{ success: boolean }>}
858
+ */
859
+ async routeService(name, targetPodId) {
860
+ if (!name || typeof name !== 'string') {
861
+ return { success: false }
862
+ }
863
+ if (!targetPodId || typeof targetPodId !== 'string') {
864
+ return { success: false }
865
+ }
866
+
867
+ this.#routes.set(name, targetPodId)
868
+ this.#log(`Routed service "${name}" to ${targetPodId}`)
869
+
870
+ // Update router if available
871
+ if (this.#router && this.#router.addRoute) {
872
+ this.#router.addRoute(targetPodId, targetPodId, 1)
873
+ }
874
+
875
+ return { success: true }
876
+ }
877
+
878
+ // -- Tunnel (port forwarding concept) ------------------------------------
879
+
880
+ /**
881
+ * Create a port-forwarding tunnel to a remote pod.
882
+ * @param {string} podId
883
+ * @param {number} remotePort
884
+ * @param {number} localPort
885
+ * @returns {Promise<{ success: boolean, tunnelId?: string }>}
886
+ */
887
+ async tunnelPort(podId, remotePort, localPort) {
888
+ if (!podId || typeof podId !== 'string') {
889
+ return { success: false }
890
+ }
891
+ if (typeof remotePort !== 'number' || remotePort <= 0) {
892
+ return { success: false }
893
+ }
894
+ if (typeof localPort !== 'number' || localPort <= 0) {
895
+ return { success: false }
896
+ }
897
+
898
+ const tunnelId = `tunnel_${++this.#tunnelCounter}`
899
+ this.#tunnels.set(tunnelId, { podId, remotePort, localPort, createdAt: Date.now() })
900
+ this.#log(`Tunnel ${tunnelId}: local:${localPort} -> ${podId}:${remotePort}`)
901
+
902
+ return { success: true, tunnelId }
903
+ }
904
+
905
+ // -- Peer management (used by the mesh layer to keep state in sync) ------
906
+
907
+ /**
908
+ * Register a known remote peer.
909
+ * @param {string} podId
910
+ * @param {object} info - { label, status, services, capabilities, resources, connections, uptime, exec?, send?, drain?, deploySkill? }
911
+ */
912
+ addPeer(podId, info) {
913
+ this.#knownPeers.set(podId, info)
914
+ }
915
+
916
+ /**
917
+ * Remove a known remote peer.
918
+ * @param {string} podId
919
+ * @returns {boolean}
920
+ */
921
+ removePeer(podId) {
922
+ this.#draining.delete(podId)
923
+ return this.#knownPeers.delete(podId)
924
+ }
925
+
926
+ /**
927
+ * Number of known remote peers.
928
+ * @returns {number}
929
+ */
930
+ get peerCount() {
931
+ return this.#knownPeers.size
932
+ }
933
+
934
+ // -- Internal helpers -----------------------------------------------------
935
+
936
+ #getLocalServices() {
937
+ const services = []
938
+ for (const [name, entry] of this.#exposedServices) {
939
+ const localPodId = this.localPodId
940
+ if (entry.podId === localPodId) {
941
+ services.push(name)
942
+ }
943
+ }
944
+ return services
945
+ }
946
+
947
+ #runtimeDescriptors() {
948
+ if (!this.#runtimeRegistry || typeof this.#runtimeRegistry.listPeers !== 'function') {
949
+ return []
950
+ }
951
+ return this.#runtimeRegistry.listPeers()
952
+ }
953
+
954
+ #runtimeDescriptorForPodId(podId) {
955
+ if (!this.#runtimeRegistry || typeof this.#runtimeRegistry.resolvePeer !== 'function') {
956
+ return null
957
+ }
958
+ return this.#runtimeRegistry.resolvePeer(podId)
959
+ }
960
+
961
+ #resolveRuntime(podId) {
962
+ return this.#runtimeDescriptorForPodId(podId)
963
+ || this.#runtimeRegistry?.resolvePeer?.(`@${podId}`)
964
+ || null
965
+ }
966
+
967
+ #descriptorPodId(descriptor) {
968
+ return descriptor.identity?.podId
969
+ || descriptor.identity?.fingerprint
970
+ || descriptor.identity?.canonicalId
971
+ || descriptor.username
972
+ }
973
+
974
+ #descriptorLabel(descriptor) {
975
+ return descriptor.metadata?.name
976
+ || descriptor.username
977
+ || descriptor.identity?.aliases?.[0]
978
+ || this.#descriptorPodId(descriptor)
979
+ }
980
+
981
+ #descriptorStatus(descriptor, podId) {
982
+ if (this.#draining.has(podId)) return 'draining'
983
+ const route = (descriptor.reachability || [])[0]
984
+ const status = descriptor.metadata?.status
985
+ if (status) return status
986
+ return route ? 'online' : 'unknown'
987
+ }
988
+
989
+ #collectComputeDescriptors(constraints = {}) {
990
+ const merged = new Map()
991
+ const descriptors = []
992
+
993
+ const localDescriptor = new ResourceDescriptor({
994
+ podId: this.localPodId,
995
+ resources: this.#peerNode.resources || {},
996
+ capabilities: dedupeStrings([
997
+ ...(this.#peerNode.capabilities || []),
998
+ ...(this.#peerNode.exec ? ['compute'] : []),
999
+ ]),
1000
+ availability: this.#draining.has(this.localPodId) ? 'busy' : 'online',
1001
+ })
1002
+ if (localDescriptor.capabilities.includes('compute')) {
1003
+ localDescriptor.source = 'local'
1004
+ descriptors.push(localDescriptor)
1005
+ }
1006
+
1007
+ if (this.#resourceRegistry?.discover) {
1008
+ for (const descriptor of this.#resourceRegistry.discover(constraints)) {
1009
+ descriptors.push(Object.assign(ResourceDescriptor.fromJSON(descriptor.toJSON()), {
1010
+ source: descriptor.source || 'resource-registry',
1011
+ }))
1012
+ }
1013
+ }
1014
+
1015
+ for (const peer of this.#runtimeDescriptors()) {
1016
+ const descriptor = runtimePeerToComputeDescriptor(peer)
1017
+ if (!descriptor) continue
1018
+ if (constraints && !descriptor.matches(constraints)) continue
1019
+ descriptors.push(descriptor)
1020
+ }
1021
+
1022
+ for (const descriptor of descriptors) {
1023
+ const existing = merged.get(descriptor.podId)
1024
+ merged.set(descriptor.podId, existing ? mergeResourceDescriptors(existing, descriptor) : descriptor)
1025
+ }
1026
+
1027
+ return [...merged.values()]
1028
+ }
1029
+ }
1030
+
1031
+ function runtimePeerToComputeDescriptor(peer) {
1032
+ const podId = peer?.identity?.podId
1033
+ || peer?.identity?.fingerprint
1034
+ || peer?.identity?.canonicalId
1035
+ || peer?.username
1036
+ if (!podId) return null
1037
+ const capabilities = dedupeStrings([
1038
+ ...(peer.capabilities || []),
1039
+ ...((peer.metadata?.runtimeClasses || []).map((runtimeClass) => `runtime:${runtimeClass}`)),
1040
+ ...(peer.peerType ? [`runtime:${peer.peerType}`] : []),
1041
+ ...(peer.shellBackend ? [`runtime:${peer.shellBackend}`] : []),
1042
+ ...(peer.shellBackend === 'vm-console' ? ['vm_console'] : []),
1043
+ ...(peer.shellBackend === 'pty' ? ['host_pty'] : []),
1044
+ ...((peer.capabilities || []).some((cap) => cap === 'shell' || cap === 'exec' || cap === 'tools')
1045
+ ? ['compute']
1046
+ : []),
1047
+ ])
1048
+ if (!capabilities.includes('compute')) {
1049
+ return null
1050
+ }
1051
+ const route = (peer.reachability || [])[0] || null
1052
+ const availability = route?.health === 'offline'
1053
+ ? 'offline'
1054
+ : route?.health === 'degraded'
1055
+ ? 'busy'
1056
+ : 'online'
1057
+ const descriptor = new ResourceDescriptor({
1058
+ podId,
1059
+ resources: peer.metadata?.resources || {},
1060
+ capabilities,
1061
+ availability,
1062
+ })
1063
+ descriptor.source = 'runtime-registry'
1064
+ return descriptor
1065
+ }
1066
+
1067
+ function mergeResourceDescriptors(base, incoming) {
1068
+ const merged = new ResourceDescriptor({
1069
+ podId: base.podId,
1070
+ resources: {
1071
+ cpu: incoming.resources.cpu || base.resources.cpu,
1072
+ gpu: incoming.resources.gpu || base.resources.gpu,
1073
+ memory: incoming.resources.memory || base.resources.memory,
1074
+ storage: incoming.resources.storage || base.resources.storage,
1075
+ bandwidth: incoming.resources.bandwidth || base.resources.bandwidth,
1076
+ },
1077
+ capabilities: dedupeStrings([...(base.capabilities || []), ...(incoming.capabilities || [])]),
1078
+ availability: availabilityPriority(incoming.availability) > availabilityPriority(base.availability)
1079
+ ? incoming.availability
1080
+ : base.availability,
1081
+ })
1082
+ merged.source = incoming.source || base.source || 'resource-registry'
1083
+ return merged
1084
+ }
1085
+
1086
+ function availabilityPriority(value) {
1087
+ switch (value) {
1088
+ case 'online':
1089
+ return 3
1090
+ case 'busy':
1091
+ return 2
1092
+ default:
1093
+ return 1
1094
+ }
1095
+ }
1096
+
1097
+ function dedupeStrings(values) {
1098
+ return [...new Set((values || []).filter(Boolean))]
1099
+ }
1100
+
1101
+ function deriveSkillName(skillContent) {
1102
+ const frontmatter = /^---\s*[\r\n]+([\s\S]*?)[\r\n]+---/.exec(skillContent)
1103
+ if (frontmatter) {
1104
+ const nameMatch = /(?:^|\n)name:\s*([a-zA-Z0-9._-]+)/.exec(frontmatter[1])
1105
+ if (nameMatch?.[1]) return nameMatch[1]
1106
+ }
1107
+ const heading = /^#\s+([^\r\n]+)/m.exec(skillContent)
1108
+ if (heading?.[1]) {
1109
+ return heading[1].trim().toLowerCase().replace(/[^a-z0-9._-]+/g, '-')
1110
+ }
1111
+ return `skill-${Date.now().toString(36)}`
1112
+ }
1113
+
1114
+ // ---------------------------------------------------------------------------
1115
+ // BrowserTool subclasses
1116
+ // ---------------------------------------------------------------------------
1117
+
1118
+ // ── meshctl_pods ──────────────────────────────────────────────────────
1119
+
1120
+ export class MeshctlPodsTool extends BrowserTool {
1121
+ #orchestrator
1122
+
1123
+ constructor(orchestrator) {
1124
+ super()
1125
+ this.#orchestrator = orchestrator
1126
+ }
1127
+
1128
+ get name() { return 'meshctl_pods' }
1129
+ get description() { return 'List all known pods (local + remote) with their status and services' }
1130
+ get parameters() {
1131
+ return {
1132
+ type: 'object',
1133
+ properties: {
1134
+ filter: { type: 'string', description: 'Status filter: online, offline, all (default: all)' },
1135
+ },
1136
+ }
1137
+ }
1138
+ get permission() { return 'read' }
1139
+
1140
+ async execute({ filter } = {}) {
1141
+ try {
1142
+ const pods = await this.#orchestrator.listPods(filter)
1143
+ if (pods.length === 0) {
1144
+ return { success: true, output: 'No pods found.' }
1145
+ }
1146
+ const lines = pods.map(p => {
1147
+ const local = p.isLocal ? ' (local)' : ''
1148
+ const svcs = p.services.length > 0 ? ` [${p.services.join(', ')}]` : ''
1149
+ return `${p.podId} | ${p.status}${local} | conns: ${p.connections}${svcs}`
1150
+ })
1151
+ return {
1152
+ success: true,
1153
+ output: `POD | STATUS | CONNECTIONS | SERVICES\n${lines.join('\n')}`,
1154
+ }
1155
+ } catch (err) {
1156
+ return { success: false, output: '', error: `Failed to list pods: ${err.message}` }
1157
+ }
1158
+ }
1159
+ }
1160
+
1161
+ // ── meshctl_status ────────────────────────────────────────────────────
1162
+
1163
+ export class MeshctlStatusTool extends BrowserTool {
1164
+ #orchestrator
1165
+
1166
+ constructor(orchestrator) {
1167
+ super()
1168
+ this.#orchestrator = orchestrator
1169
+ }
1170
+
1171
+ get name() { return 'meshctl_status' }
1172
+ get description() { return 'Get detailed status of a specific pod including resources, capabilities, and uptime' }
1173
+ get parameters() {
1174
+ return {
1175
+ type: 'object',
1176
+ properties: {
1177
+ podId: { type: 'string', description: 'Pod ID to query' },
1178
+ },
1179
+ required: ['podId'],
1180
+ }
1181
+ }
1182
+ get permission() { return 'read' }
1183
+
1184
+ async execute({ podId }) {
1185
+ try {
1186
+ const status = await this.#orchestrator.getPodStatus(podId)
1187
+ if (!status) {
1188
+ return { success: false, output: '', error: `Pod "${podId}" not found.` }
1189
+ }
1190
+ const lines = [
1191
+ `Pod: ${status.podId}${status.isLocal ? ' (local)' : ''}`,
1192
+ `Status: ${status.status}`,
1193
+ `Uptime: ${status.uptime}ms`,
1194
+ `Connections: ${status.connections}`,
1195
+ `Capabilities: ${status.capabilities.join(', ') || 'none'}`,
1196
+ `Services: ${status.services.join(', ') || 'none'}`,
1197
+ `Resources: cpu=${status.resources.cpu}, memory=${status.resources.memory}MB, storage=${status.resources.storage}MB`,
1198
+ ]
1199
+ return { success: true, output: lines.join('\n') }
1200
+ } catch (err) {
1201
+ return { success: false, output: '', error: `Failed to get status: ${err.message}` }
1202
+ }
1203
+ }
1204
+ }
1205
+
1206
+ // ── meshctl_exec ──────────────────────────────────────────────────────
1207
+
1208
+ export class MeshctlExecTool extends BrowserTool {
1209
+ #orchestrator
1210
+
1211
+ constructor(orchestrator) {
1212
+ super()
1213
+ this.#orchestrator = orchestrator
1214
+ }
1215
+
1216
+ get name() { return 'meshctl_exec' }
1217
+ get description() { return 'Execute a command on a remote pod via peer session' }
1218
+ get parameters() {
1219
+ return {
1220
+ type: 'object',
1221
+ properties: {
1222
+ podId: { type: 'string', description: 'Target pod ID' },
1223
+ command: { type: 'string', description: 'Command to execute' },
1224
+ },
1225
+ required: ['podId', 'command'],
1226
+ }
1227
+ }
1228
+ get permission() { return 'network' }
1229
+
1230
+ async execute({ podId, command }) {
1231
+ try {
1232
+ const result = await this.#orchestrator.execOnPod(podId, command)
1233
+ return {
1234
+ success: result.exitCode === 0,
1235
+ output: result.output,
1236
+ error: result.exitCode !== 0 ? `Exit code: ${result.exitCode}` : undefined,
1237
+ }
1238
+ } catch (err) {
1239
+ return { success: false, output: '', error: `Exec failed: ${err.message}` }
1240
+ }
1241
+ }
1242
+ }
1243
+
1244
+ // ── meshctl_deploy ────────────────────────────────────────────────────
1245
+
1246
+ export class MeshctlDeployTool extends BrowserTool {
1247
+ #orchestrator
1248
+
1249
+ constructor(orchestrator) {
1250
+ super()
1251
+ this.#orchestrator = orchestrator
1252
+ }
1253
+
1254
+ get name() { return 'meshctl_deploy' }
1255
+ get description() { return 'Deploy a skill (SKILL.md content) to a remote pod' }
1256
+ get parameters() {
1257
+ return {
1258
+ type: 'object',
1259
+ properties: {
1260
+ podId: { type: 'string', description: 'Target pod ID' },
1261
+ skillContent: { type: 'string', description: 'SKILL.md content to deploy' },
1262
+ },
1263
+ required: ['podId', 'skillContent'],
1264
+ }
1265
+ }
1266
+ get permission() { return 'write' }
1267
+
1268
+ async execute({ podId, skillContent }) {
1269
+ try {
1270
+ const result = await this.#orchestrator.deploySkill(podId, skillContent)
1271
+ if (result.success) {
1272
+ return { success: true, output: `Skill deployed to ${podId} (${skillContent.length} bytes)` }
1273
+ }
1274
+ return { success: false, output: '', error: result.error || 'Deploy failed' }
1275
+ } catch (err) {
1276
+ return { success: false, output: '', error: `Deploy failed: ${err.message}` }
1277
+ }
1278
+ }
1279
+ }
1280
+
1281
+ // ── meshctl_top ───────────────────────────────────────────────────────
1282
+
1283
+ export class MeshctlTopTool extends BrowserTool {
1284
+ #orchestrator
1285
+
1286
+ constructor(orchestrator) {
1287
+ super()
1288
+ this.#orchestrator = orchestrator
1289
+ }
1290
+
1291
+ get name() { return 'meshctl_top' }
1292
+ get description() { return 'Show resource usage across all pods (CPU, memory, storage, active tasks)' }
1293
+ get parameters() {
1294
+ return {
1295
+ type: 'object',
1296
+ properties: {},
1297
+ }
1298
+ }
1299
+ get permission() { return 'read' }
1300
+
1301
+ async execute() {
1302
+ try {
1303
+ const { pods } = await this.#orchestrator.topPods()
1304
+ if (pods.length === 0) {
1305
+ return { success: true, output: 'No pods found.' }
1306
+ }
1307
+ const lines = pods.map(p =>
1308
+ `${p.podId} | ${p.status} | cpu: ${p.cpu} | mem: ${p.memory}MB | storage: ${p.storage}MB | tasks: ${p.activeTasks}`
1309
+ )
1310
+ return {
1311
+ success: true,
1312
+ output: `POD | STATUS | CPU | MEMORY | STORAGE | TASKS\n${lines.join('\n')}`,
1313
+ }
1314
+ } catch (err) {
1315
+ return { success: false, output: '', error: `Top failed: ${err.message}` }
1316
+ }
1317
+ }
1318
+ }
1319
+
1320
+ // ── meshctl_compute ──────────────────────────────────────────────────
1321
+
1322
+ export class MeshctlComputeTool extends BrowserTool {
1323
+ #orchestrator
1324
+
1325
+ constructor(orchestrator) {
1326
+ super()
1327
+ this.#orchestrator = orchestrator
1328
+ }
1329
+
1330
+ get name() { return 'meshctl_compute' }
1331
+ get description() { return 'Select a compute-capable runtime and execute a task through the shared remote runtime broker' }
1332
+ get parameters() {
1333
+ return {
1334
+ type: 'object',
1335
+ properties: {
1336
+ podId: { type: 'string', description: 'Optional target pod ID (omit to auto-select)' },
1337
+ command: { type: 'string', description: 'Command to execute' },
1338
+ prefer: { type: 'string', description: 'Resource preference: gpu, cpu, any' },
1339
+ },
1340
+ required: ['command'],
1341
+ }
1342
+ }
1343
+ get permission() { return 'network' }
1344
+
1345
+ async execute({ podId, command, prefer } = {}) {
1346
+ try {
1347
+ const result = await this.#orchestrator.runComputeTask({
1348
+ selector: podId || null,
1349
+ command,
1350
+ constraints: prefer ? { prefer } : {},
1351
+ })
1352
+ return {
1353
+ success: result.exitCode === 0,
1354
+ output: `[${result.podId}] ${result.output}`.trim(),
1355
+ error: result.exitCode !== 0 ? `Exit code: ${result.exitCode}` : undefined,
1356
+ }
1357
+ } catch (err) {
1358
+ return { success: false, output: '', error: `Compute failed: ${err.message}` }
1359
+ }
1360
+ }
1361
+ }
1362
+
1363
+ // ── meshctl_expose ────────────────────────────────────────────────────
1364
+
1365
+ export class MeshctlExposeTool extends BrowserTool {
1366
+ #orchestrator
1367
+
1368
+ constructor(orchestrator) {
1369
+ super()
1370
+ this.#orchestrator = orchestrator
1371
+ }
1372
+
1373
+ get name() { return 'meshctl_expose' }
1374
+ get description() { return 'Expose a pod service on the mesh network with a named endpoint' }
1375
+ get parameters() {
1376
+ return {
1377
+ type: 'object',
1378
+ properties: {
1379
+ podId: { type: 'string', description: 'Pod ID to expose (default: local pod)' },
1380
+ port: { type: 'number', description: 'Port number to expose' },
1381
+ name: { type: 'string', description: 'Service name for discovery' },
1382
+ },
1383
+ required: ['port', 'name'],
1384
+ }
1385
+ }
1386
+ get permission() { return 'network' }
1387
+
1388
+ async execute({ podId, port, name }) {
1389
+ try {
1390
+ const effectivePodId = podId || this.#orchestrator.peerNode.podId || this.#orchestrator.peerNode.id || 'local'
1391
+ const result = await this.#orchestrator.exposePod(effectivePodId, port, name)
1392
+ if (result.success) {
1393
+ return { success: true, output: `Service "${name}" exposed at ${result.address}` }
1394
+ }
1395
+ return { success: false, output: '', error: 'Expose failed' }
1396
+ } catch (err) {
1397
+ return { success: false, output: '', error: `Expose failed: ${err.message}` }
1398
+ }
1399
+ }
1400
+ }
1401
+
1402
+ // ── meshctl_drain ─────────────────────────────────────────────────────
1403
+
1404
+ export class MeshctlDrainTool extends BrowserTool {
1405
+ #orchestrator
1406
+
1407
+ constructor(orchestrator) {
1408
+ super()
1409
+ this.#orchestrator = orchestrator
1410
+ }
1411
+
1412
+ get name() { return 'meshctl_drain' }
1413
+ get description() { return 'Gracefully drain a pod: stop accepting work, migrate tasks, and disconnect' }
1414
+ get parameters() {
1415
+ return {
1416
+ type: 'object',
1417
+ properties: {
1418
+ podId: { type: 'string', description: 'Pod ID to drain' },
1419
+ },
1420
+ required: ['podId'],
1421
+ }
1422
+ }
1423
+ get permission() { return 'network' }
1424
+
1425
+ async execute({ podId }) {
1426
+ try {
1427
+ const result = await this.#orchestrator.drainPod(podId)
1428
+ if (result.success) {
1429
+ return { success: true, output: `Pod ${podId} drained. Migrated ${result.migrated} tasks.` }
1430
+ }
1431
+ return { success: false, output: '', error: `Pod "${podId}" not found or already drained.` }
1432
+ } catch (err) {
1433
+ return { success: false, output: '', error: `Drain failed: ${err.message}` }
1434
+ }
1435
+ }
1436
+ }
1437
+
1438
+ // ---------------------------------------------------------------------------
1439
+ // Shell integration helper
1440
+ // ---------------------------------------------------------------------------
1441
+
1442
+ /**
1443
+ * Register 'meshctl' as a compound command in the shell registry.
1444
+ * Subcommands: pods, status, exec, deploy, top, compute, expose, drain
1445
+ *
1446
+ * @param {import('./clawser-shell.js').CommandRegistry} shellRegistry
1447
+ * @param {MeshOrchestrator} orchestrator
1448
+ */
1449
+ export function registerMeshctlBuiltins(shellRegistry, orchestrator) {
1450
+ shellRegistry.register('meshctl', async ({ args }) => {
1451
+ const subcommand = args[0]
1452
+ const rest = args.slice(1)
1453
+
1454
+ switch (subcommand) {
1455
+ case 'pods': {
1456
+ const filter = rest[0] || 'all'
1457
+ const pods = await orchestrator.listPods(filter)
1458
+ if (pods.length === 0) return { stdout: 'No pods found.\n', stderr: '', exitCode: 0 }
1459
+ const lines = pods.map(p => {
1460
+ const local = p.isLocal ? ' (local)' : ''
1461
+ return `${p.podId}\t${p.status}${local}\tconns:${p.connections}`
1462
+ })
1463
+ return { stdout: lines.join('\n') + '\n', stderr: '', exitCode: 0 }
1464
+ }
1465
+
1466
+ case 'status': {
1467
+ const podId = rest[0]
1468
+ if (!podId) return { stdout: '', stderr: 'Usage: meshctl status <podId>\n', exitCode: 1 }
1469
+ const status = await orchestrator.getPodStatus(podId)
1470
+ if (!status) return { stdout: '', stderr: `Pod "${podId}" not found.\n`, exitCode: 1 }
1471
+ return {
1472
+ stdout: JSON.stringify(status.toJSON(), null, 2) + '\n',
1473
+ stderr: '',
1474
+ exitCode: 0,
1475
+ }
1476
+ }
1477
+
1478
+ case 'exec': {
1479
+ const podId = rest[0]
1480
+ const command = rest.slice(1).join(' ')
1481
+ if (!podId || !command) return { stdout: '', stderr: 'Usage: meshctl exec <podId> <command>\n', exitCode: 1 }
1482
+ try {
1483
+ const result = await orchestrator.execOnPod(podId, command)
1484
+ return { stdout: result.output + '\n', stderr: '', exitCode: result.exitCode }
1485
+ } catch (err) {
1486
+ return { stdout: '', stderr: err.message + '\n', exitCode: 1 }
1487
+ }
1488
+ }
1489
+
1490
+ case 'deploy': {
1491
+ const podId = rest[0]
1492
+ const skillContent = rest.slice(1).join(' ')
1493
+ if (!podId || !skillContent) return { stdout: '', stderr: 'Usage: meshctl deploy <podId> <skillContent>\n', exitCode: 1 }
1494
+ const result = await orchestrator.deploySkill(podId, skillContent)
1495
+ if (result.success) return { stdout: `Deployed to ${podId}\n`, stderr: '', exitCode: 0 }
1496
+ return { stdout: '', stderr: result.error + '\n', exitCode: 1 }
1497
+ }
1498
+
1499
+ case 'top': {
1500
+ const { pods } = await orchestrator.topPods()
1501
+ if (pods.length === 0) return { stdout: 'No pods.\n', stderr: '', exitCode: 0 }
1502
+ const lines = pods.map(p =>
1503
+ `${p.podId}\tcpu:${p.cpu}\tmem:${p.memory}\tstorage:${p.storage}\ttasks:${p.activeTasks}`
1504
+ )
1505
+ return { stdout: lines.join('\n') + '\n', stderr: '', exitCode: 0 }
1506
+ }
1507
+
1508
+ case 'compute': {
1509
+ const [targetOrAuto, ...commandParts] = rest
1510
+ const selector = targetOrAuto && targetOrAuto !== 'auto' ? targetOrAuto : null
1511
+ const command = targetOrAuto ? commandParts.join(' ') : ''
1512
+ if (!command) return { stdout: '', stderr: 'Usage: meshctl compute <podId|auto> <command>\n', exitCode: 1 }
1513
+ try {
1514
+ const result = await orchestrator.runComputeTask({ selector, command })
1515
+ return { stdout: `[${result.podId}] ${result.output}`.trimEnd() + '\n', stderr: '', exitCode: result.exitCode }
1516
+ } catch (err) {
1517
+ return { stdout: '', stderr: err.message + '\n', exitCode: 1 }
1518
+ }
1519
+ }
1520
+
1521
+ case 'expose': {
1522
+ // meshctl expose <podId> <port> <name>
1523
+ const [ePodId, ePort, eName] = rest
1524
+ const parsedPort = parseInt(ePort, 10)
1525
+ if (!ePodId || !ePort || !eName || !Number.isFinite(parsedPort)) {
1526
+ return { stdout: '', stderr: 'Usage: meshctl expose <podId> <port> <name>\n', exitCode: 1 }
1527
+ }
1528
+ const result = await orchestrator.exposePod(ePodId, parsedPort, eName)
1529
+ if (result.success) return { stdout: `Exposed "${eName}" at ${result.address}\n`, stderr: '', exitCode: 0 }
1530
+ return { stdout: '', stderr: 'Expose failed.\n', exitCode: 1 }
1531
+ }
1532
+
1533
+ case 'drain': {
1534
+ const podId = rest[0]
1535
+ if (!podId) return { stdout: '', stderr: 'Usage: meshctl drain <podId>\n', exitCode: 1 }
1536
+ const result = await orchestrator.drainPod(podId)
1537
+ if (result.success) return { stdout: `Drained ${podId}. Migrated ${result.migrated} tasks.\n`, stderr: '', exitCode: 0 }
1538
+ return { stdout: '', stderr: `Pod "${podId}" not found.\n`, exitCode: 1 }
1539
+ }
1540
+
1541
+ default:
1542
+ return {
1543
+ stdout: '',
1544
+ stderr: `Unknown subcommand: ${subcommand || '(none)'}. Available: pods, status, exec, deploy, top, compute, expose, drain\n`,
1545
+ exitCode: 1,
1546
+ }
1547
+ }
1548
+ }, {
1549
+ description: 'Pod orchestration commands for the mesh network',
1550
+ category: 'mesh',
1551
+ usage: 'meshctl <subcommand> [args...]',
1552
+ })
1553
+ }
1554
+
1555
+ // ---------------------------------------------------------------------------
1556
+ // Tool registration helper
1557
+ // ---------------------------------------------------------------------------
1558
+
1559
+ /**
1560
+ * Create all meshctl BrowserTool instances for a given orchestrator.
1561
+ * @param {MeshOrchestrator} orchestrator
1562
+ * @returns {BrowserTool[]}
1563
+ */
1564
+ export function createMeshctlTools(orchestrator) {
1565
+ return [
1566
+ new MeshctlPodsTool(orchestrator),
1567
+ new MeshctlStatusTool(orchestrator),
1568
+ new MeshctlExecTool(orchestrator),
1569
+ new MeshctlDeployTool(orchestrator),
1570
+ new MeshctlTopTool(orchestrator),
1571
+ new MeshctlComputeTool(orchestrator),
1572
+ new MeshctlExposeTool(orchestrator),
1573
+ new MeshctlDrainTool(orchestrator),
1574
+ ]
1575
+ }